From 5d0ea7f11063c302e338e03370f2a7d6ce6f6748 Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 18 Feb 2019 16:43:01 +0100 Subject: Corrected issue #758 --- src/textures.c | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/textures.c b/src/textures.c index 5edd7201..75624fdb 100644 --- a/src/textures.c +++ b/src/textures.c @@ -3193,25 +3193,27 @@ static int SaveKTX(Image image, const char *fileName) { KTXHeader ktxHeader; - // KTX identifier (v2.2) + // KTX identifier (v1.1) //unsigned char id[12] = { 'ยซ', 'K', 'T', 'X', ' ', '1', '1', 'ยป', '\r', '\n', '\x1A', '\n' }; //unsigned char id[12] = { 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A }; + const char ktxIdentifier[12] = { 0xAB, 'K', 'T', 'X', ' ', '1', '1', 0xBB, '\r', '\n', 0x1A, '\n' }; + // Get the image header - strcpy(ktxHeader.id, "ยซKTX 11ยป\r\n\x1A\n"); // KTX 1.1 signature + strncpy(ktxHeader.id, ktxIdentifier, 12); // KTX 1.1 signature ktxHeader.endianness = 0; - ktxHeader.glType = 0; // Obtained from image.format + ktxHeader.glType = 0; // Obtained from image.format ktxHeader.glTypeSize = 1; - ktxHeader.glFormat = 0; // Obtained from image.format - ktxHeader.glInternalFormat = 0; // Obtained from image.format + ktxHeader.glFormat = 0; // Obtained from image.format + ktxHeader.glInternalFormat = 0; // Obtained from image.format ktxHeader.glBaseInternalFormat = 0; ktxHeader.width = image.width; ktxHeader.height = image.height; ktxHeader.depth = 0; ktxHeader.elements = 0; ktxHeader.faces = 1; - ktxHeader.mipmapLevels = image.mipmaps; // If it was 0, it means mipmaps should be generated on loading (not for compressed formats) - ktxHeader.keyValueDataSize = 0; // No extra data after the header + ktxHeader.mipmapLevels = image.mipmaps; // If it was 0, it means mipmaps should be generated on loading (not for compressed formats) + ktxHeader.keyValueDataSize = 0; // No extra data after the header rlGetGlTextureFormats(image.format, &ktxHeader.glInternalFormat, &ktxHeader.glFormat, &ktxHeader.glType); // rlgl module function ktxHeader.glBaseInternalFormat = ktxHeader.glFormat; // KTX 1.1 only -- cgit v1.2.3 From d62652c5b29b322c8c9fa2ab7c7912fe366cd4bc Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 18 Feb 2019 18:46:17 +0100 Subject: Update cgltf library Added some comments to loader function... --- src/external/cgltf.h | 51 +++++++++++++++++++++++++++++++++++++++++++++++---- src/models.c | 24 +++++++++++++++--------- 2 files changed, 62 insertions(+), 13 deletions(-) (limited to 'src') diff --git a/src/external/cgltf.h b/src/external/cgltf.h index 81e1ac7f..4302e77b 100644 --- a/src/external/cgltf.h +++ b/src/external/cgltf.h @@ -1,6 +1,49 @@ /** * cgltf - a single-file glTF 2.0 parser written in C99. + * + * Version: 1.0 + * + * Website: https://github.com/jkuhlmann/cgltf + * * Distributed under the MIT License, see notice at the end of this file. + * + * Building: + * Include this file where you need the struct and function + * declarations. Have exactly one source file where you define + * `CGLTF_IMPLEMENTATION` before including this file to get the + * function definitions. + * + * Reference: + * `cgltf_result cgltf_parse(const cgltf_options*, const void*, + * cgltf_size, cgltf_data**)` parses both glTF and GLB data. If + * this function returns `cgltf_result_success`, you have to call + * `cgltf_free()` on the created `cgltf_data*` variable. + * Note that contents of external files for buffers and images are not + * automatically loaded. You'll need to read these files yourself using + * URIs in the `cgltf_data` structure. + * + * `cgltf_options` is the struct passed to `cgltf_parse()` to control + * parts of the parsing process. You can use it to force the file type + * and provide memory allocation callbacks. Should be zero-initialized + * to trigger default behavior. + * + * `cgltf_data` is the struct allocated and filled by `cgltf_parse()`. + * It generally mirrors the glTF format as described by the spec (see + * https://github.com/KhronosGroup/glTF/tree/master/specification/2.0). + * + * `void cgltf_free(cgltf_data*)` frees the allocated `cgltf_data` + * variable. + * + * `cgltf_result cgltf_load_buffers(const cgltf_options*, cgltf_data*, + * const char*)` can be optionally called to open and read buffer + * files using the `FILE*` APIs. + * + * `cgltf_result cgltf_parse_file(const cgltf_options* options, const + * char* path, cgltf_data** out_data)` can be used to open the given + * file using `FILE*` APIs and parse the data using `cgltf_parse()`. + * + * `cgltf_result cgltf_validate(cgltf_data*)` can be used to do additional + * checks to make sure the parsed glTF data is valid. */ #ifndef CGLTF_H_INCLUDED__ #define CGLTF_H_INCLUDED__ @@ -462,6 +505,10 @@ void cgltf_free(cgltf_data* data); void cgltf_node_transform_local(const cgltf_node* node, cgltf_float* out_matrix); void cgltf_node_transform_world(const cgltf_node* node, cgltf_float* out_matrix); +#ifdef __cplusplus +} +#endif + #endif /* #ifndef CGLTF_H_INCLUDED__ */ /* @@ -4266,10 +4313,6 @@ static void jsmn_init(jsmn_parser *parser) { #endif /* #ifdef CGLTF_IMPLEMENTATION */ -#ifdef __cplusplus -} -#endif - /* cgltf is distributed under MIT license: * * Copyright (c) 2018 Johannes Kuhlmann diff --git a/src/models.c b/src/models.c index 5feec0f6..eace0f66 100644 --- a/src/models.c +++ b/src/models.c @@ -2748,17 +2748,17 @@ static Mesh LoadIQM(const char *fileName) #endif #if defined(SUPPORT_FILEFORMAT_GLTF) -// Load GLTF mesh data +// Load glTF mesh data static Mesh LoadGLTF(const char *fileName) { Mesh mesh = { 0 }; - // GLTF file loading + // glTF file loading FILE *gltfFile = fopen(fileName, "rb"); if (gltfFile == NULL) { - TraceLog(LOG_WARNING, "[%s] GLTF file could not be opened", fileName); + TraceLog(LOG_WARNING, "[%s] glTF file could not be opened", fileName); return mesh; } @@ -2771,22 +2771,28 @@ static Mesh LoadGLTF(const char *fileName) fclose(gltfFile); - // GLTF data loading + // glTF data loading cgltf_options options = {0}; cgltf_data data; cgltf_result result = cgltf_parse(&options, buffer, size, &data); - + + free(buffer); + if (result == cgltf_result_success) { printf("Type: %u\n", data.file_type); printf("Version: %d\n", data.version); printf("Meshes: %lu\n", data.meshes_count); + + // TODO: Process glTF data and map to mesh + + // NOTE: data.buffers[] and data.images[] should be loaded + // using buffers[n].uri and images[n].uri... or use cgltf_load_buffers(&options, data, fileName); + + cgltf_free(&data); } - else TraceLog(LOG_WARNING, "[%s] GLTF data could not be loaded", fileName); + else TraceLog(LOG_WARNING, "[%s] glTF data could not be loaded", fileName); - free(buffer); - cgltf_free(&data); - return mesh; } #endif -- cgit v1.2.3 From 497fb4e49ffe5a1c73b47d7733c9dbe3091ff976 Mon Sep 17 00:00:00 2001 From: Rob Loach Date: Mon, 18 Feb 2019 23:36:29 -0500 Subject: Remove compiled libraylib.a --- src/libraylib.a | Bin 1294540 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 src/libraylib.a (limited to 'src') diff --git a/src/libraylib.a b/src/libraylib.a deleted file mode 100644 index 1501aa44..00000000 Binary files a/src/libraylib.a and /dev/null differ -- cgit v1.2.3 From 75298b50fbfe8a8fad9c52c3cd8882072fb1ed36 Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 21 Feb 2019 11:28:10 +0100 Subject: Corrected issue with OpenURL() It was not working on Windows 10 --- src/core.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'src') diff --git a/src/core.c b/src/core.c index 67357ce9..36315113 100644 --- a/src/core.c +++ b/src/core.c @@ -1917,14 +1917,13 @@ void OpenURL(const char *url) char *cmd = (char *)calloc(strlen(url) + 10, sizeof(char)); #if defined(_WIN32) - sprintf(cmd, "explorer '%s'", url); + sprintf(cmd, "explorer %s", url); #elif defined(__linux__) sprintf(cmd, "xdg-open '%s'", url); // Alternatives: firefox, x-www-browser #elif defined(__APPLE__) sprintf(cmd, "open '%s'", url); #endif system(cmd); - free(cmd); } } -- cgit v1.2.3 From 641895b5ba778fdc9024ebb58446dcc8ea36a00a Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 21 Feb 2019 18:45:19 +0100 Subject: Remove end-line spaces --- src/core.c | 6 +- src/models.c | 208 ++++++++++++++++++++++++++++----------------------------- src/raudio.c | 14 ++-- src/rlgl.h | 114 +++++++++++++++---------------- src/shapes.c | 8 +-- src/text.c | 86 ++++++++++++------------ src/textures.c | 4 +- 7 files changed, 220 insertions(+), 220 deletions(-) (limited to 'src') diff --git a/src/core.c b/src/core.c index 36315113..714e6e2c 100644 --- a/src/core.c +++ b/src/core.c @@ -707,7 +707,7 @@ bool WindowShouldClose(void) { #if defined(PLATFORM_WEB) // Emterpreter-Async required to run sync code - // https://github.com/kripken/emscripten/wiki/Emterpreter#emterpreter-async-run-synchronous-code + // https://github.com/emscripten-core/emscripten/wiki/Emterpreter#emterpreter-async-run-synchronous-code // By default, this function is never called on a web-ready raylib example because we encapsulate // frame code in a UpdateDrawFrame() function, to allow browser manage execution asynchronously // but now emscripten allows sync code to be executed in an interpreted way, using emterpreter! @@ -1228,7 +1228,7 @@ void BeginTextureMode(RenderTexture2D target) rlLoadIdentity(); // Reset current matrix (MODELVIEW) //rlScalef(0.0f, -1.0f, 0.0f); // Flip Y-drawing (?) - + // Setup current width/height for proper aspect ratio // calculation when using BeginMode3D() currentWidth = target.texture.width; @@ -1254,7 +1254,7 @@ void EndTextureMode(void) rlMatrixMode(RL_MODELVIEW); // Switch back to MODELVIEW matrix rlLoadIdentity(); // Reset current matrix (MODELVIEW) - + // Reset current screen size currentWidth = GetScreenWidth(); currentHeight = GetScreenHeight(); diff --git a/src/models.c b/src/models.c index eace0f66..384c8db4 100644 --- a/src/models.c +++ b/src/models.c @@ -116,7 +116,7 @@ void DrawLine3D(Vector3 startPos, Vector3 endPos, Color color) void DrawCircle3D(Vector3 center, float radius, Vector3 rotationAxis, float rotationAngle, Color color) { if (rlCheckBufferLimit(2*36)) rlglDraw(); - + rlPushMatrix(); rlTranslatef(center.x, center.y, center.z); rlRotatef(rotationAngle, rotationAxis.x, rotationAxis.y, rotationAxis.z); @@ -140,7 +140,7 @@ void DrawCube(Vector3 position, float width, float height, float length, Color c float x = 0.0f; float y = 0.0f; float z = 0.0f; - + if (rlCheckBufferLimit(36)) rlglDraw(); rlPushMatrix(); @@ -221,7 +221,7 @@ void DrawCubeWires(Vector3 position, float width, float height, float length, Co float x = 0.0f; float y = 0.0f; float z = 0.0f; - + if (rlCheckBufferLimit(36)) rlglDraw(); rlPushMatrix(); @@ -626,7 +626,7 @@ Model LoadModel(const char *fileName) Model LoadModelFromMesh(Mesh mesh) { Model model = { 0 }; - + model.mesh = mesh; model.transform = MatrixIdentity(); model.material = LoadMaterialDefault(); @@ -679,11 +679,11 @@ void UnloadMesh(Mesh *mesh) void ExportMesh(Mesh mesh, const char *fileName) { bool success = false; - + if (IsFileExtension(fileName, ".obj")) { FILE *objFile = fopen(fileName, "wt"); - + fprintf(objFile, "# //////////////////////////////////////////////////////////////////////////////////\n"); fprintf(objFile, "# // //\n"); fprintf(objFile, "# // rMeshOBJ exporter v1.0 - Mesh exported as triangle faces and not optimized //\n"); @@ -696,33 +696,33 @@ void ExportMesh(Mesh mesh, const char *fileName) fprintf(objFile, "# //////////////////////////////////////////////////////////////////////////////////\n\n"); fprintf(objFile, "# Vertex Count: %i\n", mesh.vertexCount); fprintf(objFile, "# Triangle Count: %i\n\n", mesh.triangleCount); - + fprintf(objFile, "g mesh\n"); - + for (int i = 0, v = 0; i < mesh.vertexCount; i++, v += 3) { fprintf(objFile, "v %.2f %.2f %.2f\n", mesh.vertices[v], mesh.vertices[v + 1], mesh.vertices[v + 2]); } - + for (int i = 0, v = 0; i < mesh.vertexCount; i++, v += 2) { fprintf(objFile, "vt %.2f %.2f\n", mesh.texcoords[v], mesh.texcoords[v + 1]); } - + for (int i = 0, v = 0; i < mesh.vertexCount; i++, v += 3) { fprintf(objFile, "vn %.2f %.2f %.2f\n", mesh.normals[v], mesh.normals[v + 1], mesh.normals[v + 2]); } - + for (int i = 0; i < mesh.triangleCount; i += 3) { fprintf(objFile, "f %i/%i/%i %i/%i/%i %i/%i/%i\n", i, i, i, i + 1, i + 1, i + 1, i + 2, i + 2, i + 2); } - + fprintf(objFile, "\n"); - + fclose(objFile); - + success = true; } else if (IsFileExtension(fileName, ".raw")) { } // TODO: Support additional file formats to export mesh vertex data @@ -737,7 +737,7 @@ Mesh GenMeshPoly(int sides, float radius) { Mesh mesh = { 0 }; int vertexCount = sides*3; - + // Vertices definition Vector3 *vertices = (Vector3 *)malloc(vertexCount*sizeof(Vector3)); for (int i = 0, v = 0; i < 360; i += 360/sides, v += 3) @@ -745,13 +745,13 @@ Mesh GenMeshPoly(int sides, float radius) vertices[v] = (Vector3){ 0.0f, 0.0f, 0.0f }; vertices[v + 1] = (Vector3){ sinf(DEG2RAD*i)*radius, 0.0f, cosf(DEG2RAD*i)*radius }; vertices[v + 2] = (Vector3){ sinf(DEG2RAD*(i + 360/sides))*radius, 0.0f, cosf(DEG2RAD*(i + 360/sides))*radius }; - } - + } + // Normals definition Vector3 *normals = (Vector3 *)malloc(vertexCount*sizeof(Vector3)); for (int n = 0; n < vertexCount; n++) normals[n] = (Vector3){ 0.0f, 1.0f, 0.0f }; // Vector3.up; - // TexCoords definition + // TexCoords definition Vector2 *texcoords = (Vector2 *)malloc(vertexCount*sizeof(Vector2)); for (int n = 0; n < vertexCount; n++) texcoords[n] = (Vector2){ 0.0f, 0.0f }; @@ -760,7 +760,7 @@ Mesh GenMeshPoly(int sides, float radius) mesh.vertices = (float *)malloc(mesh.vertexCount*3*sizeof(float)); mesh.texcoords = (float *)malloc(mesh.vertexCount*2*sizeof(float)); mesh.normals = (float *)malloc(mesh.vertexCount*3*sizeof(float)); - + // Mesh vertices position array for (int i = 0; i < mesh.vertexCount; i++) { @@ -768,14 +768,14 @@ Mesh GenMeshPoly(int sides, float radius) mesh.vertices[3*i + 1] = vertices[i].y; mesh.vertices[3*i + 2] = vertices[i].z; } - + // Mesh texcoords array for (int i = 0; i < mesh.vertexCount; i++) { mesh.texcoords[2*i] = texcoords[i].x; mesh.texcoords[2*i + 1] = texcoords[i].y; } - + // Mesh normals array for (int i = 0; i < mesh.vertexCount; i++) { @@ -783,14 +783,14 @@ Mesh GenMeshPoly(int sides, float radius) mesh.normals[3*i + 1] = normals[i].y; mesh.normals[3*i + 2] = normals[i].z; } - + free(vertices); free(normals); free(texcoords); // Upload vertex data to GPU (static mesh) - rlLoadMesh(&mesh, false); - + rlLoadMesh(&mesh, false); + return mesh; } @@ -803,7 +803,7 @@ Mesh GenMeshPlane(float width, float length, int resX, int resZ) #if defined(CUSTOM_MESH_GEN_PLANE) resX++; resZ++; - + // Vertices definition int vertexCount = resX*resZ; // vertices get reused for the faces @@ -824,7 +824,7 @@ Mesh GenMeshPlane(float width, float length, int resX, int resZ) Vector3 *normals = (Vector3 *)malloc(vertexCount*sizeof(Vector3)); for (int n = 0; n < vertexCount; n++) normals[n] = (Vector3){ 0.0f, 1.0f, 0.0f }; // Vector3.up; - // TexCoords definition + // TexCoords definition Vector2 *texcoords = (Vector2 *)malloc(vertexCount*sizeof(Vector2)); for (int v = 0; v < resZ; v++) { @@ -847,7 +847,7 @@ Mesh GenMeshPlane(float width, float length, int resX, int resZ) triangles[t++] = i + 1; triangles[t++] = i; - triangles[t++] = i + resX; + triangles[t++] = i + resX; triangles[t++] = i + resX + 1; triangles[t++] = i + 1; } @@ -858,7 +858,7 @@ Mesh GenMeshPlane(float width, float length, int resX, int resZ) mesh.texcoords = (float *)malloc(mesh.vertexCount*2*sizeof(float)); mesh.normals = (float *)malloc(mesh.vertexCount*3*sizeof(float)); mesh.indices = (unsigned short *)malloc(mesh.triangleCount*3*sizeof(unsigned short)); - + // Mesh vertices position array for (int i = 0; i < mesh.vertexCount; i++) { @@ -866,14 +866,14 @@ Mesh GenMeshPlane(float width, float length, int resX, int resZ) mesh.vertices[3*i + 1] = vertices[i].y; mesh.vertices[3*i + 2] = vertices[i].z; } - + // Mesh texcoords array for (int i = 0; i < mesh.vertexCount; i++) { mesh.texcoords[2*i] = texcoords[i].x; mesh.texcoords[2*i + 1] = texcoords[i].y; } - + // Mesh normals array for (int i = 0; i < mesh.vertexCount; i++) { @@ -881,22 +881,22 @@ Mesh GenMeshPlane(float width, float length, int resX, int resZ) mesh.normals[3*i + 1] = normals[i].y; mesh.normals[3*i + 2] = normals[i].z; } - + // Mesh indices array initialization for (int i = 0; i < mesh.triangleCount*3; i++) mesh.indices[i] = triangles[i]; - + free(vertices); free(normals); free(texcoords); free(triangles); - + #else // Use par_shapes library to generate plane mesh par_shapes_mesh *plane = par_shapes_create_plane(resX, resZ); // No normals/texcoords generated!!! par_shapes_scale(plane, width, length, 1.0f); par_shapes_rotate(plane, -PI/2.0f, (float[]){ 1, 0, 0 }); par_shapes_translate(plane, -width/2, 0.0f, length/2); - + mesh.vertices = (float *)malloc(plane->ntriangles*3*3*sizeof(float)); mesh.texcoords = (float *)malloc(plane->ntriangles*3*2*sizeof(float)); mesh.normals = (float *)malloc(plane->ntriangles*3*3*sizeof(float)); @@ -909,11 +909,11 @@ Mesh GenMeshPlane(float width, float length, int resX, int resZ) mesh.vertices[k*3] = plane->points[plane->triangles[k]*3]; mesh.vertices[k*3 + 1] = plane->points[plane->triangles[k]*3 + 1]; mesh.vertices[k*3 + 2] = plane->points[plane->triangles[k]*3 + 2]; - + mesh.normals[k*3] = plane->normals[plane->triangles[k]*3]; mesh.normals[k*3 + 1] = plane->normals[plane->triangles[k]*3 + 1]; mesh.normals[k*3 + 2] = plane->normals[plane->triangles[k]*3 + 2]; - + mesh.texcoords[k*2] = plane->tcoords[plane->triangles[k]*2]; mesh.texcoords[k*2 + 1] = plane->tcoords[plane->triangles[k]*2 + 1]; } @@ -922,7 +922,7 @@ Mesh GenMeshPlane(float width, float length, int resX, int resZ) #endif // Upload vertex data to GPU (static mesh) - rlLoadMesh(&mesh, false); + rlLoadMesh(&mesh, false); return mesh; } @@ -960,7 +960,7 @@ Mesh GenMeshCube(float width, float height, float length) -width/2, height/2, length/2, -width/2, height/2, -length/2 }; - + float texcoords[] = { 0.0f, 0.0f, 1.0f, 0.0f, @@ -987,7 +987,7 @@ Mesh GenMeshCube(float width, float height, float length) 1.0f, 1.0f, 0.0f, 1.0f }; - + float normals[] = { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, @@ -1017,15 +1017,15 @@ Mesh GenMeshCube(float width, float height, float length) mesh.vertices = (float *)malloc(24*3*sizeof(float)); memcpy(mesh.vertices, vertices, 24*3*sizeof(float)); - + mesh.texcoords = (float *)malloc(24*2*sizeof(float)); memcpy(mesh.texcoords, texcoords, 24*2*sizeof(float)); - + mesh.normals = (float *)malloc(24*3*sizeof(float)); memcpy(mesh.normals, normals, 24*3*sizeof(float)); - + mesh.indices = (unsigned short *)malloc(36*sizeof(unsigned short)); - + int k = 0; // Indices can be initialized right now @@ -1040,10 +1040,10 @@ Mesh GenMeshCube(float width, float height, float length) k++; } - + mesh.vertexCount = 24; mesh.triangleCount = 12; - + #else // Use par_shapes library to generate cube mesh /* // Platonic solids: @@ -1057,11 +1057,11 @@ par_shapes_mesh* par_shapes_create_icosahedron(); // 20 sides polyhedron // NOTE: No normals/texcoords generated by default par_shapes_mesh *cube = par_shapes_create_cube(); cube->tcoords = PAR_MALLOC(float, 2*cube->npoints); - for (int i = 0; i < 2*cube->npoints; i++) cube->tcoords[i] = 0.0f; + for (int i = 0; i < 2*cube->npoints; i++) cube->tcoords[i] = 0.0f; par_shapes_scale(cube, width, height, length); par_shapes_translate(cube, -width/2, 0.0f, -length/2); par_shapes_compute_normals(cube); - + mesh.vertices = (float *)malloc(cube->ntriangles*3*3*sizeof(float)); mesh.texcoords = (float *)malloc(cube->ntriangles*3*2*sizeof(float)); mesh.normals = (float *)malloc(cube->ntriangles*3*3*sizeof(float)); @@ -1074,11 +1074,11 @@ par_shapes_mesh* par_shapes_create_icosahedron(); // 20 sides polyhedron mesh.vertices[k*3] = cube->points[cube->triangles[k]*3]; mesh.vertices[k*3 + 1] = cube->points[cube->triangles[k]*3 + 1]; mesh.vertices[k*3 + 2] = cube->points[cube->triangles[k]*3 + 2]; - + mesh.normals[k*3] = cube->normals[cube->triangles[k]*3]; mesh.normals[k*3 + 1] = cube->normals[cube->triangles[k]*3 + 1]; mesh.normals[k*3 + 2] = cube->normals[cube->triangles[k]*3 + 2]; - + mesh.texcoords[k*2] = cube->tcoords[cube->triangles[k]*2]; mesh.texcoords[k*2 + 1] = cube->tcoords[cube->triangles[k]*2 + 1]; } @@ -1087,7 +1087,7 @@ par_shapes_mesh* par_shapes_create_icosahedron(); // 20 sides polyhedron #endif // Upload vertex data to GPU (static mesh) - rlLoadMesh(&mesh, false); + rlLoadMesh(&mesh, false); return mesh; } @@ -1099,8 +1099,8 @@ RLAPI Mesh GenMeshSphere(float radius, int rings, int slices) par_shapes_mesh *sphere = par_shapes_create_parametric_sphere(slices, rings); par_shapes_scale(sphere, radius, radius, radius); - // NOTE: Soft normals are computed internally - + // NOTE: Soft normals are computed internally + mesh.vertices = (float *)malloc(sphere->ntriangles*3*3*sizeof(float)); mesh.texcoords = (float *)malloc(sphere->ntriangles*3*2*sizeof(float)); mesh.normals = (float *)malloc(sphere->ntriangles*3*3*sizeof(float)); @@ -1113,19 +1113,19 @@ RLAPI Mesh GenMeshSphere(float radius, int rings, int slices) mesh.vertices[k*3] = sphere->points[sphere->triangles[k]*3]; mesh.vertices[k*3 + 1] = sphere->points[sphere->triangles[k]*3 + 1]; mesh.vertices[k*3 + 2] = sphere->points[sphere->triangles[k]*3 + 2]; - + mesh.normals[k*3] = sphere->normals[sphere->triangles[k]*3]; mesh.normals[k*3 + 1] = sphere->normals[sphere->triangles[k]*3 + 1]; mesh.normals[k*3 + 2] = sphere->normals[sphere->triangles[k]*3 + 2]; - + mesh.texcoords[k*2] = sphere->tcoords[sphere->triangles[k]*2]; mesh.texcoords[k*2 + 1] = sphere->tcoords[sphere->triangles[k]*2 + 1]; } par_shapes_free_mesh(sphere); - + // Upload vertex data to GPU (static mesh) - rlLoadMesh(&mesh, false); + rlLoadMesh(&mesh, false); return mesh; } @@ -1137,8 +1137,8 @@ RLAPI Mesh GenMeshHemiSphere(float radius, int rings, int slices) par_shapes_mesh *sphere = par_shapes_create_hemisphere(slices, rings); par_shapes_scale(sphere, radius, radius, radius); - // NOTE: Soft normals are computed internally - + // NOTE: Soft normals are computed internally + mesh.vertices = (float *)malloc(sphere->ntriangles*3*3*sizeof(float)); mesh.texcoords = (float *)malloc(sphere->ntriangles*3*2*sizeof(float)); mesh.normals = (float *)malloc(sphere->ntriangles*3*3*sizeof(float)); @@ -1151,19 +1151,19 @@ RLAPI Mesh GenMeshHemiSphere(float radius, int rings, int slices) mesh.vertices[k*3] = sphere->points[sphere->triangles[k]*3]; mesh.vertices[k*3 + 1] = sphere->points[sphere->triangles[k]*3 + 1]; mesh.vertices[k*3 + 2] = sphere->points[sphere->triangles[k]*3 + 2]; - + mesh.normals[k*3] = sphere->normals[sphere->triangles[k]*3]; mesh.normals[k*3 + 1] = sphere->normals[sphere->triangles[k]*3 + 1]; mesh.normals[k*3 + 2] = sphere->normals[sphere->triangles[k]*3 + 2]; - + mesh.texcoords[k*2] = sphere->tcoords[sphere->triangles[k]*2]; mesh.texcoords[k*2 + 1] = sphere->tcoords[sphere->triangles[k]*2 + 1]; } par_shapes_free_mesh(sphere); - + // Upload vertex data to GPU (static mesh) - rlLoadMesh(&mesh, false); + rlLoadMesh(&mesh, false); return mesh; } @@ -1175,7 +1175,7 @@ Mesh GenMeshCylinder(float radius, float height, int slices) // Instance a cylinder that sits on the Z=0 plane using the given tessellation // levels across the UV domain. Think of "slices" like a number of pizza - // slices, and "stacks" like a number of stacked rings. + // slices, and "stacks" like a number of stacked rings. // Height and radius are both 1.0, but they can easily be changed with par_shapes_scale par_shapes_mesh *cylinder = par_shapes_create_cylinder(slices, 8); par_shapes_scale(cylinder, radius, radius, height); @@ -1187,16 +1187,16 @@ Mesh GenMeshCylinder(float radius, float height, int slices) for (int i = 0; i < 2*capTop->npoints; i++) capTop->tcoords[i] = 0.0f; par_shapes_rotate(capTop, -PI/2.0f, (float[]){ 1, 0, 0 }); par_shapes_translate(capTop, 0, height, 0); - + // Generate an orientable disk shape (bottom cap) par_shapes_mesh *capBottom = par_shapes_create_disk(radius, slices, (float[]){ 0, 0, 0 }, (float[]){ 0, 0, -1 }); capBottom->tcoords = PAR_MALLOC(float, 2*capBottom->npoints); for (int i = 0; i < 2*capBottom->npoints; i++) capBottom->tcoords[i] = 0.95f; par_shapes_rotate(capBottom, PI/2.0f, (float[]){ 1, 0, 0 }); - + par_shapes_merge_and_free(cylinder, capTop); par_shapes_merge_and_free(cylinder, capBottom); - + mesh.vertices = (float *)malloc(cylinder->ntriangles*3*3*sizeof(float)); mesh.texcoords = (float *)malloc(cylinder->ntriangles*3*2*sizeof(float)); mesh.normals = (float *)malloc(cylinder->ntriangles*3*3*sizeof(float)); @@ -1209,19 +1209,19 @@ Mesh GenMeshCylinder(float radius, float height, int slices) mesh.vertices[k*3] = cylinder->points[cylinder->triangles[k]*3]; mesh.vertices[k*3 + 1] = cylinder->points[cylinder->triangles[k]*3 + 1]; mesh.vertices[k*3 + 2] = cylinder->points[cylinder->triangles[k]*3 + 2]; - + mesh.normals[k*3] = cylinder->normals[cylinder->triangles[k]*3]; mesh.normals[k*3 + 1] = cylinder->normals[cylinder->triangles[k]*3 + 1]; mesh.normals[k*3 + 2] = cylinder->normals[cylinder->triangles[k]*3 + 2]; - + mesh.texcoords[k*2] = cylinder->tcoords[cylinder->triangles[k]*2]; mesh.texcoords[k*2 + 1] = cylinder->tcoords[cylinder->triangles[k]*2 + 1]; } par_shapes_free_mesh(cylinder); - + // Upload vertex data to GPU (static mesh) - rlLoadMesh(&mesh, false); + rlLoadMesh(&mesh, false); return mesh; } @@ -1233,7 +1233,7 @@ Mesh GenMeshTorus(float radius, float size, int radSeg, int sides) if (radius > 1.0f) radius = 1.0f; else if (radius < 0.1f) radius = 0.1f; - + // Create a donut that sits on the Z=0 plane with the specified inner radius // The outer radius can be controlled with par_shapes_scale par_shapes_mesh *torus = par_shapes_create_torus(radSeg, sides, radius); @@ -1251,19 +1251,19 @@ Mesh GenMeshTorus(float radius, float size, int radSeg, int sides) mesh.vertices[k*3] = torus->points[torus->triangles[k]*3]; mesh.vertices[k*3 + 1] = torus->points[torus->triangles[k]*3 + 1]; mesh.vertices[k*3 + 2] = torus->points[torus->triangles[k]*3 + 2]; - + mesh.normals[k*3] = torus->normals[torus->triangles[k]*3]; mesh.normals[k*3 + 1] = torus->normals[torus->triangles[k]*3 + 1]; mesh.normals[k*3 + 2] = torus->normals[torus->triangles[k]*3 + 2]; - + mesh.texcoords[k*2] = torus->tcoords[torus->triangles[k]*2]; mesh.texcoords[k*2 + 1] = torus->tcoords[torus->triangles[k]*2 + 1]; } par_shapes_free_mesh(torus); - + // Upload vertex data to GPU (static mesh) - rlLoadMesh(&mesh, false); + rlLoadMesh(&mesh, false); return mesh; } @@ -1272,7 +1272,7 @@ Mesh GenMeshTorus(float radius, float size, int radSeg, int sides) Mesh GenMeshKnot(float radius, float size, int radSeg, int sides) { Mesh mesh = { 0 }; - + if (radius > 3.0f) radius = 3.0f; else if (radius < 0.5f) radius = 0.5f; @@ -1291,19 +1291,19 @@ Mesh GenMeshKnot(float radius, float size, int radSeg, int sides) mesh.vertices[k*3] = knot->points[knot->triangles[k]*3]; mesh.vertices[k*3 + 1] = knot->points[knot->triangles[k]*3 + 1]; mesh.vertices[k*3 + 2] = knot->points[knot->triangles[k]*3 + 2]; - + mesh.normals[k*3] = knot->normals[knot->triangles[k]*3]; mesh.normals[k*3 + 1] = knot->normals[knot->triangles[k]*3 + 1]; mesh.normals[k*3 + 2] = knot->normals[knot->triangles[k]*3 + 2]; - + mesh.texcoords[k*2] = knot->tcoords[knot->triangles[k]*2]; mesh.texcoords[k*2 + 1] = knot->tcoords[knot->triangles[k]*2 + 1]; } par_shapes_free_mesh(knot); - + // Upload vertex data to GPU (static mesh) - rlLoadMesh(&mesh, false); + rlLoadMesh(&mesh, false); return mesh; } @@ -1411,7 +1411,7 @@ Mesh GenMeshHeightmap(Image heightmap, Vector3 size) } free(pixels); - + // Upload vertex data to GPU (static mesh) rlLoadMesh(&mesh, false); @@ -1771,9 +1771,9 @@ Mesh GenMeshCubicmap(Image cubicmap, Vector3 cubeSize) free(mapTexcoords); free(cubicmapPixels); // Free image pixel data - + // Upload vertex data to GPU (static mesh) - rlLoadMesh(&mesh, false); + rlLoadMesh(&mesh, false); return mesh; } @@ -1821,7 +1821,7 @@ void UnloadMaterial(Material material) // Unload loaded texture maps (avoid unloading default texture, managed by raylib) for (int i = 0; i < MAX_MATERIAL_MAPS; i++) { - if (material.maps[i].texture.id != GetTextureDefault().id) rlDeleteTextures(material.maps[i].texture.id); + if (material.maps[i].texture.id != GetTextureDefault().id) rlDeleteTextures(material.maps[i].texture.id); } } @@ -1842,7 +1842,7 @@ void DrawModelEx(Model model, Vector3 position, Vector3 rotationAxis, float rota Matrix matScale = MatrixScale(scale.x, scale.y, scale.z); Matrix matRotation = MatrixRotate(rotationAxis, rotationAngle*DEG2RAD); Matrix matTranslation = MatrixTranslate(position.x, position.y, position.z); - + Matrix matTransform = MatrixMultiply(MatrixMultiply(matScale, matRotation), matTranslation); // Combine model transformation matrix (model.transform) with matrix generated by function parameters (matTransform) @@ -2037,7 +2037,7 @@ bool CheckCollisionRaySphereEx(Ray ray, Vector3 spherePosition, float sphereRadi if (distance < sphereRadius) collisionDistance = vector + sqrtf(d); else collisionDistance = vector - sqrtf(d); - + // Calculate collision point Vector3 cPoint = Vector3Add(ray.position, Vector3Scale(ray.direction, collisionDistance)); @@ -2097,7 +2097,7 @@ RayHitInfo GetCollisionRayModel(Ray ray, Model *model) b = vertdata[i*3 + 1]; c = vertdata[i*3 + 2]; } - + a = Vector3Transform(a, model->transform); b = Vector3Transform(b, model->transform); c = Vector3Transform(c, model->transform); @@ -2231,7 +2231,7 @@ void MeshTangents(Mesh *mesh) { if (mesh->tangents == NULL) mesh->tangents = (float *)malloc(mesh->vertexCount*4*sizeof(float)); else TraceLog(LOG_WARNING, "Mesh tangents already exist"); - + Vector3 *tan1 = (Vector3 *)malloc(mesh->vertexCount*sizeof(Vector3)); Vector3 *tan2 = (Vector3 *)malloc(mesh->vertexCount*sizeof(Vector3)); @@ -2264,7 +2264,7 @@ void MeshTangents(Mesh *mesh) Vector3 sdir = { (t2*x1 - t1*x2)*r, (t2*y1 - t1*y2)*r, (t2*z1 - t1*z2)*r }; Vector3 tdir = { (s1*x2 - s2*x1)*r, (s1*y2 - s2*y1)*r, (s1*z2 - s2*z1)*r }; - + tan1[i + 0] = sdir; tan1[i + 1] = sdir; tan1[i + 2] = sdir; @@ -2296,10 +2296,10 @@ void MeshTangents(Mesh *mesh) mesh->tangents[i*4 + 3] = (Vector3DotProduct(Vector3CrossProduct(normal, tangent), tan2[i]) < 0.0f) ? -1.0f : 1.0f; #endif } - + free(tan1); free(tan2); - + TraceLog(LOG_INFO, "Tangents computed for mesh"); } @@ -2311,7 +2311,7 @@ void MeshBinormals(Mesh *mesh) Vector3 normal = { mesh->normals[i*3 + 0], mesh->normals[i*3 + 1], mesh->normals[i*3 + 2] }; Vector3 tangent = { mesh->tangents[i*4 + 0], mesh->tangents[i*4 + 1], mesh->tangents[i*4 + 2] }; float tangentW = mesh->tangents[i*4 + 3]; - + // TODO: Register computed binormal in mesh->binormal ? // Vector3 binormal = Vector3Multiply(Vector3CrossProduct(normal, tangent), tangentW); } @@ -2740,11 +2740,11 @@ static Material LoadMTL(const char *fileName) static Mesh LoadIQM(const char *fileName) { Mesh mesh = { 0 }; - + // TODO: Load IQM file - + return mesh; -} +} #endif #if defined(SUPPORT_FILEFORMAT_GLTF) @@ -2752,10 +2752,10 @@ static Mesh LoadIQM(const char *fileName) static Mesh LoadGLTF(const char *fileName) { Mesh mesh = { 0 }; - + // glTF file loading FILE *gltfFile = fopen(fileName, "rb"); - + if (gltfFile == NULL) { TraceLog(LOG_WARNING, "[%s] glTF file could not be opened", fileName); @@ -2768,31 +2768,31 @@ static Mesh LoadGLTF(const char *fileName) void *buffer = malloc(size); fread(buffer, size, 1, gltfFile); - + fclose(gltfFile); // glTF data loading cgltf_options options = {0}; cgltf_data data; cgltf_result result = cgltf_parse(&options, buffer, size, &data); - + free(buffer); - + if (result == cgltf_result_success) { printf("Type: %u\n", data.file_type); printf("Version: %d\n", data.version); printf("Meshes: %lu\n", data.meshes_count); - + // TODO: Process glTF data and map to mesh - + // NOTE: data.buffers[] and data.images[] should be loaded // using buffers[n].uri and images[n].uri... or use cgltf_load_buffers(&options, data, fileName); - + cgltf_free(&data); } else TraceLog(LOG_WARNING, "[%s] glTF data could not be loaded", fileName); - return mesh; + return mesh; } #endif diff --git a/src/raudio.c b/src/raudio.c index b19c7d86..e1c9fd48 100644 --- a/src/raudio.c +++ b/src/raudio.c @@ -1245,7 +1245,7 @@ Music LoadMusicStream(const char *fileName) void UnloadMusicStream(Music music) { if (music == NULL) return; - + CloseAudioStream(music->stream); #if defined(SUPPORT_FILEFORMAT_OGG) @@ -1311,7 +1311,7 @@ void ResumeMusicStream(Music music) void StopMusicStream(Music music) { if (music == NULL) return; - + StopAudioStream(music->stream); // Restart music context @@ -1343,7 +1343,7 @@ void StopMusicStream(Music music) void UpdateMusicStream(Music music) { if (music == NULL) return; - + bool streamEnding = false; unsigned int subBufferSizeInFrames = ((AudioBuffer *)music->stream.audioBuffer)->bufferSizeInFrames/2; @@ -1393,16 +1393,16 @@ void UpdateMusicStream(Music music) } break; #endif #if defined(SUPPORT_FILEFORMAT_MOD) - case MUSIC_MODULE_MOD: + case MUSIC_MODULE_MOD: { // NOTE: 3rd parameter (nbsample) specify the number of stereo 16bits samples you want, so sampleCount/2 - jar_mod_fillbuffer(&music->ctxMod, (short *)pcm, samplesCount/2, 0); + jar_mod_fillbuffer(&music->ctxMod, (short *)pcm, samplesCount/2, 0); } break; #endif default: break; } - + UpdateAudioStream(music->stream, pcm, samplesCount); if ((music->ctxType == MUSIC_MODULE_XM) || (music->ctxType == MUSIC_MODULE_MOD)) { @@ -1475,7 +1475,7 @@ void SetMusicLoopCount(Music music, int count) float GetMusicTimeLength(Music music) { float totalSeconds = 0.0f; - + if (music != NULL) totalSeconds = (float)music->totalSamples/(music->stream.sampleRate*music->stream.channels); return totalSeconds; diff --git a/src/rlgl.h b/src/rlgl.h index f2762637..c9f15385 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -356,7 +356,7 @@ typedef unsigned char byte; LOC_MAP_PREFILTER, LOC_MAP_BRDF } ShaderLocationIndex; - + // Shader uniform data types typedef enum { UNIFORM_FLOAT = 0, @@ -993,14 +993,14 @@ void rlPushMatrix(void) // Pop lattest inserted matrix from stack void rlPopMatrix(void) -{ +{ if (stackCounter > 0) { Matrix mat = stack[stackCounter - 1]; *currentMatrix = mat; stackCounter--; } - + if ((stackCounter == 0) && (currentMatrixMode == RL_MODELVIEW)) { currentMatrix = &modelview; @@ -1141,7 +1141,7 @@ void rlEnd(void) // Make sure vertexCount is the same for vertices, texcoords, colors and normals // NOTE: In OpenGL 1.1, one glColor call can be made for all the subsequent glVertex calls - + // Make sure colors count match vertex count if (vertexData[currentBuffer].vCounter != vertexData[currentBuffer].cCounter) { @@ -1156,7 +1156,7 @@ void rlEnd(void) vertexData[currentBuffer].cCounter++; } } - + // Make sure texcoords count match vertex count if (vertexData[currentBuffer].vCounter != vertexData[currentBuffer].tcCounter) { @@ -1194,10 +1194,10 @@ void rlEnd(void) void rlVertex3f(float x, float y, float z) { Vector3 vec = { x, y, z }; - + // Transform provided vector if required if (useTransformMatrix) vec = Vector3Transform(vec, transformMatrix); - + // Verify that MAX_BATCH_ELEMENTS limit not reached if (vertexData[currentBuffer].vCounter < (MAX_BATCH_ELEMENTS*4)) { @@ -1499,7 +1499,7 @@ void rlglInit(int width, int height) //for (int i = 0; i < numComp; i++) TraceLog(LOG_INFO, "Supported compressed format: 0x%x", format[i]); // NOTE: We don't need that much data on screen... right now... - + // TODO: Automatize extensions loading using rlLoadExtensions() and GLAD // Actually, when rlglInit() is called in InitWindow() in core.c, // OpenGL required extensions have already been loaded (PLATFORM_DESKTOP) @@ -1512,7 +1512,7 @@ void rlglInit(int width, int height) // NOTE: On OpenGL 3.3 VAO and NPOT are supported by default vaoSupported = true; - + // Multiple texture extensions supported by default texNPOTSupported = true; texFloatSupported = true; @@ -1585,11 +1585,11 @@ void rlglInit(int width, int height) // Check texture float support if (strcmp(extList[i], (const char *)"GL_OES_texture_float") == 0) texFloatSupported = true; - + // Check depth texture support if ((strcmp(extList[i], (const char *)"GL_OES_depth_texture") == 0) || (strcmp(extList[i], (const char *)"GL_WEBGL_depth_texture") == 0)) texDepthSupported = true; - + if (strcmp(extList[i], (const char *)"GL_OES_depth24") == 0) maxDepthBits = 24; if (strcmp(extList[i], (const char *)"GL_OES_depth32") == 0) maxDepthBits = 32; #endif @@ -1648,8 +1648,8 @@ void rlglInit(int width, int height) if (debugMarkerSupported) TraceLog(LOG_INFO, "[EXTENSION] Debug Marker supported"); - - + + // Initialize buffers, default shaders and default textures //---------------------------------------------------------- @@ -1666,7 +1666,7 @@ void rlglInit(int width, int height) // Init default vertex arrays buffers LoadBuffersDefault(); - + // Init transformations matrix accumulator transformMatrix = MatrixIdentity(); @@ -1995,9 +1995,9 @@ unsigned int rlLoadTextureDepth(int width, int height, int bits, bool useRenderB { unsigned int id = 0; unsigned int glInternalFormat = GL_DEPTH_COMPONENT16; - + if ((bits != 16) && (bits != 24) && (bits != 32)) bits = 16; - + if (bits == 24) { #if defined(GRAPHICS_API_OPENGL_33) @@ -2006,7 +2006,7 @@ unsigned int rlLoadTextureDepth(int width, int height, int bits, bool useRenderB if (maxDepthBits >= 24) glInternalFormat = GL_DEPTH_COMPONENT24_OES; #endif } - + if (bits == 32) { #if defined(GRAPHICS_API_OPENGL_33) @@ -2021,7 +2021,7 @@ unsigned int rlLoadTextureDepth(int width, int height, int bits, bool useRenderB glGenTextures(1, &id); glBindTexture(GL_TEXTURE_2D, id); glTexImage2D(GL_TEXTURE_2D, 0, glInternalFormat, width, height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL); - + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); @@ -2036,10 +2036,10 @@ unsigned int rlLoadTextureDepth(int width, int height, int bits, bool useRenderB glGenRenderbuffers(1, &id); glBindRenderbuffer(GL_RENDERBUFFER, id); glRenderbufferStorage(GL_RENDERBUFFER, glInternalFormat, width, height); - + glBindRenderbuffer(GL_RENDERBUFFER, 0); } - + return id; } @@ -2053,7 +2053,7 @@ unsigned int rlLoadTextureCubemap(void *data, int size, int format) glGenTextures(1, &cubemapId); glBindTexture(GL_TEXTURE_CUBE_MAP, cubemapId); - + unsigned int glInternalFormat, glFormat, glType; rlGetGlTextureFormats(format, &glInternalFormat, &glFormat, &glType); @@ -2084,7 +2084,7 @@ unsigned int rlLoadTextureCubemap(void *data, int size, int format) #endif } } - + // Set cubemap texture sampling parameters glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); @@ -2178,14 +2178,14 @@ void rlUnloadTexture(unsigned int id) RenderTexture2D rlLoadRenderTexture(int width, int height, int format, int depthBits, bool useDepthTexture) { RenderTexture2D target = { 0 }; - + if (useDepthTexture && texDepthSupported) target.depthTexture = true; -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) // Create the framebuffer object glGenFramebuffers(1, &target.id); glBindFramebuffer(GL_FRAMEBUFFER, target.id); - + // Create fbo color texture attachment //----------------------------------------------------------------------------------------------------- if ((format != -1) && (format < COMPRESSED_DXT1_RGB)) @@ -2198,7 +2198,7 @@ RenderTexture2D rlLoadRenderTexture(int width, int height, int format, int depth target.texture.mipmaps = 1; } //----------------------------------------------------------------------------------------------------- - + // Create fbo depth renderbuffer/texture //----------------------------------------------------------------------------------------------------- if (depthBits > 0) @@ -2210,7 +2210,7 @@ RenderTexture2D rlLoadRenderTexture(int width, int height, int format, int depth target.depth.mipmaps = 1; } //----------------------------------------------------------------------------------------------------- - + // Attach color texture and depth renderbuffer to FBO //----------------------------------------------------------------------------------------------------- rlRenderTextureAttach(target, target.texture.id, 0); // COLOR attachment @@ -2235,12 +2235,12 @@ void rlRenderTextureAttach(RenderTexture2D target, unsigned int id, int attachTy glBindFramebuffer(GL_FRAMEBUFFER, target.id); if (attachType == 0) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, id, 0); - else if (attachType == 1) + else if (attachType == 1) { if (target.depthTexture) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, id, 0); else glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, id); } - + glBindFramebuffer(GL_FRAMEBUFFER, 0); } @@ -2248,7 +2248,7 @@ void rlRenderTextureAttach(RenderTexture2D target, unsigned int id, int attachTy bool rlRenderTextureComplete(RenderTexture target) { glBindFramebuffer(GL_FRAMEBUFFER, target.id); - + GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); if (status != GL_FRAMEBUFFER_COMPLETE) @@ -2264,9 +2264,9 @@ bool rlRenderTextureComplete(RenderTexture target) default: break; } } - + glBindFramebuffer(GL_FRAMEBUFFER, 0); - + return (status == GL_FRAMEBUFFER_COMPLETE); } @@ -2349,7 +2349,7 @@ void rlLoadMesh(Mesh *mesh, bool dynamic) TraceLog(LOG_WARNING, "Trying to re-load an already loaded mesh"); return; } - + mesh->vaoId = 0; // Vertex Array Object mesh->vboId[0] = 0; // Vertex positions VBO mesh->vboId[1] = 0; // Vertex texcoords VBO @@ -2766,7 +2766,7 @@ unsigned char *rlReadScreenPixels(int width, int height) for (int x = 0; x < (width*4); x++) { imgData[((height - 1) - y)*width*4 + x] = screenData[(y*width*4) + x]; // Flip line - + // Set alpha component value to 255 (no trasparent image retrieval) // NOTE: Alpha value has already been applied to RGB in framebuffer, we don't need it! if (((x + 1)%4) == 0) imgData[((height - 1) - y)*width*4 + x] = 255; @@ -2822,7 +2822,7 @@ void *rlReadTexturePixels(Texture2D texture) // We are using Option 1, just need to care for texture format on retrieval // NOTE: This behaviour could be conditioned by graphic driver... RenderTexture2D fbo = rlLoadRenderTexture(texture.width, texture.height, UNCOMPRESSED_R8G8B8A8, 16, false); - + glBindFramebuffer(GL_FRAMEBUFFER, fbo.id); glBindTexture(GL_TEXTURE_2D, 0); @@ -2836,7 +2836,7 @@ void *rlReadTexturePixels(Texture2D texture) // Get OpenGL internal formats and data type from our texture format unsigned int glInternalFormat, glFormat, glType; rlGetGlTextureFormats(texture.format, &glInternalFormat, &glFormat, &glType); - + // NOTE: We read data as RGBA because FBO texture is configured as RGBA, despite binding a RGB texture... glReadPixels(0, 0, texture.width, texture.height, glFormat, glType, pixels); @@ -3064,7 +3064,7 @@ void SetShaderValueV(Shader shader, int uniformLoc, const void *value, int unifo case UNIFORM_SAMPLER2D: glUniform1iv(uniformLoc, count, (int *)value); break; default: TraceLog(LOG_WARNING, "Shader uniform could not be set data type not recognized"); } - + //glUseProgram(0); // Avoid reseting current shader program, in case other uniforms are set #endif } @@ -3143,7 +3143,7 @@ Texture2D GenTextureCubemap(Shader shader, Texture2D skyHDR, int size) // NOTE: Faces are stored as 32 bit floating point values glGenTextures(1, &cubemap.id); glBindTexture(GL_TEXTURE_CUBE_MAP, cubemap.id); - for (unsigned int i = 0; i < 6; i++) + for (unsigned int i = 0; i < 6; i++) { #if defined(GRAPHICS_API_OPENGL_33) glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB32F, size, size, 0, GL_RGB, GL_FLOAT, NULL); @@ -3151,7 +3151,7 @@ Texture2D GenTextureCubemap(Shader shader, Texture2D skyHDR, int size) if (texFloatSupported) glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, size, size, 0, GL_RGB, GL_FLOAT, NULL); #endif } - + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); #if defined(GRAPHICS_API_OPENGL_33) @@ -3231,7 +3231,7 @@ Texture2D GenTextureIrradiance(Shader shader, Texture2D cubemap, int size) { glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB16F, size, size, 0, GL_RGB, GL_FLOAT, NULL); } - + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); @@ -3309,7 +3309,7 @@ Texture2D GenTexturePrefilter(Shader shader, Texture2D cubemap, int size) { glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB16F, size, size, 0, GL_RGB, GL_FLOAT, NULL); } - + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); @@ -3417,7 +3417,7 @@ Texture2D GenTextureBRDF(Shader shader, int size) // Unbind framebuffer and textures glBindFramebuffer(GL_FRAMEBUFFER, 0); - + // Unload framebuffer but keep color texture glDeleteRenderbuffers(1, &rbo); glDeleteFramebuffers(1, &fbo); @@ -3464,7 +3464,7 @@ void EndBlendMode(void) void BeginScissorMode(int x, int y, int width, int height) { rlglDraw(); // Force drawing elements - + glEnable(GL_SCISSOR_TEST); glScissor(x, screenHeight - (y + height), width, height); } @@ -3473,7 +3473,7 @@ void BeginScissorMode(int x, int y, int width, int height) void EndScissorMode(void) { rlglDraw(); // Force drawing elements - + glDisable(GL_SCISSOR_TEST); } @@ -4050,7 +4050,7 @@ static void LoadBuffersDefault(void) glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(short)*6*MAX_BATCH_ELEMENTS, vertexData[i].indices, GL_STATIC_DRAW); #endif } - + TraceLog(LOG_INFO, "Internal buffers uploaded successfully (GPU)"); // Unbind the current VAO @@ -4073,7 +4073,7 @@ static void UpdateBuffersDefault(void) glBindBuffer(GL_ARRAY_BUFFER, vertexData[currentBuffer].vboId[0]); glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(float)*3*vertexData[currentBuffer].vCounter, vertexData[currentBuffer].vertices); //glBufferData(GL_ARRAY_BUFFER, sizeof(float)*3*4*MAX_BATCH_ELEMENTS, vertexData[currentBuffer].vertices, GL_DYNAMIC_DRAW); // Update all buffer - + // Texture coordinates buffer glBindBuffer(GL_ARRAY_BUFFER, vertexData[currentBuffer].vboId[1]); glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(float)*2*vertexData[currentBuffer].vCounter, vertexData[currentBuffer].texcoords); @@ -4083,13 +4083,13 @@ static void UpdateBuffersDefault(void) glBindBuffer(GL_ARRAY_BUFFER, vertexData[currentBuffer].vboId[2]); glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(unsigned char)*4*vertexData[currentBuffer].vCounter, vertexData[currentBuffer].colors); //glBufferData(GL_ARRAY_BUFFER, sizeof(float)*4*4*MAX_BATCH_ELEMENTS, vertexData[currentBuffer].colors, GL_DYNAMIC_DRAW); // Update all buffer - + // NOTE: glMapBuffer() causes sync issue. - // If GPU is working with this buffer, glMapBuffer() will wait(stall) until GPU to finish its job. + // If GPU is working with this buffer, glMapBuffer() will wait(stall) until GPU to finish its job. // To avoid waiting (idle), you can call first glBufferData() with NULL pointer before glMapBuffer(). // If you do that, the previous data in PBO will be discarded and glMapBuffer() returns a new // allocated pointer immediately even if GPU is still working with the previous data. - + // Another option: map the buffer object into client's memory // Probably this code could be moved somewhere else... // vertexData[currentBuffer].vertices = (float *)glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE); @@ -4135,7 +4135,7 @@ static void DrawBuffersDefault(void) glUniform1i(currentShader.locs[LOC_MAP_DIFFUSE], 0); // NOTE: Additional map textures not considered for default buffers drawing - + int vertexOffset = 0; if (vaoSupported) glBindVertexArray(vertexData[currentBuffer].vaoId); @@ -4160,7 +4160,7 @@ static void DrawBuffersDefault(void) } glActiveTexture(GL_TEXTURE0); - + for (int i = 0; i < drawsCounter; i++) { glBindTexture(GL_TEXTURE_2D, draws[i].textureId); @@ -4170,7 +4170,7 @@ static void DrawBuffersDefault(void) { #if defined(GRAPHICS_API_OPENGL_33) // We need to define the number of indices to be processed: quadsCount*6 - // NOTE: The final parameter tells the GPU the offset in bytes from the + // NOTE: The final parameter tells the GPU the offset in bytes from the // start of the index buffer to the location of the first index to process glDrawElements(GL_TRIANGLES, draws[i].vertexCount/4*6, GL_UNSIGNED_INT, (GLvoid *)(sizeof(GLuint)*vertexOffset/4*6)); #elif defined(GRAPHICS_API_OPENGL_ES2) @@ -4216,7 +4216,7 @@ static void DrawBuffersDefault(void) } drawsCounter = 1; - + // Change to next buffer in the list currentBuffer++; if (currentBuffer >= MAX_BATCH_BUFFERING) currentBuffer = 0; @@ -4369,14 +4369,14 @@ static void GenDrawCube(void) static VrStereoConfig SetStereoConfig(VrDeviceInfo hmd, Shader distortion) { VrStereoConfig config = { 0 }; - + // Initialize framebuffer and textures for stereo rendering // NOTE: Screen size should match HMD aspect ratio config.stereoFbo = rlLoadRenderTexture(screenWidth, screenHeight, UNCOMPRESSED_R8G8B8A8, 24, false); - + // Assign distortion shader config.distortionShader = distortion; - + // Compute aspect ratio float aspect = ((float)hmd.hResolution*0.5f)/(float)hmd.vResolution; @@ -4442,7 +4442,7 @@ static VrStereoConfig SetStereoConfig(VrDeviceInfo hmd, Shader distortion) SetShaderValue(config.distortionShader, GetShaderLocation(config.distortionShader, "hmdWarpParam"), hmd.lensDistortionValues, UNIFORM_VEC4); SetShaderValue(config.distortionShader, GetShaderLocation(config.distortionShader, "chromaAbParam"), hmd.chromaAbCorrection, UNIFORM_VEC4); #endif - + return config; } diff --git a/src/shapes.c b/src/shapes.c index 8976c81c..87bb573c 100644 --- a/src/shapes.c +++ b/src/shapes.c @@ -143,7 +143,7 @@ void DrawLineEx(Vector2 startPos, Vector2 endPos, float thick, Color color) rlTexCoord2f(recTexShapes.x/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); rlVertex2f(0.0f, thick); - + rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); rlVertex2f(d, thick); @@ -187,7 +187,7 @@ void DrawCircle(int centerX, int centerY, float radius, Color color) void DrawCircleSector(Vector2 center, float radius, int startAngle, int endAngle, Color color) { #define CIRCLE_SECTOR_LENGTH 10 - + #if defined(SUPPORT_QUADS_DRAW_MODE) if (rlCheckBufferLimit(4*((360/CIRCLE_SECTOR_LENGTH)/2))) rlglDraw(); @@ -307,10 +307,10 @@ void DrawRectanglePro(Rectangle rec, Vector2 origin, float rotation, Color color rlTexCoord2f(recTexShapes.x/texShapes.width, recTexShapes.y/texShapes.height); rlVertex2f(0.0f, 0.0f); - + rlTexCoord2f(recTexShapes.x/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); rlVertex2f(0.0f, rec.height); - + rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); rlVertex2f(rec.width, rec.height); diff --git a/src/text.c b/src/text.c index 17f6d9dd..9a7d690d 100644 --- a/src/text.c +++ b/src/text.c @@ -790,14 +790,14 @@ void DrawTextEx(Font font, const char *text, Vector2 position, float fontSize, f } // Draw text using font inside rectangle limits -void DrawTextRec(Font font, const char *text, Rectangle rec, float fontSize, float spacing, bool wordWrap, Color tint) +void DrawTextRec(Font font, const char *text, Rectangle rec, float fontSize, float spacing, bool wordWrap, Color tint) { DrawTextRecEx(font, text, rec, fontSize, spacing, wordWrap, tint, 0, 0, WHITE, WHITE); } // Draw text using font inside rectangle limits with support for text selection -void DrawTextRecEx(Font font, const char *text, Rectangle rec, float fontSize, float spacing, bool wordWrap, Color tint, - int selectStart, int selectLength, Color selectText, Color selectBack) +void DrawTextRecEx(Font font, const char *text, Rectangle rec, float fontSize, float spacing, bool wordWrap, Color tint, + int selectStart, int selectLength, Color selectText, Color selectBack) { int length = strlen(text); int textOffsetX = 0; // Offset between characters @@ -813,12 +813,12 @@ void DrawTextRecEx(Font font, const char *text, Rectangle rec, float fontSize, f int state = wordWrap? MEASURE_STATE : DRAW_STATE; int startLine = -1; // Index where to begin drawing (where a line begins) int endLine = -1; // Index where to stop drawing (where a line ends) - + for (int i = 0; i < length; i++) { int glyphWidth = 0; letter = (unsigned char)text[i]; - + if (letter != '\n') { if ((unsigned char)text[i] == 0xc2) // UTF-8 encoding identification HACK! @@ -836,41 +836,41 @@ void DrawTextRecEx(Font font, const char *text, Rectangle rec, float fontSize, f i++; } else index = GetGlyphIndex(font, (unsigned char)text[i]); - - glyphWidth = (font.chars[index].advanceX == 0)? + + glyphWidth = (font.chars[index].advanceX == 0)? (int)(font.chars[index].rec.width*scaleFactor + spacing): (int)(font.chars[index].advanceX*scaleFactor + spacing); } - + // NOTE: When wordWrap is ON we first measure how much of the text we can draw - // before going outside of the `rec` container. We store this info inside + // before going outside of the `rec` container. We store this info inside // `startLine` and `endLine` then we change states, draw the text between those two // variables then change states again and again recursively until the end of the text // (or until we get outside of the container). - // When wordWrap is OFF we don't need the measure state so we go to the drawing - // state immediately and begin drawing on the next line before we can get outside + // When wordWrap is OFF we don't need the measure state so we go to the drawing + // state immediately and begin drawing on the next line before we can get outside // the container. - if (state == MEASURE_STATE) + if (state == MEASURE_STATE) { if ((letter == ' ') || (letter == '\t') || (letter == '\n')) endLine = i; - - if ((textOffsetX + glyphWidth + 1) >= rec.width) + + if ((textOffsetX + glyphWidth + 1) >= rec.width) { endLine = (endLine < 1) ? i : endLine; if (i == endLine) endLine -= 1; if ((startLine + 1) == endLine) endLine = i - 1; state = !state; - } - else if ((i + 1) == length) + } + else if ((i + 1) == length) { endLine = i; state = !state; } - else if (letter == '\n') + else if (letter == '\n') { state = !state; } - + if (state == DRAW_STATE) { textOffsetX = 0; @@ -878,8 +878,8 @@ void DrawTextRecEx(Font font, const char *text, Rectangle rec, float fontSize, f glyphWidth = 0; } - } - else + } + else { if (letter == '\n') { @@ -888,17 +888,17 @@ void DrawTextRecEx(Font font, const char *text, Rectangle rec, float fontSize, f textOffsetY += (int)((font.baseSize + font.baseSize/2)*scaleFactor); textOffsetX = 0; } - } - else + } + else { if (!wordWrap && ((textOffsetX + glyphWidth + 1) >= rec.width)) { textOffsetY += (int)((font.baseSize + font.baseSize/2)*scaleFactor); textOffsetX = 0; } - + if ((textOffsetY + (int)((font.baseSize + font.baseSize/2)*scaleFactor)) > rec.height) break; - + //draw selected bool isGlyphSelected = false; if ((selectStart >= 0) && (i >= selectStart) && (i < (selectStart + selectLength))) @@ -907,7 +907,7 @@ void DrawTextRecEx(Font font, const char *text, Rectangle rec, float fontSize, f DrawRectangleRec(strec, selectBack); isGlyphSelected = true; } - + //draw glyph if ((letter != ' ') && (letter != '\t')) { @@ -915,12 +915,12 @@ void DrawTextRecEx(Font font, const char *text, Rectangle rec, float fontSize, f (Rectangle){ rec.x + textOffsetX + font.chars[index].offsetX*scaleFactor, rec.y + textOffsetY + font.chars[index].offsetY*scaleFactor, font.chars[index].rec.width*scaleFactor, - font.chars[index].rec.height*scaleFactor }, (Vector2){ 0, 0 }, 0.0f, + font.chars[index].rec.height*scaleFactor }, (Vector2){ 0, 0 }, 0.0f, (!isGlyphSelected) ? tint : selectText); } } - - if (wordWrap && (i == endLine)) + + if (wordWrap && (i == endLine)) { textOffsetY += (int)((font.baseSize + font.baseSize/2)*scaleFactor); textOffsetX = 0; @@ -930,7 +930,7 @@ void DrawTextRecEx(Font font, const char *text, Rectangle rec, float fontSize, f state = !state; } } - + textOffsetX += glyphWidth; } } @@ -968,11 +968,11 @@ Vector2 MeasureTextEx(Font font, const char *text, float fontSize, float spacing unsigned char letter = 0; // Current character int index = 0; // Index position in sprite font - + for (int i = 0; i < len; i++) { lenCounter++; - + if (text[i] != '\n') { if ((unsigned char)text[i] == 0xc2) // UTF-8 encoding identification @@ -1105,7 +1105,7 @@ const char *TextSubtext(const char *text, int position, int length) const char *TextReplace(char *text, const char *replace, const char *by) { char *result; - + char *insertPoint; // Next insert point char *temp; // Temp pointer int replaceLen; // Replace string length of (the string to remove) @@ -1163,7 +1163,7 @@ const char *TextInsert(const char *text, const char *insert, int position) for (int i = 0; i < position; i++) result[i] = text[i]; for (int i = position; i < insertLen + position; i++) result[i] = insert[i]; for (int i = (insertLen + position); i < (textLen + insertLen); i++) result[i] = text[i]; - + result[textLen + insertLen] = '\0'; // Make sure text string is valid! return result; @@ -1174,7 +1174,7 @@ const char *TextInsert(const char *text, const char *insert, int position) const char *TextJoin(const char **textList, int count, const char *delimiter) { // TODO: Make sure joined text could fit inside MAX_TEXT_BUFFER_LENGTH - + static char text[MAX_TEXT_BUFFER_LENGTH] = { 0 }; memset(text, 0, MAX_TEXT_BUFFER_LENGTH); @@ -1197,9 +1197,9 @@ const char **TextSplit(const char *text, char delimiter, int *count) // all used memory is static... it has some limitations: // 1. Maximum number of possible split strings is set by MAX_SUBSTRINGS_COUNT // 2. Maximum size of text to split is MAX_TEXT_BUFFER_LENGTH - + #define MAX_SUBSTRINGS_COUNT 64 - + static const char *result[MAX_SUBSTRINGS_COUNT] = { NULL }; static char buffer[MAX_TEXT_BUFFER_LENGTH] = { 0 }; memset(buffer, 0, MAX_TEXT_BUFFER_LENGTH); @@ -1208,7 +1208,7 @@ const char **TextSplit(const char *text, char delimiter, int *count) int counter = 1; // Count how many substrings we have on text and point to every one - for (int i = 0; i < MAX_TEXT_BUFFER_LENGTH; i++) + for (int i = 0; i < MAX_TEXT_BUFFER_LENGTH; i++) { buffer[i] = text[i]; if (buffer[i] == '\0') break; @@ -1217,7 +1217,7 @@ const char **TextSplit(const char *text, char delimiter, int *count) buffer[i] = '\0'; // Set an end of string at this point result[counter] = buffer + i + 1; counter++; - + if (counter == MAX_SUBSTRINGS_COUNT) break; } } @@ -1239,11 +1239,11 @@ void TextAppend(char *text, const char *append, int *position) int TextFindIndex(const char *text, const char *find) { int position = -1; - + char *ptr = strstr(text, find); - + if (ptr != NULL) position = ptr - text; - + return position; } @@ -1314,10 +1314,10 @@ int TextToInteger(const char *text) { if ((text[i] > 47) && (text[i] < 58)) result += ((int)text[i] - 48)*units; else { result = -1; break; } - + units *= 10; } - + return result; } diff --git a/src/textures.c b/src/textures.c index 75624fdb..48b89384 100644 --- a/src/textures.c +++ b/src/textures.c @@ -2529,7 +2529,7 @@ void DrawTextureQuad(Texture2D texture, Vector2 tiling, Vector2 offset, Rectangl { Rectangle source = { offset.x*texture.width, offset.y*texture.height, tiling.x*texture.width, tiling.y*texture.height }; Vector2 origin = { 0.0f, 0.0f }; - + DrawTexturePro(texture, source, quad, origin, 0.0f, tint); } @@ -3198,7 +3198,7 @@ static int SaveKTX(Image image, const char *fileName) //unsigned char id[12] = { 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A }; const char ktxIdentifier[12] = { 0xAB, 'K', 'T', 'X', ' ', '1', '1', 0xBB, '\r', '\n', 0x1A, '\n' }; - + // Get the image header strncpy(ktxHeader.id, ktxIdentifier, 12); // KTX 1.1 signature ktxHeader.endianness = 0; -- cgit v1.2.3 From 40a76cf021cfa0eb0f2265135d796dd0b8a0d7d0 Mon Sep 17 00:00:00 2001 From: Demizdor Date: Fri, 22 Feb 2019 12:27:20 +0200 Subject: Fixed height bug in DrawTextRecEx() --- src/text.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/text.c b/src/text.c index 9a7d690d..5b33e600 100644 --- a/src/text.c +++ b/src/text.c @@ -897,7 +897,7 @@ void DrawTextRecEx(Font font, const char *text, Rectangle rec, float fontSize, f textOffsetX = 0; } - if ((textOffsetY + (int)((font.baseSize + font.baseSize/2)*scaleFactor)) > rec.height) break; + if ((textOffsetY + (int)(font.baseSize*scaleFactor)) > rec.height) break; //draw selected bool isGlyphSelected = false; -- cgit v1.2.3 From a886f5e743cd50744d7800cd70a47f5cb9f663e3 Mon Sep 17 00:00:00 2001 From: Ray Date: Fri, 22 Feb 2019 12:12:21 +0100 Subject: Remove TABS --- src/core.c | 4 ++-- src/raudio.c | 4 ++-- src/shapes.c | 2 +- src/text.c | 8 ++++---- src/textures.c | 2 +- 5 files changed, 10 insertions(+), 10 deletions(-) (limited to 'src') diff --git a/src/core.c b/src/core.c index 714e6e2c..9f62b4c8 100644 --- a/src/core.c +++ b/src/core.c @@ -871,7 +871,7 @@ void *GetWindowHandle(void) { #if defined(_WIN32) // NOTE: Returned handle is: void *HWND (windows.h) - return glfwGetWin32Window(window); + return glfwGetWin32Window(window); #elif defined(__linux__) // NOTE: Returned handle is: unsigned long Window (X.h) // typedef unsigned long XID; @@ -2213,7 +2213,7 @@ void SetMouseOffset(int offsetX, int offsetY) // NOTE: Useful when rendering to different size targets void SetMouseScale(float scaleX, float scaleY) { - mouseScale = (Vector2){ scaleX, scaleY }; + mouseScale = (Vector2){ scaleX, scaleY }; } // Returns mouse wheel movement Y diff --git a/src/raudio.c b/src/raudio.c index e1c9fd48..4f3e9220 100644 --- a/src/raudio.c +++ b/src/raudio.c @@ -1406,8 +1406,8 @@ void UpdateMusicStream(Music music) UpdateAudioStream(music->stream, pcm, samplesCount); if ((music->ctxType == MUSIC_MODULE_XM) || (music->ctxType == MUSIC_MODULE_MOD)) { - if (samplesCount > 1) music->samplesLeft -= samplesCount/2; - else music->samplesLeft -= samplesCount; + if (samplesCount > 1) music->samplesLeft -= samplesCount/2; + else music->samplesLeft -= samplesCount; } else music->samplesLeft -= samplesCount; diff --git a/src/shapes.c b/src/shapes.c index 87bb573c..dbc38082 100644 --- a/src/shapes.c +++ b/src/shapes.c @@ -644,7 +644,7 @@ bool CheckCollisionCircleRec(Vector2 center, float radius, Rectangle rec) if (dy <= (rec.height/2.0f)) { return true; } float cornerDistanceSq = (dx - rec.width/2.0f)*(dx - rec.width/2.0f) + - (dy - rec.height/2.0f)*(dy - rec.height/2.0f); + (dy - rec.height/2.0f)*(dy - rec.height/2.0f); return (cornerDistanceSq <= (radius*radius)); } diff --git a/src/text.c b/src/text.c index 9a7d690d..3a5b33d6 100644 --- a/src/text.c +++ b/src/text.c @@ -1386,10 +1386,10 @@ static Font LoadBMFont(const char *fileName) char *lastSlash = NULL; lastSlash = strrchr(fileName, '/'); - if (lastSlash == NULL) - { - lastSlash = strrchr(fileName, '\\'); - } + if (lastSlash == NULL) + { + lastSlash = strrchr(fileName, '\\'); + } // NOTE: We need some extra space to avoid memory corruption on next allocations! texPath = malloc(strlen(fileName) - strlen(lastSlash) + strlen(texFileName) + 4); diff --git a/src/textures.c b/src/textures.c index 48b89384..5c48ba45 100644 --- a/src/textures.c +++ b/src/textures.c @@ -1631,7 +1631,7 @@ Color *ImageExtractPalette(Image image, int maxPaletteSize, int *extractCount) if (palCount >= maxPaletteSize) { i = image.width*image.height; // Finish palette get - printf("WARNING: Image palette is greater than %i colors!\n", maxPaletteSize); + TraceLog(LOG_WARNING, "Image palette is greater than %i colors!", maxPaletteSize); } } } -- cgit v1.2.3 From 374811c440302701496bfb474ce5861c951c5884 Mon Sep 17 00:00:00 2001 From: Ray Date: Fri, 22 Feb 2019 13:13:11 +0100 Subject: Change ternary operator formatting --- src/core.c | 44 ++++++++++++++++++++++---------------------- src/models.c | 8 ++++---- src/raudio.c | 22 +++++++++++----------- src/rlgl.h | 10 +++++----- src/shapes.c | 2 +- src/text.c | 10 +++++----- src/textures.c | 8 ++++---- 7 files changed, 52 insertions(+), 52 deletions(-) (limited to 'src') diff --git a/src/core.c b/src/core.c index 9f62b4c8..bff92600 100644 --- a/src/core.c +++ b/src/core.c @@ -1430,11 +1430,11 @@ Vector3 ColorToHSV(Color color) Vector3 hsv = { 0.0f, 0.0f, 0.0f }; float min, max, delta; - min = rgb.x < rgb.y ? rgb.x : rgb.y; - min = min < rgb.z ? min : rgb.z; + min = rgb.x < rgb.y? rgb.x : rgb.y; + min = min < rgb.z? min : rgb.z; - max = rgb.x > rgb.y ? rgb.x : rgb.y; - max = max > rgb.z ? max : rgb.z; + max = rgb.x > rgb.y? rgb.x : rgb.y; + max = max > rgb.z? max : rgb.z; hsv.z = max; // Value delta = max - min; @@ -1485,25 +1485,25 @@ Color ColorFromHSV(Vector3 hsv) // Red channel float k = fmod((5.0f + h/60.0f), 6); float t = 4.0f - k; - k = (t < k) ? t : k; - k = (k < 1) ? k : 1; - k = (k > 0) ? k : 0; + k = (t < k)? t : k; + k = (k < 1)? k : 1; + k = (k > 0)? k : 0; color.r = (v - v*s*k)*255; // Green channel k = fmod((3.0f + h/60.0f), 6); t = 4.0f - k; - k = (t < k) ? t : k; - k = (k < 1) ? k : 1; - k = (k > 0) ? k : 0; + k = (t < k)? t : k; + k = (k < 1)? k : 1; + k = (k > 0)? k : 0; color.g = (v - v*s*k)*255; // Blue channel k = fmod((1.0f + h/60.0f), 6); t = 4.0f - k; - k = (t < k) ? t : k; - k = (k < 1) ? k : 1; - k = (k > 0) ? k : 0; + k = (t < k)? t : k; + k = (k < 1)? k : 1; + k = (k > 0)? k : 0; color.b = (v - v*s*k)*255; return color; @@ -1677,7 +1677,7 @@ const char *GetFileNameWithoutExt(const char *filePath) // NOTE: strrchr() returns a pointer to the last occurrence of character lastDot = strrchr(result, nameDot); - lastSep = (pathSep == 0) ? NULL : strrchr(result, pathSep); + lastSep = (pathSep == 0)? NULL : strrchr(result, pathSep); if (lastDot != NULL) // Check if it has an extension separator... { @@ -3191,7 +3191,7 @@ static void PollInputEvents(void) // Poll Events (registered events) // NOTE: Activity is paused if not enabled (appEnabled) - while ((ident = ALooper_pollAll(appEnabled ? 0 : -1, NULL, &events,(void**)&source)) >= 0) + while ((ident = ALooper_pollAll(appEnabled? 0 : -1, NULL, &events,(void**)&source)) >= 0) { // Process this event if (source != NULL) source->process(androidApp, source); @@ -3771,7 +3771,7 @@ static EM_BOOL EmscriptenTouchCallback(int eventType, const EmscriptenTouchEvent } printf("%s, numTouches: %d %s%s%s%s\n", emscripten_event_type_to_string(eventType), event->numTouches, - event->ctrlKey ? " CTRL" : "", event->shiftKey ? " SHIFT" : "", event->altKey ? " ALT" : "", event->metaKey ? " META" : ""); + event->ctrlKey? " CTRL" : "", event->shiftKey? " SHIFT" : "", event->altKey? " ALT" : "", event->metaKey? " META" : ""); for (int i = 0; i < event->numTouches; ++i) { @@ -3825,7 +3825,7 @@ static EM_BOOL EmscriptenGamepadCallback(int eventType, const EmscriptenGamepadE { /* printf("%s: timeStamp: %g, connected: %d, index: %ld, numAxes: %d, numButtons: %d, id: \"%s\", mapping: \"%s\"\n", - eventType != 0 ? emscripten_event_type_to_string(eventType) : "Gamepad state", + eventType != 0? emscripten_event_type_to_string(eventType) : "Gamepad state", gamepadEvent->timestamp, gamepadEvent->connected, gamepadEvent->index, gamepadEvent->numAxes, gamepadEvent->numButtons, gamepadEvent->id, gamepadEvent->mapping); for(int i = 0; i < gamepadEvent->numAxes; ++i) printf("Axis %d: %g\n", i, gamepadEvent->axis[i]); @@ -4189,11 +4189,11 @@ static void EventThreadSpawn(char *device) { // Looks like a interesting device TraceLog(LOG_INFO, "Opening input device [%s] (%s%s%s%s%s)", device, - worker->isMouse ? "mouse " : "", - worker->isMultitouch ? "multitouch " : "", - worker->isTouch ? "touchscreen " : "", - worker->isGamepad ? "gamepad " : "", - worker->isKeyboard ? "keyboard " : ""); + worker->isMouse? "mouse " : "", + worker->isMultitouch? "multitouch " : "", + worker->isTouch? "touchscreen " : "", + worker->isGamepad? "gamepad " : "", + worker->isKeyboard? "keyboard " : ""); // Create a thread for this device int error = pthread_create(&worker->threadId, NULL, &EventThread, (void *)worker); diff --git a/src/models.c b/src/models.c index 384c8db4..b261f58d 100644 --- a/src/models.c +++ b/src/models.c @@ -2260,7 +2260,7 @@ void MeshTangents(Mesh *mesh) float t2 = uv3.y - uv1.y; float div = s1*t2 - s2*t1; - float r = (div == 0.0f) ? 0.0f : 1.0f/div; + float r = (div == 0.0f)? 0.0f : 1.0f/div; Vector3 sdir = { (t2*x1 - t1*x2)*r, (t2*y1 - t1*y2)*r, (t2*z1 - t1*z2)*r }; Vector3 tdir = { (s1*x2 - s2*x1)*r, (s1*y2 - s2*y1)*r, (s1*z2 - s2*z1)*r }; @@ -2293,7 +2293,7 @@ void MeshTangents(Mesh *mesh) mesh->tangents[i*4 + 0] = tangent.x; mesh->tangents[i*4 + 1] = tangent.y; mesh->tangents[i*4 + 2] = tangent.z; - mesh->tangents[i*4 + 3] = (Vector3DotProduct(Vector3CrossProduct(normal, tangent), tan2[i]) < 0.0f) ? -1.0f : 1.0f; + mesh->tangents[i*4 + 3] = (Vector3DotProduct(Vector3CrossProduct(normal, tangent), tan2[i]) < 0.0f)? -1.0f : 1.0f; #endif } @@ -2312,7 +2312,7 @@ void MeshBinormals(Mesh *mesh) Vector3 tangent = { mesh->tangents[i*4 + 0], mesh->tangents[i*4 + 1], mesh->tangents[i*4 + 2] }; float tangentW = mesh->tangents[i*4 + 3]; - // TODO: Register computed binormal in mesh->binormal ? + // TODO: Register computed binormal in mesh->binormal? // Vector3 binormal = Vector3Multiply(Vector3CrossProduct(normal, tangent), tangentW); } } @@ -2639,7 +2639,7 @@ static Material LoadMTL(const char *fileName) } break; case 'e': // Ke float float float Emmisive color (RGB) { - // TODO: Support Ke ? + // TODO: Support Ke? } break; default: break; } diff --git a/src/raudio.c b/src/raudio.c index 4f3e9220..451d3bc3 100644 --- a/src/raudio.c +++ b/src/raudio.c @@ -834,7 +834,7 @@ Sound LoadSoundFromWave(Wave wave) // // I have decided on the first option because it offloads work required for the format conversion to the to the loading stage. // The downside to this is that it uses more memory if the original sound is u8 or s16. - mal_format formatIn = ((wave.sampleSize == 8) ? mal_format_u8 : ((wave.sampleSize == 16) ? mal_format_s16 : mal_format_f32)); + mal_format formatIn = ((wave.sampleSize == 8)? mal_format_u8 : ((wave.sampleSize == 16)? mal_format_s16 : mal_format_f32)); mal_uint32 frameCountIn = wave.sampleCount/wave.channels; mal_uint32 frameCount = (mal_uint32)mal_convert_frames(NULL, DEVICE_FORMAT, DEVICE_CHANNELS, DEVICE_SAMPLE_RATE, NULL, formatIn, wave.channels, wave.sampleRate, frameCountIn); @@ -946,7 +946,7 @@ void ExportWaveAsCode(Wave wave, const char *fileName) // Write byte data as hexadecimal text fprintf(txtFile, "static unsigned char %s_DATA[%i] = { ", varFileName, dataSize); - for (int i = 0; i < dataSize - 1; i++) fprintf(txtFile, ((i%BYTES_TEXT_PER_LINE == 0) ? "0x%x,\n" : "0x%x, "), ((unsigned char *)wave.data)[i]); + for (int i = 0; i < dataSize - 1; i++) fprintf(txtFile, ((i%BYTES_TEXT_PER_LINE == 0)? "0x%x,\n" : "0x%x, "), ((unsigned char *)wave.data)[i]); fprintf(txtFile, "0x%x };\n", ((unsigned char *)wave.data)[dataSize - 1]); fclose(txtFile); @@ -997,8 +997,8 @@ void SetSoundPitch(Sound sound, float pitch) // Convert wave data to desired format void WaveFormat(Wave *wave, int sampleRate, int sampleSize, int channels) { - mal_format formatIn = ((wave->sampleSize == 8) ? mal_format_u8 : ((wave->sampleSize == 16) ? mal_format_s16 : mal_format_f32)); - mal_format formatOut = (( sampleSize == 8) ? mal_format_u8 : (( sampleSize == 16) ? mal_format_s16 : mal_format_f32)); + mal_format formatIn = ((wave->sampleSize == 8)? mal_format_u8 : ((wave->sampleSize == 16)? mal_format_s16 : mal_format_f32)); + mal_format formatOut = (( sampleSize == 8)? mal_format_u8 : (( sampleSize == 16)? mal_format_s16 : mal_format_f32)); mal_uint32 frameCountIn = wave->sampleCount; // Is wave->sampleCount actually the frame count? That terminology needs to change, if so. @@ -1511,7 +1511,7 @@ AudioStream InitAudioStream(unsigned int sampleRate, unsigned int sampleSize, un stream.channels = 1; // Fallback to mono channel } - mal_format formatIn = ((stream.sampleSize == 8) ? mal_format_u8 : ((stream.sampleSize == 16) ? mal_format_s16 : mal_format_f32)); + mal_format formatIn = ((stream.sampleSize == 8)? mal_format_u8 : ((stream.sampleSize == 16)? mal_format_s16 : mal_format_f32)); // The size of a streaming buffer must be at least double the size of a period. unsigned int periodSize = device.bufferSizeInFrames/device.periods; @@ -1528,7 +1528,7 @@ AudioStream InitAudioStream(unsigned int sampleRate, unsigned int sampleSize, un audioBuffer->looping = true; // Always loop for streaming buffers. stream.audioBuffer = audioBuffer; - TraceLog(LOG_INFO, "[AUD ID %i] Audio stream loaded successfully (%i Hz, %i bit, %s)", stream.source, stream.sampleRate, stream.sampleSize, (stream.channels == 1) ? "Mono" : "Stereo"); + TraceLog(LOG_INFO, "[AUD ID %i] Audio stream loaded successfully (%i Hz, %i bit, %s)", stream.source, stream.sampleRate, stream.sampleSize, (stream.channels == 1)? "Mono" : "Stereo"); return stream; } @@ -1566,7 +1566,7 @@ void UpdateAudioStream(AudioStream stream, const void *data, int samplesCount) else { // Just update whichever sub-buffer is processed. - subBufferToUpdate = (audioBuffer->isSubBufferProcessed[0]) ? 0 : 1; + subBufferToUpdate = (audioBuffer->isSubBufferProcessed[0])? 0 : 1; } mal_uint32 subBufferSizeInFrames = audioBuffer->bufferSizeInFrames/2; @@ -1769,7 +1769,7 @@ static Wave LoadWAV(const char *fileName) // NOTE: subChunkSize comes in bytes, we need to translate it to number of samples wave.sampleCount = (wavData.subChunkSize/(wave.sampleSize/8))/wave.channels; - TraceLog(LOG_INFO, "[%s] WAV file loaded successfully (%i Hz, %i bit, %s)", fileName, wave.sampleRate, wave.sampleSize, (wave.channels == 1) ? "Mono" : "Stereo"); + TraceLog(LOG_INFO, "[%s] WAV file loaded successfully (%i Hz, %i bit, %s)", fileName, wave.sampleRate, wave.sampleSize, (wave.channels == 1)? "Mono" : "Stereo"); } } } @@ -1890,7 +1890,7 @@ static Wave LoadOGG(const char *fileName) TraceLog(LOG_DEBUG, "[%s] Samples obtained: %i", fileName, numSamplesOgg); - TraceLog(LOG_INFO, "[%s] OGG file loaded successfully (%i Hz, %i bit, %s)", fileName, wave.sampleRate, wave.sampleSize, (wave.channels == 1) ? "Mono" : "Stereo"); + TraceLog(LOG_INFO, "[%s] OGG file loaded successfully (%i Hz, %i bit, %s)", fileName, wave.sampleRate, wave.sampleSize, (wave.channels == 1)? "Mono" : "Stereo"); stb_vorbis_close(oggFile); } @@ -1917,7 +1917,7 @@ static Wave LoadFLAC(const char *fileName) if (wave.channels > 2) TraceLog(LOG_WARNING, "[%s] FLAC channels number (%i) not supported", fileName, wave.channels); if (wave.data == NULL) TraceLog(LOG_WARNING, "[%s] FLAC data could not be loaded", fileName); - else TraceLog(LOG_INFO, "[%s] FLAC file loaded successfully (%i Hz, %i bit, %s)", fileName, wave.sampleRate, wave.sampleSize, (wave.channels == 1) ? "Mono" : "Stereo"); + else TraceLog(LOG_INFO, "[%s] FLAC file loaded successfully (%i Hz, %i bit, %s)", fileName, wave.sampleRate, wave.sampleSize, (wave.channels == 1)? "Mono" : "Stereo"); return wave; } @@ -1944,7 +1944,7 @@ static Wave LoadMP3(const char *fileName) if (wave.channels > 2) TraceLog(LOG_WARNING, "[%s] MP3 channels number (%i) not supported", fileName, wave.channels); if (wave.data == NULL) TraceLog(LOG_WARNING, "[%s] MP3 data could not be loaded", fileName); - else TraceLog(LOG_INFO, "[%s] MP3 file loaded successfully (%i Hz, %i bit, %s)", fileName, wave.sampleRate, wave.sampleSize, (wave.channels == 1) ? "Mono" : "Stereo"); + else TraceLog(LOG_INFO, "[%s] MP3 file loaded successfully (%i Hz, %i bit, %s)", fileName, wave.sampleRate, wave.sampleSize, (wave.channels == 1)? "Mono" : "Stereo"); return wave; } diff --git a/src/rlgl.h b/src/rlgl.h index c9f15385..52165150 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -775,8 +775,8 @@ typedef struct DrawCall { #endif "void main() \n" "{ \n" - " vec2 lensCenter = fragTexCoord.x < 0.5 ? leftLensCenter : rightLensCenter; \n" - " vec2 screenCenter = fragTexCoord.x < 0.5 ? leftScreenCenter : rightScreenCenter; \n" + " vec2 lensCenter = fragTexCoord.x < 0.5? leftLensCenter : rightLensCenter; \n" + " vec2 screenCenter = fragTexCoord.x < 0.5? leftScreenCenter : rightScreenCenter; \n" " vec2 theta = (fragTexCoord - lensCenter)*scaleIn; \n" " float rSq = theta.x*theta.x + theta.y*theta.y; \n" " vec2 theta1 = theta*(hmdWarpParam.x + hmdWarpParam.y*rSq + hmdWarpParam.z*rSq*rSq + hmdWarpParam.w*rSq*rSq*rSq); \n" @@ -1136,7 +1136,7 @@ void rlEnd(void) // TODO: System could be improved (a bit) just storing every draw alignment value // and adding it to vertexOffset on drawing... maybe in a future... int vertexCount = draws[drawsCounter - 1].vertexCount; - int vertexToAlign = (vertexCount >= 4) ? vertexCount%4 : (4 - vertexCount%4); + int vertexToAlign = (vertexCount >= 4)? vertexCount%4 : (4 - vertexCount%4); for (int i = 0; i < vertexToAlign; i++) rlVertex3f(-1, -1, -1); // Make sure vertexCount is the same for vertices, texcoords, colors and normals @@ -1233,7 +1233,7 @@ void rlTexCoord2f(float x, float y) } // Define one vertex (normal) -// NOTE: Normals limited to TRIANGLES only ? +// NOTE: Normals limited to TRIANGLES only? void rlNormal3f(float x, float y, float z) { // TODO: Normals usage... @@ -2206,7 +2206,7 @@ RenderTexture2D rlLoadRenderTexture(int width, int height, int format, int depth target.depth.id = rlLoadTextureDepth(width, height, depthBits, !useDepthTexture); target.depth.width = width; target.depth.height = height; - target.depth.format = 19; //DEPTH_COMPONENT_24BIT ? + target.depth.format = 19; //DEPTH_COMPONENT_24BIT? target.depth.mipmaps = 1; } //----------------------------------------------------------------------------------------------------- diff --git a/src/shapes.c b/src/shapes.c index dbc38082..837e4e9c 100644 --- a/src/shapes.c +++ b/src/shapes.c @@ -132,7 +132,7 @@ void DrawLineEx(Vector2 startPos, Vector2 endPos, float thick, Color color) rlPushMatrix(); rlTranslatef((float)startPos.x, (float)startPos.y, 0.0f); rlRotatef(RAD2DEG*angle, 0.0f, 0.0f, 1.0f); - rlTranslatef(0, (thick > 1.0f) ? -thick/2.0f : -1.0f, 0.0f); + rlTranslatef(0, (thick > 1.0f)? -thick/2.0f : -1.0f, 0.0f); rlBegin(RL_QUADS); rlColor4ub(color.r, color.g, color.b, color.a); diff --git a/src/text.c b/src/text.c index 56db3f28..39582db2 100644 --- a/src/text.c +++ b/src/text.c @@ -306,7 +306,7 @@ Font LoadFontEx(const char *fileName, int fontSize, int *fontChars, int charsCou Font font = { 0 }; font.baseSize = fontSize; - font.charsCount = (charsCount > 0) ? charsCount : 95; + font.charsCount = (charsCount > 0)? charsCount : 95; font.chars = LoadFontData(fileName, font.baseSize, fontChars, font.charsCount, FONT_DEFAULT); #if defined(SUPPORT_FILEFORMAT_TTF) @@ -483,7 +483,7 @@ CharInfo *LoadFontData(const char *fileName, int fontSize, int *fontChars, int c stbtt_GetFontVMetrics(&fontInfo, &ascent, &descent, &lineGap); // In case no chars count provided, default to 95 - charsCount = (charsCount > 0) ? charsCount : 95; + charsCount = (charsCount > 0)? charsCount : 95; // Fill fontChars in case not provided externally // NOTE: By default we fill charsCount consecutevely, starting at 32 (Space) @@ -557,7 +557,7 @@ Image GenImageFontAtlas(CharInfo *chars, int charsCount, int fontSize, int paddi Image atlas = { 0 }; // In case no chars count provided we suppose default of 95 - charsCount = (charsCount > 0) ? charsCount : 95; + charsCount = (charsCount > 0)? charsCount : 95; // Calculate image size based on required pixel area // NOTE 1: Image is forced to be squared and POT... very conservative! @@ -856,7 +856,7 @@ void DrawTextRecEx(Font font, const char *text, Rectangle rec, float fontSize, f if ((textOffsetX + glyphWidth + 1) >= rec.width) { - endLine = (endLine < 1) ? i : endLine; + endLine = (endLine < 1)? i : endLine; if (i == endLine) endLine -= 1; if ((startLine + 1) == endLine) endLine = i - 1; state = !state; @@ -916,7 +916,7 @@ void DrawTextRecEx(Font font, const char *text, Rectangle rec, float fontSize, f rec.y + textOffsetY + font.chars[index].offsetY*scaleFactor, font.chars[index].rec.width*scaleFactor, font.chars[index].rec.height*scaleFactor }, (Vector2){ 0, 0 }, 0.0f, - (!isGlyphSelected) ? tint : selectText); + (!isGlyphSelected)? tint : selectText); } } diff --git a/src/textures.c b/src/textures.c index 5c48ba45..d79cb3cb 100644 --- a/src/textures.c +++ b/src/textures.c @@ -588,7 +588,7 @@ Vector4 *GetImageDataNormalized(Image image) pixels[i].x = (float)((pixel & 0b1111100000000000) >> 11)*(1.0f/31); pixels[i].y = (float)((pixel & 0b0000011111000000) >> 6)*(1.0f/31); pixels[i].z = (float)((pixel & 0b0000000000111110) >> 1)*(1.0f/31); - pixels[i].w = ((pixel & 0b0000000000000001) == 0) ? 0.0f : 1.0f; + pixels[i].w = ((pixel & 0b0000000000000001) == 0)? 0.0f : 1.0f; } break; case UNCOMPRESSED_R5G6B5: @@ -814,7 +814,7 @@ void ExportImageAsCode(Image image, const char *fileName) fprintf(txtFile, "#define %s_FORMAT %i // raylib internal pixel format\n\n", varFileName, image.format); fprintf(txtFile, "static unsigned char %s_DATA[%i] = { ", varFileName, dataSize); - for (int i = 0; i < dataSize - 1; i++) fprintf(txtFile, ((i%BYTES_TEXT_PER_LINE == 0) ? "0x%x,\n" : "0x%x, "), ((unsigned char *)image.data)[i]); + for (int i = 0; i < dataSize - 1; i++) fprintf(txtFile, ((i%BYTES_TEXT_PER_LINE == 0)? "0x%x,\n" : "0x%x, "), ((unsigned char *)image.data)[i]); fprintf(txtFile, "0x%x };\n", ((unsigned char *)image.data)[dataSize - 1]); fclose(txtFile); @@ -984,7 +984,7 @@ void ImageFormat(Image *image, int newFormat) r = (unsigned char)(round(pixels[i].x*31.0f)); g = (unsigned char)(round(pixels[i].y*31.0f)); b = (unsigned char)(round(pixels[i].z*31.0f)); - a = (pixels[i].w > ((float)ALPHA_THRESHOLD/255.0f)) ? 1 : 0; + a = (pixels[i].w > ((float)ALPHA_THRESHOLD/255.0f))? 1 : 0; ((unsigned short *)image->data)[i] = (unsigned short)r << 11 | (unsigned short)g << 6 | (unsigned short)b << 1 | (unsigned short)a; } @@ -2231,7 +2231,7 @@ Image GenImageGradientH(int width, int height, Color left, Color right) Image GenImageGradientRadial(int width, int height, float density, Color inner, Color outer) { Color *pixels = (Color *)malloc(width*height*sizeof(Color)); - float radius = (width < height) ? (float)width/2.0f : (float)height/2.0f; + float radius = (width < height)? (float)width/2.0f : (float)height/2.0f; float centerX = (float)width/2.0f; float centerY = (float)height/2.0f; -- cgit v1.2.3 From 8ad608888e9ea24d72802520282136cf5a7659e8 Mon Sep 17 00:00:00 2001 From: ftk Date: Sat, 23 Feb 2019 10:36:25 +0000 Subject: fix audio pitch --- src/raudio.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/raudio.c b/src/raudio.c index 451d3bc3..5f42222e 100644 --- a/src/raudio.c +++ b/src/raudio.c @@ -712,11 +712,13 @@ void SetAudioBufferPitch(AudioBuffer *audioBuffer, float pitch) return; } - audioBuffer->pitch = pitch; + float pitchMul = pitch / audioBuffer->pitch; // Pitching is just an adjustment of the sample rate. Note that this changes the duration of the sound - higher pitches // will make the sound faster; lower pitches make it slower. - mal_uint32 newOutputSampleRate = (mal_uint32)((((float)audioBuffer->dsp.src.config.sampleRateOut / (float)audioBuffer->dsp.src.config.sampleRateIn) / pitch) * audioBuffer->dsp.src.config.sampleRateIn); + mal_uint32 newOutputSampleRate = (mal_uint32)((float)audioBuffer->dsp.src.config.sampleRateOut / pitchMul); + audioBuffer->pitch *= (float)audioBuffer->dsp.src.config.sampleRateOut / newOutputSampleRate; + mal_dsp_set_output_sample_rate(&audioBuffer->dsp, newOutputSampleRate); } -- cgit v1.2.3 From 795c5e949d18b8ae4753cd95ad1aa96b4f399c60 Mon Sep 17 00:00:00 2001 From: Skabunkel <> Date: Sun, 24 Feb 2019 00:13:50 +0100 Subject: #764 - Quick fix that clears alot of memory, there seems to be more hiding somewhere else. --- src/text.c | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src') diff --git a/src/text.c b/src/text.c index 39582db2..db7be366 100644 --- a/src/text.c +++ b/src/text.c @@ -684,6 +684,10 @@ void UnloadFont(Font font) // NOTE: Make sure spriteFont is not default font (fallback) if (font.texture.id != GetFontDefault().texture.id) { + for (int i = 0; i < font.charsCount; i++) + { + free(font.chars[i].data); + } UnloadTexture(font.texture); free(font.chars); -- cgit v1.2.3 From 374b4d3faf4c66a5ca97c21ab333bc235895f23f Mon Sep 17 00:00:00 2001 From: Skabunkel <> Date: Sun, 24 Feb 2019 00:17:54 +0100 Subject: Tabs to spaces --- src/text.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/text.c b/src/text.c index db7be366..f6a4a0d8 100644 --- a/src/text.c +++ b/src/text.c @@ -684,9 +684,9 @@ void UnloadFont(Font font) // NOTE: Make sure spriteFont is not default font (fallback) if (font.texture.id != GetFontDefault().texture.id) { - for (int i = 0; i < font.charsCount; i++) + for (int i = 0; i < font.charsCount; i++) { - free(font.chars[i].data); + free(font.chars[i].data); } UnloadTexture(font.texture); free(font.chars); -- cgit v1.2.3 From f2d5cddfc8076fb3a0e9618bbd0c51a40b2b0922 Mon Sep 17 00:00:00 2001 From: Skabunkel <> Date: Sun, 24 Feb 2019 01:48:29 +0100 Subject: Fixed segmentation fult created by quick fix --- src/text.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/text.c b/src/text.c index f6a4a0d8..db8875b4 100644 --- a/src/text.c +++ b/src/text.c @@ -430,6 +430,7 @@ Font LoadFontFromImage(Image image, Color key, int firstChar) spriteFont.chars[i].offsetX = 0; spriteFont.chars[i].offsetY = 0; spriteFont.chars[i].advanceX = 0; + spriteFont.chars[i].data = NULL; } spriteFont.baseSize = (int)spriteFont.chars[0].rec.height; @@ -686,7 +687,8 @@ void UnloadFont(Font font) { for (int i = 0; i < font.charsCount; i++) { - free(font.chars[i].data); + if(font.chars[i].data != NULL) + free(font.chars[i].data); } UnloadTexture(font.texture); free(font.chars); @@ -1442,6 +1444,7 @@ static Font LoadBMFont(const char *fileName) font.chars[i].offsetX = charOffsetX; font.chars[i].offsetY = charOffsetY; font.chars[i].advanceX = charAdvanceX; + font.chars[i].data = NULL; } fclose(fntFile); -- cgit v1.2.3 From 03f74835378a26c226ce3c45afae48c7488b8682 Mon Sep 17 00:00:00 2001 From: Skabunkel <> Date: Sun, 24 Feb 2019 01:56:17 +0100 Subject: Missed one --- src/text.c | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/text.c b/src/text.c index db8875b4..dc2b07ab 100644 --- a/src/text.c +++ b/src/text.c @@ -512,6 +512,7 @@ CharInfo *LoadFontData(const char *fileName, int fontSize, int *fontChars, int c if (type != FONT_SDF) chars[i].data = stbtt_GetCodepointBitmap(&fontInfo, scaleFactor, scaleFactor, ch, &chw, &chh, &chars[i].offsetX, &chars[i].offsetY); else if (ch != 32) chars[i].data = stbtt_GetCodepointSDF(&fontInfo, scaleFactor, ch, SDF_CHAR_PADDING, SDF_ON_EDGE_VALUE, SDF_PIXEL_DIST_SCALE, &chw, &chh, &chars[i].offsetX, &chars[i].offsetY); + else chars[i].data = NULL; if (type == FONT_BITMAP) { -- cgit v1.2.3 From fc11b360af4ea70adbbfd732512880bce18347b4 Mon Sep 17 00:00:00 2001 From: Skabunkel <> Date: Sun, 24 Feb 2019 01:57:31 +0100 Subject: ... tabs again... _facepalm_ --- src/text.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/text.c b/src/text.c index dc2b07ab..24f51f97 100644 --- a/src/text.c +++ b/src/text.c @@ -512,7 +512,7 @@ CharInfo *LoadFontData(const char *fileName, int fontSize, int *fontChars, int c if (type != FONT_SDF) chars[i].data = stbtt_GetCodepointBitmap(&fontInfo, scaleFactor, scaleFactor, ch, &chw, &chh, &chars[i].offsetX, &chars[i].offsetY); else if (ch != 32) chars[i].data = stbtt_GetCodepointSDF(&fontInfo, scaleFactor, ch, SDF_CHAR_PADDING, SDF_ON_EDGE_VALUE, SDF_PIXEL_DIST_SCALE, &chw, &chh, &chars[i].offsetX, &chars[i].offsetY); - else chars[i].data = NULL; + else chars[i].data = NULL; if (type == FONT_BITMAP) { -- cgit v1.2.3 From b570b32337cd08ca3cf6eece683d2e23171bcbd5 Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 28 Feb 2019 16:28:49 +0100 Subject: Added some comments on #594 --- src/rlgl.h | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/rlgl.h b/src/rlgl.h index 52165150..717801e3 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -728,6 +728,8 @@ typedef struct DrawCall { //unsigned int vaoId; // Vertex Array id to be used on the draw //unsigned int shaderId; // Shader id to be used on the draw unsigned int textureId; // Texture id to be used on the draw + // TODO: Support additional texture units? + //Matrix projection; // Projection matrix for this draw //Matrix modelview; // Modelview matrix for this draw } DrawCall; @@ -4132,9 +4134,13 @@ static void DrawBuffersDefault(void) glUniformMatrix4fv(currentShader.locs[LOC_MATRIX_MVP], 1, false, MatrixToFloat(matMVP)); glUniform4f(currentShader.locs[LOC_COLOR_DIFFUSE], 1.0f, 1.0f, 1.0f, 1.0f); - glUniform1i(currentShader.locs[LOC_MAP_DIFFUSE], 0); + glUniform1i(currentShader.locs[LOC_MAP_DIFFUSE], 0); // Provided value refers to the texture unit (active) + + // TODO: Support additional texture units on custom shader + //if (currentShader->locs[LOC_MAP_SPECULAR] > 0) glUniform1i(currentShader.locs[LOC_MAP_SPECULAR], 1); + //if (currentShader->locs[LOC_MAP_NORMAL] > 0) glUniform1i(currentShader.locs[LOC_MAP_NORMAL], 2); - // NOTE: Additional map textures not considered for default buffers drawing + // NOTE: Right now additional map textures not considered for default buffers drawing int vertexOffset = 0; @@ -4164,6 +4170,10 @@ static void DrawBuffersDefault(void) for (int i = 0; i < drawsCounter; i++) { glBindTexture(GL_TEXTURE_2D, draws[i].textureId); + + // TODO: Find some way to bind additional textures --> Use global texture IDs? Register them on draw[i]? + //if (currentShader->locs[LOC_MAP_SPECULAR] > 0) { glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, textureUnit1_id); } + //if (currentShader->locs[LOC_MAP_SPECULAR] > 0) { glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, textureUnit2_id); } if ((draws[i].mode == RL_LINES) || (draws[i].mode == RL_TRIANGLES)) glDrawArrays(draws[i].mode, vertexOffset, draws[i].vertexCount); else -- cgit v1.2.3 From a90c9c5ade55684cfd46b18f91edeb9208d1f7d7 Mon Sep 17 00:00:00 2001 From: Skabunkel <> Date: Thu, 28 Feb 2019 17:50:47 +0100 Subject: Removed unnecessary --- src/text.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'src') diff --git a/src/text.c b/src/text.c index 24f51f97..f228a4df 100644 --- a/src/text.c +++ b/src/text.c @@ -688,8 +688,7 @@ void UnloadFont(Font font) { for (int i = 0; i < font.charsCount; i++) { - if(font.chars[i].data != NULL) - free(font.chars[i].data); + free(font.chars[i].data); } UnloadTexture(font.texture); free(font.chars); -- cgit v1.2.3 From d679a97e926dce81ed64dc40612b6ac8f78ea264 Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 28 Feb 2019 18:39:58 +0100 Subject: Removed some NULL pointer checks --- src/rlgl.h | 24 ++++++++++++------------ src/textures.c | 7 ++----- 2 files changed, 14 insertions(+), 17 deletions(-) (limited to 'src') diff --git a/src/rlgl.h b/src/rlgl.h index 717801e3..a8987839 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -2727,18 +2727,18 @@ void rlDrawMesh(Mesh mesh, Material material, Matrix transform) // Unload mesh data from CPU and GPU void rlUnloadMesh(Mesh *mesh) { - if (mesh->vertices != NULL) free(mesh->vertices); - if (mesh->texcoords != NULL) free(mesh->texcoords); - if (mesh->normals != NULL) free(mesh->normals); - if (mesh->colors != NULL) free(mesh->colors); - if (mesh->tangents != NULL) free(mesh->tangents); - if (mesh->texcoords2 != NULL) free(mesh->texcoords2); - if (mesh->indices != NULL) free(mesh->indices); - - if (mesh->baseVertices != NULL) free(mesh->baseVertices); - if (mesh->baseNormals != NULL) free(mesh->baseNormals); - if (mesh->weightBias != NULL) free(mesh->weightBias); - if (mesh->weightId != NULL) free(mesh->weightId); + free(mesh->vertices); + free(mesh->texcoords); + free(mesh->normals); + free(mesh->colors); + free(mesh->tangents); + free(mesh->texcoords2); + free(mesh->indices); + + free(mesh->baseVertices); + free(mesh->baseNormals); + free(mesh->weightBias); + free(mesh->weightId); rlDeleteBuffers(mesh->vboId[0]); // vertex rlDeleteBuffers(mesh->vboId[1]); // texcoords diff --git a/src/textures.c b/src/textures.c index d79cb3cb..01c9b2f5 100644 --- a/src/textures.c +++ b/src/textures.c @@ -353,7 +353,7 @@ Image LoadImageRaw(const char *fileName, int width, int height, int format, int { TraceLog(LOG_WARNING, "[%s] RAW image data can not be read, wrong requested format or size", fileName); - if (image.data != NULL) free(image.data); + free(image.data); } else { @@ -414,10 +414,7 @@ RenderTexture2D LoadRenderTexture(int width, int height) // Unload image from CPU memory (RAM) void UnloadImage(Image image) { - if (image.data != NULL) free(image.data); - - // NOTE: It becomes anoying every time a texture is loaded - //TraceLog(LOG_INFO, "Unloaded image data"); + free(image.data); } // Unload texture from GPU memory (VRAM) -- cgit v1.2.3 From 50da9f623e1c2c70530653399a9acf1092e30a1d Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 28 Feb 2019 22:25:27 +0100 Subject: Return value in GetClipboardText() --- src/core.c | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src') diff --git a/src/core.c b/src/core.c index bff92600..dc60eee4 100644 --- a/src/core.c +++ b/src/core.c @@ -990,6 +990,8 @@ const char *GetClipboardText(void) { #if defined(PLATFORM_DESKTOP) return glfwGetClipboardString(window); +#else + return NULL; #endif } -- cgit v1.2.3 From 36fa0207f29a4f3e2ed1a8e4d541bcd14e09ff2b Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 28 Feb 2019 23:06:37 +0100 Subject: Some spacing review --- src/core.c | 2 +- src/rlgl.h | 6 +++--- src/shapes.c | 2 +- src/text.c | 2 -- 4 files changed, 5 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/core.c b/src/core.c index dc60eee4..4e195ec7 100644 --- a/src/core.c +++ b/src/core.c @@ -4321,7 +4321,7 @@ static void *EventThread(void *arg) // Button parsing if (event.type == EV_KEY) { - if((event.code == BTN_TOUCH) || (event.code == BTN_LEFT)) + if ((event.code == BTN_TOUCH) || (event.code == BTN_LEFT)) { currentMouseStateEvdev[MOUSE_LEFT_BUTTON] = event.value; if (event.value > 0) gestureEvent.touchAction = TOUCH_DOWN; diff --git a/src/rlgl.h b/src/rlgl.h index a8987839..b8895a08 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -1624,7 +1624,7 @@ void rlglInit(int width, int height) if (strcmp(extList[i], (const char *)"GL_EXT_texture_mirror_clamp") == 0) texMirrorClampSupported = true; // Debug marker support - if(strcmp(extList[i], (const char *)"GL_EXT_debug_marker") == 0) debugMarkerSupported = true; + if (strcmp(extList[i], (const char *)"GL_EXT_debug_marker") == 0) debugMarkerSupported = true; } #if defined(_WIN32) && defined(_MSC_VER) @@ -1804,7 +1804,7 @@ void rlLoadExtensions(void *loader) #if defined(GRAPHICS_API_OPENGL_21) if (GLAD_GL_VERSION_2_1) TraceLog(LOG_INFO, "OpenGL 2.1 profile supported"); #elif defined(GRAPHICS_API_OPENGL_33) - if(GLAD_GL_VERSION_3_3) TraceLog(LOG_INFO, "OpenGL 3.3 Core profile supported"); + if (GLAD_GL_VERSION_3_3) TraceLog(LOG_INFO, "OpenGL 3.3 Core profile supported"); else TraceLog(LOG_ERROR, "OpenGL 3.3 Core profile not supported"); #endif #endif @@ -4095,7 +4095,7 @@ static void UpdateBuffersDefault(void) // Another option: map the buffer object into client's memory // Probably this code could be moved somewhere else... // vertexData[currentBuffer].vertices = (float *)glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE); - // if(vertexData[currentBuffer].vertices) + // if (vertexData[currentBuffer].vertices) // { // Update vertex data // } diff --git a/src/shapes.c b/src/shapes.c index 837e4e9c..fd28f3a3 100644 --- a/src/shapes.c +++ b/src/shapes.c @@ -400,7 +400,7 @@ void DrawRectangleLinesEx(Rectangle rec, int lineThick, Color color) { if (lineThick > rec.width || lineThick > rec.height) { - if(rec.width > rec.height) lineThick = (int)rec.height/2; + if (rec.width > rec.height) lineThick = (int)rec.height/2; else if (rec.width < rec.height) lineThick = (int)rec.width/2; } diff --git a/src/text.c b/src/text.c index f228a4df..d44cdd11 100644 --- a/src/text.c +++ b/src/text.c @@ -1326,13 +1326,11 @@ int TextToInteger(const char *text) return result; } - //---------------------------------------------------------------------------------- //---------------------------------------------------------------------------------- // Module specific Functions Definition //---------------------------------------------------------------------------------- - #if defined(SUPPORT_FILEFORMAT_FNT) // Load a BMFont file (AngelCode font file) static Font LoadBMFont(const char *fileName) -- cgit v1.2.3 From d7fd6e0f1a4106690af7901173f421ea2fb1ea40 Mon Sep 17 00:00:00 2001 From: raysan5 Date: Sat, 2 Mar 2019 14:29:04 +0100 Subject: Corrected issue with possible 0 division Reported on rfxgen tool, it crashes on some parameters --- src/raudio.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/raudio.c b/src/raudio.c index 5f42222e..d24cc8e6 100644 --- a/src/raudio.c +++ b/src/raudio.c @@ -367,7 +367,7 @@ static mal_uint32 OnAudioBufferDSPRead(mal_dsp *pDSP, mal_uint32 frameCount, voi { AudioBuffer *audioBuffer = (AudioBuffer *)pUserData; - mal_uint32 subBufferSizeInFrames = audioBuffer->bufferSizeInFrames/2; + mal_uint32 subBufferSizeInFrames = (audioBuffer->bufferSizeInFrames > 1)? audioBuffer->bufferSizeInFrames/2 : audioBuffer->bufferSizeInFrames; mal_uint32 currentSubBufferIndex = audioBuffer->frameCursorPos/subBufferSizeInFrames; if (currentSubBufferIndex > 1) -- cgit v1.2.3 From 2e99c6cefbaacf03d71ad10c03a60fbb49c46aa1 Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 4 Mar 2019 22:58:20 +0100 Subject: ADDED: IsWindowResized() --- src/core.c | 15 +++++++++++++++ src/raylib.h | 1 + 2 files changed, 16 insertions(+) (limited to 'src') diff --git a/src/core.c b/src/core.c index 4e195ec7..e6852eef 100644 --- a/src/core.c +++ b/src/core.c @@ -273,6 +273,7 @@ static GLFWwindow *window; // Native window (graphic device #endif static bool windowReady = false; // Check if window has been initialized successfully static bool windowMinimized = false; // Check if window has been minimized +static bool windowResized = false; // Check if window has been resized static const char *windowTitle = NULL; // Window text title... static unsigned int displayWidth, displayHeight;// Display width and height (monitor, device-screen, LCD, ...) @@ -742,6 +743,16 @@ bool IsWindowMinimized(void) #endif } +// Check if window has been resized +bool IsWindowResized(void) +{ +#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB) || defined(PLATFORM_UWP) + return windowResized; +#else + return false; +#endif +} + // Check if window is currently hidden bool IsWindowHidden(void) { @@ -3137,6 +3148,8 @@ static void PollInputEvents(void) gamepadAxisCount = axisCount; } } + + windowResized = false; #if defined(SUPPORT_EVENTS_WAITING) glfwWaitEvents(); @@ -3414,6 +3427,8 @@ static void WindowSizeCallback(GLFWwindow *window, int width, int height) currentHeight = height; // NOTE: Postprocessing texture is not scaled to new size + + windowResized = true; } // GLFW3 WindowIconify Callback, runs when window is minimized/restored diff --git a/src/raylib.h b/src/raylib.h index 17a6efc6..9fdcf2d8 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -865,6 +865,7 @@ RLAPI bool WindowShouldClose(void); // Check if KE RLAPI void CloseWindow(void); // Close window and unload OpenGL context RLAPI bool IsWindowReady(void); // Check if window has been initialized successfully RLAPI bool IsWindowMinimized(void); // Check if window has been minimized (or lost focus) +RLAPI bool IsWindowResized(void); // Check if window has been resized RLAPI bool IsWindowHidden(void); // Check if window is currently hidden RLAPI void ToggleFullscreen(void); // Toggle fullscreen mode (only PLATFORM_DESKTOP) RLAPI void UnhideWindow(void); // Show the window -- cgit v1.2.3 From 2f97a3f83531867511f65f2b2ed894706cfb2e06 Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 5 Mar 2019 16:46:48 +0100 Subject: Proposed Model struct review --- src/raylib.h | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/raylib.h b/src/raylib.h index 9fdcf2d8..cc461204 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -342,6 +342,15 @@ typedef struct Model { Mesh mesh; // Vertex data buffers (RAM and VRAM) Matrix transform; // Local transform matrix Material material; // Shader and textures data + /* + Mesh *meshes; // Vertex data buffers (RAM and VRAM) + int meshCount; + + Material *materials; // Shader and textures data + int materialCount; + + int *meshMaterial; // Material assigned to every mesh + */ } Model; // Ray type (useful for raycast) @@ -1180,7 +1189,7 @@ RLAPI const char *TextSubtext(const char *text, int position, int length); RLAPI const char *TextReplace(char *text, const char *replace, const char *by); // Replace text string (memory should be freed!) RLAPI const char *TextInsert(const char *text, const char *insert, int position); // Insert text in a position (memory should be freed!) RLAPI const char *TextJoin(const char **textList, int count, const char *delimiter); // Join text strings with delimiter -RLAPI const char **TextSplit(const char *text, char delimiter, int *count); // Split text into multiple strings +RLAPI const char **TextSplit(const char *text, char delimiter, int *count); // Split text into multiple strings RLAPI void TextAppend(char *text, const char *append, int *position); // Append text at specific position and move cursor! RLAPI int TextFindIndex(const char *text, const char *find); // Find first text occurrence within a string RLAPI const char *TextToUpper(const char *text); // Get upper case version of provided string -- cgit v1.2.3 From 9f54a69cec1e6d2927e1998e75e316ce133e4669 Mon Sep 17 00:00:00 2001 From: Rafael Sachetto Date: Fri, 8 Mar 2019 15:06:17 -0300 Subject: Adding DrawCubeWiresV for convenience --- src/models.c | 6 ++++++ src/raylib.h | 1 + 2 files changed, 7 insertions(+) (limited to 'src') diff --git a/src/models.c b/src/models.c index b261f58d..a5dbf5e7 100644 --- a/src/models.c +++ b/src/models.c @@ -285,6 +285,12 @@ void DrawCubeWires(Vector3 position, float width, float height, float length, Co rlPopMatrix(); } +// Draw cube wires (vector version) +void DrawCubeWiresV(Vector3 position, Vector3 size, Color color) +{ + DrawCubeWires(position, size.x, size.y, size.z, color); +} + // Draw cube // NOTE: Cube position is the center position void DrawCubeTexture(Texture2D texture, Vector3 position, float width, float height, float length, Color color) diff --git a/src/raylib.h b/src/raylib.h index cc461204..ccdb4aab 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -1207,6 +1207,7 @@ RLAPI void DrawCircle3D(Vector3 center, float radius, Vector3 rotationAxis, floa RLAPI void DrawCube(Vector3 position, float width, float height, float length, Color color); // Draw cube RLAPI void DrawCubeV(Vector3 position, Vector3 size, Color color); // Draw cube (Vector version) RLAPI void DrawCubeWires(Vector3 position, float width, float height, float length, Color color); // Draw cube wires +RLAPI void DrawCubeWiresV(Vector3 position, Vector3 size, Color color); // Draw cube wires (Vector version) RLAPI void DrawCubeTexture(Texture2D texture, Vector3 position, float width, float height, float length, Color color); // Draw cube textured RLAPI void DrawSphere(Vector3 centerPos, float radius, Color color); // Draw sphere RLAPI void DrawSphereEx(Vector3 centerPos, float radius, int rings, int slices, Color color); // Draw sphere with extended parameters -- cgit v1.2.3 From 76e968f6b7b211ed056f5ffe97d13086f58a661a Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 12 Mar 2019 11:54:45 +0100 Subject: Updated audio library: mini_al -> miniaudio --- src/external/mini_al.h | 29952 ------------------------------------------ src/external/miniaudio.h | 31816 +++++++++++++++++++++++++++++++++++++++++++++ src/raudio.c | 228 +- src/raudio.h | 2 +- 4 files changed, 31934 insertions(+), 30064 deletions(-) delete mode 100644 src/external/mini_al.h create mode 100644 src/external/miniaudio.h (limited to 'src') diff --git a/src/external/mini_al.h b/src/external/mini_al.h deleted file mode 100644 index 9916c3ef..00000000 --- a/src/external/mini_al.h +++ /dev/null @@ -1,29952 +0,0 @@ -// Audio playback and capture library. Public domain. See "unlicense" statement at the end of this file. -// mini_al - v0.8.15 - 201x-xx-xx -// -// David Reid - davidreidsoftware@gmail.com - -// ABOUT -// ===== -// mini_al is a single file library for audio playback and capture. It's written in C (compilable as -// C++) and released into the public domain. -// -// Supported Backends: -// - WASAPI -// - DirectSound -// - WinMM -// - Core Audio (Apple) -// - ALSA -// - PulseAudio -// - JACK -// - sndio (OpenBSD) -// - audio(4) (NetBSD and OpenBSD) -// - OSS (FreeBSD) -// - AAudio (Android 8.0+) -// - OpenSL|ES (Android only) -// - Web Audio (Emscripten) -// - Null (Silence) -// -// Supported Formats: -// - Unsigned 8-bit PCM -// - Signed 16-bit PCM -// - Signed 24-bit PCM (tightly packed) -// - Signed 32-bit PCM -// - IEEE 32-bit floating point PCM -// -// -// USAGE -// ===== -// mini_al is a single-file library. To use it, do something like the following in one .c file. -// #define MINI_AL_IMPLEMENTATION -// #include "mini_al.h" -// -// You can then #include this file in other parts of the program as you would with any other header file. -// -// mini_al uses an asynchronous, callback based API. You initialize a device with a configuration (sample rate, -// channel count, etc.) which includes the callback you want to use to handle data transmission to/from the -// device. In the callback you either read from a data pointer in the case of playback or write to it in the case -// of capture. -// -// Playback Example -// ---------------- -// mal_uint32 on_send_samples(mal_device* pDevice, mal_uint32 frameCount, void* pSamples) -// { -// // This callback is set at initialization time and will be called when a playback device needs more -// // data. You need to write as many frames as you can to pSamples (but no more than frameCount) and -// // then return the number of frames you wrote. -// // -// // The user data (pDevice->pUserData) is set by mal_device_init(). -// return (mal_uint32)mal_decoder_read((mal_decoder*)pDevice->pUserData, frameCount, pSamples); -// } -// -// ... -// -// mal_device_config config = mal_device_config_init_playback(decoder.outputFormat, decoder.outputChannels, decoder.outputSampleRate, on_send_frames_to_device); -// -// mal_device device; -// mal_result result = mal_device_init(NULL, mal_device_type_playback, NULL, &config, &decoder /*pUserData*/, &device); -// if (result != MAL_SUCCESS) { -// return -1; -// } -// -// mal_device_start(&device); // The device is sleeping by default so you'll need to start it manually. -// -// ... -// -// mal_device_uninit(&device); // This will stop the device so no need to do that manually. -// -// -// -// If you want to disable a specific backend, #define the appropriate MAL_NO_* option before the implementation. -// -// Note that GCC and Clang requires "-msse2", "-mavx2", etc. for SIMD optimizations. -// -// -// Building for Windows -// -------------------- -// The Windows build should compile clean on all popular compilers without the need to configure any include paths -// nor link to any libraries. -// -// Building for macOS and iOS -// -------------------------- -// The macOS build should compile clean without the need to download any dependencies or link to any libraries or -// frameworks. The iOS build needs to be compiled as Objective-C (sorry) and will need to link the relevant frameworks -// but should Just Work with Xcode. -// -// Building for Linux -// ------------------ -// The Linux build only requires linking to -ldl, -lpthread and -lm. You do not need any development packages. -// -// Building for BSD -// ---------------- -// The BSD build only requires linking to -ldl, -lpthread and -lm. NetBSD uses audio(4), OpenBSD uses sndio and -// FreeBSD uses OSS. -// -// Building for Android -// -------------------- -// AAudio is the highest priority backend on Android. This should work out out of the box without needing any kind of -// compiler configuration. Support for AAudio starts with Android 8 which means older versions will fall back to -// OpenSL|ES which requires API level 16+. -// -// Building for Emscripten -// ----------------------- -// The Emscripten build emits Web Audio JavaScript directly and should Just Work without any configuration. -// -// -// NOTES -// ===== -// - This library uses an asynchronous API for delivering and requesting audio data. Each device will have -// it's own worker thread which is managed by the library. -// - If mal_device_init() is called with a device that's not aligned to the platform's natural alignment -// boundary (4 bytes on 32-bit, 8 bytes on 64-bit), it will _not_ be thread-safe. The reason for this -// is that it depends on members of mal_device being correctly aligned for atomic assignments. -// - Sample data is always native-endian and interleaved. For example, mal_format_s16 means signed 16-bit -// integer samples, interleaved. Let me know if you need non-interleaved and I'll look into it. -// - The sndio backend is currently only enabled on OpenBSD builds. -// - The audio(4) backend is supported on OpenBSD, but you may need to disable sndiod before you can use it. -// - If you are using the platform's default device, mini_al will try automatically switching the internal -// device when the device is unplugged. This feature is disabled when the device is opened in exclusive -// mode. -// -// -// BACKEND NUANCES -// =============== -// -// PulseAudio -// ---------- -// - If you experience bad glitching/noise on Arch Linux, consider this fix from the Arch wiki: -// https://wiki.archlinux.org/index.php/PulseAudio/Troubleshooting#Glitches,_skips_or_crackling -// Alternatively, consider using a different backend such as ALSA. -// -// Android -// ------- -// - To capture audio on Android, remember to add the RECORD_AUDIO permission to your manifest: -// -// - With OpenSL|ES, only a single mal_context can be active at any given time. This is due to a limitation with OpenSL|ES. -// - With AAudio, only default devices are enumerated. This is due to AAudio not having an enumeration API (devices are -// enumerated through Java). You can however perform your own device enumeration through Java and then set the ID in the -// mal_device_id structure (mal_device_id.aaudio) and pass it to mal_device_init(). -// - The backend API will perform resampling where possible. The reason for this as opposed to using mini_al's built-in -// resampler is to take advantage of any potential device-specific optimizations the driver may implement. -// -// UWP -// --- -// - UWP only supports default playback and capture devices. -// - UWP requires the Microphone capability to be enabled in the application's manifest (Package.appxmanifest): -// -// ... -// -// -// -// -// -// Web Audio / Emscripten -// ---------------------- -// - The first time a context is initialized it will create a global object called "mal" whose primary purpose is to act -// as a factory for device objects. -// - Currently the Web Audio backend uses ScriptProcessorNode's, but this may need to change later as they've been deprecated. -// - Google is implementing a policy in their browsers that prevent automatic media output without first receiving some kind -// of user input. See here for details: https://developers.google.com/web/updates/2017/09/autoplay-policy-changes. Starting -// the device may fail if you try to start playback without first handling some kind of user input. -// -// OpenAL -// ------ -// - Capture is not supported on iOS with OpenAL. Use the Core Audio backend instead. -// -// -// OPTIONS -// ======= -// #define these options before including this file. -// -// #define MAL_NO_WASAPI -// Disables the WASAPI backend. -// -// #define MAL_NO_DSOUND -// Disables the DirectSound backend. -// -// #define MAL_NO_WINMM -// Disables the WinMM backend. -// -// #define MAL_NO_ALSA -// Disables the ALSA backend. -// -// #define MAL_NO_PULSEAUDIO -// Disables the PulseAudio backend. -// -// #define MAL_NO_JACK -// Disables the JACK backend. -// -// #define MAL_NO_COREAUDIO -// Disables the Core Audio backend. -// -// #define MAL_NO_SNDIO -// Disables the sndio backend. -// -// #define MAL_NO_AUDIO4 -// Disables the audio(4) backend. -// -// #define MAL_NO_OSS -// Disables the OSS backend. -// -// #define MAL_NO_AAUDIO -// Disables the AAudio backend. -// -// #define MAL_NO_OPENSL -// Disables the OpenSL|ES backend. -// -// #define MAL_NO_WEBAUDIO -// Disables the Web Audio backend. -// -// #define MAL_NO_OPENAL -// Disables the OpenAL backend. -// -// #define MAL_NO_SDL -// Disables the SDL backend. -// -// #define MAL_NO_NULL -// Disables the null backend. -// -// #define MAL_DEFAULT_PERIODS -// When a period count of 0 is specified when a device is initialized, it will default to this. -// -// #define MAL_BASE_BUFFER_SIZE_IN_MILLISECONDS_LOW_LATENCY -// #define MAL_BASE_BUFFER_SIZE_IN_MILLISECONDS_CONSERVATIVE -// When a buffer size of 0 is specified when a device is initialized it will default to a buffer of this size, depending -// on the chosen performance profile. These can be increased or decreased depending on your specific requirements. -// -// #define MAL_NO_DECODING -// Disables the decoding APIs. -// -// #define MAL_NO_DEVICE_IO -// Disables playback and recording. This will disable mal_context and mal_device APIs. This is useful if you only want to -// use mini_al's data conversion and/or decoding APIs. -// -// #define MAL_NO_STDIO -// Disables file IO APIs. -// -// #define MAL_NO_SSE2 -// Disables SSE2 optimizations. -// -// #define MAL_NO_AVX2 -// Disables AVX2 optimizations. -// -// #define MAL_NO_AVX512 -// Disables AVX-512 optimizations. -// -// #define MAL_NO_NEON -// Disables NEON optimizations. -// -// #define MAL_LOG_LEVEL -// Sets the logging level. Set level to one of the following: -// MAL_LOG_LEVEL_VERBOSE -// MAL_LOG_LEVEL_INFO -// MAL_LOG_LEVEL_WARNING -// MAL_LOG_LEVEL_ERROR -// -// #define MAL_DEBUT_OUTPUT -// Enable printf() debug output. -// -// #ifndef MAL_COINIT_VALUE -// Windows only. The value to pass to internal calls to CoInitializeEx(). Defaults to COINIT_MULTITHREADED. - -#ifndef mini_al_h -#define mini_al_h - -#ifdef __cplusplus -extern "C" { -#endif - -#if defined(_MSC_VER) - #pragma warning(push) - #pragma warning(disable:4201) // nonstandard extension used: nameless struct/union - #pragma warning(disable:4324) // structure was padded due to alignment specifier -#endif - -// Platform/backend detection. -#ifdef _WIN32 - #define MAL_WIN32 - #if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_PC_APP || WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP) - #define MAL_WIN32_UWP - #else - #define MAL_WIN32_DESKTOP - #endif -#else - #define MAL_POSIX - #include // Unfortunate #include, but needed for pthread_t, pthread_mutex_t and pthread_cond_t types. - - #ifdef __unix__ - #define MAL_UNIX - #if defined(__DragonFly__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) - #define MAL_BSD - #endif - #endif - #ifdef __linux__ - #define MAL_LINUX - #endif - #ifdef __APPLE__ - #define MAL_APPLE - #endif - #ifdef __ANDROID__ - #define MAL_ANDROID - #endif - #ifdef __EMSCRIPTEN__ - #define MAL_EMSCRIPTEN - #endif -#endif - -#include // For size_t. - -#ifndef MAL_HAS_STDINT - #if defined(_MSC_VER) - #if _MSC_VER >= 1600 - #define MAL_HAS_STDINT - #endif - #else - #if defined(__has_include) - #if __has_include() - #define MAL_HAS_STDINT - #endif - #endif - #endif -#endif - -#if !defined(MAL_HAS_STDINT) && (defined(__GNUC__) || defined(__clang__)) // Assume support for stdint.h on GCC and Clang. - #define MAL_HAS_STDINT -#endif - -#ifndef MAL_HAS_STDINT -typedef signed char mal_int8; -typedef unsigned char mal_uint8; -typedef signed short mal_int16; -typedef unsigned short mal_uint16; -typedef signed int mal_int32; -typedef unsigned int mal_uint32; - #if defined(_MSC_VER) - typedef signed __int64 mal_int64; - typedef unsigned __int64 mal_uint64; - #else - typedef signed long long int mal_int64; - typedef unsigned long long int mal_uint64; - #endif - #if defined(_WIN32) - #if defined(_WIN64) - typedef mal_uint64 mal_uintptr; - #else - typedef mal_uint32 mal_uintptr; - #endif - #elif defined(__GNUC__) - #if defined(__LP64__) - typedef mal_uint64 mal_uintptr; - #else - typedef mal_uint32 mal_uintptr; - #endif - #else - typedef mal_uint64 mal_uintptr; // Fallback. - #endif -#else -#include -typedef int8_t mal_int8; -typedef uint8_t mal_uint8; -typedef int16_t mal_int16; -typedef uint16_t mal_uint16; -typedef int32_t mal_int32; -typedef uint32_t mal_uint32; -typedef int64_t mal_int64; -typedef uint64_t mal_uint64; -typedef uintptr_t mal_uintptr; -#endif -typedef mal_uint8 mal_bool8; -typedef mal_uint32 mal_bool32; -#define MAL_TRUE 1 -#define MAL_FALSE 0 - -typedef void* mal_handle; -typedef void* mal_ptr; -typedef void (* mal_proc)(void); - -#if defined(_MSC_VER) && !defined(_WCHAR_T_DEFINED) -typedef mal_uint16 wchar_t; -#endif - -// Define NULL for some compilers. -#ifndef NULL -#define NULL 0 -#endif - -#if defined(SIZE_MAX) - #define MAL_SIZE_MAX SIZE_MAX -#else - #define MAL_SIZE_MAX 0xFFFFFFFF /* When SIZE_MAX is not defined by the standard library just default to the maximum 32-bit unsigned integer. */ -#endif - - -#ifdef _MSC_VER -#define MAL_INLINE __forceinline -#else -#ifdef __GNUC__ -#define MAL_INLINE inline __attribute__((always_inline)) -#else -#define MAL_INLINE inline -#endif -#endif - -#ifdef _MSC_VER -#define MAL_ALIGN(alignment) __declspec(align(alignment)) -#elif !defined(__DMC__) -#define MAL_ALIGN(alignment) __attribute__((aligned(alignment))) -#else -#define MAL_ALIGN(alignment) -#endif - -#ifdef _MSC_VER -#define MAL_ALIGNED_STRUCT(alignment) MAL_ALIGN(alignment) struct -#else -#define MAL_ALIGNED_STRUCT(alignment) struct MAL_ALIGN(alignment) -#endif - -// SIMD alignment in bytes. Currently set to 64 bytes in preparation for future AVX-512 optimizations. -#define MAL_SIMD_ALIGNMENT 64 - - -// Logging levels -#define MAL_LOG_LEVEL_VERBOSE 4 -#define MAL_LOG_LEVEL_INFO 3 -#define MAL_LOG_LEVEL_WARNING 2 -#define MAL_LOG_LEVEL_ERROR 1 - -#ifndef MAL_LOG_LEVEL -#define MAL_LOG_LEVEL MAL_LOG_LEVEL_ERROR -#endif - -typedef struct mal_context mal_context; -typedef struct mal_device mal_device; - -typedef mal_uint8 mal_channel; -#define MAL_CHANNEL_NONE 0 -#define MAL_CHANNEL_MONO 1 -#define MAL_CHANNEL_FRONT_LEFT 2 -#define MAL_CHANNEL_FRONT_RIGHT 3 -#define MAL_CHANNEL_FRONT_CENTER 4 -#define MAL_CHANNEL_LFE 5 -#define MAL_CHANNEL_BACK_LEFT 6 -#define MAL_CHANNEL_BACK_RIGHT 7 -#define MAL_CHANNEL_FRONT_LEFT_CENTER 8 -#define MAL_CHANNEL_FRONT_RIGHT_CENTER 9 -#define MAL_CHANNEL_BACK_CENTER 10 -#define MAL_CHANNEL_SIDE_LEFT 11 -#define MAL_CHANNEL_SIDE_RIGHT 12 -#define MAL_CHANNEL_TOP_CENTER 13 -#define MAL_CHANNEL_TOP_FRONT_LEFT 14 -#define MAL_CHANNEL_TOP_FRONT_CENTER 15 -#define MAL_CHANNEL_TOP_FRONT_RIGHT 16 -#define MAL_CHANNEL_TOP_BACK_LEFT 17 -#define MAL_CHANNEL_TOP_BACK_CENTER 18 -#define MAL_CHANNEL_TOP_BACK_RIGHT 19 -#define MAL_CHANNEL_AUX_0 20 -#define MAL_CHANNEL_AUX_1 21 -#define MAL_CHANNEL_AUX_2 22 -#define MAL_CHANNEL_AUX_3 23 -#define MAL_CHANNEL_AUX_4 24 -#define MAL_CHANNEL_AUX_5 25 -#define MAL_CHANNEL_AUX_6 26 -#define MAL_CHANNEL_AUX_7 27 -#define MAL_CHANNEL_AUX_8 28 -#define MAL_CHANNEL_AUX_9 29 -#define MAL_CHANNEL_AUX_10 30 -#define MAL_CHANNEL_AUX_11 31 -#define MAL_CHANNEL_AUX_12 32 -#define MAL_CHANNEL_AUX_13 33 -#define MAL_CHANNEL_AUX_14 34 -#define MAL_CHANNEL_AUX_15 35 -#define MAL_CHANNEL_AUX_16 36 -#define MAL_CHANNEL_AUX_17 37 -#define MAL_CHANNEL_AUX_18 38 -#define MAL_CHANNEL_AUX_19 39 -#define MAL_CHANNEL_AUX_20 40 -#define MAL_CHANNEL_AUX_21 41 -#define MAL_CHANNEL_AUX_22 42 -#define MAL_CHANNEL_AUX_23 43 -#define MAL_CHANNEL_AUX_24 44 -#define MAL_CHANNEL_AUX_25 45 -#define MAL_CHANNEL_AUX_26 46 -#define MAL_CHANNEL_AUX_27 47 -#define MAL_CHANNEL_AUX_28 48 -#define MAL_CHANNEL_AUX_29 49 -#define MAL_CHANNEL_AUX_30 50 -#define MAL_CHANNEL_AUX_31 51 -#define MAL_CHANNEL_LEFT MAL_CHANNEL_FRONT_LEFT -#define MAL_CHANNEL_RIGHT MAL_CHANNEL_FRONT_RIGHT -#define MAL_CHANNEL_POSITION_COUNT MAL_CHANNEL_AUX_31 + 1 - -typedef int mal_result; -#define MAL_SUCCESS 0 -#define MAL_ERROR -1 // A generic error. -#define MAL_INVALID_ARGS -2 -#define MAL_INVALID_OPERATION -3 -#define MAL_OUT_OF_MEMORY -4 -#define MAL_FORMAT_NOT_SUPPORTED -5 -#define MAL_NO_BACKEND -6 -#define MAL_NO_DEVICE -7 -#define MAL_API_NOT_FOUND -8 -#define MAL_DEVICE_BUSY -9 -#define MAL_DEVICE_NOT_INITIALIZED -10 -#define MAL_DEVICE_NOT_STARTED -11 -#define MAL_DEVICE_NOT_STOPPED -12 -#define MAL_DEVICE_ALREADY_STARTED -13 -#define MAL_DEVICE_ALREADY_STARTING -14 -#define MAL_DEVICE_ALREADY_STOPPED -15 -#define MAL_DEVICE_ALREADY_STOPPING -16 -#define MAL_FAILED_TO_MAP_DEVICE_BUFFER -17 -#define MAL_FAILED_TO_UNMAP_DEVICE_BUFFER -18 -#define MAL_FAILED_TO_INIT_BACKEND -19 -#define MAL_FAILED_TO_READ_DATA_FROM_CLIENT -20 -#define MAL_FAILED_TO_READ_DATA_FROM_DEVICE -21 -#define MAL_FAILED_TO_SEND_DATA_TO_CLIENT -22 -#define MAL_FAILED_TO_SEND_DATA_TO_DEVICE -23 -#define MAL_FAILED_TO_OPEN_BACKEND_DEVICE -24 -#define MAL_FAILED_TO_START_BACKEND_DEVICE -25 -#define MAL_FAILED_TO_STOP_BACKEND_DEVICE -26 -#define MAL_FAILED_TO_CONFIGURE_BACKEND_DEVICE -27 -#define MAL_FAILED_TO_CREATE_MUTEX -28 -#define MAL_FAILED_TO_CREATE_EVENT -29 -#define MAL_FAILED_TO_CREATE_THREAD -30 -#define MAL_INVALID_DEVICE_CONFIG -31 -#define MAL_ACCESS_DENIED -32 -#define MAL_TOO_LARGE -33 -#define MAL_DEVICE_UNAVAILABLE -34 -#define MAL_TIMEOUT -35 - -// Standard sample rates. -#define MAL_SAMPLE_RATE_8000 8000 -#define MAL_SAMPLE_RATE_11025 11025 -#define MAL_SAMPLE_RATE_16000 16000 -#define MAL_SAMPLE_RATE_22050 22050 -#define MAL_SAMPLE_RATE_24000 24000 -#define MAL_SAMPLE_RATE_32000 32000 -#define MAL_SAMPLE_RATE_44100 44100 -#define MAL_SAMPLE_RATE_48000 48000 -#define MAL_SAMPLE_RATE_88200 88200 -#define MAL_SAMPLE_RATE_96000 96000 -#define MAL_SAMPLE_RATE_176400 176400 -#define MAL_SAMPLE_RATE_192000 192000 -#define MAL_SAMPLE_RATE_352800 352800 -#define MAL_SAMPLE_RATE_384000 384000 - -#define MAL_MIN_PCM_SAMPLE_SIZE_IN_BYTES 1 // For simplicity, mini_al does not support PCM samples that are not byte aligned. -#define MAL_MAX_PCM_SAMPLE_SIZE_IN_BYTES 8 -#define MAL_MIN_CHANNELS 1 -#define MAL_MAX_CHANNELS 32 -#define MAL_MIN_SAMPLE_RATE MAL_SAMPLE_RATE_8000 -#define MAL_MAX_SAMPLE_RATE MAL_SAMPLE_RATE_384000 -#define MAL_SRC_SINC_MIN_WINDOW_WIDTH 2 -#define MAL_SRC_SINC_MAX_WINDOW_WIDTH 32 -#define MAL_SRC_SINC_DEFAULT_WINDOW_WIDTH 32 -#define MAL_SRC_SINC_LOOKUP_TABLE_RESOLUTION 8 -#define MAL_SRC_INPUT_BUFFER_SIZE_IN_SAMPLES 256 - -typedef enum -{ - mal_stream_format_pcm = 0, -} mal_stream_format; - -typedef enum -{ - mal_stream_layout_interleaved = 0, - mal_stream_layout_deinterleaved -} mal_stream_layout; - -typedef enum -{ - mal_dither_mode_none = 0, - mal_dither_mode_rectangle, - mal_dither_mode_triangle -} mal_dither_mode; - -typedef enum -{ - // I like to keep these explicitly defined because they're used as a key into a lookup table. When items are - // added to this, make sure there are no gaps and that they're added to the lookup table in mal_get_bytes_per_sample(). - mal_format_unknown = 0, // Mainly used for indicating an error, but also used as the default for the output format for decoders. - mal_format_u8 = 1, - mal_format_s16 = 2, // Seems to be the most widely supported format. - mal_format_s24 = 3, // Tightly packed. 3 bytes per sample. - mal_format_s32 = 4, - mal_format_f32 = 5, - mal_format_count -} mal_format; - -typedef enum -{ - mal_channel_mix_mode_rectangular = 0, // Simple averaging based on the plane(s) the channel is sitting on. - mal_channel_mix_mode_simple, // Drop excess channels; zeroed out extra channels. - mal_channel_mix_mode_custom_weights, // Use custom weights specified in mal_channel_router_config. - mal_channel_mix_mode_planar_blend = mal_channel_mix_mode_rectangular, - mal_channel_mix_mode_default = mal_channel_mix_mode_planar_blend -} mal_channel_mix_mode; - -typedef enum -{ - mal_standard_channel_map_microsoft, - mal_standard_channel_map_alsa, - mal_standard_channel_map_rfc3551, // Based off AIFF. - mal_standard_channel_map_flac, - mal_standard_channel_map_vorbis, - mal_standard_channel_map_sound4, // FreeBSD's sound(4). - mal_standard_channel_map_sndio, // www.sndio.org/tips.html - mal_standard_channel_map_webaudio = mal_standard_channel_map_flac, // https://webaudio.github.io/web-audio-api/#ChannelOrdering. Only 1, 2, 4 and 6 channels are defined, but can fill in the gaps with logical assumptions. - mal_standard_channel_map_default = mal_standard_channel_map_microsoft -} mal_standard_channel_map; - -typedef enum -{ - mal_performance_profile_low_latency = 0, - mal_performance_profile_conservative -} mal_performance_profile; - - -typedef struct mal_format_converter mal_format_converter; -typedef mal_uint32 (* mal_format_converter_read_proc) (mal_format_converter* pConverter, mal_uint32 frameCount, void* pFramesOut, void* pUserData); -typedef mal_uint32 (* mal_format_converter_read_deinterleaved_proc)(mal_format_converter* pConverter, mal_uint32 frameCount, void** ppSamplesOut, void* pUserData); - -typedef struct -{ - mal_format formatIn; - mal_format formatOut; - mal_uint32 channels; - mal_stream_format streamFormatIn; - mal_stream_format streamFormatOut; - mal_dither_mode ditherMode; - mal_bool32 noSSE2 : 1; - mal_bool32 noAVX2 : 1; - mal_bool32 noAVX512 : 1; - mal_bool32 noNEON : 1; - mal_format_converter_read_proc onRead; - mal_format_converter_read_deinterleaved_proc onReadDeinterleaved; - void* pUserData; -} mal_format_converter_config; - -struct mal_format_converter -{ - mal_format_converter_config config; - mal_bool32 useSSE2 : 1; - mal_bool32 useAVX2 : 1; - mal_bool32 useAVX512 : 1; - mal_bool32 useNEON : 1; - void (* onConvertPCM)(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode); - void (* onInterleavePCM)(void* dst, const void** src, mal_uint64 frameCount, mal_uint32 channels); - void (* onDeinterleavePCM)(void** dst, const void* src, mal_uint64 frameCount, mal_uint32 channels); -}; - - - -typedef struct mal_channel_router mal_channel_router; -typedef mal_uint32 (* mal_channel_router_read_deinterleaved_proc)(mal_channel_router* pRouter, mal_uint32 frameCount, void** ppSamplesOut, void* pUserData); - -typedef struct -{ - mal_uint32 channelsIn; - mal_uint32 channelsOut; - mal_channel channelMapIn[MAL_MAX_CHANNELS]; - mal_channel channelMapOut[MAL_MAX_CHANNELS]; - mal_channel_mix_mode mixingMode; - float weights[MAL_MAX_CHANNELS][MAL_MAX_CHANNELS]; // [in][out]. Only used when mixingMode is set to mal_channel_mix_mode_custom_weights. - mal_bool32 noSSE2 : 1; - mal_bool32 noAVX2 : 1; - mal_bool32 noAVX512 : 1; - mal_bool32 noNEON : 1; - mal_channel_router_read_deinterleaved_proc onReadDeinterleaved; - void* pUserData; -} mal_channel_router_config; - -struct mal_channel_router -{ - mal_channel_router_config config; - mal_bool32 isPassthrough : 1; - mal_bool32 isSimpleShuffle : 1; - mal_bool32 useSSE2 : 1; - mal_bool32 useAVX2 : 1; - mal_bool32 useAVX512 : 1; - mal_bool32 useNEON : 1; - mal_uint8 shuffleTable[MAL_MAX_CHANNELS]; -}; - - - -typedef struct mal_src mal_src; -//typedef mal_uint32 (* mal_src_read_proc)(mal_src* pSRC, mal_uint32 frameCount, void* pFramesOut, void* pUserData); // Returns the number of frames that were read. -typedef mal_uint32 (* mal_src_read_deinterleaved_proc)(mal_src* pSRC, mal_uint32 frameCount, void** ppSamplesOut, void* pUserData); // Returns the number of frames that were read. - -typedef enum -{ - mal_src_algorithm_sinc = 0, - mal_src_algorithm_linear, - mal_src_algorithm_none, - mal_src_algorithm_default = mal_src_algorithm_sinc -} mal_src_algorithm; - -typedef enum -{ - mal_src_sinc_window_function_hann = 0, - mal_src_sinc_window_function_rectangular, - mal_src_sinc_window_function_default = mal_src_sinc_window_function_hann -} mal_src_sinc_window_function; - -typedef struct -{ - mal_src_sinc_window_function windowFunction; - mal_uint32 windowWidth; -} mal_src_config_sinc; - -typedef struct -{ - mal_uint32 sampleRateIn; - mal_uint32 sampleRateOut; - mal_uint32 channels; - mal_src_algorithm algorithm; - mal_bool32 neverConsumeEndOfInput : 1; - mal_bool32 noSSE2 : 1; - mal_bool32 noAVX2 : 1; - mal_bool32 noAVX512 : 1; - mal_bool32 noNEON : 1; - mal_src_read_deinterleaved_proc onReadDeinterleaved; - void* pUserData; - union - { - mal_src_config_sinc sinc; - }; -} mal_src_config; - -MAL_ALIGNED_STRUCT(MAL_SIMD_ALIGNMENT) mal_src -{ - union - { - struct - { - MAL_ALIGN(MAL_SIMD_ALIGNMENT) float input[MAL_MAX_CHANNELS][MAL_SRC_INPUT_BUFFER_SIZE_IN_SAMPLES]; - float timeIn; - mal_uint32 leftoverFrames; - } linear; - - struct - { - MAL_ALIGN(MAL_SIMD_ALIGNMENT) float input[MAL_MAX_CHANNELS][MAL_SRC_SINC_MAX_WINDOW_WIDTH*2 + MAL_SRC_INPUT_BUFFER_SIZE_IN_SAMPLES]; - float timeIn; - mal_uint32 inputFrameCount; // The number of frames sitting in the input buffer, not including the first half of the window. - mal_uint32 windowPosInSamples; // An offset of . - float table[MAL_SRC_SINC_MAX_WINDOW_WIDTH*1 * MAL_SRC_SINC_LOOKUP_TABLE_RESOLUTION]; // Precomputed lookup table. The +1 is used to avoid the need for an overflow check. - } sinc; - }; - - mal_src_config config; - mal_bool32 isEndOfInputLoaded : 1; - mal_bool32 useSSE2 : 1; - mal_bool32 useAVX2 : 1; - mal_bool32 useAVX512 : 1; - mal_bool32 useNEON : 1; -}; - -typedef struct mal_dsp mal_dsp; -typedef mal_uint32 (* mal_dsp_read_proc)(mal_dsp* pDSP, mal_uint32 frameCount, void* pSamplesOut, void* pUserData); - -typedef struct -{ - mal_format formatIn; - mal_uint32 channelsIn; - mal_uint32 sampleRateIn; - mal_channel channelMapIn[MAL_MAX_CHANNELS]; - mal_format formatOut; - mal_uint32 channelsOut; - mal_uint32 sampleRateOut; - mal_channel channelMapOut[MAL_MAX_CHANNELS]; - mal_channel_mix_mode channelMixMode; - mal_dither_mode ditherMode; - mal_src_algorithm srcAlgorithm; - mal_bool32 allowDynamicSampleRate; - mal_bool32 neverConsumeEndOfInput : 1; // <-- For SRC. - mal_bool32 noSSE2 : 1; - mal_bool32 noAVX2 : 1; - mal_bool32 noAVX512 : 1; - mal_bool32 noNEON : 1; - mal_dsp_read_proc onRead; - void* pUserData; - union - { - mal_src_config_sinc sinc; - }; -} mal_dsp_config; - -MAL_ALIGNED_STRUCT(MAL_SIMD_ALIGNMENT) mal_dsp -{ - mal_dsp_read_proc onRead; - void* pUserData; - mal_format_converter formatConverterIn; // For converting data to f32 in preparation for further processing. - mal_format_converter formatConverterOut; // For converting data to the requested output format. Used as the final step in the processing pipeline. - mal_channel_router channelRouter; // For channel conversion. - mal_src src; // For sample rate conversion. - mal_bool32 isDynamicSampleRateAllowed : 1; // mal_dsp_set_input_sample_rate() and mal_dsp_set_output_sample_rate() will fail if this is set to false. - mal_bool32 isPreFormatConversionRequired : 1; - mal_bool32 isPostFormatConversionRequired : 1; - mal_bool32 isChannelRoutingRequired : 1; - mal_bool32 isSRCRequired : 1; - mal_bool32 isChannelRoutingAtStart : 1; - mal_bool32 isPassthrough : 1; // <-- Will be set to true when the DSP pipeline is an optimized passthrough. -}; - - -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// DATA CONVERSION -// =============== -// -// This section contains the APIs for data conversion. You will find everything here for channel mapping, sample format conversion, resampling, etc. -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Channel Maps -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -// Helper for retrieving a standard channel map. -void mal_get_standard_channel_map(mal_standard_channel_map standardChannelMap, mal_uint32 channels, mal_channel channelMap[MAL_MAX_CHANNELS]); - -// Copies a channel map. -void mal_channel_map_copy(mal_channel* pOut, const mal_channel* pIn, mal_uint32 channels); - - -// Determines whether or not a channel map is valid. -// -// A blank channel map is valid (all channels set to MAL_CHANNEL_NONE). The way a blank channel map is handled is context specific, but -// is usually treated as a passthrough. -// -// Invalid channel maps: -// - A channel map with no channels -// - A channel map with more than one channel and a mono channel -mal_bool32 mal_channel_map_valid(mal_uint32 channels, const mal_channel channelMap[MAL_MAX_CHANNELS]); - -// Helper for comparing two channel maps for equality. -// -// This assumes the channel count is the same between the two. -mal_bool32 mal_channel_map_equal(mal_uint32 channels, const mal_channel channelMapA[MAL_MAX_CHANNELS], const mal_channel channelMapB[MAL_MAX_CHANNELS]); - -// Helper for determining if a channel map is blank (all channels set to MAL_CHANNEL_NONE). -mal_bool32 mal_channel_map_blank(mal_uint32 channels, const mal_channel channelMap[MAL_MAX_CHANNELS]); - -// Helper for determining whether or not a channel is present in the given channel map. -mal_bool32 mal_channel_map_contains_channel_position(mal_uint32 channels, const mal_channel channelMap[MAL_MAX_CHANNELS], mal_channel channelPosition); - - -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Format Conversion -// ================= -// The format converter serves two purposes: -// 1) Conversion between data formats (u8 to f32, etc.) -// 2) Interleaving and deinterleaving -// -// When initializing a converter, you specify the input and output formats (u8, s16, etc.) and read callbacks. There are two read callbacks - one for -// interleaved input data (onRead) and another for deinterleaved input data (onReadDeinterleaved). You implement whichever is most convenient for you. You -// can implement both, but it's not recommended as it just introduces unnecessary complexity. -// -// To read data as interleaved samples, use mal_format_converter_read(). Otherwise use mal_format_converter_read_deinterleaved(). -// -// Dithering -// --------- -// The format converter also supports dithering. Dithering can be set using ditherMode variable in the config, like so. -// -// pConfig->ditherMode = mal_dither_mode_rectangle; -// -// The different dithering modes include the following, in order of efficiency: -// - None: mal_dither_mode_none -// - Rectangle: mal_dither_mode_rectangle -// - Triangle: mal_dither_mode_triangle -// -// Note that even if the dither mode is set to something other than mal_dither_mode_none, it will be ignored for conversions where dithering is not needed. -// Dithering is available for the following conversions: -// - s16 -> u8 -// - s24 -> u8 -// - s32 -> u8 -// - f32 -> u8 -// - s24 -> s16 -// - s32 -> s16 -// - f32 -> s16 -// -// Note that it is not an error to pass something other than mal_dither_mode_none for conversions where dither is not used. It will just be ignored. -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -// Initializes a format converter. -mal_result mal_format_converter_init(const mal_format_converter_config* pConfig, mal_format_converter* pConverter); - -// Reads data from the format converter as interleaved channels. -mal_uint64 mal_format_converter_read(mal_format_converter* pConverter, mal_uint64 frameCount, void* pFramesOut, void* pUserData); - -// Reads data from the format converter as deinterleaved channels. -mal_uint64 mal_format_converter_read_deinterleaved(mal_format_converter* pConverter, mal_uint64 frameCount, void** ppSamplesOut, void* pUserData); - - -// Helper for initializing a format converter config. -mal_format_converter_config mal_format_converter_config_init_new(void); -mal_format_converter_config mal_format_converter_config_init(mal_format formatIn, mal_format formatOut, mal_uint32 channels, mal_format_converter_read_proc onRead, void* pUserData); -mal_format_converter_config mal_format_converter_config_init_deinterleaved(mal_format formatIn, mal_format formatOut, mal_uint32 channels, mal_format_converter_read_deinterleaved_proc onReadDeinterleaved, void* pUserData); - - - -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Channel Routing -// =============== -// There are two main things you can do with the channel router: -// 1) Rearrange channels -// 2) Convert from one channel count to another -// -// Channel Rearrangement -// --------------------- -// A simple example of channel rearrangement may be swapping the left and right channels in a stereo stream. To do this you just pass in the same channel -// count for both the input and output with channel maps that contain the same channels (in a different order). -// -// Channel Conversion -// ------------------ -// The channel router can also convert from one channel count to another, such as converting a 5.1 stream to stero. When changing the channel count, the -// router will first perform a 1:1 mapping of channel positions that are present in both the input and output channel maps. The second thing it will do -// is distribute the input mono channel (if any) across all output channels, excluding any None and LFE channels. If there is an output mono channel, all -// input channels will be averaged, excluding any None and LFE channels. -// -// The last case to consider is when a channel position in the input channel map is not present in the output channel map, and vice versa. In this case the -// channel router will perform a blend of other related channels to produce an audible channel. There are several blending modes. -// 1) Simple -// Unmatched channels are silenced. -// 2) Planar Blending -// Channels are blended based on a set of planes that each speaker emits audio from. -// -// Rectangular / Planar Blending -// ----------------------------- -// In this mode, channel positions are associated with a set of planes where the channel conceptually emits audio from. An example is the front/left speaker. -// This speaker is positioned to the front of the listener, so you can think of it as emitting audio from the front plane. It is also positioned to the left -// of the listener so you can think of it as also emitting audio from the left plane. Now consider the (unrealistic) situation where the input channel map -// contains only the front/left channel position, but the output channel map contains both the front/left and front/center channel. When deciding on the audio -// data to send to the front/center speaker (which has no 1:1 mapping with an input channel) we need to use some logic based on our available input channel -// positions. -// -// As mentioned earlier, our front/left speaker is, conceptually speaking, emitting audio from the front _and_ the left planes. Similarly, the front/center -// speaker is emitting audio from _only_ the front plane. What these two channels have in common is that they are both emitting audio from the front plane. -// Thus, it makes sense that the front/center speaker should receive some contribution from the front/left channel. How much contribution depends on their -// planar relationship (thus the name of this blending technique). -// -// Because the front/left channel is emitting audio from two planes (front and left), you can think of it as though it's willing to dedicate 50% of it's total -// volume to each of it's planes (a channel position emitting from 1 plane would be willing to given 100% of it's total volume to that plane, and a channel -// position emitting from 3 planes would be willing to given 33% of it's total volume to each plane). Similarly, the front/center speaker is emitting audio -// from only one plane so you can think of it as though it's willing to _take_ 100% of it's volume from front plane emissions. Now, since the front/left -// channel is willing to _give_ 50% of it's total volume to the front plane, and the front/center speaker is willing to _take_ 100% of it's total volume -// from the front, you can imagine that 50% of the front/left speaker will be given to the front/center speaker. -// -// Usage -// ----- -// To use the channel router you need to specify three things: -// 1) The input channel count and channel map -// 2) The output channel count and channel map -// 3) The mixing mode to use in the case where a 1:1 mapping is unavailable -// -// Note that input and output data is always deinterleaved 32-bit floating point. -// -// Initialize the channel router with mal_channel_router_init(). You will need to pass in a config object which specifies the input and output configuration, -// mixing mode and a callback for sending data to the router. This callback will be called when input data needs to be sent to the router for processing. Note -// that the mixing mode is only used when a 1:1 mapping is unavailable. This includes the custom weights mode. -// -// Read data from the channel router with mal_channel_router_read_deinterleaved(). Output data is always 32-bit floating point. -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -// Initializes a channel router where it is assumed that the input data is non-interleaved. -mal_result mal_channel_router_init(const mal_channel_router_config* pConfig, mal_channel_router* pRouter); - -// Reads data from the channel router as deinterleaved channels. -mal_uint64 mal_channel_router_read_deinterleaved(mal_channel_router* pRouter, mal_uint64 frameCount, void** ppSamplesOut, void* pUserData); - -// Helper for initializing a channel router config. -mal_channel_router_config mal_channel_router_config_init(mal_uint32 channelsIn, const mal_channel channelMapIn[MAL_MAX_CHANNELS], mal_uint32 channelsOut, const mal_channel channelMapOut[MAL_MAX_CHANNELS], mal_channel_mix_mode mixingMode, mal_channel_router_read_deinterleaved_proc onRead, void* pUserData); - - -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Sample Rate Conversion -// ====================== -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -// Initializes a sample rate conversion object. -mal_result mal_src_init(const mal_src_config* pConfig, mal_src* pSRC); - -// Dynamically adjusts the input sample rate. -// -// DEPRECATED. Use mal_src_set_sample_rate() instead. -mal_result mal_src_set_input_sample_rate(mal_src* pSRC, mal_uint32 sampleRateIn); - -// Dynamically adjusts the output sample rate. -// -// This is useful for dynamically adjust pitch. Keep in mind, however, that this will speed up or slow down the sound. If this -// is not acceptable you will need to use your own algorithm. -// -// DEPRECATED. Use mal_src_set_sample_rate() instead. -mal_result mal_src_set_output_sample_rate(mal_src* pSRC, mal_uint32 sampleRateOut); - -// Dynamically adjusts the sample rate. -// -// This is useful for dynamically adjust pitch. Keep in mind, however, that this will speed up or slow down the sound. If this -// is not acceptable you will need to use your own algorithm. -mal_result mal_src_set_sample_rate(mal_src* pSRC, mal_uint32 sampleRateIn, mal_uint32 sampleRateOut); - -// Reads a number of frames. -// -// Returns the number of frames actually read. -mal_uint64 mal_src_read_deinterleaved(mal_src* pSRC, mal_uint64 frameCount, void** ppSamplesOut, void* pUserData); - - -// Helper for creating a sample rate conversion config. -mal_src_config mal_src_config_init_new(void); -mal_src_config mal_src_config_init(mal_uint32 sampleRateIn, mal_uint32 sampleRateOut, mal_uint32 channels, mal_src_read_deinterleaved_proc onReadDeinterleaved, void* pUserData); - - -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// DSP -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -// Initializes a DSP object. -mal_result mal_dsp_init(const mal_dsp_config* pConfig, mal_dsp* pDSP); - -// Dynamically adjusts the input sample rate. -// -// This will fail is the DSP was not initialized with allowDynamicSampleRate. -// -// DEPRECATED. Use mal_dsp_set_sample_rate() instead. -mal_result mal_dsp_set_input_sample_rate(mal_dsp* pDSP, mal_uint32 sampleRateOut); - -// Dynamically adjusts the output sample rate. -// -// This is useful for dynamically adjust pitch. Keep in mind, however, that this will speed up or slow down the sound. If this -// is not acceptable you will need to use your own algorithm. -// -// This will fail is the DSP was not initialized with allowDynamicSampleRate. -// -// DEPRECATED. Use mal_dsp_set_sample_rate() instead. -mal_result mal_dsp_set_output_sample_rate(mal_dsp* pDSP, mal_uint32 sampleRateOut); - -// Dynamically adjusts the output sample rate. -// -// This is useful for dynamically adjust pitch. Keep in mind, however, that this will speed up or slow down the sound. If this -// is not acceptable you will need to use your own algorithm. -// -// This will fail is the DSP was not initialized with allowDynamicSampleRate. -mal_result mal_dsp_set_sample_rate(mal_dsp* pDSP, mal_uint32 sampleRateIn, mal_uint32 sampleRateOut); - - -// Reads a number of frames and runs them through the DSP processor. -mal_uint64 mal_dsp_read(mal_dsp* pDSP, mal_uint64 frameCount, void* pFramesOut, void* pUserData); - -// Helper for initializing a mal_dsp_config object. -mal_dsp_config mal_dsp_config_init_new(void); -mal_dsp_config mal_dsp_config_init(mal_format formatIn, mal_uint32 channelsIn, mal_uint32 sampleRateIn, mal_format formatOut, mal_uint32 channelsOut, mal_uint32 sampleRateOut, mal_dsp_read_proc onRead, void* pUserData); -mal_dsp_config mal_dsp_config_init_ex(mal_format formatIn, mal_uint32 channelsIn, mal_uint32 sampleRateIn, mal_channel channelMapIn[MAL_MAX_CHANNELS], mal_format formatOut, mal_uint32 channelsOut, mal_uint32 sampleRateOut, mal_channel channelMapOut[MAL_MAX_CHANNELS], mal_dsp_read_proc onRead, void* pUserData); - - -// High-level helper for doing a full format conversion in one go. Returns the number of output frames. Call this with pOut set to NULL to -// determine the required size of the output buffer. -// -// A return value of 0 indicates an error. -// -// This function is useful for one-off bulk conversions, but if you're streaming data you should use the DSP APIs instead. -mal_uint64 mal_convert_frames(void* pOut, mal_format formatOut, mal_uint32 channelsOut, mal_uint32 sampleRateOut, const void* pIn, mal_format formatIn, mal_uint32 channelsIn, mal_uint32 sampleRateIn, mal_uint64 frameCountIn); -mal_uint64 mal_convert_frames_ex(void* pOut, mal_format formatOut, mal_uint32 channelsOut, mal_uint32 sampleRateOut, mal_channel channelMapOut[MAL_MAX_CHANNELS], const void* pIn, mal_format formatIn, mal_uint32 channelsIn, mal_uint32 sampleRateIn, mal_channel channelMapIn[MAL_MAX_CHANNELS], mal_uint64 frameCountIn); - - - -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Miscellaneous Helpers -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -// malloc(). Calls MAL_MALLOC(). -void* mal_malloc(size_t sz); - -// realloc(). Calls MAL_REALLOC(). -void* mal_realloc(void* p, size_t sz); - -// free(). Calls MAL_FREE(). -void mal_free(void* p); - -// Performs an aligned malloc, with the assumption that the alignment is a power of 2. -void* mal_aligned_malloc(size_t sz, size_t alignment); - -// Free's an aligned malloc'd buffer. -void mal_aligned_free(void* p); - -// Retrieves a friendly name for a format. -const char* mal_get_format_name(mal_format format); - -// Blends two frames in floating point format. -void mal_blend_f32(float* pOut, float* pInA, float* pInB, float factor, mal_uint32 channels); - -// Retrieves the size of a sample in bytes for the given format. -// -// This API is efficient and is implemented using a lookup table. -// -// Thread Safety: SAFE -// This is API is pure. -mal_uint32 mal_get_bytes_per_sample(mal_format format); -static MAL_INLINE mal_uint32 mal_get_bytes_per_frame(mal_format format, mal_uint32 channels) { return mal_get_bytes_per_sample(format) * channels; } - - -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Format Conversion -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -void mal_pcm_u8_to_s16(void* pOut, const void* pIn, mal_uint64 count, mal_dither_mode ditherMode); -void mal_pcm_u8_to_s24(void* pOut, const void* pIn, mal_uint64 count, mal_dither_mode ditherMode); -void mal_pcm_u8_to_s32(void* pOut, const void* pIn, mal_uint64 count, mal_dither_mode ditherMode); -void mal_pcm_u8_to_f32(void* pOut, const void* pIn, mal_uint64 count, mal_dither_mode ditherMode); -void mal_pcm_s16_to_u8(void* pOut, const void* pIn, mal_uint64 count, mal_dither_mode ditherMode); -void mal_pcm_s16_to_s24(void* pOut, const void* pIn, mal_uint64 count, mal_dither_mode ditherMode); -void mal_pcm_s16_to_s32(void* pOut, const void* pIn, mal_uint64 count, mal_dither_mode ditherMode); -void mal_pcm_s16_to_f32(void* pOut, const void* pIn, mal_uint64 count, mal_dither_mode ditherMode); -void mal_pcm_s24_to_u8(void* pOut, const void* pIn, mal_uint64 count, mal_dither_mode ditherMode); -void mal_pcm_s24_to_s16(void* pOut, const void* pIn, mal_uint64 count, mal_dither_mode ditherMode); -void mal_pcm_s24_to_s32(void* pOut, const void* pIn, mal_uint64 count, mal_dither_mode ditherMode); -void mal_pcm_s24_to_f32(void* pOut, const void* pIn, mal_uint64 count, mal_dither_mode ditherMode); -void mal_pcm_s32_to_u8(void* pOut, const void* pIn, mal_uint64 count, mal_dither_mode ditherMode); -void mal_pcm_s32_to_s16(void* pOut, const void* pIn, mal_uint64 count, mal_dither_mode ditherMode); -void mal_pcm_s32_to_s24(void* pOut, const void* pIn, mal_uint64 count, mal_dither_mode ditherMode); -void mal_pcm_s32_to_f32(void* pOut, const void* pIn, mal_uint64 count, mal_dither_mode ditherMode); -void mal_pcm_f32_to_u8(void* pOut, const void* pIn, mal_uint64 count, mal_dither_mode ditherMode); -void mal_pcm_f32_to_s16(void* pOut, const void* pIn, mal_uint64 count, mal_dither_mode ditherMode); -void mal_pcm_f32_to_s24(void* pOut, const void* pIn, mal_uint64 count, mal_dither_mode ditherMode); -void mal_pcm_f32_to_s32(void* pOut, const void* pIn, mal_uint64 count, mal_dither_mode ditherMode); -void mal_pcm_convert(void* pOut, mal_format formatOut, const void* pIn, mal_format formatIn, mal_uint64 sampleCount, mal_dither_mode ditherMode); - -// Deinterleaves an interleaved buffer. -void mal_deinterleave_pcm_frames(mal_format format, mal_uint32 channels, mal_uint64 frameCount, const void* pInterleavedPCMFrames, void** ppDeinterleavedPCMFrames); - -// Interleaves a group of deinterleaved buffers. -void mal_interleave_pcm_frames(mal_format format, mal_uint32 channels, mal_uint64 frameCount, const void** ppDeinterleavedPCMFrames, void* pInterleavedPCMFrames); - - -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// DEVICE I/O -// ========== -// -// This section contains the APIs for device playback and capture. Here is where you'll find mal_device_init(), etc. -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -#ifndef MAL_NO_DEVICE_IO -// Some backends are only supported on certain platforms. -#if defined(MAL_WIN32) - #define MAL_SUPPORT_WASAPI - #if defined(MAL_WIN32_DESKTOP) // DirectSound and WinMM backends are only supported on desktop's. - #define MAL_SUPPORT_DSOUND - #define MAL_SUPPORT_WINMM - #define MAL_SUPPORT_JACK // JACK is technically supported on Windows, but I don't know how many people use it in practice... - #endif -#endif -#if defined(MAL_UNIX) - #if defined(MAL_LINUX) - #if !defined(MAL_ANDROID) // ALSA is not supported on Android. - #define MAL_SUPPORT_ALSA - #endif - #endif - #if !defined(MAL_BSD) && !defined(MAL_ANDROID) && !defined(MAL_EMSCRIPTEN) - #define MAL_SUPPORT_PULSEAUDIO - #define MAL_SUPPORT_JACK - #endif - #if defined(MAL_ANDROID) - #define MAL_SUPPORT_AAUDIO - #define MAL_SUPPORT_OPENSL - #endif - #if defined(__OpenBSD__) // <-- Change this to "#if defined(MAL_BSD)" to enable sndio on all BSD flavors. - #define MAL_SUPPORT_SNDIO // sndio is only supported on OpenBSD for now. May be expanded later if there's demand. - #endif - #if defined(__NetBSD__) || defined(__OpenBSD__) - #define MAL_SUPPORT_AUDIO4 // Only support audio(4) on platforms with known support. - #endif - #if defined(__FreeBSD__) || defined(__DragonFly__) - #define MAL_SUPPORT_OSS // Only support OSS on specific platforms with known support. - #endif -#endif -#if defined(MAL_APPLE) - #define MAL_SUPPORT_COREAUDIO -#endif -#if defined(MAL_EMSCRIPTEN) - #define MAL_SUPPORT_WEBAUDIO -#endif - -// Explicitly disable OpenAL and Null backends for Emscripten because they both use a background thread which is not properly supported right now. -#if !defined(MAL_EMSCRIPTEN) -#define MAL_SUPPORT_SDL -#define MAL_SUPPORT_OPENAL -#define MAL_SUPPORT_NULL -#endif - - -#if !defined(MAL_NO_WASAPI) && defined(MAL_SUPPORT_WASAPI) - #define MAL_ENABLE_WASAPI -#endif -#if !defined(MAL_NO_DSOUND) && defined(MAL_SUPPORT_DSOUND) - #define MAL_ENABLE_DSOUND -#endif -#if !defined(MAL_NO_WINMM) && defined(MAL_SUPPORT_WINMM) - #define MAL_ENABLE_WINMM -#endif -#if !defined(MAL_NO_ALSA) && defined(MAL_SUPPORT_ALSA) - #define MAL_ENABLE_ALSA -#endif -#if !defined(MAL_NO_PULSEAUDIO) && defined(MAL_SUPPORT_PULSEAUDIO) - #define MAL_ENABLE_PULSEAUDIO -#endif -#if !defined(MAL_NO_JACK) && defined(MAL_SUPPORT_JACK) - #define MAL_ENABLE_JACK -#endif -#if !defined(MAL_NO_COREAUDIO) && defined(MAL_SUPPORT_COREAUDIO) - #define MAL_ENABLE_COREAUDIO -#endif -#if !defined(MAL_NO_SNDIO) && defined(MAL_SUPPORT_SNDIO) - #define MAL_ENABLE_SNDIO -#endif -#if !defined(MAL_NO_AUDIO4) && defined(MAL_SUPPORT_AUDIO4) - #define MAL_ENABLE_AUDIO4 -#endif -#if !defined(MAL_NO_OSS) && defined(MAL_SUPPORT_OSS) - #define MAL_ENABLE_OSS -#endif -#if !defined(MAL_NO_AAUDIO) && defined(MAL_SUPPORT_AAUDIO) - #define MAL_ENABLE_AAUDIO -#endif -#if !defined(MAL_NO_OPENSL) && defined(MAL_SUPPORT_OPENSL) - #define MAL_ENABLE_OPENSL -#endif -#if !defined(MAL_NO_WEBAUDIO) && defined(MAL_SUPPORT_WEBAUDIO) - #define MAL_ENABLE_WEBAUDIO -#endif -#if !defined(MAL_NO_OPENAL) && defined(MAL_SUPPORT_OPENAL) - #define MAL_ENABLE_OPENAL -#endif -#if !defined(MAL_NO_SDL) && defined(MAL_SUPPORT_SDL) - #define MAL_ENABLE_SDL -#endif -#if !defined(MAL_NO_NULL) && defined(MAL_SUPPORT_NULL) - #define MAL_ENABLE_NULL -#endif - -#ifdef MAL_SUPPORT_WASAPI -// We need a IMMNotificationClient object for WASAPI. -typedef struct -{ - void* lpVtbl; - mal_uint32 counter; - mal_device* pDevice; -} mal_IMMNotificationClient; -#endif - - -typedef enum -{ - mal_backend_null, - mal_backend_wasapi, - mal_backend_dsound, - mal_backend_winmm, - mal_backend_alsa, - mal_backend_pulseaudio, - mal_backend_jack, - mal_backend_coreaudio, - mal_backend_sndio, - mal_backend_audio4, - mal_backend_oss, - mal_backend_aaudio, - mal_backend_opensl, - mal_backend_webaudio, - mal_backend_openal, - mal_backend_sdl -} mal_backend; - -// Thread priorties should be ordered such that the default priority of the worker thread is 0. -typedef enum -{ - mal_thread_priority_idle = -5, - mal_thread_priority_lowest = -4, - mal_thread_priority_low = -3, - mal_thread_priority_normal = -2, - mal_thread_priority_high = -1, - mal_thread_priority_highest = 0, - mal_thread_priority_realtime = 1, - mal_thread_priority_default = 0 -} mal_thread_priority; - -typedef struct -{ - mal_context* pContext; - - union - { -#ifdef MAL_WIN32 - struct - { - /*HANDLE*/ mal_handle hThread; - } win32; -#endif -#ifdef MAL_POSIX - struct - { - pthread_t thread; - } posix; -#endif - int _unused; - }; -} mal_thread; - -typedef struct -{ - mal_context* pContext; - - union - { -#ifdef MAL_WIN32 - struct - { - /*HANDLE*/ mal_handle hMutex; - } win32; -#endif -#ifdef MAL_POSIX - struct - { - pthread_mutex_t mutex; - } posix; -#endif - int _unused; - }; -} mal_mutex; - -typedef struct -{ - mal_context* pContext; - - union - { -#ifdef MAL_WIN32 - struct - { - /*HANDLE*/ mal_handle hEvent; - } win32; -#endif -#ifdef MAL_POSIX - struct - { - pthread_mutex_t mutex; - pthread_cond_t condition; - mal_uint32 value; - } posix; -#endif - int _unused; - }; -} mal_event; - - -#define MAL_MAX_PERIODS_DSOUND 4 -#define MAL_MAX_PERIODS_OPENAL 4 - -typedef void (* mal_log_proc) (mal_context* pContext, mal_device* pDevice, const char* message); -typedef void (* mal_recv_proc)(mal_device* pDevice, mal_uint32 frameCount, const void* pSamples); -typedef mal_uint32 (* mal_send_proc)(mal_device* pDevice, mal_uint32 frameCount, void* pSamples); -typedef void (* mal_stop_proc)(mal_device* pDevice); - -typedef enum -{ - mal_device_type_playback, - mal_device_type_capture -} mal_device_type; - -typedef enum -{ - mal_share_mode_shared = 0, - mal_share_mode_exclusive, -} mal_share_mode; - -typedef union -{ -#ifdef MAL_SUPPORT_WASAPI - wchar_t wasapi[64]; // WASAPI uses a wchar_t string for identification. -#endif -#ifdef MAL_SUPPORT_DSOUND - mal_uint8 dsound[16]; // DirectSound uses a GUID for identification. -#endif -#ifdef MAL_SUPPORT_WINMM - /*UINT_PTR*/ mal_uint32 winmm; // When creating a device, WinMM expects a Win32 UINT_PTR for device identification. In practice it's actually just a UINT. -#endif -#ifdef MAL_SUPPORT_ALSA - char alsa[256]; // ALSA uses a name string for identification. -#endif -#ifdef MAL_SUPPORT_PULSEAUDIO - char pulse[256]; // PulseAudio uses a name string for identification. -#endif -#ifdef MAL_SUPPORT_JACK - int jack; // JACK always uses default devices. -#endif -#ifdef MAL_SUPPORT_COREAUDIO - char coreaudio[256]; // Core Audio uses a string for identification. -#endif -#ifdef MAL_SUPPORT_SNDIO - char sndio[256]; // "snd/0", etc. -#endif -#ifdef MAL_SUPPORT_AUDIO4 - char audio4[256]; // "/dev/audio", etc. -#endif -#ifdef MAL_SUPPORT_OSS - char oss[64]; // "dev/dsp0", etc. "dev/dsp" for the default device. -#endif -#ifdef MAL_SUPPORT_AAUDIO - mal_int32 aaudio; // AAudio uses a 32-bit integer for identification. -#endif -#ifdef MAL_SUPPORT_OPENSL - mal_uint32 opensl; // OpenSL|ES uses a 32-bit unsigned integer for identification. -#endif -#ifdef MAL_SUPPORT_WEBAUDIO - char webaudio[32]; // Web Audio always uses default devices for now, but if this changes it'll be a GUID. -#endif -#ifdef MAL_SUPPORT_OPENAL - char openal[256]; // OpenAL seems to use human-readable device names as the ID. -#endif -#ifdef MAL_SUPPORT_SDL - int sdl; // SDL devices are identified with an index. -#endif -#ifdef MAL_SUPPORT_NULL - int nullbackend; // The null backend uses an integer for device IDs. -#endif -} mal_device_id; - -typedef struct -{ - // Basic info. This is the only information guaranteed to be filled in during device enumeration. - mal_device_id id; - char name[256]; - - // Detailed info. As much of this is filled as possible with mal_context_get_device_info(). Note that you are allowed to initialize - // a device with settings outside of this range, but it just means the data will be converted using mini_al's data conversion - // pipeline before sending the data to/from the device. Most programs will need to not worry about these values, but it's provided - // here mainly for informational purposes or in the rare case that someone might find it useful. - // - // These will be set to 0 when returned by mal_context_enumerate_devices() or mal_context_get_devices(). - mal_uint32 formatCount; - mal_format formats[mal_format_count]; - mal_uint32 minChannels; - mal_uint32 maxChannels; - mal_uint32 minSampleRate; - mal_uint32 maxSampleRate; -} mal_device_info; - -typedef struct -{ - union - { - mal_int64 counter; - double counterD; - }; -} mal_timer; - -typedef struct -{ - mal_format format; - mal_uint32 channels; - mal_uint32 sampleRate; - mal_channel channelMap[MAL_MAX_CHANNELS]; - mal_uint32 bufferSizeInFrames; - mal_uint32 bufferSizeInMilliseconds; - mal_uint32 periods; - mal_share_mode shareMode; - mal_performance_profile performanceProfile; - mal_recv_proc onRecvCallback; - mal_send_proc onSendCallback; - mal_stop_proc onStopCallback; - - struct - { - mal_bool32 noMMap; // Disables MMap mode. - } alsa; - - struct - { - const char* pStreamName; - } pulse; -} mal_device_config; - -typedef struct -{ - mal_log_proc onLog; - mal_thread_priority threadPriority; - - struct - { - mal_bool32 useVerboseDeviceEnumeration; - } alsa; - - struct - { - const char* pApplicationName; - const char* pServerName; - mal_bool32 tryAutoSpawn; // Enables autospawning of the PulseAudio daemon if necessary. - } pulse; - - struct - { - const char* pClientName; - mal_bool32 tryStartServer; - } jack; -} mal_context_config; - -typedef mal_bool32 (* mal_enum_devices_callback_proc)(mal_context* pContext, mal_device_type type, const mal_device_info* pInfo, void* pUserData); - -struct mal_context -{ - mal_backend backend; // DirectSound, ALSA, etc. - mal_context_config config; - mal_mutex deviceEnumLock; // Used to make mal_context_get_devices() thread safe. - mal_mutex deviceInfoLock; // Used to make mal_context_get_device_info() thread safe. - mal_uint32 deviceInfoCapacity; // Total capacity of pDeviceInfos. - mal_uint32 playbackDeviceInfoCount; - mal_uint32 captureDeviceInfoCount; - mal_device_info* pDeviceInfos; // Playback devices first, then capture. - mal_bool32 isBackendAsynchronous : 1; // Set when the context is initialized. Set to 1 for asynchronous backends such as Core Audio and JACK. Do not modify. - - mal_result (* onUninit )(mal_context* pContext); - mal_bool32 (* onDeviceIDEqual )(mal_context* pContext, const mal_device_id* pID0, const mal_device_id* pID1); - mal_result (* onEnumDevices )(mal_context* pContext, mal_enum_devices_callback_proc callback, void* pUserData); // Return false from the callback to stop enumeration. - mal_result (* onGetDeviceInfo )(mal_context* pContext, mal_device_type type, const mal_device_id* pDeviceID, mal_share_mode shareMode, mal_device_info* pDeviceInfo); - mal_result (* onDeviceInit )(mal_context* pContext, mal_device_type type, const mal_device_id* pDeviceID, const mal_device_config* pConfig, mal_device* pDevice); - void (* onDeviceUninit )(mal_device* pDevice); - mal_result (* onDeviceReinit )(mal_device* pDevice); - mal_result (* onDeviceStart )(mal_device* pDevice); - mal_result (* onDeviceStop )(mal_device* pDevice); - mal_result (* onDeviceBreakMainLoop)(mal_device* pDevice); - mal_result (* onDeviceMainLoop )(mal_device* pDevice); - - union - { -#ifdef MAL_SUPPORT_WASAPI - struct - { - int _unused; - } wasapi; -#endif -#ifdef MAL_SUPPORT_DSOUND - struct - { - /*HMODULE*/ mal_handle hDSoundDLL; - mal_proc DirectSoundCreate; - mal_proc DirectSoundEnumerateA; - mal_proc DirectSoundCaptureCreate; - mal_proc DirectSoundCaptureEnumerateA; - } dsound; -#endif -#ifdef MAL_SUPPORT_WINMM - struct - { - /*HMODULE*/ mal_handle hWinMM; - mal_proc waveOutGetNumDevs; - mal_proc waveOutGetDevCapsA; - mal_proc waveOutOpen; - mal_proc waveOutClose; - mal_proc waveOutPrepareHeader; - mal_proc waveOutUnprepareHeader; - mal_proc waveOutWrite; - mal_proc waveOutReset; - mal_proc waveInGetNumDevs; - mal_proc waveInGetDevCapsA; - mal_proc waveInOpen; - mal_proc waveInClose; - mal_proc waveInPrepareHeader; - mal_proc waveInUnprepareHeader; - mal_proc waveInAddBuffer; - mal_proc waveInStart; - mal_proc waveInReset; - } winmm; -#endif -#ifdef MAL_SUPPORT_ALSA - struct - { - mal_handle asoundSO; - mal_proc snd_pcm_open; - mal_proc snd_pcm_close; - mal_proc snd_pcm_hw_params_sizeof; - mal_proc snd_pcm_hw_params_any; - mal_proc snd_pcm_hw_params_set_format; - mal_proc snd_pcm_hw_params_set_format_first; - mal_proc snd_pcm_hw_params_get_format_mask; - mal_proc snd_pcm_hw_params_set_channels_near; - mal_proc snd_pcm_hw_params_set_rate_resample; - mal_proc snd_pcm_hw_params_set_rate_near; - mal_proc snd_pcm_hw_params_set_buffer_size_near; - mal_proc snd_pcm_hw_params_set_periods_near; - mal_proc snd_pcm_hw_params_set_access; - mal_proc snd_pcm_hw_params_get_format; - mal_proc snd_pcm_hw_params_get_channels; - mal_proc snd_pcm_hw_params_get_channels_min; - mal_proc snd_pcm_hw_params_get_channels_max; - mal_proc snd_pcm_hw_params_get_rate; - mal_proc snd_pcm_hw_params_get_rate_min; - mal_proc snd_pcm_hw_params_get_rate_max; - mal_proc snd_pcm_hw_params_get_buffer_size; - mal_proc snd_pcm_hw_params_get_periods; - mal_proc snd_pcm_hw_params_get_access; - mal_proc snd_pcm_hw_params; - mal_proc snd_pcm_sw_params_sizeof; - mal_proc snd_pcm_sw_params_current; - mal_proc snd_pcm_sw_params_set_avail_min; - mal_proc snd_pcm_sw_params_set_start_threshold; - mal_proc snd_pcm_sw_params; - mal_proc snd_pcm_format_mask_sizeof; - mal_proc snd_pcm_format_mask_test; - mal_proc snd_pcm_get_chmap; - mal_proc snd_pcm_prepare; - mal_proc snd_pcm_start; - mal_proc snd_pcm_drop; - mal_proc snd_device_name_hint; - mal_proc snd_device_name_get_hint; - mal_proc snd_card_get_index; - mal_proc snd_device_name_free_hint; - mal_proc snd_pcm_mmap_begin; - mal_proc snd_pcm_mmap_commit; - mal_proc snd_pcm_recover; - mal_proc snd_pcm_readi; - mal_proc snd_pcm_writei; - mal_proc snd_pcm_avail; - mal_proc snd_pcm_avail_update; - mal_proc snd_pcm_wait; - mal_proc snd_pcm_info; - mal_proc snd_pcm_info_sizeof; - mal_proc snd_pcm_info_get_name; - mal_proc snd_config_update_free_global; - - mal_mutex internalDeviceEnumLock; - } alsa; -#endif -#ifdef MAL_SUPPORT_PULSEAUDIO - struct - { - mal_handle pulseSO; - mal_proc pa_mainloop_new; - mal_proc pa_mainloop_free; - mal_proc pa_mainloop_get_api; - mal_proc pa_mainloop_iterate; - mal_proc pa_mainloop_wakeup; - mal_proc pa_context_new; - mal_proc pa_context_unref; - mal_proc pa_context_connect; - mal_proc pa_context_disconnect; - mal_proc pa_context_set_state_callback; - mal_proc pa_context_get_state; - mal_proc pa_context_get_sink_info_list; - mal_proc pa_context_get_source_info_list; - mal_proc pa_context_get_sink_info_by_name; - mal_proc pa_context_get_source_info_by_name; - mal_proc pa_operation_unref; - mal_proc pa_operation_get_state; - mal_proc pa_channel_map_init_extend; - mal_proc pa_channel_map_valid; - mal_proc pa_channel_map_compatible; - mal_proc pa_stream_new; - mal_proc pa_stream_unref; - mal_proc pa_stream_connect_playback; - mal_proc pa_stream_connect_record; - mal_proc pa_stream_disconnect; - mal_proc pa_stream_get_state; - mal_proc pa_stream_get_sample_spec; - mal_proc pa_stream_get_channel_map; - mal_proc pa_stream_get_buffer_attr; - mal_proc pa_stream_set_buffer_attr; - mal_proc pa_stream_get_device_name; - mal_proc pa_stream_set_write_callback; - mal_proc pa_stream_set_read_callback; - mal_proc pa_stream_flush; - mal_proc pa_stream_drain; - mal_proc pa_stream_cork; - mal_proc pa_stream_trigger; - mal_proc pa_stream_begin_write; - mal_proc pa_stream_write; - mal_proc pa_stream_peek; - mal_proc pa_stream_drop; - } pulse; -#endif -#ifdef MAL_SUPPORT_JACK - struct - { - mal_handle jackSO; - mal_proc jack_client_open; - mal_proc jack_client_close; - mal_proc jack_client_name_size; - mal_proc jack_set_process_callback; - mal_proc jack_set_buffer_size_callback; - mal_proc jack_on_shutdown; - mal_proc jack_get_sample_rate; - mal_proc jack_get_buffer_size; - mal_proc jack_get_ports; - mal_proc jack_activate; - mal_proc jack_deactivate; - mal_proc jack_connect; - mal_proc jack_port_register; - mal_proc jack_port_name; - mal_proc jack_port_get_buffer; - mal_proc jack_free; - } jack; -#endif -#ifdef MAL_SUPPORT_COREAUDIO - struct - { - mal_handle hCoreFoundation; - mal_proc CFStringGetCString; - - mal_handle hCoreAudio; - mal_proc AudioObjectGetPropertyData; - mal_proc AudioObjectGetPropertyDataSize; - mal_proc AudioObjectSetPropertyData; - mal_proc AudioObjectAddPropertyListener; - - mal_handle hAudioUnit; // Could possibly be set to AudioToolbox on later versions of macOS. - mal_proc AudioComponentFindNext; - mal_proc AudioComponentInstanceDispose; - mal_proc AudioComponentInstanceNew; - mal_proc AudioOutputUnitStart; - mal_proc AudioOutputUnitStop; - mal_proc AudioUnitAddPropertyListener; - mal_proc AudioUnitGetPropertyInfo; - mal_proc AudioUnitGetProperty; - mal_proc AudioUnitSetProperty; - mal_proc AudioUnitInitialize; - mal_proc AudioUnitRender; - } coreaudio; -#endif -#ifdef MAL_SUPPORT_SNDIO - struct - { - mal_handle sndioSO; - mal_proc sio_open; - mal_proc sio_close; - mal_proc sio_setpar; - mal_proc sio_getpar; - mal_proc sio_getcap; - mal_proc sio_start; - mal_proc sio_stop; - mal_proc sio_read; - mal_proc sio_write; - mal_proc sio_onmove; - mal_proc sio_nfds; - mal_proc sio_pollfd; - mal_proc sio_revents; - mal_proc sio_eof; - mal_proc sio_setvol; - mal_proc sio_onvol; - mal_proc sio_initpar; - } sndio; -#endif -#ifdef MAL_SUPPORT_AUDIO4 - struct - { - int _unused; - } audio4; -#endif -#ifdef MAL_SUPPORT_OSS - struct - { - int versionMajor; - int versionMinor; - } oss; -#endif -#ifdef MAL_SUPPORT_AAUDIO - struct - { - mal_handle hAAudio; /* libaaudio.so */ - mal_proc AAudio_createStreamBuilder; - mal_proc AAudioStreamBuilder_delete; - mal_proc AAudioStreamBuilder_setDeviceId; - mal_proc AAudioStreamBuilder_setDirection; - mal_proc AAudioStreamBuilder_setSharingMode; - mal_proc AAudioStreamBuilder_setFormat; - mal_proc AAudioStreamBuilder_setChannelCount; - mal_proc AAudioStreamBuilder_setSampleRate; - mal_proc AAudioStreamBuilder_setBufferCapacityInFrames; - mal_proc AAudioStreamBuilder_setFramesPerDataCallback; - mal_proc AAudioStreamBuilder_setDataCallback; - mal_proc AAudioStreamBuilder_setPerformanceMode; - mal_proc AAudioStreamBuilder_openStream; - mal_proc AAudioStream_close; - mal_proc AAudioStream_getState; - mal_proc AAudioStream_waitForStateChange; - mal_proc AAudioStream_getFormat; - mal_proc AAudioStream_getChannelCount; - mal_proc AAudioStream_getSampleRate; - mal_proc AAudioStream_getBufferCapacityInFrames; - mal_proc AAudioStream_getFramesPerDataCallback; - mal_proc AAudioStream_getFramesPerBurst; - mal_proc AAudioStream_requestStart; - mal_proc AAudioStream_requestStop; - } aaudio; -#endif -#ifdef MAL_SUPPORT_OPENSL - struct - { - int _unused; - } opensl; -#endif -#ifdef MAL_SUPPORT_WEBAUDIO - struct - { - int _unused; - } webaudio; -#endif -#ifdef MAL_SUPPORT_OPENAL - struct - { - /*HMODULE*/ mal_handle hOpenAL; // OpenAL32.dll, etc. - mal_proc alcCreateContext; - mal_proc alcMakeContextCurrent; - mal_proc alcProcessContext; - mal_proc alcSuspendContext; - mal_proc alcDestroyContext; - mal_proc alcGetCurrentContext; - mal_proc alcGetContextsDevice; - mal_proc alcOpenDevice; - mal_proc alcCloseDevice; - mal_proc alcGetError; - mal_proc alcIsExtensionPresent; - mal_proc alcGetProcAddress; - mal_proc alcGetEnumValue; - mal_proc alcGetString; - mal_proc alcGetIntegerv; - mal_proc alcCaptureOpenDevice; - mal_proc alcCaptureCloseDevice; - mal_proc alcCaptureStart; - mal_proc alcCaptureStop; - mal_proc alcCaptureSamples; - mal_proc alEnable; - mal_proc alDisable; - mal_proc alIsEnabled; - mal_proc alGetString; - mal_proc alGetBooleanv; - mal_proc alGetIntegerv; - mal_proc alGetFloatv; - mal_proc alGetDoublev; - mal_proc alGetBoolean; - mal_proc alGetInteger; - mal_proc alGetFloat; - mal_proc alGetDouble; - mal_proc alGetError; - mal_proc alIsExtensionPresent; - mal_proc alGetProcAddress; - mal_proc alGetEnumValue; - mal_proc alGenSources; - mal_proc alDeleteSources; - mal_proc alIsSource; - mal_proc alSourcef; - mal_proc alSource3f; - mal_proc alSourcefv; - mal_proc alSourcei; - mal_proc alSource3i; - mal_proc alSourceiv; - mal_proc alGetSourcef; - mal_proc alGetSource3f; - mal_proc alGetSourcefv; - mal_proc alGetSourcei; - mal_proc alGetSource3i; - mal_proc alGetSourceiv; - mal_proc alSourcePlayv; - mal_proc alSourceStopv; - mal_proc alSourceRewindv; - mal_proc alSourcePausev; - mal_proc alSourcePlay; - mal_proc alSourceStop; - mal_proc alSourceRewind; - mal_proc alSourcePause; - mal_proc alSourceQueueBuffers; - mal_proc alSourceUnqueueBuffers; - mal_proc alGenBuffers; - mal_proc alDeleteBuffers; - mal_proc alIsBuffer; - mal_proc alBufferData; - mal_proc alBufferf; - mal_proc alBuffer3f; - mal_proc alBufferfv; - mal_proc alBufferi; - mal_proc alBuffer3i; - mal_proc alBufferiv; - mal_proc alGetBufferf; - mal_proc alGetBuffer3f; - mal_proc alGetBufferfv; - mal_proc alGetBufferi; - mal_proc alGetBuffer3i; - mal_proc alGetBufferiv; - - mal_bool32 isEnumerationSupported : 1; - mal_bool32 isFloat32Supported : 1; - mal_bool32 isMCFormatsSupported : 1; - } openal; -#endif -#ifdef MAL_SUPPORT_SDL - struct - { - mal_handle hSDL; // SDL - mal_proc SDL_InitSubSystem; - mal_proc SDL_QuitSubSystem; - mal_proc SDL_GetNumAudioDevices; - mal_proc SDL_GetAudioDeviceName; - mal_proc SDL_CloseAudioDevice; - mal_proc SDL_OpenAudioDevice; - mal_proc SDL_PauseAudioDevice; - } sdl; -#endif -#ifdef MAL_SUPPORT_NULL - struct - { - int _unused; - } null_backend; -#endif - }; - - union - { -#ifdef MAL_WIN32 - struct - { - /*HMODULE*/ mal_handle hOle32DLL; - mal_proc CoInitializeEx; - mal_proc CoUninitialize; - mal_proc CoCreateInstance; - mal_proc CoTaskMemFree; - mal_proc PropVariantClear; - mal_proc StringFromGUID2; - - /*HMODULE*/ mal_handle hUser32DLL; - mal_proc GetForegroundWindow; - mal_proc GetDesktopWindow; - - /*HMODULE*/ mal_handle hAdvapi32DLL; - mal_proc RegOpenKeyExA; - mal_proc RegCloseKey; - mal_proc RegQueryValueExA; - } win32; -#endif -#ifdef MAL_POSIX - struct - { - mal_handle pthreadSO; - mal_proc pthread_create; - mal_proc pthread_join; - mal_proc pthread_mutex_init; - mal_proc pthread_mutex_destroy; - mal_proc pthread_mutex_lock; - mal_proc pthread_mutex_unlock; - mal_proc pthread_cond_init; - mal_proc pthread_cond_destroy; - mal_proc pthread_cond_wait; - mal_proc pthread_cond_signal; - mal_proc pthread_attr_init; - mal_proc pthread_attr_destroy; - mal_proc pthread_attr_setschedpolicy; - mal_proc pthread_attr_getschedparam; - mal_proc pthread_attr_setschedparam; - } posix; -#endif - int _unused; - }; -}; - -MAL_ALIGNED_STRUCT(MAL_SIMD_ALIGNMENT) mal_device -{ - mal_context* pContext; - mal_device_type type; - mal_format format; - mal_uint32 channels; - mal_uint32 sampleRate; - mal_channel channelMap[MAL_MAX_CHANNELS]; - mal_uint32 bufferSizeInFrames; - mal_uint32 bufferSizeInMilliseconds; - mal_uint32 periods; - mal_uint32 state; - mal_recv_proc onRecv; - mal_send_proc onSend; - mal_stop_proc onStop; - void* pUserData; // Application defined data. - char name[256]; - mal_device_config initConfig; // The configuration passed in to mal_device_init(). Mainly used for reinitializing the backend device. - mal_mutex lock; - mal_event wakeupEvent; - mal_event startEvent; - mal_event stopEvent; - mal_thread thread; - mal_result workResult; // This is set by the worker thread after it's finished doing a job. - mal_bool32 usingDefaultFormat : 1; - mal_bool32 usingDefaultChannels : 1; - mal_bool32 usingDefaultSampleRate : 1; - mal_bool32 usingDefaultChannelMap : 1; - mal_bool32 usingDefaultBufferSize : 1; - mal_bool32 usingDefaultPeriods : 1; - mal_bool32 exclusiveMode : 1; - mal_bool32 isOwnerOfContext : 1; // When set to true, uninitializing the device will also uninitialize the context. Set to true when NULL is passed into mal_device_init(). - mal_bool32 isDefaultDevice : 1; // Used to determine if the backend should try reinitializing if the default device is unplugged. - mal_format internalFormat; - mal_uint32 internalChannels; - mal_uint32 internalSampleRate; - mal_channel internalChannelMap[MAL_MAX_CHANNELS]; - mal_dsp dsp; // Samples run through this to convert samples to a format suitable for use by the backend. - mal_uint32 _dspFrameCount; // Internal use only. Used when running the device -> DSP -> client pipeline. See mal_device__on_read_from_device(). - const mal_uint8* _dspFrames; // ^^^ AS ABOVE ^^^ - - union - { -#ifdef MAL_SUPPORT_WASAPI - struct - { - /*IAudioClient**/ mal_ptr pAudioClient; - /*IAudioRenderClient**/ mal_ptr pRenderClient; - /*IAudioCaptureClient**/ mal_ptr pCaptureClient; - /*IMMDeviceEnumerator**/ mal_ptr pDeviceEnumerator; /* <-- Used for IMMNotificationClient notifications. Required for detecting default device changes. */ - mal_IMMNotificationClient notificationClient; - /*HANDLE*/ mal_handle hEvent; - /*HANDLE*/ mal_handle hBreakEvent; /* <-- Used to break from WaitForMultipleObjects() in the main loop. */ - mal_bool32 breakFromMainLoop; - mal_bool32 hasDefaultDeviceChanged; /* <-- Make sure this is always a whole 32-bits because we use atomic assignments. */ - } wasapi; -#endif -#ifdef MAL_SUPPORT_DSOUND - struct - { - /*LPDIRECTSOUND*/ mal_ptr pPlayback; - /*LPDIRECTSOUNDBUFFER*/ mal_ptr pPlaybackPrimaryBuffer; - /*LPDIRECTSOUNDBUFFER*/ mal_ptr pPlaybackBuffer; - /*LPDIRECTSOUNDCAPTURE*/ mal_ptr pCapture; - /*LPDIRECTSOUNDCAPTUREBUFFER*/ mal_ptr pCaptureBuffer; - /*LPDIRECTSOUNDNOTIFY*/ mal_ptr pNotify; - /*HANDLE*/ mal_handle pNotifyEvents[MAL_MAX_PERIODS_DSOUND]; // One event handle for each period. - /*HANDLE*/ mal_handle hStopEvent; - mal_uint32 lastProcessedFrame; // This is circular. - mal_bool32 breakFromMainLoop; - } dsound; -#endif -#ifdef MAL_SUPPORT_WINMM - struct - { - /*HWAVEOUT, HWAVEIN*/ mal_handle hDevice; - /*HANDLE*/ mal_handle hEvent; - mal_uint32 fragmentSizeInFrames; - mal_uint32 fragmentSizeInBytes; - mal_uint32 iNextHeader; // [0,periods). Used as an index into pWAVEHDR. - /*WAVEHDR**/ mal_uint8* pWAVEHDR; // One instantiation for each period. - mal_uint8* pIntermediaryBuffer; - mal_uint8* _pHeapData; // Used internally and is used for the heap allocated data for the intermediary buffer and the WAVEHDR structures. - mal_bool32 breakFromMainLoop; - } winmm; -#endif -#ifdef MAL_SUPPORT_ALSA - struct - { - /*snd_pcm_t**/ mal_ptr pPCM; - mal_bool32 isUsingMMap : 1; - mal_bool32 breakFromMainLoop : 1; - void* pIntermediaryBuffer; - } alsa; -#endif -#ifdef MAL_SUPPORT_PULSEAUDIO - struct - { - /*pa_mainloop**/ mal_ptr pMainLoop; - /*pa_mainloop_api**/ mal_ptr pAPI; - /*pa_context**/ mal_ptr pPulseContext; - /*pa_stream**/ mal_ptr pStream; - /*pa_context_state*/ mal_uint32 pulseContextState; - mal_uint32 fragmentSizeInBytes; - mal_bool32 breakFromMainLoop : 1; - } pulse; -#endif -#ifdef MAL_SUPPORT_JACK - struct - { - /*jack_client_t**/ mal_ptr pClient; - /*jack_port_t**/ mal_ptr pPorts[MAL_MAX_CHANNELS]; - float* pIntermediaryBuffer; // Typed as a float because JACK is always floating point. - } jack; -#endif -#ifdef MAL_SUPPORT_COREAUDIO - struct - { - mal_uint32 deviceObjectID; - /*AudioComponent*/ mal_ptr component; // <-- Can this be per-context? - /*AudioUnit*/ mal_ptr audioUnit; - /*AudioBufferList**/ mal_ptr pAudioBufferList; // Only used for input devices. - mal_event stopEvent; - mal_bool32 isSwitchingDevice; /* <-- Set to true when the default device has changed and mini_al is in the process of switching. */ - } coreaudio; -#endif -#ifdef MAL_SUPPORT_SNDIO - struct - { - mal_ptr handle; - mal_uint32 fragmentSizeInFrames; - mal_bool32 breakFromMainLoop; - void* pIntermediaryBuffer; - } sndio; -#endif -#ifdef MAL_SUPPORT_AUDIO4 - struct - { - int fd; - mal_uint32 fragmentSizeInFrames; - mal_bool32 breakFromMainLoop; - void* pIntermediaryBuffer; - } audio4; -#endif -#ifdef MAL_SUPPORT_OSS - struct - { - int fd; - mal_uint32 fragmentSizeInFrames; - mal_bool32 breakFromMainLoop; - void* pIntermediaryBuffer; - } oss; -#endif -#ifdef MAL_SUPPORT_AAUDIO - struct - { - /*AAudioStream**/ mal_ptr pStream; - } aaudio; -#endif -#ifdef MAL_SUPPORT_OPENSL - struct - { - /*SLObjectItf*/ mal_ptr pOutputMixObj; - /*SLOutputMixItf*/ mal_ptr pOutputMix; - /*SLObjectItf*/ mal_ptr pAudioPlayerObj; - /*SLPlayItf*/ mal_ptr pAudioPlayer; - /*SLObjectItf*/ mal_ptr pAudioRecorderObj; - /*SLRecordItf*/ mal_ptr pAudioRecorder; - /*SLAndroidSimpleBufferQueueItf*/ mal_ptr pBufferQueue; - mal_uint32 periodSizeInFrames; - mal_uint32 currentBufferIndex; - mal_uint8* pBuffer; // This is malloc()'d and is used for storing audio data. Typed as mal_uint8 for easy offsetting. - } opensl; -#endif -#ifdef MAL_SUPPORT_WEBAUDIO - struct - { - int index; /* We use a factory on the JavaScript side to manage devices and use an index for JS/C interop. */ - } webaudio; -#endif -#ifdef MAL_SUPPORT_OPENAL - struct - { - /*ALCcontext**/ mal_ptr pContextALC; - /*ALCdevice**/ mal_ptr pDeviceALC; - /*ALuint*/ mal_uint32 sourceAL; - /*ALuint*/ mal_uint32 buffersAL[MAL_MAX_PERIODS_OPENAL]; - /*ALenum*/ mal_uint32 formatAL; - mal_uint32 subBufferSizeInFrames; // This is the size of each of the OpenAL buffers (buffersAL). - mal_uint8* pIntermediaryBuffer; // This is malloc()'d and is used as the destination for reading from the client. Typed as mal_uint8 for easy offsetting. - mal_uint32 iNextBuffer; // The next buffer to unenqueue and then re-enqueue as new data is read. - mal_bool32 breakFromMainLoop; - } openal; -#endif -#ifdef MAL_SUPPORT_SDL - struct - { - mal_uint32 deviceID; - } sdl; -#endif -#ifdef MAL_SUPPORT_NULL - struct - { - mal_timer timer; - mal_uint32 lastProcessedFrame; // This is circular. - mal_bool32 breakFromMainLoop; - mal_uint8* pBuffer; // This is malloc()'d and is used as the destination for reading from the client. Typed as mal_uint8 for easy offsetting. - } null_device; -#endif - }; -}; -#if defined(_MSC_VER) - #pragma warning(pop) -#endif - -// Initializes a context. -// -// The context is used for selecting and initializing the relevant backends. -// -// Note that the location of the context cannot change throughout it's lifetime. Consider allocating -// the mal_context object with malloc() if this is an issue. The reason for this is that a pointer -// to the context is stored in the mal_device structure. -// -// is used to allow the application to prioritize backends depending on it's specific -// requirements. This can be null in which case it uses the default priority, which is as follows: -// - WASAPI -// - DirectSound -// - WinMM -// - Core Audio (Apple) -// - sndio -// - audio(4) -// - OSS -// - PulseAudio -// - ALSA -// - JACK -// - AAudio -// - OpenSL|ES -// - Web Audio / Emscripten -// - Null -// -// is used to configure the context. Use the onLog config to set a callback for whenever a -// log message is posted. The priority of the worker thread can be set with the threadPriority config. -// -// It is recommended that only a single context is active at any given time because it's a bulky data -// structure which performs run-time linking for the relevant backends every time it's initialized. -// -// Return Value: -// MAL_SUCCESS if successful; any other error code otherwise. -// -// Thread Safety: UNSAFE -mal_result mal_context_init(const mal_backend backends[], mal_uint32 backendCount, const mal_context_config* pConfig, mal_context* pContext); - -// Uninitializes a context. -// -// Results are undefined if you call this while any device created by this context is still active. -// -// Return Value: -// MAL_SUCCESS if successful; any other error code otherwise. -// -// Thread Safety: UNSAFE -mal_result mal_context_uninit(mal_context* pContext); - -// Enumerates over every device (both playback and capture). -// -// This is a lower-level enumeration function to the easier to use mal_context_get_devices(). Use -// mal_context_enumerate_devices() if you would rather not incur an internal heap allocation, or -// it simply suits your code better. -// -// Do _not_ assume the first enumerated device of a given type is the default device. -// -// Some backends and platforms may only support default playback and capture devices. -// -// Note that this only retrieves the ID and name/description of the device. The reason for only -// retrieving basic information is that it would otherwise require opening the backend device in -// order to probe it for more detailed information which can be inefficient. Consider using -// mal_context_get_device_info() for this, but don't call it from within the enumeration callback. -// -// In general, you should not do anything complicated from within the callback. In particular, do -// not try initializing a device from within the callback. -// -// Consider using mal_context_get_devices() for a simpler and safer API, albeit at the expense of -// an internal heap allocation. -// -// Returning false from the callback will stop enumeration. Returning true will continue enumeration. -// -// Return Value: -// MAL_SUCCESS if successful; any other error code otherwise. -// -// Thread Safety: SAFE -// This is guarded using a simple mutex lock. -mal_result mal_context_enumerate_devices(mal_context* pContext, mal_enum_devices_callback_proc callback, void* pUserData); - -// Retrieves basic information about every active playback and/or capture device. -// -// You can pass in NULL for the playback or capture lists in which case they'll be ignored. -// -// It is _not_ safe to assume the first device in the list is the default device. -// -// The returned pointers will become invalid upon the next call this this function, or when the -// context is uninitialized. Do not free the returned pointers. -// -// This function follows the same enumeration rules as mal_context_enumerate_devices(). See -// documentation for mal_context_enumerate_devices() for more information. -// -// Return Value: -// MAL_SUCCESS if successful; any other error code otherwise. -// -// Thread Safety: SAFE -// Since each call to this function invalidates the pointers from the previous call, you -// should not be calling this simultaneously across multiple threads. Instead, you need to -// make a copy of the returned data with your own higher level synchronization. -mal_result mal_context_get_devices(mal_context* pContext, mal_device_info** ppPlaybackDeviceInfos, mal_uint32* pPlaybackDeviceCount, mal_device_info** ppCaptureDeviceInfos, mal_uint32* pCaptureDeviceCount); - -// Retrieves information about a device with the given ID. -// -// Do _not_ call this from within the mal_context_enumerate_devices() callback. -// -// It's possible for a device to have different information and capabilities depending on wether or -// not it's opened in shared or exclusive mode. For example, in shared mode, WASAPI always uses -// floating point samples for mixing, but in exclusive mode it can be anything. Therefore, this -// function allows you to specify which share mode you want information for. Note that not all -// backends and devices support shared or exclusive mode, in which case this function will fail -// if the requested share mode is unsupported. -// -// This leaves pDeviceInfo unmodified in the result of an error. -// -// Return Value: -// MAL_SUCCESS if successful; any other error code otherwise. -// -// Thread Safety: SAFE -// This is guarded using a simple mutex lock. -mal_result mal_context_get_device_info(mal_context* pContext, mal_device_type type, const mal_device_id* pDeviceID, mal_share_mode shareMode, mal_device_info* pDeviceInfo); - -// Initializes a device. -// -// The context can be null in which case it uses the default. This is equivalent to passing in a -// context that was initialized like so: -// -// mal_context_init(NULL, 0, NULL, &context); -// -// Do not pass in null for the context if you are needing to open multiple devices. You can, -// however, use null when initializing the first device, and then use device.pContext for the -// initialization of other devices. -// -// The device ID (pDeviceID) can be null, in which case the default device is used. Otherwise, you -// can retrieve the ID by calling mal_context_get_devices() and using the ID from the returned data. -// Set pDeviceID to NULL to use the default device. Do _not_ rely on the first device ID returned -// by mal_context_enumerate_devices() or mal_context_get_devices() to be the default device. -// -// The device's configuration is controlled with pConfig. This allows you to configure the sample -// format, channel count, sample rate, etc. Before calling mal_device_init(), you will most likely -// want to initialize a mal_device_config object using mal_device_config_init(), -// mal_device_config_init_playback(), etc. You can also pass in NULL for the device config in -// which case it will use defaults, but will require you to call mal_device_set_recv_callback() or -// mal_device_set_send_callback() before starting the device. -// -// Passing in 0 to any property in pConfig will force the use of a default value. In the case of -// sample format, channel count, sample rate and channel map it will default to the values used by -// the backend's internal device. For the size of the buffer you can set bufferSizeInFrames or -// bufferSizeInMilliseconds (if both are set it will prioritize bufferSizeInFrames). If both are -// set to zero, it will default to MAL_BASE_BUFFER_SIZE_IN_MILLISECONDS_LOW_LATENCY or -// MAL_BASE_BUFFER_SIZE_IN_MILLISECONDS_CONSERVATIVE, depending on whether or not performanceProfile -// is set to mal_performance_profile_low_latency or mal_performance_profile_conservative. -// -// When sending or receiving data to/from a device, mini_al will internally perform a format -// conversion to convert between the format specified by pConfig and the format used internally by -// the backend. If you pass in NULL for pConfig or 0 for the sample format, channel count, -// sample rate _and_ channel map, data transmission will run on an optimized pass-through fast path. -// -// The property controls how frequently the background thread is woken to check for more -// data. It's tied to the buffer size, so as an example, if your buffer size is equivalent to 10 -// milliseconds and you have 2 periods, the CPU will wake up approximately every 5 milliseconds. -// -// When compiling for UWP you must ensure you call this function on the main UI thread because the -// operating system may need to present the user with a message asking for permissions. Please refer -// to the official documentation for ActivateAudioInterfaceAsync() for more information. -// -// Return Value: -// MAL_SUCCESS if successful; any other error code otherwise. -// -// Thread Safety: UNSAFE -// It is not safe to call this function simultaneously for different devices because some backends -// depend on and mutate global state (such as OpenSL|ES). The same applies to calling this at the -// same time as mal_device_uninit(). -mal_result mal_device_init(mal_context* pContext, mal_device_type type, mal_device_id* pDeviceID, const mal_device_config* pConfig, void* pUserData, mal_device* pDevice); - -// Initializes a device without a context, with extra parameters for controlling the configuration -// of the internal self-managed context. -// -// See mal_device_init() and mal_context_init(). -mal_result mal_device_init_ex(const mal_backend backends[], mal_uint32 backendCount, const mal_context_config* pContextConfig, mal_device_type type, mal_device_id* pDeviceID, const mal_device_config* pConfig, void* pUserData, mal_device* pDevice); - -// Uninitializes a device. -// -// This will explicitly stop the device. You do not need to call mal_device_stop() beforehand, but it's -// harmless if you do. -// -// Return Value: -// MAL_SUCCESS if successful; any other error code otherwise. -// -// Thread Safety: UNSAFE -// As soon as this API is called the device should be considered undefined. All bets are off if you -// try using the device at the same time as uninitializing it. -void mal_device_uninit(mal_device* pDevice); - -// Sets the callback to use when the application has received data from the device. -// -// Thread Safety: SAFE -// This API is implemented as a simple atomic assignment. -// -// DEPRECATED. Set this when the device is initialized with mal_device_init*(). -void mal_device_set_recv_callback(mal_device* pDevice, mal_recv_proc proc); - -// Sets the callback to use when the application needs to send data to the device for playback. -// -// Note that the implementation of this callback must copy over as many samples as is available. The -// return value specifies how many samples were written to the output buffer. The backend will fill -// any leftover samples with silence. -// -// Thread Safety: SAFE -// This API is implemented as a simple atomic assignment. -// -// DEPRECATED. Set this when the device is initialized with mal_device_init*(). -void mal_device_set_send_callback(mal_device* pDevice, mal_send_proc proc); - -// Sets the callback to use when the device has stopped, either explicitly or as a result of an error. -// -// Thread Safety: SAFE -// This API is implemented as a simple atomic assignment. -void mal_device_set_stop_callback(mal_device* pDevice, mal_stop_proc proc); - -// Activates the device. For playback devices this begins playback. For capture devices it begins -// recording. -// -// For a playback device, this will retrieve an initial chunk of audio data from the client before -// returning. The reason for this is to ensure there is valid audio data in the buffer, which needs -// to be done _before_ the device begins playback. -// -// This API waits until the backend device has been started for real by the worker thread. It also -// waits on a mutex for thread-safety. -// -// Return Value: -// - MAL_SUCCESS if successful; any other error code otherwise. -// - MAL_INVALID_ARGS -// One or more of the input arguments is invalid. -// - MAL_DEVICE_NOT_INITIALIZED -// The device is not currently or was never initialized. -// - MAL_DEVICE_BUSY -// The device is in the process of stopping. This will only happen if mal_device_start() and -// mal_device_stop() is called simultaneous on separate threads. This will never be returned in -// single-threaded applications. -// - MAL_DEVICE_ALREADY_STARTING -// The device is already in the process of starting. This will never be returned in single-threaded -// applications. -// - MAL_DEVICE_ALREADY_STARTED -// The device is already started. -// - MAL_FAILED_TO_READ_DATA_FROM_CLIENT -// Failed to read the initial chunk of audio data from the client. This initial chunk of data is -// required so that the device has valid audio data as soon as it starts playing. This will never -// be returned for capture devices. -// - MAL_FAILED_TO_START_BACKEND_DEVICE -// There was a backend-specific error starting the device. -// -// Thread Safety: SAFE -mal_result mal_device_start(mal_device* pDevice); - -// Puts the device to sleep, but does not uninitialize it. Use mal_device_start() to start it up again. -// -// This API needs to wait on the worker thread to stop the backend device properly before returning. It -// also waits on a mutex for thread-safety. In addition, some backends need to wait for the device to -// finish playback/recording of the current fragment which can take some time (usually proportionate to -// the buffer size that was specified at initialization time). -// -// Return Value: -// - MAL_SUCCESS if successful; any other error code otherwise. -// - MAL_INVALID_ARGS -// One or more of the input arguments is invalid. -// - MAL_DEVICE_NOT_INITIALIZED -// The device is not currently or was never initialized. -// - MAL_DEVICE_BUSY -// The device is in the process of starting. This will only happen if mal_device_start() and -// mal_device_stop() is called simultaneous on separate threads. This will never be returned in -// single-threaded applications. -// - MAL_DEVICE_ALREADY_STOPPING -// The device is already in the process of stopping. This will never be returned in single-threaded -// applications. -// - MAL_DEVICE_ALREADY_STOPPED -// The device is already stopped. -// - MAL_FAILED_TO_STOP_BACKEND_DEVICE -// There was a backend-specific error stopping the device. -// -// Thread Safety: SAFE -mal_result mal_device_stop(mal_device* pDevice); - -// Determines whether or not the device is started. -// -// This is implemented as a simple accessor. -// -// Return Value: -// True if the device is started, false otherwise. -// -// Thread Safety: SAFE -// If another thread calls mal_device_start() or mal_device_stop() at this same time as this function -// is called, there's a very small chance the return value will be out of sync. -mal_bool32 mal_device_is_started(mal_device* pDevice); - -// Retrieves the size of the buffer in bytes for the given device. -// -// This API is efficient and is implemented with just a few 32-bit integer multiplications. -// -// Thread Safety: SAFE -// This is calculated from constant values which are set at initialization time and never change. -mal_uint32 mal_device_get_buffer_size_in_bytes(mal_device* pDevice); - - -// Helper function for initializing a mal_context_config object. -mal_context_config mal_context_config_init(mal_log_proc onLog); - -// Initializes a default device config. -// -// A default configuration will configure the device such that the format, channel count, sample rate and channel map are -// the same as the backend's internal configuration. This means the application loses explicit control of these properties, -// but in return gets an optimized fast path for data transmission since mini_al will be releived of all format conversion -// duties. You will not typically want to use default configurations unless you have some specific low-latency requirements. -// -// mal_device_config_init(), mal_device_config_init_playback(), etc. will allow you to explicitly set the sample format, -// channel count, etc. -mal_device_config mal_device_config_init_default(void); -mal_device_config mal_device_config_init_default_capture(mal_recv_proc onRecvCallback); -mal_device_config mal_device_config_init_default_playback(mal_send_proc onSendCallback); - -// Helper function for initializing a mal_device_config object. -// -// This is just a helper API, and as such the returned object can be safely modified as needed. -// -// The default channel mapping is based on the channel count, as per the table below. Note that these -// can be freely changed after this function returns if you are needing something in particular. -// -// |---------------|------------------------------| -// | Channel Count | Mapping | -// |---------------|------------------------------| -// | 1 (Mono) | 0: MAL_CHANNEL_MONO | -// |---------------|------------------------------| -// | 2 (Stereo) | 0: MAL_CHANNEL_FRONT_LEFT | -// | | 1: MAL_CHANNEL_FRONT_RIGHT | -// |---------------|------------------------------| -// | 3 | 0: MAL_CHANNEL_FRONT_LEFT | -// | | 1: MAL_CHANNEL_FRONT_RIGHT | -// | | 2: MAL_CHANNEL_FRONT_CENTER | -// |---------------|------------------------------| -// | 4 (Surround) | 0: MAL_CHANNEL_FRONT_LEFT | -// | | 1: MAL_CHANNEL_FRONT_RIGHT | -// | | 2: MAL_CHANNEL_FRONT_CENTER | -// | | 3: MAL_CHANNEL_BACK_CENTER | -// |---------------|------------------------------| -// | 5 | 0: MAL_CHANNEL_FRONT_LEFT | -// | | 1: MAL_CHANNEL_FRONT_RIGHT | -// | | 2: MAL_CHANNEL_FRONT_CENTER | -// | | 3: MAL_CHANNEL_BACK_LEFT | -// | | 4: MAL_CHANNEL_BACK_RIGHT | -// |---------------|------------------------------| -// | 6 (5.1) | 0: MAL_CHANNEL_FRONT_LEFT | -// | | 1: MAL_CHANNEL_FRONT_RIGHT | -// | | 2: MAL_CHANNEL_FRONT_CENTER | -// | | 3: MAL_CHANNEL_LFE | -// | | 4: MAL_CHANNEL_SIDE_LEFT | -// | | 5: MAL_CHANNEL_SIDE_RIGHT | -// |---------------|------------------------------| -// | 7 | 0: MAL_CHANNEL_FRONT_LEFT | -// | | 1: MAL_CHANNEL_FRONT_RIGHT | -// | | 2: MAL_CHANNEL_FRONT_CENTER | -// | | 3: MAL_CHANNEL_LFE | -// | | 4: MAL_CHANNEL_BACK_CENTER | -// | | 4: MAL_CHANNEL_SIDE_LEFT | -// | | 5: MAL_CHANNEL_SIDE_RIGHT | -// |---------------|------------------------------| -// | 8 (7.1) | 0: MAL_CHANNEL_FRONT_LEFT | -// | | 1: MAL_CHANNEL_FRONT_RIGHT | -// | | 2: MAL_CHANNEL_FRONT_CENTER | -// | | 3: MAL_CHANNEL_LFE | -// | | 4: MAL_CHANNEL_BACK_LEFT | -// | | 5: MAL_CHANNEL_BACK_RIGHT | -// | | 6: MAL_CHANNEL_SIDE_LEFT | -// | | 7: MAL_CHANNEL_SIDE_RIGHT | -// |---------------|------------------------------| -// | Other | All channels set to 0. This | -// | | is equivalent to the same | -// | | mapping as the device. | -// |---------------|------------------------------| -// -// Thread Safety: SAFE -// -// Efficiency: HIGH -// This just returns a stack allocated object and consists of just a few assignments. -mal_device_config mal_device_config_init_ex(mal_format format, mal_uint32 channels, mal_uint32 sampleRate, mal_channel channelMap[MAL_MAX_CHANNELS], mal_recv_proc onRecvCallback, mal_send_proc onSendCallback); - -// A simplified version of mal_device_config_init_ex(). -static MAL_INLINE mal_device_config mal_device_config_init(mal_format format, mal_uint32 channels, mal_uint32 sampleRate, mal_recv_proc onRecvCallback, mal_send_proc onSendCallback) { return mal_device_config_init_ex(format, channels, sampleRate, NULL, onRecvCallback, onSendCallback); } - -// A simplified version of mal_device_config_init() for capture devices. -static MAL_INLINE mal_device_config mal_device_config_init_capture_ex(mal_format format, mal_uint32 channels, mal_uint32 sampleRate, mal_channel channelMap[MAL_MAX_CHANNELS], mal_recv_proc onRecvCallback) { return mal_device_config_init_ex(format, channels, sampleRate, channelMap, onRecvCallback, NULL); } -static MAL_INLINE mal_device_config mal_device_config_init_capture(mal_format format, mal_uint32 channels, mal_uint32 sampleRate, mal_recv_proc onRecvCallback) { return mal_device_config_init_capture_ex(format, channels, sampleRate, NULL, onRecvCallback); } - -// A simplified version of mal_device_config_init() for playback devices. -static MAL_INLINE mal_device_config mal_device_config_init_playback_ex(mal_format format, mal_uint32 channels, mal_uint32 sampleRate, mal_channel channelMap[MAL_MAX_CHANNELS], mal_send_proc onSendCallback) { return mal_device_config_init_ex(format, channels, sampleRate, channelMap, NULL, onSendCallback); } -static MAL_INLINE mal_device_config mal_device_config_init_playback(mal_format format, mal_uint32 channels, mal_uint32 sampleRate, mal_send_proc onSendCallback) { return mal_device_config_init_playback_ex(format, channels, sampleRate, NULL, onSendCallback); } - - - -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Utiltities -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -// Creates a mutex. -// -// A mutex must be created from a valid context. A mutex is initially unlocked. -mal_result mal_mutex_init(mal_context* pContext, mal_mutex* pMutex); - -// Deletes a mutex. -void mal_mutex_uninit(mal_mutex* pMutex); - -// Locks a mutex with an infinite timeout. -void mal_mutex_lock(mal_mutex* pMutex); - -// Unlocks a mutex. -void mal_mutex_unlock(mal_mutex* pMutex); - - -// Retrieves a friendly name for a backend. -const char* mal_get_backend_name(mal_backend backend); - -// Adjust buffer size based on a scaling factor. -// -// This just multiplies the base size by the scaling factor, making sure it's a size of at least 1. -mal_uint32 mal_scale_buffer_size(mal_uint32 baseBufferSize, float scale); - -// Calculates a buffer size in milliseconds from the specified number of frames and sample rate. -mal_uint32 mal_calculate_buffer_size_in_milliseconds_from_frames(mal_uint32 bufferSizeInFrames, mal_uint32 sampleRate); - -// Calculates a buffer size in frames from the specified number of milliseconds and sample rate. -mal_uint32 mal_calculate_buffer_size_in_frames_from_milliseconds(mal_uint32 bufferSizeInMilliseconds, mal_uint32 sampleRate); - -// Retrieves the default buffer size in milliseconds based on the specified performance profile. -mal_uint32 mal_get_default_buffer_size_in_milliseconds(mal_performance_profile performanceProfile); - -// Calculates a buffer size in frames for the specified performance profile and scale factor. -mal_uint32 mal_get_default_buffer_size_in_frames(mal_performance_profile performanceProfile, mal_uint32 sampleRate); - -#endif // MAL_NO_DEVICE_IO - - - - -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Decoding -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -#ifndef MAL_NO_DECODING - -typedef struct mal_decoder mal_decoder; - -typedef enum -{ - mal_seek_origin_start, - mal_seek_origin_current -} mal_seek_origin; - -typedef size_t (* mal_decoder_read_proc) (mal_decoder* pDecoder, void* pBufferOut, size_t bytesToRead); // Returns the number of bytes read. -typedef mal_bool32 (* mal_decoder_seek_proc) (mal_decoder* pDecoder, int byteOffset, mal_seek_origin origin); -typedef mal_result (* mal_decoder_seek_to_frame_proc)(mal_decoder* pDecoder, mal_uint64 frameIndex); -typedef mal_result (* mal_decoder_uninit_proc) (mal_decoder* pDecoder); - -typedef struct -{ - mal_format format; // Set to 0 or mal_format_unknown to use the stream's internal format. - mal_uint32 channels; // Set to 0 to use the stream's internal channels. - mal_uint32 sampleRate; // Set to 0 to use the stream's internal sample rate. - mal_channel channelMap[MAL_MAX_CHANNELS]; - mal_channel_mix_mode channelMixMode; - mal_dither_mode ditherMode; - mal_src_algorithm srcAlgorithm; - union - { - mal_src_config_sinc sinc; - } src; -} mal_decoder_config; - -struct mal_decoder -{ - mal_decoder_read_proc onRead; - mal_decoder_seek_proc onSeek; - void* pUserData; - mal_format internalFormat; - mal_uint32 internalChannels; - mal_uint32 internalSampleRate; - mal_channel internalChannelMap[MAL_MAX_CHANNELS]; - mal_format outputFormat; - mal_uint32 outputChannels; - mal_uint32 outputSampleRate; - mal_channel outputChannelMap[MAL_MAX_CHANNELS]; - mal_dsp dsp; // <-- Format conversion is achieved by running frames through this. - mal_decoder_seek_to_frame_proc onSeekToFrame; - mal_decoder_uninit_proc onUninit; - void* pInternalDecoder; // <-- The drwav/drflac/stb_vorbis/etc. objects. - struct - { - const mal_uint8* pData; - size_t dataSize; - size_t currentReadPos; - } memory; // Only used for decoders that were opened against a block of memory. -}; - -mal_decoder_config mal_decoder_config_init(mal_format outputFormat, mal_uint32 outputChannels, mal_uint32 outputSampleRate); - -mal_result mal_decoder_init(mal_decoder_read_proc onRead, mal_decoder_seek_proc onSeek, void* pUserData, const mal_decoder_config* pConfig, mal_decoder* pDecoder); -mal_result mal_decoder_init_wav(mal_decoder_read_proc onRead, mal_decoder_seek_proc onSeek, void* pUserData, const mal_decoder_config* pConfig, mal_decoder* pDecoder); -mal_result mal_decoder_init_flac(mal_decoder_read_proc onRead, mal_decoder_seek_proc onSeek, void* pUserData, const mal_decoder_config* pConfig, mal_decoder* pDecoder); -mal_result mal_decoder_init_vorbis(mal_decoder_read_proc onRead, mal_decoder_seek_proc onSeek, void* pUserData, const mal_decoder_config* pConfig, mal_decoder* pDecoder); -mal_result mal_decoder_init_mp3(mal_decoder_read_proc onRead, mal_decoder_seek_proc onSeek, void* pUserData, const mal_decoder_config* pConfig, mal_decoder* pDecoder); -mal_result mal_decoder_init_raw(mal_decoder_read_proc onRead, mal_decoder_seek_proc onSeek, void* pUserData, const mal_decoder_config* pConfigIn, const mal_decoder_config* pConfigOut, mal_decoder* pDecoder); - -mal_result mal_decoder_init_memory(const void* pData, size_t dataSize, const mal_decoder_config* pConfig, mal_decoder* pDecoder); -mal_result mal_decoder_init_memory_wav(const void* pData, size_t dataSize, const mal_decoder_config* pConfig, mal_decoder* pDecoder); -mal_result mal_decoder_init_memory_flac(const void* pData, size_t dataSize, const mal_decoder_config* pConfig, mal_decoder* pDecoder); -mal_result mal_decoder_init_memory_vorbis(const void* pData, size_t dataSize, const mal_decoder_config* pConfig, mal_decoder* pDecoder); -mal_result mal_decoder_init_memory_mp3(const void* pData, size_t dataSize, const mal_decoder_config* pConfig, mal_decoder* pDecoder); -mal_result mal_decoder_init_memory_raw(const void* pData, size_t dataSize, const mal_decoder_config* pConfigIn, const mal_decoder_config* pConfigOut, mal_decoder* pDecoder); - -#ifndef MAL_NO_STDIO -mal_result mal_decoder_init_file(const char* pFilePath, const mal_decoder_config* pConfig, mal_decoder* pDecoder); -mal_result mal_decoder_init_file_wav(const char* pFilePath, const mal_decoder_config* pConfig, mal_decoder* pDecoder); -#endif - -mal_result mal_decoder_uninit(mal_decoder* pDecoder); - -mal_uint64 mal_decoder_read(mal_decoder* pDecoder, mal_uint64 frameCount, void* pFramesOut); -mal_result mal_decoder_seek_to_frame(mal_decoder* pDecoder, mal_uint64 frameIndex); - - -// Helper for opening and decoding a file into a heap allocated block of memory. Free the returned pointer with mal_free(). On input, -// pConfig should be set to what you want. On output it will be set to what you got. -#ifndef MAL_NO_STDIO -mal_result mal_decode_file(const char* pFilePath, mal_decoder_config* pConfig, mal_uint64* pFrameCountOut, void** ppDataOut); -#endif -mal_result mal_decode_memory(const void* pData, size_t dataSize, mal_decoder_config* pConfig, mal_uint64* pFrameCountOut, void** ppDataOut); - -#endif // MAL_NO_DECODING - - -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Generation -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -typedef struct -{ - double amplitude; - double periodsPerSecond; - double delta; - double time; -} mal_sine_wave; - -mal_result mal_sine_wave_init(double amplitude, double period, mal_uint32 sampleRate, mal_sine_wave* pSineWave); -mal_uint64 mal_sine_wave_read(mal_sine_wave* pSineWave, mal_uint64 count, float* pSamples); -mal_uint64 mal_sine_wave_read_ex(mal_sine_wave* pSineWave, mal_uint64 frameCount, mal_uint32 channels, mal_stream_layout layout, float** ppFrames); - - -#ifdef __cplusplus -} -#endif -#endif //mini_al_h - - -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// IMPLEMENTATION -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -#if defined(MINI_AL_IMPLEMENTATION) || defined(MAL_IMPLEMENTATION) -#include -#include // For INT_MAX -#include // sin(), etc. - -#if defined(MAL_DEBUG_OUTPUT) -#include // for printf() for debug output -#endif - -#ifdef MAL_WIN32 - -// @raysan5: To avoid conflicting windows.h symbols with raylib, so flags are defined -// WARNING: Those flags avoid inclusion of some Win32 headers that could be required -// by user at some point and won't be included... -//------------------------------------------------------------------------------------- - -// If defined, the following flags inhibit definition of the indicated items. -#define NOGDICAPMASKS // CC_*, LC_*, PC_*, CP_*, TC_*, RC_ -#define NOVIRTUALKEYCODES // VK_* -#define NOWINMESSAGES // WM_*, EM_*, LB_*, CB_* -#define NOWINSTYLES // WS_*, CS_*, ES_*, LBS_*, SBS_*, CBS_* -#define NOSYSMETRICS // SM_* -#define NOMENUS // MF_* -#define NOICONS // IDI_* -#define NOKEYSTATES // MK_* -#define NOSYSCOMMANDS // SC_* -#define NORASTEROPS // Binary and Tertiary raster ops -#define NOSHOWWINDOW // SW_* -#define OEMRESOURCE // OEM Resource values -#define NOATOM // Atom Manager routines -#define NOCLIPBOARD // Clipboard routines -#define NOCOLOR // Screen colors -#define NOCTLMGR // Control and Dialog routines -#define NODRAWTEXT // DrawText() and DT_* -#define NOGDI // All GDI defines and routines -#define NOKERNEL // All KERNEL defines and routines -#define NOUSER // All USER defines and routines -//#define NONLS // All NLS defines and routines -#define NOMB // MB_* and MessageBox() -#define NOMEMMGR // GMEM_*, LMEM_*, GHND, LHND, associated routines -#define NOMETAFILE // typedef METAFILEPICT -#define NOMINMAX // Macros min(a,b) and max(a,b) -#define NOMSG // typedef MSG and associated routines -#define NOOPENFILE // OpenFile(), OemToAnsi, AnsiToOem, and OF_* -#define NOSCROLL // SB_* and scrolling routines -#define NOSERVICE // All Service Controller routines, SERVICE_ equates, etc. -#define NOSOUND // Sound driver routines -#define NOTEXTMETRIC // typedef TEXTMETRIC and associated routines -#define NOWH // SetWindowsHook and WH_* -#define NOWINOFFSETS // GWL_*, GCL_*, associated routines -#define NOCOMM // COMM driver routines -#define NOKANJI // Kanji support stuff. -#define NOHELP // Help engine interface. -#define NOPROFILER // Profiler interface. -#define NODEFERWINDOWPOS // DeferWindowPos routines -#define NOMCX // Modem Configuration Extensions - -// Type required before windows.h inclusion -typedef struct tagMSG *LPMSG; - -#include - -// Type required by some unused function... -typedef struct tagBITMAPINFOHEADER { - DWORD biSize; - LONG biWidth; - LONG biHeight; - WORD biPlanes; - WORD biBitCount; - DWORD biCompression; - DWORD biSizeImage; - LONG biXPelsPerMeter; - LONG biYPelsPerMeter; - DWORD biClrUsed; - DWORD biClrImportant; -} BITMAPINFOHEADER, *PBITMAPINFOHEADER; - -// @raysan5: Some required types defined for MSVC/TinyC compiler -#if defined(_MSC_VER) || defined(__TINYC__) - #include "propidl.h" -#endif -//---------------------------------------------------------------------------------- - -#else -#include // For malloc()/free() -#include // For memset() -#endif - -#if defined(MAL_APPLE) && (__MAC_OS_X_VERSION_MIN_REQUIRED < 101200) -#include // For mach_absolute_time() -#endif - -#ifdef MAL_POSIX -#include -#include -#endif - -#ifdef MAL_EMSCRIPTEN -#include -#endif - -#if !defined(MAL_64BIT) && !defined(MAL_32BIT) -#ifdef _WIN32 -#ifdef _WIN64 -#define MAL_64BIT -#else -#define MAL_32BIT -#endif -#endif -#endif - -#if !defined(MAL_64BIT) && !defined(MAL_32BIT) -#ifdef __GNUC__ -#ifdef __LP64__ -#define MAL_64BIT -#else -#define MAL_32BIT -#endif -#endif -#endif - -#if !defined(MAL_64BIT) && !defined(MAL_32BIT) -#include -#if INTPTR_MAX == INT64_MAX -#define MAL_64BIT -#else -#define MAL_32BIT -#endif -#endif - -// Architecture Detection -#if defined(__x86_64__) || defined(_M_X64) -#define MAL_X64 -#elif defined(__i386) || defined(_M_IX86) -#define MAL_X86 -#elif defined(__arm__) || defined(_M_ARM) -#define MAL_ARM -#endif - -// Cannot currently support AVX-512 if AVX is disabled. -#if !defined(MAL_NO_AVX512) && defined(MAL_NO_AVX2) -#define MAL_NO_AVX512 -#endif - -// Intrinsics Support -#if defined(MAL_X64) || defined(MAL_X86) - #if defined(_MSC_VER) && !defined(__clang__) - // MSVC. - #if !defined(MAL_NO_SSE2) // Assume all MSVC compilers support SSE2 intrinsics. - #define MAL_SUPPORT_SSE2 - #endif - //#if _MSC_VER >= 1600 && !defined(MAL_NO_AVX) // 2010 - // #define MAL_SUPPORT_AVX - //#endif - #if _MSC_VER >= 1700 && !defined(MAL_NO_AVX2) // 2012 - #define MAL_SUPPORT_AVX2 - #endif - #if _MSC_VER >= 1910 && !defined(MAL_NO_AVX512) // 2017 - #define MAL_SUPPORT_AVX512 - #endif - #else - // Assume GNUC-style. - #if defined(__SSE2__) && !defined(MAL_NO_SSE2) - #define MAL_SUPPORT_SSE2 - #endif - //#if defined(__AVX__) && !defined(MAL_NO_AVX) - // #define MAL_SUPPORT_AVX - //#endif - #if defined(__AVX2__) && !defined(MAL_NO_AVX2) - #define MAL_SUPPORT_AVX2 - #endif - #if defined(__AVX512F__) && !defined(MAL_NO_AVX512) - #define MAL_SUPPORT_AVX512 - #endif - #endif - - // If at this point we still haven't determined compiler support for the intrinsics just fall back to __has_include. - #if !defined(__GNUC__) && !defined(__clang__) && defined(__has_include) - #if !defined(MAL_SUPPORT_SSE2) && !defined(MAL_NO_SSE2) && __has_include() - #define MAL_SUPPORT_SSE2 - #endif - //#if !defined(MAL_SUPPORT_AVX) && !defined(MAL_NO_AVX) && __has_include() - // #define MAL_SUPPORT_AVX - //#endif - #if !defined(MAL_SUPPORT_AVX2) && !defined(MAL_NO_AVX2) && __has_include() - #define MAL_SUPPORT_AVX2 - #endif - #if !defined(MAL_SUPPORT_AVX512) && !defined(MAL_NO_AVX512) && __has_include() - #define MAL_SUPPORT_AVX512 - #endif - #endif - - #if defined(MAL_SUPPORT_AVX512) - #include // Not a mistake. Intentionally including instead of because otherwise the compiler will complain. - #elif defined(MAL_SUPPORT_AVX2) || defined(MAL_SUPPORT_AVX) - #include - #elif defined(MAL_SUPPORT_SSE2) - #include - #endif -#endif - -#if defined(MAL_ARM) - #if !defined(MAL_NO_NEON) && (defined(__ARM_NEON) || defined(__aarch64__) || defined(_M_ARM64)) - #define MAL_SUPPORT_NEON - #endif - - // Fall back to looking for the #include file. - #if !defined(__GNUC__) && !defined(__clang__) && defined(__has_include) - #if !defined(MAL_SUPPORT_NEON) && !defined(MAL_NO_NEON) && __has_include() - #define MAL_SUPPORT_NEON - #endif - #endif - - #if defined(MAL_SUPPORT_NEON) - #include - #endif -#endif - -#if defined(_MSC_VER) - #pragma warning(push) - #pragma warning(disable:4752) // found Intel(R) Advanced Vector Extensions; consider using /arch:AVX -#endif - -#if defined(MAL_X64) || defined(MAL_X86) - #if defined(_MSC_VER) && !defined(__clang__) - #if _MSC_VER >= 1400 - #include - static MAL_INLINE void mal_cpuid(int info[4], int fid) - { - __cpuid(info, fid); - } - #else - #define MAL_NO_CPUID - #endif - - #if _MSC_VER >= 1600 - static MAL_INLINE unsigned __int64 mal_xgetbv(int reg) - { - return _xgetbv(reg); - } - #else - #define MAL_NO_XGETBV - #endif - #elif (defined(__GNUC__) || defined(__clang__)) && !defined(MAL_ANDROID) - static MAL_INLINE void mal_cpuid(int info[4], int fid) - { - // It looks like the -fPIC option uses the ebx register which GCC complains about. We can work around this by just using a different register, the - // specific register of which I'm letting the compiler decide on. The "k" prefix is used to specify a 32-bit register. The {...} syntax is for - // supporting different assembly dialects. - // - // What's basically happening is that we're saving and restoring the ebx register manually. - #if defined(DRFLAC_X86) && defined(__PIC__) - __asm__ __volatile__ ( - "xchg{l} {%%}ebx, %k1;" - "cpuid;" - "xchg{l} {%%}ebx, %k1;" - : "=a"(info[0]), "=&r"(info[1]), "=c"(info[2]), "=d"(info[3]) : "a"(fid), "c"(0) - ); - #else - __asm__ __volatile__ ( - "cpuid" : "=a"(info[0]), "=b"(info[1]), "=c"(info[2]), "=d"(info[3]) : "a"(fid), "c"(0) - ); - #endif - } - - static MAL_INLINE unsigned long long mal_xgetbv(int reg) - { - unsigned int hi; - unsigned int lo; - - __asm__ __volatile__ ( - "xgetbv" : "=a"(lo), "=d"(hi) : "c"(reg) - ); - - return ((unsigned long long)hi << 32ULL) | (unsigned long long)lo; - } - #else - #define MAL_NO_CPUID - #define MAL_NO_XGETBV - #endif -#else - #define MAL_NO_CPUID - #define MAL_NO_XGETBV -#endif - -static MAL_INLINE mal_bool32 mal_has_sse2() -{ -#if defined(MAL_SUPPORT_SSE2) - #if (defined(MAL_X64) || defined(MAL_X86)) && !defined(MAL_NO_SSE2) - #if defined(MAL_X64) - return MAL_TRUE; // 64-bit targets always support SSE2. - #elif (defined(_M_IX86_FP) && _M_IX86_FP == 2) || defined(__SSE2__) - return MAL_TRUE; // If the compiler is allowed to freely generate SSE2 code we can assume support. - #else - #if defined(MAL_NO_CPUID) - return MAL_FALSE; - #else - int info[4]; - mal_cpuid(info, 1); - return (info[3] & (1 << 26)) != 0; - #endif - #endif - #else - return MAL_FALSE; // SSE2 is only supported on x86 and x64 architectures. - #endif -#else - return MAL_FALSE; // No compiler support. -#endif -} - -#if 0 -static MAL_INLINE mal_bool32 mal_has_avx() -{ -#if defined(MAL_SUPPORT_AVX) - #if (defined(MAL_X64) || defined(MAL_X86)) && !defined(MAL_NO_AVX) - #if defined(_AVX_) || defined(__AVX__) - return MAL_TRUE; // If the compiler is allowed to freely generate AVX code we can assume support. - #else - // AVX requires both CPU and OS support. - #if defined(MAL_NO_CPUID) || defined(MAL_NO_XGETBV) - return MAL_FALSE; - #else - int info[4]; - mal_cpuid(info, 1); - if (((info[2] & (1 << 27)) != 0) && ((info[2] & (1 << 28)) != 0)) { - mal_uint64 xrc = mal_xgetbv(0); - if ((xrc & 0x06) == 0x06) { - return MAL_TRUE; - } else { - return MAL_FALSE; - } - } else { - return MAL_FALSE; - } - #endif - #endif - #else - return MAL_FALSE; // AVX is only supported on x86 and x64 architectures. - #endif -#else - return MAL_FALSE; // No compiler support. -#endif -} -#endif - -static MAL_INLINE mal_bool32 mal_has_avx2() -{ -#if defined(MAL_SUPPORT_AVX2) - #if (defined(MAL_X64) || defined(MAL_X86)) && !defined(MAL_NO_AVX2) - #if defined(_AVX2_) || defined(__AVX2__) - return MAL_TRUE; // If the compiler is allowed to freely generate AVX2 code we can assume support. - #else - // AVX2 requires both CPU and OS support. - #if defined(MAL_NO_CPUID) || defined(MAL_NO_XGETBV) - return MAL_FALSE; - #else - int info1[4]; - int info7[4]; - mal_cpuid(info1, 1); - mal_cpuid(info7, 7); - if (((info1[2] & (1 << 27)) != 0) && ((info7[1] & (1 << 5)) != 0)) { - mal_uint64 xrc = mal_xgetbv(0); - if ((xrc & 0x06) == 0x06) { - return MAL_TRUE; - } else { - return MAL_FALSE; - } - } else { - return MAL_FALSE; - } - #endif - #endif - #else - return MAL_FALSE; // AVX2 is only supported on x86 and x64 architectures. - #endif -#else - return MAL_FALSE; // No compiler support. -#endif -} - -static MAL_INLINE mal_bool32 mal_has_avx512f() -{ -#if defined(MAL_SUPPORT_AVX512) - #if (defined(MAL_X64) || defined(MAL_X86)) && !defined(MAL_NO_AVX512) - #if defined(__AVX512F__) - return MAL_TRUE; // If the compiler is allowed to freely generate AVX-512F code we can assume support. - #else - // AVX-512 requires both CPU and OS support. - #if defined(MAL_NO_CPUID) || defined(MAL_NO_XGETBV) - return MAL_FALSE; - #else - int info1[4]; - int info7[4]; - mal_cpuid(info1, 1); - mal_cpuid(info7, 7); - if (((info1[2] & (1 << 27)) != 0) && ((info7[1] & (1 << 16)) != 0)) { - mal_uint64 xrc = mal_xgetbv(0); - if ((xrc & 0xE6) == 0xE6) { - return MAL_TRUE; - } else { - return MAL_FALSE; - } - } else { - return MAL_FALSE; - } - #endif - #endif - #else - return MAL_FALSE; // AVX-512F is only supported on x86 and x64 architectures. - #endif -#else - return MAL_FALSE; // No compiler support. -#endif -} - -static MAL_INLINE mal_bool32 mal_has_neon() -{ -#if defined(MAL_SUPPORT_NEON) - #if defined(MAL_ARM) && !defined(MAL_NO_NEON) - #if (defined(__ARM_NEON) || defined(__aarch64__) || defined(_M_ARM64)) - return MAL_TRUE; // If the compiler is allowed to freely generate NEON code we can assume support. - #else - // TODO: Runtime check. - return MAL_FALSE; - #endif - #else - return MAL_FALSE; // NEON is only supported on ARM architectures. - #endif -#else - return MAL_FALSE; // No compiler support. -#endif -} - - -static MAL_INLINE mal_bool32 mal_is_little_endian() -{ -#if defined(MAL_X86) || defined(MAL_X64) - return MAL_TRUE; -#else - int n = 1; - return (*(char*)&n) == 1; -#endif -} - -static MAL_INLINE mal_bool32 mal_is_big_endian() -{ - return !mal_is_little_endian(); -} - - -#ifndef MAL_COINIT_VALUE -#define MAL_COINIT_VALUE 0 /* 0 = COINIT_MULTITHREADED*/ -#endif - - - -#ifndef MAL_PI -#define MAL_PI 3.14159265358979323846264f -#endif -#ifndef MAL_PI_D -#define MAL_PI_D 3.14159265358979323846264 -#endif -#ifndef MAL_TAU -#define MAL_TAU 6.28318530717958647693f -#endif -#ifndef MAL_TAU_D -#define MAL_TAU_D 6.28318530717958647693 -#endif - - -// The default format when mal_format_unknown (0) is requested when initializing a device. -#ifndef MAL_DEFAULT_FORMAT -#define MAL_DEFAULT_FORMAT mal_format_f32 -#endif - -// The default channel count to use when 0 is used when initializing a device. -#ifndef MAL_DEFAULT_CHANNELS -#define MAL_DEFAULT_CHANNELS 2 -#endif - -// The default sample rate to use when 0 is used when initializing a device. -#ifndef MAL_DEFAULT_SAMPLE_RATE -#define MAL_DEFAULT_SAMPLE_RATE 48000 -#endif - -// Default periods when none is specified in mal_device_init(). More periods means more work on the CPU. -#ifndef MAL_DEFAULT_PERIODS -#define MAL_DEFAULT_PERIODS 2 -#endif - -// The base buffer size in milliseconds for low latency mode. -#ifndef MAL_BASE_BUFFER_SIZE_IN_MILLISECONDS_LOW_LATENCY -#define MAL_BASE_BUFFER_SIZE_IN_MILLISECONDS_LOW_LATENCY 25 -#endif - -// The base buffer size in milliseconds for conservative mode. -#ifndef MAL_BASE_BUFFER_SIZE_IN_MILLISECONDS_CONSERVATIVE -#define MAL_BASE_BUFFER_SIZE_IN_MILLISECONDS_CONSERVATIVE 150 -#endif - - -// Standard sample rates, in order of priority. -mal_uint32 g_malStandardSampleRatePriorities[] = { - MAL_SAMPLE_RATE_48000, // Most common - MAL_SAMPLE_RATE_44100, - - MAL_SAMPLE_RATE_32000, // Lows - MAL_SAMPLE_RATE_24000, - MAL_SAMPLE_RATE_22050, - - MAL_SAMPLE_RATE_88200, // Highs - MAL_SAMPLE_RATE_96000, - MAL_SAMPLE_RATE_176400, - MAL_SAMPLE_RATE_192000, - - MAL_SAMPLE_RATE_16000, // Extreme lows - MAL_SAMPLE_RATE_11025, - MAL_SAMPLE_RATE_8000, - - MAL_SAMPLE_RATE_352800, // Extreme highs - MAL_SAMPLE_RATE_384000 -}; - -mal_format g_malFormatPriorities[] = { - mal_format_s16, // Most common - mal_format_f32, - - //mal_format_s24_32, // Clean alignment - mal_format_s32, - - mal_format_s24, // Unclean alignment - - mal_format_u8 // Low quality -}; - - - -/////////////////////////////////////////////////////////////////////////////// -// -// Standard Library Stuff -// -/////////////////////////////////////////////////////////////////////////////// -#ifndef MAL_MALLOC -#ifdef MAL_WIN32 -#define MAL_MALLOC(sz) HeapAlloc(GetProcessHeap(), 0, (sz)) -#else -#define MAL_MALLOC(sz) malloc((sz)) -#endif -#endif - -#ifndef MAL_REALLOC -#ifdef MAL_WIN32 -#define MAL_REALLOC(p, sz) (((sz) > 0) ? ((p) ? HeapReAlloc(GetProcessHeap(), 0, (p), (sz)) : HeapAlloc(GetProcessHeap(), 0, (sz))) : ((VOID*)(size_t)(HeapFree(GetProcessHeap(), 0, (p)) & 0))) -#else -#define MAL_REALLOC(p, sz) realloc((p), (sz)) -#endif -#endif - -#ifndef MAL_FREE -#ifdef MAL_WIN32 -#define MAL_FREE(p) HeapFree(GetProcessHeap(), 0, (p)) -#else -#define MAL_FREE(p) free((p)) -#endif -#endif - -#ifndef MAL_ZERO_MEMORY -#ifdef MAL_WIN32 -#define MAL_ZERO_MEMORY(p, sz) ZeroMemory((p), (sz)) -#else -#define MAL_ZERO_MEMORY(p, sz) memset((p), 0, (sz)) -#endif -#endif - -#ifndef MAL_COPY_MEMORY -#ifdef MAL_WIN32 -#define MAL_COPY_MEMORY(dst, src, sz) CopyMemory((dst), (src), (sz)) -#else -#define MAL_COPY_MEMORY(dst, src, sz) memcpy((dst), (src), (sz)) -#endif -#endif - -#ifndef MAL_ASSERT -#ifdef MAL_WIN32 -#define MAL_ASSERT(condition) assert(condition) -#else -#define MAL_ASSERT(condition) assert(condition) -#endif -#endif - -#define mal_zero_memory MAL_ZERO_MEMORY -#define mal_copy_memory MAL_COPY_MEMORY -#define mal_assert MAL_ASSERT - -#define mal_zero_object(p) mal_zero_memory((p), sizeof(*(p))) -#define mal_countof(x) (sizeof(x) / sizeof(x[0])) -#define mal_max(x, y) (((x) > (y)) ? (x) : (y)) -#define mal_min(x, y) (((x) < (y)) ? (x) : (y)) -#define mal_clamp(x, lo, hi) (mal_max(lo, mal_min(x, hi))) -#define mal_offset_ptr(p, offset) (((mal_uint8*)(p)) + (offset)) - -#define mal_buffer_frame_capacity(buffer, channels, format) (sizeof(buffer) / mal_get_bytes_per_sample(format) / (channels)) - - -// Return Values: -// 0: Success -// 22: EINVAL -// 34: ERANGE -// -// Not using symbolic constants for errors because I want to avoid #including errno.h -int mal_strcpy_s(char* dst, size_t dstSizeInBytes, const char* src) -{ - if (dst == 0) { - return 22; - } - if (dstSizeInBytes == 0) { - return 34; - } - if (src == 0) { - dst[0] = '\0'; - return 22; - } - - size_t i; - for (i = 0; i < dstSizeInBytes && src[i] != '\0'; ++i) { - dst[i] = src[i]; - } - - if (i < dstSizeInBytes) { - dst[i] = '\0'; - return 0; - } - - dst[0] = '\0'; - return 34; -} - -int mal_strncpy_s(char* dst, size_t dstSizeInBytes, const char* src, size_t count) -{ - if (dst == 0) { - return 22; - } - if (dstSizeInBytes == 0) { - return 34; - } - if (src == 0) { - dst[0] = '\0'; - return 22; - } - - size_t maxcount = count; - if (count == ((size_t)-1) || count >= dstSizeInBytes) { // -1 = _TRUNCATE - maxcount = dstSizeInBytes - 1; - } - - size_t i; - for (i = 0; i < maxcount && src[i] != '\0'; ++i) { - dst[i] = src[i]; - } - - if (src[i] == '\0' || i == count || count == ((size_t)-1)) { - dst[i] = '\0'; - return 0; - } - - dst[0] = '\0'; - return 34; -} - -int mal_strcat_s(char* dst, size_t dstSizeInBytes, const char* src) -{ - if (dst == 0) { - return 22; - } - if (dstSizeInBytes == 0) { - return 34; - } - if (src == 0) { - dst[0] = '\0'; - return 22; - } - - char* dstorig = dst; - - while (dstSizeInBytes > 0 && dst[0] != '\0') { - dst += 1; - dstSizeInBytes -= 1; - } - - if (dstSizeInBytes == 0) { - return 22; // Unterminated. - } - - - while (dstSizeInBytes > 0 && src[0] != '\0') { - *dst++ = *src++; - dstSizeInBytes -= 1; - } - - if (dstSizeInBytes > 0) { - dst[0] = '\0'; - } else { - dstorig[0] = '\0'; - return 34; - } - - return 0; -} - -int mal_itoa_s(int value, char* dst, size_t dstSizeInBytes, int radix) -{ - if (dst == NULL || dstSizeInBytes == 0) { - return 22; - } - if (radix < 2 || radix > 36) { - dst[0] = '\0'; - return 22; - } - - int sign = (value < 0 && radix == 10) ? -1 : 1; // The negative sign is only used when the base is 10. - - unsigned int valueU; - if (value < 0) { - valueU = -value; - } else { - valueU = value; - } - - char* dstEnd = dst; - do - { - int remainder = valueU % radix; - if (remainder > 9) { - *dstEnd = (char)((remainder - 10) + 'a'); - } else { - *dstEnd = (char)(remainder + '0'); - } - - dstEnd += 1; - dstSizeInBytes -= 1; - valueU /= radix; - } while (dstSizeInBytes > 0 && valueU > 0); - - if (dstSizeInBytes == 0) { - dst[0] = '\0'; - return 22; // Ran out of room in the output buffer. - } - - if (sign < 0) { - *dstEnd++ = '-'; - dstSizeInBytes -= 1; - } - - if (dstSizeInBytes == 0) { - dst[0] = '\0'; - return 22; // Ran out of room in the output buffer. - } - - *dstEnd = '\0'; - - - // At this point the string will be reversed. - dstEnd -= 1; - while (dst < dstEnd) { - char temp = *dst; - *dst = *dstEnd; - *dstEnd = temp; - - dst += 1; - dstEnd -= 1; - } - - return 0; -} - -int mal_strcmp(const char* str1, const char* str2) -{ - if (str1 == str2) return 0; - - // These checks differ from the standard implementation. It's not important, but I prefer - // it just for sanity. - if (str1 == NULL) return -1; - if (str2 == NULL) return 1; - - for (;;) { - if (str1[0] == '\0') { - break; - } - if (str1[0] != str2[0]) { - break; - } - - str1 += 1; - str2 += 1; - } - - return ((unsigned char*)str1)[0] - ((unsigned char*)str2)[0]; -} - - -// Thanks to good old Bit Twiddling Hacks for this one: http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 -static MAL_INLINE unsigned int mal_next_power_of_2(unsigned int x) -{ - x--; - x |= x >> 1; - x |= x >> 2; - x |= x >> 4; - x |= x >> 8; - x |= x >> 16; - x++; - - return x; -} - -static MAL_INLINE unsigned int mal_prev_power_of_2(unsigned int x) -{ - return mal_next_power_of_2(x) >> 1; -} - -static MAL_INLINE unsigned int mal_round_to_power_of_2(unsigned int x) -{ - unsigned int prev = mal_prev_power_of_2(x); - unsigned int next = mal_next_power_of_2(x); - if ((next - x) > (x - prev)) { - return prev; - } else { - return next; - } -} - -static MAL_INLINE unsigned int mal_count_set_bits(unsigned int x) -{ - unsigned int count = 0; - while (x != 0) { - if (x & 1) { - count += 1; - } - - x = x >> 1; - } - - return count; -} - - - -// Clamps an f32 sample to -1..1 -static MAL_INLINE float mal_clip_f32(float x) -{ - if (x < -1) return -1; - if (x > +1) return +1; - return x; -} - -static MAL_INLINE float mal_mix_f32(float x, float y, float a) -{ - return x*(1-a) + y*a; -} -static MAL_INLINE float mal_mix_f32_fast(float x, float y, float a) -{ - float r0 = (y - x); - float r1 = r0*a; - return x + r1; - //return x + (y - x)*a; -} - -#if defined(MAL_SUPPORT_SSE2) -static MAL_INLINE __m128 mal_mix_f32_fast__sse2(__m128 x, __m128 y, __m128 a) -{ - return _mm_add_ps(x, _mm_mul_ps(_mm_sub_ps(y, x), a)); -} -#endif -#if defined(MAL_SUPPORT_AVX2) -static MAL_INLINE __m256 mal_mix_f32_fast__avx2(__m256 x, __m256 y, __m256 a) -{ - return _mm256_add_ps(x, _mm256_mul_ps(_mm256_sub_ps(y, x), a)); -} -#endif -#if defined(MAL_SUPPORT_AVX512) -static MAL_INLINE __m512 mal_mix_f32_fast__avx512(__m512 x, __m512 y, __m512 a) -{ - return _mm512_add_ps(x, _mm512_mul_ps(_mm512_sub_ps(y, x), a)); -} -#endif -#if defined(MAL_SUPPORT_NEON) -static MAL_INLINE float32x4_t mal_mix_f32_fast__neon(float32x4_t x, float32x4_t y, float32x4_t a) -{ - return vaddq_f32(x, vmulq_f32(vsubq_f32(y, x), a)); -} -#endif - - -static MAL_INLINE double mal_mix_f64(double x, double y, double a) -{ - return x*(1-a) + y*a; -} -static MAL_INLINE double mal_mix_f64_fast(double x, double y, double a) -{ - return x + (y - x)*a; -} - -static MAL_INLINE float mal_scale_to_range_f32(float x, float lo, float hi) -{ - return lo + x*(hi-lo); -} - - - -// Random Number Generation -// -// mini_al uses the LCG random number generation algorithm. This is good enough for audio. -// -// Note that mini_al's LCG implementation uses global state which is _not_ thread-local. When this is called across -// multiple threads, results will be unpredictable. However, it won't crash and results will still be random enough -// for mini_al's purposes. -#define MAL_LCG_M 4294967296 -#define MAL_LCG_A 1103515245 -#define MAL_LCG_C 12345 -static mal_int32 g_malLCG; - -void mal_seed(mal_int32 seed) -{ - g_malLCG = seed; -} - -mal_int32 mal_rand_s32() -{ - mal_int32 lcg = g_malLCG; - mal_int32 r = (MAL_LCG_A * lcg + MAL_LCG_C) % MAL_LCG_M; - g_malLCG = r; - return r; -} - -double mal_rand_f64() -{ - return (mal_rand_s32() + 0x80000000) / (double)0x7FFFFFFF; -} - -float mal_rand_f32() -{ - return (float)mal_rand_f64(); -} - -static MAL_INLINE float mal_rand_range_f32(float lo, float hi) -{ - return mal_scale_to_range_f32(mal_rand_f32(), lo, hi); -} - -static MAL_INLINE mal_int32 mal_rand_range_s32(mal_int32 lo, mal_int32 hi) -{ - double x = mal_rand_f64(); - return lo + (mal_int32)(x*(hi-lo)); -} - - -static MAL_INLINE float mal_dither_f32_rectangle(float ditherMin, float ditherMax) -{ - return mal_rand_range_f32(ditherMin, ditherMax); -} - -static MAL_INLINE float mal_dither_f32_triangle(float ditherMin, float ditherMax) -{ - float a = mal_rand_range_f32(ditherMin, 0); - float b = mal_rand_range_f32(0, ditherMax); - return a + b; -} - -static MAL_INLINE float mal_dither_f32(mal_dither_mode ditherMode, float ditherMin, float ditherMax) -{ - if (ditherMode == mal_dither_mode_rectangle) { - return mal_dither_f32_rectangle(ditherMin, ditherMax); - } - if (ditherMode == mal_dither_mode_triangle) { - return mal_dither_f32_triangle(ditherMin, ditherMax); - } - - return 0; -} - -static MAL_INLINE mal_int32 mal_dither_s32(mal_dither_mode ditherMode, mal_int32 ditherMin, mal_int32 ditherMax) -{ - if (ditherMode == mal_dither_mode_rectangle) { - mal_int32 a = mal_rand_range_s32(ditherMin, ditherMax); - return a; - } - if (ditherMode == mal_dither_mode_triangle) { - mal_int32 a = mal_rand_range_s32(ditherMin, 0); - mal_int32 b = mal_rand_range_s32(0, ditherMax); - return a + b; - } - - return 0; -} - - -// Splits a buffer into parts of equal length and of the given alignment. The returned size of the split buffers will be a -// multiple of the alignment. The alignment must be a power of 2. -void mal_split_buffer(void* pBuffer, size_t bufferSize, size_t splitCount, size_t alignment, void** ppBuffersOut, size_t* pSplitSizeOut) -{ - if (pSplitSizeOut) { - *pSplitSizeOut = 0; - } - - if (pBuffer == NULL || bufferSize == 0 || splitCount == 0) { - return; - } - - if (alignment == 0) { - alignment = 1; - } - - mal_uintptr pBufferUnaligned = (mal_uintptr)pBuffer; - mal_uintptr pBufferAligned = (pBufferUnaligned + (alignment-1)) & ~(alignment-1); - size_t unalignedBytes = (size_t)(pBufferAligned - pBufferUnaligned); - - size_t splitSize = 0; - if (bufferSize >= unalignedBytes) { - splitSize = (bufferSize - unalignedBytes) / splitCount; - splitSize = splitSize & ~(alignment-1); - } - - if (ppBuffersOut != NULL) { - for (size_t i = 0; i < splitCount; ++i) { - ppBuffersOut[i] = (mal_uint8*)(pBufferAligned + (splitSize*i)); - } - } - - if (pSplitSizeOut) { - *pSplitSizeOut = splitSize; - } -} - - -/////////////////////////////////////////////////////////////////////////////// -// -// Atomics -// -/////////////////////////////////////////////////////////////////////////////// -#if defined(_WIN32) && !defined(__GNUC__) -#define mal_memory_barrier() MemoryBarrier() -#define mal_atomic_exchange_32(a, b) InterlockedExchange((LONG*)a, (LONG)b) -#define mal_atomic_exchange_64(a, b) InterlockedExchange64((LONGLONG*)a, (LONGLONG)b) -#define mal_atomic_increment_32(a) InterlockedIncrement((LONG*)a) -#define mal_atomic_decrement_32(a) InterlockedDecrement((LONG*)a) -#else -#define mal_memory_barrier() __sync_synchronize() -#define mal_atomic_exchange_32(a, b) (void)__sync_lock_test_and_set(a, b); __sync_synchronize() -#define mal_atomic_exchange_64(a, b) (void)__sync_lock_test_and_set(a, b); __sync_synchronize() -#define mal_atomic_increment_32(a) __sync_add_and_fetch(a, 1) -#define mal_atomic_decrement_32(a) __sync_sub_and_fetch(a, 1) -#endif - -#ifdef MAL_64BIT -#define mal_atomic_exchange_ptr mal_atomic_exchange_64 -#endif -#ifdef MAL_32BIT -#define mal_atomic_exchange_ptr mal_atomic_exchange_32 -#endif - - -mal_uint32 mal_get_standard_sample_rate_priority_index(mal_uint32 sampleRate) // Lower = higher priority -{ - for (mal_uint32 i = 0; i < mal_countof(g_malStandardSampleRatePriorities); ++i) { - if (g_malStandardSampleRatePriorities[i] == sampleRate) { - return i; - } - } - - return (mal_uint32)-1; -} - - -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// DEVICE I/O -// ========== -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -#ifndef MAL_NO_DEVICE_IO -// Unfortunately using runtime linking for pthreads causes problems. This has occurred for me when testing on FreeBSD. When -// using runtime linking, deadlocks can occur (for me it happens when loading data from fread()). It turns out that doing -// compile-time linking fixes this. I'm not sure why this happens, but the safest way I can think of to fix this is to simply -// disable runtime linking by default. To enable runtime linking, #define this before the implementation of this file. I am -// not officially supporting this, but I'm leaving it here in case it's useful for somebody, somewhere. -//#define MAL_USE_RUNTIME_LINKING_FOR_PTHREAD - -// Disable run-time linking on certain backends. -#ifndef MAL_NO_RUNTIME_LINKING - #if defined(MAL_ANDROID) || defined(MAL_EMSCRIPTEN) - #define MAL_NO_RUNTIME_LINKING - #endif -#endif - -// Check if we have the necessary development packages for each backend at the top so we can use this to determine whether or not -// certain unused functions and variables can be excluded from the build to avoid warnings. -#ifdef MAL_ENABLE_WASAPI - #define MAL_HAS_WASAPI // Every compiler should support WASAPI -#endif -#ifdef MAL_ENABLE_DSOUND - #define MAL_HAS_DSOUND // Every compiler should support DirectSound. -#endif -#ifdef MAL_ENABLE_WINMM - #define MAL_HAS_WINMM // Every compiler I'm aware of supports WinMM. -#endif -#ifdef MAL_ENABLE_ALSA - #define MAL_HAS_ALSA - #ifdef MAL_NO_RUNTIME_LINKING - #ifdef __has_include - #if !__has_include() - #undef MAL_HAS_ALSA - #endif - #endif - #endif -#endif -#ifdef MAL_ENABLE_PULSEAUDIO - #define MAL_HAS_PULSEAUDIO // Development packages are unnecessary for PulseAudio. - #ifdef MAL_NO_RUNTIME_LINKING - #ifdef __has_include - #if !__has_include() - #undef MAL_HAS_PULSEAUDIO - #endif - #endif - #endif -#endif -#ifdef MAL_ENABLE_JACK - #define MAL_HAS_JACK - #ifdef MAL_NO_RUNTIME_LINKING - #ifdef __has_include - #if !__has_include() - #undef MAL_HAS_JACK - #endif - #endif - #endif -#endif -#ifdef MAL_ENABLE_COREAUDIO - #define MAL_HAS_COREAUDIO -#endif -#ifdef MAL_ENABLE_SNDIO - #define MAL_HAS_SNDIO -#endif -#ifdef MAL_ENABLE_AUDIO4 - #define MAL_HAS_AUDIO4 // When enabled, always assume audio(4) is available. -#endif -#ifdef MAL_ENABLE_OSS - #define MAL_HAS_OSS -#endif -#ifdef MAL_ENABLE_AAUDIO - #define MAL_HAS_AAUDIO -#endif -#ifdef MAL_ENABLE_OPENSL - #define MAL_HAS_OPENSL // OpenSL is the only supported backend for Android. It must be present. -#endif -#ifdef MAL_ENABLE_WEBAUDIO - #define MAL_HAS_WEBAUDIO -#endif -#ifdef MAL_ENABLE_OPENAL - #define MAL_HAS_OPENAL - #ifdef MAL_NO_RUNTIME_LINKING - #ifdef __has_include - #if !__has_include() - #undef MAL_HAS_OPENAL - #endif - #endif - #endif -#endif -#ifdef MAL_ENABLE_SDL - #define MAL_HAS_SDL - - // SDL headers are necessary if using compile-time linking. - #ifdef MAL_NO_RUNTIME_LINKING - #ifdef __has_include - #ifdef MAL_EMSCRIPTEN - #if !__has_include() - #undef MAL_HAS_SDL - #endif - #else - #if !__has_include() - #undef MAL_HAS_SDL - #endif - #endif - #endif - #endif -#endif -#ifdef MAL_ENABLE_NULL - #define MAL_HAS_NULL // Everything supports the null backend. -#endif - -const mal_backend g_malDefaultBackends[] = { - mal_backend_wasapi, - mal_backend_dsound, - mal_backend_winmm, - mal_backend_coreaudio, - mal_backend_sndio, - mal_backend_audio4, - mal_backend_oss, - mal_backend_pulseaudio, - mal_backend_alsa, - mal_backend_jack, - mal_backend_aaudio, - mal_backend_opensl, - mal_backend_webaudio, - mal_backend_openal, - mal_backend_sdl, - mal_backend_null -}; - -const char* mal_get_backend_name(mal_backend backend) -{ - switch (backend) - { - case mal_backend_null: return "Null"; - case mal_backend_wasapi: return "WASAPI"; - case mal_backend_dsound: return "DirectSound"; - case mal_backend_winmm: return "WinMM"; - case mal_backend_alsa: return "ALSA"; - case mal_backend_pulseaudio: return "PulseAudio"; - case mal_backend_jack: return "JACK"; - case mal_backend_coreaudio: return "Core Audio"; - case mal_backend_sndio: return "sndio"; - case mal_backend_audio4: return "audio(4)"; - case mal_backend_oss: return "OSS"; - case mal_backend_aaudio: return "AAudio"; - case mal_backend_opensl: return "OpenSL|ES"; - case mal_backend_webaudio: return "Web Audio"; - case mal_backend_openal: return "OpenAL"; - case mal_backend_sdl: return "SDL"; - default: return "Unknown"; - } -} - - - -#ifdef MAL_WIN32 - #define MAL_THREADCALL WINAPI - typedef unsigned long mal_thread_result; -#else - #define MAL_THREADCALL - typedef void* mal_thread_result; -#endif -typedef mal_thread_result (MAL_THREADCALL * mal_thread_entry_proc)(void* pData); - -#ifdef MAL_WIN32 -typedef HRESULT (WINAPI * MAL_PFN_CoInitializeEx)(LPVOID pvReserved, DWORD dwCoInit); -typedef void (WINAPI * MAL_PFN_CoUninitialize)(); -typedef HRESULT (WINAPI * MAL_PFN_CoCreateInstance)(REFCLSID rclsid, LPUNKNOWN pUnkOuter, DWORD dwClsContext, REFIID riid, LPVOID *ppv); -typedef void (WINAPI * MAL_PFN_CoTaskMemFree)(LPVOID pv); -typedef HRESULT (WINAPI * MAL_PFN_PropVariantClear)(PROPVARIANT *pvar); -typedef int (WINAPI * MAL_PFN_StringFromGUID2)(const GUID* const rguid, LPOLESTR lpsz, int cchMax); - -typedef HWND (WINAPI * MAL_PFN_GetForegroundWindow)(); -typedef HWND (WINAPI * MAL_PFN_GetDesktopWindow)(); - -// Microsoft documents these APIs as returning LSTATUS, but the Win32 API shipping with some compilers do not define it. It's just a LONG. -typedef LONG (WINAPI * MAL_PFN_RegOpenKeyExA)(HKEY hKey, LPCSTR lpSubKey, DWORD ulOptions, REGSAM samDesired, PHKEY phkResult); -typedef LONG (WINAPI * MAL_PFN_RegCloseKey)(HKEY hKey); -typedef LONG (WINAPI * MAL_PFN_RegQueryValueExA)(HKEY hKey, LPCSTR lpValueName, LPDWORD lpReserved, LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData); -#endif - - -#define MAL_STATE_UNINITIALIZED 0 -#define MAL_STATE_STOPPED 1 // The device's default state after initialization. -#define MAL_STATE_STARTED 2 // The worker thread is in it's main loop waiting for the driver to request or deliver audio data. -#define MAL_STATE_STARTING 3 // Transitioning from a stopped state to started. -#define MAL_STATE_STOPPING 4 // Transitioning from a started state to stopped. - -#define MAL_DEFAULT_PLAYBACK_DEVICE_NAME "Default Playback Device" -#define MAL_DEFAULT_CAPTURE_DEVICE_NAME "Default Capture Device" - - -/////////////////////////////////////////////////////////////////////////////// -// -// Timing -// -/////////////////////////////////////////////////////////////////////////////// -#ifdef MAL_WIN32 -LARGE_INTEGER g_mal_TimerFrequency = {{0}}; -void mal_timer_init(mal_timer* pTimer) -{ - if (g_mal_TimerFrequency.QuadPart == 0) { - QueryPerformanceFrequency(&g_mal_TimerFrequency); - } - - LARGE_INTEGER counter; - QueryPerformanceCounter(&counter); - pTimer->counter = counter.QuadPart; -} - -double mal_timer_get_time_in_seconds(mal_timer* pTimer) -{ - LARGE_INTEGER counter; - if (!QueryPerformanceCounter(&counter)) { - return 0; - } - - return (double)(counter.QuadPart - pTimer->counter) / g_mal_TimerFrequency.QuadPart; -} -#elif defined(MAL_APPLE) && (__MAC_OS_X_VERSION_MIN_REQUIRED < 101200) -mal_uint64 g_mal_TimerFrequency = 0; -void mal_timer_init(mal_timer* pTimer) -{ - mach_timebase_info_data_t baseTime; - mach_timebase_info(&baseTime); - g_mal_TimerFrequency = (baseTime.denom * 1e9) / baseTime.numer; - - pTimer->counter = mach_absolute_time(); -} - -double mal_timer_get_time_in_seconds(mal_timer* pTimer) -{ - mal_uint64 newTimeCounter = mach_absolute_time(); - mal_uint64 oldTimeCounter = pTimer->counter; - - return (newTimeCounter - oldTimeCounter) / g_mal_TimerFrequency; -} -#elif defined(MAL_EMSCRIPTEN) -void mal_timer_init(mal_timer* pTimer) -{ - pTimer->counterD = emscripten_get_now(); -} - -double mal_timer_get_time_in_seconds(mal_timer* pTimer) -{ - return (emscripten_get_now() - pTimer->counterD) / 1000; /* Emscripten is in milliseconds. */ -} -#else -#if defined(CLOCK_MONOTONIC) - #define MAL_CLOCK_ID CLOCK_MONOTONIC -#else - #define MAL_CLOCK_ID CLOCK_REALTIME -#endif - -void mal_timer_init(mal_timer* pTimer) -{ - struct timespec newTime; - clock_gettime(MAL_CLOCK_ID, &newTime); - - pTimer->counter = (newTime.tv_sec * 1000000000) + newTime.tv_nsec; -} - -double mal_timer_get_time_in_seconds(mal_timer* pTimer) -{ - struct timespec newTime; - clock_gettime(MAL_CLOCK_ID, &newTime); - - mal_uint64 newTimeCounter = (newTime.tv_sec * 1000000000) + newTime.tv_nsec; - mal_uint64 oldTimeCounter = pTimer->counter; - - return (newTimeCounter - oldTimeCounter) / 1000000000.0; -} -#endif - - -/////////////////////////////////////////////////////////////////////////////// -// -// Dynamic Linking -// -/////////////////////////////////////////////////////////////////////////////// -mal_handle mal_dlopen(const char* filename) -{ -#ifdef _WIN32 -#ifdef MAL_WIN32_DESKTOP - return (mal_handle)LoadLibraryA(filename); -#else - // *sigh* It appears there is no ANSI version of LoadPackagedLibrary()... - WCHAR filenameW[4096]; - if (MultiByteToWideChar(CP_UTF8, 0, filename, -1, filenameW, sizeof(filenameW)) == 0) { - return NULL; - } - - return (mal_handle)LoadPackagedLibrary(filenameW, 0); -#endif -#else - return (mal_handle)dlopen(filename, RTLD_NOW); -#endif -} - -void mal_dlclose(mal_handle handle) -{ -#ifdef _WIN32 - FreeLibrary((HMODULE)handle); -#else - dlclose((void*)handle); -#endif -} - -mal_proc mal_dlsym(mal_handle handle, const char* symbol) -{ -#ifdef _WIN32 - return (mal_proc)GetProcAddress((HMODULE)handle, symbol); -#else - return (mal_proc)dlsym((void*)handle, symbol); -#endif -} - - -/////////////////////////////////////////////////////////////////////////////// -// -// Threading -// -/////////////////////////////////////////////////////////////////////////////// -#ifdef MAL_WIN32 -int mal_thread_priority_to_win32(mal_thread_priority priority) -{ - switch (priority) { - case mal_thread_priority_idle: return THREAD_PRIORITY_IDLE; - case mal_thread_priority_lowest: return THREAD_PRIORITY_LOWEST; - case mal_thread_priority_low: return THREAD_PRIORITY_BELOW_NORMAL; - case mal_thread_priority_normal: return THREAD_PRIORITY_NORMAL; - case mal_thread_priority_high: return THREAD_PRIORITY_ABOVE_NORMAL; - case mal_thread_priority_highest: return THREAD_PRIORITY_HIGHEST; - case mal_thread_priority_realtime: return THREAD_PRIORITY_TIME_CRITICAL; - default: return mal_thread_priority_normal; - } -} - -mal_result mal_thread_create__win32(mal_context* pContext, mal_thread* pThread, mal_thread_entry_proc entryProc, void* pData) -{ - pThread->win32.hThread = CreateThread(NULL, 0, entryProc, pData, 0, NULL); - if (pThread->win32.hThread == NULL) { - return MAL_FAILED_TO_CREATE_THREAD; - } - - SetThreadPriority((HANDLE)pThread->win32.hThread, mal_thread_priority_to_win32(pContext->config.threadPriority)); - - return MAL_SUCCESS; -} - -void mal_thread_wait__win32(mal_thread* pThread) -{ - WaitForSingleObject(pThread->win32.hThread, INFINITE); -} - -void mal_sleep__win32(mal_uint32 milliseconds) -{ - Sleep((DWORD)milliseconds); -} - - -mal_result mal_mutex_init__win32(mal_context* pContext, mal_mutex* pMutex) -{ - (void)pContext; - - pMutex->win32.hMutex = CreateEventA(NULL, FALSE, TRUE, NULL); - if (pMutex->win32.hMutex == NULL) { - return MAL_FAILED_TO_CREATE_MUTEX; - } - - return MAL_SUCCESS; -} - -void mal_mutex_uninit__win32(mal_mutex* pMutex) -{ - CloseHandle(pMutex->win32.hMutex); -} - -void mal_mutex_lock__win32(mal_mutex* pMutex) -{ - WaitForSingleObject(pMutex->win32.hMutex, INFINITE); -} - -void mal_mutex_unlock__win32(mal_mutex* pMutex) -{ - SetEvent(pMutex->win32.hMutex); -} - - -mal_result mal_event_init__win32(mal_context* pContext, mal_event* pEvent) -{ - (void)pContext; - - pEvent->win32.hEvent = CreateEventW(NULL, FALSE, FALSE, NULL); - if (pEvent->win32.hEvent == NULL) { - return MAL_FAILED_TO_CREATE_EVENT; - } - - return MAL_SUCCESS; -} - -void mal_event_uninit__win32(mal_event* pEvent) -{ - CloseHandle(pEvent->win32.hEvent); -} - -mal_bool32 mal_event_wait__win32(mal_event* pEvent) -{ - return WaitForSingleObject(pEvent->win32.hEvent, INFINITE) == WAIT_OBJECT_0; -} - -mal_bool32 mal_event_signal__win32(mal_event* pEvent) -{ - return SetEvent(pEvent->win32.hEvent); -} -#endif - - -#ifdef MAL_POSIX -#include - -typedef int (* mal_pthread_create_proc)(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg); -typedef int (* mal_pthread_join_proc)(pthread_t thread, void **retval); -typedef int (* mal_pthread_mutex_init_proc)(pthread_mutex_t *__mutex, const pthread_mutexattr_t *__mutexattr); -typedef int (* mal_pthread_mutex_destroy_proc)(pthread_mutex_t *__mutex); -typedef int (* mal_pthread_mutex_lock_proc)(pthread_mutex_t *__mutex); -typedef int (* mal_pthread_mutex_unlock_proc)(pthread_mutex_t *__mutex); -typedef int (* mal_pthread_cond_init_proc)(pthread_cond_t *__restrict __cond, const pthread_condattr_t *__restrict __cond_attr); -typedef int (* mal_pthread_cond_destroy_proc)(pthread_cond_t *__cond); -typedef int (* mal_pthread_cond_signal_proc)(pthread_cond_t *__cond); -typedef int (* mal_pthread_cond_wait_proc)(pthread_cond_t *__restrict __cond, pthread_mutex_t *__restrict __mutex); -typedef int (* mal_pthread_attr_init_proc)(pthread_attr_t *attr); -typedef int (* mal_pthread_attr_destroy_proc)(pthread_attr_t *attr); -typedef int (* mal_pthread_attr_setschedpolicy_proc)(pthread_attr_t *attr, int policy); -typedef int (* mal_pthread_attr_getschedparam_proc)(const pthread_attr_t *attr, struct sched_param *param); -typedef int (* mal_pthread_attr_setschedparam_proc)(pthread_attr_t *attr, const struct sched_param *param); - -mal_bool32 mal_thread_create__posix(mal_context* pContext, mal_thread* pThread, mal_thread_entry_proc entryProc, void* pData) -{ - pthread_attr_t* pAttr = NULL; - -#if !defined(__EMSCRIPTEN__) - // Try setting the thread priority. It's not critical if anything fails here. - pthread_attr_t attr; - if (((mal_pthread_attr_init_proc)pContext->posix.pthread_attr_init)(&attr) == 0) { - int scheduler = -1; - if (pContext->config.threadPriority == mal_thread_priority_idle) { -#ifdef SCHED_IDLE - if (((mal_pthread_attr_setschedpolicy_proc)pContext->posix.pthread_attr_setschedpolicy)(&attr, SCHED_IDLE) == 0) { - scheduler = SCHED_IDLE; - } -#endif - } else if (pContext->config.threadPriority == mal_thread_priority_realtime) { -#ifdef SCHED_FIFO - if (((mal_pthread_attr_setschedpolicy_proc)pContext->posix.pthread_attr_setschedpolicy)(&attr, SCHED_FIFO) == 0) { - scheduler = SCHED_FIFO; - } -#endif -#ifdef MAL_LINUX - } else { - scheduler = sched_getscheduler(0); -#endif - } - - if (scheduler != -1) { - int priorityMin = sched_get_priority_min(scheduler); - int priorityMax = sched_get_priority_max(scheduler); - int priorityStep = (priorityMax - priorityMin) / 7; // 7 = number of priorities supported by mini_al. - - struct sched_param sched; - if (((mal_pthread_attr_getschedparam_proc)pContext->posix.pthread_attr_getschedparam)(&attr, &sched) == 0) { - if (pContext->config.threadPriority == mal_thread_priority_idle) { - sched.sched_priority = priorityMin; - } else if (pContext->config.threadPriority == mal_thread_priority_realtime) { - sched.sched_priority = priorityMax; - } else { - sched.sched_priority += ((int)pContext->config.threadPriority + 5) * priorityStep; // +5 because the lowest priority is -5. - if (sched.sched_priority < priorityMin) { - sched.sched_priority = priorityMin; - } - if (sched.sched_priority > priorityMax) { - sched.sched_priority = priorityMax; - } - } - - if (((mal_pthread_attr_setschedparam_proc)pContext->posix.pthread_attr_setschedparam)(&attr, &sched) == 0) { - pAttr = &attr; - } - } - } - - ((mal_pthread_attr_destroy_proc)pContext->posix.pthread_attr_destroy)(&attr); - } -#endif - - int result = ((mal_pthread_create_proc)pContext->posix.pthread_create)(&pThread->posix.thread, pAttr, entryProc, pData); - if (result != 0) { - return MAL_FAILED_TO_CREATE_THREAD; - } - - return MAL_SUCCESS; -} - -void mal_thread_wait__posix(mal_thread* pThread) -{ - ((mal_pthread_join_proc)pThread->pContext->posix.pthread_join)(pThread->posix.thread, NULL); -} - -void mal_sleep__posix(mal_uint32 milliseconds) -{ -#ifdef MAL_EMSCRIPTEN - (void)milliseconds; - mal_assert(MAL_FALSE); /* The Emscripten build should never sleep. */ -#else - usleep(milliseconds * 1000); /* <-- usleep is in microseconds. */ -#endif -} - - -mal_result mal_mutex_init__posix(mal_context* pContext, mal_mutex* pMutex) -{ - int result = ((mal_pthread_mutex_init_proc)pContext->posix.pthread_mutex_init)(&pMutex->posix.mutex, NULL); - if (result != 0) { - return MAL_FAILED_TO_CREATE_MUTEX; - } - - return MAL_SUCCESS; -} - -void mal_mutex_uninit__posix(mal_mutex* pMutex) -{ - ((mal_pthread_mutex_destroy_proc)pMutex->pContext->posix.pthread_mutex_destroy)(&pMutex->posix.mutex); -} - -void mal_mutex_lock__posix(mal_mutex* pMutex) -{ - ((mal_pthread_mutex_lock_proc)pMutex->pContext->posix.pthread_mutex_lock)(&pMutex->posix.mutex); -} - -void mal_mutex_unlock__posix(mal_mutex* pMutex) -{ - ((mal_pthread_mutex_unlock_proc)pMutex->pContext->posix.pthread_mutex_unlock)(&pMutex->posix.mutex); -} - - -mal_result mal_event_init__posix(mal_context* pContext, mal_event* pEvent) -{ - if (((mal_pthread_mutex_init_proc)pContext->posix.pthread_mutex_init)(&pEvent->posix.mutex, NULL) != 0) { - return MAL_FAILED_TO_CREATE_MUTEX; - } - - if (((mal_pthread_cond_init_proc)pContext->posix.pthread_cond_init)(&pEvent->posix.condition, NULL) != 0) { - return MAL_FAILED_TO_CREATE_EVENT; - } - - pEvent->posix.value = 0; - return MAL_SUCCESS; -} - -void mal_event_uninit__posix(mal_event* pEvent) -{ - ((mal_pthread_cond_destroy_proc)pEvent->pContext->posix.pthread_cond_destroy)(&pEvent->posix.condition); - ((mal_pthread_mutex_destroy_proc)pEvent->pContext->posix.pthread_mutex_destroy)(&pEvent->posix.mutex); -} - -mal_bool32 mal_event_wait__posix(mal_event* pEvent) -{ - ((mal_pthread_mutex_lock_proc)pEvent->pContext->posix.pthread_mutex_lock)(&pEvent->posix.mutex); - { - while (pEvent->posix.value == 0) { - ((mal_pthread_cond_wait_proc)pEvent->pContext->posix.pthread_cond_wait)(&pEvent->posix.condition, &pEvent->posix.mutex); - } - - pEvent->posix.value = 0; // Auto-reset. - } - ((mal_pthread_mutex_unlock_proc)pEvent->pContext->posix.pthread_mutex_unlock)(&pEvent->posix.mutex); - - return MAL_TRUE; -} - -mal_bool32 mal_event_signal__posix(mal_event* pEvent) -{ - ((mal_pthread_mutex_lock_proc)pEvent->pContext->posix.pthread_mutex_lock)(&pEvent->posix.mutex); - { - pEvent->posix.value = 1; - ((mal_pthread_cond_signal_proc)pEvent->pContext->posix.pthread_cond_signal)(&pEvent->posix.condition); - } - ((mal_pthread_mutex_unlock_proc)pEvent->pContext->posix.pthread_mutex_unlock)(&pEvent->posix.mutex); - - return MAL_TRUE; -} -#endif - -mal_result mal_thread_create(mal_context* pContext, mal_thread* pThread, mal_thread_entry_proc entryProc, void* pData) -{ - if (pContext == NULL || pThread == NULL || entryProc == NULL) return MAL_FALSE; - - pThread->pContext = pContext; - -#ifdef MAL_WIN32 - return mal_thread_create__win32(pContext, pThread, entryProc, pData); -#endif -#ifdef MAL_POSIX - return mal_thread_create__posix(pContext, pThread, entryProc, pData); -#endif -} - -void mal_thread_wait(mal_thread* pThread) -{ - if (pThread == NULL) return; - -#ifdef MAL_WIN32 - mal_thread_wait__win32(pThread); -#endif -#ifdef MAL_POSIX - mal_thread_wait__posix(pThread); -#endif -} - -void mal_sleep(mal_uint32 milliseconds) -{ -#ifdef MAL_WIN32 - mal_sleep__win32(milliseconds); -#endif -#ifdef MAL_POSIX - mal_sleep__posix(milliseconds); -#endif -} - - -mal_result mal_mutex_init(mal_context* pContext, mal_mutex* pMutex) -{ - if (pContext == NULL || pMutex == NULL) { - return MAL_INVALID_ARGS; - } - - pMutex->pContext = pContext; - -#ifdef MAL_WIN32 - return mal_mutex_init__win32(pContext, pMutex); -#endif -#ifdef MAL_POSIX - return mal_mutex_init__posix(pContext, pMutex); -#endif -} - -void mal_mutex_uninit(mal_mutex* pMutex) -{ - if (pMutex == NULL || pMutex->pContext == NULL) return; - -#ifdef MAL_WIN32 - mal_mutex_uninit__win32(pMutex); -#endif -#ifdef MAL_POSIX - mal_mutex_uninit__posix(pMutex); -#endif -} - -void mal_mutex_lock(mal_mutex* pMutex) -{ - if (pMutex == NULL || pMutex->pContext == NULL) return; - -#ifdef MAL_WIN32 - mal_mutex_lock__win32(pMutex); -#endif -#ifdef MAL_POSIX - mal_mutex_lock__posix(pMutex); -#endif -} - -void mal_mutex_unlock(mal_mutex* pMutex) -{ - if (pMutex == NULL || pMutex->pContext == NULL) return; - -#ifdef MAL_WIN32 - mal_mutex_unlock__win32(pMutex); -#endif -#ifdef MAL_POSIX - mal_mutex_unlock__posix(pMutex); -#endif -} - - -mal_result mal_event_init(mal_context* pContext, mal_event* pEvent) -{ - if (pContext == NULL || pEvent == NULL) return MAL_FALSE; - - pEvent->pContext = pContext; - -#ifdef MAL_WIN32 - return mal_event_init__win32(pContext, pEvent); -#endif -#ifdef MAL_POSIX - return mal_event_init__posix(pContext, pEvent); -#endif -} - -void mal_event_uninit(mal_event* pEvent) -{ - if (pEvent == NULL || pEvent->pContext == NULL) return; - -#ifdef MAL_WIN32 - mal_event_uninit__win32(pEvent); -#endif -#ifdef MAL_POSIX - mal_event_uninit__posix(pEvent); -#endif -} - -mal_bool32 mal_event_wait(mal_event* pEvent) -{ - if (pEvent == NULL || pEvent->pContext == NULL) return MAL_FALSE; - -#ifdef MAL_WIN32 - return mal_event_wait__win32(pEvent); -#endif -#ifdef MAL_POSIX - return mal_event_wait__posix(pEvent); -#endif -} - -mal_bool32 mal_event_signal(mal_event* pEvent) -{ - if (pEvent == NULL || pEvent->pContext == NULL) return MAL_FALSE; - -#ifdef MAL_WIN32 - return mal_event_signal__win32(pEvent); -#endif -#ifdef MAL_POSIX - return mal_event_signal__posix(pEvent); -#endif -} - - -mal_uint32 mal_get_best_sample_rate_within_range(mal_uint32 sampleRateMin, mal_uint32 sampleRateMax) -{ - // Normalize the range in case we were given something stupid. - if (sampleRateMin < MAL_MIN_SAMPLE_RATE) { - sampleRateMin = MAL_MIN_SAMPLE_RATE; - } - if (sampleRateMax > MAL_MAX_SAMPLE_RATE) { - sampleRateMax = MAL_MAX_SAMPLE_RATE; - } - if (sampleRateMin > sampleRateMax) { - sampleRateMin = sampleRateMax; - } - - if (sampleRateMin == sampleRateMax) { - return sampleRateMax; - } else { - for (size_t iStandardRate = 0; iStandardRate < mal_countof(g_malStandardSampleRatePriorities); ++iStandardRate) { - mal_uint32 standardRate = g_malStandardSampleRatePriorities[iStandardRate]; - if (standardRate >= sampleRateMin && standardRate <= sampleRateMax) { - return standardRate; - } - } - } - - // Should never get here. - mal_assert(MAL_FALSE); - return 0; -} - -mal_uint32 mal_get_closest_standard_sample_rate(mal_uint32 sampleRateIn) -{ - mal_uint32 closestRate = 0; - mal_uint32 closestDiff = 0xFFFFFFFF; - - for (size_t iStandardRate = 0; iStandardRate < mal_countof(g_malStandardSampleRatePriorities); ++iStandardRate) { - mal_uint32 standardRate = g_malStandardSampleRatePriorities[iStandardRate]; - - mal_uint32 diff; - if (sampleRateIn > standardRate) { - diff = sampleRateIn - standardRate; - } else { - diff = standardRate - sampleRateIn; - } - - if (diff == 0) { - return standardRate; // The input sample rate is a standard rate. - } - - if (closestDiff > diff) { - closestDiff = diff; - closestRate = standardRate; - } - } - - return closestRate; -} - - -mal_uint32 mal_scale_buffer_size(mal_uint32 baseBufferSize, float scale) -{ - return mal_max(1, (mal_uint32)(baseBufferSize*scale)); -} - -mal_uint32 mal_calculate_buffer_size_in_milliseconds_from_frames(mal_uint32 bufferSizeInFrames, mal_uint32 sampleRate) -{ - return bufferSizeInFrames / (sampleRate/1000); -} - -mal_uint32 mal_calculate_buffer_size_in_frames_from_milliseconds(mal_uint32 bufferSizeInMilliseconds, mal_uint32 sampleRate) -{ - return bufferSizeInMilliseconds * (sampleRate/1000); -} - -mal_uint32 mal_get_default_buffer_size_in_milliseconds(mal_performance_profile performanceProfile) -{ - if (performanceProfile == mal_performance_profile_low_latency) { - return MAL_BASE_BUFFER_SIZE_IN_MILLISECONDS_LOW_LATENCY; - } else { - return MAL_BASE_BUFFER_SIZE_IN_MILLISECONDS_CONSERVATIVE; - } -} - -mal_uint32 mal_get_default_buffer_size_in_frames(mal_performance_profile performanceProfile, mal_uint32 sampleRate) -{ - mal_uint32 bufferSizeInMilliseconds = mal_get_default_buffer_size_in_milliseconds(performanceProfile); - if (bufferSizeInMilliseconds == 0) { - bufferSizeInMilliseconds = 1; - } - - mal_uint32 sampleRateMS = (sampleRate/1000); - if (sampleRateMS == 0) { - sampleRateMS = 1; - } - - return bufferSizeInMilliseconds * sampleRateMS; -} - - -const char* mal_log_level_to_string(mal_uint32 logLevel) -{ - switch (logLevel) - { - case MAL_LOG_LEVEL_VERBOSE: return ""; - case MAL_LOG_LEVEL_INFO: return "INFO"; - case MAL_LOG_LEVEL_WARNING: return "WARNING"; - case MAL_LOG_LEVEL_ERROR: return "ERROR"; - default: return "ERROR"; - } -} - -// Posts a log message. -void mal_log(mal_context* pContext, mal_device* pDevice, mal_uint32 logLevel, const char* message) -{ - if (pContext == NULL) return; - -#if defined(MAL_LOG_LEVEL) - if (logLevel <= MAL_LOG_LEVEL) { - #if defined(MAL_DEBUG_OUTPUT) - if (logLevel <= MAL_LOG_LEVEL) { - printf("%s: %s", mal_log_level_to_string(logLevel), message); - } - #endif - - mal_log_proc onLog = pContext->config.onLog; - if (onLog) { - onLog(pContext, pDevice, message); - } - } -#endif -} - -// Posts an error. Throw a breakpoint in here if you're needing to debug. The return value is always "resultCode". -mal_result mal_context_post_error(mal_context* pContext, mal_device* pDevice, mal_uint32 logLevel, const char* message, mal_result resultCode) -{ - // Derive the context from the device if necessary. - if (pContext == NULL) { - if (pDevice != NULL) { - pContext = pDevice->pContext; - } - } - - mal_log(pContext, pDevice, logLevel, message); - return resultCode; -} - -mal_result mal_post_error(mal_device* pDevice, mal_uint32 logLevel, const char* message, mal_result resultCode) -{ - return mal_context_post_error(NULL, pDevice, logLevel, message, resultCode); -} - - -// The callback for reading from the client -> DSP -> device. -mal_uint32 mal_device__on_read_from_client(mal_dsp* pDSP, mal_uint32 frameCount, void* pFramesOut, void* pUserData) -{ - (void)pDSP; - - mal_device* pDevice = (mal_device*)pUserData; - mal_assert(pDevice != NULL); - - mal_send_proc onSend = pDevice->onSend; - if (onSend) { - return onSend(pDevice, frameCount, pFramesOut); - } - - return 0; -} - -// The callback for reading from the device -> DSP -> client. -mal_uint32 mal_device__on_read_from_device(mal_dsp* pDSP, mal_uint32 frameCount, void* pFramesOut, void* pUserData) -{ - (void)pDSP; - - mal_device* pDevice = (mal_device*)pUserData; - mal_assert(pDevice != NULL); - - if (pDevice->_dspFrameCount == 0) { - return 0; // Nothing left. - } - - mal_uint32 framesToRead = frameCount; - if (framesToRead > pDevice->_dspFrameCount) { - framesToRead = pDevice->_dspFrameCount; - } - - mal_uint32 bytesToRead = framesToRead * pDevice->internalChannels * mal_get_bytes_per_sample(pDevice->internalFormat); - mal_copy_memory(pFramesOut, pDevice->_dspFrames, bytesToRead); - pDevice->_dspFrameCount -= framesToRead; - pDevice->_dspFrames += bytesToRead; - - return framesToRead; -} - -// A helper function for reading sample data from the client. Returns the number of samples read from the client. Remaining samples -// are filled with silence. -static MAL_INLINE mal_uint32 mal_device__read_frames_from_client(mal_device* pDevice, mal_uint32 frameCount, void* pSamples) -{ - mal_assert(pDevice != NULL); - mal_assert(frameCount > 0); - mal_assert(pSamples != NULL); - - mal_uint32 framesRead = (mal_uint32)mal_dsp_read(&pDevice->dsp, frameCount, pSamples, pDevice->dsp.pUserData); - mal_uint32 samplesRead = framesRead * pDevice->internalChannels; - mal_uint32 sampleSize = mal_get_bytes_per_sample(pDevice->internalFormat); - mal_uint32 consumedBytes = samplesRead*sampleSize; - mal_uint32 remainingBytes = ((frameCount * pDevice->internalChannels) - samplesRead)*sampleSize; - mal_zero_memory((mal_uint8*)pSamples + consumedBytes, remainingBytes); - - return samplesRead; -} - -// A helper for sending sample data to the client. -static MAL_INLINE void mal_device__send_frames_to_client(mal_device* pDevice, mal_uint32 frameCount, const void* pSamples) -{ - mal_assert(pDevice != NULL); - mal_assert(frameCount > 0); - mal_assert(pSamples != NULL); - - mal_recv_proc onRecv = pDevice->onRecv; - if (onRecv) { - pDevice->_dspFrameCount = frameCount; - pDevice->_dspFrames = (const mal_uint8*)pSamples; - - mal_uint8 chunkBuffer[4096]; - mal_uint32 chunkFrameCount = sizeof(chunkBuffer) / mal_get_bytes_per_frame(pDevice->format, pDevice->channels); - - for (;;) { - mal_uint32 framesJustRead = (mal_uint32)mal_dsp_read(&pDevice->dsp, chunkFrameCount, chunkBuffer, pDevice->dsp.pUserData); - if (framesJustRead == 0) { - break; - } - - onRecv(pDevice, framesJustRead, chunkBuffer); - - if (framesJustRead < chunkFrameCount) { - break; - } - } - } -} - -// A helper for changing the state of the device. -static MAL_INLINE void mal_device__set_state(mal_device* pDevice, mal_uint32 newState) -{ - mal_atomic_exchange_32(&pDevice->state, newState); -} - -// A helper for getting the state of the device. -static MAL_INLINE mal_uint32 mal_device__get_state(mal_device* pDevice) -{ - return pDevice->state; -} - - -#ifdef MAL_WIN32 - GUID MAL_GUID_KSDATAFORMAT_SUBTYPE_PCM = {0x00000001, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}}; - GUID MAL_GUID_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT = {0x00000003, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}}; - //GUID MAL_GUID_KSDATAFORMAT_SUBTYPE_ALAW = {0x00000006, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}}; - //GUID MAL_GUID_KSDATAFORMAT_SUBTYPE_MULAW = {0x00000007, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}}; -#endif - - -mal_bool32 mal_context__device_id_equal(mal_context* pContext, const mal_device_id* pID0, const mal_device_id* pID1) -{ - mal_assert(pContext != NULL); - - if (pID0 == pID1) return MAL_TRUE; - - if ((pID0 == NULL && pID1 != NULL) || - (pID0 != NULL && pID1 == NULL)) { - return MAL_FALSE; - } - - if (pContext->onDeviceIDEqual) { - return pContext->onDeviceIDEqual(pContext, pID0, pID1); - } - - return MAL_FALSE; -} - - -typedef struct -{ - mal_device_type deviceType; - const mal_device_id* pDeviceID; - char* pName; - size_t nameBufferSize; - mal_bool32 foundDevice; -} mal_context__try_get_device_name_by_id__enum_callback_data; - -mal_bool32 mal_context__try_get_device_name_by_id__enum_callback(mal_context* pContext, mal_device_type deviceType, const mal_device_info* pDeviceInfo, void* pUserData) -{ - mal_context__try_get_device_name_by_id__enum_callback_data* pData = (mal_context__try_get_device_name_by_id__enum_callback_data*)pUserData; - mal_assert(pData != NULL); - - if (pData->deviceType == deviceType) { - if (pContext->onDeviceIDEqual(pContext, pData->pDeviceID, &pDeviceInfo->id)) { - mal_strncpy_s(pData->pName, pData->nameBufferSize, pDeviceInfo->name, (size_t)-1); - pData->foundDevice = MAL_TRUE; - } - } - - return !pData->foundDevice; -} - -// Generic function for retrieving the name of a device by it's ID. -// -// This function simply enumerates every device and then retrieves the name of the first device that has the same ID. -mal_result mal_context__try_get_device_name_by_id(mal_context* pContext, mal_device_type type, const mal_device_id* pDeviceID, char* pName, size_t nameBufferSize) -{ - mal_assert(pContext != NULL); - mal_assert(pName != NULL); - - if (pDeviceID == NULL) { - return MAL_NO_DEVICE; - } - - mal_context__try_get_device_name_by_id__enum_callback_data data; - data.deviceType = type; - data.pDeviceID = pDeviceID; - data.pName = pName; - data.nameBufferSize = nameBufferSize; - data.foundDevice = MAL_FALSE; - mal_result result = mal_context_enumerate_devices(pContext, mal_context__try_get_device_name_by_id__enum_callback, &data); - if (result != MAL_SUCCESS) { - return result; - } - - if (!data.foundDevice) { - return MAL_NO_DEVICE; - } else { - return MAL_SUCCESS; - } -} - - -mal_uint32 mal_get_format_priority_index(mal_format format) // Lower = better. -{ - for (mal_uint32 i = 0; i < mal_countof(g_malFormatPriorities); ++i) { - if (g_malFormatPriorities[i] == format) { - return i; - } - } - - // Getting here means the format could not be found or is equal to mal_format_unknown. - return (mal_uint32)-1; -} - -void mal_device__post_init_setup(mal_device* pDevice); - -/////////////////////////////////////////////////////////////////////////////// -// -// Null Backend -// -/////////////////////////////////////////////////////////////////////////////// -#ifdef MAL_HAS_NULL - -mal_bool32 mal_context_is_device_id_equal__null(mal_context* pContext, const mal_device_id* pID0, const mal_device_id* pID1) -{ - mal_assert(pContext != NULL); - mal_assert(pID0 != NULL); - mal_assert(pID1 != NULL); - (void)pContext; - - return pID0->nullbackend == pID1->nullbackend; -} - -mal_result mal_context_enumerate_devices__null(mal_context* pContext, mal_enum_devices_callback_proc callback, void* pUserData) -{ - mal_assert(pContext != NULL); - mal_assert(callback != NULL); - - mal_bool32 cbResult = MAL_TRUE; - - // Playback. - if (cbResult) { - mal_device_info deviceInfo; - mal_zero_object(&deviceInfo); - mal_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), "NULL Playback Device", (size_t)-1); - cbResult = callback(pContext, mal_device_type_playback, &deviceInfo, pUserData); - } - - // Capture. - if (cbResult) { - mal_device_info deviceInfo; - mal_zero_object(&deviceInfo); - mal_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), "NULL Capture Device", (size_t)-1); - cbResult = callback(pContext, mal_device_type_capture, &deviceInfo, pUserData); - } - - return MAL_SUCCESS; -} - -mal_result mal_context_get_device_info__null(mal_context* pContext, mal_device_type deviceType, const mal_device_id* pDeviceID, mal_share_mode shareMode, mal_device_info* pDeviceInfo) -{ - mal_assert(pContext != NULL); - - (void)pContext; - (void)shareMode; - - if (pDeviceID != NULL && pDeviceID->nullbackend != 0) { - return MAL_NO_DEVICE; // Don't know the device. - } - - // Name / Description - if (deviceType == mal_device_type_playback) { - mal_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), "NULL Playback Device", (size_t)-1); - } else { - mal_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), "NULL Capture Device", (size_t)-1); - } - - // Support everything on the null backend. - pDeviceInfo->formatCount = mal_format_count - 1; // Minus one because we don't want to include mal_format_unknown. - for (mal_uint32 iFormat = 0; iFormat < pDeviceInfo->formatCount; ++iFormat) { - pDeviceInfo->formats[iFormat] = (mal_format)(iFormat + 1); // +1 to skip over mal_format_unknown. - } - - pDeviceInfo->minChannels = 1; - pDeviceInfo->maxChannels = MAL_MAX_CHANNELS; - pDeviceInfo->minSampleRate = MAL_SAMPLE_RATE_8000; - pDeviceInfo->maxSampleRate = MAL_SAMPLE_RATE_384000; - - return MAL_SUCCESS; -} - - -void mal_device_uninit__null(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - mal_free(pDevice->null_device.pBuffer); -} - -mal_result mal_device_init__null(mal_context* pContext, mal_device_type type, const mal_device_id* pDeviceID, const mal_device_config* pConfig, mal_device* pDevice) -{ - (void)pContext; - (void)type; - (void)pDeviceID; - (void)pConfig; - - mal_assert(pDevice != NULL); - mal_zero_object(&pDevice->null_device); - - if (type == mal_device_type_playback) { - mal_strncpy_s(pDevice->name, sizeof(pDevice->name), "NULL Playback Device", (size_t)-1); - } else { - mal_strncpy_s(pDevice->name, sizeof(pDevice->name), "NULL Capture Device", (size_t)-1); - } - - if (pDevice->bufferSizeInFrames == 0) { - pDevice->bufferSizeInFrames = mal_calculate_buffer_size_in_frames_from_milliseconds(pDevice->bufferSizeInMilliseconds, pDevice->sampleRate); - } - - pDevice->null_device.pBuffer = (mal_uint8*)mal_malloc(pDevice->bufferSizeInFrames * pDevice->channels * mal_get_bytes_per_sample(pDevice->format)); - if (pDevice->null_device.pBuffer == NULL) { - return MAL_OUT_OF_MEMORY; - } - - mal_zero_memory(pDevice->null_device.pBuffer, mal_device_get_buffer_size_in_bytes(pDevice)); - - return MAL_SUCCESS; -} - -mal_result mal_device_start__null(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - mal_timer_init(&pDevice->null_device.timer); - pDevice->null_device.lastProcessedFrame = 0; - - return MAL_SUCCESS; -} - -mal_result mal_device_stop__null(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - (void)pDevice; - - return MAL_SUCCESS; -} - -mal_result mal_device_break_main_loop__null(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - pDevice->null_device.breakFromMainLoop = MAL_TRUE; - return MAL_SUCCESS; -} - -mal_bool32 mal_device__get_current_frame__null(mal_device* pDevice, mal_uint32* pCurrentPos) -{ - mal_assert(pDevice != NULL); - mal_assert(pCurrentPos != NULL); - *pCurrentPos = 0; - - mal_uint64 currentFrameAbs = (mal_uint64)(mal_timer_get_time_in_seconds(&pDevice->null_device.timer) * pDevice->sampleRate); - - *pCurrentPos = (mal_uint32)(currentFrameAbs % pDevice->bufferSizeInFrames); - return MAL_TRUE; -} - -mal_uint32 mal_device__get_available_frames__null(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - mal_uint32 currentFrame; - if (!mal_device__get_current_frame__null(pDevice, ¤tFrame)) { - return 0; - } - - // In a playback device the last processed frame should always be ahead of the current frame. The space between - // the last processed and current frame (moving forward, starting from the last processed frame) is the amount - // of space available to write. - // - // For a recording device it's the other way around - the last processed frame is always _behind_ the current - // frame and the space between is the available space. - mal_uint32 totalFrameCount = pDevice->bufferSizeInFrames; - if (pDevice->type == mal_device_type_playback) { - mal_uint32 committedBeg = currentFrame; - mal_uint32 committedEnd = pDevice->null_device.lastProcessedFrame; - if (committedEnd <= committedBeg) { - committedEnd += totalFrameCount; // Wrap around. - } - - mal_uint32 committedSize = (committedEnd - committedBeg); - mal_assert(committedSize <= totalFrameCount); - - return totalFrameCount - committedSize; - } else { - mal_uint32 validBeg = pDevice->null_device.lastProcessedFrame; - mal_uint32 validEnd = currentFrame; - if (validEnd < validBeg) { - validEnd += totalFrameCount; // Wrap around. - } - - mal_uint32 validSize = (validEnd - validBeg); - mal_assert(validSize <= totalFrameCount); - - return validSize; - } -} - -mal_uint32 mal_device__wait_for_frames__null(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - while (!pDevice->null_device.breakFromMainLoop) { - mal_uint32 framesAvailable = mal_device__get_available_frames__null(pDevice); - if (framesAvailable >= (pDevice->bufferSizeInFrames/pDevice->periods)) { - return framesAvailable; - } - - mal_sleep(pDevice->bufferSizeInMilliseconds/pDevice->periods); - } - - // We'll get here if the loop was terminated. Just return whatever's available. - return mal_device__get_available_frames__null(pDevice); -} - -mal_result mal_device_main_loop__null(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - pDevice->null_device.breakFromMainLoop = MAL_FALSE; - while (!pDevice->null_device.breakFromMainLoop) { - mal_uint32 framesAvailable = mal_device__wait_for_frames__null(pDevice); - if (framesAvailable == 0) { - continue; - } - - // If it's a playback device, don't bother grabbing more data if the device is being stopped. - if (pDevice->null_device.breakFromMainLoop && pDevice->type == mal_device_type_playback) { - return MAL_FALSE; - } - - if (framesAvailable + pDevice->null_device.lastProcessedFrame > pDevice->bufferSizeInFrames) { - framesAvailable = pDevice->bufferSizeInFrames - pDevice->null_device.lastProcessedFrame; - } - - mal_uint32 sampleCount = framesAvailable * pDevice->channels; - mal_uint32 lockOffset = pDevice->null_device.lastProcessedFrame * pDevice->channels * mal_get_bytes_per_sample(pDevice->format); - mal_uint32 lockSize = sampleCount * mal_get_bytes_per_sample(pDevice->format); - - if (pDevice->type == mal_device_type_playback) { - if (pDevice->null_device.breakFromMainLoop) { - return MAL_FALSE; - } - - mal_device__read_frames_from_client(pDevice, framesAvailable, pDevice->null_device.pBuffer + lockOffset); - } else { - mal_zero_memory(pDevice->null_device.pBuffer + lockOffset, lockSize); - mal_device__send_frames_to_client(pDevice, framesAvailable, pDevice->null_device.pBuffer + lockOffset); - } - - pDevice->null_device.lastProcessedFrame = (pDevice->null_device.lastProcessedFrame + framesAvailable) % pDevice->bufferSizeInFrames; - } - - return MAL_SUCCESS; -} - - -mal_result mal_context_uninit__null(mal_context* pContext) -{ - mal_assert(pContext != NULL); - mal_assert(pContext->backend == mal_backend_null); - - (void)pContext; - return MAL_SUCCESS; -} - -mal_result mal_context_init__null(mal_context* pContext) -{ - mal_assert(pContext != NULL); - - pContext->onUninit = mal_context_uninit__null; - pContext->onDeviceIDEqual = mal_context_is_device_id_equal__null; - pContext->onEnumDevices = mal_context_enumerate_devices__null; - pContext->onGetDeviceInfo = mal_context_get_device_info__null; - pContext->onDeviceInit = mal_device_init__null; - pContext->onDeviceUninit = mal_device_uninit__null; - pContext->onDeviceStart = mal_device_start__null; - pContext->onDeviceStop = mal_device_stop__null; - pContext->onDeviceBreakMainLoop = mal_device_break_main_loop__null; - pContext->onDeviceMainLoop = mal_device_main_loop__null; - - // The null backend always works. - return MAL_SUCCESS; -} -#endif - - -/////////////////////////////////////////////////////////////////////////////// -// -// WIN32 COMMON -// -/////////////////////////////////////////////////////////////////////////////// -#if defined(MAL_WIN32) -#include "objbase.h" -#if defined(MAL_WIN32_DESKTOP) - #define mal_CoInitializeEx(pContext, pvReserved, dwCoInit) ((MAL_PFN_CoInitializeEx)pContext->win32.CoInitializeEx)(pvReserved, dwCoInit) - #define mal_CoUninitialize(pContext) ((MAL_PFN_CoUninitialize)pContext->win32.CoUninitialize)() - #define mal_CoCreateInstance(pContext, rclsid, pUnkOuter, dwClsContext, riid, ppv) ((MAL_PFN_CoCreateInstance)pContext->win32.CoCreateInstance)(rclsid, pUnkOuter, dwClsContext, riid, ppv) - #define mal_CoTaskMemFree(pContext, pv) ((MAL_PFN_CoTaskMemFree)pContext->win32.CoTaskMemFree)(pv) - #define mal_PropVariantClear(pContext, pvar) ((MAL_PFN_PropVariantClear)pContext->win32.PropVariantClear)(pvar) -#else - #define mal_CoInitializeEx(pContext, pvReserved, dwCoInit) CoInitializeEx(pvReserved, dwCoInit) - #define mal_CoUninitialize(pContext) CoUninitialize() - #define mal_CoCreateInstance(pContext, rclsid, pUnkOuter, dwClsContext, riid, ppv) CoCreateInstance(rclsid, pUnkOuter, dwClsContext, riid, ppv) - #define mal_CoTaskMemFree(pContext, pv) CoTaskMemFree(pv) - #define mal_PropVariantClear(pContext, pvar) PropVariantClear(pvar) -#endif - -// There's a few common headers for Win32 backends which include here for simplicity. Note that we should never -// include any files that do not come standard with modern compilers, and we may need to manually define a few -// symbols. -#include -#include - -#if !defined(MAXULONG_PTR) -typedef size_t DWORD_PTR; -#endif - -#if !defined(WAVE_FORMAT_44M08) -#define WAVE_FORMAT_44M08 0x00000100 -#define WAVE_FORMAT_44S08 0x00000200 -#define WAVE_FORMAT_44M16 0x00000400 -#define WAVE_FORMAT_44S16 0x00000800 -#define WAVE_FORMAT_48M08 0x00001000 -#define WAVE_FORMAT_48S08 0x00002000 -#define WAVE_FORMAT_48M16 0x00004000 -#define WAVE_FORMAT_48S16 0x00008000 -#define WAVE_FORMAT_96M08 0x00010000 -#define WAVE_FORMAT_96S08 0x00020000 -#define WAVE_FORMAT_96M16 0x00040000 -#define WAVE_FORMAT_96S16 0x00080000 -#endif - -#ifndef SPEAKER_FRONT_LEFT -#define SPEAKER_FRONT_LEFT 0x1 -#define SPEAKER_FRONT_RIGHT 0x2 -#define SPEAKER_FRONT_CENTER 0x4 -#define SPEAKER_LOW_FREQUENCY 0x8 -#define SPEAKER_BACK_LEFT 0x10 -#define SPEAKER_BACK_RIGHT 0x20 -#define SPEAKER_FRONT_LEFT_OF_CENTER 0x40 -#define SPEAKER_FRONT_RIGHT_OF_CENTER 0x80 -#define SPEAKER_BACK_CENTER 0x100 -#define SPEAKER_SIDE_LEFT 0x200 -#define SPEAKER_SIDE_RIGHT 0x400 -#define SPEAKER_TOP_CENTER 0x800 -#define SPEAKER_TOP_FRONT_LEFT 0x1000 -#define SPEAKER_TOP_FRONT_CENTER 0x2000 -#define SPEAKER_TOP_FRONT_RIGHT 0x4000 -#define SPEAKER_TOP_BACK_LEFT 0x8000 -#define SPEAKER_TOP_BACK_CENTER 0x10000 -#define SPEAKER_TOP_BACK_RIGHT 0x20000 -#endif - -// The SDK that comes with old versions of MSVC (VC6, for example) does not appear to define WAVEFORMATEXTENSIBLE. We -// define our own implementation in this case. -#if (defined(_MSC_VER) && !defined(_WAVEFORMATEXTENSIBLE_)) || defined(__DMC__) -typedef struct -{ - WAVEFORMATEX Format; - union - { - WORD wValidBitsPerSample; - WORD wSamplesPerBlock; - WORD wReserved; - } Samples; - DWORD dwChannelMask; - GUID SubFormat; -} WAVEFORMATEXTENSIBLE; -#endif - -#ifndef WAVE_FORMAT_EXTENSIBLE -#define WAVE_FORMAT_EXTENSIBLE 0xFFFE -#endif - -#ifndef WAVE_FORMAT_IEEE_FLOAT -#define WAVE_FORMAT_IEEE_FLOAT 0x0003 -#endif - -GUID MAL_GUID_NULL = {0x00000000, 0x0000, 0x0000, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}; - -// Converts an individual Win32-style channel identifier (SPEAKER_FRONT_LEFT, etc.) to mini_al. -mal_uint8 mal_channel_id_to_mal__win32(DWORD id) -{ - switch (id) - { - case SPEAKER_FRONT_LEFT: return MAL_CHANNEL_FRONT_LEFT; - case SPEAKER_FRONT_RIGHT: return MAL_CHANNEL_FRONT_RIGHT; - case SPEAKER_FRONT_CENTER: return MAL_CHANNEL_FRONT_CENTER; - case SPEAKER_LOW_FREQUENCY: return MAL_CHANNEL_LFE; - case SPEAKER_BACK_LEFT: return MAL_CHANNEL_BACK_LEFT; - case SPEAKER_BACK_RIGHT: return MAL_CHANNEL_BACK_RIGHT; - case SPEAKER_FRONT_LEFT_OF_CENTER: return MAL_CHANNEL_FRONT_LEFT_CENTER; - case SPEAKER_FRONT_RIGHT_OF_CENTER: return MAL_CHANNEL_FRONT_RIGHT_CENTER; - case SPEAKER_BACK_CENTER: return MAL_CHANNEL_BACK_CENTER; - case SPEAKER_SIDE_LEFT: return MAL_CHANNEL_SIDE_LEFT; - case SPEAKER_SIDE_RIGHT: return MAL_CHANNEL_SIDE_RIGHT; - case SPEAKER_TOP_CENTER: return MAL_CHANNEL_TOP_CENTER; - case SPEAKER_TOP_FRONT_LEFT: return MAL_CHANNEL_TOP_FRONT_LEFT; - case SPEAKER_TOP_FRONT_CENTER: return MAL_CHANNEL_TOP_FRONT_CENTER; - case SPEAKER_TOP_FRONT_RIGHT: return MAL_CHANNEL_TOP_FRONT_RIGHT; - case SPEAKER_TOP_BACK_LEFT: return MAL_CHANNEL_TOP_BACK_LEFT; - case SPEAKER_TOP_BACK_CENTER: return MAL_CHANNEL_TOP_BACK_CENTER; - case SPEAKER_TOP_BACK_RIGHT: return MAL_CHANNEL_TOP_BACK_RIGHT; - default: return 0; - } -} - -// Converts an individual mini_al channel identifier (MAL_CHANNEL_FRONT_LEFT, etc.) to Win32-style. -DWORD mal_channel_id_to_win32(DWORD id) -{ - switch (id) - { - case MAL_CHANNEL_MONO: return SPEAKER_FRONT_CENTER; - case MAL_CHANNEL_FRONT_LEFT: return SPEAKER_FRONT_LEFT; - case MAL_CHANNEL_FRONT_RIGHT: return SPEAKER_FRONT_RIGHT; - case MAL_CHANNEL_FRONT_CENTER: return SPEAKER_FRONT_CENTER; - case MAL_CHANNEL_LFE: return SPEAKER_LOW_FREQUENCY; - case MAL_CHANNEL_BACK_LEFT: return SPEAKER_BACK_LEFT; - case MAL_CHANNEL_BACK_RIGHT: return SPEAKER_BACK_RIGHT; - case MAL_CHANNEL_FRONT_LEFT_CENTER: return SPEAKER_FRONT_LEFT_OF_CENTER; - case MAL_CHANNEL_FRONT_RIGHT_CENTER: return SPEAKER_FRONT_RIGHT_OF_CENTER; - case MAL_CHANNEL_BACK_CENTER: return SPEAKER_BACK_CENTER; - case MAL_CHANNEL_SIDE_LEFT: return SPEAKER_SIDE_LEFT; - case MAL_CHANNEL_SIDE_RIGHT: return SPEAKER_SIDE_RIGHT; - case MAL_CHANNEL_TOP_CENTER: return SPEAKER_TOP_CENTER; - case MAL_CHANNEL_TOP_FRONT_LEFT: return SPEAKER_TOP_FRONT_LEFT; - case MAL_CHANNEL_TOP_FRONT_CENTER: return SPEAKER_TOP_FRONT_CENTER; - case MAL_CHANNEL_TOP_FRONT_RIGHT: return SPEAKER_TOP_FRONT_RIGHT; - case MAL_CHANNEL_TOP_BACK_LEFT: return SPEAKER_TOP_BACK_LEFT; - case MAL_CHANNEL_TOP_BACK_CENTER: return SPEAKER_TOP_BACK_CENTER; - case MAL_CHANNEL_TOP_BACK_RIGHT: return SPEAKER_TOP_BACK_RIGHT; - default: return 0; - } -} - -// Converts a channel mapping to a Win32-style channel mask. -DWORD mal_channel_map_to_channel_mask__win32(const mal_channel channelMap[MAL_MAX_CHANNELS], mal_uint32 channels) -{ - DWORD dwChannelMask = 0; - for (mal_uint32 iChannel = 0; iChannel < channels; ++iChannel) { - dwChannelMask |= mal_channel_id_to_win32(channelMap[iChannel]); - } - - return dwChannelMask; -} - -// Converts a Win32-style channel mask to a mini_al channel map. -void mal_channel_mask_to_channel_map__win32(DWORD dwChannelMask, mal_uint32 channels, mal_channel channelMap[MAL_MAX_CHANNELS]) -{ - if (channels == 1 && dwChannelMask == 0) { - channelMap[0] = MAL_CHANNEL_MONO; - } else if (channels == 2 && dwChannelMask == 0) { - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_RIGHT; - } else { - if (channels == 1 && (dwChannelMask & SPEAKER_FRONT_CENTER) != 0) { - channelMap[0] = MAL_CHANNEL_MONO; - } else { - // Just iterate over each bit. - mal_uint32 iChannel = 0; - for (mal_uint32 iBit = 0; iBit < 32; ++iBit) { - DWORD bitValue = (dwChannelMask & (1UL << iBit)); - if (bitValue != 0) { - // The bit is set. - channelMap[iChannel] = mal_channel_id_to_mal__win32(bitValue); - iChannel += 1; - } - } - } - } -} - -#ifdef __cplusplus -mal_bool32 mal_is_guid_equal(const void* a, const void* b) -{ - return IsEqualGUID(*(const GUID*)a, *(const GUID*)b); -} -#else -#define mal_is_guid_equal(a, b) IsEqualGUID((const GUID*)a, (const GUID*)b) -#endif - -mal_format mal_format_from_WAVEFORMATEX(const WAVEFORMATEX* pWF) -{ - mal_assert(pWF != NULL); - - if (pWF->wFormatTag == WAVE_FORMAT_EXTENSIBLE) { - const WAVEFORMATEXTENSIBLE* pWFEX = (const WAVEFORMATEXTENSIBLE*)pWF; - if (mal_is_guid_equal(&pWFEX->SubFormat, &MAL_GUID_KSDATAFORMAT_SUBTYPE_PCM)) { - if (pWFEX->Samples.wValidBitsPerSample == 32) { - return mal_format_s32; - } - if (pWFEX->Samples.wValidBitsPerSample == 24) { - if (pWFEX->Format.wBitsPerSample == 32) { - //return mal_format_s24_32; - } - if (pWFEX->Format.wBitsPerSample == 24) { - return mal_format_s24; - } - } - if (pWFEX->Samples.wValidBitsPerSample == 16) { - return mal_format_s16; - } - if (pWFEX->Samples.wValidBitsPerSample == 8) { - return mal_format_u8; - } - } - if (mal_is_guid_equal(&pWFEX->SubFormat, &MAL_GUID_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)) { - if (pWFEX->Samples.wValidBitsPerSample == 32) { - return mal_format_f32; - } - //if (pWFEX->Samples.wValidBitsPerSample == 64) { - // return mal_format_f64; - //} - } - } else { - if (pWF->wFormatTag == WAVE_FORMAT_PCM) { - if (pWF->wBitsPerSample == 32) { - return mal_format_s32; - } - if (pWF->wBitsPerSample == 24) { - return mal_format_s24; - } - if (pWF->wBitsPerSample == 16) { - return mal_format_s16; - } - if (pWF->wBitsPerSample == 8) { - return mal_format_u8; - } - } - if (pWF->wFormatTag == WAVE_FORMAT_IEEE_FLOAT) { - if (pWF->wBitsPerSample == 32) { - return mal_format_f32; - } - if (pWF->wBitsPerSample == 64) { - //return mal_format_f64; - } - } - } - - return mal_format_unknown; -} -#endif - - -/////////////////////////////////////////////////////////////////////////////// -// -// WASAPI Backend -// -/////////////////////////////////////////////////////////////////////////////// -#ifdef MAL_HAS_WASAPI -//#if defined(_MSC_VER) -// #pragma warning(push) -// #pragma warning(disable:4091) // 'typedef ': ignored on left of '' when no variable is declared -//#endif -//#include -//#include -//#if defined(_MSC_VER) -// #pragma warning(pop) -//#endif - - -// Some compilers don't define VerifyVersionInfoW. Need to write this ourselves. -#if defined(__DMC__) -#define _WIN32_WINNT_VISTA 0x0600 -#define VER_MINORVERSION 0x01 -#define VER_MAJORVERSION 0x02 -#define VER_SERVICEPACKMAJOR 0x20 -#define VER_GREATER_EQUAL 0x03 - -typedef struct { - DWORD dwOSVersionInfoSize; - DWORD dwMajorVersion; - DWORD dwMinorVersion; - DWORD dwBuildNumber; - DWORD dwPlatformId; - WCHAR szCSDVersion[128]; - WORD wServicePackMajor; - WORD wServicePackMinor; - WORD wSuiteMask; - BYTE wProductType; - BYTE wReserved; -} mal_OSVERSIONINFOEXW; - -BOOL WINAPI VerifyVersionInfoW(mal_OSVERSIONINFOEXW* lpVersionInfo, DWORD dwTypeMask, DWORDLONG dwlConditionMask); -ULONGLONG WINAPI VerSetConditionMask(ULONGLONG dwlConditionMask, DWORD dwTypeBitMask, BYTE dwConditionMask); -#else -typedef OSVERSIONINFOEXW mal_OSVERSIONINFOEXW; -#endif - - -#ifndef PROPERTYKEY_DEFINED -#define PROPERTYKEY_DEFINED -typedef struct -{ - GUID fmtid; - DWORD pid; -} PROPERTYKEY; -#endif - -// Some compilers don't define PropVariantInit(). We just do this ourselves since it's just a memset(). -static MAL_INLINE void mal_PropVariantInit(PROPVARIANT* pProp) -{ - mal_zero_object(pProp); -} - - -const PROPERTYKEY MAL_PKEY_Device_FriendlyName = {{0xA45C254E, 0xDF1C, 0x4EFD, {0x80, 0x20, 0x67, 0xD1, 0x46, 0xA8, 0x50, 0xE0}}, 14}; -const PROPERTYKEY MAL_PKEY_AudioEngine_DeviceFormat = {{0xF19F064D, 0x82C, 0x4E27, {0xBC, 0x73, 0x68, 0x82, 0xA1, 0xBB, 0x8E, 0x4C}}, 0}; - -const IID MAL_IID_IUnknown = {0x00000000, 0x0000, 0x0000, {0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}}; // 00000000-0000-0000-C000-000000000046 -const IID MAL_IID_IAgileObject = {0x94EA2B94, 0xE9CC, 0x49E0, {0xC0, 0xFF, 0xEE, 0x64, 0xCA, 0x8F, 0x5B, 0x90}}; // 94EA2B94-E9CC-49E0-C0FF-EE64CA8F5B90 - -const IID MAL_IID_IAudioClient = {0x1CB9AD4C, 0xDBFA, 0x4C32, {0xB1, 0x78, 0xC2, 0xF5, 0x68, 0xA7, 0x03, 0xB2}}; // 1CB9AD4C-DBFA-4C32-B178-C2F568A703B2 = __uuidof(IAudioClient) -const IID MAL_IID_IAudioClient2 = {0x726778CD, 0xF60A, 0x4EDA, {0x82, 0xDE, 0xE4, 0x76, 0x10, 0xCD, 0x78, 0xAA}}; // 726778CD-F60A-4EDA-82DE-E47610CD78AA = __uuidof(IAudioClient2) -const IID MAL_IID_IAudioClient3 = {0x7ED4EE07, 0x8E67, 0x4CD4, {0x8C, 0x1A, 0x2B, 0x7A, 0x59, 0x87, 0xAD, 0x42}}; // 7ED4EE07-8E67-4CD4-8C1A-2B7A5987AD42 = __uuidof(IAudioClient3) -const IID MAL_IID_IAudioRenderClient = {0xF294ACFC, 0x3146, 0x4483, {0xA7, 0xBF, 0xAD, 0xDC, 0xA7, 0xC2, 0x60, 0xE2}}; // F294ACFC-3146-4483-A7BF-ADDCA7C260E2 = __uuidof(IAudioRenderClient) -const IID MAL_IID_IAudioCaptureClient = {0xC8ADBD64, 0xE71E, 0x48A0, {0xA4, 0xDE, 0x18, 0x5C, 0x39, 0x5C, 0xD3, 0x17}}; // C8ADBD64-E71E-48A0-A4DE-185C395CD317 = __uuidof(IAudioCaptureClient) -const IID MAL_IID_IMMNotificationClient = {0x7991EEC9, 0x7E89, 0x4D85, {0x83, 0x90, 0x6C, 0x70, 0x3C, 0xEC, 0x60, 0xC0}}; // 7991EEC9-7E89-4D85-8390-6C703CEC60C0 = __uuidof(IMMNotificationClient) -#ifndef MAL_WIN32_DESKTOP -const IID MAL_IID_DEVINTERFACE_AUDIO_RENDER = {0xE6327CAD, 0xDCEC, 0x4949, {0xAE, 0x8A, 0x99, 0x1E, 0x97, 0x6A, 0x79, 0xD2}}; // E6327CAD-DCEC-4949-AE8A-991E976A79D2 -const IID MAL_IID_DEVINTERFACE_AUDIO_CAPTURE = {0x2EEF81BE, 0x33FA, 0x4800, {0x96, 0x70, 0x1C, 0xD4, 0x74, 0x97, 0x2C, 0x3F}}; // 2EEF81BE-33FA-4800-9670-1CD474972C3F -const IID MAL_IID_IActivateAudioInterfaceCompletionHandler = {0x41D949AB, 0x9862, 0x444A, {0x80, 0xF6, 0xC2, 0x61, 0x33, 0x4D, 0xA5, 0xEB}}; // 41D949AB-9862-444A-80F6-C261334DA5EB -#endif - -const IID MAL_CLSID_MMDeviceEnumerator_Instance = {0xBCDE0395, 0xE52F, 0x467C, {0x8E, 0x3D, 0xC4, 0x57, 0x92, 0x91, 0x69, 0x2E}}; // BCDE0395-E52F-467C-8E3D-C4579291692E = __uuidof(MMDeviceEnumerator) -const IID MAL_IID_IMMDeviceEnumerator_Instance = {0xA95664D2, 0x9614, 0x4F35, {0xA7, 0x46, 0xDE, 0x8D, 0xB6, 0x36, 0x17, 0xE6}}; // A95664D2-9614-4F35-A746-DE8DB63617E6 = __uuidof(IMMDeviceEnumerator) -#ifdef __cplusplus -#define MAL_CLSID_MMDeviceEnumerator MAL_CLSID_MMDeviceEnumerator_Instance -#define MAL_IID_IMMDeviceEnumerator MAL_IID_IMMDeviceEnumerator_Instance -#else -#define MAL_CLSID_MMDeviceEnumerator &MAL_CLSID_MMDeviceEnumerator_Instance -#define MAL_IID_IMMDeviceEnumerator &MAL_IID_IMMDeviceEnumerator_Instance -#endif - -typedef struct mal_IUnknown mal_IUnknown; -#ifdef MAL_WIN32_DESKTOP -#define MAL_MM_DEVICE_STATE_ACTIVE 1 -#define MAL_MM_DEVICE_STATE_DISABLED 2 -#define MAL_MM_DEVICE_STATE_NOTPRESENT 4 -#define MAL_MM_DEVICE_STATE_UNPLUGGED 8 - -typedef struct mal_IMMDeviceEnumerator mal_IMMDeviceEnumerator; -typedef struct mal_IMMDeviceCollection mal_IMMDeviceCollection; -typedef struct mal_IMMDevice mal_IMMDevice; -#else -typedef struct mal_IActivateAudioInterfaceCompletionHandler mal_IActivateAudioInterfaceCompletionHandler; -typedef struct mal_IActivateAudioInterfaceAsyncOperation mal_IActivateAudioInterfaceAsyncOperation; -#endif -typedef struct mal_IPropertyStore mal_IPropertyStore; -typedef struct mal_IAudioClient mal_IAudioClient; -typedef struct mal_IAudioClient2 mal_IAudioClient2; -typedef struct mal_IAudioClient3 mal_IAudioClient3; -typedef struct mal_IAudioRenderClient mal_IAudioRenderClient; -typedef struct mal_IAudioCaptureClient mal_IAudioCaptureClient; - -typedef mal_int64 MAL_REFERENCE_TIME; - -#define MAL_AUDCLNT_STREAMFLAGS_CROSSPROCESS 0x00010000 -#define MAL_AUDCLNT_STREAMFLAGS_LOOPBACK 0x00020000 -#define MAL_AUDCLNT_STREAMFLAGS_EVENTCALLBACK 0x00040000 -#define MAL_AUDCLNT_STREAMFLAGS_NOPERSIST 0x00080000 -#define MAL_AUDCLNT_STREAMFLAGS_RATEADJUST 0x00100000 -#define MAL_AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY 0x08000000 -#define MAL_AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM 0x80000000 -#define MAL_AUDCLNT_SESSIONFLAGS_EXPIREWHENUNOWNED 0x10000000 -#define MAL_AUDCLNT_SESSIONFLAGS_DISPLAY_HIDE 0x20000000 -#define MAL_AUDCLNT_SESSIONFLAGS_DISPLAY_HIDEWHENEXPIRED 0x40000000 - -// We only care about a few error codes. -#define MAL_AUDCLNT_E_INVALID_DEVICE_PERIOD (-2004287456) -#define MAL_AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED (-2004287463) -#define MAL_AUDCLNT_S_BUFFER_EMPTY (143196161) -#define MAL_AUDCLNT_E_DEVICE_IN_USE (-2004287478) - -typedef enum -{ - mal_eRender = 0, - mal_eCapture = 1, - mal_eAll = 2 -} mal_EDataFlow; - -typedef enum -{ - mal_eConsole = 0, - mal_eMultimedia = 1, - mal_eCommunications = 2 -} mal_ERole; - -typedef enum -{ - MAL_AUDCLNT_SHAREMODE_SHARED, - MAL_AUDCLNT_SHAREMODE_EXCLUSIVE -} MAL_AUDCLNT_SHAREMODE; - -typedef enum -{ - MAL_AudioCategory_Other = 0, // <-- mini_al is only caring about Other. -} MAL_AUDIO_STREAM_CATEGORY; - -typedef struct -{ - UINT32 cbSize; - BOOL bIsOffload; - MAL_AUDIO_STREAM_CATEGORY eCategory; -} mal_AudioClientProperties; - -// IUnknown -typedef struct -{ - // IUnknown - HRESULT (STDMETHODCALLTYPE * QueryInterface)(mal_IUnknown* pThis, const IID* const riid, void** ppObject); - ULONG (STDMETHODCALLTYPE * AddRef) (mal_IUnknown* pThis); - ULONG (STDMETHODCALLTYPE * Release) (mal_IUnknown* pThis); -} mal_IUnknownVtbl; -struct mal_IUnknown -{ - mal_IUnknownVtbl* lpVtbl; -}; -HRESULT mal_IUnknown_QueryInterface(mal_IUnknown* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } -ULONG mal_IUnknown_AddRef(mal_IUnknown* pThis) { return pThis->lpVtbl->AddRef(pThis); } -ULONG mal_IUnknown_Release(mal_IUnknown* pThis) { return pThis->lpVtbl->Release(pThis); } - -#ifdef MAL_WIN32_DESKTOP - // IMMNotificationClient - typedef struct - { - // IUnknown - HRESULT (STDMETHODCALLTYPE * QueryInterface)(mal_IMMNotificationClient* pThis, const IID* const riid, void** ppObject); - ULONG (STDMETHODCALLTYPE * AddRef) (mal_IMMNotificationClient* pThis); - ULONG (STDMETHODCALLTYPE * Release) (mal_IMMNotificationClient* pThis); - - // IMMNotificationClient - HRESULT (STDMETHODCALLTYPE * OnDeviceStateChanged) (mal_IMMNotificationClient* pThis, LPCWSTR pDeviceID, DWORD dwNewState); - HRESULT (STDMETHODCALLTYPE * OnDeviceAdded) (mal_IMMNotificationClient* pThis, LPCWSTR pDeviceID); - HRESULT (STDMETHODCALLTYPE * OnDeviceRemoved) (mal_IMMNotificationClient* pThis, LPCWSTR pDeviceID); - HRESULT (STDMETHODCALLTYPE * OnDefaultDeviceChanged)(mal_IMMNotificationClient* pThis, mal_EDataFlow dataFlow, mal_ERole role, LPCWSTR pDefaultDeviceID); - HRESULT (STDMETHODCALLTYPE * OnPropertyValueChanged)(mal_IMMNotificationClient* pThis, LPCWSTR pDeviceID, const PROPERTYKEY key); - } mal_IMMNotificationClientVtbl; - - // IMMDeviceEnumerator - typedef struct - { - // IUnknown - HRESULT (STDMETHODCALLTYPE * QueryInterface)(mal_IMMDeviceEnumerator* pThis, const IID* const riid, void** ppObject); - ULONG (STDMETHODCALLTYPE * AddRef) (mal_IMMDeviceEnumerator* pThis); - ULONG (STDMETHODCALLTYPE * Release) (mal_IMMDeviceEnumerator* pThis); - - // IMMDeviceEnumerator - HRESULT (STDMETHODCALLTYPE * EnumAudioEndpoints) (mal_IMMDeviceEnumerator* pThis, mal_EDataFlow dataFlow, DWORD dwStateMask, mal_IMMDeviceCollection** ppDevices); - HRESULT (STDMETHODCALLTYPE * GetDefaultAudioEndpoint) (mal_IMMDeviceEnumerator* pThis, mal_EDataFlow dataFlow, mal_ERole role, mal_IMMDevice** ppEndpoint); - HRESULT (STDMETHODCALLTYPE * GetDevice) (mal_IMMDeviceEnumerator* pThis, LPCWSTR pID, mal_IMMDevice** ppDevice); - HRESULT (STDMETHODCALLTYPE * RegisterEndpointNotificationCallback) (mal_IMMDeviceEnumerator* pThis, mal_IMMNotificationClient* pClient); - HRESULT (STDMETHODCALLTYPE * UnregisterEndpointNotificationCallback)(mal_IMMDeviceEnumerator* pThis, mal_IMMNotificationClient* pClient); - } mal_IMMDeviceEnumeratorVtbl; - struct mal_IMMDeviceEnumerator - { - mal_IMMDeviceEnumeratorVtbl* lpVtbl; - }; - HRESULT mal_IMMDeviceEnumerator_QueryInterface(mal_IMMDeviceEnumerator* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } - ULONG mal_IMMDeviceEnumerator_AddRef(mal_IMMDeviceEnumerator* pThis) { return pThis->lpVtbl->AddRef(pThis); } - ULONG mal_IMMDeviceEnumerator_Release(mal_IMMDeviceEnumerator* pThis) { return pThis->lpVtbl->Release(pThis); } - HRESULT mal_IMMDeviceEnumerator_EnumAudioEndpoints(mal_IMMDeviceEnumerator* pThis, mal_EDataFlow dataFlow, DWORD dwStateMask, mal_IMMDeviceCollection** ppDevices) { return pThis->lpVtbl->EnumAudioEndpoints(pThis, dataFlow, dwStateMask, ppDevices); } - HRESULT mal_IMMDeviceEnumerator_GetDefaultAudioEndpoint(mal_IMMDeviceEnumerator* pThis, mal_EDataFlow dataFlow, mal_ERole role, mal_IMMDevice** ppEndpoint) { return pThis->lpVtbl->GetDefaultAudioEndpoint(pThis, dataFlow, role, ppEndpoint); } - HRESULT mal_IMMDeviceEnumerator_GetDevice(mal_IMMDeviceEnumerator* pThis, LPCWSTR pID, mal_IMMDevice** ppDevice) { return pThis->lpVtbl->GetDevice(pThis, pID, ppDevice); } - HRESULT mal_IMMDeviceEnumerator_RegisterEndpointNotificationCallback(mal_IMMDeviceEnumerator* pThis, mal_IMMNotificationClient* pClient) { return pThis->lpVtbl->RegisterEndpointNotificationCallback(pThis, pClient); } - HRESULT mal_IMMDeviceEnumerator_UnregisterEndpointNotificationCallback(mal_IMMDeviceEnumerator* pThis, mal_IMMNotificationClient* pClient) { return pThis->lpVtbl->UnregisterEndpointNotificationCallback(pThis, pClient); } - - - // IMMDeviceCollection - typedef struct - { - // IUnknown - HRESULT (STDMETHODCALLTYPE * QueryInterface)(mal_IMMDeviceCollection* pThis, const IID* const riid, void** ppObject); - ULONG (STDMETHODCALLTYPE * AddRef) (mal_IMMDeviceCollection* pThis); - ULONG (STDMETHODCALLTYPE * Release) (mal_IMMDeviceCollection* pThis); - - // IMMDeviceCollection - HRESULT (STDMETHODCALLTYPE * GetCount)(mal_IMMDeviceCollection* pThis, UINT* pDevices); - HRESULT (STDMETHODCALLTYPE * Item) (mal_IMMDeviceCollection* pThis, UINT nDevice, mal_IMMDevice** ppDevice); - } mal_IMMDeviceCollectionVtbl; - struct mal_IMMDeviceCollection - { - mal_IMMDeviceCollectionVtbl* lpVtbl; - }; - HRESULT mal_IMMDeviceCollection_QueryInterface(mal_IMMDeviceCollection* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } - ULONG mal_IMMDeviceCollection_AddRef(mal_IMMDeviceCollection* pThis) { return pThis->lpVtbl->AddRef(pThis); } - ULONG mal_IMMDeviceCollection_Release(mal_IMMDeviceCollection* pThis) { return pThis->lpVtbl->Release(pThis); } - HRESULT mal_IMMDeviceCollection_GetCount(mal_IMMDeviceCollection* pThis, UINT* pDevices) { return pThis->lpVtbl->GetCount(pThis, pDevices); } - HRESULT mal_IMMDeviceCollection_Item(mal_IMMDeviceCollection* pThis, UINT nDevice, mal_IMMDevice** ppDevice) { return pThis->lpVtbl->Item(pThis, nDevice, ppDevice); } - - - // IMMDevice - typedef struct - { - // IUnknown - HRESULT (STDMETHODCALLTYPE * QueryInterface)(mal_IMMDevice* pThis, const IID* const riid, void** ppObject); - ULONG (STDMETHODCALLTYPE * AddRef) (mal_IMMDevice* pThis); - ULONG (STDMETHODCALLTYPE * Release) (mal_IMMDevice* pThis); - - // IMMDevice - HRESULT (STDMETHODCALLTYPE * Activate) (mal_IMMDevice* pThis, const IID* const iid, DWORD dwClsCtx, PROPVARIANT* pActivationParams, void** ppInterface); - HRESULT (STDMETHODCALLTYPE * OpenPropertyStore)(mal_IMMDevice* pThis, DWORD stgmAccess, mal_IPropertyStore** ppProperties); - HRESULT (STDMETHODCALLTYPE * GetId) (mal_IMMDevice* pThis, LPWSTR *pID); - HRESULT (STDMETHODCALLTYPE * GetState) (mal_IMMDevice* pThis, DWORD *pState); - } mal_IMMDeviceVtbl; - struct mal_IMMDevice - { - mal_IMMDeviceVtbl* lpVtbl; - }; - HRESULT mal_IMMDevice_QueryInterface(mal_IMMDevice* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } - ULONG mal_IMMDevice_AddRef(mal_IMMDevice* pThis) { return pThis->lpVtbl->AddRef(pThis); } - ULONG mal_IMMDevice_Release(mal_IMMDevice* pThis) { return pThis->lpVtbl->Release(pThis); } - HRESULT mal_IMMDevice_Activate(mal_IMMDevice* pThis, const IID* const iid, DWORD dwClsCtx, PROPVARIANT* pActivationParams, void** ppInterface) { return pThis->lpVtbl->Activate(pThis, iid, dwClsCtx, pActivationParams, ppInterface); } - HRESULT mal_IMMDevice_OpenPropertyStore(mal_IMMDevice* pThis, DWORD stgmAccess, mal_IPropertyStore** ppProperties) { return pThis->lpVtbl->OpenPropertyStore(pThis, stgmAccess, ppProperties); } - HRESULT mal_IMMDevice_GetId(mal_IMMDevice* pThis, LPWSTR *pID) { return pThis->lpVtbl->GetId(pThis, pID); } - HRESULT mal_IMMDevice_GetState(mal_IMMDevice* pThis, DWORD *pState) { return pThis->lpVtbl->GetState(pThis, pState); } -#else - // IActivateAudioInterfaceAsyncOperation - typedef struct - { - // IUnknown - HRESULT (STDMETHODCALLTYPE * QueryInterface)(mal_IActivateAudioInterfaceAsyncOperation* pThis, const IID* const riid, void** ppObject); - ULONG (STDMETHODCALLTYPE * AddRef) (mal_IActivateAudioInterfaceAsyncOperation* pThis); - ULONG (STDMETHODCALLTYPE * Release) (mal_IActivateAudioInterfaceAsyncOperation* pThis); - - // IActivateAudioInterfaceAsyncOperation - HRESULT (STDMETHODCALLTYPE * GetActivateResult)(mal_IActivateAudioInterfaceAsyncOperation* pThis, HRESULT *pActivateResult, mal_IUnknown** ppActivatedInterface); - } mal_IActivateAudioInterfaceAsyncOperationVtbl; - struct mal_IActivateAudioInterfaceAsyncOperation - { - mal_IActivateAudioInterfaceAsyncOperationVtbl* lpVtbl; - }; - HRESULT mal_IActivateAudioInterfaceAsyncOperation_QueryInterface(mal_IActivateAudioInterfaceAsyncOperation* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } - ULONG mal_IActivateAudioInterfaceAsyncOperation_AddRef(mal_IActivateAudioInterfaceAsyncOperation* pThis) { return pThis->lpVtbl->AddRef(pThis); } - ULONG mal_IActivateAudioInterfaceAsyncOperation_Release(mal_IActivateAudioInterfaceAsyncOperation* pThis) { return pThis->lpVtbl->Release(pThis); } - HRESULT mal_IActivateAudioInterfaceAsyncOperation_GetActivateResult(mal_IActivateAudioInterfaceAsyncOperation* pThis, HRESULT *pActivateResult, mal_IUnknown** ppActivatedInterface) { return pThis->lpVtbl->GetActivateResult(pThis, pActivateResult, ppActivatedInterface); } -#endif - -// IPropertyStore -typedef struct -{ - // IUnknown - HRESULT (STDMETHODCALLTYPE * QueryInterface)(mal_IPropertyStore* pThis, const IID* const riid, void** ppObject); - ULONG (STDMETHODCALLTYPE * AddRef) (mal_IPropertyStore* pThis); - ULONG (STDMETHODCALLTYPE * Release) (mal_IPropertyStore* pThis); - - // IPropertyStore - HRESULT (STDMETHODCALLTYPE * GetCount)(mal_IPropertyStore* pThis, DWORD* pPropCount); - HRESULT (STDMETHODCALLTYPE * GetAt) (mal_IPropertyStore* pThis, DWORD propIndex, PROPERTYKEY* pPropKey); - HRESULT (STDMETHODCALLTYPE * GetValue)(mal_IPropertyStore* pThis, const PROPERTYKEY* const pKey, PROPVARIANT* pPropVar); - HRESULT (STDMETHODCALLTYPE * SetValue)(mal_IPropertyStore* pThis, const PROPERTYKEY* const pKey, const PROPVARIANT* const pPropVar); - HRESULT (STDMETHODCALLTYPE * Commit) (mal_IPropertyStore* pThis); -} mal_IPropertyStoreVtbl; -struct mal_IPropertyStore -{ - mal_IPropertyStoreVtbl* lpVtbl; -}; -HRESULT mal_IPropertyStore_QueryInterface(mal_IPropertyStore* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } -ULONG mal_IPropertyStore_AddRef(mal_IPropertyStore* pThis) { return pThis->lpVtbl->AddRef(pThis); } -ULONG mal_IPropertyStore_Release(mal_IPropertyStore* pThis) { return pThis->lpVtbl->Release(pThis); } -HRESULT mal_IPropertyStore_GetCount(mal_IPropertyStore* pThis, DWORD* pPropCount) { return pThis->lpVtbl->GetCount(pThis, pPropCount); } -HRESULT mal_IPropertyStore_GetAt(mal_IPropertyStore* pThis, DWORD propIndex, PROPERTYKEY* pPropKey) { return pThis->lpVtbl->GetAt(pThis, propIndex, pPropKey); } -HRESULT mal_IPropertyStore_GetValue(mal_IPropertyStore* pThis, const PROPERTYKEY* const pKey, PROPVARIANT* pPropVar) { return pThis->lpVtbl->GetValue(pThis, pKey, pPropVar); } -HRESULT mal_IPropertyStore_SetValue(mal_IPropertyStore* pThis, const PROPERTYKEY* const pKey, const PROPVARIANT* const pPropVar) { return pThis->lpVtbl->SetValue(pThis, pKey, pPropVar); } -HRESULT mal_IPropertyStore_Commit(mal_IPropertyStore* pThis) { return pThis->lpVtbl->Commit(pThis); } - - -// IAudioClient -typedef struct -{ - // IUnknown - HRESULT (STDMETHODCALLTYPE * QueryInterface)(mal_IAudioClient* pThis, const IID* const riid, void** ppObject); - ULONG (STDMETHODCALLTYPE * AddRef) (mal_IAudioClient* pThis); - ULONG (STDMETHODCALLTYPE * Release) (mal_IAudioClient* pThis); - - // IAudioClient - HRESULT (STDMETHODCALLTYPE * Initialize) (mal_IAudioClient* pThis, MAL_AUDCLNT_SHAREMODE shareMode, DWORD streamFlags, MAL_REFERENCE_TIME bufferDuration, MAL_REFERENCE_TIME periodicity, const WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid); - HRESULT (STDMETHODCALLTYPE * GetBufferSize) (mal_IAudioClient* pThis, mal_uint32* pNumBufferFrames); - HRESULT (STDMETHODCALLTYPE * GetStreamLatency) (mal_IAudioClient* pThis, MAL_REFERENCE_TIME* pLatency); - HRESULT (STDMETHODCALLTYPE * GetCurrentPadding)(mal_IAudioClient* pThis, mal_uint32* pNumPaddingFrames); - HRESULT (STDMETHODCALLTYPE * IsFormatSupported)(mal_IAudioClient* pThis, MAL_AUDCLNT_SHAREMODE shareMode, const WAVEFORMATEX* pFormat, WAVEFORMATEX** ppClosestMatch); - HRESULT (STDMETHODCALLTYPE * GetMixFormat) (mal_IAudioClient* pThis, WAVEFORMATEX** ppDeviceFormat); - HRESULT (STDMETHODCALLTYPE * GetDevicePeriod) (mal_IAudioClient* pThis, MAL_REFERENCE_TIME* pDefaultDevicePeriod, MAL_REFERENCE_TIME* pMinimumDevicePeriod); - HRESULT (STDMETHODCALLTYPE * Start) (mal_IAudioClient* pThis); - HRESULT (STDMETHODCALLTYPE * Stop) (mal_IAudioClient* pThis); - HRESULT (STDMETHODCALLTYPE * Reset) (mal_IAudioClient* pThis); - HRESULT (STDMETHODCALLTYPE * SetEventHandle) (mal_IAudioClient* pThis, HANDLE eventHandle); - HRESULT (STDMETHODCALLTYPE * GetService) (mal_IAudioClient* pThis, const IID* const riid, void** pp); -} mal_IAudioClientVtbl; -struct mal_IAudioClient -{ - mal_IAudioClientVtbl* lpVtbl; -}; -HRESULT mal_IAudioClient_QueryInterface(mal_IAudioClient* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } -ULONG mal_IAudioClient_AddRef(mal_IAudioClient* pThis) { return pThis->lpVtbl->AddRef(pThis); } -ULONG mal_IAudioClient_Release(mal_IAudioClient* pThis) { return pThis->lpVtbl->Release(pThis); } -HRESULT mal_IAudioClient_Initialize(mal_IAudioClient* pThis, MAL_AUDCLNT_SHAREMODE shareMode, DWORD streamFlags, MAL_REFERENCE_TIME bufferDuration, MAL_REFERENCE_TIME periodicity, const WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid) { return pThis->lpVtbl->Initialize(pThis, shareMode, streamFlags, bufferDuration, periodicity, pFormat, pAudioSessionGuid); } -HRESULT mal_IAudioClient_GetBufferSize(mal_IAudioClient* pThis, mal_uint32* pNumBufferFrames) { return pThis->lpVtbl->GetBufferSize(pThis, pNumBufferFrames); } -HRESULT mal_IAudioClient_GetStreamLatency(mal_IAudioClient* pThis, MAL_REFERENCE_TIME* pLatency) { return pThis->lpVtbl->GetStreamLatency(pThis, pLatency); } -HRESULT mal_IAudioClient_GetCurrentPadding(mal_IAudioClient* pThis, mal_uint32* pNumPaddingFrames) { return pThis->lpVtbl->GetCurrentPadding(pThis, pNumPaddingFrames); } -HRESULT mal_IAudioClient_IsFormatSupported(mal_IAudioClient* pThis, MAL_AUDCLNT_SHAREMODE shareMode, const WAVEFORMATEX* pFormat, WAVEFORMATEX** ppClosestMatch) { return pThis->lpVtbl->IsFormatSupported(pThis, shareMode, pFormat, ppClosestMatch); } -HRESULT mal_IAudioClient_GetMixFormat(mal_IAudioClient* pThis, WAVEFORMATEX** ppDeviceFormat) { return pThis->lpVtbl->GetMixFormat(pThis, ppDeviceFormat); } -HRESULT mal_IAudioClient_GetDevicePeriod(mal_IAudioClient* pThis, MAL_REFERENCE_TIME* pDefaultDevicePeriod, MAL_REFERENCE_TIME* pMinimumDevicePeriod) { return pThis->lpVtbl->GetDevicePeriod(pThis, pDefaultDevicePeriod, pMinimumDevicePeriod); } -HRESULT mal_IAudioClient_Start(mal_IAudioClient* pThis) { return pThis->lpVtbl->Start(pThis); } -HRESULT mal_IAudioClient_Stop(mal_IAudioClient* pThis) { return pThis->lpVtbl->Stop(pThis); } -HRESULT mal_IAudioClient_Reset(mal_IAudioClient* pThis) { return pThis->lpVtbl->Reset(pThis); } -HRESULT mal_IAudioClient_SetEventHandle(mal_IAudioClient* pThis, HANDLE eventHandle) { return pThis->lpVtbl->SetEventHandle(pThis, eventHandle); } -HRESULT mal_IAudioClient_GetService(mal_IAudioClient* pThis, const IID* const riid, void** pp) { return pThis->lpVtbl->GetService(pThis, riid, pp); } - -// IAudioClient2 -typedef struct -{ - // IUnknown - HRESULT (STDMETHODCALLTYPE * QueryInterface)(mal_IAudioClient2* pThis, const IID* const riid, void** ppObject); - ULONG (STDMETHODCALLTYPE * AddRef) (mal_IAudioClient2* pThis); - ULONG (STDMETHODCALLTYPE * Release) (mal_IAudioClient2* pThis); - - // IAudioClient - HRESULT (STDMETHODCALLTYPE * Initialize) (mal_IAudioClient2* pThis, MAL_AUDCLNT_SHAREMODE shareMode, DWORD streamFlags, MAL_REFERENCE_TIME bufferDuration, MAL_REFERENCE_TIME periodicity, const WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid); - HRESULT (STDMETHODCALLTYPE * GetBufferSize) (mal_IAudioClient2* pThis, mal_uint32* pNumBufferFrames); - HRESULT (STDMETHODCALLTYPE * GetStreamLatency) (mal_IAudioClient2* pThis, MAL_REFERENCE_TIME* pLatency); - HRESULT (STDMETHODCALLTYPE * GetCurrentPadding)(mal_IAudioClient2* pThis, mal_uint32* pNumPaddingFrames); - HRESULT (STDMETHODCALLTYPE * IsFormatSupported)(mal_IAudioClient2* pThis, MAL_AUDCLNT_SHAREMODE shareMode, const WAVEFORMATEX* pFormat, WAVEFORMATEX** ppClosestMatch); - HRESULT (STDMETHODCALLTYPE * GetMixFormat) (mal_IAudioClient2* pThis, WAVEFORMATEX** ppDeviceFormat); - HRESULT (STDMETHODCALLTYPE * GetDevicePeriod) (mal_IAudioClient2* pThis, MAL_REFERENCE_TIME* pDefaultDevicePeriod, MAL_REFERENCE_TIME* pMinimumDevicePeriod); - HRESULT (STDMETHODCALLTYPE * Start) (mal_IAudioClient2* pThis); - HRESULT (STDMETHODCALLTYPE * Stop) (mal_IAudioClient2* pThis); - HRESULT (STDMETHODCALLTYPE * Reset) (mal_IAudioClient2* pThis); - HRESULT (STDMETHODCALLTYPE * SetEventHandle) (mal_IAudioClient2* pThis, HANDLE eventHandle); - HRESULT (STDMETHODCALLTYPE * GetService) (mal_IAudioClient2* pThis, const IID* const riid, void** pp); - - // IAudioClient2 - HRESULT (STDMETHODCALLTYPE * IsOffloadCapable) (mal_IAudioClient2* pThis, MAL_AUDIO_STREAM_CATEGORY category, BOOL* pOffloadCapable); - HRESULT (STDMETHODCALLTYPE * SetClientProperties)(mal_IAudioClient2* pThis, const mal_AudioClientProperties* pProperties); - HRESULT (STDMETHODCALLTYPE * GetBufferSizeLimits)(mal_IAudioClient2* pThis, const WAVEFORMATEX* pFormat, BOOL eventDriven, MAL_REFERENCE_TIME* pMinBufferDuration, MAL_REFERENCE_TIME* pMaxBufferDuration); -} mal_IAudioClient2Vtbl; -struct mal_IAudioClient2 -{ - mal_IAudioClient2Vtbl* lpVtbl; -}; -HRESULT mal_IAudioClient2_QueryInterface(mal_IAudioClient2* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } -ULONG mal_IAudioClient2_AddRef(mal_IAudioClient2* pThis) { return pThis->lpVtbl->AddRef(pThis); } -ULONG mal_IAudioClient2_Release(mal_IAudioClient2* pThis) { return pThis->lpVtbl->Release(pThis); } -HRESULT mal_IAudioClient2_Initialize(mal_IAudioClient2* pThis, MAL_AUDCLNT_SHAREMODE shareMode, DWORD streamFlags, MAL_REFERENCE_TIME bufferDuration, MAL_REFERENCE_TIME periodicity, const WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid) { return pThis->lpVtbl->Initialize(pThis, shareMode, streamFlags, bufferDuration, periodicity, pFormat, pAudioSessionGuid); } -HRESULT mal_IAudioClient2_GetBufferSize(mal_IAudioClient2* pThis, mal_uint32* pNumBufferFrames) { return pThis->lpVtbl->GetBufferSize(pThis, pNumBufferFrames); } -HRESULT mal_IAudioClient2_GetStreamLatency(mal_IAudioClient2* pThis, MAL_REFERENCE_TIME* pLatency) { return pThis->lpVtbl->GetStreamLatency(pThis, pLatency); } -HRESULT mal_IAudioClient2_GetCurrentPadding(mal_IAudioClient2* pThis, mal_uint32* pNumPaddingFrames) { return pThis->lpVtbl->GetCurrentPadding(pThis, pNumPaddingFrames); } -HRESULT mal_IAudioClient2_IsFormatSupported(mal_IAudioClient2* pThis, MAL_AUDCLNT_SHAREMODE shareMode, const WAVEFORMATEX* pFormat, WAVEFORMATEX** ppClosestMatch) { return pThis->lpVtbl->IsFormatSupported(pThis, shareMode, pFormat, ppClosestMatch); } -HRESULT mal_IAudioClient2_GetMixFormat(mal_IAudioClient2* pThis, WAVEFORMATEX** ppDeviceFormat) { return pThis->lpVtbl->GetMixFormat(pThis, ppDeviceFormat); } -HRESULT mal_IAudioClient2_GetDevicePeriod(mal_IAudioClient2* pThis, MAL_REFERENCE_TIME* pDefaultDevicePeriod, MAL_REFERENCE_TIME* pMinimumDevicePeriod) { return pThis->lpVtbl->GetDevicePeriod(pThis, pDefaultDevicePeriod, pMinimumDevicePeriod); } -HRESULT mal_IAudioClient2_Start(mal_IAudioClient2* pThis) { return pThis->lpVtbl->Start(pThis); } -HRESULT mal_IAudioClient2_Stop(mal_IAudioClient2* pThis) { return pThis->lpVtbl->Stop(pThis); } -HRESULT mal_IAudioClient2_Reset(mal_IAudioClient2* pThis) { return pThis->lpVtbl->Reset(pThis); } -HRESULT mal_IAudioClient2_SetEventHandle(mal_IAudioClient2* pThis, HANDLE eventHandle) { return pThis->lpVtbl->SetEventHandle(pThis, eventHandle); } -HRESULT mal_IAudioClient2_GetService(mal_IAudioClient2* pThis, const IID* const riid, void** pp) { return pThis->lpVtbl->GetService(pThis, riid, pp); } -HRESULT mal_IAudioClient2_IsOffloadCapable(mal_IAudioClient2* pThis, MAL_AUDIO_STREAM_CATEGORY category, BOOL* pOffloadCapable) { return pThis->lpVtbl->IsOffloadCapable(pThis, category, pOffloadCapable); } -HRESULT mal_IAudioClient2_SetClientProperties(mal_IAudioClient2* pThis, const mal_AudioClientProperties* pProperties) { return pThis->lpVtbl->SetClientProperties(pThis, pProperties); } -HRESULT mal_IAudioClient2_GetBufferSizeLimits(mal_IAudioClient2* pThis, const WAVEFORMATEX* pFormat, BOOL eventDriven, MAL_REFERENCE_TIME* pMinBufferDuration, MAL_REFERENCE_TIME* pMaxBufferDuration) { return pThis->lpVtbl->GetBufferSizeLimits(pThis, pFormat, eventDriven, pMinBufferDuration, pMaxBufferDuration); } - - -// IAudioClient3 -typedef struct -{ - // IUnknown - HRESULT (STDMETHODCALLTYPE * QueryInterface)(mal_IAudioClient3* pThis, const IID* const riid, void** ppObject); - ULONG (STDMETHODCALLTYPE * AddRef) (mal_IAudioClient3* pThis); - ULONG (STDMETHODCALLTYPE * Release) (mal_IAudioClient3* pThis); - - // IAudioClient - HRESULT (STDMETHODCALLTYPE * Initialize) (mal_IAudioClient3* pThis, MAL_AUDCLNT_SHAREMODE shareMode, DWORD streamFlags, MAL_REFERENCE_TIME bufferDuration, MAL_REFERENCE_TIME periodicity, const WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid); - HRESULT (STDMETHODCALLTYPE * GetBufferSize) (mal_IAudioClient3* pThis, mal_uint32* pNumBufferFrames); - HRESULT (STDMETHODCALLTYPE * GetStreamLatency) (mal_IAudioClient3* pThis, MAL_REFERENCE_TIME* pLatency); - HRESULT (STDMETHODCALLTYPE * GetCurrentPadding)(mal_IAudioClient3* pThis, mal_uint32* pNumPaddingFrames); - HRESULT (STDMETHODCALLTYPE * IsFormatSupported)(mal_IAudioClient3* pThis, MAL_AUDCLNT_SHAREMODE shareMode, const WAVEFORMATEX* pFormat, WAVEFORMATEX** ppClosestMatch); - HRESULT (STDMETHODCALLTYPE * GetMixFormat) (mal_IAudioClient3* pThis, WAVEFORMATEX** ppDeviceFormat); - HRESULT (STDMETHODCALLTYPE * GetDevicePeriod) (mal_IAudioClient3* pThis, MAL_REFERENCE_TIME* pDefaultDevicePeriod, MAL_REFERENCE_TIME* pMinimumDevicePeriod); - HRESULT (STDMETHODCALLTYPE * Start) (mal_IAudioClient3* pThis); - HRESULT (STDMETHODCALLTYPE * Stop) (mal_IAudioClient3* pThis); - HRESULT (STDMETHODCALLTYPE * Reset) (mal_IAudioClient3* pThis); - HRESULT (STDMETHODCALLTYPE * SetEventHandle) (mal_IAudioClient3* pThis, HANDLE eventHandle); - HRESULT (STDMETHODCALLTYPE * GetService) (mal_IAudioClient3* pThis, const IID* const riid, void** pp); - - // IAudioClient2 - HRESULT (STDMETHODCALLTYPE * IsOffloadCapable) (mal_IAudioClient3* pThis, MAL_AUDIO_STREAM_CATEGORY category, BOOL* pOffloadCapable); - HRESULT (STDMETHODCALLTYPE * SetClientProperties)(mal_IAudioClient3* pThis, const mal_AudioClientProperties* pProperties); - HRESULT (STDMETHODCALLTYPE * GetBufferSizeLimits)(mal_IAudioClient3* pThis, const WAVEFORMATEX* pFormat, BOOL eventDriven, MAL_REFERENCE_TIME* pMinBufferDuration, MAL_REFERENCE_TIME* pMaxBufferDuration); - - // IAudioClient3 - HRESULT (STDMETHODCALLTYPE * GetSharedModeEnginePeriod) (mal_IAudioClient3* pThis, const WAVEFORMATEX* pFormat, UINT32* pDefaultPeriodInFrames, UINT32* pFundamentalPeriodInFrames, UINT32* pMinPeriodInFrames, UINT32* pMaxPeriodInFrames); - HRESULT (STDMETHODCALLTYPE * GetCurrentSharedModeEnginePeriod)(mal_IAudioClient3* pThis, WAVEFORMATEX** ppFormat, UINT32* pCurrentPeriodInFrames); - HRESULT (STDMETHODCALLTYPE * InitializeSharedAudioStream) (mal_IAudioClient3* pThis, DWORD streamFlags, UINT32 periodInFrames, const WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid); -} mal_IAudioClient3Vtbl; -struct mal_IAudioClient3 -{ - mal_IAudioClient3Vtbl* lpVtbl; -}; -HRESULT mal_IAudioClient3_QueryInterface(mal_IAudioClient3* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } -ULONG mal_IAudioClient3_AddRef(mal_IAudioClient3* pThis) { return pThis->lpVtbl->AddRef(pThis); } -ULONG mal_IAudioClient3_Release(mal_IAudioClient3* pThis) { return pThis->lpVtbl->Release(pThis); } -HRESULT mal_IAudioClient3_Initialize(mal_IAudioClient3* pThis, MAL_AUDCLNT_SHAREMODE shareMode, DWORD streamFlags, MAL_REFERENCE_TIME bufferDuration, MAL_REFERENCE_TIME periodicity, const WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid) { return pThis->lpVtbl->Initialize(pThis, shareMode, streamFlags, bufferDuration, periodicity, pFormat, pAudioSessionGuid); } -HRESULT mal_IAudioClient3_GetBufferSize(mal_IAudioClient3* pThis, mal_uint32* pNumBufferFrames) { return pThis->lpVtbl->GetBufferSize(pThis, pNumBufferFrames); } -HRESULT mal_IAudioClient3_GetStreamLatency(mal_IAudioClient3* pThis, MAL_REFERENCE_TIME* pLatency) { return pThis->lpVtbl->GetStreamLatency(pThis, pLatency); } -HRESULT mal_IAudioClient3_GetCurrentPadding(mal_IAudioClient3* pThis, mal_uint32* pNumPaddingFrames) { return pThis->lpVtbl->GetCurrentPadding(pThis, pNumPaddingFrames); } -HRESULT mal_IAudioClient3_IsFormatSupported(mal_IAudioClient3* pThis, MAL_AUDCLNT_SHAREMODE shareMode, const WAVEFORMATEX* pFormat, WAVEFORMATEX** ppClosestMatch) { return pThis->lpVtbl->IsFormatSupported(pThis, shareMode, pFormat, ppClosestMatch); } -HRESULT mal_IAudioClient3_GetMixFormat(mal_IAudioClient3* pThis, WAVEFORMATEX** ppDeviceFormat) { return pThis->lpVtbl->GetMixFormat(pThis, ppDeviceFormat); } -HRESULT mal_IAudioClient3_GetDevicePeriod(mal_IAudioClient3* pThis, MAL_REFERENCE_TIME* pDefaultDevicePeriod, MAL_REFERENCE_TIME* pMinimumDevicePeriod) { return pThis->lpVtbl->GetDevicePeriod(pThis, pDefaultDevicePeriod, pMinimumDevicePeriod); } -HRESULT mal_IAudioClient3_Start(mal_IAudioClient3* pThis) { return pThis->lpVtbl->Start(pThis); } -HRESULT mal_IAudioClient3_Stop(mal_IAudioClient3* pThis) { return pThis->lpVtbl->Stop(pThis); } -HRESULT mal_IAudioClient3_Reset(mal_IAudioClient3* pThis) { return pThis->lpVtbl->Reset(pThis); } -HRESULT mal_IAudioClient3_SetEventHandle(mal_IAudioClient3* pThis, HANDLE eventHandle) { return pThis->lpVtbl->SetEventHandle(pThis, eventHandle); } -HRESULT mal_IAudioClient3_GetService(mal_IAudioClient3* pThis, const IID* const riid, void** pp) { return pThis->lpVtbl->GetService(pThis, riid, pp); } -HRESULT mal_IAudioClient3_IsOffloadCapable(mal_IAudioClient3* pThis, MAL_AUDIO_STREAM_CATEGORY category, BOOL* pOffloadCapable) { return pThis->lpVtbl->IsOffloadCapable(pThis, category, pOffloadCapable); } -HRESULT mal_IAudioClient3_SetClientProperties(mal_IAudioClient3* pThis, const mal_AudioClientProperties* pProperties) { return pThis->lpVtbl->SetClientProperties(pThis, pProperties); } -HRESULT mal_IAudioClient3_GetBufferSizeLimits(mal_IAudioClient3* pThis, const WAVEFORMATEX* pFormat, BOOL eventDriven, MAL_REFERENCE_TIME* pMinBufferDuration, MAL_REFERENCE_TIME* pMaxBufferDuration) { return pThis->lpVtbl->GetBufferSizeLimits(pThis, pFormat, eventDriven, pMinBufferDuration, pMaxBufferDuration); } -HRESULT mal_IAudioClient3_GetSharedModeEnginePeriod(mal_IAudioClient3* pThis, const WAVEFORMATEX* pFormat, UINT32* pDefaultPeriodInFrames, UINT32* pFundamentalPeriodInFrames, UINT32* pMinPeriodInFrames, UINT32* pMaxPeriodInFrames) { return pThis->lpVtbl->GetSharedModeEnginePeriod(pThis, pFormat, pDefaultPeriodInFrames, pFundamentalPeriodInFrames, pMinPeriodInFrames, pMaxPeriodInFrames); } -HRESULT mal_IAudioClient3_GetCurrentSharedModeEnginePeriod(mal_IAudioClient3* pThis, WAVEFORMATEX** ppFormat, UINT32* pCurrentPeriodInFrames) { return pThis->lpVtbl->GetCurrentSharedModeEnginePeriod(pThis, ppFormat, pCurrentPeriodInFrames); } -HRESULT mal_IAudioClient3_InitializeSharedAudioStream(mal_IAudioClient3* pThis, DWORD streamFlags, UINT32 periodInFrames, const WAVEFORMATEX* pFormat, const GUID* pAudioSessionGUID) { return pThis->lpVtbl->InitializeSharedAudioStream(pThis, streamFlags, periodInFrames, pFormat, pAudioSessionGUID); } - - -// IAudioRenderClient -typedef struct -{ - // IUnknown - HRESULT (STDMETHODCALLTYPE * QueryInterface)(mal_IAudioRenderClient* pThis, const IID* const riid, void** ppObject); - ULONG (STDMETHODCALLTYPE * AddRef) (mal_IAudioRenderClient* pThis); - ULONG (STDMETHODCALLTYPE * Release) (mal_IAudioRenderClient* pThis); - - // IAudioRenderClient - HRESULT (STDMETHODCALLTYPE * GetBuffer) (mal_IAudioRenderClient* pThis, mal_uint32 numFramesRequested, BYTE** ppData); - HRESULT (STDMETHODCALLTYPE * ReleaseBuffer)(mal_IAudioRenderClient* pThis, mal_uint32 numFramesWritten, DWORD dwFlags); -} mal_IAudioRenderClientVtbl; -struct mal_IAudioRenderClient -{ - mal_IAudioRenderClientVtbl* lpVtbl; -}; -HRESULT mal_IAudioRenderClient_QueryInterface(mal_IAudioRenderClient* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } -ULONG mal_IAudioRenderClient_AddRef(mal_IAudioRenderClient* pThis) { return pThis->lpVtbl->AddRef(pThis); } -ULONG mal_IAudioRenderClient_Release(mal_IAudioRenderClient* pThis) { return pThis->lpVtbl->Release(pThis); } -HRESULT mal_IAudioRenderClient_GetBuffer(mal_IAudioRenderClient* pThis, mal_uint32 numFramesRequested, BYTE** ppData) { return pThis->lpVtbl->GetBuffer(pThis, numFramesRequested, ppData); } -HRESULT mal_IAudioRenderClient_ReleaseBuffer(mal_IAudioRenderClient* pThis, mal_uint32 numFramesWritten, DWORD dwFlags) { return pThis->lpVtbl->ReleaseBuffer(pThis, numFramesWritten, dwFlags); } - - -// IAudioCaptureClient -typedef struct -{ - // IUnknown - HRESULT (STDMETHODCALLTYPE * QueryInterface)(mal_IAudioCaptureClient* pThis, const IID* const riid, void** ppObject); - ULONG (STDMETHODCALLTYPE * AddRef) (mal_IAudioCaptureClient* pThis); - ULONG (STDMETHODCALLTYPE * Release) (mal_IAudioCaptureClient* pThis); - - // IAudioRenderClient - HRESULT (STDMETHODCALLTYPE * GetBuffer) (mal_IAudioCaptureClient* pThis, BYTE** ppData, mal_uint32* pNumFramesToRead, DWORD* pFlags, mal_uint64* pDevicePosition, mal_uint64* pQPCPosition); - HRESULT (STDMETHODCALLTYPE * ReleaseBuffer) (mal_IAudioCaptureClient* pThis, mal_uint32 numFramesRead); - HRESULT (STDMETHODCALLTYPE * GetNextPacketSize)(mal_IAudioCaptureClient* pThis, mal_uint32* pNumFramesInNextPacket); -} mal_IAudioCaptureClientVtbl; -struct mal_IAudioCaptureClient -{ - mal_IAudioCaptureClientVtbl* lpVtbl; -}; -HRESULT mal_IAudioCaptureClient_QueryInterface(mal_IAudioCaptureClient* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } -ULONG mal_IAudioCaptureClient_AddRef(mal_IAudioCaptureClient* pThis) { return pThis->lpVtbl->AddRef(pThis); } -ULONG mal_IAudioCaptureClient_Release(mal_IAudioCaptureClient* pThis) { return pThis->lpVtbl->Release(pThis); } -HRESULT mal_IAudioCaptureClient_GetBuffer(mal_IAudioCaptureClient* pThis, BYTE** ppData, mal_uint32* pNumFramesToRead, DWORD* pFlags, mal_uint64* pDevicePosition, mal_uint64* pQPCPosition) { return pThis->lpVtbl->GetBuffer(pThis, ppData, pNumFramesToRead, pFlags, pDevicePosition, pQPCPosition); } -HRESULT mal_IAudioCaptureClient_ReleaseBuffer(mal_IAudioCaptureClient* pThis, mal_uint32 numFramesRead) { return pThis->lpVtbl->ReleaseBuffer(pThis, numFramesRead); } -HRESULT mal_IAudioCaptureClient_GetNextPacketSize(mal_IAudioCaptureClient* pThis, mal_uint32* pNumFramesInNextPacket) { return pThis->lpVtbl->GetNextPacketSize(pThis, pNumFramesInNextPacket); } - -#ifndef MAL_WIN32_DESKTOP -#include -typedef struct mal_completion_handler_uwp mal_completion_handler_uwp; - -typedef struct -{ - // IUnknown - HRESULT (STDMETHODCALLTYPE * QueryInterface)(mal_completion_handler_uwp* pThis, const IID* const riid, void** ppObject); - ULONG (STDMETHODCALLTYPE * AddRef) (mal_completion_handler_uwp* pThis); - ULONG (STDMETHODCALLTYPE * Release) (mal_completion_handler_uwp* pThis); - - // IActivateAudioInterfaceCompletionHandler - HRESULT (STDMETHODCALLTYPE * ActivateCompleted)(mal_completion_handler_uwp* pThis, mal_IActivateAudioInterfaceAsyncOperation* pActivateOperation); -} mal_completion_handler_uwp_vtbl; -struct mal_completion_handler_uwp -{ - mal_completion_handler_uwp_vtbl* lpVtbl; - mal_uint32 counter; - HANDLE hEvent; -}; - -HRESULT STDMETHODCALLTYPE mal_completion_handler_uwp_QueryInterface(mal_completion_handler_uwp* pThis, const IID* const riid, void** ppObject) -{ - // We need to "implement" IAgileObject which is just an indicator that's used internally by WASAPI for some multithreading management. To - // "implement" this, we just make sure we return pThis when the IAgileObject is requested. - if (!mal_is_guid_equal(riid, &MAL_IID_IUnknown) && !mal_is_guid_equal(riid, &MAL_IID_IActivateAudioInterfaceCompletionHandler) && !mal_is_guid_equal(riid, &MAL_IID_IAgileObject)) { - *ppObject = NULL; - return E_NOINTERFACE; - } - - // Getting here means the IID is IUnknown or IMMNotificationClient. - *ppObject = (void*)pThis; - ((mal_completion_handler_uwp_vtbl*)pThis->lpVtbl)->AddRef(pThis); - return S_OK; -} - -ULONG STDMETHODCALLTYPE mal_completion_handler_uwp_AddRef(mal_completion_handler_uwp* pThis) -{ - return (ULONG)mal_atomic_increment_32(&pThis->counter); -} - -ULONG STDMETHODCALLTYPE mal_completion_handler_uwp_Release(mal_completion_handler_uwp* pThis) -{ - mal_uint32 newRefCount = mal_atomic_decrement_32(&pThis->counter); - if (newRefCount == 0) { - return 0; // We don't free anything here because we never allocate the object on the heap. - } - - return (ULONG)newRefCount; -} - -HRESULT STDMETHODCALLTYPE mal_completion_handler_uwp_ActivateCompleted(mal_completion_handler_uwp* pThis, mal_IActivateAudioInterfaceAsyncOperation* pActivateOperation) -{ - (void)pActivateOperation; - SetEvent(pThis->hEvent); - return S_OK; -} - - -static mal_completion_handler_uwp_vtbl g_malCompletionHandlerVtblInstance = { - mal_completion_handler_uwp_QueryInterface, - mal_completion_handler_uwp_AddRef, - mal_completion_handler_uwp_Release, - mal_completion_handler_uwp_ActivateCompleted -}; - -mal_result mal_completion_handler_uwp_init(mal_completion_handler_uwp* pHandler) -{ - mal_assert(pHandler != NULL); - mal_zero_object(pHandler); - - pHandler->lpVtbl = &g_malCompletionHandlerVtblInstance; - pHandler->counter = 1; - pHandler->hEvent = CreateEventA(NULL, FALSE, FALSE, NULL); - if (pHandler->hEvent == NULL) { - return MAL_ERROR; - } - - return MAL_SUCCESS; -} - -void mal_completion_handler_uwp_uninit(mal_completion_handler_uwp* pHandler) -{ - if (pHandler->hEvent != NULL) { - CloseHandle(pHandler->hEvent); - } -} - -void mal_completion_handler_uwp_wait(mal_completion_handler_uwp* pHandler) -{ - WaitForSingleObject(pHandler->hEvent, INFINITE); -} -#endif // !MAL_WIN32_DESKTOP - -// We need a virtual table for our notification client object that's used for detecting changes to the default device. -#ifdef MAL_WIN32_DESKTOP -HRESULT STDMETHODCALLTYPE mal_IMMNotificationClient_QueryInterface(mal_IMMNotificationClient* pThis, const IID* const riid, void** ppObject) -{ - // We care about two interfaces - IUnknown and IMMNotificationClient. If the requested IID is something else - // we just return E_NOINTERFACE. Otherwise we need to increment the reference counter and return S_OK. - if (!mal_is_guid_equal(riid, &MAL_IID_IUnknown) && !mal_is_guid_equal(riid, &MAL_IID_IMMNotificationClient)) { - *ppObject = NULL; - return E_NOINTERFACE; - } - - // Getting here means the IID is IUnknown or IMMNotificationClient. - *ppObject = (void*)pThis; - ((mal_IMMNotificationClientVtbl*)pThis->lpVtbl)->AddRef(pThis); - return S_OK; -} - -ULONG STDMETHODCALLTYPE mal_IMMNotificationClient_AddRef(mal_IMMNotificationClient* pThis) -{ - return (ULONG)mal_atomic_increment_32(&pThis->counter); -} - -ULONG STDMETHODCALLTYPE mal_IMMNotificationClient_Release(mal_IMMNotificationClient* pThis) -{ - mal_uint32 newRefCount = mal_atomic_decrement_32(&pThis->counter); - if (newRefCount == 0) { - return 0; // We don't free anything here because we never allocate the object on the heap. - } - - return (ULONG)newRefCount; -} - - -HRESULT STDMETHODCALLTYPE mal_IMMNotificationClient_OnDeviceStateChanged(mal_IMMNotificationClient* pThis, LPCWSTR pDeviceID, DWORD dwNewState) -{ -#ifdef MAL_DEBUG_OUTPUT - printf("IMMNotificationClient_OnDeviceStateChanged(pDeviceID=%S, dwNewState=%u)\n", pDeviceID, (unsigned int)dwNewState); -#endif - - (void)pThis; - (void)pDeviceID; - (void)dwNewState; - return S_OK; -} - -HRESULT STDMETHODCALLTYPE mal_IMMNotificationClient_OnDeviceAdded(mal_IMMNotificationClient* pThis, LPCWSTR pDeviceID) -{ -#ifdef MAL_DEBUG_OUTPUT - printf("IMMNotificationClient_OnDeviceAdded(pDeviceID=%S)\n", pDeviceID); -#endif - - // We don't need to worry about this event for our purposes. - (void)pThis; - (void)pDeviceID; - return S_OK; -} - -HRESULT STDMETHODCALLTYPE mal_IMMNotificationClient_OnDeviceRemoved(mal_IMMNotificationClient* pThis, LPCWSTR pDeviceID) -{ -#ifdef MAL_DEBUG_OUTPUT - printf("IMMNotificationClient_OnDeviceRemoved(pDeviceID=%S)\n", pDeviceID); -#endif - - // We don't need to worry about this event for our purposes. - (void)pThis; - (void)pDeviceID; - return S_OK; -} - -HRESULT STDMETHODCALLTYPE mal_IMMNotificationClient_OnDefaultDeviceChanged(mal_IMMNotificationClient* pThis, mal_EDataFlow dataFlow, mal_ERole role, LPCWSTR pDefaultDeviceID) -{ -#ifdef MAL_DEBUG_OUTPUT - printf("IMMNotificationClient_OnDefaultDeviceChanged(dataFlow=%d, role=%d, pDefaultDeviceID=%S)\n", dataFlow, role, pDefaultDeviceID); -#endif - - // We only ever use the eConsole role in mini_al. - if (role != mal_eConsole) { - return S_OK; - } - - // We only care about devices with the same data flow and role as the current device. - if ((pThis->pDevice->type == mal_device_type_playback && dataFlow != mal_eRender ) || - (pThis->pDevice->type == mal_device_type_capture && dataFlow != mal_eCapture)) { - return S_OK; - } - - // Not currently supporting automatic stream routing in exclusive mode. This is not working correctly on my machine due to - // AUDCLNT_E_DEVICE_IN_USE errors when reinitializing the device. If this is a bug in mini_al, we can try re-enabling this once - // it's fixed. - if (pThis->pDevice->exclusiveMode) { - return S_OK; - } - - // We don't change the device here - we change it in the worker thread to keep synchronization simple. To this I'm just setting a flag to - // indicate that the default device has changed. - mal_atomic_exchange_32(&pThis->pDevice->wasapi.hasDefaultDeviceChanged, MAL_TRUE); - SetEvent(pThis->pDevice->wasapi.hBreakEvent); // <-- The main loop will be waiting on some events. We want to break from this wait ASAP so we can change the device as quickly as possible. - - - (void)pDefaultDeviceID; - return S_OK; -} - -HRESULT STDMETHODCALLTYPE mal_IMMNotificationClient_OnPropertyValueChanged(mal_IMMNotificationClient* pThis, LPCWSTR pDeviceID, const PROPERTYKEY key) -{ -#ifdef MAL_DEBUG_OUTPUT - printf("IMMNotificationClient_OnPropertyValueChanged(pDeviceID=%S)\n", pDeviceID); -#endif - - (void)pThis; - (void)pDeviceID; - (void)key; - return S_OK; -} - -static mal_IMMNotificationClientVtbl g_malNotificationCientVtbl = { - mal_IMMNotificationClient_QueryInterface, - mal_IMMNotificationClient_AddRef, - mal_IMMNotificationClient_Release, - mal_IMMNotificationClient_OnDeviceStateChanged, - mal_IMMNotificationClient_OnDeviceAdded, - mal_IMMNotificationClient_OnDeviceRemoved, - mal_IMMNotificationClient_OnDefaultDeviceChanged, - mal_IMMNotificationClient_OnPropertyValueChanged -}; -#endif // MAL_WIN32_DESKTOP - -mal_bool32 mal_context_is_device_id_equal__wasapi(mal_context* pContext, const mal_device_id* pID0, const mal_device_id* pID1) -{ - mal_assert(pContext != NULL); - mal_assert(pID0 != NULL); - mal_assert(pID1 != NULL); - (void)pContext; - - return memcmp(pID0->wasapi, pID1->wasapi, sizeof(pID0->wasapi)) == 0; -} - -void mal_set_device_info_from_WAVEFORMATEX(const WAVEFORMATEX* pWF, mal_device_info* pInfo) -{ - mal_assert(pWF != NULL); - mal_assert(pInfo != NULL); - - pInfo->formatCount = 1; - pInfo->formats[0] = mal_format_from_WAVEFORMATEX(pWF); - pInfo->minChannels = pWF->nChannels; - pInfo->maxChannels = pWF->nChannels; - pInfo->minSampleRate = pWF->nSamplesPerSec; - pInfo->maxSampleRate = pWF->nSamplesPerSec; -} - -#ifndef MAL_WIN32_DESKTOP -mal_result mal_context_get_IAudioClient_UWP__wasapi(mal_context* pContext, mal_device_type deviceType, const mal_device_id* pDeviceID, mal_IAudioClient** ppAudioClient, mal_IUnknown** ppActivatedInterface) -{ - mal_assert(pContext != NULL); - mal_assert(ppAudioClient != NULL); - - mal_IActivateAudioInterfaceAsyncOperation *pAsyncOp = NULL; - mal_completion_handler_uwp completionHandler; - - IID iid; - if (pDeviceID != NULL) { - mal_copy_memory(&iid, pDeviceID->wasapi, sizeof(iid)); - } else { - if (deviceType == mal_device_type_playback) { - iid = MAL_IID_DEVINTERFACE_AUDIO_RENDER; - } else { - iid = MAL_IID_DEVINTERFACE_AUDIO_CAPTURE; - } - } - - LPOLESTR iidStr; -#if defined(__cplusplus) - HRESULT hr = StringFromIID(iid, &iidStr); -#else - HRESULT hr = StringFromIID(&iid, &iidStr); -#endif - if (FAILED(hr)) { - return mal_context_post_error(pContext, NULL, MAL_LOG_LEVEL_ERROR, "[WASAPI] Failed to convert device IID to string for ActivateAudioInterfaceAsync(). Out of memory.", MAL_OUT_OF_MEMORY); - } - - mal_result result = mal_completion_handler_uwp_init(&completionHandler); - if (result != MAL_SUCCESS) { - mal_CoTaskMemFree(pContext, iidStr); - return mal_context_post_error(pContext, NULL, MAL_LOG_LEVEL_ERROR, "[WASAPI] Failed to create event for waiting for ActivateAudioInterfaceAsync().", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - -#if defined(__cplusplus) - hr = ActivateAudioInterfaceAsync(iidStr, MAL_IID_IAudioClient, NULL, (IActivateAudioInterfaceCompletionHandler*)&completionHandler, (IActivateAudioInterfaceAsyncOperation**)&pAsyncOp); -#else - hr = ActivateAudioInterfaceAsync(iidStr, &MAL_IID_IAudioClient, NULL, (IActivateAudioInterfaceCompletionHandler*)&completionHandler, (IActivateAudioInterfaceAsyncOperation**)&pAsyncOp); -#endif - if (FAILED(hr)) { - mal_completion_handler_uwp_uninit(&completionHandler); - mal_CoTaskMemFree(pContext, iidStr); - return mal_context_post_error(pContext, NULL, MAL_LOG_LEVEL_ERROR, "[WASAPI] ActivateAudioInterfaceAsync() failed.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - - mal_CoTaskMemFree(pContext, iidStr); - - // Wait for the async operation for finish. - mal_completion_handler_uwp_wait(&completionHandler); - mal_completion_handler_uwp_uninit(&completionHandler); - - HRESULT activateResult; - mal_IUnknown* pActivatedInterface; - hr = mal_IActivateAudioInterfaceAsyncOperation_GetActivateResult(pAsyncOp, &activateResult, &pActivatedInterface); - mal_IActivateAudioInterfaceAsyncOperation_Release(pAsyncOp); - - if (FAILED(hr) || FAILED(activateResult)) { - return mal_context_post_error(pContext, NULL, MAL_LOG_LEVEL_ERROR, "[WASAPI] Failed to activate device.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - - // Here is where we grab the IAudioClient interface. - hr = mal_IUnknown_QueryInterface(pActivatedInterface, &MAL_IID_IAudioClient, (void**)ppAudioClient); - if (FAILED(hr)) { - return mal_context_post_error(pContext, NULL, MAL_LOG_LEVEL_ERROR, "[WASAPI] Failed to query IAudioClient interface.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - - if (ppActivatedInterface) { - *ppActivatedInterface = pActivatedInterface; - } else { - mal_IUnknown_Release(pActivatedInterface); - } - - return MAL_SUCCESS; -} -#endif - -mal_result mal_context_get_device_info_from_IAudioClient__wasapi(mal_context* pContext, /*mal_IMMDevice**/void* pMMDevice, mal_IAudioClient* pAudioClient, mal_share_mode shareMode, mal_device_info* pInfo) -{ - mal_assert(pAudioClient != NULL); - mal_assert(pInfo != NULL); - - // We use a different technique to retrieve the device information depending on whether or not we are using shared or exclusive mode. - if (shareMode == mal_share_mode_shared) { - // Shared Mode. We use GetMixFormat() here. - WAVEFORMATEX* pWF = NULL; - HRESULT hr = mal_IAudioClient_GetMixFormat((mal_IAudioClient*)pAudioClient, (WAVEFORMATEX**)&pWF); - if (SUCCEEDED(hr)) { - mal_set_device_info_from_WAVEFORMATEX(pWF, pInfo); - return MAL_SUCCESS; - } else { - return mal_context_post_error(pContext, NULL, MAL_LOG_LEVEL_ERROR, "[WASAPI] Failed to retrieve mix format for device info retrieval.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - } else { - // Exlcusive Mode. We repeatedly call IsFormatSupported() here. This is not currently support on UWP. -#ifdef MAL_WIN32_DESKTOP - // The first thing to do is get the format from PKEY_AudioEngine_DeviceFormat. This should give us a channel count we assume is - // correct which will simplify our searching. - mal_IPropertyStore *pProperties; - HRESULT hr = mal_IMMDevice_OpenPropertyStore((mal_IMMDevice*)pMMDevice, STGM_READ, &pProperties); - if (SUCCEEDED(hr)) { - PROPVARIANT var; - mal_PropVariantInit(&var); - - hr = mal_IPropertyStore_GetValue(pProperties, &MAL_PKEY_AudioEngine_DeviceFormat, &var); - if (SUCCEEDED(hr)) { - WAVEFORMATEX* pWF = (WAVEFORMATEX*)var.blob.pBlobData; - mal_set_device_info_from_WAVEFORMATEX(pWF, pInfo); - - // In my testing, the format returned by PKEY_AudioEngine_DeviceFormat is suitable for exclusive mode so we check this format - // first. If this fails, fall back to a search. - hr = mal_IAudioClient_IsFormatSupported((mal_IAudioClient*)pAudioClient, MAL_AUDCLNT_SHAREMODE_EXCLUSIVE, pWF, NULL); - mal_PropVariantClear(pContext, &var); - - if (FAILED(hr)) { - // The format returned by PKEY_AudioEngine_DeviceFormat is not supported, so fall back to a search. We assume the channel - // count returned by MAL_PKEY_AudioEngine_DeviceFormat is valid and correct. For simplicity we're only returning one format. - mal_uint32 channels = pInfo->minChannels; - - mal_format formatsToSearch[] = { - mal_format_s16, - mal_format_s24, - //mal_format_s24_32, - mal_format_f32, - mal_format_s32, - mal_format_u8 - }; - - mal_channel defaultChannelMap[MAL_MAX_CHANNELS]; - mal_get_standard_channel_map(mal_standard_channel_map_microsoft, channels, defaultChannelMap); - - WAVEFORMATEXTENSIBLE wf; - mal_zero_object(&wf); - wf.Format.cbSize = sizeof(wf); - wf.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE; - wf.Format.nChannels = (WORD)channels; - wf.dwChannelMask = mal_channel_map_to_channel_mask__win32(defaultChannelMap, channels); - - mal_bool32 found = MAL_FALSE; - for (mal_uint32 iFormat = 0; iFormat < mal_countof(formatsToSearch); ++iFormat) { - mal_format format = formatsToSearch[iFormat]; - - wf.Format.wBitsPerSample = (WORD)mal_get_bytes_per_sample(format)*8; - wf.Format.nBlockAlign = (wf.Format.nChannels * wf.Format.wBitsPerSample) / 8; - wf.Format.nAvgBytesPerSec = wf.Format.nBlockAlign * wf.Format.nSamplesPerSec; - wf.Samples.wValidBitsPerSample = /*(format == mal_format_s24_32) ? 24 :*/ wf.Format.wBitsPerSample; - if (format == mal_format_f32) { - wf.SubFormat = MAL_GUID_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT; - } else { - wf.SubFormat = MAL_GUID_KSDATAFORMAT_SUBTYPE_PCM; - } - - for (mal_uint32 iSampleRate = 0; iSampleRate < mal_countof(g_malStandardSampleRatePriorities); ++iSampleRate) { - wf.Format.nSamplesPerSec = g_malStandardSampleRatePriorities[iSampleRate]; - - hr = mal_IAudioClient_IsFormatSupported((mal_IAudioClient*)pAudioClient, MAL_AUDCLNT_SHAREMODE_EXCLUSIVE, (WAVEFORMATEX*)&wf, NULL); - if (SUCCEEDED(hr)) { - mal_set_device_info_from_WAVEFORMATEX((WAVEFORMATEX*)&wf, pInfo); - found = MAL_TRUE; - break; - } - } - - if (found) { - break; - } - } - - if (!found) { - mal_IPropertyStore_Release(pProperties); - return mal_context_post_error(pContext, NULL, MAL_LOG_LEVEL_ERROR, "[WASAPI] Failed to find suitable device format for device info retrieval.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - } - } else { - mal_IPropertyStore_Release(pProperties); - return mal_context_post_error(pContext, NULL, MAL_LOG_LEVEL_ERROR, "[WASAPI] Failed to retrieve device format for device info retrieval.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - } else { - return mal_context_post_error(pContext, NULL, MAL_LOG_LEVEL_ERROR, "[WASAPI] Failed to open property store for device info retrieval.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - - return MAL_SUCCESS; -#else - // Exclusive mode not fully supported in UWP right now. - return MAL_ERROR; -#endif - } -} - -#ifdef MAL_WIN32_DESKTOP -mal_result mal_context_get_MMDevice__wasapi(mal_context* pContext, mal_device_type deviceType, const mal_device_id* pDeviceID, mal_IMMDevice** ppMMDevice) -{ - mal_assert(pContext != NULL); - mal_assert(ppMMDevice != NULL); - - mal_IMMDeviceEnumerator* pDeviceEnumerator; - HRESULT hr = mal_CoCreateInstance(pContext, MAL_CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, MAL_IID_IMMDeviceEnumerator, (void**)&pDeviceEnumerator); - if (FAILED(hr)) { - return mal_context_post_error(pContext, NULL, MAL_LOG_LEVEL_ERROR, "[WASAPI] Failed to create IMMDeviceEnumerator.", MAL_FAILED_TO_INIT_BACKEND); - } - - if (pDeviceID == NULL) { - hr = mal_IMMDeviceEnumerator_GetDefaultAudioEndpoint(pDeviceEnumerator, (deviceType == mal_device_type_playback) ? mal_eRender : mal_eCapture, mal_eConsole, ppMMDevice); - } else { - hr = mal_IMMDeviceEnumerator_GetDevice(pDeviceEnumerator, pDeviceID->wasapi, ppMMDevice); - } - - mal_IMMDeviceEnumerator_Release(pDeviceEnumerator); - if (FAILED(hr)) { - return mal_context_post_error(pContext, NULL, MAL_LOG_LEVEL_ERROR, "[WASAPI] Failed to retrieve IMMDevice.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - - return MAL_SUCCESS; -} - -mal_result mal_context_get_device_info_from_MMDevice__wasapi(mal_context* pContext, mal_IMMDevice* pMMDevice, mal_share_mode shareMode, mal_bool32 onlySimpleInfo, mal_device_info* pInfo) -{ - mal_assert(pContext != NULL); - mal_assert(pMMDevice != NULL); - mal_assert(pInfo != NULL); - - // ID. - LPWSTR id; - HRESULT hr = mal_IMMDevice_GetId(pMMDevice, &id); - if (SUCCEEDED(hr)) { - size_t idlen = wcslen(id); - if (idlen+1 > mal_countof(pInfo->id.wasapi)) { - mal_CoTaskMemFree(pContext, id); - mal_assert(MAL_FALSE); // NOTE: If this is triggered, please report it. It means the format of the ID must haved change and is too long to fit in our fixed sized buffer. - return MAL_ERROR; - } - - mal_copy_memory(pInfo->id.wasapi, id, idlen * sizeof(wchar_t)); - pInfo->id.wasapi[idlen] = '\0'; - - mal_CoTaskMemFree(pContext, id); - } - - { - mal_IPropertyStore *pProperties; - hr = mal_IMMDevice_OpenPropertyStore(pMMDevice, STGM_READ, &pProperties); - if (SUCCEEDED(hr)) { - PROPVARIANT var; - - // Description / Friendly Name - mal_PropVariantInit(&var); - hr = mal_IPropertyStore_GetValue(pProperties, &MAL_PKEY_Device_FriendlyName, &var); - if (SUCCEEDED(hr)) { - WideCharToMultiByte(CP_UTF8, 0, var.pwszVal, -1, pInfo->name, sizeof(pInfo->name), 0, FALSE); - mal_PropVariantClear(pContext, &var); - } - - mal_IPropertyStore_Release(pProperties); - } - } - - // Format - if (!onlySimpleInfo) { - mal_IAudioClient* pAudioClient; - hr = mal_IMMDevice_Activate(pMMDevice, &MAL_IID_IAudioClient, CLSCTX_ALL, NULL, (void**)&pAudioClient); - if (SUCCEEDED(hr)) { - mal_result result = mal_context_get_device_info_from_IAudioClient__wasapi(pContext, pMMDevice, pAudioClient, shareMode, pInfo); - - mal_IAudioClient_Release(pAudioClient); - return result; - } else { - return mal_context_post_error(pContext, NULL, MAL_LOG_LEVEL_ERROR, "[WASAPI] Failed to activate audio client for device info retrieval.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - } - - return MAL_SUCCESS; -} - -mal_result mal_context_enumerate_device_collection__wasapi(mal_context* pContext, mal_IMMDeviceCollection* pDeviceCollection, mal_device_type deviceType, mal_enum_devices_callback_proc callback, void* pUserData) -{ - mal_assert(pContext != NULL); - mal_assert(callback != NULL); - - UINT deviceCount; - HRESULT hr = mal_IMMDeviceCollection_GetCount(pDeviceCollection, &deviceCount); - if (FAILED(hr)) { - return mal_context_post_error(pContext, NULL, MAL_LOG_LEVEL_ERROR, "[WASAPI] Failed to get playback device count.", MAL_NO_DEVICE); - } - - for (mal_uint32 iDevice = 0; iDevice < deviceCount; ++iDevice) { - mal_device_info deviceInfo; - mal_zero_object(&deviceInfo); - - mal_IMMDevice* pMMDevice; - hr = mal_IMMDeviceCollection_Item(pDeviceCollection, iDevice, &pMMDevice); - if (SUCCEEDED(hr)) { - mal_result result = mal_context_get_device_info_from_MMDevice__wasapi(pContext, pMMDevice, mal_share_mode_shared, MAL_TRUE, &deviceInfo); // MAL_TRUE = onlySimpleInfo. - - mal_IMMDevice_Release(pMMDevice); - if (result == MAL_SUCCESS) { - mal_bool32 cbResult = callback(pContext, deviceType, &deviceInfo, pUserData); - if (cbResult == MAL_FALSE) { - break; - } - } - } - } - - return MAL_SUCCESS; -} -#endif - -mal_result mal_context_enumerate_devices__wasapi(mal_context* pContext, mal_enum_devices_callback_proc callback, void* pUserData) -{ - mal_assert(pContext != NULL); - mal_assert(callback != NULL); - - // Different enumeration for desktop and UWP. -#ifdef MAL_WIN32_DESKTOP - // Desktop - mal_IMMDeviceEnumerator* pDeviceEnumerator; - HRESULT hr = mal_CoCreateInstance(pContext, MAL_CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, MAL_IID_IMMDeviceEnumerator, (void**)&pDeviceEnumerator); - if (FAILED(hr)) { - return mal_context_post_error(pContext, NULL, MAL_LOG_LEVEL_ERROR, "[WASAPI] Failed to create device enumerator.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - - mal_IMMDeviceCollection* pDeviceCollection; - - // Playback. - hr = mal_IMMDeviceEnumerator_EnumAudioEndpoints(pDeviceEnumerator, mal_eRender, MAL_MM_DEVICE_STATE_ACTIVE, &pDeviceCollection); - if (SUCCEEDED(hr)) { - mal_context_enumerate_device_collection__wasapi(pContext, pDeviceCollection, mal_device_type_playback, callback, pUserData); - mal_IMMDeviceCollection_Release(pDeviceCollection); - } - - // Capture. - hr = mal_IMMDeviceEnumerator_EnumAudioEndpoints(pDeviceEnumerator, mal_eCapture, MAL_MM_DEVICE_STATE_ACTIVE, &pDeviceCollection); - if (SUCCEEDED(hr)) { - mal_context_enumerate_device_collection__wasapi(pContext, pDeviceCollection, mal_device_type_capture, callback, pUserData); - mal_IMMDeviceCollection_Release(pDeviceCollection); - } - - mal_IMMDeviceEnumerator_Release(pDeviceEnumerator); -#else - // UWP - // - // The MMDevice API is only supported on desktop applications. For now, while I'm still figuring out how to properly enumerate - // over devices without using MMDevice, I'm restricting devices to defaults. - // - // Hint: DeviceInformation::FindAllAsync() with DeviceClass.AudioCapture/AudioRender. https://blogs.windows.com/buildingapps/2014/05/15/real-time-audio-in-windows-store-and-windows-phone-apps/ - if (callback) { - mal_bool32 cbResult = MAL_TRUE; - - // Playback. - if (cbResult) { - mal_device_info deviceInfo; - mal_zero_object(&deviceInfo); - mal_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MAL_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); - cbResult = callback(pContext, mal_device_type_playback, &deviceInfo, pUserData); - } - - // Capture. - if (cbResult) { - mal_device_info deviceInfo; - mal_zero_object(&deviceInfo); - mal_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MAL_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); - cbResult = callback(pContext, mal_device_type_capture, &deviceInfo, pUserData); - } - } -#endif - - return MAL_SUCCESS; -} - -mal_result mal_context_get_device_info__wasapi(mal_context* pContext, mal_device_type deviceType, const mal_device_id* pDeviceID, mal_share_mode shareMode, mal_device_info* pDeviceInfo) -{ -#ifdef MAL_WIN32_DESKTOP - mal_IMMDevice* pMMDevice = NULL; - mal_result result = mal_context_get_MMDevice__wasapi(pContext, deviceType, pDeviceID, &pMMDevice); - if (result != MAL_SUCCESS) { - return result; - } - - result = mal_context_get_device_info_from_MMDevice__wasapi(pContext, pMMDevice, shareMode, MAL_FALSE, pDeviceInfo); // MAL_FALSE = !onlySimpleInfo. - - mal_IMMDevice_Release(pMMDevice); - return result; -#else - // UWP currently only uses default devices. - if (deviceType == mal_device_type_playback) { - mal_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MAL_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); - } else { - mal_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MAL_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); - } - - // Not currently supporting exclusive mode on UWP. - if (shareMode == mal_share_mode_exclusive) { - return MAL_ERROR; - } - - mal_IAudioClient* pAudioClient; - mal_result result = mal_context_get_IAudioClient_UWP__wasapi(pContext, deviceType, pDeviceID, &pAudioClient, NULL); - if (result != MAL_SUCCESS) { - return result; - } - - result = mal_context_get_device_info_from_IAudioClient__wasapi(pContext, NULL, pAudioClient, shareMode, pDeviceInfo); - - mal_IAudioClient_Release(pAudioClient); - return result; -#endif -} - -void mal_device_uninit__wasapi(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - -#ifdef MAL_WIN32_DESKTOP - if (pDevice->wasapi.pDeviceEnumerator) { - ((mal_IMMDeviceEnumerator*)pDevice->wasapi.pDeviceEnumerator)->lpVtbl->UnregisterEndpointNotificationCallback((mal_IMMDeviceEnumerator*)pDevice->wasapi.pDeviceEnumerator, &pDevice->wasapi.notificationClient); - mal_IMMDeviceEnumerator_Release((mal_IMMDeviceEnumerator*)pDevice->wasapi.pDeviceEnumerator); - } -#endif - - if (pDevice->wasapi.pRenderClient) { - mal_IAudioRenderClient_Release((mal_IAudioRenderClient*)pDevice->wasapi.pRenderClient); - } - if (pDevice->wasapi.pCaptureClient) { - mal_IAudioCaptureClient_Release((mal_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient); - } - if (pDevice->wasapi.pAudioClient) { - mal_IAudioClient_Release((mal_IAudioClient*)pDevice->wasapi.pAudioClient); - } - - if (pDevice->wasapi.hEvent) { - CloseHandle(pDevice->wasapi.hEvent); - } - if (pDevice->wasapi.hBreakEvent) { - CloseHandle(pDevice->wasapi.hBreakEvent); - } -} - -typedef struct -{ - // Input. - mal_format formatIn; - mal_uint32 channelsIn; - mal_uint32 sampleRateIn; - mal_channel channelMapIn[MAL_MAX_CHANNELS]; - mal_uint32 bufferSizeInFramesIn; - mal_uint32 bufferSizeInMillisecondsIn; - mal_uint32 periodsIn; - mal_bool32 usingDefaultFormat; - mal_bool32 usingDefaultChannels; - mal_bool32 usingDefaultSampleRate; - mal_bool32 usingDefaultChannelMap; - mal_share_mode shareMode; - - // Output. - mal_IAudioClient* pAudioClient; - mal_IAudioRenderClient* pRenderClient; - mal_IAudioCaptureClient* pCaptureClient; - mal_format formatOut; - mal_uint32 channelsOut; - mal_uint32 sampleRateOut; - mal_channel channelMapOut[MAL_MAX_CHANNELS]; - mal_uint32 bufferSizeInFramesOut; - mal_uint32 periodsOut; - mal_bool32 exclusiveMode; - char deviceName[256]; -} mal_device_init_internal_data__wasapi; - -mal_result mal_device_init_internal__wasapi(mal_context* pContext, mal_device_type type, const mal_device_id* pDeviceID, mal_device_init_internal_data__wasapi* pData) -{ - (void)pContext; - - mal_assert(pContext != NULL); - mal_assert(pData != NULL); - - pData->pAudioClient = NULL; - pData->pRenderClient = NULL; - pData->pCaptureClient = NULL; - - - HRESULT hr; - mal_result result = MAL_SUCCESS; - const char* errorMsg = ""; - MAL_AUDCLNT_SHAREMODE shareMode = MAL_AUDCLNT_SHAREMODE_SHARED; - MAL_REFERENCE_TIME bufferDurationInMicroseconds; - mal_bool32 wasInitializedUsingIAudioClient3 = MAL_FALSE; - WAVEFORMATEXTENSIBLE wf; - -#ifdef MAL_WIN32_DESKTOP - mal_IMMDevice* pMMDevice = NULL; - result = mal_context_get_MMDevice__wasapi(pContext, type, pDeviceID, &pMMDevice); - if (result != MAL_SUCCESS) { - goto done; - } - - hr = mal_IMMDevice_Activate(pMMDevice, &MAL_IID_IAudioClient, CLSCTX_ALL, NULL, (void**)&pData->pAudioClient); - if (FAILED(hr)) { - errorMsg = "[WASAPI] Failed to activate device.", result = MAL_FAILED_TO_OPEN_BACKEND_DEVICE; - goto done; - } -#else - mal_IUnknown* pActivatedInterface = NULL; - result = mal_context_get_IAudioClient_UWP__wasapi(pContext, type, pDeviceID, &pData->pAudioClient, &pActivatedInterface); - if (result != MAL_SUCCESS) { - goto done; - } -#endif - - // Try enabling hardware offloading. - mal_IAudioClient2* pAudioClient2; - hr = mal_IAudioClient_QueryInterface(pData->pAudioClient, &MAL_IID_IAudioClient2, (void**)&pAudioClient2); - if (SUCCEEDED(hr)) { - BOOL isHardwareOffloadingSupported = 0; - hr = mal_IAudioClient2_IsOffloadCapable(pAudioClient2, MAL_AudioCategory_Other, &isHardwareOffloadingSupported); - if (SUCCEEDED(hr) && isHardwareOffloadingSupported) { - mal_AudioClientProperties clientProperties; - mal_zero_object(&clientProperties); - clientProperties.cbSize = sizeof(clientProperties); - clientProperties.bIsOffload = 1; - clientProperties.eCategory = MAL_AudioCategory_Other; - mal_IAudioClient2_SetClientProperties(pAudioClient2, &clientProperties); - } - } - - - // Here is where we try to determine the best format to use with the device. If the client if wanting exclusive mode, first try finding the best format for that. If this fails, fall back to shared mode. - result = MAL_FORMAT_NOT_SUPPORTED; - if (pData->shareMode == mal_share_mode_exclusive) { - #ifdef MAL_WIN32_DESKTOP - // In exclusive mode on desktop we always use the backend's native format. - mal_IPropertyStore* pStore = NULL; - hr = mal_IMMDevice_OpenPropertyStore(pMMDevice, STGM_READ, &pStore); - if (SUCCEEDED(hr)) { - PROPVARIANT prop; - mal_PropVariantInit(&prop); - hr = mal_IPropertyStore_GetValue(pStore, &MAL_PKEY_AudioEngine_DeviceFormat, &prop); - if (SUCCEEDED(hr)) { - WAVEFORMATEX* pActualFormat = (WAVEFORMATEX*)prop.blob.pBlobData; - hr = mal_IAudioClient_IsFormatSupported((mal_IAudioClient*)pData->pAudioClient, MAL_AUDCLNT_SHAREMODE_EXCLUSIVE, pActualFormat, NULL); - if (SUCCEEDED(hr)) { - mal_copy_memory(&wf, pActualFormat, sizeof(WAVEFORMATEXTENSIBLE)); - } - - mal_PropVariantClear(pContext, &prop); - } - - mal_IPropertyStore_Release(pStore); - } - #else - // I do not know how to query the device's native format on UWP so for now I'm just disabling support for - // exclusive mode. The alternative is to enumerate over different formats and check IsFormatSupported() - // until you find one that works. - // - // TODO: Add support for exclusive mode to UWP. - hr = S_FALSE; - #endif - - if (hr == S_OK) { - shareMode = MAL_AUDCLNT_SHAREMODE_EXCLUSIVE; - result = MAL_SUCCESS; - } - } - - // Fall back to shared mode if necessary. - if (result != MAL_SUCCESS) { - // In shared mode we are always using the format reported by the operating system. - WAVEFORMATEXTENSIBLE* pNativeFormat = NULL; - hr = mal_IAudioClient_GetMixFormat((mal_IAudioClient*)pData->pAudioClient, (WAVEFORMATEX**)&pNativeFormat); - if (hr != S_OK) { - result = MAL_FORMAT_NOT_SUPPORTED; - } else { - mal_copy_memory(&wf, pNativeFormat, sizeof(wf)); - result = MAL_SUCCESS; - } - - mal_CoTaskMemFree(pContext, pNativeFormat); - - shareMode = MAL_AUDCLNT_SHAREMODE_SHARED; - } - - // Return an error if we still haven't found a format. - if (result != MAL_SUCCESS) { - errorMsg = "[WASAPI] Failed to find best device mix format.", result = MAL_FORMAT_NOT_SUPPORTED; - goto done; - } - - pData->formatOut = mal_format_from_WAVEFORMATEX((WAVEFORMATEX*)&wf); - pData->channelsOut = wf.Format.nChannels; - pData->sampleRateOut = wf.Format.nSamplesPerSec; - - // Get the internal channel map based on the channel mask. - mal_channel_mask_to_channel_map__win32(wf.dwChannelMask, pData->channelsOut, pData->channelMapOut); - - // If we're using a default buffer size we need to calculate it based on the efficiency of the system. - pData->periodsOut = pData->periodsIn; - pData->bufferSizeInFramesOut = pData->bufferSizeInFramesIn; - if (pData->bufferSizeInFramesOut == 0) { - pData->bufferSizeInFramesOut = mal_calculate_buffer_size_in_frames_from_milliseconds(pData->bufferSizeInMillisecondsIn, pData->sampleRateOut); - } - - bufferDurationInMicroseconds = ((mal_uint64)pData->bufferSizeInFramesOut * 1000 * 1000) / pData->sampleRateOut; - - - // Slightly different initialization for shared and exclusive modes. We try exclusive mode first, and if it fails, fall back to shared mode. - if (shareMode == MAL_AUDCLNT_SHAREMODE_EXCLUSIVE) { - // Exclusive. - MAL_REFERENCE_TIME bufferDuration = bufferDurationInMicroseconds*10; - - // If the periodicy is too small, Initialize() will fail with AUDCLNT_E_INVALID_DEVICE_PERIOD. In this case we should just keep increasing - // it and trying it again. - hr = E_FAIL; - for (;;) { - hr = mal_IAudioClient_Initialize((mal_IAudioClient*)pData->pAudioClient, shareMode, MAL_AUDCLNT_STREAMFLAGS_EVENTCALLBACK, bufferDuration, bufferDuration, (WAVEFORMATEX*)&wf, NULL); - if (hr == MAL_AUDCLNT_E_INVALID_DEVICE_PERIOD) { - if (bufferDuration > 500*10000) { - break; - } else { - if (bufferDuration == 0) { // <-- Just a sanity check to prevent an infinit loop. Should never happen, but it makes me feel better. - break; - } - - bufferDuration = bufferDuration * 2; - continue; - } - } else { - break; - } - } - - if (hr == MAL_AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED) { - UINT bufferSizeInFrames; - hr = mal_IAudioClient_GetBufferSize((mal_IAudioClient*)pData->pAudioClient, &bufferSizeInFrames); - if (SUCCEEDED(hr)) { - bufferDuration = (MAL_REFERENCE_TIME)((10000.0 * 1000 / wf.Format.nSamplesPerSec * bufferSizeInFrames) + 0.5); - - // Unfortunately we need to release and re-acquire the audio client according to MSDN. Seems silly - why not just call IAudioClient_Initialize() again?! - mal_IAudioClient_Release((mal_IAudioClient*)pData->pAudioClient); - - #ifdef MAL_WIN32_DESKTOP - hr = mal_IMMDevice_Activate(pMMDevice, &MAL_IID_IAudioClient, CLSCTX_ALL, NULL, (void**)&pData->pAudioClient); - #else - hr = mal_IUnknown_QueryInterface(pActivatedInterface, &MAL_IID_IAudioClient, (void**)&pData->pAudioClient); - #endif - - if (SUCCEEDED(hr)) { - hr = mal_IAudioClient_Initialize((mal_IAudioClient*)pData->pAudioClient, shareMode, MAL_AUDCLNT_STREAMFLAGS_EVENTCALLBACK, bufferDuration, bufferDuration, (WAVEFORMATEX*)&wf, NULL); - } - } - } - - if (FAILED(hr)) { - // Failed to initialize in exclusive mode. We don't return an error here, but instead fall back to shared mode. - shareMode = MAL_AUDCLNT_SHAREMODE_SHARED; - } - } - - if (shareMode == MAL_AUDCLNT_SHAREMODE_SHARED) { - // Shared. - - // Low latency shared mode via IAudioClient3. - mal_IAudioClient3* pAudioClient3 = NULL; - hr = mal_IAudioClient_QueryInterface(pData->pAudioClient, &MAL_IID_IAudioClient3, (void**)&pAudioClient3); - if (SUCCEEDED(hr)) { - UINT32 defaultPeriodInFrames; - UINT32 fundamentalPeriodInFrames; - UINT32 minPeriodInFrames; - UINT32 maxPeriodInFrames; - hr = mal_IAudioClient3_GetSharedModeEnginePeriod(pAudioClient3, (WAVEFORMATEX*)&wf, &defaultPeriodInFrames, &fundamentalPeriodInFrames, &minPeriodInFrames, &maxPeriodInFrames); - if (SUCCEEDED(hr)) { - UINT32 desiredPeriodInFrames = pData->bufferSizeInFramesOut / pData->periodsOut; - - // Make sure the period size is a multiple of fundamentalPeriodInFrames. - desiredPeriodInFrames = desiredPeriodInFrames / fundamentalPeriodInFrames; - desiredPeriodInFrames = desiredPeriodInFrames * fundamentalPeriodInFrames; - - // The period needs to be clamped between minPeriodInFrames and maxPeriodInFrames. - desiredPeriodInFrames = mal_clamp(desiredPeriodInFrames, minPeriodInFrames, maxPeriodInFrames); - - hr = mal_IAudioClient3_InitializeSharedAudioStream(pAudioClient3, MAL_AUDCLNT_STREAMFLAGS_EVENTCALLBACK, desiredPeriodInFrames, (WAVEFORMATEX*)&wf, NULL); - if (SUCCEEDED(hr)) { - wasInitializedUsingIAudioClient3 = MAL_TRUE; - pData->bufferSizeInFramesOut = desiredPeriodInFrames * pData->periodsOut; - } - } - - mal_IAudioClient3_Release(pAudioClient3); - pAudioClient3 = NULL; - } - - // If we don't have an IAudioClient3 then we need to use the normal initialization routine. - if (!wasInitializedUsingIAudioClient3) { - MAL_REFERENCE_TIME bufferDuration = bufferDurationInMicroseconds*10; - hr = mal_IAudioClient_Initialize((mal_IAudioClient*)pData->pAudioClient, shareMode, MAL_AUDCLNT_STREAMFLAGS_EVENTCALLBACK, bufferDuration, 0, (WAVEFORMATEX*)&wf, NULL); - if (FAILED(hr)) { - if (hr == E_ACCESSDENIED) { - errorMsg = "[WASAPI] Failed to initialize device. Access denied.", result = MAL_ACCESS_DENIED; - } else if (hr == MAL_AUDCLNT_E_DEVICE_IN_USE) { - errorMsg = "[WASAPI] Failed to initialize device. Device in use.", result = MAL_DEVICE_BUSY; - } else { - errorMsg = "[WASAPI] Failed to initialize device.", result = MAL_FAILED_TO_OPEN_BACKEND_DEVICE; - } - - goto done; - } - } - } - - if (!wasInitializedUsingIAudioClient3) { - hr = mal_IAudioClient_GetBufferSize((mal_IAudioClient*)pData->pAudioClient, &pData->bufferSizeInFramesOut); - if (FAILED(hr)) { - errorMsg = "[WASAPI] Failed to get audio client's actual buffer size.", result = MAL_FAILED_TO_OPEN_BACKEND_DEVICE; - goto done; - } - } - - if (type == mal_device_type_playback) { - hr = mal_IAudioClient_GetService((mal_IAudioClient*)pData->pAudioClient, &MAL_IID_IAudioRenderClient, (void**)&pData->pRenderClient); - } else { - hr = mal_IAudioClient_GetService((mal_IAudioClient*)pData->pAudioClient, &MAL_IID_IAudioCaptureClient, (void**)&pData->pCaptureClient); - } - - if (FAILED(hr)) { - errorMsg = "[WASAPI] Failed to get audio client service.", result = MAL_API_NOT_FOUND; - goto done; - } - - - if (shareMode == MAL_AUDCLNT_SHAREMODE_SHARED) { - pData->exclusiveMode = MAL_FALSE; - } else /*if (shareMode == MAL_AUDCLNT_SHAREMODE_EXCLUSIVE)*/ { - pData->exclusiveMode = MAL_TRUE; - } - - - // Grab the name of the device. -#ifdef MAL_WIN32_DESKTOP - mal_IPropertyStore *pProperties; - hr = mal_IMMDevice_OpenPropertyStore(pMMDevice, STGM_READ, &pProperties); - if (SUCCEEDED(hr)) { - PROPVARIANT varName; - mal_PropVariantInit(&varName); - hr = mal_IPropertyStore_GetValue(pProperties, &MAL_PKEY_Device_FriendlyName, &varName); - if (SUCCEEDED(hr)) { - WideCharToMultiByte(CP_UTF8, 0, varName.pwszVal, -1, pData->deviceName, sizeof(pData->deviceName), 0, FALSE); - mal_PropVariantClear(pContext, &varName); - } - - mal_IPropertyStore_Release(pProperties); - } -#endif - -done: - // Clean up. -#ifdef MAL_WIN32_DESKTOP - if (pMMDevice != NULL) { - mal_IMMDevice_Release(pMMDevice); - } -#else - if (pActivatedInterface != NULL) { - mal_IUnknown_Release(pActivatedInterface); - } -#endif - - if (result != MAL_SUCCESS) { - if (pData->pRenderClient) { - mal_IAudioRenderClient_Release((mal_IAudioRenderClient*)pData->pRenderClient); - pData->pRenderClient = NULL; - } - if (pData->pCaptureClient) { - mal_IAudioCaptureClient_Release((mal_IAudioCaptureClient*)pData->pCaptureClient); - pData->pCaptureClient = NULL; - } - if (pData->pAudioClient) { - mal_IAudioClient_Release((mal_IAudioClient*)pData->pAudioClient); - pData->pAudioClient = NULL; - } - - return mal_context_post_error(pContext, NULL, MAL_LOG_LEVEL_ERROR, errorMsg, result); - } else { - return MAL_SUCCESS; - } -} - -mal_result mal_device_reinit__wasapi(mal_device* pDevice) -{ - mal_device_init_internal_data__wasapi data; - data.formatIn = pDevice->format; - data.channelsIn = pDevice->channels; - data.sampleRateIn = pDevice->sampleRate; - mal_copy_memory(data.channelMapIn, pDevice->channelMap, sizeof(pDevice->channelMap)); - data.bufferSizeInFramesIn = pDevice->bufferSizeInFrames; - data.bufferSizeInMillisecondsIn = pDevice->bufferSizeInMilliseconds; - data.periodsIn = pDevice->periods; - data.usingDefaultFormat = pDevice->usingDefaultFormat; - data.usingDefaultChannels = pDevice->usingDefaultChannels; - data.usingDefaultSampleRate = pDevice->usingDefaultSampleRate; - data.usingDefaultChannelMap = pDevice->usingDefaultChannelMap; - data.shareMode = pDevice->initConfig.shareMode; - mal_result result = mal_device_init_internal__wasapi(pDevice->pContext, pDevice->type, NULL, &data); - if (result != MAL_SUCCESS) { - return result; - } - - // At this point we have some new objects ready to go. We need to uninitialize the previous ones and then set the new ones. - if (pDevice->wasapi.pRenderClient) { - mal_IAudioRenderClient_Release((mal_IAudioRenderClient*)pDevice->wasapi.pRenderClient); - pDevice->wasapi.pRenderClient = NULL; - } - if (pDevice->wasapi.pCaptureClient) { - mal_IAudioCaptureClient_Release((mal_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient); - pDevice->wasapi.pCaptureClient = NULL; - } - if (pDevice->wasapi.pAudioClient) { - mal_IAudioClient_Release((mal_IAudioClient*)pDevice->wasapi.pAudioClient); - pDevice->wasapi.pAudioClient = NULL; - } - - pDevice->wasapi.pAudioClient = data.pAudioClient; - pDevice->wasapi.pRenderClient = data.pRenderClient; - pDevice->wasapi.pCaptureClient = data.pCaptureClient; - - pDevice->internalFormat = data.formatOut; - pDevice->internalChannels = data.channelsOut; - pDevice->internalSampleRate = data.sampleRateOut; - mal_copy_memory(pDevice->internalChannelMap, data.channelMapOut, sizeof(data.channelMapOut)); - pDevice->bufferSizeInFrames = data.bufferSizeInFramesOut; - pDevice->periods = data.periodsOut; - pDevice->exclusiveMode = data.exclusiveMode; - mal_strcpy_s(pDevice->name, sizeof(pDevice->name), data.deviceName); - - mal_IAudioClient_SetEventHandle((mal_IAudioClient*)pDevice->wasapi.pAudioClient, pDevice->wasapi.hEvent); - - return MAL_SUCCESS; -} - -mal_result mal_device_init__wasapi(mal_context* pContext, mal_device_type type, const mal_device_id* pDeviceID, const mal_device_config* pConfig, mal_device* pDevice) -{ - (void)pContext; - (void)pConfig; - - mal_assert(pDevice != NULL); - mal_zero_object(&pDevice->wasapi); - - mal_result result = MAL_SUCCESS; - const char* errorMsg = ""; - - mal_device_init_internal_data__wasapi data; - data.formatIn = pDevice->format; - data.channelsIn = pDevice->channels; - data.sampleRateIn = pDevice->sampleRate; - mal_copy_memory(data.channelMapIn, pDevice->channelMap, sizeof(pDevice->channelMap)); - data.bufferSizeInFramesIn = pDevice->bufferSizeInFrames; - data.bufferSizeInMillisecondsIn = pDevice->bufferSizeInMilliseconds; - data.periodsIn = pDevice->periods; - data.usingDefaultFormat = pDevice->usingDefaultFormat; - data.usingDefaultChannels = pDevice->usingDefaultChannels; - data.usingDefaultSampleRate = pDevice->usingDefaultSampleRate; - data.usingDefaultChannelMap = pDevice->usingDefaultChannelMap; - data.shareMode = pDevice->initConfig.shareMode; - result = mal_device_init_internal__wasapi(pDevice->pContext, type, pDeviceID, &data); - if (result != MAL_SUCCESS) { - return result; - } - - pDevice->wasapi.pAudioClient = data.pAudioClient; - pDevice->wasapi.pRenderClient = data.pRenderClient; - pDevice->wasapi.pCaptureClient = data.pCaptureClient; - - pDevice->internalFormat = data.formatOut; - pDevice->internalChannels = data.channelsOut; - pDevice->internalSampleRate = data.sampleRateOut; - mal_copy_memory(pDevice->internalChannelMap, data.channelMapOut, sizeof(data.channelMapOut)); - pDevice->bufferSizeInFrames = data.bufferSizeInFramesOut; - pDevice->periods = data.periodsOut; - pDevice->exclusiveMode = data.exclusiveMode; - mal_strcpy_s(pDevice->name, sizeof(pDevice->name), data.deviceName); - - - - // We need to get notifications of when the default device changes. We do this through a device enumerator by - // registering a IMMNotificationClient with it. We only care about this if it's the default device. -#ifdef MAL_WIN32_DESKTOP - mal_IMMDeviceEnumerator* pDeviceEnumerator; - HRESULT hr = mal_CoCreateInstance(pContext, MAL_CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, MAL_IID_IMMDeviceEnumerator, (void**)&pDeviceEnumerator); - if (FAILED(hr)) { - errorMsg = "[WASAPI] Failed to create device enumerator.", result = MAL_FAILED_TO_OPEN_BACKEND_DEVICE; - goto done; - } - - pDevice->wasapi.notificationClient.lpVtbl = (void*)&g_malNotificationCientVtbl; - pDevice->wasapi.notificationClient.counter = 1; - pDevice->wasapi.notificationClient.pDevice = pDevice; - - hr = pDeviceEnumerator->lpVtbl->RegisterEndpointNotificationCallback(pDeviceEnumerator, &pDevice->wasapi.notificationClient); - if (SUCCEEDED(hr)) { - pDevice->wasapi.pDeviceEnumerator = (mal_ptr)pDeviceEnumerator; - } else { - // Not the end of the world if we fail to register the notification callback. We just won't support automatic stream routing. - mal_IMMDeviceEnumerator_Release(pDeviceEnumerator); - } -#endif - - - // We need to create and set the event for event-driven mode. This event is signalled whenever a new chunk of audio - // data needs to be written or read from the device. - pDevice->wasapi.hEvent = CreateEventA(NULL, FALSE, FALSE, NULL); - if (pDevice->wasapi.hEvent == NULL) { - errorMsg = "[WASAPI] Failed to create main event for main loop.", result = MAL_FAILED_TO_CREATE_EVENT; - goto done; - } - - mal_IAudioClient_SetEventHandle((mal_IAudioClient*)pDevice->wasapi.pAudioClient, pDevice->wasapi.hEvent); - - - // When the device is playing the worker thread will be waiting on a bunch of notification events. To return from - // this wait state we need to signal a special event. - pDevice->wasapi.hBreakEvent = CreateEventA(NULL, FALSE, FALSE, NULL); - if (pDevice->wasapi.hBreakEvent == NULL) { - errorMsg = "[WASAPI] Failed to create break event for main loop break notification.", result = MAL_FAILED_TO_CREATE_EVENT; - goto done; - } - - result = MAL_SUCCESS; - -done: - // Clean up. - if (result != MAL_SUCCESS) { - mal_device_uninit__wasapi(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, errorMsg, result); - } else { - return MAL_SUCCESS; - } -} - -mal_result mal_device_start__wasapi(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - // Playback devices need to have an initial chunk of data loaded. - if (pDevice->type == mal_device_type_playback) { - BYTE* pData; - HRESULT hr = mal_IAudioRenderClient_GetBuffer((mal_IAudioRenderClient*)pDevice->wasapi.pRenderClient, pDevice->bufferSizeInFrames, &pData); - if (FAILED(hr)) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[WASAPI] Failed to retrieve buffer from internal playback device.", MAL_FAILED_TO_MAP_DEVICE_BUFFER); - } - - mal_device__read_frames_from_client(pDevice, pDevice->bufferSizeInFrames, pData); - - hr = mal_IAudioRenderClient_ReleaseBuffer((mal_IAudioRenderClient*)pDevice->wasapi.pRenderClient, pDevice->bufferSizeInFrames, 0); - if (FAILED(hr)) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[WASAPI] Failed to release internal buffer for playback device.", MAL_FAILED_TO_UNMAP_DEVICE_BUFFER); - } - } - - HRESULT hr = mal_IAudioClient_Start((mal_IAudioClient*)pDevice->wasapi.pAudioClient); - if (FAILED(hr)) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[WASAPI] Failed to start internal device.", MAL_FAILED_TO_START_BACKEND_DEVICE); - } - - return MAL_SUCCESS; -} - -mal_result mal_device_stop__wasapi(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - if (pDevice->wasapi.pAudioClient == NULL) { - return MAL_DEVICE_NOT_INITIALIZED; - } - - HRESULT hr = mal_IAudioClient_Stop((mal_IAudioClient*)pDevice->wasapi.pAudioClient); - if (FAILED(hr)) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[WASAPI] Failed to stop internal device.", MAL_FAILED_TO_STOP_BACKEND_DEVICE); - } - - // The client needs to be reset or else we won't be able to resume it again. - hr = mal_IAudioClient_Reset((mal_IAudioClient*)pDevice->wasapi.pAudioClient); - if (FAILED(hr)) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[WASAPI] Failed to reset internal device.", MAL_FAILED_TO_STOP_BACKEND_DEVICE); - } - - return MAL_SUCCESS; -} - -mal_result mal_device_break_main_loop__wasapi(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - // The main loop will be waiting on a bunch of events via the WaitForMultipleObjects() API. One of those events - // is a special event we use for forcing that function to return. - pDevice->wasapi.breakFromMainLoop = MAL_TRUE; - SetEvent(pDevice->wasapi.hBreakEvent); - return MAL_SUCCESS; -} - -mal_result mal_device__get_available_frames__wasapi(mal_device* pDevice, mal_uint32* pFrameCount) -{ - mal_assert(pDevice != NULL); - mal_assert(pFrameCount != NULL); - - *pFrameCount = 0; - - mal_uint32 paddingFramesCount; - HRESULT hr = mal_IAudioClient_GetCurrentPadding((mal_IAudioClient*)pDevice->wasapi.pAudioClient, &paddingFramesCount); - if (FAILED(hr)) { - return MAL_DEVICE_UNAVAILABLE; - } - - // Slightly different rules for exclusive and shared modes. - if (pDevice->exclusiveMode) { - *pFrameCount = paddingFramesCount; - } else { - if (pDevice->type == mal_device_type_playback) { - *pFrameCount = pDevice->bufferSizeInFrames - paddingFramesCount; - } else { - *pFrameCount = paddingFramesCount; - } - } - - return MAL_SUCCESS; -} - -mal_result mal_device__wait_for_frames__wasapi(mal_device* pDevice, mal_uint32* pFrameCount) -{ - mal_assert(pDevice != NULL); - - mal_result result; - - while (!pDevice->wasapi.breakFromMainLoop) { - // Wait for a buffer to become available or for the stop event to be signalled. - HANDLE hEvents[2]; - hEvents[0] = (HANDLE)pDevice->wasapi.hEvent; - hEvents[1] = (HANDLE)pDevice->wasapi.hBreakEvent; - if (WaitForMultipleObjects(mal_countof(hEvents), hEvents, FALSE, INFINITE) == WAIT_FAILED) { - break; - } - - // Break from the main loop if the device isn't started anymore. Likely what's happened is the application - // has requested that the device be stopped. - if (!mal_device_is_started(pDevice)) { - break; - } - - // Make sure we break from the main loop if requested from an external factor. - if (pDevice->wasapi.breakFromMainLoop) { - break; - } - - // We may want to reinitialize the device. Only do this if this device is the default. - mal_bool32 needDeviceReinit = MAL_FALSE; - - mal_bool32 hasDefaultDeviceChanged = pDevice->wasapi.hasDefaultDeviceChanged; - if (hasDefaultDeviceChanged && pDevice->isDefaultDevice) { - needDeviceReinit = MAL_TRUE; - } - - if (!needDeviceReinit) { - result = mal_device__get_available_frames__wasapi(pDevice, pFrameCount); - if (result != MAL_SUCCESS) { - if (!pDevice->exclusiveMode) { - needDeviceReinit = MAL_TRUE; - } else { - return result; - } - } - } - - - mal_atomic_exchange_32(&pDevice->wasapi.hasDefaultDeviceChanged, MAL_FALSE); - - // Here is where the device is re-initialized if required. - if (needDeviceReinit) { - #ifdef MAL_DEBUG_OUTPUT - printf("=== CHANGING DEVICE ===\n"); - #endif - - if (pDevice->pContext->onDeviceReinit) { - mal_result reinitResult = pDevice->pContext->onDeviceReinit(pDevice); - if (reinitResult != MAL_SUCCESS) { - return reinitResult; - } - - mal_device__post_init_setup(pDevice); - - // Start playing the device again, and then continue the loop from the top. - if (mal_device__get_state(pDevice) == MAL_STATE_STARTED) { - if (pDevice->pContext->onDeviceStart) { - pDevice->pContext->onDeviceStart(pDevice); - } - continue; - } - } - } - - - if (*pFrameCount > 0) { - return MAL_SUCCESS; - } - } - - // We'll get here if the loop was terminated. Just return whatever's available. - return mal_device__get_available_frames__wasapi(pDevice, pFrameCount); -} - -mal_result mal_device_main_loop__wasapi(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - // Make sure the break event is not signaled to ensure we don't end up immediately returning from WaitForMultipleObjects(). - ResetEvent(pDevice->wasapi.hBreakEvent); - - pDevice->wasapi.breakFromMainLoop = MAL_FALSE; - while (!pDevice->wasapi.breakFromMainLoop) { - mal_uint32 framesAvailable; - mal_result result = mal_device__wait_for_frames__wasapi(pDevice, &framesAvailable); - if (result != MAL_SUCCESS) { - return result; - } - - if (framesAvailable == 0) { - continue; - } - - // If it's a playback device, don't bother grabbing more data if the device is being stopped. - if (pDevice->wasapi.breakFromMainLoop && pDevice->type == mal_device_type_playback) { - return MAL_SUCCESS; - } - - if (pDevice->type == mal_device_type_playback) { - BYTE* pData; - HRESULT hr = mal_IAudioRenderClient_GetBuffer((mal_IAudioRenderClient*)pDevice->wasapi.pRenderClient, framesAvailable, &pData); - if (FAILED(hr)) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[WASAPI] Failed to retrieve internal buffer from playback device in preparation for sending new data to the device.", MAL_FAILED_TO_MAP_DEVICE_BUFFER); - } - - mal_device__read_frames_from_client(pDevice, framesAvailable, pData); - - hr = mal_IAudioRenderClient_ReleaseBuffer((mal_IAudioRenderClient*)pDevice->wasapi.pRenderClient, framesAvailable, 0); - if (FAILED(hr)) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[WASAPI] Failed to release internal buffer from playback device in preparation for sending new data to the device.", MAL_FAILED_TO_UNMAP_DEVICE_BUFFER); - } - } else { - mal_uint32 framesRemaining = framesAvailable; - while (framesRemaining > 0) { - BYTE* pData; - mal_uint32 framesToSend; - DWORD flags; - HRESULT hr = mal_IAudioCaptureClient_GetBuffer((mal_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, &pData, &framesToSend, &flags, NULL, NULL); - if (FAILED(hr)) { - mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[WASAPI] WARNING: Failed to retrieve internal buffer from capture device in preparation for sending new data to the client.", MAL_FAILED_TO_MAP_DEVICE_BUFFER); - break; - } - - if (hr != MAL_AUDCLNT_S_BUFFER_EMPTY) { - mal_device__send_frames_to_client(pDevice, framesToSend, pData); - - hr = mal_IAudioCaptureClient_ReleaseBuffer((mal_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, framesToSend); - if (FAILED(hr)) { - mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[WASAPI] WARNING: Failed to release internal buffer from capture device in preparation for sending new data to the client.", MAL_FAILED_TO_UNMAP_DEVICE_BUFFER); - break; - } - - if (framesRemaining >= framesToSend) { - framesRemaining -= framesToSend; - } else { - framesRemaining = 0; - } - } - } - } - } - - return MAL_SUCCESS; -} - -mal_result mal_context_uninit__wasapi(mal_context* pContext) -{ - mal_assert(pContext != NULL); - mal_assert(pContext->backend == mal_backend_wasapi); - (void)pContext; - - return MAL_SUCCESS; -} - -mal_result mal_context_init__wasapi(mal_context* pContext) -{ - mal_assert(pContext != NULL); - (void)pContext; - - mal_result result = MAL_SUCCESS; - -#ifdef MAL_WIN32_DESKTOP - // WASAPI is only supported in Vista SP1 and newer. The reason for SP1 and not the base version of Vista is that event-driven - // exclusive mode does not work until SP1. - mal_OSVERSIONINFOEXW osvi; - mal_zero_object(&osvi); - osvi.dwOSVersionInfoSize = sizeof(osvi); - osvi.dwMajorVersion = HIBYTE(_WIN32_WINNT_VISTA); - osvi.dwMinorVersion = LOBYTE(_WIN32_WINNT_VISTA); - osvi.wServicePackMajor = 1; - if (VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR, VerSetConditionMask(VerSetConditionMask(VerSetConditionMask(0, VER_MAJORVERSION, VER_GREATER_EQUAL), VER_MINORVERSION, VER_GREATER_EQUAL), VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL))) { - result = MAL_SUCCESS; - } else { - result = MAL_NO_BACKEND; - } -#endif - - if (result != MAL_SUCCESS) { - return result; - } - - pContext->onUninit = mal_context_uninit__wasapi; - pContext->onDeviceIDEqual = mal_context_is_device_id_equal__wasapi; - pContext->onEnumDevices = mal_context_enumerate_devices__wasapi; - pContext->onGetDeviceInfo = mal_context_get_device_info__wasapi; - pContext->onDeviceInit = mal_device_init__wasapi; - pContext->onDeviceUninit = mal_device_uninit__wasapi; - pContext->onDeviceReinit = mal_device_reinit__wasapi; - pContext->onDeviceStart = mal_device_start__wasapi; - pContext->onDeviceStop = mal_device_stop__wasapi; - pContext->onDeviceBreakMainLoop = mal_device_break_main_loop__wasapi; - pContext->onDeviceMainLoop = mal_device_main_loop__wasapi; - - return result; -} -#endif - -/////////////////////////////////////////////////////////////////////////////// -// -// DirectSound Backend -// -/////////////////////////////////////////////////////////////////////////////// -#ifdef MAL_HAS_DSOUND -//#include - -GUID MAL_GUID_IID_DirectSoundNotify = {0xb0210783, 0x89cd, 0x11d0, {0xaf, 0x08, 0x00, 0xa0, 0xc9, 0x25, 0xcd, 0x16}}; - -// mini_al only uses priority or exclusive modes. -#define MAL_DSSCL_NORMAL 1 -#define MAL_DSSCL_PRIORITY 2 -#define MAL_DSSCL_EXCLUSIVE 3 -#define MAL_DSSCL_WRITEPRIMARY 4 - -#define MAL_DSCAPS_PRIMARYMONO 0x00000001 -#define MAL_DSCAPS_PRIMARYSTEREO 0x00000002 -#define MAL_DSCAPS_PRIMARY8BIT 0x00000004 -#define MAL_DSCAPS_PRIMARY16BIT 0x00000008 -#define MAL_DSCAPS_CONTINUOUSRATE 0x00000010 -#define MAL_DSCAPS_EMULDRIVER 0x00000020 -#define MAL_DSCAPS_CERTIFIED 0x00000040 -#define MAL_DSCAPS_SECONDARYMONO 0x00000100 -#define MAL_DSCAPS_SECONDARYSTEREO 0x00000200 -#define MAL_DSCAPS_SECONDARY8BIT 0x00000400 -#define MAL_DSCAPS_SECONDARY16BIT 0x00000800 - -#define MAL_DSBCAPS_PRIMARYBUFFER 0x00000001 -#define MAL_DSBCAPS_STATIC 0x00000002 -#define MAL_DSBCAPS_LOCHARDWARE 0x00000004 -#define MAL_DSBCAPS_LOCSOFTWARE 0x00000008 -#define MAL_DSBCAPS_CTRL3D 0x00000010 -#define MAL_DSBCAPS_CTRLFREQUENCY 0x00000020 -#define MAL_DSBCAPS_CTRLPAN 0x00000040 -#define MAL_DSBCAPS_CTRLVOLUME 0x00000080 -#define MAL_DSBCAPS_CTRLPOSITIONNOTIFY 0x00000100 -#define MAL_DSBCAPS_CTRLFX 0x00000200 -#define MAL_DSBCAPS_STICKYFOCUS 0x00004000 -#define MAL_DSBCAPS_GLOBALFOCUS 0x00008000 -#define MAL_DSBCAPS_GETCURRENTPOSITION2 0x00010000 -#define MAL_DSBCAPS_MUTE3DATMAXDISTANCE 0x00020000 -#define MAL_DSBCAPS_LOCDEFER 0x00040000 -#define MAL_DSBCAPS_TRUEPLAYPOSITION 0x00080000 - -#define MAL_DSBPLAY_LOOPING 0x00000001 -#define MAL_DSBPLAY_LOCHARDWARE 0x00000002 -#define MAL_DSBPLAY_LOCSOFTWARE 0x00000004 -#define MAL_DSBPLAY_TERMINATEBY_TIME 0x00000008 -#define MAL_DSBPLAY_TERMINATEBY_DISTANCE 0x00000010 -#define MAL_DSBPLAY_TERMINATEBY_PRIORITY 0x00000020 - -#define MAL_DSCBSTART_LOOPING 0x00000001 - -typedef struct -{ - DWORD dwSize; - DWORD dwFlags; - DWORD dwBufferBytes; - DWORD dwReserved; - WAVEFORMATEX* lpwfxFormat; - GUID guid3DAlgorithm; -} MAL_DSBUFFERDESC; - -typedef struct -{ - DWORD dwSize; - DWORD dwFlags; - DWORD dwBufferBytes; - DWORD dwReserved; - WAVEFORMATEX* lpwfxFormat; - DWORD dwFXCount; - void* lpDSCFXDesc; // <-- mini_al doesn't use this, so set to void*. -} MAL_DSCBUFFERDESC; - -typedef struct -{ - DWORD dwSize; - DWORD dwFlags; - DWORD dwMinSecondarySampleRate; - DWORD dwMaxSecondarySampleRate; - DWORD dwPrimaryBuffers; - DWORD dwMaxHwMixingAllBuffers; - DWORD dwMaxHwMixingStaticBuffers; - DWORD dwMaxHwMixingStreamingBuffers; - DWORD dwFreeHwMixingAllBuffers; - DWORD dwFreeHwMixingStaticBuffers; - DWORD dwFreeHwMixingStreamingBuffers; - DWORD dwMaxHw3DAllBuffers; - DWORD dwMaxHw3DStaticBuffers; - DWORD dwMaxHw3DStreamingBuffers; - DWORD dwFreeHw3DAllBuffers; - DWORD dwFreeHw3DStaticBuffers; - DWORD dwFreeHw3DStreamingBuffers; - DWORD dwTotalHwMemBytes; - DWORD dwFreeHwMemBytes; - DWORD dwMaxContigFreeHwMemBytes; - DWORD dwUnlockTransferRateHwBuffers; - DWORD dwPlayCpuOverheadSwBuffers; - DWORD dwReserved1; - DWORD dwReserved2; -} MAL_DSCAPS; - -typedef struct -{ - DWORD dwSize; - DWORD dwFlags; - DWORD dwBufferBytes; - DWORD dwUnlockTransferRate; - DWORD dwPlayCpuOverhead; -} MAL_DSBCAPS; - -typedef struct -{ - DWORD dwSize; - DWORD dwFlags; - DWORD dwFormats; - DWORD dwChannels; -} MAL_DSCCAPS; - -typedef struct -{ - DWORD dwSize; - DWORD dwFlags; - DWORD dwBufferBytes; - DWORD dwReserved; -} MAL_DSCBCAPS; - -typedef struct -{ - DWORD dwOffset; - HANDLE hEventNotify; -} MAL_DSBPOSITIONNOTIFY; - -typedef struct mal_IDirectSound mal_IDirectSound; -typedef struct mal_IDirectSoundBuffer mal_IDirectSoundBuffer; -typedef struct mal_IDirectSoundCapture mal_IDirectSoundCapture; -typedef struct mal_IDirectSoundCaptureBuffer mal_IDirectSoundCaptureBuffer; -typedef struct mal_IDirectSoundNotify mal_IDirectSoundNotify; - - -// COM objects. The way these work is that you have a vtable (a list of function pointers, kind of -// like how C++ works internally), and then you have a structure with a single member, which is a -// pointer to the vtable. The vtable is where the methods of the object are defined. Methods need -// to be in a specific order, and parent classes need to have their methods declared first. - -// IDirectSound -typedef struct -{ - // IUnknown - HRESULT (STDMETHODCALLTYPE * QueryInterface)(mal_IDirectSound* pThis, const IID* const riid, void** ppObject); - ULONG (STDMETHODCALLTYPE * AddRef) (mal_IDirectSound* pThis); - ULONG (STDMETHODCALLTYPE * Release) (mal_IDirectSound* pThis); - - // IDirectSound - HRESULT (STDMETHODCALLTYPE * CreateSoundBuffer) (mal_IDirectSound* pThis, const MAL_DSBUFFERDESC* pDSBufferDesc, mal_IDirectSoundBuffer** ppDSBuffer, void* pUnkOuter); - HRESULT (STDMETHODCALLTYPE * GetCaps) (mal_IDirectSound* pThis, MAL_DSCAPS* pDSCaps); - HRESULT (STDMETHODCALLTYPE * DuplicateSoundBuffer)(mal_IDirectSound* pThis, mal_IDirectSoundBuffer* pDSBufferOriginal, mal_IDirectSoundBuffer** ppDSBufferDuplicate); - HRESULT (STDMETHODCALLTYPE * SetCooperativeLevel) (mal_IDirectSound* pThis, HWND hwnd, DWORD dwLevel); - HRESULT (STDMETHODCALLTYPE * Compact) (mal_IDirectSound* pThis); - HRESULT (STDMETHODCALLTYPE * GetSpeakerConfig) (mal_IDirectSound* pThis, DWORD* pSpeakerConfig); - HRESULT (STDMETHODCALLTYPE * SetSpeakerConfig) (mal_IDirectSound* pThis, DWORD dwSpeakerConfig); - HRESULT (STDMETHODCALLTYPE * Initialize) (mal_IDirectSound* pThis, const GUID* pGuidDevice); -} mal_IDirectSoundVtbl; -struct mal_IDirectSound -{ - mal_IDirectSoundVtbl* lpVtbl; -}; -HRESULT mal_IDirectSound_QueryInterface(mal_IDirectSound* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } -ULONG mal_IDirectSound_AddRef(mal_IDirectSound* pThis) { return pThis->lpVtbl->AddRef(pThis); } -ULONG mal_IDirectSound_Release(mal_IDirectSound* pThis) { return pThis->lpVtbl->Release(pThis); } -HRESULT mal_IDirectSound_CreateSoundBuffer(mal_IDirectSound* pThis, const MAL_DSBUFFERDESC* pDSBufferDesc, mal_IDirectSoundBuffer** ppDSBuffer, void* pUnkOuter) { return pThis->lpVtbl->CreateSoundBuffer(pThis, pDSBufferDesc, ppDSBuffer, pUnkOuter); } -HRESULT mal_IDirectSound_GetCaps(mal_IDirectSound* pThis, MAL_DSCAPS* pDSCaps) { return pThis->lpVtbl->GetCaps(pThis, pDSCaps); } -HRESULT mal_IDirectSound_DuplicateSoundBuffer(mal_IDirectSound* pThis, mal_IDirectSoundBuffer* pDSBufferOriginal, mal_IDirectSoundBuffer** ppDSBufferDuplicate) { return pThis->lpVtbl->DuplicateSoundBuffer(pThis, pDSBufferOriginal, ppDSBufferDuplicate); } -HRESULT mal_IDirectSound_SetCooperativeLevel(mal_IDirectSound* pThis, HWND hwnd, DWORD dwLevel) { return pThis->lpVtbl->SetCooperativeLevel(pThis, hwnd, dwLevel); } -HRESULT mal_IDirectSound_Compact(mal_IDirectSound* pThis) { return pThis->lpVtbl->Compact(pThis); } -HRESULT mal_IDirectSound_GetSpeakerConfig(mal_IDirectSound* pThis, DWORD* pSpeakerConfig) { return pThis->lpVtbl->GetSpeakerConfig(pThis, pSpeakerConfig); } -HRESULT mal_IDirectSound_SetSpeakerConfig(mal_IDirectSound* pThis, DWORD dwSpeakerConfig) { return pThis->lpVtbl->SetSpeakerConfig(pThis, dwSpeakerConfig); } -HRESULT mal_IDirectSound_Initialize(mal_IDirectSound* pThis, const GUID* pGuidDevice) { return pThis->lpVtbl->Initialize(pThis, pGuidDevice); } - - -// IDirectSoundBuffer -typedef struct -{ - // IUnknown - HRESULT (STDMETHODCALLTYPE * QueryInterface)(mal_IDirectSoundBuffer* pThis, const IID* const riid, void** ppObject); - ULONG (STDMETHODCALLTYPE * AddRef) (mal_IDirectSoundBuffer* pThis); - ULONG (STDMETHODCALLTYPE * Release) (mal_IDirectSoundBuffer* pThis); - - // IDirectSoundBuffer - HRESULT (STDMETHODCALLTYPE * GetCaps) (mal_IDirectSoundBuffer* pThis, MAL_DSBCAPS* pDSBufferCaps); - HRESULT (STDMETHODCALLTYPE * GetCurrentPosition)(mal_IDirectSoundBuffer* pThis, DWORD* pCurrentPlayCursor, DWORD* pCurrentWriteCursor); - HRESULT (STDMETHODCALLTYPE * GetFormat) (mal_IDirectSoundBuffer* pThis, WAVEFORMATEX* pFormat, DWORD dwSizeAllocated, DWORD* pSizeWritten); - HRESULT (STDMETHODCALLTYPE * GetVolume) (mal_IDirectSoundBuffer* pThis, LONG* pVolume); - HRESULT (STDMETHODCALLTYPE * GetPan) (mal_IDirectSoundBuffer* pThis, LONG* pPan); - HRESULT (STDMETHODCALLTYPE * GetFrequency) (mal_IDirectSoundBuffer* pThis, DWORD* pFrequency); - HRESULT (STDMETHODCALLTYPE * GetStatus) (mal_IDirectSoundBuffer* pThis, DWORD* pStatus); - HRESULT (STDMETHODCALLTYPE * Initialize) (mal_IDirectSoundBuffer* pThis, mal_IDirectSound* pDirectSound, const MAL_DSBUFFERDESC* pDSBufferDesc); - HRESULT (STDMETHODCALLTYPE * Lock) (mal_IDirectSoundBuffer* pThis, DWORD dwOffset, DWORD dwBytes, void** ppAudioPtr1, DWORD* pAudioBytes1, void** ppAudioPtr2, DWORD* pAudioBytes2, DWORD dwFlags); - HRESULT (STDMETHODCALLTYPE * Play) (mal_IDirectSoundBuffer* pThis, DWORD dwReserved1, DWORD dwPriority, DWORD dwFlags); - HRESULT (STDMETHODCALLTYPE * SetCurrentPosition)(mal_IDirectSoundBuffer* pThis, DWORD dwNewPosition); - HRESULT (STDMETHODCALLTYPE * SetFormat) (mal_IDirectSoundBuffer* pThis, const WAVEFORMATEX* pFormat); - HRESULT (STDMETHODCALLTYPE * SetVolume) (mal_IDirectSoundBuffer* pThis, LONG volume); - HRESULT (STDMETHODCALLTYPE * SetPan) (mal_IDirectSoundBuffer* pThis, LONG pan); - HRESULT (STDMETHODCALLTYPE * SetFrequency) (mal_IDirectSoundBuffer* pThis, DWORD dwFrequency); - HRESULT (STDMETHODCALLTYPE * Stop) (mal_IDirectSoundBuffer* pThis); - HRESULT (STDMETHODCALLTYPE * Unlock) (mal_IDirectSoundBuffer* pThis, void* pAudioPtr1, DWORD dwAudioBytes1, void* pAudioPtr2, DWORD dwAudioBytes2); - HRESULT (STDMETHODCALLTYPE * Restore) (mal_IDirectSoundBuffer* pThis); -} mal_IDirectSoundBufferVtbl; -struct mal_IDirectSoundBuffer -{ - mal_IDirectSoundBufferVtbl* lpVtbl; -}; -HRESULT mal_IDirectSoundBuffer_QueryInterface(mal_IDirectSoundBuffer* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } -ULONG mal_IDirectSoundBuffer_AddRef(mal_IDirectSoundBuffer* pThis) { return pThis->lpVtbl->AddRef(pThis); } -ULONG mal_IDirectSoundBuffer_Release(mal_IDirectSoundBuffer* pThis) { return pThis->lpVtbl->Release(pThis); } -HRESULT mal_IDirectSoundBuffer_GetCaps(mal_IDirectSoundBuffer* pThis, MAL_DSBCAPS* pDSBufferCaps) { return pThis->lpVtbl->GetCaps(pThis, pDSBufferCaps); } -HRESULT mal_IDirectSoundBuffer_GetCurrentPosition(mal_IDirectSoundBuffer* pThis, DWORD* pCurrentPlayCursor, DWORD* pCurrentWriteCursor) { return pThis->lpVtbl->GetCurrentPosition(pThis, pCurrentPlayCursor, pCurrentWriteCursor); } -HRESULT mal_IDirectSoundBuffer_GetFormat(mal_IDirectSoundBuffer* pThis, WAVEFORMATEX* pFormat, DWORD dwSizeAllocated, DWORD* pSizeWritten) { return pThis->lpVtbl->GetFormat(pThis, pFormat, dwSizeAllocated, pSizeWritten); } -HRESULT mal_IDirectSoundBuffer_GetVolume(mal_IDirectSoundBuffer* pThis, LONG* pVolume) { return pThis->lpVtbl->GetVolume(pThis, pVolume); } -HRESULT mal_IDirectSoundBuffer_GetPan(mal_IDirectSoundBuffer* pThis, LONG* pPan) { return pThis->lpVtbl->GetPan(pThis, pPan); } -HRESULT mal_IDirectSoundBuffer_GetFrequency(mal_IDirectSoundBuffer* pThis, DWORD* pFrequency) { return pThis->lpVtbl->GetFrequency(pThis, pFrequency); } -HRESULT mal_IDirectSoundBuffer_GetStatus(mal_IDirectSoundBuffer* pThis, DWORD* pStatus) { return pThis->lpVtbl->GetStatus(pThis, pStatus); } -HRESULT mal_IDirectSoundBuffer_Initialize(mal_IDirectSoundBuffer* pThis, mal_IDirectSound* pDirectSound, const MAL_DSBUFFERDESC* pDSBufferDesc) { return pThis->lpVtbl->Initialize(pThis, pDirectSound, pDSBufferDesc); } -HRESULT mal_IDirectSoundBuffer_Lock(mal_IDirectSoundBuffer* pThis, DWORD dwOffset, DWORD dwBytes, void** ppAudioPtr1, DWORD* pAudioBytes1, void** ppAudioPtr2, DWORD* pAudioBytes2, DWORD dwFlags) { return pThis->lpVtbl->Lock(pThis, dwOffset, dwBytes, ppAudioPtr1, pAudioBytes1, ppAudioPtr2, pAudioBytes2, dwFlags); } -HRESULT mal_IDirectSoundBuffer_Play(mal_IDirectSoundBuffer* pThis, DWORD dwReserved1, DWORD dwPriority, DWORD dwFlags) { return pThis->lpVtbl->Play(pThis, dwReserved1, dwPriority, dwFlags); } -HRESULT mal_IDirectSoundBuffer_SetCurrentPosition(mal_IDirectSoundBuffer* pThis, DWORD dwNewPosition) { return pThis->lpVtbl->SetCurrentPosition(pThis, dwNewPosition); } -HRESULT mal_IDirectSoundBuffer_SetFormat(mal_IDirectSoundBuffer* pThis, const WAVEFORMATEX* pFormat) { return pThis->lpVtbl->SetFormat(pThis, pFormat); } -HRESULT mal_IDirectSoundBuffer_SetVolume(mal_IDirectSoundBuffer* pThis, LONG volume) { return pThis->lpVtbl->SetVolume(pThis, volume); } -HRESULT mal_IDirectSoundBuffer_SetPan(mal_IDirectSoundBuffer* pThis, LONG pan) { return pThis->lpVtbl->SetPan(pThis, pan); } -HRESULT mal_IDirectSoundBuffer_SetFrequency(mal_IDirectSoundBuffer* pThis, DWORD dwFrequency) { return pThis->lpVtbl->SetFrequency(pThis, dwFrequency); } -HRESULT mal_IDirectSoundBuffer_Stop(mal_IDirectSoundBuffer* pThis) { return pThis->lpVtbl->Stop(pThis); } -HRESULT mal_IDirectSoundBuffer_Unlock(mal_IDirectSoundBuffer* pThis, void* pAudioPtr1, DWORD dwAudioBytes1, void* pAudioPtr2, DWORD dwAudioBytes2) { return pThis->lpVtbl->Unlock(pThis, pAudioPtr1, dwAudioBytes1, pAudioPtr2, dwAudioBytes2); } -HRESULT mal_IDirectSoundBuffer_Restore(mal_IDirectSoundBuffer* pThis) { return pThis->lpVtbl->Restore(pThis); } - - -// IDirectSoundCapture -typedef struct -{ - // IUnknown - HRESULT (STDMETHODCALLTYPE * QueryInterface)(mal_IDirectSoundCapture* pThis, const IID* const riid, void** ppObject); - ULONG (STDMETHODCALLTYPE * AddRef) (mal_IDirectSoundCapture* pThis); - ULONG (STDMETHODCALLTYPE * Release) (mal_IDirectSoundCapture* pThis); - - // IDirectSoundCapture - HRESULT (STDMETHODCALLTYPE * CreateCaptureBuffer)(mal_IDirectSoundCapture* pThis, const MAL_DSCBUFFERDESC* pDSCBufferDesc, mal_IDirectSoundCaptureBuffer** ppDSCBuffer, void* pUnkOuter); - HRESULT (STDMETHODCALLTYPE * GetCaps) (mal_IDirectSoundCapture* pThis, MAL_DSCCAPS* pDSCCaps); - HRESULT (STDMETHODCALLTYPE * Initialize) (mal_IDirectSoundCapture* pThis, const GUID* pGuidDevice); -} mal_IDirectSoundCaptureVtbl; -struct mal_IDirectSoundCapture -{ - mal_IDirectSoundCaptureVtbl* lpVtbl; -}; -HRESULT mal_IDirectSoundCapture_QueryInterface(mal_IDirectSoundCapture* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } -ULONG mal_IDirectSoundCapture_AddRef(mal_IDirectSoundCapture* pThis) { return pThis->lpVtbl->AddRef(pThis); } -ULONG mal_IDirectSoundCapture_Release(mal_IDirectSoundCapture* pThis) { return pThis->lpVtbl->Release(pThis); } -HRESULT mal_IDirectSoundCapture_CreateCaptureBuffer(mal_IDirectSoundCapture* pThis, const MAL_DSCBUFFERDESC* pDSCBufferDesc, mal_IDirectSoundCaptureBuffer** ppDSCBuffer, void* pUnkOuter) { return pThis->lpVtbl->CreateCaptureBuffer(pThis, pDSCBufferDesc, ppDSCBuffer, pUnkOuter); } -HRESULT mal_IDirectSoundCapture_GetCaps (mal_IDirectSoundCapture* pThis, MAL_DSCCAPS* pDSCCaps) { return pThis->lpVtbl->GetCaps(pThis, pDSCCaps); } -HRESULT mal_IDirectSoundCapture_Initialize (mal_IDirectSoundCapture* pThis, const GUID* pGuidDevice) { return pThis->lpVtbl->Initialize(pThis, pGuidDevice); } - - -// IDirectSoundCaptureBuffer -typedef struct -{ - // IUnknown - HRESULT (STDMETHODCALLTYPE * QueryInterface)(mal_IDirectSoundCaptureBuffer* pThis, const IID* const riid, void** ppObject); - ULONG (STDMETHODCALLTYPE * AddRef) (mal_IDirectSoundCaptureBuffer* pThis); - ULONG (STDMETHODCALLTYPE * Release) (mal_IDirectSoundCaptureBuffer* pThis); - - // IDirectSoundCaptureBuffer - HRESULT (STDMETHODCALLTYPE * GetCaps) (mal_IDirectSoundCaptureBuffer* pThis, MAL_DSCBCAPS* pDSCBCaps); - HRESULT (STDMETHODCALLTYPE * GetCurrentPosition)(mal_IDirectSoundCaptureBuffer* pThis, DWORD* pCapturePosition, DWORD* pReadPosition); - HRESULT (STDMETHODCALLTYPE * GetFormat) (mal_IDirectSoundCaptureBuffer* pThis, WAVEFORMATEX* pFormat, DWORD dwSizeAllocated, DWORD* pSizeWritten); - HRESULT (STDMETHODCALLTYPE * GetStatus) (mal_IDirectSoundCaptureBuffer* pThis, DWORD* pStatus); - HRESULT (STDMETHODCALLTYPE * Initialize) (mal_IDirectSoundCaptureBuffer* pThis, mal_IDirectSoundCapture* pDirectSoundCapture, const MAL_DSCBUFFERDESC* pDSCBufferDesc); - HRESULT (STDMETHODCALLTYPE * Lock) (mal_IDirectSoundCaptureBuffer* pThis, DWORD dwOffset, DWORD dwBytes, void** ppAudioPtr1, DWORD* pAudioBytes1, void** ppAudioPtr2, DWORD* pAudioBytes2, DWORD dwFlags); - HRESULT (STDMETHODCALLTYPE * Start) (mal_IDirectSoundCaptureBuffer* pThis, DWORD dwFlags); - HRESULT (STDMETHODCALLTYPE * Stop) (mal_IDirectSoundCaptureBuffer* pThis); - HRESULT (STDMETHODCALLTYPE * Unlock) (mal_IDirectSoundCaptureBuffer* pThis, void* pAudioPtr1, DWORD dwAudioBytes1, void* pAudioPtr2, DWORD dwAudioBytes2); -} mal_IDirectSoundCaptureBufferVtbl; -struct mal_IDirectSoundCaptureBuffer -{ - mal_IDirectSoundCaptureBufferVtbl* lpVtbl; -}; -HRESULT mal_IDirectSoundCaptureBuffer_QueryInterface(mal_IDirectSoundCaptureBuffer* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } -ULONG mal_IDirectSoundCaptureBuffer_AddRef(mal_IDirectSoundCaptureBuffer* pThis) { return pThis->lpVtbl->AddRef(pThis); } -ULONG mal_IDirectSoundCaptureBuffer_Release(mal_IDirectSoundCaptureBuffer* pThis) { return pThis->lpVtbl->Release(pThis); } -HRESULT mal_IDirectSoundCaptureBuffer_GetCaps(mal_IDirectSoundCaptureBuffer* pThis, MAL_DSCBCAPS* pDSCBCaps) { return pThis->lpVtbl->GetCaps(pThis, pDSCBCaps); } -HRESULT mal_IDirectSoundCaptureBuffer_GetCurrentPosition(mal_IDirectSoundCaptureBuffer* pThis, DWORD* pCapturePosition, DWORD* pReadPosition) { return pThis->lpVtbl->GetCurrentPosition(pThis, pCapturePosition, pReadPosition); } -HRESULT mal_IDirectSoundCaptureBuffer_GetFormat(mal_IDirectSoundCaptureBuffer* pThis, WAVEFORMATEX* pFormat, DWORD dwSizeAllocated, DWORD* pSizeWritten) { return pThis->lpVtbl->GetFormat(pThis, pFormat, dwSizeAllocated, pSizeWritten); } -HRESULT mal_IDirectSoundCaptureBuffer_GetStatus(mal_IDirectSoundCaptureBuffer* pThis, DWORD* pStatus) { return pThis->lpVtbl->GetStatus(pThis, pStatus); } -HRESULT mal_IDirectSoundCaptureBuffer_Initialize(mal_IDirectSoundCaptureBuffer* pThis, mal_IDirectSoundCapture* pDirectSoundCapture, const MAL_DSCBUFFERDESC* pDSCBufferDesc) { return pThis->lpVtbl->Initialize(pThis, pDirectSoundCapture, pDSCBufferDesc); } -HRESULT mal_IDirectSoundCaptureBuffer_Lock(mal_IDirectSoundCaptureBuffer* pThis, DWORD dwOffset, DWORD dwBytes, void** ppAudioPtr1, DWORD* pAudioBytes1, void** ppAudioPtr2, DWORD* pAudioBytes2, DWORD dwFlags) { return pThis->lpVtbl->Lock(pThis, dwOffset, dwBytes, ppAudioPtr1, pAudioBytes1, ppAudioPtr2, pAudioBytes2, dwFlags); } -HRESULT mal_IDirectSoundCaptureBuffer_Start(mal_IDirectSoundCaptureBuffer* pThis, DWORD dwFlags) { return pThis->lpVtbl->Start(pThis, dwFlags); } -HRESULT mal_IDirectSoundCaptureBuffer_Stop(mal_IDirectSoundCaptureBuffer* pThis) { return pThis->lpVtbl->Stop(pThis); } -HRESULT mal_IDirectSoundCaptureBuffer_Unlock(mal_IDirectSoundCaptureBuffer* pThis, void* pAudioPtr1, DWORD dwAudioBytes1, void* pAudioPtr2, DWORD dwAudioBytes2) { return pThis->lpVtbl->Unlock(pThis, pAudioPtr1, dwAudioBytes1, pAudioPtr2, dwAudioBytes2); } - - -// IDirectSoundNotify -typedef struct -{ - // IUnknown - HRESULT (STDMETHODCALLTYPE * QueryInterface)(mal_IDirectSoundNotify* pThis, const IID* const riid, void** ppObject); - ULONG (STDMETHODCALLTYPE * AddRef) (mal_IDirectSoundNotify* pThis); - ULONG (STDMETHODCALLTYPE * Release) (mal_IDirectSoundNotify* pThis); - - // IDirectSoundNotify - HRESULT (STDMETHODCALLTYPE * SetNotificationPositions)(mal_IDirectSoundNotify* pThis, DWORD dwPositionNotifies, const MAL_DSBPOSITIONNOTIFY* pPositionNotifies); -} mal_IDirectSoundNotifyVtbl; -struct mal_IDirectSoundNotify -{ - mal_IDirectSoundNotifyVtbl* lpVtbl; -}; -HRESULT mal_IDirectSoundNotify_QueryInterface(mal_IDirectSoundNotify* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } -ULONG mal_IDirectSoundNotify_AddRef(mal_IDirectSoundNotify* pThis) { return pThis->lpVtbl->AddRef(pThis); } -ULONG mal_IDirectSoundNotify_Release(mal_IDirectSoundNotify* pThis) { return pThis->lpVtbl->Release(pThis); } -HRESULT mal_IDirectSoundNotify_SetNotificationPositions(mal_IDirectSoundNotify* pThis, DWORD dwPositionNotifies, const MAL_DSBPOSITIONNOTIFY* pPositionNotifies) { return pThis->lpVtbl->SetNotificationPositions(pThis, dwPositionNotifies, pPositionNotifies); } - - -typedef BOOL (CALLBACK * mal_DSEnumCallbackAProc) (LPGUID pDeviceGUID, LPCSTR pDeviceDescription, LPCSTR pModule, LPVOID pContext); -typedef HRESULT (WINAPI * mal_DirectSoundCreateProc) (const GUID* pcGuidDevice, mal_IDirectSound** ppDS8, LPUNKNOWN pUnkOuter); -typedef HRESULT (WINAPI * mal_DirectSoundEnumerateAProc) (mal_DSEnumCallbackAProc pDSEnumCallback, LPVOID pContext); -typedef HRESULT (WINAPI * mal_DirectSoundCaptureCreateProc) (const GUID* pcGuidDevice, mal_IDirectSoundCapture** ppDSC8, LPUNKNOWN pUnkOuter); -typedef HRESULT (WINAPI * mal_DirectSoundCaptureEnumerateAProc)(mal_DSEnumCallbackAProc pDSEnumCallback, LPVOID pContext); - - -// Retrieves the channel count and channel map for the given speaker configuration. If the speaker configuration is unknown, -// the channel count and channel map will be left unmodified. -void mal_get_channels_from_speaker_config__dsound(DWORD speakerConfig, WORD* pChannelsOut, DWORD* pChannelMapOut) -{ - WORD channels = 0; - if (pChannelsOut != NULL) { - channels = *pChannelsOut; - } - - DWORD channelMap = 0; - if (pChannelMapOut != NULL) { - channelMap = *pChannelMapOut; - } - - // The speaker configuration is a combination of speaker config and speaker geometry. The lower 8 bits is what we care about. The upper - // 16 bits is for the geometry. - switch ((BYTE)(speakerConfig)) { - case 1 /*DSSPEAKER_HEADPHONE*/: channels = 2; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break; - case 2 /*DSSPEAKER_MONO*/: channels = 1; channelMap = SPEAKER_FRONT_CENTER; break; - case 3 /*DSSPEAKER_QUAD*/: channels = 4; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break; - case 4 /*DSSPEAKER_STEREO*/: channels = 2; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break; - case 5 /*DSSPEAKER_SURROUND*/: channels = 4; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_BACK_CENTER; break; - case 6 /*DSSPEAKER_5POINT1_BACK*/ /*DSSPEAKER_5POINT1*/: channels = 6; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break; - case 7 /*DSSPEAKER_7POINT1_WIDE*/ /*DSSPEAKER_7POINT1*/: channels = 8; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT | SPEAKER_FRONT_LEFT_OF_CENTER | SPEAKER_FRONT_RIGHT_OF_CENTER; break; - case 8 /*DSSPEAKER_7POINT1_SURROUND*/: channels = 8; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT | SPEAKER_SIDE_LEFT | SPEAKER_SIDE_RIGHT; break; - case 9 /*DSSPEAKER_5POINT1_SURROUND*/: channels = 6; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_SIDE_LEFT | SPEAKER_SIDE_RIGHT; break; - default: break; - } - - if (pChannelsOut != NULL) { - *pChannelsOut = channels; - } - - if (pChannelMapOut != NULL) { - *pChannelMapOut = channelMap; - } -} - - -mal_result mal_context_create_IDirectSound__dsound(mal_context* pContext, mal_share_mode shareMode, const mal_device_id* pDeviceID, mal_IDirectSound** ppDirectSound) -{ - mal_assert(pContext != NULL); - mal_assert(ppDirectSound != NULL); - - *ppDirectSound = NULL; - mal_IDirectSound* pDirectSound = NULL; - - if (FAILED(((mal_DirectSoundCreateProc)pContext->dsound.DirectSoundCreate)((pDeviceID == NULL) ? NULL : (const GUID*)pDeviceID->dsound, &pDirectSound, NULL))) { - return mal_context_post_error(pContext, NULL, MAL_LOG_LEVEL_ERROR, "[DirectSound] DirectSoundCreate() failed for playback device.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - - // The cooperative level must be set before doing anything else. - HWND hWnd = ((MAL_PFN_GetForegroundWindow)pContext->win32.GetForegroundWindow)(); - if (hWnd == NULL) { - hWnd = ((MAL_PFN_GetDesktopWindow)pContext->win32.GetDesktopWindow)(); - } - if (FAILED(mal_IDirectSound_SetCooperativeLevel(pDirectSound, hWnd, (shareMode == mal_share_mode_exclusive) ? MAL_DSSCL_EXCLUSIVE : MAL_DSSCL_PRIORITY))) { - return mal_context_post_error(pContext, NULL, MAL_LOG_LEVEL_ERROR, "[DirectSound] IDirectSound_SetCooperateiveLevel() failed for playback device.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - - *ppDirectSound = pDirectSound; - return MAL_SUCCESS; -} - -mal_result mal_context_create_IDirectSoundCapture__dsound(mal_context* pContext, mal_share_mode shareMode, const mal_device_id* pDeviceID, mal_IDirectSoundCapture** ppDirectSoundCapture) -{ - mal_assert(pContext != NULL); - mal_assert(ppDirectSoundCapture != NULL); - - // Everything is shared in capture mode by the looks of it. - (void)shareMode; - - *ppDirectSoundCapture = NULL; - mal_IDirectSoundCapture* pDirectSoundCapture = NULL; - - if (FAILED(((mal_DirectSoundCaptureCreateProc)pContext->dsound.DirectSoundCaptureCreate)((pDeviceID == NULL) ? NULL : (const GUID*)pDeviceID->dsound, &pDirectSoundCapture, NULL))) { - return mal_context_post_error(pContext, NULL, MAL_LOG_LEVEL_ERROR, "[DirectSound] DirectSoundCaptureCreate() failed for capture device.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - - *ppDirectSoundCapture = pDirectSoundCapture; - return MAL_SUCCESS; -} - -mal_result mal_context_get_format_info_for_IDirectSoundCapture__dsound(mal_context* pContext, mal_IDirectSoundCapture* pDirectSoundCapture, WORD* pChannels, WORD* pBitsPerSample, DWORD* pSampleRate) -{ - mal_assert(pContext != NULL); - mal_assert(pDirectSoundCapture != NULL); - - if (pChannels) { - *pChannels = 0; - } - if (pBitsPerSample) { - *pBitsPerSample = 0; - } - if (pSampleRate) { - *pSampleRate = 0; - } - - MAL_DSCCAPS caps; - mal_zero_object(&caps); - caps.dwSize = sizeof(caps); - if (FAILED(mal_IDirectSoundCapture_GetCaps(pDirectSoundCapture, &caps))) { - return mal_context_post_error(pContext, NULL, MAL_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundCapture_GetCaps() failed for capture device.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - - if (pChannels) { - *pChannels = (WORD)caps.dwChannels; - } - - // The device can support multiple formats. We just go through the different formats in order of priority and - // pick the first one. This the same type of system as the WinMM backend. - WORD bitsPerSample = 16; - DWORD sampleRate = 48000; - - if (caps.dwChannels == 1) { - if ((caps.dwFormats & WAVE_FORMAT_48M16) != 0) { - sampleRate = 48000; - } else if ((caps.dwFormats & WAVE_FORMAT_44M16) != 0) { - sampleRate = 44100; - } else if ((caps.dwFormats & WAVE_FORMAT_2M16) != 0) { - sampleRate = 22050; - } else if ((caps.dwFormats & WAVE_FORMAT_1M16) != 0) { - sampleRate = 11025; - } else if ((caps.dwFormats & WAVE_FORMAT_96M16) != 0) { - sampleRate = 96000; - } else { - bitsPerSample = 8; - if ((caps.dwFormats & WAVE_FORMAT_48M08) != 0) { - sampleRate = 48000; - } else if ((caps.dwFormats & WAVE_FORMAT_44M08) != 0) { - sampleRate = 44100; - } else if ((caps.dwFormats & WAVE_FORMAT_2M08) != 0) { - sampleRate = 22050; - } else if ((caps.dwFormats & WAVE_FORMAT_1M08) != 0) { - sampleRate = 11025; - } else if ((caps.dwFormats & WAVE_FORMAT_96M08) != 0) { - sampleRate = 96000; - } else { - bitsPerSample = 16; // Didn't find it. Just fall back to 16-bit. - } - } - } else if (caps.dwChannels == 2) { - if ((caps.dwFormats & WAVE_FORMAT_48S16) != 0) { - sampleRate = 48000; - } else if ((caps.dwFormats & WAVE_FORMAT_44S16) != 0) { - sampleRate = 44100; - } else if ((caps.dwFormats & WAVE_FORMAT_2S16) != 0) { - sampleRate = 22050; - } else if ((caps.dwFormats & WAVE_FORMAT_1S16) != 0) { - sampleRate = 11025; - } else if ((caps.dwFormats & WAVE_FORMAT_96S16) != 0) { - sampleRate = 96000; - } else { - bitsPerSample = 8; - if ((caps.dwFormats & WAVE_FORMAT_48S08) != 0) { - sampleRate = 48000; - } else if ((caps.dwFormats & WAVE_FORMAT_44S08) != 0) { - sampleRate = 44100; - } else if ((caps.dwFormats & WAVE_FORMAT_2S08) != 0) { - sampleRate = 22050; - } else if ((caps.dwFormats & WAVE_FORMAT_1S08) != 0) { - sampleRate = 11025; - } else if ((caps.dwFormats & WAVE_FORMAT_96S08) != 0) { - sampleRate = 96000; - } else { - bitsPerSample = 16; // Didn't find it. Just fall back to 16-bit. - } - } - } - - if (pBitsPerSample) { - *pBitsPerSample = bitsPerSample; - } - if (pSampleRate) { - *pSampleRate = sampleRate; - } - - return MAL_SUCCESS; -} - -mal_bool32 mal_context_is_device_id_equal__dsound(mal_context* pContext, const mal_device_id* pID0, const mal_device_id* pID1) -{ - mal_assert(pContext != NULL); - mal_assert(pID0 != NULL); - mal_assert(pID1 != NULL); - (void)pContext; - - return memcmp(pID0->dsound, pID1->dsound, sizeof(pID0->dsound)) == 0; -} - - -typedef struct -{ - mal_context* pContext; - mal_device_type deviceType; - mal_enum_devices_callback_proc callback; - void* pUserData; - mal_bool32 terminated; -} mal_context_enumerate_devices_callback_data__dsound; - -BOOL CALLBACK mal_context_enumerate_devices_callback__dsound(LPGUID lpGuid, LPCSTR lpcstrDescription, LPCSTR lpcstrModule, LPVOID lpContext) -{ - (void)lpcstrModule; - - mal_context_enumerate_devices_callback_data__dsound* pData = (mal_context_enumerate_devices_callback_data__dsound*)lpContext; - mal_assert(pData != NULL); - - mal_device_info deviceInfo; - mal_zero_object(&deviceInfo); - - // ID. - if (lpGuid != NULL) { - mal_copy_memory(deviceInfo.id.dsound, lpGuid, 16); - } else { - mal_zero_memory(deviceInfo.id.dsound, 16); - } - - // Name / Description - mal_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), lpcstrDescription, (size_t)-1); - - - // Call the callback function, but make sure we stop enumerating if the callee requested so. - pData->terminated = !pData->callback(pData->pContext, pData->deviceType, &deviceInfo, pData->pUserData); - if (pData->terminated) { - return FALSE; // Stop enumeration. - } else { - return TRUE; // Continue enumeration. - } -} - -mal_result mal_context_enumerate_devices__dsound(mal_context* pContext, mal_enum_devices_callback_proc callback, void* pUserData) -{ - mal_assert(pContext != NULL); - mal_assert(callback != NULL); - - mal_context_enumerate_devices_callback_data__dsound data; - data.pContext = pContext; - data.callback = callback; - data.pUserData = pUserData; - data.terminated = MAL_FALSE; - - // Playback. - if (!data.terminated) { - data.deviceType = mal_device_type_playback; - ((mal_DirectSoundEnumerateAProc)pContext->dsound.DirectSoundEnumerateA)(mal_context_enumerate_devices_callback__dsound, &data); - } - - // Capture. - if (!data.terminated) { - data.deviceType = mal_device_type_capture; - ((mal_DirectSoundCaptureEnumerateAProc)pContext->dsound.DirectSoundCaptureEnumerateA)(mal_context_enumerate_devices_callback__dsound, &data); - } - - return MAL_SUCCESS; -} - - -typedef struct -{ - const mal_device_id* pDeviceID; - mal_device_info* pDeviceInfo; - mal_bool32 found; -} mal_context_get_device_info_callback_data__dsound; - -BOOL CALLBACK mal_context_get_device_info_callback__dsound(LPGUID lpGuid, LPCSTR lpcstrDescription, LPCSTR lpcstrModule, LPVOID lpContext) -{ - (void)lpcstrModule; - - mal_context_get_device_info_callback_data__dsound* pData = (mal_context_get_device_info_callback_data__dsound*)lpContext; - mal_assert(pData != NULL); - - if ((pData->pDeviceID == NULL || mal_is_guid_equal(pData->pDeviceID->dsound, &MAL_GUID_NULL)) && (lpGuid == NULL || mal_is_guid_equal(lpGuid, &MAL_GUID_NULL))) { - // Default device. - mal_strncpy_s(pData->pDeviceInfo->name, sizeof(pData->pDeviceInfo->name), lpcstrDescription, (size_t)-1); - pData->found = MAL_TRUE; - return FALSE; // Stop enumeration. - } else { - // Not the default device. - if (lpGuid != NULL) { - if (memcmp(pData->pDeviceID->dsound, lpGuid, sizeof(pData->pDeviceID->dsound)) == 0) { - mal_strncpy_s(pData->pDeviceInfo->name, sizeof(pData->pDeviceInfo->name), lpcstrDescription, (size_t)-1); - pData->found = MAL_TRUE; - return FALSE; // Stop enumeration. - } - } - } - - return TRUE; -} - -mal_result mal_context_get_device_info__dsound(mal_context* pContext, mal_device_type deviceType, const mal_device_id* pDeviceID, mal_share_mode shareMode, mal_device_info* pDeviceInfo) -{ - (void)shareMode; - - if (pDeviceID != NULL) { - // ID. - mal_copy_memory(pDeviceInfo->id.dsound, pDeviceID->dsound, 16); - - // Name / Description. This is retrieved by enumerating over each device until we find that one that matches the input ID. - mal_context_get_device_info_callback_data__dsound data; - data.pDeviceID = pDeviceID; - data.pDeviceInfo = pDeviceInfo; - data.found = MAL_FALSE; - if (deviceType == mal_device_type_playback) { - ((mal_DirectSoundEnumerateAProc)pContext->dsound.DirectSoundEnumerateA)(mal_context_get_device_info_callback__dsound, &data); - } else { - ((mal_DirectSoundCaptureEnumerateAProc)pContext->dsound.DirectSoundCaptureEnumerateA)(mal_context_get_device_info_callback__dsound, &data); - } - - if (!data.found) { - return MAL_NO_DEVICE; - } - } else { - // I don't think there's a way to get the name of the default device with DirectSound. In this case we just need to use defaults. - - // ID - mal_zero_memory(pDeviceInfo->id.dsound, 16); - - // Name / Description/ - if (deviceType == mal_device_type_playback) { - mal_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MAL_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); - } else { - mal_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MAL_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); - } - } - - // Retrieving detailed information is slightly different depending on the device type. - if (deviceType == mal_device_type_playback) { - // Playback. - mal_IDirectSound* pDirectSound; - mal_result result = mal_context_create_IDirectSound__dsound(pContext, shareMode, pDeviceID, &pDirectSound); - if (result != MAL_SUCCESS) { - return result; - } - - MAL_DSCAPS caps; - mal_zero_object(&caps); - caps.dwSize = sizeof(caps); - if (FAILED(mal_IDirectSound_GetCaps(pDirectSound, &caps))) { - return mal_context_post_error(pContext, NULL, MAL_LOG_LEVEL_ERROR, "[DirectSound] IDirectSound_GetCaps() failed for playback device.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - - if ((caps.dwFlags & MAL_DSCAPS_PRIMARYSTEREO) != 0) { - // It supports at least stereo, but could support more. - WORD channels = 2; - - // Look at the speaker configuration to get a better idea on the channel count. - DWORD speakerConfig; - if (SUCCEEDED(mal_IDirectSound_GetSpeakerConfig(pDirectSound, &speakerConfig))) { - mal_get_channels_from_speaker_config__dsound(speakerConfig, &channels, NULL); - } - - pDeviceInfo->minChannels = channels; - pDeviceInfo->maxChannels = channels; - } else { - // It does not support stereo, which means we are stuck with mono. - pDeviceInfo->minChannels = 1; - pDeviceInfo->maxChannels = 1; - } - - // Sample rate. - if ((caps.dwFlags & MAL_DSCAPS_CONTINUOUSRATE) != 0) { - pDeviceInfo->minSampleRate = caps.dwMinSecondarySampleRate; - pDeviceInfo->maxSampleRate = caps.dwMaxSecondarySampleRate; - - // On my machine the min and max sample rates can return 100 and 200000 respectively. I'd rather these be within - // the range of our standard sample rates so I'm clamping. - if (caps.dwMinSecondarySampleRate < MAL_MIN_SAMPLE_RATE && caps.dwMaxSecondarySampleRate >= MAL_MIN_SAMPLE_RATE) { - pDeviceInfo->minSampleRate = MAL_MIN_SAMPLE_RATE; - } - if (caps.dwMaxSecondarySampleRate > MAL_MAX_SAMPLE_RATE && caps.dwMinSecondarySampleRate <= MAL_MAX_SAMPLE_RATE) { - pDeviceInfo->maxSampleRate = MAL_MAX_SAMPLE_RATE; - } - } else { - // Only supports a single sample rate. Set both min an max to the same thing. Do not clamp within the standard rates. - pDeviceInfo->minSampleRate = caps.dwMaxSecondarySampleRate; - pDeviceInfo->maxSampleRate = caps.dwMaxSecondarySampleRate; - } - - // DirectSound can support all formats. - pDeviceInfo->formatCount = mal_format_count - 1; // Minus one because we don't want to include mal_format_unknown. - for (mal_uint32 iFormat = 0; iFormat < pDeviceInfo->formatCount; ++iFormat) { - pDeviceInfo->formats[iFormat] = (mal_format)(iFormat + 1); // +1 to skip over mal_format_unknown. - } - - mal_IDirectSound_Release(pDirectSound); - } else { - // Capture. This is a little different to playback due to the say the supported formats are reported. Technically capture - // devices can support a number of different formats, but for simplicity and consistency with mal_device_init() I'm just - // reporting the best format. - mal_IDirectSoundCapture* pDirectSoundCapture; - mal_result result = mal_context_create_IDirectSoundCapture__dsound(pContext, shareMode, pDeviceID, &pDirectSoundCapture); - if (result != MAL_SUCCESS) { - return result; - } - - WORD channels; - WORD bitsPerSample; - DWORD sampleRate; - result = mal_context_get_format_info_for_IDirectSoundCapture__dsound(pContext, pDirectSoundCapture, &channels, &bitsPerSample, &sampleRate); - if (result != MAL_SUCCESS) { - mal_IDirectSoundCapture_Release(pDirectSoundCapture); - return result; - } - - pDeviceInfo->minChannels = channels; - pDeviceInfo->maxChannels = channels; - pDeviceInfo->minSampleRate = sampleRate; - pDeviceInfo->maxSampleRate = sampleRate; - pDeviceInfo->formatCount = 1; - if (bitsPerSample == 8) { - pDeviceInfo->formats[0] = mal_format_u8; - } else if (bitsPerSample == 16) { - pDeviceInfo->formats[0] = mal_format_s16; - } else if (bitsPerSample == 24) { - pDeviceInfo->formats[0] = mal_format_s24; - } else if (bitsPerSample == 32) { - pDeviceInfo->formats[0] = mal_format_s32; - } else { - mal_IDirectSoundCapture_Release(pDirectSoundCapture); - return MAL_FORMAT_NOT_SUPPORTED; - } - - mal_IDirectSoundCapture_Release(pDirectSoundCapture); - } - - return MAL_SUCCESS; -} - - -typedef struct -{ - mal_uint32 deviceCount; - mal_uint32 infoCount; - mal_device_info* pInfo; -} mal_device_enum_data__dsound; - -BOOL CALLBACK mal_enum_devices_callback__dsound(LPGUID lpGuid, LPCSTR lpcstrDescription, LPCSTR lpcstrModule, LPVOID lpContext) -{ - (void)lpcstrModule; - - mal_device_enum_data__dsound* pData = (mal_device_enum_data__dsound*)lpContext; - mal_assert(pData != NULL); - - if (pData->pInfo != NULL) { - if (pData->infoCount > 0) { - mal_zero_object(pData->pInfo); - mal_strncpy_s(pData->pInfo->name, sizeof(pData->pInfo->name), lpcstrDescription, (size_t)-1); - - if (lpGuid != NULL) { - mal_copy_memory(pData->pInfo->id.dsound, lpGuid, 16); - } else { - mal_zero_memory(pData->pInfo->id.dsound, 16); - } - - pData->pInfo += 1; - pData->infoCount -= 1; - pData->deviceCount += 1; - } - } else { - pData->deviceCount += 1; - } - - return TRUE; -} - -void mal_device_uninit__dsound(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - if (pDevice->dsound.pNotify != NULL) { - mal_IDirectSoundNotify_Release((mal_IDirectSoundNotify*)pDevice->dsound.pNotify); - } - - if (pDevice->dsound.hStopEvent) { - CloseHandle(pDevice->dsound.hStopEvent); - } - for (mal_uint32 i = 0; i < pDevice->periods; ++i) { - if (pDevice->dsound.pNotifyEvents[i]) { - CloseHandle(pDevice->dsound.pNotifyEvents[i]); - } - } - - if (pDevice->dsound.pCaptureBuffer != NULL) { - mal_IDirectSoundCaptureBuffer_Release((mal_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer); - } - if (pDevice->dsound.pCapture != NULL) { - mal_IDirectSoundCapture_Release((mal_IDirectSoundCapture*)pDevice->dsound.pCapture); - } - - if (pDevice->dsound.pPlaybackBuffer != NULL) { - mal_IDirectSoundBuffer_Release((mal_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer); - } - if (pDevice->dsound.pPlaybackPrimaryBuffer != NULL) { - mal_IDirectSoundBuffer_Release((mal_IDirectSoundBuffer*)pDevice->dsound.pPlaybackPrimaryBuffer); - } - if (pDevice->dsound.pPlayback != NULL) { - mal_IDirectSound_Release((mal_IDirectSound*)pDevice->dsound.pPlayback); - } -} - -mal_result mal_device_init__dsound(mal_context* pContext, mal_device_type type, const mal_device_id* pDeviceID, const mal_device_config* pConfig, mal_device* pDevice) -{ - (void)pContext; - - mal_assert(pDevice != NULL); - mal_zero_object(&pDevice->dsound); - - // Check that we have a valid format. - GUID subformat; - switch (pConfig->format) - { - case mal_format_u8: - case mal_format_s16: - case mal_format_s24: - //case mal_format_s24_32: - case mal_format_s32: - { - subformat = MAL_GUID_KSDATAFORMAT_SUBTYPE_PCM; - } break; - - case mal_format_f32: - { - subformat = MAL_GUID_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT; - } break; - - default: - return MAL_FORMAT_NOT_SUPPORTED; - } - - WAVEFORMATEXTENSIBLE wf; - mal_zero_object(&wf); - wf.Format.cbSize = sizeof(wf); - wf.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE; - wf.Format.nChannels = (WORD)pConfig->channels; - wf.Format.nSamplesPerSec = (DWORD)pConfig->sampleRate; - wf.Format.wBitsPerSample = (WORD)mal_get_bytes_per_sample(pConfig->format)*8; - wf.Format.nBlockAlign = (wf.Format.nChannels * wf.Format.wBitsPerSample) / 8; - wf.Format.nAvgBytesPerSec = wf.Format.nBlockAlign * wf.Format.nSamplesPerSec; - wf.Samples.wValidBitsPerSample = wf.Format.wBitsPerSample; - wf.dwChannelMask = mal_channel_map_to_channel_mask__win32(pConfig->channelMap, pConfig->channels); - wf.SubFormat = subformat; - - DWORD bufferSizeInBytes = 0; - - // Unfortunately DirectSound uses different APIs and data structures for playback and catpure devices :( - if (type == mal_device_type_playback) { - mal_result result = mal_context_create_IDirectSound__dsound(pContext, pConfig->shareMode, pDeviceID, (mal_IDirectSound**)&pDevice->dsound.pPlayback); - if (result != MAL_SUCCESS) { - mal_device_uninit__dsound(pDevice); - return result; - } - - MAL_DSBUFFERDESC descDSPrimary; - mal_zero_object(&descDSPrimary); - descDSPrimary.dwSize = sizeof(MAL_DSBUFFERDESC); - descDSPrimary.dwFlags = MAL_DSBCAPS_PRIMARYBUFFER | MAL_DSBCAPS_CTRLVOLUME; - if (FAILED(mal_IDirectSound_CreateSoundBuffer((mal_IDirectSound*)pDevice->dsound.pPlayback, &descDSPrimary, (mal_IDirectSoundBuffer**)&pDevice->dsound.pPlaybackPrimaryBuffer, NULL))) { - mal_device_uninit__dsound(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[DirectSound] IDirectSound_CreateSoundBuffer() failed for playback device's primary buffer.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - - - // We may want to make some adjustments to the format if we are using defaults. - MAL_DSCAPS caps; - mal_zero_object(&caps); - caps.dwSize = sizeof(caps); - if (FAILED(mal_IDirectSound_GetCaps((mal_IDirectSound*)pDevice->dsound.pPlayback, &caps))) { - mal_device_uninit__dsound(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[DirectSound] IDirectSound_GetCaps() failed for playback device.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - - if (pDevice->usingDefaultChannels) { - if ((caps.dwFlags & MAL_DSCAPS_PRIMARYSTEREO) != 0) { - // It supports at least stereo, but could support more. - wf.Format.nChannels = 2; - - // Look at the speaker configuration to get a better idea on the channel count. - DWORD speakerConfig; - if (SUCCEEDED(mal_IDirectSound_GetSpeakerConfig((mal_IDirectSound*)pDevice->dsound.pPlayback, &speakerConfig))) { - mal_get_channels_from_speaker_config__dsound(speakerConfig, &wf.Format.nChannels, &wf.dwChannelMask); - } - } else { - // It does not support stereo, which means we are stuck with mono. - wf.Format.nChannels = 1; - } - } - - if (pDevice->usingDefaultSampleRate) { - // We base the sample rate on the values returned by GetCaps(). - if ((caps.dwFlags & MAL_DSCAPS_CONTINUOUSRATE) != 0) { - wf.Format.nSamplesPerSec = mal_get_best_sample_rate_within_range(caps.dwMinSecondarySampleRate, caps.dwMaxSecondarySampleRate); - } else { - wf.Format.nSamplesPerSec = caps.dwMaxSecondarySampleRate; - } - } - - wf.Format.nBlockAlign = (wf.Format.nChannels * wf.Format.wBitsPerSample) / 8; - wf.Format.nAvgBytesPerSec = wf.Format.nBlockAlign * wf.Format.nSamplesPerSec; - - // From MSDN: - // - // The method succeeds even if the hardware does not support the requested format; DirectSound sets the buffer to the closest - // supported format. To determine whether this has happened, an application can call the GetFormat method for the primary buffer - // and compare the result with the format that was requested with the SetFormat method. - if (FAILED(mal_IDirectSoundBuffer_SetFormat((mal_IDirectSoundBuffer*)pDevice->dsound.pPlaybackPrimaryBuffer, (WAVEFORMATEX*)&wf))) { - mal_device_uninit__dsound(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[DirectSound] Failed to set format of playback device's primary buffer.", MAL_FORMAT_NOT_SUPPORTED); - } - - // Get the _actual_ properties of the buffer. - char rawdata[1024]; - WAVEFORMATEXTENSIBLE* pActualFormat = (WAVEFORMATEXTENSIBLE*)rawdata; - if (FAILED(mal_IDirectSoundBuffer_GetFormat((mal_IDirectSoundBuffer*)pDevice->dsound.pPlaybackPrimaryBuffer, (WAVEFORMATEX*)pActualFormat, sizeof(rawdata), NULL))) { - mal_device_uninit__dsound(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[DirectSound] Failed to retrieve the actual format of the playback device's primary buffer.", MAL_FORMAT_NOT_SUPPORTED); - } - - pDevice->internalFormat = mal_format_from_WAVEFORMATEX((WAVEFORMATEX*)pActualFormat); - pDevice->internalChannels = pActualFormat->Format.nChannels; - pDevice->internalSampleRate = pActualFormat->Format.nSamplesPerSec; - - // Get the internal channel map based on the channel mask. - if (pActualFormat->Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) { - mal_channel_mask_to_channel_map__win32(pActualFormat->dwChannelMask, pDevice->internalChannels, pDevice->internalChannelMap); - } else { - mal_channel_mask_to_channel_map__win32(wf.dwChannelMask, pDevice->internalChannels, pDevice->internalChannelMap); - } - - // We need to wait until we know the sample rate before we can calculate the buffer size. - if (pDevice->bufferSizeInFrames == 0) { - pDevice->bufferSizeInFrames = mal_calculate_buffer_size_in_frames_from_milliseconds(pDevice->bufferSizeInMilliseconds, pDevice->internalSampleRate); - } - - bufferSizeInBytes = pDevice->bufferSizeInFrames * pDevice->internalChannels * mal_get_bytes_per_sample(pDevice->internalFormat); - - - - // Meaning of dwFlags (from MSDN): - // - // DSBCAPS_CTRLPOSITIONNOTIFY - // The buffer has position notification capability. - // - // DSBCAPS_GLOBALFOCUS - // With this flag set, an application using DirectSound can continue to play its buffers if the user switches focus to - // another application, even if the new application uses DirectSound. - // - // DSBCAPS_GETCURRENTPOSITION2 - // In the first version of DirectSound, the play cursor was significantly ahead of the actual playing sound on emulated - // sound cards; it was directly behind the write cursor. Now, if the DSBCAPS_GETCURRENTPOSITION2 flag is specified, the - // application can get a more accurate play cursor. - MAL_DSBUFFERDESC descDS; - mal_zero_object(&descDS); - descDS.dwSize = sizeof(descDS); - descDS.dwFlags = MAL_DSBCAPS_CTRLPOSITIONNOTIFY | MAL_DSBCAPS_GLOBALFOCUS | MAL_DSBCAPS_GETCURRENTPOSITION2; - descDS.dwBufferBytes = bufferSizeInBytes; - descDS.lpwfxFormat = (WAVEFORMATEX*)&wf; - if (FAILED(mal_IDirectSound_CreateSoundBuffer((mal_IDirectSound*)pDevice->dsound.pPlayback, &descDS, (mal_IDirectSoundBuffer**)&pDevice->dsound.pPlaybackBuffer, NULL))) { - mal_device_uninit__dsound(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[DirectSound] IDirectSound_CreateSoundBuffer() failed for playback device's secondary buffer.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - - // Notifications are set up via a DIRECTSOUNDNOTIFY object which is retrieved from the buffer. - if (FAILED(mal_IDirectSoundBuffer_QueryInterface((mal_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, &MAL_GUID_IID_DirectSoundNotify, (void**)&pDevice->dsound.pNotify))) { - mal_device_uninit__dsound(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundBuffer_QueryInterface() failed for playback device's IDirectSoundNotify object.", MAL_API_NOT_FOUND); - } - } else { - // The default buffer size is treated slightly differently for DirectSound which, for some reason, seems to - // have worse latency with capture than playback (sometimes _much_ worse). - if (pDevice->usingDefaultBufferSize) { - pDevice->bufferSizeInFrames *= 2; // <-- Might need to fiddle with this to find a more ideal value. May even be able to just add a fixed amount rather than scaling. - } - - mal_result result = mal_context_create_IDirectSoundCapture__dsound(pContext, pConfig->shareMode, pDeviceID, (mal_IDirectSoundCapture**)&pDevice->dsound.pCapture); - if (result != MAL_SUCCESS) { - mal_device_uninit__dsound(pDevice); - return result; - } - - result = mal_context_get_format_info_for_IDirectSoundCapture__dsound(pContext, (mal_IDirectSoundCapture*)pDevice->dsound.pCapture, &wf.Format.nChannels, &wf.Format.wBitsPerSample, &wf.Format.nSamplesPerSec); - if (result != MAL_SUCCESS) { - mal_device_uninit__dsound(pDevice); - return result; - } - - wf.Format.nBlockAlign = (wf.Format.nChannels * wf.Format.wBitsPerSample) / 8; - wf.Format.nAvgBytesPerSec = wf.Format.nBlockAlign * wf.Format.nSamplesPerSec; - wf.Samples.wValidBitsPerSample = wf.Format.wBitsPerSample; - wf.SubFormat = MAL_GUID_KSDATAFORMAT_SUBTYPE_PCM; - - if (pDevice->bufferSizeInFrames == 0) { - pDevice->bufferSizeInFrames = mal_calculate_buffer_size_in_frames_from_milliseconds(pDevice->bufferSizeInMilliseconds, wf.Format.nSamplesPerSec); - } - - bufferSizeInBytes = pDevice->bufferSizeInFrames * wf.Format.nChannels * mal_get_bytes_per_sample(pDevice->format); - - MAL_DSCBUFFERDESC descDS; - mal_zero_object(&descDS); - descDS.dwSize = sizeof(descDS); - descDS.dwFlags = 0; - descDS.dwBufferBytes = bufferSizeInBytes; - descDS.lpwfxFormat = (WAVEFORMATEX*)&wf; - if (FAILED(mal_IDirectSoundCapture_CreateCaptureBuffer((mal_IDirectSoundCapture*)pDevice->dsound.pCapture, &descDS, (mal_IDirectSoundCaptureBuffer**)&pDevice->dsound.pCaptureBuffer, NULL))) { - mal_device_uninit__dsound(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundCapture_CreateCaptureBuffer() failed for capture device.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - - // Get the _actual_ properties of the buffer. - char rawdata[1024]; - WAVEFORMATEXTENSIBLE* pActualFormat = (WAVEFORMATEXTENSIBLE*)rawdata; - if (FAILED(mal_IDirectSoundCaptureBuffer_GetFormat((mal_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, (WAVEFORMATEX*)pActualFormat, sizeof(rawdata), NULL))) { - mal_device_uninit__dsound(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[DirectSound] Failed to retrieve the actual format of the capture device's buffer.", MAL_FORMAT_NOT_SUPPORTED); - } - - pDevice->internalFormat = mal_format_from_WAVEFORMATEX((WAVEFORMATEX*)pActualFormat); - pDevice->internalChannels = pActualFormat->Format.nChannels; - pDevice->internalSampleRate = pActualFormat->Format.nSamplesPerSec; - - // Get the internal channel map based on the channel mask. - if (pActualFormat->Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) { - mal_channel_mask_to_channel_map__win32(pActualFormat->dwChannelMask, pDevice->internalChannels, pDevice->internalChannelMap); - } else { - mal_channel_mask_to_channel_map__win32(wf.dwChannelMask, pDevice->internalChannels, pDevice->internalChannelMap); - } - - - // Notifications are set up via a DIRECTSOUNDNOTIFY object which is retrieved from the buffer. - if (FAILED(mal_IDirectSoundCaptureBuffer_QueryInterface((mal_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, &MAL_GUID_IID_DirectSoundNotify, (void**)&pDevice->dsound.pNotify))) { - mal_device_uninit__dsound(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundCaptureBuffer_QueryInterface() failed for capture device's IDirectSoundNotify object.", MAL_API_NOT_FOUND); - } - } - - // We need a notification for each period. The notification offset is slightly different depending on whether or not the - // device is a playback or capture device. For a playback device we want to be notified when a period just starts playing, - // whereas for a capture device we want to be notified when a period has just _finished_ capturing. - mal_uint32 periodSizeInBytes = pDevice->bufferSizeInFrames / pDevice->periods; - MAL_DSBPOSITIONNOTIFY notifyPoints[MAL_MAX_PERIODS_DSOUND]; // One notification event for each period. - for (mal_uint32 i = 0; i < pDevice->periods; ++i) { - pDevice->dsound.pNotifyEvents[i] = CreateEventA(NULL, FALSE, FALSE, NULL); - if (pDevice->dsound.pNotifyEvents[i] == NULL) { - mal_device_uninit__dsound(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[DirectSound] Failed to create event for buffer notifications.", MAL_FAILED_TO_CREATE_EVENT); - } - - // The notification offset is in bytes. - notifyPoints[i].dwOffset = i * periodSizeInBytes; - notifyPoints[i].hEventNotify = pDevice->dsound.pNotifyEvents[i]; - } - - if (FAILED(mal_IDirectSoundNotify_SetNotificationPositions((mal_IDirectSoundNotify*)pDevice->dsound.pNotify, pDevice->periods, notifyPoints))) { - mal_device_uninit__dsound(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundNotify_SetNotificationPositions() failed.", MAL_FAILED_TO_CREATE_EVENT); - } - - // When the device is playing the worker thread will be waiting on a bunch of notification events. To return from - // this wait state we need to signal a special event. - pDevice->dsound.hStopEvent = CreateEventA(NULL, FALSE, FALSE, NULL); - if (pDevice->dsound.hStopEvent == NULL) { - mal_device_uninit__dsound(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[DirectSound] Failed to create event for main loop break notification.", MAL_FAILED_TO_CREATE_EVENT); - } - - return MAL_SUCCESS; -} - - -mal_result mal_device_start__dsound(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - if (pDevice->type == mal_device_type_playback) { - // Before playing anything we need to grab an initial group of samples from the client. - mal_uint32 framesToRead = pDevice->bufferSizeInFrames / pDevice->periods; - mal_uint32 desiredLockSize = framesToRead * pDevice->channels * mal_get_bytes_per_sample(pDevice->format); - - void* pLockPtr; - DWORD actualLockSize; - void* pLockPtr2; - DWORD actualLockSize2; - if (SUCCEEDED(mal_IDirectSoundBuffer_Lock((mal_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, 0, desiredLockSize, &pLockPtr, &actualLockSize, &pLockPtr2, &actualLockSize2, 0))) { - framesToRead = actualLockSize / mal_get_bytes_per_sample(pDevice->format) / pDevice->channels; - mal_device__read_frames_from_client(pDevice, framesToRead, pLockPtr); - mal_IDirectSoundBuffer_Unlock((mal_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, pLockPtr, actualLockSize, pLockPtr2, actualLockSize2); - - pDevice->dsound.lastProcessedFrame = framesToRead; - if (FAILED(mal_IDirectSoundBuffer_Play((mal_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, 0, 0, MAL_DSBPLAY_LOOPING))) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundBuffer_Play() failed.", MAL_FAILED_TO_START_BACKEND_DEVICE); - } - } else { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundBuffer_Lock() failed.", MAL_FAILED_TO_MAP_DEVICE_BUFFER); - } - } else { - if (FAILED(mal_IDirectSoundCaptureBuffer_Start((mal_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, MAL_DSCBSTART_LOOPING))) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundCaptureBuffer_Start() failed.", MAL_FAILED_TO_START_BACKEND_DEVICE); - } - } - - return MAL_SUCCESS; -} - -mal_result mal_device_stop__dsound(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - if (pDevice->type == mal_device_type_playback) { - if (FAILED(mal_IDirectSoundBuffer_Stop((mal_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer))) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundBuffer_Stop() failed.", MAL_FAILED_TO_STOP_BACKEND_DEVICE); - } - - mal_IDirectSoundBuffer_SetCurrentPosition((mal_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, 0); - } else { - if (FAILED(mal_IDirectSoundCaptureBuffer_Stop((mal_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer))) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundCaptureBuffer_Stop() failed.", MAL_FAILED_TO_STOP_BACKEND_DEVICE); - } - } - - return MAL_SUCCESS; -} - -mal_result mal_device_break_main_loop__dsound(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - // The main loop will be waiting on a bunch of events via the WaitForMultipleObjects() API. One of those events - // is a special event we use for forcing that function to return. - pDevice->dsound.breakFromMainLoop = MAL_TRUE; - SetEvent(pDevice->dsound.hStopEvent); - return MAL_SUCCESS; -} - -mal_bool32 mal_device__get_current_frame__dsound(mal_device* pDevice, mal_uint32* pCurrentPos) -{ - mal_assert(pDevice != NULL); - mal_assert(pCurrentPos != NULL); - *pCurrentPos = 0; - - DWORD dwCurrentPosition; - if (pDevice->type == mal_device_type_playback) { - if (FAILED(mal_IDirectSoundBuffer_GetCurrentPosition((mal_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, NULL, &dwCurrentPosition))) { - return MAL_FALSE; - } - } else { - if (FAILED(mal_IDirectSoundCaptureBuffer_GetCurrentPosition((mal_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, &dwCurrentPosition, NULL))) { - return MAL_FALSE; - } - } - - *pCurrentPos = (mal_uint32)dwCurrentPosition / mal_get_bytes_per_sample(pDevice->format) / pDevice->channels; - return MAL_TRUE; -} - -mal_uint32 mal_device__get_available_frames__dsound(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - mal_uint32 currentFrame; - if (!mal_device__get_current_frame__dsound(pDevice, ¤tFrame)) { - return 0; - } - - // In a playback device the last processed frame should always be ahead of the current frame. The space between - // the last processed and current frame (moving forward, starting from the last processed frame) is the amount - // of space available to write. - // - // For a recording device it's the other way around - the last processed frame is always _behind_ the current - // frame and the space between is the available space. - mal_uint32 totalFrameCount = pDevice->bufferSizeInFrames; - if (pDevice->type == mal_device_type_playback) { - mal_uint32 committedBeg = currentFrame; - mal_uint32 committedEnd; - committedEnd = pDevice->dsound.lastProcessedFrame; - if (committedEnd <= committedBeg) { - committedEnd += totalFrameCount; - } - - mal_uint32 committedSize = (committedEnd - committedBeg); - mal_assert(committedSize <= totalFrameCount); - - return totalFrameCount - committedSize; - } else { - mal_uint32 validBeg = pDevice->dsound.lastProcessedFrame; - mal_uint32 validEnd = currentFrame; - if (validEnd < validBeg) { - validEnd += totalFrameCount; // Wrap around. - } - - mal_uint32 validSize = (validEnd - validBeg); - mal_assert(validSize <= totalFrameCount); - - return validSize; - } -} - -mal_uint32 mal_device__wait_for_frames__dsound(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - // The timeout to use for putting the thread to sleep is based on the size of the buffer and the period count. - DWORD timeoutInMilliseconds = (pDevice->bufferSizeInFrames / (pDevice->sampleRate/1000)) / pDevice->periods; - if (timeoutInMilliseconds < 1) { - timeoutInMilliseconds = 1; - } - - unsigned int eventCount = pDevice->periods + 1; - HANDLE pEvents[MAL_MAX_PERIODS_DSOUND + 1]; // +1 for the stop event. - mal_copy_memory(pEvents, pDevice->dsound.pNotifyEvents, sizeof(HANDLE) * pDevice->periods); - pEvents[eventCount-1] = pDevice->dsound.hStopEvent; - - while (!pDevice->dsound.breakFromMainLoop) { - mal_uint32 framesAvailable = mal_device__get_available_frames__dsound(pDevice); - if (framesAvailable > 0) { - return framesAvailable; - } - - // If we get here it means we weren't able to find any frames. We'll just wait here for a bit. - WaitForMultipleObjects(eventCount, pEvents, FALSE, timeoutInMilliseconds); - } - - // We'll get here if the loop was terminated. Just return whatever's available. - return mal_device__get_available_frames__dsound(pDevice); -} - -mal_result mal_device_main_loop__dsound(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - // Make sure the stop event is not signaled to ensure we don't end up immediately returning from WaitForMultipleObjects(). - ResetEvent(pDevice->dsound.hStopEvent); - - pDevice->dsound.breakFromMainLoop = MAL_FALSE; - while (!pDevice->dsound.breakFromMainLoop) { - mal_uint32 framesAvailable = mal_device__wait_for_frames__dsound(pDevice); - if (framesAvailable == 0) { - continue; - } - - // If it's a playback device, don't bother grabbing more data if the device is being stopped. - if (pDevice->dsound.breakFromMainLoop && pDevice->type == mal_device_type_playback) { - return MAL_FALSE; - } - - DWORD lockOffset = pDevice->dsound.lastProcessedFrame * pDevice->channels * mal_get_bytes_per_sample(pDevice->format); - DWORD lockSize = framesAvailable * pDevice->channels * mal_get_bytes_per_sample(pDevice->format); - - if (pDevice->type == mal_device_type_playback) { - void* pLockPtr; - DWORD actualLockSize; - void* pLockPtr2; - DWORD actualLockSize2; - if (FAILED(mal_IDirectSoundBuffer_Lock((mal_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, lockOffset, lockSize, &pLockPtr, &actualLockSize, &pLockPtr2, &actualLockSize2, 0))) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundBuffer_Lock() failed.", MAL_FAILED_TO_MAP_DEVICE_BUFFER); - } - - mal_uint32 frameCount = actualLockSize / mal_get_bytes_per_sample(pDevice->format) / pDevice->channels; - mal_device__read_frames_from_client(pDevice, frameCount, pLockPtr); - pDevice->dsound.lastProcessedFrame = (pDevice->dsound.lastProcessedFrame + frameCount) % pDevice->bufferSizeInFrames; - - mal_IDirectSoundBuffer_Unlock((mal_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, pLockPtr, actualLockSize, pLockPtr2, actualLockSize2); - } else { - void* pLockPtr; - DWORD actualLockSize; - void* pLockPtr2; - DWORD actualLockSize2; - if (FAILED(mal_IDirectSoundCaptureBuffer_Lock((mal_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, lockOffset, lockSize, &pLockPtr, &actualLockSize, &pLockPtr2, &actualLockSize2, 0))) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundCaptureBuffer_Lock() failed.", MAL_FAILED_TO_MAP_DEVICE_BUFFER); - } - - mal_uint32 frameCount = actualLockSize / mal_get_bytes_per_sample(pDevice->format) / pDevice->channels; - mal_device__send_frames_to_client(pDevice, frameCount, pLockPtr); - pDevice->dsound.lastProcessedFrame = (pDevice->dsound.lastProcessedFrame + frameCount) % pDevice->bufferSizeInFrames; - - mal_IDirectSoundCaptureBuffer_Unlock((mal_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, pLockPtr, actualLockSize, pLockPtr2, actualLockSize2); - } - } - - return MAL_SUCCESS; -} - - -mal_result mal_context_uninit__dsound(mal_context* pContext) -{ - mal_assert(pContext != NULL); - mal_assert(pContext->backend == mal_backend_dsound); - - mal_dlclose(pContext->dsound.hDSoundDLL); - - return MAL_SUCCESS; -} - -mal_result mal_context_init__dsound(mal_context* pContext) -{ - mal_assert(pContext != NULL); - - pContext->dsound.hDSoundDLL = mal_dlopen("dsound.dll"); - if (pContext->dsound.hDSoundDLL == NULL) { - return MAL_API_NOT_FOUND; - } - - pContext->dsound.DirectSoundCreate = mal_dlsym(pContext->dsound.hDSoundDLL, "DirectSoundCreate"); - pContext->dsound.DirectSoundEnumerateA = mal_dlsym(pContext->dsound.hDSoundDLL, "DirectSoundEnumerateA"); - pContext->dsound.DirectSoundCaptureCreate = mal_dlsym(pContext->dsound.hDSoundDLL, "DirectSoundCaptureCreate"); - pContext->dsound.DirectSoundCaptureEnumerateA = mal_dlsym(pContext->dsound.hDSoundDLL, "DirectSoundCaptureEnumerateA"); - - pContext->onUninit = mal_context_uninit__dsound; - pContext->onDeviceIDEqual = mal_context_is_device_id_equal__dsound; - pContext->onEnumDevices = mal_context_enumerate_devices__dsound; - pContext->onGetDeviceInfo = mal_context_get_device_info__dsound; - pContext->onDeviceInit = mal_device_init__dsound; - pContext->onDeviceUninit = mal_device_uninit__dsound; - pContext->onDeviceStart = mal_device_start__dsound; - pContext->onDeviceStop = mal_device_stop__dsound; - pContext->onDeviceBreakMainLoop = mal_device_break_main_loop__dsound; - pContext->onDeviceMainLoop = mal_device_main_loop__dsound; - - return MAL_SUCCESS; -} -#endif - - - -/////////////////////////////////////////////////////////////////////////////// -// -// WinMM Backend -// -/////////////////////////////////////////////////////////////////////////////// -#ifdef MAL_HAS_WINMM - -// Some older compilers don't have WAVEOUTCAPS2A and WAVEINCAPS2A, so we'll need to write this ourselves. These structures -// are exactly the same as the older ones but they have a few GUIDs for manufacturer/product/name identification. I'm keeping -// the names the same as the Win32 library for consistency, but namespaced to avoid naming conflicts with the Win32 version. -typedef struct -{ - WORD wMid; - WORD wPid; - MMVERSION vDriverVersion; - CHAR szPname[MAXPNAMELEN]; - DWORD dwFormats; - WORD wChannels; - WORD wReserved1; - DWORD dwSupport; - GUID ManufacturerGuid; - GUID ProductGuid; - GUID NameGuid; -} MAL_WAVEOUTCAPS2A; -typedef struct -{ - WORD wMid; - WORD wPid; - MMVERSION vDriverVersion; - CHAR szPname[MAXPNAMELEN]; - DWORD dwFormats; - WORD wChannels; - WORD wReserved1; - GUID ManufacturerGuid; - GUID ProductGuid; - GUID NameGuid; -} MAL_WAVEINCAPS2A; - -typedef UINT (WINAPI * MAL_PFN_waveOutGetNumDevs)(void); -typedef MMRESULT (WINAPI * MAL_PFN_waveOutGetDevCapsA)(mal_uintptr uDeviceID, LPWAVEOUTCAPSA pwoc, UINT cbwoc); -typedef MMRESULT (WINAPI * MAL_PFN_waveOutOpen)(LPHWAVEOUT phwo, UINT uDeviceID, LPCWAVEFORMATEX pwfx, DWORD_PTR dwCallback, DWORD_PTR dwInstance, DWORD fdwOpen); -typedef MMRESULT (WINAPI * MAL_PFN_waveOutClose)(HWAVEOUT hwo); -typedef MMRESULT (WINAPI * MAL_PFN_waveOutPrepareHeader)(HWAVEOUT hwo, LPWAVEHDR pwh, UINT cbwh); -typedef MMRESULT (WINAPI * MAL_PFN_waveOutUnprepareHeader)(HWAVEOUT hwo, LPWAVEHDR pwh, UINT cbwh); -typedef MMRESULT (WINAPI * MAL_PFN_waveOutWrite)(HWAVEOUT hwo, LPWAVEHDR pwh, UINT cbwh); -typedef MMRESULT (WINAPI * MAL_PFN_waveOutReset)(HWAVEOUT hwo); -typedef UINT (WINAPI * MAL_PFN_waveInGetNumDevs)(void); -typedef MMRESULT (WINAPI * MAL_PFN_waveInGetDevCapsA)(mal_uintptr uDeviceID, LPWAVEINCAPSA pwic, UINT cbwic); -typedef MMRESULT (WINAPI * MAL_PFN_waveInOpen)(LPHWAVEIN phwi, UINT uDeviceID, LPCWAVEFORMATEX pwfx, DWORD_PTR dwCallback, DWORD_PTR dwInstance, DWORD fdwOpen); -typedef MMRESULT (WINAPI * MAL_PFN_waveInClose)(HWAVEIN hwi); -typedef MMRESULT (WINAPI * MAL_PFN_waveInPrepareHeader)(HWAVEIN hwi, LPWAVEHDR pwh, UINT cbwh); -typedef MMRESULT (WINAPI * MAL_PFN_waveInUnprepareHeader)(HWAVEIN hwi, LPWAVEHDR pwh, UINT cbwh); -typedef MMRESULT (WINAPI * MAL_PFN_waveInAddBuffer)(HWAVEIN hwi, LPWAVEHDR pwh, UINT cbwh); -typedef MMRESULT (WINAPI * MAL_PFN_waveInStart)(HWAVEIN hwi); -typedef MMRESULT (WINAPI * MAL_PFN_waveInReset)(HWAVEIN hwi); - -mal_result mal_result_from_MMRESULT(MMRESULT resultMM) -{ - switch (resultMM) { - case MMSYSERR_NOERROR: return MAL_SUCCESS; - case MMSYSERR_BADDEVICEID: return MAL_INVALID_ARGS; - case MMSYSERR_INVALHANDLE: return MAL_INVALID_ARGS; - case MMSYSERR_NOMEM: return MAL_OUT_OF_MEMORY; - case MMSYSERR_INVALFLAG: return MAL_INVALID_ARGS; - case MMSYSERR_INVALPARAM: return MAL_INVALID_ARGS; - case MMSYSERR_HANDLEBUSY: return MAL_DEVICE_BUSY; - case MMSYSERR_ERROR: return MAL_ERROR; - default: return MAL_ERROR; - } -} - -char* mal_find_last_character(char* str, char ch) -{ - if (str == NULL) { - return NULL; - } - - char* last = NULL; - while (*str != '\0') { - if (*str == ch) { - last = str; - } - - str += 1; - } - - return last; -} - - -// Our own "WAVECAPS" structure that contains generic information shared between WAVEOUTCAPS2 and WAVEINCAPS2 so -// we can do things generically and typesafely. Names are being kept the same for consistency. -typedef struct -{ - CHAR szPname[MAXPNAMELEN]; - DWORD dwFormats; - WORD wChannels; - GUID NameGuid; -} MAL_WAVECAPSA; - -mal_result mal_get_best_info_from_formats_flags__winmm(DWORD dwFormats, WORD channels, WORD* pBitsPerSample, DWORD* pSampleRate) -{ - if (pBitsPerSample) { - *pBitsPerSample = 0; - } - if (pSampleRate) { - *pSampleRate = 0; - } - - WORD bitsPerSample = 0; - DWORD sampleRate = 0; - - if (channels == 1) { - bitsPerSample = 16; - if ((dwFormats & WAVE_FORMAT_48M16) != 0) { - sampleRate = 48000; - } else if ((dwFormats & WAVE_FORMAT_44M16) != 0) { - sampleRate = 44100; - } else if ((dwFormats & WAVE_FORMAT_2M16) != 0) { - sampleRate = 22050; - } else if ((dwFormats & WAVE_FORMAT_1M16) != 0) { - sampleRate = 11025; - } else if ((dwFormats & WAVE_FORMAT_96M16) != 0) { - sampleRate = 96000; - } else { - bitsPerSample = 8; - if ((dwFormats & WAVE_FORMAT_48M08) != 0) { - sampleRate = 48000; - } else if ((dwFormats & WAVE_FORMAT_44M08) != 0) { - sampleRate = 44100; - } else if ((dwFormats & WAVE_FORMAT_2M08) != 0) { - sampleRate = 22050; - } else if ((dwFormats & WAVE_FORMAT_1M08) != 0) { - sampleRate = 11025; - } else if ((dwFormats & WAVE_FORMAT_96M08) != 0) { - sampleRate = 96000; - } else { - return MAL_FORMAT_NOT_SUPPORTED; - } - } - } else { - bitsPerSample = 16; - if ((dwFormats & WAVE_FORMAT_48S16) != 0) { - sampleRate = 48000; - } else if ((dwFormats & WAVE_FORMAT_44S16) != 0) { - sampleRate = 44100; - } else if ((dwFormats & WAVE_FORMAT_2S16) != 0) { - sampleRate = 22050; - } else if ((dwFormats & WAVE_FORMAT_1S16) != 0) { - sampleRate = 11025; - } else if ((dwFormats & WAVE_FORMAT_96S16) != 0) { - sampleRate = 96000; - } else { - bitsPerSample = 8; - if ((dwFormats & WAVE_FORMAT_48S08) != 0) { - sampleRate = 48000; - } else if ((dwFormats & WAVE_FORMAT_44S08) != 0) { - sampleRate = 44100; - } else if ((dwFormats & WAVE_FORMAT_2S08) != 0) { - sampleRate = 22050; - } else if ((dwFormats & WAVE_FORMAT_1S08) != 0) { - sampleRate = 11025; - } else if ((dwFormats & WAVE_FORMAT_96S08) != 0) { - sampleRate = 96000; - } else { - return MAL_FORMAT_NOT_SUPPORTED; - } - } - } - - if (pBitsPerSample) { - *pBitsPerSample = bitsPerSample; - } - if (pSampleRate) { - *pSampleRate = sampleRate; - } - - return MAL_SUCCESS; -} - -mal_result mal_context_get_device_info_from_WAVECAPS(mal_context* pContext, MAL_WAVECAPSA* pCaps, mal_device_info* pDeviceInfo) -{ - mal_assert(pContext != NULL); - mal_assert(pCaps != NULL); - mal_assert(pDeviceInfo != NULL); - - // Name / Description - // - // Unfortunately the name specified in WAVE(OUT/IN)CAPS2 is limited to 31 characters. This results in an unprofessional looking - // situation where the names of the devices are truncated. To help work around this, we need to look at the name GUID and try - // looking in the registry for the full name. If we can't find it there, we need to just fall back to the default name. - - // Set the default to begin with. - mal_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), pCaps->szPname, (size_t)-1); - - // Now try the registry. There's a few things to consider here: - // - The name GUID can be null, in which we case we just need to stick to the original 31 characters. - // - If the name GUID is not present in the registry we'll also need to stick to the original 31 characters. - // - I like consistency, so I want the returned device names to be consistent with those returned by WASAPI and DirectSound. The - // problem, however is that WASAPI and DirectSound use " ()" format (such as "Speakers (High Definition Audio)"), - // but WinMM does not specificy the component name. From my admittedly limited testing, I've notice the component name seems to - // usually fit within the 31 characters of the fixed sized buffer, so what I'm going to do is parse that string for the component - // name, and then concatenate the name from the registry. - if (!mal_is_guid_equal(&pCaps->NameGuid, &MAL_GUID_NULL)) { - wchar_t guidStrW[256]; - if (((MAL_PFN_StringFromGUID2)pContext->win32.StringFromGUID2)(&pCaps->NameGuid, guidStrW, mal_countof(guidStrW)) > 0) { - char guidStr[256]; - WideCharToMultiByte(CP_UTF8, 0, guidStrW, -1, guidStr, sizeof(guidStr), 0, FALSE); - - char keyStr[1024]; - mal_strcpy_s(keyStr, sizeof(keyStr), "SYSTEM\\CurrentControlSet\\Control\\MediaCategories\\"); - mal_strcat_s(keyStr, sizeof(keyStr), guidStr); - - HKEY hKey; - LONG result = ((MAL_PFN_RegOpenKeyExA)pContext->win32.RegOpenKeyExA)(HKEY_LOCAL_MACHINE, keyStr, 0, KEY_READ, &hKey); - if (result == ERROR_SUCCESS) { - BYTE nameFromReg[512]; - DWORD nameFromRegSize = sizeof(nameFromReg); - result = ((MAL_PFN_RegQueryValueExA)pContext->win32.RegQueryValueExA)(hKey, "Name", 0, NULL, (LPBYTE)nameFromReg, (LPDWORD)&nameFromRegSize); - ((MAL_PFN_RegCloseKey)pContext->win32.RegCloseKey)(hKey); - - if (result == ERROR_SUCCESS) { - // We have the value from the registry, so now we need to construct the name string. - char name[1024]; - if (mal_strcpy_s(name, sizeof(name), pDeviceInfo->name) == 0) { - char* nameBeg = mal_find_last_character(name, '('); - if (nameBeg != NULL) { - size_t leadingLen = (nameBeg - name); - mal_strncpy_s(nameBeg + 1, sizeof(name) - leadingLen, (const char*)nameFromReg, (size_t)-1); - - // The closing ")", if it can fit. - if (leadingLen + nameFromRegSize < sizeof(name)-1) { - mal_strcat_s(name, sizeof(name), ")"); - } - - mal_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), name, (size_t)-1); - } - } - } - } - } - } - - - WORD bitsPerSample; - DWORD sampleRate; - mal_result result = mal_get_best_info_from_formats_flags__winmm(pCaps->dwFormats, pCaps->wChannels, &bitsPerSample, &sampleRate); - if (result != MAL_SUCCESS) { - return result; - } - - pDeviceInfo->minChannels = pCaps->wChannels; - pDeviceInfo->maxChannels = pCaps->wChannels; - pDeviceInfo->minSampleRate = sampleRate; - pDeviceInfo->maxSampleRate = sampleRate; - pDeviceInfo->formatCount = 1; - if (bitsPerSample == 8) { - pDeviceInfo->formats[0] = mal_format_u8; - } else if (bitsPerSample == 16) { - pDeviceInfo->formats[0] = mal_format_s16; - } else if (bitsPerSample == 24) { - pDeviceInfo->formats[0] = mal_format_s24; - } else if (bitsPerSample == 32) { - pDeviceInfo->formats[0] = mal_format_s32; - } else { - return MAL_FORMAT_NOT_SUPPORTED; - } - - return MAL_SUCCESS; -} - -mal_result mal_context_get_device_info_from_WAVEOUTCAPS2(mal_context* pContext, MAL_WAVEOUTCAPS2A* pCaps, mal_device_info* pDeviceInfo) -{ - mal_assert(pContext != NULL); - mal_assert(pCaps != NULL); - mal_assert(pDeviceInfo != NULL); - - MAL_WAVECAPSA caps; - mal_copy_memory(caps.szPname, pCaps->szPname, sizeof(caps.szPname)); - caps.dwFormats = pCaps->dwFormats; - caps.wChannels = pCaps->wChannels; - caps.NameGuid = pCaps->NameGuid; - return mal_context_get_device_info_from_WAVECAPS(pContext, &caps, pDeviceInfo); -} - -mal_result mal_context_get_device_info_from_WAVEINCAPS2(mal_context* pContext, MAL_WAVEINCAPS2A* pCaps, mal_device_info* pDeviceInfo) -{ - mal_assert(pContext != NULL); - mal_assert(pCaps != NULL); - mal_assert(pDeviceInfo != NULL); - - MAL_WAVECAPSA caps; - mal_copy_memory(caps.szPname, pCaps->szPname, sizeof(caps.szPname)); - caps.dwFormats = pCaps->dwFormats; - caps.wChannels = pCaps->wChannels; - caps.NameGuid = pCaps->NameGuid; - return mal_context_get_device_info_from_WAVECAPS(pContext, &caps, pDeviceInfo); -} - - -mal_bool32 mal_context_is_device_id_equal__winmm(mal_context* pContext, const mal_device_id* pID0, const mal_device_id* pID1) -{ - mal_assert(pContext != NULL); - mal_assert(pID0 != NULL); - mal_assert(pID1 != NULL); - (void)pContext; - - return pID0->winmm == pID1->winmm; -} - -mal_result mal_context_enumerate_devices__winmm(mal_context* pContext, mal_enum_devices_callback_proc callback, void* pUserData) -{ - mal_assert(pContext != NULL); - mal_assert(callback != NULL); - - // Playback. - UINT playbackDeviceCount = ((MAL_PFN_waveOutGetNumDevs)pContext->winmm.waveOutGetNumDevs)(); - for (UINT iPlaybackDevice = 0; iPlaybackDevice < playbackDeviceCount; ++iPlaybackDevice) { - MAL_WAVEOUTCAPS2A caps; - mal_zero_object(&caps); - MMRESULT result = ((MAL_PFN_waveOutGetDevCapsA)pContext->winmm.waveOutGetDevCapsA)(iPlaybackDevice, (WAVEOUTCAPSA*)&caps, sizeof(caps)); - if (result == MMSYSERR_NOERROR) { - mal_device_info deviceInfo; - mal_zero_object(&deviceInfo); - deviceInfo.id.winmm = iPlaybackDevice; - - if (mal_context_get_device_info_from_WAVEOUTCAPS2(pContext, &caps, &deviceInfo) == MAL_SUCCESS) { - mal_bool32 cbResult = callback(pContext, mal_device_type_playback, &deviceInfo, pUserData); - if (cbResult == MAL_FALSE) { - return MAL_SUCCESS; // Enumeration was stopped. - } - } - } - } - - // Capture. - UINT captureDeviceCount = ((MAL_PFN_waveInGetNumDevs)pContext->winmm.waveInGetNumDevs)(); - for (UINT iCaptureDevice = 0; iCaptureDevice < captureDeviceCount; ++iCaptureDevice) { - MAL_WAVEINCAPS2A caps; - mal_zero_object(&caps); - MMRESULT result = ((MAL_PFN_waveInGetDevCapsA)pContext->winmm.waveInGetDevCapsA)(iCaptureDevice, (WAVEINCAPSA*)&caps, sizeof(caps)); - if (result == MMSYSERR_NOERROR) { - mal_device_info deviceInfo; - mal_zero_object(&deviceInfo); - deviceInfo.id.winmm = iCaptureDevice; - - if (mal_context_get_device_info_from_WAVEINCAPS2(pContext, &caps, &deviceInfo) == MAL_SUCCESS) { - mal_bool32 cbResult = callback(pContext, mal_device_type_capture, &deviceInfo, pUserData); - if (cbResult == MAL_FALSE) { - return MAL_SUCCESS; // Enumeration was stopped. - } - } - } - } - - return MAL_SUCCESS; -} - -mal_result mal_context_get_device_info__winmm(mal_context* pContext, mal_device_type deviceType, const mal_device_id* pDeviceID, mal_share_mode shareMode, mal_device_info* pDeviceInfo) -{ - mal_assert(pContext != NULL); - (void)shareMode; - - UINT winMMDeviceID = 0; - if (pDeviceID != NULL) { - winMMDeviceID = (UINT)pDeviceID->winmm; - } - - pDeviceInfo->id.winmm = winMMDeviceID; - - if (deviceType == mal_device_type_playback) { - MAL_WAVEOUTCAPS2A caps; - mal_zero_object(&caps); - MMRESULT result = ((MAL_PFN_waveOutGetDevCapsA)pContext->winmm.waveOutGetDevCapsA)(winMMDeviceID, (WAVEOUTCAPSA*)&caps, sizeof(caps)); - if (result == MMSYSERR_NOERROR) { - return mal_context_get_device_info_from_WAVEOUTCAPS2(pContext, &caps, pDeviceInfo); - } - } else { - MAL_WAVEINCAPS2A caps; - mal_zero_object(&caps); - MMRESULT result = ((MAL_PFN_waveInGetDevCapsA)pContext->winmm.waveInGetDevCapsA)(winMMDeviceID, (WAVEINCAPSA*)&caps, sizeof(caps)); - if (result == MMSYSERR_NOERROR) { - return mal_context_get_device_info_from_WAVEINCAPS2(pContext, &caps, pDeviceInfo); - } - } - - return MAL_NO_DEVICE; -} - - -void mal_device_uninit__winmm(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - if (pDevice->type == mal_device_type_playback) { - ((MAL_PFN_waveOutClose)pDevice->pContext->winmm.waveOutClose)((HWAVEOUT)pDevice->winmm.hDevice); - } else { - ((MAL_PFN_waveInClose)pDevice->pContext->winmm.waveInClose)((HWAVEIN)pDevice->winmm.hDevice); - } - - mal_free(pDevice->winmm._pHeapData); - CloseHandle((HANDLE)pDevice->winmm.hEvent); - - mal_zero_object(&pDevice->winmm); // Safety. -} - -mal_result mal_device_init__winmm(mal_context* pContext, mal_device_type type, const mal_device_id* pDeviceID, const mal_device_config* pConfig, mal_device* pDevice) -{ - (void)pContext; - - mal_uint32 heapSize; - - mal_assert(pDevice != NULL); - mal_zero_object(&pDevice->winmm); - - UINT winMMDeviceID = 0; - if (pDeviceID != NULL) { - winMMDeviceID = (UINT)pDeviceID->winmm; - } - - const char* errorMsg = ""; - mal_result errorCode = MAL_ERROR; - mal_result result = MAL_SUCCESS; - - // WinMM doesn't seem to have a good way to query the format of the device. Therefore, we'll restrict the formats to the - // standard formats documented here https://msdn.microsoft.com/en-us/library/windows/desktop/dd743855(v=vs.85).aspx. If - // that link goes stale, just look up the documentation for WAVEOUTCAPS or WAVEINCAPS. - WAVEFORMATEX wf; - mal_zero_object(&wf); - wf.cbSize = sizeof(wf); - wf.wFormatTag = WAVE_FORMAT_PCM; - wf.nChannels = (WORD)pConfig->channels; - wf.nSamplesPerSec = (DWORD)pConfig->sampleRate; - wf.wBitsPerSample = (WORD)mal_get_bytes_per_sample(pConfig->format)*8; - - if (wf.nChannels > 2) { - wf.nChannels = 2; - } - - if (wf.wBitsPerSample != 8 && wf.wBitsPerSample != 16) { - if (wf.wBitsPerSample <= 8) { - wf.wBitsPerSample = 8; - } else { - wf.wBitsPerSample = 16; - } - } - - if (wf.nSamplesPerSec <= 11025) { - wf.nSamplesPerSec = 11025; - } else if (wf.nSamplesPerSec <= 22050) { - wf.nSamplesPerSec = 22050; - } else if (wf.nSamplesPerSec <= 44100) { - wf.nSamplesPerSec = 44100; - } else if (wf.nSamplesPerSec <= 48000) { - wf.nSamplesPerSec = 48000; - } else { - wf.nSamplesPerSec = 96000; - } - - - // Change the format based on the closest match of the supported standard formats. - DWORD dwFormats = 0; - WORD wChannels = 0; - if (type == mal_device_type_playback) { - WAVEOUTCAPSA caps; - if (((MAL_PFN_waveOutGetDevCapsA)pContext->winmm.waveOutGetDevCapsA)(winMMDeviceID, &caps, sizeof(caps)) == MMSYSERR_NOERROR) { - dwFormats = caps.dwFormats; - wChannels = caps.wChannels; - } else { - errorMsg = "[WinMM] Failed to retrieve internal device caps.", errorCode = MAL_FORMAT_NOT_SUPPORTED; - goto on_error; - } - } else { - WAVEINCAPSA caps; - if (((MAL_PFN_waveInGetDevCapsA)pContext->winmm.waveInGetDevCapsA)(winMMDeviceID, &caps, sizeof(caps)) == MMSYSERR_NOERROR) { - dwFormats = caps.dwFormats; - wChannels = caps.wChannels; - } else { - errorMsg = "[WinMM] Failed to retrieve internal device caps.", errorCode = MAL_FORMAT_NOT_SUPPORTED; - goto on_error; - } - } - - if (dwFormats == 0) { - errorMsg = "[WinMM] Failed to retrieve the supported formats for the internal device.", errorCode = MAL_FORMAT_NOT_SUPPORTED; - goto on_error; - } - - wf.nChannels = wChannels; - - result = mal_get_best_info_from_formats_flags__winmm(dwFormats, wChannels, &wf.wBitsPerSample, &wf.nSamplesPerSec); - if (result != MAL_SUCCESS) { - errorMsg = "[WinMM] Could not find appropriate format for internal device.", errorCode = result; - goto on_error; - } - - wf.nBlockAlign = (wf.nChannels * wf.wBitsPerSample) / 8; - wf.nAvgBytesPerSec = wf.nBlockAlign * wf.nSamplesPerSec; - - - // We use an event to know when a new fragment needs to be enqueued. - pDevice->winmm.hEvent = (mal_handle)CreateEvent(NULL, TRUE, TRUE, NULL); - if (pDevice->winmm.hEvent == NULL) { - errorMsg = "[WinMM] Failed to create event for fragment enqueing.", errorCode = MAL_FAILED_TO_CREATE_EVENT; - goto on_error; - } - - - if (type == mal_device_type_playback) { - MMRESULT resultMM = ((MAL_PFN_waveOutOpen)pContext->winmm.waveOutOpen)((LPHWAVEOUT)&pDevice->winmm.hDevice, winMMDeviceID, &wf, (DWORD_PTR)pDevice->winmm.hEvent, (DWORD_PTR)pDevice, CALLBACK_EVENT | WAVE_ALLOWSYNC); - if (resultMM != MMSYSERR_NOERROR) { - errorMsg = "[WinMM] Failed to open playback device.", errorCode = MAL_FAILED_TO_OPEN_BACKEND_DEVICE; - goto on_error; - } - } else { - MMRESULT resultMM = ((MAL_PFN_waveInOpen)pDevice->pContext->winmm.waveInOpen)((LPHWAVEIN)&pDevice->winmm.hDevice, winMMDeviceID, &wf, (DWORD_PTR)pDevice->winmm.hEvent, (DWORD_PTR)pDevice, CALLBACK_EVENT | WAVE_ALLOWSYNC); - if (resultMM != MMSYSERR_NOERROR) { - errorMsg = "[WinMM] Failed to open capture device.", errorCode = MAL_FAILED_TO_OPEN_BACKEND_DEVICE; - goto on_error; - } - } - - - // The internal formats need to be set based on the wf object. - if (wf.wFormatTag == WAVE_FORMAT_PCM) { - switch (wf.wBitsPerSample) { - case 8: pDevice->internalFormat = mal_format_u8; break; - case 16: pDevice->internalFormat = mal_format_s16; break; - case 24: pDevice->internalFormat = mal_format_s24; break; - case 32: pDevice->internalFormat = mal_format_s32; break; - default: mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[WinMM] The device's internal format is not supported by mini_al.", MAL_FORMAT_NOT_SUPPORTED); - } - } else { - errorMsg = "[WinMM] The device's internal format is not supported by mini_al.", errorCode = MAL_FORMAT_NOT_SUPPORTED; - goto on_error; - } - - pDevice->internalChannels = wf.nChannels; - pDevice->internalSampleRate = wf.nSamplesPerSec; - - - // Just use the default channel mapping. WinMM only supports mono or stereo anyway so it'll reliably be left/right order for stereo. - mal_get_standard_channel_map(mal_standard_channel_map_microsoft, pDevice->internalChannels, pDevice->internalChannelMap); - - - if (pDevice->bufferSizeInFrames == 0) { - pDevice->bufferSizeInFrames = mal_calculate_buffer_size_in_frames_from_milliseconds(pDevice->bufferSizeInMilliseconds, pDevice->internalSampleRate); - if (pDevice->usingDefaultBufferSize) { - float bufferSizeScaleFactor = 4; // <-- Latency with WinMM seems pretty bad from my testing... - pDevice->bufferSizeInFrames = mal_scale_buffer_size(pDevice->bufferSizeInFrames, bufferSizeScaleFactor); - } - } - - // The size of the intermediary buffer needs to be able to fit every fragment. - pDevice->winmm.fragmentSizeInFrames = pDevice->bufferSizeInFrames / pDevice->periods; - pDevice->winmm.fragmentSizeInBytes = pDevice->winmm.fragmentSizeInFrames * pDevice->internalChannels * mal_get_bytes_per_sample(pDevice->internalFormat); - - heapSize = (sizeof(WAVEHDR) * pDevice->periods) + (pDevice->winmm.fragmentSizeInBytes * pDevice->periods); - pDevice->winmm._pHeapData = (mal_uint8*)mal_malloc(heapSize); - if (pDevice->winmm._pHeapData == NULL) { - errorMsg = "[WinMM] Failed to allocate memory for the intermediary buffer.", errorCode = MAL_OUT_OF_MEMORY; - goto on_error; - } - - mal_zero_memory(pDevice->winmm._pHeapData, pDevice->winmm.fragmentSizeInBytes * pDevice->periods); - - pDevice->winmm.pWAVEHDR = pDevice->winmm._pHeapData; - pDevice->winmm.pIntermediaryBuffer = pDevice->winmm._pHeapData + (sizeof(WAVEHDR) * pDevice->periods); - - - return MAL_SUCCESS; - -on_error: - if (pDevice->type == mal_device_type_playback) { - ((MAL_PFN_waveOutClose)pContext->winmm.waveOutClose)((HWAVEOUT)pDevice->winmm.hDevice); - } else { - ((MAL_PFN_waveInClose)pContext->winmm.waveInClose)((HWAVEIN)pDevice->winmm.hDevice); - } - - mal_free(pDevice->winmm._pHeapData); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, errorMsg, errorCode); -} - - -mal_result mal_device_start__winmm(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - if (pDevice->winmm.hDevice == NULL) { - return MAL_INVALID_ARGS; - } - - if (pDevice->type == mal_device_type_playback) { - // Playback. The device is started when we call waveOutWrite() with a block of data. From MSDN: - // - // Unless the device is paused by calling the waveOutPause function, playback begins when the first data block is sent to the device. - // - // When starting the device we commit every fragment. We signal the event before calling waveOutWrite(). - mal_uint32 i; - for (i = 0; i < pDevice->periods; ++i) { - mal_zero_object(&((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i]); - ((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i].lpData = (LPSTR)(pDevice->winmm.pIntermediaryBuffer + (pDevice->winmm.fragmentSizeInBytes * i)); - ((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i].dwBufferLength = pDevice->winmm.fragmentSizeInBytes; - ((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i].dwFlags = 0L; - ((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i].dwLoops = 0L; - mal_device__read_frames_from_client(pDevice, pDevice->winmm.fragmentSizeInFrames, ((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i].lpData); - - if (((MAL_PFN_waveOutPrepareHeader)pDevice->pContext->winmm.waveOutPrepareHeader)((HWAVEOUT)pDevice->winmm.hDevice, &((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i], sizeof(WAVEHDR)) != MMSYSERR_NOERROR) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[WinMM] Failed to start backend device. Failed to prepare header.", MAL_FAILED_TO_START_BACKEND_DEVICE); - } - } - - ResetEvent(pDevice->winmm.hEvent); - - for (i = 0; i < pDevice->periods; ++i) { - if (((MAL_PFN_waveOutWrite)pDevice->pContext->winmm.waveOutWrite)((HWAVEOUT)pDevice->winmm.hDevice, &((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i], sizeof(WAVEHDR)) != MMSYSERR_NOERROR) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[WinMM] Failed to start backend device. Failed to send data to the backend device.", MAL_FAILED_TO_START_BACKEND_DEVICE); - } - } - } else { - // Capture. - for (mal_uint32 i = 0; i < pDevice->periods; ++i) { - mal_zero_object(&((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i]); - ((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i].lpData = (LPSTR)(pDevice->winmm.pIntermediaryBuffer + (pDevice->winmm.fragmentSizeInBytes * i)); - ((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i].dwBufferLength = pDevice->winmm.fragmentSizeInBytes; - ((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i].dwFlags = 0L; - ((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i].dwLoops = 0L; - - MMRESULT resultMM = ((MAL_PFN_waveInPrepareHeader)pDevice->pContext->winmm.waveInPrepareHeader)((HWAVEIN)pDevice->winmm.hDevice, &((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i], sizeof(WAVEHDR)); - if (resultMM != MMSYSERR_NOERROR) { - mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[WinMM] Failed to prepare header for capture device in preparation for adding a new capture buffer for the device.", mal_result_from_MMRESULT(resultMM)); - break; - } - - resultMM = ((MAL_PFN_waveInAddBuffer)pDevice->pContext->winmm.waveInAddBuffer)((HWAVEIN)pDevice->winmm.hDevice, &((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i], sizeof(WAVEHDR)); - if (resultMM != MMSYSERR_NOERROR) { - mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[WinMM] Failed to add new capture buffer to the internal capture device.", mal_result_from_MMRESULT(resultMM)); - break; - } - } - - ResetEvent(pDevice->winmm.hEvent); - - if (((MAL_PFN_waveInStart)pDevice->pContext->winmm.waveInStart)((HWAVEIN)pDevice->winmm.hDevice) != MMSYSERR_NOERROR) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[WinMM] Failed to start backend device.", MAL_FAILED_TO_START_BACKEND_DEVICE); - } - } - - pDevice->winmm.iNextHeader = 0; - return MAL_SUCCESS; -} - -mal_result mal_device_stop__winmm(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - if (pDevice->winmm.hDevice == NULL) { - return MAL_INVALID_ARGS; - } - - if (pDevice->type == mal_device_type_playback) { - MMRESULT resultMM = ((MAL_PFN_waveOutReset)pDevice->pContext->winmm.waveOutReset)((HWAVEOUT)pDevice->winmm.hDevice); - if (resultMM != MMSYSERR_NOERROR) { - mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[WinMM] WARNING: Failed to reset playback device.", mal_result_from_MMRESULT(resultMM)); - } - - // Unprepare all WAVEHDR structures. - for (mal_uint32 i = 0; i < pDevice->periods; ++i) { - resultMM = ((MAL_PFN_waveOutUnprepareHeader)pDevice->pContext->winmm.waveOutUnprepareHeader)((HWAVEOUT)pDevice->winmm.hDevice, &((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i], sizeof(WAVEHDR)); - if (resultMM != MMSYSERR_NOERROR) { - mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[WinMM] WARNING: Failed to unprepare header for playback device.", mal_result_from_MMRESULT(resultMM)); - } - } - } else { - MMRESULT resultMM = ((MAL_PFN_waveInReset)pDevice->pContext->winmm.waveInReset)((HWAVEIN)pDevice->winmm.hDevice); - if (resultMM != MMSYSERR_NOERROR) { - mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[WinMM] WARNING: Failed to reset capture device.", mal_result_from_MMRESULT(resultMM)); - } - - // Unprepare all WAVEHDR structures. - for (mal_uint32 i = 0; i < pDevice->periods; ++i) { - resultMM = ((MAL_PFN_waveInUnprepareHeader)pDevice->pContext->winmm.waveInUnprepareHeader)((HWAVEIN)pDevice->winmm.hDevice, &((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i], sizeof(WAVEHDR)); - if (resultMM != MMSYSERR_NOERROR) { - mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[WinMM] WARNING: Failed to unprepare header for playback device.", mal_result_from_MMRESULT(resultMM)); - } - } - } - - return MAL_SUCCESS; -} - -mal_result mal_device_break_main_loop__winmm(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - pDevice->winmm.breakFromMainLoop = MAL_TRUE; - SetEvent((HANDLE)pDevice->winmm.hEvent); - - return MAL_SUCCESS; -} - -mal_result mal_device_main_loop__winmm(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - mal_uint32 counter; - - pDevice->winmm.breakFromMainLoop = MAL_FALSE; - while (!pDevice->winmm.breakFromMainLoop) { - // Wait for a block of data to finish processing... - if (WaitForSingleObject((HANDLE)pDevice->winmm.hEvent, INFINITE) != WAIT_OBJECT_0) { - break; - } - - // Break from the main loop if the device isn't started anymore. Likely what's happened is the application - // has requested that the device be stopped. - if (!mal_device_is_started(pDevice)) { - break; - } - - // Any headers that are marked as done need to be handled. We start by processing the completed blocks. Then we reset the event - // and then write or add replacement buffers to the device. - mal_uint32 iFirstHeader = pDevice->winmm.iNextHeader; - for (counter = 0; counter < pDevice->periods; ++counter) { - mal_uint32 i = pDevice->winmm.iNextHeader; - if ((((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i].dwFlags & WHDR_DONE) == 0) { - break; - } - - if (pDevice->type == mal_device_type_playback) { - // Playback. - MMRESULT resultMM = ((MAL_PFN_waveOutUnprepareHeader)pDevice->pContext->winmm.waveOutUnprepareHeader)((HWAVEOUT)pDevice->winmm.hDevice, &((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i], sizeof(WAVEHDR)); - if (resultMM != MMSYSERR_NOERROR) { - mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[WinMM] Failed to unprepare header for playback device in preparation for sending a new block of data to the device for playback.", mal_result_from_MMRESULT(resultMM)); - return MAL_DEVICE_UNAVAILABLE; - } - - mal_zero_object(&((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i]); - ((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i].lpData = (LPSTR)(pDevice->winmm.pIntermediaryBuffer + (pDevice->winmm.fragmentSizeInBytes * i)); - ((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i].dwBufferLength = pDevice->winmm.fragmentSizeInBytes; - ((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i].dwFlags = 0L; - ((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i].dwLoops = 0L; - ((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i].dwUser = 1; // <-- Used in the next section to identify the buffers that needs to be re-written to the device. - mal_device__read_frames_from_client(pDevice, pDevice->winmm.fragmentSizeInFrames, ((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i].lpData); - - resultMM = ((MAL_PFN_waveOutPrepareHeader)pDevice->pContext->winmm.waveOutPrepareHeader)((HWAVEOUT)pDevice->winmm.hDevice, &((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i], sizeof(WAVEHDR)); - if (resultMM != MMSYSERR_NOERROR) { - mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[WinMM] Failed to prepare header for playback device in preparation for sending a new block of data to the device for playback.", mal_result_from_MMRESULT(resultMM)); - return MAL_DEVICE_UNAVAILABLE; - } - } else { - // Capture. - mal_uint32 framesCaptured = (mal_uint32)(((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i].dwBytesRecorded) / pDevice->internalChannels / mal_get_bytes_per_sample(pDevice->internalFormat); - if (framesCaptured > 0) { - mal_device__send_frames_to_client(pDevice, framesCaptured, ((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i].lpData); - } - - MMRESULT resultMM = ((MAL_PFN_waveInUnprepareHeader)pDevice->pContext->winmm.waveInUnprepareHeader)((HWAVEIN)pDevice->winmm.hDevice, &((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i], sizeof(WAVEHDR)); - if (resultMM != MMSYSERR_NOERROR) { - mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[WinMM] Failed to unprepare header for capture device in preparation for adding a new capture buffer for the device.", mal_result_from_MMRESULT(resultMM)); - return MAL_DEVICE_UNAVAILABLE; - } - - mal_zero_object(&((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i]); - ((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i].lpData = (LPSTR)(pDevice->winmm.pIntermediaryBuffer + (pDevice->winmm.fragmentSizeInBytes * i)); - ((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i].dwBufferLength = pDevice->winmm.fragmentSizeInBytes; - ((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i].dwFlags = 0L; - ((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i].dwLoops = 0L; - ((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i].dwUser = 1; // <-- Used in the next section to identify the buffers that needs to be re-added to the device. - - resultMM = ((MAL_PFN_waveInPrepareHeader)pDevice->pContext->winmm.waveInPrepareHeader)((HWAVEIN)pDevice->winmm.hDevice, &((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i], sizeof(WAVEHDR)); - if (resultMM != MMSYSERR_NOERROR) { - mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[WinMM] Failed to prepare header for capture device in preparation for adding a new capture buffer for the device.", mal_result_from_MMRESULT(resultMM)); - return MAL_DEVICE_UNAVAILABLE; - } - } - - pDevice->winmm.iNextHeader = (pDevice->winmm.iNextHeader + 1) % pDevice->periods; - } - - ResetEvent((HANDLE)pDevice->winmm.hEvent); - - for (counter = 0; counter < pDevice->periods; ++counter) { - mal_uint32 i = (iFirstHeader + counter) % pDevice->periods; - - if (((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i].dwUser == 1) { - ((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i].dwUser = 0; - - if (pDevice->type == mal_device_type_playback) { - // Playback. - MMRESULT resultMM = ((MAL_PFN_waveOutWrite)pDevice->pContext->winmm.waveOutWrite)((HWAVEOUT)pDevice->winmm.hDevice, &((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i], sizeof(WAVEHDR)); - if (resultMM != MMSYSERR_NOERROR) { - mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[WinMM] Failed to write data to the internal playback device.", mal_result_from_MMRESULT(resultMM)); - return MAL_DEVICE_UNAVAILABLE; - } - } else { - // Capture. - MMRESULT resultMM = ((MAL_PFN_waveInAddBuffer)pDevice->pContext->winmm.waveInAddBuffer)((HWAVEIN)pDevice->winmm.hDevice, &((LPWAVEHDR)pDevice->winmm.pWAVEHDR)[i], sizeof(WAVEHDR)); - if (resultMM != MMSYSERR_NOERROR) { - mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[WinMM] Failed to add new capture buffer to the internal capture device.", mal_result_from_MMRESULT(resultMM)); - return MAL_DEVICE_UNAVAILABLE; - } - } - } - } - } - - return MAL_SUCCESS; -} - - -mal_result mal_context_uninit__winmm(mal_context* pContext) -{ - mal_assert(pContext != NULL); - mal_assert(pContext->backend == mal_backend_winmm); - - mal_dlclose(pContext->winmm.hWinMM); - return MAL_SUCCESS; -} - -mal_result mal_context_init__winmm(mal_context* pContext) -{ - mal_assert(pContext != NULL); - - pContext->winmm.hWinMM = mal_dlopen("winmm.dll"); - if (pContext->winmm.hWinMM == NULL) { - return MAL_NO_BACKEND; - } - - pContext->winmm.waveOutGetNumDevs = mal_dlsym(pContext->winmm.hWinMM, "waveOutGetNumDevs"); - pContext->winmm.waveOutGetDevCapsA = mal_dlsym(pContext->winmm.hWinMM, "waveOutGetDevCapsA"); - pContext->winmm.waveOutOpen = mal_dlsym(pContext->winmm.hWinMM, "waveOutOpen"); - pContext->winmm.waveOutClose = mal_dlsym(pContext->winmm.hWinMM, "waveOutClose"); - pContext->winmm.waveOutPrepareHeader = mal_dlsym(pContext->winmm.hWinMM, "waveOutPrepareHeader"); - pContext->winmm.waveOutUnprepareHeader = mal_dlsym(pContext->winmm.hWinMM, "waveOutUnprepareHeader"); - pContext->winmm.waveOutWrite = mal_dlsym(pContext->winmm.hWinMM, "waveOutWrite"); - pContext->winmm.waveOutReset = mal_dlsym(pContext->winmm.hWinMM, "waveOutReset"); - pContext->winmm.waveInGetNumDevs = mal_dlsym(pContext->winmm.hWinMM, "waveInGetNumDevs"); - pContext->winmm.waveInGetDevCapsA = mal_dlsym(pContext->winmm.hWinMM, "waveInGetDevCapsA"); - pContext->winmm.waveInOpen = mal_dlsym(pContext->winmm.hWinMM, "waveInOpen"); - pContext->winmm.waveInClose = mal_dlsym(pContext->winmm.hWinMM, "waveInClose"); - pContext->winmm.waveInPrepareHeader = mal_dlsym(pContext->winmm.hWinMM, "waveInPrepareHeader"); - pContext->winmm.waveInUnprepareHeader = mal_dlsym(pContext->winmm.hWinMM, "waveInUnprepareHeader"); - pContext->winmm.waveInAddBuffer = mal_dlsym(pContext->winmm.hWinMM, "waveInAddBuffer"); - pContext->winmm.waveInStart = mal_dlsym(pContext->winmm.hWinMM, "waveInStart"); - pContext->winmm.waveInReset = mal_dlsym(pContext->winmm.hWinMM, "waveInReset"); - - pContext->onUninit = mal_context_uninit__winmm; - pContext->onDeviceIDEqual = mal_context_is_device_id_equal__winmm; - pContext->onEnumDevices = mal_context_enumerate_devices__winmm; - pContext->onGetDeviceInfo = mal_context_get_device_info__winmm; - pContext->onDeviceInit = mal_device_init__winmm; - pContext->onDeviceUninit = mal_device_uninit__winmm; - pContext->onDeviceStart = mal_device_start__winmm; - pContext->onDeviceStop = mal_device_stop__winmm; - pContext->onDeviceBreakMainLoop = mal_device_break_main_loop__winmm; - pContext->onDeviceMainLoop = mal_device_main_loop__winmm; - - return MAL_SUCCESS; -} -#endif - - - - -/////////////////////////////////////////////////////////////////////////////// -// -// ALSA Backend -// -/////////////////////////////////////////////////////////////////////////////// -#ifdef MAL_HAS_ALSA - -#ifdef MAL_NO_RUNTIME_LINKING -#include -typedef snd_pcm_uframes_t mal_snd_pcm_uframes_t; -typedef snd_pcm_sframes_t mal_snd_pcm_sframes_t; -typedef snd_pcm_stream_t mal_snd_pcm_stream_t; -typedef snd_pcm_format_t mal_snd_pcm_format_t; -typedef snd_pcm_access_t mal_snd_pcm_access_t; -typedef snd_pcm_t mal_snd_pcm_t; -typedef snd_pcm_hw_params_t mal_snd_pcm_hw_params_t; -typedef snd_pcm_sw_params_t mal_snd_pcm_sw_params_t; -typedef snd_pcm_format_mask_t mal_snd_pcm_format_mask_t; -typedef snd_pcm_info_t mal_snd_pcm_info_t; -typedef snd_pcm_channel_area_t mal_snd_pcm_channel_area_t; -typedef snd_pcm_chmap_t mal_snd_pcm_chmap_t; - -// snd_pcm_stream_t -#define MAL_SND_PCM_STREAM_PLAYBACK SND_PCM_STREAM_PLAYBACK -#define MAL_SND_PCM_STREAM_CAPTURE SND_PCM_STREAM_CAPTURE - -// snd_pcm_format_t -#define MAL_SND_PCM_FORMAT_UNKNOWN SND_PCM_FORMAT_UNKNOWN -#define MAL_SND_PCM_FORMAT_U8 SND_PCM_FORMAT_U8 -#define MAL_SND_PCM_FORMAT_S16_LE SND_PCM_FORMAT_S16_LE -#define MAL_SND_PCM_FORMAT_S16_BE SND_PCM_FORMAT_S16_BE -#define MAL_SND_PCM_FORMAT_S24_LE SND_PCM_FORMAT_S24_LE -#define MAL_SND_PCM_FORMAT_S24_BE SND_PCM_FORMAT_S24_BE -#define MAL_SND_PCM_FORMAT_S32_LE SND_PCM_FORMAT_S32_LE -#define MAL_SND_PCM_FORMAT_S32_BE SND_PCM_FORMAT_S32_BE -#define MAL_SND_PCM_FORMAT_FLOAT_LE SND_PCM_FORMAT_FLOAT_LE -#define MAL_SND_PCM_FORMAT_FLOAT_BE SND_PCM_FORMAT_FLOAT_BE -#define MAL_SND_PCM_FORMAT_FLOAT64_LE SND_PCM_FORMAT_FLOAT64_LE -#define MAL_SND_PCM_FORMAT_FLOAT64_BE SND_PCM_FORMAT_FLOAT64_BE -#define MAL_SND_PCM_FORMAT_MU_LAW SND_PCM_FORMAT_MU_LAW -#define MAL_SND_PCM_FORMAT_A_LAW SND_PCM_FORMAT_A_LAW -#define MAL_SND_PCM_FORMAT_S24_3LE SND_PCM_FORMAT_S24_3LE -#define MAL_SND_PCM_FORMAT_S24_3BE SND_PCM_FORMAT_S24_3BE - -// mal_snd_pcm_access_t -#define MAL_SND_PCM_ACCESS_MMAP_INTERLEAVED SND_PCM_ACCESS_MMAP_INTERLEAVED -#define MAL_SND_PCM_ACCESS_MMAP_NONINTERLEAVED SND_PCM_ACCESS_MMAP_NONINTERLEAVED -#define MAL_SND_PCM_ACCESS_MMAP_COMPLEX SND_PCM_ACCESS_MMAP_COMPLEX -#define MAL_SND_PCM_ACCESS_RW_INTERLEAVED SND_PCM_ACCESS_RW_INTERLEAVED -#define MAL_SND_PCM_ACCESS_RW_NONINTERLEAVED SND_PCM_ACCESS_RW_NONINTERLEAVED - -// Channel positions. -#define MAL_SND_CHMAP_UNKNOWN SND_CHMAP_UNKNOWN -#define MAL_SND_CHMAP_NA SND_CHMAP_NA -#define MAL_SND_CHMAP_MONO SND_CHMAP_MONO -#define MAL_SND_CHMAP_FL SND_CHMAP_FL -#define MAL_SND_CHMAP_FR SND_CHMAP_FR -#define MAL_SND_CHMAP_RL SND_CHMAP_RL -#define MAL_SND_CHMAP_RR SND_CHMAP_RR -#define MAL_SND_CHMAP_FC SND_CHMAP_FC -#define MAL_SND_CHMAP_LFE SND_CHMAP_LFE -#define MAL_SND_CHMAP_SL SND_CHMAP_SL -#define MAL_SND_CHMAP_SR SND_CHMAP_SR -#define MAL_SND_CHMAP_RC SND_CHMAP_RC -#define MAL_SND_CHMAP_FLC SND_CHMAP_FLC -#define MAL_SND_CHMAP_FRC SND_CHMAP_FRC -#define MAL_SND_CHMAP_RLC SND_CHMAP_RLC -#define MAL_SND_CHMAP_RRC SND_CHMAP_RRC -#define MAL_SND_CHMAP_FLW SND_CHMAP_FLW -#define MAL_SND_CHMAP_FRW SND_CHMAP_FRW -#define MAL_SND_CHMAP_FLH SND_CHMAP_FLH -#define MAL_SND_CHMAP_FCH SND_CHMAP_FCH -#define MAL_SND_CHMAP_FRH SND_CHMAP_FRH -#define MAL_SND_CHMAP_TC SND_CHMAP_TC -#define MAL_SND_CHMAP_TFL SND_CHMAP_TFL -#define MAL_SND_CHMAP_TFR SND_CHMAP_TFR -#define MAL_SND_CHMAP_TFC SND_CHMAP_TFC -#define MAL_SND_CHMAP_TRL SND_CHMAP_TRL -#define MAL_SND_CHMAP_TRR SND_CHMAP_TRR -#define MAL_SND_CHMAP_TRC SND_CHMAP_TRC -#define MAL_SND_CHMAP_TFLC SND_CHMAP_TFLC -#define MAL_SND_CHMAP_TFRC SND_CHMAP_TFRC -#define MAL_SND_CHMAP_TSL SND_CHMAP_TSL -#define MAL_SND_CHMAP_TSR SND_CHMAP_TSR -#define MAL_SND_CHMAP_LLFE SND_CHMAP_LLFE -#define MAL_SND_CHMAP_RLFE SND_CHMAP_RLFE -#define MAL_SND_CHMAP_BC SND_CHMAP_BC -#define MAL_SND_CHMAP_BLC SND_CHMAP_BLC -#define MAL_SND_CHMAP_BRC SND_CHMAP_BRC - -// Open mode flags. -#define MAL_SND_PCM_NO_AUTO_RESAMPLE SND_PCM_NO_AUTO_RESAMPLE -#define MAL_SND_PCM_NO_AUTO_CHANNELS SND_PCM_NO_AUTO_CHANNELS -#define MAL_SND_PCM_NO_AUTO_FORMAT SND_PCM_NO_AUTO_FORMAT -#else -#include // For EPIPE, etc. -typedef unsigned long mal_snd_pcm_uframes_t; -typedef long mal_snd_pcm_sframes_t; -typedef int mal_snd_pcm_stream_t; -typedef int mal_snd_pcm_format_t; -typedef int mal_snd_pcm_access_t; -typedef struct mal_snd_pcm_t mal_snd_pcm_t; -typedef struct mal_snd_pcm_hw_params_t mal_snd_pcm_hw_params_t; -typedef struct mal_snd_pcm_sw_params_t mal_snd_pcm_sw_params_t; -typedef struct mal_snd_pcm_format_mask_t mal_snd_pcm_format_mask_t; -typedef struct mal_snd_pcm_info_t mal_snd_pcm_info_t; -typedef struct -{ - void* addr; - unsigned int first; - unsigned int step; -} mal_snd_pcm_channel_area_t; -typedef struct -{ - unsigned int channels; - unsigned int pos[0]; -} mal_snd_pcm_chmap_t; - -// snd_pcm_stream_t -#define MAL_SND_PCM_STREAM_PLAYBACK 0 -#define MAL_SND_PCM_STREAM_CAPTURE 1 - -// snd_pcm_format_t -#define MAL_SND_PCM_FORMAT_UNKNOWN -1 -#define MAL_SND_PCM_FORMAT_U8 1 -#define MAL_SND_PCM_FORMAT_S16_LE 2 -#define MAL_SND_PCM_FORMAT_S16_BE 3 -#define MAL_SND_PCM_FORMAT_S24_LE 6 -#define MAL_SND_PCM_FORMAT_S24_BE 7 -#define MAL_SND_PCM_FORMAT_S32_LE 10 -#define MAL_SND_PCM_FORMAT_S32_BE 11 -#define MAL_SND_PCM_FORMAT_FLOAT_LE 14 -#define MAL_SND_PCM_FORMAT_FLOAT_BE 15 -#define MAL_SND_PCM_FORMAT_FLOAT64_LE 16 -#define MAL_SND_PCM_FORMAT_FLOAT64_BE 17 -#define MAL_SND_PCM_FORMAT_MU_LAW 20 -#define MAL_SND_PCM_FORMAT_A_LAW 21 -#define MAL_SND_PCM_FORMAT_S24_3LE 32 -#define MAL_SND_PCM_FORMAT_S24_3BE 33 - -// snd_pcm_access_t -#define MAL_SND_PCM_ACCESS_MMAP_INTERLEAVED 0 -#define MAL_SND_PCM_ACCESS_MMAP_NONINTERLEAVED 1 -#define MAL_SND_PCM_ACCESS_MMAP_COMPLEX 2 -#define MAL_SND_PCM_ACCESS_RW_INTERLEAVED 3 -#define MAL_SND_PCM_ACCESS_RW_NONINTERLEAVED 4 - -// Channel positions. -#define MAL_SND_CHMAP_UNKNOWN 0 -#define MAL_SND_CHMAP_NA 1 -#define MAL_SND_CHMAP_MONO 2 -#define MAL_SND_CHMAP_FL 3 -#define MAL_SND_CHMAP_FR 4 -#define MAL_SND_CHMAP_RL 5 -#define MAL_SND_CHMAP_RR 6 -#define MAL_SND_CHMAP_FC 7 -#define MAL_SND_CHMAP_LFE 8 -#define MAL_SND_CHMAP_SL 9 -#define MAL_SND_CHMAP_SR 10 -#define MAL_SND_CHMAP_RC 11 -#define MAL_SND_CHMAP_FLC 12 -#define MAL_SND_CHMAP_FRC 13 -#define MAL_SND_CHMAP_RLC 14 -#define MAL_SND_CHMAP_RRC 15 -#define MAL_SND_CHMAP_FLW 16 -#define MAL_SND_CHMAP_FRW 17 -#define MAL_SND_CHMAP_FLH 18 -#define MAL_SND_CHMAP_FCH 19 -#define MAL_SND_CHMAP_FRH 20 -#define MAL_SND_CHMAP_TC 21 -#define MAL_SND_CHMAP_TFL 22 -#define MAL_SND_CHMAP_TFR 23 -#define MAL_SND_CHMAP_TFC 24 -#define MAL_SND_CHMAP_TRL 25 -#define MAL_SND_CHMAP_TRR 26 -#define MAL_SND_CHMAP_TRC 27 -#define MAL_SND_CHMAP_TFLC 28 -#define MAL_SND_CHMAP_TFRC 29 -#define MAL_SND_CHMAP_TSL 30 -#define MAL_SND_CHMAP_TSR 31 -#define MAL_SND_CHMAP_LLFE 32 -#define MAL_SND_CHMAP_RLFE 33 -#define MAL_SND_CHMAP_BC 34 -#define MAL_SND_CHMAP_BLC 35 -#define MAL_SND_CHMAP_BRC 36 - -// Open mode flags. -#define MAL_SND_PCM_NO_AUTO_RESAMPLE 0x00010000 -#define MAL_SND_PCM_NO_AUTO_CHANNELS 0x00020000 -#define MAL_SND_PCM_NO_AUTO_FORMAT 0x00040000 -#endif - -typedef int (* mal_snd_pcm_open_proc) (mal_snd_pcm_t **pcm, const char *name, mal_snd_pcm_stream_t stream, int mode); -typedef int (* mal_snd_pcm_close_proc) (mal_snd_pcm_t *pcm); -typedef size_t (* mal_snd_pcm_hw_params_sizeof_proc) (void); -typedef int (* mal_snd_pcm_hw_params_any_proc) (mal_snd_pcm_t *pcm, mal_snd_pcm_hw_params_t *params); -typedef int (* mal_snd_pcm_hw_params_set_format_proc) (mal_snd_pcm_t *pcm, mal_snd_pcm_hw_params_t *params, mal_snd_pcm_format_t val); -typedef int (* mal_snd_pcm_hw_params_set_format_first_proc) (mal_snd_pcm_t *pcm, mal_snd_pcm_hw_params_t *params, mal_snd_pcm_format_t *format); -typedef void (* mal_snd_pcm_hw_params_get_format_mask_proc) (mal_snd_pcm_hw_params_t *params, mal_snd_pcm_format_mask_t *mask); -typedef int (* mal_snd_pcm_hw_params_set_channels_near_proc) (mal_snd_pcm_t *pcm, mal_snd_pcm_hw_params_t *params, unsigned int *val); -typedef int (* mal_snd_pcm_hw_params_set_rate_resample_proc) (mal_snd_pcm_t *pcm, mal_snd_pcm_hw_params_t *params, unsigned int val); -typedef int (* mal_snd_pcm_hw_params_set_rate_near_proc) (mal_snd_pcm_t *pcm, mal_snd_pcm_hw_params_t *params, unsigned int *val, int *dir); -typedef int (* mal_snd_pcm_hw_params_set_buffer_size_near_proc)(mal_snd_pcm_t *pcm, mal_snd_pcm_hw_params_t *params, mal_snd_pcm_uframes_t *val); -typedef int (* mal_snd_pcm_hw_params_set_periods_near_proc) (mal_snd_pcm_t *pcm, mal_snd_pcm_hw_params_t *params, unsigned int *val, int *dir); -typedef int (* mal_snd_pcm_hw_params_set_access_proc) (mal_snd_pcm_t *pcm, mal_snd_pcm_hw_params_t *params, mal_snd_pcm_access_t _access); -typedef int (* mal_snd_pcm_hw_params_get_format_proc) (const mal_snd_pcm_hw_params_t *params, mal_snd_pcm_format_t *format); -typedef int (* mal_snd_pcm_hw_params_get_channels_proc) (const mal_snd_pcm_hw_params_t *params, unsigned int *val); -typedef int (* mal_snd_pcm_hw_params_get_channels_min_proc) (const mal_snd_pcm_hw_params_t *params, unsigned int *val); -typedef int (* mal_snd_pcm_hw_params_get_channels_max_proc) (const mal_snd_pcm_hw_params_t *params, unsigned int *val); -typedef int (* mal_snd_pcm_hw_params_get_rate_proc) (const mal_snd_pcm_hw_params_t *params, unsigned int *rate, int *dir); -typedef int (* mal_snd_pcm_hw_params_get_rate_min_proc) (const mal_snd_pcm_hw_params_t *params, unsigned int *rate, int *dir); -typedef int (* mal_snd_pcm_hw_params_get_rate_max_proc) (const mal_snd_pcm_hw_params_t *params, unsigned int *rate, int *dir); -typedef int (* mal_snd_pcm_hw_params_get_buffer_size_proc) (const mal_snd_pcm_hw_params_t *params, mal_snd_pcm_uframes_t *val); -typedef int (* mal_snd_pcm_hw_params_get_periods_proc) (const mal_snd_pcm_hw_params_t *params, unsigned int *val, int *dir); -typedef int (* mal_snd_pcm_hw_params_get_access_proc) (const mal_snd_pcm_hw_params_t *params, mal_snd_pcm_access_t *_access); -typedef int (* mal_snd_pcm_hw_params_proc) (mal_snd_pcm_t *pcm, mal_snd_pcm_hw_params_t *params); -typedef size_t (* mal_snd_pcm_sw_params_sizeof_proc) (void); -typedef int (* mal_snd_pcm_sw_params_current_proc) (mal_snd_pcm_t *pcm, mal_snd_pcm_sw_params_t *params); -typedef int (* mal_snd_pcm_sw_params_set_avail_min_proc) (mal_snd_pcm_t *pcm, mal_snd_pcm_sw_params_t *params, mal_snd_pcm_uframes_t val); -typedef int (* mal_snd_pcm_sw_params_set_start_threshold_proc) (mal_snd_pcm_t *pcm, mal_snd_pcm_sw_params_t *params, mal_snd_pcm_uframes_t val); -typedef int (* mal_snd_pcm_sw_params_proc) (mal_snd_pcm_t *pcm, mal_snd_pcm_sw_params_t *params); -typedef size_t (* mal_snd_pcm_format_mask_sizeof_proc) (void); -typedef int (* mal_snd_pcm_format_mask_test_proc) (const mal_snd_pcm_format_mask_t *mask, mal_snd_pcm_format_t val); -typedef mal_snd_pcm_chmap_t * (* mal_snd_pcm_get_chmap_proc) (mal_snd_pcm_t *pcm); -typedef int (* mal_snd_pcm_prepare_proc) (mal_snd_pcm_t *pcm); -typedef int (* mal_snd_pcm_start_proc) (mal_snd_pcm_t *pcm); -typedef int (* mal_snd_pcm_drop_proc) (mal_snd_pcm_t *pcm); -typedef int (* mal_snd_device_name_hint_proc) (int card, const char *iface, void ***hints); -typedef char * (* mal_snd_device_name_get_hint_proc) (const void *hint, const char *id); -typedef int (* mal_snd_card_get_index_proc) (const char *name); -typedef int (* mal_snd_device_name_free_hint_proc) (void **hints); -typedef int (* mal_snd_pcm_mmap_begin_proc) (mal_snd_pcm_t *pcm, const mal_snd_pcm_channel_area_t **areas, mal_snd_pcm_uframes_t *offset, mal_snd_pcm_uframes_t *frames); -typedef mal_snd_pcm_sframes_t (* mal_snd_pcm_mmap_commit_proc) (mal_snd_pcm_t *pcm, mal_snd_pcm_uframes_t offset, mal_snd_pcm_uframes_t frames); -typedef int (* mal_snd_pcm_recover_proc) (mal_snd_pcm_t *pcm, int err, int silent); -typedef mal_snd_pcm_sframes_t (* mal_snd_pcm_readi_proc) (mal_snd_pcm_t *pcm, void *buffer, mal_snd_pcm_uframes_t size); -typedef mal_snd_pcm_sframes_t (* mal_snd_pcm_writei_proc) (mal_snd_pcm_t *pcm, const void *buffer, mal_snd_pcm_uframes_t size); -typedef mal_snd_pcm_sframes_t (* mal_snd_pcm_avail_proc) (mal_snd_pcm_t *pcm); -typedef mal_snd_pcm_sframes_t (* mal_snd_pcm_avail_update_proc) (mal_snd_pcm_t *pcm); -typedef int (* mal_snd_pcm_wait_proc) (mal_snd_pcm_t *pcm, int timeout); -typedef int (* mal_snd_pcm_info_proc) (mal_snd_pcm_t *pcm, mal_snd_pcm_info_t* info); -typedef size_t (* mal_snd_pcm_info_sizeof_proc) (); -typedef const char* (* mal_snd_pcm_info_get_name_proc) (const mal_snd_pcm_info_t* info); -typedef int (* mal_snd_config_update_free_global_proc) (); - -// This array specifies each of the common devices that can be used for both playback and capture. -const char* g_malCommonDeviceNamesALSA[] = { - "default", - "null", - "pulse", - "jack" -}; - -// This array allows us to blacklist specific playback devices. -const char* g_malBlacklistedPlaybackDeviceNamesALSA[] = { - "" -}; - -// This array allows us to blacklist specific capture devices. -const char* g_malBlacklistedCaptureDeviceNamesALSA[] = { - "" -}; - - -// This array allows mini_al to control device-specific default buffer sizes. This uses a scaling factor. Order is important. If -// any part of the string is present in the device's name, the associated scale will be used. -static struct -{ - const char* name; - float scale; -} g_malDefaultBufferSizeScalesALSA[] = { - {"bcm2835 IEC958/HDMI", 2.0f}, - {"bcm2835 ALSA", 2.0f} -}; - -float mal_find_default_buffer_size_scale__alsa(const char* deviceName) -{ - if (deviceName == NULL) { - return 1; - } - - for (size_t i = 0; i < mal_countof(g_malDefaultBufferSizeScalesALSA); ++i) { - if (strstr(g_malDefaultBufferSizeScalesALSA[i].name, deviceName) != NULL) { - return g_malDefaultBufferSizeScalesALSA[i].scale; - } - } - - return 1; -} - -mal_snd_pcm_format_t mal_convert_mal_format_to_alsa_format(mal_format format) -{ - mal_snd_pcm_format_t ALSAFormats[] = { - MAL_SND_PCM_FORMAT_UNKNOWN, // mal_format_unknown - MAL_SND_PCM_FORMAT_U8, // mal_format_u8 - MAL_SND_PCM_FORMAT_S16_LE, // mal_format_s16 - MAL_SND_PCM_FORMAT_S24_3LE, // mal_format_s24 - MAL_SND_PCM_FORMAT_S32_LE, // mal_format_s32 - MAL_SND_PCM_FORMAT_FLOAT_LE // mal_format_f32 - }; - - if (mal_is_big_endian()) { - ALSAFormats[0] = MAL_SND_PCM_FORMAT_UNKNOWN; - ALSAFormats[1] = MAL_SND_PCM_FORMAT_U8; - ALSAFormats[2] = MAL_SND_PCM_FORMAT_S16_BE; - ALSAFormats[3] = MAL_SND_PCM_FORMAT_S24_3BE; - ALSAFormats[4] = MAL_SND_PCM_FORMAT_S32_BE; - ALSAFormats[5] = MAL_SND_PCM_FORMAT_FLOAT_BE; - } - - - return ALSAFormats[format]; -} - -mal_format mal_convert_alsa_format_to_mal_format(mal_snd_pcm_format_t formatALSA) -{ - if (mal_is_little_endian()) { - switch (formatALSA) { - case MAL_SND_PCM_FORMAT_S16_LE: return mal_format_s16; - case MAL_SND_PCM_FORMAT_S24_3LE: return mal_format_s24; - case MAL_SND_PCM_FORMAT_S32_LE: return mal_format_s32; - case MAL_SND_PCM_FORMAT_FLOAT_LE: return mal_format_f32; - default: break; - } - } else { - switch (formatALSA) { - case MAL_SND_PCM_FORMAT_S16_BE: return mal_format_s16; - case MAL_SND_PCM_FORMAT_S24_3BE: return mal_format_s24; - case MAL_SND_PCM_FORMAT_S32_BE: return mal_format_s32; - case MAL_SND_PCM_FORMAT_FLOAT_BE: return mal_format_f32; - default: break; - } - } - - // Endian agnostic. - switch (formatALSA) { - case MAL_SND_PCM_FORMAT_U8: return mal_format_u8; - default: return mal_format_unknown; - } -} - -mal_channel mal_convert_alsa_channel_position_to_mal_channel(unsigned int alsaChannelPos) -{ - switch (alsaChannelPos) - { - case MAL_SND_CHMAP_MONO: return MAL_CHANNEL_MONO; - case MAL_SND_CHMAP_FL: return MAL_CHANNEL_FRONT_LEFT; - case MAL_SND_CHMAP_FR: return MAL_CHANNEL_FRONT_RIGHT; - case MAL_SND_CHMAP_RL: return MAL_CHANNEL_BACK_LEFT; - case MAL_SND_CHMAP_RR: return MAL_CHANNEL_BACK_RIGHT; - case MAL_SND_CHMAP_FC: return MAL_CHANNEL_FRONT_CENTER; - case MAL_SND_CHMAP_LFE: return MAL_CHANNEL_LFE; - case MAL_SND_CHMAP_SL: return MAL_CHANNEL_SIDE_LEFT; - case MAL_SND_CHMAP_SR: return MAL_CHANNEL_SIDE_RIGHT; - case MAL_SND_CHMAP_RC: return MAL_CHANNEL_BACK_CENTER; - case MAL_SND_CHMAP_FLC: return MAL_CHANNEL_FRONT_LEFT_CENTER; - case MAL_SND_CHMAP_FRC: return MAL_CHANNEL_FRONT_RIGHT_CENTER; - case MAL_SND_CHMAP_RLC: return 0; - case MAL_SND_CHMAP_RRC: return 0; - case MAL_SND_CHMAP_FLW: return 0; - case MAL_SND_CHMAP_FRW: return 0; - case MAL_SND_CHMAP_FLH: return 0; - case MAL_SND_CHMAP_FCH: return 0; - case MAL_SND_CHMAP_FRH: return 0; - case MAL_SND_CHMAP_TC: return MAL_CHANNEL_TOP_CENTER; - case MAL_SND_CHMAP_TFL: return MAL_CHANNEL_TOP_FRONT_LEFT; - case MAL_SND_CHMAP_TFR: return MAL_CHANNEL_TOP_FRONT_RIGHT; - case MAL_SND_CHMAP_TFC: return MAL_CHANNEL_TOP_FRONT_CENTER; - case MAL_SND_CHMAP_TRL: return MAL_CHANNEL_TOP_BACK_LEFT; - case MAL_SND_CHMAP_TRR: return MAL_CHANNEL_TOP_BACK_RIGHT; - case MAL_SND_CHMAP_TRC: return MAL_CHANNEL_TOP_BACK_CENTER; - default: break; - } - - return 0; -} - -mal_bool32 mal_is_common_device_name__alsa(const char* name) -{ - for (size_t iName = 0; iName < mal_countof(g_malCommonDeviceNamesALSA); ++iName) { - if (mal_strcmp(name, g_malCommonDeviceNamesALSA[iName]) == 0) { - return MAL_TRUE; - } - } - - return MAL_FALSE; -} - - -mal_bool32 mal_is_playback_device_blacklisted__alsa(const char* name) -{ - for (size_t iName = 0; iName < mal_countof(g_malBlacklistedPlaybackDeviceNamesALSA); ++iName) { - if (mal_strcmp(name, g_malBlacklistedPlaybackDeviceNamesALSA[iName]) == 0) { - return MAL_TRUE; - } - } - - return MAL_FALSE; -} - -mal_bool32 mal_is_capture_device_blacklisted__alsa(const char* name) -{ - for (size_t iName = 0; iName < mal_countof(g_malBlacklistedCaptureDeviceNamesALSA); ++iName) { - if (mal_strcmp(name, g_malBlacklistedCaptureDeviceNamesALSA[iName]) == 0) { - return MAL_TRUE; - } - } - - return MAL_FALSE; -} - -mal_bool32 mal_is_device_blacklisted__alsa(mal_device_type deviceType, const char* name) -{ - if (deviceType == mal_device_type_playback) { - return mal_is_playback_device_blacklisted__alsa(name); - } else { - return mal_is_capture_device_blacklisted__alsa(name); - } -} - - -const char* mal_find_char(const char* str, char c, int* index) -{ - int i = 0; - for (;;) { - if (str[i] == '\0') { - if (index) *index = -1; - return NULL; - } - - if (str[i] == c) { - if (index) *index = i; - return str + i; - } - - i += 1; - } - - // Should never get here, but treat it as though the character was not found to make me feel - // better inside. - if (index) *index = -1; - return NULL; -} - -mal_bool32 mal_is_device_name_in_hw_format__alsa(const char* hwid) -{ - // This function is just checking whether or not hwid is in "hw:%d,%d" format. - - if (hwid == NULL) { - return MAL_FALSE; - } - - if (hwid[0] != 'h' || hwid[1] != 'w' || hwid[2] != ':') { - return MAL_FALSE; - } - - hwid += 3; - - int commaPos; - const char* dev = mal_find_char(hwid, ',', &commaPos); - if (dev == NULL) { - return MAL_FALSE; - } else { - dev += 1; // Skip past the ",". - } - - // Check if the part between the ":" and the "," contains only numbers. If not, return false. - for (int i = 0; i < commaPos; ++i) { - if (hwid[i] < '0' || hwid[i] > '9') { - return MAL_FALSE; - } - } - - // Check if everything after the "," is numeric. If not, return false. - int i = 0; - while (dev[i] != '\0') { - if (dev[i] < '0' || dev[i] > '9') { - return MAL_FALSE; - } - i += 1; - } - - return MAL_TRUE; -} - -int mal_convert_device_name_to_hw_format__alsa(mal_context* pContext, char* dst, size_t dstSize, const char* src) // Returns 0 on success, non-0 on error. -{ - // src should look something like this: "hw:CARD=I82801AAICH,DEV=0" - - if (dst == NULL) return -1; - if (dstSize < 7) return -1; // Absolute minimum size of the output buffer is 7 bytes. - - *dst = '\0'; // Safety. - if (src == NULL) return -1; - - // If the input name is already in "hw:%d,%d" format, just return that verbatim. - if (mal_is_device_name_in_hw_format__alsa(src)) { - return mal_strcpy_s(dst, dstSize, src); - } - - - int colonPos; - src = mal_find_char(src, ':', &colonPos); - if (src == NULL) { - return -1; // Couldn't find a colon - } - - char card[256]; - - int commaPos; - const char* dev = mal_find_char(src, ',', &commaPos); - if (dev == NULL) { - dev = "0"; - mal_strncpy_s(card, sizeof(card), src+6, (size_t)-1); // +6 = ":CARD=" - } else { - dev = dev + 5; // +5 = ",DEV=" - mal_strncpy_s(card, sizeof(card), src+6, commaPos-6); // +6 = ":CARD=" - } - - int cardIndex = ((mal_snd_card_get_index_proc)pContext->alsa.snd_card_get_index)(card); - if (cardIndex < 0) { - return -2; // Failed to retrieve the card index. - } - - //printf("TESTING: CARD=%s,DEV=%s\n", card, dev); - - - // Construction. - dst[0] = 'h'; dst[1] = 'w'; dst[2] = ':'; - if (mal_itoa_s(cardIndex, dst+3, dstSize-3, 10) != 0) { - return -3; - } - if (mal_strcat_s(dst, dstSize, ",") != 0) { - return -3; - } - if (mal_strcat_s(dst, dstSize, dev) != 0) { - return -3; - } - - return 0; -} - -mal_bool32 mal_does_id_exist_in_list__alsa(mal_device_id* pUniqueIDs, mal_uint32 count, const char* pHWID) -{ - mal_assert(pHWID != NULL); - - for (mal_uint32 i = 0; i < count; ++i) { - if (mal_strcmp(pUniqueIDs[i].alsa, pHWID) == 0) { - return MAL_TRUE; - } - } - - return MAL_FALSE; -} - - -mal_result mal_context_open_pcm__alsa(mal_context* pContext, mal_share_mode shareMode, mal_device_type type, const mal_device_id* pDeviceID, mal_snd_pcm_t** ppPCM) -{ - mal_assert(pContext != NULL); - mal_assert(ppPCM != NULL); - - *ppPCM = NULL; - - mal_snd_pcm_t* pPCM = NULL; - - - - mal_snd_pcm_stream_t stream = (type == mal_device_type_playback) ? MAL_SND_PCM_STREAM_PLAYBACK : MAL_SND_PCM_STREAM_CAPTURE; - int openMode = MAL_SND_PCM_NO_AUTO_RESAMPLE | MAL_SND_PCM_NO_AUTO_CHANNELS | MAL_SND_PCM_NO_AUTO_FORMAT; - - if (pDeviceID == NULL) { - // We're opening the default device. I don't know if trying anything other than "default" is necessary, but it makes - // me feel better to try as hard as we can get to get _something_ working. - const char* defaultDeviceNames[] = { - "default", - NULL, - NULL, - NULL, - NULL, - NULL, - NULL - }; - - if (shareMode == mal_share_mode_exclusive) { - defaultDeviceNames[1] = "hw"; - defaultDeviceNames[2] = "hw:0"; - defaultDeviceNames[3] = "hw:0,0"; - } else { - if (type == mal_device_type_playback) { - defaultDeviceNames[1] = "dmix"; - defaultDeviceNames[2] = "dmix:0"; - defaultDeviceNames[3] = "dmix:0,0"; - } else { - defaultDeviceNames[1] = "dsnoop"; - defaultDeviceNames[2] = "dsnoop:0"; - defaultDeviceNames[3] = "dsnoop:0,0"; - } - defaultDeviceNames[4] = "hw"; - defaultDeviceNames[5] = "hw:0"; - defaultDeviceNames[6] = "hw:0,0"; - } - - mal_bool32 isDeviceOpen = MAL_FALSE; - for (size_t i = 0; i < mal_countof(defaultDeviceNames); ++i) { - if (defaultDeviceNames[i] != NULL && defaultDeviceNames[i][0] != '\0') { - if (((mal_snd_pcm_open_proc)pContext->alsa.snd_pcm_open)(&pPCM, defaultDeviceNames[i], stream, openMode) == 0) { - isDeviceOpen = MAL_TRUE; - break; - } - } - } - - if (!isDeviceOpen) { - return mal_context_post_error(pContext, NULL, MAL_LOG_LEVEL_ERROR, "[ALSA] snd_pcm_open() failed when trying to open an appropriate default device.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - } else { - // We're trying to open a specific device. There's a few things to consider here: - // - // mini_al recongnizes a special format of device id that excludes the "hw", "dmix", etc. prefix. It looks like this: ":0,0", ":0,1", etc. When - // an ID of this format is specified, it indicates to mini_al that it can try different combinations of plugins ("hw", "dmix", etc.) until it - // finds an appropriate one that works. This comes in very handy when trying to open a device in shared mode ("dmix"), vs exclusive mode ("hw"). - - // May end up needing to make small adjustments to the ID, so make a copy. - mal_device_id deviceID = *pDeviceID; - - mal_bool32 isDeviceOpen = MAL_FALSE; - if (deviceID.alsa[0] != ':') { - // The ID is not in ":0,0" format. Use the ID exactly as-is. - if (((mal_snd_pcm_open_proc)pContext->alsa.snd_pcm_open)(&pPCM, deviceID.alsa, stream, openMode) == 0) { - isDeviceOpen = MAL_TRUE; - } - } else { - // The ID is in ":0,0" format. Try different plugins depending on the shared mode. - if (deviceID.alsa[1] == '\0') { - deviceID.alsa[0] = '\0'; // An ID of ":" should be converted to "". - } - - char hwid[256]; - if (shareMode == mal_share_mode_shared) { - if (type == mal_device_type_playback) { - mal_strcpy_s(hwid, sizeof(hwid), "dmix"); - } else { - mal_strcpy_s(hwid, sizeof(hwid), "dsnoop"); - } - - if (mal_strcat_s(hwid, sizeof(hwid), deviceID.alsa) == 0) { - if (((mal_snd_pcm_open_proc)pContext->alsa.snd_pcm_open)(&pPCM, hwid, stream, openMode) == 0) { - isDeviceOpen = MAL_TRUE; - } - } - } - - // If at this point we still don't have an open device it means we're either preferencing exclusive mode or opening with "dmix"/"dsnoop" failed. - if (!isDeviceOpen) { - mal_strcpy_s(hwid, sizeof(hwid), "hw"); - if (mal_strcat_s(hwid, sizeof(hwid), deviceID.alsa) == 0) { - if (((mal_snd_pcm_open_proc)pContext->alsa.snd_pcm_open)(&pPCM, hwid, stream, openMode) == 0) { - isDeviceOpen = MAL_TRUE; - } - } - } - } - - if (!isDeviceOpen) { - return mal_context_post_error(pContext, NULL, MAL_LOG_LEVEL_ERROR, "[ALSA] snd_pcm_open() failed.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - } - - *ppPCM = pPCM; - return MAL_SUCCESS; -} - - -mal_bool32 mal_context_is_device_id_equal__alsa(mal_context* pContext, const mal_device_id* pID0, const mal_device_id* pID1) -{ - mal_assert(pContext != NULL); - mal_assert(pID0 != NULL); - mal_assert(pID1 != NULL); - (void)pContext; - - return mal_strcmp(pID0->alsa, pID1->alsa) == 0; -} - -mal_result mal_context_enumerate_devices__alsa(mal_context* pContext, mal_enum_devices_callback_proc callback, void* pUserData) -{ - mal_assert(pContext != NULL); - mal_assert(callback != NULL); - - mal_bool32 cbResult = MAL_TRUE; - - mal_mutex_lock(&pContext->alsa.internalDeviceEnumLock); - - char** ppDeviceHints; - if (((mal_snd_device_name_hint_proc)pContext->alsa.snd_device_name_hint)(-1, "pcm", (void***)&ppDeviceHints) < 0) { - mal_mutex_unlock(&pContext->alsa.internalDeviceEnumLock); - return MAL_NO_BACKEND; - } - - mal_device_id* pUniqueIDs = NULL; - mal_uint32 uniqueIDCount = 0; - - char** ppNextDeviceHint = ppDeviceHints; - while (*ppNextDeviceHint != NULL) { - char* NAME = ((mal_snd_device_name_get_hint_proc)pContext->alsa.snd_device_name_get_hint)(*ppNextDeviceHint, "NAME"); - char* DESC = ((mal_snd_device_name_get_hint_proc)pContext->alsa.snd_device_name_get_hint)(*ppNextDeviceHint, "DESC"); - char* IOID = ((mal_snd_device_name_get_hint_proc)pContext->alsa.snd_device_name_get_hint)(*ppNextDeviceHint, "IOID"); - - mal_device_type deviceType = mal_device_type_playback; - if ((IOID == NULL || mal_strcmp(IOID, "Output") == 0)) { - deviceType = mal_device_type_playback; - } - if ((IOID != NULL && mal_strcmp(IOID, "Input" ) == 0)) { - deviceType = mal_device_type_capture; - } - - mal_bool32 stopEnumeration = MAL_FALSE; -#if 0 - printf("NAME: %s\n", NAME); - printf("DESC: %s\n", DESC); - printf("IOID: %s\n", IOID); - - char hwid2[256]; - mal_convert_device_name_to_hw_format__alsa(pContext, hwid2, sizeof(hwid2), NAME); - printf("DEVICE ID: %s\n\n", hwid2); -#endif - - char hwid[sizeof(pUniqueIDs->alsa)]; - if (NAME != NULL) { - if (pContext->config.alsa.useVerboseDeviceEnumeration) { - // Verbose mode. Use the name exactly as-is. - mal_strncpy_s(hwid, sizeof(hwid), NAME, (size_t)-1); - } else { - // Simplified mode. Use ":%d,%d" format. - if (mal_convert_device_name_to_hw_format__alsa(pContext, hwid, sizeof(hwid), NAME) == 0) { - // At this point, hwid looks like "hw:0,0". In simplified enumeration mode, we actually want to strip off the - // plugin name so it looks like ":0,0". The reason for this is that this special format is detected at device - // initialization time and is used as an indicator to try and use the most appropriate plugin depending on the - // device type and sharing mode. - char* dst = hwid; - char* src = hwid+2; - while ((*dst++ = *src++)); - } else { - // Conversion to "hw:%d,%d" failed. Just use the name as-is. - mal_strncpy_s(hwid, sizeof(hwid), NAME, (size_t)-1); - } - - if (mal_does_id_exist_in_list__alsa(pUniqueIDs, uniqueIDCount, hwid)) { - goto next_device; // The device has already been enumerated. Move on to the next one. - } else { - // The device has not yet been enumerated. Make sure it's added to our list so that it's not enumerated again. - mal_device_id* pNewUniqueIDs = (mal_device_id*)mal_realloc(pUniqueIDs, sizeof(*pUniqueIDs) * (uniqueIDCount + 1)); - if (pNewUniqueIDs == NULL) { - goto next_device; // Failed to allocate memory. - } - - pUniqueIDs = pNewUniqueIDs; - mal_copy_memory(pUniqueIDs[uniqueIDCount].alsa, hwid, sizeof(hwid)); - uniqueIDCount += 1; - } - } - } else { - mal_zero_memory(hwid, sizeof(hwid)); - } - - mal_device_info deviceInfo; - mal_zero_object(&deviceInfo); - mal_strncpy_s(deviceInfo.id.alsa, sizeof(deviceInfo.id.alsa), hwid, (size_t)-1); - - // DESC is the friendly name. We treat this slightly differently depending on whether or not we are using verbose - // device enumeration. In verbose mode we want to take the entire description so that the end-user can distinguish - // between the subdevices of each card/dev pair. In simplified mode, however, we only want the first part of the - // description. - // - // The value in DESC seems to be split into two lines, with the first line being the name of the device and the - // second line being a description of the device. I don't like having the description be across two lines because - // it makes formatting ugly and annoying. I'm therefore deciding to put it all on a single line with the second line - // being put into parentheses. In simplified mode I'm just stripping the second line entirely. - if (DESC != NULL) { - int lfPos; - const char* line2 = mal_find_char(DESC, '\n', &lfPos); - if (line2 != NULL) { - line2 += 1; // Skip past the new-line character. - - if (pContext->config.alsa.useVerboseDeviceEnumeration) { - // Verbose mode. Put the second line in brackets. - mal_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), DESC, lfPos); - mal_strcat_s (deviceInfo.name, sizeof(deviceInfo.name), " ("); - mal_strcat_s (deviceInfo.name, sizeof(deviceInfo.name), line2); - mal_strcat_s (deviceInfo.name, sizeof(deviceInfo.name), ")"); - } else { - // Simplified mode. Strip the second line entirely. - mal_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), DESC, lfPos); - } - } else { - // There's no second line. Just copy the whole description. - mal_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), DESC, (size_t)-1); - } - } - - if (!mal_is_device_blacklisted__alsa(deviceType, NAME)) { - cbResult = callback(pContext, deviceType, &deviceInfo, pUserData); - } - - // Some devices are both playback and capture, but they are only enumerated by ALSA once. We need to fire the callback - // again for the other device type in this case. We do this for known devices. - if (cbResult) { - if (mal_is_common_device_name__alsa(NAME)) { - if (deviceType == mal_device_type_playback) { - if (!mal_is_capture_device_blacklisted__alsa(NAME)) { - cbResult = callback(pContext, mal_device_type_capture, &deviceInfo, pUserData); - } - } else { - if (!mal_is_playback_device_blacklisted__alsa(NAME)) { - cbResult = callback(pContext, mal_device_type_playback, &deviceInfo, pUserData); - } - } - } - } - - if (cbResult == MAL_FALSE) { - stopEnumeration = MAL_TRUE; - } - - next_device: - free(NAME); - free(DESC); - free(IOID); - ppNextDeviceHint += 1; - - // We need to stop enumeration if the callback returned false. - if (stopEnumeration) { - break; - } - } - - mal_free(pUniqueIDs); - ((mal_snd_device_name_free_hint_proc)pContext->alsa.snd_device_name_free_hint)((void**)ppDeviceHints); - - mal_mutex_unlock(&pContext->alsa.internalDeviceEnumLock); - - return MAL_SUCCESS; -} - - -typedef struct -{ - mal_device_type deviceType; - const mal_device_id* pDeviceID; - mal_share_mode shareMode; - mal_device_info* pDeviceInfo; - mal_bool32 foundDevice; -} mal_context_get_device_info_enum_callback_data__alsa; - -mal_bool32 mal_context_get_device_info_enum_callback__alsa(mal_context* pContext, mal_device_type deviceType, const mal_device_info* pDeviceInfo, void* pUserData) -{ - mal_context_get_device_info_enum_callback_data__alsa* pData = (mal_context_get_device_info_enum_callback_data__alsa*)pUserData; - mal_assert(pData != NULL); - - if (pData->pDeviceID == NULL && mal_strcmp(pDeviceInfo->id.alsa, "default") == 0) { - mal_strncpy_s(pData->pDeviceInfo->name, sizeof(pData->pDeviceInfo->name), pDeviceInfo->name, (size_t)-1); - pData->foundDevice = MAL_TRUE; - } else { - if (pData->deviceType == deviceType && mal_context_is_device_id_equal__alsa(pContext, pData->pDeviceID, &pDeviceInfo->id)) { - mal_strncpy_s(pData->pDeviceInfo->name, sizeof(pData->pDeviceInfo->name), pDeviceInfo->name, (size_t)-1); - pData->foundDevice = MAL_TRUE; - } - } - - // Keep enumerating until we have found the device. - return !pData->foundDevice; -} - -mal_result mal_context_get_device_info__alsa(mal_context* pContext, mal_device_type deviceType, const mal_device_id* pDeviceID, mal_share_mode shareMode, mal_device_info* pDeviceInfo) -{ - mal_assert(pContext != NULL); - - // We just enumerate to find basic information about the device. - mal_context_get_device_info_enum_callback_data__alsa data; - data.deviceType = deviceType; - data.pDeviceID = pDeviceID; - data.shareMode = shareMode; - data.pDeviceInfo = pDeviceInfo; - data.foundDevice = MAL_FALSE; - mal_result result = mal_context_enumerate_devices__alsa(pContext, mal_context_get_device_info_enum_callback__alsa, &data); - if (result != MAL_SUCCESS) { - return result; - } - - if (!data.foundDevice) { - return MAL_NO_DEVICE; - } - - - // For detailed info we need to open the device. - mal_snd_pcm_t* pPCM; - result = mal_context_open_pcm__alsa(pContext, shareMode, deviceType, pDeviceID, &pPCM); - if (result != MAL_SUCCESS) { - return result; - } - - // We need to initialize a HW parameters object in order to know what formats are supported. - mal_snd_pcm_hw_params_t* pHWParams = (mal_snd_pcm_hw_params_t*)alloca(((mal_snd_pcm_hw_params_sizeof_proc)pContext->alsa.snd_pcm_hw_params_sizeof)()); - mal_zero_memory(pHWParams, ((mal_snd_pcm_hw_params_sizeof_proc)pContext->alsa.snd_pcm_hw_params_sizeof)()); - - if (((mal_snd_pcm_hw_params_any_proc)pContext->alsa.snd_pcm_hw_params_any)(pPCM, pHWParams) < 0) { - return mal_context_post_error(pContext, NULL, MAL_LOG_LEVEL_ERROR, "[ALSA] Failed to initialize hardware parameters. snd_pcm_hw_params_any() failed.", MAL_FAILED_TO_CONFIGURE_BACKEND_DEVICE); - } - - int sampleRateDir = 0; - - ((mal_snd_pcm_hw_params_get_channels_min_proc)pContext->alsa.snd_pcm_hw_params_get_channels_min)(pHWParams, &pDeviceInfo->minChannels); - ((mal_snd_pcm_hw_params_get_channels_max_proc)pContext->alsa.snd_pcm_hw_params_get_channels_max)(pHWParams, &pDeviceInfo->maxChannels); - ((mal_snd_pcm_hw_params_get_rate_min_proc)pContext->alsa.snd_pcm_hw_params_get_rate_min)(pHWParams, &pDeviceInfo->minSampleRate, &sampleRateDir); - ((mal_snd_pcm_hw_params_get_rate_max_proc)pContext->alsa.snd_pcm_hw_params_get_rate_max)(pHWParams, &pDeviceInfo->maxSampleRate, &sampleRateDir); - - // Formats. - mal_snd_pcm_format_mask_t* pFormatMask = (mal_snd_pcm_format_mask_t*)alloca(((mal_snd_pcm_format_mask_sizeof_proc)pContext->alsa.snd_pcm_format_mask_sizeof)()); - mal_zero_memory(pFormatMask, ((mal_snd_pcm_format_mask_sizeof_proc)pContext->alsa.snd_pcm_format_mask_sizeof)()); - ((mal_snd_pcm_hw_params_get_format_mask_proc)pContext->alsa.snd_pcm_hw_params_get_format_mask)(pHWParams, pFormatMask); - - pDeviceInfo->formatCount = 0; - if (((mal_snd_pcm_format_mask_test_proc)pContext->alsa.snd_pcm_format_mask_test)(pFormatMask, MAL_SND_PCM_FORMAT_U8)) { - pDeviceInfo->formats[pDeviceInfo->formatCount++] = mal_format_u8; - } - if (((mal_snd_pcm_format_mask_test_proc)pContext->alsa.snd_pcm_format_mask_test)(pFormatMask, MAL_SND_PCM_FORMAT_S16_LE)) { - pDeviceInfo->formats[pDeviceInfo->formatCount++] = mal_format_s16; - } - if (((mal_snd_pcm_format_mask_test_proc)pContext->alsa.snd_pcm_format_mask_test)(pFormatMask, MAL_SND_PCM_FORMAT_S24_3LE)) { - pDeviceInfo->formats[pDeviceInfo->formatCount++] = mal_format_s24; - } - if (((mal_snd_pcm_format_mask_test_proc)pContext->alsa.snd_pcm_format_mask_test)(pFormatMask, MAL_SND_PCM_FORMAT_S32_LE)) { - pDeviceInfo->formats[pDeviceInfo->formatCount++] = mal_format_s32; - } - if (((mal_snd_pcm_format_mask_test_proc)pContext->alsa.snd_pcm_format_mask_test)(pFormatMask, MAL_SND_PCM_FORMAT_FLOAT_LE)) { - pDeviceInfo->formats[pDeviceInfo->formatCount++] = mal_format_f32; - } - - ((mal_snd_pcm_close_proc)pContext->alsa.snd_pcm_close)(pPCM); - return MAL_SUCCESS; -} - - -// Waits for a number of frames to become available for either capture or playback. The return -// value is the number of frames available. -// -// This will return early if the main loop is broken with mal_device__break_main_loop(). -mal_uint32 mal_device__wait_for_frames__alsa(mal_device* pDevice, mal_bool32* pRequiresRestart) -{ - mal_assert(pDevice != NULL); - - if (pRequiresRestart) *pRequiresRestart = MAL_FALSE; - - // I want it so that this function returns the period size in frames. We just wait until that number of frames are available and then return. - mal_uint32 periodSizeInFrames = pDevice->bufferSizeInFrames / pDevice->periods; - while (!pDevice->alsa.breakFromMainLoop) { - mal_snd_pcm_sframes_t framesAvailable = ((mal_snd_pcm_avail_update_proc)pDevice->pContext->alsa.snd_pcm_avail_update)((mal_snd_pcm_t*)pDevice->alsa.pPCM); - if (framesAvailable < 0) { - if (framesAvailable == -EPIPE) { - if (((mal_snd_pcm_recover_proc)pDevice->pContext->alsa.snd_pcm_recover)((mal_snd_pcm_t*)pDevice->alsa.pPCM, framesAvailable, MAL_TRUE) < 0) { - return 0; - } - - // A device recovery means a restart for mmap mode. - if (pRequiresRestart) { - *pRequiresRestart = MAL_TRUE; - } - - // Try again, but if it fails this time just return an error. - framesAvailable = ((mal_snd_pcm_avail_update_proc)pDevice->pContext->alsa.snd_pcm_avail_update)((mal_snd_pcm_t*)pDevice->alsa.pPCM); - if (framesAvailable < 0) { - return 0; - } - } - } - - if (framesAvailable >= periodSizeInFrames) { - return periodSizeInFrames; - } - - if (framesAvailable < periodSizeInFrames) { - // Less than a whole period is available so keep waiting. - int waitResult = ((mal_snd_pcm_wait_proc)pDevice->pContext->alsa.snd_pcm_wait)((mal_snd_pcm_t*)pDevice->alsa.pPCM, -1); - if (waitResult < 0) { - if (waitResult == -EPIPE) { - if (((mal_snd_pcm_recover_proc)pDevice->pContext->alsa.snd_pcm_recover)((mal_snd_pcm_t*)pDevice->alsa.pPCM, waitResult, MAL_TRUE) < 0) { - return 0; - } - - // A device recovery means a restart for mmap mode. - if (pRequiresRestart) { - *pRequiresRestart = MAL_TRUE; - } - } - } - } - } - - // We'll get here if the loop was terminated. Just return whatever's available. - mal_snd_pcm_sframes_t framesAvailable = ((mal_snd_pcm_avail_update_proc)pDevice->pContext->alsa.snd_pcm_avail_update)((mal_snd_pcm_t*)pDevice->alsa.pPCM); - if (framesAvailable < 0) { - return 0; - } - - return framesAvailable; -} - -mal_bool32 mal_device_write__alsa(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - if (!mal_device_is_started(pDevice) && mal_device__get_state(pDevice) != MAL_STATE_STARTING) { - return MAL_FALSE; - } - if (pDevice->alsa.breakFromMainLoop) { - return MAL_FALSE; - } - - if (pDevice->alsa.isUsingMMap) { - // mmap. - mal_bool32 requiresRestart; - mal_uint32 framesAvailable = mal_device__wait_for_frames__alsa(pDevice, &requiresRestart); - if (framesAvailable == 0) { - return MAL_FALSE; - } - - // Don't bother asking the client for more audio data if we're just stopping the device anyway. - if (pDevice->alsa.breakFromMainLoop) { - return MAL_FALSE; - } - - const mal_snd_pcm_channel_area_t* pAreas; - mal_snd_pcm_uframes_t mappedOffset; - mal_snd_pcm_uframes_t mappedFrames = framesAvailable; - while (framesAvailable > 0) { - int result = ((mal_snd_pcm_mmap_begin_proc)pDevice->pContext->alsa.snd_pcm_mmap_begin)((mal_snd_pcm_t*)pDevice->alsa.pPCM, &pAreas, &mappedOffset, &mappedFrames); - if (result < 0) { - return MAL_FALSE; - } - - if (mappedFrames > 0) { - void* pBuffer = (mal_uint8*)pAreas[0].addr + ((pAreas[0].first + (mappedOffset * pAreas[0].step)) / 8); - mal_device__read_frames_from_client(pDevice, mappedFrames, pBuffer); - } - - result = ((mal_snd_pcm_mmap_commit_proc)pDevice->pContext->alsa.snd_pcm_mmap_commit)((mal_snd_pcm_t*)pDevice->alsa.pPCM, mappedOffset, mappedFrames); - if (result < 0 || (mal_snd_pcm_uframes_t)result != mappedFrames) { - ((mal_snd_pcm_recover_proc)pDevice->pContext->alsa.snd_pcm_recover)((mal_snd_pcm_t*)pDevice->alsa.pPCM, result, MAL_TRUE); - return MAL_FALSE; - } - - if (requiresRestart) { - if (((mal_snd_pcm_start_proc)pDevice->pContext->alsa.snd_pcm_start)((mal_snd_pcm_t*)pDevice->alsa.pPCM) < 0) { - return MAL_FALSE; - } - } - - if (framesAvailable >= mappedFrames) { - framesAvailable -= mappedFrames; - } else { - framesAvailable = 0; - } - } - } else { - // readi/writei. - while (!pDevice->alsa.breakFromMainLoop) { - mal_uint32 framesAvailable = mal_device__wait_for_frames__alsa(pDevice, NULL); - if (framesAvailable == 0) { - continue; - } - - // Don't bother asking the client for more audio data if we're just stopping the device anyway. - if (pDevice->alsa.breakFromMainLoop) { - return MAL_FALSE; - } - - mal_device__read_frames_from_client(pDevice, framesAvailable, pDevice->alsa.pIntermediaryBuffer); - - mal_snd_pcm_sframes_t framesWritten = ((mal_snd_pcm_writei_proc)pDevice->pContext->alsa.snd_pcm_writei)((mal_snd_pcm_t*)pDevice->alsa.pPCM, pDevice->alsa.pIntermediaryBuffer, framesAvailable); - if (framesWritten < 0) { - if (framesWritten == -EAGAIN) { - continue; // Just keep trying... - } else if (framesWritten == -EPIPE) { - // Underrun. Just recover and try writing again. - if (((mal_snd_pcm_recover_proc)pDevice->pContext->alsa.snd_pcm_recover)((mal_snd_pcm_t*)pDevice->alsa.pPCM, framesWritten, MAL_TRUE) < 0) { - mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[ALSA] Failed to recover device after underrun.", MAL_FAILED_TO_START_BACKEND_DEVICE); - return MAL_FALSE; - } - - framesWritten = ((mal_snd_pcm_writei_proc)pDevice->pContext->alsa.snd_pcm_writei)((mal_snd_pcm_t*)pDevice->alsa.pPCM, pDevice->alsa.pIntermediaryBuffer, framesAvailable); - if (framesWritten < 0) { - mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[ALSA] Failed to write data to the internal device.", MAL_FAILED_TO_SEND_DATA_TO_DEVICE); - return MAL_FALSE; - } - - break; // Success. - } else { - mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[ALSA] snd_pcm_writei() failed when writing initial data.", MAL_FAILED_TO_SEND_DATA_TO_DEVICE); - return MAL_FALSE; - } - } else { - break; // Success. - } - } - } - - return MAL_TRUE; -} - -mal_bool32 mal_device_read__alsa(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - if (!mal_device_is_started(pDevice)) { - return MAL_FALSE; - } - if (pDevice->alsa.breakFromMainLoop) { - return MAL_FALSE; - } - - mal_uint32 framesToSend = 0; - void* pBuffer = NULL; - if (pDevice->alsa.pIntermediaryBuffer == NULL) { - // mmap. - mal_bool32 requiresRestart; - mal_uint32 framesAvailable = mal_device__wait_for_frames__alsa(pDevice, &requiresRestart); - if (framesAvailable == 0) { - return MAL_FALSE; - } - - const mal_snd_pcm_channel_area_t* pAreas; - mal_snd_pcm_uframes_t mappedOffset; - mal_snd_pcm_uframes_t mappedFrames = framesAvailable; - while (framesAvailable > 0) { - int result = ((mal_snd_pcm_mmap_begin_proc)pDevice->pContext->alsa.snd_pcm_mmap_begin)((mal_snd_pcm_t*)pDevice->alsa.pPCM, &pAreas, &mappedOffset, &mappedFrames); - if (result < 0) { - return MAL_FALSE; - } - - if (mappedFrames > 0) { - void* pBuffer = (mal_uint8*)pAreas[0].addr + ((pAreas[0].first + (mappedOffset * pAreas[0].step)) / 8); - mal_device__send_frames_to_client(pDevice, mappedFrames, pBuffer); - } - - result = ((mal_snd_pcm_mmap_commit_proc)pDevice->pContext->alsa.snd_pcm_mmap_commit)((mal_snd_pcm_t*)pDevice->alsa.pPCM, mappedOffset, mappedFrames); - if (result < 0 || (mal_snd_pcm_uframes_t)result != mappedFrames) { - ((mal_snd_pcm_recover_proc)pDevice->pContext->alsa.snd_pcm_recover)((mal_snd_pcm_t*)pDevice->alsa.pPCM, result, MAL_TRUE); - return MAL_FALSE; - } - - if (requiresRestart) { - if (((mal_snd_pcm_start_proc)pDevice->pContext->alsa.snd_pcm_start)((mal_snd_pcm_t*)pDevice->alsa.pPCM) < 0) { - return MAL_FALSE; - } - } - - if (framesAvailable >= mappedFrames) { - framesAvailable -= mappedFrames; - } else { - framesAvailable = 0; - } - } - } else { - // readi/writei. - mal_snd_pcm_sframes_t framesRead = 0; - while (!pDevice->alsa.breakFromMainLoop) { - mal_uint32 framesAvailable = mal_device__wait_for_frames__alsa(pDevice, NULL); - if (framesAvailable == 0) { - continue; - } - - framesRead = ((mal_snd_pcm_readi_proc)pDevice->pContext->alsa.snd_pcm_readi)((mal_snd_pcm_t*)pDevice->alsa.pPCM, pDevice->alsa.pIntermediaryBuffer, framesAvailable); - if (framesRead < 0) { - if (framesRead == -EAGAIN) { - continue; // Just keep trying... - } else if (framesRead == -EPIPE) { - // Overrun. Just recover and try reading again. - if (((mal_snd_pcm_recover_proc)pDevice->pContext->alsa.snd_pcm_recover)((mal_snd_pcm_t*)pDevice->alsa.pPCM, framesRead, MAL_TRUE) < 0) { - mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[ALSA] Failed to recover device after overrun.", MAL_FAILED_TO_START_BACKEND_DEVICE); - return MAL_FALSE; - } - - framesRead = ((mal_snd_pcm_readi_proc)pDevice->pContext->alsa.snd_pcm_readi)((mal_snd_pcm_t*)pDevice->alsa.pPCM, pDevice->alsa.pIntermediaryBuffer, framesAvailable); - if (framesRead < 0) { - mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[ALSA] Failed to read data from the internal device.", MAL_FAILED_TO_READ_DATA_FROM_DEVICE); - return MAL_FALSE; - } - - break; // Success. - } else { - return MAL_FALSE; - } - } else { - break; // Success. - } - } - - framesToSend = framesRead; - pBuffer = pDevice->alsa.pIntermediaryBuffer; - } - - if (framesToSend > 0) { - mal_device__send_frames_to_client(pDevice, framesToSend, pBuffer); - } - - return MAL_TRUE; -} - -void mal_device_uninit__alsa(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - if ((mal_snd_pcm_t*)pDevice->alsa.pPCM) { - ((mal_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)((mal_snd_pcm_t*)pDevice->alsa.pPCM); - - if (pDevice->alsa.pIntermediaryBuffer != NULL) { - mal_free(pDevice->alsa.pIntermediaryBuffer); - } - } -} - -mal_result mal_device_init__alsa(mal_context* pContext, mal_device_type type, const mal_device_id* pDeviceID, const mal_device_config* pConfig, mal_device* pDevice) -{ - (void)pContext; - - mal_assert(pDevice != NULL); - mal_zero_object(&pDevice->alsa); - - mal_snd_pcm_format_t formatALSA = mal_convert_mal_format_to_alsa_format(pConfig->format); - - mal_result result = mal_context_open_pcm__alsa(pContext, pConfig->shareMode, type, pDeviceID, (mal_snd_pcm_t**)&pDevice->alsa.pPCM); - if (result != MAL_SUCCESS) { - return result; - } - - // We may be scaling the size of the buffer. - float bufferSizeScaleFactor = 1; - - // If using the default buffer size we may want to apply some device-specific scaling for known devices that have peculiar latency characteristics (looking at you Raspberry Pi!). - if (pDevice->usingDefaultBufferSize) { - mal_snd_pcm_info_t* pInfo = (mal_snd_pcm_info_t*)alloca(((mal_snd_pcm_info_sizeof_proc)pContext->alsa.snd_pcm_info_sizeof)()); - mal_zero_memory(pInfo, ((mal_snd_pcm_info_sizeof_proc)pContext->alsa.snd_pcm_info_sizeof)()); - - // We may need to scale the size of the buffer depending on the device. - if (((mal_snd_pcm_info_proc)pContext->alsa.snd_pcm_info)((mal_snd_pcm_t*)pDevice->alsa.pPCM, pInfo) == 0) { - const char* deviceName = ((mal_snd_pcm_info_get_name_proc)pContext->alsa.snd_pcm_info_get_name)(pInfo); - if (deviceName != NULL) { - if (mal_strcmp(deviceName, "default") == 0) { - // It's the default device. We need to use DESC from snd_device_name_hint(). - char** ppDeviceHints; - if (((mal_snd_device_name_hint_proc)pContext->alsa.snd_device_name_hint)(-1, "pcm", (void***)&ppDeviceHints) < 0) { - return MAL_NO_BACKEND; - } - - char** ppNextDeviceHint = ppDeviceHints; - while (*ppNextDeviceHint != NULL) { - char* NAME = ((mal_snd_device_name_get_hint_proc)pContext->alsa.snd_device_name_get_hint)(*ppNextDeviceHint, "NAME"); - char* DESC = ((mal_snd_device_name_get_hint_proc)pContext->alsa.snd_device_name_get_hint)(*ppNextDeviceHint, "DESC"); - char* IOID = ((mal_snd_device_name_get_hint_proc)pContext->alsa.snd_device_name_get_hint)(*ppNextDeviceHint, "IOID"); - - mal_bool32 foundDevice = MAL_FALSE; - if ((type == mal_device_type_playback && (IOID == NULL || mal_strcmp(IOID, "Output") == 0)) || - (type == mal_device_type_capture && (IOID != NULL && mal_strcmp(IOID, "Input" ) == 0))) { - if (mal_strcmp(NAME, deviceName) == 0) { - bufferSizeScaleFactor = mal_find_default_buffer_size_scale__alsa(DESC); - foundDevice = MAL_TRUE; - } - } - - free(NAME); - free(DESC); - free(IOID); - ppNextDeviceHint += 1; - - if (foundDevice) { - break; - } - } - - ((mal_snd_device_name_free_hint_proc)pContext->alsa.snd_device_name_free_hint)((void**)ppDeviceHints); - } else { - bufferSizeScaleFactor = mal_find_default_buffer_size_scale__alsa(deviceName); - } - } - } - } - - - // Hardware parameters. - mal_snd_pcm_hw_params_t* pHWParams = (mal_snd_pcm_hw_params_t*)alloca(((mal_snd_pcm_hw_params_sizeof_proc)pContext->alsa.snd_pcm_hw_params_sizeof)()); - mal_zero_memory(pHWParams, ((mal_snd_pcm_hw_params_sizeof_proc)pContext->alsa.snd_pcm_hw_params_sizeof)()); - - if (((mal_snd_pcm_hw_params_any_proc)pContext->alsa.snd_pcm_hw_params_any)((mal_snd_pcm_t*)pDevice->alsa.pPCM, pHWParams) < 0) { - mal_device_uninit__alsa(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[ALSA] Failed to initialize hardware parameters. snd_pcm_hw_params_any() failed.", MAL_FAILED_TO_CONFIGURE_BACKEND_DEVICE); - } - - - // MMAP Mode - // - // Try using interleaved MMAP access. If this fails, fall back to standard readi/writei. - pDevice->alsa.isUsingMMap = MAL_FALSE; - if (!pConfig->alsa.noMMap && pDevice->type != mal_device_type_capture) { // <-- Disabling MMAP mode for capture devices because I apparently do not have a device that supports it which means I can't test it... Contributions welcome. - if (((mal_snd_pcm_hw_params_set_access_proc)pContext->alsa.snd_pcm_hw_params_set_access)((mal_snd_pcm_t*)pDevice->alsa.pPCM, pHWParams, MAL_SND_PCM_ACCESS_MMAP_INTERLEAVED) == 0) { - pDevice->alsa.isUsingMMap = MAL_TRUE; - } - } - - if (!pDevice->alsa.isUsingMMap) { - if (((mal_snd_pcm_hw_params_set_access_proc)pContext->alsa.snd_pcm_hw_params_set_access)((mal_snd_pcm_t*)pDevice->alsa.pPCM, pHWParams, MAL_SND_PCM_ACCESS_RW_INTERLEAVED) < 0) {; - mal_device_uninit__alsa(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[ALSA] Failed to set access mode to neither SND_PCM_ACCESS_MMAP_INTERLEAVED nor SND_PCM_ACCESS_RW_INTERLEAVED. snd_pcm_hw_params_set_access() failed.", MAL_FORMAT_NOT_SUPPORTED); - } - } - - - // Most important properties first. The documentation for OSS (yes, I know this is ALSA!) recommends format, channels, then sample rate. I can't - // find any documentation for ALSA specifically, so I'm going to copy the recommendation for OSS. - - // Format. - // Try getting every supported format. - mal_snd_pcm_format_mask_t* pFormatMask = (mal_snd_pcm_format_mask_t*)alloca(((mal_snd_pcm_format_mask_sizeof_proc)pContext->alsa.snd_pcm_format_mask_sizeof)()); - mal_zero_memory(pFormatMask, ((mal_snd_pcm_format_mask_sizeof_proc)pContext->alsa.snd_pcm_format_mask_sizeof)()); - - ((mal_snd_pcm_hw_params_get_format_mask_proc)pContext->alsa.snd_pcm_hw_params_get_format_mask)(pHWParams, pFormatMask); - - // At this point we should have a list of supported formats, so now we need to find the best one. We first check if the requested format is - // supported, and if so, use that one. If it's not supported, we just run though a list of formats and try to find the best one. - if (!((mal_snd_pcm_format_mask_test_proc)pContext->alsa.snd_pcm_format_mask_test)(pFormatMask, formatALSA)) { - // The requested format is not supported so now try running through the list of formats and return the best one. - mal_snd_pcm_format_t preferredFormatsALSA[] = { - MAL_SND_PCM_FORMAT_S16_LE, // mal_format_s16 - MAL_SND_PCM_FORMAT_FLOAT_LE, // mal_format_f32 - MAL_SND_PCM_FORMAT_S32_LE, // mal_format_s32 - MAL_SND_PCM_FORMAT_S24_3LE, // mal_format_s24 - MAL_SND_PCM_FORMAT_U8 // mal_format_u8 - }; - - if (mal_is_big_endian()) { - preferredFormatsALSA[0] = MAL_SND_PCM_FORMAT_S16_BE; - preferredFormatsALSA[1] = MAL_SND_PCM_FORMAT_FLOAT_BE; - preferredFormatsALSA[2] = MAL_SND_PCM_FORMAT_S32_BE; - preferredFormatsALSA[3] = MAL_SND_PCM_FORMAT_S24_3BE; - preferredFormatsALSA[4] = MAL_SND_PCM_FORMAT_U8; - } - - - formatALSA = MAL_SND_PCM_FORMAT_UNKNOWN; - for (size_t i = 0; i < (sizeof(preferredFormatsALSA) / sizeof(preferredFormatsALSA[0])); ++i) { - if (((mal_snd_pcm_format_mask_test_proc)pContext->alsa.snd_pcm_format_mask_test)(pFormatMask, preferredFormatsALSA[i])) { - formatALSA = preferredFormatsALSA[i]; - break; - } - } - - if (formatALSA == MAL_SND_PCM_FORMAT_UNKNOWN) { - mal_device_uninit__alsa(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[ALSA] Format not supported. The device does not support any mini_al formats.", MAL_FORMAT_NOT_SUPPORTED); - } - } - - if (((mal_snd_pcm_hw_params_set_format_proc)pContext->alsa.snd_pcm_hw_params_set_format)((mal_snd_pcm_t*)pDevice->alsa.pPCM, pHWParams, formatALSA) < 0) { - mal_device_uninit__alsa(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[ALSA] Format not supported. snd_pcm_hw_params_set_format() failed.", MAL_FORMAT_NOT_SUPPORTED); - } - - pDevice->internalFormat = mal_convert_alsa_format_to_mal_format(formatALSA); - if (pDevice->internalFormat == mal_format_unknown) { - mal_device_uninit__alsa(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[ALSA] The chosen format is not supported by mini_al.", MAL_FORMAT_NOT_SUPPORTED); - } - - - // Channels. - unsigned int channels = pConfig->channels; - if (((mal_snd_pcm_hw_params_set_channels_near_proc)pContext->alsa.snd_pcm_hw_params_set_channels_near)((mal_snd_pcm_t*)pDevice->alsa.pPCM, pHWParams, &channels) < 0) { - mal_device_uninit__alsa(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[ALSA] Failed to set channel count. snd_pcm_hw_params_set_channels_near() failed.", MAL_FORMAT_NOT_SUPPORTED); - } - pDevice->internalChannels = (mal_uint32)channels; - - - // Sample Rate. It appears there's either a bug in ALSA, a bug in some drivers, or I'm doing something silly; but having resampling - // enabled causes problems with some device configurations when used in conjunction with MMAP access mode. To fix this problem we - // need to disable resampling. - // - // To reproduce this problem, open the "plug:dmix" device, and set the sample rate to 44100. Internally, it looks like dmix uses a - // sample rate of 48000. The hardware parameters will get set correctly with no errors, but it looks like the 44100 -> 48000 resampling - // doesn't work properly - but only with MMAP access mode. You will notice skipping/crackling in the audio, and it'll run at a slightly - // faster rate. - // - // mini_al has built-in support for sample rate conversion (albeit low quality at the moment), so disabling resampling should be fine - // for us. The only problem is that it won't be taking advantage of any kind of hardware-accelerated resampling and it won't be very - // good quality until I get a chance to improve the quality of mini_al's software sample rate conversion. - // - // I don't currently know if the dmix plugin is the only one with this error. Indeed, this is the only one I've been able to reproduce - // this error with. In the future, we may want to restrict the disabling of resampling to only known bad plugins. - ((mal_snd_pcm_hw_params_set_rate_resample_proc)pContext->alsa.snd_pcm_hw_params_set_rate_resample)((mal_snd_pcm_t*)pDevice->alsa.pPCM, pHWParams, 0); - - unsigned int sampleRate = pConfig->sampleRate; - if (((mal_snd_pcm_hw_params_set_rate_near_proc)pContext->alsa.snd_pcm_hw_params_set_rate_near)((mal_snd_pcm_t*)pDevice->alsa.pPCM, pHWParams, &sampleRate, 0) < 0) { - mal_device_uninit__alsa(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[ALSA] Sample rate not supported. snd_pcm_hw_params_set_rate_near() failed.", MAL_FORMAT_NOT_SUPPORTED); - } - pDevice->internalSampleRate = (mal_uint32)sampleRate; - - - // At this point we know the internal sample rate which means we can calculate the buffer size in frames. - if (pDevice->bufferSizeInFrames == 0) { - pDevice->bufferSizeInFrames = mal_scale_buffer_size(mal_calculate_buffer_size_in_frames_from_milliseconds(pDevice->bufferSizeInMilliseconds, pDevice->internalSampleRate), bufferSizeScaleFactor); - } - - // Buffer Size - mal_snd_pcm_uframes_t actualBufferSize = pDevice->bufferSizeInFrames; - if (((mal_snd_pcm_hw_params_set_buffer_size_near_proc)pContext->alsa.snd_pcm_hw_params_set_buffer_size_near)((mal_snd_pcm_t*)pDevice->alsa.pPCM, pHWParams, &actualBufferSize) < 0) { - mal_device_uninit__alsa(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[ALSA] Failed to set buffer size for device. snd_pcm_hw_params_set_buffer_size() failed.", MAL_FORMAT_NOT_SUPPORTED); - } - pDevice->bufferSizeInFrames = actualBufferSize; - - // Periods. - mal_uint32 periods = pConfig->periods; - if (((mal_snd_pcm_hw_params_set_periods_near_proc)pContext->alsa.snd_pcm_hw_params_set_periods_near)((mal_snd_pcm_t*)pDevice->alsa.pPCM, pHWParams, &periods, NULL) < 0) { - mal_device_uninit__alsa(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[ALSA] Failed to set period count. snd_pcm_hw_params_set_periods_near() failed.", MAL_FORMAT_NOT_SUPPORTED); - } - pDevice->periods = periods; - - - // Apply hardware parameters. - if (((mal_snd_pcm_hw_params_proc)pContext->alsa.snd_pcm_hw_params)((mal_snd_pcm_t*)pDevice->alsa.pPCM, pHWParams) < 0) { - mal_device_uninit__alsa(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[ALSA] Failed to set hardware parameters. snd_pcm_hw_params() failed.", MAL_FAILED_TO_CONFIGURE_BACKEND_DEVICE); - } - - - - // Software parameters. - mal_snd_pcm_sw_params_t* pSWParams = (mal_snd_pcm_sw_params_t*)alloca(((mal_snd_pcm_sw_params_sizeof_proc)pContext->alsa.snd_pcm_sw_params_sizeof)()); - mal_zero_memory(pSWParams, ((mal_snd_pcm_sw_params_sizeof_proc)pContext->alsa.snd_pcm_sw_params_sizeof)()); - - if (((mal_snd_pcm_sw_params_current_proc)pContext->alsa.snd_pcm_sw_params_current)((mal_snd_pcm_t*)pDevice->alsa.pPCM, pSWParams) != 0) { - mal_device_uninit__alsa(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[ALSA] Failed to initialize software parameters. snd_pcm_sw_params_current() failed.", MAL_FAILED_TO_CONFIGURE_BACKEND_DEVICE); - } - - if (((mal_snd_pcm_sw_params_set_avail_min_proc)pContext->alsa.snd_pcm_sw_params_set_avail_min)((mal_snd_pcm_t*)pDevice->alsa.pPCM, pSWParams, /*(pDevice->sampleRate/1000) * 1*/ mal_prev_power_of_2(pDevice->bufferSizeInFrames/pDevice->periods)) != 0) { - mal_device_uninit__alsa(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[ALSA] snd_pcm_sw_params_set_avail_min() failed.", MAL_FORMAT_NOT_SUPPORTED); - } - - if (type == mal_device_type_playback && !pDevice->alsa.isUsingMMap) { // Only playback devices in writei/readi mode need a start threshold. - if (((mal_snd_pcm_sw_params_set_start_threshold_proc)pContext->alsa.snd_pcm_sw_params_set_start_threshold)((mal_snd_pcm_t*)pDevice->alsa.pPCM, pSWParams, /*(pDevice->sampleRate/1000) * 1*/ pDevice->bufferSizeInFrames/pDevice->periods) != 0) { //mal_prev_power_of_2(pDevice->bufferSizeInFrames/pDevice->periods) - mal_device_uninit__alsa(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[ALSA] Failed to set start threshold for playback device. snd_pcm_sw_params_set_start_threshold() failed.", MAL_FAILED_TO_CONFIGURE_BACKEND_DEVICE); - } - } - - if (((mal_snd_pcm_sw_params_proc)pContext->alsa.snd_pcm_sw_params)((mal_snd_pcm_t*)pDevice->alsa.pPCM, pSWParams) != 0) { - mal_device_uninit__alsa(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[ALSA] Failed to set software parameters. snd_pcm_sw_params() failed.", MAL_FAILED_TO_CONFIGURE_BACKEND_DEVICE); - } - - - - // If we're _not_ using mmap we need to use an intermediary buffer. - if (!pDevice->alsa.isUsingMMap) { - pDevice->alsa.pIntermediaryBuffer = mal_malloc(pDevice->bufferSizeInFrames * pDevice->internalChannels * mal_get_bytes_per_sample(pDevice->internalFormat)); - if (pDevice->alsa.pIntermediaryBuffer == NULL) { - mal_device_uninit__alsa(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[ALSA] Failed to allocate memory for intermediary buffer.", MAL_OUT_OF_MEMORY); - } - } - - // Grab the internal channel map. For now we're not going to bother trying to change the channel map and - // instead just do it ourselves. - mal_snd_pcm_chmap_t* pChmap = ((mal_snd_pcm_get_chmap_proc)pContext->alsa.snd_pcm_get_chmap)((mal_snd_pcm_t*)pDevice->alsa.pPCM); - if (pChmap != NULL) { - // There are cases where the returned channel map can have a different channel count than was returned by snd_pcm_hw_params_set_channels_near(). - if (pChmap->channels >= pDevice->internalChannels) { - // Drop excess channels. - for (mal_uint32 iChannel = 0; iChannel < pDevice->internalChannels; ++iChannel) { - pDevice->internalChannelMap[iChannel] = mal_convert_alsa_channel_position_to_mal_channel(pChmap->pos[iChannel]); - } - } else { - // Excess channels use defaults. Do an initial fill with defaults, overwrite the first pChmap->channels, validate to ensure there are no duplicate - // channels. If validation fails, fall back to defaults. - - // Fill with defaults. - mal_get_standard_channel_map(mal_standard_channel_map_alsa, pDevice->internalChannels, pDevice->internalChannelMap); - - // Overwrite first pChmap->channels channels. - for (mal_uint32 iChannel = 0; iChannel < pChmap->channels; ++iChannel) { - pDevice->internalChannelMap[iChannel] = mal_convert_alsa_channel_position_to_mal_channel(pChmap->pos[iChannel]); - } - - // Validate. - mal_bool32 isValid = MAL_TRUE; - for (mal_uint32 i = 0; i < pDevice->internalChannels && isValid; ++i) { - for (mal_uint32 j = i+1; j < pDevice->internalChannels; ++j) { - if (pDevice->internalChannelMap[i] == pDevice->internalChannelMap[j]) { - isValid = MAL_FALSE; - break; - } - } - } - - // If our channel map is invalid, fall back to defaults. - if (!isValid) { - mal_get_standard_channel_map(mal_standard_channel_map_alsa, pDevice->internalChannels, pDevice->internalChannelMap); - } - } - - free(pChmap); - pChmap = NULL; - } else { - // Could not retrieve the channel map. Fall back to a hard-coded assumption. - mal_get_standard_channel_map(mal_standard_channel_map_alsa, pDevice->internalChannels, pDevice->internalChannelMap); - } - - return MAL_SUCCESS; -} - - -mal_result mal_device_start__alsa(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - // Prepare the device first... - if (((mal_snd_pcm_prepare_proc)pDevice->pContext->alsa.snd_pcm_prepare)((mal_snd_pcm_t*)pDevice->alsa.pPCM) < 0) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[ALSA] Failed to prepare device.", MAL_FAILED_TO_START_BACKEND_DEVICE); - } - - // ... and then grab an initial chunk from the client. After this is done, the device should - // automatically start playing, since that's how we configured the software parameters. - if (pDevice->type == mal_device_type_playback) { - if (!mal_device_write__alsa(pDevice)) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[ALSA] Failed to write initial chunk of data to the playback device.", MAL_FAILED_TO_SEND_DATA_TO_DEVICE); - } - - // mmap mode requires an explicit start. - if (pDevice->alsa.isUsingMMap) { - if (((mal_snd_pcm_start_proc)pDevice->pContext->alsa.snd_pcm_start)((mal_snd_pcm_t*)pDevice->alsa.pPCM) < 0) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[ALSA] Failed to start capture device.", MAL_FAILED_TO_START_BACKEND_DEVICE); - } - } - } else { - if (((mal_snd_pcm_start_proc)pDevice->pContext->alsa.snd_pcm_start)((mal_snd_pcm_t*)pDevice->alsa.pPCM) < 0) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[ALSA] Failed to start capture device.", MAL_FAILED_TO_START_BACKEND_DEVICE); - } - } - - return MAL_SUCCESS; -} - -mal_result mal_device_stop__alsa(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - ((mal_snd_pcm_drop_proc)pDevice->pContext->alsa.snd_pcm_drop)((mal_snd_pcm_t*)pDevice->alsa.pPCM); - return MAL_SUCCESS; -} - -mal_result mal_device_break_main_loop__alsa(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - // First we tell the main loop that we're breaking... - pDevice->alsa.breakFromMainLoop = MAL_TRUE; - - // Then we need to force snd_pcm_wait() to return. - //((mal_snd_pcm_drop_proc)pDevice->pContext->alsa.snd_pcm_drop)((mal_snd_pcm_t*)pDevice->alsa.pPCM); - - return MAL_SUCCESS; -} - -mal_result mal_device_main_loop__alsa(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - pDevice->alsa.breakFromMainLoop = MAL_FALSE; - if (pDevice->type == mal_device_type_playback) { - // Playback. Read from client, write to device. - while (!pDevice->alsa.breakFromMainLoop && mal_device_write__alsa(pDevice)) { - } - } else { - // Capture. Read from device, write to client. - while (!pDevice->alsa.breakFromMainLoop && mal_device_read__alsa(pDevice)) { - } - } - - return MAL_SUCCESS; -} - - -mal_result mal_context_uninit__alsa(mal_context* pContext) -{ - mal_assert(pContext != NULL); - mal_assert(pContext->backend == mal_backend_alsa); - - // Clean up memory for memory leak checkers. - ((mal_snd_config_update_free_global_proc)pContext->alsa.snd_config_update_free_global)(); - -#ifndef MAL_NO_RUNTIME_LINKING - mal_dlclose(pContext->alsa.asoundSO); -#endif - - mal_mutex_uninit(&pContext->alsa.internalDeviceEnumLock); - - return MAL_SUCCESS; -} - -mal_result mal_context_init__alsa(mal_context* pContext) -{ - mal_assert(pContext != NULL); - -#ifndef MAL_NO_RUNTIME_LINKING - const char* libasoundNames[] = { - "libasound.so.2", - "libasound.so" - }; - - for (size_t i = 0; i < mal_countof(libasoundNames); ++i) { - pContext->alsa.asoundSO = mal_dlopen(libasoundNames[i]); - if (pContext->alsa.asoundSO != NULL) { - break; - } - } - - if (pContext->alsa.asoundSO == NULL) { -#ifdef MAL_DEBUG_OUTPUT - printf("[ALSA] Failed to open shared object.\n"); -#endif - return MAL_NO_BACKEND; - } - - pContext->alsa.snd_pcm_open = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_open"); - pContext->alsa.snd_pcm_close = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_close"); - pContext->alsa.snd_pcm_hw_params_sizeof = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_sizeof"); - pContext->alsa.snd_pcm_hw_params_any = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_any"); - pContext->alsa.snd_pcm_hw_params_set_format = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_set_format"); - pContext->alsa.snd_pcm_hw_params_set_format_first = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_set_format_first"); - pContext->alsa.snd_pcm_hw_params_get_format_mask = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_get_format_mask"); - pContext->alsa.snd_pcm_hw_params_set_channels_near = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_set_channels_near"); - pContext->alsa.snd_pcm_hw_params_set_rate_resample = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_set_rate_resample"); - pContext->alsa.snd_pcm_hw_params_set_rate_near = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_set_rate_near"); - pContext->alsa.snd_pcm_hw_params_set_buffer_size_near = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_set_buffer_size_near"); - pContext->alsa.snd_pcm_hw_params_set_periods_near = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_set_periods_near"); - pContext->alsa.snd_pcm_hw_params_set_access = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_set_access"); - pContext->alsa.snd_pcm_hw_params_get_format = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_get_format"); - pContext->alsa.snd_pcm_hw_params_get_channels = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_get_channels"); - pContext->alsa.snd_pcm_hw_params_get_channels_min = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_get_channels_min"); - pContext->alsa.snd_pcm_hw_params_get_channels_max = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_get_channels_max"); - pContext->alsa.snd_pcm_hw_params_get_rate = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_get_rate"); - pContext->alsa.snd_pcm_hw_params_get_rate_min = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_get_rate_min"); - pContext->alsa.snd_pcm_hw_params_get_rate_max = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_get_rate_max"); - pContext->alsa.snd_pcm_hw_params_get_buffer_size = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_get_buffer_size"); - pContext->alsa.snd_pcm_hw_params_get_periods = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_get_periods"); - pContext->alsa.snd_pcm_hw_params_get_access = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_get_access"); - pContext->alsa.snd_pcm_hw_params = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params"); - pContext->alsa.snd_pcm_sw_params_sizeof = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_sw_params_sizeof"); - pContext->alsa.snd_pcm_sw_params_current = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_sw_params_current"); - pContext->alsa.snd_pcm_sw_params_set_avail_min = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_sw_params_set_avail_min"); - pContext->alsa.snd_pcm_sw_params_set_start_threshold = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_sw_params_set_start_threshold"); - pContext->alsa.snd_pcm_sw_params = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_sw_params"); - pContext->alsa.snd_pcm_format_mask_sizeof = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_format_mask_sizeof"); - pContext->alsa.snd_pcm_format_mask_test = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_format_mask_test"); - pContext->alsa.snd_pcm_get_chmap = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_get_chmap"); - pContext->alsa.snd_pcm_prepare = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_prepare"); - pContext->alsa.snd_pcm_start = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_start"); - pContext->alsa.snd_pcm_drop = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_drop"); - pContext->alsa.snd_device_name_hint = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_device_name_hint"); - pContext->alsa.snd_device_name_get_hint = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_device_name_get_hint"); - pContext->alsa.snd_card_get_index = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_card_get_index"); - pContext->alsa.snd_device_name_free_hint = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_device_name_free_hint"); - pContext->alsa.snd_pcm_mmap_begin = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_mmap_begin"); - pContext->alsa.snd_pcm_mmap_commit = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_mmap_commit"); - pContext->alsa.snd_pcm_recover = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_recover"); - pContext->alsa.snd_pcm_readi = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_readi"); - pContext->alsa.snd_pcm_writei = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_writei"); - pContext->alsa.snd_pcm_avail = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_avail"); - pContext->alsa.snd_pcm_avail_update = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_avail_update"); - pContext->alsa.snd_pcm_wait = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_wait"); - pContext->alsa.snd_pcm_info = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_info"); - pContext->alsa.snd_pcm_info_sizeof = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_info_sizeof"); - pContext->alsa.snd_pcm_info_get_name = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_pcm_info_get_name"); - pContext->alsa.snd_config_update_free_global = (mal_proc)mal_dlsym(pContext->alsa.asoundSO, "snd_config_update_free_global"); -#else - // The system below is just for type safety. - mal_snd_pcm_open_proc _snd_pcm_open = snd_pcm_open; - mal_snd_pcm_close_proc _snd_pcm_close = snd_pcm_close; - mal_snd_pcm_hw_params_sizeof_proc _snd_pcm_hw_params_sizeof = snd_pcm_hw_params_sizeof; - mal_snd_pcm_hw_params_any_proc _snd_pcm_hw_params_any = snd_pcm_hw_params_any; - mal_snd_pcm_hw_params_set_format_proc _snd_pcm_hw_params_set_format = snd_pcm_hw_params_set_format; - mal_snd_pcm_hw_params_set_format_first_proc _snd_pcm_hw_params_set_format_first = snd_pcm_hw_params_set_format_first; - mal_snd_pcm_hw_params_get_format_mask_proc _snd_pcm_hw_params_get_format_mask = snd_pcm_hw_params_get_format_mask; - mal_snd_pcm_hw_params_set_channels_near_proc _snd_pcm_hw_params_set_channels_near = snd_pcm_hw_params_set_channels_near; - mal_snd_pcm_hw_params_set_rate_resample_proc _snd_pcm_hw_params_set_rate_resample = snd_pcm_hw_params_set_rate_resample; - mal_snd_pcm_hw_params_set_rate_near_proc _snd_pcm_hw_params_set_rate_near = snd_pcm_hw_params_set_rate_near; - mal_snd_pcm_hw_params_set_buffer_size_near_proc _snd_pcm_hw_params_set_buffer_size_near = snd_pcm_hw_params_set_buffer_size_near; - mal_snd_pcm_hw_params_set_periods_near_proc _snd_pcm_hw_params_set_periods_near = snd_pcm_hw_params_set_periods_near; - mal_snd_pcm_hw_params_set_access_proc _snd_pcm_hw_params_set_access = snd_pcm_hw_params_set_access; - mal_snd_pcm_hw_params_get_format_proc _snd_pcm_hw_params_get_format = snd_pcm_hw_params_get_format; - mal_snd_pcm_hw_params_get_channels_proc _snd_pcm_hw_params_get_channels = snd_pcm_hw_params_get_channels; - mal_snd_pcm_hw_params_get_channels_min_proc _snd_pcm_hw_params_get_channels_min = snd_pcm_hw_params_get_channels_min; - mal_snd_pcm_hw_params_get_channels_max_proc _snd_pcm_hw_params_get_channels_max = snd_pcm_hw_params_get_channels_max; - mal_snd_pcm_hw_params_get_rate_proc _snd_pcm_hw_params_get_rate = snd_pcm_hw_params_get_rate; - mal_snd_pcm_hw_params_get_rate_min_proc _snd_pcm_hw_params_get_rate_min = snd_pcm_hw_params_get_rate_min; - mal_snd_pcm_hw_params_get_rate_max_proc _snd_pcm_hw_params_get_rate_max = snd_pcm_hw_params_get_rate_max; - mal_snd_pcm_hw_params_get_buffer_size_proc _snd_pcm_hw_params_get_buffer_size = snd_pcm_hw_params_get_buffer_size; - mal_snd_pcm_hw_params_get_periods_proc _snd_pcm_hw_params_get_periods = snd_pcm_hw_params_get_periods; - mal_snd_pcm_hw_params_get_access_proc _snd_pcm_hw_params_get_access = snd_pcm_hw_params_get_access; - mal_snd_pcm_hw_params_proc _snd_pcm_hw_params = snd_pcm_hw_params; - mal_snd_pcm_sw_params_sizeof_proc _snd_pcm_sw_params_sizeof = snd_pcm_sw_params_sizeof; - mal_snd_pcm_sw_params_current_proc _snd_pcm_sw_params_current = snd_pcm_sw_params_current; - mal_snd_pcm_sw_params_set_avail_min_proc _snd_pcm_sw_params_set_avail_min = snd_pcm_sw_params_set_avail_min; - mal_snd_pcm_sw_params_set_start_threshold_proc _snd_pcm_sw_params_set_start_threshold = snd_pcm_sw_params_set_start_threshold; - mal_snd_pcm_sw_params_proc _snd_pcm_sw_params = snd_pcm_sw_params; - mal_snd_pcm_format_mask_sizeof_proc _snd_pcm_format_mask_sizeof = snd_pcm_format_mask_sizeof; - mal_snd_pcm_format_mask_test_proc _snd_pcm_format_mask_test = snd_pcm_format_mask_test; - mal_snd_pcm_get_chmap_proc _snd_pcm_get_chmap = snd_pcm_get_chmap; - mal_snd_pcm_prepare_proc _snd_pcm_prepare = snd_pcm_prepare; - mal_snd_pcm_start_proc _snd_pcm_start = snd_pcm_start; - mal_snd_pcm_drop_proc _snd_pcm_drop = snd_pcm_drop; - mal_snd_device_name_hint_proc _snd_device_name_hint = snd_device_name_hint; - mal_snd_device_name_get_hint_proc _snd_device_name_get_hint = snd_device_name_get_hint; - mal_snd_card_get_index_proc _snd_card_get_index = snd_card_get_index; - mal_snd_device_name_free_hint_proc _snd_device_name_free_hint = snd_device_name_free_hint; - mal_snd_pcm_mmap_begin_proc _snd_pcm_mmap_begin = snd_pcm_mmap_begin; - mal_snd_pcm_mmap_commit_proc _snd_pcm_mmap_commit = snd_pcm_mmap_commit; - mal_snd_pcm_recover_proc _snd_pcm_recover = snd_pcm_recover; - mal_snd_pcm_readi_proc _snd_pcm_readi = snd_pcm_readi; - mal_snd_pcm_writei_proc _snd_pcm_writei = snd_pcm_writei; - mal_snd_pcm_avail_proc _snd_pcm_avail = snd_pcm_avail; - mal_snd_pcm_avail_update_proc _snd_pcm_avail_update = snd_pcm_avail_update; - mal_snd_pcm_wait_proc _snd_pcm_wait = snd_pcm_wait; - mal_snd_pcm_info_proc _snd_pcm_info = snd_pcm_info; - mal_snd_pcm_info_sizeof_proc _snd_pcm_info_sizeof = snd_pcm_info_sizeof; - mal_snd_pcm_info_get_name_proc _snd_pcm_info_get_name = snd_pcm_info_get_name; - mal_snd_config_update_free_global_proc _snd_config_update_free_global = snd_config_update_free_global; - - pContext->alsa.snd_pcm_open = (mal_proc)_snd_pcm_open; - pContext->alsa.snd_pcm_close = (mal_proc)_snd_pcm_close; - pContext->alsa.snd_pcm_hw_params_sizeof = (mal_proc)_snd_pcm_hw_params_sizeof; - pContext->alsa.snd_pcm_hw_params_any = (mal_proc)_snd_pcm_hw_params_any; - pContext->alsa.snd_pcm_hw_params_set_format = (mal_proc)_snd_pcm_hw_params_set_format; - pContext->alsa.snd_pcm_hw_params_set_format_first = (mal_proc)_snd_pcm_hw_params_set_format_first; - pContext->alsa.snd_pcm_hw_params_get_format_mask = (mal_proc)_snd_pcm_hw_params_get_format_mask; - pContext->alsa.snd_pcm_hw_params_set_channels_near = (mal_proc)_snd_pcm_hw_params_set_channels_near; - pContext->alsa.snd_pcm_hw_params_set_rate_resample = (mal_proc)_snd_pcm_hw_params_set_rate_resample; - pContext->alsa.snd_pcm_hw_params_set_rate_near = (mal_proc)_snd_pcm_hw_params_set_rate_near; - pContext->alsa.snd_pcm_hw_params_set_buffer_size_near = (mal_proc)_snd_pcm_hw_params_set_buffer_size_near; - pContext->alsa.snd_pcm_hw_params_set_periods_near = (mal_proc)_snd_pcm_hw_params_set_periods_near; - pContext->alsa.snd_pcm_hw_params_set_access = (mal_proc)_snd_pcm_hw_params_set_access; - pContext->alsa.snd_pcm_hw_params_get_format = (mal_proc)_snd_pcm_hw_params_get_format; - pContext->alsa.snd_pcm_hw_params_get_channels = (mal_proc)_snd_pcm_hw_params_get_channels; - pContext->alsa.snd_pcm_hw_params_get_channels_min = (mal_proc)_snd_pcm_hw_params_get_channels_min; - pContext->alsa.snd_pcm_hw_params_get_channels_max = (mal_proc)_snd_pcm_hw_params_get_channels_max; - pContext->alsa.snd_pcm_hw_params_get_rate = (mal_proc)_snd_pcm_hw_params_get_rate; - pContext->alsa.snd_pcm_hw_params_get_buffer_size = (mal_proc)_snd_pcm_hw_params_get_buffer_size; - pContext->alsa.snd_pcm_hw_params_get_periods = (mal_proc)_snd_pcm_hw_params_get_periods; - pContext->alsa.snd_pcm_hw_params_get_access = (mal_proc)_snd_pcm_hw_params_get_access; - pContext->alsa.snd_pcm_hw_params = (mal_proc)_snd_pcm_hw_params; - pContext->alsa.snd_pcm_sw_params_sizeof = (mal_proc)_snd_pcm_sw_params_sizeof; - pContext->alsa.snd_pcm_sw_params_current = (mal_proc)_snd_pcm_sw_params_current; - pContext->alsa.snd_pcm_sw_params_set_avail_min = (mal_proc)_snd_pcm_sw_params_set_avail_min; - pContext->alsa.snd_pcm_sw_params_set_start_threshold = (mal_proc)_snd_pcm_sw_params_set_start_threshold; - pContext->alsa.snd_pcm_sw_params = (mal_proc)_snd_pcm_sw_params; - pContext->alsa.snd_pcm_format_mask_sizeof = (mal_proc)_snd_pcm_format_mask_sizeof; - pContext->alsa.snd_pcm_format_mask_test = (mal_proc)_snd_pcm_format_mask_test; - pContext->alsa.snd_pcm_get_chmap = (mal_proc)_snd_pcm_get_chmap; - pContext->alsa.snd_pcm_prepare = (mal_proc)_snd_pcm_prepare; - pContext->alsa.snd_pcm_start = (mal_proc)_snd_pcm_start; - pContext->alsa.snd_pcm_drop = (mal_proc)_snd_pcm_drop; - pContext->alsa.snd_device_name_hint = (mal_proc)_snd_device_name_hint; - pContext->alsa.snd_device_name_get_hint = (mal_proc)_snd_device_name_get_hint; - pContext->alsa.snd_card_get_index = (mal_proc)_snd_card_get_index; - pContext->alsa.snd_device_name_free_hint = (mal_proc)_snd_device_name_free_hint; - pContext->alsa.snd_pcm_mmap_begin = (mal_proc)_snd_pcm_mmap_begin; - pContext->alsa.snd_pcm_mmap_commit = (mal_proc)_snd_pcm_mmap_commit; - pContext->alsa.snd_pcm_recover = (mal_proc)_snd_pcm_recover; - pContext->alsa.snd_pcm_readi = (mal_proc)_snd_pcm_readi; - pContext->alsa.snd_pcm_writei = (mal_proc)_snd_pcm_writei; - pContext->alsa.snd_pcm_avail = (mal_proc)_snd_pcm_avail; - pContext->alsa.snd_pcm_avail_update = (mal_proc)_snd_pcm_avail_update; - pContext->alsa.snd_pcm_wait = (mal_proc)_snd_pcm_wait; - pContext->alsa.snd_pcm_info = (mal_proc)_snd_pcm_info; - pContext->alsa.snd_pcm_info_sizeof = (mal_proc)_snd_pcm_info_sizeof; - pContext->alsa.snd_pcm_info_get_name = (mal_proc)_snd_pcm_info_get_name; - pContext->alsa.snd_config_update_free_global = (mal_proc)_snd_config_update_free_global; -#endif - - if (mal_mutex_init(pContext, &pContext->alsa.internalDeviceEnumLock) != MAL_SUCCESS) { - mal_context_post_error(pContext, NULL, MAL_LOG_LEVEL_ERROR, "[ALSA] WARNING: Failed to initialize mutex for internal device enumeration.", MAL_ERROR); - } - - pContext->onUninit = mal_context_uninit__alsa; - pContext->onDeviceIDEqual = mal_context_is_device_id_equal__alsa; - pContext->onEnumDevices = mal_context_enumerate_devices__alsa; - pContext->onGetDeviceInfo = mal_context_get_device_info__alsa; - pContext->onDeviceInit = mal_device_init__alsa; - pContext->onDeviceUninit = mal_device_uninit__alsa; - pContext->onDeviceStart = mal_device_start__alsa; - pContext->onDeviceStop = mal_device_stop__alsa; - pContext->onDeviceBreakMainLoop = mal_device_break_main_loop__alsa; - pContext->onDeviceMainLoop = mal_device_main_loop__alsa; - - return MAL_SUCCESS; -} -#endif // ALSA - - - -/////////////////////////////////////////////////////////////////////////////// -// -// PulseAudio Backend -// -/////////////////////////////////////////////////////////////////////////////// -#ifdef MAL_HAS_PULSEAUDIO - -// It is assumed pulseaudio.h is available when compile-time linking is being used. We use this for type safety when using -// compile time linking (we don't have this luxury when using runtime linking without headers). -// -// When using compile time linking, each of our mal_* equivalents should use the sames types as defined by the header. The -// reason for this is that it allow us to take advantage of proper type safety. -#ifdef MAL_NO_RUNTIME_LINKING -#include - -#define MAL_PA_OK PA_OK -#define MAL_PA_ERR_ACCESS PA_ERR_ACCESS -#define MAL_PA_ERR_INVALID PA_ERR_INVALID -#define MAL_PA_ERR_NOENTITY PA_ERR_NOENTITY - -#define MAL_PA_CHANNELS_MAX PA_CHANNELS_MAX -#define MAL_PA_RATE_MAX PA_RATE_MAX - -typedef pa_context_flags_t mal_pa_context_flags_t; -#define MAL_PA_CONTEXT_NOFLAGS PA_CONTEXT_NOFLAGS -#define MAL_PA_CONTEXT_NOAUTOSPAWN PA_CONTEXT_NOAUTOSPAWN -#define MAL_PA_CONTEXT_NOFAIL PA_CONTEXT_NOFAIL - -typedef pa_stream_flags_t mal_pa_stream_flags_t; -#define MAL_PA_STREAM_NOFLAGS PA_STREAM_NOFLAGS -#define MAL_PA_STREAM_START_CORKED PA_STREAM_START_CORKED -#define MAL_PA_STREAM_INTERPOLATE_TIMING PA_STREAM_INTERPOLATE_TIMING -#define MAL_PA_STREAM_NOT_MONOTONIC PA_STREAM_NOT_MONOTONIC -#define MAL_PA_STREAM_AUTO_TIMING_UPDATE PA_STREAM_AUTO_TIMING_UPDATE -#define MAL_PA_STREAM_NO_REMAP_CHANNELS PA_STREAM_NO_REMAP_CHANNELS -#define MAL_PA_STREAM_NO_REMIX_CHANNELS PA_STREAM_NO_REMIX_CHANNELS -#define MAL_PA_STREAM_FIX_FORMAT PA_STREAM_FIX_FORMAT -#define MAL_PA_STREAM_FIX_RATE PA_STREAM_FIX_RATE -#define MAL_PA_STREAM_FIX_CHANNELS PA_STREAM_FIX_CHANNELS -#define MAL_PA_STREAM_DONT_MOVE PA_STREAM_DONT_MOVE -#define MAL_PA_STREAM_VARIABLE_RATE PA_STREAM_VARIABLE_RATE -#define MAL_PA_STREAM_PEAK_DETECT PA_STREAM_PEAK_DETECT -#define MAL_PA_STREAM_START_MUTED PA_STREAM_START_MUTED -#define MAL_PA_STREAM_ADJUST_LATENCY PA_STREAM_ADJUST_LATENCY -#define MAL_PA_STREAM_EARLY_REQUESTS PA_STREAM_EARLY_REQUESTS -#define MAL_PA_STREAM_DONT_INHIBIT_AUTO_SUSPEND PA_STREAM_DONT_INHIBIT_AUTO_SUSPEND -#define MAL_PA_STREAM_START_UNMUTED PA_STREAM_START_UNMUTED -#define MAL_PA_STREAM_FAIL_ON_SUSPEND PA_STREAM_FAIL_ON_SUSPEND -#define MAL_PA_STREAM_RELATIVE_VOLUME PA_STREAM_RELATIVE_VOLUME -#define MAL_PA_STREAM_PASSTHROUGH PA_STREAM_PASSTHROUGH - -typedef pa_sink_flags_t mal_pa_sink_flags_t; -#define MAL_PA_SINK_NOFLAGS PA_SINK_NOFLAGS -#define MAL_PA_SINK_HW_VOLUME_CTRL PA_SINK_HW_VOLUME_CTRL -#define MAL_PA_SINK_LATENCY PA_SINK_LATENCY -#define MAL_PA_SINK_HARDWARE PA_SINK_HARDWARE -#define MAL_PA_SINK_NETWORK PA_SINK_NETWORK -#define MAL_PA_SINK_HW_MUTE_CTRL PA_SINK_HW_MUTE_CTRL -#define MAL_PA_SINK_DECIBEL_VOLUME PA_SINK_DECIBEL_VOLUME -#define MAL_PA_SINK_FLAT_VOLUME PA_SINK_FLAT_VOLUME -#define MAL_PA_SINK_DYNAMIC_LATENCY PA_SINK_DYNAMIC_LATENCY -#define MAL_PA_SINK_SET_FORMATS PA_SINK_SET_FORMATS - -typedef pa_source_flags_t mal_pa_source_flags_t; -#define MAL_PA_SOURCE_NOFLAGS PA_SOURCE_NOFLAGS -#define MAL_PA_SOURCE_HW_VOLUME_CTRL PA_SOURCE_HW_VOLUME_CTRL -#define MAL_PA_SOURCE_LATENCY PA_SOURCE_LATENCY -#define MAL_PA_SOURCE_HARDWARE PA_SOURCE_HARDWARE -#define MAL_PA_SOURCE_NETWORK PA_SOURCE_NETWORK -#define MAL_PA_SOURCE_HW_MUTE_CTRL PA_SOURCE_HW_MUTE_CTRL -#define MAL_PA_SOURCE_DECIBEL_VOLUME PA_SOURCE_DECIBEL_VOLUME -#define MAL_PA_SOURCE_DYNAMIC_LATENCY PA_SOURCE_DYNAMIC_LATENCY -#define MAL_PA_SOURCE_FLAT_VOLUME PA_SOURCE_FLAT_VOLUME - -typedef pa_context_state_t mal_pa_context_state_t; -#define MAL_PA_CONTEXT_UNCONNECTED PA_CONTEXT_UNCONNECTED -#define MAL_PA_CONTEXT_CONNECTING PA_CONTEXT_CONNECTING -#define MAL_PA_CONTEXT_AUTHORIZING PA_CONTEXT_AUTHORIZING -#define MAL_PA_CONTEXT_SETTING_NAME PA_CONTEXT_SETTING_NAME -#define MAL_PA_CONTEXT_READY PA_CONTEXT_READY -#define MAL_PA_CONTEXT_FAILED PA_CONTEXT_FAILED -#define MAL_PA_CONTEXT_TERMINATED PA_CONTEXT_TERMINATED - -typedef pa_stream_state_t mal_pa_stream_state_t; -#define MAL_PA_STREAM_UNCONNECTED PA_STREAM_UNCONNECTED -#define MAL_PA_STREAM_CREATING PA_STREAM_CREATING -#define MAL_PA_STREAM_READY PA_STREAM_READY -#define MAL_PA_STREAM_FAILED PA_STREAM_FAILED -#define MAL_PA_STREAM_TERMINATED PA_STREAM_TERMINATED - -typedef pa_operation_state_t mal_pa_operation_state_t; -#define MAL_PA_OPERATION_RUNNING PA_OPERATION_RUNNING -#define MAL_PA_OPERATION_DONE PA_OPERATION_DONE -#define MAL_PA_OPERATION_CANCELLED PA_OPERATION_CANCELLED - -typedef pa_sink_state_t mal_pa_sink_state_t; -#define MAL_PA_SINK_INVALID_STATE PA_SINK_INVALID_STATE -#define MAL_PA_SINK_RUNNING PA_SINK_RUNNING -#define MAL_PA_SINK_IDLE PA_SINK_IDLE -#define MAL_PA_SINK_SUSPENDED PA_SINK_SUSPENDED - -typedef pa_source_state_t mal_pa_source_state_t; -#define MAL_PA_SOURCE_INVALID_STATE PA_SOURCE_INVALID_STATE -#define MAL_PA_SOURCE_RUNNING PA_SOURCE_RUNNING -#define MAL_PA_SOURCE_IDLE PA_SOURCE_IDLE -#define MAL_PA_SOURCE_SUSPENDED PA_SOURCE_SUSPENDED - -typedef pa_seek_mode_t mal_pa_seek_mode_t; -#define MAL_PA_SEEK_RELATIVE PA_SEEK_RELATIVE -#define MAL_PA_SEEK_ABSOLUTE PA_SEEK_ABSOLUTE -#define MAL_PA_SEEK_RELATIVE_ON_READ PA_SEEK_RELATIVE_ON_READ -#define MAL_PA_SEEK_RELATIVE_END PA_SEEK_RELATIVE_END - -typedef pa_channel_position_t mal_pa_channel_position_t; -#define MAL_PA_CHANNEL_POSITION_INVALID PA_CHANNEL_POSITION_INVALID -#define MAL_PA_CHANNEL_POSITION_MONO PA_CHANNEL_POSITION_MONO -#define MAL_PA_CHANNEL_POSITION_FRONT_LEFT PA_CHANNEL_POSITION_FRONT_LEFT -#define MAL_PA_CHANNEL_POSITION_FRONT_RIGHT PA_CHANNEL_POSITION_FRONT_RIGHT -#define MAL_PA_CHANNEL_POSITION_FRONT_CENTER PA_CHANNEL_POSITION_FRONT_CENTER -#define MAL_PA_CHANNEL_POSITION_REAR_CENTER PA_CHANNEL_POSITION_REAR_CENTER -#define MAL_PA_CHANNEL_POSITION_REAR_LEFT PA_CHANNEL_POSITION_REAR_LEFT -#define MAL_PA_CHANNEL_POSITION_REAR_RIGHT PA_CHANNEL_POSITION_REAR_RIGHT -#define MAL_PA_CHANNEL_POSITION_LFE PA_CHANNEL_POSITION_LFE -#define MAL_PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER -#define MAL_PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER -#define MAL_PA_CHANNEL_POSITION_SIDE_LEFT PA_CHANNEL_POSITION_SIDE_LEFT -#define MAL_PA_CHANNEL_POSITION_SIDE_RIGHT PA_CHANNEL_POSITION_SIDE_RIGHT -#define MAL_PA_CHANNEL_POSITION_AUX0 PA_CHANNEL_POSITION_AUX0 -#define MAL_PA_CHANNEL_POSITION_AUX1 PA_CHANNEL_POSITION_AUX1 -#define MAL_PA_CHANNEL_POSITION_AUX2 PA_CHANNEL_POSITION_AUX2 -#define MAL_PA_CHANNEL_POSITION_AUX3 PA_CHANNEL_POSITION_AUX3 -#define MAL_PA_CHANNEL_POSITION_AUX4 PA_CHANNEL_POSITION_AUX4 -#define MAL_PA_CHANNEL_POSITION_AUX5 PA_CHANNEL_POSITION_AUX5 -#define MAL_PA_CHANNEL_POSITION_AUX6 PA_CHANNEL_POSITION_AUX6 -#define MAL_PA_CHANNEL_POSITION_AUX7 PA_CHANNEL_POSITION_AUX7 -#define MAL_PA_CHANNEL_POSITION_AUX8 PA_CHANNEL_POSITION_AUX8 -#define MAL_PA_CHANNEL_POSITION_AUX9 PA_CHANNEL_POSITION_AUX9 -#define MAL_PA_CHANNEL_POSITION_AUX10 PA_CHANNEL_POSITION_AUX10 -#define MAL_PA_CHANNEL_POSITION_AUX11 PA_CHANNEL_POSITION_AUX11 -#define MAL_PA_CHANNEL_POSITION_AUX12 PA_CHANNEL_POSITION_AUX12 -#define MAL_PA_CHANNEL_POSITION_AUX13 PA_CHANNEL_POSITION_AUX13 -#define MAL_PA_CHANNEL_POSITION_AUX14 PA_CHANNEL_POSITION_AUX14 -#define MAL_PA_CHANNEL_POSITION_AUX15 PA_CHANNEL_POSITION_AUX15 -#define MAL_PA_CHANNEL_POSITION_AUX16 PA_CHANNEL_POSITION_AUX16 -#define MAL_PA_CHANNEL_POSITION_AUX17 PA_CHANNEL_POSITION_AUX17 -#define MAL_PA_CHANNEL_POSITION_AUX18 PA_CHANNEL_POSITION_AUX18 -#define MAL_PA_CHANNEL_POSITION_AUX19 PA_CHANNEL_POSITION_AUX19 -#define MAL_PA_CHANNEL_POSITION_AUX20 PA_CHANNEL_POSITION_AUX20 -#define MAL_PA_CHANNEL_POSITION_AUX21 PA_CHANNEL_POSITION_AUX21 -#define MAL_PA_CHANNEL_POSITION_AUX22 PA_CHANNEL_POSITION_AUX22 -#define MAL_PA_CHANNEL_POSITION_AUX23 PA_CHANNEL_POSITION_AUX23 -#define MAL_PA_CHANNEL_POSITION_AUX24 PA_CHANNEL_POSITION_AUX24 -#define MAL_PA_CHANNEL_POSITION_AUX25 PA_CHANNEL_POSITION_AUX25 -#define MAL_PA_CHANNEL_POSITION_AUX26 PA_CHANNEL_POSITION_AUX26 -#define MAL_PA_CHANNEL_POSITION_AUX27 PA_CHANNEL_POSITION_AUX27 -#define MAL_PA_CHANNEL_POSITION_AUX28 PA_CHANNEL_POSITION_AUX28 -#define MAL_PA_CHANNEL_POSITION_AUX29 PA_CHANNEL_POSITION_AUX29 -#define MAL_PA_CHANNEL_POSITION_AUX30 PA_CHANNEL_POSITION_AUX30 -#define MAL_PA_CHANNEL_POSITION_AUX31 PA_CHANNEL_POSITION_AUX31 -#define MAL_PA_CHANNEL_POSITION_TOP_CENTER PA_CHANNEL_POSITION_TOP_CENTER -#define MAL_PA_CHANNEL_POSITION_TOP_FRONT_LEFT PA_CHANNEL_POSITION_TOP_FRONT_LEFT -#define MAL_PA_CHANNEL_POSITION_TOP_FRONT_RIGHT PA_CHANNEL_POSITION_TOP_FRONT_RIGHT -#define MAL_PA_CHANNEL_POSITION_TOP_FRONT_CENTER PA_CHANNEL_POSITION_TOP_FRONT_CENTER -#define MAL_PA_CHANNEL_POSITION_TOP_REAR_LEFT PA_CHANNEL_POSITION_TOP_REAR_LEFT -#define MAL_PA_CHANNEL_POSITION_TOP_REAR_RIGHT PA_CHANNEL_POSITION_TOP_REAR_RIGHT -#define MAL_PA_CHANNEL_POSITION_TOP_REAR_CENTER PA_CHANNEL_POSITION_TOP_REAR_CENTER -#define MAL_PA_CHANNEL_POSITION_LEFT PA_CHANNEL_POSITION_LEFT -#define MAL_PA_CHANNEL_POSITION_RIGHT PA_CHANNEL_POSITION_RIGHT -#define MAL_PA_CHANNEL_POSITION_CENTER PA_CHANNEL_POSITION_CENTER -#define MAL_PA_CHANNEL_POSITION_SUBWOOFER PA_CHANNEL_POSITION_SUBWOOFER - -typedef pa_channel_map_def_t mal_pa_channel_map_def_t; -#define MAL_PA_CHANNEL_MAP_AIFF PA_CHANNEL_MAP_AIFF -#define MAL_PA_CHANNEL_MAP_ALSA PA_CHANNEL_MAP_ALSA -#define MAL_PA_CHANNEL_MAP_AUX PA_CHANNEL_MAP_AUX -#define MAL_PA_CHANNEL_MAP_WAVEEX PA_CHANNEL_MAP_WAVEEX -#define MAL_PA_CHANNEL_MAP_OSS PA_CHANNEL_MAP_OSS -#define MAL_PA_CHANNEL_MAP_DEFAULT PA_CHANNEL_MAP_DEFAULT - -typedef pa_sample_format_t mal_pa_sample_format_t; -#define MAL_PA_SAMPLE_INVALID PA_SAMPLE_INVALID -#define MAL_PA_SAMPLE_U8 PA_SAMPLE_U8 -#define MAL_PA_SAMPLE_ALAW PA_SAMPLE_ALAW -#define MAL_PA_SAMPLE_ULAW PA_SAMPLE_ULAW -#define MAL_PA_SAMPLE_S16LE PA_SAMPLE_S16LE -#define MAL_PA_SAMPLE_S16BE PA_SAMPLE_S16BE -#define MAL_PA_SAMPLE_FLOAT32LE PA_SAMPLE_FLOAT32LE -#define MAL_PA_SAMPLE_FLOAT32BE PA_SAMPLE_FLOAT32BE -#define MAL_PA_SAMPLE_S32LE PA_SAMPLE_S32LE -#define MAL_PA_SAMPLE_S32BE PA_SAMPLE_S32BE -#define MAL_PA_SAMPLE_S24LE PA_SAMPLE_S24LE -#define MAL_PA_SAMPLE_S24BE PA_SAMPLE_S24BE -#define MAL_PA_SAMPLE_S24_32LE PA_SAMPLE_S24_32LE -#define MAL_PA_SAMPLE_S24_32BE PA_SAMPLE_S24_32BE - -typedef pa_mainloop mal_pa_mainloop; -typedef pa_mainloop_api mal_pa_mainloop_api; -typedef pa_context mal_pa_context; -typedef pa_operation mal_pa_operation; -typedef pa_stream mal_pa_stream; -typedef pa_spawn_api mal_pa_spawn_api; -typedef pa_buffer_attr mal_pa_buffer_attr; -typedef pa_channel_map mal_pa_channel_map; -typedef pa_cvolume mal_pa_cvolume; -typedef pa_sample_spec mal_pa_sample_spec; -typedef pa_sink_info mal_pa_sink_info; -typedef pa_source_info mal_pa_source_info; - -typedef pa_context_notify_cb_t mal_pa_context_notify_cb_t; -typedef pa_sink_info_cb_t mal_pa_sink_info_cb_t; -typedef pa_source_info_cb_t mal_pa_source_info_cb_t; -typedef pa_stream_success_cb_t mal_pa_stream_success_cb_t; -typedef pa_stream_request_cb_t mal_pa_stream_request_cb_t; -typedef pa_free_cb_t mal_pa_free_cb_t; -#else -#define MAL_PA_OK 0 -#define MAL_PA_ERR_ACCESS 1 -#define MAL_PA_ERR_INVALID 2 -#define MAL_PA_ERR_NOENTITY 5 - -#define MAL_PA_CHANNELS_MAX 32 -#define MAL_PA_RATE_MAX 384000 - -typedef int mal_pa_context_flags_t; -#define MAL_PA_CONTEXT_NOFLAGS 0x00000000 -#define MAL_PA_CONTEXT_NOAUTOSPAWN 0x00000001 -#define MAL_PA_CONTEXT_NOFAIL 0x00000002 - -typedef int mal_pa_stream_flags_t; -#define MAL_PA_STREAM_NOFLAGS 0x00000000 -#define MAL_PA_STREAM_START_CORKED 0x00000001 -#define MAL_PA_STREAM_INTERPOLATE_TIMING 0x00000002 -#define MAL_PA_STREAM_NOT_MONOTONIC 0x00000004 -#define MAL_PA_STREAM_AUTO_TIMING_UPDATE 0x00000008 -#define MAL_PA_STREAM_NO_REMAP_CHANNELS 0x00000010 -#define MAL_PA_STREAM_NO_REMIX_CHANNELS 0x00000020 -#define MAL_PA_STREAM_FIX_FORMAT 0x00000040 -#define MAL_PA_STREAM_FIX_RATE 0x00000080 -#define MAL_PA_STREAM_FIX_CHANNELS 0x00000100 -#define MAL_PA_STREAM_DONT_MOVE 0x00000200 -#define MAL_PA_STREAM_VARIABLE_RATE 0x00000400 -#define MAL_PA_STREAM_PEAK_DETECT 0x00000800 -#define MAL_PA_STREAM_START_MUTED 0x00001000 -#define MAL_PA_STREAM_ADJUST_LATENCY 0x00002000 -#define MAL_PA_STREAM_EARLY_REQUESTS 0x00004000 -#define MAL_PA_STREAM_DONT_INHIBIT_AUTO_SUSPEND 0x00008000 -#define MAL_PA_STREAM_START_UNMUTED 0x00010000 -#define MAL_PA_STREAM_FAIL_ON_SUSPEND 0x00020000 -#define MAL_PA_STREAM_RELATIVE_VOLUME 0x00040000 -#define MAL_PA_STREAM_PASSTHROUGH 0x00080000 - -typedef int mal_pa_sink_flags_t; -#define MAL_PA_SINK_NOFLAGS 0x00000000 -#define MAL_PA_SINK_HW_VOLUME_CTRL 0x00000001 -#define MAL_PA_SINK_LATENCY 0x00000002 -#define MAL_PA_SINK_HARDWARE 0x00000004 -#define MAL_PA_SINK_NETWORK 0x00000008 -#define MAL_PA_SINK_HW_MUTE_CTRL 0x00000010 -#define MAL_PA_SINK_DECIBEL_VOLUME 0x00000020 -#define MAL_PA_SINK_FLAT_VOLUME 0x00000040 -#define MAL_PA_SINK_DYNAMIC_LATENCY 0x00000080 -#define MAL_PA_SINK_SET_FORMATS 0x00000100 - -typedef int mal_pa_source_flags_t; -#define MAL_PA_SOURCE_NOFLAGS 0x00000000 -#define MAL_PA_SOURCE_HW_VOLUME_CTRL 0x00000001 -#define MAL_PA_SOURCE_LATENCY 0x00000002 -#define MAL_PA_SOURCE_HARDWARE 0x00000004 -#define MAL_PA_SOURCE_NETWORK 0x00000008 -#define MAL_PA_SOURCE_HW_MUTE_CTRL 0x00000010 -#define MAL_PA_SOURCE_DECIBEL_VOLUME 0x00000020 -#define MAL_PA_SOURCE_DYNAMIC_LATENCY 0x00000040 -#define MAL_PA_SOURCE_FLAT_VOLUME 0x00000080 - -typedef int mal_pa_context_state_t; -#define MAL_PA_CONTEXT_UNCONNECTED 0 -#define MAL_PA_CONTEXT_CONNECTING 1 -#define MAL_PA_CONTEXT_AUTHORIZING 2 -#define MAL_PA_CONTEXT_SETTING_NAME 3 -#define MAL_PA_CONTEXT_READY 4 -#define MAL_PA_CONTEXT_FAILED 5 -#define MAL_PA_CONTEXT_TERMINATED 6 - -typedef int mal_pa_stream_state_t; -#define MAL_PA_STREAM_UNCONNECTED 0 -#define MAL_PA_STREAM_CREATING 1 -#define MAL_PA_STREAM_READY 2 -#define MAL_PA_STREAM_FAILED 3 -#define MAL_PA_STREAM_TERMINATED 4 - -typedef int mal_pa_operation_state_t; -#define MAL_PA_OPERATION_RUNNING 0 -#define MAL_PA_OPERATION_DONE 1 -#define MAL_PA_OPERATION_CANCELLED 2 - -typedef int mal_pa_sink_state_t; -#define MAL_PA_SINK_INVALID_STATE -1 -#define MAL_PA_SINK_RUNNING 0 -#define MAL_PA_SINK_IDLE 1 -#define MAL_PA_SINK_SUSPENDED 2 - -typedef int mal_pa_source_state_t; -#define MAL_PA_SOURCE_INVALID_STATE -1 -#define MAL_PA_SOURCE_RUNNING 0 -#define MAL_PA_SOURCE_IDLE 1 -#define MAL_PA_SOURCE_SUSPENDED 2 - -typedef int mal_pa_seek_mode_t; -#define MAL_PA_SEEK_RELATIVE 0 -#define MAL_PA_SEEK_ABSOLUTE 1 -#define MAL_PA_SEEK_RELATIVE_ON_READ 2 -#define MAL_PA_SEEK_RELATIVE_END 3 - -typedef int mal_pa_channel_position_t; -#define MAL_PA_CHANNEL_POSITION_INVALID -1 -#define MAL_PA_CHANNEL_POSITION_MONO 0 -#define MAL_PA_CHANNEL_POSITION_FRONT_LEFT 1 -#define MAL_PA_CHANNEL_POSITION_FRONT_RIGHT 2 -#define MAL_PA_CHANNEL_POSITION_FRONT_CENTER 3 -#define MAL_PA_CHANNEL_POSITION_REAR_CENTER 4 -#define MAL_PA_CHANNEL_POSITION_REAR_LEFT 5 -#define MAL_PA_CHANNEL_POSITION_REAR_RIGHT 6 -#define MAL_PA_CHANNEL_POSITION_LFE 7 -#define MAL_PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER 8 -#define MAL_PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER 9 -#define MAL_PA_CHANNEL_POSITION_SIDE_LEFT 10 -#define MAL_PA_CHANNEL_POSITION_SIDE_RIGHT 11 -#define MAL_PA_CHANNEL_POSITION_AUX0 12 -#define MAL_PA_CHANNEL_POSITION_AUX1 13 -#define MAL_PA_CHANNEL_POSITION_AUX2 14 -#define MAL_PA_CHANNEL_POSITION_AUX3 15 -#define MAL_PA_CHANNEL_POSITION_AUX4 16 -#define MAL_PA_CHANNEL_POSITION_AUX5 17 -#define MAL_PA_CHANNEL_POSITION_AUX6 18 -#define MAL_PA_CHANNEL_POSITION_AUX7 19 -#define MAL_PA_CHANNEL_POSITION_AUX8 20 -#define MAL_PA_CHANNEL_POSITION_AUX9 21 -#define MAL_PA_CHANNEL_POSITION_AUX10 22 -#define MAL_PA_CHANNEL_POSITION_AUX11 23 -#define MAL_PA_CHANNEL_POSITION_AUX12 24 -#define MAL_PA_CHANNEL_POSITION_AUX13 25 -#define MAL_PA_CHANNEL_POSITION_AUX14 26 -#define MAL_PA_CHANNEL_POSITION_AUX15 27 -#define MAL_PA_CHANNEL_POSITION_AUX16 28 -#define MAL_PA_CHANNEL_POSITION_AUX17 29 -#define MAL_PA_CHANNEL_POSITION_AUX18 30 -#define MAL_PA_CHANNEL_POSITION_AUX19 31 -#define MAL_PA_CHANNEL_POSITION_AUX20 32 -#define MAL_PA_CHANNEL_POSITION_AUX21 33 -#define MAL_PA_CHANNEL_POSITION_AUX22 34 -#define MAL_PA_CHANNEL_POSITION_AUX23 35 -#define MAL_PA_CHANNEL_POSITION_AUX24 36 -#define MAL_PA_CHANNEL_POSITION_AUX25 37 -#define MAL_PA_CHANNEL_POSITION_AUX26 38 -#define MAL_PA_CHANNEL_POSITION_AUX27 39 -#define MAL_PA_CHANNEL_POSITION_AUX28 40 -#define MAL_PA_CHANNEL_POSITION_AUX29 41 -#define MAL_PA_CHANNEL_POSITION_AUX30 42 -#define MAL_PA_CHANNEL_POSITION_AUX31 43 -#define MAL_PA_CHANNEL_POSITION_TOP_CENTER 44 -#define MAL_PA_CHANNEL_POSITION_TOP_FRONT_LEFT 45 -#define MAL_PA_CHANNEL_POSITION_TOP_FRONT_RIGHT 46 -#define MAL_PA_CHANNEL_POSITION_TOP_FRONT_CENTER 47 -#define MAL_PA_CHANNEL_POSITION_TOP_REAR_LEFT 48 -#define MAL_PA_CHANNEL_POSITION_TOP_REAR_RIGHT 49 -#define MAL_PA_CHANNEL_POSITION_TOP_REAR_CENTER 50 -#define MAL_PA_CHANNEL_POSITION_LEFT MAL_PA_CHANNEL_POSITION_FRONT_LEFT -#define MAL_PA_CHANNEL_POSITION_RIGHT MAL_PA_CHANNEL_POSITION_FRONT_RIGHT -#define MAL_PA_CHANNEL_POSITION_CENTER MAL_PA_CHANNEL_POSITION_FRONT_CENTER -#define MAL_PA_CHANNEL_POSITION_SUBWOOFER MAL_PA_CHANNEL_POSITION_LFE - -typedef int mal_pa_channel_map_def_t; -#define MAL_PA_CHANNEL_MAP_AIFF 0 -#define MAL_PA_CHANNEL_MAP_ALSA 1 -#define MAL_PA_CHANNEL_MAP_AUX 2 -#define MAL_PA_CHANNEL_MAP_WAVEEX 3 -#define MAL_PA_CHANNEL_MAP_OSS 4 -#define MAL_PA_CHANNEL_MAP_DEFAULT MAL_PA_CHANNEL_MAP_AIFF - -typedef int mal_pa_sample_format_t; -#define MAL_PA_SAMPLE_INVALID -1 -#define MAL_PA_SAMPLE_U8 0 -#define MAL_PA_SAMPLE_ALAW 1 -#define MAL_PA_SAMPLE_ULAW 2 -#define MAL_PA_SAMPLE_S16LE 3 -#define MAL_PA_SAMPLE_S16BE 4 -#define MAL_PA_SAMPLE_FLOAT32LE 5 -#define MAL_PA_SAMPLE_FLOAT32BE 6 -#define MAL_PA_SAMPLE_S32LE 7 -#define MAL_PA_SAMPLE_S32BE 8 -#define MAL_PA_SAMPLE_S24LE 9 -#define MAL_PA_SAMPLE_S24BE 10 -#define MAL_PA_SAMPLE_S24_32LE 11 -#define MAL_PA_SAMPLE_S24_32BE 12 - -typedef struct mal_pa_mainloop mal_pa_mainloop; -typedef struct mal_pa_mainloop_api mal_pa_mainloop_api; -typedef struct mal_pa_context mal_pa_context; -typedef struct mal_pa_operation mal_pa_operation; -typedef struct mal_pa_stream mal_pa_stream; -typedef struct mal_pa_spawn_api mal_pa_spawn_api; - -typedef struct -{ - mal_uint32 maxlength; - mal_uint32 tlength; - mal_uint32 prebuf; - mal_uint32 minreq; - mal_uint32 fragsize; -} mal_pa_buffer_attr; - -typedef struct -{ - mal_uint8 channels; - mal_pa_channel_position_t map[MAL_PA_CHANNELS_MAX]; -} mal_pa_channel_map; - -typedef struct -{ - mal_uint8 channels; - mal_uint32 values[MAL_PA_CHANNELS_MAX]; -} mal_pa_cvolume; - -typedef struct -{ - mal_pa_sample_format_t format; - mal_uint32 rate; - mal_uint8 channels; -} mal_pa_sample_spec; - -typedef struct -{ - const char* name; - mal_uint32 index; - const char* description; - mal_pa_sample_spec sample_spec; - mal_pa_channel_map channel_map; - mal_uint32 owner_module; - mal_pa_cvolume volume; - int mute; - mal_uint32 monitor_source; - const char* monitor_source_name; - mal_uint64 latency; - const char* driver; - mal_pa_sink_flags_t flags; - void* proplist; - mal_uint64 configured_latency; - mal_uint32 base_volume; - mal_pa_sink_state_t state; - mal_uint32 n_volume_steps; - mal_uint32 card; - mal_uint32 n_ports; - void** ports; - void* active_port; - mal_uint8 n_formats; - void** formats; -} mal_pa_sink_info; - -typedef struct -{ - const char *name; - mal_uint32 index; - const char *description; - mal_pa_sample_spec sample_spec; - mal_pa_channel_map channel_map; - mal_uint32 owner_module; - mal_pa_cvolume volume; - int mute; - mal_uint32 monitor_of_sink; - const char *monitor_of_sink_name; - mal_uint64 latency; - const char *driver; - mal_pa_source_flags_t flags; - void* proplist; - mal_uint64 configured_latency; - mal_uint32 base_volume; - mal_pa_source_state_t state; - mal_uint32 n_volume_steps; - mal_uint32 card; - mal_uint32 n_ports; - void** ports; - void* active_port; - mal_uint8 n_formats; - void** formats; -} mal_pa_source_info; - -typedef void (* mal_pa_context_notify_cb_t)(mal_pa_context* c, void* userdata); -typedef void (* mal_pa_sink_info_cb_t) (mal_pa_context* c, const mal_pa_sink_info* i, int eol, void* userdata); -typedef void (* mal_pa_source_info_cb_t) (mal_pa_context* c, const mal_pa_source_info* i, int eol, void* userdata); -typedef void (* mal_pa_stream_success_cb_t)(mal_pa_stream* s, int success, void* userdata); -typedef void (* mal_pa_stream_request_cb_t)(mal_pa_stream* s, size_t nbytes, void* userdata); -typedef void (* mal_pa_free_cb_t) (void* p); -#endif - - -typedef mal_pa_mainloop* (* mal_pa_mainloop_new_proc) (); -typedef void (* mal_pa_mainloop_free_proc) (mal_pa_mainloop* m); -typedef mal_pa_mainloop_api* (* mal_pa_mainloop_get_api_proc) (mal_pa_mainloop* m); -typedef int (* mal_pa_mainloop_iterate_proc) (mal_pa_mainloop* m, int block, int* retval); -typedef void (* mal_pa_mainloop_wakeup_proc) (mal_pa_mainloop* m); -typedef mal_pa_context* (* mal_pa_context_new_proc) (mal_pa_mainloop_api* mainloop, const char* name); -typedef void (* mal_pa_context_unref_proc) (mal_pa_context* c); -typedef int (* mal_pa_context_connect_proc) (mal_pa_context* c, const char* server, mal_pa_context_flags_t flags, const mal_pa_spawn_api* api); -typedef void (* mal_pa_context_disconnect_proc) (mal_pa_context* c); -typedef void (* mal_pa_context_set_state_callback_proc) (mal_pa_context* c, mal_pa_context_notify_cb_t cb, void* userdata); -typedef mal_pa_context_state_t (* mal_pa_context_get_state_proc) (mal_pa_context* c); -typedef mal_pa_operation* (* mal_pa_context_get_sink_info_list_proc) (mal_pa_context* c, mal_pa_sink_info_cb_t cb, void* userdata); -typedef mal_pa_operation* (* mal_pa_context_get_source_info_list_proc) (mal_pa_context* c, mal_pa_source_info_cb_t cb, void* userdata); -typedef mal_pa_operation* (* mal_pa_context_get_sink_info_by_name_proc) (mal_pa_context* c, const char* name, mal_pa_sink_info_cb_t cb, void* userdata); -typedef mal_pa_operation* (* mal_pa_context_get_source_info_by_name_proc)(mal_pa_context* c, const char* name, mal_pa_source_info_cb_t cb, void* userdata); -typedef void (* mal_pa_operation_unref_proc) (mal_pa_operation* o); -typedef mal_pa_operation_state_t (* mal_pa_operation_get_state_proc) (mal_pa_operation* o); -typedef mal_pa_channel_map* (* mal_pa_channel_map_init_extend_proc) (mal_pa_channel_map* m, unsigned channels, mal_pa_channel_map_def_t def); -typedef int (* mal_pa_channel_map_valid_proc) (const mal_pa_channel_map* m); -typedef int (* mal_pa_channel_map_compatible_proc) (const mal_pa_channel_map* m, const mal_pa_sample_spec* ss); -typedef mal_pa_stream* (* mal_pa_stream_new_proc) (mal_pa_context* c, const char* name, const mal_pa_sample_spec* ss, const mal_pa_channel_map* map); -typedef void (* mal_pa_stream_unref_proc) (mal_pa_stream* s); -typedef int (* mal_pa_stream_connect_playback_proc) (mal_pa_stream* s, const char* dev, const mal_pa_buffer_attr* attr, mal_pa_stream_flags_t flags, const mal_pa_cvolume* volume, mal_pa_stream* sync_stream); -typedef int (* mal_pa_stream_connect_record_proc) (mal_pa_stream* s, const char* dev, const mal_pa_buffer_attr* attr, mal_pa_stream_flags_t flags); -typedef int (* mal_pa_stream_disconnect_proc) (mal_pa_stream* s); -typedef mal_pa_stream_state_t (* mal_pa_stream_get_state_proc) (mal_pa_stream* s); -typedef const mal_pa_sample_spec* (* mal_pa_stream_get_sample_spec_proc) (mal_pa_stream* s); -typedef const mal_pa_channel_map* (* mal_pa_stream_get_channel_map_proc) (mal_pa_stream* s); -typedef const mal_pa_buffer_attr* (* mal_pa_stream_get_buffer_attr_proc) (mal_pa_stream* s); -typedef mal_pa_operation* (* mal_pa_stream_set_buffer_attr_proc) (mal_pa_stream* s, const mal_pa_buffer_attr* attr, mal_pa_stream_success_cb_t cb, void* userdata); -typedef const char* (* mal_pa_stream_get_device_name_proc) (mal_pa_stream* s); -typedef void (* mal_pa_stream_set_write_callback_proc) (mal_pa_stream* s, mal_pa_stream_request_cb_t cb, void* userdata); -typedef void (* mal_pa_stream_set_read_callback_proc) (mal_pa_stream* s, mal_pa_stream_request_cb_t cb, void* userdata); -typedef mal_pa_operation* (* mal_pa_stream_flush_proc) (mal_pa_stream* s, mal_pa_stream_success_cb_t cb, void* userdata); -typedef mal_pa_operation* (* mal_pa_stream_drain_proc) (mal_pa_stream* s, mal_pa_stream_success_cb_t cb, void* userdata); -typedef mal_pa_operation* (* mal_pa_stream_cork_proc) (mal_pa_stream* s, int b, mal_pa_stream_success_cb_t cb, void* userdata); -typedef mal_pa_operation* (* mal_pa_stream_trigger_proc) (mal_pa_stream* s, mal_pa_stream_success_cb_t cb, void* userdata); -typedef int (* mal_pa_stream_begin_write_proc) (mal_pa_stream* s, void** data, size_t* nbytes); -typedef int (* mal_pa_stream_write_proc) (mal_pa_stream* s, const void* data, size_t nbytes, mal_pa_free_cb_t free_cb, int64_t offset, mal_pa_seek_mode_t seek); -typedef int (* mal_pa_stream_peek_proc) (mal_pa_stream* s, const void** data, size_t* nbytes); -typedef int (* mal_pa_stream_drop_proc) (mal_pa_stream* s); - -typedef struct -{ - mal_uint32 count; - mal_uint32 capacity; - mal_device_info* pInfo; -} mal_pulse_device_enum_data; - -mal_result mal_result_from_pulse(int result) -{ - switch (result) { - case MAL_PA_OK: return MAL_SUCCESS; - case MAL_PA_ERR_ACCESS: return MAL_ACCESS_DENIED; - case MAL_PA_ERR_INVALID: return MAL_INVALID_ARGS; - case MAL_PA_ERR_NOENTITY: return MAL_NO_DEVICE; - default: return MAL_ERROR; - } -} - -#if 0 -mal_pa_sample_format_t mal_format_to_pulse(mal_format format) -{ - if (mal_is_little_endian()) { - switch (format) { - case mal_format_s16: return MAL_PA_SAMPLE_S16LE; - case mal_format_s24: return MAL_PA_SAMPLE_S24LE; - case mal_format_s32: return MAL_PA_SAMPLE_S32LE; - case mal_format_f32: return MAL_PA_SAMPLE_FLOAT32LE; - default: break; - } - } else { - switch (format) { - case mal_format_s16: return MAL_PA_SAMPLE_S16BE; - case mal_format_s24: return MAL_PA_SAMPLE_S24BE; - case mal_format_s32: return MAL_PA_SAMPLE_S32BE; - case mal_format_f32: return MAL_PA_SAMPLE_FLOAT32BE; - default: break; - } - } - - // Endian agnostic. - switch (format) { - case mal_format_u8: return MAL_PA_SAMPLE_U8; - default: return MAL_PA_SAMPLE_INVALID; - } -} -#endif - -mal_format mal_format_from_pulse(mal_pa_sample_format_t format) -{ - if (mal_is_little_endian()) { - switch (format) { - case MAL_PA_SAMPLE_S16LE: return mal_format_s16; - case MAL_PA_SAMPLE_S24LE: return mal_format_s24; - case MAL_PA_SAMPLE_S32LE: return mal_format_s32; - case MAL_PA_SAMPLE_FLOAT32LE: return mal_format_f32; - default: break; - } - } else { - switch (format) { - case MAL_PA_SAMPLE_S16BE: return mal_format_s16; - case MAL_PA_SAMPLE_S24BE: return mal_format_s24; - case MAL_PA_SAMPLE_S32BE: return mal_format_s32; - case MAL_PA_SAMPLE_FLOAT32BE: return mal_format_f32; - default: break; - } - } - - // Endian agnostic. - switch (format) { - case MAL_PA_SAMPLE_U8: return mal_format_u8; - default: return mal_format_unknown; - } -} - -mal_channel mal_channel_position_from_pulse(mal_pa_channel_position_t position) -{ - switch (position) - { - case MAL_PA_CHANNEL_POSITION_INVALID: return MAL_CHANNEL_NONE; - case MAL_PA_CHANNEL_POSITION_MONO: return MAL_CHANNEL_MONO; - case MAL_PA_CHANNEL_POSITION_FRONT_LEFT: return MAL_CHANNEL_FRONT_LEFT; - case MAL_PA_CHANNEL_POSITION_FRONT_RIGHT: return MAL_CHANNEL_FRONT_RIGHT; - case MAL_PA_CHANNEL_POSITION_FRONT_CENTER: return MAL_CHANNEL_FRONT_CENTER; - case MAL_PA_CHANNEL_POSITION_REAR_CENTER: return MAL_CHANNEL_BACK_CENTER; - case MAL_PA_CHANNEL_POSITION_REAR_LEFT: return MAL_CHANNEL_BACK_LEFT; - case MAL_PA_CHANNEL_POSITION_REAR_RIGHT: return MAL_CHANNEL_BACK_RIGHT; - case MAL_PA_CHANNEL_POSITION_LFE: return MAL_CHANNEL_LFE; - case MAL_PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER: return MAL_CHANNEL_FRONT_LEFT_CENTER; - case MAL_PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER: return MAL_CHANNEL_FRONT_RIGHT_CENTER; - case MAL_PA_CHANNEL_POSITION_SIDE_LEFT: return MAL_CHANNEL_SIDE_LEFT; - case MAL_PA_CHANNEL_POSITION_SIDE_RIGHT: return MAL_CHANNEL_SIDE_RIGHT; - case MAL_PA_CHANNEL_POSITION_AUX0: return MAL_CHANNEL_AUX_0; - case MAL_PA_CHANNEL_POSITION_AUX1: return MAL_CHANNEL_AUX_1; - case MAL_PA_CHANNEL_POSITION_AUX2: return MAL_CHANNEL_AUX_2; - case MAL_PA_CHANNEL_POSITION_AUX3: return MAL_CHANNEL_AUX_3; - case MAL_PA_CHANNEL_POSITION_AUX4: return MAL_CHANNEL_AUX_4; - case MAL_PA_CHANNEL_POSITION_AUX5: return MAL_CHANNEL_AUX_5; - case MAL_PA_CHANNEL_POSITION_AUX6: return MAL_CHANNEL_AUX_6; - case MAL_PA_CHANNEL_POSITION_AUX7: return MAL_CHANNEL_AUX_7; - case MAL_PA_CHANNEL_POSITION_AUX8: return MAL_CHANNEL_AUX_8; - case MAL_PA_CHANNEL_POSITION_AUX9: return MAL_CHANNEL_AUX_9; - case MAL_PA_CHANNEL_POSITION_AUX10: return MAL_CHANNEL_AUX_10; - case MAL_PA_CHANNEL_POSITION_AUX11: return MAL_CHANNEL_AUX_11; - case MAL_PA_CHANNEL_POSITION_AUX12: return MAL_CHANNEL_AUX_12; - case MAL_PA_CHANNEL_POSITION_AUX13: return MAL_CHANNEL_AUX_13; - case MAL_PA_CHANNEL_POSITION_AUX14: return MAL_CHANNEL_AUX_14; - case MAL_PA_CHANNEL_POSITION_AUX15: return MAL_CHANNEL_AUX_15; - case MAL_PA_CHANNEL_POSITION_AUX16: return MAL_CHANNEL_AUX_16; - case MAL_PA_CHANNEL_POSITION_AUX17: return MAL_CHANNEL_AUX_17; - case MAL_PA_CHANNEL_POSITION_AUX18: return MAL_CHANNEL_AUX_18; - case MAL_PA_CHANNEL_POSITION_AUX19: return MAL_CHANNEL_AUX_19; - case MAL_PA_CHANNEL_POSITION_AUX20: return MAL_CHANNEL_AUX_20; - case MAL_PA_CHANNEL_POSITION_AUX21: return MAL_CHANNEL_AUX_21; - case MAL_PA_CHANNEL_POSITION_AUX22: return MAL_CHANNEL_AUX_22; - case MAL_PA_CHANNEL_POSITION_AUX23: return MAL_CHANNEL_AUX_23; - case MAL_PA_CHANNEL_POSITION_AUX24: return MAL_CHANNEL_AUX_24; - case MAL_PA_CHANNEL_POSITION_AUX25: return MAL_CHANNEL_AUX_25; - case MAL_PA_CHANNEL_POSITION_AUX26: return MAL_CHANNEL_AUX_26; - case MAL_PA_CHANNEL_POSITION_AUX27: return MAL_CHANNEL_AUX_27; - case MAL_PA_CHANNEL_POSITION_AUX28: return MAL_CHANNEL_AUX_28; - case MAL_PA_CHANNEL_POSITION_AUX29: return MAL_CHANNEL_AUX_29; - case MAL_PA_CHANNEL_POSITION_AUX30: return MAL_CHANNEL_AUX_30; - case MAL_PA_CHANNEL_POSITION_AUX31: return MAL_CHANNEL_AUX_31; - case MAL_PA_CHANNEL_POSITION_TOP_CENTER: return MAL_CHANNEL_TOP_CENTER; - case MAL_PA_CHANNEL_POSITION_TOP_FRONT_LEFT: return MAL_CHANNEL_TOP_FRONT_LEFT; - case MAL_PA_CHANNEL_POSITION_TOP_FRONT_RIGHT: return MAL_CHANNEL_TOP_FRONT_RIGHT; - case MAL_PA_CHANNEL_POSITION_TOP_FRONT_CENTER: return MAL_CHANNEL_TOP_FRONT_CENTER; - case MAL_PA_CHANNEL_POSITION_TOP_REAR_LEFT: return MAL_CHANNEL_TOP_BACK_LEFT; - case MAL_PA_CHANNEL_POSITION_TOP_REAR_RIGHT: return MAL_CHANNEL_TOP_BACK_RIGHT; - case MAL_PA_CHANNEL_POSITION_TOP_REAR_CENTER: return MAL_CHANNEL_TOP_BACK_CENTER; - default: return MAL_CHANNEL_NONE; - } -} - -#if 0 -mal_pa_channel_position_t mal_channel_position_to_pulse(mal_channel position) -{ - switch (position) - { - case MAL_CHANNEL_NONE: return MAL_PA_CHANNEL_POSITION_INVALID; - case MAL_CHANNEL_FRONT_LEFT: return MAL_PA_CHANNEL_POSITION_FRONT_LEFT; - case MAL_CHANNEL_FRONT_RIGHT: return MAL_PA_CHANNEL_POSITION_FRONT_RIGHT; - case MAL_CHANNEL_FRONT_CENTER: return MAL_PA_CHANNEL_POSITION_FRONT_CENTER; - case MAL_CHANNEL_LFE: return MAL_PA_CHANNEL_POSITION_LFE; - case MAL_CHANNEL_BACK_LEFT: return MAL_PA_CHANNEL_POSITION_REAR_LEFT; - case MAL_CHANNEL_BACK_RIGHT: return MAL_PA_CHANNEL_POSITION_REAR_RIGHT; - case MAL_CHANNEL_FRONT_LEFT_CENTER: return MAL_PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER; - case MAL_CHANNEL_FRONT_RIGHT_CENTER: return MAL_PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER; - case MAL_CHANNEL_BACK_CENTER: return MAL_PA_CHANNEL_POSITION_REAR_CENTER; - case MAL_CHANNEL_SIDE_LEFT: return MAL_PA_CHANNEL_POSITION_SIDE_LEFT; - case MAL_CHANNEL_SIDE_RIGHT: return MAL_PA_CHANNEL_POSITION_SIDE_RIGHT; - case MAL_CHANNEL_TOP_CENTER: return MAL_PA_CHANNEL_POSITION_TOP_CENTER; - case MAL_CHANNEL_TOP_FRONT_LEFT: return MAL_PA_CHANNEL_POSITION_TOP_FRONT_LEFT; - case MAL_CHANNEL_TOP_FRONT_CENTER: return MAL_PA_CHANNEL_POSITION_TOP_FRONT_CENTER; - case MAL_CHANNEL_TOP_FRONT_RIGHT: return MAL_PA_CHANNEL_POSITION_TOP_FRONT_RIGHT; - case MAL_CHANNEL_TOP_BACK_LEFT: return MAL_PA_CHANNEL_POSITION_TOP_REAR_LEFT; - case MAL_CHANNEL_TOP_BACK_CENTER: return MAL_PA_CHANNEL_POSITION_TOP_REAR_CENTER; - case MAL_CHANNEL_TOP_BACK_RIGHT: return MAL_PA_CHANNEL_POSITION_TOP_REAR_RIGHT; - case MAL_CHANNEL_19: return MAL_PA_CHANNEL_POSITION_AUX18; - case MAL_CHANNEL_20: return MAL_PA_CHANNEL_POSITION_AUX19; - case MAL_CHANNEL_21: return MAL_PA_CHANNEL_POSITION_AUX20; - case MAL_CHANNEL_22: return MAL_PA_CHANNEL_POSITION_AUX21; - case MAL_CHANNEL_23: return MAL_PA_CHANNEL_POSITION_AUX22; - case MAL_CHANNEL_24: return MAL_PA_CHANNEL_POSITION_AUX23; - case MAL_CHANNEL_25: return MAL_PA_CHANNEL_POSITION_AUX24; - case MAL_CHANNEL_26: return MAL_PA_CHANNEL_POSITION_AUX25; - case MAL_CHANNEL_27: return MAL_PA_CHANNEL_POSITION_AUX26; - case MAL_CHANNEL_28: return MAL_PA_CHANNEL_POSITION_AUX27; - case MAL_CHANNEL_29: return MAL_PA_CHANNEL_POSITION_AUX28; - case MAL_CHANNEL_30: return MAL_PA_CHANNEL_POSITION_AUX29; - case MAL_CHANNEL_31: return MAL_PA_CHANNEL_POSITION_AUX30; - case MAL_CHANNEL_32: return MAL_PA_CHANNEL_POSITION_AUX31; - default: return (mal_pa_channel_position_t)position; - } -} -#endif - - -mal_result mal_wait_for_operation__pulse(mal_context* pContext, mal_pa_mainloop* pMainLoop, mal_pa_operation* pOP) -{ - mal_assert(pContext != NULL); - mal_assert(pMainLoop != NULL); - mal_assert(pOP != NULL); - - while (((mal_pa_operation_get_state_proc)pContext->pulse.pa_operation_get_state)(pOP) != MAL_PA_OPERATION_DONE) { - int error = ((mal_pa_mainloop_iterate_proc)pContext->pulse.pa_mainloop_iterate)(pMainLoop, 1, NULL); - if (error < 0) { - return mal_result_from_pulse(error); - } - } - - return MAL_SUCCESS; -} - -mal_result mal_device__wait_for_operation__pulse(mal_device* pDevice, mal_pa_operation* pOP) -{ - mal_assert(pDevice != NULL); - mal_assert(pOP != NULL); - - return mal_wait_for_operation__pulse(pDevice->pContext, (mal_pa_mainloop*)pDevice->pulse.pMainLoop, pOP); -} - - -mal_bool32 mal_context_is_device_id_equal__pulse(mal_context* pContext, const mal_device_id* pID0, const mal_device_id* pID1) -{ - mal_assert(pContext != NULL); - mal_assert(pID0 != NULL); - mal_assert(pID1 != NULL); - (void)pContext; - - return mal_strcmp(pID0->pulse, pID1->pulse) == 0; -} - - -typedef struct -{ - mal_context* pContext; - mal_enum_devices_callback_proc callback; - void* pUserData; - mal_bool32 isTerminated; -} mal_context_enumerate_devices_callback_data__pulse; - -void mal_context_enumerate_devices_sink_callback__pulse(mal_pa_context* pPulseContext, const mal_pa_sink_info* pSinkInfo, int endOfList, void* pUserData) -{ - mal_context_enumerate_devices_callback_data__pulse* pData = (mal_context_enumerate_devices_callback_data__pulse*)pUserData; - mal_assert(pData != NULL); - - if (endOfList || pData->isTerminated) { - return; - } - - mal_device_info deviceInfo; - mal_zero_object(&deviceInfo); - - // The name from PulseAudio is the ID for mini_al. - if (pSinkInfo->name != NULL) { - mal_strncpy_s(deviceInfo.id.pulse, sizeof(deviceInfo.id.pulse), pSinkInfo->name, (size_t)-1); - } - - // The description from PulseAudio is the name for mini_al. - if (pSinkInfo->description != NULL) { - mal_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), pSinkInfo->description, (size_t)-1); - } - - pData->isTerminated = !pData->callback(pData->pContext, mal_device_type_playback, &deviceInfo, pData->pUserData); -} - -void mal_context_enumerate_devices_source_callback__pulse(mal_pa_context* pPulseContext, const mal_pa_source_info* pSinkInfo, int endOfList, void* pUserData) -{ - mal_context_enumerate_devices_callback_data__pulse* pData = (mal_context_enumerate_devices_callback_data__pulse*)pUserData; - mal_assert(pData != NULL); - - if (endOfList || pData->isTerminated) { - return; - } - - mal_device_info deviceInfo; - mal_zero_object(&deviceInfo); - - // The name from PulseAudio is the ID for mini_al. - if (pSinkInfo->name != NULL) { - mal_strncpy_s(deviceInfo.id.pulse, sizeof(deviceInfo.id.pulse), pSinkInfo->name, (size_t)-1); - } - - // The description from PulseAudio is the name for mini_al. - if (pSinkInfo->description != NULL) { - mal_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), pSinkInfo->description, (size_t)-1); - } - - pData->isTerminated = !pData->callback(pData->pContext, mal_device_type_capture, &deviceInfo, pData->pUserData); -} - -mal_result mal_context_enumerate_devices__pulse(mal_context* pContext, mal_enum_devices_callback_proc callback, void* pUserData) -{ - mal_assert(pContext != NULL); - mal_assert(callback != NULL); - - mal_result result = MAL_SUCCESS; - - mal_context_enumerate_devices_callback_data__pulse callbackData; - callbackData.pContext = pContext; - callbackData.callback = callback; - callbackData.pUserData = pUserData; - callbackData.isTerminated = MAL_FALSE; - - mal_pa_operation* pOP = NULL; - - mal_pa_mainloop* pMainLoop = ((mal_pa_mainloop_new_proc)pContext->pulse.pa_mainloop_new)(); - if (pMainLoop == NULL) { - return MAL_FAILED_TO_INIT_BACKEND; - } - - mal_pa_mainloop_api* pAPI = ((mal_pa_mainloop_get_api_proc)pContext->pulse.pa_mainloop_get_api)(pMainLoop); - if (pAPI == NULL) { - ((mal_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); - return MAL_FAILED_TO_INIT_BACKEND; - } - - mal_pa_context* pPulseContext = ((mal_pa_context_new_proc)pContext->pulse.pa_context_new)(pAPI, pContext->config.pulse.pApplicationName); - if (pPulseContext == NULL) { - ((mal_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); - return MAL_FAILED_TO_INIT_BACKEND; - } - - int error = ((mal_pa_context_connect_proc)pContext->pulse.pa_context_connect)(pPulseContext, pContext->config.pulse.pServerName, 0, NULL); - if (error != MAL_PA_OK) { - ((mal_pa_context_unref_proc)pContext->pulse.pa_context_unref)(pPulseContext); - ((mal_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); - return mal_result_from_pulse(error); - } - - while (((mal_pa_context_get_state_proc)pContext->pulse.pa_context_get_state)(pPulseContext) != MAL_PA_CONTEXT_READY) { - error = ((mal_pa_mainloop_iterate_proc)pContext->pulse.pa_mainloop_iterate)(pMainLoop, 1, NULL); - if (error < 0) { - result = mal_result_from_pulse(error); - goto done; - } - } - - - // Playback. - if (!callbackData.isTerminated) { - pOP = ((mal_pa_context_get_sink_info_list_proc)pContext->pulse.pa_context_get_sink_info_list)(pPulseContext, mal_context_enumerate_devices_sink_callback__pulse, &callbackData); - if (pOP == NULL) { - result = MAL_ERROR; - goto done; - } - - result = mal_wait_for_operation__pulse(pContext, pMainLoop, pOP); - ((mal_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP); - if (result != MAL_SUCCESS) { - goto done; - } - } - - - // Capture. - if (!callbackData.isTerminated) { - pOP = ((mal_pa_context_get_source_info_list_proc)pContext->pulse.pa_context_get_source_info_list)(pPulseContext, mal_context_enumerate_devices_source_callback__pulse, &callbackData); - if (pOP == NULL) { - result = MAL_ERROR; - goto done; - } - - result = mal_wait_for_operation__pulse(pContext, pMainLoop, pOP); - ((mal_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP); - if (result != MAL_SUCCESS) { - goto done; - } - } - -done: - ((mal_pa_context_disconnect_proc)pContext->pulse.pa_context_disconnect)(pPulseContext); - ((mal_pa_context_unref_proc)pContext->pulse.pa_context_unref)(pPulseContext); - ((mal_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); - return result; -} - - -typedef struct -{ - mal_device_info* pDeviceInfo; - mal_bool32 foundDevice; -} mal_context_get_device_info_callback_data__pulse; - -void mal_context_get_device_info_sink_callback__pulse(mal_pa_context* pPulseContext, const mal_pa_sink_info* pInfo, int endOfList, void* pUserData) -{ - if (endOfList > 0) { - return; - } - - mal_context_get_device_info_callback_data__pulse* pData = (mal_context_get_device_info_callback_data__pulse*)pUserData; - mal_assert(pData != NULL); - pData->foundDevice = MAL_TRUE; - - if (pInfo->name != NULL) { - mal_strncpy_s(pData->pDeviceInfo->id.pulse, sizeof(pData->pDeviceInfo->id.pulse), pInfo->name, (size_t)-1); - } - - if (pInfo->description != NULL) { - mal_strncpy_s(pData->pDeviceInfo->name, sizeof(pData->pDeviceInfo->name), pInfo->description, (size_t)-1); - } - - pData->pDeviceInfo->minChannels = pInfo->sample_spec.channels; - pData->pDeviceInfo->maxChannels = pInfo->sample_spec.channels; - pData->pDeviceInfo->minSampleRate = pInfo->sample_spec.rate; - pData->pDeviceInfo->maxSampleRate = pInfo->sample_spec.rate; - pData->pDeviceInfo->formatCount = 1; - pData->pDeviceInfo->formats[0] = mal_format_from_pulse(pInfo->sample_spec.format); -} - -void mal_context_get_device_info_source_callback__pulse(mal_pa_context* pPulseContext, const mal_pa_source_info* pInfo, int endOfList, void* pUserData) -{ - if (endOfList > 0) { - return; - } - - mal_context_get_device_info_callback_data__pulse* pData = (mal_context_get_device_info_callback_data__pulse*)pUserData; - mal_assert(pData != NULL); - pData->foundDevice = MAL_TRUE; - - if (pInfo->name != NULL) { - mal_strncpy_s(pData->pDeviceInfo->id.pulse, sizeof(pData->pDeviceInfo->id.pulse), pInfo->name, (size_t)-1); - } - - if (pInfo->description != NULL) { - mal_strncpy_s(pData->pDeviceInfo->name, sizeof(pData->pDeviceInfo->name), pInfo->description, (size_t)-1); - } - - pData->pDeviceInfo->minChannels = pInfo->sample_spec.channels; - pData->pDeviceInfo->maxChannels = pInfo->sample_spec.channels; - pData->pDeviceInfo->minSampleRate = pInfo->sample_spec.rate; - pData->pDeviceInfo->maxSampleRate = pInfo->sample_spec.rate; - pData->pDeviceInfo->formatCount = 1; - pData->pDeviceInfo->formats[0] = mal_format_from_pulse(pInfo->sample_spec.format); -} - -mal_result mal_context_get_device_info__pulse(mal_context* pContext, mal_device_type deviceType, const mal_device_id* pDeviceID, mal_share_mode shareMode, mal_device_info* pDeviceInfo) -{ - mal_assert(pContext != NULL); - (void)shareMode; - - mal_result result = MAL_SUCCESS; - - mal_context_get_device_info_callback_data__pulse callbackData; - callbackData.pDeviceInfo = pDeviceInfo; - callbackData.foundDevice = MAL_FALSE; - - mal_pa_operation* pOP = NULL; - - mal_pa_mainloop* pMainLoop = ((mal_pa_mainloop_new_proc)pContext->pulse.pa_mainloop_new)(); - if (pMainLoop == NULL) { - return MAL_FAILED_TO_INIT_BACKEND; - } - - mal_pa_mainloop_api* pAPI = ((mal_pa_mainloop_get_api_proc)pContext->pulse.pa_mainloop_get_api)(pMainLoop); - if (pAPI == NULL) { - ((mal_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); - return MAL_FAILED_TO_INIT_BACKEND; - } - - mal_pa_context* pPulseContext = ((mal_pa_context_new_proc)pContext->pulse.pa_context_new)(pAPI, pContext->config.pulse.pApplicationName); - if (pPulseContext == NULL) { - ((mal_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); - return MAL_FAILED_TO_INIT_BACKEND; - } - - int error = ((mal_pa_context_connect_proc)pContext->pulse.pa_context_connect)(pPulseContext, pContext->config.pulse.pServerName, 0, NULL); - if (error != MAL_PA_OK) { - ((mal_pa_context_unref_proc)pContext->pulse.pa_context_unref)(pPulseContext); - ((mal_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); - return mal_result_from_pulse(error); - } - - while (((mal_pa_context_get_state_proc)pContext->pulse.pa_context_get_state)(pPulseContext) != MAL_PA_CONTEXT_READY) { - error = ((mal_pa_mainloop_iterate_proc)pContext->pulse.pa_mainloop_iterate)(pMainLoop, 1, NULL); - if (error < 0) { - result = mal_result_from_pulse(error); - goto done; - } - } - - if (deviceType == mal_device_type_playback) { - pOP = ((mal_pa_context_get_sink_info_by_name_proc)pContext->pulse.pa_context_get_sink_info_by_name)(pPulseContext, pDeviceID->pulse, mal_context_get_device_info_sink_callback__pulse, &callbackData); - } else { - pOP = ((mal_pa_context_get_source_info_by_name_proc)pContext->pulse.pa_context_get_source_info_by_name)(pPulseContext, pDeviceID->pulse, mal_context_get_device_info_source_callback__pulse, &callbackData); - } - - if (pOP != NULL) { - mal_wait_for_operation__pulse(pContext, pMainLoop, pOP); - ((mal_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP); - } else { - result = MAL_ERROR; - goto done; - } - - if (!callbackData.foundDevice) { - result = MAL_NO_DEVICE; - goto done; - } - - -done: - ((mal_pa_context_disconnect_proc)pContext->pulse.pa_context_disconnect)(pPulseContext); - ((mal_pa_context_unref_proc)pContext->pulse.pa_context_unref)(pPulseContext); - ((mal_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); - return result; -} - - -void mal_pulse_device_state_callback(mal_pa_context* pPulseContext, void* pUserData) -{ - mal_device* pDevice = (mal_device*)pUserData; - mal_assert(pDevice != NULL); - - mal_context* pContext = pDevice->pContext; - mal_assert(pContext != NULL); - - pDevice->pulse.pulseContextState = ((mal_pa_context_get_state_proc)pContext->pulse.pa_context_get_state)(pPulseContext); -} - -void mal_pulse_device_write_callback(mal_pa_stream* pStream, size_t sizeInBytes, void* pUserData) -{ - mal_device* pDevice = (mal_device*)pUserData; - mal_assert(pDevice != NULL); - - mal_context* pContext = pDevice->pContext; - mal_assert(pContext != NULL); - -#ifdef MAL_DEBUG_OUTPUT - printf("[PulseAudio] write_callback: sizeInBytes=%d\n", (int)sizeInBytes); -#endif - - size_t bytesRemaining = sizeInBytes; - while (bytesRemaining > 0) { - size_t bytesToReadFromClient = bytesRemaining; - if (bytesToReadFromClient > 0xFFFFFFFF) { - bytesToReadFromClient = 0xFFFFFFFF; - } - - void* pBuffer = NULL; - int error = ((mal_pa_stream_begin_write_proc)pContext->pulse.pa_stream_begin_write)((mal_pa_stream*)pDevice->pulse.pStream, &pBuffer, &bytesToReadFromClient); - if (error < 0) { - mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[PulseAudio] Failed to retrieve write buffer for sending data to the device.", mal_result_from_pulse(error)); - return; - } - -#ifdef MAL_DEBUG_OUTPUT - printf(" bytesToReadFromClient=%d", (int)bytesToReadFromClient); -#endif - - if (pBuffer != NULL && bytesToReadFromClient > 0) { - mal_uint32 framesToReadFromClient = (mal_uint32)bytesToReadFromClient / (pDevice->internalChannels*mal_get_bytes_per_sample(pDevice->internalFormat)); - if (framesToReadFromClient > 0) { - mal_device__read_frames_from_client(pDevice, framesToReadFromClient, pBuffer); - -#ifdef MAL_DEBUG_OUTPUT - printf(", framesToReadFromClient=%d\n", (int)framesToReadFromClient); -#endif - - error = ((mal_pa_stream_write_proc)pContext->pulse.pa_stream_write)((mal_pa_stream*)pDevice->pulse.pStream, pBuffer, bytesToReadFromClient, NULL, 0, MAL_PA_SEEK_RELATIVE); - if (error < 0) { - mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[PulseAudio] Failed to write data to the PulseAudio stream.", mal_result_from_pulse(error)); - return; - } - } else { -#ifdef MAL_DEBUG_OUTPUT - printf(", framesToReadFromClient=0\n"); -#endif - } - - bytesRemaining -= bytesToReadFromClient; - } else { -#ifdef MAL_DEBUG_OUTPUT - printf(", framesToReadFromClient=0\n"); -#endif - } - } -} - -void mal_pulse_device_read_callback(mal_pa_stream* pStream, size_t sizeInBytes, void* pUserData) -{ - mal_device* pDevice = (mal_device*)pUserData; - mal_assert(pDevice != NULL); - - mal_context* pContext = pDevice->pContext; - mal_assert(pContext != NULL); - - size_t bytesRemaining = sizeInBytes; - while (bytesRemaining > 0) { - size_t bytesToSendToClient = bytesRemaining; - if (bytesToSendToClient > 0xFFFFFFFF) { - bytesToSendToClient = 0xFFFFFFFF; - } - - const void* pBuffer = NULL; - int error = ((mal_pa_stream_peek_proc)pContext->pulse.pa_stream_peek)((mal_pa_stream*)pDevice->pulse.pStream, &pBuffer, &sizeInBytes); - if (error < 0) { - mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[PulseAudio] Failed to retrieve read buffer for reading data from the device.", mal_result_from_pulse(error)); - return; - } - - if (pBuffer != NULL) { - mal_uint32 framesToSendToClient = (mal_uint32)bytesToSendToClient / (pDevice->internalChannels*mal_get_bytes_per_sample(pDevice->internalFormat)); - if (framesToSendToClient > 0) { - mal_device__send_frames_to_client(pDevice, framesToSendToClient, pBuffer); - } - } - - error = ((mal_pa_stream_drop_proc)pContext->pulse.pa_stream_drop)((mal_pa_stream*)pDevice->pulse.pStream); - if (error < 0) { - mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[PulseAudio] Failed to drop fragment from the PulseAudio stream.", mal_result_from_pulse(error)); - } - - bytesRemaining -= bytesToSendToClient; - } -} - -void mal_device_sink_info_callback(mal_pa_context* pPulseContext, const mal_pa_sink_info* pInfo, int endOfList, void* pUserData) -{ - if (endOfList > 0) { - return; - } - - mal_pa_sink_info* pInfoOut = (mal_pa_sink_info*)pUserData; - mal_assert(pInfoOut != NULL); - - *pInfoOut = *pInfo; -} - -void mal_device_source_info_callback(mal_pa_context* pPulseContext, const mal_pa_source_info* pInfo, int endOfList, void* pUserData) -{ - if (endOfList > 0) { - return; - } - - mal_pa_source_info* pInfoOut = (mal_pa_source_info*)pUserData; - mal_assert(pInfoOut != NULL); - - *pInfoOut = *pInfo; -} - -void mal_device_sink_name_callback(mal_pa_context* pPulseContext, const mal_pa_sink_info* pInfo, int endOfList, void* pUserData) -{ - if (endOfList > 0) { - return; - } - - mal_device* pDevice = (mal_device*)pUserData; - mal_assert(pDevice != NULL); - - mal_strncpy_s(pDevice->name, sizeof(pDevice->name), pInfo->description, (size_t)-1); -} - -void mal_device_source_name_callback(mal_pa_context* pPulseContext, const mal_pa_source_info* pInfo, int endOfList, void* pUserData) -{ - if (endOfList > 0) { - return; - } - - mal_device* pDevice = (mal_device*)pUserData; - mal_assert(pDevice != NULL); - - mal_strncpy_s(pDevice->name, sizeof(pDevice->name), pInfo->description, (size_t)-1); -} - -void mal_device_uninit__pulse(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - mal_context* pContext = pDevice->pContext; - mal_assert(pContext != NULL); - - ((mal_pa_stream_disconnect_proc)pContext->pulse.pa_stream_disconnect)((mal_pa_stream*)pDevice->pulse.pStream); - ((mal_pa_stream_unref_proc)pContext->pulse.pa_stream_unref)((mal_pa_stream*)pDevice->pulse.pStream); - ((mal_pa_context_disconnect_proc)pContext->pulse.pa_context_disconnect)((mal_pa_context*)pDevice->pulse.pPulseContext); - ((mal_pa_context_unref_proc)pContext->pulse.pa_context_unref)((mal_pa_context*)pDevice->pulse.pPulseContext); - ((mal_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)((mal_pa_mainloop*)pDevice->pulse.pMainLoop); -} - -mal_result mal_device_init__pulse(mal_context* pContext, mal_device_type type, const mal_device_id* pDeviceID, const mal_device_config* pConfig, mal_device* pDevice) -{ - (void)pContext; - - mal_assert(pDevice != NULL); - mal_zero_object(&pDevice->pulse); - - mal_result result = MAL_SUCCESS; - int error = 0; - - const char* dev = NULL; - if (pDeviceID != NULL) { - dev = pDeviceID->pulse; - } - - mal_uint32 bufferSizeInFrames = pConfig->bufferSizeInFrames; - - mal_pa_sink_info sinkInfo; - mal_pa_source_info sourceInfo; - mal_pa_operation* pOP = NULL; - - mal_pa_sample_spec ss; - mal_pa_channel_map cmap; - mal_pa_buffer_attr attr; - mal_pa_stream_flags_t streamFlags; - - const mal_pa_sample_spec* pActualSS = NULL; - const mal_pa_channel_map* pActualCMap = NULL; - const mal_pa_buffer_attr* pActualAttr = NULL; - - - - pDevice->pulse.pMainLoop = ((mal_pa_mainloop_new_proc)pContext->pulse.pa_mainloop_new)(); - if (pDevice->pulse.pMainLoop == NULL) { - result = mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[PulseAudio] Failed to create main loop for device.", MAL_FAILED_TO_INIT_BACKEND); - goto on_error0; - } - - pDevice->pulse.pAPI = ((mal_pa_mainloop_get_api_proc)pContext->pulse.pa_mainloop_get_api)((mal_pa_mainloop*)pDevice->pulse.pMainLoop); - if (pDevice->pulse.pAPI == NULL) { - result = mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[PulseAudio] Failed to retrieve PulseAudio main loop.", MAL_FAILED_TO_INIT_BACKEND); - goto on_error1; - } - - pDevice->pulse.pPulseContext = ((mal_pa_context_new_proc)pContext->pulse.pa_context_new)((mal_pa_mainloop_api*)pDevice->pulse.pAPI, pContext->config.pulse.pApplicationName); - if (pDevice->pulse.pPulseContext == NULL) { - result = mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[PulseAudio] Failed to create PulseAudio context for device.", MAL_FAILED_TO_INIT_BACKEND); - goto on_error1; - } - - error = ((mal_pa_context_connect_proc)pContext->pulse.pa_context_connect)((mal_pa_context*)pDevice->pulse.pPulseContext, pContext->config.pulse.pServerName, (pContext->config.pulse.tryAutoSpawn) ? 0 : MAL_PA_CONTEXT_NOAUTOSPAWN, NULL); - if (error != MAL_PA_OK) { - result = mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[PulseAudio] Failed to connect PulseAudio context.", mal_result_from_pulse(error)); - goto on_error2; - } - - - pDevice->pulse.pulseContextState = MAL_PA_CONTEXT_UNCONNECTED; - ((mal_pa_context_set_state_callback_proc)pContext->pulse.pa_context_set_state_callback)((mal_pa_context*)pDevice->pulse.pPulseContext, mal_pulse_device_state_callback, pDevice); - - // Wait for PulseAudio to get itself ready before returning. - for (;;) { - if (pDevice->pulse.pulseContextState == MAL_PA_CONTEXT_READY) { - break; - } else { - error = ((mal_pa_mainloop_iterate_proc)pContext->pulse.pa_mainloop_iterate)((mal_pa_mainloop*)pDevice->pulse.pMainLoop, 1, NULL); // 1 = block. - if (error < 0) { - result = mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[PulseAudio] The PulseAudio main loop returned an error while connecting the PulseAudio context.", mal_result_from_pulse(error)); - goto on_error3; - } - continue; - } - - // An error may have occurred. - if (pDevice->pulse.pulseContextState == MAL_PA_CONTEXT_FAILED || pDevice->pulse.pulseContextState == MAL_PA_CONTEXT_TERMINATED) { - result = mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[PulseAudio] An error occurred while connecting the PulseAudio context.", MAL_ERROR); - goto on_error3; - } - - error = ((mal_pa_mainloop_iterate_proc)pContext->pulse.pa_mainloop_iterate)((mal_pa_mainloop*)pDevice->pulse.pMainLoop, 1, NULL); - if (error < 0) { - result = mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[PulseAudio] The PulseAudio main loop returned an error while connecting the PulseAudio context.", mal_result_from_pulse(error)); - goto on_error3; - } - } - - - if (type == mal_device_type_playback) { - pOP = ((mal_pa_context_get_sink_info_by_name_proc)pContext->pulse.pa_context_get_sink_info_by_name)((mal_pa_context*)pDevice->pulse.pPulseContext, dev, mal_device_sink_info_callback, &sinkInfo); - } else { - pOP = ((mal_pa_context_get_source_info_by_name_proc)pContext->pulse.pa_context_get_source_info_by_name)((mal_pa_context*)pDevice->pulse.pPulseContext, dev, mal_device_source_info_callback, &sourceInfo); - } - - if (pOP != NULL) { - mal_device__wait_for_operation__pulse(pDevice, pOP); - ((mal_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP); - } - - if (type == mal_device_type_playback) { - ss = sinkInfo.sample_spec; - cmap = sinkInfo.channel_map; - } else { - ss = sourceInfo.sample_spec; - cmap = sourceInfo.channel_map; - } - - - // Buffer size. - bufferSizeInFrames = pDevice->bufferSizeInFrames; - if (bufferSizeInFrames == 0) { - bufferSizeInFrames = mal_calculate_buffer_size_in_frames_from_milliseconds(pDevice->bufferSizeInMilliseconds, ss.rate); - - // PulseAudio seems to need a bit of an bit of size to the buffer to be reliable. - if (pDevice->usingDefaultBufferSize) { - float bufferSizeScaleFactor = 1.0f; - if (type == mal_device_type_capture) { - bufferSizeScaleFactor = 2.0f; - } - - bufferSizeInFrames = mal_scale_buffer_size(bufferSizeInFrames, bufferSizeScaleFactor); - } - } - - attr.maxlength = bufferSizeInFrames * mal_get_bytes_per_sample(mal_format_from_pulse(ss.format))*ss.channels; - attr.tlength = attr.maxlength; - attr.prebuf = (mal_uint32)-1; - attr.minreq = attr.maxlength / pConfig->periods; - attr.fragsize = attr.maxlength / pConfig->periods; - -#ifdef MAL_DEBUG_OUTPUT - printf("[PulseAudio] attr: maxlength=%d, tlength=%d, prebuf=%d, minreq=%d, fragsize=%d; bufferSizeInFrames=%d\n", attr.maxlength, attr.tlength, attr.prebuf, attr.minreq, attr.fragsize, bufferSizeInFrames); -#endif - - char streamName[256]; - if (pConfig->pulse.pStreamName != NULL) { - mal_strncpy_s(streamName, sizeof(streamName), pConfig->pulse.pStreamName, (size_t)-1); - } else { - static int g_StreamCounter = 0; - mal_strcpy_s(streamName, sizeof(streamName), "mini_al:"); - mal_itoa_s(g_StreamCounter, streamName + 8, sizeof(streamName)-8, 10); // 8 = strlen("mini_al:") - g_StreamCounter += 1; - } - - pDevice->pulse.pStream = ((mal_pa_stream_new_proc)pContext->pulse.pa_stream_new)((mal_pa_context*)pDevice->pulse.pPulseContext, streamName, &ss, &cmap); - if (pDevice->pulse.pStream == NULL) { - result = mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[PulseAudio] Failed to create PulseAudio stream.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - goto on_error3; - } - - - streamFlags = MAL_PA_STREAM_START_CORKED; - if (dev != NULL) { - streamFlags |= MAL_PA_STREAM_DONT_MOVE | MAL_PA_STREAM_FIX_FORMAT | MAL_PA_STREAM_FIX_RATE | MAL_PA_STREAM_FIX_CHANNELS; - } - - if (type == mal_device_type_playback) { - error = ((mal_pa_stream_connect_playback_proc)pContext->pulse.pa_stream_connect_playback)((mal_pa_stream*)pDevice->pulse.pStream, dev, &attr, streamFlags, NULL, NULL); - } else { - error = ((mal_pa_stream_connect_record_proc)pContext->pulse.pa_stream_connect_record)((mal_pa_stream*)pDevice->pulse.pStream, dev, &attr, streamFlags); - } - - if (error != MAL_PA_OK) { - result = mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[PulseAudio] Failed to connect PulseAudio stream.", mal_result_from_pulse(error)); - goto on_error4; - } - - while (((mal_pa_stream_get_state_proc)pContext->pulse.pa_stream_get_state)((mal_pa_stream*)pDevice->pulse.pStream) != MAL_PA_STREAM_READY) { - error = ((mal_pa_mainloop_iterate_proc)pContext->pulse.pa_mainloop_iterate)((mal_pa_mainloop*)pDevice->pulse.pMainLoop, 1, NULL); - if (error < 0) { - result = mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[PulseAudio] The PulseAudio main loop returned an error while connecting the PulseAudio stream.", mal_result_from_pulse(error)); - goto on_error5; - } - } - - - // Internal format. - pActualSS = ((mal_pa_stream_get_sample_spec_proc)pContext->pulse.pa_stream_get_sample_spec)((mal_pa_stream*)pDevice->pulse.pStream); - if (pActualSS != NULL) { - // If anything has changed between the requested and the actual sample spec, we need to update the buffer. - if (ss.format != pActualSS->format || ss.channels != pActualSS->channels || ss.rate != pActualSS->rate) { - attr.maxlength = bufferSizeInFrames * mal_get_bytes_per_sample(mal_format_from_pulse(pActualSS->format))*pActualSS->channels; - attr.tlength = attr.maxlength; - attr.prebuf = (mal_uint32)-1; - attr.minreq = attr.maxlength / pConfig->periods; - attr.fragsize = attr.maxlength / pConfig->periods; - - pOP = ((mal_pa_stream_set_buffer_attr_proc)pContext->pulse.pa_stream_set_buffer_attr)((mal_pa_stream*)pDevice->pulse.pStream, &attr, NULL, NULL); - if (pOP != NULL) { - mal_device__wait_for_operation__pulse(pDevice, pOP); - ((mal_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP); - } - } - - ss = *pActualSS; - } - - pDevice->internalFormat = mal_format_from_pulse(ss.format); - pDevice->internalChannels = ss.channels; - pDevice->internalSampleRate = ss.rate; - - - // Internal channel map. - pActualCMap = ((mal_pa_stream_get_channel_map_proc)pContext->pulse.pa_stream_get_channel_map)((mal_pa_stream*)pDevice->pulse.pStream); - if (pActualCMap != NULL) { - cmap = *pActualCMap; - } - - for (mal_uint32 iChannel = 0; iChannel < pDevice->internalChannels; ++iChannel) { - pDevice->internalChannelMap[iChannel] = mal_channel_position_from_pulse(cmap.map[iChannel]); - } - - - // Buffer size. - pActualAttr = ((mal_pa_stream_get_buffer_attr_proc)pContext->pulse.pa_stream_get_buffer_attr)((mal_pa_stream*)pDevice->pulse.pStream); - if (pActualAttr != NULL) { - attr = *pActualAttr; - } - - pDevice->bufferSizeInFrames = attr.maxlength / (mal_get_bytes_per_sample(pDevice->internalFormat)*pDevice->internalChannels); - pDevice->periods = attr.maxlength / attr.tlength; - -#ifdef MAL_DEBUG_OUTPUT - printf("[PulseAudio] actual attr: maxlength=%d, tlength=%d, prebuf=%d, minreq=%d, fragsize=%d; pDevice->bufferSizeInFrames=%d\n", attr.maxlength, attr.tlength, attr.prebuf, attr.minreq, attr.fragsize, pDevice->bufferSizeInFrames); -#endif - - - // Grab the name of the device if we can. - dev = ((mal_pa_stream_get_device_name_proc)pContext->pulse.pa_stream_get_device_name)((mal_pa_stream*)pDevice->pulse.pStream); - if (dev != NULL) { - mal_pa_operation* pOP = NULL; - if (type == mal_device_type_playback) { - pOP = ((mal_pa_context_get_sink_info_by_name_proc)pContext->pulse.pa_context_get_sink_info_by_name)((mal_pa_context*)pDevice->pulse.pPulseContext, dev, mal_device_sink_name_callback, pDevice); - } else { - pOP = ((mal_pa_context_get_source_info_by_name_proc)pContext->pulse.pa_context_get_source_info_by_name)((mal_pa_context*)pDevice->pulse.pPulseContext, dev, mal_device_source_name_callback, pDevice); - } - - if (pOP != NULL) { - mal_device__wait_for_operation__pulse(pDevice, pOP); - ((mal_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP); - } - } - - - // Set callbacks for reading and writing data to/from the PulseAudio stream. - if (type == mal_device_type_playback) { - ((mal_pa_stream_set_write_callback_proc)pContext->pulse.pa_stream_set_write_callback)((mal_pa_stream*)pDevice->pulse.pStream, mal_pulse_device_write_callback, pDevice); - } else { - ((mal_pa_stream_set_read_callback_proc)pContext->pulse.pa_stream_set_read_callback)((mal_pa_stream*)pDevice->pulse.pStream, mal_pulse_device_read_callback, pDevice); - } - - - pDevice->pulse.fragmentSizeInBytes = attr.tlength; - - return MAL_SUCCESS; - - -on_error5: ((mal_pa_stream_disconnect_proc)pContext->pulse.pa_stream_disconnect)((mal_pa_stream*)pDevice->pulse.pStream); -on_error4: ((mal_pa_stream_unref_proc)pContext->pulse.pa_stream_unref)((mal_pa_stream*)pDevice->pulse.pStream); -on_error3: ((mal_pa_context_disconnect_proc)pContext->pulse.pa_context_disconnect)((mal_pa_context*)pDevice->pulse.pPulseContext); -on_error2: ((mal_pa_context_unref_proc)pContext->pulse.pa_context_unref)((mal_pa_context*)pDevice->pulse.pPulseContext); -on_error1: ((mal_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)((mal_pa_mainloop*)pDevice->pulse.pMainLoop); -on_error0: - return result; -} - - -void mal_pulse_operation_complete_callback(mal_pa_stream* pStream, int success, void* pUserData) -{ - mal_bool32* pIsSuccessful = (mal_bool32*)pUserData; - mal_assert(pIsSuccessful != NULL); - - *pIsSuccessful = (mal_bool32)success; -} - -mal_result mal_device__cork_stream__pulse(mal_device* pDevice, int cork) -{ - mal_context* pContext = pDevice->pContext; - mal_assert(pContext != NULL); - - mal_bool32 wasSuccessful = MAL_FALSE; - mal_pa_operation* pOP = ((mal_pa_stream_cork_proc)pContext->pulse.pa_stream_cork)((mal_pa_stream*)pDevice->pulse.pStream, cork, mal_pulse_operation_complete_callback, &wasSuccessful); - if (pOP == NULL) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[PulseAudio] Failed to cork PulseAudio stream.", (cork == 0) ? MAL_FAILED_TO_START_BACKEND_DEVICE : MAL_FAILED_TO_STOP_BACKEND_DEVICE); - } - - mal_result result = mal_device__wait_for_operation__pulse(pDevice, pOP); - ((mal_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP); - - if (result != MAL_SUCCESS) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[PulseAudio] An error occurred while waiting for the PulseAudio stream to cork.", result); - } - - if (!wasSuccessful) { - if (cork) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[PulseAudio] Failed to stop PulseAudio stream.", MAL_FAILED_TO_STOP_BACKEND_DEVICE); - } else { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[PulseAudio] Failed to start PulseAudio stream.", MAL_FAILED_TO_START_BACKEND_DEVICE); - } - } - - return MAL_SUCCESS; -} - -mal_result mal_device_start__pulse(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - mal_context* pContext = pDevice->pContext; - mal_assert(pContext != NULL); - - // For both playback and capture we need to uncork the stream. Afterwards, for playback we need to fill in an initial chunk - // of data, equal to the trigger length. That should then start actual playback. - mal_result result = mal_device__cork_stream__pulse(pDevice, 0); - if (result != MAL_SUCCESS) { - return result; - } - - // A playback device is started by simply writing data to it. For capture we do nothing. - if (pDevice->type == mal_device_type_playback) { - // Playback. - mal_pulse_device_write_callback((mal_pa_stream*)pDevice->pulse.pStream, pDevice->pulse.fragmentSizeInBytes, pDevice); - - // Force an immediate start of the device just to be sure. - mal_pa_operation* pOP = ((mal_pa_stream_trigger_proc)pContext->pulse.pa_stream_trigger)((mal_pa_stream*)pDevice->pulse.pStream, NULL, NULL); - if (pOP != NULL) { - mal_device__wait_for_operation__pulse(pDevice, pOP); - ((mal_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP); - } - } else { - // Capture. Do nothing. - } - - return MAL_SUCCESS; -} - -mal_result mal_device_stop__pulse(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - mal_context* pContext = pDevice->pContext; - mal_assert(pContext != NULL); - - mal_result result = mal_device__cork_stream__pulse(pDevice, 1); - if (result != MAL_SUCCESS) { - return result; - } - - // For playback, buffers need to be flushed. For capture they need to be drained. - mal_bool32 wasSuccessful; - mal_pa_operation* pOP = NULL; - if (pDevice->type == mal_device_type_playback) { - pOP = ((mal_pa_stream_flush_proc)pContext->pulse.pa_stream_flush)((mal_pa_stream*)pDevice->pulse.pStream, mal_pulse_operation_complete_callback, &wasSuccessful); - } else { - pOP = ((mal_pa_stream_drain_proc)pContext->pulse.pa_stream_drain)((mal_pa_stream*)pDevice->pulse.pStream, mal_pulse_operation_complete_callback, &wasSuccessful); - } - - if (pOP == NULL) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[PulseAudio] Failed to flush buffers after stopping PulseAudio stream.", MAL_ERROR); - } - - result = mal_device__wait_for_operation__pulse(pDevice, pOP); - ((mal_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP); - - if (result != MAL_SUCCESS) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[PulseAudio] An error occurred while waiting for the PulseAudio stream to flush.", result); - } - - if (!wasSuccessful) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[PulseAudio] Failed to flush buffers after stopping PulseAudio stream.", MAL_ERROR); - } - - return MAL_SUCCESS; -} - -mal_result mal_device_break_main_loop__pulse(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - mal_context* pContext = pDevice->pContext; - mal_assert(pContext != NULL); - - pDevice->pulse.breakFromMainLoop = MAL_TRUE; - ((mal_pa_mainloop_wakeup_proc)pContext->pulse.pa_mainloop_wakeup)((mal_pa_mainloop*)pDevice->pulse.pMainLoop); - - return MAL_SUCCESS; -} - -mal_result mal_device_main_loop__pulse(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - mal_context* pContext = pDevice->pContext; - mal_assert(pContext != NULL); - - pDevice->pulse.breakFromMainLoop = MAL_FALSE; - while (!pDevice->pulse.breakFromMainLoop) { - // Break from the main loop if the device isn't started anymore. Likely what's happened is the application - // has requested that the device be stopped. - if (!mal_device_is_started(pDevice)) { - break; - } - - int resultPA = ((mal_pa_mainloop_iterate_proc)pContext->pulse.pa_mainloop_iterate)((mal_pa_mainloop*)pDevice->pulse.pMainLoop, 1, NULL); - if (resultPA < 0) { - break; // Some error occurred. - } - } - - return MAL_SUCCESS; -} - - -mal_result mal_context_uninit__pulse(mal_context* pContext) -{ - mal_assert(pContext != NULL); - mal_assert(pContext->backend == mal_backend_pulseaudio); - -#ifndef MAL_NO_RUNTIME_LINKING - mal_dlclose(pContext->pulse.pulseSO); -#endif - - return MAL_SUCCESS; -} - -mal_result mal_context_init__pulse(mal_context* pContext) -{ - mal_assert(pContext != NULL); - -#ifndef MAL_NO_RUNTIME_LINKING - // libpulse.so - const char* libpulseNames[] = { - "libpulse.so", - "libpulse.so.0" - }; - - for (size_t i = 0; i < mal_countof(libpulseNames); ++i) { - pContext->pulse.pulseSO = mal_dlopen(libpulseNames[i]); - if (pContext->pulse.pulseSO != NULL) { - break; - } - } - - if (pContext->pulse.pulseSO == NULL) { - return MAL_NO_BACKEND; - } - - pContext->pulse.pa_mainloop_new = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_mainloop_new"); - pContext->pulse.pa_mainloop_free = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_mainloop_free"); - pContext->pulse.pa_mainloop_get_api = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_mainloop_get_api"); - pContext->pulse.pa_mainloop_iterate = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_mainloop_iterate"); - pContext->pulse.pa_mainloop_wakeup = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_mainloop_wakeup"); - pContext->pulse.pa_context_new = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_context_new"); - pContext->pulse.pa_context_unref = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_context_unref"); - pContext->pulse.pa_context_connect = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_context_connect"); - pContext->pulse.pa_context_disconnect = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_context_disconnect"); - pContext->pulse.pa_context_set_state_callback = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_context_set_state_callback"); - pContext->pulse.pa_context_get_state = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_context_get_state"); - pContext->pulse.pa_context_get_sink_info_list = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_context_get_sink_info_list"); - pContext->pulse.pa_context_get_source_info_list = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_context_get_source_info_list"); - pContext->pulse.pa_context_get_sink_info_by_name = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_context_get_sink_info_by_name"); - pContext->pulse.pa_context_get_source_info_by_name = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_context_get_source_info_by_name"); - pContext->pulse.pa_operation_unref = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_operation_unref"); - pContext->pulse.pa_operation_get_state = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_operation_get_state"); - pContext->pulse.pa_channel_map_init_extend = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_channel_map_init_extend"); - pContext->pulse.pa_channel_map_valid = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_channel_map_valid"); - pContext->pulse.pa_channel_map_compatible = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_channel_map_compatible"); - pContext->pulse.pa_stream_new = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_stream_new"); - pContext->pulse.pa_stream_unref = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_stream_unref"); - pContext->pulse.pa_stream_connect_playback = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_stream_connect_playback"); - pContext->pulse.pa_stream_connect_record = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_stream_connect_record"); - pContext->pulse.pa_stream_disconnect = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_stream_disconnect"); - pContext->pulse.pa_stream_get_state = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_stream_get_state"); - pContext->pulse.pa_stream_get_sample_spec = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_stream_get_sample_spec"); - pContext->pulse.pa_stream_get_channel_map = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_stream_get_channel_map"); - pContext->pulse.pa_stream_get_buffer_attr = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_stream_get_buffer_attr"); - pContext->pulse.pa_stream_set_buffer_attr = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_stream_set_buffer_attr"); - pContext->pulse.pa_stream_get_device_name = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_stream_get_device_name"); - pContext->pulse.pa_stream_set_write_callback = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_stream_set_write_callback"); - pContext->pulse.pa_stream_set_read_callback = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_stream_set_read_callback"); - pContext->pulse.pa_stream_flush = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_stream_flush"); - pContext->pulse.pa_stream_drain = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_stream_drain"); - pContext->pulse.pa_stream_cork = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_stream_cork"); - pContext->pulse.pa_stream_trigger = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_stream_trigger"); - pContext->pulse.pa_stream_begin_write = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_stream_begin_write"); - pContext->pulse.pa_stream_write = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_stream_write"); - pContext->pulse.pa_stream_peek = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_stream_peek"); - pContext->pulse.pa_stream_drop = (mal_proc)mal_dlsym(pContext->pulse.pulseSO, "pa_stream_drop"); -#else - // This strange assignment system is just for type safety. - mal_pa_mainloop_new_proc _pa_mainloop_new = pa_mainloop_new; - mal_pa_mainloop_free_proc _pa_mainloop_free = pa_mainloop_free; - mal_pa_mainloop_get_api_proc _pa_mainloop_get_api = pa_mainloop_get_api; - mal_pa_mainloop_iterate_proc _pa_mainloop_iterate = pa_mainloop_iterate; - mal_pa_mainloop_wakeup_proc _pa_mainloop_wakeup = pa_mainloop_wakeup; - mal_pa_context_new_proc _pa_context_new = pa_context_new; - mal_pa_context_unref_proc _pa_context_unref = pa_context_unref; - mal_pa_context_connect_proc _pa_context_connect = pa_context_connect; - mal_pa_context_disconnect_proc _pa_context_disconnect = pa_context_disconnect; - mal_pa_context_set_state_callback_proc _pa_context_set_state_callback = pa_context_set_state_callback; - mal_pa_context_get_state_proc _pa_context_get_state = pa_context_get_state; - mal_pa_context_get_sink_info_list_proc _pa_context_get_sink_info_list = pa_context_get_sink_info_list; - mal_pa_context_get_source_info_list_proc _pa_context_get_source_info_list = pa_context_get_source_info_list; - mal_pa_context_get_sink_info_by_name_proc _pa_context_get_sink_info_by_name = pa_context_get_sink_info_by_name; - mal_pa_context_get_source_info_by_name_proc _pa_context_get_source_info_by_name= pa_context_get_source_info_by_name; - mal_pa_operation_unref_proc _pa_operation_unref = pa_operation_unref; - mal_pa_operation_get_state_proc _pa_operation_get_state = pa_operation_get_state; - mal_pa_channel_map_init_extend_proc _pa_channel_map_init_extend = pa_channel_map_init_extend; - mal_pa_channel_map_valid_proc _pa_channel_map_valid = pa_channel_map_valid; - mal_pa_channel_map_compatible_proc _pa_channel_map_compatible = pa_channel_map_compatible; - mal_pa_stream_new_proc _pa_stream_new = pa_stream_new; - mal_pa_stream_unref_proc _pa_stream_unref = pa_stream_unref; - mal_pa_stream_connect_playback_proc _pa_stream_connect_playback = pa_stream_connect_playback; - mal_pa_stream_connect_record_proc _pa_stream_connect_record = pa_stream_connect_record; - mal_pa_stream_disconnect_proc _pa_stream_disconnect = pa_stream_disconnect; - mal_pa_stream_get_state_proc _pa_stream_get_state = pa_stream_get_state; - mal_pa_stream_get_sample_spec_proc _pa_stream_get_sample_spec = pa_stream_get_sample_spec; - mal_pa_stream_get_channel_map_proc _pa_stream_get_channel_map = pa_stream_get_channel_map; - mal_pa_stream_get_buffer_attr_proc _pa_stream_get_buffer_attr = pa_stream_get_buffer_attr; - mal_pa_stream_set_buffer_attr_proc _pa_stream_set_buffer_attr = pa_stream_set_buffer_attr; - mal_pa_stream_get_device_name_proc _pa_stream_get_device_name = pa_stream_get_device_name; - mal_pa_stream_set_write_callback_proc _pa_stream_set_write_callback = pa_stream_set_write_callback; - mal_pa_stream_set_read_callback_proc _pa_stream_set_read_callback = pa_stream_set_read_callback; - mal_pa_stream_flush_proc _pa_stream_flush = pa_stream_flush; - mal_pa_stream_drain_proc _pa_stream_drain = pa_stream_drain; - mal_pa_stream_cork_proc _pa_stream_cork = pa_stream_cork; - mal_pa_stream_trigger_proc _pa_stream_trigger = pa_stream_trigger; - mal_pa_stream_begin_write_proc _pa_stream_begin_write = pa_stream_begin_write; - mal_pa_stream_write_proc _pa_stream_write = pa_stream_write; - mal_pa_stream_peek_proc _pa_stream_peek = pa_stream_peek; - mal_pa_stream_drop_proc _pa_stream_drop = pa_stream_drop; - - pContext->pulse.pa_mainloop_new = (mal_proc)_pa_mainloop_new; - pContext->pulse.pa_mainloop_free = (mal_proc)_pa_mainloop_free; - pContext->pulse.pa_mainloop_get_api = (mal_proc)_pa_mainloop_get_api; - pContext->pulse.pa_mainloop_iterate = (mal_proc)_pa_mainloop_iterate; - pContext->pulse.pa_mainloop_wakeup = (mal_proc)_pa_mainloop_wakeup; - pContext->pulse.pa_context_new = (mal_proc)_pa_context_new; - pContext->pulse.pa_context_unref = (mal_proc)_pa_context_unref; - pContext->pulse.pa_context_connect = (mal_proc)_pa_context_connect; - pContext->pulse.pa_context_disconnect = (mal_proc)_pa_context_disconnect; - pContext->pulse.pa_context_set_state_callback = (mal_proc)_pa_context_set_state_callback; - pContext->pulse.pa_context_get_state = (mal_proc)_pa_context_get_state; - pContext->pulse.pa_context_get_sink_info_list = (mal_proc)_pa_context_get_sink_info_list; - pContext->pulse.pa_context_get_source_info_list = (mal_proc)_pa_context_get_source_info_list; - pContext->pulse.pa_context_get_sink_info_by_name = (mal_proc)_pa_context_get_sink_info_by_name; - pContext->pulse.pa_context_get_source_info_by_name = (mal_proc)_pa_context_get_source_info_by_name; - pContext->pulse.pa_operation_unref = (mal_proc)_pa_operation_unref; - pContext->pulse.pa_operation_get_state = (mal_proc)_pa_operation_get_state; - pContext->pulse.pa_channel_map_init_extend = (mal_proc)_pa_channel_map_init_extend; - pContext->pulse.pa_channel_map_valid = (mal_proc)_pa_channel_map_valid; - pContext->pulse.pa_channel_map_compatible = (mal_proc)_pa_channel_map_compatible; - pContext->pulse.pa_stream_new = (mal_proc)_pa_stream_new; - pContext->pulse.pa_stream_unref = (mal_proc)_pa_stream_unref; - pContext->pulse.pa_stream_connect_playback = (mal_proc)_pa_stream_connect_playback; - pContext->pulse.pa_stream_connect_record = (mal_proc)_pa_stream_connect_record; - pContext->pulse.pa_stream_disconnect = (mal_proc)_pa_stream_disconnect; - pContext->pulse.pa_stream_get_state = (mal_proc)_pa_stream_get_state; - pContext->pulse.pa_stream_get_sample_spec = (mal_proc)_pa_stream_get_sample_spec; - pContext->pulse.pa_stream_get_channel_map = (mal_proc)_pa_stream_get_channel_map; - pContext->pulse.pa_stream_get_buffer_attr = (mal_proc)_pa_stream_get_buffer_attr; - pContext->pulse.pa_stream_set_buffer_attr = (mal_proc)_pa_stream_set_buffer_attr; - pContext->pulse.pa_stream_get_device_name = (mal_proc)_pa_stream_get_device_name; - pContext->pulse.pa_stream_set_write_callback = (mal_proc)_pa_stream_set_write_callback; - pContext->pulse.pa_stream_set_read_callback = (mal_proc)_pa_stream_set_read_callback; - pContext->pulse.pa_stream_flush = (mal_proc)_pa_stream_flush; - pContext->pulse.pa_stream_drain = (mal_proc)_pa_stream_drain; - pContext->pulse.pa_stream_cork = (mal_proc)_pa_stream_cork; - pContext->pulse.pa_stream_trigger = (mal_proc)_pa_stream_trigger; - pContext->pulse.pa_stream_begin_write = (mal_proc)_pa_stream_begin_write; - pContext->pulse.pa_stream_write = (mal_proc)_pa_stream_write; - pContext->pulse.pa_stream_peek = (mal_proc)_pa_stream_peek; - pContext->pulse.pa_stream_drop = (mal_proc)_pa_stream_drop; -#endif - - pContext->onUninit = mal_context_uninit__pulse; - pContext->onDeviceIDEqual = mal_context_is_device_id_equal__pulse; - pContext->onEnumDevices = mal_context_enumerate_devices__pulse; - pContext->onGetDeviceInfo = mal_context_get_device_info__pulse; - pContext->onDeviceInit = mal_device_init__pulse; - pContext->onDeviceUninit = mal_device_uninit__pulse; - pContext->onDeviceStart = mal_device_start__pulse; - pContext->onDeviceStop = mal_device_stop__pulse; - pContext->onDeviceBreakMainLoop = mal_device_break_main_loop__pulse; - pContext->onDeviceMainLoop = mal_device_main_loop__pulse; - - - // Although we have found the libpulse library, it doesn't necessarily mean PulseAudio is useable. We need to initialize - // and connect a dummy PulseAudio context to test PulseAudio's usability. - mal_pa_mainloop* pMainLoop = ((mal_pa_mainloop_new_proc)pContext->pulse.pa_mainloop_new)(); - if (pMainLoop == NULL) { - return MAL_NO_BACKEND; - } - - mal_pa_mainloop_api* pAPI = ((mal_pa_mainloop_get_api_proc)pContext->pulse.pa_mainloop_get_api)(pMainLoop); - if (pAPI == NULL) { - ((mal_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); - return MAL_NO_BACKEND; - } - - mal_pa_context* pPulseContext = ((mal_pa_context_new_proc)pContext->pulse.pa_context_new)(pAPI, pContext->config.pulse.pApplicationName); - if (pPulseContext == NULL) { - ((mal_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); - return MAL_NO_BACKEND; - } - - int error = ((mal_pa_context_connect_proc)pContext->pulse.pa_context_connect)(pPulseContext, pContext->config.pulse.pServerName, 0, NULL); - if (error != MAL_PA_OK) { - ((mal_pa_context_unref_proc)pContext->pulse.pa_context_unref)(pPulseContext); - ((mal_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); - return MAL_NO_BACKEND; - } - - ((mal_pa_context_disconnect_proc)pContext->pulse.pa_context_disconnect)(pPulseContext); - ((mal_pa_context_unref_proc)pContext->pulse.pa_context_unref)(pPulseContext); - ((mal_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); - return MAL_SUCCESS; -} -#endif - - -/////////////////////////////////////////////////////////////////////////////// -// -// JACK Backend -// -/////////////////////////////////////////////////////////////////////////////// -#ifdef MAL_HAS_JACK - -// It is assumed jack.h is available when compile-time linking is being used. -#ifdef MAL_NO_RUNTIME_LINKING -#include - -typedef jack_nframes_t mal_jack_nframes_t; -typedef jack_options_t mal_jack_options_t; -typedef jack_status_t mal_jack_status_t; -typedef jack_client_t mal_jack_client_t; -typedef jack_port_t mal_jack_port_t; -typedef JackProcessCallback mal_JackProcessCallback; -typedef JackBufferSizeCallback mal_JackBufferSizeCallback; -typedef JackShutdownCallback mal_JackShutdownCallback; -#define MAL_JACK_DEFAULT_AUDIO_TYPE JACK_DEFAULT_AUDIO_TYPE -#define mal_JackNoStartServer JackNoStartServer -#define mal_JackPortIsInput JackPortIsInput -#define mal_JackPortIsOutput JackPortIsOutput -#define mal_JackPortIsPhysical JackPortIsPhysical -#else -typedef mal_uint32 mal_jack_nframes_t; -typedef int mal_jack_options_t; -typedef int mal_jack_status_t; -typedef struct mal_jack_client_t mal_jack_client_t; -typedef struct mal_jack_port_t mal_jack_port_t; -typedef int (* mal_JackProcessCallback) (mal_jack_nframes_t nframes, void* arg); -typedef int (* mal_JackBufferSizeCallback)(mal_jack_nframes_t nframes, void* arg); -typedef void (* mal_JackShutdownCallback) (void* arg); -#define MAL_JACK_DEFAULT_AUDIO_TYPE "32 bit float mono audio" -#define mal_JackNoStartServer 1 -#define mal_JackPortIsInput 1 -#define mal_JackPortIsOutput 2 -#define mal_JackPortIsPhysical 4 -#endif - -typedef mal_jack_client_t* (* mal_jack_client_open_proc) (const char* client_name, mal_jack_options_t options, mal_jack_status_t* status, ...); -typedef int (* mal_jack_client_close_proc) (mal_jack_client_t* client); -typedef int (* mal_jack_client_name_size_proc) (); -typedef int (* mal_jack_set_process_callback_proc) (mal_jack_client_t* client, mal_JackProcessCallback process_callback, void* arg); -typedef int (* mal_jack_set_buffer_size_callback_proc)(mal_jack_client_t* client, mal_JackBufferSizeCallback bufsize_callback, void* arg); -typedef void (* mal_jack_on_shutdown_proc) (mal_jack_client_t* client, mal_JackShutdownCallback function, void* arg); -typedef mal_jack_nframes_t (* mal_jack_get_sample_rate_proc) (mal_jack_client_t* client); -typedef mal_jack_nframes_t (* mal_jack_get_buffer_size_proc) (mal_jack_client_t* client); -typedef const char** (* mal_jack_get_ports_proc) (mal_jack_client_t* client, const char* port_name_pattern, const char* type_name_pattern, unsigned long flags); -typedef int (* mal_jack_activate_proc) (mal_jack_client_t* client); -typedef int (* mal_jack_deactivate_proc) (mal_jack_client_t* client); -typedef int (* mal_jack_connect_proc) (mal_jack_client_t* client, const char* source_port, const char* destination_port); -typedef mal_jack_port_t* (* mal_jack_port_register_proc) (mal_jack_client_t* client, const char* port_name, const char* port_type, unsigned long flags, unsigned long buffer_size); -typedef const char* (* mal_jack_port_name_proc) (const mal_jack_port_t* port); -typedef void* (* mal_jack_port_get_buffer_proc) (mal_jack_port_t* port, mal_jack_nframes_t nframes); -typedef void (* mal_jack_free_proc) (void* ptr); - -mal_result mal_context_open_client__jack(mal_context* pContext, mal_jack_client_t** ppClient) -{ - mal_assert(pContext != NULL); - mal_assert(ppClient != NULL); - - if (ppClient) { - *ppClient = NULL; - } - - size_t maxClientNameSize = ((mal_jack_client_name_size_proc)pContext->jack.jack_client_name_size)(); // Includes null terminator. - - char clientName[256]; - mal_strncpy_s(clientName, mal_min(sizeof(clientName), maxClientNameSize), (pContext->config.jack.pClientName != NULL) ? pContext->config.jack.pClientName : "mini_al", (size_t)-1); - - mal_jack_status_t status; - mal_jack_client_t* pClient = ((mal_jack_client_open_proc)pContext->jack.jack_client_open)(clientName, (pContext->config.jack.tryStartServer) ? 0 : mal_JackNoStartServer, &status, NULL); - if (pClient == NULL) { - return MAL_FAILED_TO_OPEN_BACKEND_DEVICE; - } - - if (ppClient) { - *ppClient = pClient; - } - - return MAL_SUCCESS; -} - -mal_bool32 mal_context_is_device_id_equal__jack(mal_context* pContext, const mal_device_id* pID0, const mal_device_id* pID1) -{ - mal_assert(pContext != NULL); - mal_assert(pID0 != NULL); - mal_assert(pID1 != NULL); - (void)pContext; - - return pID0->jack == pID1->jack; -} - -mal_result mal_context_enumerate_devices__jack(mal_context* pContext, mal_enum_devices_callback_proc callback, void* pUserData) -{ - mal_assert(pContext != NULL); - mal_assert(callback != NULL); - - mal_bool32 cbResult = MAL_TRUE; - - // Playback. - if (cbResult) { - mal_device_info deviceInfo; - mal_zero_object(&deviceInfo); - mal_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MAL_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); - cbResult = callback(pContext, mal_device_type_playback, &deviceInfo, pUserData); - } - - // Capture. - if (cbResult) { - mal_device_info deviceInfo; - mal_zero_object(&deviceInfo); - mal_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MAL_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); - cbResult = callback(pContext, mal_device_type_capture, &deviceInfo, pUserData); - } - - return MAL_SUCCESS; -} - -mal_result mal_context_get_device_info__jack(mal_context* pContext, mal_device_type deviceType, const mal_device_id* pDeviceID, mal_share_mode shareMode, mal_device_info* pDeviceInfo) -{ - mal_assert(pContext != NULL); - - (void)pContext; - (void)shareMode; - - if (pDeviceID != NULL && pDeviceID->jack != 0) { - return MAL_NO_DEVICE; // Don't know the device. - } - - // Name / Description - if (deviceType == mal_device_type_playback) { - mal_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MAL_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); - } else { - mal_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MAL_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); - } - - // Jack only supports f32 and has a specific channel count and sample rate. - pDeviceInfo->formatCount = 1; - pDeviceInfo->formats[0] = mal_format_f32; - - // The channel count and sample rate can only be determined by opening the device. - mal_jack_client_t* pClient; - mal_result result = mal_context_open_client__jack(pContext, &pClient); - if (result != MAL_SUCCESS) { - return mal_context_post_error(pContext, NULL, MAL_LOG_LEVEL_ERROR, "[JACK] Failed to open client.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - - pDeviceInfo->minSampleRate = ((mal_jack_get_sample_rate_proc)pContext->jack.jack_get_sample_rate)((mal_jack_client_t*)pClient); - pDeviceInfo->maxSampleRate = pDeviceInfo->minSampleRate; - - pDeviceInfo->minChannels = 0; - pDeviceInfo->maxChannels = 0; - - const char** ppPorts = ((mal_jack_get_ports_proc)pContext->jack.jack_get_ports)((mal_jack_client_t*)pClient, NULL, NULL, mal_JackPortIsPhysical | ((deviceType == mal_device_type_playback) ? mal_JackPortIsInput : mal_JackPortIsOutput)); - if (ppPorts == NULL) { - ((mal_jack_client_close_proc)pContext->jack.jack_client_close)((mal_jack_client_t*)pClient); - return mal_context_post_error(pContext, NULL, MAL_LOG_LEVEL_ERROR, "[JACK] Failed to query physical ports.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - - while (ppPorts[pDeviceInfo->minChannels] != NULL) { - pDeviceInfo->minChannels += 1; - pDeviceInfo->maxChannels += 1; - } - - ((mal_jack_free_proc)pContext->jack.jack_free)((void*)ppPorts); - ((mal_jack_client_close_proc)pContext->jack.jack_client_close)((mal_jack_client_t*)pClient); - - return MAL_SUCCESS; -} - - -void mal_device_uninit__jack(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - mal_context* pContext = pDevice->pContext; - mal_assert(pContext != NULL); - - if (pDevice->jack.pClient != NULL) { - ((mal_jack_client_close_proc)pContext->jack.jack_client_close)((mal_jack_client_t*)pDevice->jack.pClient); - } -} - -void mal_device__jack_shutdown_callback(void* pUserData) -{ - // JACK died. Stop the device. - mal_device* pDevice = (mal_device*)pUserData; - mal_assert(pDevice != NULL); - - mal_device_stop(pDevice); -} - -int mal_device__jack_buffer_size_callback(mal_jack_nframes_t frameCount, void* pUserData) -{ - mal_device* pDevice = (mal_device*)pUserData; - mal_assert(pDevice != NULL); - - float* pNewBuffer = (float*)mal_realloc(pDevice->jack.pIntermediaryBuffer, frameCount * (pDevice->internalChannels*mal_get_bytes_per_sample(pDevice->internalFormat))); - if (pNewBuffer == NULL) { - return MAL_OUT_OF_MEMORY; - } - - pDevice->jack.pIntermediaryBuffer = pNewBuffer; - pDevice->bufferSizeInFrames = frameCount * pDevice->periods; - - return 0; -} - -int mal_device__jack_process_callback(mal_jack_nframes_t frameCount, void* pUserData) -{ - mal_device* pDevice = (mal_device*)pUserData; - mal_assert(pDevice != NULL); - - mal_context* pContext = pDevice->pContext; - mal_assert(pContext != NULL); - - if (pDevice->type == mal_device_type_playback) { - mal_device__read_frames_from_client(pDevice, frameCount, pDevice->jack.pIntermediaryBuffer); - - // Channels need to be deinterleaved. - for (mal_uint32 iChannel = 0; iChannel < pDevice->internalChannels; ++iChannel) { - float* pDst = (float*)((mal_jack_port_get_buffer_proc)pContext->jack.jack_port_get_buffer)((mal_jack_port_t*)pDevice->jack.pPorts[iChannel], frameCount); - if (pDst != NULL) { - const float* pSrc = pDevice->jack.pIntermediaryBuffer + iChannel; - for (mal_jack_nframes_t iFrame = 0; iFrame < frameCount; ++iFrame) { - *pDst = *pSrc; - - pDst += 1; - pSrc += pDevice->internalChannels; - } - } - } - } else { - // Channels need to be interleaved. - for (mal_uint32 iChannel = 0; iChannel < pDevice->internalChannels; ++iChannel) { - const float* pSrc = (const float*)((mal_jack_port_get_buffer_proc)pContext->jack.jack_port_get_buffer)((mal_jack_port_t*)pDevice->jack.pPorts[iChannel], frameCount); - if (pSrc != NULL) { - float* pDst = pDevice->jack.pIntermediaryBuffer + iChannel; - for (mal_jack_nframes_t iFrame = 0; iFrame < frameCount; ++iFrame) { - *pDst = *pSrc; - - pDst += pDevice->internalChannels; - pSrc += 1; - } - } - } - - mal_device__send_frames_to_client(pDevice, frameCount, pDevice->jack.pIntermediaryBuffer); - } - - return 0; -} - -mal_result mal_device_init__jack(mal_context* pContext, mal_device_type type, const mal_device_id* pDeviceID, const mal_device_config* pConfig, mal_device* pDevice) -{ - mal_assert(pContext != NULL); - mal_assert(pConfig != NULL); - mal_assert(pDevice != NULL); - - (void)pContext; - (void)pConfig; - - // Only supporting default devices with JACK. - if (pDeviceID != NULL && pDeviceID->jack != 0) { - return MAL_NO_DEVICE; - } - - - // Open the client. - mal_result result = mal_context_open_client__jack(pContext, (mal_jack_client_t**)&pDevice->jack.pClient); - if (result != MAL_SUCCESS) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[JACK] Failed to open client.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - - // Callbacks. - if (((mal_jack_set_process_callback_proc)pContext->jack.jack_set_process_callback)((mal_jack_client_t*)pDevice->jack.pClient, mal_device__jack_process_callback, pDevice) != 0) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[JACK] Failed to set process callback.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - if (((mal_jack_set_buffer_size_callback_proc)pContext->jack.jack_set_buffer_size_callback)((mal_jack_client_t*)pDevice->jack.pClient, mal_device__jack_buffer_size_callback, pDevice) != 0) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[JACK] Failed to set buffer size callback.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - - ((mal_jack_on_shutdown_proc)pContext->jack.jack_on_shutdown)((mal_jack_client_t*)pDevice->jack.pClient, mal_device__jack_shutdown_callback, pDevice); - - - // The format is always f32. - pDevice->internalFormat = mal_format_f32; - - // A port is a channel. - unsigned long serverPortFlags; - unsigned long clientPortFlags; - if (type == mal_device_type_playback) { - serverPortFlags = mal_JackPortIsInput; - clientPortFlags = mal_JackPortIsOutput; - } else { - serverPortFlags = mal_JackPortIsOutput; - clientPortFlags = mal_JackPortIsInput; - } - - const char** ppPorts = ((mal_jack_get_ports_proc)pContext->jack.jack_get_ports)((mal_jack_client_t*)pDevice->jack.pClient, NULL, NULL, mal_JackPortIsPhysical | serverPortFlags); - if (ppPorts == NULL) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[JACK] Failed to query physical ports.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - - pDevice->internalChannels = 0; - while (ppPorts[pDevice->internalChannels] != NULL) { - char name[64]; - if (type == mal_device_type_playback) { - mal_strcpy_s(name, sizeof(name), "playback"); - mal_itoa_s((int)pDevice->internalChannels, name+8, sizeof(name)-8, 10); // 8 = length of "playback" - } else { - mal_strcpy_s(name, sizeof(name), "capture"); - mal_itoa_s((int)pDevice->internalChannels, name+7, sizeof(name)-7, 10); // 7 = length of "capture" - } - - pDevice->jack.pPorts[pDevice->internalChannels] = ((mal_jack_port_register_proc)pContext->jack.jack_port_register)((mal_jack_client_t*)pDevice->jack.pClient, name, MAL_JACK_DEFAULT_AUDIO_TYPE, clientPortFlags, 0); - if (pDevice->jack.pPorts[pDevice->internalChannels] == NULL) { - ((mal_jack_free_proc)pContext->jack.jack_free)((void*)ppPorts); - mal_device_uninit__jack(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[JACK] Failed to register ports.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - - pDevice->internalChannels += 1; - } - - ((mal_jack_free_proc)pContext->jack.jack_free)((void*)ppPorts); - ppPorts = NULL; - - // We set the sample rate here, but apparently this can change. This is incompatible with mini_al, so changing sample rates will not be supported. - pDevice->internalSampleRate = ((mal_jack_get_sample_rate_proc)pContext->jack.jack_get_sample_rate)((mal_jack_client_t*)pDevice->jack.pClient); - - // I don't think the channel map can be queried, so just use defaults for now. - mal_get_standard_channel_map(mal_standard_channel_map_alsa, pDevice->internalChannels, pDevice->internalChannelMap); - - // The buffer size in frames can change. - pDevice->periods = 2; - pDevice->bufferSizeInFrames = ((mal_jack_get_buffer_size_proc)pContext->jack.jack_get_buffer_size)((mal_jack_client_t*)pDevice->jack.pClient) * pDevice->periods; - - // Initial allocation for the intermediary buffer. - pDevice->jack.pIntermediaryBuffer = (float*)mal_malloc((pDevice->bufferSizeInFrames/pDevice->periods)*(pDevice->internalChannels*mal_get_bytes_per_sample(pDevice->internalFormat))); - if (pDevice->jack.pIntermediaryBuffer == NULL) { - mal_device_uninit__jack(pDevice); - return MAL_OUT_OF_MEMORY; - } - - return MAL_SUCCESS; -} - - -mal_result mal_device_start__jack(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - mal_context* pContext = pDevice->pContext; - mal_assert(pContext != NULL); - - int resultJACK = ((mal_jack_activate_proc)pContext->jack.jack_activate)((mal_jack_client_t*)pDevice->jack.pClient); - if (resultJACK != 0) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[JACK] Failed to activate the JACK client.", MAL_FAILED_TO_START_BACKEND_DEVICE); - } - - const char** ppServerPorts; - if (pDevice->type == mal_device_type_playback) { - ppServerPorts = ((mal_jack_get_ports_proc)pContext->jack.jack_get_ports)((mal_jack_client_t*)pDevice->jack.pClient, NULL, NULL, mal_JackPortIsPhysical | mal_JackPortIsInput); - } else { - ppServerPorts = ((mal_jack_get_ports_proc)pContext->jack.jack_get_ports)((mal_jack_client_t*)pDevice->jack.pClient, NULL, NULL, mal_JackPortIsPhysical | mal_JackPortIsOutput); - } - - if (ppServerPorts == NULL) { - ((mal_jack_deactivate_proc)pContext->jack.jack_deactivate)((mal_jack_client_t*)pDevice->jack.pClient); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[JACK] Failed to retrieve physical ports.", MAL_ERROR); - } - - for (size_t i = 0; ppServerPorts[i] != NULL; ++i) { - const char* pServerPort = ppServerPorts[i]; - mal_assert(pServerPort != NULL); - - const char* pClientPort = ((mal_jack_port_name_proc)pContext->jack.jack_port_name)((mal_jack_port_t*)pDevice->jack.pPorts[i]); - mal_assert(pClientPort != NULL); - - if (pDevice->type == mal_device_type_playback) { - resultJACK = ((mal_jack_connect_proc)pContext->jack.jack_connect)((mal_jack_client_t*)pDevice->jack.pClient, pClientPort, pServerPort); - } else { - resultJACK = ((mal_jack_connect_proc)pContext->jack.jack_connect)((mal_jack_client_t*)pDevice->jack.pClient, pServerPort, pClientPort); - } - - if (resultJACK != 0) { - ((mal_jack_free_proc)pContext->jack.jack_free)((void*)ppServerPorts); - ((mal_jack_deactivate_proc)pContext->jack.jack_deactivate)((mal_jack_client_t*)pDevice->jack.pClient); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[JACK] Failed to connect ports.", MAL_ERROR); - } - } - - ((mal_jack_free_proc)pContext->jack.jack_free)((void*)ppServerPorts); - - return MAL_SUCCESS; -} - -mal_result mal_device_stop__jack(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - mal_context* pContext = pDevice->pContext; - mal_assert(pContext != NULL); - - if (((mal_jack_deactivate_proc)pContext->jack.jack_deactivate)((mal_jack_client_t*)pDevice->jack.pClient) != 0) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[JACK] An error occurred when deactivating the JACK client.", MAL_ERROR); - } - - mal_device__set_state(pDevice, MAL_STATE_STOPPED); - mal_stop_proc onStop = pDevice->onStop; - if (onStop) { - onStop(pDevice); - } - - return MAL_SUCCESS; -} - - -mal_result mal_context_uninit__jack(mal_context* pContext) -{ - mal_assert(pContext != NULL); - mal_assert(pContext->backend == mal_backend_jack); - -#ifndef MAL_NO_RUNTIME_LINKING - mal_dlclose(pContext->jack.jackSO); -#endif - - return MAL_SUCCESS; -} - -mal_result mal_context_init__jack(mal_context* pContext) -{ - mal_assert(pContext != NULL); - -#ifndef MAL_NO_RUNTIME_LINKING - // libjack.so - const char* libjackNames[] = { -#ifdef MAL_WIN32 - "libjack.dll" -#else - "libjack.so", - "libjack.so.0" -#endif - }; - - for (size_t i = 0; i < mal_countof(libjackNames); ++i) { - pContext->jack.jackSO = mal_dlopen(libjackNames[i]); - if (pContext->jack.jackSO != NULL) { - break; - } - } - - if (pContext->jack.jackSO == NULL) { - return MAL_NO_BACKEND; - } - - pContext->jack.jack_client_open = (mal_proc)mal_dlsym(pContext->jack.jackSO, "jack_client_open"); - pContext->jack.jack_client_close = (mal_proc)mal_dlsym(pContext->jack.jackSO, "jack_client_close"); - pContext->jack.jack_client_name_size = (mal_proc)mal_dlsym(pContext->jack.jackSO, "jack_client_name_size"); - pContext->jack.jack_set_process_callback = (mal_proc)mal_dlsym(pContext->jack.jackSO, "jack_set_process_callback"); - pContext->jack.jack_set_buffer_size_callback = (mal_proc)mal_dlsym(pContext->jack.jackSO, "jack_set_buffer_size_callback"); - pContext->jack.jack_on_shutdown = (mal_proc)mal_dlsym(pContext->jack.jackSO, "jack_on_shutdown"); - pContext->jack.jack_get_sample_rate = (mal_proc)mal_dlsym(pContext->jack.jackSO, "jack_get_sample_rate"); - pContext->jack.jack_get_buffer_size = (mal_proc)mal_dlsym(pContext->jack.jackSO, "jack_get_buffer_size"); - pContext->jack.jack_get_ports = (mal_proc)mal_dlsym(pContext->jack.jackSO, "jack_get_ports"); - pContext->jack.jack_activate = (mal_proc)mal_dlsym(pContext->jack.jackSO, "jack_activate"); - pContext->jack.jack_deactivate = (mal_proc)mal_dlsym(pContext->jack.jackSO, "jack_deactivate"); - pContext->jack.jack_connect = (mal_proc)mal_dlsym(pContext->jack.jackSO, "jack_connect"); - pContext->jack.jack_port_register = (mal_proc)mal_dlsym(pContext->jack.jackSO, "jack_port_register"); - pContext->jack.jack_port_name = (mal_proc)mal_dlsym(pContext->jack.jackSO, "jack_port_name"); - pContext->jack.jack_port_get_buffer = (mal_proc)mal_dlsym(pContext->jack.jackSO, "jack_port_get_buffer"); - pContext->jack.jack_free = (mal_proc)mal_dlsym(pContext->jack.jackSO, "jack_free"); -#else - // This strange assignment system is here just to ensure type safety of mini_al's function pointer - // types. If anything differs slightly the compiler should throw a warning. - mal_jack_client_open_proc _jack_client_open = jack_client_open; - mal_jack_client_close_proc _jack_client_close = jack_client_close; - mal_jack_client_name_size_proc _jack_client_name_size = jack_client_name_size; - mal_jack_set_process_callback_proc _jack_set_process_callback = jack_set_process_callback; - mal_jack_set_buffer_size_callback_proc _jack_set_buffer_size_callback = jack_set_buffer_size_callback; - mal_jack_on_shutdown_proc _jack_on_shutdown = jack_on_shutdown; - mal_jack_get_sample_rate_proc _jack_get_sample_rate = jack_get_sample_rate; - mal_jack_get_buffer_size_proc _jack_get_buffer_size = jack_get_buffer_size; - mal_jack_get_ports_proc _jack_get_ports = jack_get_ports; - mal_jack_activate_proc _jack_activate = jack_activate; - mal_jack_deactivate_proc _jack_deactivate = jack_deactivate; - mal_jack_connect_proc _jack_connect = jack_connect; - mal_jack_port_register_proc _jack_port_register = jack_port_register; - mal_jack_port_name_proc _jack_port_name = jack_port_name; - mal_jack_port_get_buffer_proc _jack_port_get_buffer = jack_port_get_buffer; - mal_jack_free_proc _jack_free = jack_free; - - pContext->jack.jack_client_open = (mal_proc)_jack_client_open; - pContext->jack.jack_client_close = (mal_proc)_jack_client_close; - pContext->jack.jack_client_name_size = (mal_proc)_jack_client_name_size; - pContext->jack.jack_set_process_callback = (mal_proc)_jack_set_process_callback; - pContext->jack.jack_set_buffer_size_callback = (mal_proc)_jack_set_buffer_size_callback; - pContext->jack.jack_on_shutdown = (mal_proc)_jack_on_shutdown; - pContext->jack.jack_get_sample_rate = (mal_proc)_jack_get_sample_rate; - pContext->jack.jack_get_buffer_size = (mal_proc)_jack_get_buffer_size; - pContext->jack.jack_get_ports = (mal_proc)_jack_get_ports; - pContext->jack.jack_activate = (mal_proc)_jack_activate; - pContext->jack.jack_deactivate = (mal_proc)_jack_deactivate; - pContext->jack.jack_connect = (mal_proc)_jack_connect; - pContext->jack.jack_port_register = (mal_proc)_jack_port_register; - pContext->jack.jack_port_name = (mal_proc)_jack_port_name; - pContext->jack.jack_port_get_buffer = (mal_proc)_jack_port_get_buffer; - pContext->jack.jack_free = (mal_proc)_jack_free; -#endif - - pContext->isBackendAsynchronous = MAL_TRUE; - - pContext->onUninit = mal_context_uninit__jack; - pContext->onDeviceIDEqual = mal_context_is_device_id_equal__jack; - pContext->onEnumDevices = mal_context_enumerate_devices__jack; - pContext->onGetDeviceInfo = mal_context_get_device_info__jack; - pContext->onDeviceInit = mal_device_init__jack; - pContext->onDeviceUninit = mal_device_uninit__jack; - pContext->onDeviceStart = mal_device_start__jack; - pContext->onDeviceStop = mal_device_stop__jack; - - - // Getting here means the JACK library is installed, but it doesn't necessarily mean it's usable. We need to quickly test this by connecting - // a temporary client. - mal_jack_client_t* pDummyClient; - mal_result result = mal_context_open_client__jack(pContext, &pDummyClient); - if (result != MAL_SUCCESS) { - return MAL_NO_BACKEND; - } - - ((mal_jack_client_close_proc)pContext->jack.jack_client_close)((mal_jack_client_t*)pDummyClient); - return MAL_SUCCESS; -} -#endif // JACK - - - -/////////////////////////////////////////////////////////////////////////////// -// -// Core Audio Backend -// -/////////////////////////////////////////////////////////////////////////////// -#ifdef MAL_HAS_COREAUDIO -#include - -#if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE == 1 - #define MAL_APPLE_MOBILE -#else - #define MAL_APPLE_DESKTOP -#endif - -#if defined(MAL_APPLE_DESKTOP) -#include -#else -#include -#endif - -#include - -// CoreFoundation -typedef Boolean (* mal_CFStringGetCString_proc)(CFStringRef theString, char* buffer, CFIndex bufferSize, CFStringEncoding encoding); - -// CoreAudio -#if defined(MAL_APPLE_DESKTOP) -typedef OSStatus (* mal_AudioObjectGetPropertyData_proc)(AudioObjectID inObjectID, const AudioObjectPropertyAddress* inAddress, UInt32 inQualifierDataSize, const void* inQualifierData, UInt32* ioDataSize, void* outData); -typedef OSStatus (* mal_AudioObjectGetPropertyDataSize_proc)(AudioObjectID inObjectID, const AudioObjectPropertyAddress* inAddress, UInt32 inQualifierDataSize, const void* inQualifierData, UInt32* outDataSize); -typedef OSStatus (* mal_AudioObjectSetPropertyData_proc)(AudioObjectID inObjectID, const AudioObjectPropertyAddress* inAddress, UInt32 inQualifierDataSize, const void* inQualifierData, UInt32 inDataSize, const void* inData); -typedef OSStatus (* mal_AudioObjectAddPropertyListener_proc)(AudioObjectID inObjectID, const AudioObjectPropertyAddress* inAddress, AudioObjectPropertyListenerProc inListener, void* inClientData); -#endif - -// AudioToolbox -typedef AudioComponent (* mal_AudioComponentFindNext_proc)(AudioComponent inComponent, const AudioComponentDescription* inDesc); -typedef OSStatus (* mal_AudioComponentInstanceDispose_proc)(AudioComponentInstance inInstance); -typedef OSStatus (* mal_AudioComponentInstanceNew_proc)(AudioComponent inComponent, AudioComponentInstance* outInstance); -typedef OSStatus (* mal_AudioOutputUnitStart_proc)(AudioUnit inUnit); -typedef OSStatus (* mal_AudioOutputUnitStop_proc)(AudioUnit inUnit); -typedef OSStatus (* mal_AudioUnitAddPropertyListener_proc)(AudioUnit inUnit, AudioUnitPropertyID inID, AudioUnitPropertyListenerProc inProc, void* inProcUserData); -typedef OSStatus (* mal_AudioUnitGetPropertyInfo_proc)(AudioUnit inUnit, AudioUnitPropertyID inID, AudioUnitScope inScope, AudioUnitElement inElement, UInt32* outDataSize, Boolean* outWriteable); -typedef OSStatus (* mal_AudioUnitGetProperty_proc)(AudioUnit inUnit, AudioUnitPropertyID inID, AudioUnitScope inScope, AudioUnitElement inElement, void* outData, UInt32* ioDataSize); -typedef OSStatus (* mal_AudioUnitSetProperty_proc)(AudioUnit inUnit, AudioUnitPropertyID inID, AudioUnitScope inScope, AudioUnitElement inElement, const void* inData, UInt32 inDataSize); -typedef OSStatus (* mal_AudioUnitInitialize_proc)(AudioUnit inUnit); -typedef OSStatus (* mal_AudioUnitRender_proc)(AudioUnit inUnit, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp, UInt32 inOutputBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData); - - -#define MAL_COREAUDIO_OUTPUT_BUS 0 -#define MAL_COREAUDIO_INPUT_BUS 1 - -mal_result mal_device_reinit_internal__coreaudio(mal_device* pDevice, mal_bool32 disposePreviousAudioUnit); - - -// Core Audio -// -// So far, Core Audio has been the worst backend to work with due to being both unintuitive and having almost no documentation -// apart from comments in the headers (which admittedly are quite good). For my own purposes, and for anybody out there whose -// needing to figure out how this darn thing works, I'm going to outline a few things here. -// -// Since mini_al is a fairly low-level API, one of the things it needs is control over specific devices, and it needs to be -// able to identify whether or not it can be used as playback and/or capture. The AudioObject API is the only one I've seen -// that supports this level of detail. There was some public domain sample code I stumbled across that used the AudioComponent -// and AudioUnit APIs, but I couldn't see anything that gave low-level control over device selection and capabilities (the -// distinction between playback and capture in particular). Therefore, mini_al is using the AudioObject API. -// -// Most (all?) functions in the AudioObject API take a AudioObjectID as it's input. This is the device identifier. When -// retrieving global information, such as the device list, you use kAudioObjectSystemObject. When retrieving device-specific -// data, you pass in the ID for that device. In order to retrieve device-specific IDs you need to enumerate over each of the -// devices. This is done using the AudioObjectGetPropertyDataSize() and AudioObjectGetPropertyData() APIs which seem to be -// the central APIs for retrieving information about the system and specific devices. -// -// To use the AudioObjectGetPropertyData() API you need to use the notion of a property address. A property address is a -// structure with three variables and is used to identify which property you are getting or setting. The first is the "selector" -// which is basically the specific property that you're wanting to retrieve or set. The second is the "scope", which is -// typically set to kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyScopeInput for input-specific properties and -// kAudioObjectPropertyScopeOutput for output-specific properties. The last is the "element" which is always set to -// kAudioObjectPropertyElementMaster in mini_al's case. I don't know of any cases where this would be set to anything different. -// -// Back to the earlier issue of device retrieval, you first use the AudioObjectGetPropertyDataSize() API to retrieve the size -// of the raw data which is just a list of AudioDeviceID's. You use the kAudioObjectSystemObject AudioObjectID, and a property -// address with the kAudioHardwarePropertyDevices selector and the kAudioObjectPropertyScopeGlobal scope. Once you have the -// size, allocate a block of memory of that size and then call AudioObjectGetPropertyData(). The data is just a list of -// AudioDeviceID's so just do "dataSize/sizeof(AudioDeviceID)" to know the device count. - -mal_result mal_result_from_OSStatus(OSStatus status) -{ - switch (status) - { - case noErr: return MAL_SUCCESS; - #if defined(MAL_APPLE_DESKTOP) - case kAudioHardwareNotRunningError: return MAL_DEVICE_NOT_STARTED; - case kAudioHardwareUnspecifiedError: return MAL_ERROR; - case kAudioHardwareUnknownPropertyError: return MAL_INVALID_ARGS; - case kAudioHardwareBadPropertySizeError: return MAL_INVALID_OPERATION; - case kAudioHardwareIllegalOperationError: return MAL_INVALID_OPERATION; - case kAudioHardwareBadObjectError: return MAL_INVALID_ARGS; - case kAudioHardwareBadDeviceError: return MAL_INVALID_ARGS; - case kAudioHardwareBadStreamError: return MAL_INVALID_ARGS; - case kAudioHardwareUnsupportedOperationError: return MAL_INVALID_OPERATION; - case kAudioDeviceUnsupportedFormatError: return MAL_FORMAT_NOT_SUPPORTED; - case kAudioDevicePermissionsError: return MAL_ACCESS_DENIED; - #endif - default: return MAL_ERROR; - } -} - -#if 0 -mal_channel mal_channel_from_AudioChannelBitmap(AudioChannelBitmap bit) -{ - switch (bit) - { - case kAudioChannelBit_Left: return MAL_CHANNEL_LEFT; - case kAudioChannelBit_Right: return MAL_CHANNEL_RIGHT; - case kAudioChannelBit_Center: return MAL_CHANNEL_FRONT_CENTER; - case kAudioChannelBit_LFEScreen: return MAL_CHANNEL_LFE; - case kAudioChannelBit_LeftSurround: return MAL_CHANNEL_BACK_LEFT; - case kAudioChannelBit_RightSurround: return MAL_CHANNEL_BACK_RIGHT; - case kAudioChannelBit_LeftCenter: return MAL_CHANNEL_FRONT_LEFT_CENTER; - case kAudioChannelBit_RightCenter: return MAL_CHANNEL_FRONT_RIGHT_CENTER; - case kAudioChannelBit_CenterSurround: return MAL_CHANNEL_BACK_CENTER; - case kAudioChannelBit_LeftSurroundDirect: return MAL_CHANNEL_SIDE_LEFT; - case kAudioChannelBit_RightSurroundDirect: return MAL_CHANNEL_SIDE_RIGHT; - case kAudioChannelBit_TopCenterSurround: return MAL_CHANNEL_TOP_CENTER; - case kAudioChannelBit_VerticalHeightLeft: return MAL_CHANNEL_TOP_FRONT_LEFT; - case kAudioChannelBit_VerticalHeightCenter: return MAL_CHANNEL_TOP_FRONT_CENTER; - case kAudioChannelBit_VerticalHeightRight: return MAL_CHANNEL_TOP_FRONT_RIGHT; - case kAudioChannelBit_TopBackLeft: return MAL_CHANNEL_TOP_BACK_LEFT; - case kAudioChannelBit_TopBackCenter: return MAL_CHANNEL_TOP_BACK_CENTER; - case kAudioChannelBit_TopBackRight: return MAL_CHANNEL_TOP_BACK_RIGHT; - default: return MAL_CHANNEL_NONE; - } -} -#endif - -mal_channel mal_channel_from_AudioChannelLabel(AudioChannelLabel label) -{ - switch (label) - { - case kAudioChannelLabel_Unknown: return MAL_CHANNEL_NONE; - case kAudioChannelLabel_Unused: return MAL_CHANNEL_NONE; - case kAudioChannelLabel_UseCoordinates: return MAL_CHANNEL_NONE; - case kAudioChannelLabel_Left: return MAL_CHANNEL_LEFT; - case kAudioChannelLabel_Right: return MAL_CHANNEL_RIGHT; - case kAudioChannelLabel_Center: return MAL_CHANNEL_FRONT_CENTER; - case kAudioChannelLabel_LFEScreen: return MAL_CHANNEL_LFE; - case kAudioChannelLabel_LeftSurround: return MAL_CHANNEL_BACK_LEFT; - case kAudioChannelLabel_RightSurround: return MAL_CHANNEL_BACK_RIGHT; - case kAudioChannelLabel_LeftCenter: return MAL_CHANNEL_FRONT_LEFT_CENTER; - case kAudioChannelLabel_RightCenter: return MAL_CHANNEL_FRONT_RIGHT_CENTER; - case kAudioChannelLabel_CenterSurround: return MAL_CHANNEL_BACK_CENTER; - case kAudioChannelLabel_LeftSurroundDirect: return MAL_CHANNEL_SIDE_LEFT; - case kAudioChannelLabel_RightSurroundDirect: return MAL_CHANNEL_SIDE_RIGHT; - case kAudioChannelLabel_TopCenterSurround: return MAL_CHANNEL_TOP_CENTER; - case kAudioChannelLabel_VerticalHeightLeft: return MAL_CHANNEL_TOP_FRONT_LEFT; - case kAudioChannelLabel_VerticalHeightCenter: return MAL_CHANNEL_TOP_FRONT_CENTER; - case kAudioChannelLabel_VerticalHeightRight: return MAL_CHANNEL_TOP_FRONT_RIGHT; - case kAudioChannelLabel_TopBackLeft: return MAL_CHANNEL_TOP_BACK_LEFT; - case kAudioChannelLabel_TopBackCenter: return MAL_CHANNEL_TOP_BACK_CENTER; - case kAudioChannelLabel_TopBackRight: return MAL_CHANNEL_TOP_BACK_RIGHT; - case kAudioChannelLabel_RearSurroundLeft: return MAL_CHANNEL_BACK_LEFT; - case kAudioChannelLabel_RearSurroundRight: return MAL_CHANNEL_BACK_RIGHT; - case kAudioChannelLabel_LeftWide: return MAL_CHANNEL_SIDE_LEFT; - case kAudioChannelLabel_RightWide: return MAL_CHANNEL_SIDE_RIGHT; - case kAudioChannelLabel_LFE2: return MAL_CHANNEL_LFE; - case kAudioChannelLabel_LeftTotal: return MAL_CHANNEL_LEFT; - case kAudioChannelLabel_RightTotal: return MAL_CHANNEL_RIGHT; - case kAudioChannelLabel_HearingImpaired: return MAL_CHANNEL_NONE; - case kAudioChannelLabel_Narration: return MAL_CHANNEL_MONO; - case kAudioChannelLabel_Mono: return MAL_CHANNEL_MONO; - case kAudioChannelLabel_DialogCentricMix: return MAL_CHANNEL_MONO; - case kAudioChannelLabel_CenterSurroundDirect: return MAL_CHANNEL_BACK_CENTER; - case kAudioChannelLabel_Haptic: return MAL_CHANNEL_NONE; - case kAudioChannelLabel_Ambisonic_W: return MAL_CHANNEL_NONE; - case kAudioChannelLabel_Ambisonic_X: return MAL_CHANNEL_NONE; - case kAudioChannelLabel_Ambisonic_Y: return MAL_CHANNEL_NONE; - case kAudioChannelLabel_Ambisonic_Z: return MAL_CHANNEL_NONE; - case kAudioChannelLabel_MS_Mid: return MAL_CHANNEL_LEFT; - case kAudioChannelLabel_MS_Side: return MAL_CHANNEL_RIGHT; - case kAudioChannelLabel_XY_X: return MAL_CHANNEL_LEFT; - case kAudioChannelLabel_XY_Y: return MAL_CHANNEL_RIGHT; - case kAudioChannelLabel_HeadphonesLeft: return MAL_CHANNEL_LEFT; - case kAudioChannelLabel_HeadphonesRight: return MAL_CHANNEL_RIGHT; - case kAudioChannelLabel_ClickTrack: return MAL_CHANNEL_NONE; - case kAudioChannelLabel_ForeignLanguage: return MAL_CHANNEL_NONE; - case kAudioChannelLabel_Discrete: return MAL_CHANNEL_NONE; - case kAudioChannelLabel_Discrete_0: return MAL_CHANNEL_AUX_0; - case kAudioChannelLabel_Discrete_1: return MAL_CHANNEL_AUX_1; - case kAudioChannelLabel_Discrete_2: return MAL_CHANNEL_AUX_2; - case kAudioChannelLabel_Discrete_3: return MAL_CHANNEL_AUX_3; - case kAudioChannelLabel_Discrete_4: return MAL_CHANNEL_AUX_4; - case kAudioChannelLabel_Discrete_5: return MAL_CHANNEL_AUX_5; - case kAudioChannelLabel_Discrete_6: return MAL_CHANNEL_AUX_6; - case kAudioChannelLabel_Discrete_7: return MAL_CHANNEL_AUX_7; - case kAudioChannelLabel_Discrete_8: return MAL_CHANNEL_AUX_8; - case kAudioChannelLabel_Discrete_9: return MAL_CHANNEL_AUX_9; - case kAudioChannelLabel_Discrete_10: return MAL_CHANNEL_AUX_10; - case kAudioChannelLabel_Discrete_11: return MAL_CHANNEL_AUX_11; - case kAudioChannelLabel_Discrete_12: return MAL_CHANNEL_AUX_12; - case kAudioChannelLabel_Discrete_13: return MAL_CHANNEL_AUX_13; - case kAudioChannelLabel_Discrete_14: return MAL_CHANNEL_AUX_14; - case kAudioChannelLabel_Discrete_15: return MAL_CHANNEL_AUX_15; - case kAudioChannelLabel_Discrete_65535: return MAL_CHANNEL_NONE; - - #if 0 // Introduced in a later version of macOS. - case kAudioChannelLabel_HOA_ACN: return MAL_CHANNEL_NONE; - case kAudioChannelLabel_HOA_ACN_0: return MAL_CHANNEL_AUX_0; - case kAudioChannelLabel_HOA_ACN_1: return MAL_CHANNEL_AUX_1; - case kAudioChannelLabel_HOA_ACN_2: return MAL_CHANNEL_AUX_2; - case kAudioChannelLabel_HOA_ACN_3: return MAL_CHANNEL_AUX_3; - case kAudioChannelLabel_HOA_ACN_4: return MAL_CHANNEL_AUX_4; - case kAudioChannelLabel_HOA_ACN_5: return MAL_CHANNEL_AUX_5; - case kAudioChannelLabel_HOA_ACN_6: return MAL_CHANNEL_AUX_6; - case kAudioChannelLabel_HOA_ACN_7: return MAL_CHANNEL_AUX_7; - case kAudioChannelLabel_HOA_ACN_8: return MAL_CHANNEL_AUX_8; - case kAudioChannelLabel_HOA_ACN_9: return MAL_CHANNEL_AUX_9; - case kAudioChannelLabel_HOA_ACN_10: return MAL_CHANNEL_AUX_10; - case kAudioChannelLabel_HOA_ACN_11: return MAL_CHANNEL_AUX_11; - case kAudioChannelLabel_HOA_ACN_12: return MAL_CHANNEL_AUX_12; - case kAudioChannelLabel_HOA_ACN_13: return MAL_CHANNEL_AUX_13; - case kAudioChannelLabel_HOA_ACN_14: return MAL_CHANNEL_AUX_14; - case kAudioChannelLabel_HOA_ACN_15: return MAL_CHANNEL_AUX_15; - case kAudioChannelLabel_HOA_ACN_65024: return MAL_CHANNEL_NONE; - #endif - - default: return MAL_CHANNEL_NONE; - } -} - -mal_result mal_format_from_AudioStreamBasicDescription(const AudioStreamBasicDescription* pDescription, mal_format* pFormatOut) -{ - mal_assert(pDescription != NULL); - mal_assert(pFormatOut != NULL); - - *pFormatOut = mal_format_unknown; // Safety. - - // There's a few things mini_al doesn't support. - if (pDescription->mFormatID != kAudioFormatLinearPCM) { - return MAL_FORMAT_NOT_SUPPORTED; - } - - // We don't support any non-packed formats that are aligned high. - if ((pDescription->mFormatFlags & kLinearPCMFormatFlagIsAlignedHigh) != 0) { - return MAL_FORMAT_NOT_SUPPORTED; - } - - // Only supporting native-endian. - if ((mal_is_little_endian() && (pDescription->mFormatFlags & kAudioFormatFlagIsBigEndian) != 0) || (mal_is_big_endian() && (pDescription->mFormatFlags & kAudioFormatFlagIsBigEndian) == 0)) { - return MAL_FORMAT_NOT_SUPPORTED; - } - - // We are not currently supporting non-interleaved formats (this will be added in a future version of mini_al). - //if ((pDescription->mFormatFlags & kAudioFormatFlagIsNonInterleaved) != 0) { - // return MAL_FORMAT_NOT_SUPPORTED; - //} - - if ((pDescription->mFormatFlags & kLinearPCMFormatFlagIsFloat) != 0) { - if (pDescription->mBitsPerChannel == 32) { - *pFormatOut = mal_format_f32; - return MAL_SUCCESS; - } - } else { - if ((pDescription->mFormatFlags & kLinearPCMFormatFlagIsSignedInteger) != 0) { - if (pDescription->mBitsPerChannel == 16) { - *pFormatOut = mal_format_s16; - return MAL_SUCCESS; - } else if (pDescription->mBitsPerChannel == 24) { - if (pDescription->mBytesPerFrame == (pDescription->mBitsPerChannel/8 * pDescription->mChannelsPerFrame)) { - *pFormatOut = mal_format_s24; - return MAL_SUCCESS; - } else { - if (pDescription->mBytesPerFrame/pDescription->mChannelsPerFrame == sizeof(mal_int32)) { - // TODO: Implement mal_format_s24_32. - //*pFormatOut = mal_format_s24_32; - //return MAL_SUCCESS; - return MAL_FORMAT_NOT_SUPPORTED; - } - } - } else if (pDescription->mBitsPerChannel == 32) { - *pFormatOut = mal_format_s32; - return MAL_SUCCESS; - } - } else { - if (pDescription->mBitsPerChannel == 8) { - *pFormatOut = mal_format_u8; - return MAL_SUCCESS; - } - } - } - - // Getting here means the format is not supported. - return MAL_FORMAT_NOT_SUPPORTED; -} - -mal_result mal_get_channel_map_from_AudioChannelLayout(AudioChannelLayout* pChannelLayout, mal_channel channelMap[MAL_MAX_CHANNELS]) -{ - mal_assert(pChannelLayout != NULL); - - if (pChannelLayout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelDescriptions) { - for (UInt32 iChannel = 0; iChannel < pChannelLayout->mNumberChannelDescriptions; ++iChannel) { - channelMap[iChannel] = mal_channel_from_AudioChannelLabel(pChannelLayout->mChannelDescriptions[iChannel].mChannelLabel); - } - } else -#if 0 - if (pChannelLayout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelBitmap) { - // This is the same kind of system that's used by Windows audio APIs. - UInt32 iChannel = 0; - AudioChannelBitmap bitmap = pChannelLayout->mChannelBitmap; - for (UInt32 iBit = 0; iBit < 32; ++iBit) { - AudioChannelBitmap bit = bitmap & (1 << iBit); - if (bit != 0) { - channelMap[iChannel++] = mal_channel_from_AudioChannelBit(bit); - } - } - } else -#endif - { - // Need to use the tag to determine the channel map. For now I'm just assuming a default channel map, but later on this should - // be updated to determine the mapping based on the tag. - UInt32 channelCount = AudioChannelLayoutTag_GetNumberOfChannels(pChannelLayout->mChannelLayoutTag); - switch (pChannelLayout->mChannelLayoutTag) - { - case kAudioChannelLayoutTag_Mono: - case kAudioChannelLayoutTag_Stereo: - case kAudioChannelLayoutTag_StereoHeadphones: - case kAudioChannelLayoutTag_MatrixStereo: - case kAudioChannelLayoutTag_MidSide: - case kAudioChannelLayoutTag_XY: - case kAudioChannelLayoutTag_Binaural: - case kAudioChannelLayoutTag_Ambisonic_B_Format: - { - mal_get_standard_channel_map(mal_standard_channel_map_default, channelCount, channelMap); - } break; - - case kAudioChannelLayoutTag_Octagonal: - { - channelMap[7] = MAL_CHANNEL_SIDE_RIGHT; - channelMap[6] = MAL_CHANNEL_SIDE_LEFT; - } // Intentional fallthrough. - case kAudioChannelLayoutTag_Hexagonal: - { - channelMap[5] = MAL_CHANNEL_BACK_CENTER; - } // Intentional fallthrough. - case kAudioChannelLayoutTag_Pentagonal: - { - channelMap[4] = MAL_CHANNEL_FRONT_CENTER; - } // Intentional fallghrough. - case kAudioChannelLayoutTag_Quadraphonic: - { - channelMap[3] = MAL_CHANNEL_BACK_RIGHT; - channelMap[2] = MAL_CHANNEL_BACK_LEFT; - channelMap[1] = MAL_CHANNEL_RIGHT; - channelMap[0] = MAL_CHANNEL_LEFT; - } break; - - // TODO: Add support for more tags here. - - default: - { - mal_get_standard_channel_map(mal_standard_channel_map_default, channelCount, channelMap); - } break; - } - } - - return MAL_SUCCESS; -} - - -#if defined(MAL_APPLE_DESKTOP) -mal_result mal_get_device_object_ids__coreaudio(mal_context* pContext, UInt32* pDeviceCount, AudioObjectID** ppDeviceObjectIDs) // NOTE: Free the returned buffer with mal_free(). -{ - mal_assert(pContext != NULL); - mal_assert(pDeviceCount != NULL); - mal_assert(ppDeviceObjectIDs != NULL); - (void)pContext; - - // Safety. - *pDeviceCount = 0; - *ppDeviceObjectIDs = NULL; - - AudioObjectPropertyAddress propAddressDevices; - propAddressDevices.mSelector = kAudioHardwarePropertyDevices; - propAddressDevices.mScope = kAudioObjectPropertyScopeGlobal; - propAddressDevices.mElement = kAudioObjectPropertyElementMaster; - - UInt32 deviceObjectsDataSize; - OSStatus status = ((mal_AudioObjectGetPropertyDataSize_proc)pContext->coreaudio.AudioObjectGetPropertyDataSize)(kAudioObjectSystemObject, &propAddressDevices, 0, NULL, &deviceObjectsDataSize); - if (status != noErr) { - return mal_result_from_OSStatus(status); - } - - AudioObjectID* pDeviceObjectIDs = (AudioObjectID*)mal_malloc(deviceObjectsDataSize); - if (pDeviceObjectIDs == NULL) { - return MAL_OUT_OF_MEMORY; - } - - status = ((mal_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(kAudioObjectSystemObject, &propAddressDevices, 0, NULL, &deviceObjectsDataSize, pDeviceObjectIDs); - if (status != noErr) { - mal_free(pDeviceObjectIDs); - return mal_result_from_OSStatus(status); - } - - *pDeviceCount = deviceObjectsDataSize / sizeof(AudioObjectID); - *ppDeviceObjectIDs = pDeviceObjectIDs; - return MAL_SUCCESS; -} - -mal_result mal_get_AudioObject_uid_as_CFStringRef(mal_context* pContext, AudioObjectID objectID, CFStringRef* pUID) -{ - mal_assert(pContext != NULL); - - AudioObjectPropertyAddress propAddress; - propAddress.mSelector = kAudioDevicePropertyDeviceUID; - propAddress.mScope = kAudioObjectPropertyScopeGlobal; - propAddress.mElement = kAudioObjectPropertyElementMaster; - - UInt32 dataSize = sizeof(*pUID); - OSStatus status = ((mal_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(objectID, &propAddress, 0, NULL, &dataSize, pUID); - if (status != noErr) { - return mal_result_from_OSStatus(status); - } - - return MAL_SUCCESS; -} - -mal_result mal_get_AudioObject_uid(mal_context* pContext, AudioObjectID objectID, size_t bufferSize, char* bufferOut) -{ - mal_assert(pContext != NULL); - - CFStringRef uid; - mal_result result = mal_get_AudioObject_uid_as_CFStringRef(pContext, objectID, &uid); - if (result != MAL_SUCCESS) { - return result; - } - - if (!((mal_CFStringGetCString_proc)pContext->coreaudio.CFStringGetCString)(uid, bufferOut, bufferSize, kCFStringEncodingUTF8)) { - return MAL_ERROR; - } - - return MAL_SUCCESS; -} - -mal_result mal_get_AudioObject_name(mal_context* pContext, AudioObjectID objectID, size_t bufferSize, char* bufferOut) -{ - mal_assert(pContext != NULL); - - AudioObjectPropertyAddress propAddress; - propAddress.mSelector = kAudioDevicePropertyDeviceNameCFString; - propAddress.mScope = kAudioObjectPropertyScopeGlobal; - propAddress.mElement = kAudioObjectPropertyElementMaster; - - CFStringRef deviceName = NULL; - UInt32 dataSize = sizeof(deviceName); - OSStatus status = ((mal_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(objectID, &propAddress, 0, NULL, &dataSize, &deviceName); - if (status != noErr) { - return mal_result_from_OSStatus(status); - } - - if (!((mal_CFStringGetCString_proc)pContext->coreaudio.CFStringGetCString)(deviceName, bufferOut, bufferSize, kCFStringEncodingUTF8)) { - return MAL_ERROR; - } - - return MAL_SUCCESS; -} - -mal_bool32 mal_does_AudioObject_support_scope(mal_context* pContext, AudioObjectID deviceObjectID, AudioObjectPropertyScope scope) -{ - mal_assert(pContext != NULL); - - // To know whether or not a device is an input device we need ot look at the stream configuration. If it has an output channel it's a - // playback device. - AudioObjectPropertyAddress propAddress; - propAddress.mSelector = kAudioDevicePropertyStreamConfiguration; - propAddress.mScope = scope; - propAddress.mElement = kAudioObjectPropertyElementMaster; - - UInt32 dataSize; - OSStatus status = ((mal_AudioObjectGetPropertyDataSize_proc)pContext->coreaudio.AudioObjectGetPropertyDataSize)(deviceObjectID, &propAddress, 0, NULL, &dataSize); - if (status != noErr) { - return MAL_FALSE; - } - - AudioBufferList* pBufferList = (AudioBufferList*)mal_malloc(dataSize); - if (pBufferList == NULL) { - return MAL_FALSE; // Out of memory. - } - - status = ((mal_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(deviceObjectID, &propAddress, 0, NULL, &dataSize, pBufferList); - if (status != noErr) { - mal_free(pBufferList); - return MAL_FALSE; - } - - mal_bool32 isSupported = MAL_FALSE; - if (pBufferList->mNumberBuffers > 0) { - isSupported = MAL_TRUE; - } - - mal_free(pBufferList); - return isSupported; -} - -mal_bool32 mal_does_AudioObject_support_playback(mal_context* pContext, AudioObjectID deviceObjectID) -{ - return mal_does_AudioObject_support_scope(pContext, deviceObjectID, kAudioObjectPropertyScopeOutput); -} - -mal_bool32 mal_does_AudioObject_support_capture(mal_context* pContext, AudioObjectID deviceObjectID) -{ - return mal_does_AudioObject_support_scope(pContext, deviceObjectID, kAudioObjectPropertyScopeInput); -} - - -mal_result mal_get_AudioObject_stream_descriptions(mal_context* pContext, AudioObjectID deviceObjectID, mal_device_type deviceType, UInt32* pDescriptionCount, AudioStreamRangedDescription** ppDescriptions) // NOTE: Free the returned pointer with mal_free(). -{ - mal_assert(pContext != NULL); - mal_assert(pDescriptionCount != NULL); - mal_assert(ppDescriptions != NULL); - - // TODO: Experiment with kAudioStreamPropertyAvailablePhysicalFormats instead of (or in addition to) kAudioStreamPropertyAvailableVirtualFormats. My - // MacBook Pro uses s24/32 format, however, which mini_al does not currently support. - AudioObjectPropertyAddress propAddress; - propAddress.mSelector = kAudioStreamPropertyAvailableVirtualFormats; //kAudioStreamPropertyAvailablePhysicalFormats; - propAddress.mScope = (deviceType == mal_device_type_playback) ? kAudioObjectPropertyScopeOutput : kAudioObjectPropertyScopeInput; - propAddress.mElement = kAudioObjectPropertyElementMaster; - - UInt32 dataSize; - OSStatus status = ((mal_AudioObjectGetPropertyDataSize_proc)pContext->coreaudio.AudioObjectGetPropertyDataSize)(deviceObjectID, &propAddress, 0, NULL, &dataSize); - if (status != noErr) { - return mal_result_from_OSStatus(status); - } - - AudioStreamRangedDescription* pDescriptions = (AudioStreamRangedDescription*)mal_malloc(dataSize); - if (pDescriptions == NULL) { - return MAL_OUT_OF_MEMORY; - } - - status = ((mal_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(deviceObjectID, &propAddress, 0, NULL, &dataSize, pDescriptions); - if (status != noErr) { - mal_free(pDescriptions); - return mal_result_from_OSStatus(status); - } - - *pDescriptionCount = dataSize / sizeof(*pDescriptions); - *ppDescriptions = pDescriptions; - return MAL_SUCCESS; -} - - -mal_result mal_get_AudioObject_channel_layout(mal_context* pContext, AudioObjectID deviceObjectID, mal_device_type deviceType, AudioChannelLayout** ppChannelLayout) // NOTE: Free the returned pointer with mal_free(). -{ - mal_assert(pContext != NULL); - mal_assert(ppChannelLayout != NULL); - - *ppChannelLayout = NULL; // Safety. - - AudioObjectPropertyAddress propAddress; - propAddress.mSelector = kAudioDevicePropertyPreferredChannelLayout; - propAddress.mScope = (deviceType == mal_device_type_playback) ? kAudioObjectPropertyScopeOutput : kAudioObjectPropertyScopeInput; - propAddress.mElement = kAudioObjectPropertyElementMaster; - - UInt32 dataSize; - OSStatus status = ((mal_AudioObjectGetPropertyDataSize_proc)pContext->coreaudio.AudioObjectGetPropertyDataSize)(deviceObjectID, &propAddress, 0, NULL, &dataSize); - if (status != noErr) { - return mal_result_from_OSStatus(status); - } - - AudioChannelLayout* pChannelLayout = (AudioChannelLayout*)mal_malloc(dataSize); - if (pChannelLayout == NULL) { - return MAL_OUT_OF_MEMORY; - } - - status = ((mal_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(deviceObjectID, &propAddress, 0, NULL, &dataSize, pChannelLayout); - if (status != noErr) { - mal_free(pChannelLayout); - return mal_result_from_OSStatus(status); - } - - *ppChannelLayout = pChannelLayout; - return MAL_SUCCESS; -} - -mal_result mal_get_AudioObject_channel_count(mal_context* pContext, AudioObjectID deviceObjectID, mal_device_type deviceType, mal_uint32* pChannelCount) -{ - mal_assert(pContext != NULL); - mal_assert(pChannelCount != NULL); - - *pChannelCount = 0; // Safety. - - AudioChannelLayout* pChannelLayout; - mal_result result = mal_get_AudioObject_channel_layout(pContext, deviceObjectID, deviceType, &pChannelLayout); - if (result != MAL_SUCCESS) { - return result; - } - - if (pChannelLayout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelDescriptions) { - *pChannelCount = pChannelLayout->mNumberChannelDescriptions; - } else if (pChannelLayout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelBitmap) { - *pChannelCount = mal_count_set_bits(pChannelLayout->mChannelBitmap); - } else { - *pChannelCount = AudioChannelLayoutTag_GetNumberOfChannels(pChannelLayout->mChannelLayoutTag); - } - - mal_free(pChannelLayout); - return MAL_SUCCESS; -} - -mal_result mal_get_AudioObject_channel_map(mal_context* pContext, AudioObjectID deviceObjectID, mal_device_type deviceType, mal_channel channelMap[MAL_MAX_CHANNELS]) -{ - mal_assert(pContext != NULL); - - AudioChannelLayout* pChannelLayout; - mal_result result = mal_get_AudioObject_channel_layout(pContext, deviceObjectID, deviceType, &pChannelLayout); - if (result != MAL_SUCCESS) { - return result; // Rather than always failing here, would it be more robust to simply assume a default? - } - - result = mal_get_channel_map_from_AudioChannelLayout(pChannelLayout, channelMap); - if (result != MAL_SUCCESS) { - mal_free(pChannelLayout); - return result; - } - - mal_free(pChannelLayout); - return result; -} - -mal_result mal_get_AudioObject_sample_rates(mal_context* pContext, AudioObjectID deviceObjectID, mal_device_type deviceType, UInt32* pSampleRateRangesCount, AudioValueRange** ppSampleRateRanges) // NOTE: Free the returned pointer with mal_free(). -{ - mal_assert(pContext != NULL); - mal_assert(pSampleRateRangesCount != NULL); - mal_assert(ppSampleRateRanges != NULL); - - // Safety. - *pSampleRateRangesCount = 0; - *ppSampleRateRanges = NULL; - - AudioObjectPropertyAddress propAddress; - propAddress.mSelector = kAudioDevicePropertyAvailableNominalSampleRates; - propAddress.mScope = (deviceType == mal_device_type_playback) ? kAudioObjectPropertyScopeOutput : kAudioObjectPropertyScopeInput; - propAddress.mElement = kAudioObjectPropertyElementMaster; - - UInt32 dataSize; - OSStatus status = ((mal_AudioObjectGetPropertyDataSize_proc)pContext->coreaudio.AudioObjectGetPropertyDataSize)(deviceObjectID, &propAddress, 0, NULL, &dataSize); - if (status != noErr) { - return mal_result_from_OSStatus(status); - } - - AudioValueRange* pSampleRateRanges = (AudioValueRange*)mal_malloc(dataSize); - if (pSampleRateRanges == NULL) { - return MAL_OUT_OF_MEMORY; - } - - status = ((mal_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(deviceObjectID, &propAddress, 0, NULL, &dataSize, pSampleRateRanges); - if (status != noErr) { - mal_free(pSampleRateRanges); - return mal_result_from_OSStatus(status); - } - - *pSampleRateRangesCount = dataSize / sizeof(*pSampleRateRanges); - *ppSampleRateRanges = pSampleRateRanges; - return MAL_SUCCESS; -} - -mal_result mal_get_AudioObject_get_closest_sample_rate(mal_context* pContext, AudioObjectID deviceObjectID, mal_device_type deviceType, mal_uint32 sampleRateIn, mal_uint32* pSampleRateOut) -{ - mal_assert(pContext != NULL); - mal_assert(pSampleRateOut != NULL); - - *pSampleRateOut = 0; // Safety. - - UInt32 sampleRateRangeCount; - AudioValueRange* pSampleRateRanges; - mal_result result = mal_get_AudioObject_sample_rates(pContext, deviceObjectID, deviceType, &sampleRateRangeCount, &pSampleRateRanges); - if (result != MAL_SUCCESS) { - return result; - } - - if (sampleRateRangeCount == 0) { - mal_free(pSampleRateRanges); - return MAL_ERROR; // Should never hit this case should we? - } - - if (sampleRateIn == 0) { - // Search in order of mini_al's preferred priority. - for (UInt32 iMALSampleRate = 0; iMALSampleRate < mal_countof(g_malStandardSampleRatePriorities); ++iMALSampleRate) { - mal_uint32 malSampleRate = g_malStandardSampleRatePriorities[iMALSampleRate]; - for (UInt32 iCASampleRate = 0; iCASampleRate < sampleRateRangeCount; ++iCASampleRate) { - AudioValueRange caSampleRate = pSampleRateRanges[iCASampleRate]; - if (caSampleRate.mMinimum <= malSampleRate && caSampleRate.mMaximum >= malSampleRate) { - *pSampleRateOut = malSampleRate; - mal_free(pSampleRateRanges); - return MAL_SUCCESS; - } - } - } - - // If we get here it means none of mini_al's standard sample rates matched any of the supported sample rates from the device. In this - // case we just fall back to the first one reported by Core Audio. - mal_assert(sampleRateRangeCount > 0); - - *pSampleRateOut = pSampleRateRanges[0].mMinimum; - mal_free(pSampleRateRanges); - return MAL_SUCCESS; - } else { - // Find the closest match to this sample rate. - UInt32 currentAbsoluteDifference = INT32_MAX; - UInt32 iCurrentClosestRange = (UInt32)-1; - for (UInt32 iRange = 0; iRange < sampleRateRangeCount; ++iRange) { - if (pSampleRateRanges[iRange].mMinimum <= sampleRateIn && pSampleRateRanges[iRange].mMaximum >= sampleRateIn) { - *pSampleRateOut = sampleRateIn; - mal_free(pSampleRateRanges); - return MAL_SUCCESS; - } else { - UInt32 absoluteDifference; - if (pSampleRateRanges[iRange].mMinimum > sampleRateIn) { - absoluteDifference = pSampleRateRanges[iRange].mMinimum - sampleRateIn; - } else { - absoluteDifference = sampleRateIn - pSampleRateRanges[iRange].mMaximum; - } - - if (currentAbsoluteDifference > absoluteDifference) { - currentAbsoluteDifference = absoluteDifference; - iCurrentClosestRange = iRange; - } - } - } - - mal_assert(iCurrentClosestRange != (UInt32)-1); - - *pSampleRateOut = pSampleRateRanges[iCurrentClosestRange].mMinimum; - mal_free(pSampleRateRanges); - return MAL_SUCCESS; - } - - // Should never get here, but it would mean we weren't able to find any suitable sample rates. - //mal_free(pSampleRateRanges); - //return MAL_ERROR; -} - - -mal_result mal_get_AudioObject_closest_buffer_size_in_frames(mal_context* pContext, AudioObjectID deviceObjectID, mal_device_type deviceType, mal_uint32 bufferSizeInFramesIn, mal_uint32* pBufferSizeInFramesOut) -{ - mal_assert(pContext != NULL); - mal_assert(pBufferSizeInFramesOut != NULL); - - *pBufferSizeInFramesOut = 0; // Safety. - - AudioObjectPropertyAddress propAddress; - propAddress.mSelector = kAudioDevicePropertyBufferFrameSizeRange; - propAddress.mScope = (deviceType == mal_device_type_playback) ? kAudioObjectPropertyScopeOutput : kAudioObjectPropertyScopeInput; - propAddress.mElement = kAudioObjectPropertyElementMaster; - - AudioValueRange bufferSizeRange; - UInt32 dataSize = sizeof(bufferSizeRange); - OSStatus status = ((mal_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(deviceObjectID, &propAddress, 0, NULL, &dataSize, &bufferSizeRange); - if (status != noErr) { - return mal_result_from_OSStatus(status); - } - - // This is just a clamp. - if (bufferSizeInFramesIn < bufferSizeRange.mMinimum) { - *pBufferSizeInFramesOut = (mal_uint32)bufferSizeRange.mMinimum; - } else if (bufferSizeInFramesIn > bufferSizeRange.mMaximum) { - *pBufferSizeInFramesOut = (mal_uint32)bufferSizeRange.mMaximum; - } else { - *pBufferSizeInFramesOut = bufferSizeInFramesIn; - } - - return MAL_SUCCESS; -} - -mal_result mal_set_AudioObject_buffer_size_in_frames(mal_context* pContext, AudioObjectID deviceObjectID, mal_device_type deviceType, mal_uint32* pBufferSizeInOut) -{ - mal_assert(pContext != NULL); - - mal_uint32 chosenBufferSizeInFrames; - mal_result result = mal_get_AudioObject_closest_buffer_size_in_frames(pContext, deviceObjectID, deviceType, *pBufferSizeInOut, &chosenBufferSizeInFrames); - if (result != MAL_SUCCESS) { - return result; - } - - // Try setting the size of the buffer... If this fails we just use whatever is currently set. - AudioObjectPropertyAddress propAddress; - propAddress.mSelector = kAudioDevicePropertyBufferFrameSize; - propAddress.mScope = (deviceType == mal_device_type_playback) ? kAudioObjectPropertyScopeOutput : kAudioObjectPropertyScopeInput; - propAddress.mElement = kAudioObjectPropertyElementMaster; - - ((mal_AudioObjectSetPropertyData_proc)pContext->coreaudio.AudioObjectSetPropertyData)(deviceObjectID, &propAddress, 0, NULL, sizeof(chosenBufferSizeInFrames), &chosenBufferSizeInFrames); - - // Get the actual size of the buffer. - UInt32 dataSize = sizeof(*pBufferSizeInOut); - OSStatus status = ((mal_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(deviceObjectID, &propAddress, 0, NULL, &dataSize, &chosenBufferSizeInFrames); - if (status != noErr) { - return mal_result_from_OSStatus(status); - } - - *pBufferSizeInOut = chosenBufferSizeInFrames; - return MAL_SUCCESS; -} - - -mal_result mal_find_AudioObjectID(mal_context* pContext, mal_device_type type, const mal_device_id* pDeviceID, AudioObjectID* pDeviceObjectID) -{ - mal_assert(pContext != NULL); - mal_assert(pDeviceObjectID != NULL); - - // Safety. - *pDeviceObjectID = 0; - - if (pDeviceID == NULL) { - // Default device. - AudioObjectPropertyAddress propAddressDefaultDevice; - propAddressDefaultDevice.mScope = kAudioObjectPropertyScopeGlobal; - propAddressDefaultDevice.mElement = kAudioObjectPropertyElementMaster; - if (type == mal_device_type_playback) { - propAddressDefaultDevice.mSelector = kAudioHardwarePropertyDefaultOutputDevice; - } else { - propAddressDefaultDevice.mSelector = kAudioHardwarePropertyDefaultInputDevice; - } - - UInt32 defaultDeviceObjectIDSize = sizeof(AudioObjectID); - AudioObjectID defaultDeviceObjectID; - OSStatus status = ((mal_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(kAudioObjectSystemObject, &propAddressDefaultDevice, 0, NULL, &defaultDeviceObjectIDSize, &defaultDeviceObjectID); - if (status == noErr) { - *pDeviceObjectID = defaultDeviceObjectID; - return MAL_SUCCESS; - } - } else { - // Explicit device. - UInt32 deviceCount; - AudioObjectID* pDeviceObjectIDs; - mal_result result = mal_get_device_object_ids__coreaudio(pContext, &deviceCount, &pDeviceObjectIDs); - if (result != MAL_SUCCESS) { - return result; - } - - for (UInt32 iDevice = 0; iDevice < deviceCount; ++iDevice) { - AudioObjectID deviceObjectID = pDeviceObjectIDs[iDevice]; - - char uid[256]; - if (mal_get_AudioObject_uid(pContext, deviceObjectID, sizeof(uid), uid) != MAL_SUCCESS) { - continue; - } - - if (type == mal_device_type_playback) { - if (mal_does_AudioObject_support_playback(pContext, deviceObjectID)) { - if (strcmp(uid, pDeviceID->coreaudio) == 0) { - *pDeviceObjectID = deviceObjectID; - return MAL_SUCCESS; - } - } - } else { - if (mal_does_AudioObject_support_capture(pContext, deviceObjectID)) { - if (strcmp(uid, pDeviceID->coreaudio) == 0) { - *pDeviceObjectID = deviceObjectID; - return MAL_SUCCESS; - } - } - } - } - } - - // If we get here it means we couldn't find the device. - return MAL_NO_DEVICE; -} - - -mal_result mal_find_best_format__coreaudio(mal_context* pContext, AudioObjectID deviceObjectID, mal_device_type deviceType, mal_format format, mal_uint32 channels, mal_uint32 sampleRate, mal_bool32 usingDefaultFormat, mal_bool32 usingDefaultChannels, mal_bool32 usingDefaultSampleRate, AudioStreamBasicDescription* pFormat) -{ - UInt32 deviceFormatDescriptionCount; - AudioStreamRangedDescription* pDeviceFormatDescriptions; - mal_result result = mal_get_AudioObject_stream_descriptions(pContext, deviceObjectID, deviceType, &deviceFormatDescriptionCount, &pDeviceFormatDescriptions); - if (result != MAL_SUCCESS) { - return result; - } - - mal_uint32 desiredSampleRate = sampleRate; - if (usingDefaultSampleRate) { - // When using the device's default sample rate, we get the highest priority standard rate supported by the device. Otherwise - // we just use the pre-set rate. - for (mal_uint32 iStandardRate = 0; iStandardRate < mal_countof(g_malStandardSampleRatePriorities); ++iStandardRate) { - mal_uint32 standardRate = g_malStandardSampleRatePriorities[iStandardRate]; - - mal_bool32 foundRate = MAL_FALSE; - for (UInt32 iDeviceRate = 0; iDeviceRate < deviceFormatDescriptionCount; ++iDeviceRate) { - mal_uint32 deviceRate = (mal_uint32)pDeviceFormatDescriptions[iDeviceRate].mFormat.mSampleRate; - - if (deviceRate == standardRate) { - desiredSampleRate = standardRate; - foundRate = MAL_TRUE; - break; - } - } - - if (foundRate) { - break; - } - } - } - - mal_uint32 desiredChannelCount = channels; - if (usingDefaultChannels) { - mal_get_AudioObject_channel_count(pContext, deviceObjectID, deviceType, &desiredChannelCount); // <-- Not critical if this fails. - } - - mal_format desiredFormat = format; - if (usingDefaultFormat) { - desiredFormat = g_malFormatPriorities[0]; - } - - // If we get here it means we don't have an exact match to what the client is asking for. We'll need to find the closest one. The next - // loop will check for formats that have the same sample rate to what we're asking for. If there is, we prefer that one in all cases. - AudioStreamBasicDescription bestDeviceFormatSoFar; - mal_zero_object(&bestDeviceFormatSoFar); - - mal_bool32 hasSupportedFormat = MAL_FALSE; - for (UInt32 iFormat = 0; iFormat < deviceFormatDescriptionCount; ++iFormat) { - mal_format format; - mal_result formatResult = mal_format_from_AudioStreamBasicDescription(&pDeviceFormatDescriptions[iFormat].mFormat, &format); - if (formatResult == MAL_SUCCESS && format != mal_format_unknown) { - hasSupportedFormat = MAL_TRUE; - bestDeviceFormatSoFar = pDeviceFormatDescriptions[iFormat].mFormat; - break; - } - } - - if (!hasSupportedFormat) { - return MAL_FORMAT_NOT_SUPPORTED; - } - - - for (UInt32 iFormat = 0; iFormat < deviceFormatDescriptionCount; ++iFormat) { - AudioStreamBasicDescription thisDeviceFormat = pDeviceFormatDescriptions[iFormat].mFormat; - - // If the format is not supported by mini_al we need to skip this one entirely. - mal_format thisSampleFormat; - mal_result formatResult = mal_format_from_AudioStreamBasicDescription(&pDeviceFormatDescriptions[iFormat].mFormat, &thisSampleFormat); - if (formatResult != MAL_SUCCESS || thisSampleFormat == mal_format_unknown) { - continue; // The format is not supported by mini_al. Skip. - } - - mal_format bestSampleFormatSoFar; - mal_format_from_AudioStreamBasicDescription(&bestDeviceFormatSoFar, &bestSampleFormatSoFar); - - - // Getting here means the format is supported by mini_al which makes this format a candidate. - if (thisDeviceFormat.mSampleRate != desiredSampleRate) { - // The sample rate does not match, but this format could still be usable, although it's a very low priority. If the best format - // so far has an equal sample rate we can just ignore this one. - if (bestDeviceFormatSoFar.mSampleRate == desiredSampleRate) { - continue; // The best sample rate so far has the same sample rate as what we requested which means it's still the best so far. Skip this format. - } else { - // In this case, neither the best format so far nor this one have the same sample rate. Check the channel count next. - if (thisDeviceFormat.mChannelsPerFrame != desiredChannelCount) { - // This format has a different sample rate _and_ a different channel count. - if (bestDeviceFormatSoFar.mChannelsPerFrame == desiredChannelCount) { - continue; // No change to the best format. - } else { - // Both this format and the best so far have different sample rates and different channel counts. Whichever has the - // best format is the new best. - if (mal_get_format_priority_index(thisSampleFormat) < mal_get_format_priority_index(bestSampleFormatSoFar)) { - bestDeviceFormatSoFar = thisDeviceFormat; - continue; - } else { - continue; // No change to the best format. - } - } - } else { - // This format has a different sample rate but the desired channel count. - if (bestDeviceFormatSoFar.mChannelsPerFrame == desiredChannelCount) { - // Both this format and the best so far have the desired channel count. Whichever has the best format is the new best. - if (mal_get_format_priority_index(thisSampleFormat) < mal_get_format_priority_index(bestSampleFormatSoFar)) { - bestDeviceFormatSoFar = thisDeviceFormat; - continue; - } else { - continue; // No change to the best format for now. - } - } else { - // This format has the desired channel count, but the best so far does not. We have a new best. - bestDeviceFormatSoFar = thisDeviceFormat; - continue; - } - } - } - } else { - // The sample rates match which makes this format a very high priority contender. If the best format so far has a different - // sample rate it needs to be replaced with this one. - if (bestDeviceFormatSoFar.mSampleRate != desiredSampleRate) { - bestDeviceFormatSoFar = thisDeviceFormat; - continue; - } else { - // In this case both this format and the best format so far have the same sample rate. Check the channel count next. - if (thisDeviceFormat.mChannelsPerFrame == desiredChannelCount) { - // In this case this format has the same channel count as what the client is requesting. If the best format so far has - // a different count, this one becomes the new best. - if (bestDeviceFormatSoFar.mChannelsPerFrame != desiredChannelCount) { - bestDeviceFormatSoFar = thisDeviceFormat; - continue; - } else { - // In this case both this format and the best so far have the ideal sample rate and channel count. Check the format. - if (thisSampleFormat == desiredFormat) { - bestDeviceFormatSoFar = thisDeviceFormat; - break; // Found the exact match. - } else { - // The formats are different. The new best format is the one with the highest priority format according to mini_al. - if (mal_get_format_priority_index(thisSampleFormat) < mal_get_format_priority_index(bestSampleFormatSoFar)) { - bestDeviceFormatSoFar = thisDeviceFormat; - continue; - } else { - continue; // No change to the best format for now. - } - } - } - } else { - // In this case the channel count is different to what the client has requested. If the best so far has the same channel - // count as the requested count then it remains the best. - if (bestDeviceFormatSoFar.mChannelsPerFrame == desiredChannelCount) { - continue; - } else { - // This is the case where both have the same sample rate (good) but different channel counts. Right now both have about - // the same priority, but we need to compare the format now. - if (thisSampleFormat == bestSampleFormatSoFar) { - if (mal_get_format_priority_index(thisSampleFormat) < mal_get_format_priority_index(bestSampleFormatSoFar)) { - bestDeviceFormatSoFar = thisDeviceFormat; - continue; - } else { - continue; // No change to the best format for now. - } - } - } - } - } - } - } - - *pFormat = bestDeviceFormatSoFar; - return MAL_SUCCESS; -} -#endif - -mal_result mal_get_AudioUnit_channel_map(mal_context* pContext, AudioUnit audioUnit, mal_device_type deviceType, mal_channel channelMap[MAL_MAX_CHANNELS]) -{ - mal_assert(pContext != NULL); - - AudioUnitScope deviceScope; - AudioUnitElement deviceBus; - if (deviceType == mal_device_type_playback) { - deviceScope = kAudioUnitScope_Output; - deviceBus = MAL_COREAUDIO_OUTPUT_BUS; - } else { - deviceScope = kAudioUnitScope_Input; - deviceBus = MAL_COREAUDIO_INPUT_BUS; - } - - UInt32 channelLayoutSize; - OSStatus status = ((mal_AudioUnitGetPropertyInfo_proc)pContext->coreaudio.AudioUnitGetPropertyInfo)(audioUnit, kAudioUnitProperty_AudioChannelLayout, deviceScope, deviceBus, &channelLayoutSize, NULL); - if (status != noErr) { - return mal_result_from_OSStatus(status); - } - - AudioChannelLayout* pChannelLayout = (AudioChannelLayout*)mal_malloc(channelLayoutSize); - if (pChannelLayout == NULL) { - return MAL_OUT_OF_MEMORY; - } - - status = ((mal_AudioUnitGetProperty_proc)pContext->coreaudio.AudioUnitGetProperty)(audioUnit, kAudioUnitProperty_AudioChannelLayout, deviceScope, deviceBus, pChannelLayout, &channelLayoutSize); - if (status != noErr) { - mal_free(pChannelLayout); - return mal_result_from_OSStatus(status); - } - - mal_result result = mal_get_channel_map_from_AudioChannelLayout(pChannelLayout, channelMap); - if (result != MAL_SUCCESS) { - mal_free(pChannelLayout); - return result; - } - - mal_free(pChannelLayout); - return MAL_SUCCESS; -} - -mal_bool32 mal_context_is_device_id_equal__coreaudio(mal_context* pContext, const mal_device_id* pID0, const mal_device_id* pID1) -{ - mal_assert(pContext != NULL); - mal_assert(pID0 != NULL); - mal_assert(pID1 != NULL); - (void)pContext; - - return strcmp(pID0->coreaudio, pID1->coreaudio) == 0; -} - -mal_result mal_context_enumerate_devices__coreaudio(mal_context* pContext, mal_enum_devices_callback_proc callback, void* pUserData) -{ - mal_assert(pContext != NULL); - mal_assert(callback != NULL); - -#if defined(MAL_APPLE_DESKTOP) - UInt32 deviceCount; - AudioObjectID* pDeviceObjectIDs; - mal_result result = mal_get_device_object_ids__coreaudio(pContext, &deviceCount, &pDeviceObjectIDs); - if (result != MAL_SUCCESS) { - return result; - } - - for (UInt32 iDevice = 0; iDevice < deviceCount; ++iDevice) { - AudioObjectID deviceObjectID = pDeviceObjectIDs[iDevice]; - - mal_device_info info; - mal_zero_object(&info); - if (mal_get_AudioObject_uid(pContext, deviceObjectID, sizeof(info.id.coreaudio), info.id.coreaudio) != MAL_SUCCESS) { - continue; - } - if (mal_get_AudioObject_name(pContext, deviceObjectID, sizeof(info.name), info.name) != MAL_SUCCESS) { - continue; - } - - if (mal_does_AudioObject_support_playback(pContext, deviceObjectID)) { - if (!callback(pContext, mal_device_type_playback, &info, pUserData)) { - break; - } - } - if (mal_does_AudioObject_support_capture(pContext, deviceObjectID)) { - if (!callback(pContext, mal_device_type_capture, &info, pUserData)) { - break; - } - } - } - - mal_free(pDeviceObjectIDs); -#else - // Only supporting default devices on non-Desktop platforms. - mal_device_info info; - - mal_zero_object(&info); - mal_strncpy_s(info.name, sizeof(info.name), MAL_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); - if (!callback(pContext, mal_device_type_playback, &info, pUserData)) { - return MAL_SUCCESS; - } - - mal_zero_object(&info); - mal_strncpy_s(info.name, sizeof(info.name), MAL_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); - if (!callback(pContext, mal_device_type_capture, &info, pUserData)) { - return MAL_SUCCESS; - } -#endif - - return MAL_SUCCESS; -} - -mal_result mal_context_get_device_info__coreaudio(mal_context* pContext, mal_device_type deviceType, const mal_device_id* pDeviceID, mal_share_mode shareMode, mal_device_info* pDeviceInfo) -{ - mal_assert(pContext != NULL); - (void)shareMode; - (void)pDeviceInfo; - -#if defined(MAL_APPLE_DESKTOP) - // Desktop - // ======= - AudioObjectID deviceObjectID; - mal_result result = mal_find_AudioObjectID(pContext, deviceType, pDeviceID, &deviceObjectID); - if (result != MAL_SUCCESS) { - return result; - } - - result = mal_get_AudioObject_uid(pContext, deviceObjectID, sizeof(pDeviceInfo->id.coreaudio), pDeviceInfo->id.coreaudio); - if (result != MAL_SUCCESS) { - return result; - } - - result = mal_get_AudioObject_name(pContext, deviceObjectID, sizeof(pDeviceInfo->name), pDeviceInfo->name); - if (result != MAL_SUCCESS) { - return result; - } - - // Formats. - UInt32 streamDescriptionCount; - AudioStreamRangedDescription* pStreamDescriptions; - result = mal_get_AudioObject_stream_descriptions(pContext, deviceObjectID, deviceType, &streamDescriptionCount, &pStreamDescriptions); - if (result != MAL_SUCCESS) { - return result; - } - - for (UInt32 iStreamDescription = 0; iStreamDescription < streamDescriptionCount; ++iStreamDescription) { - mal_format format; - result = mal_format_from_AudioStreamBasicDescription(&pStreamDescriptions[iStreamDescription].mFormat, &format); - if (result != MAL_SUCCESS) { - continue; - } - - mal_assert(format != mal_format_unknown); - - // Make sure the format isn't already in the output list. - mal_bool32 exists = MAL_FALSE; - for (mal_uint32 iOutputFormat = 0; iOutputFormat < pDeviceInfo->formatCount; ++iOutputFormat) { - if (pDeviceInfo->formats[iOutputFormat] == format) { - exists = MAL_TRUE; - break; - } - } - - if (!exists) { - pDeviceInfo->formats[pDeviceInfo->formatCount++] = format; - } - } - - mal_free(pStreamDescriptions); - - - // Channels. - result = mal_get_AudioObject_channel_count(pContext, deviceObjectID, deviceType, &pDeviceInfo->minChannels); - if (result != MAL_SUCCESS) { - return result; - } - pDeviceInfo->maxChannels = pDeviceInfo->minChannels; - - - // Sample rates. - UInt32 sampleRateRangeCount; - AudioValueRange* pSampleRateRanges; - result = mal_get_AudioObject_sample_rates(pContext, deviceObjectID, deviceType, &sampleRateRangeCount, &pSampleRateRanges); - if (result != MAL_SUCCESS) { - return result; - } - - if (sampleRateRangeCount > 0) { - pDeviceInfo->minSampleRate = UINT32_MAX; - pDeviceInfo->maxSampleRate = 0; - for (UInt32 iSampleRate = 0; iSampleRate < sampleRateRangeCount; ++iSampleRate) { - if (pDeviceInfo->minSampleRate > pSampleRateRanges[iSampleRate].mMinimum) { - pDeviceInfo->minSampleRate = pSampleRateRanges[iSampleRate].mMinimum; - } - if (pDeviceInfo->maxSampleRate < pSampleRateRanges[iSampleRate].mMaximum) { - pDeviceInfo->maxSampleRate = pSampleRateRanges[iSampleRate].mMaximum; - } - } - } -#else - // Mobile - // ====== - if (deviceType == mal_device_type_playback) { - mal_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MAL_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); - } else { - mal_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MAL_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); - } - - // Retrieving device information is more annoying on mobile than desktop. For simplicity I'm locking this down to whatever format is - // reported on a temporary I/O unit. The problem, however, is that this doesn't return a value for the sample rate which we need to - // retrieve from the AVAudioSession shared instance. - AudioComponentDescription desc; - desc.componentType = kAudioUnitType_Output; - desc.componentSubType = kAudioUnitSubType_RemoteIO; - desc.componentManufacturer = kAudioUnitManufacturer_Apple; - desc.componentFlags = 0; - desc.componentFlagsMask = 0; - - AudioComponent component = ((mal_AudioComponentFindNext_proc)pContext->coreaudio.AudioComponentFindNext)(NULL, &desc); - if (component == NULL) { - return MAL_FAILED_TO_INIT_BACKEND; - } - - AudioUnit audioUnit; - OSStatus status = ((mal_AudioComponentInstanceNew_proc)pContext->coreaudio.AudioComponentInstanceNew)(component, &audioUnit); - if (status != noErr) { - return mal_result_from_OSStatus(status); - } - - AudioUnitScope formatScope = (deviceType == mal_device_type_playback) ? kAudioUnitScope_Input : kAudioUnitScope_Output; - AudioUnitElement formatElement = (deviceType == mal_device_type_playback) ? MAL_COREAUDIO_OUTPUT_BUS : MAL_COREAUDIO_INPUT_BUS; - - AudioStreamBasicDescription bestFormat; - UInt32 propSize = sizeof(bestFormat); - status = ((mal_AudioUnitGetProperty_proc)pContext->coreaudio.AudioUnitGetProperty)(audioUnit, kAudioUnitProperty_StreamFormat, formatScope, formatElement, &bestFormat, &propSize); - if (status != noErr) { - ((mal_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(audioUnit); - return mal_result_from_OSStatus(status); - } - - ((mal_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(audioUnit); - audioUnit = NULL; - - - pDeviceInfo->minChannels = bestFormat.mChannelsPerFrame; - pDeviceInfo->maxChannels = bestFormat.mChannelsPerFrame; - - pDeviceInfo->formatCount = 1; - mal_result result = mal_format_from_AudioStreamBasicDescription(&bestFormat, &pDeviceInfo->formats[0]); - if (result != MAL_SUCCESS) { - return result; - } - - // It looks like Apple are wanting to push the whole AVAudioSession thing. Thus, we need to use that to determine device settings. To do - // this we just get the shared instance and inspect. - @autoreleasepool { - AVAudioSession* pAudioSession = [AVAudioSession sharedInstance]; - mal_assert(pAudioSession != NULL); - - pDeviceInfo->minSampleRate = (mal_uint32)pAudioSession.sampleRate; - pDeviceInfo->maxSampleRate = pDeviceInfo->minSampleRate; - } -#endif - - return MAL_SUCCESS; -} - - -void mal_device_uninit__coreaudio(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - mal_assert(mal_device__get_state(pDevice) == MAL_STATE_UNINITIALIZED); - - ((mal_AudioComponentInstanceDispose_proc)pDevice->pContext->coreaudio.AudioComponentInstanceDispose)((AudioUnit)pDevice->coreaudio.audioUnit); - - if (pDevice->coreaudio.pAudioBufferList) { - mal_free(pDevice->coreaudio.pAudioBufferList); - } -} - - -OSStatus mal_on_output__coreaudio(void* pUserData, AudioUnitRenderActionFlags* pActionFlags, const AudioTimeStamp* pTimeStamp, UInt32 busNumber, UInt32 frameCount, AudioBufferList* pBufferList) -{ - (void)pActionFlags; - (void)pTimeStamp; - (void)busNumber; - - mal_device* pDevice = (mal_device*)pUserData; - mal_assert(pDevice != NULL); - -#if defined(MAL_DEBUG_OUTPUT) - printf("INFO: Output Callback: busNumber=%d, frameCount=%d, mNumberBuffers=%d\n", busNumber, frameCount, pBufferList->mNumberBuffers); -#endif - - // We need to check whether or not we are outputting interleaved or non-interleaved samples. The - // way we do this is slightly different for each type. - mal_stream_layout layout = mal_stream_layout_interleaved; - if (pBufferList->mBuffers[0].mNumberChannels != pDevice->internalChannels) { - layout = mal_stream_layout_deinterleaved; - } - - if (layout == mal_stream_layout_interleaved) { - // For now we can assume everything is interleaved. - for (UInt32 iBuffer = 0; iBuffer < pBufferList->mNumberBuffers; ++iBuffer) { - if (pBufferList->mBuffers[iBuffer].mNumberChannels == pDevice->internalChannels) { - mal_uint32 frameCountForThisBuffer = pBufferList->mBuffers[iBuffer].mDataByteSize / mal_get_bytes_per_frame(pDevice->internalFormat, pDevice->internalChannels); - if (frameCountForThisBuffer > 0) { - mal_device__read_frames_from_client(pDevice, frameCountForThisBuffer, pBufferList->mBuffers[iBuffer].mData); - } - - #if defined(MAL_DEBUG_OUTPUT) - printf(" frameCount=%d, mNumberChannels=%d, mDataByteSize=%d\n", frameCount, pBufferList->mBuffers[iBuffer].mNumberChannels, pBufferList->mBuffers[iBuffer].mDataByteSize); - #endif - } else { - // This case is where the number of channels in the output buffer do not match our internal channels. It could mean that it's - // not interleaved, in which case we can't handle right now since mini_al does not yet support non-interleaved streams. We just - // output silence here. - mal_zero_memory(pBufferList->mBuffers[iBuffer].mData, pBufferList->mBuffers[iBuffer].mDataByteSize); - - #if defined(MAL_DEBUG_OUTPUT) - printf(" WARNING: Outputting silence. frameCount=%d, mNumberChannels=%d, mDataByteSize=%d\n", frameCount, pBufferList->mBuffers[iBuffer].mNumberChannels, pBufferList->mBuffers[iBuffer].mDataByteSize); - #endif - } - } - } else { - // This is the deinterleaved case. We need to update each buffer in groups of internalChannels. This - // assumes each buffer is the same size. - mal_uint8 tempBuffer[4096]; - for (UInt32 iBuffer = 0; iBuffer < pBufferList->mNumberBuffers; iBuffer += pDevice->internalChannels) { - mal_uint32 frameCountPerBuffer = pBufferList->mBuffers[iBuffer].mDataByteSize / mal_get_bytes_per_sample(pDevice->internalFormat); - - mal_uint32 framesRemaining = frameCountPerBuffer; - while (framesRemaining > 0) { - mal_uint32 framesToRead = sizeof(tempBuffer) / mal_get_bytes_per_frame(pDevice->internalFormat, pDevice->internalChannels); - if (framesToRead > framesRemaining) { - framesToRead = framesRemaining; - } - - mal_device__read_frames_from_client(pDevice, framesToRead, tempBuffer); - - void* ppDeinterleavedBuffers[MAL_MAX_CHANNELS]; - for (mal_uint32 iChannel = 0; iChannel < pDevice->internalChannels; ++iChannel) { - ppDeinterleavedBuffers[iChannel] = (void*)mal_offset_ptr(pBufferList->mBuffers[iBuffer].mData, (frameCountPerBuffer - framesRemaining) * mal_get_bytes_per_sample(pDevice->internalFormat)); - } - - mal_deinterleave_pcm_frames(pDevice->internalFormat, pDevice->internalChannels, framesToRead, tempBuffer, ppDeinterleavedBuffers); - - framesRemaining -= framesToRead; - } - } - } - - return noErr; -} - -OSStatus mal_on_input__coreaudio(void* pUserData, AudioUnitRenderActionFlags* pActionFlags, const AudioTimeStamp* pTimeStamp, UInt32 busNumber, UInt32 frameCount, AudioBufferList* pUnusedBufferList) -{ - (void)pActionFlags; - (void)pTimeStamp; - (void)busNumber; - (void)frameCount; - (void)pUnusedBufferList; - - mal_device* pDevice = (mal_device*)pUserData; - mal_assert(pDevice != NULL); - - AudioBufferList* pRenderedBufferList = (AudioBufferList*)pDevice->coreaudio.pAudioBufferList; - mal_assert(pRenderedBufferList); - - // We need to check whether or not we are outputting interleaved or non-interleaved samples. The - // way we do this is slightly different for each type. - mal_stream_layout layout = mal_stream_layout_interleaved; - if (pRenderedBufferList->mBuffers[0].mNumberChannels != pDevice->internalChannels) { - layout = mal_stream_layout_deinterleaved; - } - -#if defined(MAL_DEBUG_OUTPUT) - printf("INFO: Input Callback: busNumber=%d, frameCount=%d, mNumberBuffers=%d\n", busNumber, frameCount, pRenderedBufferList->mNumberBuffers); -#endif - - OSStatus status = ((mal_AudioUnitRender_proc)pDevice->pContext->coreaudio.AudioUnitRender)((AudioUnit)pDevice->coreaudio.audioUnit, pActionFlags, pTimeStamp, busNumber, frameCount, pRenderedBufferList); - if (status != noErr) { - #if defined(MAL_DEBUG_OUTPUT) - printf(" ERROR: AudioUnitRender() failed with %d\n", status); - #endif - return status; - } - - if (layout == mal_stream_layout_interleaved) { - for (UInt32 iBuffer = 0; iBuffer < pRenderedBufferList->mNumberBuffers; ++iBuffer) { - if (pRenderedBufferList->mBuffers[iBuffer].mNumberChannels == pDevice->internalChannels) { - mal_device__send_frames_to_client(pDevice, frameCount, pRenderedBufferList->mBuffers[iBuffer].mData); - #if defined(MAL_DEBUG_OUTPUT) - printf(" mDataByteSize=%d\n", pRenderedBufferList->mBuffers[iBuffer].mDataByteSize); - #endif - } else { - // This case is where the number of channels in the output buffer do not match our internal channels. It could mean that it's - // not interleaved, in which case we can't handle right now since mini_al does not yet support non-interleaved streams. - - mal_uint8 silentBuffer[4096]; - mal_zero_memory(silentBuffer, sizeof(silentBuffer)); - - mal_uint32 framesRemaining = frameCount; - while (framesRemaining > 0) { - mal_uint32 framesToSend = sizeof(silentBuffer) / mal_get_bytes_per_frame(pDevice->internalFormat, pDevice->internalChannels); - if (framesToSend > framesRemaining) { - framesToSend = framesRemaining; - } - - mal_device__send_frames_to_client(pDevice, framesToSend, silentBuffer); - framesRemaining -= framesToSend; - } - - #if defined(MAL_DEBUG_OUTPUT) - printf(" WARNING: Outputting silence. frameCount=%d, mNumberChannels=%d, mDataByteSize=%d\n", frameCount, pRenderedBufferList->mBuffers[iBuffer].mNumberChannels, pRenderedBufferList->mBuffers[iBuffer].mDataByteSize); - #endif - } - } - } else { - // This is the deinterleaved case. We need to interleave the audio data before sending it to the client. This - // assumes each buffer is the same size. - mal_uint8 tempBuffer[4096]; - for (UInt32 iBuffer = 0; iBuffer < pRenderedBufferList->mNumberBuffers; iBuffer += pDevice->internalChannels) { - mal_uint32 framesRemaining = frameCount; - while (framesRemaining > 0) { - mal_uint32 framesToSend = sizeof(tempBuffer) / mal_get_bytes_per_sample(pDevice->internalFormat); - if (framesToSend > framesRemaining) { - framesToSend = framesRemaining; - } - - void* ppDeinterleavedBuffers[MAL_MAX_CHANNELS]; - for (mal_uint32 iChannel = 0; iChannel < pDevice->internalChannels; ++iChannel) { - ppDeinterleavedBuffers[iChannel] = (void*)mal_offset_ptr(pRenderedBufferList->mBuffers[iBuffer].mData, (frameCount - framesRemaining) * mal_get_bytes_per_sample(pDevice->internalFormat)); - } - - mal_interleave_pcm_frames(pDevice->internalFormat, pDevice->internalChannels, framesToSend, (const void**)ppDeinterleavedBuffers, tempBuffer); - mal_device__send_frames_to_client(pDevice, framesToSend, tempBuffer); - - framesRemaining -= framesToSend; - } - } - } - - return noErr; -} - -void on_start_stop__coreaudio(void* pUserData, AudioUnit audioUnit, AudioUnitPropertyID propertyID, AudioUnitScope scope, AudioUnitElement element) -{ - (void)propertyID; - - mal_device* pDevice = (mal_device*)pUserData; - mal_assert(pDevice != NULL); - - // There's been a report of a deadlock here when triggered by mal_device_uninit(). It looks like - // AudioUnitGetProprty (called below) and AudioComponentInstanceDispose (called in mal_device_uninit) - // can try waiting on the same lock. I'm going to try working around this by not calling any Core - // Audio APIs in the callback when the device has been stopped or uninitialized. - if (mal_device__get_state(pDevice) == MAL_STATE_UNINITIALIZED || mal_device__get_state(pDevice) == MAL_STATE_STOPPING) { - mal_stop_proc onStop = pDevice->onStop; - if (onStop) { - onStop(pDevice); - } - - mal_event_signal(&pDevice->coreaudio.stopEvent); - } else { - UInt32 isRunning; - UInt32 isRunningSize = sizeof(isRunning); - OSStatus status = ((mal_AudioUnitGetProperty_proc)pDevice->pContext->coreaudio.AudioUnitGetProperty)(audioUnit, kAudioOutputUnitProperty_IsRunning, scope, element, &isRunning, &isRunningSize); - if (status != noErr) { - return; // Don't really know what to do in this case... just ignore it, I suppose... - } - - if (!isRunning) { - // The stop event is a bit annoying in Core Audio because it will be called when we automatically switch the default device. Some scenarios to consider: - // - // 1) When the device is unplugged, this will be called _before_ the default device change notification. - // 2) When the device is changed via the default device change notification, this will be called _after_ the switch. - // - // For case #1, we just check if there's a new default device available. If so, we just ignore the stop event. For case #2 we check a flag. - if (pDevice->isDefaultDevice && mal_device__get_state(pDevice) != MAL_STATE_STOPPING && mal_device__get_state(pDevice) != MAL_STATE_STOPPED) { - // It looks like the device is switching through an external event, such as the user unplugging the device or changing the default device - // via the operating system's sound settings. If we're re-initializing the device, we just terminate because we want the stopping of the - // device to be seamless to the client (we don't want them receiving the onStop event and thinking that the device has stopped when it - // hasn't!). - if (pDevice->coreaudio.isSwitchingDevice) { - return; - } - - // Getting here means the device is not reinitializing which means it may have been unplugged. From what I can see, it looks like Core Audio - // will try switching to the new default device seamlessly. We need to somehow find a way to determine whether or not Core Audio will most - // likely be successful in switching to the new device. - // - // TODO: Try to predict if Core Audio will switch devices. If not, the onStop callback needs to be posted. - return; - } - - // Getting here means we need to stop the device. - mal_stop_proc onStop = pDevice->onStop; - if (onStop) { - onStop(pDevice); - } - } - } -} - -#if defined(MAL_APPLE_DESKTOP) -OSStatus mal_default_output_device_changed__coreaudio(AudioObjectID objectID, UInt32 addressCount, const AudioObjectPropertyAddress* pAddresses, void* pUserData) -{ - (void)objectID; - - mal_device* pDevice = (mal_device*)pUserData; - mal_assert(pDevice != NULL); - - if (pDevice->isDefaultDevice) { - // Not sure if I really need to check this, but it makes me feel better. - if (addressCount == 0) { - return noErr; - } - - if ((pDevice->type == mal_device_type_playback && pAddresses[0].mSelector == kAudioHardwarePropertyDefaultOutputDevice) || - (pDevice->type == mal_device_type_capture && pAddresses[0].mSelector == kAudioHardwarePropertyDefaultInputDevice)) { -#ifdef MAL_DEBUG_OUTPUT - printf("Device Changed: addressCount=%d, pAddresses[0].mElement=%d\n", addressCount, pAddresses[0].mElement); -#endif - pDevice->coreaudio.isSwitchingDevice = MAL_TRUE; - mal_result reinitResult = mal_device_reinit_internal__coreaudio(pDevice, MAL_TRUE); - pDevice->coreaudio.isSwitchingDevice = MAL_FALSE; - - if (reinitResult == MAL_SUCCESS) { - mal_device__post_init_setup(pDevice); - - // Make sure we resume the device if applicable. - if (mal_device__get_state(pDevice) == MAL_STATE_STARTED) { - mal_result startResult = pDevice->pContext->onDeviceStart(pDevice); - if (startResult != MAL_SUCCESS) { - mal_device__set_state(pDevice, MAL_STATE_STOPPED); - } - } - } - } - } - - return noErr; -} -#endif - -typedef struct -{ - // Input. - mal_format formatIn; - mal_uint32 channelsIn; - mal_uint32 sampleRateIn; - mal_channel channelMapIn[MAL_MAX_CHANNELS]; - mal_uint32 bufferSizeInFramesIn; - mal_uint32 bufferSizeInMillisecondsIn; - mal_uint32 periodsIn; - mal_bool32 usingDefaultFormat; - mal_bool32 usingDefaultChannels; - mal_bool32 usingDefaultSampleRate; - mal_bool32 usingDefaultChannelMap; - mal_share_mode shareMode; - - // Output. -#if defined(MAL_APPLE_DESKTOP) - AudioObjectID deviceObjectID; -#endif - AudioComponent component; - AudioUnit audioUnit; - AudioBufferList* pAudioBufferList; // Only used for input devices. - mal_format formatOut; - mal_uint32 channelsOut; - mal_uint32 sampleRateOut; - mal_channel channelMapOut[MAL_MAX_CHANNELS]; - mal_uint32 bufferSizeInFramesOut; - mal_uint32 periodsOut; - mal_bool32 exclusiveMode; - char deviceName[256]; -} mal_device_init_internal_data__coreaudio; - -mal_result mal_device_init_internal__coreaudio(mal_context* pContext, mal_device_type deviceType, const mal_device_id* pDeviceID, mal_device_init_internal_data__coreaudio* pData, void* pDevice_DoNotReference) /* <-- pDevice is typed as void* intentionally so as to avoid accidentally referencing it. */ -{ - mal_assert(pContext != NULL); - mal_assert(deviceType == mal_device_type_playback || deviceType == mal_device_type_capture); - -#if defined(MAL_APPLE_DESKTOP) - pData->deviceObjectID = 0; -#endif - pData->component = NULL; - pData->audioUnit = NULL; - pData->pAudioBufferList = NULL; - - mal_result result; - -#if defined(MAL_APPLE_DESKTOP) - AudioObjectID deviceObjectID; - result = mal_find_AudioObjectID(pContext, deviceType, pDeviceID, &deviceObjectID); - if (result != MAL_SUCCESS) { - return result; - } - - pData->deviceObjectID = deviceObjectID; -#endif - - // Core audio doesn't really use the notion of a period so we can leave this unmodified, but not too over the top. - pData->periodsOut = pData->periodsIn; - if (pData->periodsOut < 1) { - pData->periodsOut = 1; - } - if (pData->periodsOut > 16) { - pData->periodsOut = 16; - } - - - // Audio component. - AudioComponentDescription desc; - desc.componentType = kAudioUnitType_Output; -#if defined(MAL_APPLE_DESKTOP) - desc.componentSubType = kAudioUnitSubType_HALOutput; -#else - desc.componentSubType = kAudioUnitSubType_RemoteIO; -#endif - desc.componentManufacturer = kAudioUnitManufacturer_Apple; - desc.componentFlags = 0; - desc.componentFlagsMask = 0; - - pData->component = ((mal_AudioComponentFindNext_proc)pContext->coreaudio.AudioComponentFindNext)(NULL, &desc); - if (pData->component == NULL) { - return MAL_FAILED_TO_INIT_BACKEND; - } - - - // Audio unit. - OSStatus status = ((mal_AudioComponentInstanceNew_proc)pContext->coreaudio.AudioComponentInstanceNew)(pData->component, (AudioUnit*)&pData->audioUnit); - if (status != noErr) { - return mal_result_from_OSStatus(status); - } - - - // The input/output buses need to be explicitly enabled and disabled. We set the flag based on the output unit first, then we just swap it for input. - UInt32 enableIOFlag = 1; - if (deviceType == mal_device_type_capture) { - enableIOFlag = 0; - } - - status = ((mal_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, MAL_COREAUDIO_OUTPUT_BUS, &enableIOFlag, sizeof(enableIOFlag)); - if (status != noErr) { - ((mal_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit); - return mal_result_from_OSStatus(status); - } - - enableIOFlag = (enableIOFlag == 0) ? 1 : 0; - status = ((mal_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, MAL_COREAUDIO_INPUT_BUS, &enableIOFlag, sizeof(enableIOFlag)); - if (status != noErr) { - ((mal_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit); - return mal_result_from_OSStatus(status); - } - - - // Set the device to use with this audio unit. This is only used on desktop since we are using defaults on mobile. -#if defined(MAL_APPLE_DESKTOP) - status = ((mal_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, (deviceType == mal_device_type_playback) ? MAL_COREAUDIO_OUTPUT_BUS : MAL_COREAUDIO_INPUT_BUS, &deviceObjectID, sizeof(AudioDeviceID)); - if (status != noErr) { - ((mal_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit); - return mal_result_from_OSStatus(result); - } -#endif - - // Format. This is the hardest part of initialization because there's a few variables to take into account. - // 1) The format must be supported by the device. - // 2) The format must be supported mini_al. - // 3) There's a priority that mini_al prefers. - // - // Ideally we would like to use a format that's as close to the hardware as possible so we can get as close to a passthrough as possible. The - // most important property is the sample rate. mini_al can do format conversion for any sample rate and channel count, but cannot do the same - // for the sample data format. If the sample data format is not supported by mini_al it must be ignored completely. - // - // On mobile platforms this is a bit different. We just force the use of whatever the audio unit's current format is set to. - AudioStreamBasicDescription bestFormat; - { - AudioUnitScope formatScope = (deviceType == mal_device_type_playback) ? kAudioUnitScope_Input : kAudioUnitScope_Output; - AudioUnitElement formatElement = (deviceType == mal_device_type_playback) ? MAL_COREAUDIO_OUTPUT_BUS : MAL_COREAUDIO_INPUT_BUS; - - #if defined(MAL_APPLE_DESKTOP) - result = mal_find_best_format__coreaudio(pContext, deviceObjectID, deviceType, pData->formatIn, pData->channelsIn, pData->sampleRateIn, pData->usingDefaultFormat, pData->usingDefaultChannels, pData->usingDefaultSampleRate, &bestFormat); - if (result != MAL_SUCCESS) { - ((mal_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit); - return result; - } - - // From what I can see, Apple's documentation implies that we should keep the sample rate consistent. - AudioStreamBasicDescription origFormat; - UInt32 origFormatSize = sizeof(origFormat); - if (deviceType == mal_device_type_playback) { - status = ((mal_AudioUnitGetProperty_proc)pContext->coreaudio.AudioUnitGetProperty)(pData->audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, MAL_COREAUDIO_OUTPUT_BUS, &origFormat, &origFormatSize); - } else { - status = ((mal_AudioUnitGetProperty_proc)pContext->coreaudio.AudioUnitGetProperty)(pData->audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, MAL_COREAUDIO_INPUT_BUS, &origFormat, &origFormatSize); - } - - if (status != noErr) { - ((mal_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit); - return result; - } - - bestFormat.mSampleRate = origFormat.mSampleRate; - - status = ((mal_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioUnitProperty_StreamFormat, formatScope, formatElement, &bestFormat, sizeof(bestFormat)); - if (status != noErr) { - // We failed to set the format, so fall back to the current format of the audio unit. - bestFormat = origFormat; - } - #else - UInt32 propSize = sizeof(bestFormat); - status = ((mal_AudioUnitGetProperty_proc)pContext->coreaudio.AudioUnitGetProperty)(pData->audioUnit, kAudioUnitProperty_StreamFormat, formatScope, formatElement, &bestFormat, &propSize); - if (status != noErr) { - ((mal_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit); - return mal_result_from_OSStatus(status); - } - - // Sample rate is a little different here because for some reason kAudioUnitProperty_StreamFormat returns 0... Oh well. We need to instead try - // setting the sample rate to what the user has requested and then just see the results of it. Need to use some Objective-C here for this since - // it depends on Apple's AVAudioSession API. To do this we just get the shared AVAudioSession instance and then set it. Note that from what I - // can tell, it looks like the sample rate is shared between playback and capture for everything. - @autoreleasepool { - AVAudioSession* pAudioSession = [AVAudioSession sharedInstance]; - mal_assert(pAudioSession != NULL); - - [pAudioSession setPreferredSampleRate:(double)pData->sampleRateIn error:nil]; - bestFormat.mSampleRate = pAudioSession.sampleRate; - } - - status = ((mal_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioUnitProperty_StreamFormat, formatScope, formatElement, &bestFormat, sizeof(bestFormat)); - if (status != noErr) { - ((mal_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit); - return mal_result_from_OSStatus(status); - } - #endif - - result = mal_format_from_AudioStreamBasicDescription(&bestFormat, &pData->formatOut); - if (result != MAL_SUCCESS) { - ((mal_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit); - return result; - } - - if (pData->formatOut == mal_format_unknown) { - ((mal_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit); - return MAL_FORMAT_NOT_SUPPORTED; - } - - pData->channelsOut = bestFormat.mChannelsPerFrame; - pData->sampleRateOut = bestFormat.mSampleRate; - } - - - // Internal channel map. This is weird in my testing. If I use the AudioObject to get the - // channel map, the channel descriptions are set to "Unknown" for some reason. To work around - // this it looks like retrieving it from the AudioUnit will work. However, and this is where - // it gets weird, it doesn't seem to work with capture devices, nor at all on iOS... Therefore - // I'm going to fall back to a default assumption in these cases. -#if defined(MAL_APPLE_DESKTOP) - result = mal_get_AudioUnit_channel_map(pContext, pData->audioUnit, deviceType, pData->channelMapOut); - if (result != MAL_SUCCESS) { - #if 0 - // Try falling back to the channel map from the AudioObject. - result = mal_get_AudioObject_channel_map(pContext, deviceObjectID, deviceType, pData->channelMapOut); - if (result != MAL_SUCCESS) { - return result; - } - #else - // Fall back to default assumptions. - mal_get_standard_channel_map(mal_standard_channel_map_default, pData->channelsOut, pData->channelMapOut); - #endif - } -#else - // TODO: Figure out how to get the channel map using AVAudioSession. - mal_get_standard_channel_map(mal_standard_channel_map_default, pData->channelsOut, pData->channelMapOut); -#endif - - - // Buffer size. Not allowing this to be configurable on iOS. - mal_uint32 actualBufferSizeInFrames = pData->bufferSizeInFramesIn; - -#if defined(MAL_APPLE_DESKTOP) - if (actualBufferSizeInFrames == 0) { - actualBufferSizeInFrames = mal_calculate_buffer_size_in_frames_from_milliseconds(pData->bufferSizeInMillisecondsIn, pData->sampleRateOut); - } - - actualBufferSizeInFrames = actualBufferSizeInFrames / pData->periodsOut; - result = mal_set_AudioObject_buffer_size_in_frames(pContext, deviceObjectID, deviceType, &actualBufferSizeInFrames); - if (result != MAL_SUCCESS) { - return result; - } - - pData->bufferSizeInFramesOut = actualBufferSizeInFrames * pData->periodsOut; -#else - actualBufferSizeInFrames = 4096; - pData->bufferSizeInFramesOut = actualBufferSizeInFrames; -#endif - - - - // During testing I discovered that the buffer size can be too big. You'll get an error like this: - // - // kAudioUnitErr_TooManyFramesToProcess : inFramesToProcess=4096, mMaxFramesPerSlice=512 - // - // Note how inFramesToProcess is smaller than mMaxFramesPerSlice. To fix, we need to set kAudioUnitProperty_MaximumFramesPerSlice to that - // of the size of our buffer, or do it the other way around and set our buffer size to the kAudioUnitProperty_MaximumFramesPerSlice. - { - /*AudioUnitScope propScope = (deviceType == mal_device_type_playback) ? kAudioUnitScope_Input : kAudioUnitScope_Output; - AudioUnitElement propBus = (deviceType == mal_device_type_playback) ? MAL_COREAUDIO_OUTPUT_BUS : MAL_COREAUDIO_INPUT_BUS; - - status = ((mal_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioUnitProperty_MaximumFramesPerSlice, propScope, propBus, &actualBufferSizeInFrames, sizeof(actualBufferSizeInFrames)); - if (status != noErr) { - ((mal_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit); - return mal_result_from_OSStatus(status); - }*/ - - status = ((mal_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 0, &actualBufferSizeInFrames, sizeof(actualBufferSizeInFrames)); - if (status != noErr) { - ((mal_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit); - return mal_result_from_OSStatus(status); - } - } - - // We need a buffer list if this is an input device. We render into this in the input callback. - if (deviceType == mal_device_type_capture) { - mal_bool32 isInterleaved = (bestFormat.mFormatFlags & kAudioFormatFlagIsNonInterleaved) == 0; - - size_t allocationSize = sizeof(AudioBufferList) - sizeof(AudioBuffer); // Subtract sizeof(AudioBuffer) because that part is dynamically sized. - if (isInterleaved) { - // Interleaved case. This is the simple case because we just have one buffer. - allocationSize += sizeof(AudioBuffer) * 1; - allocationSize += actualBufferSizeInFrames * mal_get_bytes_per_frame(pData->formatOut, pData->channelsOut); - } else { - // Non-interleaved case. This is the more complex case because there's more than one buffer. - allocationSize += sizeof(AudioBuffer) * pData->channelsOut; - allocationSize += actualBufferSizeInFrames * mal_get_bytes_per_sample(pData->formatOut) * pData->channelsOut; - } - - AudioBufferList* pBufferList = (AudioBufferList*)mal_malloc(allocationSize); - if (pBufferList == NULL) { - ((mal_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit); - return MAL_OUT_OF_MEMORY; - } - - if (isInterleaved) { - pBufferList->mNumberBuffers = 1; - pBufferList->mBuffers[0].mNumberChannels = pData->channelsOut; - pBufferList->mBuffers[0].mDataByteSize = actualBufferSizeInFrames * mal_get_bytes_per_frame(pData->formatOut, pData->channelsOut); - pBufferList->mBuffers[0].mData = (mal_uint8*)pBufferList + sizeof(AudioBufferList); - } else { - pBufferList->mNumberBuffers = pData->channelsOut; - for (mal_uint32 iBuffer = 0; iBuffer < pBufferList->mNumberBuffers; ++iBuffer) { - pBufferList->mBuffers[iBuffer].mNumberChannels = 1; - pBufferList->mBuffers[iBuffer].mDataByteSize = actualBufferSizeInFrames * mal_get_bytes_per_sample(pData->formatOut); - pBufferList->mBuffers[iBuffer].mData = (mal_uint8*)pBufferList + ((sizeof(AudioBufferList) - sizeof(AudioBuffer)) + (sizeof(AudioBuffer) * pData->channelsOut)) + (actualBufferSizeInFrames * mal_get_bytes_per_sample(pData->formatOut) * iBuffer); - } - } - - pData->pAudioBufferList = pBufferList; - } - - // Callbacks. - AURenderCallbackStruct callbackInfo; - callbackInfo.inputProcRefCon = pDevice_DoNotReference; - if (deviceType == mal_device_type_playback) { - callbackInfo.inputProc = mal_on_output__coreaudio; - status = ((mal_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Global, MAL_COREAUDIO_OUTPUT_BUS, &callbackInfo, sizeof(callbackInfo)); - if (status != noErr) { - ((mal_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit); - return mal_result_from_OSStatus(status); - } - } else { - callbackInfo.inputProc = mal_on_input__coreaudio; - status = ((mal_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Global, MAL_COREAUDIO_INPUT_BUS, &callbackInfo, sizeof(callbackInfo)); - if (status != noErr) { - ((mal_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit); - return mal_result_from_OSStatus(status); - } - } - - // We need to listen for stop events. - status = ((mal_AudioUnitAddPropertyListener_proc)pContext->coreaudio.AudioUnitAddPropertyListener)(pData->audioUnit, kAudioOutputUnitProperty_IsRunning, on_start_stop__coreaudio, pDevice_DoNotReference); - if (status != noErr) { - ((mal_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit); - return mal_result_from_OSStatus(status); - } - - // Initialize the audio unit. - status = ((mal_AudioUnitInitialize_proc)pContext->coreaudio.AudioUnitInitialize)(pData->audioUnit); - if (status != noErr) { - mal_free(pData->pAudioBufferList); - pData->pAudioBufferList = NULL; - ((mal_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit); - return mal_result_from_OSStatus(status); - } - - // Grab the name. -#if defined(MAL_APPLE_DESKTOP) - mal_get_AudioObject_name(pContext, deviceObjectID, sizeof(pData->deviceName), pData->deviceName); -#else - if (deviceType == mal_device_type_playback) { - mal_strcpy_s(pData->deviceName, sizeof(pData->deviceName), MAL_DEFAULT_PLAYBACK_DEVICE_NAME); - } else { - mal_strcpy_s(pData->deviceName, sizeof(pData->deviceName), MAL_DEFAULT_CAPTURE_DEVICE_NAME); - } -#endif - - return result; -} - -mal_result mal_device_reinit_internal__coreaudio(mal_device* pDevice, mal_bool32 disposePreviousAudioUnit) -{ - mal_device_init_internal_data__coreaudio data; - data.formatIn = pDevice->format; - data.channelsIn = pDevice->channels; - data.sampleRateIn = pDevice->sampleRate; - mal_copy_memory(data.channelMapIn, pDevice->channelMap, sizeof(pDevice->channelMap)); - data.bufferSizeInFramesIn = pDevice->bufferSizeInFrames; - data.bufferSizeInMillisecondsIn = pDevice->bufferSizeInMilliseconds; - data.periodsIn = pDevice->periods; - data.usingDefaultFormat = pDevice->usingDefaultFormat; - data.usingDefaultChannels = pDevice->usingDefaultChannels; - data.usingDefaultSampleRate = pDevice->usingDefaultSampleRate; - data.usingDefaultChannelMap = pDevice->usingDefaultChannelMap; - data.shareMode = pDevice->initConfig.shareMode; - - mal_result result = mal_device_init_internal__coreaudio(pDevice->pContext, pDevice->type, NULL, &data, (void*)pDevice); - if (result != MAL_SUCCESS) { - return result; - } - - // We have successfully initialized the new objects. We now need to uninitialize the previous objects and re-set them. - if (disposePreviousAudioUnit) { - pDevice->pContext->onDeviceStop(pDevice); - ((mal_AudioComponentInstanceDispose_proc)pDevice->pContext->coreaudio.AudioComponentInstanceDispose)((AudioUnit)pDevice->coreaudio.audioUnit); - } - if (pDevice->coreaudio.pAudioBufferList) { - mal_free(pDevice->coreaudio.pAudioBufferList); - } - -#if defined(MAL_APPLE_DESKTOP) - pDevice->coreaudio.deviceObjectID = (mal_uint32)data.deviceObjectID; -#endif - pDevice->coreaudio.component = (mal_ptr)data.component; - pDevice->coreaudio.audioUnit = (mal_ptr)data.audioUnit; - pDevice->coreaudio.pAudioBufferList = (mal_ptr)data.pAudioBufferList; - - pDevice->internalFormat = data.formatOut; - pDevice->internalChannels = data.channelsOut; - pDevice->internalSampleRate = data.sampleRateOut; - mal_copy_memory(pDevice->internalChannelMap, data.channelMapOut, sizeof(data.channelMapOut)); - pDevice->bufferSizeInFrames = data.bufferSizeInFramesOut; - pDevice->periods = data.periodsOut; - pDevice->exclusiveMode = MAL_FALSE; - mal_strcpy_s(pDevice->name, sizeof(pDevice->name), data.deviceName); - - return MAL_SUCCESS; -} - - -mal_result mal_device_init__coreaudio(mal_context* pContext, mal_device_type deviceType, const mal_device_id* pDeviceID, const mal_device_config* pConfig, mal_device* pDevice) -{ - (void)pConfig; - - mal_assert(pContext != NULL); - mal_assert(pConfig != NULL); - mal_assert(pDevice != NULL); - mal_assert(deviceType == mal_device_type_playback || deviceType == mal_device_type_capture); - - mal_device_init_internal_data__coreaudio data; - data.formatIn = pDevice->format; - data.channelsIn = pDevice->channels; - data.sampleRateIn = pDevice->sampleRate; - mal_copy_memory(data.channelMapIn, pDevice->channelMap, sizeof(pDevice->channelMap)); - data.bufferSizeInFramesIn = pDevice->bufferSizeInFrames; - data.bufferSizeInMillisecondsIn = pDevice->bufferSizeInMilliseconds; - data.periodsIn = pDevice->periods; - data.usingDefaultFormat = pDevice->usingDefaultFormat; - data.usingDefaultChannels = pDevice->usingDefaultChannels; - data.usingDefaultSampleRate = pDevice->usingDefaultSampleRate; - data.usingDefaultChannelMap = pDevice->usingDefaultChannelMap; - data.shareMode = pDevice->initConfig.shareMode; - - mal_result result = mal_device_init_internal__coreaudio(pDevice->pContext, pDevice->type, pDeviceID, &data, (void*)pDevice); - if (result != MAL_SUCCESS) { - return result; - } - - // We have successfully initialized the new objects. We now need to uninitialize the previous objects and re-set them. - pDevice->pContext->onDeviceStop(pDevice); - ((mal_AudioComponentInstanceDispose_proc)pDevice->pContext->coreaudio.AudioComponentInstanceDispose)((AudioUnit)pDevice->coreaudio.audioUnit); - if (pDevice->coreaudio.pAudioBufferList) { - mal_free(pDevice->coreaudio.pAudioBufferList); - } - -#if defined(MAL_APPLE_DESKTOP) - pDevice->coreaudio.deviceObjectID = (mal_uint32)data.deviceObjectID; -#endif - pDevice->coreaudio.component = (mal_ptr)data.component; - pDevice->coreaudio.audioUnit = (mal_ptr)data.audioUnit; - pDevice->coreaudio.pAudioBufferList = (mal_ptr)data.pAudioBufferList; - - pDevice->internalFormat = data.formatOut; - pDevice->internalChannels = data.channelsOut; - pDevice->internalSampleRate = data.sampleRateOut; - mal_copy_memory(pDevice->internalChannelMap, data.channelMapOut, sizeof(data.channelMapOut)); - pDevice->bufferSizeInFrames = data.bufferSizeInFramesOut; - pDevice->periods = data.periodsOut; - pDevice->exclusiveMode = MAL_FALSE; - mal_strcpy_s(pDevice->name, sizeof(pDevice->name), data.deviceName); - -#if defined(MAL_APPLE_DESKTOP) - // If we are using the default device we'll need to listen for changes to the system's default device so we can seemlessly - // switch the device in the background. - AudioObjectPropertyAddress propAddress; - propAddress.mSelector = (deviceType == mal_device_type_playback) ? kAudioHardwarePropertyDefaultOutputDevice : kAudioHardwarePropertyDefaultInputDevice; - propAddress.mScope = kAudioObjectPropertyScopeGlobal; - propAddress.mElement = kAudioObjectPropertyElementMaster; - ((mal_AudioObjectAddPropertyListener_proc)pDevice->pContext->coreaudio.AudioObjectAddPropertyListener)(kAudioObjectSystemObject, &propAddress, &mal_default_output_device_changed__coreaudio, pDevice); -#endif - - /* - When stopping the device, a callback is called on another thread. We need to wait for this callback - before returning from mal_device_stop(). This event is used for this. - */ - mal_event_init(pContext, &pDevice->coreaudio.stopEvent); - - return MAL_SUCCESS; -} - - -mal_result mal_device_start__coreaudio(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - OSStatus status = ((mal_AudioOutputUnitStart_proc)pDevice->pContext->coreaudio.AudioOutputUnitStart)((AudioUnit)pDevice->coreaudio.audioUnit); - if (status != noErr) { - return mal_result_from_OSStatus(status); - } - - return MAL_SUCCESS; -} - -mal_result mal_device_stop__coreaudio(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - OSStatus status = ((mal_AudioOutputUnitStop_proc)pDevice->pContext->coreaudio.AudioOutputUnitStop)((AudioUnit)pDevice->coreaudio.audioUnit); - if (status != noErr) { - return mal_result_from_OSStatus(status); - } - - /* We need to wait for the callback to finish before returning. */ - mal_event_wait(&pDevice->coreaudio.stopEvent); - return MAL_SUCCESS; -} - - -mal_result mal_context_uninit__coreaudio(mal_context* pContext) -{ - mal_assert(pContext != NULL); - mal_assert(pContext->backend == mal_backend_coreaudio); - -#if !defined(MAL_NO_RUNTIME_LINKING) && !defined(MAL_APPLE_MOBILE) - mal_dlclose(pContext->coreaudio.hAudioUnit); - mal_dlclose(pContext->coreaudio.hCoreAudio); - mal_dlclose(pContext->coreaudio.hCoreFoundation); -#endif - - (void)pContext; - return MAL_SUCCESS; -} - -mal_result mal_context_init__coreaudio(mal_context* pContext) -{ - mal_assert(pContext != NULL); - -#if defined(MAL_APPLE_MOBILE) - @autoreleasepool { - AVAudioSession* pAudioSession = [AVAudioSession sharedInstance]; - mal_assert(pAudioSession != NULL); - - [pAudioSession setCategory: AVAudioSessionCategoryPlayAndRecord error:nil]; - - // By default we want mini_al to use the speakers instead of the receiver. In the future this may - // be customizable. - mal_bool32 useSpeakers = MAL_TRUE; - if (useSpeakers) { - [pAudioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil]; - } - } -#endif - -#if !defined(MAL_NO_RUNTIME_LINKING) && !defined(MAL_APPLE_MOBILE) - pContext->coreaudio.hCoreFoundation = mal_dlopen("CoreFoundation.framework/CoreFoundation"); - if (pContext->coreaudio.hCoreFoundation == NULL) { - return MAL_API_NOT_FOUND; - } - - pContext->coreaudio.CFStringGetCString = mal_dlsym(pContext->coreaudio.hCoreFoundation, "CFStringGetCString"); - - - pContext->coreaudio.hCoreAudio = mal_dlopen("CoreAudio.framework/CoreAudio"); - if (pContext->coreaudio.hCoreAudio == NULL) { - mal_dlclose(pContext->coreaudio.hCoreFoundation); - return MAL_API_NOT_FOUND; - } - - pContext->coreaudio.AudioObjectGetPropertyData = mal_dlsym(pContext->coreaudio.hCoreAudio, "AudioObjectGetPropertyData"); - pContext->coreaudio.AudioObjectGetPropertyDataSize = mal_dlsym(pContext->coreaudio.hCoreAudio, "AudioObjectGetPropertyDataSize"); - pContext->coreaudio.AudioObjectSetPropertyData = mal_dlsym(pContext->coreaudio.hCoreAudio, "AudioObjectSetPropertyData"); - pContext->coreaudio.AudioObjectAddPropertyListener = mal_dlsym(pContext->coreaudio.hCoreAudio, "AudioObjectAddPropertyListener"); - - - // It looks like Apple has moved some APIs from AudioUnit into AudioToolbox on more recent versions of macOS. They are still - // defined in AudioUnit, but just in case they decide to remove them from there entirely I'm going to implement a fallback. - // The way it'll work is that it'll first try AudioUnit, and if the required symbols are not present there we'll fall back to - // AudioToolbox. - pContext->coreaudio.hAudioUnit = mal_dlopen("AudioUnit.framework/AudioUnit"); - if (pContext->coreaudio.hAudioUnit == NULL) { - mal_dlclose(pContext->coreaudio.hCoreAudio); - mal_dlclose(pContext->coreaudio.hCoreFoundation); - return MAL_API_NOT_FOUND; - } - - if (mal_dlsym(pContext->coreaudio.hAudioUnit, "AudioComponentFindNext") == NULL) { - // Couldn't find the required symbols in AudioUnit, so fall back to AudioToolbox. - mal_dlclose(pContext->coreaudio.hAudioUnit); - pContext->coreaudio.hAudioUnit = mal_dlopen("AudioToolbox.framework/AudioToolbox"); - if (pContext->coreaudio.hAudioUnit == NULL) { - mal_dlclose(pContext->coreaudio.hCoreAudio); - mal_dlclose(pContext->coreaudio.hCoreFoundation); - return MAL_API_NOT_FOUND; - } - } - - pContext->coreaudio.AudioComponentFindNext = mal_dlsym(pContext->coreaudio.hAudioUnit, "AudioComponentFindNext"); - pContext->coreaudio.AudioComponentInstanceDispose = mal_dlsym(pContext->coreaudio.hAudioUnit, "AudioComponentInstanceDispose"); - pContext->coreaudio.AudioComponentInstanceNew = mal_dlsym(pContext->coreaudio.hAudioUnit, "AudioComponentInstanceNew"); - pContext->coreaudio.AudioOutputUnitStart = mal_dlsym(pContext->coreaudio.hAudioUnit, "AudioOutputUnitStart"); - pContext->coreaudio.AudioOutputUnitStop = mal_dlsym(pContext->coreaudio.hAudioUnit, "AudioOutputUnitStop"); - pContext->coreaudio.AudioUnitAddPropertyListener = mal_dlsym(pContext->coreaudio.hAudioUnit, "AudioUnitAddPropertyListener"); - pContext->coreaudio.AudioUnitGetPropertyInfo = mal_dlsym(pContext->coreaudio.hAudioUnit, "AudioUnitGetPropertyInfo"); - pContext->coreaudio.AudioUnitGetProperty = mal_dlsym(pContext->coreaudio.hAudioUnit, "AudioUnitGetProperty"); - pContext->coreaudio.AudioUnitSetProperty = mal_dlsym(pContext->coreaudio.hAudioUnit, "AudioUnitSetProperty"); - pContext->coreaudio.AudioUnitInitialize = mal_dlsym(pContext->coreaudio.hAudioUnit, "AudioUnitInitialize"); - pContext->coreaudio.AudioUnitRender = mal_dlsym(pContext->coreaudio.hAudioUnit, "AudioUnitRender"); -#else - pContext->coreaudio.CFStringGetCString = (mal_proc)CFStringGetCString; - - #if defined(MAL_APPLE_DESKTOP) - pContext->coreaudio.AudioObjectGetPropertyData = (mal_proc)AudioObjectGetPropertyData; - pContext->coreaudio.AudioObjectGetPropertyDataSize = (mal_proc)AudioObjectGetPropertyDataSize; - pContext->coreaudio.AudioObjectSetPropertyData = (mal_proc)AudioObjectSetPropertyData; - pContext->coreaudio.AudioObjectAddPropertyListener = (mal_proc)AudioObjectAddPropertyListener; - #endif - - pContext->coreaudio.AudioComponentFindNext = (mal_proc)AudioComponentFindNext; - pContext->coreaudio.AudioComponentInstanceDispose = (mal_proc)AudioComponentInstanceDispose; - pContext->coreaudio.AudioComponentInstanceNew = (mal_proc)AudioComponentInstanceNew; - pContext->coreaudio.AudioOutputUnitStart = (mal_proc)AudioOutputUnitStart; - pContext->coreaudio.AudioOutputUnitStop = (mal_proc)AudioOutputUnitStop; - pContext->coreaudio.AudioUnitAddPropertyListener = (mal_proc)AudioUnitAddPropertyListener; - pContext->coreaudio.AudioUnitGetPropertyInfo = (mal_proc)AudioUnitGetPropertyInfo; - pContext->coreaudio.AudioUnitGetProperty = (mal_proc)AudioUnitGetProperty; - pContext->coreaudio.AudioUnitSetProperty = (mal_proc)AudioUnitSetProperty; - pContext->coreaudio.AudioUnitInitialize = (mal_proc)AudioUnitInitialize; - pContext->coreaudio.AudioUnitRender = (mal_proc)AudioUnitRender; -#endif - - pContext->isBackendAsynchronous = MAL_TRUE; - - pContext->onUninit = mal_context_uninit__coreaudio; - pContext->onDeviceIDEqual = mal_context_is_device_id_equal__coreaudio; - pContext->onEnumDevices = mal_context_enumerate_devices__coreaudio; - pContext->onGetDeviceInfo = mal_context_get_device_info__coreaudio; - pContext->onDeviceInit = mal_device_init__coreaudio; - pContext->onDeviceUninit = mal_device_uninit__coreaudio; - pContext->onDeviceStart = mal_device_start__coreaudio; - pContext->onDeviceStop = mal_device_stop__coreaudio; - - return MAL_SUCCESS; -} -#endif // Core Audio - - - -/////////////////////////////////////////////////////////////////////////////// -// -// sndio Backend -// -/////////////////////////////////////////////////////////////////////////////// -#ifdef MAL_HAS_SNDIO -#include -#include - -// Only supporting OpenBSD. This did not work very well at all on FreeBSD when I tried it. Not sure if this is due -// to mini_al's implementation or if it's some kind of system configuration issue, but basically the default device -// just doesn't emit any sound, or at times you'll hear tiny pieces. I will consider enabling this when there's -// demand for it or if I can get it tested and debugged more thoroughly. - -//#if defined(__NetBSD__) || defined(__OpenBSD__) -//#include -//#endif -//#if defined(__FreeBSD__) || defined(__DragonFly__) -//#include -//#endif - -#define MAL_SIO_DEVANY "default" -#define MAL_SIO_PLAY 1 -#define MAL_SIO_REC 2 -#define MAL_SIO_NENC 8 -#define MAL_SIO_NCHAN 8 -#define MAL_SIO_NRATE 16 -#define MAL_SIO_NCONF 4 - -struct mal_sio_hdl; // <-- Opaque - -struct mal_sio_par -{ - unsigned int bits; - unsigned int bps; - unsigned int sig; - unsigned int le; - unsigned int msb; - unsigned int rchan; - unsigned int pchan; - unsigned int rate; - unsigned int bufsz; - unsigned int xrun; - unsigned int round; - unsigned int appbufsz; - int __pad[3]; - unsigned int __magic; -}; - -struct mal_sio_enc -{ - unsigned int bits; - unsigned int bps; - unsigned int sig; - unsigned int le; - unsigned int msb; -}; - -struct mal_sio_conf -{ - unsigned int enc; - unsigned int rchan; - unsigned int pchan; - unsigned int rate; -}; - -struct mal_sio_cap -{ - struct mal_sio_enc enc[MAL_SIO_NENC]; - unsigned int rchan[MAL_SIO_NCHAN]; - unsigned int pchan[MAL_SIO_NCHAN]; - unsigned int rate[MAL_SIO_NRATE]; - int __pad[7]; - unsigned int nconf; - struct mal_sio_conf confs[MAL_SIO_NCONF]; -}; - -typedef struct mal_sio_hdl* (* mal_sio_open_proc) (const char*, unsigned int, int); -typedef void (* mal_sio_close_proc) (struct mal_sio_hdl*); -typedef int (* mal_sio_setpar_proc) (struct mal_sio_hdl*, struct mal_sio_par*); -typedef int (* mal_sio_getpar_proc) (struct mal_sio_hdl*, struct mal_sio_par*); -typedef int (* mal_sio_getcap_proc) (struct mal_sio_hdl*, struct mal_sio_cap*); -typedef size_t (* mal_sio_write_proc) (struct mal_sio_hdl*, const void*, size_t); -typedef size_t (* mal_sio_read_proc) (struct mal_sio_hdl*, void*, size_t); -typedef int (* mal_sio_start_proc) (struct mal_sio_hdl*); -typedef int (* mal_sio_stop_proc) (struct mal_sio_hdl*); -typedef int (* mal_sio_initpar_proc)(struct mal_sio_par*); - -mal_format mal_format_from_sio_enc__sndio(unsigned int bits, unsigned int bps, unsigned int sig, unsigned int le, unsigned int msb) -{ - // We only support native-endian right now. - if ((mal_is_little_endian() && le == 0) || (mal_is_big_endian() && le == 1)) { - return mal_format_unknown; - } - - if (bits == 8 && bps == 1 && sig == 0) { - return mal_format_u8; - } - if (bits == 16 && bps == 2 && sig == 1) { - return mal_format_s16; - } - if (bits == 24 && bps == 3 && sig == 1) { - return mal_format_s24; - } - if (bits == 24 && bps == 4 && sig == 1 && msb == 0) { - //return mal_format_s24_32; - } - if (bits == 32 && bps == 4 && sig == 1) { - return mal_format_s32; - } - - return mal_format_unknown; -} - -mal_format mal_find_best_format_from_sio_cap__sndio(struct mal_sio_cap* caps) -{ - mal_assert(caps != NULL); - - mal_format bestFormat = mal_format_unknown; - for (unsigned int iConfig = 0; iConfig < caps->nconf; iConfig += 1) { - for (unsigned int iEncoding = 0; iEncoding < MAL_SIO_NENC; iEncoding += 1) { - if ((caps->confs[iConfig].enc & (1UL << iEncoding)) == 0) { - continue; - } - - unsigned int bits = caps->enc[iEncoding].bits; - unsigned int bps = caps->enc[iEncoding].bps; - unsigned int sig = caps->enc[iEncoding].sig; - unsigned int le = caps->enc[iEncoding].le; - unsigned int msb = caps->enc[iEncoding].msb; - mal_format format = mal_format_from_sio_enc__sndio(bits, bps, sig, le, msb); - if (format == mal_format_unknown) { - continue; // Format not supported. - } - - if (bestFormat == mal_format_unknown) { - bestFormat = format; - } else { - if (mal_get_format_priority_index(bestFormat) > mal_get_format_priority_index(format)) { // <-- Lower = better. - bestFormat = format; - } - } - } - } - - return mal_format_unknown; -} - -mal_uint32 mal_find_best_channels_from_sio_cap__sndio(struct mal_sio_cap* caps, mal_device_type deviceType, mal_format requiredFormat) -{ - mal_assert(caps != NULL); - mal_assert(requiredFormat != mal_format_unknown); - - // Just pick whatever configuration has the most channels. - mal_uint32 maxChannels = 0; - for (unsigned int iConfig = 0; iConfig < caps->nconf; iConfig += 1) { - // The encoding should be of requiredFormat. - for (unsigned int iEncoding = 0; iEncoding < MAL_SIO_NENC; iEncoding += 1) { - if ((caps->confs[iConfig].enc & (1UL << iEncoding)) == 0) { - continue; - } - - unsigned int bits = caps->enc[iEncoding].bits; - unsigned int bps = caps->enc[iEncoding].bps; - unsigned int sig = caps->enc[iEncoding].sig; - unsigned int le = caps->enc[iEncoding].le; - unsigned int msb = caps->enc[iEncoding].msb; - mal_format format = mal_format_from_sio_enc__sndio(bits, bps, sig, le, msb); - if (format != requiredFormat) { - continue; - } - - // Getting here means the format is supported. Iterate over each channel count and grab the biggest one. - for (unsigned int iChannel = 0; iChannel < MAL_SIO_NCHAN; iChannel += 1) { - unsigned int chan = 0; - if (deviceType == mal_device_type_playback) { - chan = caps->confs[iConfig].pchan; - } else { - chan = caps->confs[iConfig].rchan; - } - - if ((chan & (1UL << iChannel)) == 0) { - continue; - } - - unsigned int channels; - if (deviceType == mal_device_type_playback) { - channels = caps->pchan[iChannel]; - } else { - channels = caps->rchan[iChannel]; - } - - if (maxChannels < channels) { - maxChannels = channels; - } - } - } - } - - return maxChannels; -} - -mal_uint32 mal_find_best_sample_rate_from_sio_cap__sndio(struct mal_sio_cap* caps, mal_device_type deviceType, mal_format requiredFormat, mal_uint32 requiredChannels) -{ - mal_assert(caps != NULL); - mal_assert(requiredFormat != mal_format_unknown); - mal_assert(requiredChannels > 0); - mal_assert(requiredChannels <= MAL_MAX_CHANNELS); - - mal_uint32 firstSampleRate = 0; // <-- If the device does not support a standard rate we'll fall back to the first one that's found. - - mal_uint32 bestSampleRate = 0; - for (unsigned int iConfig = 0; iConfig < caps->nconf; iConfig += 1) { - // The encoding should be of requiredFormat. - for (unsigned int iEncoding = 0; iEncoding < MAL_SIO_NENC; iEncoding += 1) { - if ((caps->confs[iConfig].enc & (1UL << iEncoding)) == 0) { - continue; - } - - unsigned int bits = caps->enc[iEncoding].bits; - unsigned int bps = caps->enc[iEncoding].bps; - unsigned int sig = caps->enc[iEncoding].sig; - unsigned int le = caps->enc[iEncoding].le; - unsigned int msb = caps->enc[iEncoding].msb; - mal_format format = mal_format_from_sio_enc__sndio(bits, bps, sig, le, msb); - if (format != requiredFormat) { - continue; - } - - // Getting here means the format is supported. Iterate over each channel count and grab the biggest one. - for (unsigned int iChannel = 0; iChannel < MAL_SIO_NCHAN; iChannel += 1) { - unsigned int chan = 0; - if (deviceType == mal_device_type_playback) { - chan = caps->confs[iConfig].pchan; - } else { - chan = caps->confs[iConfig].rchan; - } - - if ((chan & (1UL << iChannel)) == 0) { - continue; - } - - unsigned int channels; - if (deviceType == mal_device_type_playback) { - channels = caps->pchan[iChannel]; - } else { - channels = caps->rchan[iChannel]; - } - - if (channels != requiredChannels) { - continue; - } - - // Getting here means we have found a compatible encoding/channel pair. - for (unsigned int iRate = 0; iRate < MAL_SIO_NRATE; iRate += 1) { - mal_uint32 rate = (mal_uint32)caps->rate[iRate]; - - if (firstSampleRate == 0) { - firstSampleRate = rate; - } - - // Disregard this rate if it's not a standard one. - mal_uint32 ratePriority = mal_get_standard_sample_rate_priority_index(rate); - if (ratePriority == (mal_uint32)-1) { - continue; - } - - if (mal_get_standard_sample_rate_priority_index(bestSampleRate) > ratePriority) { // Lower = better. - bestSampleRate = rate; - } - } - } - } - } - - // If a standard sample rate was not found just fall back to the first one that was iterated. - if (bestSampleRate == 0) { - bestSampleRate = firstSampleRate; - } - - return bestSampleRate; -} - - -mal_bool32 mal_context_is_device_id_equal__sndio(mal_context* pContext, const mal_device_id* pID0, const mal_device_id* pID1) -{ - mal_assert(pContext != NULL); - mal_assert(pID0 != NULL); - mal_assert(pID1 != NULL); - (void)pContext; - - return mal_strcmp(pID0->sndio, pID1->sndio) == 0; -} - -mal_result mal_context_enumerate_devices__sndio(mal_context* pContext, mal_enum_devices_callback_proc callback, void* pUserData) -{ - mal_assert(pContext != NULL); - mal_assert(callback != NULL); - - // sndio doesn't seem to have a good device enumeration API, so I'm therefore only enumerating - // over default devices for now. - mal_bool32 isTerminating = MAL_FALSE; - struct mal_sio_hdl* handle; - - // Playback. - if (!isTerminating) { - handle = ((mal_sio_open_proc)pContext->sndio.sio_open)(MAL_SIO_DEVANY, MAL_SIO_PLAY, 0); - if (handle != NULL) { - // Supports playback. - mal_device_info deviceInfo; - mal_zero_object(&deviceInfo); - mal_strcpy_s(deviceInfo.id.sndio, sizeof(deviceInfo.id.sndio), MAL_SIO_DEVANY); - mal_strcpy_s(deviceInfo.name, sizeof(deviceInfo.name), MAL_DEFAULT_PLAYBACK_DEVICE_NAME); - - isTerminating = !callback(pContext, mal_device_type_playback, &deviceInfo, pUserData); - - ((mal_sio_close_proc)pContext->sndio.sio_close)(handle); - } - } - - // Capture. - if (!isTerminating) { - handle = ((mal_sio_open_proc)pContext->sndio.sio_open)(MAL_SIO_DEVANY, MAL_SIO_REC, 0); - if (handle != NULL) { - // Supports capture. - mal_device_info deviceInfo; - mal_zero_object(&deviceInfo); - mal_strcpy_s(deviceInfo.id.sndio, sizeof(deviceInfo.id.sndio), "default"); - mal_strcpy_s(deviceInfo.name, sizeof(deviceInfo.name), MAL_DEFAULT_CAPTURE_DEVICE_NAME); - - isTerminating = !callback(pContext, mal_device_type_capture, &deviceInfo, pUserData); - - ((mal_sio_close_proc)pContext->sndio.sio_close)(handle); - } - } - - return MAL_SUCCESS; -} - -mal_result mal_context_get_device_info__sndio(mal_context* pContext, mal_device_type deviceType, const mal_device_id* pDeviceID, mal_share_mode shareMode, mal_device_info* pDeviceInfo) -{ - mal_assert(pContext != NULL); - (void)shareMode; - - // We need to open the device before we can get information about it. - char devid[256]; - if (pDeviceID == NULL) { - mal_strcpy_s(devid, sizeof(devid), MAL_SIO_DEVANY); - mal_strcpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), (deviceType == mal_device_type_playback) ? MAL_DEFAULT_PLAYBACK_DEVICE_NAME : MAL_DEFAULT_CAPTURE_DEVICE_NAME); - } else { - mal_strcpy_s(devid, sizeof(devid), pDeviceID->sndio); - mal_strcpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), devid); - } - - struct mal_sio_hdl* handle = ((mal_sio_open_proc)pContext->sndio.sio_open)(devid, (deviceType == mal_device_type_playback) ? MAL_SIO_PLAY : MAL_SIO_REC, 0); - if (handle == NULL) { - return MAL_NO_DEVICE; - } - - struct mal_sio_cap caps; - if (((mal_sio_getcap_proc)pContext->sndio.sio_getcap)(handle, &caps) == 0) { - return MAL_ERROR; - } - - for (unsigned int iConfig = 0; iConfig < caps.nconf; iConfig += 1) { - // The main thing we care about is that the encoding is supported by mini_al. If it is, we want to give - // preference to some formats over others. - for (unsigned int iEncoding = 0; iEncoding < MAL_SIO_NENC; iEncoding += 1) { - if ((caps.confs[iConfig].enc & (1UL << iEncoding)) == 0) { - continue; - } - - unsigned int bits = caps.enc[iEncoding].bits; - unsigned int bps = caps.enc[iEncoding].bps; - unsigned int sig = caps.enc[iEncoding].sig; - unsigned int le = caps.enc[iEncoding].le; - unsigned int msb = caps.enc[iEncoding].msb; - mal_format format = mal_format_from_sio_enc__sndio(bits, bps, sig, le, msb); - if (format == mal_format_unknown) { - continue; // Format not supported. - } - - // Add this format if it doesn't already exist. - mal_bool32 formatExists = MAL_FALSE; - for (mal_uint32 iExistingFormat = 0; iExistingFormat < pDeviceInfo->formatCount; iExistingFormat += 1) { - if (pDeviceInfo->formats[iExistingFormat] == format) { - formatExists = MAL_TRUE; - break; - } - } - - if (!formatExists) { - pDeviceInfo->formats[pDeviceInfo->formatCount++] = format; - } - } - - // Channels. - for (unsigned int iChannel = 0; iChannel < MAL_SIO_NCHAN; iChannel += 1) { - unsigned int chan = 0; - if (deviceType == mal_device_type_playback) { - chan = caps.confs[iConfig].pchan; - } else { - chan = caps.confs[iConfig].rchan; - } - - if ((chan & (1UL << iChannel)) == 0) { - continue; - } - - unsigned int channels; - if (deviceType == mal_device_type_playback) { - channels = caps.pchan[iChannel]; - } else { - channels = caps.rchan[iChannel]; - } - - if (pDeviceInfo->minChannels > channels) { - pDeviceInfo->minChannels = channels; - } - if (pDeviceInfo->maxChannels < channels) { - pDeviceInfo->maxChannels = channels; - } - } - - // Sample rates. - for (unsigned int iRate = 0; iRate < MAL_SIO_NRATE; iRate += 1) { - if ((caps.confs[iConfig].rate & (1UL << iRate)) != 0) { - unsigned int rate = caps.rate[iRate]; - if (pDeviceInfo->minSampleRate > rate) { - pDeviceInfo->minSampleRate = rate; - } - if (pDeviceInfo->maxSampleRate < rate) { - pDeviceInfo->maxSampleRate = rate; - } - } - } - } - - ((mal_sio_close_proc)pContext->sndio.sio_close)(handle); - return MAL_SUCCESS; -} - -void mal_device_uninit__sndio(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - ((mal_sio_close_proc)pDevice->pContext->sndio.sio_close)((struct mal_sio_hdl*)pDevice->sndio.handle); - mal_free(pDevice->sndio.pIntermediaryBuffer); -} - -mal_result mal_device_init__sndio(mal_context* pContext, mal_device_type deviceType, const mal_device_id* pDeviceID, const mal_device_config* pConfig, mal_device* pDevice) -{ - (void)pContext; - - mal_assert(pDevice != NULL); - mal_zero_object(&pDevice->sndio); - - const char* deviceName = MAL_SIO_DEVANY; -//#if defined(__FreeBSD__) || defined(__DragonFly__) -// deviceName = "rsnd/0"; -//#else - if (pDeviceID != NULL) { - deviceName = pDeviceID->sndio; - } - - pDevice->sndio.handle = (mal_ptr)((mal_sio_open_proc)pContext->sndio.sio_open)(deviceName, (deviceType == mal_device_type_playback) ? MAL_SIO_PLAY : MAL_SIO_REC, 0); - if (pDevice->sndio.handle == NULL) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[sndio] Failed to open device.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - - // We need to retrieve the device caps to determine the most appropriate format to use. - struct mal_sio_cap caps; - if (((mal_sio_getcap_proc)pContext->sndio.sio_getcap)((struct mal_sio_hdl*)pDevice->sndio.handle, &caps) == 0) { - ((mal_sio_close_proc)pContext->sndio.sio_close)((struct mal_sio_hdl*)pDevice->sndio.handle); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[sndio] Failed to retrieve device caps.", MAL_ERROR); - } - - mal_format desiredFormat = pDevice->format; - if (pDevice->usingDefaultFormat) { - desiredFormat = mal_find_best_format_from_sio_cap__sndio(&caps); - } - - if (desiredFormat == mal_format_unknown) { - desiredFormat = pDevice->format; - } - - - // Note: sndio reports a huge range of available channels. This is inconvenient for us because there's no real - // way, as far as I can tell, to get the _actual_ channel count of the device. I'm therefore restricting this - // to the requested channels, regardless of whether or not the default channel count is requested. - // - // For hardware devices, I'm suspecting only a single channel count will be reported and we can safely use the - // value returned by mal_find_best_channels_from_sio_cap__sndio(). - mal_uint32 desiredChannels = pDevice->channels; - if (pDevice->usingDefaultChannels) { - if (strlen(deviceName) > strlen("rsnd/") && strncmp(deviceName, "rsnd/", strlen("rsnd/")) == 0) { - desiredChannels = mal_find_best_channels_from_sio_cap__sndio(&caps, deviceType, desiredFormat); - } - } - - if (desiredChannels == 0) { - desiredChannels = pDevice->channels; - } - - - mal_uint32 desiredSampleRate = pDevice->sampleRate; - if (pDevice->usingDefaultSampleRate) { - desiredSampleRate = mal_find_best_sample_rate_from_sio_cap__sndio(&caps, deviceType, desiredFormat, desiredChannels); - } - - if (desiredSampleRate == 0) { - desiredSampleRate = pDevice->sampleRate; - } - - - struct mal_sio_par par; - ((mal_sio_initpar_proc)pDevice->pContext->sndio.sio_initpar)(&par); - par.msb = 0; - par.le = mal_is_little_endian(); - - switch (desiredFormat) { - case mal_format_u8: - { - par.bits = 8; - par.bps = 1; - par.sig = 0; - } break; - - case mal_format_s24: - { - par.bits = 24; - par.bps = 3; - par.sig = 1; - } break; - - case mal_format_s32: - { - par.bits = 32; - par.bps = 4; - par.sig = 1; - } break; - - case mal_format_s16: - case mal_format_f32: - default: - { - par.bits = 16; - par.bps = 2; - par.sig = 1; - } break; - } - - if (deviceType == mal_device_type_playback) { - par.pchan = desiredChannels; - } else { - par.rchan = desiredChannels; - } - - par.rate = desiredSampleRate; - - // Try calculating an appropriate default buffer size after we have the sample rate. - mal_uint32 desiredBufferSizeInFrames = pDevice->bufferSizeInFrames; - if (desiredBufferSizeInFrames == 0) { - desiredBufferSizeInFrames = mal_calculate_buffer_size_in_frames_from_milliseconds(pDevice->bufferSizeInMilliseconds, par.rate); - } - - par.round = desiredBufferSizeInFrames / pDevice->periods; - par.appbufsz = par.round * pDevice->periods; - - if (((mal_sio_setpar_proc)pContext->sndio.sio_setpar)((struct mal_sio_hdl*)pDevice->sndio.handle, &par) == 0) { - ((mal_sio_close_proc)pContext->sndio.sio_close)((struct mal_sio_hdl*)pDevice->sndio.handle); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[sndio] Failed to set buffer size.", MAL_FORMAT_NOT_SUPPORTED); - } - if (((mal_sio_getpar_proc)pContext->sndio.sio_getpar)((struct mal_sio_hdl*)pDevice->sndio.handle, &par) == 0) { - ((mal_sio_close_proc)pContext->sndio.sio_close)((struct mal_sio_hdl*)pDevice->sndio.handle); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[sndio] Failed to retrieve buffer size.", MAL_FORMAT_NOT_SUPPORTED); - } - - pDevice->internalFormat = mal_format_from_sio_enc__sndio(par.bits, par.bps, par.sig, par.le, par.msb); - - if (deviceType == mal_device_type_playback) { - pDevice->internalChannels = par.pchan; - } else { - pDevice->internalChannels = par.rchan; - } - - pDevice->internalSampleRate = par.rate; - - pDevice->periods = par.appbufsz / par.round; - if (pDevice->periods < 2) { - pDevice->periods = 2; - } - pDevice->bufferSizeInFrames = par.round * pDevice->periods; - pDevice->sndio.fragmentSizeInFrames = par.round; - - mal_get_standard_channel_map(mal_standard_channel_map_sndio, pDevice->internalChannels, pDevice->internalChannelMap); - - // The device is always shared with sndio. - pDevice->exclusiveMode = MAL_FALSE; - - pDevice->sndio.pIntermediaryBuffer = mal_malloc(pDevice->sndio.fragmentSizeInFrames * mal_get_bytes_per_frame(pDevice->internalFormat, pDevice->internalChannels)); - if (pDevice->sndio.pIntermediaryBuffer == NULL) { - ((mal_sio_close_proc)pContext->sndio.sio_close)((struct mal_sio_hdl*)pDevice->sndio.handle); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[sndio] Failed to allocate memory for intermediary buffer.", MAL_OUT_OF_MEMORY); - } - -#ifdef MAL_DEBUG_OUTPUT - printf("DEVICE INFO\n"); - printf(" Format: %s\n", mal_get_format_name(pDevice->internalFormat)); - printf(" Channels: %d\n", pDevice->internalChannels); - printf(" Sample Rate: %d\n", pDevice->internalSampleRate); - printf(" Buffer Size: %d\n", pDevice->bufferSizeInFrames); - printf(" Periods: %d\n", pDevice->periods); - printf(" appbufsz: %d\n", par.appbufsz); - printf(" round: %d\n", par.round); -#endif - - return MAL_SUCCESS; -} - -mal_result mal_device_start__sndio(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - if (((mal_sio_start_proc)pDevice->pContext->sndio.sio_start)((struct mal_sio_hdl*)pDevice->sndio.handle) == 0) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[sndio] Failed to start backend device.", MAL_FAILED_TO_START_BACKEND_DEVICE); - } - - // The device is started by the next calls to read() and write(). For playback it's simple - just read - // data from the client, then write it to the device with write() which will in turn start the device. - // For capture it's a bit less intuitive - we do nothing (it'll be started automatically by the first - // call to read(). - if (pDevice->type == mal_device_type_playback) { - // Playback. Need to load the entire buffer, which means we need to write a fragment for each period. - for (mal_uint32 iPeriod = 0; iPeriod < pDevice->periods; iPeriod += 1) { - mal_device__read_frames_from_client(pDevice, pDevice->sndio.fragmentSizeInFrames, pDevice->sndio.pIntermediaryBuffer); - - int bytesWritten = ((mal_sio_write_proc)pDevice->pContext->sndio.sio_write)((struct mal_sio_hdl*)pDevice->sndio.handle, pDevice->sndio.pIntermediaryBuffer, pDevice->sndio.fragmentSizeInFrames * mal_get_bytes_per_frame(pDevice->internalFormat, pDevice->internalChannels)); - if (bytesWritten == 0) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[sndio] Failed to send initial chunk of data to the device.", MAL_FAILED_TO_SEND_DATA_TO_DEVICE); - } - } - } else { - // Capture. Do nothing. - } - - return MAL_SUCCESS; -} - -mal_result mal_device_stop__sndio(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - ((mal_sio_stop_proc)pDevice->pContext->sndio.sio_stop)((struct mal_sio_hdl*)pDevice->sndio.handle); - return MAL_SUCCESS; -} - -mal_result mal_device_break_main_loop__sndio(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - pDevice->sndio.breakFromMainLoop = MAL_TRUE; - return MAL_SUCCESS; -} - -mal_result mal_device_main_loop__sndio(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - pDevice->sndio.breakFromMainLoop = MAL_FALSE; - while (!pDevice->sndio.breakFromMainLoop) { - // Break from the main loop if the device isn't started anymore. Likely what's happened is the application - // has requested that the device be stopped. - if (!mal_device_is_started(pDevice)) { - break; - } - - if (pDevice->type == mal_device_type_playback) { - // Playback. - mal_device__read_frames_from_client(pDevice, pDevice->sndio.fragmentSizeInFrames, pDevice->sndio.pIntermediaryBuffer); - - int bytesWritten = ((mal_sio_write_proc)pDevice->pContext->sndio.sio_write)((struct mal_sio_hdl*)pDevice->sndio.handle, pDevice->sndio.pIntermediaryBuffer, pDevice->sndio.fragmentSizeInFrames * pDevice->internalChannels * mal_get_bytes_per_sample(pDevice->internalFormat)); - if (bytesWritten == 0) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[sndio] Failed to send data from the client to the device.", MAL_FAILED_TO_SEND_DATA_TO_DEVICE); - } - } else { - // Capture. - int bytesRead = ((mal_sio_read_proc)pDevice->pContext->sndio.sio_read)((struct mal_sio_hdl*)pDevice->sndio.handle, pDevice->sndio.pIntermediaryBuffer, pDevice->sndio.fragmentSizeInFrames * mal_get_bytes_per_sample(pDevice->internalFormat)); - if (bytesRead == 0) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[sndio] Failed to read data from the device to be sent to the client.", MAL_FAILED_TO_READ_DATA_FROM_DEVICE); - } - - mal_uint32 framesRead = (mal_uint32)bytesRead / pDevice->internalChannels / mal_get_bytes_per_sample(pDevice->internalFormat); - mal_device__send_frames_to_client(pDevice, framesRead, pDevice->sndio.pIntermediaryBuffer); - } - } - - return MAL_SUCCESS; -} - -mal_result mal_context_uninit__sndio(mal_context* pContext) -{ - mal_assert(pContext != NULL); - mal_assert(pContext->backend == mal_backend_sndio); - - (void)pContext; - return MAL_SUCCESS; -} - -mal_result mal_context_init__sndio(mal_context* pContext) -{ - mal_assert(pContext != NULL); - -#ifndef MAL_NO_RUNTIME_LINKING - // libpulse.so - const char* libsndioNames[] = { - "libsndio.so" - }; - - for (size_t i = 0; i < mal_countof(libsndioNames); ++i) { - pContext->sndio.sndioSO = mal_dlopen(libsndioNames[i]); - if (pContext->sndio.sndioSO != NULL) { - break; - } - } - - if (pContext->sndio.sndioSO == NULL) { - return MAL_NO_BACKEND; - } - - pContext->sndio.sio_open = (mal_proc)mal_dlsym(pContext->sndio.sndioSO, "sio_open"); - pContext->sndio.sio_close = (mal_proc)mal_dlsym(pContext->sndio.sndioSO, "sio_close"); - pContext->sndio.sio_setpar = (mal_proc)mal_dlsym(pContext->sndio.sndioSO, "sio_setpar"); - pContext->sndio.sio_getpar = (mal_proc)mal_dlsym(pContext->sndio.sndioSO, "sio_getpar"); - pContext->sndio.sio_getcap = (mal_proc)mal_dlsym(pContext->sndio.sndioSO, "sio_getcap"); - pContext->sndio.sio_write = (mal_proc)mal_dlsym(pContext->sndio.sndioSO, "sio_write"); - pContext->sndio.sio_read = (mal_proc)mal_dlsym(pContext->sndio.sndioSO, "sio_read"); - pContext->sndio.sio_start = (mal_proc)mal_dlsym(pContext->sndio.sndioSO, "sio_start"); - pContext->sndio.sio_stop = (mal_proc)mal_dlsym(pContext->sndio.sndioSO, "sio_stop"); - pContext->sndio.sio_initpar = (mal_proc)mal_dlsym(pContext->sndio.sndioSO, "sio_initpar"); -#else - pContext->sndio.sio_open = sio_open; - pContext->sndio.sio_close = sio_close; - pContext->sndio.sio_setpar = sio_setpar; - pContext->sndio.sio_getpar = sio_getpar; - pContext->sndio.sio_getcap = sio_getcap; - pContext->sndio.sio_write = sio_write; - pContext->sndio.sio_read = sio_read; - pContext->sndio.sio_start = sio_start; - pContext->sndio.sio_stop = sio_stop; - pContext->sndio.sio_initpar = sio_initpar; -#endif - - pContext->onUninit = mal_context_uninit__sndio; - pContext->onDeviceIDEqual = mal_context_is_device_id_equal__sndio; - pContext->onEnumDevices = mal_context_enumerate_devices__sndio; - pContext->onGetDeviceInfo = mal_context_get_device_info__sndio; - pContext->onDeviceInit = mal_device_init__sndio; - pContext->onDeviceUninit = mal_device_uninit__sndio; - pContext->onDeviceStart = mal_device_start__sndio; - pContext->onDeviceStop = mal_device_stop__sndio; - pContext->onDeviceBreakMainLoop = mal_device_break_main_loop__sndio; - pContext->onDeviceMainLoop = mal_device_main_loop__sndio; - - return MAL_SUCCESS; -} -#endif // sndio - - - -/////////////////////////////////////////////////////////////////////////////// -// -// audio(4) Backend -// -/////////////////////////////////////////////////////////////////////////////// -#ifdef MAL_HAS_AUDIO4 -#include -#include -#include -#include -#include -#include -#include - -#if defined(__OpenBSD__) - #include - #if defined(OpenBSD) && OpenBSD >= 201709 - #define MAL_AUDIO4_USE_NEW_API - #endif -#endif - -void mal_construct_device_id__audio4(char* id, size_t idSize, const char* base, int deviceIndex) -{ - mal_assert(id != NULL); - mal_assert(idSize > 0); - mal_assert(deviceIndex >= 0); - - size_t baseLen = strlen(base); - mal_assert(idSize > baseLen); - - mal_strcpy_s(id, idSize, base); - mal_itoa_s(deviceIndex, id+baseLen, idSize-baseLen, 10); -} - -mal_result mal_extract_device_index_from_id__audio4(const char* id, const char* base, int* pIndexOut) -{ - mal_assert(id != NULL); - mal_assert(base != NULL); - mal_assert(pIndexOut != NULL); - - size_t idLen = strlen(id); - size_t baseLen = strlen(base); - if (idLen <= baseLen) { - return MAL_ERROR; // Doesn't look like the id starts with the base. - } - - if (strncmp(id, base, baseLen) != 0) { - return MAL_ERROR; // ID does not begin with base. - } - - const char* deviceIndexStr = id + baseLen; - if (deviceIndexStr[0] == '\0') { - return MAL_ERROR; // No index specified in the ID. - } - - if (pIndexOut) { - *pIndexOut = atoi(deviceIndexStr); - } - - return MAL_SUCCESS; -} - -mal_bool32 mal_context_is_device_id_equal__audio4(mal_context* pContext, const mal_device_id* pID0, const mal_device_id* pID1) -{ - mal_assert(pContext != NULL); - mal_assert(pID0 != NULL); - mal_assert(pID1 != NULL); - (void)pContext; - - return mal_strcmp(pID0->audio4, pID1->audio4) == 0; -} - -#if !defined(MAL_AUDIO4_USE_NEW_API) -mal_format mal_format_from_encoding__audio4(unsigned int encoding, unsigned int precision) -{ - if (precision == 8 && (encoding == AUDIO_ENCODING_ULINEAR || encoding == AUDIO_ENCODING_ULINEAR || encoding == AUDIO_ENCODING_ULINEAR_LE || encoding == AUDIO_ENCODING_ULINEAR_BE)) { - return mal_format_u8; - } else { - if (mal_is_little_endian() && encoding == AUDIO_ENCODING_SLINEAR_LE) { - if (precision == 16) { - return mal_format_s16; - } else if (precision == 24) { - return mal_format_s24; - } else if (precision == 32) { - return mal_format_s32; - } - } else if (mal_is_big_endian() && encoding == AUDIO_ENCODING_SLINEAR_BE) { - if (precision == 16) { - return mal_format_s16; - } else if (precision == 24) { - return mal_format_s24; - } else if (precision == 32) { - return mal_format_s32; - } - } - } - - return mal_format_unknown; // Encoding not supported. -} - -mal_format mal_format_from_prinfo__audio4(struct audio_prinfo* prinfo) -{ - return mal_format_from_encoding__audio4(prinfo->encoding, prinfo->precision); -} -#else -mal_format mal_format_from_swpar__audio4(struct audio_swpar* par) -{ - if (par->bits == 8 && par->bps == 1 && par->sig == 0) { - return mal_format_u8; - } - if (par->bits == 16 && par->bps == 2 && par->sig == 1 && par->le == mal_is_little_endian()) { - return mal_format_s16; - } - if (par->bits == 24 && par->bps == 3 && par->sig == 1 && par->le == mal_is_little_endian()) { - return mal_format_s24; - } - if (par->bits == 32 && par->bps == 4 && par->sig == 1 && par->le == mal_is_little_endian()) { - return mal_format_f32; - } - - // Format not supported. - return mal_format_unknown; -} -#endif - -mal_result mal_context_get_device_info_from_fd__audio4(mal_context* pContext, mal_device_type deviceType, int fd, mal_device_info* pInfoOut) -{ - mal_assert(pContext != NULL); - mal_assert(fd >= 0); - mal_assert(pInfoOut != NULL); - - (void)pContext; - (void)deviceType; - - audio_device_t fdDevice; - if (ioctl(fd, AUDIO_GETDEV, &fdDevice) < 0) { - return MAL_ERROR; // Failed to retrieve device info. - } - - // Name. - mal_strcpy_s(pInfoOut->name, sizeof(pInfoOut->name), fdDevice.name); - -#if !defined(MAL_AUDIO4_USE_NEW_API) - // Supported formats. We get this by looking at the encodings. - int counter = 0; - for (;;) { - audio_encoding_t encoding; - mal_zero_object(&encoding); - encoding.index = counter; - if (ioctl(fd, AUDIO_GETENC, &encoding) < 0) { - break; - } - - mal_format format = mal_format_from_encoding__audio4(encoding.encoding, encoding.precision); - if (format != mal_format_unknown) { - pInfoOut->formats[pInfoOut->formatCount++] = format; - } - - counter += 1; - } - - audio_info_t fdInfo; - if (ioctl(fd, AUDIO_GETINFO, &fdInfo) < 0) { - return MAL_ERROR; - } - - if (deviceType == mal_device_type_playback) { - pInfoOut->minChannels = fdInfo.play.channels; - pInfoOut->maxChannels = fdInfo.play.channels; - pInfoOut->minSampleRate = fdInfo.play.sample_rate; - pInfoOut->maxSampleRate = fdInfo.play.sample_rate; - } else { - pInfoOut->minChannels = fdInfo.record.channels; - pInfoOut->maxChannels = fdInfo.record.channels; - pInfoOut->minSampleRate = fdInfo.record.sample_rate; - pInfoOut->maxSampleRate = fdInfo.record.sample_rate; - } -#else - struct audio_swpar fdPar; - if (ioctl(fd, AUDIO_GETPAR, &fdPar) < 0) { - return MAL_ERROR; - } - - mal_format format = mal_format_from_swpar__audio4(&fdPar); - if (format == mal_format_unknown) { - return MAL_FORMAT_NOT_SUPPORTED; - } - pInfoOut->formats[pInfoOut->formatCount++] = format; - - if (deviceType == mal_device_type_playback) { - pInfoOut->minChannels = fdPar.pchan; - pInfoOut->maxChannels = fdPar.pchan; - } else { - pInfoOut->minChannels = fdPar.rchan; - pInfoOut->maxChannels = fdPar.rchan; - } - - pInfoOut->minSampleRate = fdPar.rate; - pInfoOut->maxSampleRate = fdPar.rate; -#endif - - return MAL_SUCCESS; -} - -mal_result mal_context_enumerate_devices__audio4(mal_context* pContext, mal_enum_devices_callback_proc callback, void* pUserData) -{ - mal_assert(pContext != NULL); - mal_assert(callback != NULL); - - const int maxDevices = 64; - - // Every device will be named "/dev/audioN", with a "/dev/audioctlN" equivalent. We use the "/dev/audioctlN" - // version here since we can open it even when another process has control of the "/dev/audioN" device. - char devpath[256]; - for (int iDevice = 0; iDevice < maxDevices; ++iDevice) { - mal_strcpy_s(devpath, sizeof(devpath), "/dev/audioctl"); - mal_itoa_s(iDevice, devpath+strlen(devpath), sizeof(devpath)-strlen(devpath), 10); - - struct stat st; - if (stat(devpath, &st) < 0) { - break; - } - - // The device exists, but we need to check if it's usable as playback and/or capture. - int fd; - mal_bool32 isTerminating = MAL_FALSE; - - // Playback. - if (!isTerminating) { - fd = open(devpath, O_RDONLY, 0); - if (fd >= 0) { - // Supports playback. - mal_device_info deviceInfo; - mal_zero_object(&deviceInfo); - mal_construct_device_id__audio4(deviceInfo.id.audio4, sizeof(deviceInfo.id.audio4), "/dev/audio", iDevice); - if (mal_context_get_device_info_from_fd__audio4(pContext, mal_device_type_playback, fd, &deviceInfo) == MAL_SUCCESS) { - isTerminating = !callback(pContext, mal_device_type_playback, &deviceInfo, pUserData); - } - - close(fd); - } - } - - // Capture. - if (!isTerminating) { - fd = open(devpath, O_WRONLY, 0); - if (fd >= 0) { - // Supports capture. - mal_device_info deviceInfo; - mal_zero_object(&deviceInfo); - mal_construct_device_id__audio4(deviceInfo.id.audio4, sizeof(deviceInfo.id.audio4), "/dev/audio", iDevice); - if (mal_context_get_device_info_from_fd__audio4(pContext, mal_device_type_capture, fd, &deviceInfo) == MAL_SUCCESS) { - isTerminating = !callback(pContext, mal_device_type_capture, &deviceInfo, pUserData); - } - - close(fd); - } - } - - if (isTerminating) { - break; - } - } - - return MAL_SUCCESS; -} - -mal_result mal_context_get_device_info__audio4(mal_context* pContext, mal_device_type deviceType, const mal_device_id* pDeviceID, mal_share_mode shareMode, mal_device_info* pDeviceInfo) -{ - mal_assert(pContext != NULL); - (void)shareMode; - - // We need to open the "/dev/audioctlN" device to get the info. To do this we need to extract the number - // from the device ID which will be in "/dev/audioN" format. - int fd = -1; - int deviceIndex = -1; - char ctlid[256]; - if (pDeviceID == NULL) { - // Default device. - mal_strcpy_s(ctlid, sizeof(ctlid), "/dev/audioctl"); - } else { - // Specific device. We need to convert from "/dev/audioN" to "/dev/audioctlN". - mal_result result = mal_extract_device_index_from_id__audio4(pDeviceID->audio4, "/dev/audio", &deviceIndex); - if (result != MAL_SUCCESS) { - return result; - } - - mal_construct_device_id__audio4(ctlid, sizeof(ctlid), "/dev/audioctl", deviceIndex); - } - - fd = open(ctlid, (deviceType == mal_device_type_playback) ? O_WRONLY : O_RDONLY, 0); - if (fd == -1) { - return MAL_NO_DEVICE; - } - - if (deviceIndex == -1) { - mal_strcpy_s(pDeviceInfo->id.audio4, sizeof(pDeviceInfo->id.audio4), "/dev/audio"); - } else { - mal_construct_device_id__audio4(pDeviceInfo->id.audio4, sizeof(pDeviceInfo->id.audio4), "/dev/audio", deviceIndex); - } - - mal_result result = mal_context_get_device_info_from_fd__audio4(pContext, deviceType, fd, pDeviceInfo); - - close(fd); - return result; -} - -void mal_device_uninit__audio4(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - close(pDevice->audio4.fd); - mal_free(pDevice->audio4.pIntermediaryBuffer); -} - -mal_result mal_device_init__audio4(mal_context* pContext, mal_device_type deviceType, const mal_device_id* pDeviceID, const mal_device_config* pConfig, mal_device* pDevice) -{ - (void)pContext; - - mal_assert(pDevice != NULL); - mal_zero_object(&pDevice->audio4); - pDevice->audio4.fd = -1; - - // The first thing to do is open the file. - const char* deviceName = "/dev/audio"; - if (pDeviceID != NULL) { - deviceName = pDeviceID->audio4; - } - - pDevice->audio4.fd = open(deviceName, ((deviceType == mal_device_type_playback) ? O_WRONLY : O_RDONLY) | O_NONBLOCK, 0); - if (pDevice->audio4.fd == -1) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[audio4] Failed to open device.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - -#if !defined(MAL_AUDIO4_USE_NEW_API) - audio_info_t fdInfo; - AUDIO_INITINFO(&fdInfo); - - struct audio_prinfo* prinfo; - if (deviceType == mal_device_type_playback) { - prinfo = &fdInfo.play; - fdInfo.mode = AUMODE_PLAY; - } else { - prinfo = &fdInfo.record; - fdInfo.mode = AUMODE_RECORD; - } - - // Format. Note that it looks like audio4 does not support floating point formats. In this case - // we just fall back to s16. - switch (pDevice->format) - { - case mal_format_u8: - { - prinfo->encoding = AUDIO_ENCODING_ULINEAR; - prinfo->precision = 8; - } break; - - case mal_format_s24: - { - prinfo->encoding = (mal_is_little_endian()) ? AUDIO_ENCODING_SLINEAR_LE : AUDIO_ENCODING_SLINEAR_BE; - prinfo->precision = 24; - } break; - - case mal_format_s32: - { - prinfo->encoding = (mal_is_little_endian()) ? AUDIO_ENCODING_SLINEAR_LE : AUDIO_ENCODING_SLINEAR_BE; - prinfo->precision = 32; - } break; - - case mal_format_s16: - case mal_format_f32: - default: - { - prinfo->encoding = (mal_is_little_endian()) ? AUDIO_ENCODING_SLINEAR_LE : AUDIO_ENCODING_SLINEAR_BE; - prinfo->precision = 16; - } break; - } - - // We always want to the use the devices native channel count and sample rate. - mal_device_info nativeInfo; - mal_result result = mal_context_get_device_info(pContext, deviceType, pDeviceID, pConfig->shareMode, &nativeInfo); - if (result != MAL_SUCCESS) { - close(pDevice->audio4.fd); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[audio4] Failed to retrieve device format.", result); - } - - prinfo->channels = nativeInfo.maxChannels; - prinfo->sample_rate = nativeInfo.maxSampleRate; - - // We need to apply the settings so far so we can get back the actual sample rate which we need for calculating - // the default buffer size below. - if (ioctl(pDevice->audio4.fd, AUDIO_SETINFO, &fdInfo) < 0) { - close(pDevice->audio4.fd); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[audio4] Failed to set device format. AUDIO_SETINFO failed.", MAL_FORMAT_NOT_SUPPORTED); - } - - if (ioctl(pDevice->audio4.fd, AUDIO_GETINFO, &fdInfo) < 0) { - close(pDevice->audio4.fd); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[audio4] AUDIO_GETINFO failed.", MAL_FORMAT_NOT_SUPPORTED); - } - - pDevice->internalFormat = mal_format_from_prinfo__audio4(prinfo); - if (pDevice->internalFormat == mal_format_unknown) { - close(pDevice->audio4.fd); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[audio4] The device's internal device format is not supported by mini_al. The device is unusable.", MAL_FORMAT_NOT_SUPPORTED); - } - - pDevice->internalChannels = prinfo->channels; - pDevice->internalSampleRate = prinfo->sample_rate; - - - - // Try calculating an appropriate default buffer size. - if (pDevice->bufferSizeInFrames == 0) { - pDevice->bufferSizeInFrames = mal_calculate_buffer_size_in_frames_from_milliseconds(pDevice->bufferSizeInMilliseconds, pDevice->internalSampleRate); - } - - // What mini_al calls a fragment, audio4 calls a block. - mal_uint32 fragmentSizeInBytes = pDevice->bufferSizeInFrames * mal_get_bytes_per_frame(pDevice->internalFormat, pDevice->internalChannels); - if (fragmentSizeInBytes < 16) { - fragmentSizeInBytes = 16; - } - - - AUDIO_INITINFO(&fdInfo); - fdInfo.hiwat = mal_max(pDevice->periods, 5); - fdInfo.lowat = (unsigned int)(fdInfo.hiwat * 0.75); - fdInfo.blocksize = fragmentSizeInBytes / fdInfo.hiwat; - if (ioctl(pDevice->audio4.fd, AUDIO_SETINFO, &fdInfo) < 0) { - close(pDevice->audio4.fd); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[audio4] Failed to set internal buffer size. AUDIO_SETINFO failed.", MAL_FORMAT_NOT_SUPPORTED); - } - - pDevice->periods = fdInfo.hiwat; - pDevice->bufferSizeInFrames = (fdInfo.blocksize * fdInfo.hiwat) / mal_get_bytes_per_frame(pDevice->internalFormat, pDevice->internalChannels); - pDevice->audio4.fragmentSizeInFrames = fdInfo.blocksize / mal_get_bytes_per_frame(pDevice->internalFormat, pDevice->internalChannels); -#else - // We need to retrieve the format of the device so we can know the channel count and sample rate. Then we - // can calculate the buffer size. - struct audio_swpar fdPar; - if (ioctl(pDevice->audio4.fd, AUDIO_GETPAR, &fdPar) < 0) { - close(pDevice->audio4.fd); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[audio4] Failed to retrieve initial device parameters.", MAL_FORMAT_NOT_SUPPORTED); - } - - // Set the initial internal formats so we can do calculations below. - pDevice->internalFormat = mal_format_from_swpar__audio4(&fdPar); - if (deviceType == mal_device_type_playback) { - pDevice->internalChannels = fdPar.pchan; - } else { - pDevice->internalChannels = fdPar.rchan; - } - pDevice->internalSampleRate = fdPar.rate; - - if (pDevice->bufferSizeInFrames == 0) { - pDevice->bufferSizeInFrames = mal_calculate_buffer_size_in_frames_from_milliseconds(pDevice->bufferSizeInMilliseconds, pDevice->internalSampleRate); - } - - // What mini_al calls a fragment, audio4 calls a block. - mal_uint32 bufferSizeInBytes = pDevice->bufferSizeInFrames * mal_get_bytes_per_frame(pDevice->internalFormat, pDevice->internalChannels); - if (bufferSizeInBytes < 16) { - bufferSizeInBytes = 16; - } - - fdPar.nblks = pDevice->periods; - fdPar.round = bufferSizeInBytes / fdPar.nblks; - - if (ioctl(pDevice->audio4.fd, AUDIO_SETPAR, &fdPar) < 0) { - close(pDevice->audio4.fd); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[audio4] Failed to set device parameters.", MAL_FORMAT_NOT_SUPPORTED); - } - - if (ioctl(pDevice->audio4.fd, AUDIO_GETPAR, &fdPar) < 0) { - close(pDevice->audio4.fd); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[audio4] Failed to retrieve actual device parameters.", MAL_FORMAT_NOT_SUPPORTED); - } - - pDevice->internalFormat = mal_format_from_swpar__audio4(&fdPar); - if (deviceType == mal_device_type_playback) { - pDevice->internalChannels = fdPar.pchan; - } else { - pDevice->internalChannels = fdPar.rchan; - } - pDevice->internalSampleRate = fdPar.rate; - - pDevice->periods = fdPar.nblks; - pDevice->bufferSizeInFrames = (fdPar.nblks * fdPar.round) / mal_get_bytes_per_frame(pDevice->internalFormat, pDevice->internalChannels); - pDevice->audio4.fragmentSizeInFrames = fdPar.round / mal_get_bytes_per_frame(pDevice->internalFormat, pDevice->internalChannels); -#endif - - - // For the channel map, I'm not sure how to query the channel map (or if it's even possible). I'm just - // using the channels defined in FreeBSD's sound(4) man page. - mal_get_standard_channel_map(mal_standard_channel_map_sound4, pDevice->internalChannels, pDevice->internalChannelMap); - - - // The version of the operating system dictates whether or not the device is exclusive or shared. NetBSD - // introduced in-kernel mixing which means it's shared. All other BSD flavours are exclusive as far as - // I'm aware. -#if defined(__NetBSD_Version__) && __NetBSD_Version__ >= 800000000 - pDevice->exclusiveMode = MAL_FALSE; -#else - pDevice->exclusiveMode = MAL_TRUE; -#endif - - - // When not using MMAP mode we need to use an intermediary buffer to the data transfer between the client - // and device. Everything is done by the size of a fragment. - pDevice->audio4.pIntermediaryBuffer = mal_malloc(pDevice->audio4.fragmentSizeInFrames * mal_get_bytes_per_frame(pDevice->internalFormat, pDevice->internalChannels)); - if (pDevice->audio4.pIntermediaryBuffer == NULL) { - close(pDevice->audio4.fd); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[audio4] Failed to allocate memory for intermediary buffer.", MAL_OUT_OF_MEMORY); - } - - - return MAL_SUCCESS; -} - -mal_result mal_device_start__audio4(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - if (pDevice->audio4.fd == -1) { - return MAL_INVALID_ARGS; - } - - // The device is started by the next calls to read() and write(). For playback it's simple - just read - // data from the client, then write it to the device with write() which will in turn start the device. - // For capture it's a bit less intuitive - we do nothing (it'll be started automatically by the first - // call to read(). - if (pDevice->type == mal_device_type_playback) { - // Playback. Need to load the entire buffer, which means we need to write a fragment for each period. - for (mal_uint32 iPeriod = 0; iPeriod < pDevice->periods; iPeriod += 1) { - mal_device__read_frames_from_client(pDevice, pDevice->audio4.fragmentSizeInFrames, pDevice->audio4.pIntermediaryBuffer); - - int bytesWritten = write(pDevice->audio4.fd, pDevice->audio4.pIntermediaryBuffer, pDevice->audio4.fragmentSizeInFrames * mal_get_bytes_per_frame(pDevice->internalFormat, pDevice->internalChannels)); - if (bytesWritten == -1) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[audio4] Failed to send initial chunk of data to the device.", MAL_FAILED_TO_SEND_DATA_TO_DEVICE); - } - } - } else { - // Capture. Do nothing. - } - - return MAL_SUCCESS; -} - -mal_result mal_device_stop__audio4(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - if (pDevice->audio4.fd == -1) { - return MAL_INVALID_ARGS; - } - -#if !defined(MAL_AUDIO4_USE_NEW_API) - if (ioctl(pDevice->audio4.fd, AUDIO_FLUSH, 0) < 0) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[audio4] Failed to stop device. AUDIO_FLUSH failed.", MAL_FAILED_TO_STOP_BACKEND_DEVICE); - } -#else - if (ioctl(pDevice->audio4.fd, AUDIO_STOP, 0) < 0) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[audio4] Failed to stop device. AUDIO_STOP failed.", MAL_FAILED_TO_STOP_BACKEND_DEVICE); - } -#endif - - return MAL_SUCCESS; -} - -mal_result mal_device_break_main_loop__audio4(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - pDevice->audio4.breakFromMainLoop = MAL_TRUE; - return MAL_SUCCESS; -} - -mal_result mal_device__wait__audio4(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - struct pollfd fds[1]; - fds[0].fd = pDevice->audio4.fd; - fds[0].events = (pDevice->type == mal_device_type_playback) ? (POLLOUT | POLLWRBAND) : (POLLIN | POLLPRI); - int timeout = 2 * 1000; - int ioresult = poll(fds, mal_countof(fds), timeout); - if (ioresult < 0) { - #ifdef MAL_DEBUG_OUTPUT - printf("poll() failed: timeout=%d, ioresult=%d\n", pDevice->bufferSizeInMilliseconds, ioresult); - #endif - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[audio4] Failed to wait for device.", MAL_ERROR); - } - - // Check for a timeout. This has been annoying in my testing. In my testing, when the device is unplugged it will just - // hang on the next calls to write(), ioctl(), etc. The only way I have figured out how to handle this is to wait for - // a timeout from poll(). In the unplugging case poll() will timeout, however there's no indication that the device is - // unusable - no flags are set, no errors are reported, nothing. To work around this I have decided to outright fail - // in the event of a timeout. - if (ioresult == 0) { - // Check for errors. - if ((fds[0].revents & (POLLERR | POLLNVAL)) != 0) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[audio4] Failed to wait for device.", MAL_NO_DEVICE); - } - if ((fds[0].revents & (POLLHUP)) != 0) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[audio4] Failed to wait for device. Disconnected.", MAL_NO_DEVICE); - } - - // A return value of 0 from poll indicates a timeout. - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[audio4] Timeout while waiting for device.", MAL_TIMEOUT); - } - - mal_assert(ioresult > 0); - return MAL_SUCCESS; -} - -mal_result mal_device_main_loop__audio4(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - pDevice->audio4.breakFromMainLoop = MAL_FALSE; - while (!pDevice->audio4.breakFromMainLoop) { - // Break from the main loop if the device isn't started anymore. Likely what's happened is the application - // has requested that the device be stopped. - if (!mal_device_is_started(pDevice)) { - break; - } - - if (pDevice->type == mal_device_type_playback) { - // Playback. - mal_device__read_frames_from_client(pDevice, pDevice->audio4.fragmentSizeInFrames, pDevice->audio4.pIntermediaryBuffer); - - // Wait for data to become available. - mal_result result = mal_device__wait__audio4(pDevice); - if (result != MAL_SUCCESS) { - return result; - } - - size_t bytesToWrite = pDevice->audio4.fragmentSizeInFrames * mal_get_bytes_per_frame(pDevice->internalFormat, pDevice->internalChannels); - while (bytesToWrite > 0) { - ssize_t bytesWritten = write(pDevice->audio4.fd, pDevice->audio4.pIntermediaryBuffer, bytesToWrite); - if (bytesWritten < 0) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[audio4] Failed to send data from the client to the device.", MAL_FAILED_TO_SEND_DATA_TO_DEVICE); - } - - if (bytesWritten == 0) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[audio4] Failed to write any data to the device.", MAL_FAILED_TO_SEND_DATA_TO_DEVICE); - } - - bytesToWrite -= bytesWritten; - } - } else { - // Capture. - mal_result result = mal_device__wait__audio4(pDevice); - if (result != MAL_SUCCESS) { - return result; - } - - size_t totalBytesRead = 0; - size_t bytesToRead = pDevice->audio4.fragmentSizeInFrames * mal_get_bytes_per_frame(pDevice->internalFormat, pDevice->internalChannels); - while (bytesToRead > 0) { - ssize_t bytesRead = read(pDevice->audio4.fd, pDevice->audio4.pIntermediaryBuffer, bytesToRead); - if (bytesRead < 0) { - if (errno == EAGAIN) { - break; - } - - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[audio4] Failed to read data from the device to be sent to the client.", MAL_FAILED_TO_READ_DATA_FROM_DEVICE); - } - - if (bytesRead == 0) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[audio4] Failed to read any data from the device.", MAL_FAILED_TO_READ_DATA_FROM_DEVICE); - } - - bytesToRead -= bytesRead; - totalBytesRead += bytesRead; - } - - mal_uint32 framesRead = (mal_uint32)totalBytesRead / mal_get_bytes_per_frame(pDevice->internalFormat, pDevice->internalChannels); - mal_device__send_frames_to_client(pDevice, framesRead, pDevice->audio4.pIntermediaryBuffer); - } - } - - return MAL_SUCCESS; -} - -mal_result mal_context_uninit__audio4(mal_context* pContext) -{ - mal_assert(pContext != NULL); - mal_assert(pContext->backend == mal_backend_audio4); - - (void)pContext; - return MAL_SUCCESS; -} - -mal_result mal_context_init__audio4(mal_context* pContext) -{ - mal_assert(pContext != NULL); - - pContext->onUninit = mal_context_uninit__audio4; - pContext->onDeviceIDEqual = mal_context_is_device_id_equal__audio4; - pContext->onEnumDevices = mal_context_enumerate_devices__audio4; - pContext->onGetDeviceInfo = mal_context_get_device_info__audio4; - pContext->onDeviceInit = mal_device_init__audio4; - pContext->onDeviceUninit = mal_device_uninit__audio4; - pContext->onDeviceStart = mal_device_start__audio4; - pContext->onDeviceStop = mal_device_stop__audio4; - pContext->onDeviceBreakMainLoop = mal_device_break_main_loop__audio4; - pContext->onDeviceMainLoop = mal_device_main_loop__audio4; - - return MAL_SUCCESS; -} -#endif // audio4 - - -/////////////////////////////////////////////////////////////////////////////// -// -// OSS Backend -// -/////////////////////////////////////////////////////////////////////////////// -#ifdef MAL_HAS_OSS -#include -#include -#include -#include - -#ifndef SNDCTL_DSP_HALT -#define SNDCTL_DSP_HALT SNDCTL_DSP_RESET -#endif - -int mal_open_temp_device__oss() -{ - // The OSS sample code uses "/dev/mixer" as the device for getting system properties so I'm going to do the same. - int fd = open("/dev/mixer", O_RDONLY, 0); - if (fd >= 0) { - return fd; - } - - return -1; -} - -mal_result mal_context_open_device__oss(mal_context* pContext, mal_device_type type, const mal_device_id* pDeviceID, int* pfd) -{ - mal_assert(pContext != NULL); - mal_assert(pfd != NULL); - (void)pContext; - - *pfd = -1; - - char deviceName[64]; - if (pDeviceID != NULL) { - mal_strncpy_s(deviceName, sizeof(deviceName), pDeviceID->oss, (size_t)-1); - } else { - mal_strncpy_s(deviceName, sizeof(deviceName), "/dev/dsp", (size_t)-1); - } - - *pfd = open(deviceName, (type == mal_device_type_playback) ? O_WRONLY : O_RDONLY, 0); - if (*pfd == -1) { - return MAL_FAILED_TO_OPEN_BACKEND_DEVICE; - } - - return MAL_SUCCESS; -} - -mal_bool32 mal_context_is_device_id_equal__oss(mal_context* pContext, const mal_device_id* pID0, const mal_device_id* pID1) -{ - mal_assert(pContext != NULL); - mal_assert(pID0 != NULL); - mal_assert(pID1 != NULL); - (void)pContext; - - return mal_strcmp(pID0->oss, pID1->oss) == 0; -} - -mal_result mal_context_enumerate_devices__oss(mal_context* pContext, mal_enum_devices_callback_proc callback, void* pUserData) -{ - mal_assert(pContext != NULL); - mal_assert(callback != NULL); - - int fd = mal_open_temp_device__oss(); - if (fd == -1) { - return mal_context_post_error(pContext, NULL, MAL_LOG_LEVEL_ERROR, "[OSS] Failed to open a temporary device for retrieving system information used for device enumeration.", MAL_NO_BACKEND); - } - - oss_sysinfo si; - int result = ioctl(fd, SNDCTL_SYSINFO, &si); - if (result != -1) { - for (int iAudioDevice = 0; iAudioDevice < si.numaudios; ++iAudioDevice) { - oss_audioinfo ai; - ai.dev = iAudioDevice; - result = ioctl(fd, SNDCTL_AUDIOINFO, &ai); - if (result != -1) { - if (ai.devnode[0] != '\0') { // <-- Can be blank, according to documentation. - mal_device_info deviceInfo; - mal_zero_object(&deviceInfo); - - // ID - mal_strncpy_s(deviceInfo.id.oss, sizeof(deviceInfo.id.oss), ai.devnode, (size_t)-1); - - // The human readable device name should be in the "ai.handle" variable, but it can - // sometimes be empty in which case we just fall back to "ai.name" which is less user - // friendly, but usually has a value. - if (ai.handle[0] != '\0') { - mal_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), ai.handle, (size_t)-1); - } else { - mal_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), ai.name, (size_t)-1); - } - - // The device can be both playback and capture. - mal_bool32 isTerminating = MAL_FALSE; - if (!isTerminating && (ai.caps & PCM_CAP_OUTPUT) != 0) { - isTerminating = !callback(pContext, mal_device_type_playback, &deviceInfo, pUserData); - } - if (!isTerminating && (ai.caps & PCM_CAP_INPUT) != 0) { - isTerminating = !callback(pContext, mal_device_type_capture, &deviceInfo, pUserData); - } - - if (isTerminating) { - break; - } - } - } - } - } else { - close(fd); - return mal_context_post_error(pContext, NULL, MAL_LOG_LEVEL_ERROR, "[OSS] Failed to retrieve system information for device enumeration.", MAL_NO_BACKEND); - } - - close(fd); - return MAL_SUCCESS; -} - -mal_result mal_context_get_device_info__oss(mal_context* pContext, mal_device_type deviceType, const mal_device_id* pDeviceID, mal_share_mode shareMode, mal_device_info* pDeviceInfo) -{ - mal_assert(pContext != NULL); - (void)shareMode; - - // Handle the default device a little differently. - if (pDeviceID == NULL) { - if (deviceType == mal_device_type_playback) { - mal_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MAL_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); - } else { - mal_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MAL_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); - } - - return MAL_SUCCESS; - } - - - // If we get here it means we are _not_ using the default device. - mal_bool32 foundDevice = MAL_FALSE; - - int fdTemp = mal_open_temp_device__oss(); - if (fdTemp == -1) { - return mal_context_post_error(pContext, NULL, MAL_LOG_LEVEL_ERROR, "[OSS] Failed to open a temporary device for retrieving system information used for device enumeration.", MAL_NO_BACKEND); - } - - oss_sysinfo si; - int result = ioctl(fdTemp, SNDCTL_SYSINFO, &si); - if (result != -1) { - for (int iAudioDevice = 0; iAudioDevice < si.numaudios; ++iAudioDevice) { - oss_audioinfo ai; - ai.dev = iAudioDevice; - result = ioctl(fdTemp, SNDCTL_AUDIOINFO, &ai); - if (result != -1) { - if (mal_strcmp(ai.devnode, pDeviceID->oss) == 0) { - // It has the same name, so now just confirm the type. - if ((deviceType == mal_device_type_playback && ((ai.caps & PCM_CAP_OUTPUT) != 0)) || - (deviceType == mal_device_type_capture && ((ai.caps & PCM_CAP_INPUT) != 0))) { - // ID - mal_strncpy_s(pDeviceInfo->id.oss, sizeof(pDeviceInfo->id.oss), ai.devnode, (size_t)-1); - - // The human readable device name should be in the "ai.handle" variable, but it can - // sometimes be empty in which case we just fall back to "ai.name" which is less user - // friendly, but usually has a value. - if (ai.handle[0] != '\0') { - mal_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), ai.handle, (size_t)-1); - } else { - mal_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), ai.name, (size_t)-1); - } - - pDeviceInfo->minChannels = ai.min_channels; - pDeviceInfo->maxChannels = ai.max_channels; - pDeviceInfo->minSampleRate = ai.min_rate; - pDeviceInfo->maxSampleRate = ai.max_rate; - pDeviceInfo->formatCount = 0; - - unsigned int formatMask; - if (deviceType == mal_device_type_playback) { - formatMask = ai.oformats; - } else { - formatMask = ai.iformats; - } - - if ((formatMask & AFMT_U8) != 0) { - pDeviceInfo->formats[pDeviceInfo->formatCount++] = mal_format_u8; - } - if (((formatMask & AFMT_S16_LE) != 0 && mal_is_little_endian()) || (AFMT_S16_BE && mal_is_big_endian())) { - pDeviceInfo->formats[pDeviceInfo->formatCount++] = mal_format_s16; - } - if (((formatMask & AFMT_S32_LE) != 0 && mal_is_little_endian()) || (AFMT_S32_BE && mal_is_big_endian())) { - pDeviceInfo->formats[pDeviceInfo->formatCount++] = mal_format_s32; - } - - foundDevice = MAL_TRUE; - break; - } - } - } - } - } else { - close(fdTemp); - return mal_context_post_error(pContext, NULL, MAL_LOG_LEVEL_ERROR, "[OSS] Failed to retrieve system information for device enumeration.", MAL_NO_BACKEND); - } - - - close(fdTemp); - - if (!foundDevice) { - return MAL_NO_DEVICE; - } - - - return MAL_SUCCESS; -} - -void mal_device_uninit__oss(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - close(pDevice->oss.fd); - mal_free(pDevice->oss.pIntermediaryBuffer); -} - -mal_result mal_device_init__oss(mal_context* pContext, mal_device_type type, const mal_device_id* pDeviceID, const mal_device_config* pConfig, mal_device* pDevice) -{ - (void)pContext; - - mal_assert(pDevice != NULL); - mal_zero_object(&pDevice->oss); - - mal_result result = mal_context_open_device__oss(pContext, type, pDeviceID, &pDevice->oss.fd); - if (result != MAL_SUCCESS) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[OSS] Failed to open device.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - - // The OSS documantation is very clear about the order we should be initializing the device's properties: - // 1) Format - // 2) Channels - // 3) Sample rate. - - // Format. - int ossFormat = AFMT_U8; - switch (pDevice->format) { - case mal_format_s16: ossFormat = (mal_is_little_endian()) ? AFMT_S16_LE : AFMT_S16_BE; break; - case mal_format_s24: ossFormat = (mal_is_little_endian()) ? AFMT_S32_LE : AFMT_S32_BE; break; - case mal_format_s32: ossFormat = (mal_is_little_endian()) ? AFMT_S32_LE : AFMT_S32_BE; break; - case mal_format_f32: ossFormat = (mal_is_little_endian()) ? AFMT_S32_LE : AFMT_S32_BE; break; - case mal_format_u8: - default: ossFormat = AFMT_U8; break; - } - int ossResult = ioctl(pDevice->oss.fd, SNDCTL_DSP_SETFMT, &ossFormat); - if (ossResult == -1) { - close(pDevice->oss.fd); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[OSS] Failed to set format.", MAL_FORMAT_NOT_SUPPORTED); - } - - if (ossFormat == AFMT_U8) { - pDevice->internalFormat = mal_format_u8; - } else { - if (mal_is_little_endian()) { - switch (ossFormat) { - case AFMT_S16_LE: pDevice->internalFormat = mal_format_s16; break; - case AFMT_S32_LE: pDevice->internalFormat = mal_format_s32; break; - default: mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[OSS] The device's internal format is not supported by mini_al.", MAL_FORMAT_NOT_SUPPORTED); - } - } else { - switch (ossFormat) { - case AFMT_S16_BE: pDevice->internalFormat = mal_format_s16; break; - case AFMT_S32_BE: pDevice->internalFormat = mal_format_s32; break; - default: mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[OSS] The device's internal format is not supported by mini_al.", MAL_FORMAT_NOT_SUPPORTED); - } - } - } - - // Channels. - int ossChannels = (int)pConfig->channels; - ossResult = ioctl(pDevice->oss.fd, SNDCTL_DSP_CHANNELS, &ossChannels); - if (ossResult == -1) { - close(pDevice->oss.fd); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[OSS] Failed to set channel count.", MAL_FORMAT_NOT_SUPPORTED); - } - - pDevice->internalChannels = ossChannels; - - - // Sample rate. - int ossSampleRate = (int)pConfig->sampleRate; - ossResult = ioctl(pDevice->oss.fd, SNDCTL_DSP_SPEED, &ossSampleRate); - if (ossResult == -1) { - close(pDevice->oss.fd); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[OSS] Failed to set sample rate.", MAL_FORMAT_NOT_SUPPORTED); - } - - pDevice->internalSampleRate = ossSampleRate; - - - // Try calculating an appropriate default buffer size. - if (pDevice->bufferSizeInFrames == 0) { - pDevice->bufferSizeInFrames = mal_calculate_buffer_size_in_frames_from_milliseconds(pDevice->bufferSizeInMilliseconds, pDevice->internalSampleRate); - } - - // The documentation says that the fragment settings should be set as soon as possible, but I'm not sure if - // it should be done before or after format/channels/rate. - // - // OSS wants the fragment size in bytes and a power of 2. When setting, we specify the power, not the actual - // value. - mal_uint32 fragmentSizeInBytes = mal_round_to_power_of_2(pDevice->bufferSizeInFrames * pDevice->internalChannels * mal_get_bytes_per_sample(pDevice->internalFormat)); - if (fragmentSizeInBytes < 16) { - fragmentSizeInBytes = 16; - } - - mal_uint32 ossFragmentSizePower = 4; - fragmentSizeInBytes >>= 4; - while (fragmentSizeInBytes >>= 1) { - ossFragmentSizePower += 1; - } - - int ossFragment = (int)((pDevice->periods << 16) | ossFragmentSizePower); - ossResult = ioctl(pDevice->oss.fd, SNDCTL_DSP_SETFRAGMENT, &ossFragment); - if (ossResult == -1) { - close(pDevice->oss.fd); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[OSS] Failed to set fragment size and period count.", MAL_FORMAT_NOT_SUPPORTED); - } - - int actualFragmentSizeInBytes = 1 << (ossFragment & 0xFFFF); - pDevice->oss.fragmentSizeInFrames = actualFragmentSizeInBytes / mal_get_bytes_per_sample(pDevice->internalFormat) / pDevice->internalChannels; - - pDevice->periods = (mal_uint32)(ossFragment >> 16); - pDevice->bufferSizeInFrames = (mal_uint32)(pDevice->oss.fragmentSizeInFrames * pDevice->periods); - - // Set the internal channel map. Not sure if this can be queried. For now just using the channel layouts defined in FreeBSD's sound(4) man page. - mal_get_standard_channel_map(mal_standard_channel_map_sound4, pDevice->internalChannels, pDevice->internalChannelMap); - - // OSS seems to be shared. - pDevice->exclusiveMode = MAL_FALSE; - - // When not using MMAP mode, we need to use an intermediary buffer for the client <-> device transfer. We do - // everything by the size of a fragment. - pDevice->oss.pIntermediaryBuffer = mal_malloc(actualFragmentSizeInBytes); - if (pDevice->oss.pIntermediaryBuffer == NULL) { - close(pDevice->oss.fd); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[OSS] Failed to allocate memory for intermediary buffer.", MAL_OUT_OF_MEMORY); - } - - return MAL_SUCCESS; -} - - -mal_result mal_device_start__oss(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - // The device is started by the next calls to read() and write(). For playback it's simple - just read - // data from the client, then write it to the device with write() which will in turn start the device. - // For capture it's a bit less intuitive - we do nothing (it'll be started automatically by the first - // call to read(). - if (pDevice->type == mal_device_type_playback) { - // Playback. - mal_device__read_frames_from_client(pDevice, pDevice->oss.fragmentSizeInFrames, pDevice->oss.pIntermediaryBuffer); - - int bytesWritten = write(pDevice->oss.fd, pDevice->oss.pIntermediaryBuffer, pDevice->oss.fragmentSizeInFrames * pDevice->internalChannels * mal_get_bytes_per_sample(pDevice->internalFormat)); - if (bytesWritten == -1) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[OSS] Failed to send initial chunk of data to the device.", MAL_FAILED_TO_SEND_DATA_TO_DEVICE); - } - } else { - // Capture. Do nothing. - } - - return MAL_SUCCESS; -} - -mal_result mal_device_stop__oss(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - // We want to use SNDCTL_DSP_HALT. From the documentation: - // - // In multithreaded applications SNDCTL_DSP_HALT (SNDCTL_DSP_RESET) must only be called by the thread - // that actually reads/writes the audio device. It must not be called by some master thread to kill the - // audio thread. The audio thread will not stop or get any kind of notification that the device was - // stopped by the master thread. The device gets stopped but the next read or write call will silently - // restart the device. - // - // This is actually safe in our case, because this function is only ever called from within our worker - // thread anyway. Just keep this in mind, though... - - int result = ioctl(pDevice->oss.fd, SNDCTL_DSP_HALT, 0); - if (result == -1) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[OSS] Failed to stop device. SNDCTL_DSP_HALT failed.", MAL_FAILED_TO_STOP_BACKEND_DEVICE); - } - - return MAL_SUCCESS; -} - -mal_result mal_device_break_main_loop__oss(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - pDevice->oss.breakFromMainLoop = MAL_TRUE; - return MAL_SUCCESS; -} - -mal_result mal_device_main_loop__oss(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - pDevice->oss.breakFromMainLoop = MAL_FALSE; - while (!pDevice->oss.breakFromMainLoop) { - // Break from the main loop if the device isn't started anymore. Likely what's happened is the application - // has requested that the device be stopped. - if (!mal_device_is_started(pDevice)) { - break; - } - - if (pDevice->type == mal_device_type_playback) { - // Playback. - mal_device__read_frames_from_client(pDevice, pDevice->oss.fragmentSizeInFrames, pDevice->oss.pIntermediaryBuffer); - - int bytesWritten = write(pDevice->oss.fd, pDevice->oss.pIntermediaryBuffer, pDevice->oss.fragmentSizeInFrames * pDevice->internalChannels * mal_get_bytes_per_sample(pDevice->internalFormat)); - if (bytesWritten < 0) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[OSS] Failed to send data from the client to the device.", MAL_FAILED_TO_SEND_DATA_TO_DEVICE); - } - } else { - // Capture. - int bytesRead = read(pDevice->oss.fd, pDevice->oss.pIntermediaryBuffer, pDevice->oss.fragmentSizeInFrames * mal_get_bytes_per_sample(pDevice->internalFormat)); - if (bytesRead < 0) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[OSS] Failed to read data from the device to be sent to the client.", MAL_FAILED_TO_READ_DATA_FROM_DEVICE); - } - - mal_uint32 framesRead = (mal_uint32)bytesRead / pDevice->internalChannels / mal_get_bytes_per_sample(pDevice->internalFormat); - mal_device__send_frames_to_client(pDevice, framesRead, pDevice->oss.pIntermediaryBuffer); - } - } - - return MAL_SUCCESS; -} - -mal_result mal_context_uninit__oss(mal_context* pContext) -{ - mal_assert(pContext != NULL); - mal_assert(pContext->backend == mal_backend_oss); - - (void)pContext; - return MAL_SUCCESS; -} - -mal_result mal_context_init__oss(mal_context* pContext) -{ - mal_assert(pContext != NULL); - - // Try opening a temporary device first so we can get version information. This is closed at the end. - int fd = mal_open_temp_device__oss(); - if (fd == -1) { - return mal_context_post_error(pContext, NULL, MAL_LOG_LEVEL_ERROR, "[OSS] Failed to open temporary device for retrieving system properties.", MAL_NO_BACKEND); // Looks liks OSS isn't installed, or there are no available devices. - } - - // Grab the OSS version. - int ossVersion = 0; - int result = ioctl(fd, OSS_GETVERSION, &ossVersion); - if (result == -1) { - close(fd); - return mal_context_post_error(pContext, NULL, MAL_LOG_LEVEL_ERROR, "[OSS] Failed to retrieve OSS version.", MAL_NO_BACKEND); - } - - pContext->oss.versionMajor = ((ossVersion & 0xFF0000) >> 16); - pContext->oss.versionMinor = ((ossVersion & 0x00FF00) >> 8); - - pContext->onUninit = mal_context_uninit__oss; - pContext->onDeviceIDEqual = mal_context_is_device_id_equal__oss; - pContext->onEnumDevices = mal_context_enumerate_devices__oss; - pContext->onGetDeviceInfo = mal_context_get_device_info__oss; - pContext->onDeviceInit = mal_device_init__oss; - pContext->onDeviceUninit = mal_device_uninit__oss; - pContext->onDeviceStart = mal_device_start__oss; - pContext->onDeviceStop = mal_device_stop__oss; - pContext->onDeviceBreakMainLoop = mal_device_break_main_loop__oss; - pContext->onDeviceMainLoop = mal_device_main_loop__oss; - - close(fd); - return MAL_SUCCESS; -} -#endif // OSS - - -/////////////////////////////////////////////////////////////////////////////// -// -// AAudio Backend -// -/////////////////////////////////////////////////////////////////////////////// -#ifdef MAL_HAS_AAUDIO -//#include - -#define MAL_AAUDIO_UNSPECIFIED 0 - -typedef int32_t mal_aaudio_result_t; -typedef int32_t mal_aaudio_direction_t; -typedef int32_t mal_aaudio_sharing_mode_t; -typedef int32_t mal_aaudio_format_t; -typedef int32_t mal_aaudio_stream_state_t; -typedef int32_t mal_aaudio_performance_mode_t; -typedef int32_t mal_aaudio_data_callback_result_t; - -/* Result codes. mini_al only cares about the success code. */ -#define MAL_AAUDIO_OK 0 - -/* Directions. */ -#define MAL_AAUDIO_DIRECTION_OUTPUT 0 -#define MAL_AAUDIO_DIRECTION_INPUT 1 - -/* Sharing modes. */ -#define MAL_AAUDIO_SHARING_MODE_EXCLUSIVE 0 -#define MAL_AAUDIO_SHARING_MODE_SHARED 1 - -/* Formats. */ -#define MAL_AAUDIO_FORMAT_PCM_I16 1 -#define MAL_AAUDIO_FORMAT_PCM_FLOAT 2 - -/* Stream states. */ -#define MAL_AAUDIO_STREAM_STATE_UNINITIALIZED 0 -#define MAL_AAUDIO_STREAM_STATE_UNKNOWN 1 -#define MAL_AAUDIO_STREAM_STATE_OPEN 2 -#define MAL_AAUDIO_STREAM_STATE_STARTING 3 -#define MAL_AAUDIO_STREAM_STATE_STARTED 4 -#define MAL_AAUDIO_STREAM_STATE_PAUSING 5 -#define MAL_AAUDIO_STREAM_STATE_PAUSED 6 -#define MAL_AAUDIO_STREAM_STATE_FLUSHING 7 -#define MAL_AAUDIO_STREAM_STATE_FLUSHED 8 -#define MAL_AAUDIO_STREAM_STATE_STOPPING 9 -#define MAL_AAUDIO_STREAM_STATE_STOPPED 10 -#define MAL_AAUDIO_STREAM_STATE_CLOSING 11 -#define MAL_AAUDIO_STREAM_STATE_CLOSED 12 -#define MAL_AAUDIO_STREAM_STATE_DISCONNECTED 13 - -/* Performance modes. */ -#define MAL_AAUDIO_PERFORMANCE_MODE_NONE 10 -#define MAL_AAUDIO_PERFORMANCE_MODE_POWER_SAVING 11 -#define MAL_AAUDIO_PERFORMANCE_MODE_LOW_LATENCY 12 - -/* Callback results. */ -#define MAL_AAUDIO_CALLBACK_RESULT_CONTINUE 0 -#define MAL_AAUDIO_CALLBACK_RESULT_STOP 1 - -/* Objects. */ -typedef struct mal_AAudioStreamBuilder_t* mal_AAudioStreamBuilder; -typedef struct mal_AAudioStream_t* mal_AAudioStream; - -typedef mal_aaudio_data_callback_result_t (*mal_AAudioStream_dataCallback)(mal_AAudioStream* pStream, void* pUserData, void* pAudioData, int32_t numFrames); - -typedef mal_aaudio_result_t (* MAL_PFN_AAudio_createStreamBuilder) (mal_AAudioStreamBuilder** ppBuilder); -typedef mal_aaudio_result_t (* MAL_PFN_AAudioStreamBuilder_delete) (mal_AAudioStreamBuilder* pBuilder); -typedef void (* MAL_PFN_AAudioStreamBuilder_setDeviceId) (mal_AAudioStreamBuilder* pBuilder, int32_t deviceId); -typedef void (* MAL_PFN_AAudioStreamBuilder_setDirection) (mal_AAudioStreamBuilder* pBuilder, mal_aaudio_direction_t direction); -typedef void (* MAL_PFN_AAudioStreamBuilder_setSharingMode) (mal_AAudioStreamBuilder* pBuilder, mal_aaudio_sharing_mode_t sharingMode); -typedef void (* MAL_PFN_AAudioStreamBuilder_setFormat) (mal_AAudioStreamBuilder* pBuilder, mal_aaudio_format_t format); -typedef void (* MAL_PFN_AAudioStreamBuilder_setChannelCount) (mal_AAudioStreamBuilder* pBuilder, int32_t channelCount); -typedef void (* MAL_PFN_AAudioStreamBuilder_setSampleRate) (mal_AAudioStreamBuilder* pBuilder, int32_t sampleRate); -typedef void (* MAL_PFN_AAudioStreamBuilder_setBufferCapacityInFrames)(mal_AAudioStreamBuilder* pBuilder, int32_t numFrames); -typedef void (* MAL_PFN_AAudioStreamBuilder_setFramesPerDataCallback) (mal_AAudioStreamBuilder* pBuilder, int32_t numFrames); -typedef void (* MAL_PFN_AAudioStreamBuilder_setDataCallback) (mal_AAudioStreamBuilder* pBuilder, mal_AAudioStream_dataCallback callback, void* pUserData); -typedef void (* MAL_PFN_AAudioStreamBuilder_setPerformanceMode) (mal_AAudioStreamBuilder* pBuilder, mal_aaudio_performance_mode_t mode); -typedef mal_aaudio_result_t (* MAL_PFN_AAudioStreamBuilder_openStream) (mal_AAudioStreamBuilder* pBuilder, mal_AAudioStream** ppStream); -typedef mal_aaudio_result_t (* MAL_PFN_AAudioStream_close) (mal_AAudioStream* pStream); -typedef mal_aaudio_stream_state_t (* MAL_PFN_AAudioStream_getState) (mal_AAudioStream* pStream); -typedef mal_aaudio_result_t (* MAL_PFN_AAudioStream_waitForStateChange) (mal_AAudioStream* pStream, mal_aaudio_stream_state_t inputState, mal_aaudio_stream_state_t* pNextState, int64_t timeoutInNanoseconds); -typedef mal_aaudio_format_t (* MAL_PFN_AAudioStream_getFormat) (mal_AAudioStream* pStream); -typedef int32_t (* MAL_PFN_AAudioStream_getChannelCount) (mal_AAudioStream* pStream); -typedef int32_t (* MAL_PFN_AAudioStream_getSampleRate) (mal_AAudioStream* pStream); -typedef int32_t (* MAL_PFN_AAudioStream_getBufferCapacityInFrames) (mal_AAudioStream* pStream); -typedef int32_t (* MAL_PFN_AAudioStream_getFramesPerDataCallback) (mal_AAudioStream* pStream); -typedef int32_t (* MAL_PFN_AAudioStream_getFramesPerBurst) (mal_AAudioStream* pStream); -typedef mal_aaudio_result_t (* MAL_PFN_AAudioStream_requestStart) (mal_AAudioStream* pStream); -typedef mal_aaudio_result_t (* MAL_PFN_AAudioStream_requestStop) (mal_AAudioStream* pStream); - -mal_result mal_result_from_aaudio(mal_aaudio_result_t resultAA) -{ - switch (resultAA) - { - case MAL_AAUDIO_OK: return MAL_SUCCESS; - default: break; - } - - return MAL_ERROR; -} - -mal_aaudio_data_callback_result_t mal_stream_data_callback__aaudio(mal_AAudioStream* pStream, void* pUserData, void* pAudioData, int32_t frameCount) -{ - mal_device* pDevice = (mal_device*)pUserData; - mal_assert(pDevice != NULL); - - (void)pStream; - - if (pDevice->type == mal_device_type_playback) { - mal_device__read_frames_from_client(pDevice, frameCount, pAudioData); - } else { - mal_device__send_frames_to_client(pDevice, frameCount, pAudioData); - } - - return MAL_AAUDIO_CALLBACK_RESULT_CONTINUE; -} - -mal_result mal_open_stream__aaudio(mal_context* pContext, mal_device_type deviceType, const mal_device_id* pDeviceID, mal_share_mode shareMode, const mal_device_config* pConfig, const mal_device* pDevice, mal_AAudioStream** ppStream) -{ - mal_AAudioStreamBuilder* pBuilder; - mal_aaudio_result_t resultAA; - - (void)pContext; - *ppStream = NULL; - - resultAA = ((MAL_PFN_AAudio_createStreamBuilder)pContext->aaudio.AAudio_createStreamBuilder)(&pBuilder); - if (resultAA != MAL_AAUDIO_OK) { - return mal_result_from_aaudio(resultAA); - } - - if (pDeviceID != NULL) { - ((MAL_PFN_AAudioStreamBuilder_setDeviceId)pContext->aaudio.AAudioStreamBuilder_setDeviceId)(pBuilder, pDeviceID->aaudio); - } - - ((MAL_PFN_AAudioStreamBuilder_setDirection)pContext->aaudio.AAudioStreamBuilder_setDirection)(pBuilder, (deviceType == mal_device_type_playback) ? MAL_AAUDIO_DIRECTION_OUTPUT : MAL_AAUDIO_DIRECTION_INPUT); - ((MAL_PFN_AAudioStreamBuilder_setSharingMode)pContext->aaudio.AAudioStreamBuilder_setSharingMode)(pBuilder, (shareMode == mal_share_mode_shared) ? MAL_AAUDIO_SHARING_MODE_SHARED : MAL_AAUDIO_SHARING_MODE_EXCLUSIVE); - - if (pConfig != NULL) { - if (pDevice == NULL || !pDevice->usingDefaultSampleRate) { - ((MAL_PFN_AAudioStreamBuilder_setSampleRate)pContext->aaudio.AAudioStreamBuilder_setSampleRate)(pBuilder, pConfig->sampleRate); - } - if (pDevice == NULL || !pDevice->usingDefaultChannels) { - ((MAL_PFN_AAudioStreamBuilder_setChannelCount)pContext->aaudio.AAudioStreamBuilder_setChannelCount)(pBuilder, pConfig->channels); - } - if (pDevice == NULL || !pDevice->usingDefaultFormat) { - ((MAL_PFN_AAudioStreamBuilder_setFormat)pContext->aaudio.AAudioStreamBuilder_setFormat)(pBuilder, (pConfig->format == mal_format_s16) ? MAL_AAUDIO_FORMAT_PCM_I16 : MAL_AAUDIO_FORMAT_PCM_FLOAT); - } - - ((MAL_PFN_AAudioStreamBuilder_setBufferCapacityInFrames)pContext->aaudio.AAudioStreamBuilder_setBufferCapacityInFrames)(pBuilder, pConfig->bufferSizeInFrames); - - /* TODO: Don't set the data callback when synchronous reading and writing is being used. */ - ((MAL_PFN_AAudioStreamBuilder_setFramesPerDataCallback)pContext->aaudio.AAudioStreamBuilder_setFramesPerDataCallback)(pBuilder, pConfig->bufferSizeInFrames / pConfig->periods); - ((MAL_PFN_AAudioStreamBuilder_setDataCallback)pContext->aaudio.AAudioStreamBuilder_setDataCallback)(pBuilder, mal_stream_data_callback__aaudio, (void*)pDevice); - - /* Not sure how this affects things, but since there's a mapping between mini_al's performance profiles and AAudio's performance modes, let go ahead and set it. */ - ((MAL_PFN_AAudioStreamBuilder_setPerformanceMode)pContext->aaudio.AAudioStreamBuilder_setPerformanceMode)(pBuilder, (pConfig->performanceProfile == mal_performance_profile_low_latency) ? MAL_AAUDIO_PERFORMANCE_MODE_LOW_LATENCY : MAL_AAUDIO_PERFORMANCE_MODE_NONE); - } - - resultAA = ((MAL_PFN_AAudioStreamBuilder_openStream)pContext->aaudio.AAudioStreamBuilder_openStream)(pBuilder, ppStream); - if (resultAA != MAL_AAUDIO_OK) { - *ppStream = NULL; - ((MAL_PFN_AAudioStreamBuilder_delete)pContext->aaudio.AAudioStreamBuilder_delete)(pBuilder); - return mal_result_from_aaudio(resultAA); - } - - ((MAL_PFN_AAudioStreamBuilder_delete)pContext->aaudio.AAudioStreamBuilder_delete)(pBuilder); - return MAL_SUCCESS; -} - -mal_result mal_close_stream__aaudio(mal_context* pContext, mal_AAudioStream* pStream) -{ - return mal_result_from_aaudio(((MAL_PFN_AAudioStream_close)pContext->aaudio.AAudioStream_close)(pStream)); -} - -mal_bool32 mal_has_default_device__aaudio(mal_context* pContext, mal_device_type deviceType) -{ - /* The only way to know this is to try creating a stream. */ - mal_AAudioStream* pStream; - mal_result result = mal_open_stream__aaudio(pContext, deviceType, NULL, mal_share_mode_shared, NULL, NULL, &pStream); - if (result != MAL_SUCCESS) { - return MAL_FALSE; - } - - mal_close_stream__aaudio(pContext, pStream); - return MAL_TRUE; -} - -mal_result mal_wait_for_simple_state_transition__aaudio(mal_context* pContext, mal_AAudioStream* pStream, mal_aaudio_stream_state_t oldState, mal_aaudio_stream_state_t newState) -{ - mal_aaudio_stream_state_t actualNewState; - mal_aaudio_result_t resultAA = ((MAL_PFN_AAudioStream_waitForStateChange)pContext->aaudio.AAudioStream_waitForStateChange)(pStream, oldState, &actualNewState, 5000000000); /* 5 second timeout. */ - if (resultAA != MAL_AAUDIO_OK) { - return mal_result_from_aaudio(resultAA); - } - - if (newState != actualNewState) { - return MAL_ERROR; /* Failed to transition into the expected state. */ - } - - return MAL_SUCCESS; -} - - -mal_bool32 mal_context_is_device_id_equal__aaudio(mal_context* pContext, const mal_device_id* pID0, const mal_device_id* pID1) -{ - mal_assert(pContext != NULL); - mal_assert(pID0 != NULL); - mal_assert(pID1 != NULL); - (void)pContext; - - return pID0->aaudio == pID1->aaudio; -} - -mal_result mal_context_enumerate_devices__aaudio(mal_context* pContext, mal_enum_devices_callback_proc callback, void* pUserData) -{ - mal_bool32 cbResult = MAL_TRUE; - - mal_assert(pContext != NULL); - mal_assert(callback != NULL); - - /* Unfortunately AAudio does not have an enumeration API. Therefore I'm only going to report default devices, but only if it can instantiate a stream. */ - - /* Playback. */ - if (cbResult) { - mal_device_info deviceInfo; - mal_zero_object(&deviceInfo); - deviceInfo.id.aaudio = MAL_AAUDIO_UNSPECIFIED; - mal_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MAL_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); - - if (mal_has_default_device__aaudio(pContext, mal_device_type_playback)) { - cbResult = callback(pContext, mal_device_type_playback, &deviceInfo, pUserData); - } - } - - /* Capture. */ - if (cbResult) { - mal_device_info deviceInfo; - mal_zero_object(&deviceInfo); - deviceInfo.id.aaudio = MAL_AAUDIO_UNSPECIFIED; - mal_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MAL_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); - - if (mal_has_default_device__aaudio(pContext, mal_device_type_capture)) { - cbResult = callback(pContext, mal_device_type_capture, &deviceInfo, pUserData); - } - } - - return MAL_SUCCESS; -} - -mal_result mal_context_get_device_info__aaudio(mal_context* pContext, mal_device_type deviceType, const mal_device_id* pDeviceID, mal_share_mode shareMode, mal_device_info* pDeviceInfo) -{ - mal_AAudioStream* pStream; - mal_result result; - - mal_assert(pContext != NULL); - - /* ID */ - if (pDeviceID != NULL) { - pDeviceInfo->id.aaudio = pDeviceID->aaudio; - } else { - pDeviceInfo->id.aaudio = MAL_AAUDIO_UNSPECIFIED; - } - - /* Name */ - if (deviceType == mal_device_type_playback) { - mal_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MAL_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); - } else { - mal_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MAL_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); - } - - - /* We'll need to open the device to get accurate sample rate and channel count information. */ - result = mal_open_stream__aaudio(pContext, deviceType, pDeviceID, shareMode, NULL, NULL, &pStream); - if (result != MAL_SUCCESS) { - return result; - } - - pDeviceInfo->minChannels = ((MAL_PFN_AAudioStream_getChannelCount)pContext->aaudio.AAudioStream_getChannelCount)(pStream); - pDeviceInfo->maxChannels = pDeviceInfo->minChannels; - pDeviceInfo->minSampleRate = ((MAL_PFN_AAudioStream_getSampleRate)pContext->aaudio.AAudioStream_getSampleRate)(pStream); - pDeviceInfo->maxSampleRate = pDeviceInfo->minSampleRate; - - mal_close_stream__aaudio(pContext, pStream); - pStream = NULL; - - - /* AAudio supports s16 and f32. */ - pDeviceInfo->formatCount = 2; - pDeviceInfo->formats[0] = mal_format_s16; - pDeviceInfo->formats[1] = mal_format_f32; - - return MAL_SUCCESS; -} - - -void mal_device_uninit__aaudio(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - mal_close_stream__aaudio(pDevice->pContext, (mal_AAudioStream*)pDevice->aaudio.pStream); - pDevice->aaudio.pStream = NULL; -} - -mal_result mal_device_init__aaudio(mal_context* pContext, mal_device_type type, const mal_device_id* pDeviceID, const mal_device_config* pConfig, mal_device* pDevice) -{ - mal_result result; - - mal_assert(pDevice != NULL); - - /* We need to make a copy of the config so we can make an adjustment to the buffer size. */ - mal_device_config config = *pConfig; - config.bufferSizeInFrames = pDevice->bufferSizeInFrames; - if (config.bufferSizeInFrames == 0) { - config.bufferSizeInFrames = mal_calculate_buffer_size_in_frames_from_milliseconds(pDevice->bufferSizeInMilliseconds, pDevice->sampleRate); - } - - /* We first need to try opening the stream. */ - result = mal_open_stream__aaudio(pContext, type, pDeviceID, pConfig->shareMode, &config, pDevice, (mal_AAudioStream**)&pDevice->aaudio.pStream); - if (result != MAL_SUCCESS) { - return result; /* Failed to open the AAudio stream. */ - } - - pDevice->internalFormat = (((MAL_PFN_AAudioStream_getFormat)pContext->aaudio.AAudioStream_getFormat)((mal_AAudioStream*)pDevice->aaudio.pStream) == MAL_AAUDIO_FORMAT_PCM_I16) ? mal_format_s16 : mal_format_f32; - pDevice->internalChannels = ((MAL_PFN_AAudioStream_getChannelCount)pContext->aaudio.AAudioStream_getChannelCount)((mal_AAudioStream*)pDevice->aaudio.pStream); - pDevice->internalSampleRate = ((MAL_PFN_AAudioStream_getSampleRate)pContext->aaudio.AAudioStream_getSampleRate)((mal_AAudioStream*)pDevice->aaudio.pStream); - mal_get_standard_channel_map(mal_standard_channel_map_default, pDevice->internalChannels, pDevice->internalChannelMap); /* <-- Cannot find info on channel order, so assuming a default. */ - pDevice->bufferSizeInFrames = ((MAL_PFN_AAudioStream_getBufferCapacityInFrames)pContext->aaudio.AAudioStream_getBufferCapacityInFrames)((mal_AAudioStream*)pDevice->aaudio.pStream); - - /* TODO: When synchronous reading and writing is supported, use AAudioStream_getFramesPerBurst() instead of AAudioStream_getFramesPerDataCallback(). Keep - * using AAudioStream_getFramesPerDataCallback() for asynchronous mode, though. */ - int32_t framesPerPeriod = ((MAL_PFN_AAudioStream_getFramesPerDataCallback)pContext->aaudio.AAudioStream_getFramesPerDataCallback)((mal_AAudioStream*)pDevice->aaudio.pStream); - if (framesPerPeriod > 0) { - pDevice->periods = 1; - } else { - pDevice->periods = pDevice->bufferSizeInFrames / framesPerPeriod; - } - - return MAL_SUCCESS; -} - -mal_result mal_device_start__aaudio(mal_device* pDevice) -{ - mal_aaudio_result_t resultAA; - - mal_assert(pDevice != NULL); - - resultAA = ((MAL_PFN_AAudioStream_requestStart)pDevice->pContext->aaudio.AAudioStream_requestStart)((mal_AAudioStream*)pDevice->aaudio.pStream); - if (resultAA != MAL_AAUDIO_OK) { - return mal_result_from_aaudio(resultAA); - } - - /* Do we actually need to wait for the device to transition into it's started state? */ - - /* The device should be in either a starting or started state. If it's not set to started we need to wait for it to transition. It should go from starting to started. */ - mal_aaudio_stream_state_t currentState = ((MAL_PFN_AAudioStream_getState)pDevice->pContext->aaudio.AAudioStream_getState)((mal_AAudioStream*)pDevice->aaudio.pStream); - if (currentState != MAL_AAUDIO_STREAM_STATE_STARTED) { - mal_result result; - - if (currentState != MAL_AAUDIO_STREAM_STATE_STARTING) { - return MAL_ERROR; /* Expecting the stream to be a starting or started state. */ - } - - result = mal_wait_for_simple_state_transition__aaudio(pDevice->pContext, (mal_AAudioStream*)pDevice->aaudio.pStream, currentState, MAL_AAUDIO_STREAM_STATE_STARTED); - if (result != MAL_SUCCESS) { - return result; - } - } - - return MAL_SUCCESS; -} - -mal_result mal_device_stop__aaudio(mal_device* pDevice) -{ - mal_aaudio_result_t resultAA; - - mal_assert(pDevice != NULL); - - resultAA = ((MAL_PFN_AAudioStream_requestStop)pDevice->pContext->aaudio.AAudioStream_requestStop)((mal_AAudioStream*)pDevice->aaudio.pStream); - if (resultAA != MAL_AAUDIO_OK) { - return mal_result_from_aaudio(resultAA); - } - - /* The device should be in either a stopping or stopped state. If it's not set to started we need to wait for it to transition. It should go from stopping to stopped. */ - mal_aaudio_stream_state_t currentState = ((MAL_PFN_AAudioStream_getState)pDevice->pContext->aaudio.AAudioStream_getState)((mal_AAudioStream*)pDevice->aaudio.pStream); - if (currentState != MAL_AAUDIO_STREAM_STATE_STOPPED) { - mal_result result; - - if (currentState != MAL_AAUDIO_STREAM_STATE_STOPPING) { - return MAL_ERROR; /* Expecting the stream to be a stopping or stopped state. */ - } - - result = mal_wait_for_simple_state_transition__aaudio(pDevice->pContext, (mal_AAudioStream*)pDevice->aaudio.pStream, currentState, MAL_AAUDIO_STREAM_STATE_STOPPED); - if (result != MAL_SUCCESS) { - return result; - } - } - - mal_stop_proc onStop = pDevice->onStop; - if (onStop) { - onStop(pDevice); - } - - return MAL_SUCCESS; -} - - -mal_result mal_context_uninit__aaudio(mal_context* pContext) -{ - mal_assert(pContext != NULL); - mal_assert(pContext->backend == mal_backend_aaudio); - - mal_dlclose(pContext->aaudio.hAAudio); - pContext->aaudio.hAAudio = NULL; - - return MAL_SUCCESS; -} - -mal_result mal_context_init__aaudio(mal_context* pContext) -{ - mal_assert(pContext != NULL); - (void)pContext; - - const char* libNames[] = { - "libaaudio.so" - }; - - for (size_t i = 0; i < mal_countof(libNames); ++i) { - pContext->aaudio.hAAudio = mal_dlopen(libNames[i]); - if (pContext->aaudio.hAAudio != NULL) { - break; - } - } - - if (pContext->aaudio.hAAudio == NULL) { - return MAL_FAILED_TO_INIT_BACKEND; - } - - pContext->aaudio.AAudio_createStreamBuilder = (mal_proc)mal_dlsym(pContext->aaudio.hAAudio, "AAudio_createStreamBuilder"); - pContext->aaudio.AAudioStreamBuilder_delete = (mal_proc)mal_dlsym(pContext->aaudio.hAAudio, "AAudioStreamBuilder_delete"); - pContext->aaudio.AAudioStreamBuilder_setDeviceId = (mal_proc)mal_dlsym(pContext->aaudio.hAAudio, "AAudioStreamBuilder_setDeviceId"); - pContext->aaudio.AAudioStreamBuilder_setDirection = (mal_proc)mal_dlsym(pContext->aaudio.hAAudio, "AAudioStreamBuilder_setDirection"); - pContext->aaudio.AAudioStreamBuilder_setSharingMode = (mal_proc)mal_dlsym(pContext->aaudio.hAAudio, "AAudioStreamBuilder_setSharingMode"); - pContext->aaudio.AAudioStreamBuilder_setFormat = (mal_proc)mal_dlsym(pContext->aaudio.hAAudio, "AAudioStreamBuilder_setFormat"); - pContext->aaudio.AAudioStreamBuilder_setChannelCount = (mal_proc)mal_dlsym(pContext->aaudio.hAAudio, "AAudioStreamBuilder_setChannelCount"); - pContext->aaudio.AAudioStreamBuilder_setSampleRate = (mal_proc)mal_dlsym(pContext->aaudio.hAAudio, "AAudioStreamBuilder_setSampleRate"); - pContext->aaudio.AAudioStreamBuilder_setBufferCapacityInFrames = (mal_proc)mal_dlsym(pContext->aaudio.hAAudio, "AAudioStreamBuilder_setBufferCapacityInFrames"); - pContext->aaudio.AAudioStreamBuilder_setFramesPerDataCallback = (mal_proc)mal_dlsym(pContext->aaudio.hAAudio, "AAudioStreamBuilder_setFramesPerDataCallback"); - pContext->aaudio.AAudioStreamBuilder_setDataCallback = (mal_proc)mal_dlsym(pContext->aaudio.hAAudio, "AAudioStreamBuilder_setDataCallback"); - pContext->aaudio.AAudioStreamBuilder_setPerformanceMode = (mal_proc)mal_dlsym(pContext->aaudio.hAAudio, "AAudioStreamBuilder_setPerformanceMode"); - pContext->aaudio.AAudioStreamBuilder_openStream = (mal_proc)mal_dlsym(pContext->aaudio.hAAudio, "AAudioStreamBuilder_openStream"); - pContext->aaudio.AAudioStream_close = (mal_proc)mal_dlsym(pContext->aaudio.hAAudio, "AAudioStream_close"); - pContext->aaudio.AAudioStream_getState = (mal_proc)mal_dlsym(pContext->aaudio.hAAudio, "AAudioStream_getState"); - pContext->aaudio.AAudioStream_waitForStateChange = (mal_proc)mal_dlsym(pContext->aaudio.hAAudio, "AAudioStream_waitForStateChange"); - pContext->aaudio.AAudioStream_getFormat = (mal_proc)mal_dlsym(pContext->aaudio.hAAudio, "AAudioStream_getFormat"); - pContext->aaudio.AAudioStream_getChannelCount = (mal_proc)mal_dlsym(pContext->aaudio.hAAudio, "AAudioStream_getChannelCount"); - pContext->aaudio.AAudioStream_getSampleRate = (mal_proc)mal_dlsym(pContext->aaudio.hAAudio, "AAudioStream_getSampleRate"); - pContext->aaudio.AAudioStream_getBufferCapacityInFrames = (mal_proc)mal_dlsym(pContext->aaudio.hAAudio, "AAudioStream_getBufferCapacityInFrames"); - pContext->aaudio.AAudioStream_getFramesPerDataCallback = (mal_proc)mal_dlsym(pContext->aaudio.hAAudio, "AAudioStream_getFramesPerDataCallback"); - pContext->aaudio.AAudioStream_getFramesPerBurst = (mal_proc)mal_dlsym(pContext->aaudio.hAAudio, "AAudioStream_getFramesPerBurst"); - pContext->aaudio.AAudioStream_requestStart = (mal_proc)mal_dlsym(pContext->aaudio.hAAudio, "AAudioStream_requestStart"); - pContext->aaudio.AAudioStream_requestStop = (mal_proc)mal_dlsym(pContext->aaudio.hAAudio, "AAudioStream_requestStop"); - - pContext->isBackendAsynchronous = MAL_TRUE; - - pContext->onUninit = mal_context_uninit__aaudio; - pContext->onDeviceIDEqual = mal_context_is_device_id_equal__aaudio; - pContext->onEnumDevices = mal_context_enumerate_devices__aaudio; - pContext->onGetDeviceInfo = mal_context_get_device_info__aaudio; - pContext->onDeviceInit = mal_device_init__aaudio; - pContext->onDeviceUninit = mal_device_uninit__aaudio; - pContext->onDeviceStart = mal_device_start__aaudio; - pContext->onDeviceStop = mal_device_stop__aaudio; - - return MAL_SUCCESS; -} -#endif // AAudio - - -/////////////////////////////////////////////////////////////////////////////// -// -// OpenSL|ES Backend -// -/////////////////////////////////////////////////////////////////////////////// -#ifdef MAL_HAS_OPENSL -#include -#ifdef MAL_ANDROID -#include -#endif - -// OpenSL|ES has one-per-application objects :( -SLObjectItf g_malEngineObjectSL = NULL; -SLEngineItf g_malEngineSL = NULL; -mal_uint32 g_malOpenSLInitCounter = 0; - -#define MAL_OPENSL_OBJ(p) (*((SLObjectItf)(p))) -#define MAL_OPENSL_OUTPUTMIX(p) (*((SLOutputMixItf)(p))) -#define MAL_OPENSL_PLAY(p) (*((SLPlayItf)(p))) -#define MAL_OPENSL_RECORD(p) (*((SLRecordItf)(p))) - -#ifdef MAL_ANDROID -#define MAL_OPENSL_BUFFERQUEUE(p) (*((SLAndroidSimpleBufferQueueItf)(p))) -#else -#define MAL_OPENSL_BUFFERQUEUE(p) (*((SLBufferQueueItf)(p))) -#endif - -// Converts an individual OpenSL-style channel identifier (SL_SPEAKER_FRONT_LEFT, etc.) to mini_al. -mal_uint8 mal_channel_id_to_mal__opensl(SLuint32 id) -{ - switch (id) - { - case SL_SPEAKER_FRONT_LEFT: return MAL_CHANNEL_FRONT_LEFT; - case SL_SPEAKER_FRONT_RIGHT: return MAL_CHANNEL_FRONT_RIGHT; - case SL_SPEAKER_FRONT_CENTER: return MAL_CHANNEL_FRONT_CENTER; - case SL_SPEAKER_LOW_FREQUENCY: return MAL_CHANNEL_LFE; - case SL_SPEAKER_BACK_LEFT: return MAL_CHANNEL_BACK_LEFT; - case SL_SPEAKER_BACK_RIGHT: return MAL_CHANNEL_BACK_RIGHT; - case SL_SPEAKER_FRONT_LEFT_OF_CENTER: return MAL_CHANNEL_FRONT_LEFT_CENTER; - case SL_SPEAKER_FRONT_RIGHT_OF_CENTER: return MAL_CHANNEL_FRONT_RIGHT_CENTER; - case SL_SPEAKER_BACK_CENTER: return MAL_CHANNEL_BACK_CENTER; - case SL_SPEAKER_SIDE_LEFT: return MAL_CHANNEL_SIDE_LEFT; - case SL_SPEAKER_SIDE_RIGHT: return MAL_CHANNEL_SIDE_RIGHT; - case SL_SPEAKER_TOP_CENTER: return MAL_CHANNEL_TOP_CENTER; - case SL_SPEAKER_TOP_FRONT_LEFT: return MAL_CHANNEL_TOP_FRONT_LEFT; - case SL_SPEAKER_TOP_FRONT_CENTER: return MAL_CHANNEL_TOP_FRONT_CENTER; - case SL_SPEAKER_TOP_FRONT_RIGHT: return MAL_CHANNEL_TOP_FRONT_RIGHT; - case SL_SPEAKER_TOP_BACK_LEFT: return MAL_CHANNEL_TOP_BACK_LEFT; - case SL_SPEAKER_TOP_BACK_CENTER: return MAL_CHANNEL_TOP_BACK_CENTER; - case SL_SPEAKER_TOP_BACK_RIGHT: return MAL_CHANNEL_TOP_BACK_RIGHT; - default: return 0; - } -} - -// Converts an individual mini_al channel identifier (MAL_CHANNEL_FRONT_LEFT, etc.) to OpenSL-style. -SLuint32 mal_channel_id_to_opensl(mal_uint8 id) -{ - switch (id) - { - case MAL_CHANNEL_MONO: return SL_SPEAKER_FRONT_CENTER; - case MAL_CHANNEL_FRONT_LEFT: return SL_SPEAKER_FRONT_LEFT; - case MAL_CHANNEL_FRONT_RIGHT: return SL_SPEAKER_FRONT_RIGHT; - case MAL_CHANNEL_FRONT_CENTER: return SL_SPEAKER_FRONT_CENTER; - case MAL_CHANNEL_LFE: return SL_SPEAKER_LOW_FREQUENCY; - case MAL_CHANNEL_BACK_LEFT: return SL_SPEAKER_BACK_LEFT; - case MAL_CHANNEL_BACK_RIGHT: return SL_SPEAKER_BACK_RIGHT; - case MAL_CHANNEL_FRONT_LEFT_CENTER: return SL_SPEAKER_FRONT_LEFT_OF_CENTER; - case MAL_CHANNEL_FRONT_RIGHT_CENTER: return SL_SPEAKER_FRONT_RIGHT_OF_CENTER; - case MAL_CHANNEL_BACK_CENTER: return SL_SPEAKER_BACK_CENTER; - case MAL_CHANNEL_SIDE_LEFT: return SL_SPEAKER_SIDE_LEFT; - case MAL_CHANNEL_SIDE_RIGHT: return SL_SPEAKER_SIDE_RIGHT; - case MAL_CHANNEL_TOP_CENTER: return SL_SPEAKER_TOP_CENTER; - case MAL_CHANNEL_TOP_FRONT_LEFT: return SL_SPEAKER_TOP_FRONT_LEFT; - case MAL_CHANNEL_TOP_FRONT_CENTER: return SL_SPEAKER_TOP_FRONT_CENTER; - case MAL_CHANNEL_TOP_FRONT_RIGHT: return SL_SPEAKER_TOP_FRONT_RIGHT; - case MAL_CHANNEL_TOP_BACK_LEFT: return SL_SPEAKER_TOP_BACK_LEFT; - case MAL_CHANNEL_TOP_BACK_CENTER: return SL_SPEAKER_TOP_BACK_CENTER; - case MAL_CHANNEL_TOP_BACK_RIGHT: return SL_SPEAKER_TOP_BACK_RIGHT; - default: return 0; - } -} - -// Converts a channel mapping to an OpenSL-style channel mask. -SLuint32 mal_channel_map_to_channel_mask__opensl(const mal_channel channelMap[MAL_MAX_CHANNELS], mal_uint32 channels) -{ - SLuint32 channelMask = 0; - for (mal_uint32 iChannel = 0; iChannel < channels; ++iChannel) { - channelMask |= mal_channel_id_to_opensl(channelMap[iChannel]); - } - - return channelMask; -} - -// Converts an OpenSL-style channel mask to a mini_al channel map. -void mal_channel_mask_to_channel_map__opensl(SLuint32 channelMask, mal_uint32 channels, mal_channel channelMap[MAL_MAX_CHANNELS]) -{ - if (channels == 1 && channelMask == 0) { - channelMap[0] = MAL_CHANNEL_MONO; - } else if (channels == 2 && channelMask == 0) { - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_RIGHT; - } else { - if (channels == 1 && (channelMask & SL_SPEAKER_FRONT_CENTER) != 0) { - channelMap[0] = MAL_CHANNEL_MONO; - } else { - // Just iterate over each bit. - mal_uint32 iChannel = 0; - for (mal_uint32 iBit = 0; iBit < 32; ++iBit) { - SLuint32 bitValue = (channelMask & (1UL << iBit)); - if (bitValue != 0) { - // The bit is set. - channelMap[iChannel] = mal_channel_id_to_mal__opensl(bitValue); - iChannel += 1; - } - } - } - } -} - -SLuint32 mal_round_to_standard_sample_rate__opensl(SLuint32 samplesPerSec) -{ - if (samplesPerSec <= SL_SAMPLINGRATE_8) { - return SL_SAMPLINGRATE_8; - } - if (samplesPerSec <= SL_SAMPLINGRATE_11_025) { - return SL_SAMPLINGRATE_11_025; - } - if (samplesPerSec <= SL_SAMPLINGRATE_12) { - return SL_SAMPLINGRATE_12; - } - if (samplesPerSec <= SL_SAMPLINGRATE_16) { - return SL_SAMPLINGRATE_16; - } - if (samplesPerSec <= SL_SAMPLINGRATE_22_05) { - return SL_SAMPLINGRATE_22_05; - } - if (samplesPerSec <= SL_SAMPLINGRATE_24) { - return SL_SAMPLINGRATE_24; - } - if (samplesPerSec <= SL_SAMPLINGRATE_32) { - return SL_SAMPLINGRATE_32; - } - if (samplesPerSec <= SL_SAMPLINGRATE_44_1) { - return SL_SAMPLINGRATE_44_1; - } - if (samplesPerSec <= SL_SAMPLINGRATE_48) { - return SL_SAMPLINGRATE_48; - } - - // Android doesn't support more than 48000. -#ifndef MAL_ANDROID - if (samplesPerSec <= SL_SAMPLINGRATE_64) { - return SL_SAMPLINGRATE_64; - } - if (samplesPerSec <= SL_SAMPLINGRATE_88_2) { - return SL_SAMPLINGRATE_88_2; - } - if (samplesPerSec <= SL_SAMPLINGRATE_96) { - return SL_SAMPLINGRATE_96; - } - if (samplesPerSec <= SL_SAMPLINGRATE_192) { - return SL_SAMPLINGRATE_192; - } -#endif - - return SL_SAMPLINGRATE_16; -} - - -mal_bool32 mal_context_is_device_id_equal__opensl(mal_context* pContext, const mal_device_id* pID0, const mal_device_id* pID1) -{ - mal_assert(pContext != NULL); - mal_assert(pID0 != NULL); - mal_assert(pID1 != NULL); - (void)pContext; - - return pID0->opensl == pID1->opensl; -} - -mal_result mal_context_enumerate_devices__opensl(mal_context* pContext, mal_enum_devices_callback_proc callback, void* pUserData) -{ - mal_assert(pContext != NULL); - mal_assert(callback != NULL); - - mal_assert(g_malOpenSLInitCounter > 0); /* <-- If you trigger this it means you've either not initialized the context, or you've uninitialized it and then attempted to enumerate devices. */ - if (g_malOpenSLInitCounter == 0) { - return MAL_INVALID_OPERATION; - } - - // TODO: Test Me. - // - // This is currently untested, so for now we are just returning default devices. -#if 0 && !defined(MAL_ANDROID) - mal_bool32 isTerminated = MAL_FALSE; - - SLuint32 pDeviceIDs[128]; - SLint32 deviceCount = sizeof(pDeviceIDs) / sizeof(pDeviceIDs[0]); - - SLAudioIODeviceCapabilitiesItf deviceCaps; - SLresult resultSL = (*g_malEngineObjectSL)->GetInterface(g_malEngineObjectSL, SL_IID_AUDIOIODEVICECAPABILITIES, &deviceCaps); - if (resultSL != SL_RESULT_SUCCESS) { - // The interface may not be supported so just report a default device. - goto return_default_device; - } - - // Playback - if (!isTerminated) { - resultSL = (*deviceCaps)->GetAvailableAudioOutputs(deviceCaps, &deviceCount, pDeviceIDs); - if (resultSL != SL_RESULT_SUCCESS) { - return MAL_NO_DEVICE; - } - - for (SLint32 iDevice = 0; iDevice < deviceCount; ++iDevice) { - mal_device_info deviceInfo; - mal_zero_object(&deviceInfo); - deviceInfo.id.opensl = pDeviceIDs[iDevice]; - - SLAudioOutputDescriptor desc; - resultSL = (*deviceCaps)->QueryAudioOutputCapabilities(deviceCaps, deviceInfo.id.opensl, &desc); - if (resultSL == SL_RESULT_SUCCESS) { - mal_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), (const char*)desc.pDeviceName, (size_t)-1); - - mal_bool32 cbResult = callback(pContext, mal_device_type_playback, &deviceInfo, pUserData); - if (cbResult == MAL_FALSE) { - isTerminated = MAL_TRUE; - break; - } - } - } - } - - // Capture - if (!isTerminated) { - resultSL = (*deviceCaps)->GetAvailableAudioInputs(deviceCaps, &deviceCount, pDeviceIDs); - if (resultSL != SL_RESULT_SUCCESS) { - return MAL_NO_DEVICE; - } - - for (SLint32 iDevice = 0; iDevice < deviceCount; ++iDevice) { - mal_device_info deviceInfo; - mal_zero_object(&deviceInfo); - deviceInfo.id.opensl = pDeviceIDs[iDevice]; - - SLAudioInputDescriptor desc; - resultSL = (*deviceCaps)->QueryAudioInputCapabilities(deviceCaps, deviceInfo.id.opensl, &desc); - if (resultSL == SL_RESULT_SUCCESS) { - mal_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), (const char*)desc.deviceName, (size_t)-1); - - mal_bool32 cbResult = callback(pContext, mal_device_type_capture, &deviceInfo, pUserData); - if (cbResult == MAL_FALSE) { - isTerminated = MAL_TRUE; - break; - } - } - } - } - - return MAL_SUCCESS; -#else - goto return_default_device; -#endif - -return_default_device:; - mal_bool32 cbResult = MAL_TRUE; - - // Playback. - if (cbResult) { - mal_device_info deviceInfo; - mal_zero_object(&deviceInfo); - mal_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MAL_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); - cbResult = callback(pContext, mal_device_type_playback, &deviceInfo, pUserData); - } - - // Capture. - if (cbResult) { - mal_device_info deviceInfo; - mal_zero_object(&deviceInfo); - mal_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MAL_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); - cbResult = callback(pContext, mal_device_type_capture, &deviceInfo, pUserData); - } - - return MAL_SUCCESS; -} - -mal_result mal_context_get_device_info__opensl(mal_context* pContext, mal_device_type deviceType, const mal_device_id* pDeviceID, mal_share_mode shareMode, mal_device_info* pDeviceInfo) -{ - mal_assert(pContext != NULL); - (void)shareMode; - - mal_assert(g_malOpenSLInitCounter > 0); /* <-- If you trigger this it means you've either not initialized the context, or you've uninitialized it and then attempted to get device info. */ - if (g_malOpenSLInitCounter == 0) { - return MAL_INVALID_OPERATION; - } - - // TODO: Test Me. - // - // This is currently untested, so for now we are just returning default devices. -#if 0 && !defined(MAL_ANDROID) - SLAudioIODeviceCapabilitiesItf deviceCaps; - SLresult resultSL = (*g_malEngineObjectSL)->GetInterface(g_malEngineObjectSL, SL_IID_AUDIOIODEVICECAPABILITIES, &deviceCaps); - if (resultSL != SL_RESULT_SUCCESS) { - // The interface may not be supported so just report a default device. - goto return_default_device; - } - - if (deviceType == mal_device_type_playback) { - SLAudioOutputDescriptor desc; - resultSL = (*deviceCaps)->QueryAudioOutputCapabilities(deviceCaps, pDeviceID->opensl, &desc); - if (resultSL != SL_RESULT_SUCCESS) { - return MAL_NO_DEVICE; - } - - mal_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), (const char*)desc.pDeviceName, (size_t)-1); - } else { - SLAudioInputDescriptor desc; - resultSL = (*deviceCaps)->QueryAudioInputCapabilities(deviceCaps, pDeviceID->opensl, &desc); - if (resultSL != SL_RESULT_SUCCESS) { - return MAL_NO_DEVICE; - } - - mal_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), (const char*)desc.deviceName, (size_t)-1); - } - - goto return_detailed_info; -#else - goto return_default_device; -#endif - -return_default_device: - if (pDeviceID != NULL) { - if ((deviceType == mal_device_type_playback && pDeviceID->opensl != SL_DEFAULTDEVICEID_AUDIOOUTPUT) || - (deviceType == mal_device_type_capture && pDeviceID->opensl != SL_DEFAULTDEVICEID_AUDIOINPUT)) { - return MAL_NO_DEVICE; // Don't know the device. - } - } - - // Name / Description - if (deviceType == mal_device_type_playback) { - mal_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MAL_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); - } else { - mal_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MAL_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); - } - - goto return_detailed_info; - - -return_detailed_info: - - // For now we're just outputting a set of values that are supported by the API but not necessarily supported - // by the device natively. Later on we should work on this so that it more closely reflects the device's - // actual native format. - pDeviceInfo->minChannels = 1; - pDeviceInfo->maxChannels = 2; - pDeviceInfo->minSampleRate = 8000; - pDeviceInfo->maxSampleRate = 48000; - pDeviceInfo->formatCount = 2; - pDeviceInfo->formats[0] = mal_format_u8; - pDeviceInfo->formats[1] = mal_format_s16; -#if defined(MAL_ANDROID) && __ANDROID_API__ >= 21 - pDeviceInfo->formats[pDeviceInfo->formatCount] = mal_format_f32; - pDeviceInfo->formatCount += 1; -#endif - - return MAL_SUCCESS; -} - - -#ifdef MAL_ANDROID -//void mal_buffer_queue_callback__opensl_android(SLAndroidSimpleBufferQueueItf pBufferQueue, SLuint32 eventFlags, const void* pBuffer, SLuint32 bufferSize, SLuint32 dataUsed, void* pContext) -void mal_buffer_queue_callback__opensl_android(SLAndroidSimpleBufferQueueItf pBufferQueue, void* pUserData) -{ - (void)pBufferQueue; - - // For now, only supporting Android implementations of OpenSL|ES since that's the only one I've - // been able to test with and I currently depend on Android-specific extensions (simple buffer - // queues). -#ifndef MAL_ANDROID - return MAL_NO_BACKEND; -#endif - - mal_device* pDevice = (mal_device*)pUserData; - mal_assert(pDevice != NULL); - - // For now, don't do anything unless the buffer was fully processed. From what I can tell, it looks like - // OpenSL|ES 1.1 improves on buffer queues to the point that we could much more intelligently handle this, - // but unfortunately it looks like Android is only supporting OpenSL|ES 1.0.1 for now :( - if (pDevice->state != MAL_STATE_STARTED) { - return; - } - - size_t periodSizeInBytes = pDevice->opensl.periodSizeInFrames * pDevice->internalChannels * mal_get_bytes_per_sample(pDevice->internalFormat); - mal_uint8* pBuffer = pDevice->opensl.pBuffer + (pDevice->opensl.currentBufferIndex * periodSizeInBytes); - - if (pDevice->type == mal_device_type_playback) { - if (pDevice->state != MAL_STATE_STARTED) { - return; - } - - mal_device__read_frames_from_client(pDevice, pDevice->opensl.periodSizeInFrames, pBuffer); - - SLresult resultSL = MAL_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueue)->Enqueue((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueue, pBuffer, periodSizeInBytes); - if (resultSL != SL_RESULT_SUCCESS) { - return; - } - } else { - mal_device__send_frames_to_client(pDevice, pDevice->opensl.periodSizeInFrames, pBuffer); - - SLresult resultSL = MAL_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueue)->Enqueue((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueue, pBuffer, periodSizeInBytes); - if (resultSL != SL_RESULT_SUCCESS) { - return; - } - } - - pDevice->opensl.currentBufferIndex = (pDevice->opensl.currentBufferIndex + 1) % pDevice->periods; -} -#endif - -void mal_device_uninit__opensl(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - mal_assert(g_malOpenSLInitCounter > 0); /* <-- If you trigger this it means you've either not initialized the context, or you've uninitialized it before uninitializing the device. */ - if (g_malOpenSLInitCounter == 0) { - return; - } - - // Uninit device. - if (pDevice->type == mal_device_type_playback) { - if (pDevice->opensl.pAudioPlayerObj) { - MAL_OPENSL_OBJ(pDevice->opensl.pAudioPlayerObj)->Destroy((SLObjectItf)pDevice->opensl.pAudioPlayerObj); - } - if (pDevice->opensl.pOutputMixObj) { - MAL_OPENSL_OBJ(pDevice->opensl.pOutputMixObj)->Destroy((SLObjectItf)pDevice->opensl.pOutputMixObj); - } - } else { - if (pDevice->opensl.pAudioRecorderObj) { - MAL_OPENSL_OBJ(pDevice->opensl.pAudioRecorderObj)->Destroy((SLObjectItf)pDevice->opensl.pAudioRecorderObj); - } - } - - mal_free(pDevice->opensl.pBuffer); -} - -mal_result mal_device_init__opensl(mal_context* pContext, mal_device_type type, const mal_device_id* pDeviceID, const mal_device_config* pConfig, mal_device* pDevice) -{ - (void)pContext; - - mal_assert(g_malOpenSLInitCounter > 0); /* <-- If you trigger this it means you've either not initialized the context, or you've uninitialized it and then attempted to initialize a new device. */ - if (g_malOpenSLInitCounter == 0) { - return MAL_INVALID_OPERATION; - } - - // For now, only supporting Android implementations of OpenSL|ES since that's the only one I've - // been able to test with and I currently depend on Android-specific extensions (simple buffer - // queues). -#ifndef MAL_ANDROID - return MAL_NO_BACKEND; -#endif - - // Use s32 as the internal format for when floating point is specified. - if (pConfig->format == mal_format_f32) { - pDevice->internalFormat = mal_format_s32; - } - - // Now we can start initializing the device properly. - mal_assert(pDevice != NULL); - mal_zero_object(&pDevice->opensl); - - SLDataLocator_AndroidSimpleBufferQueue queue; - queue.locatorType = SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE; - queue.numBuffers = pConfig->periods; - - SLDataFormat_PCM* pFormat = NULL; - -#if defined(MAL_ANDROID) && __ANDROID_API__ >= 21 - SLAndroidDataFormat_PCM_EX pcmEx; - if (pDevice->format == mal_format_f32 /*|| pDevice->format == mal_format_f64*/) { - pcmEx.formatType = SL_ANDROID_DATAFORMAT_PCM_EX; - pcmEx.representation = SL_ANDROID_PCM_REPRESENTATION_FLOAT; - } else { - pcmEx.formatType = SL_DATAFORMAT_PCM; - } - pFormat = (SLDataFormat_PCM*)&pcmEx; -#else - SLDataFormat_PCM pcm; - pcm.formatType = SL_DATAFORMAT_PCM; - pFormat = &pcm; -#endif - - pFormat->numChannels = pDevice->channels; - pFormat->samplesPerSec = mal_round_to_standard_sample_rate__opensl(pDevice->sampleRate * 1000); // In millihertz. - pFormat->bitsPerSample = mal_get_bytes_per_sample(pDevice->format)*8; - pFormat->containerSize = pFormat->bitsPerSample; // Always tightly packed for now. - pFormat->channelMask = mal_channel_map_to_channel_mask__opensl(pConfig->channelMap, pFormat->numChannels); - pFormat->endianness = (mal_is_little_endian()) ? SL_BYTEORDER_LITTLEENDIAN : SL_BYTEORDER_BIGENDIAN; - - // Android has a few restrictions on the format as documented here: https://developer.android.com/ndk/guides/audio/opensl-for-android.html - // - Only mono and stereo is supported. - // - Only u8 and s16 formats are supported. - // - Maximum sample rate of 48000. -#ifdef MAL_ANDROID - if (pFormat->numChannels > 2) { - pFormat->numChannels = 2; - } -#if __ANDROID_API__ >= 21 - if (pFormat->formatType == SL_ANDROID_DATAFORMAT_PCM_EX) { - // It's floating point. - mal_assert(pcmEx.representation == SL_ANDROID_PCM_REPRESENTATION_FLOAT); - if (pFormat->bitsPerSample > 32) { - pFormat->bitsPerSample = 32; - } - } else { - if (pFormat->bitsPerSample > 16) { - pFormat->bitsPerSample = 16; - } - } -#else - if (pFormat->bitsPerSample > 16) { - pFormat->bitsPerSample = 16; - } -#endif - pFormat->containerSize = pFormat->bitsPerSample; // Always tightly packed for now. - - if (pFormat->samplesPerSec > SL_SAMPLINGRATE_48) { - pFormat->samplesPerSec = SL_SAMPLINGRATE_48; - } -#endif - - if (type == mal_device_type_playback) { - SLresult resultSL = (*g_malEngineSL)->CreateOutputMix(g_malEngineSL, (SLObjectItf*)&pDevice->opensl.pOutputMixObj, 0, NULL, NULL); - if (resultSL != SL_RESULT_SUCCESS) { - mal_device_uninit__opensl(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[OpenSL] Failed to create output mix.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - - if (MAL_OPENSL_OBJ(pDevice->opensl.pOutputMixObj)->Realize((SLObjectItf)pDevice->opensl.pOutputMixObj, SL_BOOLEAN_FALSE)) { - mal_device_uninit__opensl(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[OpenSL] Failed to realize output mix object.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - - if (MAL_OPENSL_OBJ(pDevice->opensl.pOutputMixObj)->GetInterface((SLObjectItf)pDevice->opensl.pOutputMixObj, SL_IID_OUTPUTMIX, &pDevice->opensl.pOutputMix) != SL_RESULT_SUCCESS) { - mal_device_uninit__opensl(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[OpenSL] Failed to retrieve SL_IID_OUTPUTMIX interface.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - - // Set the output device. - if (pDeviceID != NULL) { - SLuint32 deviceID_OpenSL = pDeviceID->opensl; - MAL_OPENSL_OUTPUTMIX(pDevice->opensl.pOutputMix)->ReRoute((SLOutputMixItf)pDevice->opensl.pOutputMix, 1, &deviceID_OpenSL); - } - - SLDataSource source; - source.pLocator = &queue; - source.pFormat = pFormat; - - SLDataLocator_OutputMix outmixLocator; - outmixLocator.locatorType = SL_DATALOCATOR_OUTPUTMIX; - outmixLocator.outputMix = (SLObjectItf)pDevice->opensl.pOutputMixObj; - - SLDataSink sink; - sink.pLocator = &outmixLocator; - sink.pFormat = NULL; - - const SLInterfaceID itfIDs1[] = {SL_IID_ANDROIDSIMPLEBUFFERQUEUE}; - const SLboolean itfIDsRequired1[] = {SL_BOOLEAN_TRUE}; - resultSL = (*g_malEngineSL)->CreateAudioPlayer(g_malEngineSL, (SLObjectItf*)&pDevice->opensl.pAudioPlayerObj, &source, &sink, 1, itfIDs1, itfIDsRequired1); - if (resultSL == SL_RESULT_CONTENT_UNSUPPORTED) { - // Unsupported format. Fall back to something safer and try again. If this fails, just abort. - pFormat->formatType = SL_DATAFORMAT_PCM; - pFormat->numChannels = 2; - pFormat->samplesPerSec = SL_SAMPLINGRATE_16; - pFormat->bitsPerSample = 16; - pFormat->containerSize = pFormat->bitsPerSample; // Always tightly packed for now. - pFormat->channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT; - resultSL = (*g_malEngineSL)->CreateAudioPlayer(g_malEngineSL, (SLObjectItf*)&pDevice->opensl.pAudioPlayerObj, &source, &sink, 1, itfIDs1, itfIDsRequired1); - } - - if (resultSL != SL_RESULT_SUCCESS) { - mal_device_uninit__opensl(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[OpenSL] Failed to create audio player.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - - - if (MAL_OPENSL_OBJ(pDevice->opensl.pAudioPlayerObj)->Realize((SLObjectItf)pDevice->opensl.pAudioPlayerObj, SL_BOOLEAN_FALSE) != SL_RESULT_SUCCESS) { - mal_device_uninit__opensl(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[OpenSL] Failed to realize audio player.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - - if (MAL_OPENSL_OBJ(pDevice->opensl.pAudioPlayerObj)->GetInterface((SLObjectItf)pDevice->opensl.pAudioPlayerObj, SL_IID_PLAY, &pDevice->opensl.pAudioPlayer) != SL_RESULT_SUCCESS) { - mal_device_uninit__opensl(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[OpenSL] Failed to retrieve SL_IID_PLAY interface.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - - if (MAL_OPENSL_OBJ(pDevice->opensl.pAudioPlayerObj)->GetInterface((SLObjectItf)pDevice->opensl.pAudioPlayerObj, SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &pDevice->opensl.pBufferQueue) != SL_RESULT_SUCCESS) { - mal_device_uninit__opensl(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[OpenSL] Failed to retrieve SL_IID_ANDROIDSIMPLEBUFFERQUEUE interface.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - - if (MAL_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueue)->RegisterCallback((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueue, mal_buffer_queue_callback__opensl_android, pDevice) != SL_RESULT_SUCCESS) { - mal_device_uninit__opensl(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[OpenSL] Failed to register buffer queue callback.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - } else { - SLDataLocator_IODevice locatorDevice; - locatorDevice.locatorType = SL_DATALOCATOR_IODEVICE; - locatorDevice.deviceType = SL_IODEVICE_AUDIOINPUT; - locatorDevice.deviceID = (pDeviceID == NULL) ? SL_DEFAULTDEVICEID_AUDIOINPUT : pDeviceID->opensl; - locatorDevice.device = NULL; - - SLDataSource source; - source.pLocator = &locatorDevice; - source.pFormat = NULL; - - SLDataSink sink; - sink.pLocator = &queue; - sink.pFormat = pFormat; - - const SLInterfaceID itfIDs1[] = {SL_IID_ANDROIDSIMPLEBUFFERQUEUE}; - const SLboolean itfIDsRequired1[] = {SL_BOOLEAN_TRUE}; - SLresult resultSL = (*g_malEngineSL)->CreateAudioRecorder(g_malEngineSL, (SLObjectItf*)&pDevice->opensl.pAudioRecorderObj, &source, &sink, 1, itfIDs1, itfIDsRequired1); - if (resultSL == SL_RESULT_CONTENT_UNSUPPORTED) { - // Unsupported format. Fall back to something safer and try again. If this fails, just abort. - pFormat->formatType = SL_DATAFORMAT_PCM; - pFormat->numChannels = 1; - pFormat->samplesPerSec = SL_SAMPLINGRATE_16; - pFormat->bitsPerSample = 16; - pFormat->containerSize = pFormat->bitsPerSample; // Always tightly packed for now. - pFormat->channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT; - resultSL = (*g_malEngineSL)->CreateAudioRecorder(g_malEngineSL, (SLObjectItf*)&pDevice->opensl.pAudioRecorderObj, &source, &sink, 1, itfIDs1, itfIDsRequired1); - } - - if (resultSL != SL_RESULT_SUCCESS) { - mal_device_uninit__opensl(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[OpenSL] Failed to create audio recorder.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - - if (MAL_OPENSL_OBJ(pDevice->opensl.pAudioRecorderObj)->Realize((SLObjectItf)pDevice->opensl.pAudioRecorderObj, SL_BOOLEAN_FALSE) != SL_RESULT_SUCCESS) { - mal_device_uninit__opensl(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[OpenSL] Failed to realize audio recorder.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - - if (MAL_OPENSL_OBJ(pDevice->opensl.pAudioRecorderObj)->GetInterface((SLObjectItf)pDevice->opensl.pAudioRecorderObj, SL_IID_RECORD, &pDevice->opensl.pAudioRecorder) != SL_RESULT_SUCCESS) { - mal_device_uninit__opensl(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[OpenSL] Failed to retrieve SL_IID_RECORD interface.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - - if (MAL_OPENSL_OBJ(pDevice->opensl.pAudioRecorderObj)->GetInterface((SLObjectItf)pDevice->opensl.pAudioRecorderObj, SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &pDevice->opensl.pBufferQueue) != SL_RESULT_SUCCESS) { - mal_device_uninit__opensl(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[OpenSL] Failed to retrieve SL_IID_ANDROIDSIMPLEBUFFERQUEUE interface.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - - if (MAL_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueue)->RegisterCallback((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueue, mal_buffer_queue_callback__opensl_android, pDevice) != SL_RESULT_SUCCESS) { - mal_device_uninit__opensl(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[OpenSL] Failed to register buffer queue callback.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - } - - - // The internal format is determined by the pFormat object. - mal_bool32 isFloatingPoint = MAL_FALSE; -#if defined(MAL_ANDROID) && __ANDROID_API__ >= 21 - if (pFormat->formatType == SL_ANDROID_DATAFORMAT_PCM_EX) { - mal_assert(pcmEx.representation == SL_ANDROID_PCM_REPRESENTATION_FLOAT); - isFloatingPoint = MAL_TRUE; - } -#endif - if (isFloatingPoint) { - if (pFormat->bitsPerSample == 32) { - pDevice->internalFormat = mal_format_f32; - } -#if 0 - if (pFormat->bitsPerSample == 64) { - pDevice->internalFormat = mal_format_f64; - } -#endif - } else { - if (pFormat->bitsPerSample == 8) { - pDevice->internalFormat = mal_format_u8; - } else if (pFormat->bitsPerSample == 16) { - pDevice->internalFormat = mal_format_s16; - } else if (pFormat->bitsPerSample == 24) { - pDevice->internalFormat = mal_format_s24; - } else if (pFormat->bitsPerSample == 32) { - pDevice->internalFormat = mal_format_s32; - } - } - - pDevice->internalChannels = pFormat->numChannels; - pDevice->internalSampleRate = pFormat->samplesPerSec / 1000; - mal_channel_mask_to_channel_map__opensl(pFormat->channelMask, pDevice->internalChannels, pDevice->internalChannelMap); - - // Try calculating an appropriate default buffer size. - if (pDevice->bufferSizeInFrames == 0) { - pDevice->bufferSizeInFrames = mal_calculate_buffer_size_in_frames_from_milliseconds(pDevice->bufferSizeInMilliseconds, pDevice->internalSampleRate); - } - - pDevice->opensl.currentBufferIndex = 0; - pDevice->opensl.periodSizeInFrames = pDevice->bufferSizeInFrames / pConfig->periods; - pDevice->bufferSizeInFrames = pDevice->opensl.periodSizeInFrames * pConfig->periods; - - size_t bufferSizeInBytes = pDevice->bufferSizeInFrames * pDevice->internalChannels * mal_get_bytes_per_sample(pDevice->internalFormat); - pDevice->opensl.pBuffer = (mal_uint8*)mal_malloc(bufferSizeInBytes); - if (pDevice->opensl.pBuffer == NULL) { - mal_device_uninit__opensl(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[OpenSL] Failed to allocate memory for data buffer.", MAL_OUT_OF_MEMORY); - } - - mal_zero_memory(pDevice->opensl.pBuffer, bufferSizeInBytes); - - return MAL_SUCCESS; -} - -mal_result mal_device_start__opensl(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - mal_assert(g_malOpenSLInitCounter > 0); /* <-- If you trigger this it means you've either not initialized the context, or you've uninitialized it and then attempted to start the device. */ - if (g_malOpenSLInitCounter == 0) { - return MAL_INVALID_OPERATION; - } - - if (pDevice->type == mal_device_type_playback) { - SLresult resultSL = MAL_OPENSL_PLAY(pDevice->opensl.pAudioPlayer)->SetPlayState((SLPlayItf)pDevice->opensl.pAudioPlayer, SL_PLAYSTATE_PLAYING); - if (resultSL != SL_RESULT_SUCCESS) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[OpenSL] Failed to start internal playback device.", MAL_FAILED_TO_START_BACKEND_DEVICE); - } - - // We need to enqueue a buffer for each period. - mal_device__read_frames_from_client(pDevice, pDevice->bufferSizeInFrames, pDevice->opensl.pBuffer); - - size_t periodSizeInBytes = pDevice->opensl.periodSizeInFrames * pDevice->internalChannels * mal_get_bytes_per_sample(pDevice->internalFormat); - for (mal_uint32 iPeriod = 0; iPeriod < pDevice->periods; ++iPeriod) { - resultSL = MAL_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueue)->Enqueue((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueue, pDevice->opensl.pBuffer + (periodSizeInBytes * iPeriod), periodSizeInBytes); - if (resultSL != SL_RESULT_SUCCESS) { - MAL_OPENSL_PLAY(pDevice->opensl.pAudioPlayer)->SetPlayState((SLPlayItf)pDevice->opensl.pAudioPlayer, SL_PLAYSTATE_STOPPED); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[OpenSL] Failed to enqueue buffer for playback device.", MAL_FAILED_TO_START_BACKEND_DEVICE); - } - } - } else { - SLresult resultSL = MAL_OPENSL_RECORD(pDevice->opensl.pAudioRecorder)->SetRecordState((SLRecordItf)pDevice->opensl.pAudioRecorder, SL_RECORDSTATE_RECORDING); - if (resultSL != SL_RESULT_SUCCESS) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[OpenSL] Failed to start internal capture device.", MAL_FAILED_TO_START_BACKEND_DEVICE); - } - - size_t periodSizeInBytes = pDevice->opensl.periodSizeInFrames * pDevice->internalChannels * mal_get_bytes_per_sample(pDevice->internalFormat); - for (mal_uint32 iPeriod = 0; iPeriod < pDevice->periods; ++iPeriod) { - resultSL = MAL_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueue)->Enqueue((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueue, pDevice->opensl.pBuffer + (periodSizeInBytes * iPeriod), periodSizeInBytes); - if (resultSL != SL_RESULT_SUCCESS) { - MAL_OPENSL_RECORD(pDevice->opensl.pAudioRecorder)->SetRecordState((SLRecordItf)pDevice->opensl.pAudioRecorder, SL_RECORDSTATE_STOPPED); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[OpenSL] Failed to enqueue buffer for capture device.", MAL_FAILED_TO_START_BACKEND_DEVICE); - } - } - } - - return MAL_SUCCESS; -} - -mal_result mal_device_stop__opensl(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - mal_assert(g_malOpenSLInitCounter > 0); /* <-- If you trigger this it means you've either not initialized the context, or you've uninitialized it before stopping/uninitializing the device. */ - if (g_malOpenSLInitCounter == 0) { - return MAL_INVALID_OPERATION; - } - - if (pDevice->type == mal_device_type_playback) { - SLresult resultSL = MAL_OPENSL_PLAY(pDevice->opensl.pAudioPlayer)->SetPlayState((SLPlayItf)pDevice->opensl.pAudioPlayer, SL_PLAYSTATE_STOPPED); - if (resultSL != SL_RESULT_SUCCESS) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[OpenSL] Failed to stop internal playback device.", MAL_FAILED_TO_STOP_BACKEND_DEVICE); - } - } else { - SLresult resultSL = MAL_OPENSL_RECORD(pDevice->opensl.pAudioRecorder)->SetRecordState((SLRecordItf)pDevice->opensl.pAudioRecorder, SL_RECORDSTATE_STOPPED); - if (resultSL != SL_RESULT_SUCCESS) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "[OpenSL] Failed to stop internal capture device.", MAL_FAILED_TO_STOP_BACKEND_DEVICE); - } - } - - // Make sure any queued buffers are cleared. - MAL_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueue)->Clear((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueue); - - // Make sure the client is aware that the device has stopped. There may be an OpenSL|ES callback for this, but I haven't found it. - mal_stop_proc onStop = pDevice->onStop; - if (onStop) { - onStop(pDevice); - } - - return MAL_SUCCESS; -} - - -mal_result mal_context_uninit__opensl(mal_context* pContext) -{ - mal_assert(pContext != NULL); - mal_assert(pContext->backend == mal_backend_opensl); - (void)pContext; - - // Uninit global data. - if (g_malOpenSLInitCounter > 0) { - if (mal_atomic_decrement_32(&g_malOpenSLInitCounter) == 0) { - (*g_malEngineObjectSL)->Destroy(g_malEngineObjectSL); - } - } - - return MAL_SUCCESS; -} - -mal_result mal_context_init__opensl(mal_context* pContext) -{ - mal_assert(pContext != NULL); - (void)pContext; - - // Initialize global data first if applicable. - if (mal_atomic_increment_32(&g_malOpenSLInitCounter) == 1) { - SLresult resultSL = slCreateEngine(&g_malEngineObjectSL, 0, NULL, 0, NULL, NULL); - if (resultSL != SL_RESULT_SUCCESS) { - mal_atomic_decrement_32(&g_malOpenSLInitCounter); - return MAL_NO_BACKEND; - } - - (*g_malEngineObjectSL)->Realize(g_malEngineObjectSL, SL_BOOLEAN_FALSE); - - resultSL = (*g_malEngineObjectSL)->GetInterface(g_malEngineObjectSL, SL_IID_ENGINE, &g_malEngineSL); - if (resultSL != SL_RESULT_SUCCESS) { - (*g_malEngineObjectSL)->Destroy(g_malEngineObjectSL); - mal_atomic_decrement_32(&g_malOpenSLInitCounter); - return MAL_NO_BACKEND; - } - } - - pContext->isBackendAsynchronous = MAL_TRUE; - - pContext->onUninit = mal_context_uninit__opensl; - pContext->onDeviceIDEqual = mal_context_is_device_id_equal__opensl; - pContext->onEnumDevices = mal_context_enumerate_devices__opensl; - pContext->onGetDeviceInfo = mal_context_get_device_info__opensl; - pContext->onDeviceInit = mal_device_init__opensl; - pContext->onDeviceUninit = mal_device_uninit__opensl; - pContext->onDeviceStart = mal_device_start__opensl; - pContext->onDeviceStop = mal_device_stop__opensl; - - return MAL_SUCCESS; -} -#endif // OpenSL|ES - - -/////////////////////////////////////////////////////////////////////////////// -// -// Web Audio Backend -// -/////////////////////////////////////////////////////////////////////////////// -#ifdef MAL_HAS_WEBAUDIO -#include - -mal_bool32 mal_is_capture_supported__webaudio() -{ - return EM_ASM_INT({ - return (navigator.mediaDevices !== undefined && navigator.mediaDevices.getUserMedia !== undefined); - }, 0) != 0; /* Must pass in a dummy argument for C99 compatibility. */ -} - -#ifdef __cplusplus -extern "C" { -#endif -EMSCRIPTEN_KEEPALIVE void mal_device_process_pcm_frames__webaudio(mal_device* pDevice, int frameCount, float* pFrames) -{ - if (pDevice->type == mal_device_type_playback) { - /* Playback. Write to pFrames. */ - mal_device__read_frames_from_client(pDevice, (mal_uint32)frameCount, pFrames); - } else { - /* Capture. Read from pFrames. */ - mal_device__send_frames_to_client(pDevice, (mal_uint32)frameCount, pFrames); - } -} -#ifdef __cplusplus -} -#endif - -mal_bool32 mal_context_is_device_id_equal__webaudio(mal_context* pContext, const mal_device_id* pID0, const mal_device_id* pID1) -{ - mal_assert(pContext != NULL); - mal_assert(pID0 != NULL); - mal_assert(pID1 != NULL); - (void)pContext; - - return mal_strcmp(pID0->webaudio, pID1->webaudio) == 0; -} - -mal_result mal_context_enumerate_devices__webaudio(mal_context* pContext, mal_enum_devices_callback_proc callback, void* pUserData) -{ - mal_assert(pContext != NULL); - mal_assert(callback != NULL); - - // Only supporting default devices for now. - mal_bool32 cbResult = MAL_TRUE; - - // Playback. - if (cbResult) { - mal_device_info deviceInfo; - mal_zero_object(&deviceInfo); - mal_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MAL_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); - cbResult = callback(pContext, mal_device_type_playback, &deviceInfo, pUserData); - } - - // Capture. - if (cbResult) { - if (mal_is_capture_supported__webaudio()) { - mal_device_info deviceInfo; - mal_zero_object(&deviceInfo); - mal_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MAL_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); - cbResult = callback(pContext, mal_device_type_capture, &deviceInfo, pUserData); - } - } - - return MAL_SUCCESS; -} - -mal_result mal_context_get_device_info__webaudio(mal_context* pContext, mal_device_type deviceType, const mal_device_id* pDeviceID, mal_share_mode shareMode, mal_device_info* pDeviceInfo) -{ - mal_assert(pContext != NULL); - (void)shareMode; - - if (deviceType == mal_device_type_capture && !mal_is_capture_supported__webaudio()) { - return MAL_NO_DEVICE; - } - - - mal_zero_memory(pDeviceInfo->id.webaudio, sizeof(pDeviceInfo->id.webaudio)); - - /* Only supporting default devices for now. */ - if (deviceType == mal_device_type_playback) { - mal_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MAL_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); - } else { - mal_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MAL_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); - } - - /* Web Audio can support any number of channels and sample rates. It only supports f32 formats, however. */ - pDeviceInfo->minChannels = 1; - pDeviceInfo->maxChannels = MAL_MAX_CHANNELS; - if (pDeviceInfo->maxChannels > 32) { - pDeviceInfo->maxChannels = 32; /* Maximum output channel count is 32 for createScriptProcessor() (JavaScript). */ - } - - /* We can query the sample rate by just using a temporary audio context. */ - pDeviceInfo->minSampleRate = EM_ASM_INT({ - try { - var temp = new (window.AudioContext || window.webkitAudioContext)(); - var sampleRate = temp.sampleRate; - temp.close(); - return sampleRate; - } catch(e) { - return 0; - } - }, 0); /* Must pass in a dummy argument for C99 compatibility. */ - pDeviceInfo->maxSampleRate = pDeviceInfo->minSampleRate; - if (pDeviceInfo->minSampleRate == 0) { - return MAL_NO_DEVICE; - } - - /* Web Audio only supports f32. */ - pDeviceInfo->formatCount = 1; - pDeviceInfo->formats[0] = mal_format_f32; - - return MAL_SUCCESS; -} - - -void mal_device_uninit__webaudio(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - EM_ASM({ - var device = mal.get_device_by_index($0); - - /* Make sure all nodes are disconnected and marked for collection. */ - if (device.scriptNode !== undefined) { - device.scriptNode.onaudioprocess = function(e) {}; /* We want to reset the callback to ensure it doesn't get called after AudioContext.close() has returned. Shouldn't happen since we're disconnecting, but just to be safe... */ - device.scriptNode.disconnect(); - device.scriptNode = undefined; - } - if (device.streamNode !== undefined) { - device.streamNode.disconnect(); - device.streamNode = undefined; - } - - /* - Stop the device. I think there is a chance the callback could get fired after calling this, hence why we want - to clear the callback before closing. - */ - device.webaudio.close(); - device.webaudio = undefined; - - /* Can't forget to free the intermediary buffer. This is the buffer that's shared between JavaScript and C. */ - if (device.intermediaryBuffer !== undefined) { - Module._free(device.intermediaryBuffer); - device.intermediaryBuffer = undefined; - device.intermediaryBufferView = undefined; - device.intermediaryBufferSizeInBytes = undefined; - } - - /* Make sure the device is untracked so the slot can be reused later. */ - mal.untrack_device_by_index($0); - }, pDevice->webaudio.index, pDevice->type == mal_device_type_playback); -} - -mal_result mal_device_init__webaudio(mal_context* pContext, mal_device_type deviceType, const mal_device_id* pDeviceID, const mal_device_config* pConfig, mal_device* pDevice) -{ - if (deviceType == mal_device_type_capture && !mal_is_capture_supported__webaudio()) { - return MAL_NO_DEVICE; - } - - /* Try calculating an appropriate default buffer size. */ - if (pDevice->bufferSizeInFrames == 0) { - pDevice->bufferSizeInFrames = mal_calculate_buffer_size_in_frames_from_milliseconds(pDevice->bufferSizeInMilliseconds, pDevice->sampleRate); - if (pDevice->usingDefaultBufferSize) { - float bufferSizeScaleFactor = 1; - pDevice->bufferSizeInFrames = mal_scale_buffer_size(pDevice->bufferSizeInFrames, bufferSizeScaleFactor); - } - } - - /* The size of the buffer must be a power of 2 and between 256 and 16384. */ - if (pDevice->bufferSizeInFrames < 256) { - pDevice->bufferSizeInFrames = 256; - } else if (pDevice->bufferSizeInFrames > 16384) { - pDevice->bufferSizeInFrames = 16384; - } else { - pDevice->bufferSizeInFrames = mal_next_power_of_2(pDevice->bufferSizeInFrames); - } - - /* We create the device on the JavaScript side and reference it using an index. We use this to make it possible to reference the device between JavaScript and C. */ - pDevice->webaudio.index = EM_ASM_INT({ - var channels = $0; - var sampleRate = $1; - var bufferSize = $2; /* In PCM frames. */ - var isPlayback = $3; - var pDevice = $4; - - if (typeof(mal) === 'undefined') { - return -1; /* Context not initialized. */ - } - - var device = {}; - - /* The AudioContext must be created in a suspended state. */ - device.webaudio = new (window.AudioContext || window.webkitAudioContext)({sampleRate:sampleRate}); - device.webaudio.suspend(); - - /* - We need an intermediary buffer which we use for JavaScript and C interop. This buffer stores interleaved f32 PCM data. Because it's passed between - JavaScript and C it needs to be allocated and freed using Module._malloc() and Module._free(). - */ - device.intermediaryBufferSizeInBytes = channels * bufferSize * 4; - device.intermediaryBuffer = Module._malloc(device.intermediaryBufferSizeInBytes); - device.intermediaryBufferView = new Float32Array(Module.HEAPF32.buffer, device.intermediaryBuffer, device.intermediaryBufferSizeInBytes); - - /* - Both playback and capture devices use a ScriptProcessorNode for performing per-sample operations. - - ScriptProcessorNode is actually deprecated so this is likely to be temporary. The way this works for playback is very simple. You just set a callback - that's periodically fired, just like a normal audio callback function. But apparently this design is "flawed" and is now deprecated in favour of - something called AudioWorklets which _forces_ you to load a _separate_ .js file at run time... nice... Hopefully ScriptProcessorNode will continue to - work for years to come, but this may need to change to use AudioSourceBufferNode instead, which I think is what Emscripten uses for it's built-in SDL - implementation. I'll be avoiding that insane AudioWorklet API like the plague... - - For capture it is a bit unintuitive. We use the ScriptProccessorNode _only_ to get the raw PCM data. It is connected to an AudioContext just like the - playback case, however we just output silence to the AudioContext instead of passing any real data. It would make more sense to me to use the - MediaRecorder API, but unfortunately you need to specify a MIME time (Opus, Vorbis, etc.) for the binary blob that's returned to the client, but I've - been unable to figure out how to get this as raw PCM. The closes I can think is to use the MIME type for WAV files and just parse it, but I don't know - how well this would work. Although ScriptProccessorNode is deprecated, in practice it seems to have pretty good browser support so I'm leaving it like - this for now. If anything knows how I could get raw PCM data using the MediaRecorder API please let me know! - */ - device.scriptNode = device.webaudio.createScriptProcessor(bufferSize, channels, channels); - - if (isPlayback) { - device.scriptNode.onaudioprocess = function(e) { - if (device.intermediaryBuffer === undefined) { - return; /* This means the device has been uninitialized. */ - } - - var outputSilence = false; - - /* Sanity check. This will never happen, right? */ - if (e.outputBuffer.numberOfChannels != channels) { - console.log("Playback: Channel count mismatch. " + e.outputBufer.numberOfChannels + " != " + channels + ". Outputting silence."); - outputSilence = true; - return; - } - - /* This looped design guards against the situation where e.outputBuffer is a different size to the original buffer size. Should never happen in practice. */ - var totalFramesProcessed = 0; - while (totalFramesProcessed < e.outputBuffer.length) { - var framesRemaining = e.outputBuffer.length - totalFramesProcessed; - var framesToProcess = framesRemaining; - if (framesToProcess > (device.intermediaryBufferSizeInBytes/channels/4)) { - framesToProcess = (device.intermediaryBufferSizeInBytes/channels/4); - } - - /* Read data from the client into our intermediary buffer. */ - ccall("mal_device_process_pcm_frames__webaudio", "undefined", ["number", "number", "number"], [pDevice, framesToProcess, device.intermediaryBuffer]); - - /* At this point we'll have data in our intermediary buffer which we now need to deinterleave and copy over to the output buffers. */ - if (outputSilence) { - for (var iChannel = 0; iChannel < e.outputBuffer.numberOfChannels; ++iChannel) { - e.outputBuffer.getChannelData(iChannel).fill(0.0); - } - } else { - for (var iChannel = 0; iChannel < e.outputBuffer.numberOfChannels; ++iChannel) { - for (var iFrame = 0; iFrame < framesToProcess; ++iFrame) { - e.outputBuffer.getChannelData(iChannel)[totalFramesProcessed + iFrame] = device.intermediaryBufferView[iFrame*channels + iChannel]; - } - } - } - - totalFramesProcessed += framesToProcess; - } - }; - - device.scriptNode.connect(device.webaudio.destination); - } else { - device.scriptNode.onaudioprocess = function(e) { - if (device.intermediaryBuffer === undefined) { - return; /* This means the device has been uninitialized. */ - } - - /* Make sure silence it output to the AudioContext destination. Not doing this will cause sound to come out of the speakers! */ - for (var iChannel = 0; iChannel < e.outputBuffer.numberOfChannels; ++iChannel) { - e.outputBuffer.getChannelData(iChannel).fill(0.0); - } - - /* There are some situations where we may want to send silence to the client. */ - var sendSilence = false; - if (device.streamNode === undefined) { - sendSilence = true; - } - - /* Sanity check. This will never happen, right? */ - if (e.inputBuffer.numberOfChannels != channels) { - console.log("Capture: Channel count mismatch. " + e.inputBufer.numberOfChannels + " != " + channels + ". Sending silence."); - sendSilence = true; - } - - /* This looped design guards against the situation where e.inputBuffer is a different size to the original buffer size. Should never happen in practice. */ - var totalFramesProcessed = 0; - while (totalFramesProcessed < e.inputBuffer.length) { - var framesRemaining = e.inputBuffer.length - totalFramesProcessed; - var framesToProcess = framesRemaining; - if (framesToProcess > (device.intermediaryBufferSizeInBytes/channels/4)) { - framesToProcess = (device.intermediaryBufferSizeInBytes/channels/4); - } - - /* We need to do the reverse of the playback case. We need to interleave the input data and copy it into the intermediary buffer. Then we send it to the client. */ - if (sendSilence) { - device.intermediaryBufferView.fill(0.0); - } else { - for (var iFrame = 0; iFrame < framesToProcess; ++iFrame) { - for (var iChannel = 0; iChannel < e.inputBuffer.numberOfChannels; ++iChannel) { - device.intermediaryBufferView[iFrame*channels + iChannel] = e.inputBuffer.getChannelData(iChannel)[totalFramesProcessed + iFrame]; - } - } - } - - /* Send data to the client from our intermediary buffer. */ - ccall("mal_device_process_pcm_frames__webaudio", "undefined", ["number", "number", "number"], [pDevice, framesToProcess, device.intermediaryBuffer]); - - totalFramesProcessed += framesToProcess; - } - }; - - navigator.mediaDevices.getUserMedia({audio:true, video:false}) - .then(function(stream) { - device.streamNode = device.webaudio.createMediaStreamSource(stream); - device.streamNode.connect(device.scriptNode); - device.scriptNode.connect(device.webaudio.destination); - }) - .catch(function(error) { - /* I think this should output silence... */ - device.scriptNode.connect(device.webaudio.destination); - }); - } - - return mal.track_device(device); - }, pConfig->channels, pConfig->sampleRate, pDevice->bufferSizeInFrames, deviceType == mal_device_type_playback, pDevice); - - if (pDevice->webaudio.index < 0) { - return MAL_FAILED_TO_OPEN_BACKEND_DEVICE; - } - - pDevice->internalFormat = mal_format_f32; - pDevice->internalChannels = pConfig->channels; - pDevice->internalSampleRate = EM_ASM_INT({ return mal.get_device_by_index($0).webaudio.sampleRate; }, pDevice->webaudio.index); - mal_get_standard_channel_map(mal_standard_channel_map_webaudio, pDevice->internalChannels, pDevice->internalChannelMap); - pDevice->periods = 1; - - return MAL_SUCCESS; -} - -mal_result mal_device_start__webaudio(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - EM_ASM({ - mal.get_device_by_index($0).webaudio.resume(); - }, pDevice->webaudio.index); - - return MAL_SUCCESS; -} - -mal_result mal_device_stop__webaudio(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - EM_ASM({ - mal.get_device_by_index($0).webaudio.suspend(); - }, pDevice->webaudio.index); - - mal_stop_proc onStop = pDevice->onStop; - if (onStop) { - onStop(pDevice); - } - - return MAL_SUCCESS; -} - -mal_result mal_context_uninit__webaudio(mal_context* pContext) -{ - mal_assert(pContext != NULL); - mal_assert(pContext->backend == mal_backend_webaudio); - - /* Nothing needs to be done here. */ - (void)pContext; - - return MAL_SUCCESS; -} - -mal_result mal_context_init__webaudio(mal_context* pContext) -{ - mal_assert(pContext != NULL); - - /* Here is where our global JavaScript object is initialized. */ - int resultFromJS = EM_ASM_INT({ - if ((window.AudioContext || window.webkitAudioContext) === undefined) { - return 0; /* Web Audio not supported. */ - } - - if (typeof(mal) === 'undefined') { - mal = {}; - mal.devices = []; /* Device cache for mapping devices to indexes for JavaScript/C interop. */ - - mal.track_device = function(device) { - /* Try inserting into a free slot first. */ - for (var iDevice = 0; iDevice < mal.devices.length; ++iDevice) { - if (mal.devices[iDevice] == null) { - mal.devices[iDevice] = device; - return iDevice; - } - } - - /* Getting here means there is no empty slots in the array so we just push to the end. */ - mal.devices.push(device); - return mal.devices.length - 1; - }; - - mal.untrack_device_by_index = function(deviceIndex) { - /* We just set the device's slot to null. The slot will get reused in the next call to mal_track_device. */ - mal.devices[deviceIndex] = null; - - /* Trim the array if possible. */ - while (mal.devices.length > 0) { - if (mal.devices[mal.devices.length-1] == null) { - mal.devices.pop(); - } else { - break; - } - } - }; - - mal.untrack_device = function(device) { - for (var iDevice = 0; iDevice < mal.devices.length; ++iDevice) { - if (mal.devices[iDevice] == device) { - return mal.untrack_device_by_index(iDevice); - } - } - }; - - mal.get_device_by_index = function(deviceIndex) { - return mal.devices[deviceIndex]; - }; - } - - return 1; - }, 0); /* Must pass in a dummy argument for C99 compatibility. */ - - if (resultFromJS != 1) { - return MAL_FAILED_TO_INIT_BACKEND; - } - - - pContext->isBackendAsynchronous = MAL_TRUE; - - pContext->onUninit = mal_context_uninit__webaudio; - pContext->onDeviceIDEqual = mal_context_is_device_id_equal__webaudio; - pContext->onEnumDevices = mal_context_enumerate_devices__webaudio; - pContext->onGetDeviceInfo = mal_context_get_device_info__webaudio; - pContext->onDeviceInit = mal_device_init__webaudio; - pContext->onDeviceUninit = mal_device_uninit__webaudio; - pContext->onDeviceStart = mal_device_start__webaudio; - pContext->onDeviceStop = mal_device_stop__webaudio; - - return MAL_SUCCESS; -} -#endif // Web Audio - - -/////////////////////////////////////////////////////////////////////////////// -// -// OpenAL Backend -// -/////////////////////////////////////////////////////////////////////////////// -#ifdef MAL_HAS_OPENAL -#ifdef MAL_WIN32 -#define MAL_AL_APIENTRY __cdecl -#else -#define MAL_AL_APIENTRY -#endif - -#ifdef MAL_NO_RUNTIME_LINKING - #if defined(MAL_APPLE) - #include - #include - #else - #include - #include - #endif -#endif - -typedef struct mal_ALCdevice_struct mal_ALCdevice; -typedef struct mal_ALCcontext_struct mal_ALCcontext; -typedef char mal_ALCboolean; -typedef char mal_ALCchar; -typedef signed char mal_ALCbyte; -typedef unsigned char mal_ALCubyte; -typedef short mal_ALCshort; -typedef unsigned short mal_ALCushort; -typedef int mal_ALCint; -typedef unsigned int mal_ALCuint; -typedef int mal_ALCsizei; -typedef int mal_ALCenum; -typedef float mal_ALCfloat; -typedef double mal_ALCdouble; -typedef void mal_ALCvoid; - -typedef mal_ALCboolean mal_ALboolean; -typedef mal_ALCchar mal_ALchar; -typedef mal_ALCbyte mal_ALbyte; -typedef mal_ALCubyte mal_ALubyte; -typedef mal_ALCshort mal_ALshort; -typedef mal_ALCushort mal_ALushort; -typedef mal_ALCint mal_ALint; -typedef mal_ALCuint mal_ALuint; -typedef mal_ALCsizei mal_ALsizei; -typedef mal_ALCenum mal_ALenum; -typedef mal_ALCfloat mal_ALfloat; -typedef mal_ALCdouble mal_ALdouble; -typedef mal_ALCvoid mal_ALvoid; - -#define MAL_ALC_DEVICE_SPECIFIER 0x1005 -#define MAL_ALC_CAPTURE_DEVICE_SPECIFIER 0x310 -#define MAL_ALC_CAPTURE_SAMPLES 0x312 - -#define MAL_AL_SOURCE_STATE 0x1010 -#define MAL_AL_INITIAL 0x1011 -#define MAL_AL_PLAYING 0x1012 -#define MAL_AL_PAUSED 0x1013 -#define MAL_AL_STOPPED 0x1014 -#define MAL_AL_BUFFERS_PROCESSED 0x1016 - -#define MAL_AL_FORMAT_MONO8 0x1100 -#define MAL_AL_FORMAT_MONO16 0x1101 -#define MAL_AL_FORMAT_STEREO8 0x1102 -#define MAL_AL_FORMAT_STEREO16 0x1103 -#define MAL_AL_FORMAT_MONO_FLOAT32 0x10010 -#define MAL_AL_FORMAT_STEREO_FLOAT32 0x10011 -#define MAL_AL_FORMAT_51CHN16 0x120B -#define MAL_AL_FORMAT_51CHN32 0x120C -#define MAL_AL_FORMAT_51CHN8 0x120A -#define MAL_AL_FORMAT_61CHN16 0x120E -#define MAL_AL_FORMAT_61CHN32 0x120F -#define MAL_AL_FORMAT_61CHN8 0x120D -#define MAL_AL_FORMAT_71CHN16 0x1211 -#define MAL_AL_FORMAT_71CHN32 0x1212 -#define MAL_AL_FORMAT_71CHN8 0x1210 -#define MAL_AL_FORMAT_QUAD16 0x1205 -#define MAL_AL_FORMAT_QUAD32 0x1206 -#define MAL_AL_FORMAT_QUAD8 0x1204 -#define MAL_AL_FORMAT_REAR16 0x1208 -#define MAL_AL_FORMAT_REAR32 0x1209 -#define MAL_AL_FORMAT_REAR8 0x1207 - -typedef mal_ALCcontext* (MAL_AL_APIENTRY * MAL_LPALCCREATECONTEXT) (mal_ALCdevice *device, const mal_ALCint *attrlist); -typedef mal_ALCboolean (MAL_AL_APIENTRY * MAL_LPALCMAKECONTEXTCURRENT) (mal_ALCcontext *context); -typedef void (MAL_AL_APIENTRY * MAL_LPALCPROCESSCONTEXT) (mal_ALCcontext *context); -typedef void (MAL_AL_APIENTRY * MAL_LPALCSUSPENDCONTEXT) (mal_ALCcontext *context); -typedef void (MAL_AL_APIENTRY * MAL_LPALCDESTROYCONTEXT) (mal_ALCcontext *context); -typedef mal_ALCcontext* (MAL_AL_APIENTRY * MAL_LPALCGETCURRENTCONTEXT) (void); -typedef mal_ALCdevice* (MAL_AL_APIENTRY * MAL_LPALCGETCONTEXTSDEVICE) (mal_ALCcontext *context); -typedef mal_ALCdevice* (MAL_AL_APIENTRY * MAL_LPALCOPENDEVICE) (const mal_ALCchar *devicename); -typedef mal_ALCboolean (MAL_AL_APIENTRY * MAL_LPALCCLOSEDEVICE) (mal_ALCdevice *device); -typedef mal_ALCenum (MAL_AL_APIENTRY * MAL_LPALCGETERROR) (mal_ALCdevice *device); -typedef mal_ALCboolean (MAL_AL_APIENTRY * MAL_LPALCISEXTENSIONPRESENT) (mal_ALCdevice *device, const mal_ALCchar *extname); -typedef void* (MAL_AL_APIENTRY * MAL_LPALCGETPROCADDRESS) (mal_ALCdevice *device, const mal_ALCchar *funcname); -typedef mal_ALCenum (MAL_AL_APIENTRY * MAL_LPALCGETENUMVALUE) (mal_ALCdevice *device, const mal_ALCchar *enumname); -typedef const mal_ALCchar* (MAL_AL_APIENTRY * MAL_LPALCGETSTRING) (mal_ALCdevice *device, mal_ALCenum param); -typedef void (MAL_AL_APIENTRY * MAL_LPALCGETINTEGERV) (mal_ALCdevice *device, mal_ALCenum param, mal_ALCsizei size, mal_ALCint *values); -typedef mal_ALCdevice* (MAL_AL_APIENTRY * MAL_LPALCCAPTUREOPENDEVICE) (const mal_ALCchar *devicename, mal_ALCuint frequency, mal_ALCenum format, mal_ALCsizei buffersize); -typedef mal_ALCboolean (MAL_AL_APIENTRY * MAL_LPALCCAPTURECLOSEDEVICE) (mal_ALCdevice *device); -typedef void (MAL_AL_APIENTRY * MAL_LPALCCAPTURESTART) (mal_ALCdevice *device); -typedef void (MAL_AL_APIENTRY * MAL_LPALCCAPTURESTOP) (mal_ALCdevice *device); -typedef void (MAL_AL_APIENTRY * MAL_LPALCCAPTURESAMPLES) (mal_ALCdevice *device, mal_ALCvoid *buffer, mal_ALCsizei samples); - -typedef void (MAL_AL_APIENTRY * MAL_LPALENABLE) (mal_ALenum capability); -typedef void (MAL_AL_APIENTRY * MAL_LPALDISABLE) (mal_ALenum capability); -typedef mal_ALboolean (MAL_AL_APIENTRY * MAL_LPALISENABLED) (mal_ALenum capability); -typedef const mal_ALchar* (MAL_AL_APIENTRY * MAL_LPALGETSTRING) (mal_ALenum param); -typedef void (MAL_AL_APIENTRY * MAL_LPALGETBOOLEANV) (mal_ALenum param, mal_ALboolean *values); -typedef void (MAL_AL_APIENTRY * MAL_LPALGETINTEGERV) (mal_ALenum param, mal_ALint *values); -typedef void (MAL_AL_APIENTRY * MAL_LPALGETFLOATV) (mal_ALenum param, mal_ALfloat *values); -typedef void (MAL_AL_APIENTRY * MAL_LPALGETDOUBLEV) (mal_ALenum param, mal_ALdouble *values); -typedef mal_ALboolean (MAL_AL_APIENTRY * MAL_LPALGETBOOLEAN) (mal_ALenum param); -typedef mal_ALint (MAL_AL_APIENTRY * MAL_LPALGETINTEGER) (mal_ALenum param); -typedef mal_ALfloat (MAL_AL_APIENTRY * MAL_LPALGETFLOAT) (mal_ALenum param); -typedef mal_ALdouble (MAL_AL_APIENTRY * MAL_LPALGETDOUBLE) (mal_ALenum param); -typedef mal_ALenum (MAL_AL_APIENTRY * MAL_LPALGETERROR) (void); -typedef mal_ALboolean (MAL_AL_APIENTRY * MAL_LPALISEXTENSIONPRESENT) (const mal_ALchar *extname); -typedef void* (MAL_AL_APIENTRY * MAL_LPALGETPROCADDRESS) (const mal_ALchar *fname); -typedef mal_ALenum (MAL_AL_APIENTRY * MAL_LPALGETENUMVALUE) (const mal_ALchar *ename); -typedef void (MAL_AL_APIENTRY * MAL_LPALGENSOURCES) (mal_ALsizei n, mal_ALuint *sources); -typedef void (MAL_AL_APIENTRY * MAL_LPALDELETESOURCES) (mal_ALsizei n, const mal_ALuint *sources); -typedef mal_ALboolean (MAL_AL_APIENTRY * MAL_LPALISSOURCE) (mal_ALuint source); -typedef void (MAL_AL_APIENTRY * MAL_LPALSOURCEF) (mal_ALuint source, mal_ALenum param, mal_ALfloat value); -typedef void (MAL_AL_APIENTRY * MAL_LPALSOURCE3F) (mal_ALuint source, mal_ALenum param, mal_ALfloat value1, mal_ALfloat value2, mal_ALfloat value3); -typedef void (MAL_AL_APIENTRY * MAL_LPALSOURCEFV) (mal_ALuint source, mal_ALenum param, const mal_ALfloat *values); -typedef void (MAL_AL_APIENTRY * MAL_LPALSOURCEI) (mal_ALuint source, mal_ALenum param, mal_ALint value); -typedef void (MAL_AL_APIENTRY * MAL_LPALSOURCE3I) (mal_ALuint source, mal_ALenum param, mal_ALint value1, mal_ALint value2, mal_ALint value3); -typedef void (MAL_AL_APIENTRY * MAL_LPALSOURCEIV) (mal_ALuint source, mal_ALenum param, const mal_ALint *values); -typedef void (MAL_AL_APIENTRY * MAL_LPALGETSOURCEF) (mal_ALuint source, mal_ALenum param, mal_ALfloat *value); -typedef void (MAL_AL_APIENTRY * MAL_LPALGETSOURCE3F) (mal_ALuint source, mal_ALenum param, mal_ALfloat *value1, mal_ALfloat *value2, mal_ALfloat *value3); -typedef void (MAL_AL_APIENTRY * MAL_LPALGETSOURCEFV) (mal_ALuint source, mal_ALenum param, mal_ALfloat *values); -typedef void (MAL_AL_APIENTRY * MAL_LPALGETSOURCEI) (mal_ALuint source, mal_ALenum param, mal_ALint *value); -typedef void (MAL_AL_APIENTRY * MAL_LPALGETSOURCE3I) (mal_ALuint source, mal_ALenum param, mal_ALint *value1, mal_ALint *value2, mal_ALint *value3); -typedef void (MAL_AL_APIENTRY * MAL_LPALGETSOURCEIV) (mal_ALuint source, mal_ALenum param, mal_ALint *values); -typedef void (MAL_AL_APIENTRY * MAL_LPALSOURCEPLAYV) (mal_ALsizei n, const mal_ALuint *sources); -typedef void (MAL_AL_APIENTRY * MAL_LPALSOURCESTOPV) (mal_ALsizei n, const mal_ALuint *sources); -typedef void (MAL_AL_APIENTRY * MAL_LPALSOURCEREWINDV) (mal_ALsizei n, const mal_ALuint *sources); -typedef void (MAL_AL_APIENTRY * MAL_LPALSOURCEPAUSEV) (mal_ALsizei n, const mal_ALuint *sources); -typedef void (MAL_AL_APIENTRY * MAL_LPALSOURCEPLAY) (mal_ALuint source); -typedef void (MAL_AL_APIENTRY * MAL_LPALSOURCESTOP) (mal_ALuint source); -typedef void (MAL_AL_APIENTRY * MAL_LPALSOURCEREWIND) (mal_ALuint source); -typedef void (MAL_AL_APIENTRY * MAL_LPALSOURCEPAUSE) (mal_ALuint source); -typedef void (MAL_AL_APIENTRY * MAL_LPALSOURCEQUEUEBUFFERS) (mal_ALuint source, mal_ALsizei nb, const mal_ALuint *buffers); -typedef void (MAL_AL_APIENTRY * MAL_LPALSOURCEUNQUEUEBUFFERS)(mal_ALuint source, mal_ALsizei nb, mal_ALuint *buffers); -typedef void (MAL_AL_APIENTRY * MAL_LPALGENBUFFERS) (mal_ALsizei n, mal_ALuint *buffers); -typedef void (MAL_AL_APIENTRY * MAL_LPALDELETEBUFFERS) (mal_ALsizei n, const mal_ALuint *buffers); -typedef mal_ALboolean (MAL_AL_APIENTRY * MAL_LPALISBUFFER) (mal_ALuint buffer); -typedef void (MAL_AL_APIENTRY * MAL_LPALBUFFERDATA) (mal_ALuint buffer, mal_ALenum format, const mal_ALvoid *data, mal_ALsizei size, mal_ALsizei freq); -typedef void (MAL_AL_APIENTRY * MAL_LPALBUFFERF) (mal_ALuint buffer, mal_ALenum param, mal_ALfloat value); -typedef void (MAL_AL_APIENTRY * MAL_LPALBUFFER3F) (mal_ALuint buffer, mal_ALenum param, mal_ALfloat value1, mal_ALfloat value2, mal_ALfloat value3); -typedef void (MAL_AL_APIENTRY * MAL_LPALBUFFERFV) (mal_ALuint buffer, mal_ALenum param, const mal_ALfloat *values); -typedef void (MAL_AL_APIENTRY * MAL_LPALBUFFERI) (mal_ALuint buffer, mal_ALenum param, mal_ALint value); -typedef void (MAL_AL_APIENTRY * MAL_LPALBUFFER3I) (mal_ALuint buffer, mal_ALenum param, mal_ALint value1, mal_ALint value2, mal_ALint value3); -typedef void (MAL_AL_APIENTRY * MAL_LPALBUFFERIV) (mal_ALuint buffer, mal_ALenum param, const mal_ALint *values); -typedef void (MAL_AL_APIENTRY * MAL_LPALGETBUFFERF) (mal_ALuint buffer, mal_ALenum param, mal_ALfloat *value); -typedef void (MAL_AL_APIENTRY * MAL_LPALGETBUFFER3F) (mal_ALuint buffer, mal_ALenum param, mal_ALfloat *value1, mal_ALfloat *value2, mal_ALfloat *value3); -typedef void (MAL_AL_APIENTRY * MAL_LPALGETBUFFERFV) (mal_ALuint buffer, mal_ALenum param, mal_ALfloat *values); -typedef void (MAL_AL_APIENTRY * MAL_LPALGETBUFFERI) (mal_ALuint buffer, mal_ALenum param, mal_ALint *value); -typedef void (MAL_AL_APIENTRY * MAL_LPALGETBUFFER3I) (mal_ALuint buffer, mal_ALenum param, mal_ALint *value1, mal_ALint *value2, mal_ALint *value3); -typedef void (MAL_AL_APIENTRY * MAL_LPALGETBUFFERIV) (mal_ALuint buffer, mal_ALenum param, mal_ALint *values); - -mal_bool32 mal_context_is_device_id_equal__openal(mal_context* pContext, const mal_device_id* pID0, const mal_device_id* pID1) -{ - mal_assert(pContext != NULL); - mal_assert(pID0 != NULL); - mal_assert(pID1 != NULL); - (void)pContext; - - return mal_strcmp(pID0->openal, pID1->openal) == 0; -} - -mal_result mal_context_enumerate_devices__openal(mal_context* pContext, mal_enum_devices_callback_proc callback, void* pUserData) -{ - mal_assert(pContext != NULL); - mal_assert(callback != NULL); - - if (pContext->openal.isEnumerationSupported) { - mal_bool32 isTerminated = MAL_FALSE; - - // Playback - if (!isTerminated) { - const mal_ALCchar* pPlaybackDeviceNames = ((MAL_LPALCGETSTRING)pContext->openal.alcGetString)(NULL, MAL_ALC_DEVICE_SPECIFIER); - if (pPlaybackDeviceNames == NULL) { - return MAL_NO_DEVICE; - } - - // Each device is stored in pDeviceNames, separated by a null-terminator. The string itself is double-null-terminated. - const mal_ALCchar* pNextPlaybackDeviceName = pPlaybackDeviceNames; - while (pNextPlaybackDeviceName[0] != '\0') { - mal_device_info deviceInfo; - mal_zero_object(&deviceInfo); - mal_strncpy_s(deviceInfo.id.openal, sizeof(deviceInfo.id.openal), (const char*)pNextPlaybackDeviceName, (size_t)-1); - mal_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), (const char*)pNextPlaybackDeviceName, (size_t)-1); - - mal_bool32 cbResult = callback(pContext, mal_device_type_playback, &deviceInfo, pUserData); - if (cbResult == MAL_FALSE) { - isTerminated = MAL_TRUE; - break; - } - - // Move to the next device name. - while (*pNextPlaybackDeviceName != '\0') { - pNextPlaybackDeviceName += 1; - } - - // Skip past the null terminator. - pNextPlaybackDeviceName += 1; - }; - } - - // Capture - if (!isTerminated) { - const mal_ALCchar* pCaptureDeviceNames = ((MAL_LPALCGETSTRING)pContext->openal.alcGetString)(NULL, MAL_ALC_CAPTURE_DEVICE_SPECIFIER); - if (pCaptureDeviceNames == NULL) { - return MAL_NO_DEVICE; - } - - const mal_ALCchar* pNextCaptureDeviceName = pCaptureDeviceNames; - while (pNextCaptureDeviceName[0] != '\0') { - mal_device_info deviceInfo; - mal_zero_object(&deviceInfo); - mal_strncpy_s(deviceInfo.id.openal, sizeof(deviceInfo.id.openal), (const char*)pNextCaptureDeviceName, (size_t)-1); - mal_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), (const char*)pNextCaptureDeviceName, (size_t)-1); - - mal_bool32 cbResult = callback(pContext, mal_device_type_capture, &deviceInfo, pUserData); - if (cbResult == MAL_FALSE) { - isTerminated = MAL_TRUE; - break; - } - - // Move to the next device name. - while (*pNextCaptureDeviceName != '\0') { - pNextCaptureDeviceName += 1; - } - - // Skip past the null terminator. - pNextCaptureDeviceName += 1; - }; - } - } else { - // Enumeration is not supported. Use default devices. - mal_bool32 cbResult = MAL_TRUE; - - // Playback. - if (cbResult) { - mal_device_info deviceInfo; - mal_zero_object(&deviceInfo); - mal_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MAL_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); - cbResult = callback(pContext, mal_device_type_playback, &deviceInfo, pUserData); - } - - // Capture. - if (cbResult) { - mal_device_info deviceInfo; - mal_zero_object(&deviceInfo); - mal_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MAL_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); - cbResult = callback(pContext, mal_device_type_capture, &deviceInfo, pUserData); - } - } - - return MAL_SUCCESS; -} - - -typedef struct -{ - mal_device_type deviceType; - const mal_device_id* pDeviceID; - mal_share_mode shareMode; - mal_device_info* pDeviceInfo; - mal_bool32 foundDevice; -} mal_context_get_device_info_enum_callback_data__openal; - -mal_bool32 mal_context_get_device_info_enum_callback__openal(mal_context* pContext, mal_device_type deviceType, const mal_device_info* pDeviceInfo, void* pUserData) -{ - mal_context_get_device_info_enum_callback_data__openal* pData = (mal_context_get_device_info_enum_callback_data__openal*)pUserData; - mal_assert(pData != NULL); - - if (pData->deviceType == deviceType && mal_context_is_device_id_equal__openal(pContext, pData->pDeviceID, &pDeviceInfo->id)) { - mal_strncpy_s(pData->pDeviceInfo->name, sizeof(pData->pDeviceInfo->name), pDeviceInfo->name, (size_t)-1); - pData->foundDevice = MAL_TRUE; - } - - // Keep enumerating until we have found the device. - return !pData->foundDevice; -} - -mal_result mal_context_get_device_info__openal(mal_context* pContext, mal_device_type deviceType, const mal_device_id* pDeviceID, mal_share_mode shareMode, mal_device_info* pDeviceInfo) -{ - mal_assert(pContext != NULL); - (void)shareMode; - - // Name / Description - if (pDeviceID == NULL) { - if (deviceType == mal_device_type_playback) { - mal_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MAL_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); - } else { - mal_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MAL_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); - } - - return MAL_SUCCESS; - } else { - mal_context_get_device_info_enum_callback_data__openal data; - data.deviceType = deviceType; - data.pDeviceID = pDeviceID; - data.shareMode = shareMode; - data.pDeviceInfo = pDeviceInfo; - data.foundDevice = MAL_FALSE; - mal_result result = mal_context_enumerate_devices__openal(pContext, mal_context_get_device_info_enum_callback__openal, &data); - if (result != MAL_SUCCESS) { - return result; - } - - if (!data.foundDevice) { - return MAL_NO_DEVICE; - } - } - - // mini_al's OpenAL backend only supports: - // - mono and stereo - // - u8, s16 and f32 - // - All standard sample rates - pDeviceInfo->minChannels = 1; - pDeviceInfo->maxChannels = 2; - pDeviceInfo->minSampleRate = MAL_MIN_SAMPLE_RATE; - pDeviceInfo->maxSampleRate = MAL_MAX_SAMPLE_RATE; - pDeviceInfo->formatCount = 2; - pDeviceInfo->formats[0] = mal_format_u8; - pDeviceInfo->formats[1] = mal_format_s16; - if (pContext->openal.isFloat32Supported) { - pDeviceInfo->formats[pDeviceInfo->formatCount] = mal_format_f32; - pDeviceInfo->formatCount += 1; - } - - return MAL_SUCCESS; -} - - -void mal_device_uninit__openal(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - // Delete buffers and source first. - ((MAL_LPALCMAKECONTEXTCURRENT)pDevice->pContext->openal.alcMakeContextCurrent)((mal_ALCcontext*)pDevice->openal.pContextALC); - if (pDevice->openal.sourceAL != 0) { - ((MAL_LPALDELETESOURCES)pDevice->pContext->openal.alDeleteSources)(1, (const mal_ALuint*)&pDevice->openal.sourceAL); - } - if (pDevice->periods > 0 && pDevice->openal.buffersAL[0] != 0) { - ((MAL_LPALDELETEBUFFERS)pDevice->pContext->openal.alDeleteBuffers)(pDevice->periods, (const mal_ALuint*)pDevice->openal.buffersAL); - } - - - // Now that resources have been deleted we can destroy the OpenAL context and close the device. - ((MAL_LPALCMAKECONTEXTCURRENT)pDevice->pContext->openal.alcMakeContextCurrent)(NULL); - ((MAL_LPALCDESTROYCONTEXT)pDevice->pContext->openal.alcDestroyContext)((mal_ALCcontext*)pDevice->openal.pContextALC); - - if (pDevice->type == mal_device_type_playback) { - ((MAL_LPALCCLOSEDEVICE)pDevice->pContext->openal.alcCloseDevice)((mal_ALCdevice*)pDevice->openal.pDeviceALC); - } else { - ((MAL_LPALCCAPTURECLOSEDEVICE)pDevice->pContext->openal.alcCaptureCloseDevice)((mal_ALCdevice*)pDevice->openal.pDeviceALC); - } - - mal_free(pDevice->openal.pIntermediaryBuffer); -} - -mal_result mal_device_init__openal(mal_context* pContext, mal_device_type type, const mal_device_id* pDeviceID, const mal_device_config* pConfig, mal_device* pDevice) -{ - if (pDevice->periods > MAL_MAX_PERIODS_OPENAL) { - pDevice->periods = MAL_MAX_PERIODS_OPENAL; - } - - // Try calculating an appropriate default buffer size. - if (pDevice->bufferSizeInFrames == 0) { - pDevice->bufferSizeInFrames = mal_calculate_buffer_size_in_frames_from_milliseconds(pDevice->bufferSizeInMilliseconds, pDevice->sampleRate); - if (pDevice->usingDefaultBufferSize) { - float bufferSizeScaleFactor = 3; - pDevice->bufferSizeInFrames = mal_scale_buffer_size(pDevice->bufferSizeInFrames, bufferSizeScaleFactor); - } - } - - mal_ALCsizei bufferSizeInSamplesAL = pDevice->bufferSizeInFrames; - mal_ALCuint frequencyAL = pConfig->sampleRate; - - mal_uint32 channelsAL = 0; - - // OpenAL currently only supports only mono and stereo. TODO: Check for the AL_EXT_MCFORMATS extension and use one of those formats for quad, 5.1, etc. - mal_ALCenum formatAL = 0; - if (pConfig->channels == 1) { - // Mono. - channelsAL = 1; - if (pConfig->format == mal_format_f32) { - if (pContext->openal.isFloat32Supported) { - formatAL = MAL_AL_FORMAT_MONO_FLOAT32; - } else { - formatAL = MAL_AL_FORMAT_MONO16; - } - } else if (pConfig->format == mal_format_s32) { - formatAL = MAL_AL_FORMAT_MONO16; - } else if (pConfig->format == mal_format_s24) { - formatAL = MAL_AL_FORMAT_MONO16; - } else if (pConfig->format == mal_format_s16) { - formatAL = MAL_AL_FORMAT_MONO16; - } else if (pConfig->format == mal_format_u8) { - formatAL = MAL_AL_FORMAT_MONO8; - } - } else { - // Stereo. - channelsAL = 2; - if (pConfig->format == mal_format_f32) { - if (pContext->openal.isFloat32Supported) { - formatAL = MAL_AL_FORMAT_STEREO_FLOAT32; - } else { - formatAL = MAL_AL_FORMAT_STEREO16; - } - } else if (pConfig->format == mal_format_s32) { - formatAL = MAL_AL_FORMAT_STEREO16; - } else if (pConfig->format == mal_format_s24) { - formatAL = MAL_AL_FORMAT_STEREO16; - } else if (pConfig->format == mal_format_s16) { - formatAL = MAL_AL_FORMAT_STEREO16; - } else if (pConfig->format == mal_format_u8) { - formatAL = MAL_AL_FORMAT_STEREO8; - } - } - - if (formatAL == 0) { - return mal_context_post_error(pContext, NULL, MAL_LOG_LEVEL_ERROR, "[OpenAL] Format not supported.", MAL_FORMAT_NOT_SUPPORTED); - } - - bufferSizeInSamplesAL *= channelsAL; - - - // OpenAL feels a bit unintuitive to me... The global object is a device, and it would appear that each device can have - // many context's... - mal_ALCdevice* pDeviceALC = NULL; - if (type == mal_device_type_playback) { - pDeviceALC = ((MAL_LPALCOPENDEVICE)pContext->openal.alcOpenDevice)((pDeviceID == NULL) ? NULL : pDeviceID->openal); - } else { - pDeviceALC = ((MAL_LPALCCAPTUREOPENDEVICE)pContext->openal.alcCaptureOpenDevice)((pDeviceID == NULL) ? NULL : pDeviceID->openal, frequencyAL, formatAL, bufferSizeInSamplesAL); - } - - if (pDeviceALC == NULL) { - return mal_context_post_error(pContext, NULL, MAL_LOG_LEVEL_ERROR, "[OpenAL] Failed to open device.", MAL_FAILED_TO_INIT_BACKEND); - } - - // A context is only required for playback. - mal_ALCcontext* pContextALC = NULL; - if (pDevice->type == mal_device_type_playback) { - pContextALC = ((MAL_LPALCCREATECONTEXT)pContext->openal.alcCreateContext)(pDeviceALC, NULL); - if (pContextALC == NULL) { - ((MAL_LPALCCLOSEDEVICE)pDevice->pContext->openal.alcCloseDevice)(pDeviceALC); - return mal_context_post_error(pContext, NULL, MAL_LOG_LEVEL_ERROR, "[OpenAL] Failed to open OpenAL context.", MAL_FAILED_TO_INIT_BACKEND); - } - - ((MAL_LPALCMAKECONTEXTCURRENT)pDevice->pContext->openal.alcMakeContextCurrent)(pContextALC); - - mal_ALuint sourceAL; - ((MAL_LPALGENSOURCES)pDevice->pContext->openal.alGenSources)(1, &sourceAL); - pDevice->openal.sourceAL = sourceAL; - - // We create the buffers, but only fill and queue them when the device is started. - mal_ALuint buffersAL[MAL_MAX_PERIODS_OPENAL]; - ((MAL_LPALGENBUFFERS)pDevice->pContext->openal.alGenBuffers)(pDevice->periods, buffersAL); - for (mal_uint32 i = 0; i < pDevice->periods; ++i) { - pDevice->openal.buffersAL[i] = buffersAL[i]; - } - } - - pDevice->internalChannels = channelsAL; - pDevice->internalSampleRate = frequencyAL; - - switch (formatAL) - { - case MAL_AL_FORMAT_MONO8: - case MAL_AL_FORMAT_STEREO8: - case MAL_AL_FORMAT_REAR8: - case MAL_AL_FORMAT_QUAD8: - case MAL_AL_FORMAT_51CHN8: - case MAL_AL_FORMAT_61CHN8: - case MAL_AL_FORMAT_71CHN8: - { - pDevice->internalFormat = mal_format_u8; - } break; - - case MAL_AL_FORMAT_MONO16: - case MAL_AL_FORMAT_STEREO16: - case MAL_AL_FORMAT_REAR16: - case MAL_AL_FORMAT_QUAD16: - case MAL_AL_FORMAT_51CHN16: - case MAL_AL_FORMAT_61CHN16: - case MAL_AL_FORMAT_71CHN16: - { - pDevice->internalFormat = mal_format_s16; - } break; - - case MAL_AL_FORMAT_REAR32: - case MAL_AL_FORMAT_QUAD32: - case MAL_AL_FORMAT_51CHN32: - case MAL_AL_FORMAT_61CHN32: - case MAL_AL_FORMAT_71CHN32: - { - pDevice->internalFormat = mal_format_s32; - } break; - - case MAL_AL_FORMAT_MONO_FLOAT32: - case MAL_AL_FORMAT_STEREO_FLOAT32: - { - pDevice->internalFormat = mal_format_f32; - } break; - } - - // From what I can tell, the ordering of channels is fixed for OpenAL. - switch (formatAL) - { - case MAL_AL_FORMAT_MONO8: - case MAL_AL_FORMAT_MONO16: - case MAL_AL_FORMAT_MONO_FLOAT32: - { - pDevice->internalChannelMap[0] = MAL_CHANNEL_FRONT_CENTER; - } break; - - case MAL_AL_FORMAT_STEREO8: - case MAL_AL_FORMAT_STEREO16: - case MAL_AL_FORMAT_STEREO_FLOAT32: - { - pDevice->internalChannelMap[0] = MAL_CHANNEL_FRONT_LEFT; - pDevice->internalChannelMap[1] = MAL_CHANNEL_FRONT_RIGHT; - } break; - - case MAL_AL_FORMAT_REAR8: - case MAL_AL_FORMAT_REAR16: - case MAL_AL_FORMAT_REAR32: - { - pDevice->internalChannelMap[0] = MAL_CHANNEL_BACK_LEFT; - pDevice->internalChannelMap[1] = MAL_CHANNEL_BACK_RIGHT; - } break; - - case MAL_AL_FORMAT_QUAD8: - case MAL_AL_FORMAT_QUAD16: - case MAL_AL_FORMAT_QUAD32: - { - pDevice->internalChannelMap[0] = MAL_CHANNEL_FRONT_LEFT; - pDevice->internalChannelMap[1] = MAL_CHANNEL_FRONT_RIGHT; - pDevice->internalChannelMap[2] = MAL_CHANNEL_BACK_LEFT; - pDevice->internalChannelMap[3] = MAL_CHANNEL_BACK_RIGHT; - } break; - - case MAL_AL_FORMAT_51CHN8: - case MAL_AL_FORMAT_51CHN16: - case MAL_AL_FORMAT_51CHN32: - { - pDevice->internalChannelMap[0] = MAL_CHANNEL_FRONT_LEFT; - pDevice->internalChannelMap[1] = MAL_CHANNEL_FRONT_RIGHT; - pDevice->internalChannelMap[2] = MAL_CHANNEL_FRONT_CENTER; - pDevice->internalChannelMap[3] = MAL_CHANNEL_LFE; - pDevice->internalChannelMap[4] = MAL_CHANNEL_BACK_LEFT; - pDevice->internalChannelMap[5] = MAL_CHANNEL_BACK_RIGHT; - } break; - - case MAL_AL_FORMAT_61CHN8: - case MAL_AL_FORMAT_61CHN16: - case MAL_AL_FORMAT_61CHN32: - { - pDevice->internalChannelMap[0] = MAL_CHANNEL_FRONT_LEFT; - pDevice->internalChannelMap[1] = MAL_CHANNEL_FRONT_RIGHT; - pDevice->internalChannelMap[2] = MAL_CHANNEL_FRONT_CENTER; - pDevice->internalChannelMap[3] = MAL_CHANNEL_LFE; - pDevice->internalChannelMap[4] = MAL_CHANNEL_BACK_CENTER; - pDevice->internalChannelMap[5] = MAL_CHANNEL_SIDE_LEFT; - pDevice->internalChannelMap[6] = MAL_CHANNEL_SIDE_RIGHT; - } break; - - case MAL_AL_FORMAT_71CHN8: - case MAL_AL_FORMAT_71CHN16: - case MAL_AL_FORMAT_71CHN32: - { - pDevice->internalChannelMap[0] = MAL_CHANNEL_FRONT_LEFT; - pDevice->internalChannelMap[1] = MAL_CHANNEL_FRONT_RIGHT; - pDevice->internalChannelMap[2] = MAL_CHANNEL_FRONT_CENTER; - pDevice->internalChannelMap[3] = MAL_CHANNEL_LFE; - pDevice->internalChannelMap[4] = MAL_CHANNEL_BACK_LEFT; - pDevice->internalChannelMap[5] = MAL_CHANNEL_BACK_RIGHT; - pDevice->internalChannelMap[6] = MAL_CHANNEL_SIDE_LEFT; - pDevice->internalChannelMap[7] = MAL_CHANNEL_SIDE_RIGHT; - } break; - - default: break; - } - - pDevice->openal.pDeviceALC = pDeviceALC; - pDevice->openal.pContextALC = pContextALC; - pDevice->openal.formatAL = formatAL; - pDevice->openal.subBufferSizeInFrames = pDevice->bufferSizeInFrames / pDevice->periods; - pDevice->openal.pIntermediaryBuffer = (mal_uint8*)mal_malloc(pDevice->openal.subBufferSizeInFrames * channelsAL * mal_get_bytes_per_sample(pDevice->internalFormat)); - if (pDevice->openal.pIntermediaryBuffer == NULL) { - mal_device_uninit__openal(pDevice); - return mal_context_post_error(pContext, NULL, MAL_LOG_LEVEL_ERROR, "[OpenAL] Failed to allocate memory for intermediary buffer.", MAL_OUT_OF_MEMORY); - } - - return MAL_SUCCESS; -} - -mal_result mal_device_start__openal(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - if (pDevice->type == mal_device_type_playback) { - // Playback. - // - // When starting playback we want to ensure each buffer is filled and queued before playing the source. - pDevice->openal.iNextBuffer = 0; - - ((MAL_LPALCMAKECONTEXTCURRENT)pDevice->pContext->openal.alcMakeContextCurrent)((mal_ALCcontext*)pDevice->openal.pContextALC); - - for (mal_uint32 i = 0; i < pDevice->periods; ++i) { - mal_device__read_frames_from_client(pDevice, pDevice->openal.subBufferSizeInFrames, pDevice->openal.pIntermediaryBuffer); - - mal_ALuint bufferAL = pDevice->openal.buffersAL[i]; - ((MAL_LPALBUFFERDATA)pDevice->pContext->openal.alBufferData)(bufferAL, pDevice->openal.formatAL, pDevice->openal.pIntermediaryBuffer, pDevice->openal.subBufferSizeInFrames * pDevice->internalChannels * mal_get_bytes_per_sample(pDevice->internalFormat), pDevice->internalSampleRate); - ((MAL_LPALSOURCEQUEUEBUFFERS)pDevice->pContext->openal.alSourceQueueBuffers)(pDevice->openal.sourceAL, 1, &bufferAL); - } - - // Start the source only after filling and queueing each buffer. - ((MAL_LPALSOURCEPLAY)pDevice->pContext->openal.alSourcePlay)(pDevice->openal.sourceAL); - } else { - // Capture. - ((MAL_LPALCCAPTURESTART)pDevice->pContext->openal.alcCaptureStart)((mal_ALCdevice*)pDevice->openal.pDeviceALC); - } - - return MAL_SUCCESS; -} - -mal_result mal_device_stop__openal(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - if (pDevice->type == mal_device_type_playback) { - ((MAL_LPALCMAKECONTEXTCURRENT)pDevice->pContext->openal.alcMakeContextCurrent)((mal_ALCcontext*)pDevice->openal.pContextALC); - ((MAL_LPALSOURCESTOP)pDevice->pContext->openal.alSourceStop)(pDevice->openal.sourceAL); - } else { - ((MAL_LPALCCAPTURESTOP)pDevice->pContext->openal.alcCaptureStop)((mal_ALCdevice*)pDevice->openal.pDeviceALC); - } - - return MAL_SUCCESS; -} - -mal_result mal_device_break_main_loop__openal(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - pDevice->openal.breakFromMainLoop = MAL_TRUE; - return MAL_SUCCESS; -} - -mal_uint32 mal_device__get_available_frames__openal(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - if (pDevice->type == mal_device_type_playback) { - ((MAL_LPALCMAKECONTEXTCURRENT)pDevice->pContext->openal.alcMakeContextCurrent)((mal_ALCcontext*)pDevice->openal.pContextALC); - - mal_ALint processedBufferCount = 0; - ((MAL_LPALGETSOURCEI)pDevice->pContext->openal.alGetSourcei)(pDevice->openal.sourceAL, MAL_AL_BUFFERS_PROCESSED, &processedBufferCount); - - return processedBufferCount * pDevice->openal.subBufferSizeInFrames; - } else { - mal_ALint samplesAvailable = 0; - ((MAL_LPALCGETINTEGERV)pDevice->pContext->openal.alcGetIntegerv)((mal_ALCdevice*)pDevice->openal.pDeviceALC, MAL_ALC_CAPTURE_SAMPLES, 1, &samplesAvailable); - - return samplesAvailable / pDevice->channels; - } -} - -mal_uint32 mal_device__wait_for_frames__openal(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - while (!pDevice->openal.breakFromMainLoop) { - mal_uint32 framesAvailable = mal_device__get_available_frames__openal(pDevice); - if (framesAvailable > 0) { - return framesAvailable; - } - - mal_sleep(1); - } - - // We'll get here if the loop was terminated. When capturing we want to return whatever is available. For playback we just drop it. - if (pDevice->type == mal_device_type_playback) { - return 0; - } else { - return mal_device__get_available_frames__openal(pDevice); - } -} - -mal_result mal_device_main_loop__openal(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - pDevice->openal.breakFromMainLoop = MAL_FALSE; - while (!pDevice->openal.breakFromMainLoop) { - mal_uint32 framesAvailable = mal_device__wait_for_frames__openal(pDevice); - if (framesAvailable == 0) { - continue; - } - - // If it's a playback device, don't bother grabbing more data if the device is being stopped. - if (pDevice->openal.breakFromMainLoop && pDevice->type == mal_device_type_playback) { - return MAL_FALSE; - } - - if (pDevice->type == mal_device_type_playback) { - while (framesAvailable > 0) { - mal_uint32 framesToRead = (framesAvailable > pDevice->openal.subBufferSizeInFrames) ? pDevice->openal.subBufferSizeInFrames : framesAvailable; - - mal_ALuint bufferAL = pDevice->openal.buffersAL[pDevice->openal.iNextBuffer]; - pDevice->openal.iNextBuffer = (pDevice->openal.iNextBuffer + 1) % pDevice->periods; - - mal_device__read_frames_from_client(pDevice, framesToRead, pDevice->openal.pIntermediaryBuffer); - - ((MAL_LPALCMAKECONTEXTCURRENT)pDevice->pContext->openal.alcMakeContextCurrent)((mal_ALCcontext*)pDevice->openal.pContextALC); - ((MAL_LPALSOURCEUNQUEUEBUFFERS)pDevice->pContext->openal.alSourceUnqueueBuffers)(pDevice->openal.sourceAL, 1, &bufferAL); - ((MAL_LPALBUFFERDATA)pDevice->pContext->openal.alBufferData)(bufferAL, pDevice->openal.formatAL, pDevice->openal.pIntermediaryBuffer, pDevice->openal.subBufferSizeInFrames * pDevice->internalChannels * mal_get_bytes_per_sample(pDevice->internalFormat), pDevice->internalSampleRate); - ((MAL_LPALSOURCEQUEUEBUFFERS)pDevice->pContext->openal.alSourceQueueBuffers)(pDevice->openal.sourceAL, 1, &bufferAL); - - framesAvailable -= framesToRead; - } - - - // There's a chance the source has stopped playing due to there not being any buffer's queue. Make sure it's restarted. - mal_ALenum state; - ((MAL_LPALGETSOURCEI)pDevice->pContext->openal.alGetSourcei)(pDevice->openal.sourceAL, MAL_AL_SOURCE_STATE, &state); - - if (state != MAL_AL_PLAYING) { - ((MAL_LPALSOURCEPLAY)pDevice->pContext->openal.alSourcePlay)(pDevice->openal.sourceAL); - } - } else { - while (framesAvailable > 0) { - mal_uint32 framesToSend = (framesAvailable > pDevice->openal.subBufferSizeInFrames) ? pDevice->openal.subBufferSizeInFrames : framesAvailable; - ((MAL_LPALCCAPTURESAMPLES)pDevice->pContext->openal.alcCaptureSamples)((mal_ALCdevice*)pDevice->openal.pDeviceALC, pDevice->openal.pIntermediaryBuffer, framesToSend); - - mal_device__send_frames_to_client(pDevice, framesToSend, pDevice->openal.pIntermediaryBuffer); - framesAvailable -= framesToSend; - } - } - } - - return MAL_SUCCESS; -} - - -mal_result mal_context_uninit__openal(mal_context* pContext) -{ - mal_assert(pContext != NULL); - mal_assert(pContext->backend == mal_backend_openal); - -#ifndef MAL_NO_RUNTIME_LINKING - mal_dlclose(pContext->openal.hOpenAL); -#endif - - return MAL_SUCCESS; -} - -mal_result mal_context_init__openal(mal_context* pContext) -{ - mal_assert(pContext != NULL); - -#ifndef MAL_NO_RUNTIME_LINKING - const char* libNames[] = { -#if defined(MAL_WIN32) - "OpenAL32.dll", - "soft_oal.dll" -#endif -#if defined(MAL_UNIX) && !defined(MAL_APPLE) - "libopenal.so", - "libopenal.so.1" -#endif -#if defined(MAL_APPLE) - "OpenAL.framework/OpenAL" -#endif - }; - - for (size_t i = 0; i < mal_countof(libNames); ++i) { - pContext->openal.hOpenAL = mal_dlopen(libNames[i]); - if (pContext->openal.hOpenAL != NULL) { - break; - } - } - - if (pContext->openal.hOpenAL == NULL) { - return MAL_FAILED_TO_INIT_BACKEND; - } - - pContext->openal.alcCreateContext = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alcCreateContext"); - pContext->openal.alcMakeContextCurrent = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alcMakeContextCurrent"); - pContext->openal.alcProcessContext = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alcProcessContext"); - pContext->openal.alcSuspendContext = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alcSuspendContext"); - pContext->openal.alcDestroyContext = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alcDestroyContext"); - pContext->openal.alcGetCurrentContext = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alcGetCurrentContext"); - pContext->openal.alcGetContextsDevice = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alcGetContextsDevice"); - pContext->openal.alcOpenDevice = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alcOpenDevice"); - pContext->openal.alcCloseDevice = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alcCloseDevice"); - pContext->openal.alcGetError = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alcGetError"); - pContext->openal.alcIsExtensionPresent = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alcIsExtensionPresent"); - pContext->openal.alcGetProcAddress = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alcGetProcAddress"); - pContext->openal.alcGetEnumValue = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alcGetEnumValue"); - pContext->openal.alcGetString = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alcGetString"); - pContext->openal.alcGetIntegerv = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alcGetIntegerv"); - pContext->openal.alcCaptureOpenDevice = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alcCaptureOpenDevice"); - pContext->openal.alcCaptureCloseDevice = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alcCaptureCloseDevice"); - pContext->openal.alcCaptureStart = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alcCaptureStart"); - pContext->openal.alcCaptureStop = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alcCaptureStop"); - pContext->openal.alcCaptureSamples = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alcCaptureSamples"); - - pContext->openal.alEnable = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alEnable"); - pContext->openal.alDisable = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alDisable"); - pContext->openal.alIsEnabled = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alIsEnabled"); - pContext->openal.alGetString = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alGetString"); - pContext->openal.alGetBooleanv = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alGetBooleanv"); - pContext->openal.alGetIntegerv = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alGetIntegerv"); - pContext->openal.alGetFloatv = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alGetFloatv"); - pContext->openal.alGetDoublev = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alGetDoublev"); - pContext->openal.alGetBoolean = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alGetBoolean"); - pContext->openal.alGetInteger = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alGetInteger"); - pContext->openal.alGetFloat = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alGetFloat"); - pContext->openal.alGetDouble = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alGetDouble"); - pContext->openal.alGetError = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alGetError"); - pContext->openal.alIsExtensionPresent = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alIsExtensionPresent"); - pContext->openal.alGetProcAddress = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alGetProcAddress"); - pContext->openal.alGetEnumValue = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alGetEnumValue"); - pContext->openal.alGenSources = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alGenSources"); - pContext->openal.alDeleteSources = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alDeleteSources"); - pContext->openal.alIsSource = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alIsSource"); - pContext->openal.alSourcef = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alSourcef"); - pContext->openal.alSource3f = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alSource3f"); - pContext->openal.alSourcefv = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alSourcefv"); - pContext->openal.alSourcei = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alSourcei"); - pContext->openal.alSource3i = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alSource3i"); - pContext->openal.alSourceiv = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alSourceiv"); - pContext->openal.alGetSourcef = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alGetSourcef"); - pContext->openal.alGetSource3f = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alGetSource3f"); - pContext->openal.alGetSourcefv = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alGetSourcefv"); - pContext->openal.alGetSourcei = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alGetSourcei"); - pContext->openal.alGetSource3i = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alGetSource3i"); - pContext->openal.alGetSourceiv = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alGetSourceiv"); - pContext->openal.alSourcePlayv = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alSourcePlayv"); - pContext->openal.alSourceStopv = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alSourceStopv"); - pContext->openal.alSourceRewindv = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alSourceRewindv"); - pContext->openal.alSourcePausev = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alSourcePausev"); - pContext->openal.alSourcePlay = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alSourcePlay"); - pContext->openal.alSourceStop = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alSourceStop"); - pContext->openal.alSourceRewind = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alSourceRewind"); - pContext->openal.alSourcePause = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alSourcePause"); - pContext->openal.alSourceQueueBuffers = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alSourceQueueBuffers"); - pContext->openal.alSourceUnqueueBuffers = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alSourceUnqueueBuffers"); - pContext->openal.alGenBuffers = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alGenBuffers"); - pContext->openal.alDeleteBuffers = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alDeleteBuffers"); - pContext->openal.alIsBuffer = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alIsBuffer"); - pContext->openal.alBufferData = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alBufferData"); - pContext->openal.alBufferf = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alBufferf"); - pContext->openal.alBuffer3f = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alBuffer3f"); - pContext->openal.alBufferfv = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alBufferfv"); - pContext->openal.alBufferi = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alBufferi"); - pContext->openal.alBuffer3i = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alBuffer3i"); - pContext->openal.alBufferiv = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alBufferiv"); - pContext->openal.alGetBufferf = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alGetBufferf"); - pContext->openal.alGetBuffer3f = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alGetBuffer3f"); - pContext->openal.alGetBufferfv = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alGetBufferfv"); - pContext->openal.alGetBufferi = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alGetBufferi"); - pContext->openal.alGetBuffer3i = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alGetBuffer3i"); - pContext->openal.alGetBufferiv = (mal_proc)mal_dlsym(pContext->openal.hOpenAL, "alGetBufferiv"); -#else - pContext->openal.alcCreateContext = (mal_proc)alcCreateContext; - pContext->openal.alcMakeContextCurrent = (mal_proc)alcMakeContextCurrent; - pContext->openal.alcProcessContext = (mal_proc)alcProcessContext; - pContext->openal.alcSuspendContext = (mal_proc)alcSuspendContext; - pContext->openal.alcDestroyContext = (mal_proc)alcDestroyContext; - pContext->openal.alcGetCurrentContext = (mal_proc)alcGetCurrentContext; - pContext->openal.alcGetContextsDevice = (mal_proc)alcGetContextsDevice; - pContext->openal.alcOpenDevice = (mal_proc)alcOpenDevice; - pContext->openal.alcCloseDevice = (mal_proc)alcCloseDevice; - pContext->openal.alcGetError = (mal_proc)alcGetError; - pContext->openal.alcIsExtensionPresent = (mal_proc)alcIsExtensionPresent; - pContext->openal.alcGetProcAddress = (mal_proc)alcGetProcAddress; - pContext->openal.alcGetEnumValue = (mal_proc)alcGetEnumValue; - pContext->openal.alcGetString = (mal_proc)alcGetString; - pContext->openal.alcGetIntegerv = (mal_proc)alcGetIntegerv; - pContext->openal.alcCaptureOpenDevice = (mal_proc)alcCaptureOpenDevice; - pContext->openal.alcCaptureCloseDevice = (mal_proc)alcCaptureCloseDevice; - pContext->openal.alcCaptureStart = (mal_proc)alcCaptureStart; - pContext->openal.alcCaptureStop = (mal_proc)alcCaptureStop; - pContext->openal.alcCaptureSamples = (mal_proc)alcCaptureSamples; - - pContext->openal.alEnable = (mal_proc)alEnable; - pContext->openal.alDisable = (mal_proc)alDisable; - pContext->openal.alIsEnabled = (mal_proc)alIsEnabled; - pContext->openal.alGetString = (mal_proc)alGetString; - pContext->openal.alGetBooleanv = (mal_proc)alGetBooleanv; - pContext->openal.alGetIntegerv = (mal_proc)alGetIntegerv; - pContext->openal.alGetFloatv = (mal_proc)alGetFloatv; - pContext->openal.alGetDoublev = (mal_proc)alGetDoublev; - pContext->openal.alGetBoolean = (mal_proc)alGetBoolean; - pContext->openal.alGetInteger = (mal_proc)alGetInteger; - pContext->openal.alGetFloat = (mal_proc)alGetFloat; - pContext->openal.alGetDouble = (mal_proc)alGetDouble; - pContext->openal.alGetError = (mal_proc)alGetError; - pContext->openal.alIsExtensionPresent = (mal_proc)alIsExtensionPresent; - pContext->openal.alGetProcAddress = (mal_proc)alGetProcAddress; - pContext->openal.alGetEnumValue = (mal_proc)alGetEnumValue; - pContext->openal.alGenSources = (mal_proc)alGenSources; - pContext->openal.alDeleteSources = (mal_proc)alDeleteSources; - pContext->openal.alIsSource = (mal_proc)alIsSource; - pContext->openal.alSourcef = (mal_proc)alSourcef; - pContext->openal.alSource3f = (mal_proc)alSource3f; - pContext->openal.alSourcefv = (mal_proc)alSourcefv; - pContext->openal.alSourcei = (mal_proc)alSourcei; - pContext->openal.alSource3i = (mal_proc)alSource3i; - pContext->openal.alSourceiv = (mal_proc)alSourceiv; - pContext->openal.alGetSourcef = (mal_proc)alGetSourcef; - pContext->openal.alGetSource3f = (mal_proc)alGetSource3f; - pContext->openal.alGetSourcefv = (mal_proc)alGetSourcefv; - pContext->openal.alGetSourcei = (mal_proc)alGetSourcei; - pContext->openal.alGetSource3i = (mal_proc)alGetSource3i; - pContext->openal.alGetSourceiv = (mal_proc)alGetSourceiv; - pContext->openal.alSourcePlayv = (mal_proc)alSourcePlayv; - pContext->openal.alSourceStopv = (mal_proc)alSourceStopv; - pContext->openal.alSourceRewindv = (mal_proc)alSourceRewindv; - pContext->openal.alSourcePausev = (mal_proc)alSourcePausev; - pContext->openal.alSourcePlay = (mal_proc)alSourcePlay; - pContext->openal.alSourceStop = (mal_proc)alSourceStop; - pContext->openal.alSourceRewind = (mal_proc)alSourceRewind; - pContext->openal.alSourcePause = (mal_proc)alSourcePause; - pContext->openal.alSourceQueueBuffers = (mal_proc)alSourceQueueBuffers; - pContext->openal.alSourceUnqueueBuffers = (mal_proc)alSourceUnqueueBuffers; - pContext->openal.alGenBuffers = (mal_proc)alGenBuffers; - pContext->openal.alDeleteBuffers = (mal_proc)alDeleteBuffers; - pContext->openal.alIsBuffer = (mal_proc)alIsBuffer; - pContext->openal.alBufferData = (mal_proc)alBufferData; - pContext->openal.alBufferf = (mal_proc)alBufferf; - pContext->openal.alBuffer3f = (mal_proc)alBuffer3f; - pContext->openal.alBufferfv = (mal_proc)alBufferfv; - pContext->openal.alBufferi = (mal_proc)alBufferi; - pContext->openal.alBuffer3i = (mal_proc)alBuffer3i; - pContext->openal.alBufferiv = (mal_proc)alBufferiv; - pContext->openal.alGetBufferf = (mal_proc)alGetBufferf; - pContext->openal.alGetBuffer3f = (mal_proc)alGetBuffer3f; - pContext->openal.alGetBufferfv = (mal_proc)alGetBufferfv; - pContext->openal.alGetBufferi = (mal_proc)alGetBufferi; - pContext->openal.alGetBuffer3i = (mal_proc)alGetBuffer3i; - pContext->openal.alGetBufferiv = (mal_proc)alGetBufferiv; -#endif - - // We depend on the ALC_ENUMERATION_EXT extension for enumeration. If this is not supported we fall back to default devices. - pContext->openal.isEnumerationSupported = ((MAL_LPALCISEXTENSIONPRESENT)pContext->openal.alcIsExtensionPresent)(NULL, "ALC_ENUMERATION_EXT"); - pContext->openal.isFloat32Supported = ((MAL_LPALISEXTENSIONPRESENT)pContext->openal.alIsExtensionPresent)("AL_EXT_float32"); - pContext->openal.isMCFormatsSupported = ((MAL_LPALISEXTENSIONPRESENT)pContext->openal.alIsExtensionPresent)("AL_EXT_MCFORMATS"); - - pContext->onUninit = mal_context_uninit__openal; - pContext->onDeviceIDEqual = mal_context_is_device_id_equal__openal; - pContext->onEnumDevices = mal_context_enumerate_devices__openal; - pContext->onGetDeviceInfo = mal_context_get_device_info__openal; - pContext->onDeviceInit = mal_device_init__openal; - pContext->onDeviceUninit = mal_device_uninit__openal; - pContext->onDeviceStart = mal_device_start__openal; - pContext->onDeviceStop = mal_device_stop__openal; - pContext->onDeviceBreakMainLoop = mal_device_break_main_loop__openal; - pContext->onDeviceMainLoop = mal_device_main_loop__openal; - - return MAL_SUCCESS; -} -#endif // OpenAL - - - -/////////////////////////////////////////////////////////////////////////////// -// -// SDL Backend -// -/////////////////////////////////////////////////////////////////////////////// -#ifdef MAL_HAS_SDL - -#define MAL_SDL_INIT_AUDIO 0x00000010 -#define MAL_AUDIO_U8 0x0008 -#define MAL_AUDIO_S16 0x8010 -#define MAL_AUDIO_S32 0x8020 -#define MAL_AUDIO_F32 0x8120 -#define MAL_SDL_AUDIO_ALLOW_FREQUENCY_CHANGE 0x00000001 -#define MAL_SDL_AUDIO_ALLOW_FORMAT_CHANGE 0x00000002 -#define MAL_SDL_AUDIO_ALLOW_CHANNELS_CHANGE 0x00000004 -#define MAL_SDL_AUDIO_ALLOW_ANY_CHANGE (MAL_SDL_AUDIO_ALLOW_FREQUENCY_CHANGE | MAL_SDL_AUDIO_ALLOW_FORMAT_CHANGE | MAL_SDL_AUDIO_ALLOW_CHANNELS_CHANGE) - -// If we are linking at compile time we'll just #include SDL.h. Otherwise we can just redeclare some stuff to avoid the -// need for development packages to be installed. -#ifdef MAL_NO_RUNTIME_LINKING - #define SDL_MAIN_HANDLED - #ifdef MAL_EMSCRIPTEN - #include - #else - #include - #endif - - typedef SDL_AudioCallback MAL_SDL_AudioCallback; - typedef SDL_AudioSpec MAL_SDL_AudioSpec; - typedef SDL_AudioFormat MAL_SDL_AudioFormat; - typedef SDL_AudioDeviceID MAL_SDL_AudioDeviceID; -#else - typedef void (* MAL_SDL_AudioCallback)(void* userdata, mal_uint8* stream, int len); - typedef mal_uint16 MAL_SDL_AudioFormat; - typedef mal_uint32 MAL_SDL_AudioDeviceID; - - typedef struct MAL_SDL_AudioSpec - { - int freq; - MAL_SDL_AudioFormat format; - mal_uint8 channels; - mal_uint8 silence; - mal_uint16 samples; - mal_uint16 padding; - mal_uint32 size; - MAL_SDL_AudioCallback callback; - void* userdata; - } MAL_SDL_AudioSpec; -#endif - -typedef int (* MAL_PFN_SDL_InitSubSystem)(mal_uint32 flags); -typedef void (* MAL_PFN_SDL_QuitSubSystem)(mal_uint32 flags); -typedef int (* MAL_PFN_SDL_GetNumAudioDevices)(int iscapture); -typedef const char* (* MAL_PFN_SDL_GetAudioDeviceName)(int index, int iscapture); -typedef void (* MAL_PFN_SDL_CloseAudioDevice)(MAL_SDL_AudioDeviceID dev); -typedef MAL_SDL_AudioDeviceID (* MAL_PFN_SDL_OpenAudioDevice)(const char* device, int iscapture, const MAL_SDL_AudioSpec* desired, MAL_SDL_AudioSpec* obtained, int allowed_changes); -typedef void (* MAL_PFN_SDL_PauseAudioDevice)(MAL_SDL_AudioDeviceID dev, int pause_on); - -MAL_SDL_AudioFormat mal_format_to_sdl(mal_format format) -{ - switch (format) - { - case mal_format_unknown: return 0; - case mal_format_u8: return MAL_AUDIO_U8; - case mal_format_s16: return MAL_AUDIO_S16; - case mal_format_s24: return MAL_AUDIO_S32; // Closest match. - case mal_format_s32: return MAL_AUDIO_S32; - default: return 0; - } -} - -mal_format mal_format_from_sdl(MAL_SDL_AudioFormat format) -{ - switch (format) - { - case MAL_AUDIO_U8: return mal_format_u8; - case MAL_AUDIO_S16: return mal_format_s16; - case MAL_AUDIO_S32: return mal_format_s32; - case MAL_AUDIO_F32: return mal_format_f32; - default: return mal_format_unknown; - } -} - -mal_bool32 mal_context_is_device_id_equal__sdl(mal_context* pContext, const mal_device_id* pID0, const mal_device_id* pID1) -{ - mal_assert(pContext != NULL); - mal_assert(pID0 != NULL); - mal_assert(pID1 != NULL); - (void)pContext; - - return pID0->sdl == pID1->sdl; -} - -mal_result mal_context_enumerate_devices__sdl(mal_context* pContext, mal_enum_devices_callback_proc callback, void* pUserData) -{ - mal_assert(pContext != NULL); - mal_assert(callback != NULL); - - mal_bool32 isTerminated = MAL_FALSE; - - // Playback - if (!isTerminated) { - int deviceCount = ((MAL_PFN_SDL_GetNumAudioDevices)pContext->sdl.SDL_GetNumAudioDevices)(0); - for (int i = 0; i < deviceCount; ++i) { - mal_device_info deviceInfo; - mal_zero_object(&deviceInfo); - - deviceInfo.id.sdl = i; - mal_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), ((MAL_PFN_SDL_GetAudioDeviceName)pContext->sdl.SDL_GetAudioDeviceName)(i, 0), (size_t)-1); - - mal_bool32 cbResult = callback(pContext, mal_device_type_playback, &deviceInfo, pUserData); - if (cbResult == MAL_FALSE) { - isTerminated = MAL_TRUE; - break; - } - } - } - - // Capture - if (!isTerminated) { - int deviceCount = ((MAL_PFN_SDL_GetNumAudioDevices)pContext->sdl.SDL_GetNumAudioDevices)(1); - for (int i = 0; i < deviceCount; ++i) { - mal_device_info deviceInfo; - mal_zero_object(&deviceInfo); - - deviceInfo.id.sdl = i; - mal_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), ((MAL_PFN_SDL_GetAudioDeviceName)pContext->sdl.SDL_GetAudioDeviceName)(i, 1), (size_t)-1); - - mal_bool32 cbResult = callback(pContext, mal_device_type_capture, &deviceInfo, pUserData); - if (cbResult == MAL_FALSE) { - isTerminated = MAL_TRUE; - break; - } - } - } - - return MAL_SUCCESS; -} - -mal_result mal_context_get_device_info__sdl(mal_context* pContext, mal_device_type deviceType, const mal_device_id* pDeviceID, mal_share_mode shareMode, mal_device_info* pDeviceInfo) -{ - mal_assert(pContext != NULL); - (void)shareMode; - - if (pDeviceID == NULL) { - if (deviceType == mal_device_type_playback) { - pDeviceInfo->id.sdl = 0; - mal_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MAL_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); - } else { - pDeviceInfo->id.sdl = 0; - mal_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MAL_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); - } - } else { - pDeviceInfo->id.sdl = pDeviceID->sdl; - mal_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), ((MAL_PFN_SDL_GetAudioDeviceName)pContext->sdl.SDL_GetAudioDeviceName)(pDeviceID->sdl, (deviceType == mal_device_type_playback) ? 0 : 1), (size_t)-1); - } - - // To get an accurate idea on the backend's native format we need to open the device. Not ideal, but it's the only way. An - // alternative to this is to report all channel counts, sample rates and formats, but that doesn't offer a good representation - // of the device's _actual_ ideal format. - // - // Note: With Emscripten, it looks like non-zero values need to be specified for desiredSpec. Whatever is specified in - // desiredSpec will be used by SDL since it uses it just does it's own format conversion internally. Therefore, from what - // I can tell, there's no real way to know the device's actual format which means I'm just going to fall back to the full - // range of channels and sample rates on Emscripten builds. -#if defined(__EMSCRIPTEN__) - pDeviceInfo->minChannels = MAL_MIN_CHANNELS; - pDeviceInfo->maxChannels = MAL_MAX_CHANNELS; - pDeviceInfo->minSampleRate = MAL_MIN_SAMPLE_RATE; - pDeviceInfo->maxSampleRate = MAL_MAX_SAMPLE_RATE; - pDeviceInfo->formatCount = 3; - pDeviceInfo->formats[0] = mal_format_u8; - pDeviceInfo->formats[1] = mal_format_s16; - pDeviceInfo->formats[2] = mal_format_s32; -#else - MAL_SDL_AudioSpec desiredSpec, obtainedSpec; - mal_zero_memory(&desiredSpec, sizeof(desiredSpec)); - - int isCapture = (deviceType == mal_device_type_playback) ? 0 : 1; - - const char* pDeviceName = NULL; - if (pDeviceID != NULL) { - pDeviceName = ((MAL_PFN_SDL_GetAudioDeviceName)pContext->sdl.SDL_GetAudioDeviceName)(pDeviceID->sdl, isCapture); - } - - MAL_SDL_AudioDeviceID tempDeviceID = ((MAL_PFN_SDL_OpenAudioDevice)pContext->sdl.SDL_OpenAudioDevice)(pDeviceName, isCapture, &desiredSpec, &obtainedSpec, MAL_SDL_AUDIO_ALLOW_ANY_CHANGE); - if (tempDeviceID == 0) { - return mal_context_post_error(pContext, NULL, MAL_LOG_LEVEL_ERROR, "Failed to open SDL device.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - - ((MAL_PFN_SDL_CloseAudioDevice)pContext->sdl.SDL_CloseAudioDevice)(tempDeviceID); - - pDeviceInfo->minChannels = obtainedSpec.channels; - pDeviceInfo->maxChannels = obtainedSpec.channels; - pDeviceInfo->minSampleRate = obtainedSpec.freq; - pDeviceInfo->maxSampleRate = obtainedSpec.freq; - pDeviceInfo->formatCount = 1; - if (obtainedSpec.format == MAL_AUDIO_U8) { - pDeviceInfo->formats[0] = mal_format_u8; - } else if (obtainedSpec.format == MAL_AUDIO_S16) { - pDeviceInfo->formats[0] = mal_format_s16; - } else if (obtainedSpec.format == MAL_AUDIO_S32) { - pDeviceInfo->formats[0] = mal_format_s32; - } else if (obtainedSpec.format == MAL_AUDIO_F32) { - pDeviceInfo->formats[0] = mal_format_f32; - } else { - return MAL_FORMAT_NOT_SUPPORTED; - } -#endif - - return MAL_SUCCESS; -} - - -void mal_device_uninit__sdl(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - ((MAL_PFN_SDL_CloseAudioDevice)pDevice->pContext->sdl.SDL_CloseAudioDevice)(pDevice->sdl.deviceID); -} - - -void mal_audio_callback__sdl(void* pUserData, mal_uint8* pBuffer, int bufferSizeInBytes) -{ - mal_device* pDevice = (mal_device*)pUserData; - mal_assert(pDevice != NULL); - - mal_uint32 bufferSizeInFrames = (mal_uint32)bufferSizeInBytes / mal_get_bytes_per_frame(pDevice->internalFormat, pDevice->internalChannels); - -#ifdef MAL_DEBUG_OUTPUT - printf("[SDL] Callback: bufferSizeInBytes=%d, bufferSizeInFrames=%d\n", bufferSizeInBytes, bufferSizeInFrames); -#endif - - if (pDevice->type == mal_device_type_playback) { - mal_device__read_frames_from_client(pDevice, bufferSizeInFrames, pBuffer); - } else { - mal_device__send_frames_to_client(pDevice, bufferSizeInFrames, pBuffer); - } -} - -mal_result mal_device_init__sdl(mal_context* pContext, mal_device_type type, const mal_device_id* pDeviceID, const mal_device_config* pConfig, mal_device* pDevice) -{ - mal_assert(pContext != NULL); - mal_assert(pConfig != NULL); - mal_assert(pDevice != NULL); - - (void)pContext; - - if (pDevice->bufferSizeInFrames == 0) { - pDevice->bufferSizeInFrames = mal_calculate_buffer_size_in_frames_from_milliseconds(pDevice->bufferSizeInMilliseconds, pDevice->sampleRate); - } - - // SDL wants the buffer size to be a power of 2. The SDL_AudioSpec property for this is only a Uint16, so we need - // to explicitly clamp this because it will be easy to overflow. - mal_uint32 bufferSize = pDevice->bufferSizeInFrames; - if (bufferSize > 32768) { - bufferSize = 32768; - } else { - bufferSize = mal_next_power_of_2(bufferSize); - } - - mal_assert(bufferSize <= 32768); - - - MAL_SDL_AudioSpec desiredSpec, obtainedSpec; - mal_zero_memory(&desiredSpec, sizeof(desiredSpec)); - desiredSpec.freq = (int)pConfig->sampleRate; - desiredSpec.format = mal_format_to_sdl(pConfig->format); - desiredSpec.channels = (mal_uint8)pConfig->channels; - desiredSpec.samples = (mal_uint16)bufferSize; - desiredSpec.callback = mal_audio_callback__sdl; - desiredSpec.userdata = pDevice; - - // Fall back to f32 if we don't have an appropriate mapping between mini_al and SDL. - if (desiredSpec.format == 0) { - desiredSpec.format = MAL_AUDIO_F32; - } - - int isCapture = (type == mal_device_type_playback) ? 0 : 1; - - const char* pDeviceName = NULL; - if (pDeviceID != NULL) { - pDeviceName = ((MAL_PFN_SDL_GetAudioDeviceName)pDevice->pContext->sdl.SDL_GetAudioDeviceName)(pDeviceID->sdl, isCapture); - } - - pDevice->sdl.deviceID = ((MAL_PFN_SDL_OpenAudioDevice)pDevice->pContext->sdl.SDL_OpenAudioDevice)(pDeviceName, isCapture, &desiredSpec, &obtainedSpec, MAL_SDL_AUDIO_ALLOW_ANY_CHANGE); - if (pDevice->sdl.deviceID == 0) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "Failed to open SDL2 device.", MAL_FAILED_TO_OPEN_BACKEND_DEVICE); - } - - pDevice->internalFormat = mal_format_from_sdl(obtainedSpec.format); - pDevice->internalChannels = obtainedSpec.channels; - pDevice->internalSampleRate = (mal_uint32)obtainedSpec.freq; - mal_get_standard_channel_map(mal_standard_channel_map_default, pDevice->internalChannels, pDevice->internalChannelMap); - pDevice->bufferSizeInFrames = obtainedSpec.samples; - pDevice->periods = 1; // SDL doesn't seem to tell us what the period count is. Just set this 1. - -#ifdef MAL_DEBUG_OUTPUT - printf("=== SDL CONFIG ===\n"); - printf(" FORMAT: %s -> %s\n", mal_get_format_name(pConfig->format), mal_get_format_name(pDevice->internalFormat)); - printf(" CHANNELS: %d -> %d\n", desiredSpec.channels, obtainedSpec.channels); - printf(" SAMPLE RATE: %d -> %d\n", desiredSpec.freq, obtainedSpec.freq); - printf(" BUFFER SIZE IN SAMPLES: %d -> %d\n", desiredSpec.samples, obtainedSpec.samples); -#endif - - return MAL_SUCCESS; -} - -mal_result mal_device_start__sdl(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - ((MAL_PFN_SDL_PauseAudioDevice)pDevice->pContext->sdl.SDL_PauseAudioDevice)(pDevice->sdl.deviceID, 0); - return MAL_SUCCESS; -} - -mal_result mal_device_stop__sdl(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - ((MAL_PFN_SDL_PauseAudioDevice)pDevice->pContext->sdl.SDL_PauseAudioDevice)(pDevice->sdl.deviceID, 1); - - mal_device__set_state(pDevice, MAL_STATE_STOPPED); - mal_stop_proc onStop = pDevice->onStop; - if (onStop) { - onStop(pDevice); - } - - return MAL_SUCCESS; -} - - -mal_result mal_context_uninit__sdl(mal_context* pContext) -{ - mal_assert(pContext != NULL); - mal_assert(pContext->backend == mal_backend_sdl); - - ((MAL_PFN_SDL_QuitSubSystem)pContext->sdl.SDL_QuitSubSystem)(MAL_SDL_INIT_AUDIO); - return MAL_SUCCESS; -} - -mal_result mal_context_init__sdl(mal_context* pContext) -{ - mal_assert(pContext != NULL); - -#ifndef MAL_NO_RUNTIME_LINKING - // Run-time linking. - const char* libNames[] = { -#if defined(MAL_WIN32) - "SDL2.dll" -#elif defined(MAL_APPLE) - "SDL2.framework/SDL2" -#else - "libSDL2-2.0.so.0" -#endif - }; - - for (size_t i = 0; i < mal_countof(libNames); ++i) { - pContext->sdl.hSDL = mal_dlopen(libNames[i]); - if (pContext->sdl.hSDL != NULL) { - break; - } - } - - if (pContext->sdl.hSDL == NULL) { - return MAL_NO_BACKEND; // Couldn't find SDL2.dll, etc. Most likely it's not installed. - } - - pContext->sdl.SDL_InitSubSystem = mal_dlsym(pContext->sdl.hSDL, "SDL_InitSubSystem"); - pContext->sdl.SDL_QuitSubSystem = mal_dlsym(pContext->sdl.hSDL, "SDL_QuitSubSystem"); - pContext->sdl.SDL_GetNumAudioDevices = mal_dlsym(pContext->sdl.hSDL, "SDL_GetNumAudioDevices"); - pContext->sdl.SDL_GetAudioDeviceName = mal_dlsym(pContext->sdl.hSDL, "SDL_GetAudioDeviceName"); - pContext->sdl.SDL_CloseAudioDevice = mal_dlsym(pContext->sdl.hSDL, "SDL_CloseAudioDevice"); - pContext->sdl.SDL_OpenAudioDevice = mal_dlsym(pContext->sdl.hSDL, "SDL_OpenAudioDevice"); - pContext->sdl.SDL_PauseAudioDevice = mal_dlsym(pContext->sdl.hSDL, "SDL_PauseAudioDevice"); -#else - // Compile-time linking. - pContext->sdl.SDL_InitSubSystem = (mal_proc)SDL_InitSubSystem; - pContext->sdl.SDL_QuitSubSystem = (mal_proc)SDL_QuitSubSystem; - pContext->sdl.SDL_GetNumAudioDevices = (mal_proc)SDL_GetNumAudioDevices; - pContext->sdl.SDL_GetAudioDeviceName = (mal_proc)SDL_GetAudioDeviceName; - pContext->sdl.SDL_CloseAudioDevice = (mal_proc)SDL_CloseAudioDevice; - pContext->sdl.SDL_OpenAudioDevice = (mal_proc)SDL_OpenAudioDevice; - pContext->sdl.SDL_PauseAudioDevice = (mal_proc)SDL_PauseAudioDevice; -#endif - - int resultSDL = ((MAL_PFN_SDL_InitSubSystem)pContext->sdl.SDL_InitSubSystem)(MAL_SDL_INIT_AUDIO); - if (resultSDL != 0) { - return MAL_ERROR; - } - - pContext->isBackendAsynchronous = MAL_TRUE; - - pContext->onUninit = mal_context_uninit__sdl; - pContext->onDeviceIDEqual = mal_context_is_device_id_equal__sdl; - pContext->onEnumDevices = mal_context_enumerate_devices__sdl; - pContext->onGetDeviceInfo = mal_context_get_device_info__sdl; - pContext->onDeviceInit = mal_device_init__sdl; - pContext->onDeviceUninit = mal_device_uninit__sdl; - pContext->onDeviceStart = mal_device_start__sdl; - pContext->onDeviceStop = mal_device_stop__sdl; - - return MAL_SUCCESS; -} -#endif // SDL - - - -mal_bool32 mal__is_channel_map_valid(const mal_channel* channelMap, mal_uint32 channels) -{ - // A blank channel map should be allowed, in which case it should use an appropriate default which will depend on context. - if (channelMap[0] != MAL_CHANNEL_NONE) { - if (channels == 0) { - return MAL_FALSE; // No channels. - } - - // A channel cannot be present in the channel map more than once. - for (mal_uint32 iChannel = 0; iChannel < channels; ++iChannel) { - for (mal_uint32 jChannel = iChannel + 1; jChannel < channels; ++jChannel) { - if (channelMap[iChannel] == channelMap[jChannel]) { - return MAL_FALSE; - } - } - } - } - - return MAL_TRUE; -} - - -void mal_device__post_init_setup(mal_device* pDevice) -{ - mal_assert(pDevice != NULL); - - // Make sure the internal channel map was set correctly by the backend. If it's not valid, just fall back to defaults. - if (!mal_channel_map_valid(pDevice->internalChannels, pDevice->internalChannelMap)) { - mal_get_standard_channel_map(mal_standard_channel_map_default, pDevice->internalChannels, pDevice->internalChannelMap); - } - - - // If the format/channels/rate is using defaults we need to set these to be the same as the internal config. - if (pDevice->usingDefaultFormat) { - pDevice->format = pDevice->internalFormat; - } - if (pDevice->usingDefaultChannels) { - pDevice->channels = pDevice->internalChannels; - } - if (pDevice->usingDefaultSampleRate) { - pDevice->sampleRate = pDevice->internalSampleRate; - } - if (pDevice->usingDefaultChannelMap) { - mal_copy_memory(pDevice->channelMap, pDevice->internalChannelMap, sizeof(pDevice->channelMap)); - } - - // Buffer size. The backend will have set bufferSizeInFrames. We need to calculate bufferSizeInMilliseconds here. - pDevice->bufferSizeInMilliseconds = pDevice->bufferSizeInFrames / (pDevice->internalSampleRate/1000); - - - // We need a DSP object which is where samples are moved through in order to convert them to the - // format required by the backend. - mal_dsp_config dspConfig = mal_dsp_config_init_new(); - dspConfig.neverConsumeEndOfInput = MAL_TRUE; - dspConfig.pUserData = pDevice; - if (pDevice->type == mal_device_type_playback) { - dspConfig.formatIn = pDevice->format; - dspConfig.channelsIn = pDevice->channels; - dspConfig.sampleRateIn = pDevice->sampleRate; - mal_copy_memory(dspConfig.channelMapIn, pDevice->channelMap, sizeof(dspConfig.channelMapIn)); - dspConfig.formatOut = pDevice->internalFormat; - dspConfig.channelsOut = pDevice->internalChannels; - dspConfig.sampleRateOut = pDevice->internalSampleRate; - mal_copy_memory(dspConfig.channelMapOut, pDevice->internalChannelMap, sizeof(dspConfig.channelMapOut)); - dspConfig.onRead = mal_device__on_read_from_client; - mal_dsp_init(&dspConfig, &pDevice->dsp); - } else { - dspConfig.formatIn = pDevice->internalFormat; - dspConfig.channelsIn = pDevice->internalChannels; - dspConfig.sampleRateIn = pDevice->internalSampleRate; - mal_copy_memory(dspConfig.channelMapIn, pDevice->internalChannelMap, sizeof(dspConfig.channelMapIn)); - dspConfig.formatOut = pDevice->format; - dspConfig.channelsOut = pDevice->channels; - dspConfig.sampleRateOut = pDevice->sampleRate; - mal_copy_memory(dspConfig.channelMapOut, pDevice->channelMap, sizeof(dspConfig.channelMapOut)); - dspConfig.onRead = mal_device__on_read_from_device; - mal_dsp_init(&dspConfig, &pDevice->dsp); - } -} - - -mal_thread_result MAL_THREADCALL mal_worker_thread(void* pData) -{ - mal_device* pDevice = (mal_device*)pData; - mal_assert(pDevice != NULL); - -#ifdef MAL_WIN32 - mal_CoInitializeEx(pDevice->pContext, NULL, MAL_COINIT_VALUE); -#endif - - // When the device is being initialized it's initial state is set to MAL_STATE_UNINITIALIZED. Before returning from - // mal_device_init(), the state needs to be set to something valid. In mini_al the device's default state immediately - // after initialization is stopped, so therefore we need to mark the device as such. mini_al will wait on the worker - // thread to signal an event to know when the worker thread is ready for action. - mal_device__set_state(pDevice, MAL_STATE_STOPPED); - mal_event_signal(&pDevice->stopEvent); - - for (;;) { - // We wait on an event to know when something has requested that the device be started and the main loop entered. - mal_event_wait(&pDevice->wakeupEvent); - - // Default result code. - pDevice->workResult = MAL_SUCCESS; - - // If the reason for the wake up is that we are terminating, just break from the loop. - if (mal_device__get_state(pDevice) == MAL_STATE_UNINITIALIZED) { - break; - } - - // Getting to this point means the device is wanting to get started. The function that has requested that the device - // be started will be waiting on an event (pDevice->startEvent) which means we need to make sure we signal the event - // in both the success and error case. It's important that the state of the device is set _before_ signaling the event. - mal_assert(mal_device__get_state(pDevice) == MAL_STATE_STARTING); - - pDevice->workResult = pDevice->pContext->onDeviceStart(pDevice); - if (pDevice->workResult != MAL_SUCCESS) { - mal_device__set_state(pDevice, MAL_STATE_STOPPED); - mal_event_signal(&pDevice->startEvent); - continue; - } - - // At this point the device should be started. - mal_device__set_state(pDevice, MAL_STATE_STARTED); - mal_event_signal(&pDevice->startEvent); - - - // Now we just enter the main loop. When the main loop is terminated the device needs to be marked as stopped. This can - // be broken with mal_device__break_main_loop(). - mal_result mainLoopResult = pDevice->pContext->onDeviceMainLoop(pDevice); - if (mainLoopResult != MAL_SUCCESS && pDevice->isDefaultDevice && mal_device__get_state(pDevice) == MAL_STATE_STARTED && !pDevice->exclusiveMode) { - // Something has failed during the main loop. It could be that the device has been lost. If it's the default device, - // we can try switching over to the new default device by uninitializing and reinitializing. - mal_result reinitResult = MAL_ERROR; - if (pDevice->pContext->onDeviceReinit) { - reinitResult = pDevice->pContext->onDeviceReinit(pDevice); - } else { - pDevice->pContext->onDeviceStop(pDevice); - mal_device__set_state(pDevice, MAL_STATE_STOPPED); - - pDevice->pContext->onDeviceUninit(pDevice); - mal_device__set_state(pDevice, MAL_STATE_UNINITIALIZED); - - reinitResult = pDevice->pContext->onDeviceInit(pDevice->pContext, pDevice->type, NULL, &pDevice->initConfig, pDevice); - } - - // Perform the post initialization setup just in case the data conversion pipeline needs to be reinitialized. - if (reinitResult == MAL_SUCCESS) { - mal_device__post_init_setup(pDevice); - } - - // If reinitialization was successful, loop back to the start. - if (reinitResult == MAL_SUCCESS) { - mal_device__set_state(pDevice, MAL_STATE_STARTING); // <-- The device is restarting. - mal_event_signal(&pDevice->wakeupEvent); - continue; - } - } - - - // Getting here means we have broken from the main loop which happens the application has requested that device be stopped. Note that this - // may have actually already happened above if the device was lost and mini_al has attempted to re-initialize the device. In this case we - // don't want to be doing this a second time. - if (mal_device__get_state(pDevice) != MAL_STATE_UNINITIALIZED) { - pDevice->pContext->onDeviceStop(pDevice); - } - - // After the device has stopped, make sure an event is posted. - mal_stop_proc onStop = pDevice->onStop; - if (onStop) { - onStop(pDevice); - } - - // A function somewhere is waiting for the device to have stopped for real so we need to signal an event to allow it to continue. Note that - // it's possible that the device has been uninitialized which means we need to _not_ change the status to stopped. We cannot go from an - // uninitialized state to stopped state. - if (mal_device__get_state(pDevice) != MAL_STATE_UNINITIALIZED) { - mal_device__set_state(pDevice, MAL_STATE_STOPPED); - mal_event_signal(&pDevice->stopEvent); - } - } - - // Make sure we aren't continuously waiting on a stop event. - mal_event_signal(&pDevice->stopEvent); // <-- Is this still needed? - -#ifdef MAL_WIN32 - mal_CoUninitialize(pDevice->pContext); -#endif - - return (mal_thread_result)0; -} - - -// Helper for determining whether or not the given device is initialized. -mal_bool32 mal_device__is_initialized(mal_device* pDevice) -{ - if (pDevice == NULL) return MAL_FALSE; - return mal_device__get_state(pDevice) != MAL_STATE_UNINITIALIZED; -} - - -#ifdef MAL_WIN32 -mal_result mal_context_uninit_backend_apis__win32(mal_context* pContext) -{ - mal_CoUninitialize(pContext); - mal_dlclose(pContext->win32.hUser32DLL); - mal_dlclose(pContext->win32.hOle32DLL); - mal_dlclose(pContext->win32.hAdvapi32DLL); - - return MAL_SUCCESS; -} - -mal_result mal_context_init_backend_apis__win32(mal_context* pContext) -{ -#ifdef MAL_WIN32_DESKTOP - // Ole32.dll - pContext->win32.hOle32DLL = mal_dlopen("ole32.dll"); - if (pContext->win32.hOle32DLL == NULL) { - return MAL_FAILED_TO_INIT_BACKEND; - } - - pContext->win32.CoInitializeEx = (mal_proc)mal_dlsym(pContext->win32.hOle32DLL, "CoInitializeEx"); - pContext->win32.CoUninitialize = (mal_proc)mal_dlsym(pContext->win32.hOle32DLL, "CoUninitialize"); - pContext->win32.CoCreateInstance = (mal_proc)mal_dlsym(pContext->win32.hOle32DLL, "CoCreateInstance"); - pContext->win32.CoTaskMemFree = (mal_proc)mal_dlsym(pContext->win32.hOle32DLL, "CoTaskMemFree"); - pContext->win32.PropVariantClear = (mal_proc)mal_dlsym(pContext->win32.hOle32DLL, "PropVariantClear"); - pContext->win32.StringFromGUID2 = (mal_proc)mal_dlsym(pContext->win32.hOle32DLL, "StringFromGUID2"); - - - // User32.dll - pContext->win32.hUser32DLL = mal_dlopen("user32.dll"); - if (pContext->win32.hUser32DLL == NULL) { - return MAL_FAILED_TO_INIT_BACKEND; - } - - pContext->win32.GetForegroundWindow = (mal_proc)mal_dlsym(pContext->win32.hUser32DLL, "GetForegroundWindow"); - pContext->win32.GetDesktopWindow = (mal_proc)mal_dlsym(pContext->win32.hUser32DLL, "GetDesktopWindow"); - - - // Advapi32.dll - pContext->win32.hAdvapi32DLL = mal_dlopen("advapi32.dll"); - if (pContext->win32.hAdvapi32DLL == NULL) { - return MAL_FAILED_TO_INIT_BACKEND; - } - - pContext->win32.RegOpenKeyExA = (mal_proc)mal_dlsym(pContext->win32.hAdvapi32DLL, "RegOpenKeyExA"); - pContext->win32.RegCloseKey = (mal_proc)mal_dlsym(pContext->win32.hAdvapi32DLL, "RegCloseKey"); - pContext->win32.RegQueryValueExA = (mal_proc)mal_dlsym(pContext->win32.hAdvapi32DLL, "RegQueryValueExA"); -#endif - - mal_CoInitializeEx(pContext, NULL, MAL_COINIT_VALUE); - return MAL_SUCCESS; -} -#else -mal_result mal_context_uninit_backend_apis__nix(mal_context* pContext) -{ -#if defined(MAL_USE_RUNTIME_LINKING_FOR_PTHREAD) && !defined(MAL_NO_RUNTIME_LINKING) - mal_dlclose(pContext->posix.pthreadSO); -#else - (void)pContext; -#endif - - return MAL_SUCCESS; -} - -mal_result mal_context_init_backend_apis__nix(mal_context* pContext) -{ - // pthread -#if defined(MAL_USE_RUNTIME_LINKING_FOR_PTHREAD) && !defined(MAL_NO_RUNTIME_LINKING) - const char* libpthreadFileNames[] = { - "libpthread.so", - "libpthread.so.0", - "libpthread.dylib" - }; - - for (size_t i = 0; i < sizeof(libpthreadFileNames) / sizeof(libpthreadFileNames[0]); ++i) { - pContext->posix.pthreadSO = mal_dlopen(libpthreadFileNames[i]); - if (pContext->posix.pthreadSO != NULL) { - break; - } - } - - if (pContext->posix.pthreadSO == NULL) { - return MAL_FAILED_TO_INIT_BACKEND; - } - - pContext->posix.pthread_create = (mal_proc)mal_dlsym(pContext->posix.pthreadSO, "pthread_create"); - pContext->posix.pthread_join = (mal_proc)mal_dlsym(pContext->posix.pthreadSO, "pthread_join"); - pContext->posix.pthread_mutex_init = (mal_proc)mal_dlsym(pContext->posix.pthreadSO, "pthread_mutex_init"); - pContext->posix.pthread_mutex_destroy = (mal_proc)mal_dlsym(pContext->posix.pthreadSO, "pthread_mutex_destroy"); - pContext->posix.pthread_mutex_lock = (mal_proc)mal_dlsym(pContext->posix.pthreadSO, "pthread_mutex_lock"); - pContext->posix.pthread_mutex_unlock = (mal_proc)mal_dlsym(pContext->posix.pthreadSO, "pthread_mutex_unlock"); - pContext->posix.pthread_cond_init = (mal_proc)mal_dlsym(pContext->posix.pthreadSO, "pthread_cond_init"); - pContext->posix.pthread_cond_destroy = (mal_proc)mal_dlsym(pContext->posix.pthreadSO, "pthread_cond_destroy"); - pContext->posix.pthread_cond_wait = (mal_proc)mal_dlsym(pContext->posix.pthreadSO, "pthread_cond_wait"); - pContext->posix.pthread_cond_signal = (mal_proc)mal_dlsym(pContext->posix.pthreadSO, "pthread_cond_signal"); - pContext->posix.pthread_attr_init = (mal_proc)mal_dlsym(pContext->posix.pthreadSO, "pthread_attr_init"); - pContext->posix.pthread_attr_destroy = (mal_proc)mal_dlsym(pContext->posix.pthreadSO, "pthread_attr_destroy"); - pContext->posix.pthread_attr_setschedpolicy = (mal_proc)mal_dlsym(pContext->posix.pthreadSO, "pthread_attr_setschedpolicy"); - pContext->posix.pthread_attr_getschedparam = (mal_proc)mal_dlsym(pContext->posix.pthreadSO, "pthread_attr_getschedparam"); - pContext->posix.pthread_attr_setschedparam = (mal_proc)mal_dlsym(pContext->posix.pthreadSO, "pthread_attr_setschedparam"); -#else - pContext->posix.pthread_create = (mal_proc)pthread_create; - pContext->posix.pthread_join = (mal_proc)pthread_join; - pContext->posix.pthread_mutex_init = (mal_proc)pthread_mutex_init; - pContext->posix.pthread_mutex_destroy = (mal_proc)pthread_mutex_destroy; - pContext->posix.pthread_mutex_lock = (mal_proc)pthread_mutex_lock; - pContext->posix.pthread_mutex_unlock = (mal_proc)pthread_mutex_unlock; - pContext->posix.pthread_cond_init = (mal_proc)pthread_cond_init; - pContext->posix.pthread_cond_destroy = (mal_proc)pthread_cond_destroy; - pContext->posix.pthread_cond_wait = (mal_proc)pthread_cond_wait; - pContext->posix.pthread_cond_signal = (mal_proc)pthread_cond_signal; - pContext->posix.pthread_attr_init = (mal_proc)pthread_attr_init; - pContext->posix.pthread_attr_destroy = (mal_proc)pthread_attr_destroy; -#if !defined(__EMSCRIPTEN__) - pContext->posix.pthread_attr_setschedpolicy = (mal_proc)pthread_attr_setschedpolicy; - pContext->posix.pthread_attr_getschedparam = (mal_proc)pthread_attr_getschedparam; - pContext->posix.pthread_attr_setschedparam = (mal_proc)pthread_attr_setschedparam; -#endif -#endif - - return MAL_SUCCESS; -} -#endif - -mal_result mal_context_init_backend_apis(mal_context* pContext) -{ - mal_result result; -#ifdef MAL_WIN32 - result = mal_context_init_backend_apis__win32(pContext); -#else - result = mal_context_init_backend_apis__nix(pContext); -#endif - - return result; -} - -mal_result mal_context_uninit_backend_apis(mal_context* pContext) -{ - mal_result result; -#ifdef MAL_WIN32 - result = mal_context_uninit_backend_apis__win32(pContext); -#else - result = mal_context_uninit_backend_apis__nix(pContext); -#endif - - return result; -} - - -mal_bool32 mal_context_is_backend_asynchronous(mal_context* pContext) -{ - return pContext->isBackendAsynchronous; -} - -mal_result mal_context_init(const mal_backend backends[], mal_uint32 backendCount, const mal_context_config* pConfig, mal_context* pContext) -{ - if (pContext == NULL) { - return MAL_INVALID_ARGS; - } - - mal_zero_object(pContext); - - // Always make sure the config is set first to ensure properties are available as soon as possible. - if (pConfig != NULL) { - pContext->config = *pConfig; - } else { - pContext->config = mal_context_config_init(NULL); - } - - // Backend APIs need to be initialized first. This is where external libraries will be loaded and linked. - mal_result result = mal_context_init_backend_apis(pContext); - if (result != MAL_SUCCESS) { - return result; - } - - mal_backend* pBackendsToIterate = (mal_backend*)backends; - mal_uint32 backendsToIterateCount = backendCount; - if (pBackendsToIterate == NULL) { - pBackendsToIterate = (mal_backend*)g_malDefaultBackends; - backendsToIterateCount = mal_countof(g_malDefaultBackends); - } - - mal_assert(pBackendsToIterate != NULL); - - for (mal_uint32 iBackend = 0; iBackend < backendsToIterateCount; ++iBackend) { - mal_backend backend = pBackendsToIterate[iBackend]; - - result = MAL_NO_BACKEND; - switch (backend) { - #ifdef MAL_HAS_WASAPI - case mal_backend_wasapi: - { - result = mal_context_init__wasapi(pContext); - } break; - #endif - #ifdef MAL_HAS_DSOUND - case mal_backend_dsound: - { - result = mal_context_init__dsound(pContext); - } break; - #endif - #ifdef MAL_HAS_WINMM - case mal_backend_winmm: - { - result = mal_context_init__winmm(pContext); - } break; - #endif - #ifdef MAL_HAS_ALSA - case mal_backend_alsa: - { - result = mal_context_init__alsa(pContext); - } break; - #endif - #ifdef MAL_HAS_PULSEAUDIO - case mal_backend_pulseaudio: - { - result = mal_context_init__pulse(pContext); - } break; - #endif - #ifdef MAL_HAS_JACK - case mal_backend_jack: - { - result = mal_context_init__jack(pContext); - } break; - #endif - #ifdef MAL_HAS_COREAUDIO - case mal_backend_coreaudio: - { - result = mal_context_init__coreaudio(pContext); - } break; - #endif - #ifdef MAL_HAS_SNDIO - case mal_backend_sndio: - { - result = mal_context_init__sndio(pContext); - } break; - #endif - #ifdef MAL_HAS_AUDIO4 - case mal_backend_audio4: - { - result = mal_context_init__audio4(pContext); - } break; - #endif - #ifdef MAL_HAS_OSS - case mal_backend_oss: - { - result = mal_context_init__oss(pContext); - } break; - #endif - #ifdef MAL_HAS_AAUDIO - case mal_backend_aaudio: - { - result = mal_context_init__aaudio(pContext); - } break; - #endif - #ifdef MAL_HAS_OPENSL - case mal_backend_opensl: - { - result = mal_context_init__opensl(pContext); - } break; - #endif - #ifdef MAL_HAS_WEBAUDIO - case mal_backend_webaudio: - { - result = mal_context_init__webaudio(pContext); - } break; - #endif - #ifdef MAL_HAS_OPENAL - case mal_backend_openal: - { - result = mal_context_init__openal(pContext); - } break; - #endif - #ifdef MAL_HAS_SDL - case mal_backend_sdl: - { - result = mal_context_init__sdl(pContext); - } break; - #endif - #ifdef MAL_HAS_NULL - case mal_backend_null: - { - result = mal_context_init__null(pContext); - } break; - #endif - - default: break; - } - - // If this iteration was successful, return. - if (result == MAL_SUCCESS) { - result = mal_mutex_init(pContext, &pContext->deviceEnumLock); - if (result != MAL_SUCCESS) { - mal_context_post_error(pContext, NULL, MAL_LOG_LEVEL_WARNING, "Failed to initialize mutex for device enumeration. mal_context_get_devices() is not thread safe.", MAL_FAILED_TO_CREATE_MUTEX); - } - result = mal_mutex_init(pContext, &pContext->deviceInfoLock); - if (result != MAL_SUCCESS) { - mal_context_post_error(pContext, NULL, MAL_LOG_LEVEL_WARNING, "Failed to initialize mutex for device info retrieval. mal_context_get_device_info() is not thread safe.", MAL_FAILED_TO_CREATE_MUTEX); - } - -#ifdef MAL_DEBUG_OUTPUT - printf("[mini_al] Endian: %s\n", mal_is_little_endian() ? "LE" : "BE"); - printf("[mini_al] SSE2: %s\n", mal_has_sse2() ? "YES" : "NO"); - printf("[mini_al] AVX2: %s\n", mal_has_avx2() ? "YES" : "NO"); - printf("[mini_al] AVX512F: %s\n", mal_has_avx512f() ? "YES" : "NO"); - printf("[mini_al] NEON: %s\n", mal_has_neon() ? "YES" : "NO"); -#endif - - pContext->backend = backend; - return result; - } - } - - // If we get here it means an error occurred. - mal_zero_object(pContext); // Safety. - return MAL_NO_BACKEND; -} - -mal_result mal_context_uninit(mal_context* pContext) -{ - if (pContext == NULL) { - return MAL_INVALID_ARGS; - } - - pContext->onUninit(pContext); - - mal_context_uninit_backend_apis(pContext); - mal_mutex_uninit(&pContext->deviceEnumLock); - mal_mutex_uninit(&pContext->deviceInfoLock); - mal_free(pContext->pDeviceInfos); - - return MAL_SUCCESS; -} - - -mal_result mal_context_enumerate_devices(mal_context* pContext, mal_enum_devices_callback_proc callback, void* pUserData) -{ - if (pContext == NULL || pContext->onEnumDevices == NULL || callback == NULL) { - return MAL_INVALID_ARGS; - } - - mal_result result; - mal_mutex_lock(&pContext->deviceEnumLock); - { - result = pContext->onEnumDevices(pContext, callback, pUserData); - } - mal_mutex_unlock(&pContext->deviceEnumLock); - - return result; -} - - -mal_bool32 mal_context_get_devices__enum_callback(mal_context* pContext, mal_device_type type, const mal_device_info* pInfo, void* pUserData) -{ - (void)pUserData; - - // We need to insert the device info into our main internal buffer. Where it goes depends on the device type. If it's a capture device - // it's just appended to the end. If it's a playback device it's inserted just before the first capture device. - - // First make sure we have room. Since the number of devices we add to the list is usually relatively small I've decided to use a - // simple fixed size increment for buffer expansion. - const mal_uint32 bufferExpansionCount = 2; - const mal_uint32 totalDeviceInfoCount = pContext->playbackDeviceInfoCount + pContext->captureDeviceInfoCount; - - if (pContext->deviceInfoCapacity >= totalDeviceInfoCount) { - mal_uint32 newCapacity = totalDeviceInfoCount + bufferExpansionCount; - mal_device_info* pNewInfos = (mal_device_info*)mal_realloc(pContext->pDeviceInfos, sizeof(*pContext->pDeviceInfos)*newCapacity); - if (pNewInfos == NULL) { - return MAL_FALSE; // Out of memory. - } - - pContext->pDeviceInfos = pNewInfos; - pContext->deviceInfoCapacity = newCapacity; - } - - if (type == mal_device_type_playback) { - // Playback. Insert just before the first capture device. - - // The first thing to do is move all of the capture devices down a slot. - mal_uint32 iFirstCaptureDevice = pContext->playbackDeviceInfoCount; - for (size_t iCaptureDevice = totalDeviceInfoCount; iCaptureDevice > iFirstCaptureDevice; --iCaptureDevice) { - pContext->pDeviceInfos[iCaptureDevice] = pContext->pDeviceInfos[iCaptureDevice-1]; - } - - // Now just insert where the first capture device was before moving it down a slot. - pContext->pDeviceInfos[iFirstCaptureDevice] = *pInfo; - pContext->playbackDeviceInfoCount += 1; - } else { - // Capture. Insert at the end. - pContext->pDeviceInfos[totalDeviceInfoCount] = *pInfo; - pContext->captureDeviceInfoCount += 1; - } - - return MAL_TRUE; -} - -mal_result mal_context_get_devices(mal_context* pContext, mal_device_info** ppPlaybackDeviceInfos, mal_uint32* pPlaybackDeviceCount, mal_device_info** ppCaptureDeviceInfos, mal_uint32* pCaptureDeviceCount) -{ - // Safety. - if (ppPlaybackDeviceInfos != NULL) *ppPlaybackDeviceInfos = NULL; - if (pPlaybackDeviceCount != NULL) *pPlaybackDeviceCount = 0; - if (ppCaptureDeviceInfos != NULL) *ppCaptureDeviceInfos = NULL; - if (pCaptureDeviceCount != NULL) *pCaptureDeviceCount = 0; - - if (pContext == NULL || pContext->onEnumDevices == NULL) { - return MAL_INVALID_ARGS; - } - - // Note that we don't use mal_context_enumerate_devices() here because we want to do locking at a higher level. - mal_result result; - mal_mutex_lock(&pContext->deviceEnumLock); - { - // Reset everything first. - pContext->playbackDeviceInfoCount = 0; - pContext->captureDeviceInfoCount = 0; - - // Now enumerate over available devices. - result = pContext->onEnumDevices(pContext, mal_context_get_devices__enum_callback, NULL); - if (result == MAL_SUCCESS) { - // Playback devices. - if (ppPlaybackDeviceInfos != NULL) { - *ppPlaybackDeviceInfos = pContext->pDeviceInfos; - } - if (pPlaybackDeviceCount != NULL) { - *pPlaybackDeviceCount = pContext->playbackDeviceInfoCount; - } - - // Capture devices. - if (ppCaptureDeviceInfos != NULL) { - *ppCaptureDeviceInfos = pContext->pDeviceInfos + pContext->playbackDeviceInfoCount; // Capture devices come after playback devices. - } - if (pCaptureDeviceCount != NULL) { - *pCaptureDeviceCount = pContext->captureDeviceInfoCount; - } - } - } - mal_mutex_unlock(&pContext->deviceEnumLock); - - return result; -} - -mal_result mal_context_get_device_info(mal_context* pContext, mal_device_type type, const mal_device_id* pDeviceID, mal_share_mode shareMode, mal_device_info* pDeviceInfo) -{ - // NOTE: Do not clear pDeviceInfo on entry. The reason is the pDeviceID may actually point to pDeviceInfo->id which will break things. - if (pContext == NULL || pDeviceInfo == NULL) { - return MAL_INVALID_ARGS; - } - - mal_device_info deviceInfo; - mal_zero_object(&deviceInfo); - - // Help the backend out by copying over the device ID if we have one. - if (pDeviceID != NULL) { - mal_copy_memory(&deviceInfo.id, pDeviceID, sizeof(*pDeviceID)); - } - - // The backend may have an optimized device info retrieval function. If so, try that first. - if (pContext->onGetDeviceInfo != NULL) { - mal_result result; - mal_mutex_lock(&pContext->deviceInfoLock); - { - result = pContext->onGetDeviceInfo(pContext, type, pDeviceID, shareMode, &deviceInfo); - } - mal_mutex_unlock(&pContext->deviceInfoLock); - - // Clamp ranges. - deviceInfo.minChannels = mal_max(deviceInfo.minChannels, MAL_MIN_CHANNELS); - deviceInfo.maxChannels = mal_min(deviceInfo.maxChannels, MAL_MAX_CHANNELS); - deviceInfo.minSampleRate = mal_max(deviceInfo.minSampleRate, MAL_MIN_SAMPLE_RATE); - deviceInfo.maxSampleRate = mal_min(deviceInfo.maxSampleRate, MAL_MAX_SAMPLE_RATE); - - *pDeviceInfo = deviceInfo; - return result; - } - - // Getting here means onGetDeviceInfo has not been set. - return MAL_ERROR; -} - - -mal_result mal_device_init(mal_context* pContext, mal_device_type type, mal_device_id* pDeviceID, const mal_device_config* pConfig, void* pUserData, mal_device* pDevice) -{ - if (pContext == NULL) { - return mal_device_init_ex(NULL, 0, NULL, type, pDeviceID, pConfig, pUserData, pDevice); - } - - - if (pDevice == NULL) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "mal_device_init() called with invalid arguments (pDevice == NULL).", MAL_INVALID_ARGS); - } - - // The config is allowed to be NULL, in which case we default to mal_device_config_init_default(). - mal_device_config config; - if (pConfig == NULL) { - config = mal_device_config_init_default(); - } else { - config = *pConfig; - } - - // Basic config validation. - if (config.channels > MAL_MAX_CHANNELS) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "mal_device_init() called with an invalid config. Channel count cannot exceed 32.", MAL_INVALID_DEVICE_CONFIG); - } - if (!mal__is_channel_map_valid(config.channelMap, config.channels)) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "mal_device_init() called with invalid config. Channel map is invalid.", MAL_INVALID_DEVICE_CONFIG); - } - - - mal_zero_object(pDevice); - pDevice->pContext = pContext; - pDevice->initConfig = config; - - // Set the user data and log callback ASAP to ensure it is available for the entire initialization process. - pDevice->pUserData = pUserData; - pDevice->onStop = config.onStopCallback; - pDevice->onSend = config.onSendCallback; - pDevice->onRecv = config.onRecvCallback; - - if (((size_t)pDevice % sizeof(pDevice)) != 0) { - if (pContext->config.onLog) { - pContext->config.onLog(pContext, pDevice, "WARNING: mal_device_init() called for a device that is not properly aligned. Thread safety is not supported."); - } - } - - if (pDeviceID == NULL) { - pDevice->isDefaultDevice = MAL_TRUE; - } - - - // When passing in 0 for the format/channels/rate/chmap it means the device will be using whatever is chosen by the backend. If everything is set - // to defaults it means the format conversion pipeline will run on a fast path where data transfer is just passed straight through to the backend. - if (config.format == mal_format_unknown) { - config.format = MAL_DEFAULT_FORMAT; - pDevice->usingDefaultFormat = MAL_TRUE; - } - if (config.channels == 0) { - config.channels = MAL_DEFAULT_CHANNELS; - pDevice->usingDefaultChannels = MAL_TRUE; - } - if (config.sampleRate == 0) { - config.sampleRate = MAL_DEFAULT_SAMPLE_RATE; - pDevice->usingDefaultSampleRate = MAL_TRUE; - } - if (config.channelMap[0] == MAL_CHANNEL_NONE) { - pDevice->usingDefaultChannelMap = MAL_TRUE; - } - - - // Default buffer size. - if (config.bufferSizeInMilliseconds == 0 && config.bufferSizeInFrames == 0) { - config.bufferSizeInMilliseconds = (config.performanceProfile == mal_performance_profile_low_latency) ? MAL_BASE_BUFFER_SIZE_IN_MILLISECONDS_LOW_LATENCY : MAL_BASE_BUFFER_SIZE_IN_MILLISECONDS_CONSERVATIVE; - pDevice->usingDefaultBufferSize = MAL_TRUE; - } - - // Default periods. - if (config.periods == 0) { - config.periods = MAL_DEFAULT_PERIODS; - pDevice->usingDefaultPeriods = MAL_TRUE; - } - - pDevice->type = type; - pDevice->format = config.format; - pDevice->channels = config.channels; - pDevice->sampleRate = config.sampleRate; - mal_copy_memory(pDevice->channelMap, config.channelMap, sizeof(config.channelMap[0]) * config.channels); - pDevice->bufferSizeInFrames = config.bufferSizeInFrames; - pDevice->bufferSizeInMilliseconds = config.bufferSizeInMilliseconds; - pDevice->periods = config.periods; - - // The internal format, channel count and sample rate can be modified by the backend. - pDevice->internalFormat = pDevice->format; - pDevice->internalChannels = pDevice->channels; - pDevice->internalSampleRate = pDevice->sampleRate; - mal_copy_memory(pDevice->internalChannelMap, pDevice->channelMap, sizeof(pDevice->channelMap)); - - if (mal_mutex_init(pContext, &pDevice->lock) != MAL_SUCCESS) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "Failed to create mutex.", MAL_FAILED_TO_CREATE_MUTEX); - } - - // When the device is started, the worker thread is the one that does the actual startup of the backend device. We - // use a semaphore to wait for the background thread to finish the work. The same applies for stopping the device. - // - // Each of these semaphores is released internally by the worker thread when the work is completed. The start - // semaphore is also used to wake up the worker thread. - if (mal_event_init(pContext, &pDevice->wakeupEvent) != MAL_SUCCESS) { - mal_mutex_uninit(&pDevice->lock); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "Failed to create worker thread wakeup event.", MAL_FAILED_TO_CREATE_EVENT); - } - if (mal_event_init(pContext, &pDevice->startEvent) != MAL_SUCCESS) { - mal_event_uninit(&pDevice->wakeupEvent); - mal_mutex_uninit(&pDevice->lock); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "Failed to create worker thread start event.", MAL_FAILED_TO_CREATE_EVENT); - } - if (mal_event_init(pContext, &pDevice->stopEvent) != MAL_SUCCESS) { - mal_event_uninit(&pDevice->startEvent); - mal_event_uninit(&pDevice->wakeupEvent); - mal_mutex_uninit(&pDevice->lock); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "Failed to create worker thread stop event.", MAL_FAILED_TO_CREATE_EVENT); - } - - - mal_result result = pContext->onDeviceInit(pContext, type, pDeviceID, &config, pDevice); - if (result != MAL_SUCCESS) { - return MAL_NO_BACKEND; // The error message will have been posted with mal_post_error() by the source of the error so don't bother calling it here. - } - - mal_device__post_init_setup(pDevice); - - - // If the backend did not fill out a name for the device, try a generic method. - if (pDevice->name[0] == '\0') { - if (mal_context__try_get_device_name_by_id(pContext, type, pDeviceID, pDevice->name, sizeof(pDevice->name)) != MAL_SUCCESS) { - // We failed to get the device name, so fall back to some generic names. - if (pDeviceID == NULL) { - if (type == mal_device_type_playback) { - mal_strncpy_s(pDevice->name, sizeof(pDevice->name), MAL_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); - } else { - mal_strncpy_s(pDevice->name, sizeof(pDevice->name), MAL_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); - } - } else { - if (type == mal_device_type_playback) { - mal_strncpy_s(pDevice->name, sizeof(pDevice->name), "Playback Device", (size_t)-1); - } else { - mal_strncpy_s(pDevice->name, sizeof(pDevice->name), "Capture Device", (size_t)-1); - } - } - } - } - - - // Some backends don't require the worker thread. - if (!mal_context_is_backend_asynchronous(pContext)) { - // The worker thread. - if (mal_thread_create(pContext, &pDevice->thread, mal_worker_thread, pDevice) != MAL_SUCCESS) { - mal_device_uninit(pDevice); - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "Failed to create worker thread.", MAL_FAILED_TO_CREATE_THREAD); - } - - // Wait for the worker thread to put the device into it's stopped state for real. - mal_event_wait(&pDevice->stopEvent); - } else { - mal_device__set_state(pDevice, MAL_STATE_STOPPED); - } - - -#ifdef MAL_DEBUG_OUTPUT - printf("[%s] %s (%s)\n", mal_get_backend_name(pDevice->pContext->backend), pDevice->name, (pDevice->type == mal_device_type_playback) ? "Playback" : "Capture"); - printf(" Format: %s -> %s\n", mal_get_format_name(pDevice->format), mal_get_format_name(pDevice->internalFormat)); - printf(" Channels: %d -> %d\n", pDevice->channels, pDevice->internalChannels); - printf(" Sample Rate: %d -> %d\n", pDevice->sampleRate, pDevice->internalSampleRate); - printf(" Conversion:\n"); - printf(" Pre Format Conversion: %s\n", pDevice->dsp.isPreFormatConversionRequired ? "YES" : "NO"); - printf(" Post Format Conversion: %s\n", pDevice->dsp.isPostFormatConversionRequired ? "YES" : "NO"); - printf(" Channel Routing: %s\n", pDevice->dsp.isChannelRoutingRequired ? "YES" : "NO"); - printf(" SRC: %s\n", pDevice->dsp.isSRCRequired ? "YES" : "NO"); - printf(" Channel Routing at Start: %s\n", pDevice->dsp.isChannelRoutingAtStart ? "YES" : "NO"); - printf(" Passthrough: %s\n", pDevice->dsp.isPassthrough ? "YES" : "NO"); -#endif - - - mal_assert(mal_device__get_state(pDevice) == MAL_STATE_STOPPED); - return MAL_SUCCESS; -} - -mal_result mal_device_init_ex(const mal_backend backends[], mal_uint32 backendCount, const mal_context_config* pContextConfig, mal_device_type type, mal_device_id* pDeviceID, const mal_device_config* pConfig, void* pUserData, mal_device* pDevice) -{ - mal_context* pContext = (mal_context*)mal_malloc(sizeof(*pContext)); - if (pContext == NULL) { - return MAL_OUT_OF_MEMORY; - } - - mal_backend* pBackendsToIterate = (mal_backend*)backends; - mal_uint32 backendsToIterateCount = backendCount; - if (pBackendsToIterate == NULL) { - pBackendsToIterate = (mal_backend*)g_malDefaultBackends; - backendsToIterateCount = mal_countof(g_malDefaultBackends); - } - - mal_result result = MAL_NO_BACKEND; - - for (mal_uint32 iBackend = 0; iBackend < backendsToIterateCount; ++iBackend) { - result = mal_context_init(&pBackendsToIterate[iBackend], 1, pContextConfig, pContext); - if (result == MAL_SUCCESS) { - result = mal_device_init(pContext, type, pDeviceID, pConfig, pUserData, pDevice); - if (result == MAL_SUCCESS) { - break; // Success. - } else { - mal_context_uninit(pContext); // Failure. - } - } - } - - if (result != MAL_SUCCESS) { - mal_free(pContext); - return result; - } - - pDevice->isOwnerOfContext = MAL_TRUE; - return result; -} - -void mal_device_uninit(mal_device* pDevice) -{ - if (!mal_device__is_initialized(pDevice)) { - return; - } - - // Make sure the device is stopped first. The backends will probably handle this naturally, - // but I like to do it explicitly for my own sanity. - if (mal_device_is_started(pDevice)) { - mal_device_stop(pDevice); - } - - // Putting the device into an uninitialized state will make the worker thread return. - mal_device__set_state(pDevice, MAL_STATE_UNINITIALIZED); - - // Wake up the worker thread and wait for it to properly terminate. - if (!mal_context_is_backend_asynchronous(pDevice->pContext)) { - mal_event_signal(&pDevice->wakeupEvent); - mal_thread_wait(&pDevice->thread); - } - - pDevice->pContext->onDeviceUninit(pDevice); - - mal_event_uninit(&pDevice->stopEvent); - mal_event_uninit(&pDevice->startEvent); - mal_event_uninit(&pDevice->wakeupEvent); - mal_mutex_uninit(&pDevice->lock); - - if (pDevice->isOwnerOfContext) { - mal_context_uninit(pDevice->pContext); - mal_free(pDevice->pContext); - } - - mal_zero_object(pDevice); -} - -void mal_device_set_recv_callback(mal_device* pDevice, mal_recv_proc proc) -{ - if (pDevice == NULL) return; - mal_atomic_exchange_ptr(&pDevice->onRecv, proc); -} - -void mal_device_set_send_callback(mal_device* pDevice, mal_send_proc proc) -{ - if (pDevice == NULL) return; - mal_atomic_exchange_ptr(&pDevice->onSend, proc); -} - -void mal_device_set_stop_callback(mal_device* pDevice, mal_stop_proc proc) -{ - if (pDevice == NULL) return; - mal_atomic_exchange_ptr(&pDevice->onStop, proc); -} - -mal_result mal_device_start(mal_device* pDevice) -{ - if (pDevice == NULL) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "mal_device_start() called with invalid arguments (pDevice == NULL).", MAL_INVALID_ARGS); - } - - if (mal_device__get_state(pDevice) == MAL_STATE_UNINITIALIZED) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "mal_device_start() called for an uninitialized device.", MAL_DEVICE_NOT_INITIALIZED); - } - - mal_result result = MAL_ERROR; - mal_mutex_lock(&pDevice->lock); - { - // Starting, stopping and pausing are wrapped in a mutex which means we can assert that the device is in a stopped or paused state. - mal_assert(mal_device__get_state(pDevice) == MAL_STATE_STOPPED /*|| mal_device__get_state(pDevice) == MAL_STATE_PAUSED*/); - - mal_device__set_state(pDevice, MAL_STATE_STARTING); - - // Asynchronous backends need to be handled differently. - if (mal_context_is_backend_asynchronous(pDevice->pContext)) { - result = pDevice->pContext->onDeviceStart(pDevice); - if (result == MAL_SUCCESS) { - mal_device__set_state(pDevice, MAL_STATE_STARTED); - } - } else { - // Synchronous backends are started by signaling an event that's being waited on in the worker thread. We first wake up the - // thread and then wait for the start event. - mal_event_signal(&pDevice->wakeupEvent); - - // Wait for the worker thread to finish starting the device. Note that the worker thread will be the one - // who puts the device into the started state. Don't call mal_device__set_state() here. - mal_event_wait(&pDevice->startEvent); - result = pDevice->workResult; - } - } - mal_mutex_unlock(&pDevice->lock); - - return result; -} - -mal_result mal_device_stop(mal_device* pDevice) -{ - if (pDevice == NULL) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "mal_device_stop() called with invalid arguments (pDevice == NULL).", MAL_INVALID_ARGS); - } - - if (mal_device__get_state(pDevice) == MAL_STATE_UNINITIALIZED) { - return mal_post_error(pDevice, MAL_LOG_LEVEL_ERROR, "mal_device_stop() called for an uninitialized device.", MAL_DEVICE_NOT_INITIALIZED); - } - - mal_result result = MAL_ERROR; - mal_mutex_lock(&pDevice->lock); - { - // Starting, stopping and pausing are wrapped in a mutex which means we can assert that the device is in a started or paused state. - mal_assert(mal_device__get_state(pDevice) == MAL_STATE_STARTED /*|| mal_device__get_state(pDevice) == MAL_STATE_PAUSED*/); - - mal_device__set_state(pDevice, MAL_STATE_STOPPING); - - // There's no need to wake up the thread like we do when starting. - - // Asynchronous backends need to be handled differently. - if (mal_context_is_backend_asynchronous(pDevice->pContext)) { - result = pDevice->pContext->onDeviceStop(pDevice); - mal_device__set_state(pDevice, MAL_STATE_STOPPED); - } else { - // Synchronous backends. - - // When we get here the worker thread is likely in a wait state while waiting for the backend device to deliver or request - // audio data. We need to force these to return as quickly as possible. - pDevice->pContext->onDeviceBreakMainLoop(pDevice); - - // We need to wait for the worker thread to become available for work before returning. Note that the worker thread will be - // the one who puts the device into the stopped state. Don't call mal_device__set_state() here. - mal_event_wait(&pDevice->stopEvent); - result = MAL_SUCCESS; - } - } - mal_mutex_unlock(&pDevice->lock); - - return result; -} - -mal_bool32 mal_device_is_started(mal_device* pDevice) -{ - if (pDevice == NULL) return MAL_FALSE; - return mal_device__get_state(pDevice) == MAL_STATE_STARTED; -} - -mal_uint32 mal_device_get_buffer_size_in_bytes(mal_device* pDevice) -{ - if (pDevice == NULL) return 0; - return pDevice->bufferSizeInFrames * pDevice->channels * mal_get_bytes_per_sample(pDevice->format); -} - -mal_context_config mal_context_config_init(mal_log_proc onLog) -{ - mal_context_config config; - mal_zero_object(&config); - - config.onLog = onLog; - - return config; -} - - -mal_device_config mal_device_config_init_default() -{ - mal_device_config config; - mal_zero_object(&config); - - return config; -} - -mal_device_config mal_device_config_init_default_capture(mal_recv_proc onRecvCallback) -{ - mal_device_config config = mal_device_config_init_default(); - config.onRecvCallback = onRecvCallback; - - return config; -} - -mal_device_config mal_device_config_init_default_playback(mal_send_proc onSendCallback) -{ - mal_device_config config = mal_device_config_init_default(); - config.onSendCallback = onSendCallback; - - return config; -} - - -mal_device_config mal_device_config_init_ex(mal_format format, mal_uint32 channels, mal_uint32 sampleRate, mal_channel channelMap[MAL_MAX_CHANNELS], mal_recv_proc onRecvCallback, mal_send_proc onSendCallback) -{ - mal_device_config config = mal_device_config_init_default(); - - config.format = format; - config.channels = channels; - config.sampleRate = sampleRate; - config.onRecvCallback = onRecvCallback; - config.onSendCallback = onSendCallback; - - if (channels > 0) { - if (channelMap == NULL) { - if (channels > 8) { - mal_zero_memory(config.channelMap, sizeof(mal_channel)*MAL_MAX_CHANNELS); - } else { - mal_get_standard_channel_map(mal_standard_channel_map_default, channels, config.channelMap); - } - } else { - mal_copy_memory(config.channelMap, channelMap, sizeof(config.channelMap)); - } - } else { - mal_zero_memory(config.channelMap, sizeof(mal_channel)*MAL_MAX_CHANNELS); - } - - return config; -} -#endif // MAL_NO_DEVICE_IO - - -void mal_get_standard_channel_map_microsoft(mal_uint32 channels, mal_channel channelMap[MAL_MAX_CHANNELS]) -{ - // Based off the speaker configurations mentioned here: https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/ksmedia/ns-ksmedia-ksaudio_channel_config - switch (channels) - { - case 1: - { - channelMap[0] = MAL_CHANNEL_MONO; - } break; - - case 2: - { - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_RIGHT; - } break; - - case 3: // Not defined, but best guess. - { - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_RIGHT; - channelMap[2] = MAL_CHANNEL_FRONT_CENTER; - } break; - - case 4: - { -#ifndef MAL_USE_QUAD_MICROSOFT_CHANNEL_MAP - // Surround. Using the Surround profile has the advantage of the 3rd channel (MAL_CHANNEL_FRONT_CENTER) mapping nicely - // with higher channel counts. - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_RIGHT; - channelMap[2] = MAL_CHANNEL_FRONT_CENTER; - channelMap[3] = MAL_CHANNEL_BACK_CENTER; -#else - // Quad. - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_RIGHT; - channelMap[2] = MAL_CHANNEL_BACK_LEFT; - channelMap[3] = MAL_CHANNEL_BACK_RIGHT; -#endif - } break; - - case 5: // Not defined, but best guess. - { - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_RIGHT; - channelMap[2] = MAL_CHANNEL_FRONT_CENTER; - channelMap[3] = MAL_CHANNEL_BACK_LEFT; - channelMap[4] = MAL_CHANNEL_BACK_RIGHT; - } break; - - case 6: - { - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_RIGHT; - channelMap[2] = MAL_CHANNEL_FRONT_CENTER; - channelMap[3] = MAL_CHANNEL_LFE; - channelMap[4] = MAL_CHANNEL_SIDE_LEFT; - channelMap[5] = MAL_CHANNEL_SIDE_RIGHT; - } break; - - case 7: // Not defined, but best guess. - { - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_RIGHT; - channelMap[2] = MAL_CHANNEL_FRONT_CENTER; - channelMap[3] = MAL_CHANNEL_LFE; - channelMap[4] = MAL_CHANNEL_BACK_CENTER; - channelMap[5] = MAL_CHANNEL_SIDE_LEFT; - channelMap[6] = MAL_CHANNEL_SIDE_RIGHT; - } break; - - case 8: - default: - { - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_RIGHT; - channelMap[2] = MAL_CHANNEL_FRONT_CENTER; - channelMap[3] = MAL_CHANNEL_LFE; - channelMap[4] = MAL_CHANNEL_BACK_LEFT; - channelMap[5] = MAL_CHANNEL_BACK_RIGHT; - channelMap[6] = MAL_CHANNEL_SIDE_LEFT; - channelMap[7] = MAL_CHANNEL_SIDE_RIGHT; - } break; - } - - // Remainder. - if (channels > 8) { - for (mal_uint32 iChannel = 8; iChannel < MAL_MAX_CHANNELS; ++iChannel) { - channelMap[iChannel] = (mal_channel)(MAL_CHANNEL_AUX_0 + (iChannel-8)); - } - } -} - -void mal_get_standard_channel_map_alsa(mal_uint32 channels, mal_channel channelMap[MAL_MAX_CHANNELS]) -{ - switch (channels) - { - case 1: - { - channelMap[0] = MAL_CHANNEL_MONO; - } break; - - case 2: - { - channelMap[0] = MAL_CHANNEL_LEFT; - channelMap[1] = MAL_CHANNEL_RIGHT; - } break; - - case 3: - { - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_RIGHT; - channelMap[2] = MAL_CHANNEL_FRONT_CENTER; - } break; - - case 4: - { - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_RIGHT; - channelMap[2] = MAL_CHANNEL_BACK_LEFT; - channelMap[3] = MAL_CHANNEL_BACK_RIGHT; - } break; - - case 5: - { - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_RIGHT; - channelMap[2] = MAL_CHANNEL_BACK_LEFT; - channelMap[3] = MAL_CHANNEL_BACK_RIGHT; - channelMap[4] = MAL_CHANNEL_FRONT_CENTER; - } break; - - case 6: - { - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_RIGHT; - channelMap[2] = MAL_CHANNEL_BACK_LEFT; - channelMap[3] = MAL_CHANNEL_BACK_RIGHT; - channelMap[4] = MAL_CHANNEL_FRONT_CENTER; - channelMap[5] = MAL_CHANNEL_LFE; - } break; - - case 7: - { - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_RIGHT; - channelMap[2] = MAL_CHANNEL_BACK_LEFT; - channelMap[3] = MAL_CHANNEL_BACK_RIGHT; - channelMap[4] = MAL_CHANNEL_FRONT_CENTER; - channelMap[5] = MAL_CHANNEL_LFE; - channelMap[6] = MAL_CHANNEL_BACK_CENTER; - } break; - - case 8: - default: - { - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_RIGHT; - channelMap[2] = MAL_CHANNEL_BACK_LEFT; - channelMap[3] = MAL_CHANNEL_BACK_RIGHT; - channelMap[4] = MAL_CHANNEL_FRONT_CENTER; - channelMap[5] = MAL_CHANNEL_LFE; - channelMap[6] = MAL_CHANNEL_SIDE_LEFT; - channelMap[7] = MAL_CHANNEL_SIDE_RIGHT; - } break; - } - - // Remainder. - if (channels > 8) { - for (mal_uint32 iChannel = 8; iChannel < MAL_MAX_CHANNELS; ++iChannel) { - channelMap[iChannel] = (mal_channel)(MAL_CHANNEL_AUX_0 + (iChannel-8)); - } - } -} - -void mal_get_standard_channel_map_rfc3551(mal_uint32 channels, mal_channel channelMap[MAL_MAX_CHANNELS]) -{ - switch (channels) - { - case 1: - { - channelMap[0] = MAL_CHANNEL_MONO; - } break; - - case 2: - { - channelMap[0] = MAL_CHANNEL_LEFT; - channelMap[1] = MAL_CHANNEL_RIGHT; - } break; - - case 3: - { - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_RIGHT; - channelMap[2] = MAL_CHANNEL_FRONT_CENTER; - } break; - - case 4: - { - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_CENTER; - channelMap[2] = MAL_CHANNEL_FRONT_RIGHT; - channelMap[3] = MAL_CHANNEL_BACK_CENTER; - } break; - - case 5: - { - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_RIGHT; - channelMap[2] = MAL_CHANNEL_FRONT_CENTER; - channelMap[3] = MAL_CHANNEL_BACK_LEFT; - channelMap[4] = MAL_CHANNEL_BACK_RIGHT; - } break; - - case 6: - { - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_SIDE_LEFT; - channelMap[2] = MAL_CHANNEL_FRONT_CENTER; - channelMap[3] = MAL_CHANNEL_FRONT_RIGHT; - channelMap[4] = MAL_CHANNEL_SIDE_RIGHT; - channelMap[5] = MAL_CHANNEL_BACK_CENTER; - } break; - } - - // Remainder. - if (channels > 8) { - for (mal_uint32 iChannel = 6; iChannel < MAL_MAX_CHANNELS; ++iChannel) { - channelMap[iChannel] = (mal_channel)(MAL_CHANNEL_AUX_0 + (iChannel-6)); - } - } -} - -void mal_get_standard_channel_map_flac(mal_uint32 channels, mal_channel channelMap[MAL_MAX_CHANNELS]) -{ - switch (channels) - { - case 1: - { - channelMap[0] = MAL_CHANNEL_MONO; - } break; - - case 2: - { - channelMap[0] = MAL_CHANNEL_LEFT; - channelMap[1] = MAL_CHANNEL_RIGHT; - } break; - - case 3: - { - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_RIGHT; - channelMap[2] = MAL_CHANNEL_FRONT_CENTER; - } break; - - case 4: - { - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_RIGHT; - channelMap[2] = MAL_CHANNEL_BACK_LEFT; - channelMap[3] = MAL_CHANNEL_BACK_RIGHT; - } break; - - case 5: - { - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_RIGHT; - channelMap[2] = MAL_CHANNEL_FRONT_CENTER; - channelMap[3] = MAL_CHANNEL_BACK_LEFT; - channelMap[4] = MAL_CHANNEL_BACK_RIGHT; - } break; - - case 6: - { - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_RIGHT; - channelMap[2] = MAL_CHANNEL_FRONT_CENTER; - channelMap[3] = MAL_CHANNEL_LFE; - channelMap[4] = MAL_CHANNEL_BACK_LEFT; - channelMap[5] = MAL_CHANNEL_BACK_RIGHT; - } break; - - case 7: - { - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_RIGHT; - channelMap[2] = MAL_CHANNEL_FRONT_CENTER; - channelMap[3] = MAL_CHANNEL_LFE; - channelMap[4] = MAL_CHANNEL_BACK_CENTER; - channelMap[5] = MAL_CHANNEL_SIDE_LEFT; - channelMap[6] = MAL_CHANNEL_SIDE_RIGHT; - } break; - - case 8: - default: - { - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_RIGHT; - channelMap[2] = MAL_CHANNEL_FRONT_CENTER; - channelMap[3] = MAL_CHANNEL_LFE; - channelMap[4] = MAL_CHANNEL_BACK_LEFT; - channelMap[5] = MAL_CHANNEL_BACK_RIGHT; - channelMap[6] = MAL_CHANNEL_SIDE_LEFT; - channelMap[7] = MAL_CHANNEL_SIDE_RIGHT; - } break; - } - - // Remainder. - if (channels > 8) { - for (mal_uint32 iChannel = 8; iChannel < MAL_MAX_CHANNELS; ++iChannel) { - channelMap[iChannel] = (mal_channel)(MAL_CHANNEL_AUX_0 + (iChannel-8)); - } - } -} - -void mal_get_standard_channel_map_vorbis(mal_uint32 channels, mal_channel channelMap[MAL_MAX_CHANNELS]) -{ - // In Vorbis' type 0 channel mapping, the first two channels are not always the standard left/right - it - // will have the center speaker where the right usually goes. Why?! - switch (channels) - { - case 1: - { - channelMap[0] = MAL_CHANNEL_MONO; - } break; - - case 2: - { - channelMap[0] = MAL_CHANNEL_LEFT; - channelMap[1] = MAL_CHANNEL_RIGHT; - } break; - - case 3: - { - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_CENTER; - channelMap[2] = MAL_CHANNEL_FRONT_RIGHT; - } break; - - case 4: - { - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_RIGHT; - channelMap[2] = MAL_CHANNEL_BACK_LEFT; - channelMap[3] = MAL_CHANNEL_BACK_RIGHT; - } break; - - case 5: - { - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_CENTER; - channelMap[2] = MAL_CHANNEL_FRONT_RIGHT; - channelMap[3] = MAL_CHANNEL_BACK_LEFT; - channelMap[4] = MAL_CHANNEL_BACK_RIGHT; - } break; - - case 6: - { - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_CENTER; - channelMap[2] = MAL_CHANNEL_FRONT_RIGHT; - channelMap[3] = MAL_CHANNEL_BACK_LEFT; - channelMap[4] = MAL_CHANNEL_BACK_RIGHT; - channelMap[5] = MAL_CHANNEL_LFE; - } break; - - case 7: - { - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_CENTER; - channelMap[2] = MAL_CHANNEL_FRONT_RIGHT; - channelMap[3] = MAL_CHANNEL_SIDE_LEFT; - channelMap[4] = MAL_CHANNEL_SIDE_RIGHT; - channelMap[5] = MAL_CHANNEL_BACK_CENTER; - channelMap[6] = MAL_CHANNEL_LFE; - } break; - - case 8: - default: - { - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_CENTER; - channelMap[2] = MAL_CHANNEL_FRONT_RIGHT; - channelMap[3] = MAL_CHANNEL_SIDE_LEFT; - channelMap[4] = MAL_CHANNEL_SIDE_RIGHT; - channelMap[5] = MAL_CHANNEL_BACK_LEFT; - channelMap[6] = MAL_CHANNEL_BACK_RIGHT; - channelMap[7] = MAL_CHANNEL_LFE; - } break; - } - - // Remainder. - if (channels > 8) { - for (mal_uint32 iChannel = 8; iChannel < MAL_MAX_CHANNELS; ++iChannel) { - channelMap[iChannel] = (mal_channel)(MAL_CHANNEL_AUX_0 + (iChannel-8)); - } - } -} - -void mal_get_standard_channel_map_sound4(mal_uint32 channels, mal_channel channelMap[MAL_MAX_CHANNELS]) -{ - switch (channels) - { - case 1: - { - channelMap[0] = MAL_CHANNEL_MONO; - } break; - - case 2: - { - channelMap[0] = MAL_CHANNEL_LEFT; - channelMap[1] = MAL_CHANNEL_RIGHT; - } break; - - case 3: - { - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_RIGHT; - channelMap[2] = MAL_CHANNEL_BACK_CENTER; - } break; - - case 4: - { - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_RIGHT; - channelMap[2] = MAL_CHANNEL_BACK_LEFT; - channelMap[3] = MAL_CHANNEL_BACK_RIGHT; - } break; - - case 5: - { - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_RIGHT; - channelMap[2] = MAL_CHANNEL_BACK_LEFT; - channelMap[3] = MAL_CHANNEL_BACK_RIGHT; - channelMap[4] = MAL_CHANNEL_FRONT_CENTER; - } break; - - case 6: - { - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_RIGHT; - channelMap[2] = MAL_CHANNEL_BACK_LEFT; - channelMap[3] = MAL_CHANNEL_BACK_RIGHT; - channelMap[4] = MAL_CHANNEL_FRONT_CENTER; - channelMap[5] = MAL_CHANNEL_LFE; - } break; - - case 7: - { - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_RIGHT; - channelMap[2] = MAL_CHANNEL_BACK_LEFT; - channelMap[3] = MAL_CHANNEL_BACK_RIGHT; - channelMap[4] = MAL_CHANNEL_FRONT_CENTER; - channelMap[5] = MAL_CHANNEL_BACK_CENTER; - channelMap[6] = MAL_CHANNEL_LFE; - } break; - - case 8: - default: - { - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_RIGHT; - channelMap[2] = MAL_CHANNEL_BACK_LEFT; - channelMap[3] = MAL_CHANNEL_BACK_RIGHT; - channelMap[4] = MAL_CHANNEL_FRONT_CENTER; - channelMap[5] = MAL_CHANNEL_LFE; - channelMap[6] = MAL_CHANNEL_SIDE_LEFT; - channelMap[7] = MAL_CHANNEL_SIDE_RIGHT; - } break; - } - - // Remainder. - if (channels > 8) { - for (mal_uint32 iChannel = 8; iChannel < MAL_MAX_CHANNELS; ++iChannel) { - channelMap[iChannel] = (mal_channel)(MAL_CHANNEL_AUX_0 + (iChannel-8)); - } - } -} - -void mal_get_standard_channel_map_sndio(mal_uint32 channels, mal_channel channelMap[MAL_MAX_CHANNELS]) -{ - switch (channels) - { - case 1: - { - channelMap[0] = MAL_CHANNEL_MONO; - } break; - - case 2: - { - channelMap[0] = MAL_CHANNEL_LEFT; - channelMap[1] = MAL_CHANNEL_RIGHT; - } break; - - case 3: - { - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_RIGHT; - channelMap[2] = MAL_CHANNEL_FRONT_CENTER; - } break; - - case 4: - { - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_RIGHT; - channelMap[2] = MAL_CHANNEL_BACK_LEFT; - channelMap[3] = MAL_CHANNEL_BACK_RIGHT; - } break; - - case 5: - { - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_RIGHT; - channelMap[2] = MAL_CHANNEL_BACK_LEFT; - channelMap[3] = MAL_CHANNEL_BACK_RIGHT; - channelMap[4] = MAL_CHANNEL_FRONT_CENTER; - } break; - - case 6: - default: - { - channelMap[0] = MAL_CHANNEL_FRONT_LEFT; - channelMap[1] = MAL_CHANNEL_FRONT_RIGHT; - channelMap[2] = MAL_CHANNEL_BACK_LEFT; - channelMap[3] = MAL_CHANNEL_BACK_RIGHT; - channelMap[4] = MAL_CHANNEL_FRONT_CENTER; - channelMap[5] = MAL_CHANNEL_LFE; - } break; - } - - // Remainder. - if (channels > 6) { - for (mal_uint32 iChannel = 6; iChannel < MAL_MAX_CHANNELS; ++iChannel) { - channelMap[iChannel] = (mal_channel)(MAL_CHANNEL_AUX_0 + (iChannel-6)); - } - } -} - -void mal_get_standard_channel_map(mal_standard_channel_map standardChannelMap, mal_uint32 channels, mal_channel channelMap[MAL_MAX_CHANNELS]) -{ - switch (standardChannelMap) - { - case mal_standard_channel_map_alsa: - { - mal_get_standard_channel_map_alsa(channels, channelMap); - } break; - - case mal_standard_channel_map_rfc3551: - { - mal_get_standard_channel_map_rfc3551(channels, channelMap); - } break; - - case mal_standard_channel_map_flac: - { - mal_get_standard_channel_map_flac(channels, channelMap); - } break; - - case mal_standard_channel_map_vorbis: - { - mal_get_standard_channel_map_vorbis(channels, channelMap); - } break; - - case mal_standard_channel_map_sound4: - { - mal_get_standard_channel_map_sound4(channels, channelMap); - } break; - - case mal_standard_channel_map_sndio: - { - mal_get_standard_channel_map_sndio(channels, channelMap); - } break; - - case mal_standard_channel_map_microsoft: - default: - { - mal_get_standard_channel_map_microsoft(channels, channelMap); - } break; - } -} - -void mal_channel_map_copy(mal_channel* pOut, const mal_channel* pIn, mal_uint32 channels) -{ - if (pOut != NULL && pIn != NULL && channels > 0) { - mal_copy_memory(pOut, pIn, sizeof(*pOut) * channels); - } -} - -mal_bool32 mal_channel_map_valid(mal_uint32 channels, const mal_channel channelMap[MAL_MAX_CHANNELS]) -{ - if (channelMap == NULL) { - return MAL_FALSE; - } - - // A channel count of 0 is invalid. - if (channels == 0) { - return MAL_FALSE; - } - - // It does not make sense to have a mono channel when there is more than 1 channel. - if (channels > 1) { - for (mal_uint32 iChannel = 0; iChannel < channels; ++iChannel) { - if (channelMap[iChannel] == MAL_CHANNEL_MONO) { - return MAL_FALSE; - } - } - } - - return MAL_TRUE; -} - -mal_bool32 mal_channel_map_equal(mal_uint32 channels, const mal_channel channelMapA[MAL_MAX_CHANNELS], const mal_channel channelMapB[MAL_MAX_CHANNELS]) -{ - if (channelMapA == channelMapB) { - return MAL_FALSE; - } - - if (channels == 0 || channels > MAL_MAX_CHANNELS) { - return MAL_FALSE; - } - - for (mal_uint32 iChannel = 0; iChannel < channels; ++iChannel) { - if (channelMapA[iChannel] != channelMapB[iChannel]) { - return MAL_FALSE; - } - } - - return MAL_TRUE; -} - -mal_bool32 mal_channel_map_blank(mal_uint32 channels, const mal_channel channelMap[MAL_MAX_CHANNELS]) -{ - for (mal_uint32 iChannel = 0; iChannel < channels; ++iChannel) { - if (channelMap[iChannel] != MAL_CHANNEL_NONE) { - return MAL_FALSE; - } - } - - return MAL_TRUE; -} - -mal_bool32 mal_channel_map_contains_channel_position(mal_uint32 channels, const mal_channel channelMap[MAL_MAX_CHANNELS], mal_channel channelPosition) -{ - for (mal_uint32 iChannel = 0; iChannel < channels; ++iChannel) { - if (channelMap[iChannel] == channelPosition) { - return MAL_TRUE; - } - } - - return MAL_FALSE; -} - - - - -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Format Conversion. -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -//#define MAL_USE_REFERENCE_CONVERSION_APIS 1 -//#define MAL_USE_SSE - -void mal_copy_memory_64(void* dst, const void* src, mal_uint64 sizeInBytes) -{ -#if 0xFFFFFFFFFFFFFFFF <= MAL_SIZE_MAX - mal_copy_memory(dst, src, (size_t)sizeInBytes); -#else - while (sizeInBytes > 0) { - mal_uint64 bytesToCopyNow = sizeInBytes; - if (bytesToCopyNow > MAL_SIZE_MAX) { - bytesToCopyNow = MAL_SIZE_MAX; - } - - mal_copy_memory(dst, src, (size_t)bytesToCopyNow); // Safe cast to size_t. - - sizeInBytes -= bytesToCopyNow; - dst = ( void*)(( mal_uint8*)dst + bytesToCopyNow); - src = (const void*)((const mal_uint8*)src + bytesToCopyNow); - } -#endif -} - -void mal_zero_memory_64(void* dst, mal_uint64 sizeInBytes) -{ -#if 0xFFFFFFFFFFFFFFFF <= MAL_SIZE_MAX - mal_zero_memory(dst, (size_t)sizeInBytes); -#else - while (sizeInBytes > 0) { - mal_uint64 bytesToZeroNow = sizeInBytes; - if (bytesToZeroNow > MAL_SIZE_MAX) { - bytesToZeroNow = MAL_SIZE_MAX; - } - - mal_zero_memory(dst, (size_t)bytesToZeroNow); // Safe cast to size_t. - - sizeInBytes -= bytesToZeroNow; - dst = (void*)((mal_uint8*)dst + bytesToZeroNow); - } -#endif -} - - -// u8 -void mal_pcm_u8_to_u8(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - (void)ditherMode; - mal_copy_memory_64(dst, src, count * sizeof(mal_uint8)); -} - - -void mal_pcm_u8_to_s16__reference(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - (void)ditherMode; - - mal_int16* dst_s16 = (mal_int16*)dst; - const mal_uint8* src_u8 = (const mal_uint8*)src; - - mal_uint64 i; - for (i = 0; i < count; i += 1) { - mal_int16 x = src_u8[i]; - x = x - 128; - x = x << 8; - dst_s16[i] = x; - } -} - -void mal_pcm_u8_to_s16__optimized(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_u8_to_s16__reference(dst, src, count, ditherMode); -} - -#if defined(MAL_SUPPORT_SSE2) -void mal_pcm_u8_to_s16__sse2(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_u8_to_s16__optimized(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_AVX2) -void mal_pcm_u8_to_s16__avx2(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_u8_to_s16__optimized(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_AVX512) -void mal_pcm_u8_to_s16__avx512(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_u8_to_s16__avx2(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_NEON) -void mal_pcm_u8_to_s16__neon(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_u8_to_s16__optimized(dst, src, count, ditherMode); -} -#endif - -void mal_pcm_u8_to_s16(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ -#ifdef MAL_USE_REFERENCE_CONVERSION_APIS - mal_pcm_u8_to_s16__reference(dst, src, count, ditherMode); -#else - mal_pcm_u8_to_s16__optimized(dst, src, count, ditherMode); -#endif -} - - -void mal_pcm_u8_to_s24__reference(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - (void)ditherMode; - - mal_uint8* dst_s24 = (mal_uint8*)dst; - const mal_uint8* src_u8 = (const mal_uint8*)src; - - mal_uint64 i; - for (i = 0; i < count; i += 1) { - mal_int16 x = src_u8[i]; - x = x - 128; - - dst_s24[i*3+0] = 0; - dst_s24[i*3+1] = 0; - dst_s24[i*3+2] = (mal_uint8)((mal_int8)x); - } -} - -void mal_pcm_u8_to_s24__optimized(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_u8_to_s24__reference(dst, src, count, ditherMode); -} - -#if defined(MAL_SUPPORT_SSE2) -void mal_pcm_u8_to_s24__sse2(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_u8_to_s24__optimized(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_AVX2) -void mal_pcm_u8_to_s24__avx2(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_u8_to_s24__optimized(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_AVX512) -void mal_pcm_u8_to_s24__avx512(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_u8_to_s24__avx2(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_NEON) -void mal_pcm_u8_to_s24__neon(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_u8_to_s24__optimized(dst, src, count, ditherMode); -} -#endif - -void mal_pcm_u8_to_s24(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ -#ifdef MAL_USE_REFERENCE_CONVERSION_APIS - mal_pcm_u8_to_s24__reference(dst, src, count, ditherMode); -#else - mal_pcm_u8_to_s24__optimized(dst, src, count, ditherMode); -#endif -} - - -void mal_pcm_u8_to_s32__reference(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - (void)ditherMode; - - mal_int32* dst_s32 = (mal_int32*)dst; - const mal_uint8* src_u8 = (const mal_uint8*)src; - - mal_uint64 i; - for (i = 0; i < count; i += 1) { - mal_int32 x = src_u8[i]; - x = x - 128; - x = x << 24; - dst_s32[i] = x; - } -} - -void mal_pcm_u8_to_s32__optimized(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_u8_to_s32__reference(dst, src, count, ditherMode); -} - -#if defined(MAL_SUPPORT_SSE2) -void mal_pcm_u8_to_s32__sse2(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_u8_to_s32__optimized(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_AVX2) -void mal_pcm_u8_to_s32__avx2(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_u8_to_s32__optimized(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_AVX512) -void mal_pcm_u8_to_s32__avx512(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_u8_to_s32__avx2(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_NEON) -void mal_pcm_u8_to_s32__neon(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_u8_to_s32__optimized(dst, src, count, ditherMode); -} -#endif - -void mal_pcm_u8_to_s32(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ -#ifdef MAL_USE_REFERENCE_CONVERSION_APIS - mal_pcm_u8_to_s32__reference(dst, src, count, ditherMode); -#else - mal_pcm_u8_to_s32__optimized(dst, src, count, ditherMode); -#endif -} - - -void mal_pcm_u8_to_f32__reference(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - (void)ditherMode; - - float* dst_f32 = (float*)dst; - const mal_uint8* src_u8 = (const mal_uint8*)src; - - mal_uint64 i; - for (i = 0; i < count; i += 1) { - float x = (float)src_u8[i]; - x = x * 0.00784313725490196078f; // 0..255 to 0..2 - x = x - 1; // 0..2 to -1..1 - - dst_f32[i] = x; - } -} - -void mal_pcm_u8_to_f32__optimized(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_u8_to_f32__reference(dst, src, count, ditherMode); -} - -#if defined(MAL_SUPPORT_SSE2) -void mal_pcm_u8_to_f32__sse2(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_u8_to_f32__optimized(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_AVX2) -void mal_pcm_u8_to_f32__avx2(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_u8_to_f32__optimized(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_AVX512) -void mal_pcm_u8_to_f32__avx512(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_u8_to_f32__avx2(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_NEON) -void mal_pcm_u8_to_f32__neon(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_u8_to_f32__optimized(dst, src, count, ditherMode); -} -#endif - -void mal_pcm_u8_to_f32(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ -#ifdef MAL_USE_REFERENCE_CONVERSION_APIS - mal_pcm_u8_to_f32__reference(dst, src, count, ditherMode); -#else - mal_pcm_u8_to_f32__optimized(dst, src, count, ditherMode); -#endif -} - - - -void mal_pcm_interleave_u8__reference(void* dst, const void** src, mal_uint64 frameCount, mal_uint32 channels) -{ - mal_uint8* dst_u8 = (mal_uint8*)dst; - const mal_uint8** src_u8 = (const mal_uint8**)src; - - mal_uint64 iFrame; - for (iFrame = 0; iFrame < frameCount; iFrame += 1) { - mal_uint32 iChannel; - for (iChannel = 0; iChannel < channels; iChannel += 1) { - dst_u8[iFrame*channels + iChannel] = src_u8[iChannel][iFrame]; - } - } -} - -void mal_pcm_interleave_u8__optimized(void* dst, const void** src, mal_uint64 frameCount, mal_uint32 channels) -{ - mal_uint8* dst_u8 = (mal_uint8*)dst; - const mal_uint8** src_u8 = (const mal_uint8**)src; - - if (channels == 1) { - mal_copy_memory_64(dst, src[0], frameCount * sizeof(mal_uint8)); - } else if (channels == 2) { - mal_uint64 iFrame; - for (iFrame = 0; iFrame < frameCount; iFrame += 1) { - dst_u8[iFrame*2 + 0] = src_u8[0][iFrame]; - dst_u8[iFrame*2 + 1] = src_u8[1][iFrame]; - } - } else { - mal_uint64 iFrame; - for (iFrame = 0; iFrame < frameCount; iFrame += 1) { - mal_uint32 iChannel; - for (iChannel = 0; iChannel < channels; iChannel += 1) { - dst_u8[iFrame*channels + iChannel] = src_u8[iChannel][iFrame]; - } - } - } -} - -void mal_pcm_interleave_u8(void* dst, const void** src, mal_uint64 frameCount, mal_uint32 channels) -{ -#ifdef MAL_USE_REFERENCE_CONVERSION_APIS - mal_pcm_interleave_u8__reference(dst, src, frameCount, channels); -#else - mal_pcm_interleave_u8__optimized(dst, src, frameCount, channels); -#endif -} - - -void mal_pcm_deinterleave_u8__reference(void** dst, const void* src, mal_uint64 frameCount, mal_uint32 channels) -{ - mal_uint8** dst_u8 = (mal_uint8**)dst; - const mal_uint8* src_u8 = (const mal_uint8*)src; - - mal_uint64 iFrame; - for (iFrame = 0; iFrame < frameCount; iFrame += 1) { - mal_uint32 iChannel; - for (iChannel = 0; iChannel < channels; iChannel += 1) { - dst_u8[iChannel][iFrame] = src_u8[iFrame*channels + iChannel]; - } - } -} - -void mal_pcm_deinterleave_u8__optimized(void** dst, const void* src, mal_uint64 frameCount, mal_uint32 channels) -{ - mal_pcm_deinterleave_u8__reference(dst, src, frameCount, channels); -} - -void mal_pcm_deinterleave_u8(void** dst, const void* src, mal_uint64 frameCount, mal_uint32 channels) -{ -#ifdef MAL_USE_REFERENCE_CONVERSION_APIS - mal_pcm_deinterleave_u8__reference(dst, src, frameCount, channels); -#else - mal_pcm_deinterleave_u8__optimized(dst, src, frameCount, channels); -#endif -} - - -// s16 -void mal_pcm_s16_to_u8__reference(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_uint8* dst_u8 = (mal_uint8*)dst; - const mal_int16* src_s16 = (const mal_int16*)src; - - if (ditherMode == mal_dither_mode_none) { - mal_uint64 i; - for (i = 0; i < count; i += 1) { - mal_int16 x = src_s16[i]; - x = x >> 8; - x = x + 128; - dst_u8[i] = (mal_uint8)x; - } - } else { - mal_uint64 i; - for (i = 0; i < count; i += 1) { - mal_int16 x = src_s16[i]; - - // Dither. Don't overflow. - mal_int32 dither = mal_dither_s32(ditherMode, -0x80, 0x7F); - if ((x + dither) <= 0x7FFF) { - x = (mal_int16)(x + dither); - } else { - x = 0x7FFF; - } - - x = x >> 8; - x = x + 128; - dst_u8[i] = (mal_uint8)x; - } - } -} - -void mal_pcm_s16_to_u8__optimized(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s16_to_u8__reference(dst, src, count, ditherMode); -} - -#if defined(MAL_SUPPORT_SSE2) -void mal_pcm_s16_to_u8__sse2(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s16_to_u8__optimized(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_AVX2) -void mal_pcm_s16_to_u8__avx2(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s16_to_u8__optimized(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_AVX512) -void mal_pcm_s16_to_u8__avx512(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s16_to_u8__avx2(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_NEON) -void mal_pcm_s16_to_u8__neon(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s16_to_u8__optimized(dst, src, count, ditherMode); -} -#endif - -void mal_pcm_s16_to_u8(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ -#ifdef MAL_USE_REFERENCE_CONVERSION_APIS - mal_pcm_s16_to_u8__reference(dst, src, count, ditherMode); -#else - mal_pcm_s16_to_u8__optimized(dst, src, count, ditherMode); -#endif -} - - -void mal_pcm_s16_to_s16(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - (void)ditherMode; - mal_copy_memory_64(dst, src, count * sizeof(mal_int16)); -} - - -void mal_pcm_s16_to_s24__reference(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - (void)ditherMode; - - mal_uint8* dst_s24 = (mal_uint8*)dst; - const mal_int16* src_s16 = (const mal_int16*)src; - - mal_uint64 i; - for (i = 0; i < count; i += 1) { - dst_s24[i*3+0] = 0; - dst_s24[i*3+1] = (mal_uint8)(src_s16[i] & 0xFF); - dst_s24[i*3+2] = (mal_uint8)(src_s16[i] >> 8); - } -} - -void mal_pcm_s16_to_s24__optimized(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s16_to_s24__reference(dst, src, count, ditherMode); -} - -#if defined(MAL_SUPPORT_SSE2) -void mal_pcm_s16_to_s24__sse2(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s16_to_s24__optimized(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_AVX2) -void mal_pcm_s16_to_s24__avx2(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s16_to_s24__optimized(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_AVX512) -void mal_pcm_s16_to_s24__avx512(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s16_to_s24__avx2(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_NEON) -void mal_pcm_s16_to_s24__neon(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s16_to_s24__optimized(dst, src, count, ditherMode); -} -#endif - -void mal_pcm_s16_to_s24(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ -#ifdef MAL_USE_REFERENCE_CONVERSION_APIS - mal_pcm_s16_to_s24__reference(dst, src, count, ditherMode); -#else - mal_pcm_s16_to_s24__optimized(dst, src, count, ditherMode); -#endif -} - - -void mal_pcm_s16_to_s32__reference(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - (void)ditherMode; - - mal_int32* dst_s32 = (mal_int32*)dst; - const mal_int16* src_s16 = (const mal_int16*)src; - - mal_uint64 i; - for (i = 0; i < count; i += 1) { - dst_s32[i] = src_s16[i] << 16; - } -} - -void mal_pcm_s16_to_s32__optimized(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s16_to_s32__reference(dst, src, count, ditherMode); -} - -#if defined(MAL_SUPPORT_SSE2) -void mal_pcm_s16_to_s32__sse2(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s16_to_s32__optimized(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_AVX2) -void mal_pcm_s16_to_s32__avx2(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s16_to_s32__optimized(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_AVX512) -void mal_pcm_s16_to_s32__avx512(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s16_to_s32__avx2(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_NEON) -void mal_pcm_s16_to_s32__neon(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s16_to_s32__optimized(dst, src, count, ditherMode); -} -#endif - -void mal_pcm_s16_to_s32(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ -#ifdef MAL_USE_REFERENCE_CONVERSION_APIS - mal_pcm_s16_to_s32__reference(dst, src, count, ditherMode); -#else - mal_pcm_s16_to_s32__optimized(dst, src, count, ditherMode); -#endif -} - - -void mal_pcm_s16_to_f32__reference(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - (void)ditherMode; - - float* dst_f32 = (float*)dst; - const mal_int16* src_s16 = (const mal_int16*)src; - - mal_uint64 i; - for (i = 0; i < count; i += 1) { - float x = (float)src_s16[i]; - -#if 0 - // The accurate way. - x = x + 32768.0f; // -32768..32767 to 0..65535 - x = x * 0.00003051804379339284f; // 0..65536 to 0..2 - x = x - 1; // 0..2 to -1..1 -#else - // The fast way. - x = x * 0.000030517578125f; // -32768..32767 to -1..0.999969482421875 -#endif - - dst_f32[i] = x; - } -} - -void mal_pcm_s16_to_f32__optimized(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s16_to_f32__reference(dst, src, count, ditherMode); -} - -#if defined(MAL_SUPPORT_SSE2) -void mal_pcm_s16_to_f32__sse2(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s16_to_f32__optimized(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_AVX2) -void mal_pcm_s16_to_f32__avx2(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s16_to_f32__optimized(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_AVX512) -void mal_pcm_s16_to_f32__avx512(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s16_to_f32__avx2(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_NEON) -void mal_pcm_s16_to_f32__neon(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s16_to_f32__optimized(dst, src, count, ditherMode); -} -#endif - -void mal_pcm_s16_to_f32(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ -#ifdef MAL_USE_REFERENCE_CONVERSION_APIS - mal_pcm_s16_to_f32__reference(dst, src, count, ditherMode); -#else - mal_pcm_s16_to_f32__optimized(dst, src, count, ditherMode); -#endif -} - - -void mal_pcm_interleave_s16__reference(void* dst, const void** src, mal_uint64 frameCount, mal_uint32 channels) -{ - mal_int16* dst_s16 = (mal_int16*)dst; - const mal_int16** src_s16 = (const mal_int16**)src; - - mal_uint64 iFrame; - for (iFrame = 0; iFrame < frameCount; iFrame += 1) { - mal_uint32 iChannel; - for (iChannel = 0; iChannel < channels; iChannel += 1) { - dst_s16[iFrame*channels + iChannel] = src_s16[iChannel][iFrame]; - } - } -} - -void mal_pcm_interleave_s16__optimized(void* dst, const void** src, mal_uint64 frameCount, mal_uint32 channels) -{ - mal_pcm_interleave_s16__reference(dst, src, frameCount, channels); -} - -void mal_pcm_interleave_s16(void* dst, const void** src, mal_uint64 frameCount, mal_uint32 channels) -{ -#ifdef MAL_USE_REFERENCE_CONVERSION_APIS - mal_pcm_interleave_s16__reference(dst, src, frameCount, channels); -#else - mal_pcm_interleave_s16__optimized(dst, src, frameCount, channels); -#endif -} - - -void mal_pcm_deinterleave_s16__reference(void** dst, const void* src, mal_uint64 frameCount, mal_uint32 channels) -{ - mal_int16** dst_s16 = (mal_int16**)dst; - const mal_int16* src_s16 = (const mal_int16*)src; - - mal_uint64 iFrame; - for (iFrame = 0; iFrame < frameCount; iFrame += 1) { - mal_uint32 iChannel; - for (iChannel = 0; iChannel < channels; iChannel += 1) { - dst_s16[iChannel][iFrame] = src_s16[iFrame*channels + iChannel]; - } - } -} - -void mal_pcm_deinterleave_s16__optimized(void** dst, const void* src, mal_uint64 frameCount, mal_uint32 channels) -{ - mal_pcm_deinterleave_s16__reference(dst, src, frameCount, channels); -} - -void mal_pcm_deinterleave_s16(void** dst, const void* src, mal_uint64 frameCount, mal_uint32 channels) -{ -#ifdef MAL_USE_REFERENCE_CONVERSION_APIS - mal_pcm_deinterleave_s16__reference(dst, src, frameCount, channels); -#else - mal_pcm_deinterleave_s16__optimized(dst, src, frameCount, channels); -#endif -} - - -// s24 -void mal_pcm_s24_to_u8__reference(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_uint8* dst_u8 = (mal_uint8*)dst; - const mal_uint8* src_s24 = (const mal_uint8*)src; - - if (ditherMode == mal_dither_mode_none) { - mal_uint64 i; - for (i = 0; i < count; i += 1) { - mal_int8 x = (mal_int8)src_s24[i*3 + 2] + 128; - dst_u8[i] = (mal_uint8)x; - } - } else { - mal_uint64 i; - for (i = 0; i < count; i += 1) { - mal_int32 x = (mal_int32)(((mal_uint32)(src_s24[i*3+0]) << 8) | ((mal_uint32)(src_s24[i*3+1]) << 16) | ((mal_uint32)(src_s24[i*3+2])) << 24); - - // Dither. Don't overflow. - mal_int32 dither = mal_dither_s32(ditherMode, -0x800000, 0x7FFFFF); - if ((mal_int64)x + dither <= 0x7FFFFFFF) { - x = x + dither; - } else { - x = 0x7FFFFFFF; - } - - x = x >> 24; - x = x + 128; - dst_u8[i] = (mal_uint8)x; - } - } -} - -void mal_pcm_s24_to_u8__optimized(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s24_to_u8__reference(dst, src, count, ditherMode); -} - -#if defined(MAL_SUPPORT_SSE2) -void mal_pcm_s24_to_u8__sse2(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s24_to_u8__optimized(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_AVX2) -void mal_pcm_s24_to_u8__avx2(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s24_to_u8__optimized(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_AVX512) -void mal_pcm_s24_to_u8__avx512(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s24_to_u8__avx2(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_NEON) -void mal_pcm_s24_to_u8__neon(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s24_to_u8__optimized(dst, src, count, ditherMode); -} -#endif - -void mal_pcm_s24_to_u8(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ -#ifdef MAL_USE_REFERENCE_CONVERSION_APIS - mal_pcm_s24_to_u8__reference(dst, src, count, ditherMode); -#else - mal_pcm_s24_to_u8__optimized(dst, src, count, ditherMode); -#endif -} - - -void mal_pcm_s24_to_s16__reference(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_int16* dst_s16 = (mal_int16*)dst; - const mal_uint8* src_s24 = (const mal_uint8*)src; - - if (ditherMode == mal_dither_mode_none) { - mal_uint64 i; - for (i = 0; i < count; i += 1) { - mal_uint16 dst_lo = ((mal_uint16)src_s24[i*3 + 1]); - mal_uint16 dst_hi = ((mal_uint16)src_s24[i*3 + 2]) << 8; - dst_s16[i] = (mal_int16)dst_lo | dst_hi; - } - } else { - mal_uint64 i; - for (i = 0; i < count; i += 1) { - mal_int32 x = (mal_int32)(((mal_uint32)(src_s24[i*3+0]) << 8) | ((mal_uint32)(src_s24[i*3+1]) << 16) | ((mal_uint32)(src_s24[i*3+2])) << 24); - - // Dither. Don't overflow. - mal_int32 dither = mal_dither_s32(ditherMode, -0x8000, 0x7FFF); - if ((mal_int64)x + dither <= 0x7FFFFFFF) { - x = x + dither; - } else { - x = 0x7FFFFFFF; - } - - x = x >> 16; - dst_s16[i] = (mal_int16)x; - } - } -} - -void mal_pcm_s24_to_s16__optimized(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s24_to_s16__reference(dst, src, count, ditherMode); -} - -#if defined(MAL_SUPPORT_SSE2) -void mal_pcm_s24_to_s16__sse2(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s24_to_s16__optimized(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_AVX2) -void mal_pcm_s24_to_s16__avx2(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s24_to_s16__optimized(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_AVX512) -void mal_pcm_s24_to_s16__avx512(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s24_to_s16__avx2(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_NEON) -void mal_pcm_s24_to_s16__neon(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s24_to_s16__optimized(dst, src, count, ditherMode); -} -#endif - -void mal_pcm_s24_to_s16(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ -#ifdef MAL_USE_REFERENCE_CONVERSION_APIS - mal_pcm_s24_to_s16__reference(dst, src, count, ditherMode); -#else - mal_pcm_s24_to_s16__optimized(dst, src, count, ditherMode); -#endif -} - - -void mal_pcm_s24_to_s24(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - (void)ditherMode; - - mal_copy_memory_64(dst, src, count * 3); -} - - -void mal_pcm_s24_to_s32__reference(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - (void)ditherMode; - - mal_int32* dst_s32 = (mal_int32*)dst; - const mal_uint8* src_s24 = (const mal_uint8*)src; - - mal_uint64 i; - for (i = 0; i < count; i += 1) { - dst_s32[i] = (mal_int32)(((mal_uint32)(src_s24[i*3+0]) << 8) | ((mal_uint32)(src_s24[i*3+1]) << 16) | ((mal_uint32)(src_s24[i*3+2])) << 24); - } -} - -void mal_pcm_s24_to_s32__optimized(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s24_to_s32__reference(dst, src, count, ditherMode); -} - -#if defined(MAL_SUPPORT_SSE2) -void mal_pcm_s24_to_s32__sse2(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s24_to_s32__optimized(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_AVX2) -void mal_pcm_s24_to_s32__avx2(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s24_to_s32__optimized(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_AVX512) -void mal_pcm_s24_to_s32__avx512(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s24_to_s32__avx2(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_NEON) -void mal_pcm_s24_to_s32__neon(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s24_to_s32__optimized(dst, src, count, ditherMode); -} -#endif - -void mal_pcm_s24_to_s32(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ -#ifdef MAL_USE_REFERENCE_CONVERSION_APIS - mal_pcm_s24_to_s32__reference(dst, src, count, ditherMode); -#else - mal_pcm_s24_to_s32__optimized(dst, src, count, ditherMode); -#endif -} - - -void mal_pcm_s24_to_f32__reference(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - (void)ditherMode; - - float* dst_f32 = (float*)dst; - const mal_uint8* src_s24 = (const mal_uint8*)src; - - mal_uint64 i; - for (i = 0; i < count; i += 1) { - float x = (float)(((mal_int32)(((mal_uint32)(src_s24[i*3+0]) << 8) | ((mal_uint32)(src_s24[i*3+1]) << 16) | ((mal_uint32)(src_s24[i*3+2])) << 24)) >> 8); - -#if 0 - // The accurate way. - x = x + 8388608.0f; // -8388608..8388607 to 0..16777215 - x = x * 0.00000011920929665621f; // 0..16777215 to 0..2 - x = x - 1; // 0..2 to -1..1 -#else - // The fast way. - x = x * 0.00000011920928955078125f; // -8388608..8388607 to -1..0.999969482421875 -#endif - - dst_f32[i] = x; - } -} - -void mal_pcm_s24_to_f32__optimized(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s24_to_f32__reference(dst, src, count, ditherMode); -} - -#if defined(MAL_SUPPORT_SSE2) -void mal_pcm_s24_to_f32__sse2(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s24_to_f32__optimized(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_AVX2) -void mal_pcm_s24_to_f32__avx2(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s24_to_f32__optimized(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_AVX512) -void mal_pcm_s24_to_f32__avx512(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s24_to_f32__avx2(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_NEON) -void mal_pcm_s24_to_f32__neon(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s24_to_f32__optimized(dst, src, count, ditherMode); -} -#endif - -void mal_pcm_s24_to_f32(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ -#ifdef MAL_USE_REFERENCE_CONVERSION_APIS - mal_pcm_s24_to_f32__reference(dst, src, count, ditherMode); -#else - mal_pcm_s24_to_f32__optimized(dst, src, count, ditherMode); -#endif -} - - -void mal_pcm_interleave_s24__reference(void* dst, const void** src, mal_uint64 frameCount, mal_uint32 channels) -{ - mal_uint8* dst8 = (mal_uint8*)dst; - const mal_uint8** src8 = (const mal_uint8**)src; - - mal_uint64 iFrame; - for (iFrame = 0; iFrame < frameCount; iFrame += 1) { - mal_uint32 iChannel; - for (iChannel = 0; iChannel < channels; iChannel += 1) { - dst8[iFrame*3*channels + iChannel*3 + 0] = src8[iChannel][iFrame*3 + 0]; - dst8[iFrame*3*channels + iChannel*3 + 1] = src8[iChannel][iFrame*3 + 1]; - dst8[iFrame*3*channels + iChannel*3 + 2] = src8[iChannel][iFrame*3 + 2]; - } - } -} - -void mal_pcm_interleave_s24__optimized(void* dst, const void** src, mal_uint64 frameCount, mal_uint32 channels) -{ - mal_pcm_interleave_s24__reference(dst, src, frameCount, channels); -} - -void mal_pcm_interleave_s24(void* dst, const void** src, mal_uint64 frameCount, mal_uint32 channels) -{ -#ifdef MAL_USE_REFERENCE_CONVERSION_APIS - mal_pcm_interleave_s24__reference(dst, src, frameCount, channels); -#else - mal_pcm_interleave_s24__optimized(dst, src, frameCount, channels); -#endif -} - - -void mal_pcm_deinterleave_s24__reference(void** dst, const void* src, mal_uint64 frameCount, mal_uint32 channels) -{ - mal_uint8** dst8 = (mal_uint8**)dst; - const mal_uint8* src8 = (const mal_uint8*)src; - - mal_uint32 iFrame; - for (iFrame = 0; iFrame < frameCount; iFrame += 1) { - mal_uint32 iChannel; - for (iChannel = 0; iChannel < channels; iChannel += 1) { - dst8[iChannel][iFrame*3 + 0] = src8[iFrame*3*channels + iChannel*3 + 0]; - dst8[iChannel][iFrame*3 + 1] = src8[iFrame*3*channels + iChannel*3 + 1]; - dst8[iChannel][iFrame*3 + 2] = src8[iFrame*3*channels + iChannel*3 + 2]; - } - } -} - -void mal_pcm_deinterleave_s24__optimized(void** dst, const void* src, mal_uint64 frameCount, mal_uint32 channels) -{ - mal_pcm_deinterleave_s24__reference(dst, src, frameCount, channels); -} - -void mal_pcm_deinterleave_s24(void** dst, const void* src, mal_uint64 frameCount, mal_uint32 channels) -{ -#ifdef MAL_USE_REFERENCE_CONVERSION_APIS - mal_pcm_deinterleave_s24__reference(dst, src, frameCount, channels); -#else - mal_pcm_deinterleave_s24__optimized(dst, src, frameCount, channels); -#endif -} - - - -// s32 -void mal_pcm_s32_to_u8__reference(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_uint8* dst_u8 = (mal_uint8*)dst; - const mal_int32* src_s32 = (const mal_int32*)src; - - if (ditherMode == mal_dither_mode_none) { - mal_uint64 i; - for (i = 0; i < count; i += 1) { - mal_int32 x = src_s32[i]; - x = x >> 24; - x = x + 128; - dst_u8[i] = (mal_uint8)x; - } - } else { - mal_uint64 i; - for (i = 0; i < count; i += 1) { - mal_int32 x = src_s32[i]; - - // Dither. Don't overflow. - mal_int32 dither = mal_dither_s32(ditherMode, -0x800000, 0x7FFFFF); - if ((mal_int64)x + dither <= 0x7FFFFFFF) { - x = x + dither; - } else { - x = 0x7FFFFFFF; - } - - x = x >> 24; - x = x + 128; - dst_u8[i] = (mal_uint8)x; - } - } -} - -void mal_pcm_s32_to_u8__optimized(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s32_to_u8__reference(dst, src, count, ditherMode); -} - -#if defined(MAL_SUPPORT_SSE2) -void mal_pcm_s32_to_u8__sse2(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s32_to_u8__optimized(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_AVX2) -void mal_pcm_s32_to_u8__avx2(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s32_to_u8__optimized(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_AVX512) -void mal_pcm_s32_to_u8__avx512(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s32_to_u8__avx2(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_NEON) -void mal_pcm_s32_to_u8__neon(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s32_to_u8__optimized(dst, src, count, ditherMode); -} -#endif - -void mal_pcm_s32_to_u8(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ -#ifdef MAL_USE_REFERENCE_CONVERSION_APIS - mal_pcm_s32_to_u8__reference(dst, src, count, ditherMode); -#else - mal_pcm_s32_to_u8__optimized(dst, src, count, ditherMode); -#endif -} - - -void mal_pcm_s32_to_s16__reference(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_int16* dst_s16 = (mal_int16*)dst; - const mal_int32* src_s32 = (const mal_int32*)src; - - if (ditherMode == mal_dither_mode_none) { - mal_uint64 i; - for (i = 0; i < count; i += 1) { - mal_int32 x = src_s32[i]; - x = x >> 16; - dst_s16[i] = (mal_int16)x; - } - } else { - mal_uint64 i; - for (i = 0; i < count; i += 1) { - mal_int32 x = src_s32[i]; - - // Dither. Don't overflow. - mal_int32 dither = mal_dither_s32(ditherMode, -0x8000, 0x7FFF); - if ((mal_int64)x + dither <= 0x7FFFFFFF) { - x = x + dither; - } else { - x = 0x7FFFFFFF; - } - - x = x >> 16; - dst_s16[i] = (mal_int16)x; - } - } -} - -void mal_pcm_s32_to_s16__optimized(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s32_to_s16__reference(dst, src, count, ditherMode); -} - -#if defined(MAL_SUPPORT_SSE2) -void mal_pcm_s32_to_s16__sse2(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s32_to_s16__optimized(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_AVX2) -void mal_pcm_s32_to_s16__avx2(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s32_to_s16__optimized(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_AVX512) -void mal_pcm_s32_to_s16__avx512(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s32_to_s16__avx2(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_NEON) -void mal_pcm_s32_to_s16__neon(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s32_to_s16__optimized(dst, src, count, ditherMode); -} -#endif - -void mal_pcm_s32_to_s16(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ -#ifdef MAL_USE_REFERENCE_CONVERSION_APIS - mal_pcm_s32_to_s16__reference(dst, src, count, ditherMode); -#else - mal_pcm_s32_to_s16__optimized(dst, src, count, ditherMode); -#endif -} - - -void mal_pcm_s32_to_s24__reference(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - (void)ditherMode; // No dithering for s32 -> s24. - - mal_uint8* dst_s24 = (mal_uint8*)dst; - const mal_int32* src_s32 = (const mal_int32*)src; - - mal_uint64 i; - for (i = 0; i < count; i += 1) { - mal_uint32 x = (mal_uint32)src_s32[i]; - dst_s24[i*3+0] = (mal_uint8)((x & 0x0000FF00) >> 8); - dst_s24[i*3+1] = (mal_uint8)((x & 0x00FF0000) >> 16); - dst_s24[i*3+2] = (mal_uint8)((x & 0xFF000000) >> 24); - } -} - -void mal_pcm_s32_to_s24__optimized(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s32_to_s24__reference(dst, src, count, ditherMode); -} - -#if defined(MAL_SUPPORT_SSE2) -void mal_pcm_s32_to_s24__sse2(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s32_to_s24__optimized(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_AVX2) -void mal_pcm_s32_to_s24__avx2(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s32_to_s24__optimized(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_AVX512) -void mal_pcm_s32_to_s24__avx512(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s32_to_s24__avx2(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_NEON) -void mal_pcm_s32_to_s24__neon(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s32_to_s24__optimized(dst, src, count, ditherMode); -} -#endif - -void mal_pcm_s32_to_s24(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ -#ifdef MAL_USE_REFERENCE_CONVERSION_APIS - mal_pcm_s32_to_s24__reference(dst, src, count, ditherMode); -#else - mal_pcm_s32_to_s24__optimized(dst, src, count, ditherMode); -#endif -} - - -void mal_pcm_s32_to_s32(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - (void)ditherMode; - - mal_copy_memory_64(dst, src, count * sizeof(mal_int32)); -} - - -void mal_pcm_s32_to_f32__reference(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - (void)ditherMode; // No dithering for s32 -> f32. - - float* dst_f32 = (float*)dst; - const mal_int32* src_s32 = (const mal_int32*)src; - - mal_uint64 i; - for (i = 0; i < count; i += 1) { - double x = src_s32[i]; - -#if 0 - x = x + 2147483648.0; - x = x * 0.0000000004656612873077392578125; - x = x - 1; -#else - x = x / 2147483648.0; -#endif - - dst_f32[i] = (float)x; - } -} - -void mal_pcm_s32_to_f32__optimized(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s32_to_f32__reference(dst, src, count, ditherMode); -} - -#if defined(MAL_SUPPORT_SSE2) -void mal_pcm_s32_to_f32__sse2(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s32_to_f32__optimized(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_AVX2) -void mal_pcm_s32_to_f32__avx2(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s32_to_f32__optimized(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_AVX512) -void mal_pcm_s32_to_f32__avx512(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s32_to_f32__avx2(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_NEON) -void mal_pcm_s32_to_f32__neon(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_s32_to_f32__optimized(dst, src, count, ditherMode); -} -#endif - -void mal_pcm_s32_to_f32(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ -#ifdef MAL_USE_REFERENCE_CONVERSION_APIS - mal_pcm_s32_to_f32__reference(dst, src, count, ditherMode); -#else - mal_pcm_s32_to_f32__optimized(dst, src, count, ditherMode); -#endif -} - - -void mal_pcm_interleave_s32__reference(void* dst, const void** src, mal_uint64 frameCount, mal_uint32 channels) -{ - mal_int32* dst_s32 = (mal_int32*)dst; - const mal_int32** src_s32 = (const mal_int32**)src; - - mal_uint64 iFrame; - for (iFrame = 0; iFrame < frameCount; iFrame += 1) { - mal_uint32 iChannel; - for (iChannel = 0; iChannel < channels; iChannel += 1) { - dst_s32[iFrame*channels + iChannel] = src_s32[iChannel][iFrame]; - } - } -} - -void mal_pcm_interleave_s32__optimized(void* dst, const void** src, mal_uint64 frameCount, mal_uint32 channels) -{ - mal_pcm_interleave_s32__reference(dst, src, frameCount, channels); -} - -void mal_pcm_interleave_s32(void* dst, const void** src, mal_uint64 frameCount, mal_uint32 channels) -{ -#ifdef MAL_USE_REFERENCE_CONVERSION_APIS - mal_pcm_interleave_s32__reference(dst, src, frameCount, channels); -#else - mal_pcm_interleave_s32__optimized(dst, src, frameCount, channels); -#endif -} - - -void mal_pcm_deinterleave_s32__reference(void** dst, const void* src, mal_uint64 frameCount, mal_uint32 channels) -{ - mal_int32** dst_s32 = (mal_int32**)dst; - const mal_int32* src_s32 = (const mal_int32*)src; - - mal_uint64 iFrame; - for (iFrame = 0; iFrame < frameCount; iFrame += 1) { - mal_uint32 iChannel; - for (iChannel = 0; iChannel < channels; iChannel += 1) { - dst_s32[iChannel][iFrame] = src_s32[iFrame*channels + iChannel]; - } - } -} - -void mal_pcm_deinterleave_s32__optimized(void** dst, const void* src, mal_uint64 frameCount, mal_uint32 channels) -{ - mal_pcm_deinterleave_s32__reference(dst, src, frameCount, channels); -} - -void mal_pcm_deinterleave_s32(void** dst, const void* src, mal_uint64 frameCount, mal_uint32 channels) -{ -#ifdef MAL_USE_REFERENCE_CONVERSION_APIS - mal_pcm_deinterleave_s32__reference(dst, src, frameCount, channels); -#else - mal_pcm_deinterleave_s32__optimized(dst, src, frameCount, channels); -#endif -} - - -// f32 -void mal_pcm_f32_to_u8__reference(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_uint8* dst_u8 = (mal_uint8*)dst; - const float* src_f32 = (const float*)src; - - float ditherMin = 0; - float ditherMax = 0; - if (ditherMode != mal_dither_mode_none) { - ditherMin = 1.0f / -128; - ditherMax = 1.0f / 127; - } - - mal_uint64 i; - for (i = 0; i < count; i += 1) { - float x = src_f32[i]; - x = x + mal_dither_f32(ditherMode, ditherMin, ditherMax); - x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); // clip - x = x + 1; // -1..1 to 0..2 - x = x * 127.5f; // 0..2 to 0..255 - - dst_u8[i] = (mal_uint8)x; - } -} - -void mal_pcm_f32_to_u8__optimized(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_f32_to_u8__reference(dst, src, count, ditherMode); -} - -#if defined(MAL_SUPPORT_SSE2) -void mal_pcm_f32_to_u8__sse2(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_f32_to_u8__optimized(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_AVX2) -void mal_pcm_f32_to_u8__avx2(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_f32_to_u8__optimized(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_AVX512) -void mal_pcm_f32_to_u8__avx512(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_f32_to_u8__avx2(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_NEON) -void mal_pcm_f32_to_u8__neon(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_f32_to_u8__optimized(dst, src, count, ditherMode); -} -#endif - -void mal_pcm_f32_to_u8(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ -#ifdef MAL_USE_REFERENCE_CONVERSION_APIS - mal_pcm_f32_to_u8__reference(dst, src, count, ditherMode); -#else - mal_pcm_f32_to_u8__optimized(dst, src, count, ditherMode); -#endif -} - - -void mal_pcm_f32_to_s16__reference(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_int16* dst_s16 = (mal_int16*)dst; - const float* src_f32 = (const float*)src; - - float ditherMin = 0; - float ditherMax = 0; - if (ditherMode != mal_dither_mode_none) { - ditherMin = 1.0f / -32768; - ditherMax = 1.0f / 32767; - } - - mal_uint64 i; - for (i = 0; i < count; i += 1) { - float x = src_f32[i]; - x = x + mal_dither_f32(ditherMode, ditherMin, ditherMax); - x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); // clip - -#if 0 - // The accurate way. - x = x + 1; // -1..1 to 0..2 - x = x * 32767.5f; // 0..2 to 0..65535 - x = x - 32768.0f; // 0...65535 to -32768..32767 -#else - // The fast way. - x = x * 32767.0f; // -1..1 to -32767..32767 -#endif - - dst_s16[i] = (mal_int16)x; - } -} - -void mal_pcm_f32_to_s16__optimized(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_int16* dst_s16 = (mal_int16*)dst; - const float* src_f32 = (const float*)src; - - float ditherMin = 0; - float ditherMax = 0; - if (ditherMode != mal_dither_mode_none) { - ditherMin = 1.0f / -32768; - ditherMax = 1.0f / 32767; - } - - mal_uint64 i = 0; - - // Unrolled. - mal_uint64 count4 = count >> 2; - for (mal_uint64 i4 = 0; i4 < count4; i4 += 1) { - float d0 = mal_dither_f32(ditherMode, ditherMin, ditherMax); - float d1 = mal_dither_f32(ditherMode, ditherMin, ditherMax); - float d2 = mal_dither_f32(ditherMode, ditherMin, ditherMax); - float d3 = mal_dither_f32(ditherMode, ditherMin, ditherMax); - - float x0 = src_f32[i+0]; - float x1 = src_f32[i+1]; - float x2 = src_f32[i+2]; - float x3 = src_f32[i+3]; - - x0 = x0 + d0; - x1 = x1 + d1; - x2 = x2 + d2; - x3 = x3 + d3; - - x0 = ((x0 < -1) ? -1 : ((x0 > 1) ? 1 : x0)); - x1 = ((x1 < -1) ? -1 : ((x1 > 1) ? 1 : x1)); - x2 = ((x2 < -1) ? -1 : ((x2 > 1) ? 1 : x2)); - x3 = ((x3 < -1) ? -1 : ((x3 > 1) ? 1 : x3)); - - x0 = x0 * 32767.0f; - x1 = x1 * 32767.0f; - x2 = x2 * 32767.0f; - x3 = x3 * 32767.0f; - - dst_s16[i+0] = (mal_int16)x0; - dst_s16[i+1] = (mal_int16)x1; - dst_s16[i+2] = (mal_int16)x2; - dst_s16[i+3] = (mal_int16)x3; - - i += 4; - } - - // Leftover. - for (; i < count; i += 1) { - float x = src_f32[i]; - x = x + mal_dither_f32(ditherMode, ditherMin, ditherMax); - x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); // clip - x = x * 32767.0f; // -1..1 to -32767..32767 - - dst_s16[i] = (mal_int16)x; - } -} - -#if defined(MAL_SUPPORT_SSE2) -void mal_pcm_f32_to_s16__sse2(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - // Both the input and output buffers need to be aligned to 16 bytes. - if ((((mal_uintptr)dst & 15) != 0) || (((mal_uintptr)src & 15) != 0)) { - mal_pcm_f32_to_s16__optimized(dst, src, count, ditherMode); - return; - } - - mal_int16* dst_s16 = (mal_int16*)dst; - const float* src_f32 = (const float*)src; - - float ditherMin = 0; - float ditherMax = 0; - if (ditherMode != mal_dither_mode_none) { - ditherMin = 1.0f / -32768; - ditherMax = 1.0f / 32767; - } - - mal_uint64 i = 0; - - // SSE2. SSE allows us to output 8 s16's at a time which means our loop is unrolled 8 times. - mal_uint64 count8 = count >> 3; - for (mal_uint64 i8 = 0; i8 < count8; i8 += 1) { - __m128 d0; - __m128 d1; - if (ditherMode == mal_dither_mode_none) { - d0 = _mm_set1_ps(0); - d1 = _mm_set1_ps(0); - } else if (ditherMode == mal_dither_mode_rectangle) { - d0 = _mm_set_ps( - mal_dither_f32_rectangle(ditherMin, ditherMax), - mal_dither_f32_rectangle(ditherMin, ditherMax), - mal_dither_f32_rectangle(ditherMin, ditherMax), - mal_dither_f32_rectangle(ditherMin, ditherMax) - ); - d1 = _mm_set_ps( - mal_dither_f32_rectangle(ditherMin, ditherMax), - mal_dither_f32_rectangle(ditherMin, ditherMax), - mal_dither_f32_rectangle(ditherMin, ditherMax), - mal_dither_f32_rectangle(ditherMin, ditherMax) - ); - } else { - d0 = _mm_set_ps( - mal_dither_f32_triangle(ditherMin, ditherMax), - mal_dither_f32_triangle(ditherMin, ditherMax), - mal_dither_f32_triangle(ditherMin, ditherMax), - mal_dither_f32_triangle(ditherMin, ditherMax) - ); - d1 = _mm_set_ps( - mal_dither_f32_triangle(ditherMin, ditherMax), - mal_dither_f32_triangle(ditherMin, ditherMax), - mal_dither_f32_triangle(ditherMin, ditherMax), - mal_dither_f32_triangle(ditherMin, ditherMax) - ); - } - - __m128 x0 = *((__m128*)(src_f32 + i) + 0); - __m128 x1 = *((__m128*)(src_f32 + i) + 1); - - x0 = _mm_add_ps(x0, d0); - x1 = _mm_add_ps(x1, d1); - - x0 = _mm_mul_ps(x0, _mm_set1_ps(32767.0f)); - x1 = _mm_mul_ps(x1, _mm_set1_ps(32767.0f)); - - _mm_stream_si128(((__m128i*)(dst_s16 + i)), _mm_packs_epi32(_mm_cvttps_epi32(x0), _mm_cvttps_epi32(x1))); - - i += 8; - } - - - // Leftover. - for (; i < count; i += 1) { - float x = src_f32[i]; - x = x + mal_dither_f32(ditherMode, ditherMin, ditherMax); - x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); // clip - x = x * 32767.0f; // -1..1 to -32767..32767 - - dst_s16[i] = (mal_int16)x; - } -} -#endif -#if defined(MAL_SUPPORT_AVX2) -void mal_pcm_f32_to_s16__avx2(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - // Both the input and output buffers need to be aligned to 32 bytes. - if ((((mal_uintptr)dst & 31) != 0) || (((mal_uintptr)src & 31) != 0)) { - mal_pcm_f32_to_s16__optimized(dst, src, count, ditherMode); - return; - } - - mal_int16* dst_s16 = (mal_int16*)dst; - const float* src_f32 = (const float*)src; - - float ditherMin = 0; - float ditherMax = 0; - if (ditherMode != mal_dither_mode_none) { - ditherMin = 1.0f / -32768; - ditherMax = 1.0f / 32767; - } - - mal_uint64 i = 0; - - // AVX2. AVX2 allows us to output 16 s16's at a time which means our loop is unrolled 16 times. - mal_uint64 count16 = count >> 4; - for (mal_uint64 i16 = 0; i16 < count16; i16 += 1) { - __m256 d0; - __m256 d1; - if (ditherMode == mal_dither_mode_none) { - d0 = _mm256_set1_ps(0); - d1 = _mm256_set1_ps(0); - } else if (ditherMode == mal_dither_mode_rectangle) { - d0 = _mm256_set_ps( - mal_dither_f32_rectangle(ditherMin, ditherMax), - mal_dither_f32_rectangle(ditherMin, ditherMax), - mal_dither_f32_rectangle(ditherMin, ditherMax), - mal_dither_f32_rectangle(ditherMin, ditherMax), - mal_dither_f32_rectangle(ditherMin, ditherMax), - mal_dither_f32_rectangle(ditherMin, ditherMax), - mal_dither_f32_rectangle(ditherMin, ditherMax), - mal_dither_f32_rectangle(ditherMin, ditherMax) - ); - d1 = _mm256_set_ps( - mal_dither_f32_rectangle(ditherMin, ditherMax), - mal_dither_f32_rectangle(ditherMin, ditherMax), - mal_dither_f32_rectangle(ditherMin, ditherMax), - mal_dither_f32_rectangle(ditherMin, ditherMax), - mal_dither_f32_rectangle(ditherMin, ditherMax), - mal_dither_f32_rectangle(ditherMin, ditherMax), - mal_dither_f32_rectangle(ditherMin, ditherMax), - mal_dither_f32_rectangle(ditherMin, ditherMax) - ); - } else { - d0 = _mm256_set_ps( - mal_dither_f32_triangle(ditherMin, ditherMax), - mal_dither_f32_triangle(ditherMin, ditherMax), - mal_dither_f32_triangle(ditherMin, ditherMax), - mal_dither_f32_triangle(ditherMin, ditherMax), - mal_dither_f32_triangle(ditherMin, ditherMax), - mal_dither_f32_triangle(ditherMin, ditherMax), - mal_dither_f32_triangle(ditherMin, ditherMax), - mal_dither_f32_triangle(ditherMin, ditherMax) - ); - d1 = _mm256_set_ps( - mal_dither_f32_triangle(ditherMin, ditherMax), - mal_dither_f32_triangle(ditherMin, ditherMax), - mal_dither_f32_triangle(ditherMin, ditherMax), - mal_dither_f32_triangle(ditherMin, ditherMax), - mal_dither_f32_triangle(ditherMin, ditherMax), - mal_dither_f32_triangle(ditherMin, ditherMax), - mal_dither_f32_triangle(ditherMin, ditherMax), - mal_dither_f32_triangle(ditherMin, ditherMax) - ); - } - - __m256 x0 = *((__m256*)(src_f32 + i) + 0); - __m256 x1 = *((__m256*)(src_f32 + i) + 1); - - x0 = _mm256_add_ps(x0, d0); - x1 = _mm256_add_ps(x1, d1); - - x0 = _mm256_mul_ps(x0, _mm256_set1_ps(32767.0f)); - x1 = _mm256_mul_ps(x1, _mm256_set1_ps(32767.0f)); - - // Computing the final result is a little more complicated for AVX2 than SSE2. - __m256i i0 = _mm256_cvttps_epi32(x0); - __m256i i1 = _mm256_cvttps_epi32(x1); - __m256i p0 = _mm256_permute2x128_si256(i0, i1, 0 | 32); - __m256i p1 = _mm256_permute2x128_si256(i0, i1, 1 | 48); - __m256i r = _mm256_packs_epi32(p0, p1); - - _mm256_stream_si256(((__m256i*)(dst_s16 + i)), r); - - i += 16; - } - - - // Leftover. - for (; i < count; i += 1) { - float x = src_f32[i]; - x = x + mal_dither_f32(ditherMode, ditherMin, ditherMax); - x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); // clip - x = x * 32767.0f; // -1..1 to -32767..32767 - - dst_s16[i] = (mal_int16)x; - } -} -#endif -#if defined(MAL_SUPPORT_AVX512) -void mal_pcm_f32_to_s16__avx512(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - // TODO: Convert this from AVX to AVX-512. - mal_pcm_f32_to_s16__avx2(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_NEON) -void mal_pcm_f32_to_s16__neon(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - // Both the input and output buffers need to be aligned to 16 bytes. - if ((((mal_uintptr)dst & 15) != 0) || (((mal_uintptr)src & 15) != 0)) { - mal_pcm_f32_to_s16__optimized(dst, src, count, ditherMode); - return; - } - - mal_int16* dst_s16 = (mal_int16*)dst; - const float* src_f32 = (const float*)src; - - float ditherMin = 0; - float ditherMax = 0; - if (ditherMode != mal_dither_mode_none) { - ditherMin = 1.0f / -32768; - ditherMax = 1.0f / 32767; - } - - mal_uint64 i = 0; - - // NEON. NEON allows us to output 8 s16's at a time which means our loop is unrolled 8 times. - mal_uint64 count8 = count >> 3; - for (mal_uint64 i8 = 0; i8 < count8; i8 += 1) { - float32x4_t d0; - float32x4_t d1; - if (ditherMode == mal_dither_mode_none) { - d0 = vmovq_n_f32(0); - d1 = vmovq_n_f32(0); - } else if (ditherMode == mal_dither_mode_rectangle) { - float d0v[4]; - d0v[0] = mal_dither_f32_rectangle(ditherMin, ditherMax); - d0v[1] = mal_dither_f32_rectangle(ditherMin, ditherMax); - d0v[2] = mal_dither_f32_rectangle(ditherMin, ditherMax); - d0v[3] = mal_dither_f32_rectangle(ditherMin, ditherMax); - d0 = vld1q_f32(d0v); - - float d1v[4]; - d1v[0] = mal_dither_f32_rectangle(ditherMin, ditherMax); - d1v[1] = mal_dither_f32_rectangle(ditherMin, ditherMax); - d1v[2] = mal_dither_f32_rectangle(ditherMin, ditherMax); - d1v[3] = mal_dither_f32_rectangle(ditherMin, ditherMax); - d1 = vld1q_f32(d1v); - } else { - float d0v[4]; - d0v[0] = mal_dither_f32_triangle(ditherMin, ditherMax); - d0v[1] = mal_dither_f32_triangle(ditherMin, ditherMax); - d0v[2] = mal_dither_f32_triangle(ditherMin, ditherMax); - d0v[3] = mal_dither_f32_triangle(ditherMin, ditherMax); - d0 = vld1q_f32(d0v); - - float d1v[4]; - d1v[0] = mal_dither_f32_triangle(ditherMin, ditherMax); - d1v[1] = mal_dither_f32_triangle(ditherMin, ditherMax); - d1v[2] = mal_dither_f32_triangle(ditherMin, ditherMax); - d1v[3] = mal_dither_f32_triangle(ditherMin, ditherMax); - d1 = vld1q_f32(d1v); - } - - float32x4_t x0 = *((float32x4_t*)(src_f32 + i) + 0); - float32x4_t x1 = *((float32x4_t*)(src_f32 + i) + 1); - - x0 = vaddq_f32(x0, d0); - x1 = vaddq_f32(x1, d1); - - x0 = vmulq_n_f32(x0, 32767.0f); - x1 = vmulq_n_f32(x1, 32767.0f); - - int32x4_t i0 = vcvtq_s32_f32(x0); - int32x4_t i1 = vcvtq_s32_f32(x1); - *((int16x8_t*)(dst_s16 + i)) = vcombine_s16(vqmovn_s32(i0), vqmovn_s32(i1)); - - i += 8; - } - - - // Leftover. - for (; i < count; i += 1) { - float x = src_f32[i]; - x = x + mal_dither_f32(ditherMode, ditherMin, ditherMax); - x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); // clip - x = x * 32767.0f; // -1..1 to -32767..32767 - - dst_s16[i] = (mal_int16)x; - } -} -#endif - -void mal_pcm_f32_to_s16(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ -#ifdef MAL_USE_REFERENCE_CONVERSION_APIS - mal_pcm_f32_to_s16__reference(dst, src, count, ditherMode); -#else - mal_pcm_f32_to_s16__optimized(dst, src, count, ditherMode); -#endif -} - - -void mal_pcm_f32_to_s24__reference(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - (void)ditherMode; // No dithering for f32 -> s24. - - mal_uint8* dst_s24 = (mal_uint8*)dst; - const float* src_f32 = (const float*)src; - - mal_uint64 i; - for (i = 0; i < count; i += 1) { - float x = src_f32[i]; - x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); // clip - -#if 0 - // The accurate way. - x = x + 1; // -1..1 to 0..2 - x = x * 8388607.5f; // 0..2 to 0..16777215 - x = x - 8388608.0f; // 0..16777215 to -8388608..8388607 -#else - // The fast way. - x = x * 8388607.0f; // -1..1 to -8388607..8388607 -#endif - - mal_int32 r = (mal_int32)x; - dst_s24[(i*3)+0] = (mal_uint8)((r & 0x0000FF) >> 0); - dst_s24[(i*3)+1] = (mal_uint8)((r & 0x00FF00) >> 8); - dst_s24[(i*3)+2] = (mal_uint8)((r & 0xFF0000) >> 16); - } -} - -void mal_pcm_f32_to_s24__optimized(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_f32_to_s24__reference(dst, src, count, ditherMode); -} - -#if defined(MAL_SUPPORT_SSE2) -void mal_pcm_f32_to_s24__sse2(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_f32_to_s24__optimized(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_AVX2) -void mal_pcm_f32_to_s24__avx2(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_f32_to_s24__optimized(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_AVX512) -void mal_pcm_f32_to_s24__avx512(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_f32_to_s24__avx2(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_NEON) -void mal_pcm_f32_to_s24__neon(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_f32_to_s24__optimized(dst, src, count, ditherMode); -} -#endif - -void mal_pcm_f32_to_s24(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ -#ifdef MAL_USE_REFERENCE_CONVERSION_APIS - mal_pcm_f32_to_s24__reference(dst, src, count, ditherMode); -#else - mal_pcm_f32_to_s24__optimized(dst, src, count, ditherMode); -#endif -} - - -void mal_pcm_f32_to_s32__reference(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - (void)ditherMode; // No dithering for f32 -> s32. - - mal_int32* dst_s32 = (mal_int32*)dst; - const float* src_f32 = (const float*)src; - - mal_uint32 i; - for (i = 0; i < count; i += 1) { - double x = src_f32[i]; - x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); // clip - -#if 0 - // The accurate way. - x = x + 1; // -1..1 to 0..2 - x = x * 2147483647.5; // 0..2 to 0..4294967295 - x = x - 2147483648.0; // 0...4294967295 to -2147483648..2147483647 -#else - // The fast way. - x = x * 2147483647.0; // -1..1 to -2147483647..2147483647 -#endif - - dst_s32[i] = (mal_int32)x; - } -} - -void mal_pcm_f32_to_s32__optimized(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_f32_to_s32__reference(dst, src, count, ditherMode); -} - -#if defined(MAL_SUPPORT_SSE2) -void mal_pcm_f32_to_s32__sse2(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_f32_to_s32__optimized(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_AVX2) -void mal_pcm_f32_to_s32__avx2(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_f32_to_s32__optimized(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_AVX512) -void mal_pcm_f32_to_s32__avx512(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_f32_to_s32__avx2(dst, src, count, ditherMode); -} -#endif -#if defined(MAL_SUPPORT_NEON) -void mal_pcm_f32_to_s32__neon(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - mal_pcm_f32_to_s32__optimized(dst, src, count, ditherMode); -} -#endif - -void mal_pcm_f32_to_s32(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ -#ifdef MAL_USE_REFERENCE_CONVERSION_APIS - mal_pcm_f32_to_s32__reference(dst, src, count, ditherMode); -#else - mal_pcm_f32_to_s32__optimized(dst, src, count, ditherMode); -#endif -} - - -void mal_pcm_f32_to_f32(void* dst, const void* src, mal_uint64 count, mal_dither_mode ditherMode) -{ - (void)ditherMode; - - mal_copy_memory_64(dst, src, count * sizeof(float)); -} - - -void mal_pcm_interleave_f32__reference(void* dst, const void** src, mal_uint64 frameCount, mal_uint32 channels) -{ - float* dst_f32 = (float*)dst; - const float** src_f32 = (const float**)src; - - mal_uint64 iFrame; - for (iFrame = 0; iFrame < frameCount; iFrame += 1) { - mal_uint32 iChannel; - for (iChannel = 0; iChannel < channels; iChannel += 1) { - dst_f32[iFrame*channels + iChannel] = src_f32[iChannel][iFrame]; - } - } -} - -void mal_pcm_interleave_f32__optimized(void* dst, const void** src, mal_uint64 frameCount, mal_uint32 channels) -{ - mal_pcm_interleave_f32__reference(dst, src, frameCount, channels); -} - -void mal_pcm_interleave_f32(void* dst, const void** src, mal_uint64 frameCount, mal_uint32 channels) -{ -#ifdef MAL_USE_REFERENCE_CONVERSION_APIS - mal_pcm_interleave_f32__reference(dst, src, frameCount, channels); -#else - mal_pcm_interleave_f32__optimized(dst, src, frameCount, channels); -#endif -} - - -void mal_pcm_deinterleave_f32__reference(void** dst, const void* src, mal_uint64 frameCount, mal_uint32 channels) -{ - float** dst_f32 = (float**)dst; - const float* src_f32 = (const float*)src; - - mal_uint64 iFrame; - for (iFrame = 0; iFrame < frameCount; iFrame += 1) { - mal_uint32 iChannel; - for (iChannel = 0; iChannel < channels; iChannel += 1) { - dst_f32[iChannel][iFrame] = src_f32[iFrame*channels + iChannel]; - } - } -} - -void mal_pcm_deinterleave_f32__optimized(void** dst, const void* src, mal_uint64 frameCount, mal_uint32 channels) -{ - mal_pcm_deinterleave_f32__reference(dst, src, frameCount, channels); -} - -void mal_pcm_deinterleave_f32(void** dst, const void* src, mal_uint64 frameCount, mal_uint32 channels) -{ -#ifdef MAL_USE_REFERENCE_CONVERSION_APIS - mal_pcm_deinterleave_f32__reference(dst, src, frameCount, channels); -#else - mal_pcm_deinterleave_f32__optimized(dst, src, frameCount, channels); -#endif -} - - -void mal_format_converter_init_callbacks__default(mal_format_converter* pConverter) -{ - mal_assert(pConverter != NULL); - - switch (pConverter->config.formatIn) - { - case mal_format_u8: - { - if (pConverter->config.formatOut == mal_format_u8) { - pConverter->onConvertPCM = mal_pcm_u8_to_u8; - } else if (pConverter->config.formatOut == mal_format_s16) { - pConverter->onConvertPCM = mal_pcm_u8_to_s16; - } else if (pConverter->config.formatOut == mal_format_s24) { - pConverter->onConvertPCM = mal_pcm_u8_to_s24; - } else if (pConverter->config.formatOut == mal_format_s32) { - pConverter->onConvertPCM = mal_pcm_u8_to_s32; - } else if (pConverter->config.formatOut == mal_format_f32) { - pConverter->onConvertPCM = mal_pcm_u8_to_f32; - } - } break; - - case mal_format_s16: - { - if (pConverter->config.formatOut == mal_format_u8) { - pConverter->onConvertPCM = mal_pcm_s16_to_u8; - } else if (pConverter->config.formatOut == mal_format_s16) { - pConverter->onConvertPCM = mal_pcm_s16_to_s16; - } else if (pConverter->config.formatOut == mal_format_s24) { - pConverter->onConvertPCM = mal_pcm_s16_to_s24; - } else if (pConverter->config.formatOut == mal_format_s32) { - pConverter->onConvertPCM = mal_pcm_s16_to_s32; - } else if (pConverter->config.formatOut == mal_format_f32) { - pConverter->onConvertPCM = mal_pcm_s16_to_f32; - } - } break; - - case mal_format_s24: - { - if (pConverter->config.formatOut == mal_format_u8) { - pConverter->onConvertPCM = mal_pcm_s24_to_u8; - } else if (pConverter->config.formatOut == mal_format_s16) { - pConverter->onConvertPCM = mal_pcm_s24_to_s16; - } else if (pConverter->config.formatOut == mal_format_s24) { - pConverter->onConvertPCM = mal_pcm_s24_to_s24; - } else if (pConverter->config.formatOut == mal_format_s32) { - pConverter->onConvertPCM = mal_pcm_s24_to_s32; - } else if (pConverter->config.formatOut == mal_format_f32) { - pConverter->onConvertPCM = mal_pcm_s24_to_f32; - } - } break; - - case mal_format_s32: - { - if (pConverter->config.formatOut == mal_format_u8) { - pConverter->onConvertPCM = mal_pcm_s32_to_u8; - } else if (pConverter->config.formatOut == mal_format_s16) { - pConverter->onConvertPCM = mal_pcm_s32_to_s16; - } else if (pConverter->config.formatOut == mal_format_s24) { - pConverter->onConvertPCM = mal_pcm_s32_to_s24; - } else if (pConverter->config.formatOut == mal_format_s32) { - pConverter->onConvertPCM = mal_pcm_s32_to_s32; - } else if (pConverter->config.formatOut == mal_format_f32) { - pConverter->onConvertPCM = mal_pcm_s32_to_f32; - } - } break; - - case mal_format_f32: - default: - { - if (pConverter->config.formatOut == mal_format_u8) { - pConverter->onConvertPCM = mal_pcm_f32_to_u8; - } else if (pConverter->config.formatOut == mal_format_s16) { - pConverter->onConvertPCM = mal_pcm_f32_to_s16; - } else if (pConverter->config.formatOut == mal_format_s24) { - pConverter->onConvertPCM = mal_pcm_f32_to_s24; - } else if (pConverter->config.formatOut == mal_format_s32) { - pConverter->onConvertPCM = mal_pcm_f32_to_s32; - } else if (pConverter->config.formatOut == mal_format_f32) { - pConverter->onConvertPCM = mal_pcm_f32_to_f32; - } - } break; - } -} - -#if defined(MAL_SUPPORT_SSE2) -void mal_format_converter_init_callbacks__sse2(mal_format_converter* pConverter) -{ - mal_assert(pConverter != NULL); - - switch (pConverter->config.formatIn) - { - case mal_format_u8: - { - if (pConverter->config.formatOut == mal_format_u8) { - pConverter->onConvertPCM = mal_pcm_u8_to_u8; - } else if (pConverter->config.formatOut == mal_format_s16) { - pConverter->onConvertPCM = mal_pcm_u8_to_s16__sse2; - } else if (pConverter->config.formatOut == mal_format_s24) { - pConverter->onConvertPCM = mal_pcm_u8_to_s24__sse2; - } else if (pConverter->config.formatOut == mal_format_s32) { - pConverter->onConvertPCM = mal_pcm_u8_to_s32__sse2; - } else if (pConverter->config.formatOut == mal_format_f32) { - pConverter->onConvertPCM = mal_pcm_u8_to_f32__sse2; - } - } break; - - case mal_format_s16: - { - if (pConverter->config.formatOut == mal_format_u8) { - pConverter->onConvertPCM = mal_pcm_s16_to_u8__sse2; - } else if (pConverter->config.formatOut == mal_format_s16) { - pConverter->onConvertPCM = mal_pcm_s16_to_s16; - } else if (pConverter->config.formatOut == mal_format_s24) { - pConverter->onConvertPCM = mal_pcm_s16_to_s24__sse2; - } else if (pConverter->config.formatOut == mal_format_s32) { - pConverter->onConvertPCM = mal_pcm_s16_to_s32__sse2; - } else if (pConverter->config.formatOut == mal_format_f32) { - pConverter->onConvertPCM = mal_pcm_s16_to_f32__sse2; - } - } break; - - case mal_format_s24: - { - if (pConverter->config.formatOut == mal_format_u8) { - pConverter->onConvertPCM = mal_pcm_s24_to_u8__sse2; - } else if (pConverter->config.formatOut == mal_format_s16) { - pConverter->onConvertPCM = mal_pcm_s24_to_s16__sse2; - } else if (pConverter->config.formatOut == mal_format_s24) { - pConverter->onConvertPCM = mal_pcm_s24_to_s24; - } else if (pConverter->config.formatOut == mal_format_s32) { - pConverter->onConvertPCM = mal_pcm_s24_to_s32__sse2; - } else if (pConverter->config.formatOut == mal_format_f32) { - pConverter->onConvertPCM = mal_pcm_s24_to_f32__sse2; - } - } break; - - case mal_format_s32: - { - if (pConverter->config.formatOut == mal_format_u8) { - pConverter->onConvertPCM = mal_pcm_s32_to_u8__sse2; - } else if (pConverter->config.formatOut == mal_format_s16) { - pConverter->onConvertPCM = mal_pcm_s32_to_s16__sse2; - } else if (pConverter->config.formatOut == mal_format_s24) { - pConverter->onConvertPCM = mal_pcm_s32_to_s24__sse2; - } else if (pConverter->config.formatOut == mal_format_s32) { - pConverter->onConvertPCM = mal_pcm_s32_to_s32; - } else if (pConverter->config.formatOut == mal_format_f32) { - pConverter->onConvertPCM = mal_pcm_s32_to_f32__sse2; - } - } break; - - case mal_format_f32: - default: - { - if (pConverter->config.formatOut == mal_format_u8) { - pConverter->onConvertPCM = mal_pcm_f32_to_u8__sse2; - } else if (pConverter->config.formatOut == mal_format_s16) { - pConverter->onConvertPCM = mal_pcm_f32_to_s16__sse2; - } else if (pConverter->config.formatOut == mal_format_s24) { - pConverter->onConvertPCM = mal_pcm_f32_to_s24__sse2; - } else if (pConverter->config.formatOut == mal_format_s32) { - pConverter->onConvertPCM = mal_pcm_f32_to_s32__sse2; - } else if (pConverter->config.formatOut == mal_format_f32) { - pConverter->onConvertPCM = mal_pcm_f32_to_f32; - } - } break; - } -} -#endif - -#if defined(MAL_SUPPORT_AVX2) -void mal_format_converter_init_callbacks__avx2(mal_format_converter* pConverter) -{ - mal_assert(pConverter != NULL); - - switch (pConverter->config.formatIn) - { - case mal_format_u8: - { - if (pConverter->config.formatOut == mal_format_u8) { - pConverter->onConvertPCM = mal_pcm_u8_to_u8; - } else if (pConverter->config.formatOut == mal_format_s16) { - pConverter->onConvertPCM = mal_pcm_u8_to_s16__avx2; - } else if (pConverter->config.formatOut == mal_format_s24) { - pConverter->onConvertPCM = mal_pcm_u8_to_s24__avx2; - } else if (pConverter->config.formatOut == mal_format_s32) { - pConverter->onConvertPCM = mal_pcm_u8_to_s32__avx2; - } else if (pConverter->config.formatOut == mal_format_f32) { - pConverter->onConvertPCM = mal_pcm_u8_to_f32__avx2; - } - } break; - - case mal_format_s16: - { - if (pConverter->config.formatOut == mal_format_u8) { - pConverter->onConvertPCM = mal_pcm_s16_to_u8__avx2; - } else if (pConverter->config.formatOut == mal_format_s16) { - pConverter->onConvertPCM = mal_pcm_s16_to_s16; - } else if (pConverter->config.formatOut == mal_format_s24) { - pConverter->onConvertPCM = mal_pcm_s16_to_s24__avx2; - } else if (pConverter->config.formatOut == mal_format_s32) { - pConverter->onConvertPCM = mal_pcm_s16_to_s32__avx2; - } else if (pConverter->config.formatOut == mal_format_f32) { - pConverter->onConvertPCM = mal_pcm_s16_to_f32__avx2; - } - } break; - - case mal_format_s24: - { - if (pConverter->config.formatOut == mal_format_u8) { - pConverter->onConvertPCM = mal_pcm_s24_to_u8__avx2; - } else if (pConverter->config.formatOut == mal_format_s16) { - pConverter->onConvertPCM = mal_pcm_s24_to_s16__avx2; - } else if (pConverter->config.formatOut == mal_format_s24) { - pConverter->onConvertPCM = mal_pcm_s24_to_s24; - } else if (pConverter->config.formatOut == mal_format_s32) { - pConverter->onConvertPCM = mal_pcm_s24_to_s32__avx2; - } else if (pConverter->config.formatOut == mal_format_f32) { - pConverter->onConvertPCM = mal_pcm_s24_to_f32__avx2; - } - } break; - - case mal_format_s32: - { - if (pConverter->config.formatOut == mal_format_u8) { - pConverter->onConvertPCM = mal_pcm_s32_to_u8__avx2; - } else if (pConverter->config.formatOut == mal_format_s16) { - pConverter->onConvertPCM = mal_pcm_s32_to_s16__avx2; - } else if (pConverter->config.formatOut == mal_format_s24) { - pConverter->onConvertPCM = mal_pcm_s32_to_s24__avx2; - } else if (pConverter->config.formatOut == mal_format_s32) { - pConverter->onConvertPCM = mal_pcm_s32_to_s32; - } else if (pConverter->config.formatOut == mal_format_f32) { - pConverter->onConvertPCM = mal_pcm_s32_to_f32__avx2; - } - } break; - - case mal_format_f32: - default: - { - if (pConverter->config.formatOut == mal_format_u8) { - pConverter->onConvertPCM = mal_pcm_f32_to_u8__avx2; - } else if (pConverter->config.formatOut == mal_format_s16) { - pConverter->onConvertPCM = mal_pcm_f32_to_s16__avx2; - } else if (pConverter->config.formatOut == mal_format_s24) { - pConverter->onConvertPCM = mal_pcm_f32_to_s24__avx2; - } else if (pConverter->config.formatOut == mal_format_s32) { - pConverter->onConvertPCM = mal_pcm_f32_to_s32__avx2; - } else if (pConverter->config.formatOut == mal_format_f32) { - pConverter->onConvertPCM = mal_pcm_f32_to_f32; - } - } break; - } -} -#endif - -#if defined(MAL_SUPPORT_AVX512) -void mal_format_converter_init_callbacks__avx512(mal_format_converter* pConverter) -{ - mal_assert(pConverter != NULL); - - switch (pConverter->config.formatIn) - { - case mal_format_u8: - { - if (pConverter->config.formatOut == mal_format_u8) { - pConverter->onConvertPCM = mal_pcm_u8_to_u8; - } else if (pConverter->config.formatOut == mal_format_s16) { - pConverter->onConvertPCM = mal_pcm_u8_to_s16__avx512; - } else if (pConverter->config.formatOut == mal_format_s24) { - pConverter->onConvertPCM = mal_pcm_u8_to_s24__avx512; - } else if (pConverter->config.formatOut == mal_format_s32) { - pConverter->onConvertPCM = mal_pcm_u8_to_s32__avx512; - } else if (pConverter->config.formatOut == mal_format_f32) { - pConverter->onConvertPCM = mal_pcm_u8_to_f32__avx512; - } - } break; - - case mal_format_s16: - { - if (pConverter->config.formatOut == mal_format_u8) { - pConverter->onConvertPCM = mal_pcm_s16_to_u8__avx512; - } else if (pConverter->config.formatOut == mal_format_s16) { - pConverter->onConvertPCM = mal_pcm_s16_to_s16; - } else if (pConverter->config.formatOut == mal_format_s24) { - pConverter->onConvertPCM = mal_pcm_s16_to_s24__avx512; - } else if (pConverter->config.formatOut == mal_format_s32) { - pConverter->onConvertPCM = mal_pcm_s16_to_s32__avx512; - } else if (pConverter->config.formatOut == mal_format_f32) { - pConverter->onConvertPCM = mal_pcm_s16_to_f32__avx512; - } - } break; - - case mal_format_s24: - { - if (pConverter->config.formatOut == mal_format_u8) { - pConverter->onConvertPCM = mal_pcm_s24_to_u8__avx512; - } else if (pConverter->config.formatOut == mal_format_s16) { - pConverter->onConvertPCM = mal_pcm_s24_to_s16__avx512; - } else if (pConverter->config.formatOut == mal_format_s24) { - pConverter->onConvertPCM = mal_pcm_s24_to_s24; - } else if (pConverter->config.formatOut == mal_format_s32) { - pConverter->onConvertPCM = mal_pcm_s24_to_s32__avx512; - } else if (pConverter->config.formatOut == mal_format_f32) { - pConverter->onConvertPCM = mal_pcm_s24_to_f32__avx512; - } - } break; - - case mal_format_s32: - { - if (pConverter->config.formatOut == mal_format_u8) { - pConverter->onConvertPCM = mal_pcm_s32_to_u8__avx512; - } else if (pConverter->config.formatOut == mal_format_s16) { - pConverter->onConvertPCM = mal_pcm_s32_to_s16__avx512; - } else if (pConverter->config.formatOut == mal_format_s24) { - pConverter->onConvertPCM = mal_pcm_s32_to_s24__avx512; - } else if (pConverter->config.formatOut == mal_format_s32) { - pConverter->onConvertPCM = mal_pcm_s32_to_s32; - } else if (pConverter->config.formatOut == mal_format_f32) { - pConverter->onConvertPCM = mal_pcm_s32_to_f32__avx512; - } - } break; - - case mal_format_f32: - default: - { - if (pConverter->config.formatOut == mal_format_u8) { - pConverter->onConvertPCM = mal_pcm_f32_to_u8__avx512; - } else if (pConverter->config.formatOut == mal_format_s16) { - pConverter->onConvertPCM = mal_pcm_f32_to_s16__avx512; - } else if (pConverter->config.formatOut == mal_format_s24) { - pConverter->onConvertPCM = mal_pcm_f32_to_s24__avx512; - } else if (pConverter->config.formatOut == mal_format_s32) { - pConverter->onConvertPCM = mal_pcm_f32_to_s32__avx512; - } else if (pConverter->config.formatOut == mal_format_f32) { - pConverter->onConvertPCM = mal_pcm_f32_to_f32; - } - } break; - } -} -#endif - -#if defined(MAL_SUPPORT_NEON) -void mal_format_converter_init_callbacks__neon(mal_format_converter* pConverter) -{ - mal_assert(pConverter != NULL); - - switch (pConverter->config.formatIn) - { - case mal_format_u8: - { - if (pConverter->config.formatOut == mal_format_u8) { - pConverter->onConvertPCM = mal_pcm_u8_to_u8; - } else if (pConverter->config.formatOut == mal_format_s16) { - pConverter->onConvertPCM = mal_pcm_u8_to_s16__neon; - } else if (pConverter->config.formatOut == mal_format_s24) { - pConverter->onConvertPCM = mal_pcm_u8_to_s24__neon; - } else if (pConverter->config.formatOut == mal_format_s32) { - pConverter->onConvertPCM = mal_pcm_u8_to_s32__neon; - } else if (pConverter->config.formatOut == mal_format_f32) { - pConverter->onConvertPCM = mal_pcm_u8_to_f32__neon; - } - } break; - - case mal_format_s16: - { - if (pConverter->config.formatOut == mal_format_u8) { - pConverter->onConvertPCM = mal_pcm_s16_to_u8__neon; - } else if (pConverter->config.formatOut == mal_format_s16) { - pConverter->onConvertPCM = mal_pcm_s16_to_s16; - } else if (pConverter->config.formatOut == mal_format_s24) { - pConverter->onConvertPCM = mal_pcm_s16_to_s24__neon; - } else if (pConverter->config.formatOut == mal_format_s32) { - pConverter->onConvertPCM = mal_pcm_s16_to_s32__neon; - } else if (pConverter->config.formatOut == mal_format_f32) { - pConverter->onConvertPCM = mal_pcm_s16_to_f32__neon; - } - } break; - - case mal_format_s24: - { - if (pConverter->config.formatOut == mal_format_u8) { - pConverter->onConvertPCM = mal_pcm_s24_to_u8__neon; - } else if (pConverter->config.formatOut == mal_format_s16) { - pConverter->onConvertPCM = mal_pcm_s24_to_s16__neon; - } else if (pConverter->config.formatOut == mal_format_s24) { - pConverter->onConvertPCM = mal_pcm_s24_to_s24; - } else if (pConverter->config.formatOut == mal_format_s32) { - pConverter->onConvertPCM = mal_pcm_s24_to_s32__neon; - } else if (pConverter->config.formatOut == mal_format_f32) { - pConverter->onConvertPCM = mal_pcm_s24_to_f32__neon; - } - } break; - - case mal_format_s32: - { - if (pConverter->config.formatOut == mal_format_u8) { - pConverter->onConvertPCM = mal_pcm_s32_to_u8__neon; - } else if (pConverter->config.formatOut == mal_format_s16) { - pConverter->onConvertPCM = mal_pcm_s32_to_s16__neon; - } else if (pConverter->config.formatOut == mal_format_s24) { - pConverter->onConvertPCM = mal_pcm_s32_to_s24__neon; - } else if (pConverter->config.formatOut == mal_format_s32) { - pConverter->onConvertPCM = mal_pcm_s32_to_s32; - } else if (pConverter->config.formatOut == mal_format_f32) { - pConverter->onConvertPCM = mal_pcm_s32_to_f32__neon; - } - } break; - - case mal_format_f32: - default: - { - if (pConverter->config.formatOut == mal_format_u8) { - pConverter->onConvertPCM = mal_pcm_f32_to_u8__neon; - } else if (pConverter->config.formatOut == mal_format_s16) { - pConverter->onConvertPCM = mal_pcm_f32_to_s16__neon; - } else if (pConverter->config.formatOut == mal_format_s24) { - pConverter->onConvertPCM = mal_pcm_f32_to_s24__neon; - } else if (pConverter->config.formatOut == mal_format_s32) { - pConverter->onConvertPCM = mal_pcm_f32_to_s32__neon; - } else if (pConverter->config.formatOut == mal_format_f32) { - pConverter->onConvertPCM = mal_pcm_f32_to_f32; - } - } break; - } -} -#endif - -mal_result mal_format_converter_init(const mal_format_converter_config* pConfig, mal_format_converter* pConverter) -{ - if (pConverter == NULL) { - return MAL_INVALID_ARGS; - } - mal_zero_object(pConverter); - - if (pConfig == NULL) { - return MAL_INVALID_ARGS; - } - - pConverter->config = *pConfig; - - // SIMD - pConverter->useSSE2 = mal_has_sse2() && !pConfig->noSSE2; - pConverter->useAVX2 = mal_has_avx2() && !pConfig->noAVX2; - pConverter->useAVX512 = mal_has_avx512f() && !pConfig->noAVX512; - pConverter->useNEON = mal_has_neon() && !pConfig->noNEON; - -#if defined(MAL_SUPPORT_AVX512) - if (pConverter->useAVX512) { - mal_format_converter_init_callbacks__avx512(pConverter); - } else -#endif -#if defined(MAL_SUPPORT_AVX2) - if (pConverter->useAVX2) { - mal_format_converter_init_callbacks__avx2(pConverter); - } else -#endif -#if defined(MAL_SUPPORT_SSE2) - if (pConverter->useSSE2) { - mal_format_converter_init_callbacks__sse2(pConverter); - } else -#endif -#if defined(MAL_SUPPORT_NEON) - if (pConverter->useNEON) { - mal_format_converter_init_callbacks__neon(pConverter); - } else -#endif - { - mal_format_converter_init_callbacks__default(pConverter); - } - - switch (pConfig->formatOut) - { - case mal_format_u8: - { - pConverter->onInterleavePCM = mal_pcm_interleave_u8; - pConverter->onDeinterleavePCM = mal_pcm_deinterleave_u8; - } break; - case mal_format_s16: - { - pConverter->onInterleavePCM = mal_pcm_interleave_s16; - pConverter->onDeinterleavePCM = mal_pcm_deinterleave_s16; - } break; - case mal_format_s24: - { - pConverter->onInterleavePCM = mal_pcm_interleave_s24; - pConverter->onDeinterleavePCM = mal_pcm_deinterleave_s24; - } break; - case mal_format_s32: - { - pConverter->onInterleavePCM = mal_pcm_interleave_s32; - pConverter->onDeinterleavePCM = mal_pcm_deinterleave_s32; - } break; - case mal_format_f32: - default: - { - pConverter->onInterleavePCM = mal_pcm_interleave_f32; - pConverter->onDeinterleavePCM = mal_pcm_deinterleave_f32; - } break; - } - - return MAL_SUCCESS; -} - -mal_uint64 mal_format_converter_read(mal_format_converter* pConverter, mal_uint64 frameCount, void* pFramesOut, void* pUserData) -{ - if (pConverter == NULL || pFramesOut == NULL) { - return 0; - } - - mal_uint64 totalFramesRead = 0; - mal_uint32 sampleSizeIn = mal_get_bytes_per_sample(pConverter->config.formatIn); - mal_uint32 sampleSizeOut = mal_get_bytes_per_sample(pConverter->config.formatOut); - //mal_uint32 frameSizeIn = sampleSizeIn * pConverter->config.channels; - mal_uint32 frameSizeOut = sampleSizeOut * pConverter->config.channels; - mal_uint8* pNextFramesOut = (mal_uint8*)pFramesOut; - - if (pConverter->config.onRead != NULL) { - // Input data is interleaved. - if (pConverter->config.formatIn == pConverter->config.formatOut) { - // Pass through. - while (totalFramesRead < frameCount) { - mal_uint64 framesRemaining = (frameCount - totalFramesRead); - mal_uint64 framesToReadRightNow = framesRemaining; - if (framesToReadRightNow > 0xFFFFFFFF) { - framesToReadRightNow = 0xFFFFFFFF; - } - - mal_uint32 framesJustRead = (mal_uint32)pConverter->config.onRead(pConverter, (mal_uint32)framesToReadRightNow, pNextFramesOut, pUserData); - if (framesJustRead == 0) { - break; - } - - totalFramesRead += framesJustRead; - pNextFramesOut += framesJustRead * frameSizeOut; - - if (framesJustRead < framesToReadRightNow) { - break; - } - } - } else { - // Conversion required. - MAL_ALIGN(MAL_SIMD_ALIGNMENT) mal_uint8 temp[MAL_MAX_CHANNELS * MAL_MAX_PCM_SAMPLE_SIZE_IN_BYTES * 128]; - mal_assert(sizeof(temp) <= 0xFFFFFFFF); - - mal_uint32 maxFramesToReadAtATime = sizeof(temp) / sampleSizeIn / pConverter->config.channels; - - while (totalFramesRead < frameCount) { - mal_uint64 framesRemaining = (frameCount - totalFramesRead); - mal_uint64 framesToReadRightNow = framesRemaining; - if (framesToReadRightNow > maxFramesToReadAtATime) { - framesToReadRightNow = maxFramesToReadAtATime; - } - - mal_uint32 framesJustRead = (mal_uint32)pConverter->config.onRead(pConverter, (mal_uint32)framesToReadRightNow, temp, pUserData); - if (framesJustRead == 0) { - break; - } - - pConverter->onConvertPCM(pNextFramesOut, temp, framesJustRead*pConverter->config.channels, pConverter->config.ditherMode); - - totalFramesRead += framesJustRead; - pNextFramesOut += framesJustRead * frameSizeOut; - - if (framesJustRead < framesToReadRightNow) { - break; - } - } - } - } else { - // Input data is deinterleaved. If a conversion is required we need to do an intermediary step. - MAL_ALIGN(MAL_SIMD_ALIGNMENT) mal_uint8 tempSamplesOfOutFormat[MAL_MAX_CHANNELS * MAL_MAX_PCM_SAMPLE_SIZE_IN_BYTES * 128]; - mal_assert(sizeof(tempSamplesOfOutFormat) <= 0xFFFFFFFFF); - - void* ppTempSamplesOfOutFormat[MAL_MAX_CHANNELS]; - size_t splitBufferSizeOut; - mal_split_buffer(tempSamplesOfOutFormat, sizeof(tempSamplesOfOutFormat), pConverter->config.channels, MAL_SIMD_ALIGNMENT, (void**)&ppTempSamplesOfOutFormat, &splitBufferSizeOut); - - mal_uint32 maxFramesToReadAtATime = (mal_uint32)(splitBufferSizeOut / sampleSizeIn); - - while (totalFramesRead < frameCount) { - mal_uint64 framesRemaining = (frameCount - totalFramesRead); - mal_uint64 framesToReadRightNow = framesRemaining; - if (framesToReadRightNow > maxFramesToReadAtATime) { - framesToReadRightNow = maxFramesToReadAtATime; - } - - mal_uint32 framesJustRead = 0; - - if (pConverter->config.formatIn == pConverter->config.formatOut) { - // Only interleaving. - framesJustRead = (mal_uint32)pConverter->config.onReadDeinterleaved(pConverter, (mal_uint32)framesToReadRightNow, ppTempSamplesOfOutFormat, pUserData); - if (framesJustRead == 0) { - break; - } - } else { - // Interleaving + Conversion. Convert first, then interleave. - MAL_ALIGN(MAL_SIMD_ALIGNMENT) mal_uint8 tempSamplesOfInFormat[MAL_MAX_CHANNELS * MAL_MAX_PCM_SAMPLE_SIZE_IN_BYTES * 128]; - - void* ppTempSamplesOfInFormat[MAL_MAX_CHANNELS]; - size_t splitBufferSizeIn; - mal_split_buffer(tempSamplesOfInFormat, sizeof(tempSamplesOfInFormat), pConverter->config.channels, MAL_SIMD_ALIGNMENT, (void**)&ppTempSamplesOfInFormat, &splitBufferSizeIn); - - if (framesToReadRightNow > (splitBufferSizeIn / sampleSizeIn)) { - framesToReadRightNow = (splitBufferSizeIn / sampleSizeIn); - } - - framesJustRead = (mal_uint32)pConverter->config.onReadDeinterleaved(pConverter, (mal_uint32)framesToReadRightNow, ppTempSamplesOfInFormat, pUserData); - if (framesJustRead == 0) { - break; - } - - for (mal_uint32 iChannel = 0; iChannel < pConverter->config.channels; iChannel += 1) { - pConverter->onConvertPCM(ppTempSamplesOfOutFormat[iChannel], ppTempSamplesOfInFormat[iChannel], framesJustRead, pConverter->config.ditherMode); - } - } - - pConverter->onInterleavePCM(pNextFramesOut, (const void**)ppTempSamplesOfOutFormat, framesJustRead, pConverter->config.channels); - - totalFramesRead += framesJustRead; - pNextFramesOut += framesJustRead * frameSizeOut; - - if (framesJustRead < framesToReadRightNow) { - break; - } - } - } - - return totalFramesRead; -} - -mal_uint64 mal_format_converter_read_deinterleaved(mal_format_converter* pConverter, mal_uint64 frameCount, void** ppSamplesOut, void* pUserData) -{ - if (pConverter == NULL || ppSamplesOut == NULL) { - return 0; - } - - mal_uint64 totalFramesRead = 0; - mal_uint32 sampleSizeIn = mal_get_bytes_per_sample(pConverter->config.formatIn); - mal_uint32 sampleSizeOut = mal_get_bytes_per_sample(pConverter->config.formatOut); - - mal_uint8* ppNextSamplesOut[MAL_MAX_CHANNELS]; - mal_copy_memory(ppNextSamplesOut, ppSamplesOut, sizeof(void*) * pConverter->config.channels); - - if (pConverter->config.onRead != NULL) { - // Input data is interleaved. - MAL_ALIGN(MAL_SIMD_ALIGNMENT) mal_uint8 tempSamplesOfOutFormat[MAL_MAX_CHANNELS * MAL_MAX_PCM_SAMPLE_SIZE_IN_BYTES * 128]; - mal_assert(sizeof(tempSamplesOfOutFormat) <= 0xFFFFFFFF); - - mal_uint32 maxFramesToReadAtATime = sizeof(tempSamplesOfOutFormat) / sampleSizeIn / pConverter->config.channels; - - while (totalFramesRead < frameCount) { - mal_uint64 framesRemaining = (frameCount - totalFramesRead); - mal_uint64 framesToReadRightNow = framesRemaining; - if (framesToReadRightNow > maxFramesToReadAtATime) { - framesToReadRightNow = maxFramesToReadAtATime; - } - - mal_uint32 framesJustRead = 0; - - if (pConverter->config.formatIn == pConverter->config.formatOut) { - // Only de-interleaving. - framesJustRead = (mal_uint32)pConverter->config.onRead(pConverter, (mal_uint32)framesToReadRightNow, tempSamplesOfOutFormat, pUserData); - if (framesJustRead == 0) { - break; - } - } else { - // De-interleaving + Conversion. Convert first, then de-interleave. - MAL_ALIGN(MAL_SIMD_ALIGNMENT) mal_uint8 tempSamplesOfInFormat[sizeof(tempSamplesOfOutFormat)]; - - framesJustRead = (mal_uint32)pConverter->config.onRead(pConverter, (mal_uint32)framesToReadRightNow, tempSamplesOfInFormat, pUserData); - if (framesJustRead == 0) { - break; - } - - pConverter->onConvertPCM(tempSamplesOfOutFormat, tempSamplesOfInFormat, framesJustRead * pConverter->config.channels, pConverter->config.ditherMode); - } - - pConverter->onDeinterleavePCM((void**)ppNextSamplesOut, tempSamplesOfOutFormat, framesJustRead, pConverter->config.channels); - - totalFramesRead += framesJustRead; - for (mal_uint32 iChannel = 0; iChannel < pConverter->config.channels; ++iChannel) { - ppNextSamplesOut[iChannel] += framesJustRead * sampleSizeOut; - } - - if (framesJustRead < framesToReadRightNow) { - break; - } - } - } else { - // Input data is deinterleaved. - if (pConverter->config.formatIn == pConverter->config.formatOut) { - // Pass through. - while (totalFramesRead < frameCount) { - mal_uint64 framesRemaining = (frameCount - totalFramesRead); - mal_uint64 framesToReadRightNow = framesRemaining; - if (framesToReadRightNow > 0xFFFFFFFF) { - framesToReadRightNow = 0xFFFFFFFF; - } - - mal_uint32 framesJustRead = (mal_uint32)pConverter->config.onReadDeinterleaved(pConverter, (mal_uint32)framesToReadRightNow, (void**)ppNextSamplesOut, pUserData); - if (framesJustRead == 0) { - break; - } - - totalFramesRead += framesJustRead; - for (mal_uint32 iChannel = 0; iChannel < pConverter->config.channels; ++iChannel) { - ppNextSamplesOut[iChannel] += framesJustRead * sampleSizeOut; - } - - if (framesJustRead < framesToReadRightNow) { - break; - } - } - } else { - // Conversion required. - MAL_ALIGN(MAL_SIMD_ALIGNMENT) mal_uint8 temp[MAL_MAX_CHANNELS][MAL_MAX_PCM_SAMPLE_SIZE_IN_BYTES * 128]; - mal_assert(sizeof(temp) <= 0xFFFFFFFF); - - void* ppTemp[MAL_MAX_CHANNELS]; - size_t splitBufferSize; - mal_split_buffer(temp, sizeof(temp), pConverter->config.channels, MAL_SIMD_ALIGNMENT, (void**)&ppTemp, &splitBufferSize); - - mal_uint32 maxFramesToReadAtATime = (mal_uint32)(splitBufferSize / sampleSizeIn); - - while (totalFramesRead < frameCount) { - mal_uint64 framesRemaining = (frameCount - totalFramesRead); - mal_uint64 framesToReadRightNow = framesRemaining; - if (framesToReadRightNow > maxFramesToReadAtATime) { - framesToReadRightNow = maxFramesToReadAtATime; - } - - mal_uint32 framesJustRead = (mal_uint32)pConverter->config.onReadDeinterleaved(pConverter, (mal_uint32)framesToReadRightNow, ppTemp, pUserData); - if (framesJustRead == 0) { - break; - } - - for (mal_uint32 iChannel = 0; iChannel < pConverter->config.channels; iChannel += 1) { - pConverter->onConvertPCM(ppNextSamplesOut[iChannel], ppTemp[iChannel], framesJustRead, pConverter->config.ditherMode); - ppNextSamplesOut[iChannel] += framesJustRead * sampleSizeOut; - } - - totalFramesRead += framesJustRead; - - if (framesJustRead < framesToReadRightNow) { - break; - } - } - } - } - - return totalFramesRead; -} - - -mal_format_converter_config mal_format_converter_config_init_new() -{ - mal_format_converter_config config; - mal_zero_object(&config); - - return config; -} - -mal_format_converter_config mal_format_converter_config_init(mal_format formatIn, mal_format formatOut, mal_uint32 channels, mal_format_converter_read_proc onRead, void* pUserData) -{ - mal_format_converter_config config = mal_format_converter_config_init_new(); - config.formatIn = formatIn; - config.formatOut = formatOut; - config.channels = channels; - config.onRead = onRead; - config.onReadDeinterleaved = NULL; - config.pUserData = pUserData; - - return config; -} - -mal_format_converter_config mal_format_converter_config_init_deinterleaved(mal_format formatIn, mal_format formatOut, mal_uint32 channels, mal_format_converter_read_deinterleaved_proc onReadDeinterleaved, void* pUserData) -{ - mal_format_converter_config config = mal_format_converter_config_init(formatIn, formatOut, channels, NULL, pUserData); - config.onReadDeinterleaved = onReadDeinterleaved; - - return config; -} - - - -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Channel Routing -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -// -X = Left, +X = Right -// -Y = Bottom, +Y = Top -// -Z = Front, +Z = Back -typedef struct -{ - float x; - float y; - float z; -} mal_vec3; - -static MAL_INLINE mal_vec3 mal_vec3f(float x, float y, float z) -{ - mal_vec3 r; - r.x = x; - r.y = y; - r.z = z; - - return r; -} - -static MAL_INLINE mal_vec3 mal_vec3_add(mal_vec3 a, mal_vec3 b) -{ - return mal_vec3f( - a.x + b.x, - a.y + b.y, - a.z + b.z - ); -} - -static MAL_INLINE mal_vec3 mal_vec3_sub(mal_vec3 a, mal_vec3 b) -{ - return mal_vec3f( - a.x - b.x, - a.y - b.y, - a.z - b.z - ); -} - -static MAL_INLINE mal_vec3 mal_vec3_mul(mal_vec3 a, mal_vec3 b) -{ - return mal_vec3f( - a.x * b.x, - a.y * b.y, - a.z * b.z - ); -} - -static MAL_INLINE mal_vec3 mal_vec3_div(mal_vec3 a, mal_vec3 b) -{ - return mal_vec3f( - a.x / b.x, - a.y / b.y, - a.z / b.z - ); -} - -static MAL_INLINE float mal_vec3_dot(mal_vec3 a, mal_vec3 b) -{ - return a.x*b.x + a.y*b.y + a.z*b.z; -} - -static MAL_INLINE float mal_vec3_length2(mal_vec3 a) -{ - return mal_vec3_dot(a, a); -} - -static MAL_INLINE float mal_vec3_length(mal_vec3 a) -{ - return (float)sqrt(mal_vec3_length2(a)); -} - -static MAL_INLINE mal_vec3 mal_vec3_normalize(mal_vec3 a) -{ - float len = 1 / mal_vec3_length(a); - - mal_vec3 r; - r.x = a.x * len; - r.y = a.y * len; - r.z = a.z * len; - - return r; -} - -static MAL_INLINE float mal_vec3_distance(mal_vec3 a, mal_vec3 b) -{ - return mal_vec3_length(mal_vec3_sub(a, b)); -} - - -#define MAL_PLANE_LEFT 0 -#define MAL_PLANE_RIGHT 1 -#define MAL_PLANE_FRONT 2 -#define MAL_PLANE_BACK 3 -#define MAL_PLANE_BOTTOM 4 -#define MAL_PLANE_TOP 5 - -float g_malChannelPlaneRatios[MAL_CHANNEL_POSITION_COUNT][6] = { - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_NONE - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_MONO - { 0.5f, 0.0f, 0.5f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_FRONT_LEFT - { 0.0f, 0.5f, 0.5f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_FRONT_RIGHT - { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_FRONT_CENTER - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_LFE - { 0.5f, 0.0f, 0.0f, 0.5f, 0.0f, 0.0f}, // MAL_CHANNEL_BACK_LEFT - { 0.0f, 0.5f, 0.0f, 0.5f, 0.0f, 0.0f}, // MAL_CHANNEL_BACK_RIGHT - { 0.25f, 0.0f, 0.75f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_FRONT_LEFT_CENTER - { 0.0f, 0.25f, 0.75f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_FRONT_RIGHT_CENTER - { 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f}, // MAL_CHANNEL_BACK_CENTER - { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_SIDE_LEFT - { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_SIDE_RIGHT - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f}, // MAL_CHANNEL_TOP_CENTER - { 0.33f, 0.0f, 0.33f, 0.0f, 0.0f, 0.34f}, // MAL_CHANNEL_TOP_FRONT_LEFT - { 0.0f, 0.0f, 0.5f, 0.0f, 0.0f, 0.5f}, // MAL_CHANNEL_TOP_FRONT_CENTER - { 0.0f, 0.33f, 0.33f, 0.0f, 0.0f, 0.34f}, // MAL_CHANNEL_TOP_FRONT_RIGHT - { 0.33f, 0.0f, 0.0f, 0.33f, 0.0f, 0.34f}, // MAL_CHANNEL_TOP_BACK_LEFT - { 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, 0.5f}, // MAL_CHANNEL_TOP_BACK_CENTER - { 0.0f, 0.33f, 0.0f, 0.33f, 0.0f, 0.34f}, // MAL_CHANNEL_TOP_BACK_RIGHT - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_AUX_0 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_AUX_1 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_AUX_2 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_AUX_3 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_AUX_4 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_AUX_5 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_AUX_6 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_AUX_7 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_AUX_8 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_AUX_9 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_AUX_10 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_AUX_11 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_AUX_12 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_AUX_13 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_AUX_14 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_AUX_15 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_AUX_16 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_AUX_17 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_AUX_18 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_AUX_19 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_AUX_20 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_AUX_21 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_AUX_22 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_AUX_23 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_AUX_24 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_AUX_25 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_AUX_26 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_AUX_27 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_AUX_28 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_AUX_29 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_AUX_30 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MAL_CHANNEL_AUX_31 -}; - -float mal_calculate_channel_position_planar_weight(mal_channel channelPositionA, mal_channel channelPositionB) -{ - // Imagine the following simplified example: You have a single input speaker which is the front/left speaker which you want to convert to - // the following output configuration: - // - // - front/left - // - side/left - // - back/left - // - // The front/left output is easy - it the same speaker position so it receives the full contribution of the front/left input. The amount - // of contribution to apply to the side/left and back/left speakers, however, is a bit more complicated. - // - // Imagine the front/left speaker as emitting audio from two planes - the front plane and the left plane. You can think of the front/left - // speaker emitting half of it's total volume from the front, and the other half from the left. Since part of it's volume is being emitted - // from the left side, and the side/left and back/left channels also emit audio from the left plane, one would expect that they would - // receive some amount of contribution from front/left speaker. The amount of contribution depends on how many planes are shared between - // the two speakers. Note that in the examples below I've added a top/front/left speaker as an example just to show how the math works - // across 3 spatial dimensions. - // - // The first thing to do is figure out how each speaker's volume is spread over each of plane: - // - front/left: 2 planes (front and left) = 1/2 = half it's total volume on each plane - // - side/left: 1 plane (left only) = 1/1 = entire volume from left plane - // - back/left: 2 planes (back and left) = 1/2 = half it's total volume on each plane - // - top/front/left: 3 planes (top, front and left) = 1/3 = one third it's total volume on each plane - // - // The amount of volume each channel contributes to each of it's planes is what controls how much it is willing to given and take to other - // channels on the same plane. The volume that is willing to the given by one channel is multiplied by the volume that is willing to be - // taken by the other to produce the final contribution. - - // Contribution = Sum(Volume to Give * Volume to Take) - float contribution = - g_malChannelPlaneRatios[channelPositionA][0] * g_malChannelPlaneRatios[channelPositionB][0] + - g_malChannelPlaneRatios[channelPositionA][1] * g_malChannelPlaneRatios[channelPositionB][1] + - g_malChannelPlaneRatios[channelPositionA][2] * g_malChannelPlaneRatios[channelPositionB][2] + - g_malChannelPlaneRatios[channelPositionA][3] * g_malChannelPlaneRatios[channelPositionB][3] + - g_malChannelPlaneRatios[channelPositionA][4] * g_malChannelPlaneRatios[channelPositionB][4] + - g_malChannelPlaneRatios[channelPositionA][5] * g_malChannelPlaneRatios[channelPositionB][5]; - - return contribution; -} - -float mal_channel_router__calculate_input_channel_planar_weight(const mal_channel_router* pRouter, mal_channel channelPositionIn, mal_channel channelPositionOut) -{ - mal_assert(pRouter != NULL); - (void)pRouter; - - return mal_calculate_channel_position_planar_weight(channelPositionIn, channelPositionOut); -} - -mal_bool32 mal_channel_router__is_spatial_channel_position(const mal_channel_router* pRouter, mal_channel channelPosition) -{ - mal_assert(pRouter != NULL); - (void)pRouter; - - if (channelPosition == MAL_CHANNEL_NONE || channelPosition == MAL_CHANNEL_MONO || channelPosition == MAL_CHANNEL_LFE) { - return MAL_FALSE; - } - - for (int i = 0; i < 6; ++i) { - if (g_malChannelPlaneRatios[channelPosition][i] != 0) { - return MAL_TRUE; - } - } - - return MAL_FALSE; -} - -mal_result mal_channel_router_init(const mal_channel_router_config* pConfig, mal_channel_router* pRouter) -{ - if (pRouter == NULL) { - return MAL_INVALID_ARGS; - } - - mal_zero_object(pRouter); - - if (pConfig == NULL) { - return MAL_INVALID_ARGS; - } - if (pConfig->onReadDeinterleaved == NULL) { - return MAL_INVALID_ARGS; - } - - if (!mal_channel_map_valid(pConfig->channelsIn, pConfig->channelMapIn)) { - return MAL_INVALID_ARGS; // Invalid input channel map. - } - if (!mal_channel_map_valid(pConfig->channelsOut, pConfig->channelMapOut)) { - return MAL_INVALID_ARGS; // Invalid output channel map. - } - - pRouter->config = *pConfig; - - // SIMD - pRouter->useSSE2 = mal_has_sse2() && !pConfig->noSSE2; - pRouter->useAVX2 = mal_has_avx2() && !pConfig->noAVX2; - pRouter->useAVX512 = mal_has_avx512f() && !pConfig->noAVX512; - pRouter->useNEON = mal_has_neon() && !pConfig->noNEON; - - // If the input and output channels and channel maps are the same we should use a passthrough. - if (pRouter->config.channelsIn == pRouter->config.channelsOut) { - if (mal_channel_map_equal(pRouter->config.channelsIn, pRouter->config.channelMapIn, pRouter->config.channelMapOut)) { - pRouter->isPassthrough = MAL_TRUE; - } - if (mal_channel_map_blank(pRouter->config.channelsIn, pRouter->config.channelMapIn) || mal_channel_map_blank(pRouter->config.channelsOut, pRouter->config.channelMapOut)) { - pRouter->isPassthrough = MAL_TRUE; - } - } - - // Here is where we do a bit of pre-processing to know how each channel should be combined to make up the output. Rules: - // - // 1) If it's a passthrough, do nothing - it's just a simple memcpy(). - // 2) If the channel counts are the same and every channel position in the input map is present in the output map, use a - // simple shuffle. An example might be different 5.1 channel layouts. - // 3) Otherwise channels are blended based on spatial locality. - if (!pRouter->isPassthrough) { - if (pRouter->config.channelsIn == pRouter->config.channelsOut) { - mal_bool32 areAllChannelPositionsPresent = MAL_TRUE; - for (mal_uint32 iChannelIn = 0; iChannelIn < pRouter->config.channelsIn; ++iChannelIn) { - mal_bool32 isInputChannelPositionInOutput = MAL_FALSE; - for (mal_uint32 iChannelOut = 0; iChannelOut < pRouter->config.channelsOut; ++iChannelOut) { - if (pRouter->config.channelMapIn[iChannelIn] == pRouter->config.channelMapOut[iChannelOut]) { - isInputChannelPositionInOutput = MAL_TRUE; - break; - } - } - - if (!isInputChannelPositionInOutput) { - areAllChannelPositionsPresent = MAL_FALSE; - break; - } - } - - if (areAllChannelPositionsPresent) { - pRouter->isSimpleShuffle = MAL_TRUE; - - // All the router will be doing is rearranging channels which means all we need to do is use a shuffling table which is just - // a mapping between the index of the input channel to the index of the output channel. - for (mal_uint32 iChannelIn = 0; iChannelIn < pRouter->config.channelsIn; ++iChannelIn) { - for (mal_uint32 iChannelOut = 0; iChannelOut < pRouter->config.channelsOut; ++iChannelOut) { - if (pRouter->config.channelMapIn[iChannelIn] == pRouter->config.channelMapOut[iChannelOut]) { - pRouter->shuffleTable[iChannelIn] = (mal_uint8)iChannelOut; - break; - } - } - } - } - } - } - - - // Here is where weights are calculated. Note that we calculate the weights at all times, even when using a passthrough and simple - // shuffling. We use different algorithms for calculating weights depending on our mixing mode. - // - // In simple mode we don't do any blending (except for converting between mono, which is done in a later step). Instead we just - // map 1:1 matching channels. In this mode, if no channels in the input channel map correspond to anything in the output channel - // map, nothing will be heard! - - // In all cases we need to make sure all channels that are present in both channel maps have a 1:1 mapping. - for (mal_uint32 iChannelIn = 0; iChannelIn < pRouter->config.channelsIn; ++iChannelIn) { - mal_channel channelPosIn = pRouter->config.channelMapIn[iChannelIn]; - - for (mal_uint32 iChannelOut = 0; iChannelOut < pRouter->config.channelsOut; ++iChannelOut) { - mal_channel channelPosOut = pRouter->config.channelMapOut[iChannelOut]; - - if (channelPosIn == channelPosOut) { - pRouter->config.weights[iChannelIn][iChannelOut] = 1; - } - } - } - - // The mono channel is accumulated on all other channels, except LFE. Make sure in this loop we exclude output mono channels since - // they were handled in the pass above. - for (mal_uint32 iChannelIn = 0; iChannelIn < pRouter->config.channelsIn; ++iChannelIn) { - mal_channel channelPosIn = pRouter->config.channelMapIn[iChannelIn]; - - if (channelPosIn == MAL_CHANNEL_MONO) { - for (mal_uint32 iChannelOut = 0; iChannelOut < pRouter->config.channelsOut; ++iChannelOut) { - mal_channel channelPosOut = pRouter->config.channelMapOut[iChannelOut]; - - if (channelPosOut != MAL_CHANNEL_NONE && channelPosOut != MAL_CHANNEL_MONO && channelPosOut != MAL_CHANNEL_LFE) { - pRouter->config.weights[iChannelIn][iChannelOut] = 1; - } - } - } - } - - // The output mono channel is the average of all non-none, non-mono and non-lfe input channels. - { - mal_uint32 len = 0; - for (mal_uint32 iChannelIn = 0; iChannelIn < pRouter->config.channelsIn; ++iChannelIn) { - mal_channel channelPosIn = pRouter->config.channelMapIn[iChannelIn]; - - if (channelPosIn != MAL_CHANNEL_NONE && channelPosIn != MAL_CHANNEL_MONO && channelPosIn != MAL_CHANNEL_LFE) { - len += 1; - } - } - - if (len > 0) { - float monoWeight = 1.0f / len; - - for (mal_uint32 iChannelOut = 0; iChannelOut < pRouter->config.channelsOut; ++iChannelOut) { - mal_channel channelPosOut = pRouter->config.channelMapOut[iChannelOut]; - - if (channelPosOut == MAL_CHANNEL_MONO) { - for (mal_uint32 iChannelIn = 0; iChannelIn < pRouter->config.channelsIn; ++iChannelIn) { - mal_channel channelPosIn = pRouter->config.channelMapIn[iChannelIn]; - - if (channelPosIn != MAL_CHANNEL_NONE && channelPosIn != MAL_CHANNEL_MONO && channelPosIn != MAL_CHANNEL_LFE) { - pRouter->config.weights[iChannelIn][iChannelOut] += monoWeight; - } - } - } - } - } - } - - - // Input and output channels that are not present on the other side need to be blended in based on spatial locality. - switch (pRouter->config.mixingMode) - { - case mal_channel_mix_mode_rectangular: - { - // Unmapped input channels. - for (mal_uint32 iChannelIn = 0; iChannelIn < pRouter->config.channelsIn; ++iChannelIn) { - mal_channel channelPosIn = pRouter->config.channelMapIn[iChannelIn]; - - if (mal_channel_router__is_spatial_channel_position(pRouter, channelPosIn)) { - if (!mal_channel_map_contains_channel_position(pRouter->config.channelsOut, pRouter->config.channelMapOut, channelPosIn)) { - for (mal_uint32 iChannelOut = 0; iChannelOut < pRouter->config.channelsOut; ++iChannelOut) { - mal_channel channelPosOut = pRouter->config.channelMapOut[iChannelOut]; - - if (mal_channel_router__is_spatial_channel_position(pRouter, channelPosOut)) { - float weight = 0; - if (pRouter->config.mixingMode == mal_channel_mix_mode_planar_blend) { - weight = mal_channel_router__calculate_input_channel_planar_weight(pRouter, channelPosIn, channelPosOut); - } - - // Only apply the weight if we haven't already got some contribution from the respective channels. - if (pRouter->config.weights[iChannelIn][iChannelOut] == 0) { - pRouter->config.weights[iChannelIn][iChannelOut] = weight; - } - } - } - } - } - } - - // Unmapped output channels. - for (mal_uint32 iChannelOut = 0; iChannelOut < pRouter->config.channelsOut; ++iChannelOut) { - mal_channel channelPosOut = pRouter->config.channelMapOut[iChannelOut]; - - if (mal_channel_router__is_spatial_channel_position(pRouter, channelPosOut)) { - if (!mal_channel_map_contains_channel_position(pRouter->config.channelsIn, pRouter->config.channelMapIn, channelPosOut)) { - for (mal_uint32 iChannelIn = 0; iChannelIn < pRouter->config.channelsIn; ++iChannelIn) { - mal_channel channelPosIn = pRouter->config.channelMapIn[iChannelIn]; - - if (mal_channel_router__is_spatial_channel_position(pRouter, channelPosIn)) { - float weight = 0; - if (pRouter->config.mixingMode == mal_channel_mix_mode_planar_blend) { - weight = mal_channel_router__calculate_input_channel_planar_weight(pRouter, channelPosIn, channelPosOut); - } - - // Only apply the weight if we haven't already got some contribution from the respective channels. - if (pRouter->config.weights[iChannelIn][iChannelOut] == 0) { - pRouter->config.weights[iChannelIn][iChannelOut] = weight; - } - } - } - } - } - } - } break; - - case mal_channel_mix_mode_custom_weights: - case mal_channel_mix_mode_simple: - default: - { - /* Fallthrough. */ - } break; - } - - return MAL_SUCCESS; -} - -static MAL_INLINE mal_bool32 mal_channel_router__can_use_sse2(mal_channel_router* pRouter, const float* pSamplesOut, const float* pSamplesIn) -{ - return pRouter->useSSE2 && (((mal_uintptr)pSamplesOut & 15) == 0) && (((mal_uintptr)pSamplesIn & 15) == 0); -} - -static MAL_INLINE mal_bool32 mal_channel_router__can_use_avx2(mal_channel_router* pRouter, const float* pSamplesOut, const float* pSamplesIn) -{ - return pRouter->useAVX2 && (((mal_uintptr)pSamplesOut & 31) == 0) && (((mal_uintptr)pSamplesIn & 31) == 0); -} - -static MAL_INLINE mal_bool32 mal_channel_router__can_use_avx512(mal_channel_router* pRouter, const float* pSamplesOut, const float* pSamplesIn) -{ - return pRouter->useAVX512 && (((mal_uintptr)pSamplesOut & 63) == 0) && (((mal_uintptr)pSamplesIn & 63) == 0); -} - -static MAL_INLINE mal_bool32 mal_channel_router__can_use_neon(mal_channel_router* pRouter, const float* pSamplesOut, const float* pSamplesIn) -{ - return pRouter->useNEON && (((mal_uintptr)pSamplesOut & 15) == 0) && (((mal_uintptr)pSamplesIn & 15) == 0); -} - -void mal_channel_router__do_routing(mal_channel_router* pRouter, mal_uint64 frameCount, float** ppSamplesOut, const float** ppSamplesIn) -{ - mal_assert(pRouter != NULL); - mal_assert(pRouter->isPassthrough == MAL_FALSE); - - if (pRouter->isSimpleShuffle) { - // A shuffle is just a re-arrangement of channels and does not require any arithmetic. - mal_assert(pRouter->config.channelsIn == pRouter->config.channelsOut); - for (mal_uint32 iChannelIn = 0; iChannelIn < pRouter->config.channelsIn; ++iChannelIn) { - mal_uint32 iChannelOut = pRouter->shuffleTable[iChannelIn]; - mal_copy_memory_64(ppSamplesOut[iChannelOut], ppSamplesIn[iChannelIn], frameCount * sizeof(float)); - } - } else { - // This is the more complicated case. Each of the output channels is accumulated with 0 or more input channels. - - // Clear. - for (mal_uint32 iChannelOut = 0; iChannelOut < pRouter->config.channelsOut; ++iChannelOut) { - mal_zero_memory_64(ppSamplesOut[iChannelOut], frameCount * sizeof(float)); - } - - // Accumulate. - for (mal_uint32 iChannelIn = 0; iChannelIn < pRouter->config.channelsIn; ++iChannelIn) { - for (mal_uint32 iChannelOut = 0; iChannelOut < pRouter->config.channelsOut; ++iChannelOut) { - mal_uint64 iFrame = 0; -#if defined(MAL_SUPPORT_NEON) - if (mal_channel_router__can_use_neon(pRouter, ppSamplesOut[iChannelOut], ppSamplesIn[iChannelIn])) { - float32x4_t weight = vmovq_n_f32(pRouter->config.weights[iChannelIn][iChannelOut]); - - mal_uint64 frameCount4 = frameCount/4; - for (mal_uint64 iFrame4 = 0; iFrame4 < frameCount4; iFrame4 += 1) { - float32x4_t* pO = (float32x4_t*)ppSamplesOut[iChannelOut] + iFrame4; - float32x4_t* pI = (float32x4_t*)ppSamplesIn [iChannelIn ] + iFrame4; - *pO = vaddq_f32(*pO, vmulq_f32(*pI, weight)); - } - - iFrame += frameCount4*4; - } - else -#endif -#if defined(MAL_SUPPORT_AVX512) - if (mal_channel_router__can_use_avx512(pRouter, ppSamplesOut[iChannelOut], ppSamplesIn[iChannelIn])) { - __m512 weight = _mm512_set1_ps(pRouter->config.weights[iChannelIn][iChannelOut]); - - mal_uint64 frameCount16 = frameCount/16; - for (mal_uint64 iFrame16 = 0; iFrame16 < frameCount16; iFrame16 += 1) { - __m512* pO = (__m512*)ppSamplesOut[iChannelOut] + iFrame16; - __m512* pI = (__m512*)ppSamplesIn [iChannelIn ] + iFrame16; - *pO = _mm512_add_ps(*pO, _mm512_mul_ps(*pI, weight)); - } - - iFrame += frameCount16*16; - } - else -#endif -#if defined(MAL_SUPPORT_AVX2) - if (mal_channel_router__can_use_avx2(pRouter, ppSamplesOut[iChannelOut], ppSamplesIn[iChannelIn])) { - __m256 weight = _mm256_set1_ps(pRouter->config.weights[iChannelIn][iChannelOut]); - - mal_uint64 frameCount8 = frameCount/8; - for (mal_uint64 iFrame8 = 0; iFrame8 < frameCount8; iFrame8 += 1) { - __m256* pO = (__m256*)ppSamplesOut[iChannelOut] + iFrame8; - __m256* pI = (__m256*)ppSamplesIn [iChannelIn ] + iFrame8; - *pO = _mm256_add_ps(*pO, _mm256_mul_ps(*pI, weight)); - } - - iFrame += frameCount8*8; - } - else -#endif -#if defined(MAL_SUPPORT_SSE2) - if (mal_channel_router__can_use_sse2(pRouter, ppSamplesOut[iChannelOut], ppSamplesIn[iChannelIn])) { - __m128 weight = _mm_set1_ps(pRouter->config.weights[iChannelIn][iChannelOut]); - - mal_uint64 frameCount4 = frameCount/4; - for (mal_uint64 iFrame4 = 0; iFrame4 < frameCount4; iFrame4 += 1) { - __m128* pO = (__m128*)ppSamplesOut[iChannelOut] + iFrame4; - __m128* pI = (__m128*)ppSamplesIn [iChannelIn ] + iFrame4; - *pO = _mm_add_ps(*pO, _mm_mul_ps(*pI, weight)); - } - - iFrame += frameCount4*4; - } else -#endif - { // Reference. - float weight0 = pRouter->config.weights[iChannelIn][iChannelOut]; - float weight1 = pRouter->config.weights[iChannelIn][iChannelOut]; - float weight2 = pRouter->config.weights[iChannelIn][iChannelOut]; - float weight3 = pRouter->config.weights[iChannelIn][iChannelOut]; - - mal_uint64 frameCount4 = frameCount/4; - for (mal_uint64 iFrame4 = 0; iFrame4 < frameCount4; iFrame4 += 1) { - ppSamplesOut[iChannelOut][iFrame+0] += ppSamplesIn[iChannelIn][iFrame+0] * weight0; - ppSamplesOut[iChannelOut][iFrame+1] += ppSamplesIn[iChannelIn][iFrame+1] * weight1; - ppSamplesOut[iChannelOut][iFrame+2] += ppSamplesIn[iChannelIn][iFrame+2] * weight2; - ppSamplesOut[iChannelOut][iFrame+3] += ppSamplesIn[iChannelIn][iFrame+3] * weight3; - iFrame += 4; - } - } - - // Leftover. - for (; iFrame < frameCount; ++iFrame) { - ppSamplesOut[iChannelOut][iFrame] += ppSamplesIn[iChannelIn][iFrame] * pRouter->config.weights[iChannelIn][iChannelOut]; - } - } - } - } -} - -mal_uint64 mal_channel_router_read_deinterleaved(mal_channel_router* pRouter, mal_uint64 frameCount, void** ppSamplesOut, void* pUserData) -{ - if (pRouter == NULL || ppSamplesOut == NULL) { - return 0; - } - - // Fast path for a passthrough. - if (pRouter->isPassthrough) { - if (frameCount <= 0xFFFFFFFF) { - return (mal_uint32)pRouter->config.onReadDeinterleaved(pRouter, (mal_uint32)frameCount, ppSamplesOut, pUserData); - } else { - float* ppNextSamplesOut[MAL_MAX_CHANNELS]; - mal_copy_memory(ppNextSamplesOut, ppSamplesOut, sizeof(float*) * pRouter->config.channelsOut); - - mal_uint64 totalFramesRead = 0; - while (totalFramesRead < frameCount) { - mal_uint64 framesRemaining = (frameCount - totalFramesRead); - mal_uint64 framesToReadRightNow = framesRemaining; - if (framesToReadRightNow > 0xFFFFFFFF) { - framesToReadRightNow = 0xFFFFFFFF; - } - - mal_uint32 framesJustRead = (mal_uint32)pRouter->config.onReadDeinterleaved(pRouter, (mal_uint32)framesToReadRightNow, (void**)ppNextSamplesOut, pUserData); - if (framesJustRead == 0) { - break; - } - - totalFramesRead += framesJustRead; - for (mal_uint32 iChannel = 0; iChannel < pRouter->config.channelsOut; ++iChannel) { - ppNextSamplesOut[iChannel] += framesJustRead; - } - - if (framesJustRead < framesToReadRightNow) { - break; - } - } - } - } - - // Slower path for a non-passthrough. - float* ppNextSamplesOut[MAL_MAX_CHANNELS]; - mal_copy_memory(ppNextSamplesOut, ppSamplesOut, sizeof(float*) * pRouter->config.channelsOut); - - MAL_ALIGN(MAL_SIMD_ALIGNMENT) float temp[MAL_MAX_CHANNELS * 256]; - mal_assert(sizeof(temp) <= 0xFFFFFFFF); - - float* ppTemp[MAL_MAX_CHANNELS]; - size_t maxBytesToReadPerFrameEachIteration; - mal_split_buffer(temp, sizeof(temp), pRouter->config.channelsIn, MAL_SIMD_ALIGNMENT, (void**)&ppTemp, &maxBytesToReadPerFrameEachIteration); - - size_t maxFramesToReadEachIteration = maxBytesToReadPerFrameEachIteration/sizeof(float); - - mal_uint64 totalFramesRead = 0; - while (totalFramesRead < frameCount) { - mal_uint64 framesRemaining = (frameCount - totalFramesRead); - mal_uint64 framesToReadRightNow = framesRemaining; - if (framesToReadRightNow > maxFramesToReadEachIteration) { - framesToReadRightNow = maxFramesToReadEachIteration; - } - - mal_uint32 framesJustRead = pRouter->config.onReadDeinterleaved(pRouter, (mal_uint32)framesToReadRightNow, (void**)ppTemp, pUserData); - if (framesJustRead == 0) { - break; - } - - mal_channel_router__do_routing(pRouter, framesJustRead, (float**)ppNextSamplesOut, (const float**)ppTemp); // <-- Real work is done here. - - totalFramesRead += framesJustRead; - if (totalFramesRead < frameCount) { - for (mal_uint32 iChannel = 0; iChannel < pRouter->config.channelsIn; iChannel += 1) { - ppNextSamplesOut[iChannel] += framesJustRead; - } - } - - if (framesJustRead < framesToReadRightNow) { - break; - } - } - - return totalFramesRead; -} - -mal_channel_router_config mal_channel_router_config_init(mal_uint32 channelsIn, const mal_channel channelMapIn[MAL_MAX_CHANNELS], mal_uint32 channelsOut, const mal_channel channelMapOut[MAL_MAX_CHANNELS], mal_channel_mix_mode mixingMode, mal_channel_router_read_deinterleaved_proc onRead, void* pUserData) -{ - mal_channel_router_config config; - mal_zero_object(&config); - - config.channelsIn = channelsIn; - for (mal_uint32 iChannel = 0; iChannel < channelsIn; ++iChannel) { - config.channelMapIn[iChannel] = channelMapIn[iChannel]; - } - - config.channelsOut = channelsOut; - for (mal_uint32 iChannel = 0; iChannel < channelsOut; ++iChannel) { - config.channelMapOut[iChannel] = channelMapOut[iChannel]; - } - - config.mixingMode = mixingMode; - config.onReadDeinterleaved = onRead; - config.pUserData = pUserData; - - return config; -} - - - -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// SRC -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -#define mal_floorf(x) ((float)floor((double)(x))) -#define mal_sinf(x) ((float)sin((double)(x))) -#define mal_cosf(x) ((float)cos((double)(x))) - -static MAL_INLINE double mal_sinc(double x) -{ - if (x != 0) { - return sin(MAL_PI_D*x) / (MAL_PI_D*x); - } else { - return 1; - } -} - -#define mal_sincf(x) ((float)mal_sinc((double)(x))) - -mal_uint64 mal_calculate_frame_count_after_src(mal_uint32 sampleRateOut, mal_uint32 sampleRateIn, mal_uint64 frameCountIn) -{ - double srcRatio = (double)sampleRateOut / sampleRateIn; - double frameCountOutF = frameCountIn * srcRatio; - - mal_uint64 frameCountOut = (mal_uint64)frameCountOutF; - - // If the output frame count is fractional, make sure we add an extra frame to ensure there's enough room for that last sample. - if ((frameCountOutF - frameCountOut) > 0.0) { - frameCountOut += 1; - } - - return frameCountOut; -} - - -mal_uint64 mal_src_read_deinterleaved__passthrough(mal_src* pSRC, mal_uint64 frameCount, void** ppSamplesOut, void* pUserData); -mal_uint64 mal_src_read_deinterleaved__linear(mal_src* pSRC, mal_uint64 frameCount, void** ppSamplesOut, void* pUserData); -mal_uint64 mal_src_read_deinterleaved__sinc(mal_src* pSRC, mal_uint64 frameCount, void** ppSamplesOut, void* pUserData); - -void mal_src__build_sinc_table__sinc(mal_src* pSRC) -{ - mal_assert(pSRC != NULL); - - pSRC->sinc.table[0] = 1.0f; - for (mal_uint32 i = 1; i < mal_countof(pSRC->sinc.table); i += 1) { - double x = i*MAL_PI_D / MAL_SRC_SINC_LOOKUP_TABLE_RESOLUTION; - pSRC->sinc.table[i] = (float)(sin(x)/x); - } -} - -void mal_src__build_sinc_table__rectangular(mal_src* pSRC) -{ - // This is the same as the base sinc table. - mal_src__build_sinc_table__sinc(pSRC); -} - -void mal_src__build_sinc_table__hann(mal_src* pSRC) -{ - mal_src__build_sinc_table__sinc(pSRC); - - for (mal_uint32 i = 0; i < mal_countof(pSRC->sinc.table); i += 1) { - double x = pSRC->sinc.table[i]; - double N = MAL_SRC_SINC_MAX_WINDOW_WIDTH*2; - double n = ((double)(i) / MAL_SRC_SINC_LOOKUP_TABLE_RESOLUTION) + MAL_SRC_SINC_MAX_WINDOW_WIDTH; - double w = 0.5 * (1 - cos((2*MAL_PI_D*n) / (N))); - - pSRC->sinc.table[i] = (float)(x * w); - } -} - -mal_result mal_src_init(const mal_src_config* pConfig, mal_src* pSRC) -{ - if (pSRC == NULL) { - return MAL_INVALID_ARGS; - } - - mal_zero_object(pSRC); - - if (pConfig == NULL || pConfig->onReadDeinterleaved == NULL) { - return MAL_INVALID_ARGS; - } - if (pConfig->channels == 0 || pConfig->channels > MAL_MAX_CHANNELS) { - return MAL_INVALID_ARGS; - } - - pSRC->config = *pConfig; - - // SIMD - pSRC->useSSE2 = mal_has_sse2() && !pConfig->noSSE2; - pSRC->useAVX2 = mal_has_avx2() && !pConfig->noAVX2; - pSRC->useAVX512 = mal_has_avx512f() && !pConfig->noAVX512; - pSRC->useNEON = mal_has_neon() && !pConfig->noNEON; - - if (pSRC->config.algorithm == mal_src_algorithm_sinc) { - // Make sure the window width within bounds. - if (pSRC->config.sinc.windowWidth == 0) { - pSRC->config.sinc.windowWidth = MAL_SRC_SINC_DEFAULT_WINDOW_WIDTH; - } - if (pSRC->config.sinc.windowWidth < MAL_SRC_SINC_MIN_WINDOW_WIDTH) { - pSRC->config.sinc.windowWidth = MAL_SRC_SINC_MIN_WINDOW_WIDTH; - } - if (pSRC->config.sinc.windowWidth > MAL_SRC_SINC_MAX_WINDOW_WIDTH) { - pSRC->config.sinc.windowWidth = MAL_SRC_SINC_MAX_WINDOW_WIDTH; - } - - // Set up the lookup table. - switch (pSRC->config.sinc.windowFunction) { - case mal_src_sinc_window_function_hann: mal_src__build_sinc_table__hann(pSRC); break; - case mal_src_sinc_window_function_rectangular: mal_src__build_sinc_table__rectangular(pSRC); break; - default: return MAL_INVALID_ARGS; // <-- Hitting this means the window function is unknown to mini_al. - } - } - - return MAL_SUCCESS; -} - -mal_result mal_src_set_input_sample_rate(mal_src* pSRC, mal_uint32 sampleRateIn) -{ - if (pSRC == NULL) { - return MAL_INVALID_ARGS; - } - - // Must have a sample rate of > 0. - if (sampleRateIn == 0) { - return MAL_INVALID_ARGS; - } - - mal_atomic_exchange_32(&pSRC->config.sampleRateIn, sampleRateIn); - return MAL_SUCCESS; -} - -mal_result mal_src_set_output_sample_rate(mal_src* pSRC, mal_uint32 sampleRateOut) -{ - if (pSRC == NULL) { - return MAL_INVALID_ARGS; - } - - // Must have a sample rate of > 0. - if (sampleRateOut == 0) { - return MAL_INVALID_ARGS; - } - - mal_atomic_exchange_32(&pSRC->config.sampleRateOut, sampleRateOut); - return MAL_SUCCESS; -} - -mal_result mal_src_set_sample_rate(mal_src* pSRC, mal_uint32 sampleRateIn, mal_uint32 sampleRateOut) -{ - if (pSRC == NULL) { - return MAL_INVALID_ARGS; - } - - // Must have a sample rate of > 0. - if (sampleRateIn == 0 || sampleRateOut == 0) { - return MAL_INVALID_ARGS; - } - - mal_atomic_exchange_32(&pSRC->config.sampleRateIn, sampleRateIn); - mal_atomic_exchange_32(&pSRC->config.sampleRateOut, sampleRateOut); - - return MAL_SUCCESS; -} - -mal_uint64 mal_src_read_deinterleaved(mal_src* pSRC, mal_uint64 frameCount, void** ppSamplesOut, void* pUserData) -{ - if (pSRC == NULL || frameCount == 0 || ppSamplesOut == NULL) { - return 0; - } - - mal_src_algorithm algorithm = pSRC->config.algorithm; - - // Can use a function pointer for this. - switch (algorithm) { - case mal_src_algorithm_none: return mal_src_read_deinterleaved__passthrough(pSRC, frameCount, ppSamplesOut, pUserData); - case mal_src_algorithm_linear: return mal_src_read_deinterleaved__linear( pSRC, frameCount, ppSamplesOut, pUserData); - case mal_src_algorithm_sinc: return mal_src_read_deinterleaved__sinc( pSRC, frameCount, ppSamplesOut, pUserData); - default: break; - } - - // Should never get here. - return 0; -} - -mal_uint64 mal_src_read_deinterleaved__passthrough(mal_src* pSRC, mal_uint64 frameCount, void** ppSamplesOut, void* pUserData) -{ - if (frameCount <= 0xFFFFFFFF) { - return pSRC->config.onReadDeinterleaved(pSRC, (mal_uint32)frameCount, ppSamplesOut, pUserData); - } else { - float* ppNextSamplesOut[MAL_MAX_CHANNELS]; - for (mal_uint32 iChannel = 0; iChannel < pSRC->config.channels; ++iChannel) { - ppNextSamplesOut[iChannel] = (float*)ppSamplesOut[iChannel]; - } - - mal_uint64 totalFramesRead = 0; - while (totalFramesRead < frameCount) { - mal_uint64 framesRemaining = frameCount - totalFramesRead; - mal_uint64 framesToReadRightNow = framesRemaining; - if (framesToReadRightNow > 0xFFFFFFFF) { - framesToReadRightNow = 0xFFFFFFFF; - } - - mal_uint32 framesJustRead = (mal_uint32)pSRC->config.onReadDeinterleaved(pSRC, (mal_uint32)framesToReadRightNow, (void**)ppNextSamplesOut, pUserData); - if (framesJustRead == 0) { - break; - } - - totalFramesRead += framesJustRead; - for (mal_uint32 iChannel = 0; iChannel < pSRC->config.channels; ++iChannel) { - ppNextSamplesOut[iChannel] += framesJustRead; - } - - if (framesJustRead < framesToReadRightNow) { - break; - } - } - - return totalFramesRead; - } -} - -mal_uint64 mal_src_read_deinterleaved__linear(mal_src* pSRC, mal_uint64 frameCount, void** ppSamplesOut, void* pUserData) -{ - mal_assert(pSRC != NULL); - mal_assert(frameCount > 0); - mal_assert(ppSamplesOut != NULL); - - float* ppNextSamplesOut[MAL_MAX_CHANNELS]; - mal_copy_memory(ppNextSamplesOut, ppSamplesOut, sizeof(void*) * pSRC->config.channels); - - - float factor = (float)pSRC->config.sampleRateIn / pSRC->config.sampleRateOut; - - mal_uint32 maxFrameCountPerChunkIn = mal_countof(pSRC->linear.input[0]); - - mal_uint64 totalFramesRead = 0; - while (totalFramesRead < frameCount) { - mal_uint64 framesRemaining = frameCount - totalFramesRead; - mal_uint64 framesToRead = framesRemaining; - if (framesToRead > 16384) { - framesToRead = 16384; // <-- Keep this small because we're using 32-bit floats for calculating sample positions and I don't want to run out of precision with huge sample counts. - } - - - // Read Input Data - // =============== - float tBeg = pSRC->linear.timeIn; - float tEnd = tBeg + (framesToRead*factor); - - mal_uint32 framesToReadFromClient = (mal_uint32)(tEnd) + 1 + 1; // +1 to make tEnd 1-based and +1 because we always need to an extra sample for interpolation. - if (framesToReadFromClient >= maxFrameCountPerChunkIn) { - framesToReadFromClient = maxFrameCountPerChunkIn; - } - - float* ppSamplesFromClient[MAL_MAX_CHANNELS]; - for (mal_uint32 iChannel = 0; iChannel < pSRC->config.channels; ++iChannel) { - ppSamplesFromClient[iChannel] = pSRC->linear.input[iChannel] + pSRC->linear.leftoverFrames; - } - - mal_uint32 framesReadFromClient = 0; - if (framesToReadFromClient > pSRC->linear.leftoverFrames) { - framesReadFromClient = (mal_uint32)pSRC->config.onReadDeinterleaved(pSRC, (mal_uint32)framesToReadFromClient - pSRC->linear.leftoverFrames, (void**)ppSamplesFromClient, pUserData); - } - - framesReadFromClient += pSRC->linear.leftoverFrames; // <-- You can sort of think of it as though we've re-read the leftover samples from the client. - if (framesReadFromClient < 2) { - break; - } - - for (mal_uint32 iChannel = 0; iChannel < pSRC->config.channels; ++iChannel) { - ppSamplesFromClient[iChannel] = pSRC->linear.input[iChannel]; - } - - - // Write Output Data - // ================= - - // At this point we have a bunch of frames that the client has given to us for processing. From this we can determine the maximum number of output frames - // that can be processed from this input. We want to output as many samples as possible from our input data. - float tAvailable = framesReadFromClient - tBeg - 1; // Subtract 1 because the last input sample is needed for interpolation and cannot be included in the output sample count calculation. - - mal_uint32 maxOutputFramesToRead = (mal_uint32)(tAvailable / factor); - if (maxOutputFramesToRead == 0) { - maxOutputFramesToRead = 1; - } - if (maxOutputFramesToRead > framesToRead) { - maxOutputFramesToRead = (mal_uint32)framesToRead; - } - - // Output frames are always read in groups of 4 because I'm planning on using this as a reference for some SIMD-y stuff later. - mal_uint32 maxOutputFramesToRead4 = maxOutputFramesToRead/4; - for (mal_uint32 iChannel = 0; iChannel < pSRC->config.channels; ++iChannel) { - float t0 = pSRC->linear.timeIn + factor*0; - float t1 = pSRC->linear.timeIn + factor*1; - float t2 = pSRC->linear.timeIn + factor*2; - float t3 = pSRC->linear.timeIn + factor*3; - - for (mal_uint32 iFrameOut = 0; iFrameOut < maxOutputFramesToRead4; iFrameOut += 1) { - float iPrevSample0 = (float)floor(t0); - float iPrevSample1 = (float)floor(t1); - float iPrevSample2 = (float)floor(t2); - float iPrevSample3 = (float)floor(t3); - - float iNextSample0 = iPrevSample0 + 1; - float iNextSample1 = iPrevSample1 + 1; - float iNextSample2 = iPrevSample2 + 1; - float iNextSample3 = iPrevSample3 + 1; - - float alpha0 = t0 - iPrevSample0; - float alpha1 = t1 - iPrevSample1; - float alpha2 = t2 - iPrevSample2; - float alpha3 = t3 - iPrevSample3; - - float prevSample0 = ppSamplesFromClient[iChannel][(mal_uint32)iPrevSample0]; - float prevSample1 = ppSamplesFromClient[iChannel][(mal_uint32)iPrevSample1]; - float prevSample2 = ppSamplesFromClient[iChannel][(mal_uint32)iPrevSample2]; - float prevSample3 = ppSamplesFromClient[iChannel][(mal_uint32)iPrevSample3]; - - float nextSample0 = ppSamplesFromClient[iChannel][(mal_uint32)iNextSample0]; - float nextSample1 = ppSamplesFromClient[iChannel][(mal_uint32)iNextSample1]; - float nextSample2 = ppSamplesFromClient[iChannel][(mal_uint32)iNextSample2]; - float nextSample3 = ppSamplesFromClient[iChannel][(mal_uint32)iNextSample3]; - - ppNextSamplesOut[iChannel][iFrameOut*4 + 0] = mal_mix_f32_fast(prevSample0, nextSample0, alpha0); - ppNextSamplesOut[iChannel][iFrameOut*4 + 1] = mal_mix_f32_fast(prevSample1, nextSample1, alpha1); - ppNextSamplesOut[iChannel][iFrameOut*4 + 2] = mal_mix_f32_fast(prevSample2, nextSample2, alpha2); - ppNextSamplesOut[iChannel][iFrameOut*4 + 3] = mal_mix_f32_fast(prevSample3, nextSample3, alpha3); - - t0 += factor*4; - t1 += factor*4; - t2 += factor*4; - t3 += factor*4; - } - - float t = pSRC->linear.timeIn + (factor*maxOutputFramesToRead4*4); - for (mal_uint32 iFrameOut = (maxOutputFramesToRead4*4); iFrameOut < maxOutputFramesToRead; iFrameOut += 1) { - float iPrevSample = (float)floor(t); - float iNextSample = iPrevSample + 1; - float alpha = t - iPrevSample; - - mal_assert(iPrevSample < mal_countof(pSRC->linear.input[iChannel])); - mal_assert(iNextSample < mal_countof(pSRC->linear.input[iChannel])); - - float prevSample = ppSamplesFromClient[iChannel][(mal_uint32)iPrevSample]; - float nextSample = ppSamplesFromClient[iChannel][(mal_uint32)iNextSample]; - - ppNextSamplesOut[iChannel][iFrameOut] = mal_mix_f32_fast(prevSample, nextSample, alpha); - - t += factor; - } - - ppNextSamplesOut[iChannel] += maxOutputFramesToRead; - } - - totalFramesRead += maxOutputFramesToRead; - - - // Residual - // ======== - float tNext = pSRC->linear.timeIn + (maxOutputFramesToRead*factor); - - pSRC->linear.timeIn = tNext; - mal_assert(tNext <= framesReadFromClient+1); - - mal_uint32 iNextFrame = (mal_uint32)floor(tNext); - pSRC->linear.leftoverFrames = framesReadFromClient - iNextFrame; - pSRC->linear.timeIn = tNext - iNextFrame; - - for (mal_uint32 iChannel = 0; iChannel < pSRC->config.channels; ++iChannel) { - for (mal_uint32 iFrame = 0; iFrame < pSRC->linear.leftoverFrames; ++iFrame) { - float sample = ppSamplesFromClient[iChannel][framesReadFromClient-pSRC->linear.leftoverFrames + iFrame]; - ppSamplesFromClient[iChannel][iFrame] = sample; - } - } - - - // Exit the loop if we've found everything from the client. - if (framesReadFromClient < framesToReadFromClient) { - break; - } - } - - return totalFramesRead; -} - - -mal_src_config mal_src_config_init_new() -{ - mal_src_config config; - mal_zero_object(&config); - - return config; -} - -mal_src_config mal_src_config_init(mal_uint32 sampleRateIn, mal_uint32 sampleRateOut, mal_uint32 channels, mal_src_read_deinterleaved_proc onReadDeinterleaved, void* pUserData) -{ - mal_src_config config = mal_src_config_init_new(); - config.sampleRateIn = sampleRateIn; - config.sampleRateOut = sampleRateOut; - config.channels = channels; - config.onReadDeinterleaved = onReadDeinterleaved; - config.pUserData = pUserData; - - return config; -} - - -/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Sinc Sample Rate Conversion -// =========================== -// -// The sinc SRC algorithm uses a windowed sinc to perform interpolation of samples. Currently, mini_al's implementation supports rectangular and Hann window -// methods. -// -// Whenever an output sample is being computed, it looks at a sub-section of the input samples. I've called this sub-section in the code below the "window", -// which I realize is a bit ambigous with the mathematical "window", but it works for me when I need to conceptualize things in my head. The window is made up -// of two halves. The first half contains past input samples (initialized to zero), and the second half contains future input samples. As time moves forward -// and input samples are consumed, the window moves forward. The larger the window, the better the quality at the expense of slower processing. The window is -// limited the range [MAL_SRC_SINC_MIN_WINDOW_WIDTH, MAL_SRC_SINC_MAX_WINDOW_WIDTH] and defaults to MAL_SRC_SINC_DEFAULT_WINDOW_WIDTH. -// -// Input samples are cached for efficiency (to prevent frequently requesting tiny numbers of samples from the client). When the window gets to the end of the -// cache, it's moved back to the start, and more samples are read from the client. If the client has no more data to give, the cache is filled with zeros and -// the last of the input samples will be consumed. Once the last of the input samples have been consumed, no more samples will be output. -// -// -// When reading output samples, we always first read whatever is already in the input cache. Only when the cache has been fully consumed do we read more data -// from the client. -// -// To access samples in the input buffer you do so relative to the window. When the window itself is at position 0, the first item in the buffer is accessed -// with "windowPos + windowWidth". Generally, to access any sample relative to the window you do "windowPos + windowWidth + sampleIndexRelativeToWindow". -// -/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -// Comment this to disable interpolation of table lookups. Less accurate, but faster. -#define MAL_USE_SINC_TABLE_INTERPOLATION - -// Retrieves a sample from the input buffer's window. Values >= 0 retrieve future samples. Negative values return past samples. -static MAL_INLINE float mal_src_sinc__get_input_sample_from_window(const mal_src* pSRC, mal_uint32 channel, mal_uint32 windowPosInSamples, mal_int32 sampleIndex) -{ - mal_assert(pSRC != NULL); - mal_assert(channel < pSRC->config.channels); - mal_assert(sampleIndex >= -(mal_int32)pSRC->config.sinc.windowWidth); - mal_assert(sampleIndex < (mal_int32)pSRC->config.sinc.windowWidth); - - // The window should always be contained within the input cache. - mal_assert(windowPosInSamples < mal_countof(pSRC->sinc.input[0]) - pSRC->config.sinc.windowWidth); - - return pSRC->sinc.input[channel][windowPosInSamples + pSRC->config.sinc.windowWidth + sampleIndex]; -} - -static MAL_INLINE float mal_src_sinc__interpolation_factor(const mal_src* pSRC, float x) -{ - mal_assert(pSRC != NULL); - - float xabs = (float)fabs(x); - //if (xabs >= MAL_SRC_SINC_MAX_WINDOW_WIDTH /*pSRC->config.sinc.windowWidth*/) { - // xabs = 1; // <-- A non-zero integer will always return 0. - //} - - xabs = xabs * MAL_SRC_SINC_LOOKUP_TABLE_RESOLUTION; - mal_int32 ixabs = (mal_int32)xabs; - -#if defined(MAL_USE_SINC_TABLE_INTERPOLATION) - float a = xabs - ixabs; - return mal_mix_f32_fast(pSRC->sinc.table[ixabs], pSRC->sinc.table[ixabs+1], a); -#else - return pSRC->sinc.table[ixabs]; -#endif -} - -#if defined(MAL_SUPPORT_SSE2) -static MAL_INLINE __m128 mal_fabsf_sse2(__m128 x) -{ - return _mm_and_ps(_mm_castsi128_ps(_mm_set1_epi32(0x7FFFFFFF)), x); -} - -static MAL_INLINE __m128 mal_truncf_sse2(__m128 x) -{ - return _mm_cvtepi32_ps(_mm_cvttps_epi32(x)); -} - -static MAL_INLINE __m128 mal_src_sinc__interpolation_factor__sse2(const mal_src* pSRC, __m128 x) -{ - //__m128 windowWidth128 = _mm_set1_ps(MAL_SRC_SINC_MAX_WINDOW_WIDTH); - __m128 resolution128 = _mm_set1_ps(MAL_SRC_SINC_LOOKUP_TABLE_RESOLUTION); - //__m128 one = _mm_set1_ps(1); - - __m128 xabs = mal_fabsf_sse2(x); - - // if (MAL_SRC_SINC_MAX_WINDOW_WIDTH <= xabs) xabs = 1 else xabs = xabs; - //__m128 xcmp = _mm_cmp_ps(windowWidth128, xabs, 2); // 2 = Less than or equal = _mm_cmple_ps. - //xabs = _mm_or_ps(_mm_and_ps(one, xcmp), _mm_andnot_ps(xcmp, xabs)); // xabs = (xcmp) ? 1 : xabs; - - xabs = _mm_mul_ps(xabs, resolution128); - __m128i ixabs = _mm_cvttps_epi32(xabs); - - int* ixabsv = (int*)&ixabs; - - __m128 lo = _mm_set_ps( - pSRC->sinc.table[ixabsv[3]], - pSRC->sinc.table[ixabsv[2]], - pSRC->sinc.table[ixabsv[1]], - pSRC->sinc.table[ixabsv[0]] - ); - - __m128 hi = _mm_set_ps( - pSRC->sinc.table[ixabsv[3]+1], - pSRC->sinc.table[ixabsv[2]+1], - pSRC->sinc.table[ixabsv[1]+1], - pSRC->sinc.table[ixabsv[0]+1] - ); - - __m128 a = _mm_sub_ps(xabs, _mm_cvtepi32_ps(ixabs)); - __m128 r = mal_mix_f32_fast__sse2(lo, hi, a); - - return r; -} -#endif - -#if defined(MAL_SUPPORT_AVX2) -static MAL_INLINE __m256 mal_fabsf_avx2(__m256 x) -{ - return _mm256_and_ps(_mm256_castsi256_ps(_mm256_set1_epi32(0x7FFFFFFF)), x); -} - -#if 0 -static MAL_INLINE __m256 mal_src_sinc__interpolation_factor__avx2(const mal_src* pSRC, __m256 x) -{ - //__m256 windowWidth256 = _mm256_set1_ps(MAL_SRC_SINC_MAX_WINDOW_WIDTH); - __m256 resolution256 = _mm256_set1_ps(MAL_SRC_SINC_LOOKUP_TABLE_RESOLUTION); - //__m256 one = _mm256_set1_ps(1); - - __m256 xabs = mal_fabsf_avx2(x); - - // if (MAL_SRC_SINC_MAX_WINDOW_WIDTH <= xabs) xabs = 1 else xabs = xabs; - //__m256 xcmp = _mm256_cmp_ps(windowWidth256, xabs, 2); // 2 = Less than or equal = _mm_cmple_ps. - //xabs = _mm256_or_ps(_mm256_and_ps(one, xcmp), _mm256_andnot_ps(xcmp, xabs)); // xabs = (xcmp) ? 1 : xabs; - - xabs = _mm256_mul_ps(xabs, resolution256); - - __m256i ixabs = _mm256_cvttps_epi32(xabs); - __m256 a = _mm256_sub_ps(xabs, _mm256_cvtepi32_ps(ixabs)); - - - int* ixabsv = (int*)&ixabs; - - __m256 lo = _mm256_set_ps( - pSRC->sinc.table[ixabsv[7]], - pSRC->sinc.table[ixabsv[6]], - pSRC->sinc.table[ixabsv[5]], - pSRC->sinc.table[ixabsv[4]], - pSRC->sinc.table[ixabsv[3]], - pSRC->sinc.table[ixabsv[2]], - pSRC->sinc.table[ixabsv[1]], - pSRC->sinc.table[ixabsv[0]] - ); - - __m256 hi = _mm256_set_ps( - pSRC->sinc.table[ixabsv[7]+1], - pSRC->sinc.table[ixabsv[6]+1], - pSRC->sinc.table[ixabsv[5]+1], - pSRC->sinc.table[ixabsv[4]+1], - pSRC->sinc.table[ixabsv[3]+1], - pSRC->sinc.table[ixabsv[2]+1], - pSRC->sinc.table[ixabsv[1]+1], - pSRC->sinc.table[ixabsv[0]+1] - ); - - __m256 r = mal_mix_f32_fast__avx2(lo, hi, a); - - return r; -} -#endif - -#endif - -#if defined(MAL_SUPPORT_NEON) -static MAL_INLINE float32x4_t mal_fabsf_neon(float32x4_t x) -{ - return vabdq_f32(vmovq_n_f32(0), x); -} - -static MAL_INLINE float32x4_t mal_src_sinc__interpolation_factor__neon(const mal_src* pSRC, float32x4_t x) -{ - float32x4_t xabs = mal_fabsf_neon(x); - xabs = vmulq_n_f32(xabs, MAL_SRC_SINC_LOOKUP_TABLE_RESOLUTION); - - int32x4_t ixabs = vcvtq_s32_f32(xabs); - - int* ixabsv = (int*)&ixabs; - - float lo[4]; - lo[0] = pSRC->sinc.table[ixabsv[0]]; - lo[1] = pSRC->sinc.table[ixabsv[1]]; - lo[2] = pSRC->sinc.table[ixabsv[2]]; - lo[3] = pSRC->sinc.table[ixabsv[3]]; - - float hi[4]; - hi[0] = pSRC->sinc.table[ixabsv[0]+1]; - hi[1] = pSRC->sinc.table[ixabsv[1]+1]; - hi[2] = pSRC->sinc.table[ixabsv[2]+1]; - hi[3] = pSRC->sinc.table[ixabsv[3]+1]; - - float32x4_t a = vsubq_f32(xabs, vcvtq_f32_s32(ixabs)); - float32x4_t r = mal_mix_f32_fast__neon(vld1q_f32(lo), vld1q_f32(hi), a); - - return r; -} -#endif - -mal_uint64 mal_src_read_deinterleaved__sinc(mal_src* pSRC, mal_uint64 frameCount, void** ppSamplesOut, void* pUserData) -{ - mal_assert(pSRC != NULL); - mal_assert(frameCount > 0); - mal_assert(ppSamplesOut != NULL); - - float factor = (float)pSRC->config.sampleRateIn / pSRC->config.sampleRateOut; - float inverseFactor = 1/factor; - - mal_int32 windowWidth = (mal_int32)pSRC->config.sinc.windowWidth; - mal_int32 windowWidth2 = windowWidth*2; - - // There are cases where it's actually more efficient to increase the window width so that it's aligned with the respective - // SIMD pipeline being used. - mal_int32 windowWidthSIMD = windowWidth; - if (pSRC->useNEON) { - windowWidthSIMD = (windowWidthSIMD + 1) & ~(1); - } else if (pSRC->useAVX512) { - windowWidthSIMD = (windowWidthSIMD + 7) & ~(7); - } else if (pSRC->useAVX2) { - windowWidthSIMD = (windowWidthSIMD + 3) & ~(3); - } else if (pSRC->useSSE2) { - windowWidthSIMD = (windowWidthSIMD + 1) & ~(1); - } - - mal_int32 windowWidthSIMD2 = windowWidthSIMD*2; - (void)windowWidthSIMD2; // <-- Silence a warning when SIMD is disabled. - - float* ppNextSamplesOut[MAL_MAX_CHANNELS]; - mal_copy_memory(ppNextSamplesOut, ppSamplesOut, sizeof(void*) * pSRC->config.channels); - - float _windowSamplesUnaligned[MAL_SRC_SINC_MAX_WINDOW_WIDTH*2 + MAL_SIMD_ALIGNMENT]; - float* windowSamples = (float*)(((mal_uintptr)_windowSamplesUnaligned + MAL_SIMD_ALIGNMENT-1) & ~(MAL_SIMD_ALIGNMENT-1)); - mal_zero_memory(windowSamples, MAL_SRC_SINC_MAX_WINDOW_WIDTH*2 * sizeof(float)); - - float _iWindowFUnaligned[MAL_SRC_SINC_MAX_WINDOW_WIDTH*2 + MAL_SIMD_ALIGNMENT]; - float* iWindowF = (float*)(((mal_uintptr)_iWindowFUnaligned + MAL_SIMD_ALIGNMENT-1) & ~(MAL_SIMD_ALIGNMENT-1)); - mal_zero_memory(iWindowF, MAL_SRC_SINC_MAX_WINDOW_WIDTH*2 * sizeof(float)); - for (mal_int32 i = 0; i < windowWidth2; ++i) { - iWindowF[i] = (float)(i - windowWidth); - } - - mal_uint64 totalOutputFramesRead = 0; - while (totalOutputFramesRead < frameCount) { - // The maximum number of frames we can read this iteration depends on how many input samples we have available to us. This is the number - // of input samples between the end of the window and the end of the cache. - mal_uint32 maxInputSamplesAvailableInCache = mal_countof(pSRC->sinc.input[0]) - (pSRC->config.sinc.windowWidth*2) - pSRC->sinc.windowPosInSamples; - if (maxInputSamplesAvailableInCache > pSRC->sinc.inputFrameCount) { - maxInputSamplesAvailableInCache = pSRC->sinc.inputFrameCount; - } - - // Never consume the tail end of the input data if requested. - if (pSRC->config.neverConsumeEndOfInput) { - if (maxInputSamplesAvailableInCache >= pSRC->config.sinc.windowWidth) { - maxInputSamplesAvailableInCache -= pSRC->config.sinc.windowWidth; - } else { - maxInputSamplesAvailableInCache = 0; - } - } - - float timeInBeg = pSRC->sinc.timeIn; - float timeInEnd = (float)(pSRC->sinc.windowPosInSamples + maxInputSamplesAvailableInCache); - - mal_assert(timeInBeg >= 0); - mal_assert(timeInBeg <= timeInEnd); - - mal_uint64 maxOutputFramesToRead = (mal_uint64)(((timeInEnd - timeInBeg) * inverseFactor)); - - mal_uint64 outputFramesRemaining = frameCount - totalOutputFramesRead; - mal_uint64 outputFramesToRead = outputFramesRemaining; - if (outputFramesToRead > maxOutputFramesToRead) { - outputFramesToRead = maxOutputFramesToRead; - } - - for (mal_uint32 iChannel = 0; iChannel < pSRC->config.channels; iChannel += 1) { - // Do SRC. - float timeIn = timeInBeg; - for (mal_uint32 iSample = 0; iSample < outputFramesToRead; iSample += 1) { - float sampleOut = 0; - float iTimeInF = mal_floorf(timeIn); - mal_uint32 iTimeIn = (mal_uint32)iTimeInF; - - mal_int32 iWindow = 0; - - // Pre-load the window samples into an aligned buffer to begin with. Need to put these into an aligned buffer to make SIMD easier. - windowSamples[0] = 0; // <-- The first sample is always zero. - for (mal_int32 i = 1; i < windowWidth2; ++i) { - windowSamples[i] = pSRC->sinc.input[iChannel][iTimeIn + i]; - } - -#if defined(MAL_SUPPORT_AVX2) || defined(MAL_SUPPORT_AVX512) - if (pSRC->useAVX2 || pSRC->useAVX512) { - __m256i ixabs[MAL_SRC_SINC_MAX_WINDOW_WIDTH*2/8]; - __m256 a[MAL_SRC_SINC_MAX_WINDOW_WIDTH*2/8]; - __m256 resolution256 = _mm256_set1_ps(MAL_SRC_SINC_LOOKUP_TABLE_RESOLUTION); - - __m256 t = _mm256_set1_ps((timeIn - iTimeInF)); - __m256 r = _mm256_set1_ps(0); - - mal_int32 windowWidth8 = windowWidthSIMD2 >> 3; - for (mal_int32 iWindow8 = 0; iWindow8 < windowWidth8; iWindow8 += 1) { - __m256 w = *((__m256*)iWindowF + iWindow8); - - __m256 xabs = _mm256_sub_ps(t, w); - xabs = mal_fabsf_avx2(xabs); - xabs = _mm256_mul_ps(xabs, resolution256); - - ixabs[iWindow8] = _mm256_cvttps_epi32(xabs); - a[iWindow8] = _mm256_sub_ps(xabs, _mm256_cvtepi32_ps(ixabs[iWindow8])); - } - - for (mal_int32 iWindow8 = 0; iWindow8 < windowWidth8; iWindow8 += 1) { - int* ixabsv = (int*)&ixabs[iWindow8]; - - __m256 lo = _mm256_set_ps( - pSRC->sinc.table[ixabsv[7]], - pSRC->sinc.table[ixabsv[6]], - pSRC->sinc.table[ixabsv[5]], - pSRC->sinc.table[ixabsv[4]], - pSRC->sinc.table[ixabsv[3]], - pSRC->sinc.table[ixabsv[2]], - pSRC->sinc.table[ixabsv[1]], - pSRC->sinc.table[ixabsv[0]] - ); - - __m256 hi = _mm256_set_ps( - pSRC->sinc.table[ixabsv[7]+1], - pSRC->sinc.table[ixabsv[6]+1], - pSRC->sinc.table[ixabsv[5]+1], - pSRC->sinc.table[ixabsv[4]+1], - pSRC->sinc.table[ixabsv[3]+1], - pSRC->sinc.table[ixabsv[2]+1], - pSRC->sinc.table[ixabsv[1]+1], - pSRC->sinc.table[ixabsv[0]+1] - ); - - __m256 s = *((__m256*)windowSamples + iWindow8); - r = _mm256_add_ps(r, _mm256_mul_ps(s, mal_mix_f32_fast__avx2(lo, hi, a[iWindow8]))); - } - - // Horizontal add. - __m256 x = _mm256_hadd_ps(r, _mm256_permute2f128_ps(r, r, 1)); - x = _mm256_hadd_ps(x, x); - x = _mm256_hadd_ps(x, x); - sampleOut += _mm_cvtss_f32(_mm256_castps256_ps128(x)); - - iWindow += windowWidth8 * 8; - } - else -#endif -#if defined(MAL_SUPPORT_SSE2) - if (pSRC->useSSE2) { - __m128 t = _mm_set1_ps((timeIn - iTimeInF)); - __m128 r = _mm_set1_ps(0); - - mal_int32 windowWidth4 = windowWidthSIMD2 >> 2; - for (mal_int32 iWindow4 = 0; iWindow4 < windowWidth4; iWindow4 += 1) { - __m128* s = (__m128*)windowSamples + iWindow4; - __m128* w = (__m128*)iWindowF + iWindow4; - - __m128 a = mal_src_sinc__interpolation_factor__sse2(pSRC, _mm_sub_ps(t, *w)); - r = _mm_add_ps(r, _mm_mul_ps(*s, a)); - } - - sampleOut += ((float*)(&r))[0]; - sampleOut += ((float*)(&r))[1]; - sampleOut += ((float*)(&r))[2]; - sampleOut += ((float*)(&r))[3]; - - iWindow += windowWidth4 * 4; - } - else -#endif -#if defined(MAL_SUPPORT_NEON) - if (pSRC->useNEON) { - float32x4_t t = vmovq_n_f32((timeIn - iTimeInF)); - float32x4_t r = vmovq_n_f32(0); - - mal_int32 windowWidth4 = windowWidthSIMD2 >> 2; - for (mal_int32 iWindow4 = 0; iWindow4 < windowWidth4; iWindow4 += 1) { - float32x4_t* s = (float32x4_t*)windowSamples + iWindow4; - float32x4_t* w = (float32x4_t*)iWindowF + iWindow4; - - float32x4_t a = mal_src_sinc__interpolation_factor__neon(pSRC, vsubq_f32(t, *w)); - r = vaddq_f32(r, vmulq_f32(*s, a)); - } - - sampleOut += ((float*)(&r))[0]; - sampleOut += ((float*)(&r))[1]; - sampleOut += ((float*)(&r))[2]; - sampleOut += ((float*)(&r))[3]; - - iWindow += windowWidth4 * 4; - } - else -#endif - { - iWindow += 1; // The first one is a dummy for SIMD alignment purposes. Skip it. - } - - // Non-SIMD/Reference implementation. - float t = (timeIn - iTimeIn); - for (; iWindow < windowWidth2; iWindow += 1) { - float s = windowSamples[iWindow]; - float w = iWindowF[iWindow]; - - float a = mal_src_sinc__interpolation_factor(pSRC, (t - w)); - float r = s * a; - - sampleOut += r; - } - - ppNextSamplesOut[iChannel][iSample] = (float)sampleOut; - - timeIn += factor; - } - - ppNextSamplesOut[iChannel] += outputFramesToRead; - } - - totalOutputFramesRead += outputFramesToRead; - - mal_uint32 prevWindowPosInSamples = pSRC->sinc.windowPosInSamples; - - pSRC->sinc.timeIn += (outputFramesToRead * factor); - pSRC->sinc.windowPosInSamples = (mal_uint32)pSRC->sinc.timeIn; - pSRC->sinc.inputFrameCount -= pSRC->sinc.windowPosInSamples - prevWindowPosInSamples; - - // If the window has reached a point where we cannot read a whole output sample it needs to be moved back to the start. - mal_uint32 availableOutputFrames = (mal_uint32)((timeInEnd - pSRC->sinc.timeIn) * inverseFactor); - - if (availableOutputFrames == 0) { - size_t samplesToMove = mal_countof(pSRC->sinc.input[0]) - pSRC->sinc.windowPosInSamples; - - pSRC->sinc.timeIn -= mal_floorf(pSRC->sinc.timeIn); - pSRC->sinc.windowPosInSamples = 0; - - // Move everything from the end of the cache up to the front. - for (mal_uint32 iChannel = 0; iChannel < pSRC->config.channels; iChannel += 1) { - memmove(pSRC->sinc.input[iChannel], pSRC->sinc.input[iChannel] + mal_countof(pSRC->sinc.input[iChannel]) - samplesToMove, samplesToMove * sizeof(*pSRC->sinc.input[iChannel])); - } - } - - // Read more data from the client if required. - if (pSRC->isEndOfInputLoaded) { - pSRC->isEndOfInputLoaded = MAL_FALSE; - break; - } - - // Everything beyond this point is reloading. If we're at the end of the input data we do _not_ want to try reading any more in this function call. If the - // caller wants to keep trying, they can reload their internal data sources and call this function again. We should never be - mal_assert(pSRC->isEndOfInputLoaded == MAL_FALSE); - - if (pSRC->sinc.inputFrameCount <= pSRC->config.sinc.windowWidth || availableOutputFrames == 0) { - float* ppInputDst[MAL_MAX_CHANNELS] = {0}; - for (mal_uint32 iChannel = 0; iChannel < pSRC->config.channels; iChannel += 1) { - ppInputDst[iChannel] = pSRC->sinc.input[iChannel] + pSRC->config.sinc.windowWidth + pSRC->sinc.inputFrameCount; - } - - // Now read data from the client. - mal_uint32 framesToReadFromClient = mal_countof(pSRC->sinc.input[0]) - (pSRC->config.sinc.windowWidth + pSRC->sinc.inputFrameCount); - - mal_uint32 framesReadFromClient = 0; - if (framesToReadFromClient > 0) { - framesReadFromClient = pSRC->config.onReadDeinterleaved(pSRC, framesToReadFromClient, (void**)ppInputDst, pUserData); - } - - if (framesReadFromClient != framesToReadFromClient) { - pSRC->isEndOfInputLoaded = MAL_TRUE; - } else { - pSRC->isEndOfInputLoaded = MAL_FALSE; - } - - if (framesReadFromClient != 0) { - pSRC->sinc.inputFrameCount += framesReadFromClient; - } else { - // We couldn't get anything more from the client. If no more output samples can be computed from the available input samples - // we need to return. - if (pSRC->config.neverConsumeEndOfInput) { - if ((pSRC->sinc.inputFrameCount * inverseFactor) <= pSRC->config.sinc.windowWidth) { - break; - } - } else { - if ((pSRC->sinc.inputFrameCount * inverseFactor) < 1) { - break; - } - } - } - - // Anything left over in the cache must be set to zero. - mal_uint32 leftoverFrames = mal_countof(pSRC->sinc.input[0]) - (pSRC->config.sinc.windowWidth + pSRC->sinc.inputFrameCount); - if (leftoverFrames > 0) { - for (mal_uint32 iChannel = 0; iChannel < pSRC->config.channels; iChannel += 1) { - mal_zero_memory(pSRC->sinc.input[iChannel] + pSRC->config.sinc.windowWidth + pSRC->sinc.inputFrameCount, leftoverFrames * sizeof(float)); - } - } - } - } - - return totalOutputFramesRead; -} - - - -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// FORMAT CONVERSION -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -void mal_pcm_convert(void* pOut, mal_format formatOut, const void* pIn, mal_format formatIn, mal_uint64 sampleCount, mal_dither_mode ditherMode) -{ - if (formatOut == formatIn) { - mal_copy_memory_64(pOut, pIn, sampleCount * mal_get_bytes_per_sample(formatOut)); - return; - } - - switch (formatIn) - { - case mal_format_u8: - { - switch (formatOut) - { - case mal_format_s16: mal_pcm_u8_to_s16(pOut, pIn, sampleCount, ditherMode); return; - case mal_format_s24: mal_pcm_u8_to_s24(pOut, pIn, sampleCount, ditherMode); return; - case mal_format_s32: mal_pcm_u8_to_s32(pOut, pIn, sampleCount, ditherMode); return; - case mal_format_f32: mal_pcm_u8_to_f32(pOut, pIn, sampleCount, ditherMode); return; - default: break; - } - } break; - - case mal_format_s16: - { - switch (formatOut) - { - case mal_format_u8: mal_pcm_s16_to_u8( pOut, pIn, sampleCount, ditherMode); return; - case mal_format_s24: mal_pcm_s16_to_s24(pOut, pIn, sampleCount, ditherMode); return; - case mal_format_s32: mal_pcm_s16_to_s32(pOut, pIn, sampleCount, ditherMode); return; - case mal_format_f32: mal_pcm_s16_to_f32(pOut, pIn, sampleCount, ditherMode); return; - default: break; - } - } break; - - case mal_format_s24: - { - switch (formatOut) - { - case mal_format_u8: mal_pcm_s24_to_u8( pOut, pIn, sampleCount, ditherMode); return; - case mal_format_s16: mal_pcm_s24_to_s16(pOut, pIn, sampleCount, ditherMode); return; - case mal_format_s32: mal_pcm_s24_to_s32(pOut, pIn, sampleCount, ditherMode); return; - case mal_format_f32: mal_pcm_s24_to_f32(pOut, pIn, sampleCount, ditherMode); return; - default: break; - } - } break; - - case mal_format_s32: - { - switch (formatOut) - { - case mal_format_u8: mal_pcm_s32_to_u8( pOut, pIn, sampleCount, ditherMode); return; - case mal_format_s16: mal_pcm_s32_to_s16(pOut, pIn, sampleCount, ditherMode); return; - case mal_format_s24: mal_pcm_s32_to_s24(pOut, pIn, sampleCount, ditherMode); return; - case mal_format_f32: mal_pcm_s32_to_f32(pOut, pIn, sampleCount, ditherMode); return; - default: break; - } - } break; - - case mal_format_f32: - { - switch (formatOut) - { - case mal_format_u8: mal_pcm_f32_to_u8( pOut, pIn, sampleCount, ditherMode); return; - case mal_format_s16: mal_pcm_f32_to_s16(pOut, pIn, sampleCount, ditherMode); return; - case mal_format_s24: mal_pcm_f32_to_s24(pOut, pIn, sampleCount, ditherMode); return; - case mal_format_s32: mal_pcm_f32_to_s32(pOut, pIn, sampleCount, ditherMode); return; - default: break; - } - } break; - - default: break; - } -} - -void mal_deinterleave_pcm_frames(mal_format format, mal_uint32 channels, mal_uint64 frameCount, const void* pInterleavedPCMFrames, void** ppDeinterleavedPCMFrames) -{ - if (pInterleavedPCMFrames == NULL || ppDeinterleavedPCMFrames == NULL) { - return; // Invalid args. - } - - // For efficiency we do this per format. - switch (format) { - case mal_format_s16: - { - const mal_int16* pSrcS16 = (const mal_int16*)pInterleavedPCMFrames; - for (mal_uint64 iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) { - for (mal_uint32 iChannel = 0; iChannel < channels; ++iChannel) { - mal_int16* pDstS16 = (mal_int16*)ppDeinterleavedPCMFrames[iChannel]; - pDstS16[iPCMFrame] = pSrcS16[iPCMFrame*channels+iChannel]; - } - } - } break; - - case mal_format_f32: - { - const float* pSrcF32 = (const float*)pInterleavedPCMFrames; - for (mal_uint64 iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) { - for (mal_uint32 iChannel = 0; iChannel < channels; ++iChannel) { - float* pDstF32 = (float*)ppDeinterleavedPCMFrames[iChannel]; - pDstF32[iPCMFrame] = pSrcF32[iPCMFrame*channels+iChannel]; - } - } - } break; - - default: - { - mal_uint32 sampleSizeInBytes = mal_get_bytes_per_sample(format); - - for (mal_uint64 iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) { - for (mal_uint32 iChannel = 0; iChannel < channels; ++iChannel) { - void* pDst = mal_offset_ptr(ppDeinterleavedPCMFrames[iChannel], iPCMFrame*sampleSizeInBytes); - const void* pSrc = mal_offset_ptr(pInterleavedPCMFrames, (iPCMFrame*channels+iChannel)*sampleSizeInBytes); - memcpy(pDst, pSrc, sampleSizeInBytes); - } - } - } break; - } -} - -void mal_interleave_pcm_frames(mal_format format, mal_uint32 channels, mal_uint64 frameCount, const void** ppDeinterleavedPCMFrames, void* pInterleavedPCMFrames) -{ - switch (format) - { - case mal_format_s16: - { - mal_int16* pDstS16 = (mal_int16*)pInterleavedPCMFrames; - for (mal_uint64 iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) { - for (mal_uint32 iChannel = 0; iChannel < channels; ++iChannel) { - const mal_int16* pSrcS16 = (const mal_int16*)ppDeinterleavedPCMFrames[iChannel]; - pDstS16[iPCMFrame*channels+iChannel] = pSrcS16[iPCMFrame]; - } - } - } break; - - case mal_format_f32: - { - float* pDstF32 = (float*)pInterleavedPCMFrames; - for (mal_uint64 iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) { - for (mal_uint32 iChannel = 0; iChannel < channels; ++iChannel) { - const float* pSrcF32 = (const float*)ppDeinterleavedPCMFrames[iChannel]; - pDstF32[iPCMFrame*channels+iChannel] = pSrcF32[iPCMFrame]; - } - } - } break; - - default: - { - mal_uint32 sampleSizeInBytes = mal_get_bytes_per_sample(format); - - for (mal_uint64 iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) { - for (mal_uint32 iChannel = 0; iChannel < channels; ++iChannel) { - void* pDst = mal_offset_ptr(pInterleavedPCMFrames, (iPCMFrame*channels+iChannel)*sampleSizeInBytes); - const void* pSrc = mal_offset_ptr(ppDeinterleavedPCMFrames[iChannel], iPCMFrame*sampleSizeInBytes); - memcpy(pDst, pSrc, sampleSizeInBytes); - } - } - } break; - } -} - - - -typedef struct -{ - mal_dsp* pDSP; - void* pUserDataForClient; -} mal_dsp_callback_data; - -mal_uint32 mal_dsp__pre_format_converter_on_read(mal_format_converter* pConverter, mal_uint32 frameCount, void* pFramesOut, void* pUserData) -{ - (void)pConverter; - - mal_dsp_callback_data* pData = (mal_dsp_callback_data*)pUserData; - mal_assert(pData != NULL); - - mal_dsp* pDSP = pData->pDSP; - mal_assert(pDSP != NULL); - - return pDSP->onRead(pDSP, frameCount, pFramesOut, pData->pUserDataForClient); -} - -mal_uint32 mal_dsp__post_format_converter_on_read(mal_format_converter* pConverter, mal_uint32 frameCount, void* pFramesOut, void* pUserData) -{ - (void)pConverter; - - mal_dsp_callback_data* pData = (mal_dsp_callback_data*)pUserData; - mal_assert(pData != NULL); - - mal_dsp* pDSP = pData->pDSP; - mal_assert(pDSP != NULL); - - // When this version of this callback is used it means we're reading directly from the client. - mal_assert(pDSP->isPreFormatConversionRequired == MAL_FALSE); - mal_assert(pDSP->isChannelRoutingRequired == MAL_FALSE); - mal_assert(pDSP->isSRCRequired == MAL_FALSE); - - return pDSP->onRead(pDSP, frameCount, pFramesOut, pData->pUserDataForClient); -} - -mal_uint32 mal_dsp__post_format_converter_on_read_deinterleaved(mal_format_converter* pConverter, mal_uint32 frameCount, void** ppSamplesOut, void* pUserData) -{ - (void)pConverter; - - mal_dsp_callback_data* pData = (mal_dsp_callback_data*)pUserData; - mal_assert(pData != NULL); - - mal_dsp* pDSP = pData->pDSP; - mal_assert(pDSP != NULL); - - if (!pDSP->isChannelRoutingAtStart) { - return (mal_uint32)mal_channel_router_read_deinterleaved(&pDSP->channelRouter, frameCount, ppSamplesOut, pUserData); - } else { - if (pDSP->isSRCRequired) { - return (mal_uint32)mal_src_read_deinterleaved(&pDSP->src, frameCount, ppSamplesOut, pUserData); - } else { - return (mal_uint32)mal_channel_router_read_deinterleaved(&pDSP->channelRouter, frameCount, ppSamplesOut, pUserData); - } - } -} - -mal_uint32 mal_dsp__src_on_read_deinterleaved(mal_src* pSRC, mal_uint32 frameCount, void** ppSamplesOut, void* pUserData) -{ - (void)pSRC; - - mal_dsp_callback_data* pData = (mal_dsp_callback_data*)pUserData; - mal_assert(pData != NULL); - - mal_dsp* pDSP = pData->pDSP; - mal_assert(pDSP != NULL); - - // If the channel routing stage is at the front we need to read from that. Otherwise we read from the pre format converter. - if (pDSP->isChannelRoutingAtStart) { - return (mal_uint32)mal_channel_router_read_deinterleaved(&pDSP->channelRouter, frameCount, ppSamplesOut, pUserData); - } else { - return (mal_uint32)mal_format_converter_read_deinterleaved(&pDSP->formatConverterIn, frameCount, ppSamplesOut, pUserData); - } -} - -mal_uint32 mal_dsp__channel_router_on_read_deinterleaved(mal_channel_router* pRouter, mal_uint32 frameCount, void** ppSamplesOut, void* pUserData) -{ - (void)pRouter; - - mal_dsp_callback_data* pData = (mal_dsp_callback_data*)pUserData; - mal_assert(pData != NULL); - - mal_dsp* pDSP = pData->pDSP; - mal_assert(pDSP != NULL); - - // If the channel routing stage is at the front of the pipeline we read from the pre format converter. Otherwise we read from the sample rate converter. - if (pDSP->isChannelRoutingAtStart) { - return (mal_uint32)mal_format_converter_read_deinterleaved(&pDSP->formatConverterIn, frameCount, ppSamplesOut, pUserData); - } else { - if (pDSP->isSRCRequired) { - return (mal_uint32)mal_src_read_deinterleaved(&pDSP->src, frameCount, ppSamplesOut, pUserData); - } else { - return (mal_uint32)mal_format_converter_read_deinterleaved(&pDSP->formatConverterIn, frameCount, ppSamplesOut, pUserData); - } - } -} - -mal_result mal_dsp_init(const mal_dsp_config* pConfig, mal_dsp* pDSP) -{ - if (pDSP == NULL) { - return MAL_INVALID_ARGS; - } - - mal_zero_object(pDSP); - pDSP->onRead = pConfig->onRead; - pDSP->pUserData = pConfig->pUserData; - pDSP->isDynamicSampleRateAllowed = pConfig->allowDynamicSampleRate; - - - // In general, this is the pipeline used for data conversion. Note that this can actually change which is explained later. - // - // Pre Format Conversion -> Sample Rate Conversion -> Channel Routing -> Post Format Conversion - // - // Pre Format Conversion - // --------------------- - // This is where the sample data is converted to a format that's usable by the later stages in the pipeline. Input data - // is converted to deinterleaved floating-point. - // - // Channel Routing - // --------------- - // Channel routing is where stereo is converted to 5.1, mono is converted to stereo, etc. This stage depends on the - // pre format conversion stage. - // - // Sample Rate Conversion - // ---------------------- - // Sample rate conversion depends on the pre format conversion stage and as the name implies performs sample rate conversion. - // - // Post Format Conversion - // ---------------------- - // This stage is where our deinterleaved floating-point data from the previous stages are converted to the requested output - // format. - // - // - // Optimizations - // ------------- - // Sometimes the conversion pipeline is rearranged for efficiency. The first obvious optimization is to eliminate unnecessary - // stages in the pipeline. When no channel routing nor sample rate conversion is necessary, the entire pipeline is optimized - // down to just this: - // - // Post Format Conversion - // - // When sample rate conversion is not unnecessary: - // - // Pre Format Conversion -> Channel Routing -> Post Format Conversion - // - // When channel routing is unnecessary: - // - // Pre Format Conversion -> Sample Rate Conversion -> Post Format Conversion - // - // A slightly less obvious optimization is used depending on whether or not we are increasing or decreasing the number of - // channels. Because everything in the pipeline works on a per-channel basis, the efficiency of the pipeline is directly - // proportionate to the number of channels that need to be processed. Therefore, it's can be more efficient to move the - // channel conversion stage to an earlier or later stage. When the channel count is being reduced, we move the channel - // conversion stage to the start of the pipeline so that later stages can work on a smaller number of channels at a time. - // Otherwise, we move the channel conversion stage to the end of the pipeline. When reducing the channel count, the pipeline - // will look like this: - // - // Pre Format Conversion -> Channel Routing -> Sample Rate Conversion -> Post Format Conversion - // - // Notice how the Channel Routing and Sample Rate Conversion stages are swapped so that the SRC stage has less data to process. - - // First we need to determine what's required and what's not. - if (pConfig->sampleRateIn != pConfig->sampleRateOut || pConfig->allowDynamicSampleRate) { - pDSP->isSRCRequired = MAL_TRUE; - } - if (pConfig->channelsIn != pConfig->channelsOut || !mal_channel_map_equal(pConfig->channelsIn, pConfig->channelMapIn, pConfig->channelMapOut)) { - pDSP->isChannelRoutingRequired = MAL_TRUE; - } - - // If neither a sample rate conversion nor channel conversion is necessary we can skip the pre format conversion. - if (!pDSP->isSRCRequired && !pDSP->isChannelRoutingRequired) { - // We don't need a pre format conversion stage, but we may still need a post format conversion stage. - if (pConfig->formatIn != pConfig->formatOut) { - pDSP->isPostFormatConversionRequired = MAL_TRUE; - } - } else { - pDSP->isPreFormatConversionRequired = MAL_TRUE; - pDSP->isPostFormatConversionRequired = MAL_TRUE; - } - - // Use a passthrough if none of the stages are being used. - if (!pDSP->isPreFormatConversionRequired && !pDSP->isPostFormatConversionRequired && !pDSP->isChannelRoutingRequired && !pDSP->isSRCRequired) { - pDSP->isPassthrough = MAL_TRUE; - } - - // Move the channel conversion stage to the start of the pipeline if we are reducing the channel count. - if (pConfig->channelsOut < pConfig->channelsIn) { - pDSP->isChannelRoutingAtStart = MAL_TRUE; - } - - - // We always initialize every stage of the pipeline regardless of whether or not the stage is used because it simplifies - // a few things when it comes to dynamically changing properties post-initialization. - mal_result result = MAL_SUCCESS; - - // Pre format conversion. - { - mal_format_converter_config preFormatConverterConfig = mal_format_converter_config_init( - pConfig->formatIn, - mal_format_f32, - pConfig->channelsIn, - mal_dsp__pre_format_converter_on_read, - pDSP - ); - preFormatConverterConfig.ditherMode = pConfig->ditherMode; - preFormatConverterConfig.noSSE2 = pConfig->noSSE2; - preFormatConverterConfig.noAVX2 = pConfig->noAVX2; - preFormatConverterConfig.noAVX512 = pConfig->noAVX512; - preFormatConverterConfig.noNEON = pConfig->noNEON; - - result = mal_format_converter_init(&preFormatConverterConfig, &pDSP->formatConverterIn); - if (result != MAL_SUCCESS) { - return result; - } - } - - // Post format conversion. The exact configuration for this depends on whether or not we are reading data directly from the client - // or from an earlier stage in the pipeline. - { - mal_format_converter_config postFormatConverterConfig = mal_format_converter_config_init_new(); - postFormatConverterConfig.formatIn = pConfig->formatIn; - postFormatConverterConfig.formatOut = pConfig->formatOut; - postFormatConverterConfig.channels = pConfig->channelsOut; - postFormatConverterConfig.ditherMode = pConfig->ditherMode; - postFormatConverterConfig.noSSE2 = pConfig->noSSE2; - postFormatConverterConfig.noAVX2 = pConfig->noAVX2; - postFormatConverterConfig.noAVX512 = pConfig->noAVX512; - postFormatConverterConfig.noNEON = pConfig->noNEON; - if (pDSP->isPreFormatConversionRequired) { - postFormatConverterConfig.onReadDeinterleaved = mal_dsp__post_format_converter_on_read_deinterleaved; - postFormatConverterConfig.formatIn = mal_format_f32; - } else { - postFormatConverterConfig.onRead = mal_dsp__post_format_converter_on_read; - } - - result = mal_format_converter_init(&postFormatConverterConfig, &pDSP->formatConverterOut); - if (result != MAL_SUCCESS) { - return result; - } - } - - // SRC - { - mal_src_config srcConfig = mal_src_config_init( - pConfig->sampleRateIn, - pConfig->sampleRateOut, - ((pConfig->channelsIn < pConfig->channelsOut) ? pConfig->channelsIn : pConfig->channelsOut), - mal_dsp__src_on_read_deinterleaved, - pDSP - ); - srcConfig.algorithm = pConfig->srcAlgorithm; - srcConfig.neverConsumeEndOfInput = pConfig->neverConsumeEndOfInput; - srcConfig.noSSE2 = pConfig->noSSE2; - srcConfig.noAVX2 = pConfig->noAVX2; - srcConfig.noAVX512 = pConfig->noAVX512; - srcConfig.noNEON = pConfig->noNEON; - mal_copy_memory(&srcConfig.sinc, &pConfig->sinc, sizeof(pConfig->sinc)); - - result = mal_src_init(&srcConfig, &pDSP->src); - if (result != MAL_SUCCESS) { - return result; - } - } - - // Channel conversion - { - mal_channel_router_config routerConfig = mal_channel_router_config_init( - pConfig->channelsIn, - pConfig->channelMapIn, - pConfig->channelsOut, - pConfig->channelMapOut, - pConfig->channelMixMode, - mal_dsp__channel_router_on_read_deinterleaved, - pDSP); - routerConfig.noSSE2 = pConfig->noSSE2; - routerConfig.noAVX2 = pConfig->noAVX2; - routerConfig.noAVX512 = pConfig->noAVX512; - routerConfig.noNEON = pConfig->noNEON; - - result = mal_channel_router_init(&routerConfig, &pDSP->channelRouter); - if (result != MAL_SUCCESS) { - return result; - } - } - - return MAL_SUCCESS; -} - - -mal_result mal_dsp_refresh_sample_rate(mal_dsp* pDSP) -{ - // The SRC stage will already have been initialized so we can just set it there. - mal_src_set_input_sample_rate(&pDSP->src, pDSP->src.config.sampleRateIn); - mal_src_set_output_sample_rate(&pDSP->src, pDSP->src.config.sampleRateOut); - - return MAL_SUCCESS; -} - -mal_result mal_dsp_set_input_sample_rate(mal_dsp* pDSP, mal_uint32 sampleRateIn) -{ - if (pDSP == NULL) { - return MAL_INVALID_ARGS; - } - - // Must have a sample rate of > 0. - if (sampleRateIn == 0) { - return MAL_INVALID_ARGS; - } - - // Must have been initialized with allowDynamicSampleRate. - if (!pDSP->isDynamicSampleRateAllowed) { - return MAL_INVALID_OPERATION; - } - - mal_atomic_exchange_32(&pDSP->src.config.sampleRateIn, sampleRateIn); - return mal_dsp_refresh_sample_rate(pDSP); -} - -mal_result mal_dsp_set_output_sample_rate(mal_dsp* pDSP, mal_uint32 sampleRateOut) -{ - if (pDSP == NULL) { - return MAL_INVALID_ARGS; - } - - // Must have a sample rate of > 0. - if (sampleRateOut == 0) { - return MAL_INVALID_ARGS; - } - - // Must have been initialized with allowDynamicSampleRate. - if (!pDSP->isDynamicSampleRateAllowed) { - return MAL_INVALID_OPERATION; - } - - mal_atomic_exchange_32(&pDSP->src.config.sampleRateOut, sampleRateOut); - return mal_dsp_refresh_sample_rate(pDSP); -} - -mal_result mal_dsp_set_sample_rate(mal_dsp* pDSP, mal_uint32 sampleRateIn, mal_uint32 sampleRateOut) -{ - if (pDSP == NULL) { - return MAL_INVALID_ARGS; - } - - // Must have a sample rate of > 0. - if (sampleRateIn == 0 || sampleRateOut == 0) { - return MAL_INVALID_ARGS; - } - - // Must have been initialized with allowDynamicSampleRate. - if (!pDSP->isDynamicSampleRateAllowed) { - return MAL_INVALID_OPERATION; - } - - mal_atomic_exchange_32(&pDSP->src.config.sampleRateIn, sampleRateIn); - mal_atomic_exchange_32(&pDSP->src.config.sampleRateOut, sampleRateOut); - - return mal_dsp_refresh_sample_rate(pDSP); -} - -mal_uint64 mal_dsp_read(mal_dsp* pDSP, mal_uint64 frameCount, void* pFramesOut, void* pUserData) -{ - if (pDSP == NULL || pFramesOut == NULL) return 0; - - // Fast path. - if (pDSP->isPassthrough) { - if (frameCount <= 0xFFFFFFFF) { - return (mal_uint32)pDSP->onRead(pDSP, (mal_uint32)frameCount, pFramesOut, pUserData); - } else { - mal_uint8* pNextFramesOut = (mal_uint8*)pFramesOut; - - mal_uint64 totalFramesRead = 0; - while (totalFramesRead < frameCount) { - mal_uint64 framesRemaining = (frameCount - totalFramesRead); - mal_uint64 framesToReadRightNow = framesRemaining; - if (framesToReadRightNow > 0xFFFFFFFF) { - framesToReadRightNow = 0xFFFFFFFF; - } - - mal_uint32 framesRead = pDSP->onRead(pDSP, (mal_uint32)framesToReadRightNow, pNextFramesOut, pUserData); - if (framesRead == 0) { - break; - } - - pNextFramesOut += framesRead * pDSP->channelRouter.config.channelsOut * mal_get_bytes_per_sample(pDSP->formatConverterOut.config.formatOut); - totalFramesRead += framesRead; - } - - return totalFramesRead; - } - } - - // Slower path. The real work is done here. To do this all we need to do is read from the last stage in the pipeline. - mal_assert(pDSP->isPostFormatConversionRequired == MAL_TRUE); - - mal_dsp_callback_data data; - data.pDSP = pDSP; - data.pUserDataForClient = pUserData; - return mal_format_converter_read(&pDSP->formatConverterOut, frameCount, pFramesOut, &data); -} - - -typedef struct -{ - const void* pDataIn; - mal_format formatIn; - mal_uint32 channelsIn; - mal_uint64 totalFrameCount; - mal_uint64 iNextFrame; - mal_bool32 isFeedingZeros; // When set to true, feeds the DSP zero samples. -} mal_convert_frames__data; - -mal_uint32 mal_convert_frames__on_read(mal_dsp* pDSP, mal_uint32 frameCount, void* pFramesOut, void* pUserData) -{ - (void)pDSP; - - mal_convert_frames__data* pData = (mal_convert_frames__data*)pUserData; - mal_assert(pData != NULL); - mal_assert(pData->totalFrameCount >= pData->iNextFrame); - - mal_uint32 framesToRead = frameCount; - mal_uint64 framesRemaining = (pData->totalFrameCount - pData->iNextFrame); - if (framesToRead > framesRemaining) { - framesToRead = (mal_uint32)framesRemaining; - } - - mal_uint32 frameSizeInBytes = mal_get_bytes_per_frame(pData->formatIn, pData->channelsIn); - - if (!pData->isFeedingZeros) { - mal_copy_memory(pFramesOut, (const mal_uint8*)pData->pDataIn + (frameSizeInBytes * pData->iNextFrame), frameSizeInBytes * framesToRead); - } else { - mal_zero_memory(pFramesOut, frameSizeInBytes * framesToRead); - } - - pData->iNextFrame += framesToRead; - return framesToRead; -} - -mal_dsp_config mal_dsp_config_init_new() -{ - mal_dsp_config config; - mal_zero_object(&config); - - return config; -} - -mal_dsp_config mal_dsp_config_init(mal_format formatIn, mal_uint32 channelsIn, mal_uint32 sampleRateIn, mal_format formatOut, mal_uint32 channelsOut, mal_uint32 sampleRateOut, mal_dsp_read_proc onRead, void* pUserData) -{ - return mal_dsp_config_init_ex(formatIn, channelsIn, sampleRateIn, NULL, formatOut, channelsOut, sampleRateOut, NULL, onRead, pUserData); -} - -mal_dsp_config mal_dsp_config_init_ex(mal_format formatIn, mal_uint32 channelsIn, mal_uint32 sampleRateIn, mal_channel channelMapIn[MAL_MAX_CHANNELS], mal_format formatOut, mal_uint32 channelsOut, mal_uint32 sampleRateOut, mal_channel channelMapOut[MAL_MAX_CHANNELS], mal_dsp_read_proc onRead, void* pUserData) -{ - mal_dsp_config config; - mal_zero_object(&config); - config.formatIn = formatIn; - config.channelsIn = channelsIn; - config.sampleRateIn = sampleRateIn; - config.formatOut = formatOut; - config.channelsOut = channelsOut; - config.sampleRateOut = sampleRateOut; - if (channelMapIn != NULL) { - mal_copy_memory(config.channelMapIn, channelMapIn, sizeof(config.channelMapIn)); - } - if (channelMapOut != NULL) { - mal_copy_memory(config.channelMapOut, channelMapOut, sizeof(config.channelMapOut)); - } - config.onRead = onRead; - config.pUserData = pUserData; - - return config; -} - - - -mal_uint64 mal_convert_frames(void* pOut, mal_format formatOut, mal_uint32 channelsOut, mal_uint32 sampleRateOut, const void* pIn, mal_format formatIn, mal_uint32 channelsIn, mal_uint32 sampleRateIn, mal_uint64 frameCountIn) -{ - mal_channel channelMapOut[MAL_MAX_CHANNELS]; - mal_get_standard_channel_map(mal_standard_channel_map_default, channelsOut, channelMapOut); - - mal_channel channelMapIn[MAL_MAX_CHANNELS]; - mal_get_standard_channel_map(mal_standard_channel_map_default, channelsIn, channelMapIn); - - return mal_convert_frames_ex(pOut, formatOut, channelsOut, sampleRateOut, channelMapOut, pIn, formatIn, channelsIn, sampleRateIn, channelMapIn, frameCountIn); -} - -mal_uint64 mal_convert_frames_ex(void* pOut, mal_format formatOut, mal_uint32 channelsOut, mal_uint32 sampleRateOut, mal_channel channelMapOut[MAL_MAX_CHANNELS], const void* pIn, mal_format formatIn, mal_uint32 channelsIn, mal_uint32 sampleRateIn, mal_channel channelMapIn[MAL_MAX_CHANNELS], mal_uint64 frameCountIn) -{ - if (frameCountIn == 0) { - return 0; - } - - mal_uint64 frameCountOut = mal_calculate_frame_count_after_src(sampleRateOut, sampleRateIn, frameCountIn); - if (pOut == NULL) { - return frameCountOut; - } - - mal_convert_frames__data data; - data.pDataIn = pIn; - data.formatIn = formatIn; - data.channelsIn = channelsIn; - data.totalFrameCount = frameCountIn; - data.iNextFrame = 0; - data.isFeedingZeros = MAL_FALSE; - - mal_dsp_config config; - mal_zero_object(&config); - - config.formatIn = formatIn; - config.channelsIn = channelsIn; - config.sampleRateIn = sampleRateIn; - if (channelMapIn != NULL) { - mal_channel_map_copy(config.channelMapIn, channelMapIn, channelsIn); - } else { - mal_get_standard_channel_map(mal_standard_channel_map_default, config.channelsIn, config.channelMapIn); - } - - config.formatOut = formatOut; - config.channelsOut = channelsOut; - config.sampleRateOut = sampleRateOut; - if (channelMapOut != NULL) { - mal_channel_map_copy(config.channelMapOut, channelMapOut, channelsOut); - } else { - mal_get_standard_channel_map(mal_standard_channel_map_default, config.channelsOut, config.channelMapOut); - } - - config.onRead = mal_convert_frames__on_read; - config.pUserData = &data; - - mal_dsp dsp; - if (mal_dsp_init(&config, &dsp) != MAL_SUCCESS) { - return 0; - } - - // Always output our computed frame count. There is a chance the sample rate conversion routine may not output the last sample - // due to precision issues with 32-bit floats, in which case we should feed the DSP zero samples so it can generate that last - // frame. - mal_uint64 totalFramesRead = mal_dsp_read(&dsp, frameCountOut, pOut, dsp.pUserData); - if (totalFramesRead < frameCountOut) { - mal_uint32 bpf = mal_get_bytes_per_frame(formatIn, channelsIn); - - data.isFeedingZeros = MAL_TRUE; - data.totalFrameCount = 0xFFFFFFFFFFFFFFFF; - data.pDataIn = NULL; - - while (totalFramesRead < frameCountOut) { - mal_uint64 framesToRead = (frameCountOut - totalFramesRead); - mal_assert(framesToRead > 0); - - mal_uint64 framesJustRead = mal_dsp_read(&dsp, framesToRead, mal_offset_ptr(pOut, totalFramesRead * bpf), dsp.pUserData); - totalFramesRead += framesJustRead; - - if (framesJustRead < framesToRead) { - break; - } - } - - // At this point we should have output every sample, but just to be super duper sure, just fill the rest with zeros. - if (totalFramesRead < frameCountOut) { - mal_zero_memory_64(mal_offset_ptr(pOut, totalFramesRead * bpf), ((frameCountOut - totalFramesRead) * bpf)); - totalFramesRead = frameCountOut; - } - } - - mal_assert(totalFramesRead == frameCountOut); - return totalFramesRead; -} - - - - -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Miscellaneous Helpers -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -void* mal_malloc(size_t sz) -{ - return MAL_MALLOC(sz); -} - -void* mal_realloc(void* p, size_t sz) -{ - return MAL_REALLOC(p, sz); -} - -void mal_free(void* p) -{ - MAL_FREE(p); -} - -void* mal_aligned_malloc(size_t sz, size_t alignment) -{ - if (alignment == 0) { - return 0; - } - - size_t extraBytes = alignment-1 + sizeof(void*); - - void* pUnaligned = mal_malloc(sz + extraBytes); - if (pUnaligned == NULL) { - return NULL; - } - - void* pAligned = (void*)(((mal_uintptr)pUnaligned + extraBytes) & ~((mal_uintptr)(alignment-1))); - ((void**)pAligned)[-1] = pUnaligned; - - return pAligned; -} - -void mal_aligned_free(void* p) -{ - mal_free(((void**)p)[-1]); -} - -const char* mal_get_format_name(mal_format format) -{ - switch (format) - { - case mal_format_unknown: return "Unknown"; - case mal_format_u8: return "8-bit Unsigned Integer"; - case mal_format_s16: return "16-bit Signed Integer"; - case mal_format_s24: return "24-bit Signed Integer (Tightly Packed)"; - case mal_format_s32: return "32-bit Signed Integer"; - case mal_format_f32: return "32-bit IEEE Floating Point"; - default: return "Invalid"; - } -} - -void mal_blend_f32(float* pOut, float* pInA, float* pInB, float factor, mal_uint32 channels) -{ - for (mal_uint32 i = 0; i < channels; ++i) { - pOut[i] = mal_mix_f32(pInA[i], pInB[i], factor); - } -} - - -mal_uint32 mal_get_bytes_per_sample(mal_format format) -{ - mal_uint32 sizes[] = { - 0, // unknown - 1, // u8 - 2, // s16 - 3, // s24 - 4, // s32 - 4, // f32 - }; - return sizes[format]; -} - - -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// DECODING -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -#ifndef MAL_NO_DECODING - -mal_decoder_config mal_decoder_config_init(mal_format outputFormat, mal_uint32 outputChannels, mal_uint32 outputSampleRate) -{ - mal_decoder_config config; - mal_zero_object(&config); - config.format = outputFormat; - config.channels = outputChannels; - config.sampleRate = outputSampleRate; - mal_get_standard_channel_map(mal_standard_channel_map_default, config.channels, config.channelMap); - - return config; -} - -mal_decoder_config mal_decoder_config_init_copy(const mal_decoder_config* pConfig) -{ - mal_decoder_config config; - if (pConfig != NULL) { - config = *pConfig; - } else { - mal_zero_object(&config); - } - - return config; -} - -mal_result mal_decoder__init_dsp(mal_decoder* pDecoder, const mal_decoder_config* pConfig, mal_dsp_read_proc onRead) -{ - mal_assert(pDecoder != NULL); - - // Output format. - if (pConfig->format == mal_format_unknown) { - pDecoder->outputFormat = pDecoder->internalFormat; - } else { - pDecoder->outputFormat = pConfig->format; - } - - if (pConfig->channels == 0) { - pDecoder->outputChannels = pDecoder->internalChannels; - } else { - pDecoder->outputChannels = pConfig->channels; - } - - if (pConfig->sampleRate == 0) { - pDecoder->outputSampleRate = pDecoder->internalSampleRate; - } else { - pDecoder->outputSampleRate = pConfig->sampleRate; - } - - if (mal_channel_map_blank(pDecoder->outputChannels, pConfig->channelMap)) { - mal_get_standard_channel_map(mal_standard_channel_map_default, pDecoder->outputChannels, pDecoder->outputChannelMap); - } else { - mal_copy_memory(pDecoder->outputChannelMap, pConfig->channelMap, sizeof(pConfig->channelMap)); - } - - - // DSP. - mal_dsp_config dspConfig = mal_dsp_config_init_ex( - pDecoder->internalFormat, pDecoder->internalChannels, pDecoder->internalSampleRate, pDecoder->internalChannelMap, - pDecoder->outputFormat, pDecoder->outputChannels, pDecoder->outputSampleRate, pDecoder->outputChannelMap, - onRead, pDecoder); - dspConfig.channelMixMode = pConfig->channelMixMode; - dspConfig.ditherMode = pConfig->ditherMode; - dspConfig.srcAlgorithm = pConfig->srcAlgorithm; - dspConfig.sinc = pConfig->src.sinc; - - return mal_dsp_init(&dspConfig, &pDecoder->dsp); -} - -// WAV -#ifdef dr_wav_h -#define MAL_HAS_WAV - -size_t mal_decoder_internal_on_read__wav(void* pUserData, void* pBufferOut, size_t bytesToRead) -{ - mal_decoder* pDecoder = (mal_decoder*)pUserData; - mal_assert(pDecoder != NULL); - mal_assert(pDecoder->onRead != NULL); - - return pDecoder->onRead(pDecoder, pBufferOut, bytesToRead); -} - -drwav_bool32 mal_decoder_internal_on_seek__wav(void* pUserData, int offset, drwav_seek_origin origin) -{ - mal_decoder* pDecoder = (mal_decoder*)pUserData; - mal_assert(pDecoder != NULL); - mal_assert(pDecoder->onSeek != NULL); - - return pDecoder->onSeek(pDecoder, offset, (origin == drwav_seek_origin_start) ? mal_seek_origin_start : mal_seek_origin_current); -} - -mal_result mal_decoder_internal_on_seek_to_frame__wav(mal_decoder* pDecoder, mal_uint64 frameIndex) -{ - drwav* pWav = (drwav*)pDecoder->pInternalDecoder; - mal_assert(pWav != NULL); - - drwav_bool32 result = drwav_seek_to_pcm_frame(pWav, frameIndex); - if (result) { - return MAL_SUCCESS; - } else { - return MAL_ERROR; - } -} - -mal_result mal_decoder_internal_on_uninit__wav(mal_decoder* pDecoder) -{ - drwav_close((drwav*)pDecoder->pInternalDecoder); - return MAL_SUCCESS; -} - -mal_uint32 mal_decoder_internal_on_read_frames__wav(mal_dsp* pDSP, mal_uint32 frameCount, void* pSamplesOut, void* pUserData) -{ - (void)pDSP; - - mal_decoder* pDecoder = (mal_decoder*)pUserData; - mal_assert(pDecoder != NULL); - - drwav* pWav = (drwav*)pDecoder->pInternalDecoder; - mal_assert(pWav != NULL); - - switch (pDecoder->internalFormat) { - case mal_format_s16: return (mal_uint32)drwav_read_pcm_frames_s16(pWav, frameCount, (drwav_int16*)pSamplesOut); - case mal_format_s32: return (mal_uint32)drwav_read_pcm_frames_s32(pWav, frameCount, (drwav_int32*)pSamplesOut); - case mal_format_f32: return (mal_uint32)drwav_read_pcm_frames_f32(pWav, frameCount, (float*)pSamplesOut); - default: break; - } - - // Should never get here. If we do, it means the internal format was not set correctly at initialization time. - mal_assert(MAL_FALSE); - return 0; -} - -mal_result mal_decoder_init_wav__internal(const mal_decoder_config* pConfig, mal_decoder* pDecoder) -{ - mal_assert(pConfig != NULL); - mal_assert(pDecoder != NULL); - - // Try opening the decoder first. - drwav* pWav = drwav_open(mal_decoder_internal_on_read__wav, mal_decoder_internal_on_seek__wav, pDecoder); - if (pWav == NULL) { - return MAL_ERROR; - } - - // If we get here it means we successfully initialized the WAV decoder. We can now initialize the rest of the mal_decoder. - pDecoder->onSeekToFrame = mal_decoder_internal_on_seek_to_frame__wav; - pDecoder->onUninit = mal_decoder_internal_on_uninit__wav; - pDecoder->pInternalDecoder = pWav; - - // Try to be as optimal as possible for the internal format. If mini_al does not support a format we will fall back to f32. - pDecoder->internalFormat = mal_format_unknown; - switch (pWav->translatedFormatTag) { - case DR_WAVE_FORMAT_PCM: - { - if (pWav->bitsPerSample == 8) { - pDecoder->internalFormat = mal_format_s16; - } else if (pWav->bitsPerSample == 16) { - pDecoder->internalFormat = mal_format_s16; - } else if (pWav->bitsPerSample == 32) { - pDecoder->internalFormat = mal_format_s32; - } - } break; - - case DR_WAVE_FORMAT_IEEE_FLOAT: - { - if (pWav->bitsPerSample == 32) { - pDecoder->internalFormat = mal_format_f32; - } - } break; - - case DR_WAVE_FORMAT_ALAW: - case DR_WAVE_FORMAT_MULAW: - case DR_WAVE_FORMAT_ADPCM: - case DR_WAVE_FORMAT_DVI_ADPCM: - { - pDecoder->internalFormat = mal_format_s16; - } break; - } - - if (pDecoder->internalFormat == mal_format_unknown) { - pDecoder->internalFormat = mal_format_f32; - } - - pDecoder->internalChannels = pWav->channels; - pDecoder->internalSampleRate = pWav->sampleRate; - mal_get_standard_channel_map(mal_standard_channel_map_microsoft, pDecoder->internalChannels, pDecoder->internalChannelMap); - - mal_result result = mal_decoder__init_dsp(pDecoder, pConfig, mal_decoder_internal_on_read_frames__wav); - if (result != MAL_SUCCESS) { - drwav_close(pWav); - return result; - } - - return MAL_SUCCESS; -} -#endif - -// FLAC -#ifdef dr_flac_h -#define MAL_HAS_FLAC - -size_t mal_decoder_internal_on_read__flac(void* pUserData, void* pBufferOut, size_t bytesToRead) -{ - mal_decoder* pDecoder = (mal_decoder*)pUserData; - mal_assert(pDecoder != NULL); - mal_assert(pDecoder->onRead != NULL); - - return pDecoder->onRead(pDecoder, pBufferOut, bytesToRead); -} - -drflac_bool32 mal_decoder_internal_on_seek__flac(void* pUserData, int offset, drflac_seek_origin origin) -{ - mal_decoder* pDecoder = (mal_decoder*)pUserData; - mal_assert(pDecoder != NULL); - mal_assert(pDecoder->onSeek != NULL); - - return pDecoder->onSeek(pDecoder, offset, (origin == drflac_seek_origin_start) ? mal_seek_origin_start : mal_seek_origin_current); -} - -mal_result mal_decoder_internal_on_seek_to_frame__flac(mal_decoder* pDecoder, mal_uint64 frameIndex) -{ - drflac* pFlac = (drflac*)pDecoder->pInternalDecoder; - mal_assert(pFlac != NULL); - - drflac_bool32 result = drflac_seek_to_pcm_frame(pFlac, frameIndex); - if (result) { - return MAL_SUCCESS; - } else { - return MAL_ERROR; - } -} - -mal_result mal_decoder_internal_on_uninit__flac(mal_decoder* pDecoder) -{ - drflac_close((drflac*)pDecoder->pInternalDecoder); - return MAL_SUCCESS; -} - -mal_uint32 mal_decoder_internal_on_read_frames__flac(mal_dsp* pDSP, mal_uint32 frameCount, void* pSamplesOut, void* pUserData) -{ - (void)pDSP; - - mal_decoder* pDecoder = (mal_decoder*)pUserData; - mal_assert(pDecoder != NULL); - mal_assert(pDecoder->internalFormat == mal_format_s32); - - drflac* pFlac = (drflac*)pDecoder->pInternalDecoder; - mal_assert(pFlac != NULL); - - switch (pDecoder->internalFormat) { - case mal_format_s16: return (mal_uint32)drflac_read_pcm_frames_s16(pFlac, frameCount, (drflac_int16*)pSamplesOut); - case mal_format_s32: return (mal_uint32)drflac_read_pcm_frames_s32(pFlac, frameCount, (drflac_int32*)pSamplesOut); - case mal_format_f32: return (mal_uint32)drflac_read_pcm_frames_f32(pFlac, frameCount, (float*)pSamplesOut); - default: break; - } - - // Should never get here. If we do, it means the internal format was not set correctly at initialization time. - mal_assert(MAL_FALSE); - return 0; -} - -mal_result mal_decoder_init_flac__internal(const mal_decoder_config* pConfig, mal_decoder* pDecoder) -{ - mal_assert(pConfig != NULL); - mal_assert(pDecoder != NULL); - - // Try opening the decoder first. - drflac* pFlac = drflac_open(mal_decoder_internal_on_read__flac, mal_decoder_internal_on_seek__flac, pDecoder); - if (pFlac == NULL) { - return MAL_ERROR; - } - - // If we get here it means we successfully initialized the FLAC decoder. We can now initialize the rest of the mal_decoder. - pDecoder->onSeekToFrame = mal_decoder_internal_on_seek_to_frame__flac; - pDecoder->onUninit = mal_decoder_internal_on_uninit__flac; - pDecoder->pInternalDecoder = pFlac; - - // dr_flac supports reading as s32, s16 and f32. Try to do a one-to-one mapping if possible, but fall back to s32 if not. s32 is the "native" FLAC format - // since it's the only one that's truly lossless. - pDecoder->internalFormat = mal_format_s32; - if (pConfig->format == mal_format_s16) { - pDecoder->internalFormat = mal_format_s16; - } else if (pConfig->format == mal_format_f32) { - pDecoder->internalFormat = mal_format_f32; - } - - pDecoder->internalChannels = pFlac->channels; - pDecoder->internalSampleRate = pFlac->sampleRate; - mal_get_standard_channel_map(mal_standard_channel_map_flac, pDecoder->internalChannels, pDecoder->internalChannelMap); - - mal_result result = mal_decoder__init_dsp(pDecoder, pConfig, mal_decoder_internal_on_read_frames__flac); - if (result != MAL_SUCCESS) { - drflac_close(pFlac); - return result; - } - - return MAL_SUCCESS; -} -#endif - -// Vorbis -#ifdef STB_VORBIS_INCLUDE_STB_VORBIS_H -#define MAL_HAS_VORBIS - -// The size in bytes of each chunk of data to read from the Vorbis stream. -#define MAL_VORBIS_DATA_CHUNK_SIZE 4096 - -typedef struct -{ - stb_vorbis* pInternalVorbis; - mal_uint8* pData; - size_t dataSize; - size_t dataCapacity; - mal_uint32 framesConsumed; // The number of frames consumed in ppPacketData. - mal_uint32 framesRemaining; // The number of frames remaining in ppPacketData. - float** ppPacketData; -} mal_vorbis_decoder; - -mal_uint32 mal_vorbis_decoder_read(mal_vorbis_decoder* pVorbis, mal_decoder* pDecoder, mal_uint32 frameCount, void* pSamplesOut) -{ - mal_assert(pVorbis != NULL); - mal_assert(pDecoder != NULL); - mal_assert(pDecoder->onRead != NULL); - mal_assert(pDecoder->onSeek != NULL); - - float* pSamplesOutF = (float*)pSamplesOut; - - mal_uint32 totalFramesRead = 0; - while (frameCount > 0) { - // Read from the in-memory buffer first. - while (pVorbis->framesRemaining > 0 && frameCount > 0) { - for (mal_uint32 iChannel = 0; iChannel < pDecoder->internalChannels; ++iChannel) { - pSamplesOutF[0] = pVorbis->ppPacketData[iChannel][pVorbis->framesConsumed]; - pSamplesOutF += 1; - } - - pVorbis->framesConsumed += 1; - pVorbis->framesRemaining -= 1; - frameCount -= 1; - totalFramesRead += 1; - } - - if (frameCount == 0) { - break; - } - - mal_assert(pVorbis->framesRemaining == 0); - - // We've run out of cached frames, so decode the next packet and continue iteration. - do - { - if (pVorbis->dataSize > INT_MAX) { - break; // Too big. - } - - int samplesRead = 0; - int consumedDataSize = stb_vorbis_decode_frame_pushdata(pVorbis->pInternalVorbis, pVorbis->pData, (int)pVorbis->dataSize, NULL, (float***)&pVorbis->ppPacketData, &samplesRead); - if (consumedDataSize != 0) { - size_t leftoverDataSize = (pVorbis->dataSize - (size_t)consumedDataSize); - for (size_t i = 0; i < leftoverDataSize; ++i) { - pVorbis->pData[i] = pVorbis->pData[i + consumedDataSize]; - } - - pVorbis->dataSize = leftoverDataSize; - pVorbis->framesConsumed = 0; - pVorbis->framesRemaining = samplesRead; - break; - } else { - // Need more data. If there's any room in the existing buffer allocation fill that first. Otherwise expand. - if (pVorbis->dataCapacity == pVorbis->dataSize) { - // No room. Expand. - pVorbis->dataCapacity += MAL_VORBIS_DATA_CHUNK_SIZE; - mal_uint8* pNewData = (mal_uint8*)mal_realloc(pVorbis->pData, pVorbis->dataCapacity); - if (pNewData == NULL) { - return totalFramesRead; // Out of memory. - } - - pVorbis->pData = pNewData; - } - - // Fill in a chunk. - size_t bytesRead = pDecoder->onRead(pDecoder, pVorbis->pData + pVorbis->dataSize, (pVorbis->dataCapacity - pVorbis->dataSize)); - if (bytesRead == 0) { - return totalFramesRead; // Error reading more data. - } - - pVorbis->dataSize += bytesRead; - } - } while (MAL_TRUE); - } - - return totalFramesRead; -} - -mal_result mal_vorbis_decoder_seek_to_frame(mal_vorbis_decoder* pVorbis, mal_decoder* pDecoder, mal_uint64 frameIndex) -{ - mal_assert(pVorbis != NULL); - mal_assert(pDecoder != NULL); - mal_assert(pDecoder->onRead != NULL); - mal_assert(pDecoder->onSeek != NULL); - - // This is terribly inefficient because stb_vorbis does not have a good seeking solution with it's push API. Currently this just performs - // a full decode right from the start of the stream. Later on I'll need to write a layer that goes through all of the Ogg pages until we - // find the one containing the sample we need. Then we know exactly where to seek for stb_vorbis. - if (!pDecoder->onSeek(pDecoder, 0, mal_seek_origin_start)) { - return MAL_ERROR; - } - - stb_vorbis_flush_pushdata(pVorbis->pInternalVorbis); - pVorbis->framesConsumed = 0; - pVorbis->framesRemaining = 0; - pVorbis->dataSize = 0; - - float buffer[4096]; - while (frameIndex > 0) { - mal_uint32 framesToRead = mal_countof(buffer)/pDecoder->internalChannels; - if (framesToRead > frameIndex) { - framesToRead = (mal_uint32)frameIndex; - } - - mal_uint32 framesRead = mal_vorbis_decoder_read(pVorbis, pDecoder, framesToRead, buffer); - if (framesRead == 0) { - return MAL_ERROR; - } - - frameIndex -= framesRead; - } - - return MAL_SUCCESS; -} - - -mal_result mal_decoder_internal_on_seek_to_frame__vorbis(mal_decoder* pDecoder, mal_uint64 frameIndex) -{ - mal_assert(pDecoder != NULL); - mal_assert(pDecoder->onRead != NULL); - mal_assert(pDecoder->onSeek != NULL); - - mal_vorbis_decoder* pVorbis = (mal_vorbis_decoder*)pDecoder->pInternalDecoder; - mal_assert(pVorbis != NULL); - - return mal_vorbis_decoder_seek_to_frame(pVorbis, pDecoder, frameIndex); -} - -mal_result mal_decoder_internal_on_uninit__vorbis(mal_decoder* pDecoder) -{ - mal_vorbis_decoder* pVorbis = (mal_vorbis_decoder*)pDecoder->pInternalDecoder; - mal_assert(pVorbis != NULL); - - stb_vorbis_close(pVorbis->pInternalVorbis); - mal_free(pVorbis->pData); - mal_free(pVorbis); - - return MAL_SUCCESS; -} - -mal_uint32 mal_decoder_internal_on_read_frames__vorbis(mal_dsp* pDSP, mal_uint32 frameCount, void* pSamplesOut, void* pUserData) -{ - (void)pDSP; - - mal_decoder* pDecoder = (mal_decoder*)pUserData; - mal_assert(pDecoder != NULL); - mal_assert(pDecoder->internalFormat == mal_format_f32); - mal_assert(pDecoder->onRead != NULL); - mal_assert(pDecoder->onSeek != NULL); - - mal_vorbis_decoder* pVorbis = (mal_vorbis_decoder*)pDecoder->pInternalDecoder; - mal_assert(pVorbis != NULL); - - return mal_vorbis_decoder_read(pVorbis, pDecoder, frameCount, pSamplesOut); -} - -mal_result mal_decoder_init_vorbis__internal(const mal_decoder_config* pConfig, mal_decoder* pDecoder) -{ - mal_assert(pConfig != NULL); - mal_assert(pDecoder != NULL); - mal_assert(pDecoder->onRead != NULL); - mal_assert(pDecoder->onSeek != NULL); - - stb_vorbis* pInternalVorbis = NULL; - - // We grow the buffer in chunks. - size_t dataSize = 0; - size_t dataCapacity = 0; - mal_uint8* pData = NULL; - do - { - // Allocate memory for a new chunk. - dataCapacity += MAL_VORBIS_DATA_CHUNK_SIZE; - mal_uint8* pNewData = (mal_uint8*)mal_realloc(pData, dataCapacity); - if (pNewData == NULL) { - mal_free(pData); - return MAL_OUT_OF_MEMORY; - } - - pData = pNewData; - - // Fill in a chunk. - size_t bytesRead = pDecoder->onRead(pDecoder, pData + dataSize, (dataCapacity - dataSize)); - if (bytesRead == 0) { - return MAL_ERROR; - } - - dataSize += bytesRead; - if (dataSize > INT_MAX) { - return MAL_ERROR; // Too big. - } - - int vorbisError = 0; - int consumedDataSize = 0; - pInternalVorbis = stb_vorbis_open_pushdata(pData, (int)dataSize, &consumedDataSize, &vorbisError, NULL); - if (pInternalVorbis != NULL) { - // If we get here it means we were able to open the stb_vorbis decoder. There may be some leftover bytes in our buffer, so - // we need to move those bytes down to the front of the buffer since they'll be needed for future decoding. - size_t leftoverDataSize = (dataSize - (size_t)consumedDataSize); - for (size_t i = 0; i < leftoverDataSize; ++i) { - pData[i] = pData[i + consumedDataSize]; - } - - dataSize = leftoverDataSize; - break; // Success. - } else { - if (vorbisError == VORBIS_need_more_data) { - continue; - } else { - return MAL_ERROR; // Failed to open the stb_vorbis decoder. - } - } - } while (MAL_TRUE); - - - // If we get here it means we successfully opened the Vorbis decoder. - stb_vorbis_info vorbisInfo = stb_vorbis_get_info(pInternalVorbis); - - // Don't allow more than MAL_MAX_CHANNELS channels. - if (vorbisInfo.channels > MAL_MAX_CHANNELS) { - stb_vorbis_close(pInternalVorbis); - mal_free(pData); - return MAL_ERROR; // Too many channels. - } - - size_t vorbisDataSize = sizeof(mal_vorbis_decoder) + sizeof(float)*vorbisInfo.max_frame_size; - mal_vorbis_decoder* pVorbis = (mal_vorbis_decoder*)mal_malloc(vorbisDataSize); - if (pVorbis == NULL) { - stb_vorbis_close(pInternalVorbis); - mal_free(pData); - return MAL_OUT_OF_MEMORY; - } - - mal_zero_memory(pVorbis, vorbisDataSize); - pVorbis->pInternalVorbis = pInternalVorbis; - pVorbis->pData = pData; - pVorbis->dataSize = dataSize; - pVorbis->dataCapacity = dataCapacity; - - pDecoder->onSeekToFrame = mal_decoder_internal_on_seek_to_frame__vorbis; - pDecoder->onUninit = mal_decoder_internal_on_uninit__vorbis; - pDecoder->pInternalDecoder = pVorbis; - - // The internal format is always f32. - pDecoder->internalFormat = mal_format_f32; - pDecoder->internalChannels = vorbisInfo.channels; - pDecoder->internalSampleRate = vorbisInfo.sample_rate; - mal_get_standard_channel_map(mal_standard_channel_map_vorbis, pDecoder->internalChannels, pDecoder->internalChannelMap); - - mal_result result = mal_decoder__init_dsp(pDecoder, pConfig, mal_decoder_internal_on_read_frames__vorbis); - if (result != MAL_SUCCESS) { - stb_vorbis_close(pVorbis->pInternalVorbis); - mal_free(pVorbis->pData); - mal_free(pVorbis); - return result; - } - - return MAL_SUCCESS; -} -#endif - -// MP3 -#ifdef dr_mp3_h -#define MAL_HAS_MP3 - -size_t mal_decoder_internal_on_read__mp3(void* pUserData, void* pBufferOut, size_t bytesToRead) -{ - mal_decoder* pDecoder = (mal_decoder*)pUserData; - mal_assert(pDecoder != NULL); - mal_assert(pDecoder->onRead != NULL); - - return pDecoder->onRead(pDecoder, pBufferOut, bytesToRead); -} - -drmp3_bool32 mal_decoder_internal_on_seek__mp3(void* pUserData, int offset, drmp3_seek_origin origin) -{ - mal_decoder* pDecoder = (mal_decoder*)pUserData; - mal_assert(pDecoder != NULL); - mal_assert(pDecoder->onSeek != NULL); - - return pDecoder->onSeek(pDecoder, offset, (origin == drmp3_seek_origin_start) ? mal_seek_origin_start : mal_seek_origin_current); -} - -mal_result mal_decoder_internal_on_seek_to_frame__mp3(mal_decoder* pDecoder, mal_uint64 frameIndex) -{ - drmp3* pMP3 = (drmp3*)pDecoder->pInternalDecoder; - mal_assert(pMP3 != NULL); - - drmp3_bool32 result = drmp3_seek_to_pcm_frame(pMP3, frameIndex); - if (result) { - return MAL_SUCCESS; - } else { - return MAL_ERROR; - } -} - -mal_result mal_decoder_internal_on_uninit__mp3(mal_decoder* pDecoder) -{ - drmp3_uninit((drmp3*)pDecoder->pInternalDecoder); - mal_free(pDecoder->pInternalDecoder); - return MAL_SUCCESS; -} - -mal_uint32 mal_decoder_internal_on_read_frames__mp3(mal_dsp* pDSP, mal_uint32 frameCount, void* pSamplesOut, void* pUserData) -{ - (void)pDSP; - - mal_decoder* pDecoder = (mal_decoder*)pUserData; - mal_assert(pDecoder != NULL); - mal_assert(pDecoder->internalFormat == mal_format_f32); - - drmp3* pMP3 = (drmp3*)pDecoder->pInternalDecoder; - mal_assert(pMP3 != NULL); - - return (mal_uint32)drmp3_read_pcm_frames_f32(pMP3, frameCount, (float*)pSamplesOut); -} - -mal_result mal_decoder_init_mp3__internal(const mal_decoder_config* pConfig, mal_decoder* pDecoder) -{ - mal_assert(pConfig != NULL); - mal_assert(pDecoder != NULL); - - drmp3* pMP3 = (drmp3*)mal_malloc(sizeof(*pMP3)); - if (pMP3 == NULL) { - return MAL_OUT_OF_MEMORY; - } - - // Try opening the decoder first. MP3 can have variable sample rates (it's per frame/packet). We therefore need - // to use some smarts to determine the most appropriate internal sample rate. These are the rules we're going - // to use: - // - // Sample Rates - // 1) If an output sample rate is specified in pConfig we just use that. Otherwise; - // 2) Fall back to 44100. - // - // The internal channel count is always stereo, and the internal format is always f32. - drmp3_config mp3Config; - mal_zero_object(&mp3Config); - mp3Config.outputChannels = 2; - mp3Config.outputSampleRate = (pConfig->sampleRate != 0) ? pConfig->sampleRate : 44100; - if (!drmp3_init(pMP3, mal_decoder_internal_on_read__mp3, mal_decoder_internal_on_seek__mp3, pDecoder, &mp3Config)) { - return MAL_ERROR; - } - - // If we get here it means we successfully initialized the MP3 decoder. We can now initialize the rest of the mal_decoder. - pDecoder->onSeekToFrame = mal_decoder_internal_on_seek_to_frame__mp3; - pDecoder->onUninit = mal_decoder_internal_on_uninit__mp3; - pDecoder->pInternalDecoder = pMP3; - - // Internal format. - pDecoder->internalFormat = mal_format_f32; - pDecoder->internalChannels = pMP3->channels; - pDecoder->internalSampleRate = pMP3->sampleRate; - mal_get_standard_channel_map(mal_standard_channel_map_default, pDecoder->internalChannels, pDecoder->internalChannelMap); - - mal_result result = mal_decoder__init_dsp(pDecoder, pConfig, mal_decoder_internal_on_read_frames__mp3); - if (result != MAL_SUCCESS) { - mal_free(pMP3); - return result; - } - - return MAL_SUCCESS; -} -#endif - -// Raw -mal_result mal_decoder_internal_on_seek_to_frame__raw(mal_decoder* pDecoder, mal_uint64 frameIndex) -{ - mal_assert(pDecoder != NULL); - - if (pDecoder->onSeek == NULL) { - return MAL_ERROR; - } - - mal_bool32 result = MAL_FALSE; - - // The callback uses a 32 bit integer whereas we use a 64 bit unsigned integer. We just need to continuously seek until we're at the correct position. - mal_uint64 totalBytesToSeek = frameIndex * mal_get_bytes_per_frame(pDecoder->internalFormat, pDecoder->internalChannels); - if (totalBytesToSeek < 0x7FFFFFFF) { - // Simple case. - result = pDecoder->onSeek(pDecoder, (int)(frameIndex * mal_get_bytes_per_frame(pDecoder->internalFormat, pDecoder->internalChannels)), mal_seek_origin_start); - } else { - // Complex case. Start by doing a seek relative to the start. Then keep looping using offset seeking. - result = pDecoder->onSeek(pDecoder, 0x7FFFFFFF, mal_seek_origin_start); - if (result == MAL_TRUE) { - totalBytesToSeek -= 0x7FFFFFFF; - - while (totalBytesToSeek > 0) { - mal_uint64 bytesToSeekThisIteration = totalBytesToSeek; - if (bytesToSeekThisIteration > 0x7FFFFFFF) { - bytesToSeekThisIteration = 0x7FFFFFFF; - } - - result = pDecoder->onSeek(pDecoder, (int)bytesToSeekThisIteration, mal_seek_origin_current); - if (result != MAL_TRUE) { - break; - } - - totalBytesToSeek -= bytesToSeekThisIteration; - } - } - } - - if (result) { - return MAL_SUCCESS; - } else { - return MAL_ERROR; - } -} - -mal_result mal_decoder_internal_on_uninit__raw(mal_decoder* pDecoder) -{ - (void)pDecoder; - return MAL_SUCCESS; -} - -mal_uint32 mal_decoder_internal_on_read_frames__raw(mal_dsp* pDSP, mal_uint32 frameCount, void* pSamplesOut, void* pUserData) -{ - (void)pDSP; - - mal_decoder* pDecoder = (mal_decoder*)pUserData; - mal_assert(pDecoder != NULL); - - // For raw decoding we just read directly from the decoder's callbacks. - mal_uint32 bpf = mal_get_bytes_per_frame(pDecoder->internalFormat, pDecoder->internalChannels); - return (mal_uint32)pDecoder->onRead(pDecoder, pSamplesOut, frameCount * bpf) / bpf; -} - -mal_result mal_decoder_init_raw__internal(const mal_decoder_config* pConfigIn, const mal_decoder_config* pConfigOut, mal_decoder* pDecoder) -{ - mal_assert(pConfigIn != NULL); - mal_assert(pConfigOut != NULL); - mal_assert(pDecoder != NULL); - - pDecoder->onSeekToFrame = mal_decoder_internal_on_seek_to_frame__raw; - pDecoder->onUninit = mal_decoder_internal_on_uninit__raw; - - // Internal format. - pDecoder->internalFormat = pConfigIn->format; - pDecoder->internalChannels = pConfigIn->channels; - pDecoder->internalSampleRate = pConfigIn->sampleRate; - mal_channel_map_copy(pDecoder->internalChannelMap, pConfigIn->channelMap, pConfigIn->channels); - - mal_result result = mal_decoder__init_dsp(pDecoder, pConfigOut, mal_decoder_internal_on_read_frames__raw); - if (result != MAL_SUCCESS) { - return result; - } - - return MAL_SUCCESS; -} - -mal_result mal_decoder__preinit(mal_decoder_read_proc onRead, mal_decoder_seek_proc onSeek, void* pUserData, const mal_decoder_config* pConfig, mal_decoder* pDecoder) -{ - mal_assert(pConfig != NULL); - - if (pDecoder == NULL) { - return MAL_INVALID_ARGS; - } - - mal_zero_object(pDecoder); - - if (onRead == NULL || onSeek == NULL) { - return MAL_INVALID_ARGS; - } - - pDecoder->onRead = onRead; - pDecoder->onSeek = onSeek; - pDecoder->pUserData = pUserData; - - (void)pConfig; - return MAL_SUCCESS; -} - -mal_result mal_decoder_init_wav(mal_decoder_read_proc onRead, mal_decoder_seek_proc onSeek, void* pUserData, const mal_decoder_config* pConfig, mal_decoder* pDecoder) -{ - mal_decoder_config config = mal_decoder_config_init_copy(pConfig); - - mal_result result = mal_decoder__preinit(onRead, onSeek, pUserData, &config, pDecoder); - if (result != MAL_SUCCESS) { - return result; - } - -#ifdef MAL_HAS_WAV - return mal_decoder_init_wav__internal(&config, pDecoder); -#else - return MAL_NO_BACKEND; -#endif -} - -mal_result mal_decoder_init_flac(mal_decoder_read_proc onRead, mal_decoder_seek_proc onSeek, void* pUserData, const mal_decoder_config* pConfig, mal_decoder* pDecoder) -{ - mal_decoder_config config = mal_decoder_config_init_copy(pConfig); - - mal_result result = mal_decoder__preinit(onRead, onSeek, pUserData, &config, pDecoder); - if (result != MAL_SUCCESS) { - return result; - } - -#ifdef MAL_HAS_FLAC - return mal_decoder_init_flac__internal(&config, pDecoder); -#else - return MAL_NO_BACKEND; -#endif -} - -mal_result mal_decoder_init_vorbis(mal_decoder_read_proc onRead, mal_decoder_seek_proc onSeek, void* pUserData, const mal_decoder_config* pConfig, mal_decoder* pDecoder) -{ - mal_decoder_config config = mal_decoder_config_init_copy(pConfig); - - mal_result result = mal_decoder__preinit(onRead, onSeek, pUserData, &config, pDecoder); - if (result != MAL_SUCCESS) { - return result; - } - -#ifdef MAL_HAS_VORBIS - return mal_decoder_init_vorbis__internal(&config, pDecoder); -#else - return MAL_NO_BACKEND; -#endif -} - -mal_result mal_decoder_init_mp3(mal_decoder_read_proc onRead, mal_decoder_seek_proc onSeek, void* pUserData, const mal_decoder_config* pConfig, mal_decoder* pDecoder) -{ - mal_decoder_config config = mal_decoder_config_init_copy(pConfig); - - mal_result result = mal_decoder__preinit(onRead, onSeek, pUserData, &config, pDecoder); - if (result != MAL_SUCCESS) { - return result; - } - -#ifdef MAL_HAS_MP3 - return mal_decoder_init_mp3__internal(&config, pDecoder); -#else - return MAL_NO_BACKEND; -#endif -} - -mal_result mal_decoder_init_raw(mal_decoder_read_proc onRead, mal_decoder_seek_proc onSeek, void* pUserData, const mal_decoder_config* pConfigIn, const mal_decoder_config* pConfigOut, mal_decoder* pDecoder) -{ - mal_decoder_config config = mal_decoder_config_init_copy(pConfigOut); - - mal_result result = mal_decoder__preinit(onRead, onSeek, pUserData, &config, pDecoder); - if (result != MAL_SUCCESS) { - return result; - } - - return mal_decoder_init_raw__internal(pConfigIn, &config, pDecoder); -} - -mal_result mal_decoder_init__internal(mal_decoder_read_proc onRead, mal_decoder_seek_proc onSeek, void* pUserData, const mal_decoder_config* pConfig, mal_decoder* pDecoder) -{ - mal_assert(pConfig != NULL); - mal_assert(pDecoder != NULL); - - // Silence some warnings in the case that we don't have any decoder backends enabled. - (void)onRead; - (void)onSeek; - (void)pUserData; - (void)pConfig; - (void)pDecoder; - - // We use trial and error to open a decoder. - mal_result result = MAL_NO_BACKEND; - -#ifdef MAL_HAS_WAV - if (result != MAL_SUCCESS) { - result = mal_decoder_init_wav__internal(pConfig, pDecoder); - if (result != MAL_SUCCESS) { - onSeek(pDecoder, 0, mal_seek_origin_start); - } - } -#endif -#ifdef MAL_HAS_FLAC - if (result != MAL_SUCCESS) { - result = mal_decoder_init_flac__internal(pConfig, pDecoder); - if (result != MAL_SUCCESS) { - onSeek(pDecoder, 0, mal_seek_origin_start); - } - } -#endif -#ifdef MAL_HAS_VORBIS - if (result != MAL_SUCCESS) { - result = mal_decoder_init_vorbis__internal(pConfig, pDecoder); - if (result != MAL_SUCCESS) { - onSeek(pDecoder, 0, mal_seek_origin_start); - } - } -#endif -#ifdef MAL_HAS_MP3 - if (result != MAL_SUCCESS) { - result = mal_decoder_init_mp3__internal(pConfig, pDecoder); - if (result != MAL_SUCCESS) { - onSeek(pDecoder, 0, mal_seek_origin_start); - } - } -#endif - - if (result != MAL_SUCCESS) { - return result; - } - - return result; -} - -mal_result mal_decoder_init(mal_decoder_read_proc onRead, mal_decoder_seek_proc onSeek, void* pUserData, const mal_decoder_config* pConfig, mal_decoder* pDecoder) -{ - mal_decoder_config config = mal_decoder_config_init_copy(pConfig); - - mal_result result = mal_decoder__preinit(onRead, onSeek, pUserData, &config, pDecoder); - if (result != MAL_SUCCESS) { - return result; - } - - return mal_decoder_init__internal(onRead, onSeek, pUserData, &config, pDecoder); -} - - -size_t mal_decoder__on_read_memory(mal_decoder* pDecoder, void* pBufferOut, size_t bytesToRead) -{ - mal_assert(pDecoder->memory.dataSize >= pDecoder->memory.currentReadPos); - - size_t bytesRemaining = pDecoder->memory.dataSize - pDecoder->memory.currentReadPos; - if (bytesToRead > bytesRemaining) { - bytesToRead = bytesRemaining; - } - - if (bytesToRead > 0) { - mal_copy_memory(pBufferOut, pDecoder->memory.pData + pDecoder->memory.currentReadPos, bytesToRead); - pDecoder->memory.currentReadPos += bytesToRead; - } - - return bytesToRead; -} - -mal_bool32 mal_decoder__on_seek_memory(mal_decoder* pDecoder, int byteOffset, mal_seek_origin origin) -{ - if (origin == mal_seek_origin_current) { - if (byteOffset > 0) { - if (pDecoder->memory.currentReadPos + byteOffset > pDecoder->memory.dataSize) { - byteOffset = (int)(pDecoder->memory.dataSize - pDecoder->memory.currentReadPos); // Trying to seek too far forward. - } - } else { - if (pDecoder->memory.currentReadPos < (size_t)-byteOffset) { - byteOffset = -(int)pDecoder->memory.currentReadPos; // Trying to seek too far backwards. - } - } - - // This will never underflow thanks to the clamps above. - pDecoder->memory.currentReadPos += byteOffset; - } else { - if ((mal_uint32)byteOffset <= pDecoder->memory.dataSize) { - pDecoder->memory.currentReadPos = byteOffset; - } else { - pDecoder->memory.currentReadPos = pDecoder->memory.dataSize; // Trying to seek too far forward. - } - } - - return MAL_TRUE; -} - -mal_result mal_decoder__preinit_memory(const void* pData, size_t dataSize, const mal_decoder_config* pConfig, mal_decoder* pDecoder) -{ - mal_result result = mal_decoder__preinit(mal_decoder__on_read_memory, mal_decoder__on_seek_memory, NULL, pConfig, pDecoder); - if (result != MAL_SUCCESS) { - return result; - } - - if (pData == NULL || dataSize == 0) { - return MAL_INVALID_ARGS; - } - - pDecoder->memory.pData = (const mal_uint8*)pData; - pDecoder->memory.dataSize = dataSize; - pDecoder->memory.currentReadPos = 0; - - (void)pConfig; - return MAL_SUCCESS; -} - -mal_result mal_decoder_init_memory(const void* pData, size_t dataSize, const mal_decoder_config* pConfig, mal_decoder* pDecoder) -{ - mal_decoder_config config = mal_decoder_config_init_copy(pConfig); // Make sure the config is not NULL. - - mal_result result = mal_decoder__preinit_memory(pData, dataSize, &config, pDecoder); - if (result != MAL_SUCCESS) { - return result; - } - - return mal_decoder_init__internal(mal_decoder__on_read_memory, mal_decoder__on_seek_memory, NULL, &config, pDecoder); -} - -mal_result mal_decoder_init_memory_wav(const void* pData, size_t dataSize, const mal_decoder_config* pConfig, mal_decoder* pDecoder) -{ - mal_decoder_config config = mal_decoder_config_init_copy(pConfig); // Make sure the config is not NULL. - - mal_result result = mal_decoder__preinit_memory(pData, dataSize, &config, pDecoder); - if (result != MAL_SUCCESS) { - return result; - } - -#ifdef MAL_HAS_WAV - return mal_decoder_init_wav__internal(&config, pDecoder); -#else - return MAL_NO_BACKEND; -#endif -} - -mal_result mal_decoder_init_memory_flac(const void* pData, size_t dataSize, const mal_decoder_config* pConfig, mal_decoder* pDecoder) -{ - mal_decoder_config config = mal_decoder_config_init_copy(pConfig); // Make sure the config is not NULL. - - mal_result result = mal_decoder__preinit_memory(pData, dataSize, &config, pDecoder); - if (result != MAL_SUCCESS) { - return result; - } - -#ifdef MAL_HAS_FLAC - return mal_decoder_init_flac__internal(&config, pDecoder); -#else - return MAL_NO_BACKEND; -#endif -} - -mal_result mal_decoder_init_memory_vorbis(const void* pData, size_t dataSize, const mal_decoder_config* pConfig, mal_decoder* pDecoder) -{ - mal_decoder_config config = mal_decoder_config_init_copy(pConfig); // Make sure the config is not NULL. - - mal_result result = mal_decoder__preinit_memory(pData, dataSize, &config, pDecoder); - if (result != MAL_SUCCESS) { - return result; - } - -#ifdef MAL_HAS_VORBIS - return mal_decoder_init_vorbis__internal(&config, pDecoder); -#else - return MAL_NO_BACKEND; -#endif -} - -mal_result mal_decoder_init_memory_mp3(const void* pData, size_t dataSize, const mal_decoder_config* pConfig, mal_decoder* pDecoder) -{ - mal_decoder_config config = mal_decoder_config_init_copy(pConfig); // Make sure the config is not NULL. - - mal_result result = mal_decoder__preinit_memory(pData, dataSize, &config, pDecoder); - if (result != MAL_SUCCESS) { - return result; - } - -#ifdef MAL_HAS_MP3 - return mal_decoder_init_mp3__internal(&config, pDecoder); -#else - return MAL_NO_BACKEND; -#endif -} - -mal_result mal_decoder_init_memory_raw(const void* pData, size_t dataSize, const mal_decoder_config* pConfigIn, const mal_decoder_config* pConfigOut, mal_decoder* pDecoder) -{ - mal_decoder_config config = mal_decoder_config_init_copy(pConfigOut); // Make sure the config is not NULL. - - mal_result result = mal_decoder__preinit_memory(pData, dataSize, &config, pDecoder); - if (result != MAL_SUCCESS) { - return result; - } - - return mal_decoder_init_raw__internal(pConfigIn, &config, pDecoder); -} - -#ifndef MAL_NO_STDIO -#include -#if !defined(_MSC_VER) && !defined(__DMC__) -#include // For strcasecmp(). -#endif - -const char* mal_path_file_name(const char* path) -{ - if (path == NULL) { - return NULL; - } - - const char* fileName = path; - - // We just loop through the path until we find the last slash. - while (path[0] != '\0') { - if (path[0] == '/' || path[0] == '\\') { - fileName = path; - } - - path += 1; - } - - // At this point the file name is sitting on a slash, so just move forward. - while (fileName[0] != '\0' && (fileName[0] == '/' || fileName[0] == '\\')) { - fileName += 1; - } - - return fileName; -} - -const char* mal_path_extension(const char* path) -{ - if (path == NULL) { - path = ""; - } - - const char* extension = mal_path_file_name(path); - const char* lastOccurance = NULL; - - // Just find the last '.' and return. - while (extension[0] != '\0') { - if (extension[0] == '.') { - extension += 1; - lastOccurance = extension; - } - - extension += 1; - } - - return (lastOccurance != NULL) ? lastOccurance : extension; -} - -mal_bool32 mal_path_extension_equal(const char* path, const char* extension) -{ - if (path == NULL || extension == NULL) { - return MAL_FALSE; - } - - const char* ext1 = extension; - const char* ext2 = mal_path_extension(path); - -#if defined(_MSC_VER) || defined(__DMC__) - return _stricmp(ext1, ext2) == 0; -#else - return strcasecmp(ext1, ext2) == 0; -#endif -} - -size_t mal_decoder__on_read_stdio(mal_decoder* pDecoder, void* pBufferOut, size_t bytesToRead) -{ - return fread(pBufferOut, 1, bytesToRead, (FILE*)pDecoder->pUserData); -} - -mal_bool32 mal_decoder__on_seek_stdio(mal_decoder* pDecoder, int byteOffset, mal_seek_origin origin) -{ - return fseek((FILE*)pDecoder->pUserData, byteOffset, (origin == mal_seek_origin_current) ? SEEK_CUR : SEEK_SET) == 0; -} - -mal_result mal_decoder__preinit_file(const char* pFilePath, const mal_decoder_config* pConfig, mal_decoder* pDecoder) -{ - if (pDecoder == NULL) { - return MAL_INVALID_ARGS; - } - - mal_zero_object(pDecoder); - - if (pFilePath == NULL || pFilePath[0] == '\0') { - return MAL_INVALID_ARGS; - } - - FILE* pFile; -#if defined(_MSC_VER) && _MSC_VER >= 1400 - if (fopen_s(&pFile, pFilePath, "rb") != 0) { - return MAL_ERROR; - } -#else - pFile = fopen(pFilePath, "rb"); - if (pFile == NULL) { - return MAL_ERROR; - } -#endif - - // We need to manually set the user data so the calls to mal_decoder__on_seek_stdio() succeed. - pDecoder->pUserData = pFile; - - (void)pConfig; - return MAL_SUCCESS; -} - -mal_result mal_decoder_init_file(const char* pFilePath, const mal_decoder_config* pConfig, mal_decoder* pDecoder) -{ - mal_result result = mal_decoder__preinit_file(pFilePath, pConfig, pDecoder); // This sets pDecoder->pUserData to a FILE*. - if (result != MAL_SUCCESS) { - return result; - } - - // WAV - if (mal_path_extension_equal(pFilePath, "wav")) { - result = mal_decoder_init_wav(mal_decoder__on_read_stdio, mal_decoder__on_seek_stdio, pDecoder->pUserData, pConfig, pDecoder); - if (result == MAL_SUCCESS) { - return MAL_SUCCESS; - } - - mal_decoder__on_seek_stdio(pDecoder, 0, mal_seek_origin_start); - } - - // FLAC - if (mal_path_extension_equal(pFilePath, "flac")) { - result = mal_decoder_init_flac(mal_decoder__on_read_stdio, mal_decoder__on_seek_stdio, pDecoder->pUserData, pConfig, pDecoder); - if (result == MAL_SUCCESS) { - return MAL_SUCCESS; - } - - mal_decoder__on_seek_stdio(pDecoder, 0, mal_seek_origin_start); - } - - // MP3 - if (mal_path_extension_equal(pFilePath, "mp3")) { - result = mal_decoder_init_mp3(mal_decoder__on_read_stdio, mal_decoder__on_seek_stdio, pDecoder->pUserData, pConfig, pDecoder); - if (result == MAL_SUCCESS) { - return MAL_SUCCESS; - } - - mal_decoder__on_seek_stdio(pDecoder, 0, mal_seek_origin_start); - } - - // Trial and error. - return mal_decoder_init(mal_decoder__on_read_stdio, mal_decoder__on_seek_stdio, pDecoder->pUserData, pConfig, pDecoder); -} - -mal_result mal_decoder_init_file_wav(const char* pFilePath, const mal_decoder_config* pConfig, mal_decoder* pDecoder) -{ - mal_result result = mal_decoder__preinit_file(pFilePath, pConfig, pDecoder); - if (result != MAL_SUCCESS) { - return result; - } - - return mal_decoder_init_wav(mal_decoder__on_read_stdio, mal_decoder__on_seek_stdio, pDecoder->pUserData, pConfig, pDecoder); -} - -mal_result mal_decoder_init_file_flac(const char* pFilePath, const mal_decoder_config* pConfig, mal_decoder* pDecoder) -{ - mal_result result = mal_decoder__preinit_file(pFilePath, pConfig, pDecoder); - if (result != MAL_SUCCESS) { - return result; - } - - return mal_decoder_init_flac(mal_decoder__on_read_stdio, mal_decoder__on_seek_stdio, pDecoder->pUserData, pConfig, pDecoder); -} - -mal_result mal_decoder_init_file_vorbis(const char* pFilePath, const mal_decoder_config* pConfig, mal_decoder* pDecoder) -{ - mal_result result = mal_decoder__preinit_file(pFilePath, pConfig, pDecoder); - if (result != MAL_SUCCESS) { - return result; - } - - return mal_decoder_init_vorbis(mal_decoder__on_read_stdio, mal_decoder__on_seek_stdio, pDecoder->pUserData, pConfig, pDecoder); -} - -mal_result mal_decoder_init_file_mp3(const char* pFilePath, const mal_decoder_config* pConfig, mal_decoder* pDecoder) -{ - mal_result result = mal_decoder__preinit_file(pFilePath, pConfig, pDecoder); - if (result != MAL_SUCCESS) { - return result; - } - - return mal_decoder_init_mp3(mal_decoder__on_read_stdio, mal_decoder__on_seek_stdio, pDecoder->pUserData, pConfig, pDecoder); -} -#endif - -mal_result mal_decoder_uninit(mal_decoder* pDecoder) -{ - if (pDecoder == NULL) { - return MAL_INVALID_ARGS; - } - - if (pDecoder->onUninit) { - pDecoder->onUninit(pDecoder); - } - -#ifndef MAL_NO_STDIO - // If we have a file handle, close it. - if (pDecoder->onRead == mal_decoder__on_read_stdio) { - fclose((FILE*)pDecoder->pUserData); - } -#endif - - return MAL_SUCCESS; -} - -mal_uint64 mal_decoder_read(mal_decoder* pDecoder, mal_uint64 frameCount, void* pFramesOut) -{ - if (pDecoder == NULL) return 0; - - return mal_dsp_read(&pDecoder->dsp, frameCount, pFramesOut, pDecoder->dsp.pUserData); -} - -mal_result mal_decoder_seek_to_frame(mal_decoder* pDecoder, mal_uint64 frameIndex) -{ - if (pDecoder == NULL) return 0; - - if (pDecoder->onSeekToFrame) { - return pDecoder->onSeekToFrame(pDecoder, frameIndex); - } - - // Should never get here, but if we do it means onSeekToFrame was not set by the backend. - return MAL_INVALID_ARGS; -} - - -mal_result mal_decoder__full_decode_and_uninit(mal_decoder* pDecoder, mal_decoder_config* pConfigOut, mal_uint64* pFrameCountOut, void** ppDataOut) -{ - mal_assert(pDecoder != NULL); - - mal_uint64 totalFrameCount = 0; - mal_uint64 bpf = mal_get_bytes_per_frame(pDecoder->outputFormat, pDecoder->outputChannels); - - // The frame count is unknown until we try reading. Thus, we just run in a loop. - mal_uint64 dataCapInFrames = 0; - void* pDataOut = NULL; - for (;;) { - // Make room if there's not enough. - if (totalFrameCount == dataCapInFrames) { - mal_uint64 newDataCapInFrames = dataCapInFrames*2; - if (newDataCapInFrames == 0) { - newDataCapInFrames = 4096; - } - - if ((newDataCapInFrames * bpf) > MAL_SIZE_MAX) { - mal_free(pDataOut); - return MAL_TOO_LARGE; - } - - - void* pNewDataOut = (void*)mal_realloc(pDataOut, (size_t)(newDataCapInFrames * bpf)); - if (pNewDataOut == NULL) { - mal_free(pDataOut); - return MAL_OUT_OF_MEMORY; - } - - dataCapInFrames = newDataCapInFrames; - pDataOut = pNewDataOut; - } - - mal_uint64 frameCountToTryReading = dataCapInFrames - totalFrameCount; - mal_assert(frameCountToTryReading > 0); - - mal_uint64 framesJustRead = mal_decoder_read(pDecoder, frameCountToTryReading, (mal_uint8*)pDataOut + (totalFrameCount * bpf)); - totalFrameCount += framesJustRead; - - if (framesJustRead < frameCountToTryReading) { - break; - } - } - - - if (pConfigOut != NULL) { - pConfigOut->format = pDecoder->outputFormat; - pConfigOut->channels = pDecoder->outputChannels; - pConfigOut->sampleRate = pDecoder->outputSampleRate; - mal_channel_map_copy(pConfigOut->channelMap, pDecoder->outputChannelMap, pDecoder->outputChannels); - } - - if (ppDataOut != NULL) { - *ppDataOut = pDataOut; - } else { - mal_free(pDataOut); - } - - if (pFrameCountOut != NULL) { - *pFrameCountOut = totalFrameCount; - } - - mal_decoder_uninit(pDecoder); - return MAL_SUCCESS; -} - -#ifndef MAL_NO_STDIO -mal_result mal_decode_file(const char* pFilePath, mal_decoder_config* pConfig, mal_uint64* pFrameCountOut, void** ppDataOut) -{ - if (pFrameCountOut != NULL) { - *pFrameCountOut = 0; - } - if (ppDataOut != NULL) { - *ppDataOut = NULL; - } - - if (pFilePath == NULL) { - return MAL_INVALID_ARGS; - } - - mal_decoder_config config = mal_decoder_config_init_copy(pConfig); - - mal_decoder decoder; - mal_result result = mal_decoder_init_file(pFilePath, &config, &decoder); - if (result != MAL_SUCCESS) { - return result; - } - - return mal_decoder__full_decode_and_uninit(&decoder, pConfig, pFrameCountOut, ppDataOut); -} -#endif - -mal_result mal_decode_memory(const void* pData, size_t dataSize, mal_decoder_config* pConfig, mal_uint64* pFrameCountOut, void** ppDataOut) -{ - if (pFrameCountOut != NULL) { - *pFrameCountOut = 0; - } - if (ppDataOut != NULL) { - *ppDataOut = NULL; - } - - if (pData == NULL || dataSize == 0) { - return MAL_INVALID_ARGS; - } - - mal_decoder_config config = mal_decoder_config_init_copy(pConfig); - - mal_decoder decoder; - mal_result result = mal_decoder_init_memory(pData, dataSize, &config, &decoder); - if (result != MAL_SUCCESS) { - return result; - } - - return mal_decoder__full_decode_and_uninit(&decoder, pConfig, pFrameCountOut, ppDataOut); -} - -#endif // MAL_NO_DECODING - - - - -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// GENERATION -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -mal_result mal_sine_wave_init(double amplitude, double periodsPerSecond, mal_uint32 sampleRate, mal_sine_wave* pSineWave) -{ - if (pSineWave == NULL) { - return MAL_INVALID_ARGS; - } - mal_zero_object(pSineWave); - - if (amplitude == 0 || periodsPerSecond == 0) { - return MAL_INVALID_ARGS; - } - - if (amplitude > 1) { - amplitude = 1; - } - if (amplitude < -1) { - amplitude = -1; - } - - pSineWave->amplitude = amplitude; - pSineWave->periodsPerSecond = periodsPerSecond; - pSineWave->delta = MAL_TAU_D / sampleRate; - pSineWave->time = 0; - - return MAL_SUCCESS; -} - -mal_uint64 mal_sine_wave_read(mal_sine_wave* pSineWave, mal_uint64 count, float* pSamples) -{ - return mal_sine_wave_read_ex(pSineWave, count, 1, mal_stream_layout_interleaved, &pSamples); -} - -mal_uint64 mal_sine_wave_read_ex(mal_sine_wave* pSineWave, mal_uint64 frameCount, mal_uint32 channels, mal_stream_layout layout, float** ppFrames) -{ - if (pSineWave == NULL) { - return 0; - } - - if (ppFrames != NULL) { - for (mal_uint64 iFrame = 0; iFrame < frameCount; iFrame += 1) { - float s = (float)(sin(pSineWave->time * pSineWave->periodsPerSecond) * pSineWave->amplitude); - pSineWave->time += pSineWave->delta; - - if (layout == mal_stream_layout_interleaved) { - for (mal_uint32 iChannel = 0; iChannel < channels; iChannel += 1) { - ppFrames[0][iFrame*channels + iChannel] = s; - } - } else { - for (mal_uint32 iChannel = 0; iChannel < channels; iChannel += 1) { - ppFrames[iChannel][iFrame] = s; - } - } - } - } else { - pSineWave->time += pSineWave->delta * frameCount; - } - - return frameCount; -} - -#if defined(_MSC_VER) - #pragma warning(pop) -#endif - -#endif // MINI_AL_IMPLEMENTATION - - -// REVISION HISTORY -// ================ -// -// v0.8.15 - 201x-xx-xx -// - Add Web Audio backend. This is used when compiling with Emscripten. The SDL backend, which was previously -// used for web support, will be removed in a future version. -// - Add AAudio backend (Android Audio). This is the new priority backend for Android. Support for AAudio starts -// with Android 8. OpenSL|ES is used as a fallback for older versions of Android. -// - Deprecate the OpenAL backend. -// - Deprecate the SDL backend. -// -// v0.8.14 - 2018-12-16 -// - Core Audio: Fix a bug where the device state is not set correctly after stopping. -// - Add support for custom weights to the channel router. -// - Update decoders to use updated APIs in dr_flac, dr_mp3 and dr_wav. -// -// v0.8.13 - 2018-12-04 -// - Core Audio: Fix a bug with channel mapping. -// - Fix a bug with channel routing where the back/left and back/right channels have the wrong weight. -// -// v0.8.12 - 2018-11-27 -// - Drop support for SDL 1.2. The Emscripten build now requires "-s USE_SDL=2". -// - Fix a linking error with ALSA. -// - Fix a bug on iOS where the device name is not set correctly. -// -// v0.8.11 - 2018-11-21 -// - iOS bug fixes. -// - Minor tweaks to PulseAudio. -// -// v0.8.10 - 2018-10-21 -// - Core Audio: Fix a hang when uninitializing a device. -// - Fix a bug where an incorrect value is returned from mal_device_stop(). -// -// v0.8.9 - 2018-09-28 -// - Fix a bug with the SDL backend where device initialization fails. -// -// v0.8.8 - 2018-09-14 -// - Fix Linux build with the ALSA backend. -// - Minor documentation fix. -// -// v0.8.7 - 2018-09-12 -// - Fix a bug with UWP detection. -// -// v0.8.6 - 2018-08-26 -// - Automatically switch the internal device when the default device is unplugged. Note that this is still in the -// early stages and not all backends handle this the same way. As of this version, this will not detect a default -// device switch when changed from the operating system's audio preferences (unless the backend itself handles -// this automatically). This is not supported in exclusive mode. -// - WASAPI and Core Audio: Add support for stream routing. When the application is using a default device and the -// user switches the default device via the operating system's audio preferences, mini_al will automatically switch -// the internal device to the new default. This is not supported in exclusive mode. -// - WASAPI: Add support for hardware offloading via IAudioClient2. Only supported on Windows 8 and newer. -// - WASAPI: Add support for low-latency shared mode via IAudioClient3. Only supported on Windows 10 and newer. -// - Add support for compiling the UWP build as C. -// - mal_device_set_recv_callback() and mal_device_set_send_callback() have been deprecated. You must now set this -// when the device is initialized with mal_device_init*(). These will be removed in version 0.9.0. -// -// v0.8.5 - 2018-08-12 -// - Add support for specifying the size of a device's buffer in milliseconds. You can still set the buffer size in -// frames if that suits you. When bufferSizeInFrames is 0, bufferSizeInMilliseconds will be used. If both are non-0 -// then bufferSizeInFrames will take priority. If both are set to 0 the default buffer size is used. -// - Add support for the audio(4) backend to OpenBSD. -// - Fix a bug with the ALSA backend that was causing problems on Raspberry Pi. This significantly improves the -// Raspberry Pi experience. -// - Fix a bug where an incorrect number of samples is returned from sinc resampling. -// - Add support for setting the value to be passed to internal calls to CoInitializeEx(). -// - WASAPI and WinMM: Stop the device when it is unplugged. -// -// v0.8.4 - 2018-08-06 -// - Add sndio backend for OpenBSD. -// - Add audio(4) backend for NetBSD. -// - Drop support for the OSS backend on everything except FreeBSD and DragonFly BSD. -// - Formats are now native-endian (were previously little-endian). -// - Mark some APIs as deprecated: -// - mal_src_set_input_sample_rate() and mal_src_set_output_sample_rate() are replaced with mal_src_set_sample_rate(). -// - mal_dsp_set_input_sample_rate() and mal_dsp_set_output_sample_rate() are replaced with mal_dsp_set_sample_rate(). -// - Fix a bug when capturing using the WASAPI backend. -// - Fix some aliasing issues with resampling, specifically when increasing the sample rate. -// - Fix warnings. -// -// v0.8.3 - 2018-07-15 -// - Fix a crackling bug when resampling in capture mode. -// - Core Audio: Fix a bug where capture does not work. -// - ALSA: Fix a bug where the worker thread can get stuck in an infinite loop. -// - PulseAudio: Fix a bug where mal_context_init() succeeds when PulseAudio is unusable. -// - JACK: Fix a bug where mal_context_init() succeeds when JACK is unusable. -// -// v0.8.2 - 2018-07-07 -// - Fix a bug on macOS with Core Audio where the internal callback is not called. -// -// v0.8.1 - 2018-07-06 -// - Fix compilation errors and warnings. -// -// v0.8 - 2018-07-05 -// - Changed MAL_IMPLEMENTATION to MINI_AL_IMPLEMENTATION for consistency with other libraries. The old -// way is still supported for now, but you should update as it may be removed in the future. -// - API CHANGE: Replace device enumeration APIs. mal_enumerate_devices() has been replaced with -// mal_context_get_devices(). An additional low-level device enumration API has been introduced called -// mal_context_enumerate_devices() which uses a callback to report devices. -// - API CHANGE: Rename mal_get_sample_size_in_bytes() to mal_get_bytes_per_sample() and add -// mal_get_bytes_per_frame(). -// - API CHANGE: Replace mal_device_config.preferExclusiveMode with mal_device_config.shareMode. -// - This new config can be set to mal_share_mode_shared (default) or mal_share_mode_exclusive. -// - API CHANGE: Remove excludeNullDevice from mal_context_config.alsa. -// - API CHANGE: Rename MAL_MAX_SAMPLE_SIZE_IN_BYTES to MAL_MAX_PCM_SAMPLE_SIZE_IN_BYTES. -// - API CHANGE: Change the default channel mapping to the standard Microsoft mapping. -// - API CHANGE: Remove backend-specific result codes. -// - API CHANGE: Changes to the format conversion APIs (mal_pcm_f32_to_s16(), etc.) -// - Add support for Core Audio (Apple). -// - Add support for PulseAudio. -// - This is the highest priority backend on Linux (higher priority than ALSA) since it is commonly -// installed by default on many of the popular distros and offer's more seamless integration on -// platforms where PulseAudio is used. In addition, if PulseAudio is installed and running (which -// is extremely common), it's better to just use PulseAudio directly rather than going through the -// "pulse" ALSA plugin (which is what the "default" ALSA device is likely set to). -// - Add support for JACK. -// - Remove dependency on asound.h for the ALSA backend. This means the ALSA development packages are no -// longer required to build mini_al. -// - Remove dependency on dsound.h for the DirectSound backend. This fixes build issues with some -// distributions of MinGW. -// - Remove dependency on audioclient.h for the WASAPI backend. This fixes build issues with some -// distributions of MinGW. -// - Add support for dithering to format conversion. -// - Add support for configuring the priority of the worker thread. -// - Add a sine wave generator. -// - Improve efficiency of sample rate conversion. -// - Introduce the notion of standard channel maps. Use mal_get_standard_channel_map(). -// - Introduce the notion of default device configurations. A default config uses the same configuration -// as the backend's internal device, and as such results in a pass-through data transmission pipeline. -// - Add support for passing in NULL for the device config in mal_device_init(), which uses a default -// config. This requires manually calling mal_device_set_send/recv_callback(). -// - Add support for decoding from raw PCM data (mal_decoder_init_raw(), etc.) -// - Make mal_device_init_ex() more robust. -// - Make some APIs more const-correct. -// - Fix errors with SDL detection on Apple platforms. -// - Fix errors with OpenAL detection. -// - Fix some memory leaks. -// - Fix a bug with opening decoders from memory. -// - Early work on SSE2, AVX2 and NEON optimizations. -// - Miscellaneous bug fixes. -// - Documentation updates. -// -// v0.7 - 2018-02-25 -// - API CHANGE: Change mal_src_read_frames() and mal_dsp_read_frames() to use 64-bit sample counts. -// - Add decoder APIs for loading WAV, FLAC, Vorbis and MP3 files. -// - Allow opening of devices without a context. -// - In this case the context is created and managed internally by the device. -// - Change the default channel mapping to the same as that used by FLAC. -// - Fix build errors with macOS. -// -// v0.6c - 2018-02-12 -// - Fix build errors with BSD/OSS. -// -// v0.6b - 2018-02-03 -// - Fix some warnings when compiling with Visual C++. -// -// v0.6a - 2018-01-26 -// - Fix errors with channel mixing when increasing the channel count. -// - Improvements to the build system for the OpenAL backend. -// - Documentation fixes. -// -// v0.6 - 2017-12-08 -// - API CHANGE: Expose and improve mutex APIs. If you were using the mutex APIs before this version you'll -// need to update. -// - API CHANGE: SRC and DSP callbacks now take a pointer to a mal_src and mal_dsp object respectively. -// - API CHANGE: Improvements to event and thread APIs. These changes make these APIs more consistent. -// - Add support for SDL and Emscripten. -// - Simplify the build system further for when development packages for various backends are not installed. -// With this change, when the compiler supports __has_include, backends without the relevant development -// packages installed will be ignored. This fixes the build for old versions of MinGW. -// - Fixes to the Android build. -// - Add mal_convert_frames(). This is a high-level helper API for performing a one-time, bulk conversion of -// audio data to a different format. -// - Improvements to f32 -> u8/s16/s24/s32 conversion routines. -// - Fix a bug where the wrong value is returned from mal_device_start() for the OpenSL backend. -// - Fixes and improvements for Raspberry Pi. -// - Warning fixes. -// -// v0.5 - 2017-11-11 -// - API CHANGE: The mal_context_init() function now takes a pointer to a mal_context_config object for -// configuring the context. The works in the same kind of way as the device config. The rationale for this -// change is to give applications better control over context-level properties, add support for backend- -// specific configurations, and support extensibility without breaking the API. -// - API CHANGE: The alsa.preferPlugHW device config variable has been removed since it's not really useful for -// anything anymore. -// - ALSA: By default, device enumeration will now only enumerate over unique card/device pairs. Applications -// can enable verbose device enumeration by setting the alsa.useVerboseDeviceEnumeration context config -// variable. -// - ALSA: When opening a device in shared mode (the default), the dmix/dsnoop plugin will be prioritized. If -// this fails it will fall back to the hw plugin. With this change the preferExclusiveMode config is now -// honored. Note that this does not happen when alsa.useVerboseDeviceEnumeration is set to true (see above) -// which is by design. -// - ALSA: Add support for excluding the "null" device using the alsa.excludeNullDevice context config variable. -// - ALSA: Fix a bug with channel mapping which causes an assertion to fail. -// - Fix errors with enumeration when pInfo is set to NULL. -// - OSS: Fix a bug when starting a device when the client sends 0 samples for the initial buffer fill. -// -// v0.4 - 2017-11-05 -// - API CHANGE: The log callback is now per-context rather than per-device and as is thus now passed to -// mal_context_init(). The rationale for this change is that it allows applications to capture diagnostic -// messages at the context level. Previously this was only available at the device level. -// - API CHANGE: The device config passed to mal_device_init() is now const. -// - Added support for OSS which enables support on BSD platforms. -// - Added support for WinMM (waveOut/waveIn). -// - Added support for UWP (Universal Windows Platform) applications. Currently C++ only. -// - Added support for exclusive mode for selected backends. Currently supported on WASAPI. -// - POSIX builds no longer require explicit linking to libpthread (-lpthread). -// - ALSA: Explicit linking to libasound (-lasound) is no longer required. -// - ALSA: Latency improvements. -// - ALSA: Use MMAP mode where available. This can be disabled with the alsa.noMMap config. -// - ALSA: Use "hw" devices instead of "plughw" devices by default. This can be disabled with the -// alsa.preferPlugHW config. -// - WASAPI is now the highest priority backend on Windows platforms. -// - Fixed an error with sample rate conversion which was causing crackling when capturing. -// - Improved error handling. -// - Improved compiler support. -// - Miscellaneous bug fixes. -// -// v0.3 - 2017-06-19 -// - API CHANGE: Introduced the notion of a context. The context is the highest level object and is required for -// enumerating and creating devices. Now, applications must first create a context, and then use that to -// enumerate and create devices. The reason for this change is to ensure device enumeration and creation is -// tied to the same backend. In addition, some backends are better suited to this design. -// - API CHANGE: Removed the rewinding APIs because they're too inconsistent across the different backends, hard -// to test and maintain, and just generally unreliable. -// - Added helper APIs for initializing mal_device_config objects. -// - Null Backend: Fixed a crash when recording. -// - Fixed build for UWP. -// - Added support for f32 formats to the OpenSL|ES backend. -// - Added initial implementation of the WASAPI backend. -// - Added initial implementation of the OpenAL backend. -// - Added support for low quality linear sample rate conversion. -// - Added early support for basic channel mapping. -// -// v0.2 - 2016-10-28 -// - API CHANGE: Add user data pointer as the last parameter to mal_device_init(). The rationale for this -// change is to ensure the logging callback has access to the user data during initialization. -// - API CHANGE: Have device configuration properties be passed to mal_device_init() via a structure. Rationale: -// 1) The number of parameters is just getting too much. -// 2) It makes it a bit easier to add new configuration properties in the future. In particular, there's a -// chance there will be support added for backend-specific properties. -// - Dropped support for f64, A-law and Mu-law formats since they just aren't common enough to justify the -// added maintenance cost. -// - DirectSound: Increased the default buffer size for capture devices. -// - Added initial implementation of the OpenSL|ES backend. -// -// v0.1 - 2016-10-21 -// - Initial versioned release. - - -/* -This is free and unencumbered software released into the public domain. - -Anyone is free to copy, modify, publish, use, compile, sell, or -distribute this software, either in source code form or as a compiled -binary, for any purpose, commercial or non-commercial, and by any -means. - -In jurisdictions that recognize copyright laws, the author or authors -of this software dedicate any and all copyright interest in the -software to the public domain. We make this dedication for the benefit -of the public at large and to the detriment of our heirs and -successors. We intend this dedication to be an overt act of -relinquishment in perpetuity of all present and future rights to this -software under copyright law. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR -OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, -ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. - -For more information, please refer to -*/ diff --git a/src/external/miniaudio.h b/src/external/miniaudio.h new file mode 100644 index 00000000..c41f7a49 --- /dev/null +++ b/src/external/miniaudio.h @@ -0,0 +1,31816 @@ +/* +Audio playback and capture library. Choice of public domain or MIT-0. See license statements at the end of this file. +miniaudio (formerly mini_al) - v0.9 - 2019-03-06 + +David Reid - davidreidsoftware@gmail.com +*/ + +/* +MAJOR CHANGES IN VERSION 0.9 +============================ +Version 0.9 includes major API changes, centered mostly around full-duplex and the rebrand to "miniaudio". Before I go into +detail about the major changes I would like to apologize. I know it's annoying dealing with breaking API changes, but I think +it's best to get these changes out of the way now while the library is still relatively young and unknown. + +There's been a lot of refactoring with this release so there's a good chance a few bugs have been introduced. I apologize in +advance for this. You may want to hold off on upgrading for the short term if you're worried. If mini_al v0.8.14 works for +you, and you don't need full-duplex support, you can avoid upgrading (though you won't be getting future bug fixes). + + +Rebranding to "miniaudio" +------------------------- +The decision was made to rename mini_al to miniaudio. Don't worry, it's the same project. The reason for this is simple: + +1) Having the word "audio" in the title makes it immediately clear that the library is related to audio; and +2) I don't like the look of the underscore. + +This rebrand has necessitated a change in namespace from "mal" to "ma". I know this is annoying, and I apologize, but it's +better to get this out of the road now rather than later. Also, since there are necessary API changes for full-duplex support +I think it's better to just get the namespace change over and done with at the same time as the full-duplex changes. I'm hoping +this will be the last of the major API changes. Fingers crossed! + +The implementation define is now "#define MINIAUDIO_IMPLEMENTATION". You can also use "#define MA_IMPLEMENTATION" if that's +your preference. + + +Full-Duplex Support +------------------- +The major feature added to version 0.9 is full-duplex. This has necessitated a few API changes. + +1) The data callback has now changed. Previously there was one type of callback for playback and another for capture. I wanted + to avoid a third callback just for full-duplex so the decision was made to break this API and unify the callbacks. Now, + there is just one callback which is the same for all three modes (playback, capture, duplex). The new callback looks like + the following: + + void data_callback(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount); + + This callback allows you to move data straight out of the input buffer and into the output buffer in full-duplex mode. In + playback-only mode, pInput will be null. Likewise, pOutput will be null in capture-only mode. The sample count is no longer + returned from the callback since it's not necessary for miniaudio anymore. + +2) The device config needed to change in order to support full-duplex. Full-duplex requires the ability to allow the client + to choose a different PCM format for the playback and capture sides. The old ma_device_config object simply did not allow + this and needed to change. With these changes you now specify the device ID, format, channels, channel map and share mode + on a per-playback and per-capture basis (see example below). The sample rate must be the same for playback and capture. + + Since the device config API has changed I have also decided to take the opportunity to simplify device initialization. Now, + the device ID, device type and callback user data are set in the config. ma_device_init() is now simplified down to taking + just the context, device config and a pointer to the device object being initialized. The rationale for this change is that + it just makes more sense to me that these are set as part of the config like everything else. + + Example device initialization: + + ma_device_config config = ma_device_config_init(ma_device_type_duplex); // Or ma_device_type_playback or ma_device_type_capture. + config.playback.pDeviceID = &myPlaybackDeviceID; // Or NULL for the default playback device. + config.playback.format = ma_format_f32; + config.playback.channels = 2; + config.capture.pDeviceID = &myCaptureDeviceID; // Or NULL for the default capture device. + config.capture.format = ma_format_s16; + config.capture.channels = 1; + config.sampleRate = 44100; + config.dataCallback = data_callback; + config.pUserData = &myUserData; + + result = ma_device_init(&myContext, &config, &device); + if (result != MA_SUCCESS) { + ... handle error ... + } + + Note that the "onDataCallback" member of ma_device_config has been renamed to "dataCallback". Also, "onStopCallback" has + been renamed to "stopCallback". + +This is the first pass for full-duplex and there is a known bug. You will hear crackling on the following backends when sample +rate conversion is required for the playback device: + - Core Audio + - JACK + - AAudio + - OpenSL + - WebAudio + +In addition to the above, not all platforms have been absolutely thoroughly tested simply because I lack the hardware for such +thorough testing. If you experience a bug, an issue report on GitHub or an email would be greatly appreciated (and a sample +program that reproduces the issue if possible). + + +Other API Changes +----------------- +In addition to the above, the following API changes have been made: + +- The log callback is no longer passed to ma_context_config_init(). Instead you need to set it manually after initialization. +- The onLogCallback member of ma_context_config has been renamed to "logCallback". +- The log callback now takes a logLevel parameter. The new callback looks like: void log_callback(ma_context* pContext, ma_device* pDevice, ma_uint32 logLevel, const char* message) + - You can use ma_log_level_to_string() to convert the logLevel to human readable text if you want to log it. +- Some APIs have been renamed: + - mal_decoder_read() -> ma_decoder_read_pcm_frames() + - mal_decoder_seek_to_frame() -> ma_decoder_seek_to_pcm_frame() + - mal_sine_wave_read() -> ma_sine_wave_read_f32() + - mal_sine_wave_read_ex() -> ma_sine_wave_read_f32_ex() +- Some APIs have been removed: + - mal_device_get_buffer_size_in_bytes() + - mal_device_set_recv_callback() + - mal_device_set_send_callback() + - mal_src_set_input_sample_rate() + - mal_src_set_output_sample_rate() +- Error codes have been rearranged. If you're a binding maintainer you will need to update. +- The ma_backend enums have been rearranged to priority order. The rationale for this is to simplify automatic backend selection + and to make it easier to see the priority. If you're a binding maintainer you will need to update. +- ma_dsp has been renamed to ma_pcm_converter. The rationale for this change is that I'm expecting "ma_dsp" to conflict with + some future planned high-level APIs. +- For functions that take a pointer/count combo, such as ma_decoder_read_pcm_frames(), the parameter order has changed so that + the pointer comes before the count. The rationale for this is to keep it consistent with things like memcpy(). + + +Miscellaneous Changes +--------------------- +The following miscellaneous changes have also been made. + +- The AAudio backend has been added for Android 8 and above. This is Android's new "High-Performance Audio" API. (For the + record, this is one of the nicest audio APIs out there, just behind the BSD audio APIs). +- The WebAudio backend has been added. This is based on ScriptProcessorNode. This removes the need for SDL. +- The SDL and OpenAL backends have been removed. These were originally implemented to add support for platforms for which miniaudio + was not explicitly supported. These are no longer needed and have therefore been removed. +- Device initialization now fails if the requested share mode is not supported. If you ask for exclusive mode, you either get an + exclusive mode device, or an error. The rationale for this change is to give the client more control over how to handle cases + when the desired shared mode is unavailable. +- A lock-free ring buffer API has been added. There are two varients of this. "ma_rb" operates on bytes, whereas "ma_pcm_rb" + operates on PCM frames. +- The library is now licensed as a choice of Public Domain (Unlicense) _or_ MIT-0 (No Attribution) which is the same as MIT, but + removes the attribution requirement. The rationale for this is to support countries that don't recognize public domain. +*/ + +/* +ABOUT +===== +miniaudio is a single file library for audio playback and capture. It's written in C (compilable as +C++) and released into the public domain. + +Supported Backends: + - WASAPI + - DirectSound + - WinMM + - Core Audio (Apple) + - ALSA + - PulseAudio + - JACK + - sndio (OpenBSD) + - audio(4) (NetBSD and OpenBSD) + - OSS (FreeBSD) + - AAudio (Android 8.0+) + - OpenSL|ES (Android only) + - Web Audio (Emscripten) + - Null (Silence) + +Supported Formats: + - Unsigned 8-bit PCM + - Signed 16-bit PCM + - Signed 24-bit PCM (tightly packed) + - Signed 32-bit PCM + - IEEE 32-bit floating point PCM + + +USAGE +===== +miniaudio is a single-file library. To use it, do something like the following in one .c file. + #define MINIAUDIO_IMPLEMENTATION + #include "miniaudio.h" + +You can then #include this file in other parts of the program as you would with any other header file. + +miniaudio uses an asynchronous, callback based API. You initialize a device with a configuration (sample rate, +channel count, etc.) which includes the callback you want to use to handle data transmission to/from the +device. In the callback you either read from a data pointer in the case of playback or write to it in the case +of capture. + +Playback Example +---------------- + void data_callback(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount) + { + ma_decoder* pDecoder = (ma_decoder*)pDevice->pUserData; + if (pDecoder == NULL) { + return; + } + + ma_decoder_read_pcm_frames(pDecoder, frameCount, pOutput); + } + + ... + + ma_device_config config = ma_device_config_init(ma_device_type_playback); + config.playback.format = decoder.outputFormat; + config.playback.channels = decoder.outputChannels; + config.sampleRate = decoder.outputSampleRate; + config.dataCallback = data_callback; + config.pUserData = &decoder; + + ma_device device; + if (ma_device_init(NULL, &config, &device) != MA_SUCCESS) { + ... An error occurred ... + } + + ma_device_start(&device); // The device is sleeping by default so you'll need to start it manually. + + ... + + ma_device_uninit(&device); // This will stop the device so no need to do that manually. + + +BUILDING +======== +miniaudio should Just Work by adding it to your project's source tree. You do not need to download or install +any dependencies. See below for platform-specific details. + +If you want to disable a specific backend, #define the appropriate MA_NO_* option before the implementation. + +Note that GCC and Clang requires "-msse2", "-mavx2", etc. for SIMD optimizations. + + +Building for Windows +-------------------- +The Windows build should compile clean on all popular compilers without the need to configure any include paths +nor link to any libraries. + +Building for macOS and iOS +-------------------------- +The macOS build should compile clean without the need to download any dependencies or link to any libraries or +frameworks. The iOS build needs to be compiled as Objective-C (sorry) and will need to link the relevant frameworks +but should Just Work with Xcode. + +Building for Linux +------------------ +The Linux build only requires linking to -ldl, -lpthread and -lm. You do not need any development packages. + +Building for BSD +---------------- +The BSD build only requires linking to -ldl, -lpthread and -lm. NetBSD uses audio(4), OpenBSD uses sndio and +FreeBSD uses OSS. + +Building for Android +-------------------- +AAudio is the highest priority backend on Android. This should work out out of the box without needing any kind of +compiler configuration. Support for AAudio starts with Android 8 which means older versions will fall back to +OpenSL|ES which requires API level 16+. + +Building for Emscripten +----------------------- +The Emscripten build emits Web Audio JavaScript directly and should Just Work without any configuration. + + +NOTES +===== +- This library uses an asynchronous API for delivering and requesting audio data. Each device will have + it's own worker thread which is managed by the library. +- If ma_device_init() is called with a device that's not aligned to the platform's natural alignment + boundary (4 bytes on 32-bit, 8 bytes on 64-bit), it will _not_ be thread-safe. The reason for this + is that it depends on members of ma_device being correctly aligned for atomic assignments. +- Sample data is always native-endian and interleaved. For example, ma_format_s16 means signed 16-bit + integer samples, interleaved. Let me know if you need non-interleaved and I'll look into it. +- The sndio backend is currently only enabled on OpenBSD builds. +- The audio(4) backend is supported on OpenBSD, but you may need to disable sndiod before you can use it. +- Automatic stream routing is enabled on a per-backend basis. Support is explicitly enabled for WASAPI + and Core Audio, however other backends such as PulseAudio may naturally support it, though not all have + been tested. + + +BACKEND NUANCES +=============== + +PulseAudio +---------- +- If you experience bad glitching/noise on Arch Linux, consider this fix from the Arch wiki: + https://wiki.archlinux.org/index.php/PulseAudio/Troubleshooting#Glitches,_skips_or_crackling + Alternatively, consider using a different backend such as ALSA. + +Android +------- +- To capture audio on Android, remember to add the RECORD_AUDIO permission to your manifest: + +- With OpenSL|ES, only a single ma_context can be active at any given time. This is due to a limitation with OpenSL|ES. +- With AAudio, only default devices are enumerated. This is due to AAudio not having an enumeration API (devices are + enumerated through Java). You can however perform your own device enumeration through Java and then set the ID in the + ma_device_id structure (ma_device_id.aaudio) and pass it to ma_device_init(). +- The backend API will perform resampling where possible. The reason for this as opposed to using miniaudio's built-in + resampler is to take advantage of any potential device-specific optimizations the driver may implement. + +UWP +--- +- UWP only supports default playback and capture devices. +- UWP requires the Microphone capability to be enabled in the application's manifest (Package.appxmanifest): + + ... + + + + + +Web Audio / Emscripten +---------------------- +- The first time a context is initialized it will create a global object called "mal" whose primary purpose is to act + as a factory for device objects. +- Currently the Web Audio backend uses ScriptProcessorNode's, but this may need to change later as they've been deprecated. +- Google is implementing a policy in their browsers that prevent automatic media output without first receiving some kind + of user input. See here for details: https://developers.google.com/web/updates/2017/09/autoplay-policy-changes. Starting + the device may fail if you try to start playback without first handling some kind of user input. + + +OPTIONS +======= +#define these options before including this file. + +#define MA_NO_WASAPI + Disables the WASAPI backend. + +#define MA_NO_DSOUND + Disables the DirectSound backend. + +#define MA_NO_WINMM + Disables the WinMM backend. + +#define MA_NO_ALSA + Disables the ALSA backend. + +#define MA_NO_PULSEAUDIO + Disables the PulseAudio backend. + +#define MA_NO_JACK + Disables the JACK backend. + +#define MA_NO_COREAUDIO + Disables the Core Audio backend. + +#define MA_NO_SNDIO + Disables the sndio backend. + +#define MA_NO_AUDIO4 + Disables the audio(4) backend. + +#define MA_NO_OSS + Disables the OSS backend. + +#define MA_NO_AAUDIO + Disables the AAudio backend. + +#define MA_NO_OPENSL + Disables the OpenSL|ES backend. + +#define MA_NO_WEBAUDIO + Disables the Web Audio backend. + +#define MA_NO_NULL + Disables the null backend. + +#define MA_DEFAULT_PERIODS + When a period count of 0 is specified when a device is initialized, it will default to this. + +#define MA_BASE_BUFFER_SIZE_IN_MILLISECONDS_LOW_LATENCY +#define MA_BASE_BUFFER_SIZE_IN_MILLISECONDS_CONSERVATIVE + When a buffer size of 0 is specified when a device is initialized it will default to a buffer of this size, depending + on the chosen performance profile. These can be increased or decreased depending on your specific requirements. + +#define MA_NO_DECODING + Disables the decoding APIs. + +#define MA_NO_DEVICE_IO + Disables playback and recording. This will disable ma_context and ma_device APIs. This is useful if you only want to + use miniaudio's data conversion and/or decoding APIs. + +#define MA_NO_STDIO + Disables file IO APIs. + +#define MA_NO_SSE2 + Disables SSE2 optimizations. + +#define MA_NO_AVX2 + Disables AVX2 optimizations. + +#define MA_NO_AVX512 + Disables AVX-512 optimizations. + +#define MA_NO_NEON + Disables NEON optimizations. + +#define MA_LOG_LEVEL + Sets the logging level. Set level to one of the following: + MA_LOG_LEVEL_VERBOSE + MA_LOG_LEVEL_INFO + MA_LOG_LEVEL_WARNING + MA_LOG_LEVEL_ERROR + +#define MA_DEBUT_OUTPUT + Enable printf() debug output. + +#define MA_COINIT_VALUE + Windows only. The value to pass to internal calls to CoInitializeEx(). Defaults to COINIT_MULTITHREADED. + + +DEFINITIONS +=========== +This section defines common terms used throughout miniaudio. Unfortunately there is often ambiguity in the use of terms +throughout the audio space, so this section is intended to clarify how miniaudio uses each term. + +Sample +------ +A sample is a single unit of audio data. If the sample format is f32, then one sample is one 32-bit floating point number. + +Frame / PCM Frame +----------------- +A frame is a groups of samples equal to the number of channels. For a stereo stream a frame is 2 samples, a mono frame +is 1 sample, a 5.1 surround sound frame is 6 samples, etc. The terms "frame" and "PCM frame" are the same thing in +miniaudio. Note that this is different to a compressed frame. If ever miniaudio needs to refer to a compressed frame, such +as a FLAC frame, it will always clarify what it's referring to with something like "FLAC frame" or whatnot. + +Channel +------- +A stream of monaural audio that is emitted from an individual speaker in a speaker system, or received from an individual +microphone in a microphone system. A stereo stream has two channels (a left channel, and a right channel), a 5.1 surround +sound system has 6 channels, etc. Some audio systems refer to a channel as a complex audio stream that's mixed with other +channels to produce the final mix - this is completely different to miniaudio's use of the term "channel" and should not be +confused. + +Sample Rate +----------- +The sample rate in miniaudio is always expressed in Hz, such as 44100, 48000, etc. It's the number of PCM frames that are +processed per second. + +Formats +------- +Throughout miniaudio you will see references to different sample formats: + u8 - Unsigned 8-bit integer + s16 - Signed 16-bit integer + s24 - Signed 24-bit integer (tightly packed). + s32 - Signed 32-bit integer + f32 - 32-bit floating point +*/ + +#ifndef miniaudio_h +#define miniaudio_h + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(_MSC_VER) + #pragma warning(push) + #pragma warning(disable:4201) // nonstandard extension used: nameless struct/union + #pragma warning(disable:4324) // structure was padded due to alignment specifier +#endif + +// Platform/backend detection. +#ifdef _WIN32 + #define MA_WIN32 + #if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_PC_APP || WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP) + #define MA_WIN32_UWP + #else + #define MA_WIN32_DESKTOP + #endif +#else + #define MA_POSIX + #include // Unfortunate #include, but needed for pthread_t, pthread_mutex_t and pthread_cond_t types. + + #ifdef __unix__ + #define MA_UNIX + #if defined(__DragonFly__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) + #define MA_BSD + #endif + #endif + #ifdef __linux__ + #define MA_LINUX + #endif + #ifdef __APPLE__ + #define MA_APPLE + #endif + #ifdef __ANDROID__ + #define MA_ANDROID + #endif + #ifdef __EMSCRIPTEN__ + #define MA_EMSCRIPTEN + #endif +#endif + +#include /* For size_t. */ + +/* Sized types. Prefer built-in types. Fall back to stdint. */ +#ifdef _MSC_VER + #if defined(__clang__) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wlanguage-extension-token" + #pragma GCC diagnostic ignored "-Wc++11-long-long" + #endif + typedef signed __int8 ma_int8; + typedef unsigned __int8 ma_uint8; + typedef signed __int16 ma_int16; + typedef unsigned __int16 ma_uint16; + typedef signed __int32 ma_int32; + typedef unsigned __int32 ma_uint32; + typedef signed __int64 ma_int64; + typedef unsigned __int64 ma_uint64; + #if defined(__clang__) + #pragma GCC diagnostic pop + #endif +#else + #define MA_HAS_STDINT + #include + typedef int8_t ma_int8; + typedef uint8_t ma_uint8; + typedef int16_t ma_int16; + typedef uint16_t ma_uint16; + typedef int32_t ma_int32; + typedef uint32_t ma_uint32; + typedef int64_t ma_int64; + typedef uint64_t ma_uint64; +#endif + +#ifdef MA_HAS_STDINT + typedef uintptr_t ma_uintptr; +#else + #if defined(_WIN32) + #if defined(_WIN64) + typedef ma_uint64 ma_uintptr; + #else + typedef ma_uint32 ma_uintptr; + #endif + #elif defined(__GNUC__) + #if defined(__LP64__) + typedef ma_uint64 ma_uintptr; + #else + typedef ma_uint32 ma_uintptr; + #endif + #else + typedef ma_uint64 ma_uintptr; /* Fallback. */ + #endif +#endif + +typedef ma_uint8 ma_bool8; +typedef ma_uint32 ma_bool32; +#define MA_TRUE 1 +#define MA_FALSE 0 + +typedef void* ma_handle; +typedef void* ma_ptr; +typedef void (* ma_proc)(void); + +#if defined(_MSC_VER) && !defined(_WCHAR_T_DEFINED) +typedef ma_uint16 wchar_t; +#endif + +// Define NULL for some compilers. +#ifndef NULL +#define NULL 0 +#endif + +#if defined(SIZE_MAX) + #define MA_SIZE_MAX SIZE_MAX +#else + #define MA_SIZE_MAX 0xFFFFFFFF /* When SIZE_MAX is not defined by the standard library just default to the maximum 32-bit unsigned integer. */ +#endif + + +#ifdef _MSC_VER +#define MA_INLINE __forceinline +#else +#ifdef __GNUC__ +#define MA_INLINE inline __attribute__((always_inline)) +#else +#define MA_INLINE inline +#endif +#endif + +#ifdef _MSC_VER +#define MA_ALIGN(alignment) __declspec(align(alignment)) +#elif !defined(__DMC__) +#define MA_ALIGN(alignment) __attribute__((aligned(alignment))) +#else +#define MA_ALIGN(alignment) +#endif + +#ifdef _MSC_VER +#define MA_ALIGNED_STRUCT(alignment) MA_ALIGN(alignment) struct +#else +#define MA_ALIGNED_STRUCT(alignment) struct MA_ALIGN(alignment) +#endif + +// SIMD alignment in bytes. Currently set to 64 bytes in preparation for future AVX-512 optimizations. +#define MA_SIMD_ALIGNMENT 64 + + +// Logging levels +#define MA_LOG_LEVEL_VERBOSE 4 +#define MA_LOG_LEVEL_INFO 3 +#define MA_LOG_LEVEL_WARNING 2 +#define MA_LOG_LEVEL_ERROR 1 + +#ifndef MA_LOG_LEVEL +#define MA_LOG_LEVEL MA_LOG_LEVEL_ERROR +#endif + +typedef struct ma_context ma_context; +typedef struct ma_device ma_device; + +typedef ma_uint8 ma_channel; +#define MA_CHANNEL_NONE 0 +#define MA_CHANNEL_MONO 1 +#define MA_CHANNEL_FRONT_LEFT 2 +#define MA_CHANNEL_FRONT_RIGHT 3 +#define MA_CHANNEL_FRONT_CENTER 4 +#define MA_CHANNEL_LFE 5 +#define MA_CHANNEL_BACK_LEFT 6 +#define MA_CHANNEL_BACK_RIGHT 7 +#define MA_CHANNEL_FRONT_LEFT_CENTER 8 +#define MA_CHANNEL_FRONT_RIGHT_CENTER 9 +#define MA_CHANNEL_BACK_CENTER 10 +#define MA_CHANNEL_SIDE_LEFT 11 +#define MA_CHANNEL_SIDE_RIGHT 12 +#define MA_CHANNEL_TOP_CENTER 13 +#define MA_CHANNEL_TOP_FRONT_LEFT 14 +#define MA_CHANNEL_TOP_FRONT_CENTER 15 +#define MA_CHANNEL_TOP_FRONT_RIGHT 16 +#define MA_CHANNEL_TOP_BACK_LEFT 17 +#define MA_CHANNEL_TOP_BACK_CENTER 18 +#define MA_CHANNEL_TOP_BACK_RIGHT 19 +#define MA_CHANNEL_AUX_0 20 +#define MA_CHANNEL_AUX_1 21 +#define MA_CHANNEL_AUX_2 22 +#define MA_CHANNEL_AUX_3 23 +#define MA_CHANNEL_AUX_4 24 +#define MA_CHANNEL_AUX_5 25 +#define MA_CHANNEL_AUX_6 26 +#define MA_CHANNEL_AUX_7 27 +#define MA_CHANNEL_AUX_8 28 +#define MA_CHANNEL_AUX_9 29 +#define MA_CHANNEL_AUX_10 30 +#define MA_CHANNEL_AUX_11 31 +#define MA_CHANNEL_AUX_12 32 +#define MA_CHANNEL_AUX_13 33 +#define MA_CHANNEL_AUX_14 34 +#define MA_CHANNEL_AUX_15 35 +#define MA_CHANNEL_AUX_16 36 +#define MA_CHANNEL_AUX_17 37 +#define MA_CHANNEL_AUX_18 38 +#define MA_CHANNEL_AUX_19 39 +#define MA_CHANNEL_AUX_20 40 +#define MA_CHANNEL_AUX_21 41 +#define MA_CHANNEL_AUX_22 42 +#define MA_CHANNEL_AUX_23 43 +#define MA_CHANNEL_AUX_24 44 +#define MA_CHANNEL_AUX_25 45 +#define MA_CHANNEL_AUX_26 46 +#define MA_CHANNEL_AUX_27 47 +#define MA_CHANNEL_AUX_28 48 +#define MA_CHANNEL_AUX_29 49 +#define MA_CHANNEL_AUX_30 50 +#define MA_CHANNEL_AUX_31 51 +#define MA_CHANNEL_LEFT MA_CHANNEL_FRONT_LEFT +#define MA_CHANNEL_RIGHT MA_CHANNEL_FRONT_RIGHT +#define MA_CHANNEL_POSITION_COUNT MA_CHANNEL_AUX_31 + 1 + + +typedef int ma_result; +#define MA_SUCCESS 0 + +/* General errors. */ +#define MA_ERROR -1 /* A generic error. */ +#define MA_INVALID_ARGS -2 +#define MA_INVALID_OPERATION -3 +#define MA_OUT_OF_MEMORY -4 +#define MA_ACCESS_DENIED -5 +#define MA_TOO_LARGE -6 +#define MA_TIMEOUT -7 + +/* General miniaudio-specific errors. */ +#define MA_FORMAT_NOT_SUPPORTED -100 +#define MA_DEVICE_TYPE_NOT_SUPPORTED -101 +#define MA_SHARE_MODE_NOT_SUPPORTED -102 +#define MA_NO_BACKEND -103 +#define MA_NO_DEVICE -104 +#define MA_API_NOT_FOUND -105 +#define MA_INVALID_DEVICE_CONFIG -106 + +/* State errors. */ +#define MA_DEVICE_BUSY -200 +#define MA_DEVICE_NOT_INITIALIZED -201 +#define MA_DEVICE_NOT_STARTED -202 +#define MA_DEVICE_UNAVAILABLE -203 + +/* Operation errors. */ +#define MA_FAILED_TO_MAP_DEVICE_BUFFER -300 +#define MA_FAILED_TO_UNMAP_DEVICE_BUFFER -301 +#define MA_FAILED_TO_INIT_BACKEND -302 +#define MA_FAILED_TO_READ_DATA_FROM_CLIENT -303 +#define MA_FAILED_TO_READ_DATA_FROM_DEVICE -304 +#define MA_FAILED_TO_SEND_DATA_TO_CLIENT -305 +#define MA_FAILED_TO_SEND_DATA_TO_DEVICE -306 +#define MA_FAILED_TO_OPEN_BACKEND_DEVICE -307 +#define MA_FAILED_TO_START_BACKEND_DEVICE -308 +#define MA_FAILED_TO_STOP_BACKEND_DEVICE -309 +#define MA_FAILED_TO_CONFIGURE_BACKEND_DEVICE -310 +#define MA_FAILED_TO_CREATE_MUTEX -311 +#define MA_FAILED_TO_CREATE_EVENT -312 +#define MA_FAILED_TO_CREATE_THREAD -313 + + +// Standard sample rates. +#define MA_SAMPLE_RATE_8000 8000 +#define MA_SAMPLE_RATE_11025 11025 +#define MA_SAMPLE_RATE_16000 16000 +#define MA_SAMPLE_RATE_22050 22050 +#define MA_SAMPLE_RATE_24000 24000 +#define MA_SAMPLE_RATE_32000 32000 +#define MA_SAMPLE_RATE_44100 44100 +#define MA_SAMPLE_RATE_48000 48000 +#define MA_SAMPLE_RATE_88200 88200 +#define MA_SAMPLE_RATE_96000 96000 +#define MA_SAMPLE_RATE_176400 176400 +#define MA_SAMPLE_RATE_192000 192000 +#define MA_SAMPLE_RATE_352800 352800 +#define MA_SAMPLE_RATE_384000 384000 + +#define MA_MIN_PCM_SAMPLE_SIZE_IN_BYTES 1 // For simplicity, miniaudio does not support PCM samples that are not byte aligned. +#define MA_MAX_PCM_SAMPLE_SIZE_IN_BYTES 8 +#define MA_MIN_CHANNELS 1 +#define MA_MAX_CHANNELS 32 +#define MA_MIN_SAMPLE_RATE MA_SAMPLE_RATE_8000 +#define MA_MAX_SAMPLE_RATE MA_SAMPLE_RATE_384000 +#define MA_SRC_SINC_MIN_WINDOW_WIDTH 2 +#define MA_SRC_SINC_MAX_WINDOW_WIDTH 32 +#define MA_SRC_SINC_DEFAULT_WINDOW_WIDTH 32 +#define MA_SRC_SINC_LOOKUP_TABLE_RESOLUTION 8 +#define MA_SRC_INPUT_BUFFER_SIZE_IN_SAMPLES 256 + +typedef enum +{ + ma_stream_format_pcm = 0, +} ma_stream_format; + +typedef enum +{ + ma_stream_layout_interleaved = 0, + ma_stream_layout_deinterleaved +} ma_stream_layout; + +typedef enum +{ + ma_dither_mode_none = 0, + ma_dither_mode_rectangle, + ma_dither_mode_triangle +} ma_dither_mode; + +typedef enum +{ + // I like to keep these explicitly defined because they're used as a key into a lookup table. When items are + // added to this, make sure there are no gaps and that they're added to the lookup table in ma_get_bytes_per_sample(). + ma_format_unknown = 0, // Mainly used for indicating an error, but also used as the default for the output format for decoders. + ma_format_u8 = 1, + ma_format_s16 = 2, // Seems to be the most widely supported format. + ma_format_s24 = 3, // Tightly packed. 3 bytes per sample. + ma_format_s32 = 4, + ma_format_f32 = 5, + ma_format_count +} ma_format; + +typedef enum +{ + ma_channel_mix_mode_rectangular = 0, // Simple averaging based on the plane(s) the channel is sitting on. + ma_channel_mix_mode_simple, // Drop excess channels; zeroed out extra channels. + ma_channel_mix_mode_custom_weights, // Use custom weights specified in ma_channel_router_config. + ma_channel_mix_mode_planar_blend = ma_channel_mix_mode_rectangular, + ma_channel_mix_mode_default = ma_channel_mix_mode_planar_blend +} ma_channel_mix_mode; + +typedef enum +{ + ma_standard_channel_map_microsoft, + ma_standard_channel_map_alsa, + ma_standard_channel_map_rfc3551, // Based off AIFF. + ma_standard_channel_map_flac, + ma_standard_channel_map_vorbis, + ma_standard_channel_map_sound4, // FreeBSD's sound(4). + ma_standard_channel_map_sndio, // www.sndio.org/tips.html + ma_standard_channel_map_webaudio = ma_standard_channel_map_flac, // https://webaudio.github.io/web-audio-api/#ChannelOrdering. Only 1, 2, 4 and 6 channels are defined, but can fill in the gaps with logical assumptions. + ma_standard_channel_map_default = ma_standard_channel_map_microsoft +} ma_standard_channel_map; + +typedef enum +{ + ma_performance_profile_low_latency = 0, + ma_performance_profile_conservative +} ma_performance_profile; + + +typedef struct ma_format_converter ma_format_converter; +typedef ma_uint32 (* ma_format_converter_read_proc) (ma_format_converter* pConverter, ma_uint32 frameCount, void* pFramesOut, void* pUserData); +typedef ma_uint32 (* ma_format_converter_read_deinterleaved_proc)(ma_format_converter* pConverter, ma_uint32 frameCount, void** ppSamplesOut, void* pUserData); + +typedef struct +{ + ma_format formatIn; + ma_format formatOut; + ma_uint32 channels; + ma_stream_format streamFormatIn; + ma_stream_format streamFormatOut; + ma_dither_mode ditherMode; + ma_bool32 noSSE2 : 1; + ma_bool32 noAVX2 : 1; + ma_bool32 noAVX512 : 1; + ma_bool32 noNEON : 1; + ma_format_converter_read_proc onRead; + ma_format_converter_read_deinterleaved_proc onReadDeinterleaved; + void* pUserData; +} ma_format_converter_config; + +struct ma_format_converter +{ + ma_format_converter_config config; + ma_bool32 useSSE2 : 1; + ma_bool32 useAVX2 : 1; + ma_bool32 useAVX512 : 1; + ma_bool32 useNEON : 1; + void (* onConvertPCM)(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode); + void (* onInterleavePCM)(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels); + void (* onDeinterleavePCM)(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels); +}; + + + +typedef struct ma_channel_router ma_channel_router; +typedef ma_uint32 (* ma_channel_router_read_deinterleaved_proc)(ma_channel_router* pRouter, ma_uint32 frameCount, void** ppSamplesOut, void* pUserData); + +typedef struct +{ + ma_uint32 channelsIn; + ma_uint32 channelsOut; + ma_channel channelMapIn[MA_MAX_CHANNELS]; + ma_channel channelMapOut[MA_MAX_CHANNELS]; + ma_channel_mix_mode mixingMode; + float weights[MA_MAX_CHANNELS][MA_MAX_CHANNELS]; // [in][out]. Only used when mixingMode is set to ma_channel_mix_mode_custom_weights. + ma_bool32 noSSE2 : 1; + ma_bool32 noAVX2 : 1; + ma_bool32 noAVX512 : 1; + ma_bool32 noNEON : 1; + ma_channel_router_read_deinterleaved_proc onReadDeinterleaved; + void* pUserData; +} ma_channel_router_config; + +struct ma_channel_router +{ + ma_channel_router_config config; + ma_bool32 isPassthrough : 1; + ma_bool32 isSimpleShuffle : 1; + ma_bool32 useSSE2 : 1; + ma_bool32 useAVX2 : 1; + ma_bool32 useAVX512 : 1; + ma_bool32 useNEON : 1; + ma_uint8 shuffleTable[MA_MAX_CHANNELS]; +}; + + + +typedef struct ma_src ma_src; +typedef ma_uint32 (* ma_src_read_deinterleaved_proc)(ma_src* pSRC, ma_uint32 frameCount, void** ppSamplesOut, void* pUserData); // Returns the number of frames that were read. + +typedef enum +{ + ma_src_algorithm_linear = 0, + ma_src_algorithm_sinc, + ma_src_algorithm_none, + ma_src_algorithm_default = ma_src_algorithm_linear +} ma_src_algorithm; + +typedef enum +{ + ma_src_sinc_window_function_hann = 0, + ma_src_sinc_window_function_rectangular, + ma_src_sinc_window_function_default = ma_src_sinc_window_function_hann +} ma_src_sinc_window_function; + +typedef struct +{ + ma_src_sinc_window_function windowFunction; + ma_uint32 windowWidth; +} ma_src_config_sinc; + +typedef struct +{ + ma_uint32 sampleRateIn; + ma_uint32 sampleRateOut; + ma_uint32 channels; + ma_src_algorithm algorithm; + ma_bool32 neverConsumeEndOfInput : 1; + ma_bool32 noSSE2 : 1; + ma_bool32 noAVX2 : 1; + ma_bool32 noAVX512 : 1; + ma_bool32 noNEON : 1; + ma_src_read_deinterleaved_proc onReadDeinterleaved; + void* pUserData; + union + { + ma_src_config_sinc sinc; + }; +} ma_src_config; + +MA_ALIGNED_STRUCT(MA_SIMD_ALIGNMENT) ma_src +{ + union + { + struct + { + MA_ALIGN(MA_SIMD_ALIGNMENT) float input[MA_MAX_CHANNELS][MA_SRC_INPUT_BUFFER_SIZE_IN_SAMPLES]; + float timeIn; + ma_uint32 leftoverFrames; + } linear; + + struct + { + MA_ALIGN(MA_SIMD_ALIGNMENT) float input[MA_MAX_CHANNELS][MA_SRC_SINC_MAX_WINDOW_WIDTH*2 + MA_SRC_INPUT_BUFFER_SIZE_IN_SAMPLES]; + float timeIn; + ma_uint32 inputFrameCount; // The number of frames sitting in the input buffer, not including the first half of the window. + ma_uint32 windowPosInSamples; // An offset of . + float table[MA_SRC_SINC_MAX_WINDOW_WIDTH*1 * MA_SRC_SINC_LOOKUP_TABLE_RESOLUTION]; // Precomputed lookup table. The +1 is used to avoid the need for an overflow check. + } sinc; + }; + + ma_src_config config; + ma_bool32 isEndOfInputLoaded : 1; + ma_bool32 useSSE2 : 1; + ma_bool32 useAVX2 : 1; + ma_bool32 useAVX512 : 1; + ma_bool32 useNEON : 1; +}; + +typedef struct ma_pcm_converter ma_pcm_converter; +typedef ma_uint32 (* ma_pcm_converter_read_proc)(ma_pcm_converter* pDSP, void* pSamplesOut, ma_uint32 frameCount, void* pUserData); + +typedef struct +{ + ma_format formatIn; + ma_uint32 channelsIn; + ma_uint32 sampleRateIn; + ma_channel channelMapIn[MA_MAX_CHANNELS]; + ma_format formatOut; + ma_uint32 channelsOut; + ma_uint32 sampleRateOut; + ma_channel channelMapOut[MA_MAX_CHANNELS]; + ma_channel_mix_mode channelMixMode; + ma_dither_mode ditherMode; + ma_src_algorithm srcAlgorithm; + ma_bool32 allowDynamicSampleRate; + ma_bool32 neverConsumeEndOfInput : 1; // <-- For SRC. + ma_bool32 noSSE2 : 1; + ma_bool32 noAVX2 : 1; + ma_bool32 noAVX512 : 1; + ma_bool32 noNEON : 1; + ma_pcm_converter_read_proc onRead; + void* pUserData; + union + { + ma_src_config_sinc sinc; + }; +} ma_pcm_converter_config; + +MA_ALIGNED_STRUCT(MA_SIMD_ALIGNMENT) ma_pcm_converter +{ + ma_pcm_converter_read_proc onRead; + void* pUserData; + ma_format_converter formatConverterIn; // For converting data to f32 in preparation for further processing. + ma_format_converter formatConverterOut; // For converting data to the requested output format. Used as the final step in the processing pipeline. + ma_channel_router channelRouter; // For channel conversion. + ma_src src; // For sample rate conversion. + ma_bool32 isDynamicSampleRateAllowed : 1; // ma_pcm_converter_set_input_sample_rate() and ma_pcm_converter_set_output_sample_rate() will fail if this is set to false. + ma_bool32 isPreFormatConversionRequired : 1; + ma_bool32 isPostFormatConversionRequired : 1; + ma_bool32 isChannelRoutingRequired : 1; + ma_bool32 isSRCRequired : 1; + ma_bool32 isChannelRoutingAtStart : 1; + ma_bool32 isPassthrough : 1; // <-- Will be set to true when the DSP pipeline is an optimized passthrough. +}; + + +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// +// DATA CONVERSION +// =============== +// +// This section contains the APIs for data conversion. You will find everything here for channel mapping, sample format conversion, resampling, etc. +// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Channel Maps +// ============ +// +// Below is the channel map used by ma_standard_channel_map_default: +// +// |---------------|------------------------------| +// | Channel Count | Mapping | +// |---------------|------------------------------| +// | 1 (Mono) | 0: MA_CHANNEL_MONO | +// |---------------|------------------------------| +// | 2 (Stereo) | 0: MA_CHANNEL_FRONT_LEFT | +// | | 1: MA_CHANNEL_FRONT_RIGHT | +// |---------------|------------------------------| +// | 3 | 0: MA_CHANNEL_FRONT_LEFT | +// | | 1: MA_CHANNEL_FRONT_RIGHT | +// | | 2: MA_CHANNEL_FRONT_CENTER | +// |---------------|------------------------------| +// | 4 (Surround) | 0: MA_CHANNEL_FRONT_LEFT | +// | | 1: MA_CHANNEL_FRONT_RIGHT | +// | | 2: MA_CHANNEL_FRONT_CENTER | +// | | 3: MA_CHANNEL_BACK_CENTER | +// |---------------|------------------------------| +// | 5 | 0: MA_CHANNEL_FRONT_LEFT | +// | | 1: MA_CHANNEL_FRONT_RIGHT | +// | | 2: MA_CHANNEL_FRONT_CENTER | +// | | 3: MA_CHANNEL_BACK_LEFT | +// | | 4: MA_CHANNEL_BACK_RIGHT | +// |---------------|------------------------------| +// | 6 (5.1) | 0: MA_CHANNEL_FRONT_LEFT | +// | | 1: MA_CHANNEL_FRONT_RIGHT | +// | | 2: MA_CHANNEL_FRONT_CENTER | +// | | 3: MA_CHANNEL_LFE | +// | | 4: MA_CHANNEL_SIDE_LEFT | +// | | 5: MA_CHANNEL_SIDE_RIGHT | +// |---------------|------------------------------| +// | 7 | 0: MA_CHANNEL_FRONT_LEFT | +// | | 1: MA_CHANNEL_FRONT_RIGHT | +// | | 2: MA_CHANNEL_FRONT_CENTER | +// | | 3: MA_CHANNEL_LFE | +// | | 4: MA_CHANNEL_BACK_CENTER | +// | | 4: MA_CHANNEL_SIDE_LEFT | +// | | 5: MA_CHANNEL_SIDE_RIGHT | +// |---------------|------------------------------| +// | 8 (7.1) | 0: MA_CHANNEL_FRONT_LEFT | +// | | 1: MA_CHANNEL_FRONT_RIGHT | +// | | 2: MA_CHANNEL_FRONT_CENTER | +// | | 3: MA_CHANNEL_LFE | +// | | 4: MA_CHANNEL_BACK_LEFT | +// | | 5: MA_CHANNEL_BACK_RIGHT | +// | | 6: MA_CHANNEL_SIDE_LEFT | +// | | 7: MA_CHANNEL_SIDE_RIGHT | +// |---------------|------------------------------| +// | Other | All channels set to 0. This | +// | | is equivalent to the same | +// | | mapping as the device. | +// |---------------|------------------------------| +// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +// Helper for retrieving a standard channel map. +void ma_get_standard_channel_map(ma_standard_channel_map standardChannelMap, ma_uint32 channels, ma_channel channelMap[MA_MAX_CHANNELS]); + +// Copies a channel map. +void ma_channel_map_copy(ma_channel* pOut, const ma_channel* pIn, ma_uint32 channels); + + +// Determines whether or not a channel map is valid. +// +// A blank channel map is valid (all channels set to MA_CHANNEL_NONE). The way a blank channel map is handled is context specific, but +// is usually treated as a passthrough. +// +// Invalid channel maps: +// - A channel map with no channels +// - A channel map with more than one channel and a mono channel +ma_bool32 ma_channel_map_valid(ma_uint32 channels, const ma_channel channelMap[MA_MAX_CHANNELS]); + +// Helper for comparing two channel maps for equality. +// +// This assumes the channel count is the same between the two. +ma_bool32 ma_channel_map_equal(ma_uint32 channels, const ma_channel channelMapA[MA_MAX_CHANNELS], const ma_channel channelMapB[MA_MAX_CHANNELS]); + +// Helper for determining if a channel map is blank (all channels set to MA_CHANNEL_NONE). +ma_bool32 ma_channel_map_blank(ma_uint32 channels, const ma_channel channelMap[MA_MAX_CHANNELS]); + +// Helper for determining whether or not a channel is present in the given channel map. +ma_bool32 ma_channel_map_contains_channel_position(ma_uint32 channels, const ma_channel channelMap[MA_MAX_CHANNELS], ma_channel channelPosition); + + +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Format Conversion +// ================= +// The format converter serves two purposes: +// 1) Conversion between data formats (u8 to f32, etc.) +// 2) Interleaving and deinterleaving +// +// When initializing a converter, you specify the input and output formats (u8, s16, etc.) and read callbacks. There are two read callbacks - one for +// interleaved input data (onRead) and another for deinterleaved input data (onReadDeinterleaved). You implement whichever is most convenient for you. You +// can implement both, but it's not recommended as it just introduces unnecessary complexity. +// +// To read data as interleaved samples, use ma_format_converter_read(). Otherwise use ma_format_converter_read_deinterleaved(). +// +// Dithering +// --------- +// The format converter also supports dithering. Dithering can be set using ditherMode variable in the config, like so. +// +// pConfig->ditherMode = ma_dither_mode_rectangle; +// +// The different dithering modes include the following, in order of efficiency: +// - None: ma_dither_mode_none +// - Rectangle: ma_dither_mode_rectangle +// - Triangle: ma_dither_mode_triangle +// +// Note that even if the dither mode is set to something other than ma_dither_mode_none, it will be ignored for conversions where dithering is not needed. +// Dithering is available for the following conversions: +// - s16 -> u8 +// - s24 -> u8 +// - s32 -> u8 +// - f32 -> u8 +// - s24 -> s16 +// - s32 -> s16 +// - f32 -> s16 +// +// Note that it is not an error to pass something other than ma_dither_mode_none for conversions where dither is not used. It will just be ignored. +// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +// Initializes a format converter. +ma_result ma_format_converter_init(const ma_format_converter_config* pConfig, ma_format_converter* pConverter); + +// Reads data from the format converter as interleaved channels. +ma_uint64 ma_format_converter_read(ma_format_converter* pConverter, ma_uint64 frameCount, void* pFramesOut, void* pUserData); + +// Reads data from the format converter as deinterleaved channels. +ma_uint64 ma_format_converter_read_deinterleaved(ma_format_converter* pConverter, ma_uint64 frameCount, void** ppSamplesOut, void* pUserData); + + +// Helper for initializing a format converter config. +ma_format_converter_config ma_format_converter_config_init_new(void); +ma_format_converter_config ma_format_converter_config_init(ma_format formatIn, ma_format formatOut, ma_uint32 channels, ma_format_converter_read_proc onRead, void* pUserData); +ma_format_converter_config ma_format_converter_config_init_deinterleaved(ma_format formatIn, ma_format formatOut, ma_uint32 channels, ma_format_converter_read_deinterleaved_proc onReadDeinterleaved, void* pUserData); + + + +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Channel Routing +// =============== +// There are two main things you can do with the channel router: +// 1) Rearrange channels +// 2) Convert from one channel count to another +// +// Channel Rearrangement +// --------------------- +// A simple example of channel rearrangement may be swapping the left and right channels in a stereo stream. To do this you just pass in the same channel +// count for both the input and output with channel maps that contain the same channels (in a different order). +// +// Channel Conversion +// ------------------ +// The channel router can also convert from one channel count to another, such as converting a 5.1 stream to stero. When changing the channel count, the +// router will first perform a 1:1 mapping of channel positions that are present in both the input and output channel maps. The second thing it will do +// is distribute the input mono channel (if any) across all output channels, excluding any None and LFE channels. If there is an output mono channel, all +// input channels will be averaged, excluding any None and LFE channels. +// +// The last case to consider is when a channel position in the input channel map is not present in the output channel map, and vice versa. In this case the +// channel router will perform a blend of other related channels to produce an audible channel. There are several blending modes. +// 1) Simple +// Unmatched channels are silenced. +// 2) Planar Blending +// Channels are blended based on a set of planes that each speaker emits audio from. +// +// Rectangular / Planar Blending +// ----------------------------- +// In this mode, channel positions are associated with a set of planes where the channel conceptually emits audio from. An example is the front/left speaker. +// This speaker is positioned to the front of the listener, so you can think of it as emitting audio from the front plane. It is also positioned to the left +// of the listener so you can think of it as also emitting audio from the left plane. Now consider the (unrealistic) situation where the input channel map +// contains only the front/left channel position, but the output channel map contains both the front/left and front/center channel. When deciding on the audio +// data to send to the front/center speaker (which has no 1:1 mapping with an input channel) we need to use some logic based on our available input channel +// positions. +// +// As mentioned earlier, our front/left speaker is, conceptually speaking, emitting audio from the front _and_ the left planes. Similarly, the front/center +// speaker is emitting audio from _only_ the front plane. What these two channels have in common is that they are both emitting audio from the front plane. +// Thus, it makes sense that the front/center speaker should receive some contribution from the front/left channel. How much contribution depends on their +// planar relationship (thus the name of this blending technique). +// +// Because the front/left channel is emitting audio from two planes (front and left), you can think of it as though it's willing to dedicate 50% of it's total +// volume to each of it's planes (a channel position emitting from 1 plane would be willing to given 100% of it's total volume to that plane, and a channel +// position emitting from 3 planes would be willing to given 33% of it's total volume to each plane). Similarly, the front/center speaker is emitting audio +// from only one plane so you can think of it as though it's willing to _take_ 100% of it's volume from front plane emissions. Now, since the front/left +// channel is willing to _give_ 50% of it's total volume to the front plane, and the front/center speaker is willing to _take_ 100% of it's total volume +// from the front, you can imagine that 50% of the front/left speaker will be given to the front/center speaker. +// +// Usage +// ----- +// To use the channel router you need to specify three things: +// 1) The input channel count and channel map +// 2) The output channel count and channel map +// 3) The mixing mode to use in the case where a 1:1 mapping is unavailable +// +// Note that input and output data is always deinterleaved 32-bit floating point. +// +// Initialize the channel router with ma_channel_router_init(). You will need to pass in a config object which specifies the input and output configuration, +// mixing mode and a callback for sending data to the router. This callback will be called when input data needs to be sent to the router for processing. Note +// that the mixing mode is only used when a 1:1 mapping is unavailable. This includes the custom weights mode. +// +// Read data from the channel router with ma_channel_router_read_deinterleaved(). Output data is always 32-bit floating point. +// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +// Initializes a channel router where it is assumed that the input data is non-interleaved. +ma_result ma_channel_router_init(const ma_channel_router_config* pConfig, ma_channel_router* pRouter); + +// Reads data from the channel router as deinterleaved channels. +ma_uint64 ma_channel_router_read_deinterleaved(ma_channel_router* pRouter, ma_uint64 frameCount, void** ppSamplesOut, void* pUserData); + +// Helper for initializing a channel router config. +ma_channel_router_config ma_channel_router_config_init(ma_uint32 channelsIn, const ma_channel channelMapIn[MA_MAX_CHANNELS], ma_uint32 channelsOut, const ma_channel channelMapOut[MA_MAX_CHANNELS], ma_channel_mix_mode mixingMode, ma_channel_router_read_deinterleaved_proc onRead, void* pUserData); + + +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Sample Rate Conversion +// ====================== +// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +// Initializes a sample rate conversion object. +ma_result ma_src_init(const ma_src_config* pConfig, ma_src* pSRC); + +// Dynamically adjusts the sample rate. +// +// This is useful for dynamically adjust pitch. Keep in mind, however, that this will speed up or slow down the sound. If this +// is not acceptable you will need to use your own algorithm. +ma_result ma_src_set_sample_rate(ma_src* pSRC, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut); + +// Reads a number of frames. +// +// Returns the number of frames actually read. +ma_uint64 ma_src_read_deinterleaved(ma_src* pSRC, ma_uint64 frameCount, void** ppSamplesOut, void* pUserData); + + +// Helper for creating a sample rate conversion config. +ma_src_config ma_src_config_init_new(void); +ma_src_config ma_src_config_init(ma_uint32 sampleRateIn, ma_uint32 sampleRateOut, ma_uint32 channels, ma_src_read_deinterleaved_proc onReadDeinterleaved, void* pUserData); + + +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Conversion +// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +// Initializes a DSP object. +ma_result ma_pcm_converter_init(const ma_pcm_converter_config* pConfig, ma_pcm_converter* pDSP); + +// Dynamically adjusts the input sample rate. +// +// This will fail is the DSP was not initialized with allowDynamicSampleRate. +// +// DEPRECATED. Use ma_pcm_converter_set_sample_rate() instead. +ma_result ma_pcm_converter_set_input_sample_rate(ma_pcm_converter* pDSP, ma_uint32 sampleRateOut); + +// Dynamically adjusts the output sample rate. +// +// This is useful for dynamically adjust pitch. Keep in mind, however, that this will speed up or slow down the sound. If this +// is not acceptable you will need to use your own algorithm. +// +// This will fail is the DSP was not initialized with allowDynamicSampleRate. +// +// DEPRECATED. Use ma_pcm_converter_set_sample_rate() instead. +ma_result ma_pcm_converter_set_output_sample_rate(ma_pcm_converter* pDSP, ma_uint32 sampleRateOut); + +// Dynamically adjusts the output sample rate. +// +// This is useful for dynamically adjust pitch. Keep in mind, however, that this will speed up or slow down the sound. If this +// is not acceptable you will need to use your own algorithm. +// +// This will fail is the DSP was not initialized with allowDynamicSampleRate. +ma_result ma_pcm_converter_set_sample_rate(ma_pcm_converter* pDSP, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut); + + +// Reads a number of frames and runs them through the DSP processor. +ma_uint64 ma_pcm_converter_read(ma_pcm_converter* pDSP, void* pFramesOut, ma_uint64 frameCount); + +// Helper for initializing a ma_pcm_converter_config object. +ma_pcm_converter_config ma_pcm_converter_config_init_new(void); +ma_pcm_converter_config ma_pcm_converter_config_init(ma_format formatIn, ma_uint32 channelsIn, ma_uint32 sampleRateIn, ma_format formatOut, ma_uint32 channelsOut, ma_uint32 sampleRateOut, ma_pcm_converter_read_proc onRead, void* pUserData); +ma_pcm_converter_config ma_pcm_converter_config_init_ex(ma_format formatIn, ma_uint32 channelsIn, ma_uint32 sampleRateIn, ma_channel channelMapIn[MA_MAX_CHANNELS], ma_format formatOut, ma_uint32 channelsOut, ma_uint32 sampleRateOut, ma_channel channelMapOut[MA_MAX_CHANNELS], ma_pcm_converter_read_proc onRead, void* pUserData); + + +// High-level helper for doing a full format conversion in one go. Returns the number of output frames. Call this with pOut set to NULL to +// determine the required size of the output buffer. +// +// A return value of 0 indicates an error. +// +// This function is useful for one-off bulk conversions, but if you're streaming data you should use the DSP APIs instead. +ma_uint64 ma_convert_frames(void* pOut, ma_format formatOut, ma_uint32 channelsOut, ma_uint32 sampleRateOut, const void* pIn, ma_format formatIn, ma_uint32 channelsIn, ma_uint32 sampleRateIn, ma_uint64 frameCount); +ma_uint64 ma_convert_frames_ex(void* pOut, ma_format formatOut, ma_uint32 channelsOut, ma_uint32 sampleRateOut, ma_channel channelMapOut[MA_MAX_CHANNELS], const void* pIn, ma_format formatIn, ma_uint32 channelsIn, ma_uint32 sampleRateIn, ma_channel channelMapIn[MA_MAX_CHANNELS], ma_uint64 frameCount); + + +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Ring Buffer +// =========== +// +// Features +// -------- +// - Lock free (assuming single producer, single consumer) +// - Support for interleaved and deinterleaved streams +// - Allows the caller to allocate their own block of memory +// +// Usage +// ----- +// - Call ma_rb_init() to initialize a simple buffer, with an optional pre-allocated buffer. If you pass in NULL +// for the pre-allocated buffer, it will be allocated for you and free()'d in ma_rb_uninit(). If you pass in +// your own pre-allocated buffer, free()-ing is left to you. +// +// - Call ma_rb_init_ex() if you need a deinterleaved buffer. The data for each sub-buffer is offset from each +// other based on the stride. Use ma_rb_get_subbuffer_stride(), ma_rb_get_subbuffer_offset() and +// ma_rb_get_subbuffer_ptr() to manage your sub-buffers. +// +// - Use ma_rb_acquire_read() and ma_rb_acquire_write() to retrieve a pointer to a section of the ring buffer. +// You specify the number of bytes you need, and on output it will set to what was actually acquired. If the +// read or write pointer is positioned such that the number of bytes requested will require a loop, it will be +// clamped to the end of the buffer. Therefore, the number of bytes you're given may be less than the number +// you requested. +// +// - After calling ma_rb_acquire_read/write(), you do your work on the buffer and then "commit" it with +// ma_rb_commit_read/write(). This is where the read/write pointers are updated. When you commit you need to +// pass in the buffer that was returned by the earlier call to ma_rb_acquire_read/write() and is only used +// for validation. The number of bytes passed to ma_rb_commit_read/write() is what's used to increment the +// pointers. +// +// - If you want to correct for drift between the write pointer and the read pointer you can use a combination +// of ma_rb_pointer_distance(), ma_rb_seek_read() and ma_rb_seek_write(). Note that you can only move the +// pointers forward, and you should only move the read pointer forward via the consumer thread, and the write +// pointer forward by the producer thread. If there is too much space between the pointers, move the read +// pointer forward. If there is too little space between the pointers, move the write pointer forward. +// +// +// Notes +// ----- +// - Thread safety depends on a single producer, single consumer model. Only one thread is allowed to write, and +// only one thread is allowed to read. The producer is the only one allowed to move the write pointer, and the +// consumer is the only one allowed to move the read pointer. +// - Operates on bytes. Use ma_pcm_rb to operate in terms of PCM frames. +// - Maximum buffer size in bytes is 0x7FFFFFFF-(MA_SIMD_ALIGNMENT-1) because of reasons. +// +// +// PCM Ring Buffer +// =============== +// This is the same as the regular ring buffer, except that it works on PCM frames instead of bytes. +// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +typedef struct +{ + void* pBuffer; + ma_uint32 subbufferSizeInBytes; + ma_uint32 subbufferCount; + ma_uint32 subbufferStrideInBytes; + volatile ma_uint32 encodedReadOffset; /* Most significant bit is the loop flag. Lower 31 bits contains the actual offset in bytes. */ + volatile ma_uint32 encodedWriteOffset; /* Most significant bit is the loop flag. Lower 31 bits contains the actual offset in bytes. */ + ma_bool32 ownsBuffer : 1; /* Used to know whether or not miniaudio is responsible for free()-ing the buffer. */ + ma_bool32 clearOnWriteAcquire : 1; /* When set, clears the acquired write buffer before returning from ma_rb_acquire_write(). */ +} ma_rb; + +ma_result ma_rb_init_ex(size_t subbufferSizeInBytes, size_t subbufferCount, size_t subbufferStrideInBytes, void* pOptionalPreallocatedBuffer, ma_rb* pRB); +ma_result ma_rb_init(size_t bufferSizeInBytes, void* pOptionalPreallocatedBuffer, ma_rb* pRB); +void ma_rb_uninit(ma_rb* pRB); +ma_result ma_rb_acquire_read(ma_rb* pRB, size_t* pSizeInBytes, void** ppBufferOut); +ma_result ma_rb_commit_read(ma_rb* pRB, size_t sizeInBytes, void* pBufferOut); +ma_result ma_rb_acquire_write(ma_rb* pRB, size_t* pSizeInBytes, void** ppBufferOut); +ma_result ma_rb_commit_write(ma_rb* pRB, size_t sizeInBytes, void* pBufferOut); +ma_result ma_rb_seek_read(ma_rb* pRB, size_t offsetInBytes); +ma_result ma_rb_seek_write(ma_rb* pRB, size_t offsetInBytes); +ma_int32 ma_rb_pointer_distance(ma_rb* pRB); /* Returns the distance between the write pointer and the read pointer. Should never be negative for a correct program. */ +size_t ma_rb_get_subbuffer_size(ma_rb* pRB); +size_t ma_rb_get_subbuffer_stride(ma_rb* pRB); +size_t ma_rb_get_subbuffer_offset(ma_rb* pRB, size_t subbufferIndex); +void* ma_rb_get_subbuffer_ptr(ma_rb* pRB, size_t subbufferIndex, void* pBuffer); + + +typedef struct +{ + ma_rb rb; + ma_format format; + ma_uint32 channels; +} ma_pcm_rb; + +ma_result ma_pcm_rb_init_ex(ma_format format, ma_uint32 channels, ma_uint32 subbufferSizeInFrames, ma_uint32 subbufferCount, ma_uint32 subbufferStrideInFrames, void* pOptionalPreallocatedBuffer, ma_pcm_rb* pRB); +ma_result ma_pcm_rb_init(ma_format format, ma_uint32 channels, ma_uint32 bufferSizeInFrames, void* pOptionalPreallocatedBuffer, ma_pcm_rb* pRB); +void ma_pcm_rb_uninit(ma_pcm_rb* pRB); +ma_result ma_pcm_rb_acquire_read(ma_pcm_rb* pRB, ma_uint32* pSizeInFrames, void** ppBufferOut); +ma_result ma_pcm_rb_commit_read(ma_pcm_rb* pRB, ma_uint32 sizeInFrames, void* pBufferOut); +ma_result ma_pcm_rb_acquire_write(ma_pcm_rb* pRB, ma_uint32* pSizeInFrames, void** ppBufferOut); +ma_result ma_pcm_rb_commit_write(ma_pcm_rb* pRB, ma_uint32 sizeInFrames, void* pBufferOut); +ma_result ma_pcm_rb_seek_read(ma_pcm_rb* pRB, ma_uint32 offsetInFrames); +ma_result ma_pcm_rb_seek_write(ma_pcm_rb* pRB, ma_uint32 offsetInFrames); +ma_int32 ma_pcm_rb_pointer_disance(ma_pcm_rb* pRB); /* Return value is in frames. */ +ma_uint32 ma_pcm_rb_get_subbuffer_size(ma_pcm_rb* pRB); +ma_uint32 ma_pcm_rb_get_subbuffer_stride(ma_pcm_rb* pRB); +ma_uint32 ma_pcm_rb_get_subbuffer_offset(ma_pcm_rb* pRB, ma_uint32 subbufferIndex); +void* ma_pcm_rb_get_subbuffer_ptr(ma_pcm_rb* pRB, ma_uint32 subbufferIndex, void* pBuffer); + + +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Miscellaneous Helpers +// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +// malloc(). Calls MA_MALLOC(). +void* ma_malloc(size_t sz); + +// realloc(). Calls MA_REALLOC(). +void* ma_realloc(void* p, size_t sz); + +// free(). Calls MA_FREE(). +void ma_free(void* p); + +// Performs an aligned malloc, with the assumption that the alignment is a power of 2. +void* ma_aligned_malloc(size_t sz, size_t alignment); + +// Free's an aligned malloc'd buffer. +void ma_aligned_free(void* p); + +// Retrieves a friendly name for a format. +const char* ma_get_format_name(ma_format format); + +// Blends two frames in floating point format. +void ma_blend_f32(float* pOut, float* pInA, float* pInB, float factor, ma_uint32 channels); + +// Retrieves the size of a sample in bytes for the given format. +// +// This API is efficient and is implemented using a lookup table. +// +// Thread Safety: SAFE +// This is API is pure. +ma_uint32 ma_get_bytes_per_sample(ma_format format); +static MA_INLINE ma_uint32 ma_get_bytes_per_frame(ma_format format, ma_uint32 channels) { return ma_get_bytes_per_sample(format) * channels; } + +// Converts a log level to a string. +const char* ma_log_level_to_string(ma_uint32 logLevel); + + +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Format Conversion +// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +void ma_pcm_u8_to_s16(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); +void ma_pcm_u8_to_s24(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); +void ma_pcm_u8_to_s32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); +void ma_pcm_u8_to_f32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); +void ma_pcm_s16_to_u8(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); +void ma_pcm_s16_to_s24(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); +void ma_pcm_s16_to_s32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); +void ma_pcm_s16_to_f32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); +void ma_pcm_s24_to_u8(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); +void ma_pcm_s24_to_s16(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); +void ma_pcm_s24_to_s32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); +void ma_pcm_s24_to_f32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); +void ma_pcm_s32_to_u8(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); +void ma_pcm_s32_to_s16(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); +void ma_pcm_s32_to_s24(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); +void ma_pcm_s32_to_f32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); +void ma_pcm_f32_to_u8(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); +void ma_pcm_f32_to_s16(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); +void ma_pcm_f32_to_s24(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); +void ma_pcm_f32_to_s32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); +void ma_pcm_convert(void* pOut, ma_format formatOut, const void* pIn, ma_format formatIn, ma_uint64 sampleCount, ma_dither_mode ditherMode); + +// Deinterleaves an interleaved buffer. +void ma_deinterleave_pcm_frames(ma_format format, ma_uint32 channels, ma_uint64 frameCount, const void* pInterleavedPCMFrames, void** ppDeinterleavedPCMFrames); + +// Interleaves a group of deinterleaved buffers. +void ma_interleave_pcm_frames(ma_format format, ma_uint32 channels, ma_uint64 frameCount, const void** ppDeinterleavedPCMFrames, void* pInterleavedPCMFrames); + + +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// +// DEVICE I/O +// ========== +// +// This section contains the APIs for device playback and capture. Here is where you'll find ma_device_init(), etc. +// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +#ifndef MA_NO_DEVICE_IO +// Some backends are only supported on certain platforms. +#if defined(MA_WIN32) + #define MA_SUPPORT_WASAPI + #if defined(MA_WIN32_DESKTOP) // DirectSound and WinMM backends are only supported on desktop's. + #define MA_SUPPORT_DSOUND + #define MA_SUPPORT_WINMM + #define MA_SUPPORT_JACK // JACK is technically supported on Windows, but I don't know how many people use it in practice... + #endif +#endif +#if defined(MA_UNIX) + #if defined(MA_LINUX) + #if !defined(MA_ANDROID) // ALSA is not supported on Android. + #define MA_SUPPORT_ALSA + #endif + #endif + #if !defined(MA_BSD) && !defined(MA_ANDROID) && !defined(MA_EMSCRIPTEN) + #define MA_SUPPORT_PULSEAUDIO + #define MA_SUPPORT_JACK + #endif + #if defined(MA_ANDROID) + #define MA_SUPPORT_AAUDIO + #define MA_SUPPORT_OPENSL + #endif + #if defined(__OpenBSD__) // <-- Change this to "#if defined(MA_BSD)" to enable sndio on all BSD flavors. + #define MA_SUPPORT_SNDIO // sndio is only supported on OpenBSD for now. May be expanded later if there's demand. + #endif + #if defined(__NetBSD__) || defined(__OpenBSD__) + #define MA_SUPPORT_AUDIO4 // Only support audio(4) on platforms with known support. + #endif + #if defined(__FreeBSD__) || defined(__DragonFly__) + #define MA_SUPPORT_OSS // Only support OSS on specific platforms with known support. + #endif +#endif +#if defined(MA_APPLE) + #define MA_SUPPORT_COREAUDIO +#endif +#if defined(MA_EMSCRIPTEN) + #define MA_SUPPORT_WEBAUDIO +#endif + +// Explicitly disable the Null backend for Emscripten because it uses a background thread which is not properly supported right now. +#if !defined(MA_EMSCRIPTEN) +#define MA_SUPPORT_NULL +#endif + + +#if !defined(MA_NO_WASAPI) && defined(MA_SUPPORT_WASAPI) + #define MA_ENABLE_WASAPI +#endif +#if !defined(MA_NO_DSOUND) && defined(MA_SUPPORT_DSOUND) + #define MA_ENABLE_DSOUND +#endif +#if !defined(MA_NO_WINMM) && defined(MA_SUPPORT_WINMM) + #define MA_ENABLE_WINMM +#endif +#if !defined(MA_NO_ALSA) && defined(MA_SUPPORT_ALSA) + #define MA_ENABLE_ALSA +#endif +#if !defined(MA_NO_PULSEAUDIO) && defined(MA_SUPPORT_PULSEAUDIO) + #define MA_ENABLE_PULSEAUDIO +#endif +#if !defined(MA_NO_JACK) && defined(MA_SUPPORT_JACK) + #define MA_ENABLE_JACK +#endif +#if !defined(MA_NO_COREAUDIO) && defined(MA_SUPPORT_COREAUDIO) + #define MA_ENABLE_COREAUDIO +#endif +#if !defined(MA_NO_SNDIO) && defined(MA_SUPPORT_SNDIO) + #define MA_ENABLE_SNDIO +#endif +#if !defined(MA_NO_AUDIO4) && defined(MA_SUPPORT_AUDIO4) + #define MA_ENABLE_AUDIO4 +#endif +#if !defined(MA_NO_OSS) && defined(MA_SUPPORT_OSS) + #define MA_ENABLE_OSS +#endif +#if !defined(MA_NO_AAUDIO) && defined(MA_SUPPORT_AAUDIO) + #define MA_ENABLE_AAUDIO +#endif +#if !defined(MA_NO_OPENSL) && defined(MA_SUPPORT_OPENSL) + #define MA_ENABLE_OPENSL +#endif +#if !defined(MA_NO_WEBAUDIO) && defined(MA_SUPPORT_WEBAUDIO) + #define MA_ENABLE_WEBAUDIO +#endif +#if !defined(MA_NO_NULL) && defined(MA_SUPPORT_NULL) + #define MA_ENABLE_NULL +#endif + +#ifdef MA_SUPPORT_WASAPI +// We need a IMMNotificationClient object for WASAPI. +typedef struct +{ + void* lpVtbl; + ma_uint32 counter; + ma_device* pDevice; +} ma_IMMNotificationClient; +#endif + +/* Backend enums must be in priority order. */ +typedef enum +{ + ma_backend_wasapi, + ma_backend_dsound, + ma_backend_winmm, + ma_backend_coreaudio, + ma_backend_sndio, + ma_backend_audio4, + ma_backend_oss, + ma_backend_pulseaudio, + ma_backend_alsa, + ma_backend_jack, + ma_backend_aaudio, + ma_backend_opensl, + ma_backend_webaudio, + ma_backend_null /* <-- Must always be the last item. Lowest priority, and used as the terminator for backend enumeration. */ +} ma_backend; + +// Thread priorties should be ordered such that the default priority of the worker thread is 0. +typedef enum +{ + ma_thread_priority_idle = -5, + ma_thread_priority_lowest = -4, + ma_thread_priority_low = -3, + ma_thread_priority_normal = -2, + ma_thread_priority_high = -1, + ma_thread_priority_highest = 0, + ma_thread_priority_realtime = 1, + ma_thread_priority_default = 0 +} ma_thread_priority; + +typedef struct +{ + ma_context* pContext; + + union + { +#ifdef MA_WIN32 + struct + { + /*HANDLE*/ ma_handle hThread; + } win32; +#endif +#ifdef MA_POSIX + struct + { + pthread_t thread; + } posix; +#endif + int _unused; + }; +} ma_thread; + +typedef struct +{ + ma_context* pContext; + + union + { +#ifdef MA_WIN32 + struct + { + /*HANDLE*/ ma_handle hMutex; + } win32; +#endif +#ifdef MA_POSIX + struct + { + pthread_mutex_t mutex; + } posix; +#endif + int _unused; + }; +} ma_mutex; + +typedef struct +{ + ma_context* pContext; + + union + { +#ifdef MA_WIN32 + struct + { + /*HANDLE*/ ma_handle hEvent; + } win32; +#endif +#ifdef MA_POSIX + struct + { + pthread_mutex_t mutex; + pthread_cond_t condition; + ma_uint32 value; + } posix; +#endif + int _unused; + }; +} ma_event; + + +/* +The callback for processing audio data from the device. + +pOutput is a pointer to a buffer that will receive audio data that will later be played back through the speakers. This will be non-null +for a playback or full-duplex device and null for a capture device. + +pInput is a pointer to a buffer containing input data from the device. This will be non-null for a capture or full-duplex device, and +null for a playback device. + +frameCount is the number of PCM frames to process. If an output buffer is provided (pOutput is not null), applications should write out +to the entire output buffer. + +Do _not_ call any miniaudio APIs from the callback. Attempting the stop the device can result in a deadlock. The proper way to stop the +device is to call ma_device_stop() from a different thread, normally the main application thread. +*/ +typedef void (* ma_device_callback_proc)(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount); + +/* +The callback for when the device has been stopped. + +This will be called when the device is stopped explicitly with ma_device_stop() and also called implicitly when the device is stopped +through external forces such as being unplugged or an internal error occuring. + +Do not restart the device from the callback. +*/ +typedef void (* ma_stop_proc)(ma_device* pDevice); + +/* +The callback for handling log messages. + +It is possible for pDevice to be null in which case the log originated from the context. If it is non-null you can assume the message +came from the device. + +logLevel is one of the following: + MA_LOG_LEVEL_VERBOSE + MA_LOG_LEVEL_INFO + MA_LOG_LEVEL_WARNING + MA_LOG_LEVEL_ERROR +*/ +typedef void (* ma_log_proc)(ma_context* pContext, ma_device* pDevice, ma_uint32 logLevel, const char* message); + +typedef enum +{ + ma_device_type_playback = 1, + ma_device_type_capture = 2, + ma_device_type_duplex = ma_device_type_playback | ma_device_type_capture, +} ma_device_type; + +typedef enum +{ + ma_share_mode_shared = 0, + ma_share_mode_exclusive, +} ma_share_mode; + +typedef union +{ +#ifdef MA_SUPPORT_WASAPI + wchar_t wasapi[64]; // WASAPI uses a wchar_t string for identification. +#endif +#ifdef MA_SUPPORT_DSOUND + ma_uint8 dsound[16]; // DirectSound uses a GUID for identification. +#endif +#ifdef MA_SUPPORT_WINMM + /*UINT_PTR*/ ma_uint32 winmm; // When creating a device, WinMM expects a Win32 UINT_PTR for device identification. In practice it's actually just a UINT. +#endif +#ifdef MA_SUPPORT_ALSA + char alsa[256]; // ALSA uses a name string for identification. +#endif +#ifdef MA_SUPPORT_PULSEAUDIO + char pulse[256]; // PulseAudio uses a name string for identification. +#endif +#ifdef MA_SUPPORT_JACK + int jack; // JACK always uses default devices. +#endif +#ifdef MA_SUPPORT_COREAUDIO + char coreaudio[256]; // Core Audio uses a string for identification. +#endif +#ifdef MA_SUPPORT_SNDIO + char sndio[256]; // "snd/0", etc. +#endif +#ifdef MA_SUPPORT_AUDIO4 + char audio4[256]; // "/dev/audio", etc. +#endif +#ifdef MA_SUPPORT_OSS + char oss[64]; // "dev/dsp0", etc. "dev/dsp" for the default device. +#endif +#ifdef MA_SUPPORT_AAUDIO + ma_int32 aaudio; // AAudio uses a 32-bit integer for identification. +#endif +#ifdef MA_SUPPORT_OPENSL + ma_uint32 opensl; // OpenSL|ES uses a 32-bit unsigned integer for identification. +#endif +#ifdef MA_SUPPORT_WEBAUDIO + char webaudio[32]; // Web Audio always uses default devices for now, but if this changes it'll be a GUID. +#endif +#ifdef MA_SUPPORT_NULL + int nullbackend; // The null backend uses an integer for device IDs. +#endif +} ma_device_id; + +typedef struct +{ + // Basic info. This is the only information guaranteed to be filled in during device enumeration. + ma_device_id id; + char name[256]; + + // Detailed info. As much of this is filled as possible with ma_context_get_device_info(). Note that you are allowed to initialize + // a device with settings outside of this range, but it just means the data will be converted using miniaudio's data conversion + // pipeline before sending the data to/from the device. Most programs will need to not worry about these values, but it's provided + // here mainly for informational purposes or in the rare case that someone might find it useful. + // + // These will be set to 0 when returned by ma_context_enumerate_devices() or ma_context_get_devices(). + ma_uint32 formatCount; + ma_format formats[ma_format_count]; + ma_uint32 minChannels; + ma_uint32 maxChannels; + ma_uint32 minSampleRate; + ma_uint32 maxSampleRate; +} ma_device_info; + +typedef struct +{ + union + { + ma_int64 counter; + double counterD; + }; +} ma_timer; + +typedef struct +{ + ma_device_type deviceType; + ma_uint32 sampleRate; + ma_uint32 bufferSizeInFrames; + ma_uint32 bufferSizeInMilliseconds; + ma_uint32 periods; + ma_performance_profile performanceProfile; + ma_device_callback_proc dataCallback; + ma_stop_proc stopCallback; + void* pUserData; + struct + { + ma_device_id* pDeviceID; + ma_format format; + ma_uint32 channels; + ma_channel channelMap[MA_MAX_CHANNELS]; + ma_share_mode shareMode; + } playback; + struct + { + ma_device_id* pDeviceID; + ma_format format; + ma_uint32 channels; + ma_channel channelMap[MA_MAX_CHANNELS]; + ma_share_mode shareMode; + } capture; + + struct + { + ma_bool32 noMMap; // Disables MMap mode. + } alsa; + struct + { + const char* pStreamNamePlayback; + const char* pStreamNameCapture; + } pulse; +} ma_device_config; + +typedef struct +{ + ma_log_proc logCallback; + ma_thread_priority threadPriority; + + struct + { + ma_bool32 useVerboseDeviceEnumeration; + } alsa; + + struct + { + const char* pApplicationName; + const char* pServerName; + ma_bool32 tryAutoSpawn; // Enables autospawning of the PulseAudio daemon if necessary. + } pulse; + + struct + { + const char* pClientName; + ma_bool32 tryStartServer; + } jack; +} ma_context_config; + +typedef ma_bool32 (* ma_enum_devices_callback_proc)(ma_context* pContext, ma_device_type deviceType, const ma_device_info* pInfo, void* pUserData); + +struct ma_context +{ + ma_backend backend; // DirectSound, ALSA, etc. + ma_context_config config; + ma_mutex deviceEnumLock; // Used to make ma_context_get_devices() thread safe. + ma_mutex deviceInfoLock; // Used to make ma_context_get_device_info() thread safe. + ma_uint32 deviceInfoCapacity; // Total capacity of pDeviceInfos. + ma_uint32 playbackDeviceInfoCount; + ma_uint32 captureDeviceInfoCount; + ma_device_info* pDeviceInfos; // Playback devices first, then capture. + ma_bool32 isBackendAsynchronous : 1; // Set when the context is initialized. Set to 1 for asynchronous backends such as Core Audio and JACK. Do not modify. + + ma_result (* onUninit )(ma_context* pContext); + ma_bool32 (* onDeviceIDEqual )(ma_context* pContext, const ma_device_id* pID0, const ma_device_id* pID1); + ma_result (* onEnumDevices )(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData); // Return false from the callback to stop enumeration. + ma_result (* onGetDeviceInfo )(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_share_mode shareMode, ma_device_info* pDeviceInfo); + ma_result (* onDeviceInit )(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice); + void (* onDeviceUninit )(ma_device* pDevice); + ma_result (* onDeviceStart )(ma_device* pDevice); + ma_result (* onDeviceStop )(ma_device* pDevice); + ma_result (* onDeviceWrite )(ma_device* pDevice, const void* pPCMFrames, ma_uint32 frameCount); /* Data is in internal device format. */ + ma_result (* onDeviceRead )(ma_device* pDevice, void* pPCMFrames, ma_uint32 frameCount); /* Data is in internal device format. */ + ma_result (* onDeviceMainLoop)(ma_device* pDevice); + + union + { +#ifdef MA_SUPPORT_WASAPI + struct + { + int _unused; + } wasapi; +#endif +#ifdef MA_SUPPORT_DSOUND + struct + { + ma_handle hDSoundDLL; + ma_proc DirectSoundCreate; + ma_proc DirectSoundEnumerateA; + ma_proc DirectSoundCaptureCreate; + ma_proc DirectSoundCaptureEnumerateA; + } dsound; +#endif +#ifdef MA_SUPPORT_WINMM + struct + { + ma_handle hWinMM; + ma_proc waveOutGetNumDevs; + ma_proc waveOutGetDevCapsA; + ma_proc waveOutOpen; + ma_proc waveOutClose; + ma_proc waveOutPrepareHeader; + ma_proc waveOutUnprepareHeader; + ma_proc waveOutWrite; + ma_proc waveOutReset; + ma_proc waveInGetNumDevs; + ma_proc waveInGetDevCapsA; + ma_proc waveInOpen; + ma_proc waveInClose; + ma_proc waveInPrepareHeader; + ma_proc waveInUnprepareHeader; + ma_proc waveInAddBuffer; + ma_proc waveInStart; + ma_proc waveInReset; + } winmm; +#endif +#ifdef MA_SUPPORT_ALSA + struct + { + ma_handle asoundSO; + ma_proc snd_pcm_open; + ma_proc snd_pcm_close; + ma_proc snd_pcm_hw_params_sizeof; + ma_proc snd_pcm_hw_params_any; + ma_proc snd_pcm_hw_params_set_format; + ma_proc snd_pcm_hw_params_set_format_first; + ma_proc snd_pcm_hw_params_get_format_mask; + ma_proc snd_pcm_hw_params_set_channels_near; + ma_proc snd_pcm_hw_params_set_rate_resample; + ma_proc snd_pcm_hw_params_set_rate_near; + ma_proc snd_pcm_hw_params_set_buffer_size_near; + ma_proc snd_pcm_hw_params_set_periods_near; + ma_proc snd_pcm_hw_params_set_access; + ma_proc snd_pcm_hw_params_get_format; + ma_proc snd_pcm_hw_params_get_channels; + ma_proc snd_pcm_hw_params_get_channels_min; + ma_proc snd_pcm_hw_params_get_channels_max; + ma_proc snd_pcm_hw_params_get_rate; + ma_proc snd_pcm_hw_params_get_rate_min; + ma_proc snd_pcm_hw_params_get_rate_max; + ma_proc snd_pcm_hw_params_get_buffer_size; + ma_proc snd_pcm_hw_params_get_periods; + ma_proc snd_pcm_hw_params_get_access; + ma_proc snd_pcm_hw_params; + ma_proc snd_pcm_sw_params_sizeof; + ma_proc snd_pcm_sw_params_current; + ma_proc snd_pcm_sw_params_get_boundary; + ma_proc snd_pcm_sw_params_set_avail_min; + ma_proc snd_pcm_sw_params_set_start_threshold; + ma_proc snd_pcm_sw_params_set_stop_threshold; + ma_proc snd_pcm_sw_params; + ma_proc snd_pcm_format_mask_sizeof; + ma_proc snd_pcm_format_mask_test; + ma_proc snd_pcm_get_chmap; + ma_proc snd_pcm_state; + ma_proc snd_pcm_prepare; + ma_proc snd_pcm_start; + ma_proc snd_pcm_drop; + ma_proc snd_pcm_drain; + ma_proc snd_device_name_hint; + ma_proc snd_device_name_get_hint; + ma_proc snd_card_get_index; + ma_proc snd_device_name_free_hint; + ma_proc snd_pcm_mmap_begin; + ma_proc snd_pcm_mmap_commit; + ma_proc snd_pcm_recover; + ma_proc snd_pcm_readi; + ma_proc snd_pcm_writei; + ma_proc snd_pcm_avail; + ma_proc snd_pcm_avail_update; + ma_proc snd_pcm_wait; + ma_proc snd_pcm_info; + ma_proc snd_pcm_info_sizeof; + ma_proc snd_pcm_info_get_name; + ma_proc snd_config_update_free_global; + + ma_mutex internalDeviceEnumLock; + } alsa; +#endif +#ifdef MA_SUPPORT_PULSEAUDIO + struct + { + ma_handle pulseSO; + ma_proc pa_mainloop_new; + ma_proc pa_mainloop_free; + ma_proc pa_mainloop_get_api; + ma_proc pa_mainloop_iterate; + ma_proc pa_mainloop_wakeup; + ma_proc pa_context_new; + ma_proc pa_context_unref; + ma_proc pa_context_connect; + ma_proc pa_context_disconnect; + ma_proc pa_context_set_state_callback; + ma_proc pa_context_get_state; + ma_proc pa_context_get_sink_info_list; + ma_proc pa_context_get_source_info_list; + ma_proc pa_context_get_sink_info_by_name; + ma_proc pa_context_get_source_info_by_name; + ma_proc pa_operation_unref; + ma_proc pa_operation_get_state; + ma_proc pa_channel_map_init_extend; + ma_proc pa_channel_map_valid; + ma_proc pa_channel_map_compatible; + ma_proc pa_stream_new; + ma_proc pa_stream_unref; + ma_proc pa_stream_connect_playback; + ma_proc pa_stream_connect_record; + ma_proc pa_stream_disconnect; + ma_proc pa_stream_get_state; + ma_proc pa_stream_get_sample_spec; + ma_proc pa_stream_get_channel_map; + ma_proc pa_stream_get_buffer_attr; + ma_proc pa_stream_set_buffer_attr; + ma_proc pa_stream_get_device_name; + ma_proc pa_stream_set_write_callback; + ma_proc pa_stream_set_read_callback; + ma_proc pa_stream_flush; + ma_proc pa_stream_drain; + ma_proc pa_stream_is_corked; + ma_proc pa_stream_cork; + ma_proc pa_stream_trigger; + ma_proc pa_stream_begin_write; + ma_proc pa_stream_write; + ma_proc pa_stream_peek; + ma_proc pa_stream_drop; + ma_proc pa_stream_writable_size; + ma_proc pa_stream_readable_size; + } pulse; +#endif +#ifdef MA_SUPPORT_JACK + struct + { + ma_handle jackSO; + ma_proc jack_client_open; + ma_proc jack_client_close; + ma_proc jack_client_name_size; + ma_proc jack_set_process_callback; + ma_proc jack_set_buffer_size_callback; + ma_proc jack_on_shutdown; + ma_proc jack_get_sample_rate; + ma_proc jack_get_buffer_size; + ma_proc jack_get_ports; + ma_proc jack_activate; + ma_proc jack_deactivate; + ma_proc jack_connect; + ma_proc jack_port_register; + ma_proc jack_port_name; + ma_proc jack_port_get_buffer; + ma_proc jack_free; + } jack; +#endif +#ifdef MA_SUPPORT_COREAUDIO + struct + { + ma_handle hCoreFoundation; + ma_proc CFStringGetCString; + + ma_handle hCoreAudio; + ma_proc AudioObjectGetPropertyData; + ma_proc AudioObjectGetPropertyDataSize; + ma_proc AudioObjectSetPropertyData; + ma_proc AudioObjectAddPropertyListener; + + ma_handle hAudioUnit; // Could possibly be set to AudioToolbox on later versions of macOS. + ma_proc AudioComponentFindNext; + ma_proc AudioComponentInstanceDispose; + ma_proc AudioComponentInstanceNew; + ma_proc AudioOutputUnitStart; + ma_proc AudioOutputUnitStop; + ma_proc AudioUnitAddPropertyListener; + ma_proc AudioUnitGetPropertyInfo; + ma_proc AudioUnitGetProperty; + ma_proc AudioUnitSetProperty; + ma_proc AudioUnitInitialize; + ma_proc AudioUnitRender; + + /*AudioComponent*/ ma_ptr component; + } coreaudio; +#endif +#ifdef MA_SUPPORT_SNDIO + struct + { + ma_handle sndioSO; + ma_proc sio_open; + ma_proc sio_close; + ma_proc sio_setpar; + ma_proc sio_getpar; + ma_proc sio_getcap; + ma_proc sio_start; + ma_proc sio_stop; + ma_proc sio_read; + ma_proc sio_write; + ma_proc sio_onmove; + ma_proc sio_nfds; + ma_proc sio_pollfd; + ma_proc sio_revents; + ma_proc sio_eof; + ma_proc sio_setvol; + ma_proc sio_onvol; + ma_proc sio_initpar; + } sndio; +#endif +#ifdef MA_SUPPORT_AUDIO4 + struct + { + int _unused; + } audio4; +#endif +#ifdef MA_SUPPORT_OSS + struct + { + int versionMajor; + int versionMinor; + } oss; +#endif +#ifdef MA_SUPPORT_AAUDIO + struct + { + ma_handle hAAudio; /* libaaudio.so */ + ma_proc AAudio_createStreamBuilder; + ma_proc AAudioStreamBuilder_delete; + ma_proc AAudioStreamBuilder_setDeviceId; + ma_proc AAudioStreamBuilder_setDirection; + ma_proc AAudioStreamBuilder_setSharingMode; + ma_proc AAudioStreamBuilder_setFormat; + ma_proc AAudioStreamBuilder_setChannelCount; + ma_proc AAudioStreamBuilder_setSampleRate; + ma_proc AAudioStreamBuilder_setBufferCapacityInFrames; + ma_proc AAudioStreamBuilder_setFramesPerDataCallback; + ma_proc AAudioStreamBuilder_setDataCallback; + ma_proc AAudioStreamBuilder_setPerformanceMode; + ma_proc AAudioStreamBuilder_openStream; + ma_proc AAudioStream_close; + ma_proc AAudioStream_getState; + ma_proc AAudioStream_waitForStateChange; + ma_proc AAudioStream_getFormat; + ma_proc AAudioStream_getChannelCount; + ma_proc AAudioStream_getSampleRate; + ma_proc AAudioStream_getBufferCapacityInFrames; + ma_proc AAudioStream_getFramesPerDataCallback; + ma_proc AAudioStream_getFramesPerBurst; + ma_proc AAudioStream_requestStart; + ma_proc AAudioStream_requestStop; + } aaudio; +#endif +#ifdef MA_SUPPORT_OPENSL + struct + { + int _unused; + } opensl; +#endif +#ifdef MA_SUPPORT_WEBAUDIO + struct + { + int _unused; + } webaudio; +#endif +#ifdef MA_SUPPORT_NULL + struct + { + int _unused; + } null_backend; +#endif + }; + + union + { +#ifdef MA_WIN32 + struct + { + /*HMODULE*/ ma_handle hOle32DLL; + ma_proc CoInitializeEx; + ma_proc CoUninitialize; + ma_proc CoCreateInstance; + ma_proc CoTaskMemFree; + ma_proc PropVariantClear; + ma_proc StringFromGUID2; + + /*HMODULE*/ ma_handle hUser32DLL; + ma_proc GetForegroundWindow; + ma_proc GetDesktopWindow; + + /*HMODULE*/ ma_handle hAdvapi32DLL; + ma_proc RegOpenKeyExA; + ma_proc RegCloseKey; + ma_proc RegQueryValueExA; + } win32; +#endif +#ifdef MA_POSIX + struct + { + ma_handle pthreadSO; + ma_proc pthread_create; + ma_proc pthread_join; + ma_proc pthread_mutex_init; + ma_proc pthread_mutex_destroy; + ma_proc pthread_mutex_lock; + ma_proc pthread_mutex_unlock; + ma_proc pthread_cond_init; + ma_proc pthread_cond_destroy; + ma_proc pthread_cond_wait; + ma_proc pthread_cond_signal; + ma_proc pthread_attr_init; + ma_proc pthread_attr_destroy; + ma_proc pthread_attr_setschedpolicy; + ma_proc pthread_attr_getschedparam; + ma_proc pthread_attr_setschedparam; + } posix; +#endif + int _unused; + }; +}; + +MA_ALIGNED_STRUCT(MA_SIMD_ALIGNMENT) ma_device +{ + ma_context* pContext; + ma_device_type type; + ma_uint32 sampleRate; + ma_uint32 state; + ma_device_callback_proc onData; + ma_stop_proc onStop; + void* pUserData; // Application defined data. + ma_mutex lock; + ma_event wakeupEvent; + ma_event startEvent; + ma_event stopEvent; + ma_thread thread; + ma_result workResult; // This is set by the worker thread after it's finished doing a job. + ma_bool32 usingDefaultSampleRate : 1; + ma_bool32 usingDefaultBufferSize : 1; + ma_bool32 usingDefaultPeriods : 1; + ma_bool32 isOwnerOfContext : 1; // When set to true, uninitializing the device will also uninitialize the context. Set to true when NULL is passed into ma_device_init(). + struct + { + char name[256]; /* Maybe temporary. Likely to be replaced with a query API. */ + ma_share_mode shareMode; /* Set to whatever was passed in when the device was initialized. */ + ma_bool32 usingDefaultFormat : 1; + ma_bool32 usingDefaultChannels : 1; + ma_bool32 usingDefaultChannelMap : 1; + ma_format format; + ma_uint32 channels; + ma_channel channelMap[MA_MAX_CHANNELS]; + ma_format internalFormat; + ma_uint32 internalChannels; + ma_uint32 internalSampleRate; + ma_channel internalChannelMap[MA_MAX_CHANNELS]; + ma_uint32 internalBufferSizeInFrames; + ma_uint32 internalPeriods; + ma_pcm_converter converter; + ma_uint32 _dspFrameCount; // Internal use only. Used as the data source when reading from the device. + const ma_uint8* _dspFrames; // ^^^ AS ABOVE ^^^ + } playback; + struct + { + char name[256]; /* Maybe temporary. Likely to be replaced with a query API. */ + ma_share_mode shareMode; /* Set to whatever was passed in when the device was initialized. */ + ma_bool32 usingDefaultFormat : 1; + ma_bool32 usingDefaultChannels : 1; + ma_bool32 usingDefaultChannelMap : 1; + ma_format format; + ma_uint32 channels; + ma_channel channelMap[MA_MAX_CHANNELS]; + ma_format internalFormat; + ma_uint32 internalChannels; + ma_uint32 internalSampleRate; + ma_channel internalChannelMap[MA_MAX_CHANNELS]; + ma_uint32 internalBufferSizeInFrames; + ma_uint32 internalPeriods; + ma_pcm_converter converter; + ma_uint32 _dspFrameCount; // Internal use only. Used as the data source when reading from the device. + const ma_uint8* _dspFrames; // ^^^ AS ABOVE ^^^ + } capture; + + union + { +#ifdef MA_SUPPORT_WASAPI + struct + { + /*IAudioClient**/ ma_ptr pAudioClientPlayback; + /*IAudioClient**/ ma_ptr pAudioClientCapture; + /*IAudioRenderClient**/ ma_ptr pRenderClient; + /*IAudioCaptureClient**/ ma_ptr pCaptureClient; + /*IMMDeviceEnumerator**/ ma_ptr pDeviceEnumerator; /* Used for IMMNotificationClient notifications. Required for detecting default device changes. */ + ma_IMMNotificationClient notificationClient; + /*HANDLE*/ ma_handle hEventPlayback; /* Auto reset. Initialized to signaled. */ + /*HANDLE*/ ma_handle hEventCapture; /* Auto reset. Initialized to unsignaled. */ + ma_uint32 actualBufferSizeInFramesPlayback; /* Value from GetBufferSize(). internalBufferSizeInFrames is not set to the _actual_ buffer size when low-latency shared mode is being used due to the way the IAudioClient3 API works. */ + ma_uint32 actualBufferSizeInFramesCapture; + ma_uint32 originalBufferSizeInFrames; + ma_uint32 originalBufferSizeInMilliseconds; + ma_uint32 originalPeriods; + ma_bool32 hasDefaultPlaybackDeviceChanged; /* <-- Make sure this is always a whole 32-bits because we use atomic assignments. */ + ma_bool32 hasDefaultCaptureDeviceChanged; /* <-- Make sure this is always a whole 32-bits because we use atomic assignments. */ + ma_uint32 periodSizeInFramesPlayback; + ma_uint32 periodSizeInFramesCapture; + ma_bool32 isStartedCapture; + ma_bool32 isStartedPlayback; + } wasapi; +#endif +#ifdef MA_SUPPORT_DSOUND + struct + { + /*LPDIRECTSOUND*/ ma_ptr pPlayback; + /*LPDIRECTSOUNDBUFFER*/ ma_ptr pPlaybackPrimaryBuffer; + /*LPDIRECTSOUNDBUFFER*/ ma_ptr pPlaybackBuffer; + /*LPDIRECTSOUNDCAPTURE*/ ma_ptr pCapture; + /*LPDIRECTSOUNDCAPTUREBUFFER*/ ma_ptr pCaptureBuffer; + } dsound; +#endif +#ifdef MA_SUPPORT_WINMM + struct + { + /*HWAVEOUT*/ ma_handle hDevicePlayback; + /*HWAVEIN*/ ma_handle hDeviceCapture; + /*HANDLE*/ ma_handle hEventPlayback; + /*HANDLE*/ ma_handle hEventCapture; + ma_uint32 fragmentSizeInFrames; + ma_uint32 fragmentSizeInBytes; + ma_uint32 iNextHeaderPlayback; /* [0,periods). Used as an index into pWAVEHDRPlayback. */ + ma_uint32 iNextHeaderCapture; /* [0,periods). Used as an index into pWAVEHDRCapture. */ + ma_uint32 headerFramesConsumedPlayback; /* The number of PCM frames consumed in the buffer in pWAVEHEADER[iNextHeader]. */ + ma_uint32 headerFramesConsumedCapture; /* ^^^ */ + /*WAVEHDR**/ ma_uint8* pWAVEHDRPlayback; /* One instantiation for each period. */ + /*WAVEHDR**/ ma_uint8* pWAVEHDRCapture; /* One instantiation for each period. */ + ma_uint8* pIntermediaryBufferPlayback; + ma_uint8* pIntermediaryBufferCapture; + ma_uint8* _pHeapData; /* Used internally and is used for the heap allocated data for the intermediary buffer and the WAVEHDR structures. */ + ma_bool32 isStarted; + } winmm; +#endif +#ifdef MA_SUPPORT_ALSA + struct + { + /*snd_pcm_t**/ ma_ptr pPCMPlayback; + /*snd_pcm_t**/ ma_ptr pPCMCapture; + ma_bool32 isUsingMMapPlayback : 1; + ma_bool32 isUsingMMapCapture : 1; + } alsa; +#endif +#ifdef MA_SUPPORT_PULSEAUDIO + struct + { + /*pa_mainloop**/ ma_ptr pMainLoop; + /*pa_mainloop_api**/ ma_ptr pAPI; + /*pa_context**/ ma_ptr pPulseContext; + /*pa_stream**/ ma_ptr pStreamPlayback; + /*pa_stream**/ ma_ptr pStreamCapture; + /*pa_context_state*/ ma_uint32 pulseContextState; + void* pMappedBufferPlayback; + const void* pMappedBufferCapture; + ma_uint32 mappedBufferFramesRemainingPlayback; + ma_uint32 mappedBufferFramesRemainingCapture; + ma_uint32 mappedBufferFramesCapacityPlayback; + ma_uint32 mappedBufferFramesCapacityCapture; + ma_bool32 breakFromMainLoop : 1; + } pulse; +#endif +#ifdef MA_SUPPORT_JACK + struct + { + /*jack_client_t**/ ma_ptr pClient; + /*jack_port_t**/ ma_ptr pPortsPlayback[MA_MAX_CHANNELS]; + /*jack_port_t**/ ma_ptr pPortsCapture[MA_MAX_CHANNELS]; + float* pIntermediaryBufferPlayback; // Typed as a float because JACK is always floating point. + float* pIntermediaryBufferCapture; + ma_pcm_rb duplexRB; + } jack; +#endif +#ifdef MA_SUPPORT_COREAUDIO + struct + { + ma_uint32 deviceObjectIDPlayback; + ma_uint32 deviceObjectIDCapture; + /*AudioUnit*/ ma_ptr audioUnitPlayback; + /*AudioUnit*/ ma_ptr audioUnitCapture; + /*AudioBufferList**/ ma_ptr pAudioBufferList; // Only used for input devices. + ma_event stopEvent; + ma_uint32 originalBufferSizeInFrames; + ma_uint32 originalBufferSizeInMilliseconds; + ma_uint32 originalPeriods; + ma_bool32 isDefaultPlaybackDevice; + ma_bool32 isDefaultCaptureDevice; + ma_bool32 isSwitchingPlaybackDevice; /* <-- Set to true when the default device has changed and miniaudio is in the process of switching. */ + ma_bool32 isSwitchingCaptureDevice; /* <-- Set to true when the default device has changed and miniaudio is in the process of switching. */ + ma_pcm_rb duplexRB; + } coreaudio; +#endif +#ifdef MA_SUPPORT_SNDIO + struct + { + ma_ptr handlePlayback; + ma_ptr handleCapture; + ma_bool32 isStartedPlayback; + ma_bool32 isStartedCapture; + } sndio; +#endif +#ifdef MA_SUPPORT_AUDIO4 + struct + { + int fdPlayback; + int fdCapture; + } audio4; +#endif +#ifdef MA_SUPPORT_OSS + struct + { + int fdPlayback; + int fdCapture; + } oss; +#endif +#ifdef MA_SUPPORT_AAUDIO + struct + { + /*AAudioStream**/ ma_ptr pStreamPlayback; + /*AAudioStream**/ ma_ptr pStreamCapture; + ma_pcm_rb duplexRB; + } aaudio; +#endif +#ifdef MA_SUPPORT_OPENSL + struct + { + /*SLObjectItf*/ ma_ptr pOutputMixObj; + /*SLOutputMixItf*/ ma_ptr pOutputMix; + /*SLObjectItf*/ ma_ptr pAudioPlayerObj; + /*SLPlayItf*/ ma_ptr pAudioPlayer; + /*SLObjectItf*/ ma_ptr pAudioRecorderObj; + /*SLRecordItf*/ ma_ptr pAudioRecorder; + /*SLAndroidSimpleBufferQueueItf*/ ma_ptr pBufferQueuePlayback; + /*SLAndroidSimpleBufferQueueItf*/ ma_ptr pBufferQueueCapture; + ma_uint32 currentBufferIndexPlayback; + ma_uint32 currentBufferIndexCapture; + ma_uint8* pBufferPlayback; // This is malloc()'d and is used for storing audio data. Typed as ma_uint8 for easy offsetting. + ma_uint8* pBufferCapture; + ma_pcm_rb duplexRB; + } opensl; +#endif +#ifdef MA_SUPPORT_WEBAUDIO + struct + { + int indexPlayback; /* We use a factory on the JavaScript side to manage devices and use an index for JS/C interop. */ + int indexCapture; + ma_pcm_rb duplexRB; /* In external capture format. */ + } webaudio; +#endif +#ifdef MA_SUPPORT_NULL + struct + { + ma_thread deviceThread; + ma_event operationEvent; + ma_event operationCompletionEvent; + ma_uint32 operation; + ma_result operationResult; + ma_timer timer; + double priorRunTime; + ma_uint32 currentPeriodFramesRemainingPlayback; + ma_uint32 currentPeriodFramesRemainingCapture; + ma_uint64 lastProcessedFramePlayback; + ma_uint32 lastProcessedFrameCapture; + ma_bool32 isStarted; + } null_device; +#endif + }; +}; +#if defined(_MSC_VER) + #pragma warning(pop) +#endif + +// Initializes a context. +// +// The context is used for selecting and initializing the relevant backends. +// +// Note that the location of the context cannot change throughout it's lifetime. Consider allocating +// the ma_context object with malloc() if this is an issue. The reason for this is that a pointer +// to the context is stored in the ma_device structure. +// +// is used to allow the application to prioritize backends depending on it's specific +// requirements. This can be null in which case it uses the default priority, which is as follows: +// - WASAPI +// - DirectSound +// - WinMM +// - Core Audio (Apple) +// - sndio +// - audio(4) +// - OSS +// - PulseAudio +// - ALSA +// - JACK +// - AAudio +// - OpenSL|ES +// - Web Audio / Emscripten +// - Null +// +// is used to configure the context. Use the logCallback config to set a callback for whenever a +// log message is posted. The priority of the worker thread can be set with the threadPriority config. +// +// It is recommended that only a single context is active at any given time because it's a bulky data +// structure which performs run-time linking for the relevant backends every time it's initialized. +// +// Return Value: +// MA_SUCCESS if successful; any other error code otherwise. +// +// Thread Safety: UNSAFE +ma_result ma_context_init(const ma_backend backends[], ma_uint32 backendCount, const ma_context_config* pConfig, ma_context* pContext); + +// Uninitializes a context. +// +// Results are undefined if you call this while any device created by this context is still active. +// +// Return Value: +// MA_SUCCESS if successful; any other error code otherwise. +// +// Thread Safety: UNSAFE +ma_result ma_context_uninit(ma_context* pContext); + +// Enumerates over every device (both playback and capture). +// +// This is a lower-level enumeration function to the easier to use ma_context_get_devices(). Use +// ma_context_enumerate_devices() if you would rather not incur an internal heap allocation, or +// it simply suits your code better. +// +// Do _not_ assume the first enumerated device of a given type is the default device. +// +// Some backends and platforms may only support default playback and capture devices. +// +// Note that this only retrieves the ID and name/description of the device. The reason for only +// retrieving basic information is that it would otherwise require opening the backend device in +// order to probe it for more detailed information which can be inefficient. Consider using +// ma_context_get_device_info() for this, but don't call it from within the enumeration callback. +// +// In general, you should not do anything complicated from within the callback. In particular, do +// not try initializing a device from within the callback. +// +// Consider using ma_context_get_devices() for a simpler and safer API, albeit at the expense of +// an internal heap allocation. +// +// Returning false from the callback will stop enumeration. Returning true will continue enumeration. +// +// Return Value: +// MA_SUCCESS if successful; any other error code otherwise. +// +// Thread Safety: SAFE +// This is guarded using a simple mutex lock. +ma_result ma_context_enumerate_devices(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData); + +// Retrieves basic information about every active playback and/or capture device. +// +// You can pass in NULL for the playback or capture lists in which case they'll be ignored. +// +// It is _not_ safe to assume the first device in the list is the default device. +// +// The returned pointers will become invalid upon the next call this this function, or when the +// context is uninitialized. Do not free the returned pointers. +// +// This function follows the same enumeration rules as ma_context_enumerate_devices(). See +// documentation for ma_context_enumerate_devices() for more information. +// +// Return Value: +// MA_SUCCESS if successful; any other error code otherwise. +// +// Thread Safety: SAFE +// Since each call to this function invalidates the pointers from the previous call, you +// should not be calling this simultaneously across multiple threads. Instead, you need to +// make a copy of the returned data with your own higher level synchronization. +ma_result ma_context_get_devices(ma_context* pContext, ma_device_info** ppPlaybackDeviceInfos, ma_uint32* pPlaybackDeviceCount, ma_device_info** ppCaptureDeviceInfos, ma_uint32* pCaptureDeviceCount); + +// Retrieves information about a device with the given ID. +// +// Do _not_ call this from within the ma_context_enumerate_devices() callback. +// +// It's possible for a device to have different information and capabilities depending on wether or +// not it's opened in shared or exclusive mode. For example, in shared mode, WASAPI always uses +// floating point samples for mixing, but in exclusive mode it can be anything. Therefore, this +// function allows you to specify which share mode you want information for. Note that not all +// backends and devices support shared or exclusive mode, in which case this function will fail +// if the requested share mode is unsupported. +// +// This leaves pDeviceInfo unmodified in the result of an error. +// +// Return Value: +// MA_SUCCESS if successful; any other error code otherwise. +// +// Thread Safety: SAFE +// This is guarded using a simple mutex lock. +ma_result ma_context_get_device_info(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_share_mode shareMode, ma_device_info* pDeviceInfo); + +// Initializes a device. +// +// The context can be null in which case it uses the default. This is equivalent to passing in a +// context that was initialized like so: +// +// ma_context_init(NULL, 0, NULL, &context); +// +// Do not pass in null for the context if you are needing to open multiple devices. You can, +// however, use null when initializing the first device, and then use device.pContext for the +// initialization of other devices. +// +// The device's configuration is controlled with pConfig. This allows you to configure the sample +// format, channel count, sample rate, etc. Before calling ma_device_init(), you will need to +// initialize a ma_device_config object using ma_device_config_init(). You must set the callback in +// the device config. +// +// Passing in 0 to any property in pConfig will force the use of a default value. In the case of +// sample format, channel count, sample rate and channel map it will default to the values used by +// the backend's internal device. For the size of the buffer you can set bufferSizeInFrames or +// bufferSizeInMilliseconds (if both are set it will prioritize bufferSizeInFrames). If both are +// set to zero, it will default to MA_BASE_BUFFER_SIZE_IN_MILLISECONDS_LOW_LATENCY or +// MA_BASE_BUFFER_SIZE_IN_MILLISECONDS_CONSERVATIVE, depending on whether or not performanceProfile +// is set to ma_performance_profile_low_latency or ma_performance_profile_conservative. +// +// If you request exclusive mode and the backend does not support it an error will be returned. For +// robustness, you may want to first try initializing the device in exclusive mode, and then fall back +// to shared mode if required. Alternatively you can just request shared mode (the default if you +// leave it unset in the config) which is the most reliable option. Some backends do not have a +// practical way of choosing whether or not the device should be exclusive or not (ALSA, for example) +// in which case it just acts as a hint. Unless you have special requirements you should try avoiding +// exclusive mode as it's intrusive to the user. Starting with Windows 10, miniaudio will use low-latency +// shared mode where possible which may make exclusive mode unnecessary. +// +// When sending or receiving data to/from a device, miniaudio will internally perform a format +// conversion to convert between the format specified by pConfig and the format used internally by +// the backend. If you pass in NULL for pConfig or 0 for the sample format, channel count, +// sample rate _and_ channel map, data transmission will run on an optimized pass-through fast path. +// +// The buffer size should be treated as a hint. miniaudio will try it's best to use exactly what you +// ask for, but it may differ. You should not assume the number of frames specified in each call to +// the data callback is exactly what you originally specified. +// +// The property controls how frequently the background thread is woken to check for more +// data. It's tied to the buffer size, so as an example, if your buffer size is equivalent to 10 +// milliseconds and you have 2 periods, the CPU will wake up approximately every 5 milliseconds. +// +// When compiling for UWP you must ensure you call this function on the main UI thread because the +// operating system may need to present the user with a message asking for permissions. Please refer +// to the official documentation for ActivateAudioInterfaceAsync() for more information. +// +// ALSA Specific: When initializing the default device, requesting shared mode will try using the +// "dmix" device for playback and the "dsnoop" device for capture. If these fail it will try falling +// back to the "hw" device. +// +// Return Value: +// MA_SUCCESS if successful; any other error code otherwise. +// +// Thread Safety: UNSAFE +// It is not safe to call this function simultaneously for different devices because some backends +// depend on and mutate global state (such as OpenSL|ES). The same applies to calling this at the +// same time as ma_device_uninit(). +ma_result ma_device_init(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice); + +// Initializes a device without a context, with extra parameters for controlling the configuration +// of the internal self-managed context. +// +// See ma_device_init() and ma_context_init(). +ma_result ma_device_init_ex(const ma_backend backends[], ma_uint32 backendCount, const ma_context_config* pContextConfig, const ma_device_config* pConfig, ma_device* pDevice); + +// Uninitializes a device. +// +// This will explicitly stop the device. You do not need to call ma_device_stop() beforehand, but it's +// harmless if you do. +// +// Return Value: +// MA_SUCCESS if successful; any other error code otherwise. +// +// Thread Safety: UNSAFE +// As soon as this API is called the device should be considered undefined. All bets are off if you +// try using the device at the same time as uninitializing it. +void ma_device_uninit(ma_device* pDevice); + +// Sets the callback to use when the device has stopped, either explicitly or as a result of an error. +// +// Thread Safety: SAFE +// This API is implemented as a simple atomic assignment. +void ma_device_set_stop_callback(ma_device* pDevice, ma_stop_proc proc); + +// Activates the device. For playback devices this begins playback. For capture devices it begins +// recording. +// +// For a playback device, this will retrieve an initial chunk of audio data from the client before +// returning. The reason for this is to ensure there is valid audio data in the buffer, which needs +// to be done _before_ the device begins playback. +// +// This API waits until the backend device has been started for real by the worker thread. It also +// waits on a mutex for thread-safety. +// +// Return Value: +// MA_SUCCESS if successful; any other error code otherwise. +// +// Thread Safety: SAFE +ma_result ma_device_start(ma_device* pDevice); + +// Puts the device to sleep, but does not uninitialize it. Use ma_device_start() to start it up again. +// +// This API needs to wait on the worker thread to stop the backend device properly before returning. It +// also waits on a mutex for thread-safety. In addition, some backends need to wait for the device to +// finish playback/recording of the current fragment which can take some time (usually proportionate to +// the buffer size that was specified at initialization time). +// +// This should not drop unprocessed samples. Backends are required to either pause the stream in-place +// or drain the buffer if pausing is not possible. The reason for this is that stopping the device and +// the resuming it with ma_device_start() (which you might do when your program loses focus) may result +// in a situation where those samples are never output to the speakers or received from the microphone +// which can in turn result in de-syncs. +// +// Return Value: +// MA_SUCCESS if successful; any other error code otherwise. +// +// Thread Safety: SAFE +ma_result ma_device_stop(ma_device* pDevice); + +// Determines whether or not the device is started. +// +// This is implemented as a simple accessor. +// +// Return Value: +// True if the device is started, false otherwise. +// +// Thread Safety: SAFE +// If another thread calls ma_device_start() or ma_device_stop() at this same time as this function +// is called, there's a very small chance the return value will be out of sync. +ma_bool32 ma_device_is_started(ma_device* pDevice); + + +// Helper function for initializing a ma_context_config object. +ma_context_config ma_context_config_init(void); + +// Initializes a device config. +// +// By default, the device config will use native device settings (format, channels, sample rate, etc.). Using native +// settings means you will get an optimized pass-through data transmission pipeline to and from the device, but you will +// need to do all format conversions manually. Normally you would want to use a known format that your program can handle +// natively, which you can do by specifying it after this function returns, like so: +// +// ma_device_config config = ma_device_config_init(ma_device_type_playback); +// config.callback = my_data_callback; +// config.pUserData = pMyUserData; +// config.format = ma_format_f32; +// config.channels = 2; +// config.sampleRate = 44100; +// +// In this case miniaudio will perform all of the necessary data conversion for you behind the scenes. +// +// Currently miniaudio only supports asynchronous, callback based data delivery which means you must specify callback. A +// pointer to user data can also be specified which is set in the pUserData member of the ma_device object. +// +// To specify a channel map you can use ma_get_standard_channel_map(): +// +// ma_get_standard_channel_map(ma_standard_channel_map_default, config.channels, config.channelMap); +// +// Alternatively you can set the channel map manually if you need something specific or something that isn't one of miniaudio's +// stock channel maps. +// +// By default the system's default device will be used. Set the pDeviceID member to a pointer to a ma_device_id object to +// use a specific device. You can enumerate over the devices with ma_context_enumerate_devices() or ma_context_get_devices() +// which will give you access to the device ID. Set pDeviceID to NULL to use the default device. +// +// The device type can be one of the ma_device_type's: +// ma_device_type_playback +// ma_device_type_capture +// ma_device_type_duplex +// +// Thread Safety: SAFE +ma_device_config ma_device_config_init(ma_device_type deviceType); + + +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Utiltities +// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +// Creates a mutex. +// +// A mutex must be created from a valid context. A mutex is initially unlocked. +ma_result ma_mutex_init(ma_context* pContext, ma_mutex* pMutex); + +// Deletes a mutex. +void ma_mutex_uninit(ma_mutex* pMutex); + +// Locks a mutex with an infinite timeout. +void ma_mutex_lock(ma_mutex* pMutex); + +// Unlocks a mutex. +void ma_mutex_unlock(ma_mutex* pMutex); + + +// Retrieves a friendly name for a backend. +const char* ma_get_backend_name(ma_backend backend); + +// Adjust buffer size based on a scaling factor. +// +// This just multiplies the base size by the scaling factor, making sure it's a size of at least 1. +ma_uint32 ma_scale_buffer_size(ma_uint32 baseBufferSize, float scale); + +// Calculates a buffer size in milliseconds from the specified number of frames and sample rate. +ma_uint32 ma_calculate_buffer_size_in_milliseconds_from_frames(ma_uint32 bufferSizeInFrames, ma_uint32 sampleRate); + +// Calculates a buffer size in frames from the specified number of milliseconds and sample rate. +ma_uint32 ma_calculate_buffer_size_in_frames_from_milliseconds(ma_uint32 bufferSizeInMilliseconds, ma_uint32 sampleRate); + +// Retrieves the default buffer size in milliseconds based on the specified performance profile. +ma_uint32 ma_get_default_buffer_size_in_milliseconds(ma_performance_profile performanceProfile); + +// Calculates a buffer size in frames for the specified performance profile and scale factor. +ma_uint32 ma_get_default_buffer_size_in_frames(ma_performance_profile performanceProfile, ma_uint32 sampleRate); + + +// Copies silent frames into the given buffer. +void ma_zero_pcm_frames(void* p, ma_uint32 frameCount, ma_format format, ma_uint32 channels); + +#endif // MA_NO_DEVICE_IO + + + + +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Decoding +// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +#ifndef MA_NO_DECODING + +typedef struct ma_decoder ma_decoder; + +typedef enum +{ + ma_seek_origin_start, + ma_seek_origin_current +} ma_seek_origin; + +typedef size_t (* ma_decoder_read_proc) (ma_decoder* pDecoder, void* pBufferOut, size_t bytesToRead); // Returns the number of bytes read. +typedef ma_bool32 (* ma_decoder_seek_proc) (ma_decoder* pDecoder, int byteOffset, ma_seek_origin origin); +typedef ma_result (* ma_decoder_seek_to_pcm_frame_proc)(ma_decoder* pDecoder, ma_uint64 frameIndex); +typedef ma_result (* ma_decoder_uninit_proc) (ma_decoder* pDecoder); + +typedef struct +{ + ma_format format; // Set to 0 or ma_format_unknown to use the stream's internal format. + ma_uint32 channels; // Set to 0 to use the stream's internal channels. + ma_uint32 sampleRate; // Set to 0 to use the stream's internal sample rate. + ma_channel channelMap[MA_MAX_CHANNELS]; + ma_channel_mix_mode channelMixMode; + ma_dither_mode ditherMode; + ma_src_algorithm srcAlgorithm; + union + { + ma_src_config_sinc sinc; + } src; +} ma_decoder_config; + +struct ma_decoder +{ + ma_decoder_read_proc onRead; + ma_decoder_seek_proc onSeek; + void* pUserData; + ma_uint64 readPointer; /* Used for returning back to a previous position after analysing the stream or whatnot. */ + ma_format internalFormat; + ma_uint32 internalChannels; + ma_uint32 internalSampleRate; + ma_channel internalChannelMap[MA_MAX_CHANNELS]; + ma_format outputFormat; + ma_uint32 outputChannels; + ma_uint32 outputSampleRate; + ma_channel outputChannelMap[MA_MAX_CHANNELS]; + ma_pcm_converter dsp; // <-- Format conversion is achieved by running frames through this. + ma_decoder_seek_to_pcm_frame_proc onSeekToPCMFrame; + ma_decoder_uninit_proc onUninit; + void* pInternalDecoder; // <-- The drwav/drflac/stb_vorbis/etc. objects. + struct + { + const ma_uint8* pData; + size_t dataSize; + size_t currentReadPos; + } memory; // Only used for decoders that were opened against a block of memory. +}; + +ma_decoder_config ma_decoder_config_init(ma_format outputFormat, ma_uint32 outputChannels, ma_uint32 outputSampleRate); + +ma_result ma_decoder_init(ma_decoder_read_proc onRead, ma_decoder_seek_proc onSeek, void* pUserData, const ma_decoder_config* pConfig, ma_decoder* pDecoder); +ma_result ma_decoder_init_wav(ma_decoder_read_proc onRead, ma_decoder_seek_proc onSeek, void* pUserData, const ma_decoder_config* pConfig, ma_decoder* pDecoder); +ma_result ma_decoder_init_flac(ma_decoder_read_proc onRead, ma_decoder_seek_proc onSeek, void* pUserData, const ma_decoder_config* pConfig, ma_decoder* pDecoder); +ma_result ma_decoder_init_vorbis(ma_decoder_read_proc onRead, ma_decoder_seek_proc onSeek, void* pUserData, const ma_decoder_config* pConfig, ma_decoder* pDecoder); +ma_result ma_decoder_init_mp3(ma_decoder_read_proc onRead, ma_decoder_seek_proc onSeek, void* pUserData, const ma_decoder_config* pConfig, ma_decoder* pDecoder); +ma_result ma_decoder_init_raw(ma_decoder_read_proc onRead, ma_decoder_seek_proc onSeek, void* pUserData, const ma_decoder_config* pConfigIn, const ma_decoder_config* pConfigOut, ma_decoder* pDecoder); + +ma_result ma_decoder_init_memory(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder); +ma_result ma_decoder_init_memory_wav(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder); +ma_result ma_decoder_init_memory_flac(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder); +ma_result ma_decoder_init_memory_vorbis(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder); +ma_result ma_decoder_init_memory_mp3(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder); +ma_result ma_decoder_init_memory_raw(const void* pData, size_t dataSize, const ma_decoder_config* pConfigIn, const ma_decoder_config* pConfigOut, ma_decoder* pDecoder); + +#ifndef MA_NO_STDIO +ma_result ma_decoder_init_file(const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder); +ma_result ma_decoder_init_file_wav(const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder); +#endif + +ma_result ma_decoder_uninit(ma_decoder* pDecoder); + +ma_uint64 ma_decoder_read_pcm_frames(ma_decoder* pDecoder, void* pFramesOut, ma_uint64 frameCount); +ma_result ma_decoder_seek_to_pcm_frame(ma_decoder* pDecoder, ma_uint64 frameIndex); + + +// Helper for opening and decoding a file into a heap allocated block of memory. Free the returned pointer with ma_free(). On input, +// pConfig should be set to what you want. On output it will be set to what you got. +#ifndef MA_NO_STDIO +ma_result ma_decode_file(const char* pFilePath, ma_decoder_config* pConfig, ma_uint64* pFrameCountOut, void** ppDataOut); +#endif +ma_result ma_decode_memory(const void* pData, size_t dataSize, ma_decoder_config* pConfig, ma_uint64* pFrameCountOut, void** ppDataOut); + +#endif // MA_NO_DECODING + + +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Generation +// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +typedef struct +{ + double amplitude; + double periodsPerSecond; + double delta; + double time; +} ma_sine_wave; + +ma_result ma_sine_wave_init(double amplitude, double period, ma_uint32 sampleRate, ma_sine_wave* pSineWave); +ma_uint64 ma_sine_wave_read_f32(ma_sine_wave* pSineWave, ma_uint64 count, float* pSamples); +ma_uint64 ma_sine_wave_read_f32_ex(ma_sine_wave* pSineWave, ma_uint64 frameCount, ma_uint32 channels, ma_stream_layout layout, float** ppFrames); + + +#ifdef __cplusplus +} +#endif +#endif //miniaudio_h + + +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// +// IMPLEMENTATION +// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +#if defined(MINIAUDIO_IMPLEMENTATION) || defined(MA_IMPLEMENTATION) +#include +#include // For INT_MAX +#include // sin(), etc. + +#if defined(MA_DEBUG_OUTPUT) +#include // for printf() for debug output +#endif + +#ifdef MA_WIN32 +// @raysan5: To avoid conflicting windows.h symbols with raylib, so flags are defined +// WARNING: Those flags avoid inclusion of some Win32 headers that could be required +// by user at some point and won't be included... +//------------------------------------------------------------------------------------- + +// If defined, the following flags inhibit definition of the indicated items. +#define NOGDICAPMASKS // CC_*, LC_*, PC_*, CP_*, TC_*, RC_ +#define NOVIRTUALKEYCODES // VK_* +#define NOWINMESSAGES // WM_*, EM_*, LB_*, CB_* +#define NOWINSTYLES // WS_*, CS_*, ES_*, LBS_*, SBS_*, CBS_* +#define NOSYSMETRICS // SM_* +#define NOMENUS // MF_* +#define NOICONS // IDI_* +#define NOKEYSTATES // MK_* +#define NOSYSCOMMANDS // SC_* +#define NORASTEROPS // Binary and Tertiary raster ops +#define NOSHOWWINDOW // SW_* +#define OEMRESOURCE // OEM Resource values +#define NOATOM // Atom Manager routines +#define NOCLIPBOARD // Clipboard routines +#define NOCOLOR // Screen colors +#define NOCTLMGR // Control and Dialog routines +#define NODRAWTEXT // DrawText() and DT_* +#define NOGDI // All GDI defines and routines +#define NOKERNEL // All KERNEL defines and routines +#define NOUSER // All USER defines and routines +//#define NONLS // All NLS defines and routines +#define NOMB // MB_* and MessageBox() +#define NOMEMMGR // GMEM_*, LMEM_*, GHND, LHND, associated routines +#define NOMETAFILE // typedef METAFILEPICT +#define NOMINMAX // Macros min(a,b) and max(a,b) +#define NOMSG // typedef MSG and associated routines +#define NOOPENFILE // OpenFile(), OemToAnsi, AnsiToOem, and OF_* +#define NOSCROLL // SB_* and scrolling routines +#define NOSERVICE // All Service Controller routines, SERVICE_ equates, etc. +#define NOSOUND // Sound driver routines +#define NOTEXTMETRIC // typedef TEXTMETRIC and associated routines +#define NOWH // SetWindowsHook and WH_* +#define NOWINOFFSETS // GWL_*, GCL_*, associated routines +#define NOCOMM // COMM driver routines +#define NOKANJI // Kanji support stuff. +#define NOHELP // Help engine interface. +#define NOPROFILER // Profiler interface. +#define NODEFERWINDOWPOS // DeferWindowPos routines +#define NOMCX // Modem Configuration Extensions + +// Type required before windows.h inclusion +typedef struct tagMSG *LPMSG; + +#include + +// Type required by some unused function... +typedef struct tagBITMAPINFOHEADER { + DWORD biSize; + LONG biWidth; + LONG biHeight; + WORD biPlanes; + WORD biBitCount; + DWORD biCompression; + DWORD biSizeImage; + LONG biXPelsPerMeter; + LONG biYPelsPerMeter; + DWORD biClrUsed; + DWORD biClrImportant; +} BITMAPINFOHEADER, *PBITMAPINFOHEADER; + +#include +#include +#include + +// @raysan5: Some required types defined for MSVC/TinyC compiler +#if defined(_MSC_VER) || defined(__TINYC__) + #include "propidl.h" +#endif +//---------------------------------------------------------------------------------- + +#else +#include // For malloc()/free() +#include // For memset() +#endif + +#if defined(MA_APPLE) && (__MAC_OS_X_VERSION_MIN_REQUIRED < 101200) +#include // For mach_absolute_time() +#endif + +#ifdef MA_POSIX +#include +#include +#endif + +#ifdef MA_EMSCRIPTEN +#include +#endif + +#if !defined(MA_64BIT) && !defined(MA_32BIT) +#ifdef _WIN32 +#ifdef _WIN64 +#define MA_64BIT +#else +#define MA_32BIT +#endif +#endif +#endif + +#if !defined(MA_64BIT) && !defined(MA_32BIT) +#ifdef __GNUC__ +#ifdef __LP64__ +#define MA_64BIT +#else +#define MA_32BIT +#endif +#endif +#endif + +#if !defined(MA_64BIT) && !defined(MA_32BIT) +#include +#if INTPTR_MAX == INT64_MAX +#define MA_64BIT +#else +#define MA_32BIT +#endif +#endif + +// Architecture Detection +#if defined(__x86_64__) || defined(_M_X64) +#define MA_X64 +#elif defined(__i386) || defined(_M_IX86) +#define MA_X86 +#elif defined(__arm__) || defined(_M_ARM) +#define MA_ARM +#endif + +// Cannot currently support AVX-512 if AVX is disabled. +#if !defined(MA_NO_AVX512) && defined(MA_NO_AVX2) +#define MA_NO_AVX512 +#endif + +// Intrinsics Support +#if defined(MA_X64) || defined(MA_X86) + #if defined(_MSC_VER) && !defined(__clang__) + // MSVC. + #if !defined(MA_NO_SSE2) // Assume all MSVC compilers support SSE2 intrinsics. + #define MA_SUPPORT_SSE2 + #endif + //#if _MSC_VER >= 1600 && !defined(MA_NO_AVX) // 2010 + // #define MA_SUPPORT_AVX + //#endif + #if _MSC_VER >= 1700 && !defined(MA_NO_AVX2) // 2012 + #define MA_SUPPORT_AVX2 + #endif + #if _MSC_VER >= 1910 && !defined(MA_NO_AVX512) // 2017 + #define MA_SUPPORT_AVX512 + #endif + #else + // Assume GNUC-style. + #if defined(__SSE2__) && !defined(MA_NO_SSE2) + #define MA_SUPPORT_SSE2 + #endif + //#if defined(__AVX__) && !defined(MA_NO_AVX) + // #define MA_SUPPORT_AVX + //#endif + #if defined(__AVX2__) && !defined(MA_NO_AVX2) + #define MA_SUPPORT_AVX2 + #endif + #if defined(__AVX512F__) && !defined(MA_NO_AVX512) + #define MA_SUPPORT_AVX512 + #endif + #endif + + // If at this point we still haven't determined compiler support for the intrinsics just fall back to __has_include. + #if !defined(__GNUC__) && !defined(__clang__) && defined(__has_include) + #if !defined(MA_SUPPORT_SSE2) && !defined(MA_NO_SSE2) && __has_include() + #define MA_SUPPORT_SSE2 + #endif + //#if !defined(MA_SUPPORT_AVX) && !defined(MA_NO_AVX) && __has_include() + // #define MA_SUPPORT_AVX + //#endif + #if !defined(MA_SUPPORT_AVX2) && !defined(MA_NO_AVX2) && __has_include() + #define MA_SUPPORT_AVX2 + #endif + #if !defined(MA_SUPPORT_AVX512) && !defined(MA_NO_AVX512) && __has_include() + #define MA_SUPPORT_AVX512 + #endif + #endif + + #if defined(MA_SUPPORT_AVX512) + #include // Not a mistake. Intentionally including instead of because otherwise the compiler will complain. + #elif defined(MA_SUPPORT_AVX2) || defined(MA_SUPPORT_AVX) + #include + #elif defined(MA_SUPPORT_SSE2) + #include + #endif +#endif + +#if defined(MA_ARM) + #if !defined(MA_NO_NEON) && (defined(__ARM_NEON) || defined(__aarch64__) || defined(_M_ARM64)) + #define MA_SUPPORT_NEON + #endif + + // Fall back to looking for the #include file. + #if !defined(__GNUC__) && !defined(__clang__) && defined(__has_include) + #if !defined(MA_SUPPORT_NEON) && !defined(MA_NO_NEON) && __has_include() + #define MA_SUPPORT_NEON + #endif + #endif + + #if defined(MA_SUPPORT_NEON) + #include + #endif +#endif + +#if defined(_MSC_VER) + #pragma warning(push) + #pragma warning(disable:4752) // found Intel(R) Advanced Vector Extensions; consider using /arch:AVX +#endif + +#if defined(MA_X64) || defined(MA_X86) + #if defined(_MSC_VER) && !defined(__clang__) + #if _MSC_VER >= 1400 + #include + static MA_INLINE void ma_cpuid(int info[4], int fid) + { + __cpuid(info, fid); + } + #else + #define MA_NO_CPUID + #endif + + #if _MSC_VER >= 1600 + static MA_INLINE unsigned __int64 ma_xgetbv(int reg) + { + return _xgetbv(reg); + } + #else + #define MA_NO_XGETBV + #endif + #elif (defined(__GNUC__) || defined(__clang__)) && !defined(MA_ANDROID) + static MA_INLINE void ma_cpuid(int info[4], int fid) + { + // It looks like the -fPIC option uses the ebx register which GCC complains about. We can work around this by just using a different register, the + // specific register of which I'm letting the compiler decide on. The "k" prefix is used to specify a 32-bit register. The {...} syntax is for + // supporting different assembly dialects. + // + // What's basically happening is that we're saving and restoring the ebx register manually. + #if defined(DRFLAC_X86) && defined(__PIC__) + __asm__ __volatile__ ( + "xchg{l} {%%}ebx, %k1;" + "cpuid;" + "xchg{l} {%%}ebx, %k1;" + : "=a"(info[0]), "=&r"(info[1]), "=c"(info[2]), "=d"(info[3]) : "a"(fid), "c"(0) + ); + #else + __asm__ __volatile__ ( + "cpuid" : "=a"(info[0]), "=b"(info[1]), "=c"(info[2]), "=d"(info[3]) : "a"(fid), "c"(0) + ); + #endif + } + + static MA_INLINE unsigned long long ma_xgetbv(int reg) + { + unsigned int hi; + unsigned int lo; + + __asm__ __volatile__ ( + "xgetbv" : "=a"(lo), "=d"(hi) : "c"(reg) + ); + + return ((unsigned long long)hi << 32ULL) | (unsigned long long)lo; + } + #else + #define MA_NO_CPUID + #define MA_NO_XGETBV + #endif +#else + #define MA_NO_CPUID + #define MA_NO_XGETBV +#endif + +static MA_INLINE ma_bool32 ma_has_sse2() +{ +#if defined(MA_SUPPORT_SSE2) + #if (defined(MA_X64) || defined(MA_X86)) && !defined(MA_NO_SSE2) + #if defined(MA_X64) + return MA_TRUE; // 64-bit targets always support SSE2. + #elif (defined(_M_IX86_FP) && _M_IX86_FP == 2) || defined(__SSE2__) + return MA_TRUE; // If the compiler is allowed to freely generate SSE2 code we can assume support. + #else + #if defined(MA_NO_CPUID) + return MA_FALSE; + #else + int info[4]; + ma_cpuid(info, 1); + return (info[3] & (1 << 26)) != 0; + #endif + #endif + #else + return MA_FALSE; // SSE2 is only supported on x86 and x64 architectures. + #endif +#else + return MA_FALSE; // No compiler support. +#endif +} + +#if 0 +static MA_INLINE ma_bool32 ma_has_avx() +{ +#if defined(MA_SUPPORT_AVX) + #if (defined(MA_X64) || defined(MA_X86)) && !defined(MA_NO_AVX) + #if defined(_AVX_) || defined(__AVX__) + return MA_TRUE; // If the compiler is allowed to freely generate AVX code we can assume support. + #else + // AVX requires both CPU and OS support. + #if defined(MA_NO_CPUID) || defined(MA_NO_XGETBV) + return MA_FALSE; + #else + int info[4]; + ma_cpuid(info, 1); + if (((info[2] & (1 << 27)) != 0) && ((info[2] & (1 << 28)) != 0)) { + ma_uint64 xrc = ma_xgetbv(0); + if ((xrc & 0x06) == 0x06) { + return MA_TRUE; + } else { + return MA_FALSE; + } + } else { + return MA_FALSE; + } + #endif + #endif + #else + return MA_FALSE; // AVX is only supported on x86 and x64 architectures. + #endif +#else + return MA_FALSE; // No compiler support. +#endif +} +#endif + +static MA_INLINE ma_bool32 ma_has_avx2() +{ +#if defined(MA_SUPPORT_AVX2) + #if (defined(MA_X64) || defined(MA_X86)) && !defined(MA_NO_AVX2) + #if defined(_AVX2_) || defined(__AVX2__) + return MA_TRUE; // If the compiler is allowed to freely generate AVX2 code we can assume support. + #else + // AVX2 requires both CPU and OS support. + #if defined(MA_NO_CPUID) || defined(MA_NO_XGETBV) + return MA_FALSE; + #else + int info1[4]; + int info7[4]; + ma_cpuid(info1, 1); + ma_cpuid(info7, 7); + if (((info1[2] & (1 << 27)) != 0) && ((info7[1] & (1 << 5)) != 0)) { + ma_uint64 xrc = ma_xgetbv(0); + if ((xrc & 0x06) == 0x06) { + return MA_TRUE; + } else { + return MA_FALSE; + } + } else { + return MA_FALSE; + } + #endif + #endif + #else + return MA_FALSE; // AVX2 is only supported on x86 and x64 architectures. + #endif +#else + return MA_FALSE; // No compiler support. +#endif +} + +static MA_INLINE ma_bool32 ma_has_avx512f() +{ +#if defined(MA_SUPPORT_AVX512) + #if (defined(MA_X64) || defined(MA_X86)) && !defined(MA_NO_AVX512) + #if defined(__AVX512F__) + return MA_TRUE; // If the compiler is allowed to freely generate AVX-512F code we can assume support. + #else + // AVX-512 requires both CPU and OS support. + #if defined(MA_NO_CPUID) || defined(MA_NO_XGETBV) + return MA_FALSE; + #else + int info1[4]; + int info7[4]; + ma_cpuid(info1, 1); + ma_cpuid(info7, 7); + if (((info1[2] & (1 << 27)) != 0) && ((info7[1] & (1 << 16)) != 0)) { + ma_uint64 xrc = ma_xgetbv(0); + if ((xrc & 0xE6) == 0xE6) { + return MA_TRUE; + } else { + return MA_FALSE; + } + } else { + return MA_FALSE; + } + #endif + #endif + #else + return MA_FALSE; // AVX-512F is only supported on x86 and x64 architectures. + #endif +#else + return MA_FALSE; // No compiler support. +#endif +} + +static MA_INLINE ma_bool32 ma_has_neon() +{ +#if defined(MA_SUPPORT_NEON) + #if defined(MA_ARM) && !defined(MA_NO_NEON) + #if (defined(__ARM_NEON) || defined(__aarch64__) || defined(_M_ARM64)) + return MA_TRUE; // If the compiler is allowed to freely generate NEON code we can assume support. + #else + // TODO: Runtime check. + return MA_FALSE; + #endif + #else + return MA_FALSE; // NEON is only supported on ARM architectures. + #endif +#else + return MA_FALSE; // No compiler support. +#endif +} + + +static MA_INLINE ma_bool32 ma_is_little_endian() +{ +#if defined(MA_X86) || defined(MA_X64) + return MA_TRUE; +#else + int n = 1; + return (*(char*)&n) == 1; +#endif +} + +static MA_INLINE ma_bool32 ma_is_big_endian() +{ + return !ma_is_little_endian(); +} + + +#ifndef MA_COINIT_VALUE +#define MA_COINIT_VALUE 0 /* 0 = COINIT_MULTITHREADED*/ +#endif + + + +#ifndef MA_PI +#define MA_PI 3.14159265358979323846264f +#endif +#ifndef MA_PI_D +#define MA_PI_D 3.14159265358979323846264 +#endif +#ifndef MA_TAU +#define MA_TAU 6.28318530717958647693f +#endif +#ifndef MA_TAU_D +#define MA_TAU_D 6.28318530717958647693 +#endif + + +// The default format when ma_format_unknown (0) is requested when initializing a device. +#ifndef MA_DEFAULT_FORMAT +#define MA_DEFAULT_FORMAT ma_format_f32 +#endif + +// The default channel count to use when 0 is used when initializing a device. +#ifndef MA_DEFAULT_CHANNELS +#define MA_DEFAULT_CHANNELS 2 +#endif + +// The default sample rate to use when 0 is used when initializing a device. +#ifndef MA_DEFAULT_SAMPLE_RATE +#define MA_DEFAULT_SAMPLE_RATE 48000 +#endif + +// Default periods when none is specified in ma_device_init(). More periods means more work on the CPU. +#ifndef MA_DEFAULT_PERIODS +#define MA_DEFAULT_PERIODS 3 +#endif + +// The base buffer size in milliseconds for low latency mode. +#ifndef MA_BASE_BUFFER_SIZE_IN_MILLISECONDS_LOW_LATENCY +#define MA_BASE_BUFFER_SIZE_IN_MILLISECONDS_LOW_LATENCY (10*MA_DEFAULT_PERIODS) +#endif + +// The base buffer size in milliseconds for conservative mode. +#ifndef MA_BASE_BUFFER_SIZE_IN_MILLISECONDS_CONSERVATIVE +#define MA_BASE_BUFFER_SIZE_IN_MILLISECONDS_CONSERVATIVE (100*MA_DEFAULT_PERIODS) +#endif + + +// Standard sample rates, in order of priority. +ma_uint32 g_maStandardSampleRatePriorities[] = { + MA_SAMPLE_RATE_48000, // Most common + MA_SAMPLE_RATE_44100, + + MA_SAMPLE_RATE_32000, // Lows + MA_SAMPLE_RATE_24000, + MA_SAMPLE_RATE_22050, + + MA_SAMPLE_RATE_88200, // Highs + MA_SAMPLE_RATE_96000, + MA_SAMPLE_RATE_176400, + MA_SAMPLE_RATE_192000, + + MA_SAMPLE_RATE_16000, // Extreme lows + MA_SAMPLE_RATE_11025, + MA_SAMPLE_RATE_8000, + + MA_SAMPLE_RATE_352800, // Extreme highs + MA_SAMPLE_RATE_384000 +}; + +ma_format g_maFormatPriorities[] = { + ma_format_s16, // Most common + ma_format_f32, + + //ma_format_s24_32, // Clean alignment + ma_format_s32, + + ma_format_s24, // Unclean alignment + + ma_format_u8 // Low quality +}; + + + +/////////////////////////////////////////////////////////////////////////////// +// +// Standard Library Stuff +// +/////////////////////////////////////////////////////////////////////////////// +#ifndef MA_MALLOC +#ifdef MA_WIN32 +#define MA_MALLOC(sz) HeapAlloc(GetProcessHeap(), 0, (sz)) +#else +#define MA_MALLOC(sz) malloc((sz)) +#endif +#endif + +#ifndef MA_REALLOC +#ifdef MA_WIN32 +#define MA_REALLOC(p, sz) (((sz) > 0) ? ((p) ? HeapReAlloc(GetProcessHeap(), 0, (p), (sz)) : HeapAlloc(GetProcessHeap(), 0, (sz))) : ((VOID*)(size_t)(HeapFree(GetProcessHeap(), 0, (p)) & 0))) +#else +#define MA_REALLOC(p, sz) realloc((p), (sz)) +#endif +#endif + +#ifndef MA_FREE +#ifdef MA_WIN32 +#define MA_FREE(p) HeapFree(GetProcessHeap(), 0, (p)) +#else +#define MA_FREE(p) free((p)) +#endif +#endif + +#ifndef MA_ZERO_MEMORY +#ifdef MA_WIN32 +#define MA_ZERO_MEMORY(p, sz) ZeroMemory((p), (sz)) +#else +#define MA_ZERO_MEMORY(p, sz) memset((p), 0, (sz)) +#endif +#endif + +#ifndef MA_COPY_MEMORY +#ifdef MA_WIN32 +#define MA_COPY_MEMORY(dst, src, sz) CopyMemory((dst), (src), (sz)) +#else +#define MA_COPY_MEMORY(dst, src, sz) memcpy((dst), (src), (sz)) +#endif +#endif + +#ifndef MA_ASSERT +#ifdef MA_WIN32 +#define MA_ASSERT(condition) assert(condition) +#else +#define MA_ASSERT(condition) assert(condition) +#endif +#endif + +#define ma_zero_memory MA_ZERO_MEMORY +#define ma_copy_memory MA_COPY_MEMORY +#define ma_assert MA_ASSERT + +#define ma_zero_object(p) ma_zero_memory((p), sizeof(*(p))) +#define ma_countof(x) (sizeof(x) / sizeof(x[0])) +#define ma_max(x, y) (((x) > (y)) ? (x) : (y)) +#define ma_min(x, y) (((x) < (y)) ? (x) : (y)) +#define ma_clamp(x, lo, hi) (ma_max(lo, ma_min(x, hi))) +#define ma_offset_ptr(p, offset) (((ma_uint8*)(p)) + (offset)) + +#define ma_buffer_frame_capacity(buffer, channels, format) (sizeof(buffer) / ma_get_bytes_per_sample(format) / (channels)) + + +// Return Values: +// 0: Success +// 22: EINVAL +// 34: ERANGE +// +// Not using symbolic constants for errors because I want to avoid #including errno.h +int ma_strcpy_s(char* dst, size_t dstSizeInBytes, const char* src) +{ + if (dst == 0) { + return 22; + } + if (dstSizeInBytes == 0) { + return 34; + } + if (src == 0) { + dst[0] = '\0'; + return 22; + } + + size_t i; + for (i = 0; i < dstSizeInBytes && src[i] != '\0'; ++i) { + dst[i] = src[i]; + } + + if (i < dstSizeInBytes) { + dst[i] = '\0'; + return 0; + } + + dst[0] = '\0'; + return 34; +} + +int ma_strncpy_s(char* dst, size_t dstSizeInBytes, const char* src, size_t count) +{ + if (dst == 0) { + return 22; + } + if (dstSizeInBytes == 0) { + return 34; + } + if (src == 0) { + dst[0] = '\0'; + return 22; + } + + size_t maxcount = count; + if (count == ((size_t)-1) || count >= dstSizeInBytes) { // -1 = _TRUNCATE + maxcount = dstSizeInBytes - 1; + } + + size_t i; + for (i = 0; i < maxcount && src[i] != '\0'; ++i) { + dst[i] = src[i]; + } + + if (src[i] == '\0' || i == count || count == ((size_t)-1)) { + dst[i] = '\0'; + return 0; + } + + dst[0] = '\0'; + return 34; +} + +int ma_strcat_s(char* dst, size_t dstSizeInBytes, const char* src) +{ + if (dst == 0) { + return 22; + } + if (dstSizeInBytes == 0) { + return 34; + } + if (src == 0) { + dst[0] = '\0'; + return 22; + } + + char* dstorig = dst; + + while (dstSizeInBytes > 0 && dst[0] != '\0') { + dst += 1; + dstSizeInBytes -= 1; + } + + if (dstSizeInBytes == 0) { + return 22; // Unterminated. + } + + + while (dstSizeInBytes > 0 && src[0] != '\0') { + *dst++ = *src++; + dstSizeInBytes -= 1; + } + + if (dstSizeInBytes > 0) { + dst[0] = '\0'; + } else { + dstorig[0] = '\0'; + return 34; + } + + return 0; +} + +int ma_itoa_s(int value, char* dst, size_t dstSizeInBytes, int radix) +{ + if (dst == NULL || dstSizeInBytes == 0) { + return 22; + } + if (radix < 2 || radix > 36) { + dst[0] = '\0'; + return 22; + } + + int sign = (value < 0 && radix == 10) ? -1 : 1; // The negative sign is only used when the base is 10. + + unsigned int valueU; + if (value < 0) { + valueU = -value; + } else { + valueU = value; + } + + char* dstEnd = dst; + do + { + int remainder = valueU % radix; + if (remainder > 9) { + *dstEnd = (char)((remainder - 10) + 'a'); + } else { + *dstEnd = (char)(remainder + '0'); + } + + dstEnd += 1; + dstSizeInBytes -= 1; + valueU /= radix; + } while (dstSizeInBytes > 0 && valueU > 0); + + if (dstSizeInBytes == 0) { + dst[0] = '\0'; + return 22; // Ran out of room in the output buffer. + } + + if (sign < 0) { + *dstEnd++ = '-'; + dstSizeInBytes -= 1; + } + + if (dstSizeInBytes == 0) { + dst[0] = '\0'; + return 22; // Ran out of room in the output buffer. + } + + *dstEnd = '\0'; + + + // At this point the string will be reversed. + dstEnd -= 1; + while (dst < dstEnd) { + char temp = *dst; + *dst = *dstEnd; + *dstEnd = temp; + + dst += 1; + dstEnd -= 1; + } + + return 0; +} + +int ma_strcmp(const char* str1, const char* str2) +{ + if (str1 == str2) return 0; + + // These checks differ from the standard implementation. It's not important, but I prefer + // it just for sanity. + if (str1 == NULL) return -1; + if (str2 == NULL) return 1; + + for (;;) { + if (str1[0] == '\0') { + break; + } + if (str1[0] != str2[0]) { + break; + } + + str1 += 1; + str2 += 1; + } + + return ((unsigned char*)str1)[0] - ((unsigned char*)str2)[0]; +} + + +// Thanks to good old Bit Twiddling Hacks for this one: http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 +static MA_INLINE unsigned int ma_next_power_of_2(unsigned int x) +{ + x--; + x |= x >> 1; + x |= x >> 2; + x |= x >> 4; + x |= x >> 8; + x |= x >> 16; + x++; + + return x; +} + +static MA_INLINE unsigned int ma_prev_power_of_2(unsigned int x) +{ + return ma_next_power_of_2(x) >> 1; +} + +static MA_INLINE unsigned int ma_round_to_power_of_2(unsigned int x) +{ + unsigned int prev = ma_prev_power_of_2(x); + unsigned int next = ma_next_power_of_2(x); + if ((next - x) > (x - prev)) { + return prev; + } else { + return next; + } +} + +static MA_INLINE unsigned int ma_count_set_bits(unsigned int x) +{ + unsigned int count = 0; + while (x != 0) { + if (x & 1) { + count += 1; + } + + x = x >> 1; + } + + return count; +} + + + +// Clamps an f32 sample to -1..1 +static MA_INLINE float ma_clip_f32(float x) +{ + if (x < -1) return -1; + if (x > +1) return +1; + return x; +} + +static MA_INLINE float ma_mix_f32(float x, float y, float a) +{ + return x*(1-a) + y*a; +} +static MA_INLINE float ma_mix_f32_fast(float x, float y, float a) +{ + float r0 = (y - x); + float r1 = r0*a; + return x + r1; + //return x + (y - x)*a; +} + +#if defined(MA_SUPPORT_SSE2) +static MA_INLINE __m128 ma_mix_f32_fast__sse2(__m128 x, __m128 y, __m128 a) +{ + return _mm_add_ps(x, _mm_mul_ps(_mm_sub_ps(y, x), a)); +} +#endif +#if defined(MA_SUPPORT_AVX2) +static MA_INLINE __m256 ma_mix_f32_fast__avx2(__m256 x, __m256 y, __m256 a) +{ + return _mm256_add_ps(x, _mm256_mul_ps(_mm256_sub_ps(y, x), a)); +} +#endif +#if defined(MA_SUPPORT_AVX512) +static MA_INLINE __m512 ma_mix_f32_fast__avx512(__m512 x, __m512 y, __m512 a) +{ + return _mm512_add_ps(x, _mm512_mul_ps(_mm512_sub_ps(y, x), a)); +} +#endif +#if defined(MA_SUPPORT_NEON) +static MA_INLINE float32x4_t ma_mix_f32_fast__neon(float32x4_t x, float32x4_t y, float32x4_t a) +{ + return vaddq_f32(x, vmulq_f32(vsubq_f32(y, x), a)); +} +#endif + + +static MA_INLINE double ma_mix_f64(double x, double y, double a) +{ + return x*(1-a) + y*a; +} +static MA_INLINE double ma_mix_f64_fast(double x, double y, double a) +{ + return x + (y - x)*a; +} + +static MA_INLINE float ma_scale_to_range_f32(float x, float lo, float hi) +{ + return lo + x*(hi-lo); +} + + + +// Random Number Generation +// +// miniaudio uses the LCG random number generation algorithm. This is good enough for audio. +// +// Note that miniaudio's LCG implementation uses global state which is _not_ thread-local. When this is called across +// multiple threads, results will be unpredictable. However, it won't crash and results will still be random enough +// for miniaudio's purposes. +#define MA_LCG_M 4294967296 +#define MA_LCG_A 1103515245 +#define MA_LCG_C 12345 +static ma_int32 g_maLCG; + +void ma_seed(ma_int32 seed) +{ + g_maLCG = seed; +} + +ma_int32 ma_rand_s32() +{ + ma_int32 lcg = g_maLCG; + ma_int32 r = (MA_LCG_A * lcg + MA_LCG_C) % MA_LCG_M; + g_maLCG = r; + return r; +} + +double ma_rand_f64() +{ + return (ma_rand_s32() + 0x80000000) / (double)0x7FFFFFFF; +} + +float ma_rand_f32() +{ + return (float)ma_rand_f64(); +} + +static MA_INLINE float ma_rand_range_f32(float lo, float hi) +{ + return ma_scale_to_range_f32(ma_rand_f32(), lo, hi); +} + +static MA_INLINE ma_int32 ma_rand_range_s32(ma_int32 lo, ma_int32 hi) +{ + double x = ma_rand_f64(); + return lo + (ma_int32)(x*(hi-lo)); +} + + +static MA_INLINE float ma_dither_f32_rectangle(float ditherMin, float ditherMax) +{ + return ma_rand_range_f32(ditherMin, ditherMax); +} + +static MA_INLINE float ma_dither_f32_triangle(float ditherMin, float ditherMax) +{ + float a = ma_rand_range_f32(ditherMin, 0); + float b = ma_rand_range_f32(0, ditherMax); + return a + b; +} + +static MA_INLINE float ma_dither_f32(ma_dither_mode ditherMode, float ditherMin, float ditherMax) +{ + if (ditherMode == ma_dither_mode_rectangle) { + return ma_dither_f32_rectangle(ditherMin, ditherMax); + } + if (ditherMode == ma_dither_mode_triangle) { + return ma_dither_f32_triangle(ditherMin, ditherMax); + } + + return 0; +} + +static MA_INLINE ma_int32 ma_dither_s32(ma_dither_mode ditherMode, ma_int32 ditherMin, ma_int32 ditherMax) +{ + if (ditherMode == ma_dither_mode_rectangle) { + ma_int32 a = ma_rand_range_s32(ditherMin, ditherMax); + return a; + } + if (ditherMode == ma_dither_mode_triangle) { + ma_int32 a = ma_rand_range_s32(ditherMin, 0); + ma_int32 b = ma_rand_range_s32(0, ditherMax); + return a + b; + } + + return 0; +} + + +// Splits a buffer into parts of equal length and of the given alignment. The returned size of the split buffers will be a +// multiple of the alignment. The alignment must be a power of 2. +void ma_split_buffer(void* pBuffer, size_t bufferSize, size_t splitCount, size_t alignment, void** ppBuffersOut, size_t* pSplitSizeOut) +{ + if (pSplitSizeOut) { + *pSplitSizeOut = 0; + } + + if (pBuffer == NULL || bufferSize == 0 || splitCount == 0) { + return; + } + + if (alignment == 0) { + alignment = 1; + } + + ma_uintptr pBufferUnaligned = (ma_uintptr)pBuffer; + ma_uintptr pBufferAligned = (pBufferUnaligned + (alignment-1)) & ~(alignment-1); + size_t unalignedBytes = (size_t)(pBufferAligned - pBufferUnaligned); + + size_t splitSize = 0; + if (bufferSize >= unalignedBytes) { + splitSize = (bufferSize - unalignedBytes) / splitCount; + splitSize = splitSize & ~(alignment-1); + } + + if (ppBuffersOut != NULL) { + for (size_t i = 0; i < splitCount; ++i) { + ppBuffersOut[i] = (ma_uint8*)(pBufferAligned + (splitSize*i)); + } + } + + if (pSplitSizeOut) { + *pSplitSizeOut = splitSize; + } +} + + +/////////////////////////////////////////////////////////////////////////////// +// +// Atomics +// +/////////////////////////////////////////////////////////////////////////////// +#if defined(_WIN32) && !defined(__GNUC__) +#define ma_memory_barrier() MemoryBarrier() +#define ma_atomic_exchange_32(a, b) InterlockedExchange((LONG*)a, (LONG)b) +#define ma_atomic_exchange_64(a, b) InterlockedExchange64((LONGLONG*)a, (LONGLONG)b) +#define ma_atomic_increment_32(a) InterlockedIncrement((LONG*)a) +#define ma_atomic_decrement_32(a) InterlockedDecrement((LONG*)a) +#else +#define ma_memory_barrier() __sync_synchronize() +#define ma_atomic_exchange_32(a, b) (void)__sync_lock_test_and_set(a, b); __sync_synchronize() +#define ma_atomic_exchange_64(a, b) (void)__sync_lock_test_and_set(a, b); __sync_synchronize() +#define ma_atomic_increment_32(a) __sync_add_and_fetch(a, 1) +#define ma_atomic_decrement_32(a) __sync_sub_and_fetch(a, 1) +#endif + +#ifdef MA_64BIT +#define ma_atomic_exchange_ptr ma_atomic_exchange_64 +#endif +#ifdef MA_32BIT +#define ma_atomic_exchange_ptr ma_atomic_exchange_32 +#endif + + +ma_uint32 ma_get_standard_sample_rate_priority_index(ma_uint32 sampleRate) // Lower = higher priority +{ + for (ma_uint32 i = 0; i < ma_countof(g_maStandardSampleRatePriorities); ++i) { + if (g_maStandardSampleRatePriorities[i] == sampleRate) { + return i; + } + } + + return (ma_uint32)-1; +} + +ma_uint64 ma_calculate_frame_count_after_src(ma_uint32 sampleRateOut, ma_uint32 sampleRateIn, ma_uint64 frameCountIn) +{ + double srcRatio = (double)sampleRateOut / sampleRateIn; + double frameCountOutF = frameCountIn * srcRatio; + + ma_uint64 frameCountOut = (ma_uint64)frameCountOutF; + + // If the output frame count is fractional, make sure we add an extra frame to ensure there's enough room for that last sample. + if ((frameCountOutF - frameCountOut) > 0.0) { + frameCountOut += 1; + } + + return frameCountOut; +} + + +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// +// DEVICE I/O +// ========== +// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +#ifndef MA_NO_DEVICE_IO +// Unfortunately using runtime linking for pthreads causes problems. This has occurred for me when testing on FreeBSD. When +// using runtime linking, deadlocks can occur (for me it happens when loading data from fread()). It turns out that doing +// compile-time linking fixes this. I'm not sure why this happens, but the safest way I can think of to fix this is to simply +// disable runtime linking by default. To enable runtime linking, #define this before the implementation of this file. I am +// not officially supporting this, but I'm leaving it here in case it's useful for somebody, somewhere. +//#define MA_USE_RUNTIME_LINKING_FOR_PTHREAD + +// Disable run-time linking on certain backends. +#ifndef MA_NO_RUNTIME_LINKING + #if defined(MA_ANDROID) || defined(MA_EMSCRIPTEN) + #define MA_NO_RUNTIME_LINKING + #endif +#endif + +// Check if we have the necessary development packages for each backend at the top so we can use this to determine whether or not +// certain unused functions and variables can be excluded from the build to avoid warnings. +#ifdef MA_ENABLE_WASAPI + #define MA_HAS_WASAPI // Every compiler should support WASAPI +#endif +#ifdef MA_ENABLE_DSOUND + #define MA_HAS_DSOUND // Every compiler should support DirectSound. +#endif +#ifdef MA_ENABLE_WINMM + #define MA_HAS_WINMM // Every compiler I'm aware of supports WinMM. +#endif +#ifdef MA_ENABLE_ALSA + #define MA_HAS_ALSA + #ifdef MA_NO_RUNTIME_LINKING + #ifdef __has_include + #if !__has_include() + #undef MA_HAS_ALSA + #endif + #endif + #endif +#endif +#ifdef MA_ENABLE_PULSEAUDIO + #define MA_HAS_PULSEAUDIO + #ifdef MA_NO_RUNTIME_LINKING + #ifdef __has_include + #if !__has_include() + #undef MA_HAS_PULSEAUDIO + #endif + #endif + #endif +#endif +#ifdef MA_ENABLE_JACK + #define MA_HAS_JACK + #ifdef MA_NO_RUNTIME_LINKING + #ifdef __has_include + #if !__has_include() + #undef MA_HAS_JACK + #endif + #endif + #endif +#endif +#ifdef MA_ENABLE_COREAUDIO + #define MA_HAS_COREAUDIO +#endif +#ifdef MA_ENABLE_SNDIO + #define MA_HAS_SNDIO +#endif +#ifdef MA_ENABLE_AUDIO4 + #define MA_HAS_AUDIO4 +#endif +#ifdef MA_ENABLE_OSS + #define MA_HAS_OSS +#endif +#ifdef MA_ENABLE_AAUDIO + #define MA_HAS_AAUDIO +#endif +#ifdef MA_ENABLE_OPENSL + #define MA_HAS_OPENSL +#endif +#ifdef MA_ENABLE_WEBAUDIO + #define MA_HAS_WEBAUDIO +#endif +#ifdef MA_ENABLE_NULL + #define MA_HAS_NULL // Everything supports the null backend. +#endif + +const char* ma_get_backend_name(ma_backend backend) +{ + switch (backend) + { + case ma_backend_wasapi: return "WASAPI"; + case ma_backend_dsound: return "DirectSound"; + case ma_backend_winmm: return "WinMM"; + case ma_backend_coreaudio: return "Core Audio"; + case ma_backend_sndio: return "sndio"; + case ma_backend_audio4: return "audio(4)"; + case ma_backend_oss: return "OSS"; + case ma_backend_pulseaudio: return "PulseAudio"; + case ma_backend_alsa: return "ALSA"; + case ma_backend_jack: return "JACK"; + case ma_backend_aaudio: return "AAudio"; + case ma_backend_opensl: return "OpenSL|ES"; + case ma_backend_webaudio: return "Web Audio"; + case ma_backend_null: return "Null"; + default: return "Unknown"; + } +} + + + +#ifdef MA_WIN32 + #define MA_THREADCALL WINAPI + typedef unsigned long ma_thread_result; +#else + #define MA_THREADCALL + typedef void* ma_thread_result; +#endif +typedef ma_thread_result (MA_THREADCALL * ma_thread_entry_proc)(void* pData); + +#ifdef MA_WIN32 +typedef HRESULT (WINAPI * MA_PFN_CoInitializeEx)(LPVOID pvReserved, DWORD dwCoInit); +typedef void (WINAPI * MA_PFN_CoUninitialize)(); +typedef HRESULT (WINAPI * MA_PFN_CoCreateInstance)(REFCLSID rclsid, LPUNKNOWN pUnkOuter, DWORD dwClsContext, REFIID riid, LPVOID *ppv); +typedef void (WINAPI * MA_PFN_CoTaskMemFree)(LPVOID pv); +typedef HRESULT (WINAPI * MA_PFN_PropVariantClear)(PROPVARIANT *pvar); +typedef int (WINAPI * MA_PFN_StringFromGUID2)(const GUID* const rguid, LPOLESTR lpsz, int cchMax); + +typedef HWND (WINAPI * MA_PFN_GetForegroundWindow)(); +typedef HWND (WINAPI * MA_PFN_GetDesktopWindow)(); + +// Microsoft documents these APIs as returning LSTATUS, but the Win32 API shipping with some compilers do not define it. It's just a LONG. +typedef LONG (WINAPI * MA_PFN_RegOpenKeyExA)(HKEY hKey, LPCSTR lpSubKey, DWORD ulOptions, REGSAM samDesired, PHKEY phkResult); +typedef LONG (WINAPI * MA_PFN_RegCloseKey)(HKEY hKey); +typedef LONG (WINAPI * MA_PFN_RegQueryValueExA)(HKEY hKey, LPCSTR lpValueName, LPDWORD lpReserved, LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData); +#endif + + +#define MA_STATE_UNINITIALIZED 0 +#define MA_STATE_STOPPED 1 // The device's default state after initialization. +#define MA_STATE_STARTED 2 // The worker thread is in it's main loop waiting for the driver to request or deliver audio data. +#define MA_STATE_STARTING 3 // Transitioning from a stopped state to started. +#define MA_STATE_STOPPING 4 // Transitioning from a started state to stopped. + +#define MA_DEFAULT_PLAYBACK_DEVICE_NAME "Default Playback Device" +#define MA_DEFAULT_CAPTURE_DEVICE_NAME "Default Capture Device" + + +/////////////////////////////////////////////////////////////////////////////// +// +// Timing +// +/////////////////////////////////////////////////////////////////////////////// +#ifdef MA_WIN32 +LARGE_INTEGER g_ma_TimerFrequency = {{0}}; +void ma_timer_init(ma_timer* pTimer) +{ + if (g_ma_TimerFrequency.QuadPart == 0) { + QueryPerformanceFrequency(&g_ma_TimerFrequency); + } + + LARGE_INTEGER counter; + QueryPerformanceCounter(&counter); + pTimer->counter = counter.QuadPart; +} + +double ma_timer_get_time_in_seconds(ma_timer* pTimer) +{ + LARGE_INTEGER counter; + if (!QueryPerformanceCounter(&counter)) { + return 0; + } + + return (double)(counter.QuadPart - pTimer->counter) / g_ma_TimerFrequency.QuadPart; +} +#elif defined(MA_APPLE) && (__MAC_OS_X_VERSION_MIN_REQUIRED < 101200) +ma_uint64 g_ma_TimerFrequency = 0; +void ma_timer_init(ma_timer* pTimer) +{ + mach_timebase_info_data_t baseTime; + mach_timebase_info(&baseTime); + g_ma_TimerFrequency = (baseTime.denom * 1e9) / baseTime.numer; + + pTimer->counter = mach_absolute_time(); +} + +double ma_timer_get_time_in_seconds(ma_timer* pTimer) +{ + ma_uint64 newTimeCounter = mach_absolute_time(); + ma_uint64 oldTimeCounter = pTimer->counter; + + return (newTimeCounter - oldTimeCounter) / g_ma_TimerFrequency; +} +#elif defined(MA_EMSCRIPTEN) +void ma_timer_init(ma_timer* pTimer) +{ + pTimer->counterD = emscripten_get_now(); +} + +double ma_timer_get_time_in_seconds(ma_timer* pTimer) +{ + return (emscripten_get_now() - pTimer->counterD) / 1000; /* Emscripten is in milliseconds. */ +} +#else +#if defined(CLOCK_MONOTONIC) + #define MA_CLOCK_ID CLOCK_MONOTONIC +#else + #define MA_CLOCK_ID CLOCK_REALTIME +#endif + +void ma_timer_init(ma_timer* pTimer) +{ + struct timespec newTime; + clock_gettime(MA_CLOCK_ID, &newTime); + + pTimer->counter = (newTime.tv_sec * 1000000000) + newTime.tv_nsec; +} + +double ma_timer_get_time_in_seconds(ma_timer* pTimer) +{ + struct timespec newTime; + clock_gettime(MA_CLOCK_ID, &newTime); + + ma_uint64 newTimeCounter = (newTime.tv_sec * 1000000000) + newTime.tv_nsec; + ma_uint64 oldTimeCounter = pTimer->counter; + + return (newTimeCounter - oldTimeCounter) / 1000000000.0; +} +#endif + + +/////////////////////////////////////////////////////////////////////////////// +// +// Dynamic Linking +// +/////////////////////////////////////////////////////////////////////////////// +ma_handle ma_dlopen(const char* filename) +{ +#ifdef _WIN32 +#ifdef MA_WIN32_DESKTOP + return (ma_handle)LoadLibraryA(filename); +#else + // *sigh* It appears there is no ANSI version of LoadPackagedLibrary()... + WCHAR filenameW[4096]; + if (MultiByteToWideChar(CP_UTF8, 0, filename, -1, filenameW, sizeof(filenameW)) == 0) { + return NULL; + } + + return (ma_handle)LoadPackagedLibrary(filenameW, 0); +#endif +#else + return (ma_handle)dlopen(filename, RTLD_NOW); +#endif +} + +void ma_dlclose(ma_handle handle) +{ +#ifdef _WIN32 + FreeLibrary((HMODULE)handle); +#else + dlclose((void*)handle); +#endif +} + +ma_proc ma_dlsym(ma_handle handle, const char* symbol) +{ +#ifdef _WIN32 + return (ma_proc)GetProcAddress((HMODULE)handle, symbol); +#else + return (ma_proc)dlsym((void*)handle, symbol); +#endif +} + + +/////////////////////////////////////////////////////////////////////////////// +// +// Threading +// +/////////////////////////////////////////////////////////////////////////////// +#ifdef MA_WIN32 +int ma_thread_priority_to_win32(ma_thread_priority priority) +{ + switch (priority) { + case ma_thread_priority_idle: return THREAD_PRIORITY_IDLE; + case ma_thread_priority_lowest: return THREAD_PRIORITY_LOWEST; + case ma_thread_priority_low: return THREAD_PRIORITY_BELOW_NORMAL; + case ma_thread_priority_normal: return THREAD_PRIORITY_NORMAL; + case ma_thread_priority_high: return THREAD_PRIORITY_ABOVE_NORMAL; + case ma_thread_priority_highest: return THREAD_PRIORITY_HIGHEST; + case ma_thread_priority_realtime: return THREAD_PRIORITY_TIME_CRITICAL; + default: return ma_thread_priority_normal; + } +} + +ma_result ma_thread_create__win32(ma_context* pContext, ma_thread* pThread, ma_thread_entry_proc entryProc, void* pData) +{ + pThread->win32.hThread = CreateThread(NULL, 0, entryProc, pData, 0, NULL); + if (pThread->win32.hThread == NULL) { + return MA_FAILED_TO_CREATE_THREAD; + } + + SetThreadPriority((HANDLE)pThread->win32.hThread, ma_thread_priority_to_win32(pContext->config.threadPriority)); + + return MA_SUCCESS; +} + +void ma_thread_wait__win32(ma_thread* pThread) +{ + WaitForSingleObject(pThread->win32.hThread, INFINITE); +} + +void ma_sleep__win32(ma_uint32 milliseconds) +{ + Sleep((DWORD)milliseconds); +} + + +ma_result ma_mutex_init__win32(ma_context* pContext, ma_mutex* pMutex) +{ + (void)pContext; + + pMutex->win32.hMutex = CreateEventA(NULL, FALSE, TRUE, NULL); + if (pMutex->win32.hMutex == NULL) { + return MA_FAILED_TO_CREATE_MUTEX; + } + + return MA_SUCCESS; +} + +void ma_mutex_uninit__win32(ma_mutex* pMutex) +{ + CloseHandle(pMutex->win32.hMutex); +} + +void ma_mutex_lock__win32(ma_mutex* pMutex) +{ + WaitForSingleObject(pMutex->win32.hMutex, INFINITE); +} + +void ma_mutex_unlock__win32(ma_mutex* pMutex) +{ + SetEvent(pMutex->win32.hMutex); +} + + +ma_result ma_event_init__win32(ma_context* pContext, ma_event* pEvent) +{ + (void)pContext; + + pEvent->win32.hEvent = CreateEventW(NULL, FALSE, FALSE, NULL); + if (pEvent->win32.hEvent == NULL) { + return MA_FAILED_TO_CREATE_EVENT; + } + + return MA_SUCCESS; +} + +void ma_event_uninit__win32(ma_event* pEvent) +{ + CloseHandle(pEvent->win32.hEvent); +} + +ma_bool32 ma_event_wait__win32(ma_event* pEvent) +{ + return WaitForSingleObject(pEvent->win32.hEvent, INFINITE) == WAIT_OBJECT_0; +} + +ma_bool32 ma_event_signal__win32(ma_event* pEvent) +{ + return SetEvent(pEvent->win32.hEvent); +} +#endif + + +#ifdef MA_POSIX +#include + +typedef int (* ma_pthread_create_proc)(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg); +typedef int (* ma_pthread_join_proc)(pthread_t thread, void **retval); +typedef int (* ma_pthread_mutex_init_proc)(pthread_mutex_t *__mutex, const pthread_mutexattr_t *__mutexattr); +typedef int (* ma_pthread_mutex_destroy_proc)(pthread_mutex_t *__mutex); +typedef int (* ma_pthread_mutex_lock_proc)(pthread_mutex_t *__mutex); +typedef int (* ma_pthread_mutex_unlock_proc)(pthread_mutex_t *__mutex); +typedef int (* ma_pthread_cond_init_proc)(pthread_cond_t *__restrict __cond, const pthread_condattr_t *__restrict __cond_attr); +typedef int (* ma_pthread_cond_destroy_proc)(pthread_cond_t *__cond); +typedef int (* ma_pthread_cond_signal_proc)(pthread_cond_t *__cond); +typedef int (* ma_pthread_cond_wait_proc)(pthread_cond_t *__restrict __cond, pthread_mutex_t *__restrict __mutex); +typedef int (* ma_pthread_attr_init_proc)(pthread_attr_t *attr); +typedef int (* ma_pthread_attr_destroy_proc)(pthread_attr_t *attr); +typedef int (* ma_pthread_attr_setschedpolicy_proc)(pthread_attr_t *attr, int policy); +typedef int (* ma_pthread_attr_getschedparam_proc)(const pthread_attr_t *attr, struct sched_param *param); +typedef int (* ma_pthread_attr_setschedparam_proc)(pthread_attr_t *attr, const struct sched_param *param); + +ma_bool32 ma_thread_create__posix(ma_context* pContext, ma_thread* pThread, ma_thread_entry_proc entryProc, void* pData) +{ + pthread_attr_t* pAttr = NULL; + +#if !defined(__EMSCRIPTEN__) + // Try setting the thread priority. It's not critical if anything fails here. + pthread_attr_t attr; + if (((ma_pthread_attr_init_proc)pContext->posix.pthread_attr_init)(&attr) == 0) { + int scheduler = -1; + if (pContext->config.threadPriority == ma_thread_priority_idle) { +#ifdef SCHED_IDLE + if (((ma_pthread_attr_setschedpolicy_proc)pContext->posix.pthread_attr_setschedpolicy)(&attr, SCHED_IDLE) == 0) { + scheduler = SCHED_IDLE; + } +#endif + } else if (pContext->config.threadPriority == ma_thread_priority_realtime) { +#ifdef SCHED_FIFO + if (((ma_pthread_attr_setschedpolicy_proc)pContext->posix.pthread_attr_setschedpolicy)(&attr, SCHED_FIFO) == 0) { + scheduler = SCHED_FIFO; + } +#endif +#ifdef MA_LINUX + } else { + scheduler = sched_getscheduler(0); +#endif + } + + if (scheduler != -1) { + int priorityMin = sched_get_priority_min(scheduler); + int priorityMax = sched_get_priority_max(scheduler); + int priorityStep = (priorityMax - priorityMin) / 7; // 7 = number of priorities supported by miniaudio. + + struct sched_param sched; + if (((ma_pthread_attr_getschedparam_proc)pContext->posix.pthread_attr_getschedparam)(&attr, &sched) == 0) { + if (pContext->config.threadPriority == ma_thread_priority_idle) { + sched.sched_priority = priorityMin; + } else if (pContext->config.threadPriority == ma_thread_priority_realtime) { + sched.sched_priority = priorityMax; + } else { + sched.sched_priority += ((int)pContext->config.threadPriority + 5) * priorityStep; // +5 because the lowest priority is -5. + if (sched.sched_priority < priorityMin) { + sched.sched_priority = priorityMin; + } + if (sched.sched_priority > priorityMax) { + sched.sched_priority = priorityMax; + } + } + + if (((ma_pthread_attr_setschedparam_proc)pContext->posix.pthread_attr_setschedparam)(&attr, &sched) == 0) { + pAttr = &attr; + } + } + } + + ((ma_pthread_attr_destroy_proc)pContext->posix.pthread_attr_destroy)(&attr); + } +#endif + + int result = ((ma_pthread_create_proc)pContext->posix.pthread_create)(&pThread->posix.thread, pAttr, entryProc, pData); + if (result != 0) { + return MA_FAILED_TO_CREATE_THREAD; + } + + return MA_SUCCESS; +} + +void ma_thread_wait__posix(ma_thread* pThread) +{ + ((ma_pthread_join_proc)pThread->pContext->posix.pthread_join)(pThread->posix.thread, NULL); +} + +void ma_sleep__posix(ma_uint32 milliseconds) +{ +#ifdef MA_EMSCRIPTEN + (void)milliseconds; + ma_assert(MA_FALSE); /* The Emscripten build should never sleep. */ +#else + usleep(milliseconds * 1000); /* <-- usleep is in microseconds. */ +#endif +} + + +ma_result ma_mutex_init__posix(ma_context* pContext, ma_mutex* pMutex) +{ + int result = ((ma_pthread_mutex_init_proc)pContext->posix.pthread_mutex_init)(&pMutex->posix.mutex, NULL); + if (result != 0) { + return MA_FAILED_TO_CREATE_MUTEX; + } + + return MA_SUCCESS; +} + +void ma_mutex_uninit__posix(ma_mutex* pMutex) +{ + ((ma_pthread_mutex_destroy_proc)pMutex->pContext->posix.pthread_mutex_destroy)(&pMutex->posix.mutex); +} + +void ma_mutex_lock__posix(ma_mutex* pMutex) +{ + ((ma_pthread_mutex_lock_proc)pMutex->pContext->posix.pthread_mutex_lock)(&pMutex->posix.mutex); +} + +void ma_mutex_unlock__posix(ma_mutex* pMutex) +{ + ((ma_pthread_mutex_unlock_proc)pMutex->pContext->posix.pthread_mutex_unlock)(&pMutex->posix.mutex); +} + + +ma_result ma_event_init__posix(ma_context* pContext, ma_event* pEvent) +{ + if (((ma_pthread_mutex_init_proc)pContext->posix.pthread_mutex_init)(&pEvent->posix.mutex, NULL) != 0) { + return MA_FAILED_TO_CREATE_MUTEX; + } + + if (((ma_pthread_cond_init_proc)pContext->posix.pthread_cond_init)(&pEvent->posix.condition, NULL) != 0) { + return MA_FAILED_TO_CREATE_EVENT; + } + + pEvent->posix.value = 0; + return MA_SUCCESS; +} + +void ma_event_uninit__posix(ma_event* pEvent) +{ + ((ma_pthread_cond_destroy_proc)pEvent->pContext->posix.pthread_cond_destroy)(&pEvent->posix.condition); + ((ma_pthread_mutex_destroy_proc)pEvent->pContext->posix.pthread_mutex_destroy)(&pEvent->posix.mutex); +} + +ma_bool32 ma_event_wait__posix(ma_event* pEvent) +{ + ((ma_pthread_mutex_lock_proc)pEvent->pContext->posix.pthread_mutex_lock)(&pEvent->posix.mutex); + { + while (pEvent->posix.value == 0) { + ((ma_pthread_cond_wait_proc)pEvent->pContext->posix.pthread_cond_wait)(&pEvent->posix.condition, &pEvent->posix.mutex); + } + pEvent->posix.value = 0; // Auto-reset. + } + ((ma_pthread_mutex_unlock_proc)pEvent->pContext->posix.pthread_mutex_unlock)(&pEvent->posix.mutex); + + return MA_TRUE; +} + +ma_bool32 ma_event_signal__posix(ma_event* pEvent) +{ + ((ma_pthread_mutex_lock_proc)pEvent->pContext->posix.pthread_mutex_lock)(&pEvent->posix.mutex); + { + pEvent->posix.value = 1; + ((ma_pthread_cond_signal_proc)pEvent->pContext->posix.pthread_cond_signal)(&pEvent->posix.condition); + } + ((ma_pthread_mutex_unlock_proc)pEvent->pContext->posix.pthread_mutex_unlock)(&pEvent->posix.mutex); + + return MA_TRUE; +} +#endif + +ma_result ma_thread_create(ma_context* pContext, ma_thread* pThread, ma_thread_entry_proc entryProc, void* pData) +{ + if (pContext == NULL || pThread == NULL || entryProc == NULL) return MA_FALSE; + + pThread->pContext = pContext; + +#ifdef MA_WIN32 + return ma_thread_create__win32(pContext, pThread, entryProc, pData); +#endif +#ifdef MA_POSIX + return ma_thread_create__posix(pContext, pThread, entryProc, pData); +#endif +} + +void ma_thread_wait(ma_thread* pThread) +{ + if (pThread == NULL) return; + +#ifdef MA_WIN32 + ma_thread_wait__win32(pThread); +#endif +#ifdef MA_POSIX + ma_thread_wait__posix(pThread); +#endif +} + +void ma_sleep(ma_uint32 milliseconds) +{ +#ifdef MA_WIN32 + ma_sleep__win32(milliseconds); +#endif +#ifdef MA_POSIX + ma_sleep__posix(milliseconds); +#endif +} + + +ma_result ma_mutex_init(ma_context* pContext, ma_mutex* pMutex) +{ + if (pContext == NULL || pMutex == NULL) { + return MA_INVALID_ARGS; + } + + pMutex->pContext = pContext; + +#ifdef MA_WIN32 + return ma_mutex_init__win32(pContext, pMutex); +#endif +#ifdef MA_POSIX + return ma_mutex_init__posix(pContext, pMutex); +#endif +} + +void ma_mutex_uninit(ma_mutex* pMutex) +{ + if (pMutex == NULL || pMutex->pContext == NULL) return; + +#ifdef MA_WIN32 + ma_mutex_uninit__win32(pMutex); +#endif +#ifdef MA_POSIX + ma_mutex_uninit__posix(pMutex); +#endif +} + +void ma_mutex_lock(ma_mutex* pMutex) +{ + if (pMutex == NULL || pMutex->pContext == NULL) return; + +#ifdef MA_WIN32 + ma_mutex_lock__win32(pMutex); +#endif +#ifdef MA_POSIX + ma_mutex_lock__posix(pMutex); +#endif +} + +void ma_mutex_unlock(ma_mutex* pMutex) +{ + if (pMutex == NULL || pMutex->pContext == NULL) return; + +#ifdef MA_WIN32 + ma_mutex_unlock__win32(pMutex); +#endif +#ifdef MA_POSIX + ma_mutex_unlock__posix(pMutex); +#endif +} + + +ma_result ma_event_init(ma_context* pContext, ma_event* pEvent) +{ + if (pContext == NULL || pEvent == NULL) return MA_FALSE; + + pEvent->pContext = pContext; + +#ifdef MA_WIN32 + return ma_event_init__win32(pContext, pEvent); +#endif +#ifdef MA_POSIX + return ma_event_init__posix(pContext, pEvent); +#endif +} + +void ma_event_uninit(ma_event* pEvent) +{ + if (pEvent == NULL || pEvent->pContext == NULL) return; + +#ifdef MA_WIN32 + ma_event_uninit__win32(pEvent); +#endif +#ifdef MA_POSIX + ma_event_uninit__posix(pEvent); +#endif +} + +ma_bool32 ma_event_wait(ma_event* pEvent) +{ + if (pEvent == NULL || pEvent->pContext == NULL) return MA_FALSE; + +#ifdef MA_WIN32 + return ma_event_wait__win32(pEvent); +#endif +#ifdef MA_POSIX + return ma_event_wait__posix(pEvent); +#endif +} + +ma_bool32 ma_event_signal(ma_event* pEvent) +{ + if (pEvent == NULL || pEvent->pContext == NULL) return MA_FALSE; + +#ifdef MA_WIN32 + return ma_event_signal__win32(pEvent); +#endif +#ifdef MA_POSIX + return ma_event_signal__posix(pEvent); +#endif +} + + +ma_uint32 ma_get_best_sample_rate_within_range(ma_uint32 sampleRateMin, ma_uint32 sampleRateMax) +{ + // Normalize the range in case we were given something stupid. + if (sampleRateMin < MA_MIN_SAMPLE_RATE) { + sampleRateMin = MA_MIN_SAMPLE_RATE; + } + if (sampleRateMax > MA_MAX_SAMPLE_RATE) { + sampleRateMax = MA_MAX_SAMPLE_RATE; + } + if (sampleRateMin > sampleRateMax) { + sampleRateMin = sampleRateMax; + } + + if (sampleRateMin == sampleRateMax) { + return sampleRateMax; + } else { + for (size_t iStandardRate = 0; iStandardRate < ma_countof(g_maStandardSampleRatePriorities); ++iStandardRate) { + ma_uint32 standardRate = g_maStandardSampleRatePriorities[iStandardRate]; + if (standardRate >= sampleRateMin && standardRate <= sampleRateMax) { + return standardRate; + } + } + } + + // Should never get here. + ma_assert(MA_FALSE); + return 0; +} + +ma_uint32 ma_get_closest_standard_sample_rate(ma_uint32 sampleRateIn) +{ + ma_uint32 closestRate = 0; + ma_uint32 closestDiff = 0xFFFFFFFF; + + for (size_t iStandardRate = 0; iStandardRate < ma_countof(g_maStandardSampleRatePriorities); ++iStandardRate) { + ma_uint32 standardRate = g_maStandardSampleRatePriorities[iStandardRate]; + + ma_uint32 diff; + if (sampleRateIn > standardRate) { + diff = sampleRateIn - standardRate; + } else { + diff = standardRate - sampleRateIn; + } + + if (diff == 0) { + return standardRate; // The input sample rate is a standard rate. + } + + if (closestDiff > diff) { + closestDiff = diff; + closestRate = standardRate; + } + } + + return closestRate; +} + + +ma_uint32 ma_scale_buffer_size(ma_uint32 baseBufferSize, float scale) +{ + return ma_max(1, (ma_uint32)(baseBufferSize*scale)); +} + +ma_uint32 ma_calculate_buffer_size_in_milliseconds_from_frames(ma_uint32 bufferSizeInFrames, ma_uint32 sampleRate) +{ + return bufferSizeInFrames / (sampleRate/1000); +} + +ma_uint32 ma_calculate_buffer_size_in_frames_from_milliseconds(ma_uint32 bufferSizeInMilliseconds, ma_uint32 sampleRate) +{ + return bufferSizeInMilliseconds * (sampleRate/1000); +} + +ma_uint32 ma_get_default_buffer_size_in_milliseconds(ma_performance_profile performanceProfile) +{ + if (performanceProfile == ma_performance_profile_low_latency) { + return MA_BASE_BUFFER_SIZE_IN_MILLISECONDS_LOW_LATENCY; + } else { + return MA_BASE_BUFFER_SIZE_IN_MILLISECONDS_CONSERVATIVE; + } +} + +ma_uint32 ma_get_default_buffer_size_in_frames(ma_performance_profile performanceProfile, ma_uint32 sampleRate) +{ + ma_uint32 bufferSizeInMilliseconds = ma_get_default_buffer_size_in_milliseconds(performanceProfile); + if (bufferSizeInMilliseconds == 0) { + bufferSizeInMilliseconds = 1; + } + + ma_uint32 sampleRateMS = (sampleRate/1000); + if (sampleRateMS == 0) { + sampleRateMS = 1; + } + + return bufferSizeInMilliseconds * sampleRateMS; +} + +ma_uint32 ma_get_fragment_size_in_bytes(ma_uint32 bufferSizeInFrames, ma_uint32 periods, ma_format format, ma_uint32 channels) +{ + ma_uint32 fragmentSizeInFrames = bufferSizeInFrames / periods; + return fragmentSizeInFrames * ma_get_bytes_per_frame(format, channels); +} + +void ma_zero_pcm_frames(void* p, ma_uint32 frameCount, ma_format format, ma_uint32 channels) +{ + ma_zero_memory(p, frameCount * ma_get_bytes_per_frame(format, channels)); +} + + +const char* ma_log_level_to_string(ma_uint32 logLevel) +{ + switch (logLevel) + { + case MA_LOG_LEVEL_VERBOSE: return ""; + case MA_LOG_LEVEL_INFO: return "INFO"; + case MA_LOG_LEVEL_WARNING: return "WARNING"; + case MA_LOG_LEVEL_ERROR: return "ERROR"; + default: return "ERROR"; + } +} + +// Posts a log message. +void ma_log(ma_context* pContext, ma_device* pDevice, ma_uint32 logLevel, const char* message) +{ + if (pContext == NULL) return; + +#if defined(MA_LOG_LEVEL) + if (logLevel <= MA_LOG_LEVEL) { + #if defined(MA_DEBUG_OUTPUT) + if (logLevel <= MA_LOG_LEVEL) { + printf("%s: %s\n", ma_log_level_to_string(logLevel), message); + } + #endif + + ma_log_proc onLog = pContext->config.logCallback; + if (onLog) { + onLog(pContext, pDevice, logLevel, message); + } + } +#endif +} + +// Posts an error. Throw a breakpoint in here if you're needing to debug. The return value is always "resultCode". +ma_result ma_context_post_error(ma_context* pContext, ma_device* pDevice, ma_uint32 logLevel, const char* message, ma_result resultCode) +{ + // Derive the context from the device if necessary. + if (pContext == NULL) { + if (pDevice != NULL) { + pContext = pDevice->pContext; + } + } + + ma_log(pContext, pDevice, logLevel, message); + return resultCode; +} + +ma_result ma_post_error(ma_device* pDevice, ma_uint32 logLevel, const char* message, ma_result resultCode) +{ + return ma_context_post_error(NULL, pDevice, logLevel, message, resultCode); +} + + + +// The callback for reading from the client -> DSP -> device. +ma_uint32 ma_device__on_read_from_client(ma_pcm_converter* pDSP, void* pFramesOut, ma_uint32 frameCount, void* pUserData) +{ + (void)pDSP; + + ma_device* pDevice = (ma_device*)pUserData; + ma_assert(pDevice != NULL); + + ma_zero_pcm_frames(pFramesOut, frameCount, pDevice->playback.format, pDevice->playback.channels); + + ma_device_callback_proc onData = pDevice->onData; + if (onData) { + onData(pDevice, pFramesOut, NULL, frameCount); + return frameCount; + } + + return 0; +} + +/* The PCM converter callback for reading from a buffer. */ +ma_uint32 ma_device__pcm_converter__on_read_from_buffer_capture(ma_pcm_converter* pConverter, void* pFramesOut, ma_uint32 frameCount, void* pUserData) +{ + ma_device* pDevice = (ma_device*)pUserData; + ma_assert(pDevice != NULL); + + if (pDevice->capture._dspFrameCount == 0) { + return 0; // Nothing left. + } + + ma_uint32 framesToRead = frameCount; + if (framesToRead > pDevice->capture._dspFrameCount) { + framesToRead = pDevice->capture._dspFrameCount; + } + + ma_uint32 bytesToRead = framesToRead * ma_get_bytes_per_frame(pConverter->formatConverterIn.config.formatIn, pConverter->channelRouter.config.channelsIn); + ma_copy_memory(pFramesOut, pDevice->capture._dspFrames, bytesToRead); + pDevice->capture._dspFrameCount -= framesToRead; + pDevice->capture._dspFrames += bytesToRead; + + return framesToRead; +} + +ma_uint32 ma_device__pcm_converter__on_read_from_buffer_playback(ma_pcm_converter* pConverter, void* pFramesOut, ma_uint32 frameCount, void* pUserData) +{ + ma_device* pDevice = (ma_device*)pUserData; + ma_assert(pDevice != NULL); + + if (pDevice->playback._dspFrameCount == 0) { + return 0; // Nothing left. + } + + ma_uint32 framesToRead = frameCount; + if (framesToRead > pDevice->playback._dspFrameCount) { + framesToRead = pDevice->playback._dspFrameCount; + } + + ma_uint32 bytesToRead = framesToRead * ma_get_bytes_per_frame(pConverter->formatConverterIn.config.formatIn, pConverter->channelRouter.config.channelsIn); + ma_copy_memory(pFramesOut, pDevice->playback._dspFrames, bytesToRead); + pDevice->playback._dspFrameCount -= framesToRead; + pDevice->playback._dspFrames += bytesToRead; + + return framesToRead; +} + + + +// A helper function for reading sample data from the client. +static MA_INLINE void ma_device__read_frames_from_client(ma_device* pDevice, ma_uint32 frameCount, void* pSamples) +{ + ma_assert(pDevice != NULL); + ma_assert(frameCount > 0); + ma_assert(pSamples != NULL); + + ma_pcm_converter_read(&pDevice->playback.converter, pSamples, frameCount); +} + +// A helper for sending sample data to the client. +static MA_INLINE void ma_device__send_frames_to_client(ma_device* pDevice, ma_uint32 frameCount, const void* pSamples) +{ + ma_assert(pDevice != NULL); + ma_assert(frameCount > 0); + ma_assert(pSamples != NULL); + + ma_device_callback_proc onData = pDevice->onData; + if (onData) { + pDevice->capture._dspFrameCount = frameCount; + pDevice->capture._dspFrames = (const ma_uint8*)pSamples; + + ma_uint8 chunkBuffer[4096]; + ma_uint32 chunkFrameCount = sizeof(chunkBuffer) / ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels); + + for (;;) { + ma_uint32 framesJustRead = (ma_uint32)ma_pcm_converter_read(&pDevice->capture.converter, chunkBuffer, chunkFrameCount); + if (framesJustRead == 0) { + break; + } + + onData(pDevice, NULL, chunkBuffer, framesJustRead); + + if (framesJustRead < chunkFrameCount) { + break; + } + } + } +} + +static MA_INLINE ma_result ma_device__handle_duplex_callback_capture(ma_device* pDevice, ma_uint32 frameCount, const void* pFramesInInternalFormat, ma_pcm_rb* pRB) +{ + ma_assert(pDevice != NULL); + ma_assert(frameCount > 0); + ma_assert(pFramesInInternalFormat != NULL); + ma_assert(pRB != NULL); + + ma_result result; + + pDevice->capture._dspFrameCount = (ma_uint32)frameCount; + pDevice->capture._dspFrames = (const ma_uint8*)pFramesInInternalFormat; + + /* Write to the ring buffer. The ring buffer is in the external format. */ + for (;;) { + ma_uint32 framesProcessed; + ma_uint32 framesToProcess = 256; + void* pFramesInExternalFormat; + result = ma_pcm_rb_acquire_write(pRB, &framesToProcess, &pFramesInExternalFormat); + if (result != MA_SUCCESS) { + ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "Failed to acquire capture PCM frames from ring buffer.", result); + break; + } + + if (framesToProcess == 0) { + if (ma_pcm_rb_pointer_disance(pRB) == (ma_int32)ma_pcm_rb_get_subbuffer_size(pRB)) { + break; /* Overrun. Not enough room in the ring buffer for input frame. Excess frames are dropped. */ + } + } + + /* Convert. */ + framesProcessed = (ma_uint32)ma_pcm_converter_read(&pDevice->capture.converter, pFramesInExternalFormat, framesToProcess); + + result = ma_pcm_rb_commit_write(pRB, framesProcessed, pFramesInExternalFormat); + if (result != MA_SUCCESS) { + ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "Failed to commit capture PCM frames to ring buffer.", result); + break; + } + + if (framesProcessed < framesToProcess) { + break; /* Done. */ + } + } + + return MA_SUCCESS; +} + +static MA_INLINE ma_result ma_device__handle_duplex_callback_playback(ma_device* pDevice, ma_uint32 frameCount, void* pFramesInInternalFormat, ma_pcm_rb* pRB) +{ + ma_assert(pDevice != NULL); + ma_assert(frameCount > 0); + ma_assert(pFramesInInternalFormat != NULL); + ma_assert(pRB != NULL); + + /* + Sitting in the ring buffer should be captured data from the capture callback in external format. If there's not enough data in there for + the whole frameCount frames we just use silence instead for the input data. + */ + ma_result result; + ma_uint8 playbackFramesInExternalFormat[4096]; + ma_uint8 silentInputFrames[4096]; + ma_zero_memory(silentInputFrames, sizeof(silentInputFrames)); + + /* We need to calculate how many output frames are required to be read from the client to completely fill frameCount internal frames. */ + ma_uint32 totalFramesToReadFromClient = (ma_uint32)ma_calculate_frame_count_after_src(pDevice->sampleRate, pDevice->playback.internalSampleRate, frameCount); // ma_pcm_converter_get_required_input_frame_count(&pDevice->playback.converter, (ma_uint32)frameCount); + ma_uint32 totalFramesReadFromClient = 0; + while (totalFramesReadFromClient < totalFramesToReadFromClient && ma_device_is_started(pDevice)) { + ma_uint32 framesRemainingFromClient = (totalFramesToReadFromClient - totalFramesReadFromClient); + ma_uint32 framesToProcessFromClient = sizeof(playbackFramesInExternalFormat) / ma_get_bytes_per_frame(pDevice->playback.format, pDevice->playback.channels); + if (framesToProcessFromClient > framesRemainingFromClient) { + framesToProcessFromClient = framesRemainingFromClient; + } + + /* We need to grab captured samples before firing the callback. If there's not enough input samples we just pass silence. */ + ma_uint32 inputFrameCount = framesToProcessFromClient; + void* pInputFrames; + result = ma_pcm_rb_acquire_read(pRB, &inputFrameCount, &pInputFrames); + if (result == MA_SUCCESS) { + if (inputFrameCount > 0) { + /* Use actual input frames. */ + pDevice->onData(pDevice, playbackFramesInExternalFormat, pInputFrames, inputFrameCount); + } else { + if (ma_pcm_rb_pointer_disance(pRB) == 0) { + break; /* Underrun. */ + } + } + + /* We're done with the captured samples. */ + result = ma_pcm_rb_commit_read(pRB, inputFrameCount, pInputFrames); + if (result != MA_SUCCESS) { + break; /* Don't know what to do here... Just abandon ship. */ + } + } else { + /* Use silent input frames. */ + inputFrameCount = ma_min( + sizeof(playbackFramesInExternalFormat) / ma_get_bytes_per_frame(pDevice->playback.format, pDevice->playback.channels), + sizeof(silentInputFrames) / ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels) + ); + + pDevice->onData(pDevice, playbackFramesInExternalFormat, silentInputFrames, inputFrameCount); + } + + /* We have samples in external format so now we need to convert to internal format and output to the device. */ + pDevice->playback._dspFrameCount = inputFrameCount; + pDevice->playback._dspFrames = (const ma_uint8*)playbackFramesInExternalFormat; + ma_pcm_converter_read(&pDevice->playback.converter, pFramesInInternalFormat, inputFrameCount); + + totalFramesReadFromClient += inputFrameCount; + pFramesInInternalFormat = ma_offset_ptr(pFramesInInternalFormat, inputFrameCount * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels)); + } + + return MA_SUCCESS; +} + +// A helper for changing the state of the device. +static MA_INLINE void ma_device__set_state(ma_device* pDevice, ma_uint32 newState) +{ + ma_atomic_exchange_32(&pDevice->state, newState); +} + +// A helper for getting the state of the device. +static MA_INLINE ma_uint32 ma_device__get_state(ma_device* pDevice) +{ + return pDevice->state; +} + +/* A helper for determining whether or not the device is running in async mode. */ +static MA_INLINE ma_bool32 ma_device__is_async(ma_device* pDevice) +{ + return pDevice->onData != NULL; +} + + +#ifdef MA_WIN32 + GUID MA_GUID_KSDATAFORMAT_SUBTYPE_PCM = {0x00000001, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}}; + GUID MA_GUID_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT = {0x00000003, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}}; + //GUID MA_GUID_KSDATAFORMAT_SUBTYPE_ALAW = {0x00000006, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}}; + //GUID MA_GUID_KSDATAFORMAT_SUBTYPE_MULAW = {0x00000007, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}}; +#endif + + +ma_bool32 ma_context__device_id_equal(ma_context* pContext, const ma_device_id* pID0, const ma_device_id* pID1) +{ + ma_assert(pContext != NULL); + + if (pID0 == pID1) return MA_TRUE; + + if ((pID0 == NULL && pID1 != NULL) || + (pID0 != NULL && pID1 == NULL)) { + return MA_FALSE; + } + + if (pContext->onDeviceIDEqual) { + return pContext->onDeviceIDEqual(pContext, pID0, pID1); + } + + return MA_FALSE; +} + + +typedef struct +{ + ma_device_type deviceType; + const ma_device_id* pDeviceID; + char* pName; + size_t nameBufferSize; + ma_bool32 foundDevice; +} ma_context__try_get_device_name_by_id__enum_callback_data; + +ma_bool32 ma_context__try_get_device_name_by_id__enum_callback(ma_context* pContext, ma_device_type deviceType, const ma_device_info* pDeviceInfo, void* pUserData) +{ + ma_context__try_get_device_name_by_id__enum_callback_data* pData = (ma_context__try_get_device_name_by_id__enum_callback_data*)pUserData; + ma_assert(pData != NULL); + + if (pData->deviceType == deviceType) { + if (pContext->onDeviceIDEqual(pContext, pData->pDeviceID, &pDeviceInfo->id)) { + ma_strncpy_s(pData->pName, pData->nameBufferSize, pDeviceInfo->name, (size_t)-1); + pData->foundDevice = MA_TRUE; + } + } + + return !pData->foundDevice; +} + +// Generic function for retrieving the name of a device by it's ID. +// +// This function simply enumerates every device and then retrieves the name of the first device that has the same ID. +ma_result ma_context__try_get_device_name_by_id(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, char* pName, size_t nameBufferSize) +{ + ma_assert(pContext != NULL); + ma_assert(pName != NULL); + + if (pDeviceID == NULL) { + return MA_NO_DEVICE; + } + + ma_context__try_get_device_name_by_id__enum_callback_data data; + data.deviceType = deviceType; + data.pDeviceID = pDeviceID; + data.pName = pName; + data.nameBufferSize = nameBufferSize; + data.foundDevice = MA_FALSE; + ma_result result = ma_context_enumerate_devices(pContext, ma_context__try_get_device_name_by_id__enum_callback, &data); + if (result != MA_SUCCESS) { + return result; + } + + if (!data.foundDevice) { + return MA_NO_DEVICE; + } else { + return MA_SUCCESS; + } +} + + +ma_uint32 ma_get_format_priority_index(ma_format format) // Lower = better. +{ + for (ma_uint32 i = 0; i < ma_countof(g_maFormatPriorities); ++i) { + if (g_maFormatPriorities[i] == format) { + return i; + } + } + + // Getting here means the format could not be found or is equal to ma_format_unknown. + return (ma_uint32)-1; +} + +void ma_device__post_init_setup(ma_device* pDevice, ma_device_type deviceType); + +/////////////////////////////////////////////////////////////////////////////// +// +// Null Backend +// +/////////////////////////////////////////////////////////////////////////////// +#ifdef MA_HAS_NULL + +#define MA_DEVICE_OP_NONE__NULL 0 +#define MA_DEVICE_OP_START__NULL 1 +#define MA_DEVICE_OP_SUSPEND__NULL 2 +#define MA_DEVICE_OP_KILL__NULL 3 + +ma_thread_result MA_THREADCALL ma_device_thread__null(void* pData) +{ + ma_device* pDevice = (ma_device*)pData; + ma_assert(pDevice != NULL); + + for (;;) { /* Keep the thread alive until the device is uninitialized. */ + /* Wait for an operation to be requested. */ + ma_event_wait(&pDevice->null_device.operationEvent); + + /* At this point an event should have been triggered. */ + + /* Starting the device needs to put the thread into a loop. */ + if (pDevice->null_device.operation == MA_DEVICE_OP_START__NULL) { + ma_atomic_exchange_32(&pDevice->null_device.operation, MA_DEVICE_OP_NONE__NULL); + + /* Reset the timer just in case. */ + ma_timer_init(&pDevice->null_device.timer); + + /* Keep looping until an operation has been requested. */ + while (pDevice->null_device.operation != MA_DEVICE_OP_NONE__NULL && pDevice->null_device.operation != MA_DEVICE_OP_START__NULL) { + ma_sleep(10); /* Don't hog the CPU. */ + } + + /* Getting here means a suspend or kill operation has been requested. */ + ma_atomic_exchange_32(&pDevice->null_device.operationResult, MA_SUCCESS); + ma_event_signal(&pDevice->null_device.operationCompletionEvent); + continue; + } + + /* Suspending the device means we need to stop the timer and just continue the loop. */ + if (pDevice->null_device.operation == MA_DEVICE_OP_SUSPEND__NULL) { + ma_atomic_exchange_32(&pDevice->null_device.operation, MA_DEVICE_OP_NONE__NULL); + + /* We need to add the current run time to the prior run time, then reset the timer. */ + pDevice->null_device.priorRunTime += ma_timer_get_time_in_seconds(&pDevice->null_device.timer); + ma_timer_init(&pDevice->null_device.timer); + + /* We're done. */ + ma_atomic_exchange_32(&pDevice->null_device.operationResult, MA_SUCCESS); + ma_event_signal(&pDevice->null_device.operationCompletionEvent); + continue; + } + + /* Killing the device means we need to get out of this loop so that this thread can terminate. */ + if (pDevice->null_device.operation == MA_DEVICE_OP_KILL__NULL) { + ma_atomic_exchange_32(&pDevice->null_device.operation, MA_DEVICE_OP_NONE__NULL); + ma_atomic_exchange_32(&pDevice->null_device.operationResult, MA_SUCCESS); + ma_event_signal(&pDevice->null_device.operationCompletionEvent); + break; + } + + /* Getting a signal on a "none" operation probably means an error. Return invalid operation. */ + if (pDevice->null_device.operation == MA_DEVICE_OP_NONE__NULL) { + ma_assert(MA_FALSE); /* <-- Trigger this in debug mode to ensure developers are aware they're doing something wrong (or there's a bug in a miniaudio). */ + ma_atomic_exchange_32(&pDevice->null_device.operationResult, MA_INVALID_OPERATION); + ma_event_signal(&pDevice->null_device.operationCompletionEvent); + continue; /* Continue the loop. Don't terminate. */ + } + } + + return (ma_thread_result)0; +} + +ma_result ma_device_do_operation__null(ma_device* pDevice, ma_uint32 operation) +{ + ma_atomic_exchange_32(&pDevice->null_device.operation, operation); + if (!ma_event_signal(&pDevice->null_device.operationEvent)) { + return MA_ERROR; + } + + if (!ma_event_wait(&pDevice->null_device.operationCompletionEvent)) { + return MA_ERROR; + } + + return pDevice->null_device.operationResult; +} + +ma_uint64 ma_device_get_total_run_time_in_frames__null(ma_device* pDevice) +{ + ma_uint32 internalSampleRate; + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + internalSampleRate = pDevice->capture.internalSampleRate; + } else { + internalSampleRate = pDevice->playback.internalSampleRate; + } + + + return (ma_uint64)((pDevice->null_device.priorRunTime + ma_timer_get_time_in_seconds(&pDevice->null_device.timer)) * internalSampleRate); +} + +ma_bool32 ma_context_is_device_id_equal__null(ma_context* pContext, const ma_device_id* pID0, const ma_device_id* pID1) +{ + ma_assert(pContext != NULL); + ma_assert(pID0 != NULL); + ma_assert(pID1 != NULL); + (void)pContext; + + return pID0->nullbackend == pID1->nullbackend; +} + +ma_result ma_context_enumerate_devices__null(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData) +{ + ma_assert(pContext != NULL); + ma_assert(callback != NULL); + + ma_bool32 cbResult = MA_TRUE; + + // Playback. + if (cbResult) { + ma_device_info deviceInfo; + ma_zero_object(&deviceInfo); + ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), "NULL Playback Device", (size_t)-1); + cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData); + } + + // Capture. + if (cbResult) { + ma_device_info deviceInfo; + ma_zero_object(&deviceInfo); + ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), "NULL Capture Device", (size_t)-1); + cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData); + } + + return MA_SUCCESS; +} + +ma_result ma_context_get_device_info__null(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_share_mode shareMode, ma_device_info* pDeviceInfo) +{ + ma_assert(pContext != NULL); + + (void)pContext; + (void)shareMode; + + if (pDeviceID != NULL && pDeviceID->nullbackend != 0) { + return MA_NO_DEVICE; // Don't know the device. + } + + // Name / Description + if (deviceType == ma_device_type_playback) { + ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), "NULL Playback Device", (size_t)-1); + } else { + ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), "NULL Capture Device", (size_t)-1); + } + + // Support everything on the null backend. + pDeviceInfo->formatCount = ma_format_count - 1; // Minus one because we don't want to include ma_format_unknown. + for (ma_uint32 iFormat = 0; iFormat < pDeviceInfo->formatCount; ++iFormat) { + pDeviceInfo->formats[iFormat] = (ma_format)(iFormat + 1); // +1 to skip over ma_format_unknown. + } + + pDeviceInfo->minChannels = 1; + pDeviceInfo->maxChannels = MA_MAX_CHANNELS; + pDeviceInfo->minSampleRate = MA_SAMPLE_RATE_8000; + pDeviceInfo->maxSampleRate = MA_SAMPLE_RATE_384000; + + return MA_SUCCESS; +} + + +void ma_device_uninit__null(ma_device* pDevice) +{ + ma_assert(pDevice != NULL); + + /* Keep it clean and wait for the device thread to finish before returning. */ + ma_device_do_operation__null(pDevice, MA_DEVICE_OP_KILL__NULL); + + /* At this point the loop in the device thread is as good as terminated so we can uninitialize our events. */ + ma_event_uninit(&pDevice->null_device.operationCompletionEvent); + ma_event_uninit(&pDevice->null_device.operationEvent); +} + +ma_result ma_device_init__null(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice) +{ + (void)pContext; + (void)pConfig; + + ma_result result; + + ma_assert(pDevice != NULL); + + ma_zero_object(&pDevice->null_device); + + ma_uint32 bufferSizeInFrames = pConfig->bufferSizeInFrames; + if (bufferSizeInFrames == 0) { + bufferSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(pConfig->bufferSizeInMilliseconds, pConfig->sampleRate); + } + + if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) { + ma_strncpy_s(pDevice->capture.name, sizeof(pDevice->capture.name), "NULL Capture Device", (size_t)-1); + pDevice->capture.internalFormat = pConfig->capture.format; + pDevice->capture.internalChannels = pConfig->capture.channels; + ma_channel_map_copy(pDevice->capture.internalChannelMap, pConfig->capture.channelMap, pConfig->capture.channels); + pDevice->capture.internalBufferSizeInFrames = bufferSizeInFrames; + pDevice->capture.internalPeriods = pConfig->periods; + } + if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) { + ma_strncpy_s(pDevice->playback.name, sizeof(pDevice->playback.name), "NULL Playback Device", (size_t)-1); + pDevice->playback.internalFormat = pConfig->playback.format; + pDevice->playback.internalChannels = pConfig->playback.channels; + ma_channel_map_copy(pDevice->playback.internalChannelMap, pConfig->playback.channelMap, pConfig->playback.channels); + pDevice->playback.internalBufferSizeInFrames = bufferSizeInFrames; + pDevice->playback.internalPeriods = pConfig->periods; + } + + /* + In order to get timing right, we need to create a thread that does nothing but keeps track of the timer. This timer is started when the + first period is "written" to it, and then stopped in ma_device_stop__null(). + */ + result = ma_event_init(pContext, &pDevice->null_device.operationEvent); + if (result != MA_SUCCESS) { + return result; + } + + result = ma_event_init(pContext, &pDevice->null_device.operationCompletionEvent); + if (result != MA_SUCCESS) { + return result; + } + + result = ma_thread_create(pContext, &pDevice->thread, ma_device_thread__null, pDevice); + if (result != MA_SUCCESS) { + return result; + } + + return MA_SUCCESS; +} + +ma_result ma_device_start__null(ma_device* pDevice) +{ + ma_assert(pDevice != NULL); + + ma_device_do_operation__null(pDevice, MA_DEVICE_OP_START__NULL); + + ma_atomic_exchange_32(&pDevice->null_device.isStarted, MA_TRUE); + return MA_SUCCESS; +} + +ma_result ma_device_stop__null(ma_device* pDevice) +{ + ma_assert(pDevice != NULL); + + ma_device_do_operation__null(pDevice, MA_DEVICE_OP_SUSPEND__NULL); + + ma_atomic_exchange_32(&pDevice->null_device.isStarted, MA_FALSE); + return MA_SUCCESS; +} + +ma_result ma_device_write__null(ma_device* pDevice, const void* pPCMFrames, ma_uint32 frameCount) +{ + ma_result result = MA_SUCCESS; + ma_uint32 totalPCMFramesProcessed; + ma_bool32 wasStartedOnEntry; + + wasStartedOnEntry = pDevice->null_device.isStarted; + + /* Keep going until everything has been read. */ + totalPCMFramesProcessed = 0; + while (totalPCMFramesProcessed < frameCount) { + /* If there are any frames remaining in the current period, consume those first. */ + if (pDevice->null_device.currentPeriodFramesRemainingPlayback > 0) { + ma_uint32 framesRemaining = (frameCount - totalPCMFramesProcessed); + ma_uint32 framesToProcess = pDevice->null_device.currentPeriodFramesRemainingPlayback; + if (framesToProcess > framesRemaining) { + framesToProcess = framesRemaining; + } + + /* We don't actually do anything with pPCMFrames, so just mark it as unused to prevent a warning. */ + (void)pPCMFrames; + + pDevice->null_device.currentPeriodFramesRemainingPlayback -= framesToProcess; + totalPCMFramesProcessed += framesToProcess; + } + + /* If we've consumed the current period we'll need to mark it as such an ensure the device is started if it's not already. */ + if (pDevice->null_device.currentPeriodFramesRemainingPlayback == 0) { + pDevice->null_device.currentPeriodFramesRemainingPlayback = 0; + + if (!pDevice->null_device.isStarted && !wasStartedOnEntry) { + result = ma_device_start__null(pDevice); + if (result != MA_SUCCESS) { + break; + } + } + } + + /* If we've consumed the whole buffer we can return now. */ + ma_assert(totalPCMFramesProcessed <= frameCount); + if (totalPCMFramesProcessed == frameCount) { + break; + } + + /* Getting here means we've still got more frames to consume, we but need to wait for it to become available. */ + ma_uint64 targetFrame = pDevice->null_device.lastProcessedFramePlayback; + for (;;) { + /* Stop waiting if the device has been stopped. */ + if (!pDevice->null_device.isStarted) { + break; + } + + ma_uint64 currentFrame = ma_device_get_total_run_time_in_frames__null(pDevice); + if (currentFrame >= targetFrame) { + break; + } + + /* Getting here means we haven't yet reached the target sample, so continue waiting. */ + ma_sleep(10); + } + + pDevice->null_device.lastProcessedFramePlayback += pDevice->playback.internalBufferSizeInFrames / pDevice->playback.internalPeriods; + pDevice->null_device.currentPeriodFramesRemainingPlayback = pDevice->playback.internalBufferSizeInFrames / pDevice->playback.internalPeriods; + } + + return result; +} + +ma_result ma_device_read__null(ma_device* pDevice, void* pPCMFrames, ma_uint32 frameCount) +{ + ma_result result = MA_SUCCESS; + ma_uint32 totalPCMFramesProcessed; + + /* The device needs to be started immediately. */ + if (!pDevice->null_device.isStarted) { + result = ma_device_start__null(pDevice); + if (result != MA_SUCCESS) { + return result; + } + } + + /* Keep going until everything has been read. */ + totalPCMFramesProcessed = 0; + while (totalPCMFramesProcessed < frameCount) { + /* If there are any frames remaining in the current period, consume those first. */ + if (pDevice->null_device.currentPeriodFramesRemainingCapture > 0) { + ma_uint32 bpf = ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels); + ma_uint32 framesRemaining = (frameCount - totalPCMFramesProcessed); + ma_uint32 framesToProcess = pDevice->null_device.currentPeriodFramesRemainingCapture; + if (framesToProcess > framesRemaining) { + framesToProcess = framesRemaining; + } + + /* We need to ensured the output buffer is zeroed. */ + ma_zero_memory(ma_offset_ptr(pPCMFrames, totalPCMFramesProcessed*bpf), framesToProcess*bpf); + + pDevice->null_device.currentPeriodFramesRemainingCapture -= framesToProcess; + totalPCMFramesProcessed += framesToProcess; + } + + /* If we've consumed the current period we'll need to mark it as such an ensure the device is started if it's not already. */ + if (pDevice->null_device.currentPeriodFramesRemainingCapture == 0) { + pDevice->null_device.currentPeriodFramesRemainingCapture = 0; + } + + /* If we've consumed the whole buffer we can return now. */ + ma_assert(totalPCMFramesProcessed <= frameCount); + if (totalPCMFramesProcessed == frameCount) { + break; + } + + /* Getting here means we've still got more frames to consume, we but need to wait for it to become available. */ + ma_uint64 targetFrame = pDevice->null_device.lastProcessedFrameCapture + (pDevice->capture.internalBufferSizeInFrames / pDevice->capture.internalPeriods); + for (;;) { + /* Stop waiting if the device has been stopped. */ + if (!pDevice->null_device.isStarted) { + break; + } + + ma_uint64 currentFrame = ma_device_get_total_run_time_in_frames__null(pDevice); + if (currentFrame >= targetFrame) { + break; + } + + /* Getting here means we haven't yet reached the target sample, so continue waiting. */ + ma_sleep(10); + } + + pDevice->null_device.lastProcessedFrameCapture += pDevice->capture.internalBufferSizeInFrames / pDevice->capture.internalPeriods; + pDevice->null_device.currentPeriodFramesRemainingCapture = pDevice->capture.internalBufferSizeInFrames / pDevice->capture.internalPeriods; + } + + return result; +} + +ma_result ma_context_uninit__null(ma_context* pContext) +{ + ma_assert(pContext != NULL); + ma_assert(pContext->backend == ma_backend_null); + + (void)pContext; + return MA_SUCCESS; +} + +ma_result ma_context_init__null(ma_context* pContext) +{ + ma_assert(pContext != NULL); + + pContext->onUninit = ma_context_uninit__null; + pContext->onDeviceIDEqual = ma_context_is_device_id_equal__null; + pContext->onEnumDevices = ma_context_enumerate_devices__null; + pContext->onGetDeviceInfo = ma_context_get_device_info__null; + pContext->onDeviceInit = ma_device_init__null; + pContext->onDeviceUninit = ma_device_uninit__null; + pContext->onDeviceStart = ma_device_start__null; + pContext->onDeviceStop = ma_device_stop__null; + pContext->onDeviceWrite = ma_device_write__null; + pContext->onDeviceRead = ma_device_read__null; + + /* The null backend always works. */ + return MA_SUCCESS; +} +#endif + + +/////////////////////////////////////////////////////////////////////////////// +// +// WIN32 COMMON +// +/////////////////////////////////////////////////////////////////////////////// +#if defined(MA_WIN32) +#if defined(MA_WIN32_DESKTOP) + #define ma_CoInitializeEx(pContext, pvReserved, dwCoInit) ((MA_PFN_CoInitializeEx)pContext->win32.CoInitializeEx)(pvReserved, dwCoInit) + #define ma_CoUninitialize(pContext) ((MA_PFN_CoUninitialize)pContext->win32.CoUninitialize)() + #define ma_CoCreateInstance(pContext, rclsid, pUnkOuter, dwClsContext, riid, ppv) ((MA_PFN_CoCreateInstance)pContext->win32.CoCreateInstance)(rclsid, pUnkOuter, dwClsContext, riid, ppv) + #define ma_CoTaskMemFree(pContext, pv) ((MA_PFN_CoTaskMemFree)pContext->win32.CoTaskMemFree)(pv) + #define ma_PropVariantClear(pContext, pvar) ((MA_PFN_PropVariantClear)pContext->win32.PropVariantClear)(pvar) +#else + #define ma_CoInitializeEx(pContext, pvReserved, dwCoInit) CoInitializeEx(pvReserved, dwCoInit) + #define ma_CoUninitialize(pContext) CoUninitialize() + #define ma_CoCreateInstance(pContext, rclsid, pUnkOuter, dwClsContext, riid, ppv) CoCreateInstance(rclsid, pUnkOuter, dwClsContext, riid, ppv) + #define ma_CoTaskMemFree(pContext, pv) CoTaskMemFree(pv) + #define ma_PropVariantClear(pContext, pvar) PropVariantClear(pvar) +#endif + +#if !defined(MAXULONG_PTR) +typedef size_t DWORD_PTR; +#endif + +#if !defined(WAVE_FORMAT_44M08) +#define WAVE_FORMAT_44M08 0x00000100 +#define WAVE_FORMAT_44S08 0x00000200 +#define WAVE_FORMAT_44M16 0x00000400 +#define WAVE_FORMAT_44S16 0x00000800 +#define WAVE_FORMAT_48M08 0x00001000 +#define WAVE_FORMAT_48S08 0x00002000 +#define WAVE_FORMAT_48M16 0x00004000 +#define WAVE_FORMAT_48S16 0x00008000 +#define WAVE_FORMAT_96M08 0x00010000 +#define WAVE_FORMAT_96S08 0x00020000 +#define WAVE_FORMAT_96M16 0x00040000 +#define WAVE_FORMAT_96S16 0x00080000 +#endif + +#ifndef SPEAKER_FRONT_LEFT +#define SPEAKER_FRONT_LEFT 0x1 +#define SPEAKER_FRONT_RIGHT 0x2 +#define SPEAKER_FRONT_CENTER 0x4 +#define SPEAKER_LOW_FREQUENCY 0x8 +#define SPEAKER_BACK_LEFT 0x10 +#define SPEAKER_BACK_RIGHT 0x20 +#define SPEAKER_FRONT_LEFT_OF_CENTER 0x40 +#define SPEAKER_FRONT_RIGHT_OF_CENTER 0x80 +#define SPEAKER_BACK_CENTER 0x100 +#define SPEAKER_SIDE_LEFT 0x200 +#define SPEAKER_SIDE_RIGHT 0x400 +#define SPEAKER_TOP_CENTER 0x800 +#define SPEAKER_TOP_FRONT_LEFT 0x1000 +#define SPEAKER_TOP_FRONT_CENTER 0x2000 +#define SPEAKER_TOP_FRONT_RIGHT 0x4000 +#define SPEAKER_TOP_BACK_LEFT 0x8000 +#define SPEAKER_TOP_BACK_CENTER 0x10000 +#define SPEAKER_TOP_BACK_RIGHT 0x20000 +#endif + +// The SDK that comes with old versions of MSVC (VC6, for example) does not appear to define WAVEFORMATEXTENSIBLE. We +// define our own implementation in this case. +#if (defined(_MSC_VER) && !defined(_WAVEFORMATEXTENSIBLE_)) || defined(__DMC__) +typedef struct +{ + WAVEFORMATEX Format; + union + { + WORD wValidBitsPerSample; + WORD wSamplesPerBlock; + WORD wReserved; + } Samples; + DWORD dwChannelMask; + GUID SubFormat; +} WAVEFORMATEXTENSIBLE; +#endif + +#ifndef WAVE_FORMAT_EXTENSIBLE +#define WAVE_FORMAT_EXTENSIBLE 0xFFFE +#endif + +#ifndef WAVE_FORMAT_IEEE_FLOAT +#define WAVE_FORMAT_IEEE_FLOAT 0x0003 +#endif + +GUID MA_GUID_NULL = {0x00000000, 0x0000, 0x0000, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}; + +// Converts an individual Win32-style channel identifier (SPEAKER_FRONT_LEFT, etc.) to miniaudio. +ma_uint8 ma_channel_id_to_ma__win32(DWORD id) +{ + switch (id) + { + case SPEAKER_FRONT_LEFT: return MA_CHANNEL_FRONT_LEFT; + case SPEAKER_FRONT_RIGHT: return MA_CHANNEL_FRONT_RIGHT; + case SPEAKER_FRONT_CENTER: return MA_CHANNEL_FRONT_CENTER; + case SPEAKER_LOW_FREQUENCY: return MA_CHANNEL_LFE; + case SPEAKER_BACK_LEFT: return MA_CHANNEL_BACK_LEFT; + case SPEAKER_BACK_RIGHT: return MA_CHANNEL_BACK_RIGHT; + case SPEAKER_FRONT_LEFT_OF_CENTER: return MA_CHANNEL_FRONT_LEFT_CENTER; + case SPEAKER_FRONT_RIGHT_OF_CENTER: return MA_CHANNEL_FRONT_RIGHT_CENTER; + case SPEAKER_BACK_CENTER: return MA_CHANNEL_BACK_CENTER; + case SPEAKER_SIDE_LEFT: return MA_CHANNEL_SIDE_LEFT; + case SPEAKER_SIDE_RIGHT: return MA_CHANNEL_SIDE_RIGHT; + case SPEAKER_TOP_CENTER: return MA_CHANNEL_TOP_CENTER; + case SPEAKER_TOP_FRONT_LEFT: return MA_CHANNEL_TOP_FRONT_LEFT; + case SPEAKER_TOP_FRONT_CENTER: return MA_CHANNEL_TOP_FRONT_CENTER; + case SPEAKER_TOP_FRONT_RIGHT: return MA_CHANNEL_TOP_FRONT_RIGHT; + case SPEAKER_TOP_BACK_LEFT: return MA_CHANNEL_TOP_BACK_LEFT; + case SPEAKER_TOP_BACK_CENTER: return MA_CHANNEL_TOP_BACK_CENTER; + case SPEAKER_TOP_BACK_RIGHT: return MA_CHANNEL_TOP_BACK_RIGHT; + default: return 0; + } +} + +// Converts an individual miniaudio channel identifier (MA_CHANNEL_FRONT_LEFT, etc.) to Win32-style. +DWORD ma_channel_id_to_win32(DWORD id) +{ + switch (id) + { + case MA_CHANNEL_MONO: return SPEAKER_FRONT_CENTER; + case MA_CHANNEL_FRONT_LEFT: return SPEAKER_FRONT_LEFT; + case MA_CHANNEL_FRONT_RIGHT: return SPEAKER_FRONT_RIGHT; + case MA_CHANNEL_FRONT_CENTER: return SPEAKER_FRONT_CENTER; + case MA_CHANNEL_LFE: return SPEAKER_LOW_FREQUENCY; + case MA_CHANNEL_BACK_LEFT: return SPEAKER_BACK_LEFT; + case MA_CHANNEL_BACK_RIGHT: return SPEAKER_BACK_RIGHT; + case MA_CHANNEL_FRONT_LEFT_CENTER: return SPEAKER_FRONT_LEFT_OF_CENTER; + case MA_CHANNEL_FRONT_RIGHT_CENTER: return SPEAKER_FRONT_RIGHT_OF_CENTER; + case MA_CHANNEL_BACK_CENTER: return SPEAKER_BACK_CENTER; + case MA_CHANNEL_SIDE_LEFT: return SPEAKER_SIDE_LEFT; + case MA_CHANNEL_SIDE_RIGHT: return SPEAKER_SIDE_RIGHT; + case MA_CHANNEL_TOP_CENTER: return SPEAKER_TOP_CENTER; + case MA_CHANNEL_TOP_FRONT_LEFT: return SPEAKER_TOP_FRONT_LEFT; + case MA_CHANNEL_TOP_FRONT_CENTER: return SPEAKER_TOP_FRONT_CENTER; + case MA_CHANNEL_TOP_FRONT_RIGHT: return SPEAKER_TOP_FRONT_RIGHT; + case MA_CHANNEL_TOP_BACK_LEFT: return SPEAKER_TOP_BACK_LEFT; + case MA_CHANNEL_TOP_BACK_CENTER: return SPEAKER_TOP_BACK_CENTER; + case MA_CHANNEL_TOP_BACK_RIGHT: return SPEAKER_TOP_BACK_RIGHT; + default: return 0; + } +} + +// Converts a channel mapping to a Win32-style channel mask. +DWORD ma_channel_map_to_channel_mask__win32(const ma_channel channelMap[MA_MAX_CHANNELS], ma_uint32 channels) +{ + DWORD dwChannelMask = 0; + for (ma_uint32 iChannel = 0; iChannel < channels; ++iChannel) { + dwChannelMask |= ma_channel_id_to_win32(channelMap[iChannel]); + } + + return dwChannelMask; +} + +// Converts a Win32-style channel mask to a miniaudio channel map. +void ma_channel_mask_to_channel_map__win32(DWORD dwChannelMask, ma_uint32 channels, ma_channel channelMap[MA_MAX_CHANNELS]) +{ + if (channels == 1 && dwChannelMask == 0) { + channelMap[0] = MA_CHANNEL_MONO; + } else if (channels == 2 && dwChannelMask == 0) { + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_RIGHT; + } else { + if (channels == 1 && (dwChannelMask & SPEAKER_FRONT_CENTER) != 0) { + channelMap[0] = MA_CHANNEL_MONO; + } else { + // Just iterate over each bit. + ma_uint32 iChannel = 0; + for (ma_uint32 iBit = 0; iBit < 32; ++iBit) { + DWORD bitValue = (dwChannelMask & (1UL << iBit)); + if (bitValue != 0) { + // The bit is set. + channelMap[iChannel] = ma_channel_id_to_ma__win32(bitValue); + iChannel += 1; + } + } + } + } +} + +#ifdef __cplusplus +ma_bool32 ma_is_guid_equal(const void* a, const void* b) +{ + return IsEqualGUID(*(const GUID*)a, *(const GUID*)b); +} +#else +#define ma_is_guid_equal(a, b) IsEqualGUID((const GUID*)a, (const GUID*)b) +#endif + +ma_format ma_format_from_WAVEFORMATEX(const WAVEFORMATEX* pWF) +{ + ma_assert(pWF != NULL); + + if (pWF->wFormatTag == WAVE_FORMAT_EXTENSIBLE) { + const WAVEFORMATEXTENSIBLE* pWFEX = (const WAVEFORMATEXTENSIBLE*)pWF; + if (ma_is_guid_equal(&pWFEX->SubFormat, &MA_GUID_KSDATAFORMAT_SUBTYPE_PCM)) { + if (pWFEX->Samples.wValidBitsPerSample == 32) { + return ma_format_s32; + } + if (pWFEX->Samples.wValidBitsPerSample == 24) { + if (pWFEX->Format.wBitsPerSample == 32) { + //return ma_format_s24_32; + } + if (pWFEX->Format.wBitsPerSample == 24) { + return ma_format_s24; + } + } + if (pWFEX->Samples.wValidBitsPerSample == 16) { + return ma_format_s16; + } + if (pWFEX->Samples.wValidBitsPerSample == 8) { + return ma_format_u8; + } + } + if (ma_is_guid_equal(&pWFEX->SubFormat, &MA_GUID_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)) { + if (pWFEX->Samples.wValidBitsPerSample == 32) { + return ma_format_f32; + } + //if (pWFEX->Samples.wValidBitsPerSample == 64) { + // return ma_format_f64; + //} + } + } else { + if (pWF->wFormatTag == WAVE_FORMAT_PCM) { + if (pWF->wBitsPerSample == 32) { + return ma_format_s32; + } + if (pWF->wBitsPerSample == 24) { + return ma_format_s24; + } + if (pWF->wBitsPerSample == 16) { + return ma_format_s16; + } + if (pWF->wBitsPerSample == 8) { + return ma_format_u8; + } + } + if (pWF->wFormatTag == WAVE_FORMAT_IEEE_FLOAT) { + if (pWF->wBitsPerSample == 32) { + return ma_format_f32; + } + if (pWF->wBitsPerSample == 64) { + //return ma_format_f64; + } + } + } + + return ma_format_unknown; +} +#endif + + +/////////////////////////////////////////////////////////////////////////////// +// +// WASAPI Backend +// +/////////////////////////////////////////////////////////////////////////////// +#ifdef MA_HAS_WASAPI +//#if defined(_MSC_VER) +// #pragma warning(push) +// #pragma warning(disable:4091) // 'typedef ': ignored on left of '' when no variable is declared +//#endif +//#include +//#include +//#if defined(_MSC_VER) +// #pragma warning(pop) +//#endif + + +// Some compilers don't define VerifyVersionInfoW. Need to write this ourselves. +#if defined(__DMC__) +#define _WIN32_WINNT_VISTA 0x0600 +#define VER_MINORVERSION 0x01 +#define VER_MAJORVERSION 0x02 +#define VER_SERVICEPACKMAJOR 0x20 +#define VER_GREATER_EQUAL 0x03 + +typedef struct { + DWORD dwOSVersionInfoSize; + DWORD dwMajorVersion; + DWORD dwMinorVersion; + DWORD dwBuildNumber; + DWORD dwPlatformId; + WCHAR szCSDVersion[128]; + WORD wServicePackMajor; + WORD wServicePackMinor; + WORD wSuiteMask; + BYTE wProductType; + BYTE wReserved; +} ma_OSVERSIONINFOEXW; + +BOOL WINAPI VerifyVersionInfoW(ma_OSVERSIONINFOEXW* lpVersionInfo, DWORD dwTypeMask, DWORDLONG dwlConditionMask); +ULONGLONG WINAPI VerSetConditionMask(ULONGLONG dwlConditionMask, DWORD dwTypeBitMask, BYTE dwConditionMask); +#else +typedef OSVERSIONINFOEXW ma_OSVERSIONINFOEXW; +#endif + + +#ifndef PROPERTYKEY_DEFINED +#define PROPERTYKEY_DEFINED +typedef struct +{ + GUID fmtid; + DWORD pid; +} PROPERTYKEY; +#endif + +// Some compilers don't define PropVariantInit(). We just do this ourselves since it's just a memset(). +static MA_INLINE void ma_PropVariantInit(PROPVARIANT* pProp) +{ + ma_zero_object(pProp); +} + + +const PROPERTYKEY MA_PKEY_Device_FriendlyName = {{0xA45C254E, 0xDF1C, 0x4EFD, {0x80, 0x20, 0x67, 0xD1, 0x46, 0xA8, 0x50, 0xE0}}, 14}; +const PROPERTYKEY MA_PKEY_AudioEngine_DeviceFormat = {{0xF19F064D, 0x82C, 0x4E27, {0xBC, 0x73, 0x68, 0x82, 0xA1, 0xBB, 0x8E, 0x4C}}, 0}; + +const IID MA_IID_IUnknown = {0x00000000, 0x0000, 0x0000, {0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}}; // 00000000-0000-0000-C000-000000000046 +const IID MA_IID_IAgileObject = {0x94EA2B94, 0xE9CC, 0x49E0, {0xC0, 0xFF, 0xEE, 0x64, 0xCA, 0x8F, 0x5B, 0x90}}; // 94EA2B94-E9CC-49E0-C0FF-EE64CA8F5B90 + +const IID MA_IID_IAudioClient = {0x1CB9AD4C, 0xDBFA, 0x4C32, {0xB1, 0x78, 0xC2, 0xF5, 0x68, 0xA7, 0x03, 0xB2}}; // 1CB9AD4C-DBFA-4C32-B178-C2F568A703B2 = __uuidof(IAudioClient) +const IID MA_IID_IAudioClient2 = {0x726778CD, 0xF60A, 0x4EDA, {0x82, 0xDE, 0xE4, 0x76, 0x10, 0xCD, 0x78, 0xAA}}; // 726778CD-F60A-4EDA-82DE-E47610CD78AA = __uuidof(IAudioClient2) +const IID MA_IID_IAudioClient3 = {0x7ED4EE07, 0x8E67, 0x4CD4, {0x8C, 0x1A, 0x2B, 0x7A, 0x59, 0x87, 0xAD, 0x42}}; // 7ED4EE07-8E67-4CD4-8C1A-2B7A5987AD42 = __uuidof(IAudioClient3) +const IID MA_IID_IAudioRenderClient = {0xF294ACFC, 0x3146, 0x4483, {0xA7, 0xBF, 0xAD, 0xDC, 0xA7, 0xC2, 0x60, 0xE2}}; // F294ACFC-3146-4483-A7BF-ADDCA7C260E2 = __uuidof(IAudioRenderClient) +const IID MA_IID_IAudioCaptureClient = {0xC8ADBD64, 0xE71E, 0x48A0, {0xA4, 0xDE, 0x18, 0x5C, 0x39, 0x5C, 0xD3, 0x17}}; // C8ADBD64-E71E-48A0-A4DE-185C395CD317 = __uuidof(IAudioCaptureClient) +const IID MA_IID_IMMNotificationClient = {0x7991EEC9, 0x7E89, 0x4D85, {0x83, 0x90, 0x6C, 0x70, 0x3C, 0xEC, 0x60, 0xC0}}; // 7991EEC9-7E89-4D85-8390-6C703CEC60C0 = __uuidof(IMMNotificationClient) +#ifndef MA_WIN32_DESKTOP +const IID MA_IID_DEVINTERFACE_AUDIO_RENDER = {0xE6327CAD, 0xDCEC, 0x4949, {0xAE, 0x8A, 0x99, 0x1E, 0x97, 0x6A, 0x79, 0xD2}}; // E6327CAD-DCEC-4949-AE8A-991E976A79D2 +const IID MA_IID_DEVINTERFACE_AUDIO_CAPTURE = {0x2EEF81BE, 0x33FA, 0x4800, {0x96, 0x70, 0x1C, 0xD4, 0x74, 0x97, 0x2C, 0x3F}}; // 2EEF81BE-33FA-4800-9670-1CD474972C3F +const IID MA_IID_IActivateAudioInterfaceCompletionHandler = {0x41D949AB, 0x9862, 0x444A, {0x80, 0xF6, 0xC2, 0x61, 0x33, 0x4D, 0xA5, 0xEB}}; // 41D949AB-9862-444A-80F6-C261334DA5EB +#endif + +const IID MA_CLSID_MMDeviceEnumerator_Instance = {0xBCDE0395, 0xE52F, 0x467C, {0x8E, 0x3D, 0xC4, 0x57, 0x92, 0x91, 0x69, 0x2E}}; // BCDE0395-E52F-467C-8E3D-C4579291692E = __uuidof(MMDeviceEnumerator) +const IID MA_IID_IMMDeviceEnumerator_Instance = {0xA95664D2, 0x9614, 0x4F35, {0xA7, 0x46, 0xDE, 0x8D, 0xB6, 0x36, 0x17, 0xE6}}; // A95664D2-9614-4F35-A746-DE8DB63617E6 = __uuidof(IMMDeviceEnumerator) +#ifdef __cplusplus +#define MA_CLSID_MMDeviceEnumerator MA_CLSID_MMDeviceEnumerator_Instance +#define MA_IID_IMMDeviceEnumerator MA_IID_IMMDeviceEnumerator_Instance +#else +#define MA_CLSID_MMDeviceEnumerator &MA_CLSID_MMDeviceEnumerator_Instance +#define MA_IID_IMMDeviceEnumerator &MA_IID_IMMDeviceEnumerator_Instance +#endif + +typedef struct ma_IUnknown ma_IUnknown; +#ifdef MA_WIN32_DESKTOP +#define MA_MM_DEVICE_STATE_ACTIVE 1 +#define MA_MM_DEVICE_STATE_DISABLED 2 +#define MA_MM_DEVICE_STATE_NOTPRESENT 4 +#define MA_MM_DEVICE_STATE_UNPLUGGED 8 + +typedef struct ma_IMMDeviceEnumerator ma_IMMDeviceEnumerator; +typedef struct ma_IMMDeviceCollection ma_IMMDeviceCollection; +typedef struct ma_IMMDevice ma_IMMDevice; +#else +typedef struct ma_IActivateAudioInterfaceCompletionHandler ma_IActivateAudioInterfaceCompletionHandler; +typedef struct ma_IActivateAudioInterfaceAsyncOperation ma_IActivateAudioInterfaceAsyncOperation; +#endif +typedef struct ma_IPropertyStore ma_IPropertyStore; +typedef struct ma_IAudioClient ma_IAudioClient; +typedef struct ma_IAudioClient2 ma_IAudioClient2; +typedef struct ma_IAudioClient3 ma_IAudioClient3; +typedef struct ma_IAudioRenderClient ma_IAudioRenderClient; +typedef struct ma_IAudioCaptureClient ma_IAudioCaptureClient; + +typedef ma_int64 MA_REFERENCE_TIME; + +#define MA_AUDCLNT_STREAMFLAGS_CROSSPROCESS 0x00010000 +#define MA_AUDCLNT_STREAMFLAGS_LOOPBACK 0x00020000 +#define MA_AUDCLNT_STREAMFLAGS_EVENTCALLBACK 0x00040000 +#define MA_AUDCLNT_STREAMFLAGS_NOPERSIST 0x00080000 +#define MA_AUDCLNT_STREAMFLAGS_RATEADJUST 0x00100000 +#define MA_AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY 0x08000000 +#define MA_AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM 0x80000000 +#define MA_AUDCLNT_SESSIONFLAGS_EXPIREWHENUNOWNED 0x10000000 +#define MA_AUDCLNT_SESSIONFLAGS_DISPLAY_HIDE 0x20000000 +#define MA_AUDCLNT_SESSIONFLAGS_DISPLAY_HIDEWHENEXPIRED 0x40000000 + +// We only care about a few error codes. +#define MA_AUDCLNT_E_INVALID_DEVICE_PERIOD (-2004287456) +#define MA_AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED (-2004287463) +#define MA_AUDCLNT_S_BUFFER_EMPTY (143196161) +#define MA_AUDCLNT_E_DEVICE_IN_USE (-2004287478) + +typedef enum +{ + ma_eRender = 0, + ma_eCapture = 1, + ma_eAll = 2 +} ma_EDataFlow; + +typedef enum +{ + ma_eConsole = 0, + ma_eMultimedia = 1, + ma_eCommunications = 2 +} ma_ERole; + +typedef enum +{ + MA_AUDCLNT_SHAREMODE_SHARED, + MA_AUDCLNT_SHAREMODE_EXCLUSIVE +} MA_AUDCLNT_SHAREMODE; + +typedef enum +{ + MA_AudioCategory_Other = 0, // <-- miniaudio is only caring about Other. +} MA_AUDIO_STREAM_CATEGORY; + +typedef struct +{ + UINT32 cbSize; + BOOL bIsOffload; + MA_AUDIO_STREAM_CATEGORY eCategory; +} ma_AudioClientProperties; + +// IUnknown +typedef struct +{ + // IUnknown + HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IUnknown* pThis, const IID* const riid, void** ppObject); + ULONG (STDMETHODCALLTYPE * AddRef) (ma_IUnknown* pThis); + ULONG (STDMETHODCALLTYPE * Release) (ma_IUnknown* pThis); +} ma_IUnknownVtbl; +struct ma_IUnknown +{ + ma_IUnknownVtbl* lpVtbl; +}; +HRESULT ma_IUnknown_QueryInterface(ma_IUnknown* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } +ULONG ma_IUnknown_AddRef(ma_IUnknown* pThis) { return pThis->lpVtbl->AddRef(pThis); } +ULONG ma_IUnknown_Release(ma_IUnknown* pThis) { return pThis->lpVtbl->Release(pThis); } + +#ifdef MA_WIN32_DESKTOP + // IMMNotificationClient + typedef struct + { + // IUnknown + HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IMMNotificationClient* pThis, const IID* const riid, void** ppObject); + ULONG (STDMETHODCALLTYPE * AddRef) (ma_IMMNotificationClient* pThis); + ULONG (STDMETHODCALLTYPE * Release) (ma_IMMNotificationClient* pThis); + + // IMMNotificationClient + HRESULT (STDMETHODCALLTYPE * OnDeviceStateChanged) (ma_IMMNotificationClient* pThis, LPCWSTR pDeviceID, DWORD dwNewState); + HRESULT (STDMETHODCALLTYPE * OnDeviceAdded) (ma_IMMNotificationClient* pThis, LPCWSTR pDeviceID); + HRESULT (STDMETHODCALLTYPE * OnDeviceRemoved) (ma_IMMNotificationClient* pThis, LPCWSTR pDeviceID); + HRESULT (STDMETHODCALLTYPE * OnDefaultDeviceChanged)(ma_IMMNotificationClient* pThis, ma_EDataFlow dataFlow, ma_ERole role, LPCWSTR pDefaultDeviceID); + HRESULT (STDMETHODCALLTYPE * OnPropertyValueChanged)(ma_IMMNotificationClient* pThis, LPCWSTR pDeviceID, const PROPERTYKEY key); + } ma_IMMNotificationClientVtbl; + + // IMMDeviceEnumerator + typedef struct + { + // IUnknown + HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IMMDeviceEnumerator* pThis, const IID* const riid, void** ppObject); + ULONG (STDMETHODCALLTYPE * AddRef) (ma_IMMDeviceEnumerator* pThis); + ULONG (STDMETHODCALLTYPE * Release) (ma_IMMDeviceEnumerator* pThis); + + // IMMDeviceEnumerator + HRESULT (STDMETHODCALLTYPE * EnumAudioEndpoints) (ma_IMMDeviceEnumerator* pThis, ma_EDataFlow dataFlow, DWORD dwStateMask, ma_IMMDeviceCollection** ppDevices); + HRESULT (STDMETHODCALLTYPE * GetDefaultAudioEndpoint) (ma_IMMDeviceEnumerator* pThis, ma_EDataFlow dataFlow, ma_ERole role, ma_IMMDevice** ppEndpoint); + HRESULT (STDMETHODCALLTYPE * GetDevice) (ma_IMMDeviceEnumerator* pThis, LPCWSTR pID, ma_IMMDevice** ppDevice); + HRESULT (STDMETHODCALLTYPE * RegisterEndpointNotificationCallback) (ma_IMMDeviceEnumerator* pThis, ma_IMMNotificationClient* pClient); + HRESULT (STDMETHODCALLTYPE * UnregisterEndpointNotificationCallback)(ma_IMMDeviceEnumerator* pThis, ma_IMMNotificationClient* pClient); + } ma_IMMDeviceEnumeratorVtbl; + struct ma_IMMDeviceEnumerator + { + ma_IMMDeviceEnumeratorVtbl* lpVtbl; + }; + HRESULT ma_IMMDeviceEnumerator_QueryInterface(ma_IMMDeviceEnumerator* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } + ULONG ma_IMMDeviceEnumerator_AddRef(ma_IMMDeviceEnumerator* pThis) { return pThis->lpVtbl->AddRef(pThis); } + ULONG ma_IMMDeviceEnumerator_Release(ma_IMMDeviceEnumerator* pThis) { return pThis->lpVtbl->Release(pThis); } + HRESULT ma_IMMDeviceEnumerator_EnumAudioEndpoints(ma_IMMDeviceEnumerator* pThis, ma_EDataFlow dataFlow, DWORD dwStateMask, ma_IMMDeviceCollection** ppDevices) { return pThis->lpVtbl->EnumAudioEndpoints(pThis, dataFlow, dwStateMask, ppDevices); } + HRESULT ma_IMMDeviceEnumerator_GetDefaultAudioEndpoint(ma_IMMDeviceEnumerator* pThis, ma_EDataFlow dataFlow, ma_ERole role, ma_IMMDevice** ppEndpoint) { return pThis->lpVtbl->GetDefaultAudioEndpoint(pThis, dataFlow, role, ppEndpoint); } + HRESULT ma_IMMDeviceEnumerator_GetDevice(ma_IMMDeviceEnumerator* pThis, LPCWSTR pID, ma_IMMDevice** ppDevice) { return pThis->lpVtbl->GetDevice(pThis, pID, ppDevice); } + HRESULT ma_IMMDeviceEnumerator_RegisterEndpointNotificationCallback(ma_IMMDeviceEnumerator* pThis, ma_IMMNotificationClient* pClient) { return pThis->lpVtbl->RegisterEndpointNotificationCallback(pThis, pClient); } + HRESULT ma_IMMDeviceEnumerator_UnregisterEndpointNotificationCallback(ma_IMMDeviceEnumerator* pThis, ma_IMMNotificationClient* pClient) { return pThis->lpVtbl->UnregisterEndpointNotificationCallback(pThis, pClient); } + + + // IMMDeviceCollection + typedef struct + { + // IUnknown + HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IMMDeviceCollection* pThis, const IID* const riid, void** ppObject); + ULONG (STDMETHODCALLTYPE * AddRef) (ma_IMMDeviceCollection* pThis); + ULONG (STDMETHODCALLTYPE * Release) (ma_IMMDeviceCollection* pThis); + + // IMMDeviceCollection + HRESULT (STDMETHODCALLTYPE * GetCount)(ma_IMMDeviceCollection* pThis, UINT* pDevices); + HRESULT (STDMETHODCALLTYPE * Item) (ma_IMMDeviceCollection* pThis, UINT nDevice, ma_IMMDevice** ppDevice); + } ma_IMMDeviceCollectionVtbl; + struct ma_IMMDeviceCollection + { + ma_IMMDeviceCollectionVtbl* lpVtbl; + }; + HRESULT ma_IMMDeviceCollection_QueryInterface(ma_IMMDeviceCollection* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } + ULONG ma_IMMDeviceCollection_AddRef(ma_IMMDeviceCollection* pThis) { return pThis->lpVtbl->AddRef(pThis); } + ULONG ma_IMMDeviceCollection_Release(ma_IMMDeviceCollection* pThis) { return pThis->lpVtbl->Release(pThis); } + HRESULT ma_IMMDeviceCollection_GetCount(ma_IMMDeviceCollection* pThis, UINT* pDevices) { return pThis->lpVtbl->GetCount(pThis, pDevices); } + HRESULT ma_IMMDeviceCollection_Item(ma_IMMDeviceCollection* pThis, UINT nDevice, ma_IMMDevice** ppDevice) { return pThis->lpVtbl->Item(pThis, nDevice, ppDevice); } + + + // IMMDevice + typedef struct + { + // IUnknown + HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IMMDevice* pThis, const IID* const riid, void** ppObject); + ULONG (STDMETHODCALLTYPE * AddRef) (ma_IMMDevice* pThis); + ULONG (STDMETHODCALLTYPE * Release) (ma_IMMDevice* pThis); + + // IMMDevice + HRESULT (STDMETHODCALLTYPE * Activate) (ma_IMMDevice* pThis, const IID* const iid, DWORD dwClsCtx, PROPVARIANT* pActivationParams, void** ppInterface); + HRESULT (STDMETHODCALLTYPE * OpenPropertyStore)(ma_IMMDevice* pThis, DWORD stgmAccess, ma_IPropertyStore** ppProperties); + HRESULT (STDMETHODCALLTYPE * GetId) (ma_IMMDevice* pThis, LPWSTR *pID); + HRESULT (STDMETHODCALLTYPE * GetState) (ma_IMMDevice* pThis, DWORD *pState); + } ma_IMMDeviceVtbl; + struct ma_IMMDevice + { + ma_IMMDeviceVtbl* lpVtbl; + }; + HRESULT ma_IMMDevice_QueryInterface(ma_IMMDevice* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } + ULONG ma_IMMDevice_AddRef(ma_IMMDevice* pThis) { return pThis->lpVtbl->AddRef(pThis); } + ULONG ma_IMMDevice_Release(ma_IMMDevice* pThis) { return pThis->lpVtbl->Release(pThis); } + HRESULT ma_IMMDevice_Activate(ma_IMMDevice* pThis, const IID* const iid, DWORD dwClsCtx, PROPVARIANT* pActivationParams, void** ppInterface) { return pThis->lpVtbl->Activate(pThis, iid, dwClsCtx, pActivationParams, ppInterface); } + HRESULT ma_IMMDevice_OpenPropertyStore(ma_IMMDevice* pThis, DWORD stgmAccess, ma_IPropertyStore** ppProperties) { return pThis->lpVtbl->OpenPropertyStore(pThis, stgmAccess, ppProperties); } + HRESULT ma_IMMDevice_GetId(ma_IMMDevice* pThis, LPWSTR *pID) { return pThis->lpVtbl->GetId(pThis, pID); } + HRESULT ma_IMMDevice_GetState(ma_IMMDevice* pThis, DWORD *pState) { return pThis->lpVtbl->GetState(pThis, pState); } +#else + // IActivateAudioInterfaceAsyncOperation + typedef struct + { + // IUnknown + HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IActivateAudioInterfaceAsyncOperation* pThis, const IID* const riid, void** ppObject); + ULONG (STDMETHODCALLTYPE * AddRef) (ma_IActivateAudioInterfaceAsyncOperation* pThis); + ULONG (STDMETHODCALLTYPE * Release) (ma_IActivateAudioInterfaceAsyncOperation* pThis); + + // IActivateAudioInterfaceAsyncOperation + HRESULT (STDMETHODCALLTYPE * GetActivateResult)(ma_IActivateAudioInterfaceAsyncOperation* pThis, HRESULT *pActivateResult, ma_IUnknown** ppActivatedInterface); + } ma_IActivateAudioInterfaceAsyncOperationVtbl; + struct ma_IActivateAudioInterfaceAsyncOperation + { + ma_IActivateAudioInterfaceAsyncOperationVtbl* lpVtbl; + }; + HRESULT ma_IActivateAudioInterfaceAsyncOperation_QueryInterface(ma_IActivateAudioInterfaceAsyncOperation* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } + ULONG ma_IActivateAudioInterfaceAsyncOperation_AddRef(ma_IActivateAudioInterfaceAsyncOperation* pThis) { return pThis->lpVtbl->AddRef(pThis); } + ULONG ma_IActivateAudioInterfaceAsyncOperation_Release(ma_IActivateAudioInterfaceAsyncOperation* pThis) { return pThis->lpVtbl->Release(pThis); } + HRESULT ma_IActivateAudioInterfaceAsyncOperation_GetActivateResult(ma_IActivateAudioInterfaceAsyncOperation* pThis, HRESULT *pActivateResult, ma_IUnknown** ppActivatedInterface) { return pThis->lpVtbl->GetActivateResult(pThis, pActivateResult, ppActivatedInterface); } +#endif + +// IPropertyStore +typedef struct +{ + // IUnknown + HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IPropertyStore* pThis, const IID* const riid, void** ppObject); + ULONG (STDMETHODCALLTYPE * AddRef) (ma_IPropertyStore* pThis); + ULONG (STDMETHODCALLTYPE * Release) (ma_IPropertyStore* pThis); + + // IPropertyStore + HRESULT (STDMETHODCALLTYPE * GetCount)(ma_IPropertyStore* pThis, DWORD* pPropCount); + HRESULT (STDMETHODCALLTYPE * GetAt) (ma_IPropertyStore* pThis, DWORD propIndex, PROPERTYKEY* pPropKey); + HRESULT (STDMETHODCALLTYPE * GetValue)(ma_IPropertyStore* pThis, const PROPERTYKEY* const pKey, PROPVARIANT* pPropVar); + HRESULT (STDMETHODCALLTYPE * SetValue)(ma_IPropertyStore* pThis, const PROPERTYKEY* const pKey, const PROPVARIANT* const pPropVar); + HRESULT (STDMETHODCALLTYPE * Commit) (ma_IPropertyStore* pThis); +} ma_IPropertyStoreVtbl; +struct ma_IPropertyStore +{ + ma_IPropertyStoreVtbl* lpVtbl; +}; +HRESULT ma_IPropertyStore_QueryInterface(ma_IPropertyStore* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } +ULONG ma_IPropertyStore_AddRef(ma_IPropertyStore* pThis) { return pThis->lpVtbl->AddRef(pThis); } +ULONG ma_IPropertyStore_Release(ma_IPropertyStore* pThis) { return pThis->lpVtbl->Release(pThis); } +HRESULT ma_IPropertyStore_GetCount(ma_IPropertyStore* pThis, DWORD* pPropCount) { return pThis->lpVtbl->GetCount(pThis, pPropCount); } +HRESULT ma_IPropertyStore_GetAt(ma_IPropertyStore* pThis, DWORD propIndex, PROPERTYKEY* pPropKey) { return pThis->lpVtbl->GetAt(pThis, propIndex, pPropKey); } +HRESULT ma_IPropertyStore_GetValue(ma_IPropertyStore* pThis, const PROPERTYKEY* const pKey, PROPVARIANT* pPropVar) { return pThis->lpVtbl->GetValue(pThis, pKey, pPropVar); } +HRESULT ma_IPropertyStore_SetValue(ma_IPropertyStore* pThis, const PROPERTYKEY* const pKey, const PROPVARIANT* const pPropVar) { return pThis->lpVtbl->SetValue(pThis, pKey, pPropVar); } +HRESULT ma_IPropertyStore_Commit(ma_IPropertyStore* pThis) { return pThis->lpVtbl->Commit(pThis); } + + +// IAudioClient +typedef struct +{ + // IUnknown + HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IAudioClient* pThis, const IID* const riid, void** ppObject); + ULONG (STDMETHODCALLTYPE * AddRef) (ma_IAudioClient* pThis); + ULONG (STDMETHODCALLTYPE * Release) (ma_IAudioClient* pThis); + + // IAudioClient + HRESULT (STDMETHODCALLTYPE * Initialize) (ma_IAudioClient* pThis, MA_AUDCLNT_SHAREMODE shareMode, DWORD streamFlags, MA_REFERENCE_TIME bufferDuration, MA_REFERENCE_TIME periodicity, const WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid); + HRESULT (STDMETHODCALLTYPE * GetBufferSize) (ma_IAudioClient* pThis, ma_uint32* pNumBufferFrames); + HRESULT (STDMETHODCALLTYPE * GetStreamLatency) (ma_IAudioClient* pThis, MA_REFERENCE_TIME* pLatency); + HRESULT (STDMETHODCALLTYPE * GetCurrentPadding)(ma_IAudioClient* pThis, ma_uint32* pNumPaddingFrames); + HRESULT (STDMETHODCALLTYPE * IsFormatSupported)(ma_IAudioClient* pThis, MA_AUDCLNT_SHAREMODE shareMode, const WAVEFORMATEX* pFormat, WAVEFORMATEX** ppClosestMatch); + HRESULT (STDMETHODCALLTYPE * GetMixFormat) (ma_IAudioClient* pThis, WAVEFORMATEX** ppDeviceFormat); + HRESULT (STDMETHODCALLTYPE * GetDevicePeriod) (ma_IAudioClient* pThis, MA_REFERENCE_TIME* pDefaultDevicePeriod, MA_REFERENCE_TIME* pMinimumDevicePeriod); + HRESULT (STDMETHODCALLTYPE * Start) (ma_IAudioClient* pThis); + HRESULT (STDMETHODCALLTYPE * Stop) (ma_IAudioClient* pThis); + HRESULT (STDMETHODCALLTYPE * Reset) (ma_IAudioClient* pThis); + HRESULT (STDMETHODCALLTYPE * SetEventHandle) (ma_IAudioClient* pThis, HANDLE eventHandle); + HRESULT (STDMETHODCALLTYPE * GetService) (ma_IAudioClient* pThis, const IID* const riid, void** pp); +} ma_IAudioClientVtbl; +struct ma_IAudioClient +{ + ma_IAudioClientVtbl* lpVtbl; +}; +HRESULT ma_IAudioClient_QueryInterface(ma_IAudioClient* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } +ULONG ma_IAudioClient_AddRef(ma_IAudioClient* pThis) { return pThis->lpVtbl->AddRef(pThis); } +ULONG ma_IAudioClient_Release(ma_IAudioClient* pThis) { return pThis->lpVtbl->Release(pThis); } +HRESULT ma_IAudioClient_Initialize(ma_IAudioClient* pThis, MA_AUDCLNT_SHAREMODE shareMode, DWORD streamFlags, MA_REFERENCE_TIME bufferDuration, MA_REFERENCE_TIME periodicity, const WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid) { return pThis->lpVtbl->Initialize(pThis, shareMode, streamFlags, bufferDuration, periodicity, pFormat, pAudioSessionGuid); } +HRESULT ma_IAudioClient_GetBufferSize(ma_IAudioClient* pThis, ma_uint32* pNumBufferFrames) { return pThis->lpVtbl->GetBufferSize(pThis, pNumBufferFrames); } +HRESULT ma_IAudioClient_GetStreamLatency(ma_IAudioClient* pThis, MA_REFERENCE_TIME* pLatency) { return pThis->lpVtbl->GetStreamLatency(pThis, pLatency); } +HRESULT ma_IAudioClient_GetCurrentPadding(ma_IAudioClient* pThis, ma_uint32* pNumPaddingFrames) { return pThis->lpVtbl->GetCurrentPadding(pThis, pNumPaddingFrames); } +HRESULT ma_IAudioClient_IsFormatSupported(ma_IAudioClient* pThis, MA_AUDCLNT_SHAREMODE shareMode, const WAVEFORMATEX* pFormat, WAVEFORMATEX** ppClosestMatch) { return pThis->lpVtbl->IsFormatSupported(pThis, shareMode, pFormat, ppClosestMatch); } +HRESULT ma_IAudioClient_GetMixFormat(ma_IAudioClient* pThis, WAVEFORMATEX** ppDeviceFormat) { return pThis->lpVtbl->GetMixFormat(pThis, ppDeviceFormat); } +HRESULT ma_IAudioClient_GetDevicePeriod(ma_IAudioClient* pThis, MA_REFERENCE_TIME* pDefaultDevicePeriod, MA_REFERENCE_TIME* pMinimumDevicePeriod) { return pThis->lpVtbl->GetDevicePeriod(pThis, pDefaultDevicePeriod, pMinimumDevicePeriod); } +HRESULT ma_IAudioClient_Start(ma_IAudioClient* pThis) { return pThis->lpVtbl->Start(pThis); } +HRESULT ma_IAudioClient_Stop(ma_IAudioClient* pThis) { return pThis->lpVtbl->Stop(pThis); } +HRESULT ma_IAudioClient_Reset(ma_IAudioClient* pThis) { return pThis->lpVtbl->Reset(pThis); } +HRESULT ma_IAudioClient_SetEventHandle(ma_IAudioClient* pThis, HANDLE eventHandle) { return pThis->lpVtbl->SetEventHandle(pThis, eventHandle); } +HRESULT ma_IAudioClient_GetService(ma_IAudioClient* pThis, const IID* const riid, void** pp) { return pThis->lpVtbl->GetService(pThis, riid, pp); } + +// IAudioClient2 +typedef struct +{ + // IUnknown + HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IAudioClient2* pThis, const IID* const riid, void** ppObject); + ULONG (STDMETHODCALLTYPE * AddRef) (ma_IAudioClient2* pThis); + ULONG (STDMETHODCALLTYPE * Release) (ma_IAudioClient2* pThis); + + // IAudioClient + HRESULT (STDMETHODCALLTYPE * Initialize) (ma_IAudioClient2* pThis, MA_AUDCLNT_SHAREMODE shareMode, DWORD streamFlags, MA_REFERENCE_TIME bufferDuration, MA_REFERENCE_TIME periodicity, const WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid); + HRESULT (STDMETHODCALLTYPE * GetBufferSize) (ma_IAudioClient2* pThis, ma_uint32* pNumBufferFrames); + HRESULT (STDMETHODCALLTYPE * GetStreamLatency) (ma_IAudioClient2* pThis, MA_REFERENCE_TIME* pLatency); + HRESULT (STDMETHODCALLTYPE * GetCurrentPadding)(ma_IAudioClient2* pThis, ma_uint32* pNumPaddingFrames); + HRESULT (STDMETHODCALLTYPE * IsFormatSupported)(ma_IAudioClient2* pThis, MA_AUDCLNT_SHAREMODE shareMode, const WAVEFORMATEX* pFormat, WAVEFORMATEX** ppClosestMatch); + HRESULT (STDMETHODCALLTYPE * GetMixFormat) (ma_IAudioClient2* pThis, WAVEFORMATEX** ppDeviceFormat); + HRESULT (STDMETHODCALLTYPE * GetDevicePeriod) (ma_IAudioClient2* pThis, MA_REFERENCE_TIME* pDefaultDevicePeriod, MA_REFERENCE_TIME* pMinimumDevicePeriod); + HRESULT (STDMETHODCALLTYPE * Start) (ma_IAudioClient2* pThis); + HRESULT (STDMETHODCALLTYPE * Stop) (ma_IAudioClient2* pThis); + HRESULT (STDMETHODCALLTYPE * Reset) (ma_IAudioClient2* pThis); + HRESULT (STDMETHODCALLTYPE * SetEventHandle) (ma_IAudioClient2* pThis, HANDLE eventHandle); + HRESULT (STDMETHODCALLTYPE * GetService) (ma_IAudioClient2* pThis, const IID* const riid, void** pp); + + // IAudioClient2 + HRESULT (STDMETHODCALLTYPE * IsOffloadCapable) (ma_IAudioClient2* pThis, MA_AUDIO_STREAM_CATEGORY category, BOOL* pOffloadCapable); + HRESULT (STDMETHODCALLTYPE * SetClientProperties)(ma_IAudioClient2* pThis, const ma_AudioClientProperties* pProperties); + HRESULT (STDMETHODCALLTYPE * GetBufferSizeLimits)(ma_IAudioClient2* pThis, const WAVEFORMATEX* pFormat, BOOL eventDriven, MA_REFERENCE_TIME* pMinBufferDuration, MA_REFERENCE_TIME* pMaxBufferDuration); +} ma_IAudioClient2Vtbl; +struct ma_IAudioClient2 +{ + ma_IAudioClient2Vtbl* lpVtbl; +}; +HRESULT ma_IAudioClient2_QueryInterface(ma_IAudioClient2* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } +ULONG ma_IAudioClient2_AddRef(ma_IAudioClient2* pThis) { return pThis->lpVtbl->AddRef(pThis); } +ULONG ma_IAudioClient2_Release(ma_IAudioClient2* pThis) { return pThis->lpVtbl->Release(pThis); } +HRESULT ma_IAudioClient2_Initialize(ma_IAudioClient2* pThis, MA_AUDCLNT_SHAREMODE shareMode, DWORD streamFlags, MA_REFERENCE_TIME bufferDuration, MA_REFERENCE_TIME periodicity, const WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid) { return pThis->lpVtbl->Initialize(pThis, shareMode, streamFlags, bufferDuration, periodicity, pFormat, pAudioSessionGuid); } +HRESULT ma_IAudioClient2_GetBufferSize(ma_IAudioClient2* pThis, ma_uint32* pNumBufferFrames) { return pThis->lpVtbl->GetBufferSize(pThis, pNumBufferFrames); } +HRESULT ma_IAudioClient2_GetStreamLatency(ma_IAudioClient2* pThis, MA_REFERENCE_TIME* pLatency) { return pThis->lpVtbl->GetStreamLatency(pThis, pLatency); } +HRESULT ma_IAudioClient2_GetCurrentPadding(ma_IAudioClient2* pThis, ma_uint32* pNumPaddingFrames) { return pThis->lpVtbl->GetCurrentPadding(pThis, pNumPaddingFrames); } +HRESULT ma_IAudioClient2_IsFormatSupported(ma_IAudioClient2* pThis, MA_AUDCLNT_SHAREMODE shareMode, const WAVEFORMATEX* pFormat, WAVEFORMATEX** ppClosestMatch) { return pThis->lpVtbl->IsFormatSupported(pThis, shareMode, pFormat, ppClosestMatch); } +HRESULT ma_IAudioClient2_GetMixFormat(ma_IAudioClient2* pThis, WAVEFORMATEX** ppDeviceFormat) { return pThis->lpVtbl->GetMixFormat(pThis, ppDeviceFormat); } +HRESULT ma_IAudioClient2_GetDevicePeriod(ma_IAudioClient2* pThis, MA_REFERENCE_TIME* pDefaultDevicePeriod, MA_REFERENCE_TIME* pMinimumDevicePeriod) { return pThis->lpVtbl->GetDevicePeriod(pThis, pDefaultDevicePeriod, pMinimumDevicePeriod); } +HRESULT ma_IAudioClient2_Start(ma_IAudioClient2* pThis) { return pThis->lpVtbl->Start(pThis); } +HRESULT ma_IAudioClient2_Stop(ma_IAudioClient2* pThis) { return pThis->lpVtbl->Stop(pThis); } +HRESULT ma_IAudioClient2_Reset(ma_IAudioClient2* pThis) { return pThis->lpVtbl->Reset(pThis); } +HRESULT ma_IAudioClient2_SetEventHandle(ma_IAudioClient2* pThis, HANDLE eventHandle) { return pThis->lpVtbl->SetEventHandle(pThis, eventHandle); } +HRESULT ma_IAudioClient2_GetService(ma_IAudioClient2* pThis, const IID* const riid, void** pp) { return pThis->lpVtbl->GetService(pThis, riid, pp); } +HRESULT ma_IAudioClient2_IsOffloadCapable(ma_IAudioClient2* pThis, MA_AUDIO_STREAM_CATEGORY category, BOOL* pOffloadCapable) { return pThis->lpVtbl->IsOffloadCapable(pThis, category, pOffloadCapable); } +HRESULT ma_IAudioClient2_SetClientProperties(ma_IAudioClient2* pThis, const ma_AudioClientProperties* pProperties) { return pThis->lpVtbl->SetClientProperties(pThis, pProperties); } +HRESULT ma_IAudioClient2_GetBufferSizeLimits(ma_IAudioClient2* pThis, const WAVEFORMATEX* pFormat, BOOL eventDriven, MA_REFERENCE_TIME* pMinBufferDuration, MA_REFERENCE_TIME* pMaxBufferDuration) { return pThis->lpVtbl->GetBufferSizeLimits(pThis, pFormat, eventDriven, pMinBufferDuration, pMaxBufferDuration); } + + +// IAudioClient3 +typedef struct +{ + // IUnknown + HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IAudioClient3* pThis, const IID* const riid, void** ppObject); + ULONG (STDMETHODCALLTYPE * AddRef) (ma_IAudioClient3* pThis); + ULONG (STDMETHODCALLTYPE * Release) (ma_IAudioClient3* pThis); + + // IAudioClient + HRESULT (STDMETHODCALLTYPE * Initialize) (ma_IAudioClient3* pThis, MA_AUDCLNT_SHAREMODE shareMode, DWORD streamFlags, MA_REFERENCE_TIME bufferDuration, MA_REFERENCE_TIME periodicity, const WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid); + HRESULT (STDMETHODCALLTYPE * GetBufferSize) (ma_IAudioClient3* pThis, ma_uint32* pNumBufferFrames); + HRESULT (STDMETHODCALLTYPE * GetStreamLatency) (ma_IAudioClient3* pThis, MA_REFERENCE_TIME* pLatency); + HRESULT (STDMETHODCALLTYPE * GetCurrentPadding)(ma_IAudioClient3* pThis, ma_uint32* pNumPaddingFrames); + HRESULT (STDMETHODCALLTYPE * IsFormatSupported)(ma_IAudioClient3* pThis, MA_AUDCLNT_SHAREMODE shareMode, const WAVEFORMATEX* pFormat, WAVEFORMATEX** ppClosestMatch); + HRESULT (STDMETHODCALLTYPE * GetMixFormat) (ma_IAudioClient3* pThis, WAVEFORMATEX** ppDeviceFormat); + HRESULT (STDMETHODCALLTYPE * GetDevicePeriod) (ma_IAudioClient3* pThis, MA_REFERENCE_TIME* pDefaultDevicePeriod, MA_REFERENCE_TIME* pMinimumDevicePeriod); + HRESULT (STDMETHODCALLTYPE * Start) (ma_IAudioClient3* pThis); + HRESULT (STDMETHODCALLTYPE * Stop) (ma_IAudioClient3* pThis); + HRESULT (STDMETHODCALLTYPE * Reset) (ma_IAudioClient3* pThis); + HRESULT (STDMETHODCALLTYPE * SetEventHandle) (ma_IAudioClient3* pThis, HANDLE eventHandle); + HRESULT (STDMETHODCALLTYPE * GetService) (ma_IAudioClient3* pThis, const IID* const riid, void** pp); + + // IAudioClient2 + HRESULT (STDMETHODCALLTYPE * IsOffloadCapable) (ma_IAudioClient3* pThis, MA_AUDIO_STREAM_CATEGORY category, BOOL* pOffloadCapable); + HRESULT (STDMETHODCALLTYPE * SetClientProperties)(ma_IAudioClient3* pThis, const ma_AudioClientProperties* pProperties); + HRESULT (STDMETHODCALLTYPE * GetBufferSizeLimits)(ma_IAudioClient3* pThis, const WAVEFORMATEX* pFormat, BOOL eventDriven, MA_REFERENCE_TIME* pMinBufferDuration, MA_REFERENCE_TIME* pMaxBufferDuration); + + // IAudioClient3 + HRESULT (STDMETHODCALLTYPE * GetSharedModeEnginePeriod) (ma_IAudioClient3* pThis, const WAVEFORMATEX* pFormat, UINT32* pDefaultPeriodInFrames, UINT32* pFundamentalPeriodInFrames, UINT32* pMinPeriodInFrames, UINT32* pMaxPeriodInFrames); + HRESULT (STDMETHODCALLTYPE * GetCurrentSharedModeEnginePeriod)(ma_IAudioClient3* pThis, WAVEFORMATEX** ppFormat, UINT32* pCurrentPeriodInFrames); + HRESULT (STDMETHODCALLTYPE * InitializeSharedAudioStream) (ma_IAudioClient3* pThis, DWORD streamFlags, UINT32 periodInFrames, const WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid); +} ma_IAudioClient3Vtbl; +struct ma_IAudioClient3 +{ + ma_IAudioClient3Vtbl* lpVtbl; +}; +HRESULT ma_IAudioClient3_QueryInterface(ma_IAudioClient3* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } +ULONG ma_IAudioClient3_AddRef(ma_IAudioClient3* pThis) { return pThis->lpVtbl->AddRef(pThis); } +ULONG ma_IAudioClient3_Release(ma_IAudioClient3* pThis) { return pThis->lpVtbl->Release(pThis); } +HRESULT ma_IAudioClient3_Initialize(ma_IAudioClient3* pThis, MA_AUDCLNT_SHAREMODE shareMode, DWORD streamFlags, MA_REFERENCE_TIME bufferDuration, MA_REFERENCE_TIME periodicity, const WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid) { return pThis->lpVtbl->Initialize(pThis, shareMode, streamFlags, bufferDuration, periodicity, pFormat, pAudioSessionGuid); } +HRESULT ma_IAudioClient3_GetBufferSize(ma_IAudioClient3* pThis, ma_uint32* pNumBufferFrames) { return pThis->lpVtbl->GetBufferSize(pThis, pNumBufferFrames); } +HRESULT ma_IAudioClient3_GetStreamLatency(ma_IAudioClient3* pThis, MA_REFERENCE_TIME* pLatency) { return pThis->lpVtbl->GetStreamLatency(pThis, pLatency); } +HRESULT ma_IAudioClient3_GetCurrentPadding(ma_IAudioClient3* pThis, ma_uint32* pNumPaddingFrames) { return pThis->lpVtbl->GetCurrentPadding(pThis, pNumPaddingFrames); } +HRESULT ma_IAudioClient3_IsFormatSupported(ma_IAudioClient3* pThis, MA_AUDCLNT_SHAREMODE shareMode, const WAVEFORMATEX* pFormat, WAVEFORMATEX** ppClosestMatch) { return pThis->lpVtbl->IsFormatSupported(pThis, shareMode, pFormat, ppClosestMatch); } +HRESULT ma_IAudioClient3_GetMixFormat(ma_IAudioClient3* pThis, WAVEFORMATEX** ppDeviceFormat) { return pThis->lpVtbl->GetMixFormat(pThis, ppDeviceFormat); } +HRESULT ma_IAudioClient3_GetDevicePeriod(ma_IAudioClient3* pThis, MA_REFERENCE_TIME* pDefaultDevicePeriod, MA_REFERENCE_TIME* pMinimumDevicePeriod) { return pThis->lpVtbl->GetDevicePeriod(pThis, pDefaultDevicePeriod, pMinimumDevicePeriod); } +HRESULT ma_IAudioClient3_Start(ma_IAudioClient3* pThis) { return pThis->lpVtbl->Start(pThis); } +HRESULT ma_IAudioClient3_Stop(ma_IAudioClient3* pThis) { return pThis->lpVtbl->Stop(pThis); } +HRESULT ma_IAudioClient3_Reset(ma_IAudioClient3* pThis) { return pThis->lpVtbl->Reset(pThis); } +HRESULT ma_IAudioClient3_SetEventHandle(ma_IAudioClient3* pThis, HANDLE eventHandle) { return pThis->lpVtbl->SetEventHandle(pThis, eventHandle); } +HRESULT ma_IAudioClient3_GetService(ma_IAudioClient3* pThis, const IID* const riid, void** pp) { return pThis->lpVtbl->GetService(pThis, riid, pp); } +HRESULT ma_IAudioClient3_IsOffloadCapable(ma_IAudioClient3* pThis, MA_AUDIO_STREAM_CATEGORY category, BOOL* pOffloadCapable) { return pThis->lpVtbl->IsOffloadCapable(pThis, category, pOffloadCapable); } +HRESULT ma_IAudioClient3_SetClientProperties(ma_IAudioClient3* pThis, const ma_AudioClientProperties* pProperties) { return pThis->lpVtbl->SetClientProperties(pThis, pProperties); } +HRESULT ma_IAudioClient3_GetBufferSizeLimits(ma_IAudioClient3* pThis, const WAVEFORMATEX* pFormat, BOOL eventDriven, MA_REFERENCE_TIME* pMinBufferDuration, MA_REFERENCE_TIME* pMaxBufferDuration) { return pThis->lpVtbl->GetBufferSizeLimits(pThis, pFormat, eventDriven, pMinBufferDuration, pMaxBufferDuration); } +HRESULT ma_IAudioClient3_GetSharedModeEnginePeriod(ma_IAudioClient3* pThis, const WAVEFORMATEX* pFormat, UINT32* pDefaultPeriodInFrames, UINT32* pFundamentalPeriodInFrames, UINT32* pMinPeriodInFrames, UINT32* pMaxPeriodInFrames) { return pThis->lpVtbl->GetSharedModeEnginePeriod(pThis, pFormat, pDefaultPeriodInFrames, pFundamentalPeriodInFrames, pMinPeriodInFrames, pMaxPeriodInFrames); } +HRESULT ma_IAudioClient3_GetCurrentSharedModeEnginePeriod(ma_IAudioClient3* pThis, WAVEFORMATEX** ppFormat, UINT32* pCurrentPeriodInFrames) { return pThis->lpVtbl->GetCurrentSharedModeEnginePeriod(pThis, ppFormat, pCurrentPeriodInFrames); } +HRESULT ma_IAudioClient3_InitializeSharedAudioStream(ma_IAudioClient3* pThis, DWORD streamFlags, UINT32 periodInFrames, const WAVEFORMATEX* pFormat, const GUID* pAudioSessionGUID) { return pThis->lpVtbl->InitializeSharedAudioStream(pThis, streamFlags, periodInFrames, pFormat, pAudioSessionGUID); } + + +// IAudioRenderClient +typedef struct +{ + // IUnknown + HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IAudioRenderClient* pThis, const IID* const riid, void** ppObject); + ULONG (STDMETHODCALLTYPE * AddRef) (ma_IAudioRenderClient* pThis); + ULONG (STDMETHODCALLTYPE * Release) (ma_IAudioRenderClient* pThis); + + // IAudioRenderClient + HRESULT (STDMETHODCALLTYPE * GetBuffer) (ma_IAudioRenderClient* pThis, ma_uint32 numFramesRequested, BYTE** ppData); + HRESULT (STDMETHODCALLTYPE * ReleaseBuffer)(ma_IAudioRenderClient* pThis, ma_uint32 numFramesWritten, DWORD dwFlags); +} ma_IAudioRenderClientVtbl; +struct ma_IAudioRenderClient +{ + ma_IAudioRenderClientVtbl* lpVtbl; +}; +HRESULT ma_IAudioRenderClient_QueryInterface(ma_IAudioRenderClient* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } +ULONG ma_IAudioRenderClient_AddRef(ma_IAudioRenderClient* pThis) { return pThis->lpVtbl->AddRef(pThis); } +ULONG ma_IAudioRenderClient_Release(ma_IAudioRenderClient* pThis) { return pThis->lpVtbl->Release(pThis); } +HRESULT ma_IAudioRenderClient_GetBuffer(ma_IAudioRenderClient* pThis, ma_uint32 numFramesRequested, BYTE** ppData) { return pThis->lpVtbl->GetBuffer(pThis, numFramesRequested, ppData); } +HRESULT ma_IAudioRenderClient_ReleaseBuffer(ma_IAudioRenderClient* pThis, ma_uint32 numFramesWritten, DWORD dwFlags) { return pThis->lpVtbl->ReleaseBuffer(pThis, numFramesWritten, dwFlags); } + + +// IAudioCaptureClient +typedef struct +{ + // IUnknown + HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IAudioCaptureClient* pThis, const IID* const riid, void** ppObject); + ULONG (STDMETHODCALLTYPE * AddRef) (ma_IAudioCaptureClient* pThis); + ULONG (STDMETHODCALLTYPE * Release) (ma_IAudioCaptureClient* pThis); + + // IAudioRenderClient + HRESULT (STDMETHODCALLTYPE * GetBuffer) (ma_IAudioCaptureClient* pThis, BYTE** ppData, ma_uint32* pNumFramesToRead, DWORD* pFlags, ma_uint64* pDevicePosition, ma_uint64* pQPCPosition); + HRESULT (STDMETHODCALLTYPE * ReleaseBuffer) (ma_IAudioCaptureClient* pThis, ma_uint32 numFramesRead); + HRESULT (STDMETHODCALLTYPE * GetNextPacketSize)(ma_IAudioCaptureClient* pThis, ma_uint32* pNumFramesInNextPacket); +} ma_IAudioCaptureClientVtbl; +struct ma_IAudioCaptureClient +{ + ma_IAudioCaptureClientVtbl* lpVtbl; +}; +HRESULT ma_IAudioCaptureClient_QueryInterface(ma_IAudioCaptureClient* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } +ULONG ma_IAudioCaptureClient_AddRef(ma_IAudioCaptureClient* pThis) { return pThis->lpVtbl->AddRef(pThis); } +ULONG ma_IAudioCaptureClient_Release(ma_IAudioCaptureClient* pThis) { return pThis->lpVtbl->Release(pThis); } +HRESULT ma_IAudioCaptureClient_GetBuffer(ma_IAudioCaptureClient* pThis, BYTE** ppData, ma_uint32* pNumFramesToRead, DWORD* pFlags, ma_uint64* pDevicePosition, ma_uint64* pQPCPosition) { return pThis->lpVtbl->GetBuffer(pThis, ppData, pNumFramesToRead, pFlags, pDevicePosition, pQPCPosition); } +HRESULT ma_IAudioCaptureClient_ReleaseBuffer(ma_IAudioCaptureClient* pThis, ma_uint32 numFramesRead) { return pThis->lpVtbl->ReleaseBuffer(pThis, numFramesRead); } +HRESULT ma_IAudioCaptureClient_GetNextPacketSize(ma_IAudioCaptureClient* pThis, ma_uint32* pNumFramesInNextPacket) { return pThis->lpVtbl->GetNextPacketSize(pThis, pNumFramesInNextPacket); } + +#ifndef MA_WIN32_DESKTOP +#include +typedef struct ma_completion_handler_uwp ma_completion_handler_uwp; + +typedef struct +{ + // IUnknown + HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_completion_handler_uwp* pThis, const IID* const riid, void** ppObject); + ULONG (STDMETHODCALLTYPE * AddRef) (ma_completion_handler_uwp* pThis); + ULONG (STDMETHODCALLTYPE * Release) (ma_completion_handler_uwp* pThis); + + // IActivateAudioInterfaceCompletionHandler + HRESULT (STDMETHODCALLTYPE * ActivateCompleted)(ma_completion_handler_uwp* pThis, ma_IActivateAudioInterfaceAsyncOperation* pActivateOperation); +} ma_completion_handler_uwp_vtbl; +struct ma_completion_handler_uwp +{ + ma_completion_handler_uwp_vtbl* lpVtbl; + ma_uint32 counter; + HANDLE hEvent; +}; + +HRESULT STDMETHODCALLTYPE ma_completion_handler_uwp_QueryInterface(ma_completion_handler_uwp* pThis, const IID* const riid, void** ppObject) +{ + // We need to "implement" IAgileObject which is just an indicator that's used internally by WASAPI for some multithreading management. To + // "implement" this, we just make sure we return pThis when the IAgileObject is requested. + if (!ma_is_guid_equal(riid, &MA_IID_IUnknown) && !ma_is_guid_equal(riid, &MA_IID_IActivateAudioInterfaceCompletionHandler) && !ma_is_guid_equal(riid, &MA_IID_IAgileObject)) { + *ppObject = NULL; + return E_NOINTERFACE; + } + + // Getting here means the IID is IUnknown or IMMNotificationClient. + *ppObject = (void*)pThis; + ((ma_completion_handler_uwp_vtbl*)pThis->lpVtbl)->AddRef(pThis); + return S_OK; +} + +ULONG STDMETHODCALLTYPE ma_completion_handler_uwp_AddRef(ma_completion_handler_uwp* pThis) +{ + return (ULONG)ma_atomic_increment_32(&pThis->counter); +} + +ULONG STDMETHODCALLTYPE ma_completion_handler_uwp_Release(ma_completion_handler_uwp* pThis) +{ + ma_uint32 newRefCount = ma_atomic_decrement_32(&pThis->counter); + if (newRefCount == 0) { + return 0; // We don't free anything here because we never allocate the object on the heap. + } + + return (ULONG)newRefCount; +} + +HRESULT STDMETHODCALLTYPE ma_completion_handler_uwp_ActivateCompleted(ma_completion_handler_uwp* pThis, ma_IActivateAudioInterfaceAsyncOperation* pActivateOperation) +{ + (void)pActivateOperation; + SetEvent(pThis->hEvent); + return S_OK; +} + + +static ma_completion_handler_uwp_vtbl g_maCompletionHandlerVtblInstance = { + ma_completion_handler_uwp_QueryInterface, + ma_completion_handler_uwp_AddRef, + ma_completion_handler_uwp_Release, + ma_completion_handler_uwp_ActivateCompleted +}; + +ma_result ma_completion_handler_uwp_init(ma_completion_handler_uwp* pHandler) +{ + ma_assert(pHandler != NULL); + ma_zero_object(pHandler); + + pHandler->lpVtbl = &g_maCompletionHandlerVtblInstance; + pHandler->counter = 1; + pHandler->hEvent = CreateEventA(NULL, FALSE, FALSE, NULL); + if (pHandler->hEvent == NULL) { + return MA_ERROR; + } + + return MA_SUCCESS; +} + +void ma_completion_handler_uwp_uninit(ma_completion_handler_uwp* pHandler) +{ + if (pHandler->hEvent != NULL) { + CloseHandle(pHandler->hEvent); + } +} + +void ma_completion_handler_uwp_wait(ma_completion_handler_uwp* pHandler) +{ + WaitForSingleObject(pHandler->hEvent, INFINITE); +} +#endif // !MA_WIN32_DESKTOP + +// We need a virtual table for our notification client object that's used for detecting changes to the default device. +#ifdef MA_WIN32_DESKTOP +HRESULT STDMETHODCALLTYPE ma_IMMNotificationClient_QueryInterface(ma_IMMNotificationClient* pThis, const IID* const riid, void** ppObject) +{ + // We care about two interfaces - IUnknown and IMMNotificationClient. If the requested IID is something else + // we just return E_NOINTERFACE. Otherwise we need to increment the reference counter and return S_OK. + if (!ma_is_guid_equal(riid, &MA_IID_IUnknown) && !ma_is_guid_equal(riid, &MA_IID_IMMNotificationClient)) { + *ppObject = NULL; + return E_NOINTERFACE; + } + + // Getting here means the IID is IUnknown or IMMNotificationClient. + *ppObject = (void*)pThis; + ((ma_IMMNotificationClientVtbl*)pThis->lpVtbl)->AddRef(pThis); + return S_OK; +} + +ULONG STDMETHODCALLTYPE ma_IMMNotificationClient_AddRef(ma_IMMNotificationClient* pThis) +{ + return (ULONG)ma_atomic_increment_32(&pThis->counter); +} + +ULONG STDMETHODCALLTYPE ma_IMMNotificationClient_Release(ma_IMMNotificationClient* pThis) +{ + ma_uint32 newRefCount = ma_atomic_decrement_32(&pThis->counter); + if (newRefCount == 0) { + return 0; // We don't free anything here because we never allocate the object on the heap. + } + + return (ULONG)newRefCount; +} + + +HRESULT STDMETHODCALLTYPE ma_IMMNotificationClient_OnDeviceStateChanged(ma_IMMNotificationClient* pThis, LPCWSTR pDeviceID, DWORD dwNewState) +{ +#ifdef MA_DEBUG_OUTPUT + printf("IMMNotificationClient_OnDeviceStateChanged(pDeviceID=%S, dwNewState=%u)\n", (pDeviceID != NULL) ? pDeviceID : L"(NULL)", (unsigned int)dwNewState); +#endif + + (void)pThis; + (void)pDeviceID; + (void)dwNewState; + return S_OK; +} + +HRESULT STDMETHODCALLTYPE ma_IMMNotificationClient_OnDeviceAdded(ma_IMMNotificationClient* pThis, LPCWSTR pDeviceID) +{ +#ifdef MA_DEBUG_OUTPUT + printf("IMMNotificationClient_OnDeviceAdded(pDeviceID=%S)\n", (pDeviceID != NULL) ? pDeviceID : L"(NULL)"); +#endif + + // We don't need to worry about this event for our purposes. + (void)pThis; + (void)pDeviceID; + return S_OK; +} + +HRESULT STDMETHODCALLTYPE ma_IMMNotificationClient_OnDeviceRemoved(ma_IMMNotificationClient* pThis, LPCWSTR pDeviceID) +{ +#ifdef MA_DEBUG_OUTPUT + printf("IMMNotificationClient_OnDeviceRemoved(pDeviceID=%S)\n", (pDeviceID != NULL) ? pDeviceID : L"(NULL)"); +#endif + + // We don't need to worry about this event for our purposes. + (void)pThis; + (void)pDeviceID; + return S_OK; +} + +HRESULT STDMETHODCALLTYPE ma_IMMNotificationClient_OnDefaultDeviceChanged(ma_IMMNotificationClient* pThis, ma_EDataFlow dataFlow, ma_ERole role, LPCWSTR pDefaultDeviceID) +{ +#ifdef MA_DEBUG_OUTPUT + printf("IMMNotificationClient_OnDefaultDeviceChanged(dataFlow=%d, role=%d, pDefaultDeviceID=%S)\n", dataFlow, role, (pDefaultDeviceID != NULL) ? pDefaultDeviceID : L"(NULL)"); +#endif + + // We only ever use the eConsole role in miniaudio. + if (role != ma_eConsole) { + return S_OK; + } + + // We only care about devices with the same data flow and role as the current device. + if ((pThis->pDevice->type == ma_device_type_playback && dataFlow != ma_eRender) || + (pThis->pDevice->type == ma_device_type_capture && dataFlow != ma_eCapture)) { + return S_OK; + } + + // Not currently supporting automatic stream routing in exclusive mode. This is not working correctly on my machine due to + // AUDCLNT_E_DEVICE_IN_USE errors when reinitializing the device. If this is a bug in miniaudio, we can try re-enabling this once + // it's fixed. + if ((dataFlow == ma_eRender && pThis->pDevice->playback.shareMode == ma_share_mode_exclusive) || + (dataFlow == ma_eCapture && pThis->pDevice->capture.shareMode == ma_share_mode_exclusive)) { + return S_OK; + } + + // We don't change the device here - we change it in the worker thread to keep synchronization simple. To do this I'm just setting a flag to + // indicate that the default device has changed. + if (dataFlow == ma_eRender) { + ma_atomic_exchange_32(&pThis->pDevice->wasapi.hasDefaultPlaybackDeviceChanged, MA_TRUE); + } + if (dataFlow == ma_eCapture) { + ma_atomic_exchange_32(&pThis->pDevice->wasapi.hasDefaultCaptureDeviceChanged, MA_TRUE); + } + + (void)pDefaultDeviceID; + return S_OK; +} + +HRESULT STDMETHODCALLTYPE ma_IMMNotificationClient_OnPropertyValueChanged(ma_IMMNotificationClient* pThis, LPCWSTR pDeviceID, const PROPERTYKEY key) +{ +#ifdef MA_DEBUG_OUTPUT + printf("IMMNotificationClient_OnPropertyValueChanged(pDeviceID=%S)\n", (pDeviceID != NULL) ? pDeviceID : L"(NULL)"); +#endif + + (void)pThis; + (void)pDeviceID; + (void)key; + return S_OK; +} + +static ma_IMMNotificationClientVtbl g_maNotificationCientVtbl = { + ma_IMMNotificationClient_QueryInterface, + ma_IMMNotificationClient_AddRef, + ma_IMMNotificationClient_Release, + ma_IMMNotificationClient_OnDeviceStateChanged, + ma_IMMNotificationClient_OnDeviceAdded, + ma_IMMNotificationClient_OnDeviceRemoved, + ma_IMMNotificationClient_OnDefaultDeviceChanged, + ma_IMMNotificationClient_OnPropertyValueChanged +}; +#endif // MA_WIN32_DESKTOP + +#ifdef MA_WIN32_DESKTOP +typedef ma_IMMDevice ma_WASAPIDeviceInterface; +#else +typedef ma_IUnknown ma_WASAPIDeviceInterface; +#endif + + + +ma_bool32 ma_context_is_device_id_equal__wasapi(ma_context* pContext, const ma_device_id* pID0, const ma_device_id* pID1) +{ + ma_assert(pContext != NULL); + ma_assert(pID0 != NULL); + ma_assert(pID1 != NULL); + (void)pContext; + + return memcmp(pID0->wasapi, pID1->wasapi, sizeof(pID0->wasapi)) == 0; +} + +void ma_set_device_info_from_WAVEFORMATEX(const WAVEFORMATEX* pWF, ma_device_info* pInfo) +{ + ma_assert(pWF != NULL); + ma_assert(pInfo != NULL); + + pInfo->formatCount = 1; + pInfo->formats[0] = ma_format_from_WAVEFORMATEX(pWF); + pInfo->minChannels = pWF->nChannels; + pInfo->maxChannels = pWF->nChannels; + pInfo->minSampleRate = pWF->nSamplesPerSec; + pInfo->maxSampleRate = pWF->nSamplesPerSec; +} + +ma_result ma_context_get_device_info_from_IAudioClient__wasapi(ma_context* pContext, /*ma_IMMDevice**/void* pMMDevice, ma_IAudioClient* pAudioClient, ma_share_mode shareMode, ma_device_info* pInfo) +{ + ma_assert(pAudioClient != NULL); + ma_assert(pInfo != NULL); + + // We use a different technique to retrieve the device information depending on whether or not we are using shared or exclusive mode. + if (shareMode == ma_share_mode_shared) { + // Shared Mode. We use GetMixFormat() here. + WAVEFORMATEX* pWF = NULL; + HRESULT hr = ma_IAudioClient_GetMixFormat((ma_IAudioClient*)pAudioClient, (WAVEFORMATEX**)&pWF); + if (SUCCEEDED(hr)) { + ma_set_device_info_from_WAVEFORMATEX(pWF, pInfo); + return MA_SUCCESS; + } else { + return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to retrieve mix format for device info retrieval.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + } else { + // Exlcusive Mode. We repeatedly call IsFormatSupported() here. This is not currently support on UWP. +#ifdef MA_WIN32_DESKTOP + // The first thing to do is get the format from PKEY_AudioEngine_DeviceFormat. This should give us a channel count we assume is + // correct which will simplify our searching. + ma_IPropertyStore *pProperties; + HRESULT hr = ma_IMMDevice_OpenPropertyStore((ma_IMMDevice*)pMMDevice, STGM_READ, &pProperties); + if (SUCCEEDED(hr)) { + PROPVARIANT var; + ma_PropVariantInit(&var); + + hr = ma_IPropertyStore_GetValue(pProperties, &MA_PKEY_AudioEngine_DeviceFormat, &var); + if (SUCCEEDED(hr)) { + WAVEFORMATEX* pWF = (WAVEFORMATEX*)var.blob.pBlobData; + ma_set_device_info_from_WAVEFORMATEX(pWF, pInfo); + + // In my testing, the format returned by PKEY_AudioEngine_DeviceFormat is suitable for exclusive mode so we check this format + // first. If this fails, fall back to a search. + hr = ma_IAudioClient_IsFormatSupported((ma_IAudioClient*)pAudioClient, MA_AUDCLNT_SHAREMODE_EXCLUSIVE, pWF, NULL); + ma_PropVariantClear(pContext, &var); + + if (FAILED(hr)) { + // The format returned by PKEY_AudioEngine_DeviceFormat is not supported, so fall back to a search. We assume the channel + // count returned by MA_PKEY_AudioEngine_DeviceFormat is valid and correct. For simplicity we're only returning one format. + ma_uint32 channels = pInfo->minChannels; + + ma_format formatsToSearch[] = { + ma_format_s16, + ma_format_s24, + //ma_format_s24_32, + ma_format_f32, + ma_format_s32, + ma_format_u8 + }; + + ma_channel defaultChannelMap[MA_MAX_CHANNELS]; + ma_get_standard_channel_map(ma_standard_channel_map_microsoft, channels, defaultChannelMap); + + WAVEFORMATEXTENSIBLE wf; + ma_zero_object(&wf); + wf.Format.cbSize = sizeof(wf); + wf.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE; + wf.Format.nChannels = (WORD)channels; + wf.dwChannelMask = ma_channel_map_to_channel_mask__win32(defaultChannelMap, channels); + + ma_bool32 found = MA_FALSE; + for (ma_uint32 iFormat = 0; iFormat < ma_countof(formatsToSearch); ++iFormat) { + ma_format format = formatsToSearch[iFormat]; + + wf.Format.wBitsPerSample = (WORD)ma_get_bytes_per_sample(format)*8; + wf.Format.nBlockAlign = (wf.Format.nChannels * wf.Format.wBitsPerSample) / 8; + wf.Format.nAvgBytesPerSec = wf.Format.nBlockAlign * wf.Format.nSamplesPerSec; + wf.Samples.wValidBitsPerSample = /*(format == ma_format_s24_32) ? 24 :*/ wf.Format.wBitsPerSample; + if (format == ma_format_f32) { + wf.SubFormat = MA_GUID_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT; + } else { + wf.SubFormat = MA_GUID_KSDATAFORMAT_SUBTYPE_PCM; + } + + for (ma_uint32 iSampleRate = 0; iSampleRate < ma_countof(g_maStandardSampleRatePriorities); ++iSampleRate) { + wf.Format.nSamplesPerSec = g_maStandardSampleRatePriorities[iSampleRate]; + + hr = ma_IAudioClient_IsFormatSupported((ma_IAudioClient*)pAudioClient, MA_AUDCLNT_SHAREMODE_EXCLUSIVE, (WAVEFORMATEX*)&wf, NULL); + if (SUCCEEDED(hr)) { + ma_set_device_info_from_WAVEFORMATEX((WAVEFORMATEX*)&wf, pInfo); + found = MA_TRUE; + break; + } + } + + if (found) { + break; + } + } + + if (!found) { + ma_IPropertyStore_Release(pProperties); + return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to find suitable device format for device info retrieval.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + } + } else { + ma_IPropertyStore_Release(pProperties); + return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to retrieve device format for device info retrieval.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + } else { + return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to open property store for device info retrieval.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + + return MA_SUCCESS; +#else + // Exclusive mode not fully supported in UWP right now. + return MA_ERROR; +#endif + } +} + +#ifdef MA_WIN32_DESKTOP +ma_result ma_context_get_MMDevice__wasapi(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_IMMDevice** ppMMDevice) +{ + ma_assert(pContext != NULL); + ma_assert(ppMMDevice != NULL); + + ma_IMMDeviceEnumerator* pDeviceEnumerator; + HRESULT hr = ma_CoCreateInstance(pContext, MA_CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, MA_IID_IMMDeviceEnumerator, (void**)&pDeviceEnumerator); + if (FAILED(hr)) { + return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create IMMDeviceEnumerator.", MA_FAILED_TO_INIT_BACKEND); + } + + if (pDeviceID == NULL) { + hr = ma_IMMDeviceEnumerator_GetDefaultAudioEndpoint(pDeviceEnumerator, (deviceType == ma_device_type_playback) ? ma_eRender : ma_eCapture, ma_eConsole, ppMMDevice); + } else { + hr = ma_IMMDeviceEnumerator_GetDevice(pDeviceEnumerator, pDeviceID->wasapi, ppMMDevice); + } + + ma_IMMDeviceEnumerator_Release(pDeviceEnumerator); + if (FAILED(hr)) { + return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to retrieve IMMDevice.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + + return MA_SUCCESS; +} + +ma_result ma_context_get_device_info_from_MMDevice__wasapi(ma_context* pContext, ma_IMMDevice* pMMDevice, ma_share_mode shareMode, ma_bool32 onlySimpleInfo, ma_device_info* pInfo) +{ + ma_assert(pContext != NULL); + ma_assert(pMMDevice != NULL); + ma_assert(pInfo != NULL); + + // ID. + LPWSTR id; + HRESULT hr = ma_IMMDevice_GetId(pMMDevice, &id); + if (SUCCEEDED(hr)) { + size_t idlen = wcslen(id); + if (idlen+1 > ma_countof(pInfo->id.wasapi)) { + ma_CoTaskMemFree(pContext, id); + ma_assert(MA_FALSE); // NOTE: If this is triggered, please report it. It means the format of the ID must haved change and is too long to fit in our fixed sized buffer. + return MA_ERROR; + } + + ma_copy_memory(pInfo->id.wasapi, id, idlen * sizeof(wchar_t)); + pInfo->id.wasapi[idlen] = '\0'; + + ma_CoTaskMemFree(pContext, id); + } + + { + ma_IPropertyStore *pProperties; + hr = ma_IMMDevice_OpenPropertyStore(pMMDevice, STGM_READ, &pProperties); + if (SUCCEEDED(hr)) { + PROPVARIANT var; + + // Description / Friendly Name + ma_PropVariantInit(&var); + hr = ma_IPropertyStore_GetValue(pProperties, &MA_PKEY_Device_FriendlyName, &var); + if (SUCCEEDED(hr)) { + WideCharToMultiByte(CP_UTF8, 0, var.pwszVal, -1, pInfo->name, sizeof(pInfo->name), 0, FALSE); + ma_PropVariantClear(pContext, &var); + } + + ma_IPropertyStore_Release(pProperties); + } + } + + // Format + if (!onlySimpleInfo) { + ma_IAudioClient* pAudioClient; + hr = ma_IMMDevice_Activate(pMMDevice, &MA_IID_IAudioClient, CLSCTX_ALL, NULL, (void**)&pAudioClient); + if (SUCCEEDED(hr)) { + ma_result result = ma_context_get_device_info_from_IAudioClient__wasapi(pContext, pMMDevice, pAudioClient, shareMode, pInfo); + + ma_IAudioClient_Release(pAudioClient); + return result; + } else { + return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to activate audio client for device info retrieval.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + } + + return MA_SUCCESS; +} + +ma_result ma_context_enumerate_device_collection__wasapi(ma_context* pContext, ma_IMMDeviceCollection* pDeviceCollection, ma_device_type deviceType, ma_enum_devices_callback_proc callback, void* pUserData) +{ + ma_assert(pContext != NULL); + ma_assert(callback != NULL); + + UINT deviceCount; + HRESULT hr = ma_IMMDeviceCollection_GetCount(pDeviceCollection, &deviceCount); + if (FAILED(hr)) { + return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to get playback device count.", MA_NO_DEVICE); + } + + for (ma_uint32 iDevice = 0; iDevice < deviceCount; ++iDevice) { + ma_device_info deviceInfo; + ma_zero_object(&deviceInfo); + + ma_IMMDevice* pMMDevice; + hr = ma_IMMDeviceCollection_Item(pDeviceCollection, iDevice, &pMMDevice); + if (SUCCEEDED(hr)) { + ma_result result = ma_context_get_device_info_from_MMDevice__wasapi(pContext, pMMDevice, ma_share_mode_shared, MA_TRUE, &deviceInfo); // MA_TRUE = onlySimpleInfo. + + ma_IMMDevice_Release(pMMDevice); + if (result == MA_SUCCESS) { + ma_bool32 cbResult = callback(pContext, deviceType, &deviceInfo, pUserData); + if (cbResult == MA_FALSE) { + break; + } + } + } + } + + return MA_SUCCESS; +} +#endif + +#ifdef MA_WIN32_DESKTOP +ma_result ma_context_get_IAudioClient_Desktop__wasapi(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_IAudioClient** ppAudioClient, ma_IMMDevice** ppMMDevice) +{ + ma_result result; + HRESULT hr; + + ma_assert(pContext != NULL); + ma_assert(ppAudioClient != NULL); + ma_assert(ppMMDevice != NULL); + + result = ma_context_get_MMDevice__wasapi(pContext, deviceType, pDeviceID, ppMMDevice); + if (result != MA_SUCCESS) { + return result; + } + + hr = ma_IMMDevice_Activate(*ppMMDevice, &MA_IID_IAudioClient, CLSCTX_ALL, NULL, (void**)ppAudioClient); + if (FAILED(hr)) { + return MA_FAILED_TO_OPEN_BACKEND_DEVICE; + } + + return MA_SUCCESS; +} +#else +ma_result ma_context_get_IAudioClient_UWP__wasapi(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_IAudioClient** ppAudioClient, ma_IUnknown** ppActivatedInterface) +{ + ma_assert(pContext != NULL); + ma_assert(ppAudioClient != NULL); + + ma_IActivateAudioInterfaceAsyncOperation *pAsyncOp = NULL; + ma_completion_handler_uwp completionHandler; + + IID iid; + if (pDeviceID != NULL) { + ma_copy_memory(&iid, pDeviceID->wasapi, sizeof(iid)); + } else { + if (deviceType == ma_device_type_playback) { + iid = MA_IID_DEVINTERFACE_AUDIO_RENDER; + } else { + iid = MA_IID_DEVINTERFACE_AUDIO_CAPTURE; + } + } + + LPOLESTR iidStr; +#if defined(__cplusplus) + HRESULT hr = StringFromIID(iid, &iidStr); +#else + HRESULT hr = StringFromIID(&iid, &iidStr); +#endif + if (FAILED(hr)) { + return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to convert device IID to string for ActivateAudioInterfaceAsync(). Out of memory.", MA_OUT_OF_MEMORY); + } + + ma_result result = ma_completion_handler_uwp_init(&completionHandler); + if (result != MA_SUCCESS) { + ma_CoTaskMemFree(pContext, iidStr); + return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create event for waiting for ActivateAudioInterfaceAsync().", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + +#if defined(__cplusplus) + hr = ActivateAudioInterfaceAsync(iidStr, MA_IID_IAudioClient, NULL, (IActivateAudioInterfaceCompletionHandler*)&completionHandler, (IActivateAudioInterfaceAsyncOperation**)&pAsyncOp); +#else + hr = ActivateAudioInterfaceAsync(iidStr, &MA_IID_IAudioClient, NULL, (IActivateAudioInterfaceCompletionHandler*)&completionHandler, (IActivateAudioInterfaceAsyncOperation**)&pAsyncOp); +#endif + if (FAILED(hr)) { + ma_completion_handler_uwp_uninit(&completionHandler); + ma_CoTaskMemFree(pContext, iidStr); + return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[WASAPI] ActivateAudioInterfaceAsync() failed.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + + ma_CoTaskMemFree(pContext, iidStr); + + // Wait for the async operation for finish. + ma_completion_handler_uwp_wait(&completionHandler); + ma_completion_handler_uwp_uninit(&completionHandler); + + HRESULT activateResult; + ma_IUnknown* pActivatedInterface; + hr = ma_IActivateAudioInterfaceAsyncOperation_GetActivateResult(pAsyncOp, &activateResult, &pActivatedInterface); + ma_IActivateAudioInterfaceAsyncOperation_Release(pAsyncOp); + + if (FAILED(hr) || FAILED(activateResult)) { + return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to activate device.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + + // Here is where we grab the IAudioClient interface. + hr = ma_IUnknown_QueryInterface(pActivatedInterface, &MA_IID_IAudioClient, (void**)ppAudioClient); + if (FAILED(hr)) { + return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to query IAudioClient interface.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + + if (ppActivatedInterface) { + *ppActivatedInterface = pActivatedInterface; + } else { + ma_IUnknown_Release(pActivatedInterface); + } + + return MA_SUCCESS; +} +#endif + +ma_result ma_context_get_IAudioClient__wasapi(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_IAudioClient** ppAudioClient, ma_WASAPIDeviceInterface** ppDeviceInterface) +{ +#ifdef MA_WIN32_DESKTOP + return ma_context_get_IAudioClient_Desktop__wasapi(pContext, deviceType, pDeviceID, ppAudioClient, ppDeviceInterface); +#else + return ma_context_get_IAudioClient_UWP__wasapi(pContext, deviceType, pDeviceID, ppAudioClient, ppDeviceInterface); +#endif +} + + +ma_result ma_context_enumerate_devices__wasapi(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData) +{ + ma_assert(pContext != NULL); + ma_assert(callback != NULL); + + // Different enumeration for desktop and UWP. +#ifdef MA_WIN32_DESKTOP + // Desktop + ma_IMMDeviceEnumerator* pDeviceEnumerator; + HRESULT hr = ma_CoCreateInstance(pContext, MA_CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, MA_IID_IMMDeviceEnumerator, (void**)&pDeviceEnumerator); + if (FAILED(hr)) { + return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create device enumerator.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + + ma_IMMDeviceCollection* pDeviceCollection; + + // Playback. + hr = ma_IMMDeviceEnumerator_EnumAudioEndpoints(pDeviceEnumerator, ma_eRender, MA_MM_DEVICE_STATE_ACTIVE, &pDeviceCollection); + if (SUCCEEDED(hr)) { + ma_context_enumerate_device_collection__wasapi(pContext, pDeviceCollection, ma_device_type_playback, callback, pUserData); + ma_IMMDeviceCollection_Release(pDeviceCollection); + } + + // Capture. + hr = ma_IMMDeviceEnumerator_EnumAudioEndpoints(pDeviceEnumerator, ma_eCapture, MA_MM_DEVICE_STATE_ACTIVE, &pDeviceCollection); + if (SUCCEEDED(hr)) { + ma_context_enumerate_device_collection__wasapi(pContext, pDeviceCollection, ma_device_type_capture, callback, pUserData); + ma_IMMDeviceCollection_Release(pDeviceCollection); + } + + ma_IMMDeviceEnumerator_Release(pDeviceEnumerator); +#else + // UWP + // + // The MMDevice API is only supported on desktop applications. For now, while I'm still figuring out how to properly enumerate + // over devices without using MMDevice, I'm restricting devices to defaults. + // + // Hint: DeviceInformation::FindAllAsync() with DeviceClass.AudioCapture/AudioRender. https://blogs.windows.com/buildingapps/2014/05/15/real-time-audio-in-windows-store-and-windows-phone-apps/ + if (callback) { + ma_bool32 cbResult = MA_TRUE; + + // Playback. + if (cbResult) { + ma_device_info deviceInfo; + ma_zero_object(&deviceInfo); + ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); + cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData); + } + + // Capture. + if (cbResult) { + ma_device_info deviceInfo; + ma_zero_object(&deviceInfo); + ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); + cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData); + } + } +#endif + + return MA_SUCCESS; +} + +ma_result ma_context_get_device_info__wasapi(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_share_mode shareMode, ma_device_info* pDeviceInfo) +{ +#ifdef MA_WIN32_DESKTOP + ma_IMMDevice* pMMDevice = NULL; + ma_result result = ma_context_get_MMDevice__wasapi(pContext, deviceType, pDeviceID, &pMMDevice); + if (result != MA_SUCCESS) { + return result; + } + + result = ma_context_get_device_info_from_MMDevice__wasapi(pContext, pMMDevice, shareMode, MA_FALSE, pDeviceInfo); // MA_FALSE = !onlySimpleInfo. + + ma_IMMDevice_Release(pMMDevice); + return result; +#else + // UWP currently only uses default devices. + if (deviceType == ma_device_type_playback) { + ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); + } else { + ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); + } + + // Not currently supporting exclusive mode on UWP. + if (shareMode == ma_share_mode_exclusive) { + return MA_ERROR; + } + + ma_IAudioClient* pAudioClient; + ma_result result = ma_context_get_IAudioClient_UWP__wasapi(pContext, deviceType, pDeviceID, &pAudioClient, NULL); + if (result != MA_SUCCESS) { + return result; + } + + result = ma_context_get_device_info_from_IAudioClient__wasapi(pContext, NULL, pAudioClient, shareMode, pDeviceInfo); + + ma_IAudioClient_Release(pAudioClient); + return result; +#endif +} + +void ma_device_uninit__wasapi(ma_device* pDevice) +{ + ma_assert(pDevice != NULL); + +#ifdef MA_WIN32_DESKTOP + if (pDevice->wasapi.pDeviceEnumerator) { + ((ma_IMMDeviceEnumerator*)pDevice->wasapi.pDeviceEnumerator)->lpVtbl->UnregisterEndpointNotificationCallback((ma_IMMDeviceEnumerator*)pDevice->wasapi.pDeviceEnumerator, &pDevice->wasapi.notificationClient); + ma_IMMDeviceEnumerator_Release((ma_IMMDeviceEnumerator*)pDevice->wasapi.pDeviceEnumerator); + } +#endif + + if (pDevice->wasapi.pRenderClient) { + ma_IAudioRenderClient_Release((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient); + } + if (pDevice->wasapi.pCaptureClient) { + ma_IAudioCaptureClient_Release((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient); + } + + if (pDevice->wasapi.pAudioClientPlayback) { + ma_IAudioClient_Release((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback); + } + if (pDevice->wasapi.pAudioClientCapture) { + ma_IAudioClient_Release((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture); + } + + if (pDevice->wasapi.hEventPlayback) { + CloseHandle(pDevice->wasapi.hEventPlayback); + } + if (pDevice->wasapi.hEventCapture) { + CloseHandle(pDevice->wasapi.hEventCapture); + } +} + + +typedef struct +{ + // Input. + ma_format formatIn; + ma_uint32 channelsIn; + ma_uint32 sampleRateIn; + ma_channel channelMapIn[MA_MAX_CHANNELS]; + ma_uint32 bufferSizeInFramesIn; + ma_uint32 bufferSizeInMillisecondsIn; + ma_uint32 periodsIn; + ma_bool32 usingDefaultFormat; + ma_bool32 usingDefaultChannels; + ma_bool32 usingDefaultSampleRate; + ma_bool32 usingDefaultChannelMap; + ma_share_mode shareMode; + + // Output. + ma_IAudioClient* pAudioClient; + ma_IAudioRenderClient* pRenderClient; + ma_IAudioCaptureClient* pCaptureClient; + ma_format formatOut; + ma_uint32 channelsOut; + ma_uint32 sampleRateOut; + ma_channel channelMapOut[MA_MAX_CHANNELS]; + ma_uint32 bufferSizeInFramesOut; + ma_uint32 periodSizeInFramesOut; + ma_uint32 periodsOut; + char deviceName[256]; +} ma_device_init_internal_data__wasapi; + +ma_result ma_device_init_internal__wasapi(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_init_internal_data__wasapi* pData) +{ + (void)pContext; + + ma_assert(pContext != NULL); + ma_assert(pData != NULL); + + /* This function is only used to initialize one device type: either playback or capture. Never full-duplex. */ + if (deviceType == ma_device_type_duplex) { + return MA_INVALID_ARGS; + } + + pData->pAudioClient = NULL; + pData->pRenderClient = NULL; + pData->pCaptureClient = NULL; + + + HRESULT hr; + ma_result result = MA_SUCCESS; + const char* errorMsg = ""; + MA_AUDCLNT_SHAREMODE shareMode = MA_AUDCLNT_SHAREMODE_SHARED; + MA_REFERENCE_TIME bufferDurationInMicroseconds; + ma_bool32 wasInitializedUsingIAudioClient3 = MA_FALSE; + WAVEFORMATEXTENSIBLE wf; + ma_WASAPIDeviceInterface* pDeviceInterface = NULL; + + result = ma_context_get_IAudioClient__wasapi(pContext, deviceType, pDeviceID, &pData->pAudioClient, &pDeviceInterface); + if (result != MA_SUCCESS) { + goto done; + } + + + // Try enabling hardware offloading. + ma_IAudioClient2* pAudioClient2; + hr = ma_IAudioClient_QueryInterface(pData->pAudioClient, &MA_IID_IAudioClient2, (void**)&pAudioClient2); + if (SUCCEEDED(hr)) { + BOOL isHardwareOffloadingSupported = 0; + hr = ma_IAudioClient2_IsOffloadCapable(pAudioClient2, MA_AudioCategory_Other, &isHardwareOffloadingSupported); + if (SUCCEEDED(hr) && isHardwareOffloadingSupported) { + ma_AudioClientProperties clientProperties; + ma_zero_object(&clientProperties); + clientProperties.cbSize = sizeof(clientProperties); + clientProperties.bIsOffload = 1; + clientProperties.eCategory = MA_AudioCategory_Other; + ma_IAudioClient2_SetClientProperties(pAudioClient2, &clientProperties); + } + } + + + // Here is where we try to determine the best format to use with the device. If the client if wanting exclusive mode, first try finding the best format for that. If this fails, fall back to shared mode. + result = MA_FORMAT_NOT_SUPPORTED; + if (pData->shareMode == ma_share_mode_exclusive) { + #ifdef MA_WIN32_DESKTOP + // In exclusive mode on desktop we always use the backend's native format. + ma_IPropertyStore* pStore = NULL; + hr = ma_IMMDevice_OpenPropertyStore(pDeviceInterface, STGM_READ, &pStore); + if (SUCCEEDED(hr)) { + PROPVARIANT prop; + ma_PropVariantInit(&prop); + hr = ma_IPropertyStore_GetValue(pStore, &MA_PKEY_AudioEngine_DeviceFormat, &prop); + if (SUCCEEDED(hr)) { + WAVEFORMATEX* pActualFormat = (WAVEFORMATEX*)prop.blob.pBlobData; + hr = ma_IAudioClient_IsFormatSupported((ma_IAudioClient*)pData->pAudioClient, MA_AUDCLNT_SHAREMODE_EXCLUSIVE, pActualFormat, NULL); + if (SUCCEEDED(hr)) { + ma_copy_memory(&wf, pActualFormat, sizeof(WAVEFORMATEXTENSIBLE)); + } + + ma_PropVariantClear(pContext, &prop); + } + + ma_IPropertyStore_Release(pStore); + } + #else + // I do not know how to query the device's native format on UWP so for now I'm just disabling support for + // exclusive mode. The alternative is to enumerate over different formats and check IsFormatSupported() + // until you find one that works. + // + // TODO: Add support for exclusive mode to UWP. + hr = S_FALSE; + #endif + + if (hr == S_OK) { + shareMode = MA_AUDCLNT_SHAREMODE_EXCLUSIVE; + result = MA_SUCCESS; + } else { + result = MA_SHARE_MODE_NOT_SUPPORTED; + } + } else { + // In shared mode we are always using the format reported by the operating system. + WAVEFORMATEXTENSIBLE* pNativeFormat = NULL; + hr = ma_IAudioClient_GetMixFormat((ma_IAudioClient*)pData->pAudioClient, (WAVEFORMATEX**)&pNativeFormat); + if (hr != S_OK) { + result = MA_FORMAT_NOT_SUPPORTED; + } else { + ma_copy_memory(&wf, pNativeFormat, sizeof(wf)); + result = MA_SUCCESS; + } + + ma_CoTaskMemFree(pContext, pNativeFormat); + + shareMode = MA_AUDCLNT_SHAREMODE_SHARED; + } + + // Return an error if we still haven't found a format. + if (result != MA_SUCCESS) { + errorMsg = "[WASAPI] Failed to find best device mix format."; + goto done; + } + + pData->formatOut = ma_format_from_WAVEFORMATEX((WAVEFORMATEX*)&wf); + pData->channelsOut = wf.Format.nChannels; + pData->sampleRateOut = wf.Format.nSamplesPerSec; + + // Get the internal channel map based on the channel mask. + ma_channel_mask_to_channel_map__win32(wf.dwChannelMask, pData->channelsOut, pData->channelMapOut); + + // If we're using a default buffer size we need to calculate it based on the efficiency of the system. + pData->periodsOut = pData->periodsIn; + pData->bufferSizeInFramesOut = pData->bufferSizeInFramesIn; + if (pData->bufferSizeInFramesOut == 0) { + pData->bufferSizeInFramesOut = ma_calculate_buffer_size_in_frames_from_milliseconds(pData->bufferSizeInMillisecondsIn, pData->sampleRateOut); + } + + bufferDurationInMicroseconds = ((ma_uint64)pData->bufferSizeInFramesOut * 1000 * 1000) / pData->sampleRateOut; + + + // Slightly different initialization for shared and exclusive modes. We try exclusive mode first, and if it fails, fall back to shared mode. + if (shareMode == MA_AUDCLNT_SHAREMODE_EXCLUSIVE) { + MA_REFERENCE_TIME bufferDuration = (bufferDurationInMicroseconds / pData->periodsOut) * 10; + + // If the periodicy is too small, Initialize() will fail with AUDCLNT_E_INVALID_DEVICE_PERIOD. In this case we should just keep increasing + // it and trying it again. + hr = E_FAIL; + for (;;) { + hr = ma_IAudioClient_Initialize((ma_IAudioClient*)pData->pAudioClient, shareMode, MA_AUDCLNT_STREAMFLAGS_EVENTCALLBACK, bufferDuration, bufferDuration, (WAVEFORMATEX*)&wf, NULL); + if (hr == MA_AUDCLNT_E_INVALID_DEVICE_PERIOD) { + if (bufferDuration > 500*10000) { + break; + } else { + if (bufferDuration == 0) { // <-- Just a sanity check to prevent an infinit loop. Should never happen, but it makes me feel better. + break; + } + + bufferDuration = bufferDuration * 2; + continue; + } + } else { + break; + } + } + + if (hr == MA_AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED) { + UINT bufferSizeInFrames; + hr = ma_IAudioClient_GetBufferSize((ma_IAudioClient*)pData->pAudioClient, &bufferSizeInFrames); + if (SUCCEEDED(hr)) { + bufferDuration = (MA_REFERENCE_TIME)((10000.0 * 1000 / wf.Format.nSamplesPerSec * bufferSizeInFrames) + 0.5); + + // Unfortunately we need to release and re-acquire the audio client according to MSDN. Seems silly - why not just call IAudioClient_Initialize() again?! + ma_IAudioClient_Release((ma_IAudioClient*)pData->pAudioClient); + + #ifdef MA_WIN32_DESKTOP + hr = ma_IMMDevice_Activate(pDeviceInterface, &MA_IID_IAudioClient, CLSCTX_ALL, NULL, (void**)&pData->pAudioClient); + #else + hr = ma_IUnknown_QueryInterface(pDeviceInterface, &MA_IID_IAudioClient, (void**)&pData->pAudioClient); + #endif + + if (SUCCEEDED(hr)) { + hr = ma_IAudioClient_Initialize((ma_IAudioClient*)pData->pAudioClient, shareMode, MA_AUDCLNT_STREAMFLAGS_EVENTCALLBACK, bufferDuration, bufferDuration, (WAVEFORMATEX*)&wf, NULL); + } + } + } + + if (FAILED(hr)) { + /* Failed to initialize in exclusive mode. Don't fall back to shared mode - instead tell the client about it. They can reinitialize in shared mode if they want. */ + if (hr == E_ACCESSDENIED) { + errorMsg = "[WASAPI] Failed to initialize device in exclusive mode. Access denied.", result = MA_ACCESS_DENIED; + } else if (hr == MA_AUDCLNT_E_DEVICE_IN_USE) { + errorMsg = "[WASAPI] Failed to initialize device in exclusive mode. Device in use.", result = MA_DEVICE_BUSY; + } else { + errorMsg = "[WASAPI] Failed to initialize device in exclusive mode."; result = MA_SHARE_MODE_NOT_SUPPORTED; + } + goto done; + } + } + + if (shareMode == MA_AUDCLNT_SHAREMODE_SHARED) { + /* Low latency shared mode via IAudioClient3. */ +#ifndef MA_WASAPI_NO_LOW_LATENCY_SHARED_MODE + ma_IAudioClient3* pAudioClient3 = NULL; + hr = ma_IAudioClient_QueryInterface(pData->pAudioClient, &MA_IID_IAudioClient3, (void**)&pAudioClient3); + if (SUCCEEDED(hr)) { + UINT32 defaultPeriodInFrames; + UINT32 fundamentalPeriodInFrames; + UINT32 minPeriodInFrames; + UINT32 maxPeriodInFrames; + hr = ma_IAudioClient3_GetSharedModeEnginePeriod(pAudioClient3, (WAVEFORMATEX*)&wf, &defaultPeriodInFrames, &fundamentalPeriodInFrames, &minPeriodInFrames, &maxPeriodInFrames); + if (SUCCEEDED(hr)) { + UINT32 desiredPeriodInFrames = pData->bufferSizeInFramesOut / pData->periodsOut; + UINT32 actualPeriodInFrames = desiredPeriodInFrames; + + /* Make sure the period size is a multiple of fundamentalPeriodInFrames. */ + actualPeriodInFrames = actualPeriodInFrames / fundamentalPeriodInFrames; + actualPeriodInFrames = actualPeriodInFrames * fundamentalPeriodInFrames; + + /* The period needs to be clamped between minPeriodInFrames and maxPeriodInFrames. */ + actualPeriodInFrames = ma_clamp(actualPeriodInFrames, minPeriodInFrames, maxPeriodInFrames); + + /* If the client requested a largish buffer than we don't actually want to use low latency shared mode because it forces small buffers. */ + if (actualPeriodInFrames >= desiredPeriodInFrames) { + hr = ma_IAudioClient3_InitializeSharedAudioStream(pAudioClient3, MA_AUDCLNT_STREAMFLAGS_EVENTCALLBACK, actualPeriodInFrames, (WAVEFORMATEX*)&wf, NULL); + if (SUCCEEDED(hr)) { + wasInitializedUsingIAudioClient3 = MA_TRUE; + pData->periodSizeInFramesOut = actualPeriodInFrames; + pData->bufferSizeInFramesOut = actualPeriodInFrames * pData->periodsOut; + } + } + } + + ma_IAudioClient3_Release(pAudioClient3); + pAudioClient3 = NULL; + } +#endif + + // If we don't have an IAudioClient3 then we need to use the normal initialization routine. + if (!wasInitializedUsingIAudioClient3) { + MA_REFERENCE_TIME bufferDuration = bufferDurationInMicroseconds*10; + hr = ma_IAudioClient_Initialize((ma_IAudioClient*)pData->pAudioClient, shareMode, MA_AUDCLNT_STREAMFLAGS_EVENTCALLBACK, bufferDuration, 0, (WAVEFORMATEX*)&wf, NULL); + if (FAILED(hr)) { + if (hr == E_ACCESSDENIED) { + errorMsg = "[WASAPI] Failed to initialize device. Access denied.", result = MA_ACCESS_DENIED; + } else if (hr == MA_AUDCLNT_E_DEVICE_IN_USE) { + errorMsg = "[WASAPI] Failed to initialize device. Device in use.", result = MA_DEVICE_BUSY; + } else { + errorMsg = "[WASAPI] Failed to initialize device.", result = MA_FAILED_TO_OPEN_BACKEND_DEVICE; + } + + goto done; + } + } + } + + if (!wasInitializedUsingIAudioClient3) { + hr = ma_IAudioClient_GetBufferSize((ma_IAudioClient*)pData->pAudioClient, &pData->bufferSizeInFramesOut); + if (FAILED(hr)) { + errorMsg = "[WASAPI] Failed to get audio client's actual buffer size.", result = MA_FAILED_TO_OPEN_BACKEND_DEVICE; + goto done; + } + + pData->periodSizeInFramesOut = pData->bufferSizeInFramesOut / pData->periodsOut; + } + + if (deviceType == ma_device_type_playback) { + hr = ma_IAudioClient_GetService((ma_IAudioClient*)pData->pAudioClient, &MA_IID_IAudioRenderClient, (void**)&pData->pRenderClient); + } else { + hr = ma_IAudioClient_GetService((ma_IAudioClient*)pData->pAudioClient, &MA_IID_IAudioCaptureClient, (void**)&pData->pCaptureClient); + } + + if (FAILED(hr)) { + errorMsg = "[WASAPI] Failed to get audio client service.", result = MA_API_NOT_FOUND; + goto done; + } + + + // Grab the name of the device. +#ifdef MA_WIN32_DESKTOP + ma_IPropertyStore *pProperties; + hr = ma_IMMDevice_OpenPropertyStore(pDeviceInterface, STGM_READ, &pProperties); + if (SUCCEEDED(hr)) { + PROPVARIANT varName; + ma_PropVariantInit(&varName); + hr = ma_IPropertyStore_GetValue(pProperties, &MA_PKEY_Device_FriendlyName, &varName); + if (SUCCEEDED(hr)) { + WideCharToMultiByte(CP_UTF8, 0, varName.pwszVal, -1, pData->deviceName, sizeof(pData->deviceName), 0, FALSE); + ma_PropVariantClear(pContext, &varName); + } + + ma_IPropertyStore_Release(pProperties); + } +#endif + +done: + // Clean up. +#ifdef MA_WIN32_DESKTOP + if (pDeviceInterface != NULL) { + ma_IMMDevice_Release(pDeviceInterface); + } +#else + if (pDeviceInterface != NULL) { + ma_IUnknown_Release(pDeviceInterface); + } +#endif + + if (result != MA_SUCCESS) { + if (pData->pRenderClient) { + ma_IAudioRenderClient_Release((ma_IAudioRenderClient*)pData->pRenderClient); + pData->pRenderClient = NULL; + } + if (pData->pCaptureClient) { + ma_IAudioCaptureClient_Release((ma_IAudioCaptureClient*)pData->pCaptureClient); + pData->pCaptureClient = NULL; + } + if (pData->pAudioClient) { + ma_IAudioClient_Release((ma_IAudioClient*)pData->pAudioClient); + pData->pAudioClient = NULL; + } + + return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, errorMsg, result); + } else { + return MA_SUCCESS; + } +} + +ma_result ma_device_reinit__wasapi(ma_device* pDevice, ma_device_type deviceType) +{ + ma_assert(pDevice != NULL); + + // We only re-initialize the playback or capture device. Never a full-duplex device. + if (deviceType == ma_device_type_duplex) { + return MA_INVALID_ARGS; + } + + ma_device_init_internal_data__wasapi data; + if (deviceType == ma_device_type_capture) { + data.formatIn = pDevice->capture.format; + data.channelsIn = pDevice->capture.channels; + ma_copy_memory(data.channelMapIn, pDevice->capture.channelMap, sizeof(pDevice->capture.channelMap)); + data.shareMode = pDevice->capture.shareMode; + data.usingDefaultFormat = pDevice->capture.usingDefaultFormat; + data.usingDefaultChannels = pDevice->capture.usingDefaultChannels; + data.usingDefaultChannelMap = pDevice->capture.usingDefaultChannelMap; + } else { + data.formatIn = pDevice->playback.format; + data.channelsIn = pDevice->playback.channels; + ma_copy_memory(data.channelMapIn, pDevice->playback.channelMap, sizeof(pDevice->playback.channelMap)); + data.shareMode = pDevice->playback.shareMode; + data.usingDefaultFormat = pDevice->playback.usingDefaultFormat; + data.usingDefaultChannels = pDevice->playback.usingDefaultChannels; + data.usingDefaultChannelMap = pDevice->playback.usingDefaultChannelMap; + } + + data.sampleRateIn = pDevice->sampleRate; + data.usingDefaultSampleRate = pDevice->usingDefaultSampleRate; + data.bufferSizeInFramesIn = pDevice->wasapi.originalBufferSizeInFrames; + data.bufferSizeInMillisecondsIn = pDevice->wasapi.originalBufferSizeInMilliseconds; + data.periodsIn = pDevice->wasapi.originalPeriods; + ma_result result = ma_device_init_internal__wasapi(pDevice->pContext, deviceType, NULL, &data); + if (result != MA_SUCCESS) { + return result; + } + + // At this point we have some new objects ready to go. We need to uninitialize the previous ones and then set the new ones. + if (deviceType == ma_device_type_capture) { + if (pDevice->wasapi.pCaptureClient) { + ma_IAudioCaptureClient_Release((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient); + pDevice->wasapi.pCaptureClient = NULL; + } + + if (pDevice->wasapi.pAudioClientCapture) { + ma_IAudioClient_Release((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture); + pDevice->wasapi.pAudioClientCapture = NULL; + } + + pDevice->wasapi.pAudioClientCapture = data.pAudioClient; + pDevice->wasapi.pCaptureClient = data.pCaptureClient; + + pDevice->capture.internalFormat = data.formatOut; + pDevice->capture.internalChannels = data.channelsOut; + pDevice->capture.internalSampleRate = data.sampleRateOut; + ma_copy_memory(pDevice->capture.internalChannelMap, data.channelMapOut, sizeof(data.channelMapOut)); + pDevice->capture.internalBufferSizeInFrames = data.bufferSizeInFramesOut; + pDevice->capture.internalPeriods = data.periodsOut; + ma_strcpy_s(pDevice->capture.name, sizeof(pDevice->capture.name), data.deviceName); + + ma_IAudioClient_SetEventHandle((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture, pDevice->wasapi.hEventCapture); + + pDevice->wasapi.periodSizeInFramesCapture = data.periodSizeInFramesOut; + ma_IAudioClient_GetBufferSize((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture, &pDevice->wasapi.actualBufferSizeInFramesCapture); + + /* The device may be in a started state. If so we need to immediately restart it. */ + if (pDevice->wasapi.isStartedCapture) { + HRESULT hr = ma_IAudioClient_Start((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture); + if (FAILED(hr)) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to start internal capture device after reinitialization.", MA_FAILED_TO_START_BACKEND_DEVICE); + } + } + } + + if (deviceType == ma_device_type_playback) { + if (pDevice->wasapi.pRenderClient) { + ma_IAudioRenderClient_Release((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient); + pDevice->wasapi.pRenderClient = NULL; + } + + if (pDevice->wasapi.pAudioClientPlayback) { + ma_IAudioClient_Release((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback); + pDevice->wasapi.pAudioClientPlayback = NULL; + } + + pDevice->wasapi.pAudioClientPlayback = data.pAudioClient; + pDevice->wasapi.pRenderClient = data.pRenderClient; + + pDevice->playback.internalFormat = data.formatOut; + pDevice->playback.internalChannels = data.channelsOut; + pDevice->playback.internalSampleRate = data.sampleRateOut; + ma_copy_memory(pDevice->playback.internalChannelMap, data.channelMapOut, sizeof(data.channelMapOut)); + pDevice->playback.internalBufferSizeInFrames = data.bufferSizeInFramesOut; + pDevice->playback.internalPeriods = data.periodsOut; + ma_strcpy_s(pDevice->playback.name, sizeof(pDevice->playback.name), data.deviceName); + + ma_IAudioClient_SetEventHandle((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback, pDevice->wasapi.hEventPlayback); + + pDevice->wasapi.periodSizeInFramesPlayback = data.periodSizeInFramesOut; + ma_IAudioClient_GetBufferSize((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback, &pDevice->wasapi.actualBufferSizeInFramesPlayback); + + /* The device may be in a started state. If so we need to immediately restart it. */ + if (pDevice->wasapi.isStartedPlayback) { + HRESULT hr = ma_IAudioClient_Start((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback); + if (FAILED(hr)) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to start internal playback device after reinitialization.", MA_FAILED_TO_START_BACKEND_DEVICE); + } + } + } + + return MA_SUCCESS; +} + +ma_result ma_device_init__wasapi(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice) +{ + ma_result result = MA_SUCCESS; + + (void)pContext; + + ma_assert(pContext != NULL); + ma_assert(pDevice != NULL); + + ma_zero_object(&pDevice->wasapi); + pDevice->wasapi.originalBufferSizeInFrames = pConfig->bufferSizeInFrames; + pDevice->wasapi.originalBufferSizeInMilliseconds = pConfig->bufferSizeInMilliseconds; + pDevice->wasapi.originalPeriods = pConfig->periods; + + if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) { + ma_device_init_internal_data__wasapi data; + data.formatIn = pConfig->capture.format; + data.channelsIn = pConfig->capture.channels; + data.sampleRateIn = pConfig->sampleRate; + ma_copy_memory(data.channelMapIn, pConfig->capture.channelMap, sizeof(pConfig->capture.channelMap)); + data.usingDefaultFormat = pDevice->capture.usingDefaultFormat; + data.usingDefaultChannels = pDevice->capture.usingDefaultChannels; + data.usingDefaultSampleRate = pDevice->usingDefaultSampleRate; + data.usingDefaultChannelMap = pDevice->capture.usingDefaultChannelMap; + data.shareMode = pConfig->capture.shareMode; + data.bufferSizeInFramesIn = pConfig->bufferSizeInFrames; + data.bufferSizeInMillisecondsIn = pConfig->bufferSizeInMilliseconds; + data.periodsIn = pConfig->periods; + + result = ma_device_init_internal__wasapi(pDevice->pContext, ma_device_type_capture, pConfig->capture.pDeviceID, &data); + if (result != MA_SUCCESS) { + return result; + } + + pDevice->wasapi.pAudioClientCapture = data.pAudioClient; + pDevice->wasapi.pCaptureClient = data.pCaptureClient; + + pDevice->capture.internalFormat = data.formatOut; + pDevice->capture.internalChannels = data.channelsOut; + pDevice->capture.internalSampleRate = data.sampleRateOut; + ma_copy_memory(pDevice->capture.internalChannelMap, data.channelMapOut, sizeof(data.channelMapOut)); + pDevice->capture.internalBufferSizeInFrames = data.bufferSizeInFramesOut; + pDevice->capture.internalPeriods = data.periodsOut; + ma_strcpy_s(pDevice->capture.name, sizeof(pDevice->capture.name), data.deviceName); + + /* + The event for capture needs to be manual reset for the same reason as playback. We keep the initial state set to unsignaled, + however, because we want to block until we actually have something for the first call to ma_device_read(). + */ + pDevice->wasapi.hEventCapture = CreateEventA(NULL, FALSE, FALSE, NULL); /* Auto reset, unsignaled by default. */ + if (pDevice->wasapi.hEventCapture == NULL) { + if (pDevice->wasapi.pCaptureClient != NULL) { + ma_IAudioCaptureClient_Release((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient); + pDevice->wasapi.pCaptureClient = NULL; + } + if (pDevice->wasapi.pAudioClientCapture != NULL) { + ma_IAudioClient_Release((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture); + pDevice->wasapi.pAudioClientCapture = NULL; + } + + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create event for capture.", MA_FAILED_TO_CREATE_EVENT); + } + ma_IAudioClient_SetEventHandle((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture, pDevice->wasapi.hEventCapture); + + pDevice->wasapi.periodSizeInFramesCapture = data.periodSizeInFramesOut; + ma_IAudioClient_GetBufferSize((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture, &pDevice->wasapi.actualBufferSizeInFramesCapture); + } + + if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) { + ma_device_init_internal_data__wasapi data; + data.formatIn = pConfig->playback.format; + data.channelsIn = pConfig->playback.channels; + data.sampleRateIn = pConfig->sampleRate; + ma_copy_memory(data.channelMapIn, pConfig->playback.channelMap, sizeof(pConfig->playback.channelMap)); + data.usingDefaultFormat = pDevice->playback.usingDefaultFormat; + data.usingDefaultChannels = pDevice->playback.usingDefaultChannels; + data.usingDefaultSampleRate = pDevice->usingDefaultSampleRate; + data.usingDefaultChannelMap = pDevice->playback.usingDefaultChannelMap; + data.shareMode = pConfig->playback.shareMode; + data.bufferSizeInFramesIn = pConfig->bufferSizeInFrames; + data.bufferSizeInMillisecondsIn = pConfig->bufferSizeInMilliseconds; + data.periodsIn = pConfig->periods; + + result = ma_device_init_internal__wasapi(pDevice->pContext, ma_device_type_playback, pConfig->playback.pDeviceID, &data); + if (result != MA_SUCCESS) { + if (pConfig->deviceType == ma_device_type_duplex) { + if (pDevice->wasapi.pCaptureClient != NULL) { + ma_IAudioCaptureClient_Release((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient); + pDevice->wasapi.pCaptureClient = NULL; + } + if (pDevice->wasapi.pAudioClientCapture != NULL) { + ma_IAudioClient_Release((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture); + pDevice->wasapi.pAudioClientCapture = NULL; + } + + CloseHandle(pDevice->wasapi.hEventCapture); + pDevice->wasapi.hEventCapture = NULL; + } + return result; + } + + pDevice->wasapi.pAudioClientPlayback = data.pAudioClient; + pDevice->wasapi.pRenderClient = data.pRenderClient; + + pDevice->playback.internalFormat = data.formatOut; + pDevice->playback.internalChannels = data.channelsOut; + pDevice->playback.internalSampleRate = data.sampleRateOut; + ma_copy_memory(pDevice->playback.internalChannelMap, data.channelMapOut, sizeof(data.channelMapOut)); + pDevice->playback.internalBufferSizeInFrames = data.bufferSizeInFramesOut; + pDevice->playback.internalPeriods = data.periodsOut; + ma_strcpy_s(pDevice->playback.name, sizeof(pDevice->playback.name), data.deviceName); + + /* + The event for playback is needs to be manual reset because we want to explicitly control the fact that it becomes signalled + only after the whole available space has been filled, never before. + + The playback event also needs to be initially set to a signaled state so that the first call to ma_device_write() is able + to get passed WaitForMultipleObjects(). + */ + pDevice->wasapi.hEventPlayback = CreateEventA(NULL, FALSE, TRUE, NULL); /* Auto reset, signaled by default. */ + if (pDevice->wasapi.hEventPlayback == NULL) { + if (pConfig->deviceType == ma_device_type_duplex) { + if (pDevice->wasapi.pCaptureClient != NULL) { + ma_IAudioCaptureClient_Release((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient); + pDevice->wasapi.pCaptureClient = NULL; + } + if (pDevice->wasapi.pAudioClientCapture != NULL) { + ma_IAudioClient_Release((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture); + pDevice->wasapi.pAudioClientCapture = NULL; + } + + CloseHandle(pDevice->wasapi.hEventCapture); + pDevice->wasapi.hEventCapture = NULL; + } + + if (pDevice->wasapi.pRenderClient != NULL) { + ma_IAudioRenderClient_Release((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient); + pDevice->wasapi.pRenderClient = NULL; + } + if (pDevice->wasapi.pAudioClientPlayback != NULL) { + ma_IAudioClient_Release((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback); + pDevice->wasapi.pAudioClientPlayback = NULL; + } + + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create event for playback.", MA_FAILED_TO_CREATE_EVENT); + } + ma_IAudioClient_SetEventHandle((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback, pDevice->wasapi.hEventPlayback); + + pDevice->wasapi.periodSizeInFramesPlayback = data.periodSizeInFramesOut; + ma_IAudioClient_GetBufferSize((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback, &pDevice->wasapi.actualBufferSizeInFramesPlayback); + } + + + // We need to get notifications of when the default device changes. We do this through a device enumerator by + // registering a IMMNotificationClient with it. We only care about this if it's the default device. +#ifdef MA_WIN32_DESKTOP + ma_IMMDeviceEnumerator* pDeviceEnumerator; + HRESULT hr = ma_CoCreateInstance(pContext, MA_CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, MA_IID_IMMDeviceEnumerator, (void**)&pDeviceEnumerator); + if (FAILED(hr)) { + ma_device_uninit__wasapi(pDevice); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create device enumerator.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + + pDevice->wasapi.notificationClient.lpVtbl = (void*)&g_maNotificationCientVtbl; + pDevice->wasapi.notificationClient.counter = 1; + pDevice->wasapi.notificationClient.pDevice = pDevice; + + hr = pDeviceEnumerator->lpVtbl->RegisterEndpointNotificationCallback(pDeviceEnumerator, &pDevice->wasapi.notificationClient); + if (SUCCEEDED(hr)) { + pDevice->wasapi.pDeviceEnumerator = (ma_ptr)pDeviceEnumerator; + } else { + // Not the end of the world if we fail to register the notification callback. We just won't support automatic stream routing. + ma_IMMDeviceEnumerator_Release(pDeviceEnumerator); + } +#endif + + ma_atomic_exchange_32(&pDevice->wasapi.isStartedCapture, MA_FALSE); + ma_atomic_exchange_32(&pDevice->wasapi.isStartedPlayback, MA_FALSE); + + return MA_SUCCESS; +} + +ma_result ma_device__get_available_frames__wasapi(ma_device* pDevice, ma_IAudioClient* pAudioClient, ma_uint32* pFrameCount) +{ + ma_assert(pDevice != NULL); + ma_assert(pFrameCount != NULL); + + *pFrameCount = 0; + + if ((ma_ptr)pAudioClient != pDevice->wasapi.pAudioClientPlayback && (ma_ptr)pAudioClient != pDevice->wasapi.pAudioClientCapture) { + return MA_INVALID_OPERATION; + } + + ma_uint32 paddingFramesCount; + HRESULT hr = ma_IAudioClient_GetCurrentPadding(pAudioClient, &paddingFramesCount); + if (FAILED(hr)) { + return MA_DEVICE_UNAVAILABLE; + } + + // Slightly different rules for exclusive and shared modes. + ma_share_mode shareMode = ((ma_ptr)pAudioClient == pDevice->wasapi.pAudioClientPlayback) ? pDevice->playback.shareMode : pDevice->capture.shareMode; + if (shareMode == ma_share_mode_exclusive) { + *pFrameCount = paddingFramesCount; + } else { + if ((ma_ptr)pAudioClient == pDevice->wasapi.pAudioClientPlayback) { + *pFrameCount = pDevice->wasapi.actualBufferSizeInFramesPlayback - paddingFramesCount; + } else { + *pFrameCount = paddingFramesCount; + } + } + + return MA_SUCCESS; +} + +ma_bool32 ma_device_is_reroute_required__wasapi(ma_device* pDevice, ma_device_type deviceType) +{ + ma_assert(pDevice != NULL); + + if (deviceType == ma_device_type_playback) { + return pDevice->wasapi.hasDefaultPlaybackDeviceChanged; + } + + if (deviceType == ma_device_type_capture) { + return pDevice->wasapi.hasDefaultCaptureDeviceChanged; + } + + return MA_FALSE; +} + +ma_result ma_device_reroute__wasapi(ma_device* pDevice, ma_device_type deviceType) +{ + if (deviceType == ma_device_type_duplex) { + return MA_INVALID_ARGS; + } + + if (deviceType == ma_device_type_playback) { + ma_atomic_exchange_32(&pDevice->wasapi.hasDefaultPlaybackDeviceChanged, MA_FALSE); + } + if (deviceType == ma_device_type_capture) { + ma_atomic_exchange_32(&pDevice->wasapi.hasDefaultCaptureDeviceChanged, MA_FALSE); + } + + + #ifdef MA_DEBUG_OUTPUT + printf("=== CHANGING DEVICE ===\n"); + #endif + + ma_result result = ma_device_reinit__wasapi(pDevice, deviceType); + if (result != MA_SUCCESS) { + return result; + } + + ma_device__post_init_setup(pDevice, deviceType); + + return MA_SUCCESS; +} + + +ma_result ma_device_main_loop__wasapi(ma_device* pDevice) +{ + ma_result result; + HRESULT hr; + ma_bool32 exitLoop = MA_FALSE; + ma_uint32 framesWrittenToPlaybackDevice = 0; + ma_uint32 mappedBufferSizeInFramesCapture = 0; + ma_uint32 mappedBufferSizeInFramesPlayback = 0; + ma_uint32 mappedBufferFramesRemainingCapture = 0; + ma_uint32 mappedBufferFramesRemainingPlayback = 0; + BYTE* pMappedBufferCapture = NULL; + BYTE* pMappedBufferPlayback = NULL; + ma_uint32 bpfCapture = ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels); + ma_uint32 bpfPlayback = ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels); + ma_uint8 inputDataInExternalFormat[4096]; + ma_uint32 inputDataInExternalFormatCap = sizeof(inputDataInExternalFormat) / bpfCapture; + ma_uint8 outputDataInExternalFormat[4096]; + ma_uint32 outputDataInExternalFormatCap = sizeof(outputDataInExternalFormat) / bpfPlayback; + + ma_assert(pDevice != NULL); + + /* The playback device needs to be started immediately. */ + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + hr = ma_IAudioClient_Start((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture); + if (FAILED(hr)) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to start internal capture device.", MA_FAILED_TO_START_BACKEND_DEVICE); + } + ma_atomic_exchange_32(&pDevice->wasapi.isStartedCapture, MA_TRUE); + } + + while (ma_device__get_state(pDevice) == MA_STATE_STARTED && !exitLoop) { + /* We may need to reroute the device. */ + if (ma_device_is_reroute_required__wasapi(pDevice, ma_device_type_playback)) { + result = ma_device_reroute__wasapi(pDevice, ma_device_type_playback); + if (result != MA_SUCCESS) { + exitLoop = MA_TRUE; + break; + } + } + if (ma_device_is_reroute_required__wasapi(pDevice, ma_device_type_capture)) { + result = ma_device_reroute__wasapi(pDevice, ma_device_type_capture); + if (result != MA_SUCCESS) { + exitLoop = MA_TRUE; + break; + } + } + + switch (pDevice->type) + { + case ma_device_type_duplex: + { + ma_uint32 framesAvailableCapture; + ma_uint32 framesAvailablePlayback; + DWORD flagsCapture; /* Passed to IAudioCaptureClient_GetBuffer(). */ + + /* The process is to map the playback buffer and fill it as quickly as possible from input data. */ + if (pMappedBufferPlayback == NULL) { + /* WASAPI is weird with exclusive mode. You need to wait on the event _before_ querying the available frames. */ + if (pDevice->playback.shareMode == ma_share_mode_exclusive) { + if (WaitForSingleObject(pDevice->wasapi.hEventPlayback, INFINITE) == WAIT_FAILED) { + return MA_ERROR; /* Wait failed. */ + } + } + + result = ma_device__get_available_frames__wasapi(pDevice, (ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback, &framesAvailablePlayback); + if (result != MA_SUCCESS) { + return result; + } + + //printf("TRACE 1: framesAvailablePlayback=%d\n", framesAvailablePlayback); + + + /* In exclusive mode, the frame count needs to exactly match the value returned by GetCurrentPadding(). */ + if (pDevice->playback.shareMode != ma_share_mode_exclusive) { + if (framesAvailablePlayback >= pDevice->wasapi.periodSizeInFramesPlayback) { + framesAvailablePlayback = pDevice->wasapi.periodSizeInFramesPlayback; + } + } + + /* If there's no frames available in the playback device we need to wait for more. */ + if (framesAvailablePlayback == 0) { + /* In exclusive mode we waited at the top. */ + if (pDevice->playback.shareMode != ma_share_mode_exclusive) { + if (WaitForSingleObject(pDevice->wasapi.hEventPlayback, INFINITE) == WAIT_FAILED) { + return MA_ERROR; /* Wait failed. */ + } + } + + continue; + } + + /* We're ready to map the playback device's buffer. We don't release this until it's been entirely filled. */ + hr = ma_IAudioRenderClient_GetBuffer((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient, framesAvailablePlayback, &pMappedBufferPlayback); + if (FAILED(hr)) { + ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to retrieve internal buffer from playback device in preparation for writing to the device.", MA_FAILED_TO_MAP_DEVICE_BUFFER); + exitLoop = MA_TRUE; + break; + } + + mappedBufferSizeInFramesPlayback = framesAvailablePlayback; + mappedBufferFramesRemainingPlayback = framesAvailablePlayback; + } + + /* At this point we should have a buffer available for output. We need to keep writing input samples to it. */ + for (;;) { + /* Try grabbing some captured data if we haven't already got a mapped buffer. */ + if (pMappedBufferCapture == NULL) { + if (pDevice->capture.shareMode == ma_share_mode_shared) { + if (WaitForSingleObject(pDevice->wasapi.hEventCapture, INFINITE) == WAIT_FAILED) { + return MA_ERROR; /* Wait failed. */ + } + } + + result = ma_device__get_available_frames__wasapi(pDevice, (ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture, &framesAvailableCapture); + if (result != MA_SUCCESS) { + exitLoop = MA_TRUE; + break; + } + + //printf("TRACE 2: framesAvailableCapture=%d\n", framesAvailableCapture); + + /* Wait for more if nothing is available. */ + if (framesAvailableCapture == 0) { + /* In exclusive mode we waited at the top. */ + if (pDevice->capture.shareMode != ma_share_mode_shared) { + if (WaitForSingleObject(pDevice->wasapi.hEventCapture, INFINITE) == WAIT_FAILED) { + return MA_ERROR; /* Wait failed. */ + } + } + + continue; + } + + /* Getting here means there's data available for writing to the output device. */ + mappedBufferSizeInFramesCapture = framesAvailableCapture; + hr = ma_IAudioCaptureClient_GetBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, (BYTE**)&pMappedBufferCapture, &mappedBufferSizeInFramesCapture, &flagsCapture, NULL, NULL); + if (FAILED(hr)) { + ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to retrieve internal buffer from capture device in preparation for writing to the device.", MA_FAILED_TO_MAP_DEVICE_BUFFER); + exitLoop = MA_TRUE; + break; + } + + /* TODO: How do we handle the capture flags returned by GetBuffer()? In particular, AUDCLNT_BUFFERFLAGS_SILENT (1). */ + #ifdef MA_DEBUG_OUTPUT + if (flagsCapture != 0) { + printf("[WASAPI] Capture Flags: %d\n", flagsCapture); + } + #endif + + mappedBufferFramesRemainingCapture = mappedBufferSizeInFramesCapture; + + pDevice->capture._dspFrameCount = mappedBufferSizeInFramesCapture; + pDevice->capture._dspFrames = (const ma_uint8*)pMappedBufferCapture; + } + + + /* At this point we should have both input and output data available. We now need to post it to the convert the data and post it to the client. */ + for (;;) { + BYTE* pRunningBufferCapture; + BYTE* pRunningBufferPlayback; + ma_uint32 framesToProcess; + ma_uint32 framesProcessed; + + pRunningBufferCapture = pMappedBufferCapture + ((mappedBufferSizeInFramesCapture - mappedBufferFramesRemainingCapture ) * bpfPlayback); + pRunningBufferPlayback = pMappedBufferPlayback + ((mappedBufferSizeInFramesPlayback - mappedBufferFramesRemainingPlayback) * bpfPlayback); + + /* There may be some data sitting in the converter that needs to be processed first. Once this is exhaused, run the data callback again. */ + if (!pDevice->playback.converter.isPassthrough) { + framesProcessed = (ma_uint32)ma_pcm_converter_read(&pDevice->playback.converter, pRunningBufferPlayback, mappedBufferFramesRemainingPlayback); + if (framesProcessed > 0) { + mappedBufferFramesRemainingPlayback -= framesProcessed; + if (mappedBufferFramesRemainingPlayback == 0) { + break; + } + } + } + + /* + Getting here means we need to fire the callback. If format conversion is unnecessary, we can optimize this by passing the pointers to the internal + buffers directly to the callback. + */ + if (pDevice->capture.converter.isPassthrough && pDevice->playback.converter.isPassthrough) { + /* Optimal path. We can pass mapped pointers directly to the callback. */ + framesToProcess = ma_min(mappedBufferFramesRemainingCapture, mappedBufferFramesRemainingPlayback); + framesProcessed = framesToProcess; + + pDevice->onData(pDevice, pRunningBufferPlayback, pRunningBufferCapture, framesToProcess); + + mappedBufferFramesRemainingCapture -= framesProcessed; + mappedBufferFramesRemainingPlayback -= framesProcessed; + + if (mappedBufferFramesRemainingCapture == 0) { + break; /* Exhausted input data. */ + } + if (mappedBufferFramesRemainingPlayback == 0) { + break; /* Exhausted output data. */ + } + } else if (pDevice->capture.converter.isPassthrough) { + /* The input buffer is a passthrough, but the playback buffer requires a conversion. */ + framesToProcess = ma_min(mappedBufferFramesRemainingCapture, outputDataInExternalFormatCap); + framesProcessed = framesToProcess; + + pDevice->onData(pDevice, outputDataInExternalFormat, pRunningBufferCapture, framesToProcess); + mappedBufferFramesRemainingCapture -= framesProcessed; + + pDevice->playback._dspFrameCount = framesProcessed; + pDevice->playback._dspFrames = (const ma_uint8*)outputDataInExternalFormat; + + if (mappedBufferFramesRemainingCapture == 0) { + break; /* Exhausted input data. */ + } + } else if (pDevice->playback.converter.isPassthrough) { + /* The input buffer requires conversion, the playback buffer is passthrough. */ + framesToProcess = ma_min(inputDataInExternalFormatCap, mappedBufferFramesRemainingPlayback); + framesProcessed = (ma_uint32)ma_pcm_converter_read(&pDevice->capture.converter, inputDataInExternalFormat, framesToProcess); + if (framesProcessed == 0) { + /* Getting here means we've run out of input data. */ + mappedBufferFramesRemainingCapture = 0; + break; + } + + pDevice->onData(pDevice, pRunningBufferPlayback, inputDataInExternalFormat, framesProcessed); + mappedBufferFramesRemainingPlayback -= framesProcessed; + + if (framesProcessed < framesToProcess) { + mappedBufferFramesRemainingCapture = 0; + break; /* Exhausted input data. */ + } + + if (mappedBufferFramesRemainingPlayback == 0) { + break; /* Exhausted output data. */ + } + } else { + framesToProcess = ma_min(inputDataInExternalFormatCap, outputDataInExternalFormatCap); + framesProcessed = (ma_uint32)ma_pcm_converter_read(&pDevice->capture.converter, inputDataInExternalFormat, framesToProcess); + if (framesProcessed == 0) { + /* Getting here means we've run out of input data. */ + mappedBufferFramesRemainingCapture = 0; + break; + } + + pDevice->onData(pDevice, outputDataInExternalFormat, inputDataInExternalFormat, framesProcessed); + + pDevice->playback._dspFrameCount = framesProcessed; + pDevice->playback._dspFrames = (const ma_uint8*)outputDataInExternalFormat; + + if (framesProcessed < framesToProcess) { + /* Getting here means we've run out of input data. */ + mappedBufferFramesRemainingCapture = 0; + break; + } + } + } + + + /* If at this point we've run out of capture data we need to release the buffer. */ + if (mappedBufferFramesRemainingCapture == 0 && pMappedBufferCapture != NULL) { + hr = ma_IAudioCaptureClient_ReleaseBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, mappedBufferSizeInFramesCapture); + if (FAILED(hr)) { + ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to release internal buffer from capture device after reading from the device.", MA_FAILED_TO_UNMAP_DEVICE_BUFFER); + exitLoop = MA_TRUE; + break; + } + + //printf("TRACE: Released capture buffer\n"); + + pMappedBufferCapture = NULL; + mappedBufferFramesRemainingCapture = 0; + mappedBufferSizeInFramesCapture = 0; + } + + /* Get out of this loop if we're run out of room in the playback buffer. */ + if (mappedBufferFramesRemainingPlayback == 0) { + break; + } + } + + + /* If at this point we've run out of data we need to release the buffer. */ + if (mappedBufferFramesRemainingPlayback == 0 && pMappedBufferPlayback != NULL) { + hr = ma_IAudioRenderClient_ReleaseBuffer((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient, mappedBufferSizeInFramesPlayback, 0); + if (FAILED(hr)) { + ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to release internal buffer from playback device after writing to the device.", MA_FAILED_TO_UNMAP_DEVICE_BUFFER); + exitLoop = MA_TRUE; + break; + } + + //printf("TRACE: Released playback buffer\n"); + framesWrittenToPlaybackDevice += mappedBufferSizeInFramesPlayback; + + pMappedBufferPlayback = NULL; + mappedBufferFramesRemainingPlayback = 0; + mappedBufferSizeInFramesPlayback = 0; + } + + if (!pDevice->wasapi.isStartedPlayback) { + if (pDevice->playback.shareMode == ma_share_mode_exclusive || framesWrittenToPlaybackDevice >= (pDevice->playback.internalBufferSizeInFrames/pDevice->playback.internalPeriods)*2) { + hr = ma_IAudioClient_Start((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback); + if (FAILED(hr)) { + ma_IAudioClient_Stop((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture); + ma_IAudioClient_Reset((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to start internal playback device.", MA_FAILED_TO_START_BACKEND_DEVICE); + } + ma_atomic_exchange_32(&pDevice->wasapi.isStartedPlayback, MA_TRUE); + } + } + } break; + + + + case ma_device_type_capture: + { + ma_uint32 framesAvailableCapture; + DWORD flagsCapture; /* Passed to IAudioCaptureClient_GetBuffer(). */ + + /* Wait for data to become available first. */ + if (WaitForSingleObject(pDevice->wasapi.hEventCapture, INFINITE) == WAIT_FAILED) { + exitLoop = MA_TRUE; + break; /* Wait failed. */ + } + + /* See how many frames are available. Since we waited at the top, I don't think this should ever return 0. I'm checking for this anyway. */ + result = ma_device__get_available_frames__wasapi(pDevice, (ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture, &framesAvailableCapture); + if (result != MA_SUCCESS) { + exitLoop = MA_TRUE; + break; + } + + if (framesAvailableCapture < pDevice->wasapi.periodSizeInFramesCapture) { + continue; /* Nothing available. Keep waiting. */ + } + + /* Map a the data buffer in preparation for sending to the client. */ + mappedBufferSizeInFramesCapture = framesAvailableCapture; + hr = ma_IAudioCaptureClient_GetBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, (BYTE**)&pMappedBufferCapture, &mappedBufferSizeInFramesCapture, &flagsCapture, NULL, NULL); + if (FAILED(hr)) { + ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to retrieve internal buffer from capture device in preparation for writing to the device.", MA_FAILED_TO_MAP_DEVICE_BUFFER); + exitLoop = MA_TRUE; + break; + } + + /* We should have a buffer at this point. If we are running a passthrough pipeline we can send it straight to the callback. Otherwise we need to convert. */ + if (pDevice->capture.converter.isPassthrough) { + pDevice->onData(pDevice, NULL, pMappedBufferCapture, mappedBufferSizeInFramesCapture); + } else { + ma_device__send_frames_to_client(pDevice, mappedBufferSizeInFramesCapture, pMappedBufferCapture); + } + + /* At this point we're done with the buffer. */ + hr = ma_IAudioCaptureClient_ReleaseBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, mappedBufferSizeInFramesCapture); + pMappedBufferCapture = NULL; /* <-- Important. Not doing this can result in an error once we leave this loop because it will use this to know whether or not a final ReleaseBuffer() needs to be called. */ + mappedBufferSizeInFramesCapture = 0; + if (FAILED(hr)) { + ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to release internal buffer from capture device after reading from the device.", MA_FAILED_TO_UNMAP_DEVICE_BUFFER); + exitLoop = MA_TRUE; + break; + } + } break; + + + + case ma_device_type_playback: + { + ma_uint32 framesAvailablePlayback; + + /* Wait for space to become available first. */ + if (WaitForSingleObject(pDevice->wasapi.hEventPlayback, INFINITE) == WAIT_FAILED) { + exitLoop = MA_TRUE; + break; /* Wait failed. */ + } + + /* Check how much space is available. If this returns 0 we just keep waiting. */ + result = ma_device__get_available_frames__wasapi(pDevice, (ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback, &framesAvailablePlayback); + if (result != MA_SUCCESS) { + exitLoop = MA_TRUE; + break; + } + + if (framesAvailablePlayback < pDevice->wasapi.periodSizeInFramesPlayback) { + continue; /* No space available. */ + } + + /* Map a the data buffer in preparation for the callback. */ + hr = ma_IAudioRenderClient_GetBuffer((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient, framesAvailablePlayback, &pMappedBufferPlayback); + if (FAILED(hr)) { + ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to retrieve internal buffer from playback device in preparation for writing to the device.", MA_FAILED_TO_MAP_DEVICE_BUFFER); + exitLoop = MA_TRUE; + break; + } + + if (pDevice->playback.converter.isPassthrough) { + pDevice->onData(pDevice, pMappedBufferPlayback, NULL, framesAvailablePlayback); + } else { + ma_device__read_frames_from_client(pDevice, framesAvailablePlayback, pMappedBufferPlayback); + } + + /* At this point we're done writing to the device and we just need to release the buffer. */ + hr = ma_IAudioRenderClient_ReleaseBuffer((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient, framesAvailablePlayback, 0); + pMappedBufferPlayback = NULL; /* <-- Important. Not doing this can result in an error once we leave this loop because it will use this to know whether or not a final ReleaseBuffer() needs to be called. */ + mappedBufferSizeInFramesPlayback = 0; + + if (FAILED(hr)) { + ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to release internal buffer from playback device after writing to the device.", MA_FAILED_TO_UNMAP_DEVICE_BUFFER); + exitLoop = MA_TRUE; + break; + } + + framesWrittenToPlaybackDevice += framesAvailablePlayback; + if (!pDevice->wasapi.isStartedPlayback) { + if (pDevice->playback.shareMode == ma_share_mode_exclusive || framesWrittenToPlaybackDevice >= (pDevice->playback.internalBufferSizeInFrames/pDevice->playback.internalPeriods)*1) { + hr = ma_IAudioClient_Start((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback); + if (FAILED(hr)) { + ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to start internal playback device.", MA_FAILED_TO_START_BACKEND_DEVICE); + exitLoop = MA_TRUE; + break; + } + ma_atomic_exchange_32(&pDevice->wasapi.isStartedPlayback, MA_TRUE); + } + } + } break; + + default: return MA_INVALID_ARGS; + } + } + + /* Here is where the device needs to be stopped. */ + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + /* Any mapped buffers need to be released. */ + if (pMappedBufferCapture != NULL) { + hr = ma_IAudioCaptureClient_ReleaseBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, mappedBufferSizeInFramesCapture); + } + + hr = ma_IAudioClient_Stop((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture); + if (FAILED(hr)) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to stop internal capture device.", MA_FAILED_TO_STOP_BACKEND_DEVICE); + } + + /* The audio client needs to be reset otherwise restarting will fail. */ + hr = ma_IAudioClient_Reset((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture); + if (FAILED(hr)) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to reset internal capture device.", MA_FAILED_TO_STOP_BACKEND_DEVICE); + } + + ma_atomic_exchange_32(&pDevice->wasapi.isStartedCapture, MA_FALSE); + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + /* Any mapped buffers need to be released. */ + if (pMappedBufferPlayback != NULL) { + hr = ma_IAudioRenderClient_ReleaseBuffer((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient, mappedBufferSizeInFramesPlayback, 0); + } + + /* + The buffer needs to be drained before stopping the device. Not doing this will result in the last few frames not getting output to + the speakers. This is a problem for very short sounds because it'll result in a significant potion of it not getting played. + */ + if (pDevice->wasapi.isStartedPlayback) { + if (pDevice->playback.shareMode == ma_share_mode_exclusive) { + WaitForSingleObject(pDevice->wasapi.hEventPlayback, INFINITE); + } else { + ma_uint32 prevFramesAvaialablePlayback = (size_t)-1; + ma_uint32 framesAvailablePlayback; + for (;;) { + result = ma_device__get_available_frames__wasapi(pDevice, (ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback, &framesAvailablePlayback); + if (result != MA_SUCCESS) { + break; + } + + if (framesAvailablePlayback >= pDevice->wasapi.actualBufferSizeInFramesPlayback) { + break; + } + + /* + Just a safety check to avoid an infinite loop. If this iteration results in a situation where the number of available frames + has not changed, get out of the loop. I don't think this should ever happen, but I think it's nice to have just in case. + */ + if (framesAvailablePlayback == prevFramesAvaialablePlayback) { + break; + } + prevFramesAvaialablePlayback = framesAvailablePlayback; + + WaitForSingleObject(pDevice->wasapi.hEventPlayback, INFINITE); + ResetEvent(pDevice->wasapi.hEventPlayback); /* Manual reset. */ + } + } + } + + hr = ma_IAudioClient_Stop((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback); + if (FAILED(hr)) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to stop internal playback device.", MA_FAILED_TO_STOP_BACKEND_DEVICE); + } + + /* The audio client needs to be reset otherwise restarting will fail. */ + hr = ma_IAudioClient_Reset((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback); + if (FAILED(hr)) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to reset internal playback device.", MA_FAILED_TO_STOP_BACKEND_DEVICE); + } + + ma_atomic_exchange_32(&pDevice->wasapi.isStartedPlayback, MA_FALSE); + } + + return MA_SUCCESS; +} + +ma_result ma_context_uninit__wasapi(ma_context* pContext) +{ + ma_assert(pContext != NULL); + ma_assert(pContext->backend == ma_backend_wasapi); + (void)pContext; + + return MA_SUCCESS; +} + +ma_result ma_context_init__wasapi(ma_context* pContext) +{ + ma_assert(pContext != NULL); + (void)pContext; + + ma_result result = MA_SUCCESS; + +#ifdef MA_WIN32_DESKTOP + // WASAPI is only supported in Vista SP1 and newer. The reason for SP1 and not the base version of Vista is that event-driven + // exclusive mode does not work until SP1. + ma_OSVERSIONINFOEXW osvi; + ma_zero_object(&osvi); + osvi.dwOSVersionInfoSize = sizeof(osvi); + osvi.dwMajorVersion = HIBYTE(_WIN32_WINNT_VISTA); + osvi.dwMinorVersion = LOBYTE(_WIN32_WINNT_VISTA); + osvi.wServicePackMajor = 1; + if (VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR, VerSetConditionMask(VerSetConditionMask(VerSetConditionMask(0, VER_MAJORVERSION, VER_GREATER_EQUAL), VER_MINORVERSION, VER_GREATER_EQUAL), VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL))) { + result = MA_SUCCESS; + } else { + result = MA_NO_BACKEND; + } +#endif + + if (result != MA_SUCCESS) { + return result; + } + + pContext->onUninit = ma_context_uninit__wasapi; + pContext->onDeviceIDEqual = ma_context_is_device_id_equal__wasapi; + pContext->onEnumDevices = ma_context_enumerate_devices__wasapi; + pContext->onGetDeviceInfo = ma_context_get_device_info__wasapi; + pContext->onDeviceInit = ma_device_init__wasapi; + pContext->onDeviceUninit = ma_device_uninit__wasapi; + pContext->onDeviceStart = NULL; /* Not used. Started in onDeviceMainLoop. */ + pContext->onDeviceStop = NULL; /* Not used. Stopped in onDeviceMainLoop. */ + pContext->onDeviceWrite = NULL; + pContext->onDeviceRead = NULL; + pContext->onDeviceMainLoop = ma_device_main_loop__wasapi; + + return result; +} +#endif + +/////////////////////////////////////////////////////////////////////////////// +// +// DirectSound Backend +// +/////////////////////////////////////////////////////////////////////////////// +#ifdef MA_HAS_DSOUND +//#include + +GUID MA_GUID_IID_DirectSoundNotify = {0xb0210783, 0x89cd, 0x11d0, {0xaf, 0x08, 0x00, 0xa0, 0xc9, 0x25, 0xcd, 0x16}}; + +// miniaudio only uses priority or exclusive modes. +#define MA_DSSCL_NORMAL 1 +#define MA_DSSCL_PRIORITY 2 +#define MA_DSSCL_EXCLUSIVE 3 +#define MA_DSSCL_WRITEPRIMARY 4 + +#define MA_DSCAPS_PRIMARYMONO 0x00000001 +#define MA_DSCAPS_PRIMARYSTEREO 0x00000002 +#define MA_DSCAPS_PRIMARY8BIT 0x00000004 +#define MA_DSCAPS_PRIMARY16BIT 0x00000008 +#define MA_DSCAPS_CONTINUOUSRATE 0x00000010 +#define MA_DSCAPS_EMULDRIVER 0x00000020 +#define MA_DSCAPS_CERTIFIED 0x00000040 +#define MA_DSCAPS_SECONDARYMONO 0x00000100 +#define MA_DSCAPS_SECONDARYSTEREO 0x00000200 +#define MA_DSCAPS_SECONDARY8BIT 0x00000400 +#define MA_DSCAPS_SECONDARY16BIT 0x00000800 + +#define MA_DSBCAPS_PRIMARYBUFFER 0x00000001 +#define MA_DSBCAPS_STATIC 0x00000002 +#define MA_DSBCAPS_LOCHARDWARE 0x00000004 +#define MA_DSBCAPS_LOCSOFTWARE 0x00000008 +#define MA_DSBCAPS_CTRL3D 0x00000010 +#define MA_DSBCAPS_CTRLFREQUENCY 0x00000020 +#define MA_DSBCAPS_CTRLPAN 0x00000040 +#define MA_DSBCAPS_CTRLVOLUME 0x00000080 +#define MA_DSBCAPS_CTRLPOSITIONNOTIFY 0x00000100 +#define MA_DSBCAPS_CTRLFX 0x00000200 +#define MA_DSBCAPS_STICKYFOCUS 0x00004000 +#define MA_DSBCAPS_GLOBALFOCUS 0x00008000 +#define MA_DSBCAPS_GETCURRENTPOSITION2 0x00010000 +#define MA_DSBCAPS_MUTE3DATMAXDISTANCE 0x00020000 +#define MA_DSBCAPS_LOCDEFER 0x00040000 +#define MA_DSBCAPS_TRUEPLAYPOSITION 0x00080000 + +#define MA_DSBPLAY_LOOPING 0x00000001 +#define MA_DSBPLAY_LOCHARDWARE 0x00000002 +#define MA_DSBPLAY_LOCSOFTWARE 0x00000004 +#define MA_DSBPLAY_TERMINATEBY_TIME 0x00000008 +#define MA_DSBPLAY_TERMINATEBY_DISTANCE 0x00000010 +#define MA_DSBPLAY_TERMINATEBY_PRIORITY 0x00000020 + +#define MA_DSCBSTART_LOOPING 0x00000001 + +typedef struct +{ + DWORD dwSize; + DWORD dwFlags; + DWORD dwBufferBytes; + DWORD dwReserved; + WAVEFORMATEX* lpwfxFormat; + GUID guid3DAlgorithm; +} MA_DSBUFFERDESC; + +typedef struct +{ + DWORD dwSize; + DWORD dwFlags; + DWORD dwBufferBytes; + DWORD dwReserved; + WAVEFORMATEX* lpwfxFormat; + DWORD dwFXCount; + void* lpDSCFXDesc; // <-- miniaudio doesn't use this, so set to void*. +} MA_DSCBUFFERDESC; + +typedef struct +{ + DWORD dwSize; + DWORD dwFlags; + DWORD dwMinSecondarySampleRate; + DWORD dwMaxSecondarySampleRate; + DWORD dwPrimaryBuffers; + DWORD dwMaxHwMixingAllBuffers; + DWORD dwMaxHwMixingStaticBuffers; + DWORD dwMaxHwMixingStreamingBuffers; + DWORD dwFreeHwMixingAllBuffers; + DWORD dwFreeHwMixingStaticBuffers; + DWORD dwFreeHwMixingStreamingBuffers; + DWORD dwMaxHw3DAllBuffers; + DWORD dwMaxHw3DStaticBuffers; + DWORD dwMaxHw3DStreamingBuffers; + DWORD dwFreeHw3DAllBuffers; + DWORD dwFreeHw3DStaticBuffers; + DWORD dwFreeHw3DStreamingBuffers; + DWORD dwTotalHwMemBytes; + DWORD dwFreeHwMemBytes; + DWORD dwMaxContigFreeHwMemBytes; + DWORD dwUnlockTransferRateHwBuffers; + DWORD dwPlayCpuOverheadSwBuffers; + DWORD dwReserved1; + DWORD dwReserved2; +} MA_DSCAPS; + +typedef struct +{ + DWORD dwSize; + DWORD dwFlags; + DWORD dwBufferBytes; + DWORD dwUnlockTransferRate; + DWORD dwPlayCpuOverhead; +} MA_DSBCAPS; + +typedef struct +{ + DWORD dwSize; + DWORD dwFlags; + DWORD dwFormats; + DWORD dwChannels; +} MA_DSCCAPS; + +typedef struct +{ + DWORD dwSize; + DWORD dwFlags; + DWORD dwBufferBytes; + DWORD dwReserved; +} MA_DSCBCAPS; + +typedef struct +{ + DWORD dwOffset; + HANDLE hEventNotify; +} MA_DSBPOSITIONNOTIFY; + +typedef struct ma_IDirectSound ma_IDirectSound; +typedef struct ma_IDirectSoundBuffer ma_IDirectSoundBuffer; +typedef struct ma_IDirectSoundCapture ma_IDirectSoundCapture; +typedef struct ma_IDirectSoundCaptureBuffer ma_IDirectSoundCaptureBuffer; +typedef struct ma_IDirectSoundNotify ma_IDirectSoundNotify; + + +// COM objects. The way these work is that you have a vtable (a list of function pointers, kind of +// like how C++ works internally), and then you have a structure with a single member, which is a +// pointer to the vtable. The vtable is where the methods of the object are defined. Methods need +// to be in a specific order, and parent classes need to have their methods declared first. + +// IDirectSound +typedef struct +{ + // IUnknown + HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IDirectSound* pThis, const IID* const riid, void** ppObject); + ULONG (STDMETHODCALLTYPE * AddRef) (ma_IDirectSound* pThis); + ULONG (STDMETHODCALLTYPE * Release) (ma_IDirectSound* pThis); + + // IDirectSound + HRESULT (STDMETHODCALLTYPE * CreateSoundBuffer) (ma_IDirectSound* pThis, const MA_DSBUFFERDESC* pDSBufferDesc, ma_IDirectSoundBuffer** ppDSBuffer, void* pUnkOuter); + HRESULT (STDMETHODCALLTYPE * GetCaps) (ma_IDirectSound* pThis, MA_DSCAPS* pDSCaps); + HRESULT (STDMETHODCALLTYPE * DuplicateSoundBuffer)(ma_IDirectSound* pThis, ma_IDirectSoundBuffer* pDSBufferOriginal, ma_IDirectSoundBuffer** ppDSBufferDuplicate); + HRESULT (STDMETHODCALLTYPE * SetCooperativeLevel) (ma_IDirectSound* pThis, HWND hwnd, DWORD dwLevel); + HRESULT (STDMETHODCALLTYPE * Compact) (ma_IDirectSound* pThis); + HRESULT (STDMETHODCALLTYPE * GetSpeakerConfig) (ma_IDirectSound* pThis, DWORD* pSpeakerConfig); + HRESULT (STDMETHODCALLTYPE * SetSpeakerConfig) (ma_IDirectSound* pThis, DWORD dwSpeakerConfig); + HRESULT (STDMETHODCALLTYPE * Initialize) (ma_IDirectSound* pThis, const GUID* pGuidDevice); +} ma_IDirectSoundVtbl; +struct ma_IDirectSound +{ + ma_IDirectSoundVtbl* lpVtbl; +}; +HRESULT ma_IDirectSound_QueryInterface(ma_IDirectSound* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } +ULONG ma_IDirectSound_AddRef(ma_IDirectSound* pThis) { return pThis->lpVtbl->AddRef(pThis); } +ULONG ma_IDirectSound_Release(ma_IDirectSound* pThis) { return pThis->lpVtbl->Release(pThis); } +HRESULT ma_IDirectSound_CreateSoundBuffer(ma_IDirectSound* pThis, const MA_DSBUFFERDESC* pDSBufferDesc, ma_IDirectSoundBuffer** ppDSBuffer, void* pUnkOuter) { return pThis->lpVtbl->CreateSoundBuffer(pThis, pDSBufferDesc, ppDSBuffer, pUnkOuter); } +HRESULT ma_IDirectSound_GetCaps(ma_IDirectSound* pThis, MA_DSCAPS* pDSCaps) { return pThis->lpVtbl->GetCaps(pThis, pDSCaps); } +HRESULT ma_IDirectSound_DuplicateSoundBuffer(ma_IDirectSound* pThis, ma_IDirectSoundBuffer* pDSBufferOriginal, ma_IDirectSoundBuffer** ppDSBufferDuplicate) { return pThis->lpVtbl->DuplicateSoundBuffer(pThis, pDSBufferOriginal, ppDSBufferDuplicate); } +HRESULT ma_IDirectSound_SetCooperativeLevel(ma_IDirectSound* pThis, HWND hwnd, DWORD dwLevel) { return pThis->lpVtbl->SetCooperativeLevel(pThis, hwnd, dwLevel); } +HRESULT ma_IDirectSound_Compact(ma_IDirectSound* pThis) { return pThis->lpVtbl->Compact(pThis); } +HRESULT ma_IDirectSound_GetSpeakerConfig(ma_IDirectSound* pThis, DWORD* pSpeakerConfig) { return pThis->lpVtbl->GetSpeakerConfig(pThis, pSpeakerConfig); } +HRESULT ma_IDirectSound_SetSpeakerConfig(ma_IDirectSound* pThis, DWORD dwSpeakerConfig) { return pThis->lpVtbl->SetSpeakerConfig(pThis, dwSpeakerConfig); } +HRESULT ma_IDirectSound_Initialize(ma_IDirectSound* pThis, const GUID* pGuidDevice) { return pThis->lpVtbl->Initialize(pThis, pGuidDevice); } + + +// IDirectSoundBuffer +typedef struct +{ + // IUnknown + HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IDirectSoundBuffer* pThis, const IID* const riid, void** ppObject); + ULONG (STDMETHODCALLTYPE * AddRef) (ma_IDirectSoundBuffer* pThis); + ULONG (STDMETHODCALLTYPE * Release) (ma_IDirectSoundBuffer* pThis); + + // IDirectSoundBuffer + HRESULT (STDMETHODCALLTYPE * GetCaps) (ma_IDirectSoundBuffer* pThis, MA_DSBCAPS* pDSBufferCaps); + HRESULT (STDMETHODCALLTYPE * GetCurrentPosition)(ma_IDirectSoundBuffer* pThis, DWORD* pCurrentPlayCursor, DWORD* pCurrentWriteCursor); + HRESULT (STDMETHODCALLTYPE * GetFormat) (ma_IDirectSoundBuffer* pThis, WAVEFORMATEX* pFormat, DWORD dwSizeAllocated, DWORD* pSizeWritten); + HRESULT (STDMETHODCALLTYPE * GetVolume) (ma_IDirectSoundBuffer* pThis, LONG* pVolume); + HRESULT (STDMETHODCALLTYPE * GetPan) (ma_IDirectSoundBuffer* pThis, LONG* pPan); + HRESULT (STDMETHODCALLTYPE * GetFrequency) (ma_IDirectSoundBuffer* pThis, DWORD* pFrequency); + HRESULT (STDMETHODCALLTYPE * GetStatus) (ma_IDirectSoundBuffer* pThis, DWORD* pStatus); + HRESULT (STDMETHODCALLTYPE * Initialize) (ma_IDirectSoundBuffer* pThis, ma_IDirectSound* pDirectSound, const MA_DSBUFFERDESC* pDSBufferDesc); + HRESULT (STDMETHODCALLTYPE * Lock) (ma_IDirectSoundBuffer* pThis, DWORD dwOffset, DWORD dwBytes, void** ppAudioPtr1, DWORD* pAudioBytes1, void** ppAudioPtr2, DWORD* pAudioBytes2, DWORD dwFlags); + HRESULT (STDMETHODCALLTYPE * Play) (ma_IDirectSoundBuffer* pThis, DWORD dwReserved1, DWORD dwPriority, DWORD dwFlags); + HRESULT (STDMETHODCALLTYPE * SetCurrentPosition)(ma_IDirectSoundBuffer* pThis, DWORD dwNewPosition); + HRESULT (STDMETHODCALLTYPE * SetFormat) (ma_IDirectSoundBuffer* pThis, const WAVEFORMATEX* pFormat); + HRESULT (STDMETHODCALLTYPE * SetVolume) (ma_IDirectSoundBuffer* pThis, LONG volume); + HRESULT (STDMETHODCALLTYPE * SetPan) (ma_IDirectSoundBuffer* pThis, LONG pan); + HRESULT (STDMETHODCALLTYPE * SetFrequency) (ma_IDirectSoundBuffer* pThis, DWORD dwFrequency); + HRESULT (STDMETHODCALLTYPE * Stop) (ma_IDirectSoundBuffer* pThis); + HRESULT (STDMETHODCALLTYPE * Unlock) (ma_IDirectSoundBuffer* pThis, void* pAudioPtr1, DWORD dwAudioBytes1, void* pAudioPtr2, DWORD dwAudioBytes2); + HRESULT (STDMETHODCALLTYPE * Restore) (ma_IDirectSoundBuffer* pThis); +} ma_IDirectSoundBufferVtbl; +struct ma_IDirectSoundBuffer +{ + ma_IDirectSoundBufferVtbl* lpVtbl; +}; +HRESULT ma_IDirectSoundBuffer_QueryInterface(ma_IDirectSoundBuffer* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } +ULONG ma_IDirectSoundBuffer_AddRef(ma_IDirectSoundBuffer* pThis) { return pThis->lpVtbl->AddRef(pThis); } +ULONG ma_IDirectSoundBuffer_Release(ma_IDirectSoundBuffer* pThis) { return pThis->lpVtbl->Release(pThis); } +HRESULT ma_IDirectSoundBuffer_GetCaps(ma_IDirectSoundBuffer* pThis, MA_DSBCAPS* pDSBufferCaps) { return pThis->lpVtbl->GetCaps(pThis, pDSBufferCaps); } +HRESULT ma_IDirectSoundBuffer_GetCurrentPosition(ma_IDirectSoundBuffer* pThis, DWORD* pCurrentPlayCursor, DWORD* pCurrentWriteCursor) { return pThis->lpVtbl->GetCurrentPosition(pThis, pCurrentPlayCursor, pCurrentWriteCursor); } +HRESULT ma_IDirectSoundBuffer_GetFormat(ma_IDirectSoundBuffer* pThis, WAVEFORMATEX* pFormat, DWORD dwSizeAllocated, DWORD* pSizeWritten) { return pThis->lpVtbl->GetFormat(pThis, pFormat, dwSizeAllocated, pSizeWritten); } +HRESULT ma_IDirectSoundBuffer_GetVolume(ma_IDirectSoundBuffer* pThis, LONG* pVolume) { return pThis->lpVtbl->GetVolume(pThis, pVolume); } +HRESULT ma_IDirectSoundBuffer_GetPan(ma_IDirectSoundBuffer* pThis, LONG* pPan) { return pThis->lpVtbl->GetPan(pThis, pPan); } +HRESULT ma_IDirectSoundBuffer_GetFrequency(ma_IDirectSoundBuffer* pThis, DWORD* pFrequency) { return pThis->lpVtbl->GetFrequency(pThis, pFrequency); } +HRESULT ma_IDirectSoundBuffer_GetStatus(ma_IDirectSoundBuffer* pThis, DWORD* pStatus) { return pThis->lpVtbl->GetStatus(pThis, pStatus); } +HRESULT ma_IDirectSoundBuffer_Initialize(ma_IDirectSoundBuffer* pThis, ma_IDirectSound* pDirectSound, const MA_DSBUFFERDESC* pDSBufferDesc) { return pThis->lpVtbl->Initialize(pThis, pDirectSound, pDSBufferDesc); } +HRESULT ma_IDirectSoundBuffer_Lock(ma_IDirectSoundBuffer* pThis, DWORD dwOffset, DWORD dwBytes, void** ppAudioPtr1, DWORD* pAudioBytes1, void** ppAudioPtr2, DWORD* pAudioBytes2, DWORD dwFlags) { return pThis->lpVtbl->Lock(pThis, dwOffset, dwBytes, ppAudioPtr1, pAudioBytes1, ppAudioPtr2, pAudioBytes2, dwFlags); } +HRESULT ma_IDirectSoundBuffer_Play(ma_IDirectSoundBuffer* pThis, DWORD dwReserved1, DWORD dwPriority, DWORD dwFlags) { return pThis->lpVtbl->Play(pThis, dwReserved1, dwPriority, dwFlags); } +HRESULT ma_IDirectSoundBuffer_SetCurrentPosition(ma_IDirectSoundBuffer* pThis, DWORD dwNewPosition) { return pThis->lpVtbl->SetCurrentPosition(pThis, dwNewPosition); } +HRESULT ma_IDirectSoundBuffer_SetFormat(ma_IDirectSoundBuffer* pThis, const WAVEFORMATEX* pFormat) { return pThis->lpVtbl->SetFormat(pThis, pFormat); } +HRESULT ma_IDirectSoundBuffer_SetVolume(ma_IDirectSoundBuffer* pThis, LONG volume) { return pThis->lpVtbl->SetVolume(pThis, volume); } +HRESULT ma_IDirectSoundBuffer_SetPan(ma_IDirectSoundBuffer* pThis, LONG pan) { return pThis->lpVtbl->SetPan(pThis, pan); } +HRESULT ma_IDirectSoundBuffer_SetFrequency(ma_IDirectSoundBuffer* pThis, DWORD dwFrequency) { return pThis->lpVtbl->SetFrequency(pThis, dwFrequency); } +HRESULT ma_IDirectSoundBuffer_Stop(ma_IDirectSoundBuffer* pThis) { return pThis->lpVtbl->Stop(pThis); } +HRESULT ma_IDirectSoundBuffer_Unlock(ma_IDirectSoundBuffer* pThis, void* pAudioPtr1, DWORD dwAudioBytes1, void* pAudioPtr2, DWORD dwAudioBytes2) { return pThis->lpVtbl->Unlock(pThis, pAudioPtr1, dwAudioBytes1, pAudioPtr2, dwAudioBytes2); } +HRESULT ma_IDirectSoundBuffer_Restore(ma_IDirectSoundBuffer* pThis) { return pThis->lpVtbl->Restore(pThis); } + + +// IDirectSoundCapture +typedef struct +{ + // IUnknown + HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IDirectSoundCapture* pThis, const IID* const riid, void** ppObject); + ULONG (STDMETHODCALLTYPE * AddRef) (ma_IDirectSoundCapture* pThis); + ULONG (STDMETHODCALLTYPE * Release) (ma_IDirectSoundCapture* pThis); + + // IDirectSoundCapture + HRESULT (STDMETHODCALLTYPE * CreateCaptureBuffer)(ma_IDirectSoundCapture* pThis, const MA_DSCBUFFERDESC* pDSCBufferDesc, ma_IDirectSoundCaptureBuffer** ppDSCBuffer, void* pUnkOuter); + HRESULT (STDMETHODCALLTYPE * GetCaps) (ma_IDirectSoundCapture* pThis, MA_DSCCAPS* pDSCCaps); + HRESULT (STDMETHODCALLTYPE * Initialize) (ma_IDirectSoundCapture* pThis, const GUID* pGuidDevice); +} ma_IDirectSoundCaptureVtbl; +struct ma_IDirectSoundCapture +{ + ma_IDirectSoundCaptureVtbl* lpVtbl; +}; +HRESULT ma_IDirectSoundCapture_QueryInterface(ma_IDirectSoundCapture* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } +ULONG ma_IDirectSoundCapture_AddRef(ma_IDirectSoundCapture* pThis) { return pThis->lpVtbl->AddRef(pThis); } +ULONG ma_IDirectSoundCapture_Release(ma_IDirectSoundCapture* pThis) { return pThis->lpVtbl->Release(pThis); } +HRESULT ma_IDirectSoundCapture_CreateCaptureBuffer(ma_IDirectSoundCapture* pThis, const MA_DSCBUFFERDESC* pDSCBufferDesc, ma_IDirectSoundCaptureBuffer** ppDSCBuffer, void* pUnkOuter) { return pThis->lpVtbl->CreateCaptureBuffer(pThis, pDSCBufferDesc, ppDSCBuffer, pUnkOuter); } +HRESULT ma_IDirectSoundCapture_GetCaps (ma_IDirectSoundCapture* pThis, MA_DSCCAPS* pDSCCaps) { return pThis->lpVtbl->GetCaps(pThis, pDSCCaps); } +HRESULT ma_IDirectSoundCapture_Initialize (ma_IDirectSoundCapture* pThis, const GUID* pGuidDevice) { return pThis->lpVtbl->Initialize(pThis, pGuidDevice); } + + +// IDirectSoundCaptureBuffer +typedef struct +{ + // IUnknown + HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IDirectSoundCaptureBuffer* pThis, const IID* const riid, void** ppObject); + ULONG (STDMETHODCALLTYPE * AddRef) (ma_IDirectSoundCaptureBuffer* pThis); + ULONG (STDMETHODCALLTYPE * Release) (ma_IDirectSoundCaptureBuffer* pThis); + + // IDirectSoundCaptureBuffer + HRESULT (STDMETHODCALLTYPE * GetCaps) (ma_IDirectSoundCaptureBuffer* pThis, MA_DSCBCAPS* pDSCBCaps); + HRESULT (STDMETHODCALLTYPE * GetCurrentPosition)(ma_IDirectSoundCaptureBuffer* pThis, DWORD* pCapturePosition, DWORD* pReadPosition); + HRESULT (STDMETHODCALLTYPE * GetFormat) (ma_IDirectSoundCaptureBuffer* pThis, WAVEFORMATEX* pFormat, DWORD dwSizeAllocated, DWORD* pSizeWritten); + HRESULT (STDMETHODCALLTYPE * GetStatus) (ma_IDirectSoundCaptureBuffer* pThis, DWORD* pStatus); + HRESULT (STDMETHODCALLTYPE * Initialize) (ma_IDirectSoundCaptureBuffer* pThis, ma_IDirectSoundCapture* pDirectSoundCapture, const MA_DSCBUFFERDESC* pDSCBufferDesc); + HRESULT (STDMETHODCALLTYPE * Lock) (ma_IDirectSoundCaptureBuffer* pThis, DWORD dwOffset, DWORD dwBytes, void** ppAudioPtr1, DWORD* pAudioBytes1, void** ppAudioPtr2, DWORD* pAudioBytes2, DWORD dwFlags); + HRESULT (STDMETHODCALLTYPE * Start) (ma_IDirectSoundCaptureBuffer* pThis, DWORD dwFlags); + HRESULT (STDMETHODCALLTYPE * Stop) (ma_IDirectSoundCaptureBuffer* pThis); + HRESULT (STDMETHODCALLTYPE * Unlock) (ma_IDirectSoundCaptureBuffer* pThis, void* pAudioPtr1, DWORD dwAudioBytes1, void* pAudioPtr2, DWORD dwAudioBytes2); +} ma_IDirectSoundCaptureBufferVtbl; +struct ma_IDirectSoundCaptureBuffer +{ + ma_IDirectSoundCaptureBufferVtbl* lpVtbl; +}; +HRESULT ma_IDirectSoundCaptureBuffer_QueryInterface(ma_IDirectSoundCaptureBuffer* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } +ULONG ma_IDirectSoundCaptureBuffer_AddRef(ma_IDirectSoundCaptureBuffer* pThis) { return pThis->lpVtbl->AddRef(pThis); } +ULONG ma_IDirectSoundCaptureBuffer_Release(ma_IDirectSoundCaptureBuffer* pThis) { return pThis->lpVtbl->Release(pThis); } +HRESULT ma_IDirectSoundCaptureBuffer_GetCaps(ma_IDirectSoundCaptureBuffer* pThis, MA_DSCBCAPS* pDSCBCaps) { return pThis->lpVtbl->GetCaps(pThis, pDSCBCaps); } +HRESULT ma_IDirectSoundCaptureBuffer_GetCurrentPosition(ma_IDirectSoundCaptureBuffer* pThis, DWORD* pCapturePosition, DWORD* pReadPosition) { return pThis->lpVtbl->GetCurrentPosition(pThis, pCapturePosition, pReadPosition); } +HRESULT ma_IDirectSoundCaptureBuffer_GetFormat(ma_IDirectSoundCaptureBuffer* pThis, WAVEFORMATEX* pFormat, DWORD dwSizeAllocated, DWORD* pSizeWritten) { return pThis->lpVtbl->GetFormat(pThis, pFormat, dwSizeAllocated, pSizeWritten); } +HRESULT ma_IDirectSoundCaptureBuffer_GetStatus(ma_IDirectSoundCaptureBuffer* pThis, DWORD* pStatus) { return pThis->lpVtbl->GetStatus(pThis, pStatus); } +HRESULT ma_IDirectSoundCaptureBuffer_Initialize(ma_IDirectSoundCaptureBuffer* pThis, ma_IDirectSoundCapture* pDirectSoundCapture, const MA_DSCBUFFERDESC* pDSCBufferDesc) { return pThis->lpVtbl->Initialize(pThis, pDirectSoundCapture, pDSCBufferDesc); } +HRESULT ma_IDirectSoundCaptureBuffer_Lock(ma_IDirectSoundCaptureBuffer* pThis, DWORD dwOffset, DWORD dwBytes, void** ppAudioPtr1, DWORD* pAudioBytes1, void** ppAudioPtr2, DWORD* pAudioBytes2, DWORD dwFlags) { return pThis->lpVtbl->Lock(pThis, dwOffset, dwBytes, ppAudioPtr1, pAudioBytes1, ppAudioPtr2, pAudioBytes2, dwFlags); } +HRESULT ma_IDirectSoundCaptureBuffer_Start(ma_IDirectSoundCaptureBuffer* pThis, DWORD dwFlags) { return pThis->lpVtbl->Start(pThis, dwFlags); } +HRESULT ma_IDirectSoundCaptureBuffer_Stop(ma_IDirectSoundCaptureBuffer* pThis) { return pThis->lpVtbl->Stop(pThis); } +HRESULT ma_IDirectSoundCaptureBuffer_Unlock(ma_IDirectSoundCaptureBuffer* pThis, void* pAudioPtr1, DWORD dwAudioBytes1, void* pAudioPtr2, DWORD dwAudioBytes2) { return pThis->lpVtbl->Unlock(pThis, pAudioPtr1, dwAudioBytes1, pAudioPtr2, dwAudioBytes2); } + + +// IDirectSoundNotify +typedef struct +{ + // IUnknown + HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IDirectSoundNotify* pThis, const IID* const riid, void** ppObject); + ULONG (STDMETHODCALLTYPE * AddRef) (ma_IDirectSoundNotify* pThis); + ULONG (STDMETHODCALLTYPE * Release) (ma_IDirectSoundNotify* pThis); + + // IDirectSoundNotify + HRESULT (STDMETHODCALLTYPE * SetNotificationPositions)(ma_IDirectSoundNotify* pThis, DWORD dwPositionNotifies, const MA_DSBPOSITIONNOTIFY* pPositionNotifies); +} ma_IDirectSoundNotifyVtbl; +struct ma_IDirectSoundNotify +{ + ma_IDirectSoundNotifyVtbl* lpVtbl; +}; +HRESULT ma_IDirectSoundNotify_QueryInterface(ma_IDirectSoundNotify* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); } +ULONG ma_IDirectSoundNotify_AddRef(ma_IDirectSoundNotify* pThis) { return pThis->lpVtbl->AddRef(pThis); } +ULONG ma_IDirectSoundNotify_Release(ma_IDirectSoundNotify* pThis) { return pThis->lpVtbl->Release(pThis); } +HRESULT ma_IDirectSoundNotify_SetNotificationPositions(ma_IDirectSoundNotify* pThis, DWORD dwPositionNotifies, const MA_DSBPOSITIONNOTIFY* pPositionNotifies) { return pThis->lpVtbl->SetNotificationPositions(pThis, dwPositionNotifies, pPositionNotifies); } + + +typedef BOOL (CALLBACK * ma_DSEnumCallbackAProc) (LPGUID pDeviceGUID, LPCSTR pDeviceDescription, LPCSTR pModule, LPVOID pContext); +typedef HRESULT (WINAPI * ma_DirectSoundCreateProc) (const GUID* pcGuidDevice, ma_IDirectSound** ppDS8, LPUNKNOWN pUnkOuter); +typedef HRESULT (WINAPI * ma_DirectSoundEnumerateAProc) (ma_DSEnumCallbackAProc pDSEnumCallback, LPVOID pContext); +typedef HRESULT (WINAPI * ma_DirectSoundCaptureCreateProc) (const GUID* pcGuidDevice, ma_IDirectSoundCapture** ppDSC8, LPUNKNOWN pUnkOuter); +typedef HRESULT (WINAPI * ma_DirectSoundCaptureEnumerateAProc)(ma_DSEnumCallbackAProc pDSEnumCallback, LPVOID pContext); + + +// Retrieves the channel count and channel map for the given speaker configuration. If the speaker configuration is unknown, +// the channel count and channel map will be left unmodified. +void ma_get_channels_from_speaker_config__dsound(DWORD speakerConfig, WORD* pChannelsOut, DWORD* pChannelMapOut) +{ + WORD channels = 0; + if (pChannelsOut != NULL) { + channels = *pChannelsOut; + } + + DWORD channelMap = 0; + if (pChannelMapOut != NULL) { + channelMap = *pChannelMapOut; + } + + // The speaker configuration is a combination of speaker config and speaker geometry. The lower 8 bits is what we care about. The upper + // 16 bits is for the geometry. + switch ((BYTE)(speakerConfig)) { + case 1 /*DSSPEAKER_HEADPHONE*/: channels = 2; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break; + case 2 /*DSSPEAKER_MONO*/: channels = 1; channelMap = SPEAKER_FRONT_CENTER; break; + case 3 /*DSSPEAKER_QUAD*/: channels = 4; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break; + case 4 /*DSSPEAKER_STEREO*/: channels = 2; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break; + case 5 /*DSSPEAKER_SURROUND*/: channels = 4; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_BACK_CENTER; break; + case 6 /*DSSPEAKER_5POINT1_BACK*/ /*DSSPEAKER_5POINT1*/: channels = 6; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break; + case 7 /*DSSPEAKER_7POINT1_WIDE*/ /*DSSPEAKER_7POINT1*/: channels = 8; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT | SPEAKER_FRONT_LEFT_OF_CENTER | SPEAKER_FRONT_RIGHT_OF_CENTER; break; + case 8 /*DSSPEAKER_7POINT1_SURROUND*/: channels = 8; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT | SPEAKER_SIDE_LEFT | SPEAKER_SIDE_RIGHT; break; + case 9 /*DSSPEAKER_5POINT1_SURROUND*/: channels = 6; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_SIDE_LEFT | SPEAKER_SIDE_RIGHT; break; + default: break; + } + + if (pChannelsOut != NULL) { + *pChannelsOut = channels; + } + + if (pChannelMapOut != NULL) { + *pChannelMapOut = channelMap; + } +} + + +ma_result ma_context_create_IDirectSound__dsound(ma_context* pContext, ma_share_mode shareMode, const ma_device_id* pDeviceID, ma_IDirectSound** ppDirectSound) +{ + ma_assert(pContext != NULL); + ma_assert(ppDirectSound != NULL); + + *ppDirectSound = NULL; + ma_IDirectSound* pDirectSound = NULL; + + if (FAILED(((ma_DirectSoundCreateProc)pContext->dsound.DirectSoundCreate)((pDeviceID == NULL) ? NULL : (const GUID*)pDeviceID->dsound, &pDirectSound, NULL))) { + return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[DirectSound] DirectSoundCreate() failed for playback device.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + + // The cooperative level must be set before doing anything else. + HWND hWnd = ((MA_PFN_GetForegroundWindow)pContext->win32.GetForegroundWindow)(); + if (hWnd == NULL) { + hWnd = ((MA_PFN_GetDesktopWindow)pContext->win32.GetDesktopWindow)(); + } + if (FAILED(ma_IDirectSound_SetCooperativeLevel(pDirectSound, hWnd, (shareMode == ma_share_mode_exclusive) ? MA_DSSCL_EXCLUSIVE : MA_DSSCL_PRIORITY))) { + return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSound_SetCooperateiveLevel() failed for playback device.", MA_SHARE_MODE_NOT_SUPPORTED); + } + + *ppDirectSound = pDirectSound; + return MA_SUCCESS; +} + +ma_result ma_context_create_IDirectSoundCapture__dsound(ma_context* pContext, ma_share_mode shareMode, const ma_device_id* pDeviceID, ma_IDirectSoundCapture** ppDirectSoundCapture) +{ + ma_assert(pContext != NULL); + ma_assert(ppDirectSoundCapture != NULL); + + /* DirectSound does not support exclusive mode for capture. */ + if (shareMode == ma_share_mode_exclusive) { + return MA_SHARE_MODE_NOT_SUPPORTED; + } + + *ppDirectSoundCapture = NULL; + ma_IDirectSoundCapture* pDirectSoundCapture = NULL; + + if (FAILED(((ma_DirectSoundCaptureCreateProc)pContext->dsound.DirectSoundCaptureCreate)((pDeviceID == NULL) ? NULL : (const GUID*)pDeviceID->dsound, &pDirectSoundCapture, NULL))) { + return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[DirectSound] DirectSoundCaptureCreate() failed for capture device.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + + *ppDirectSoundCapture = pDirectSoundCapture; + return MA_SUCCESS; +} + +ma_result ma_context_get_format_info_for_IDirectSoundCapture__dsound(ma_context* pContext, ma_IDirectSoundCapture* pDirectSoundCapture, WORD* pChannels, WORD* pBitsPerSample, DWORD* pSampleRate) +{ + ma_assert(pContext != NULL); + ma_assert(pDirectSoundCapture != NULL); + + if (pChannels) { + *pChannels = 0; + } + if (pBitsPerSample) { + *pBitsPerSample = 0; + } + if (pSampleRate) { + *pSampleRate = 0; + } + + MA_DSCCAPS caps; + ma_zero_object(&caps); + caps.dwSize = sizeof(caps); + if (FAILED(ma_IDirectSoundCapture_GetCaps(pDirectSoundCapture, &caps))) { + return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundCapture_GetCaps() failed for capture device.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + + if (pChannels) { + *pChannels = (WORD)caps.dwChannels; + } + + // The device can support multiple formats. We just go through the different formats in order of priority and + // pick the first one. This the same type of system as the WinMM backend. + WORD bitsPerSample = 16; + DWORD sampleRate = 48000; + + if (caps.dwChannels == 1) { + if ((caps.dwFormats & WAVE_FORMAT_48M16) != 0) { + sampleRate = 48000; + } else if ((caps.dwFormats & WAVE_FORMAT_44M16) != 0) { + sampleRate = 44100; + } else if ((caps.dwFormats & WAVE_FORMAT_2M16) != 0) { + sampleRate = 22050; + } else if ((caps.dwFormats & WAVE_FORMAT_1M16) != 0) { + sampleRate = 11025; + } else if ((caps.dwFormats & WAVE_FORMAT_96M16) != 0) { + sampleRate = 96000; + } else { + bitsPerSample = 8; + if ((caps.dwFormats & WAVE_FORMAT_48M08) != 0) { + sampleRate = 48000; + } else if ((caps.dwFormats & WAVE_FORMAT_44M08) != 0) { + sampleRate = 44100; + } else if ((caps.dwFormats & WAVE_FORMAT_2M08) != 0) { + sampleRate = 22050; + } else if ((caps.dwFormats & WAVE_FORMAT_1M08) != 0) { + sampleRate = 11025; + } else if ((caps.dwFormats & WAVE_FORMAT_96M08) != 0) { + sampleRate = 96000; + } else { + bitsPerSample = 16; // Didn't find it. Just fall back to 16-bit. + } + } + } else if (caps.dwChannels == 2) { + if ((caps.dwFormats & WAVE_FORMAT_48S16) != 0) { + sampleRate = 48000; + } else if ((caps.dwFormats & WAVE_FORMAT_44S16) != 0) { + sampleRate = 44100; + } else if ((caps.dwFormats & WAVE_FORMAT_2S16) != 0) { + sampleRate = 22050; + } else if ((caps.dwFormats & WAVE_FORMAT_1S16) != 0) { + sampleRate = 11025; + } else if ((caps.dwFormats & WAVE_FORMAT_96S16) != 0) { + sampleRate = 96000; + } else { + bitsPerSample = 8; + if ((caps.dwFormats & WAVE_FORMAT_48S08) != 0) { + sampleRate = 48000; + } else if ((caps.dwFormats & WAVE_FORMAT_44S08) != 0) { + sampleRate = 44100; + } else if ((caps.dwFormats & WAVE_FORMAT_2S08) != 0) { + sampleRate = 22050; + } else if ((caps.dwFormats & WAVE_FORMAT_1S08) != 0) { + sampleRate = 11025; + } else if ((caps.dwFormats & WAVE_FORMAT_96S08) != 0) { + sampleRate = 96000; + } else { + bitsPerSample = 16; // Didn't find it. Just fall back to 16-bit. + } + } + } + + if (pBitsPerSample) { + *pBitsPerSample = bitsPerSample; + } + if (pSampleRate) { + *pSampleRate = sampleRate; + } + + return MA_SUCCESS; +} + +ma_bool32 ma_context_is_device_id_equal__dsound(ma_context* pContext, const ma_device_id* pID0, const ma_device_id* pID1) +{ + ma_assert(pContext != NULL); + ma_assert(pID0 != NULL); + ma_assert(pID1 != NULL); + (void)pContext; + + return memcmp(pID0->dsound, pID1->dsound, sizeof(pID0->dsound)) == 0; +} + + +typedef struct +{ + ma_context* pContext; + ma_device_type deviceType; + ma_enum_devices_callback_proc callback; + void* pUserData; + ma_bool32 terminated; +} ma_context_enumerate_devices_callback_data__dsound; + +BOOL CALLBACK ma_context_enumerate_devices_callback__dsound(LPGUID lpGuid, LPCSTR lpcstrDescription, LPCSTR lpcstrModule, LPVOID lpContext) +{ + (void)lpcstrModule; + + ma_context_enumerate_devices_callback_data__dsound* pData = (ma_context_enumerate_devices_callback_data__dsound*)lpContext; + ma_assert(pData != NULL); + + ma_device_info deviceInfo; + ma_zero_object(&deviceInfo); + + // ID. + if (lpGuid != NULL) { + ma_copy_memory(deviceInfo.id.dsound, lpGuid, 16); + } else { + ma_zero_memory(deviceInfo.id.dsound, 16); + } + + // Name / Description + ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), lpcstrDescription, (size_t)-1); + + + // Call the callback function, but make sure we stop enumerating if the callee requested so. + pData->terminated = !pData->callback(pData->pContext, pData->deviceType, &deviceInfo, pData->pUserData); + if (pData->terminated) { + return FALSE; // Stop enumeration. + } else { + return TRUE; // Continue enumeration. + } +} + +ma_result ma_context_enumerate_devices__dsound(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData) +{ + ma_assert(pContext != NULL); + ma_assert(callback != NULL); + + ma_context_enumerate_devices_callback_data__dsound data; + data.pContext = pContext; + data.callback = callback; + data.pUserData = pUserData; + data.terminated = MA_FALSE; + + // Playback. + if (!data.terminated) { + data.deviceType = ma_device_type_playback; + ((ma_DirectSoundEnumerateAProc)pContext->dsound.DirectSoundEnumerateA)(ma_context_enumerate_devices_callback__dsound, &data); + } + + // Capture. + if (!data.terminated) { + data.deviceType = ma_device_type_capture; + ((ma_DirectSoundCaptureEnumerateAProc)pContext->dsound.DirectSoundCaptureEnumerateA)(ma_context_enumerate_devices_callback__dsound, &data); + } + + return MA_SUCCESS; +} + + +typedef struct +{ + const ma_device_id* pDeviceID; + ma_device_info* pDeviceInfo; + ma_bool32 found; +} ma_context_get_device_info_callback_data__dsound; + +BOOL CALLBACK ma_context_get_device_info_callback__dsound(LPGUID lpGuid, LPCSTR lpcstrDescription, LPCSTR lpcstrModule, LPVOID lpContext) +{ + (void)lpcstrModule; + + ma_context_get_device_info_callback_data__dsound* pData = (ma_context_get_device_info_callback_data__dsound*)lpContext; + ma_assert(pData != NULL); + + if ((pData->pDeviceID == NULL || ma_is_guid_equal(pData->pDeviceID->dsound, &MA_GUID_NULL)) && (lpGuid == NULL || ma_is_guid_equal(lpGuid, &MA_GUID_NULL))) { + // Default device. + ma_strncpy_s(pData->pDeviceInfo->name, sizeof(pData->pDeviceInfo->name), lpcstrDescription, (size_t)-1); + pData->found = MA_TRUE; + return FALSE; // Stop enumeration. + } else { + // Not the default device. + if (lpGuid != NULL) { + if (memcmp(pData->pDeviceID->dsound, lpGuid, sizeof(pData->pDeviceID->dsound)) == 0) { + ma_strncpy_s(pData->pDeviceInfo->name, sizeof(pData->pDeviceInfo->name), lpcstrDescription, (size_t)-1); + pData->found = MA_TRUE; + return FALSE; // Stop enumeration. + } + } + } + + return TRUE; +} + +ma_result ma_context_get_device_info__dsound(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_share_mode shareMode, ma_device_info* pDeviceInfo) +{ + /* Exclusive mode and capture not supported with DirectSound. */ + if (deviceType == ma_device_type_capture && shareMode == ma_share_mode_exclusive) { + return MA_SHARE_MODE_NOT_SUPPORTED; + } + + if (pDeviceID != NULL) { + // ID. + ma_copy_memory(pDeviceInfo->id.dsound, pDeviceID->dsound, 16); + + // Name / Description. This is retrieved by enumerating over each device until we find that one that matches the input ID. + ma_context_get_device_info_callback_data__dsound data; + data.pDeviceID = pDeviceID; + data.pDeviceInfo = pDeviceInfo; + data.found = MA_FALSE; + if (deviceType == ma_device_type_playback) { + ((ma_DirectSoundEnumerateAProc)pContext->dsound.DirectSoundEnumerateA)(ma_context_get_device_info_callback__dsound, &data); + } else { + ((ma_DirectSoundCaptureEnumerateAProc)pContext->dsound.DirectSoundCaptureEnumerateA)(ma_context_get_device_info_callback__dsound, &data); + } + + if (!data.found) { + return MA_NO_DEVICE; + } + } else { + // I don't think there's a way to get the name of the default device with DirectSound. In this case we just need to use defaults. + + // ID + ma_zero_memory(pDeviceInfo->id.dsound, 16); + + // Name / Description/ + if (deviceType == ma_device_type_playback) { + ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); + } else { + ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); + } + } + + // Retrieving detailed information is slightly different depending on the device type. + if (deviceType == ma_device_type_playback) { + // Playback. + ma_IDirectSound* pDirectSound; + ma_result result = ma_context_create_IDirectSound__dsound(pContext, shareMode, pDeviceID, &pDirectSound); + if (result != MA_SUCCESS) { + return result; + } + + MA_DSCAPS caps; + ma_zero_object(&caps); + caps.dwSize = sizeof(caps); + if (FAILED(ma_IDirectSound_GetCaps(pDirectSound, &caps))) { + return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSound_GetCaps() failed for playback device.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + + if ((caps.dwFlags & MA_DSCAPS_PRIMARYSTEREO) != 0) { + // It supports at least stereo, but could support more. + WORD channels = 2; + + // Look at the speaker configuration to get a better idea on the channel count. + DWORD speakerConfig; + if (SUCCEEDED(ma_IDirectSound_GetSpeakerConfig(pDirectSound, &speakerConfig))) { + ma_get_channels_from_speaker_config__dsound(speakerConfig, &channels, NULL); + } + + pDeviceInfo->minChannels = channels; + pDeviceInfo->maxChannels = channels; + } else { + // It does not support stereo, which means we are stuck with mono. + pDeviceInfo->minChannels = 1; + pDeviceInfo->maxChannels = 1; + } + + // Sample rate. + if ((caps.dwFlags & MA_DSCAPS_CONTINUOUSRATE) != 0) { + pDeviceInfo->minSampleRate = caps.dwMinSecondarySampleRate; + pDeviceInfo->maxSampleRate = caps.dwMaxSecondarySampleRate; + + // On my machine the min and max sample rates can return 100 and 200000 respectively. I'd rather these be within + // the range of our standard sample rates so I'm clamping. + if (caps.dwMinSecondarySampleRate < MA_MIN_SAMPLE_RATE && caps.dwMaxSecondarySampleRate >= MA_MIN_SAMPLE_RATE) { + pDeviceInfo->minSampleRate = MA_MIN_SAMPLE_RATE; + } + if (caps.dwMaxSecondarySampleRate > MA_MAX_SAMPLE_RATE && caps.dwMinSecondarySampleRate <= MA_MAX_SAMPLE_RATE) { + pDeviceInfo->maxSampleRate = MA_MAX_SAMPLE_RATE; + } + } else { + // Only supports a single sample rate. Set both min an max to the same thing. Do not clamp within the standard rates. + pDeviceInfo->minSampleRate = caps.dwMaxSecondarySampleRate; + pDeviceInfo->maxSampleRate = caps.dwMaxSecondarySampleRate; + } + + // DirectSound can support all formats. + pDeviceInfo->formatCount = ma_format_count - 1; // Minus one because we don't want to include ma_format_unknown. + for (ma_uint32 iFormat = 0; iFormat < pDeviceInfo->formatCount; ++iFormat) { + pDeviceInfo->formats[iFormat] = (ma_format)(iFormat + 1); // +1 to skip over ma_format_unknown. + } + + ma_IDirectSound_Release(pDirectSound); + } else { + // Capture. This is a little different to playback due to the say the supported formats are reported. Technically capture + // devices can support a number of different formats, but for simplicity and consistency with ma_device_init() I'm just + // reporting the best format. + ma_IDirectSoundCapture* pDirectSoundCapture; + ma_result result = ma_context_create_IDirectSoundCapture__dsound(pContext, shareMode, pDeviceID, &pDirectSoundCapture); + if (result != MA_SUCCESS) { + return result; + } + + WORD channels; + WORD bitsPerSample; + DWORD sampleRate; + result = ma_context_get_format_info_for_IDirectSoundCapture__dsound(pContext, pDirectSoundCapture, &channels, &bitsPerSample, &sampleRate); + if (result != MA_SUCCESS) { + ma_IDirectSoundCapture_Release(pDirectSoundCapture); + return result; + } + + pDeviceInfo->minChannels = channels; + pDeviceInfo->maxChannels = channels; + pDeviceInfo->minSampleRate = sampleRate; + pDeviceInfo->maxSampleRate = sampleRate; + pDeviceInfo->formatCount = 1; + if (bitsPerSample == 8) { + pDeviceInfo->formats[0] = ma_format_u8; + } else if (bitsPerSample == 16) { + pDeviceInfo->formats[0] = ma_format_s16; + } else if (bitsPerSample == 24) { + pDeviceInfo->formats[0] = ma_format_s24; + } else if (bitsPerSample == 32) { + pDeviceInfo->formats[0] = ma_format_s32; + } else { + ma_IDirectSoundCapture_Release(pDirectSoundCapture); + return MA_FORMAT_NOT_SUPPORTED; + } + + ma_IDirectSoundCapture_Release(pDirectSoundCapture); + } + + return MA_SUCCESS; +} + + +typedef struct +{ + ma_uint32 deviceCount; + ma_uint32 infoCount; + ma_device_info* pInfo; +} ma_device_enum_data__dsound; + +BOOL CALLBACK ma_enum_devices_callback__dsound(LPGUID lpGuid, LPCSTR lpcstrDescription, LPCSTR lpcstrModule, LPVOID lpContext) +{ + (void)lpcstrModule; + + ma_device_enum_data__dsound* pData = (ma_device_enum_data__dsound*)lpContext; + ma_assert(pData != NULL); + + if (pData->pInfo != NULL) { + if (pData->infoCount > 0) { + ma_zero_object(pData->pInfo); + ma_strncpy_s(pData->pInfo->name, sizeof(pData->pInfo->name), lpcstrDescription, (size_t)-1); + + if (lpGuid != NULL) { + ma_copy_memory(pData->pInfo->id.dsound, lpGuid, 16); + } else { + ma_zero_memory(pData->pInfo->id.dsound, 16); + } + + pData->pInfo += 1; + pData->infoCount -= 1; + pData->deviceCount += 1; + } + } else { + pData->deviceCount += 1; + } + + return TRUE; +} + +void ma_device_uninit__dsound(ma_device* pDevice) +{ + ma_assert(pDevice != NULL); + + if (pDevice->dsound.pCaptureBuffer != NULL) { + ma_IDirectSoundCaptureBuffer_Release((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer); + } + if (pDevice->dsound.pCapture != NULL) { + ma_IDirectSoundCapture_Release((ma_IDirectSoundCapture*)pDevice->dsound.pCapture); + } + + if (pDevice->dsound.pPlaybackBuffer != NULL) { + ma_IDirectSoundBuffer_Release((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer); + } + if (pDevice->dsound.pPlaybackPrimaryBuffer != NULL) { + ma_IDirectSoundBuffer_Release((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackPrimaryBuffer); + } + if (pDevice->dsound.pPlayback != NULL) { + ma_IDirectSound_Release((ma_IDirectSound*)pDevice->dsound.pPlayback); + } +} + +ma_result ma_config_to_WAVEFORMATEXTENSIBLE(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, const ma_channel* pChannelMap, WAVEFORMATEXTENSIBLE* pWF) +{ + GUID subformat; + switch (format) + { + case ma_format_u8: + case ma_format_s16: + case ma_format_s24: + //case ma_format_s24_32: + case ma_format_s32: + { + subformat = MA_GUID_KSDATAFORMAT_SUBTYPE_PCM; + } break; + + case ma_format_f32: + { + subformat = MA_GUID_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT; + } break; + + default: + return MA_FORMAT_NOT_SUPPORTED; + } + + ma_zero_object(pWF); + pWF->Format.cbSize = sizeof(*pWF); + pWF->Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE; + pWF->Format.nChannels = (WORD)channels; + pWF->Format.nSamplesPerSec = (DWORD)sampleRate; + pWF->Format.wBitsPerSample = (WORD)ma_get_bytes_per_sample(format)*8; + pWF->Format.nBlockAlign = (pWF->Format.nChannels * pWF->Format.wBitsPerSample) / 8; + pWF->Format.nAvgBytesPerSec = pWF->Format.nBlockAlign * pWF->Format.nSamplesPerSec; + pWF->Samples.wValidBitsPerSample = pWF->Format.wBitsPerSample; + pWF->dwChannelMask = ma_channel_map_to_channel_mask__win32(pChannelMap, channels); + pWF->SubFormat = subformat; + + return MA_SUCCESS; +} + +ma_result ma_device_init__dsound(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice) +{ + ma_result result; + + (void)pContext; + + ma_assert(pDevice != NULL); + ma_zero_object(&pDevice->dsound); + + ma_uint32 bufferSizeInMilliseconds = pConfig->bufferSizeInMilliseconds; + if (bufferSizeInMilliseconds == 0) { + bufferSizeInMilliseconds = ma_calculate_buffer_size_in_milliseconds_from_frames(pConfig->bufferSizeInFrames, pConfig->sampleRate); + } + + /* DirectSound should use a latency of about 20ms per period for low latency mode. */ + if (pDevice->usingDefaultBufferSize) { + if (pConfig->performanceProfile == ma_performance_profile_low_latency) { + bufferSizeInMilliseconds = 20 * pConfig->periods; + } else { + bufferSizeInMilliseconds = 200 * pConfig->periods; + } + } + + /* DirectSound breaks down with tiny buffer sizes (bad glitching and silent output). I am therefore restricting the size of the buffer to a minimum of 20 milliseconds. */ + if ((bufferSizeInMilliseconds/pConfig->periods) < 20) { + bufferSizeInMilliseconds = pConfig->periods * 20; + } + + // Unfortunately DirectSound uses different APIs and data structures for playback and catpure devices. We need to initialize + // the capture device first because we'll want to match it's buffer size and period count on the playback side if we're using + // full-duplex mode. + if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) { + WAVEFORMATEXTENSIBLE wf; + result = ma_config_to_WAVEFORMATEXTENSIBLE(pConfig->capture.format, pConfig->capture.channels, pConfig->sampleRate, pConfig->capture.channelMap, &wf); + if (result != MA_SUCCESS) { + return result; + } + + result = ma_context_create_IDirectSoundCapture__dsound(pContext, pConfig->capture.shareMode, pConfig->capture.pDeviceID, (ma_IDirectSoundCapture**)&pDevice->dsound.pCapture); + if (result != MA_SUCCESS) { + ma_device_uninit__dsound(pDevice); + return result; + } + + result = ma_context_get_format_info_for_IDirectSoundCapture__dsound(pContext, (ma_IDirectSoundCapture*)pDevice->dsound.pCapture, &wf.Format.nChannels, &wf.Format.wBitsPerSample, &wf.Format.nSamplesPerSec); + if (result != MA_SUCCESS) { + ma_device_uninit__dsound(pDevice); + return result; + } + + wf.Format.nBlockAlign = (wf.Format.nChannels * wf.Format.wBitsPerSample) / 8; + wf.Format.nAvgBytesPerSec = wf.Format.nBlockAlign * wf.Format.nSamplesPerSec; + wf.Samples.wValidBitsPerSample = wf.Format.wBitsPerSample; + wf.SubFormat = MA_GUID_KSDATAFORMAT_SUBTYPE_PCM; + + /* The size of the buffer must be a clean multiple of the period count. */ + ma_uint32 bufferSizeInFrames = (ma_calculate_buffer_size_in_frames_from_milliseconds(bufferSizeInMilliseconds, wf.Format.nSamplesPerSec) / pConfig->periods) * pConfig->periods; + + MA_DSCBUFFERDESC descDS; + ma_zero_object(&descDS); + descDS.dwSize = sizeof(descDS); + descDS.dwFlags = 0; + descDS.dwBufferBytes = bufferSizeInFrames * ma_get_bytes_per_frame(pDevice->capture.internalFormat, wf.Format.nChannels); + descDS.lpwfxFormat = (WAVEFORMATEX*)&wf; + if (FAILED(ma_IDirectSoundCapture_CreateCaptureBuffer((ma_IDirectSoundCapture*)pDevice->dsound.pCapture, &descDS, (ma_IDirectSoundCaptureBuffer**)&pDevice->dsound.pCaptureBuffer, NULL))) { + ma_device_uninit__dsound(pDevice); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundCapture_CreateCaptureBuffer() failed for capture device.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + + // Get the _actual_ properties of the buffer. + char rawdata[1024]; + WAVEFORMATEXTENSIBLE* pActualFormat = (WAVEFORMATEXTENSIBLE*)rawdata; + if (FAILED(ma_IDirectSoundCaptureBuffer_GetFormat((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, (WAVEFORMATEX*)pActualFormat, sizeof(rawdata), NULL))) { + ma_device_uninit__dsound(pDevice); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to retrieve the actual format of the capture device's buffer.", MA_FORMAT_NOT_SUPPORTED); + } + + pDevice->capture.internalFormat = ma_format_from_WAVEFORMATEX((WAVEFORMATEX*)pActualFormat); + pDevice->capture.internalChannels = pActualFormat->Format.nChannels; + pDevice->capture.internalSampleRate = pActualFormat->Format.nSamplesPerSec; + + // Get the internal channel map based on the channel mask. + if (pActualFormat->Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) { + ma_channel_mask_to_channel_map__win32(pActualFormat->dwChannelMask, pDevice->capture.internalChannels, pDevice->capture.internalChannelMap); + } else { + ma_channel_mask_to_channel_map__win32(wf.dwChannelMask, pDevice->capture.internalChannels, pDevice->capture.internalChannelMap); + } + + /* + After getting the actual format the size of the buffer in frames may have actually changed. However, we want this to be as close to what the + user has asked for as possible, so let's go ahead and release the old capture buffer and create a new one in this case. + */ + if (bufferSizeInFrames != (descDS.dwBufferBytes / ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels))) { + descDS.dwBufferBytes = bufferSizeInFrames * ma_get_bytes_per_frame(pDevice->capture.internalFormat, wf.Format.nChannels); + ma_IDirectSoundCaptureBuffer_Release((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer); + + if (FAILED(ma_IDirectSoundCapture_CreateCaptureBuffer((ma_IDirectSoundCapture*)pDevice->dsound.pCapture, &descDS, (ma_IDirectSoundCaptureBuffer**)&pDevice->dsound.pCaptureBuffer, NULL))) { + ma_device_uninit__dsound(pDevice); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] Second attempt at IDirectSoundCapture_CreateCaptureBuffer() failed for capture device.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + } + + /* DirectSound should give us a buffer exactly the size we asked for. */ + pDevice->capture.internalBufferSizeInFrames = bufferSizeInFrames; + pDevice->capture.internalPeriods = pConfig->periods; + } + + if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) { + WAVEFORMATEXTENSIBLE wf; + result = ma_config_to_WAVEFORMATEXTENSIBLE(pConfig->playback.format, pConfig->playback.channels, pConfig->sampleRate, pConfig->playback.channelMap, &wf); + if (result != MA_SUCCESS) { + return result; + } + + result = ma_context_create_IDirectSound__dsound(pContext, pConfig->playback.shareMode, pConfig->playback.pDeviceID, (ma_IDirectSound**)&pDevice->dsound.pPlayback); + if (result != MA_SUCCESS) { + ma_device_uninit__dsound(pDevice); + return result; + } + + MA_DSBUFFERDESC descDSPrimary; + ma_zero_object(&descDSPrimary); + descDSPrimary.dwSize = sizeof(MA_DSBUFFERDESC); + descDSPrimary.dwFlags = MA_DSBCAPS_PRIMARYBUFFER | MA_DSBCAPS_CTRLVOLUME; + if (FAILED(ma_IDirectSound_CreateSoundBuffer((ma_IDirectSound*)pDevice->dsound.pPlayback, &descDSPrimary, (ma_IDirectSoundBuffer**)&pDevice->dsound.pPlaybackPrimaryBuffer, NULL))) { + ma_device_uninit__dsound(pDevice); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSound_CreateSoundBuffer() failed for playback device's primary buffer.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + + + // We may want to make some adjustments to the format if we are using defaults. + MA_DSCAPS caps; + ma_zero_object(&caps); + caps.dwSize = sizeof(caps); + if (FAILED(ma_IDirectSound_GetCaps((ma_IDirectSound*)pDevice->dsound.pPlayback, &caps))) { + ma_device_uninit__dsound(pDevice); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSound_GetCaps() failed for playback device.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + + if (pDevice->playback.usingDefaultChannels) { + if ((caps.dwFlags & MA_DSCAPS_PRIMARYSTEREO) != 0) { + // It supports at least stereo, but could support more. + wf.Format.nChannels = 2; + + // Look at the speaker configuration to get a better idea on the channel count. + DWORD speakerConfig; + if (SUCCEEDED(ma_IDirectSound_GetSpeakerConfig((ma_IDirectSound*)pDevice->dsound.pPlayback, &speakerConfig))) { + ma_get_channels_from_speaker_config__dsound(speakerConfig, &wf.Format.nChannels, &wf.dwChannelMask); + } + } else { + // It does not support stereo, which means we are stuck with mono. + wf.Format.nChannels = 1; + } + } + + if (pDevice->usingDefaultSampleRate) { + // We base the sample rate on the values returned by GetCaps(). + if ((caps.dwFlags & MA_DSCAPS_CONTINUOUSRATE) != 0) { + wf.Format.nSamplesPerSec = ma_get_best_sample_rate_within_range(caps.dwMinSecondarySampleRate, caps.dwMaxSecondarySampleRate); + } else { + wf.Format.nSamplesPerSec = caps.dwMaxSecondarySampleRate; + } + } + + wf.Format.nBlockAlign = (wf.Format.nChannels * wf.Format.wBitsPerSample) / 8; + wf.Format.nAvgBytesPerSec = wf.Format.nBlockAlign * wf.Format.nSamplesPerSec; + + // From MSDN: + // + // The method succeeds even if the hardware does not support the requested format; DirectSound sets the buffer to the closest + // supported format. To determine whether this has happened, an application can call the GetFormat method for the primary buffer + // and compare the result with the format that was requested with the SetFormat method. + if (FAILED(ma_IDirectSoundBuffer_SetFormat((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackPrimaryBuffer, (WAVEFORMATEX*)&wf))) { + ma_device_uninit__dsound(pDevice); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to set format of playback device's primary buffer.", MA_FORMAT_NOT_SUPPORTED); + } + + // Get the _actual_ properties of the buffer. + char rawdata[1024]; + WAVEFORMATEXTENSIBLE* pActualFormat = (WAVEFORMATEXTENSIBLE*)rawdata; + if (FAILED(ma_IDirectSoundBuffer_GetFormat((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackPrimaryBuffer, (WAVEFORMATEX*)pActualFormat, sizeof(rawdata), NULL))) { + ma_device_uninit__dsound(pDevice); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to retrieve the actual format of the playback device's primary buffer.", MA_FORMAT_NOT_SUPPORTED); + } + + pDevice->playback.internalFormat = ma_format_from_WAVEFORMATEX((WAVEFORMATEX*)pActualFormat); + pDevice->playback.internalChannels = pActualFormat->Format.nChannels; + pDevice->playback.internalSampleRate = pActualFormat->Format.nSamplesPerSec; + + // Get the internal channel map based on the channel mask. + if (pActualFormat->Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) { + ma_channel_mask_to_channel_map__win32(pActualFormat->dwChannelMask, pDevice->playback.internalChannels, pDevice->playback.internalChannelMap); + } else { + ma_channel_mask_to_channel_map__win32(wf.dwChannelMask, pDevice->playback.internalChannels, pDevice->playback.internalChannelMap); + } + + /* The size of the buffer must be a clean multiple of the period count. */ + ma_uint32 bufferSizeInFrames = (ma_calculate_buffer_size_in_frames_from_milliseconds(bufferSizeInMilliseconds, pDevice->playback.internalSampleRate) / pConfig->periods) * pConfig->periods; + + // Meaning of dwFlags (from MSDN): + // + // DSBCAPS_CTRLPOSITIONNOTIFY + // The buffer has position notification capability. + // + // DSBCAPS_GLOBALFOCUS + // With this flag set, an application using DirectSound can continue to play its buffers if the user switches focus to + // another application, even if the new application uses DirectSound. + // + // DSBCAPS_GETCURRENTPOSITION2 + // In the first version of DirectSound, the play cursor was significantly ahead of the actual playing sound on emulated + // sound cards; it was directly behind the write cursor. Now, if the DSBCAPS_GETCURRENTPOSITION2 flag is specified, the + // application can get a more accurate play cursor. + MA_DSBUFFERDESC descDS; + ma_zero_object(&descDS); + descDS.dwSize = sizeof(descDS); + descDS.dwFlags = MA_DSBCAPS_CTRLPOSITIONNOTIFY | MA_DSBCAPS_GLOBALFOCUS | MA_DSBCAPS_GETCURRENTPOSITION2; + descDS.dwBufferBytes = bufferSizeInFrames * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels); + descDS.lpwfxFormat = (WAVEFORMATEX*)&wf; + if (FAILED(ma_IDirectSound_CreateSoundBuffer((ma_IDirectSound*)pDevice->dsound.pPlayback, &descDS, (ma_IDirectSoundBuffer**)&pDevice->dsound.pPlaybackBuffer, NULL))) { + ma_device_uninit__dsound(pDevice); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSound_CreateSoundBuffer() failed for playback device's secondary buffer.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + + /* DirectSound should give us a buffer exactly the size we asked for. */ + pDevice->playback.internalBufferSizeInFrames = bufferSizeInFrames; + pDevice->playback.internalPeriods = pConfig->periods; + } + + return MA_SUCCESS; +} + + +ma_result ma_device_main_loop__dsound(ma_device* pDevice) +{ + ma_result result = MA_SUCCESS; + ma_uint32 bpfCapture = ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels); + ma_uint32 bpfPlayback = ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels); + HRESULT hr; + DWORD lockOffsetInBytesCapture; + DWORD lockSizeInBytesCapture; + DWORD mappedSizeInBytesCapture; + void* pMappedBufferCapture; + DWORD lockOffsetInBytesPlayback; + DWORD lockSizeInBytesPlayback; + DWORD mappedSizeInBytesPlayback; + void* pMappedBufferPlayback; + DWORD prevReadCursorInBytesCapture = 0; + DWORD prevPlayCursorInBytesPlayback = 0; + ma_bool32 physicalPlayCursorLoopFlagPlayback = 0; + DWORD virtualWriteCursorInBytesPlayback = 0; + ma_bool32 virtualWriteCursorLoopFlagPlayback = 0; + ma_bool32 isPlaybackDeviceStarted = MA_FALSE; + ma_uint32 framesWrittenToPlaybackDevice = 0; /* For knowing whether or not the playback device needs to be started. */ + ma_uint32 waitTimeInMilliseconds = 1; + + ma_assert(pDevice != NULL); + + /* The first thing to do is start the capture device. The playback device is only started after the first period is written. */ + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + if (FAILED(ma_IDirectSoundCaptureBuffer_Start((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, MA_DSCBSTART_LOOPING))) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundCaptureBuffer_Start() failed.", MA_FAILED_TO_START_BACKEND_DEVICE); + } + } + + while (ma_device__get_state(pDevice) == MA_STATE_STARTED) { + switch (pDevice->type) + { + case ma_device_type_duplex: + { + DWORD physicalCaptureCursorInBytes; + DWORD physicalReadCursorInBytes; + if (FAILED(ma_IDirectSoundCaptureBuffer_GetCurrentPosition((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, &physicalCaptureCursorInBytes, &physicalReadCursorInBytes))) { + return MA_ERROR; + } + + /* If nothing is available we just sleep for a bit and return from this iteration. */ + if (physicalReadCursorInBytes == prevReadCursorInBytesCapture) { + ma_sleep(waitTimeInMilliseconds); + continue; /* Nothing is available in the capture buffer. */ + } + + /* + The current position has moved. We need to map all of the captured samples and write them to the playback device, making sure + we don't return until every frame has been copied over. + */ + if (prevReadCursorInBytesCapture < physicalReadCursorInBytes) { + /* The capture position has not looped. This is the simple case. */ + lockOffsetInBytesCapture = prevReadCursorInBytesCapture; + lockSizeInBytesCapture = (physicalReadCursorInBytes - prevReadCursorInBytesCapture); + } else { + /* + The capture position has looped. This is the more complex case. Map to the end of the buffer. If this does not return anything, + do it again from the start. + */ + if (prevReadCursorInBytesCapture < pDevice->capture.internalBufferSizeInFrames*bpfCapture) { + /* Lock up to the end of the buffer. */ + lockOffsetInBytesCapture = prevReadCursorInBytesCapture; + lockSizeInBytesCapture = (pDevice->capture.internalBufferSizeInFrames*bpfCapture) - prevReadCursorInBytesCapture; + } else { + /* Lock starting from the start of the buffer. */ + lockOffsetInBytesCapture = 0; + lockSizeInBytesCapture = physicalReadCursorInBytes; + } + } + + if (lockSizeInBytesCapture == 0) { + ma_sleep(waitTimeInMilliseconds); + continue; /* Nothing is available in the capture buffer. */ + } + + hr = ma_IDirectSoundCaptureBuffer_Lock((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, lockOffsetInBytesCapture, lockSizeInBytesCapture, &pMappedBufferCapture, &mappedSizeInBytesCapture, NULL, NULL, 0); + if (FAILED(hr)) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to map buffer from capture device in preparation for writing to the device.", MA_FAILED_TO_MAP_DEVICE_BUFFER); + } + + + /* At this point we have some input data that we need to output. We do not return until every mapped frame of the input data is written to the playback device. */ + pDevice->capture._dspFrameCount = mappedSizeInBytesCapture / bpfCapture; + pDevice->capture._dspFrames = (const ma_uint8*)pMappedBufferCapture; + for (;;) { /* Keep writing to the playback device. */ + ma_uint8 inputFramesInExternalFormat[4096]; + ma_uint32 inputFramesInExternalFormatCap = sizeof(inputFramesInExternalFormat) / ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels); + ma_uint32 inputFramesInExternalFormatCount; + ma_uint8 outputFramesInExternalFormat[4096]; + ma_uint32 outputFramesInExternalFormatCap = sizeof(outputFramesInExternalFormat) / ma_get_bytes_per_frame(pDevice->playback.format, pDevice->playback.channels); + + inputFramesInExternalFormatCount = (ma_uint32)ma_pcm_converter_read(&pDevice->capture.converter, inputFramesInExternalFormat, ma_min(inputFramesInExternalFormatCap, outputFramesInExternalFormatCap)); + if (inputFramesInExternalFormatCount == 0) { + break; /* No more input data. */ + } + + pDevice->onData(pDevice, outputFramesInExternalFormat, inputFramesInExternalFormat, inputFramesInExternalFormatCount); + + /* At this point we have input and output data in external format. All we need to do now is convert it to the output format. This may take a few passes. */ + pDevice->playback._dspFrameCount = inputFramesInExternalFormatCount; + pDevice->playback._dspFrames = (const ma_uint8*)outputFramesInExternalFormat; + for (;;) { + ma_uint32 framesWrittenThisIteration; + DWORD physicalPlayCursorInBytes; + DWORD physicalWriteCursorInBytes; + DWORD availableBytesPlayback; + DWORD silentPaddingInBytes = 0; /* <-- Must be initialized to 0. */ + + /* We need the physical play and write cursors. */ + if (FAILED(ma_IDirectSoundBuffer_GetCurrentPosition((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, &physicalPlayCursorInBytes, &physicalWriteCursorInBytes))) { + break; + } + + if (physicalPlayCursorInBytes < prevPlayCursorInBytesPlayback) { + physicalPlayCursorLoopFlagPlayback = !physicalPlayCursorLoopFlagPlayback; + } + prevPlayCursorInBytesPlayback = physicalPlayCursorInBytes; + + /* If there's any bytes available for writing we can do that now. The space between the virtual cursor position and play cursor. */ + if (physicalPlayCursorLoopFlagPlayback == virtualWriteCursorLoopFlagPlayback) { + /* Same loop iteration. The available bytes wraps all the way around from the virtual write cursor to the physical play cursor. */ + if (physicalPlayCursorInBytes <= virtualWriteCursorInBytesPlayback) { + availableBytesPlayback = (pDevice->playback.internalBufferSizeInFrames*bpfPlayback) - virtualWriteCursorInBytesPlayback; + availableBytesPlayback += physicalPlayCursorInBytes; /* Wrap around. */ + } else { + /* This is an error. */ + #ifdef MA_DEBUG_OUTPUT + printf("[DirectSound] (Duplex/Playback) WARNING: Play cursor has moved in front of the write cursor (same loop iterations). physicalPlayCursorInBytes=%d, virtualWriteCursorInBytes=%d.\n", physicalPlayCursorInBytes, virtualWriteCursorInBytesPlayback); + #endif + availableBytesPlayback = 0; + } + } else { + /* Different loop iterations. The available bytes only goes from the virtual write cursor to the physical play cursor. */ + if (physicalPlayCursorInBytes >= virtualWriteCursorInBytesPlayback) { + availableBytesPlayback = physicalPlayCursorInBytes - virtualWriteCursorInBytesPlayback; + } else { + /* This is an error. */ + #ifdef MA_DEBUG_OUTPUT + printf("[DirectSound] (Duplex/Playback) WARNING: Write cursor has moved behind the play cursor (different loop iterations). physicalPlayCursorInBytes=%d, virtualWriteCursorInBytes=%d.\n", physicalPlayCursorInBytes, virtualWriteCursorInBytesPlayback); + #endif + availableBytesPlayback = 0; + } + } + + #ifdef MA_DEBUG_OUTPUT + //printf("[DirectSound] (Duplex/Playback) physicalPlayCursorInBytes=%d, availableBytesPlayback=%d\n", physicalPlayCursorInBytes, availableBytesPlayback); + #endif + + /* If there's no room available for writing we need to wait for more. */ + if (availableBytesPlayback == 0) { + /* If we haven't started the device yet, this will never get beyond 0. In this case we need to get the device started. */ + if (!isPlaybackDeviceStarted) { + if (FAILED(ma_IDirectSoundBuffer_Play((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, 0, 0, MA_DSBPLAY_LOOPING))) { + ma_IDirectSoundCaptureBuffer_Stop((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundBuffer_Play() failed.", MA_FAILED_TO_START_BACKEND_DEVICE); + } + isPlaybackDeviceStarted = MA_TRUE; + } else { + ma_sleep(waitTimeInMilliseconds); + continue; + } + } + + + /* Getting here means there room available somewhere. We limit this to either the end of the buffer or the physical play cursor, whichever is closest. */ + lockOffsetInBytesPlayback = virtualWriteCursorInBytesPlayback; + if (physicalPlayCursorLoopFlagPlayback == virtualWriteCursorLoopFlagPlayback) { + /* Same loop iteration. Go up to the end of the buffer. */ + lockSizeInBytesPlayback = (pDevice->playback.internalBufferSizeInFrames*bpfPlayback) - virtualWriteCursorInBytesPlayback; + } else { + /* Different loop iterations. Go up to the physical play cursor. */ + lockSizeInBytesPlayback = physicalPlayCursorInBytes - virtualWriteCursorInBytesPlayback; + } + + hr = ma_IDirectSoundBuffer_Lock((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, lockOffsetInBytesPlayback, lockSizeInBytesPlayback, &pMappedBufferPlayback, &mappedSizeInBytesPlayback, NULL, NULL, 0); + if (FAILED(hr)) { + result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to map buffer from playback device in preparation for writing to the device.", MA_FAILED_TO_MAP_DEVICE_BUFFER); + break; + } + + /* + Experiment: If the playback buffer is being starved, pad it with some silence to get it back in sync. This will cause a glitch, but it may prevent + endless glitching due to it constantly running out of data. + */ + if (isPlaybackDeviceStarted) { + DWORD bytesQueuedForPlayback = (pDevice->playback.internalBufferSizeInFrames*bpfPlayback) - availableBytesPlayback; + if (bytesQueuedForPlayback < ((pDevice->playback.internalBufferSizeInFrames/pDevice->playback.internalPeriods)*bpfPlayback)) { + silentPaddingInBytes = ((pDevice->playback.internalBufferSizeInFrames/pDevice->playback.internalPeriods)*2*bpfPlayback) - bytesQueuedForPlayback; + if (silentPaddingInBytes > lockSizeInBytesPlayback) { + silentPaddingInBytes = lockSizeInBytesPlayback; + } + + #ifdef MA_DEBUG_OUTPUT + printf("[DirectSound] (Duplex/Playback) Playback buffer starved. availableBytesPlayback=%d, silentPaddingInBytes=%d\n", availableBytesPlayback, silentPaddingInBytes); + #endif + } + } + + /* At this point we have a buffer for output. */ + if (silentPaddingInBytes > 0) { + ma_zero_memory(pMappedBufferPlayback, silentPaddingInBytes); + framesWrittenThisIteration = silentPaddingInBytes/bpfPlayback; + } else { + framesWrittenThisIteration = (ma_uint32)ma_pcm_converter_read(&pDevice->playback.converter, pMappedBufferPlayback, mappedSizeInBytesPlayback/bpfPlayback); + } + + + hr = ma_IDirectSoundBuffer_Unlock((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, pMappedBufferPlayback, framesWrittenThisIteration*bpfPlayback, NULL, 0); + if (FAILED(hr)) { + result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to unlock internal buffer from playback device after writing to the device.", MA_FAILED_TO_UNMAP_DEVICE_BUFFER); + break; + } + + virtualWriteCursorInBytesPlayback += framesWrittenThisIteration*bpfPlayback; + if ((virtualWriteCursorInBytesPlayback/bpfPlayback) == pDevice->playback.internalBufferSizeInFrames) { + virtualWriteCursorInBytesPlayback = 0; + virtualWriteCursorLoopFlagPlayback = !virtualWriteCursorLoopFlagPlayback; + } + + /* + We may need to start the device. We want two full periods to be written before starting the playback device. Having an extra period adds + a bit of a buffer to prevent the playback buffer from getting starved. + */ + framesWrittenToPlaybackDevice += framesWrittenThisIteration; + if (!isPlaybackDeviceStarted && framesWrittenToPlaybackDevice >= ((pDevice->playback.internalBufferSizeInFrames/pDevice->playback.internalPeriods)*2)) { + if (FAILED(ma_IDirectSoundBuffer_Play((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, 0, 0, MA_DSBPLAY_LOOPING))) { + ma_IDirectSoundCaptureBuffer_Stop((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundBuffer_Play() failed.", MA_FAILED_TO_START_BACKEND_DEVICE); + } + isPlaybackDeviceStarted = MA_TRUE; + } + + if (framesWrittenThisIteration < mappedSizeInBytesPlayback/bpfPlayback) { + break; /* We're finished with the output data.*/ + } + } + + if (inputFramesInExternalFormatCount < inputFramesInExternalFormatCap) { + break; /* We just consumed every input sample. */ + } + } + + + /* At this point we're done with the mapped portion of the capture buffer. */ + hr = ma_IDirectSoundCaptureBuffer_Unlock((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, pMappedBufferCapture, mappedSizeInBytesCapture, NULL, 0); + if (FAILED(hr)) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to unlock internal buffer from capture device after reading from the device.", MA_FAILED_TO_UNMAP_DEVICE_BUFFER); + } + prevReadCursorInBytesCapture = (lockOffsetInBytesCapture + mappedSizeInBytesCapture); + } break; + + + + case ma_device_type_capture: + { + DWORD physicalCaptureCursorInBytes; + DWORD physicalReadCursorInBytes; + if (FAILED(ma_IDirectSoundCaptureBuffer_GetCurrentPosition((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, &physicalCaptureCursorInBytes, &physicalReadCursorInBytes))) { + return MA_ERROR; + } + + /* If the previous capture position is the same as the current position we need to wait a bit longer. */ + if (prevReadCursorInBytesCapture == physicalReadCursorInBytes) { + ma_sleep(waitTimeInMilliseconds); + continue; + } + + /* Getting here means we have capture data available. */ + if (prevReadCursorInBytesCapture < physicalReadCursorInBytes) { + /* The capture position has not looped. This is the simple case. */ + lockOffsetInBytesCapture = prevReadCursorInBytesCapture; + lockSizeInBytesCapture = (physicalReadCursorInBytes - prevReadCursorInBytesCapture); + } else { + /* + The capture position has looped. This is the more complex case. Map to the end of the buffer. If this does not return anything, + do it again from the start. + */ + if (prevReadCursorInBytesCapture < pDevice->capture.internalBufferSizeInFrames*bpfCapture) { + /* Lock up to the end of the buffer. */ + lockOffsetInBytesCapture = prevReadCursorInBytesCapture; + lockSizeInBytesCapture = (pDevice->capture.internalBufferSizeInFrames*bpfCapture) - prevReadCursorInBytesCapture; + } else { + /* Lock starting from the start of the buffer. */ + lockOffsetInBytesCapture = 0; + lockSizeInBytesCapture = physicalReadCursorInBytes; + } + } + + #ifdef MA_DEBUG_OUTPUT + //printf("[DirectSound] (Capture) physicalCaptureCursorInBytes=%d, physicalReadCursorInBytes=%d\n", physicalCaptureCursorInBytes, physicalReadCursorInBytes); + //printf("[DirectSound] (Capture) lockOffsetInBytesCapture=%d, lockSizeInBytesCapture=%d\n", lockOffsetInBytesCapture, lockSizeInBytesCapture); + #endif + + if (lockSizeInBytesCapture < (pDevice->capture.internalBufferSizeInFrames/pDevice->capture.internalPeriods)) { + ma_sleep(waitTimeInMilliseconds); + continue; /* Nothing is available in the capture buffer. */ + } + + hr = ma_IDirectSoundCaptureBuffer_Lock((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, lockOffsetInBytesCapture, lockSizeInBytesCapture, &pMappedBufferCapture, &mappedSizeInBytesCapture, NULL, NULL, 0); + if (FAILED(hr)) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to map buffer from capture device in preparation for writing to the device.", MA_FAILED_TO_MAP_DEVICE_BUFFER); + } + + #ifdef MA_DEBUG_OUTPUT + if (lockSizeInBytesCapture != mappedSizeInBytesCapture) { + printf("[DirectSound] (Capture) lockSizeInBytesCapture=%d != mappedSizeInBytesCapture=%d\n", lockSizeInBytesCapture, mappedSizeInBytesCapture); + } + #endif + + /* Optimization: If we are running as a passthrough we can pass the mapped pointer to the callback directly. */ + if (pDevice->capture.converter.isPassthrough) { + /* Passthrough. */ + pDevice->onData(pDevice, NULL, pMappedBufferCapture, mappedSizeInBytesCapture/bpfCapture); + } else { + /* Not a passthrough. */ + ma_device__send_frames_to_client(pDevice, mappedSizeInBytesCapture/bpfCapture, pMappedBufferCapture); + } + + hr = ma_IDirectSoundCaptureBuffer_Unlock((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, pMappedBufferCapture, mappedSizeInBytesCapture, NULL, 0); + if (FAILED(hr)) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to unlock internal buffer from capture device after reading from the device.", MA_FAILED_TO_UNMAP_DEVICE_BUFFER); + } + prevReadCursorInBytesCapture = lockOffsetInBytesCapture + mappedSizeInBytesCapture; + + if (prevReadCursorInBytesCapture == (pDevice->capture.internalBufferSizeInFrames*bpfCapture)) { + prevReadCursorInBytesCapture = 0; + } + } break; + + + + case ma_device_type_playback: + { + DWORD availableBytesPlayback; + DWORD physicalPlayCursorInBytes; + DWORD physicalWriteCursorInBytes; + if (FAILED(ma_IDirectSoundBuffer_GetCurrentPosition((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, &physicalPlayCursorInBytes, &physicalWriteCursorInBytes))) { + break; + } + + if (physicalPlayCursorInBytes < prevPlayCursorInBytesPlayback) { + physicalPlayCursorLoopFlagPlayback = !physicalPlayCursorLoopFlagPlayback; + } + prevPlayCursorInBytesPlayback = physicalPlayCursorInBytes; + + /* If there's any bytes available for writing we can do that now. The space between the virtual cursor position and play cursor. */ + if (physicalPlayCursorLoopFlagPlayback == virtualWriteCursorLoopFlagPlayback) { + /* Same loop iteration. The available bytes wraps all the way around from the virtual write cursor to the physical play cursor. */ + if (physicalPlayCursorInBytes <= virtualWriteCursorInBytesPlayback) { + availableBytesPlayback = (pDevice->playback.internalBufferSizeInFrames*bpfPlayback) - virtualWriteCursorInBytesPlayback; + availableBytesPlayback += physicalPlayCursorInBytes; /* Wrap around. */ + } else { + /* This is an error. */ + #ifdef MA_DEBUG_OUTPUT + printf("[DirectSound] (Playback) WARNING: Play cursor has moved in front of the write cursor (same loop iterations). physicalPlayCursorInBytes=%d, virtualWriteCursorInBytes=%d.\n", physicalPlayCursorInBytes, virtualWriteCursorInBytesPlayback); + #endif + availableBytesPlayback = 0; + } + } else { + /* Different loop iterations. The available bytes only goes from the virtual write cursor to the physical play cursor. */ + if (physicalPlayCursorInBytes >= virtualWriteCursorInBytesPlayback) { + availableBytesPlayback = physicalPlayCursorInBytes - virtualWriteCursorInBytesPlayback; + } else { + /* This is an error. */ + #ifdef MA_DEBUG_OUTPUT + printf("[DirectSound] (Playback) WARNING: Write cursor has moved behind the play cursor (different loop iterations). physicalPlayCursorInBytes=%d, virtualWriteCursorInBytes=%d.\n", physicalPlayCursorInBytes, virtualWriteCursorInBytesPlayback); + #endif + availableBytesPlayback = 0; + } + } + + #ifdef MA_DEBUG_OUTPUT + //printf("[DirectSound] (Playback) physicalPlayCursorInBytes=%d, availableBytesPlayback=%d\n", physicalPlayCursorInBytes, availableBytesPlayback); + #endif + + /* If there's no room available for writing we need to wait for more. */ + if (availableBytesPlayback < (pDevice->playback.internalBufferSizeInFrames/pDevice->playback.internalPeriods)) { + /* If we haven't started the device yet, this will never get beyond 0. In this case we need to get the device started. */ + if (availableBytesPlayback == 0 && !isPlaybackDeviceStarted) { + if (FAILED(ma_IDirectSoundBuffer_Play((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, 0, 0, MA_DSBPLAY_LOOPING))) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundBuffer_Play() failed.", MA_FAILED_TO_START_BACKEND_DEVICE); + } + isPlaybackDeviceStarted = MA_TRUE; + } else { + ma_sleep(waitTimeInMilliseconds); + continue; + } + } + + /* Getting here means there room available somewhere. We limit this to either the end of the buffer or the physical play cursor, whichever is closest. */ + lockOffsetInBytesPlayback = virtualWriteCursorInBytesPlayback; + if (physicalPlayCursorLoopFlagPlayback == virtualWriteCursorLoopFlagPlayback) { + /* Same loop iteration. Go up to the end of the buffer. */ + lockSizeInBytesPlayback = (pDevice->playback.internalBufferSizeInFrames*bpfPlayback) - virtualWriteCursorInBytesPlayback; + } else { + /* Different loop iterations. Go up to the physical play cursor. */ + lockSizeInBytesPlayback = physicalPlayCursorInBytes - virtualWriteCursorInBytesPlayback; + } + + hr = ma_IDirectSoundBuffer_Lock((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, lockOffsetInBytesPlayback, lockSizeInBytesPlayback, &pMappedBufferPlayback, &mappedSizeInBytesPlayback, NULL, NULL, 0); + if (FAILED(hr)) { + result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to map buffer from playback device in preparation for writing to the device.", MA_FAILED_TO_MAP_DEVICE_BUFFER); + break; + } + + /* + At this point we have a buffer for output. If we don't need to do any data conversion we can pass the mapped pointer to the buffer directly. Otherwise + we need to convert the data. + */ + if (pDevice->playback.converter.isPassthrough) { + /* Passthrough. */ + pDevice->onData(pDevice, pMappedBufferPlayback, NULL, (mappedSizeInBytesPlayback/bpfPlayback)); + } else { + /* Conversion. */ + ma_device__read_frames_from_client(pDevice, (mappedSizeInBytesPlayback/bpfPlayback), pMappedBufferPlayback); + } + + hr = ma_IDirectSoundBuffer_Unlock((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, pMappedBufferPlayback, mappedSizeInBytesPlayback, NULL, 0); + if (FAILED(hr)) { + result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to unlock internal buffer from playback device after writing to the device.", MA_FAILED_TO_UNMAP_DEVICE_BUFFER); + break; + } + + virtualWriteCursorInBytesPlayback += mappedSizeInBytesPlayback; + if (virtualWriteCursorInBytesPlayback == pDevice->playback.internalBufferSizeInFrames*bpfPlayback) { + virtualWriteCursorInBytesPlayback = 0; + virtualWriteCursorLoopFlagPlayback = !virtualWriteCursorLoopFlagPlayback; + } + + /* + We may need to start the device. We want two full periods to be written before starting the playback device. Having an extra period adds + a bit of a buffer to prevent the playback buffer from getting starved. + */ + framesWrittenToPlaybackDevice += mappedSizeInBytesPlayback/bpfPlayback; + if (!isPlaybackDeviceStarted && framesWrittenToPlaybackDevice >= (pDevice->playback.internalBufferSizeInFrames/pDevice->playback.internalPeriods)) { + if (FAILED(ma_IDirectSoundBuffer_Play((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, 0, 0, MA_DSBPLAY_LOOPING))) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundBuffer_Play() failed.", MA_FAILED_TO_START_BACKEND_DEVICE); + } + isPlaybackDeviceStarted = MA_TRUE; + } + } break; + + + default: return MA_INVALID_ARGS; /* Invalid device type. */ + } + + if (result != MA_SUCCESS) { + return result; + } + } + + /* Getting here means the device is being stopped. */ + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + if (FAILED(ma_IDirectSoundCaptureBuffer_Stop((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer))) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundCaptureBuffer_Stop() failed.", MA_FAILED_TO_STOP_BACKEND_DEVICE); + } + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + /* The playback device should be drained before stopping. All we do is wait until the available bytes is equal to the size of the buffer. */ + if (isPlaybackDeviceStarted) { + for (;;) { + DWORD availableBytesPlayback = 0; + DWORD physicalPlayCursorInBytes; + DWORD physicalWriteCursorInBytes; + if (FAILED(ma_IDirectSoundBuffer_GetCurrentPosition((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, &physicalPlayCursorInBytes, &physicalWriteCursorInBytes))) { + break; + } + + if (physicalPlayCursorInBytes < prevPlayCursorInBytesPlayback) { + physicalPlayCursorLoopFlagPlayback = !physicalPlayCursorLoopFlagPlayback; + } + prevPlayCursorInBytesPlayback = physicalPlayCursorInBytes; + + if (physicalPlayCursorLoopFlagPlayback == virtualWriteCursorLoopFlagPlayback) { + /* Same loop iteration. The available bytes wraps all the way around from the virtual write cursor to the physical play cursor. */ + if (physicalPlayCursorInBytes <= virtualWriteCursorInBytesPlayback) { + availableBytesPlayback = (pDevice->playback.internalBufferSizeInFrames*bpfPlayback) - virtualWriteCursorInBytesPlayback; + availableBytesPlayback += physicalPlayCursorInBytes; /* Wrap around. */ + } else { + break; + } + } else { + /* Different loop iterations. The available bytes only goes from the virtual write cursor to the physical play cursor. */ + if (physicalPlayCursorInBytes >= virtualWriteCursorInBytesPlayback) { + availableBytesPlayback = physicalPlayCursorInBytes - virtualWriteCursorInBytesPlayback; + } else { + break; + } + } + + if (availableBytesPlayback >= (pDevice->playback.internalBufferSizeInFrames*bpfPlayback)) { + break; + } + + ma_sleep(waitTimeInMilliseconds); + } + } + + if (FAILED(ma_IDirectSoundBuffer_Stop((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer))) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundBuffer_Stop() failed.", MA_FAILED_TO_STOP_BACKEND_DEVICE); + } + + ma_IDirectSoundBuffer_SetCurrentPosition((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, 0); + } + + return MA_SUCCESS; +} + +ma_result ma_context_uninit__dsound(ma_context* pContext) +{ + ma_assert(pContext != NULL); + ma_assert(pContext->backend == ma_backend_dsound); + + ma_dlclose(pContext->dsound.hDSoundDLL); + + return MA_SUCCESS; +} + +ma_result ma_context_init__dsound(ma_context* pContext) +{ + ma_assert(pContext != NULL); + + pContext->dsound.hDSoundDLL = ma_dlopen("dsound.dll"); + if (pContext->dsound.hDSoundDLL == NULL) { + return MA_API_NOT_FOUND; + } + + pContext->dsound.DirectSoundCreate = ma_dlsym(pContext->dsound.hDSoundDLL, "DirectSoundCreate"); + pContext->dsound.DirectSoundEnumerateA = ma_dlsym(pContext->dsound.hDSoundDLL, "DirectSoundEnumerateA"); + pContext->dsound.DirectSoundCaptureCreate = ma_dlsym(pContext->dsound.hDSoundDLL, "DirectSoundCaptureCreate"); + pContext->dsound.DirectSoundCaptureEnumerateA = ma_dlsym(pContext->dsound.hDSoundDLL, "DirectSoundCaptureEnumerateA"); + + pContext->onUninit = ma_context_uninit__dsound; + pContext->onDeviceIDEqual = ma_context_is_device_id_equal__dsound; + pContext->onEnumDevices = ma_context_enumerate_devices__dsound; + pContext->onGetDeviceInfo = ma_context_get_device_info__dsound; + pContext->onDeviceInit = ma_device_init__dsound; + pContext->onDeviceUninit = ma_device_uninit__dsound; + pContext->onDeviceStart = NULL; /* Not used. Started in onDeviceMainLoop. */ + pContext->onDeviceStop = NULL; /* Not used. Stopped in onDeviceMainLoop. */ + pContext->onDeviceWrite = NULL; + pContext->onDeviceRead = NULL; + pContext->onDeviceMainLoop = ma_device_main_loop__dsound; + + return MA_SUCCESS; +} +#endif + + + +/////////////////////////////////////////////////////////////////////////////// +// +// WinMM Backend +// +/////////////////////////////////////////////////////////////////////////////// +#ifdef MA_HAS_WINMM + +// Some older compilers don't have WAVEOUTCAPS2A and WAVEINCAPS2A, so we'll need to write this ourselves. These structures +// are exactly the same as the older ones but they have a few GUIDs for manufacturer/product/name identification. I'm keeping +// the names the same as the Win32 library for consistency, but namespaced to avoid naming conflicts with the Win32 version. +typedef struct +{ + WORD wMid; + WORD wPid; + MMVERSION vDriverVersion; + CHAR szPname[MAXPNAMELEN]; + DWORD dwFormats; + WORD wChannels; + WORD wReserved1; + DWORD dwSupport; + GUID ManufacturerGuid; + GUID ProductGuid; + GUID NameGuid; +} MA_WAVEOUTCAPS2A; +typedef struct +{ + WORD wMid; + WORD wPid; + MMVERSION vDriverVersion; + CHAR szPname[MAXPNAMELEN]; + DWORD dwFormats; + WORD wChannels; + WORD wReserved1; + GUID ManufacturerGuid; + GUID ProductGuid; + GUID NameGuid; +} MA_WAVEINCAPS2A; + +typedef UINT (WINAPI * MA_PFN_waveOutGetNumDevs)(void); +typedef MMRESULT (WINAPI * MA_PFN_waveOutGetDevCapsA)(ma_uintptr uDeviceID, LPWAVEOUTCAPSA pwoc, UINT cbwoc); +typedef MMRESULT (WINAPI * MA_PFN_waveOutOpen)(LPHWAVEOUT phwo, UINT uDeviceID, LPCWAVEFORMATEX pwfx, DWORD_PTR dwCallback, DWORD_PTR dwInstance, DWORD fdwOpen); +typedef MMRESULT (WINAPI * MA_PFN_waveOutClose)(HWAVEOUT hwo); +typedef MMRESULT (WINAPI * MA_PFN_waveOutPrepareHeader)(HWAVEOUT hwo, LPWAVEHDR pwh, UINT cbwh); +typedef MMRESULT (WINAPI * MA_PFN_waveOutUnprepareHeader)(HWAVEOUT hwo, LPWAVEHDR pwh, UINT cbwh); +typedef MMRESULT (WINAPI * MA_PFN_waveOutWrite)(HWAVEOUT hwo, LPWAVEHDR pwh, UINT cbwh); +typedef MMRESULT (WINAPI * MA_PFN_waveOutReset)(HWAVEOUT hwo); +typedef UINT (WINAPI * MA_PFN_waveInGetNumDevs)(void); +typedef MMRESULT (WINAPI * MA_PFN_waveInGetDevCapsA)(ma_uintptr uDeviceID, LPWAVEINCAPSA pwic, UINT cbwic); +typedef MMRESULT (WINAPI * MA_PFN_waveInOpen)(LPHWAVEIN phwi, UINT uDeviceID, LPCWAVEFORMATEX pwfx, DWORD_PTR dwCallback, DWORD_PTR dwInstance, DWORD fdwOpen); +typedef MMRESULT (WINAPI * MA_PFN_waveInClose)(HWAVEIN hwi); +typedef MMRESULT (WINAPI * MA_PFN_waveInPrepareHeader)(HWAVEIN hwi, LPWAVEHDR pwh, UINT cbwh); +typedef MMRESULT (WINAPI * MA_PFN_waveInUnprepareHeader)(HWAVEIN hwi, LPWAVEHDR pwh, UINT cbwh); +typedef MMRESULT (WINAPI * MA_PFN_waveInAddBuffer)(HWAVEIN hwi, LPWAVEHDR pwh, UINT cbwh); +typedef MMRESULT (WINAPI * MA_PFN_waveInStart)(HWAVEIN hwi); +typedef MMRESULT (WINAPI * MA_PFN_waveInReset)(HWAVEIN hwi); + +ma_result ma_result_from_MMRESULT(MMRESULT resultMM) +{ + switch (resultMM) { + case MMSYSERR_NOERROR: return MA_SUCCESS; + case MMSYSERR_BADDEVICEID: return MA_INVALID_ARGS; + case MMSYSERR_INVALHANDLE: return MA_INVALID_ARGS; + case MMSYSERR_NOMEM: return MA_OUT_OF_MEMORY; + case MMSYSERR_INVALFLAG: return MA_INVALID_ARGS; + case MMSYSERR_INVALPARAM: return MA_INVALID_ARGS; + case MMSYSERR_HANDLEBUSY: return MA_DEVICE_BUSY; + case MMSYSERR_ERROR: return MA_ERROR; + default: return MA_ERROR; + } +} + +char* ma_find_last_character(char* str, char ch) +{ + if (str == NULL) { + return NULL; + } + + char* last = NULL; + while (*str != '\0') { + if (*str == ch) { + last = str; + } + + str += 1; + } + + return last; +} + + +// Our own "WAVECAPS" structure that contains generic information shared between WAVEOUTCAPS2 and WAVEINCAPS2 so +// we can do things generically and typesafely. Names are being kept the same for consistency. +typedef struct +{ + CHAR szPname[MAXPNAMELEN]; + DWORD dwFormats; + WORD wChannels; + GUID NameGuid; +} MA_WAVECAPSA; + +ma_result ma_get_best_info_from_formats_flags__winmm(DWORD dwFormats, WORD channels, WORD* pBitsPerSample, DWORD* pSampleRate) +{ + if (pBitsPerSample) { + *pBitsPerSample = 0; + } + if (pSampleRate) { + *pSampleRate = 0; + } + + WORD bitsPerSample = 0; + DWORD sampleRate = 0; + + if (channels == 1) { + bitsPerSample = 16; + if ((dwFormats & WAVE_FORMAT_48M16) != 0) { + sampleRate = 48000; + } else if ((dwFormats & WAVE_FORMAT_44M16) != 0) { + sampleRate = 44100; + } else if ((dwFormats & WAVE_FORMAT_2M16) != 0) { + sampleRate = 22050; + } else if ((dwFormats & WAVE_FORMAT_1M16) != 0) { + sampleRate = 11025; + } else if ((dwFormats & WAVE_FORMAT_96M16) != 0) { + sampleRate = 96000; + } else { + bitsPerSample = 8; + if ((dwFormats & WAVE_FORMAT_48M08) != 0) { + sampleRate = 48000; + } else if ((dwFormats & WAVE_FORMAT_44M08) != 0) { + sampleRate = 44100; + } else if ((dwFormats & WAVE_FORMAT_2M08) != 0) { + sampleRate = 22050; + } else if ((dwFormats & WAVE_FORMAT_1M08) != 0) { + sampleRate = 11025; + } else if ((dwFormats & WAVE_FORMAT_96M08) != 0) { + sampleRate = 96000; + } else { + return MA_FORMAT_NOT_SUPPORTED; + } + } + } else { + bitsPerSample = 16; + if ((dwFormats & WAVE_FORMAT_48S16) != 0) { + sampleRate = 48000; + } else if ((dwFormats & WAVE_FORMAT_44S16) != 0) { + sampleRate = 44100; + } else if ((dwFormats & WAVE_FORMAT_2S16) != 0) { + sampleRate = 22050; + } else if ((dwFormats & WAVE_FORMAT_1S16) != 0) { + sampleRate = 11025; + } else if ((dwFormats & WAVE_FORMAT_96S16) != 0) { + sampleRate = 96000; + } else { + bitsPerSample = 8; + if ((dwFormats & WAVE_FORMAT_48S08) != 0) { + sampleRate = 48000; + } else if ((dwFormats & WAVE_FORMAT_44S08) != 0) { + sampleRate = 44100; + } else if ((dwFormats & WAVE_FORMAT_2S08) != 0) { + sampleRate = 22050; + } else if ((dwFormats & WAVE_FORMAT_1S08) != 0) { + sampleRate = 11025; + } else if ((dwFormats & WAVE_FORMAT_96S08) != 0) { + sampleRate = 96000; + } else { + return MA_FORMAT_NOT_SUPPORTED; + } + } + } + + if (pBitsPerSample) { + *pBitsPerSample = bitsPerSample; + } + if (pSampleRate) { + *pSampleRate = sampleRate; + } + + return MA_SUCCESS; +} + +ma_result ma_formats_flags_to_WAVEFORMATEX__winmm(DWORD dwFormats, WORD channels, WAVEFORMATEX* pWF) +{ + ma_assert(pWF != NULL); + + ma_zero_object(pWF); + pWF->cbSize = sizeof(*pWF); + pWF->wFormatTag = WAVE_FORMAT_PCM; + pWF->nChannels = (WORD)channels; + if (pWF->nChannels > 2) { + pWF->nChannels = 2; + } + + if (channels == 1) { + pWF->wBitsPerSample = 16; + if ((dwFormats & WAVE_FORMAT_48M16) != 0) { + pWF->nSamplesPerSec = 48000; + } else if ((dwFormats & WAVE_FORMAT_44M16) != 0) { + pWF->nSamplesPerSec = 44100; + } else if ((dwFormats & WAVE_FORMAT_2M16) != 0) { + pWF->nSamplesPerSec = 22050; + } else if ((dwFormats & WAVE_FORMAT_1M16) != 0) { + pWF->nSamplesPerSec = 11025; + } else if ((dwFormats & WAVE_FORMAT_96M16) != 0) { + pWF->nSamplesPerSec = 96000; + } else { + pWF->wBitsPerSample = 8; + if ((dwFormats & WAVE_FORMAT_48M08) != 0) { + pWF->nSamplesPerSec = 48000; + } else if ((dwFormats & WAVE_FORMAT_44M08) != 0) { + pWF->nSamplesPerSec = 44100; + } else if ((dwFormats & WAVE_FORMAT_2M08) != 0) { + pWF->nSamplesPerSec = 22050; + } else if ((dwFormats & WAVE_FORMAT_1M08) != 0) { + pWF->nSamplesPerSec = 11025; + } else if ((dwFormats & WAVE_FORMAT_96M08) != 0) { + pWF->nSamplesPerSec = 96000; + } else { + return MA_FORMAT_NOT_SUPPORTED; + } + } + } else { + pWF->wBitsPerSample = 16; + if ((dwFormats & WAVE_FORMAT_48S16) != 0) { + pWF->nSamplesPerSec = 48000; + } else if ((dwFormats & WAVE_FORMAT_44S16) != 0) { + pWF->nSamplesPerSec = 44100; + } else if ((dwFormats & WAVE_FORMAT_2S16) != 0) { + pWF->nSamplesPerSec = 22050; + } else if ((dwFormats & WAVE_FORMAT_1S16) != 0) { + pWF->nSamplesPerSec = 11025; + } else if ((dwFormats & WAVE_FORMAT_96S16) != 0) { + pWF->nSamplesPerSec = 96000; + } else { + pWF->wBitsPerSample = 8; + if ((dwFormats & WAVE_FORMAT_48S08) != 0) { + pWF->nSamplesPerSec = 48000; + } else if ((dwFormats & WAVE_FORMAT_44S08) != 0) { + pWF->nSamplesPerSec = 44100; + } else if ((dwFormats & WAVE_FORMAT_2S08) != 0) { + pWF->nSamplesPerSec = 22050; + } else if ((dwFormats & WAVE_FORMAT_1S08) != 0) { + pWF->nSamplesPerSec = 11025; + } else if ((dwFormats & WAVE_FORMAT_96S08) != 0) { + pWF->nSamplesPerSec = 96000; + } else { + return MA_FORMAT_NOT_SUPPORTED; + } + } + } + + pWF->nBlockAlign = (pWF->nChannels * pWF->wBitsPerSample) / 8; + pWF->nAvgBytesPerSec = pWF->nBlockAlign * pWF->nSamplesPerSec; + + return MA_SUCCESS; +} + +ma_result ma_context_get_device_info_from_WAVECAPS(ma_context* pContext, MA_WAVECAPSA* pCaps, ma_device_info* pDeviceInfo) +{ + ma_assert(pContext != NULL); + ma_assert(pCaps != NULL); + ma_assert(pDeviceInfo != NULL); + + // Name / Description + // + // Unfortunately the name specified in WAVE(OUT/IN)CAPS2 is limited to 31 characters. This results in an unprofessional looking + // situation where the names of the devices are truncated. To help work around this, we need to look at the name GUID and try + // looking in the registry for the full name. If we can't find it there, we need to just fall back to the default name. + + // Set the default to begin with. + ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), pCaps->szPname, (size_t)-1); + + // Now try the registry. There's a few things to consider here: + // - The name GUID can be null, in which we case we just need to stick to the original 31 characters. + // - If the name GUID is not present in the registry we'll also need to stick to the original 31 characters. + // - I like consistency, so I want the returned device names to be consistent with those returned by WASAPI and DirectSound. The + // problem, however is that WASAPI and DirectSound use " ()" format (such as "Speakers (High Definition Audio)"), + // but WinMM does not specificy the component name. From my admittedly limited testing, I've notice the component name seems to + // usually fit within the 31 characters of the fixed sized buffer, so what I'm going to do is parse that string for the component + // name, and then concatenate the name from the registry. + if (!ma_is_guid_equal(&pCaps->NameGuid, &MA_GUID_NULL)) { + wchar_t guidStrW[256]; + if (((MA_PFN_StringFromGUID2)pContext->win32.StringFromGUID2)(&pCaps->NameGuid, guidStrW, ma_countof(guidStrW)) > 0) { + char guidStr[256]; + WideCharToMultiByte(CP_UTF8, 0, guidStrW, -1, guidStr, sizeof(guidStr), 0, FALSE); + + char keyStr[1024]; + ma_strcpy_s(keyStr, sizeof(keyStr), "SYSTEM\\CurrentControlSet\\Control\\MediaCategories\\"); + ma_strcat_s(keyStr, sizeof(keyStr), guidStr); + + HKEY hKey; + LONG result = ((MA_PFN_RegOpenKeyExA)pContext->win32.RegOpenKeyExA)(HKEY_LOCAL_MACHINE, keyStr, 0, KEY_READ, &hKey); + if (result == ERROR_SUCCESS) { + BYTE nameFromReg[512]; + DWORD nameFromRegSize = sizeof(nameFromReg); + result = ((MA_PFN_RegQueryValueExA)pContext->win32.RegQueryValueExA)(hKey, "Name", 0, NULL, (LPBYTE)nameFromReg, (LPDWORD)&nameFromRegSize); + ((MA_PFN_RegCloseKey)pContext->win32.RegCloseKey)(hKey); + + if (result == ERROR_SUCCESS) { + // We have the value from the registry, so now we need to construct the name string. + char name[1024]; + if (ma_strcpy_s(name, sizeof(name), pDeviceInfo->name) == 0) { + char* nameBeg = ma_find_last_character(name, '('); + if (nameBeg != NULL) { + size_t leadingLen = (nameBeg - name); + ma_strncpy_s(nameBeg + 1, sizeof(name) - leadingLen, (const char*)nameFromReg, (size_t)-1); + + // The closing ")", if it can fit. + if (leadingLen + nameFromRegSize < sizeof(name)-1) { + ma_strcat_s(name, sizeof(name), ")"); + } + + ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), name, (size_t)-1); + } + } + } + } + } + } + + + WORD bitsPerSample; + DWORD sampleRate; + ma_result result = ma_get_best_info_from_formats_flags__winmm(pCaps->dwFormats, pCaps->wChannels, &bitsPerSample, &sampleRate); + if (result != MA_SUCCESS) { + return result; + } + + pDeviceInfo->minChannels = pCaps->wChannels; + pDeviceInfo->maxChannels = pCaps->wChannels; + pDeviceInfo->minSampleRate = sampleRate; + pDeviceInfo->maxSampleRate = sampleRate; + pDeviceInfo->formatCount = 1; + if (bitsPerSample == 8) { + pDeviceInfo->formats[0] = ma_format_u8; + } else if (bitsPerSample == 16) { + pDeviceInfo->formats[0] = ma_format_s16; + } else if (bitsPerSample == 24) { + pDeviceInfo->formats[0] = ma_format_s24; + } else if (bitsPerSample == 32) { + pDeviceInfo->formats[0] = ma_format_s32; + } else { + return MA_FORMAT_NOT_SUPPORTED; + } + + return MA_SUCCESS; +} + +ma_result ma_context_get_device_info_from_WAVEOUTCAPS2(ma_context* pContext, MA_WAVEOUTCAPS2A* pCaps, ma_device_info* pDeviceInfo) +{ + ma_assert(pContext != NULL); + ma_assert(pCaps != NULL); + ma_assert(pDeviceInfo != NULL); + + MA_WAVECAPSA caps; + ma_copy_memory(caps.szPname, pCaps->szPname, sizeof(caps.szPname)); + caps.dwFormats = pCaps->dwFormats; + caps.wChannels = pCaps->wChannels; + caps.NameGuid = pCaps->NameGuid; + return ma_context_get_device_info_from_WAVECAPS(pContext, &caps, pDeviceInfo); +} + +ma_result ma_context_get_device_info_from_WAVEINCAPS2(ma_context* pContext, MA_WAVEINCAPS2A* pCaps, ma_device_info* pDeviceInfo) +{ + ma_assert(pContext != NULL); + ma_assert(pCaps != NULL); + ma_assert(pDeviceInfo != NULL); + + MA_WAVECAPSA caps; + ma_copy_memory(caps.szPname, pCaps->szPname, sizeof(caps.szPname)); + caps.dwFormats = pCaps->dwFormats; + caps.wChannels = pCaps->wChannels; + caps.NameGuid = pCaps->NameGuid; + return ma_context_get_device_info_from_WAVECAPS(pContext, &caps, pDeviceInfo); +} + + +ma_bool32 ma_context_is_device_id_equal__winmm(ma_context* pContext, const ma_device_id* pID0, const ma_device_id* pID1) +{ + ma_assert(pContext != NULL); + ma_assert(pID0 != NULL); + ma_assert(pID1 != NULL); + (void)pContext; + + return pID0->winmm == pID1->winmm; +} + +ma_result ma_context_enumerate_devices__winmm(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData) +{ + ma_assert(pContext != NULL); + ma_assert(callback != NULL); + + // Playback. + UINT playbackDeviceCount = ((MA_PFN_waveOutGetNumDevs)pContext->winmm.waveOutGetNumDevs)(); + for (UINT iPlaybackDevice = 0; iPlaybackDevice < playbackDeviceCount; ++iPlaybackDevice) { + MA_WAVEOUTCAPS2A caps; + ma_zero_object(&caps); + MMRESULT result = ((MA_PFN_waveOutGetDevCapsA)pContext->winmm.waveOutGetDevCapsA)(iPlaybackDevice, (WAVEOUTCAPSA*)&caps, sizeof(caps)); + if (result == MMSYSERR_NOERROR) { + ma_device_info deviceInfo; + ma_zero_object(&deviceInfo); + deviceInfo.id.winmm = iPlaybackDevice; + + if (ma_context_get_device_info_from_WAVEOUTCAPS2(pContext, &caps, &deviceInfo) == MA_SUCCESS) { + ma_bool32 cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData); + if (cbResult == MA_FALSE) { + return MA_SUCCESS; // Enumeration was stopped. + } + } + } + } + + // Capture. + UINT captureDeviceCount = ((MA_PFN_waveInGetNumDevs)pContext->winmm.waveInGetNumDevs)(); + for (UINT iCaptureDevice = 0; iCaptureDevice < captureDeviceCount; ++iCaptureDevice) { + MA_WAVEINCAPS2A caps; + ma_zero_object(&caps); + MMRESULT result = ((MA_PFN_waveInGetDevCapsA)pContext->winmm.waveInGetDevCapsA)(iCaptureDevice, (WAVEINCAPSA*)&caps, sizeof(caps)); + if (result == MMSYSERR_NOERROR) { + ma_device_info deviceInfo; + ma_zero_object(&deviceInfo); + deviceInfo.id.winmm = iCaptureDevice; + + if (ma_context_get_device_info_from_WAVEINCAPS2(pContext, &caps, &deviceInfo) == MA_SUCCESS) { + ma_bool32 cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData); + if (cbResult == MA_FALSE) { + return MA_SUCCESS; // Enumeration was stopped. + } + } + } + } + + return MA_SUCCESS; +} + +ma_result ma_context_get_device_info__winmm(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_share_mode shareMode, ma_device_info* pDeviceInfo) +{ + ma_assert(pContext != NULL); + + if (shareMode == ma_share_mode_exclusive) { + return MA_SHARE_MODE_NOT_SUPPORTED; + } + + UINT winMMDeviceID = 0; + if (pDeviceID != NULL) { + winMMDeviceID = (UINT)pDeviceID->winmm; + } + + pDeviceInfo->id.winmm = winMMDeviceID; + + if (deviceType == ma_device_type_playback) { + MA_WAVEOUTCAPS2A caps; + ma_zero_object(&caps); + MMRESULT result = ((MA_PFN_waveOutGetDevCapsA)pContext->winmm.waveOutGetDevCapsA)(winMMDeviceID, (WAVEOUTCAPSA*)&caps, sizeof(caps)); + if (result == MMSYSERR_NOERROR) { + return ma_context_get_device_info_from_WAVEOUTCAPS2(pContext, &caps, pDeviceInfo); + } + } else { + MA_WAVEINCAPS2A caps; + ma_zero_object(&caps); + MMRESULT result = ((MA_PFN_waveInGetDevCapsA)pContext->winmm.waveInGetDevCapsA)(winMMDeviceID, (WAVEINCAPSA*)&caps, sizeof(caps)); + if (result == MMSYSERR_NOERROR) { + return ma_context_get_device_info_from_WAVEINCAPS2(pContext, &caps, pDeviceInfo); + } + } + + return MA_NO_DEVICE; +} + + +void ma_device_uninit__winmm(ma_device* pDevice) +{ + ma_assert(pDevice != NULL); + + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + ((MA_PFN_waveInClose)pDevice->pContext->winmm.waveInClose)((HWAVEIN)pDevice->winmm.hDeviceCapture); + CloseHandle((HANDLE)pDevice->winmm.hEventCapture); + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + ((MA_PFN_waveOutReset)pDevice->pContext->winmm.waveOutReset)((HWAVEOUT)pDevice->winmm.hDevicePlayback); + ((MA_PFN_waveOutClose)pDevice->pContext->winmm.waveOutClose)((HWAVEOUT)pDevice->winmm.hDevicePlayback); + CloseHandle((HANDLE)pDevice->winmm.hEventPlayback); + } + + ma_free(pDevice->winmm._pHeapData); + + ma_zero_object(&pDevice->winmm); // Safety. +} + +ma_result ma_device_init__winmm(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice) +{ + const char* errorMsg = ""; + ma_result errorCode = MA_ERROR; + ma_result result = MA_SUCCESS; + ma_uint32 heapSize; + UINT winMMDeviceIDPlayback = 0; + UINT winMMDeviceIDCapture = 0; + + ma_assert(pDevice != NULL); + ma_zero_object(&pDevice->winmm); + + /* No exlusive mode with WinMM. */ + if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pConfig->playback.shareMode == ma_share_mode_exclusive) || + ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pConfig->capture.shareMode == ma_share_mode_exclusive)) { + return MA_SHARE_MODE_NOT_SUPPORTED; + } + + ma_uint32 bufferSizeInMilliseconds = pConfig->bufferSizeInMilliseconds; + if (bufferSizeInMilliseconds == 0) { + bufferSizeInMilliseconds = ma_calculate_buffer_size_in_milliseconds_from_frames(pConfig->bufferSizeInFrames, pConfig->sampleRate); + } + + /* WinMM has horrible latency. */ + if (pDevice->usingDefaultBufferSize) { + if (pConfig->performanceProfile == ma_performance_profile_low_latency) { + bufferSizeInMilliseconds = 40 * pConfig->periods; + } else { + bufferSizeInMilliseconds = 400 * pConfig->periods; + } + } + + + if (pConfig->playback.pDeviceID != NULL) { + winMMDeviceIDPlayback = (UINT)pConfig->playback.pDeviceID->winmm; + } + if (pConfig->capture.pDeviceID != NULL) { + winMMDeviceIDCapture = (UINT)pConfig->capture.pDeviceID->winmm; + } + + // The capture device needs to be initialized first. + if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) { + WAVEINCAPSA caps; + WAVEFORMATEX wf; + MMRESULT resultMM; + + // We use an event to know when a new fragment needs to be enqueued. + pDevice->winmm.hEventCapture = (ma_handle)CreateEvent(NULL, TRUE, TRUE, NULL); + if (pDevice->winmm.hEventCapture == NULL) { + errorMsg = "[WinMM] Failed to create event for fragment enqueing for the capture device.", errorCode = MA_FAILED_TO_CREATE_EVENT; + goto on_error; + } + + // The format should be based on the device's actual format. + if (((MA_PFN_waveInGetDevCapsA)pContext->winmm.waveInGetDevCapsA)(winMMDeviceIDCapture, &caps, sizeof(caps)) != MMSYSERR_NOERROR) { + errorMsg = "[WinMM] Failed to retrieve internal device caps.", errorCode = MA_FORMAT_NOT_SUPPORTED; + goto on_error; + } + + result = ma_formats_flags_to_WAVEFORMATEX__winmm(caps.dwFormats, caps.wChannels, &wf); + if (result != MA_SUCCESS) { + errorMsg = "[WinMM] Could not find appropriate format for internal device.", errorCode = result; + goto on_error; + } + + resultMM = ((MA_PFN_waveInOpen)pDevice->pContext->winmm.waveInOpen)((LPHWAVEIN)&pDevice->winmm.hDeviceCapture, winMMDeviceIDCapture, &wf, (DWORD_PTR)pDevice->winmm.hEventCapture, (DWORD_PTR)pDevice, CALLBACK_EVENT | WAVE_ALLOWSYNC); + if (resultMM != MMSYSERR_NOERROR) { + errorMsg = "[WinMM] Failed to open capture device.", errorCode = MA_FAILED_TO_OPEN_BACKEND_DEVICE; + goto on_error; + } + + pDevice->capture.internalFormat = ma_format_from_WAVEFORMATEX(&wf); + pDevice->capture.internalChannels = wf.nChannels; + pDevice->capture.internalSampleRate = wf.nSamplesPerSec; + ma_get_standard_channel_map(ma_standard_channel_map_microsoft, pDevice->capture.internalChannels, pDevice->capture.internalChannelMap); + pDevice->capture.internalPeriods = pConfig->periods; + pDevice->capture.internalBufferSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(bufferSizeInMilliseconds, pDevice->capture.internalSampleRate); + } + + if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) { + WAVEOUTCAPSA caps; + WAVEFORMATEX wf; + MMRESULT resultMM; + + // We use an event to know when a new fragment needs to be enqueued. + pDevice->winmm.hEventPlayback = (ma_handle)CreateEvent(NULL, TRUE, TRUE, NULL); + if (pDevice->winmm.hEventPlayback == NULL) { + errorMsg = "[WinMM] Failed to create event for fragment enqueing for the playback device.", errorCode = MA_FAILED_TO_CREATE_EVENT; + goto on_error; + } + + // The format should be based on the device's actual format. + if (((MA_PFN_waveOutGetDevCapsA)pContext->winmm.waveOutGetDevCapsA)(winMMDeviceIDPlayback, &caps, sizeof(caps)) != MMSYSERR_NOERROR) { + errorMsg = "[WinMM] Failed to retrieve internal device caps.", errorCode = MA_FORMAT_NOT_SUPPORTED; + goto on_error; + } + + result = ma_formats_flags_to_WAVEFORMATEX__winmm(caps.dwFormats, caps.wChannels, &wf); + if (result != MA_SUCCESS) { + errorMsg = "[WinMM] Could not find appropriate format for internal device.", errorCode = result; + goto on_error; + } + + resultMM = ((MA_PFN_waveOutOpen)pContext->winmm.waveOutOpen)((LPHWAVEOUT)&pDevice->winmm.hDevicePlayback, winMMDeviceIDPlayback, &wf, (DWORD_PTR)pDevice->winmm.hEventPlayback, (DWORD_PTR)pDevice, CALLBACK_EVENT | WAVE_ALLOWSYNC); + if (resultMM != MMSYSERR_NOERROR) { + errorMsg = "[WinMM] Failed to open playback device.", errorCode = MA_FAILED_TO_OPEN_BACKEND_DEVICE; + goto on_error; + } + + pDevice->playback.internalFormat = ma_format_from_WAVEFORMATEX(&wf); + pDevice->playback.internalChannels = wf.nChannels; + pDevice->playback.internalSampleRate = wf.nSamplesPerSec; + ma_get_standard_channel_map(ma_standard_channel_map_microsoft, pDevice->playback.internalChannels, pDevice->playback.internalChannelMap); + pDevice->playback.internalPeriods = pConfig->periods; + pDevice->playback.internalBufferSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(bufferSizeInMilliseconds, pDevice->playback.internalSampleRate); + } + + // The heap allocated data is allocated like so: + // + // [Capture WAVEHDRs][Playback WAVEHDRs][Capture Intermediary Buffer][Playback Intermediary Buffer] + heapSize = 0; + if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) { + heapSize += sizeof(WAVEHDR)*pDevice->capture.internalPeriods + (pDevice->capture.internalBufferSizeInFrames*ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels)); + } + if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) { + heapSize += sizeof(WAVEHDR)*pDevice->playback.internalPeriods + (pDevice->playback.internalBufferSizeInFrames*ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels)); + } + + pDevice->winmm._pHeapData = (ma_uint8*)ma_malloc(heapSize); + if (pDevice->winmm._pHeapData == NULL) { + errorMsg = "[WinMM] Failed to allocate memory for the intermediary buffer.", errorCode = MA_OUT_OF_MEMORY; + goto on_error; + } + + ma_zero_memory(pDevice->winmm._pHeapData, heapSize); + + if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) { + if (pConfig->deviceType == ma_device_type_capture) { + pDevice->winmm.pWAVEHDRCapture = pDevice->winmm._pHeapData; + pDevice->winmm.pIntermediaryBufferCapture = pDevice->winmm._pHeapData + (sizeof(WAVEHDR)*(pDevice->capture.internalPeriods)); + } else { + pDevice->winmm.pWAVEHDRCapture = pDevice->winmm._pHeapData; + pDevice->winmm.pIntermediaryBufferCapture = pDevice->winmm._pHeapData + (sizeof(WAVEHDR)*(pDevice->capture.internalPeriods + pDevice->playback.internalPeriods)); + } + + /* Prepare headers. */ + for (ma_uint32 iPeriod = 0; iPeriod < pDevice->capture.internalPeriods; ++iPeriod) { + ma_uint32 fragmentSizeInBytes = ma_get_fragment_size_in_bytes(pDevice->capture.internalBufferSizeInFrames, pDevice->capture.internalPeriods, pDevice->capture.internalFormat, pDevice->capture.internalChannels); + + ((WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod].lpData = (LPSTR)(pDevice->winmm.pIntermediaryBufferCapture + (fragmentSizeInBytes*iPeriod)); + ((WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod].dwBufferLength = fragmentSizeInBytes; + ((WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod].dwFlags = 0L; + ((WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod].dwLoops = 0L; + ((MA_PFN_waveInPrepareHeader)pContext->winmm.waveInPrepareHeader)((HWAVEIN)pDevice->winmm.hDeviceCapture, &((WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod], sizeof(WAVEHDR)); + + /* + The user data of the WAVEHDR structure is a single flag the controls whether or not it is ready for writing. Consider it to be named "isLocked". A value of 0 means + it's unlocked and available for writing. A value of 1 means it's locked. + */ + ((WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod].dwUser = 0; + } + } + if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) { + if (pConfig->deviceType == ma_device_type_playback) { + pDevice->winmm.pWAVEHDRPlayback = pDevice->winmm._pHeapData; + pDevice->winmm.pIntermediaryBufferPlayback = pDevice->winmm._pHeapData + (sizeof(WAVEHDR)*pDevice->playback.internalPeriods); + } else { + pDevice->winmm.pWAVEHDRPlayback = pDevice->winmm._pHeapData + (sizeof(WAVEHDR)*(pDevice->capture.internalPeriods)); + pDevice->winmm.pIntermediaryBufferPlayback = pDevice->winmm._pHeapData + (sizeof(WAVEHDR)*(pDevice->capture.internalPeriods + pDevice->playback.internalPeriods)) + (pDevice->playback.internalBufferSizeInFrames*ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels)); + } + + /* Prepare headers. */ + for (ma_uint32 iPeriod = 0; iPeriod < pDevice->playback.internalPeriods; ++iPeriod) { + ma_uint32 fragmentSizeInBytes = ma_get_fragment_size_in_bytes(pDevice->playback.internalBufferSizeInFrames, pDevice->playback.internalPeriods, pDevice->playback.internalFormat, pDevice->playback.internalChannels); + + ((WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod].lpData = (LPSTR)(pDevice->winmm.pIntermediaryBufferPlayback + (fragmentSizeInBytes*iPeriod)); + ((WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod].dwBufferLength = fragmentSizeInBytes; + ((WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod].dwFlags = 0L; + ((WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod].dwLoops = 0L; + ((MA_PFN_waveOutPrepareHeader)pContext->winmm.waveOutPrepareHeader)((HWAVEOUT)pDevice->winmm.hDevicePlayback, &((WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod], sizeof(WAVEHDR)); + + /* + The user data of the WAVEHDR structure is a single flag the controls whether or not it is ready for writing. Consider it to be named "isLocked". A value of 0 means + it's unlocked and available for writing. A value of 1 means it's locked. + */ + ((WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod].dwUser = 0; + } + } + + return MA_SUCCESS; + +on_error: + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + if (pDevice->winmm.pWAVEHDRCapture != NULL) { + for (ma_uint32 iPeriod = 0; iPeriod < pDevice->capture.internalPeriods; ++iPeriod) { + ((MA_PFN_waveInUnprepareHeader)pContext->winmm.waveInUnprepareHeader)((HWAVEIN)pDevice->winmm.hDeviceCapture, &((WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod], sizeof(WAVEHDR)); + } + } + + ((MA_PFN_waveInClose)pContext->winmm.waveInClose)((HWAVEIN)pDevice->winmm.hDeviceCapture); + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + if (pDevice->winmm.pWAVEHDRCapture != NULL) { + for (ma_uint32 iPeriod = 0; iPeriod < pDevice->playback.internalPeriods; ++iPeriod) { + ((MA_PFN_waveOutUnprepareHeader)pContext->winmm.waveOutUnprepareHeader)((HWAVEOUT)pDevice->winmm.hDevicePlayback, &((WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod], sizeof(WAVEHDR)); + } + } + + ((MA_PFN_waveOutClose)pContext->winmm.waveOutClose)((HWAVEOUT)pDevice->winmm.hDevicePlayback); + } + + ma_free(pDevice->winmm._pHeapData); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, errorMsg, errorCode); +} + +ma_result ma_device_stop__winmm(ma_device* pDevice) +{ + ma_assert(pDevice != NULL); + + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + if (pDevice->winmm.hDeviceCapture == NULL) { + return MA_INVALID_ARGS; + } + + MMRESULT resultMM = ((MA_PFN_waveInReset)pDevice->pContext->winmm.waveInReset)((HWAVEIN)pDevice->winmm.hDeviceCapture); + if (resultMM != MMSYSERR_NOERROR) { + ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WinMM] WARNING: Failed to reset capture device.", ma_result_from_MMRESULT(resultMM)); + } + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + if (pDevice->winmm.hDevicePlayback == NULL) { + return MA_INVALID_ARGS; + } + + MMRESULT resultMM = ((MA_PFN_waveOutReset)pDevice->pContext->winmm.waveOutReset)((HWAVEOUT)pDevice->winmm.hDevicePlayback); + if (resultMM != MMSYSERR_NOERROR) { + ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WinMM] WARNING: Failed to reset playback device.", ma_result_from_MMRESULT(resultMM)); + } + } + + ma_atomic_exchange_32(&pDevice->winmm.isStarted, MA_FALSE); + return MA_SUCCESS; +} + +ma_result ma_device_write__winmm(ma_device* pDevice, const void* pPCMFrames, ma_uint32 frameCount) +{ + ma_result result = MA_SUCCESS; + MMRESULT resultMM; + ma_uint32 totalFramesWritten; + WAVEHDR* pWAVEHDR = (WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback; + + ma_assert(pDevice != NULL); + ma_assert(pPCMFrames != NULL); + + /* Keep processing as much data as possible. */ + totalFramesWritten = 0; + while (totalFramesWritten < frameCount) { + /* If the current header has some space available we need to write part of it. */ + if (pWAVEHDR[pDevice->winmm.iNextHeaderPlayback].dwUser == 0) { /* 0 = unlocked. */ + /* + This header has room in it. We copy as much of it as we can. If we end up fully consuming the buffer we need to + write it out and move on to the next iteration. + */ + ma_uint32 bpf = ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels); + ma_uint32 framesRemainingInHeader = (pWAVEHDR[pDevice->winmm.iNextHeaderPlayback].dwBufferLength/bpf) - pDevice->winmm.headerFramesConsumedPlayback; + + ma_uint32 framesToCopy = ma_min(framesRemainingInHeader, (frameCount - totalFramesWritten)); + const void* pSrc = ma_offset_ptr(pPCMFrames, totalFramesWritten*bpf); + void* pDst = ma_offset_ptr(pWAVEHDR[pDevice->winmm.iNextHeaderPlayback].lpData, pDevice->winmm.headerFramesConsumedPlayback*bpf); + ma_copy_memory(pDst, pSrc, framesToCopy*bpf); + + pDevice->winmm.headerFramesConsumedPlayback += framesToCopy; + totalFramesWritten += framesToCopy; + + /* If we've consumed the buffer entirely we need to write it out to the device. */ + if (pDevice->winmm.headerFramesConsumedPlayback == (pWAVEHDR[pDevice->winmm.iNextHeaderPlayback].dwBufferLength/bpf)) { + pWAVEHDR[pDevice->winmm.iNextHeaderPlayback].dwUser = 1; /* 1 = locked. */ + pWAVEHDR[pDevice->winmm.iNextHeaderPlayback].dwFlags &= ~WHDR_DONE; /* <-- Need to make sure the WHDR_DONE flag is unset. */ + + /* Make sure the event is reset to a non-signaled state to ensure we don't prematurely return from WaitForSingleObject(). */ + ResetEvent((HANDLE)pDevice->winmm.hEventPlayback); + + /* The device will be started here. */ + resultMM = ((MA_PFN_waveOutWrite)pDevice->pContext->winmm.waveOutWrite)((HWAVEOUT)pDevice->winmm.hDevicePlayback, &pWAVEHDR[pDevice->winmm.iNextHeaderPlayback], sizeof(WAVEHDR)); + if (resultMM != MMSYSERR_NOERROR) { + result = ma_result_from_MMRESULT(resultMM); + ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WinMM] waveOutWrite() failed.", result); + break; + } + ma_atomic_exchange_32(&pDevice->winmm.isStarted, MA_TRUE); + + /* Make sure we move to the next header. */ + pDevice->winmm.iNextHeaderPlayback = (pDevice->winmm.iNextHeaderPlayback + 1) % pDevice->playback.internalPeriods; + pDevice->winmm.headerFramesConsumedPlayback = 0; + } + + /* If at this point we have consumed the entire input buffer we can return. */ + ma_assert(totalFramesWritten <= frameCount); + if (totalFramesWritten == frameCount) { + break; + } + + /* Getting here means there's more to process. */ + continue; + } + + /* Getting here means there isn't enough room in the buffer and we need to wait for one to become available. */ + if (WaitForSingleObject((HANDLE)pDevice->winmm.hEventPlayback, INFINITE) != WAIT_OBJECT_0) { + result = MA_ERROR; + break; + } + + /* Something happened. If the next buffer has been marked as done we need to reset a bit of state. */ + if ((pWAVEHDR[pDevice->winmm.iNextHeaderPlayback].dwFlags & WHDR_DONE) != 0) { + pWAVEHDR[pDevice->winmm.iNextHeaderPlayback].dwUser = 0; /* 0 = unlocked (make it available for writing). */ + pDevice->winmm.headerFramesConsumedPlayback = 0; + } + + /* If the device has been stopped we need to break. */ + if (!pDevice->winmm.isStarted) { + break; + } + } + + return result; +} + +ma_result ma_device_read__winmm(ma_device* pDevice, void* pPCMFrames, ma_uint32 frameCount) +{ + ma_assert(pDevice != NULL); + ma_assert(pPCMFrames != NULL); + + ma_result result = MA_SUCCESS; + MMRESULT resultMM; + ma_uint32 totalFramesRead; + WAVEHDR* pWAVEHDR = (WAVEHDR*)pDevice->winmm.pWAVEHDRCapture; + + /* We want to start the device immediately. */ + if (!pDevice->winmm.isStarted) { + /* Make sure the event is reset to a non-signaled state to ensure we don't prematurely return from WaitForSingleObject(). */ + ResetEvent((HANDLE)pDevice->winmm.hEventCapture); + + /* To start the device we attach all of the buffers and then start it. As the buffers are filled with data we will get notifications. */ + for (ma_uint32 iPeriod = 0; iPeriod < pDevice->capture.internalPeriods; ++iPeriod) { + resultMM = ((MA_PFN_waveInAddBuffer)pDevice->pContext->winmm.waveInAddBuffer)((HWAVEIN)pDevice->winmm.hDeviceCapture, &((LPWAVEHDR)pDevice->winmm.pWAVEHDRCapture)[iPeriod], sizeof(WAVEHDR)); + if (resultMM != MMSYSERR_NOERROR) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WinMM] Failed to attach input buffers to capture device in preparation for capture.", ma_result_from_MMRESULT(resultMM)); + } + + /* Make sure all of the buffers start out locked. We don't want to access them until the backend tells us we can. */ + pWAVEHDR[iPeriod].dwUser = 1; /* 1 = locked. */ + } + + /* Capture devices need to be explicitly started, unlike playback devices. */ + resultMM = ((MA_PFN_waveInStart)pDevice->pContext->winmm.waveInStart)((HWAVEIN)pDevice->winmm.hDeviceCapture); + if (resultMM != MMSYSERR_NOERROR) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WinMM] Failed to start backend device.", ma_result_from_MMRESULT(resultMM)); + } + + ma_atomic_exchange_32(&pDevice->winmm.isStarted, MA_TRUE); + } + + /* Keep processing as much data as possible. */ + totalFramesRead = 0; + while (totalFramesRead < frameCount) { + /* If the current header has some space available we need to write part of it. */ + if (pWAVEHDR[pDevice->winmm.iNextHeaderCapture].dwUser == 0) { /* 0 = unlocked. */ + /* The buffer is available for reading. If we fully consume it we need to add it back to the buffer. */ + ma_uint32 bpf = ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels); + ma_uint32 framesRemainingInHeader = (pWAVEHDR[pDevice->winmm.iNextHeaderCapture].dwBufferLength/bpf) - pDevice->winmm.headerFramesConsumedCapture; + + ma_uint32 framesToCopy = ma_min(framesRemainingInHeader, (frameCount - totalFramesRead)); + const void* pSrc = ma_offset_ptr(pWAVEHDR[pDevice->winmm.iNextHeaderCapture].lpData, pDevice->winmm.headerFramesConsumedCapture*bpf); + void* pDst = ma_offset_ptr(pPCMFrames, totalFramesRead*bpf); + ma_copy_memory(pDst, pSrc, framesToCopy*bpf); + + pDevice->winmm.headerFramesConsumedCapture += framesToCopy; + totalFramesRead += framesToCopy; + + /* If we've consumed the buffer entirely we need to add it back to the device. */ + if (pDevice->winmm.headerFramesConsumedCapture == (pWAVEHDR[pDevice->winmm.iNextHeaderCapture].dwBufferLength/bpf)) { + pWAVEHDR[pDevice->winmm.iNextHeaderCapture].dwUser = 1; /* 1 = locked. */ + pWAVEHDR[pDevice->winmm.iNextHeaderCapture].dwFlags &= ~WHDR_DONE; /* <-- Need to make sure the WHDR_DONE flag is unset. */ + + /* Make sure the event is reset to a non-signaled state to ensure we don't prematurely return from WaitForSingleObject(). */ + ResetEvent((HANDLE)pDevice->winmm.hEventCapture); + + /* The device will be started here. */ + resultMM = ((MA_PFN_waveInAddBuffer)pDevice->pContext->winmm.waveInAddBuffer)((HWAVEIN)pDevice->winmm.hDeviceCapture, &((LPWAVEHDR)pDevice->winmm.pWAVEHDRCapture)[pDevice->winmm.iNextHeaderCapture], sizeof(WAVEHDR)); + if (resultMM != MMSYSERR_NOERROR) { + result = ma_result_from_MMRESULT(resultMM); + ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WinMM] waveInAddBuffer() failed.", result); + break; + } + + /* Make sure we move to the next header. */ + pDevice->winmm.iNextHeaderCapture = (pDevice->winmm.iNextHeaderCapture + 1) % pDevice->capture.internalPeriods; + pDevice->winmm.headerFramesConsumedCapture = 0; + } + + /* If at this point we have filled the entire input buffer we can return. */ + ma_assert(totalFramesRead <= frameCount); + if (totalFramesRead == frameCount) { + break; + } + + /* Getting here means there's more to process. */ + continue; + } + + /* Getting here means there isn't enough any data left to send to the client which means we need to wait for more. */ + if (WaitForSingleObject((HANDLE)pDevice->winmm.hEventCapture, INFINITE) != WAIT_OBJECT_0) { + result = MA_ERROR; + break; + } + + /* Something happened. If the next buffer has been marked as done we need to reset a bit of state. */ + if ((pWAVEHDR[pDevice->winmm.iNextHeaderCapture].dwFlags & WHDR_DONE) != 0) { + pWAVEHDR[pDevice->winmm.iNextHeaderCapture].dwUser = 0; /* 0 = unlocked (make it available for reading). */ + pDevice->winmm.headerFramesConsumedCapture = 0; + } + + /* If the device has been stopped we need to break. */ + if (!pDevice->winmm.isStarted) { + break; + } + } + + return result; +} + +ma_result ma_context_uninit__winmm(ma_context* pContext) +{ + ma_assert(pContext != NULL); + ma_assert(pContext->backend == ma_backend_winmm); + + ma_dlclose(pContext->winmm.hWinMM); + return MA_SUCCESS; +} + +ma_result ma_context_init__winmm(ma_context* pContext) +{ + ma_assert(pContext != NULL); + + pContext->winmm.hWinMM = ma_dlopen("winmm.dll"); + if (pContext->winmm.hWinMM == NULL) { + return MA_NO_BACKEND; + } + + pContext->winmm.waveOutGetNumDevs = ma_dlsym(pContext->winmm.hWinMM, "waveOutGetNumDevs"); + pContext->winmm.waveOutGetDevCapsA = ma_dlsym(pContext->winmm.hWinMM, "waveOutGetDevCapsA"); + pContext->winmm.waveOutOpen = ma_dlsym(pContext->winmm.hWinMM, "waveOutOpen"); + pContext->winmm.waveOutClose = ma_dlsym(pContext->winmm.hWinMM, "waveOutClose"); + pContext->winmm.waveOutPrepareHeader = ma_dlsym(pContext->winmm.hWinMM, "waveOutPrepareHeader"); + pContext->winmm.waveOutUnprepareHeader = ma_dlsym(pContext->winmm.hWinMM, "waveOutUnprepareHeader"); + pContext->winmm.waveOutWrite = ma_dlsym(pContext->winmm.hWinMM, "waveOutWrite"); + pContext->winmm.waveOutReset = ma_dlsym(pContext->winmm.hWinMM, "waveOutReset"); + pContext->winmm.waveInGetNumDevs = ma_dlsym(pContext->winmm.hWinMM, "waveInGetNumDevs"); + pContext->winmm.waveInGetDevCapsA = ma_dlsym(pContext->winmm.hWinMM, "waveInGetDevCapsA"); + pContext->winmm.waveInOpen = ma_dlsym(pContext->winmm.hWinMM, "waveInOpen"); + pContext->winmm.waveInClose = ma_dlsym(pContext->winmm.hWinMM, "waveInClose"); + pContext->winmm.waveInPrepareHeader = ma_dlsym(pContext->winmm.hWinMM, "waveInPrepareHeader"); + pContext->winmm.waveInUnprepareHeader = ma_dlsym(pContext->winmm.hWinMM, "waveInUnprepareHeader"); + pContext->winmm.waveInAddBuffer = ma_dlsym(pContext->winmm.hWinMM, "waveInAddBuffer"); + pContext->winmm.waveInStart = ma_dlsym(pContext->winmm.hWinMM, "waveInStart"); + pContext->winmm.waveInReset = ma_dlsym(pContext->winmm.hWinMM, "waveInReset"); + + pContext->onUninit = ma_context_uninit__winmm; + pContext->onDeviceIDEqual = ma_context_is_device_id_equal__winmm; + pContext->onEnumDevices = ma_context_enumerate_devices__winmm; + pContext->onGetDeviceInfo = ma_context_get_device_info__winmm; + pContext->onDeviceInit = ma_device_init__winmm; + pContext->onDeviceUninit = ma_device_uninit__winmm; + pContext->onDeviceStart = NULL; /* Not used. Started in onDeviceWrite/onDeviceRead. */ + pContext->onDeviceStop = ma_device_stop__winmm; + pContext->onDeviceWrite = ma_device_write__winmm; + pContext->onDeviceRead = ma_device_read__winmm; + + return MA_SUCCESS; +} +#endif + + + + +/////////////////////////////////////////////////////////////////////////////// +// +// ALSA Backend +// +/////////////////////////////////////////////////////////////////////////////// +#ifdef MA_HAS_ALSA + +#ifdef MA_NO_RUNTIME_LINKING +#include +typedef snd_pcm_uframes_t ma_snd_pcm_uframes_t; +typedef snd_pcm_sframes_t ma_snd_pcm_sframes_t; +typedef snd_pcm_stream_t ma_snd_pcm_stream_t; +typedef snd_pcm_format_t ma_snd_pcm_format_t; +typedef snd_pcm_access_t ma_snd_pcm_access_t; +typedef snd_pcm_t ma_snd_pcm_t; +typedef snd_pcm_hw_params_t ma_snd_pcm_hw_params_t; +typedef snd_pcm_sw_params_t ma_snd_pcm_sw_params_t; +typedef snd_pcm_format_mask_t ma_snd_pcm_format_mask_t; +typedef snd_pcm_info_t ma_snd_pcm_info_t; +typedef snd_pcm_channel_area_t ma_snd_pcm_channel_area_t; +typedef snd_pcm_chmap_t ma_snd_pcm_chmap_t; + +// snd_pcm_stream_t +#define MA_SND_PCM_STREAM_PLAYBACK SND_PCM_STREAM_PLAYBACK +#define MA_SND_PCM_STREAM_CAPTURE SND_PCM_STREAM_CAPTURE + +// snd_pcm_format_t +#define MA_SND_PCM_FORMAT_UNKNOWN SND_PCM_FORMAT_UNKNOWN +#define MA_SND_PCM_FORMAT_U8 SND_PCM_FORMAT_U8 +#define MA_SND_PCM_FORMAT_S16_LE SND_PCM_FORMAT_S16_LE +#define MA_SND_PCM_FORMAT_S16_BE SND_PCM_FORMAT_S16_BE +#define MA_SND_PCM_FORMAT_S24_LE SND_PCM_FORMAT_S24_LE +#define MA_SND_PCM_FORMAT_S24_BE SND_PCM_FORMAT_S24_BE +#define MA_SND_PCM_FORMAT_S32_LE SND_PCM_FORMAT_S32_LE +#define MA_SND_PCM_FORMAT_S32_BE SND_PCM_FORMAT_S32_BE +#define MA_SND_PCM_FORMAT_FLOAT_LE SND_PCM_FORMAT_FLOAT_LE +#define MA_SND_PCM_FORMAT_FLOAT_BE SND_PCM_FORMAT_FLOAT_BE +#define MA_SND_PCM_FORMAT_FLOAT64_LE SND_PCM_FORMAT_FLOAT64_LE +#define MA_SND_PCM_FORMAT_FLOAT64_BE SND_PCM_FORMAT_FLOAT64_BE +#define MA_SND_PCM_FORMAT_MU_LAW SND_PCM_FORMAT_MU_LAW +#define MA_SND_PCM_FORMAT_A_LAW SND_PCM_FORMAT_A_LAW +#define MA_SND_PCM_FORMAT_S24_3LE SND_PCM_FORMAT_S24_3LE +#define MA_SND_PCM_FORMAT_S24_3BE SND_PCM_FORMAT_S24_3BE + +// ma_snd_pcm_access_t +#define MA_SND_PCM_ACCESS_MMAP_INTERLEAVED SND_PCM_ACCESS_MMAP_INTERLEAVED +#define MA_SND_PCM_ACCESS_MMAP_NONINTERLEAVED SND_PCM_ACCESS_MMAP_NONINTERLEAVED +#define MA_SND_PCM_ACCESS_MMAP_COMPLEX SND_PCM_ACCESS_MMAP_COMPLEX +#define MA_SND_PCM_ACCESS_RW_INTERLEAVED SND_PCM_ACCESS_RW_INTERLEAVED +#define MA_SND_PCM_ACCESS_RW_NONINTERLEAVED SND_PCM_ACCESS_RW_NONINTERLEAVED + +// Channel positions. +#define MA_SND_CHMAP_UNKNOWN SND_CHMAP_UNKNOWN +#define MA_SND_CHMAP_NA SND_CHMAP_NA +#define MA_SND_CHMAP_MONO SND_CHMAP_MONO +#define MA_SND_CHMAP_FL SND_CHMAP_FL +#define MA_SND_CHMAP_FR SND_CHMAP_FR +#define MA_SND_CHMAP_RL SND_CHMAP_RL +#define MA_SND_CHMAP_RR SND_CHMAP_RR +#define MA_SND_CHMAP_FC SND_CHMAP_FC +#define MA_SND_CHMAP_LFE SND_CHMAP_LFE +#define MA_SND_CHMAP_SL SND_CHMAP_SL +#define MA_SND_CHMAP_SR SND_CHMAP_SR +#define MA_SND_CHMAP_RC SND_CHMAP_RC +#define MA_SND_CHMAP_FLC SND_CHMAP_FLC +#define MA_SND_CHMAP_FRC SND_CHMAP_FRC +#define MA_SND_CHMAP_RLC SND_CHMAP_RLC +#define MA_SND_CHMAP_RRC SND_CHMAP_RRC +#define MA_SND_CHMAP_FLW SND_CHMAP_FLW +#define MA_SND_CHMAP_FRW SND_CHMAP_FRW +#define MA_SND_CHMAP_FLH SND_CHMAP_FLH +#define MA_SND_CHMAP_FCH SND_CHMAP_FCH +#define MA_SND_CHMAP_FRH SND_CHMAP_FRH +#define MA_SND_CHMAP_TC SND_CHMAP_TC +#define MA_SND_CHMAP_TFL SND_CHMAP_TFL +#define MA_SND_CHMAP_TFR SND_CHMAP_TFR +#define MA_SND_CHMAP_TFC SND_CHMAP_TFC +#define MA_SND_CHMAP_TRL SND_CHMAP_TRL +#define MA_SND_CHMAP_TRR SND_CHMAP_TRR +#define MA_SND_CHMAP_TRC SND_CHMAP_TRC +#define MA_SND_CHMAP_TFLC SND_CHMAP_TFLC +#define MA_SND_CHMAP_TFRC SND_CHMAP_TFRC +#define MA_SND_CHMAP_TSL SND_CHMAP_TSL +#define MA_SND_CHMAP_TSR SND_CHMAP_TSR +#define MA_SND_CHMAP_LLFE SND_CHMAP_LLFE +#define MA_SND_CHMAP_RLFE SND_CHMAP_RLFE +#define MA_SND_CHMAP_BC SND_CHMAP_BC +#define MA_SND_CHMAP_BLC SND_CHMAP_BLC +#define MA_SND_CHMAP_BRC SND_CHMAP_BRC + +// Open mode flags. +#define MA_SND_PCM_NO_AUTO_RESAMPLE SND_PCM_NO_AUTO_RESAMPLE +#define MA_SND_PCM_NO_AUTO_CHANNELS SND_PCM_NO_AUTO_CHANNELS +#define MA_SND_PCM_NO_AUTO_FORMAT SND_PCM_NO_AUTO_FORMAT +#else +#include // For EPIPE, etc. +typedef unsigned long ma_snd_pcm_uframes_t; +typedef long ma_snd_pcm_sframes_t; +typedef int ma_snd_pcm_stream_t; +typedef int ma_snd_pcm_format_t; +typedef int ma_snd_pcm_access_t; +typedef struct ma_snd_pcm_t ma_snd_pcm_t; +typedef struct ma_snd_pcm_hw_params_t ma_snd_pcm_hw_params_t; +typedef struct ma_snd_pcm_sw_params_t ma_snd_pcm_sw_params_t; +typedef struct ma_snd_pcm_format_mask_t ma_snd_pcm_format_mask_t; +typedef struct ma_snd_pcm_info_t ma_snd_pcm_info_t; +typedef struct +{ + void* addr; + unsigned int first; + unsigned int step; +} ma_snd_pcm_channel_area_t; +typedef struct +{ + unsigned int channels; + unsigned int pos[0]; +} ma_snd_pcm_chmap_t; + +// snd_pcm_state_t +#define MA_SND_PCM_STATE_OPEN 0 +#define MA_SND_PCM_STATE_SETUP 1 +#define MA_SND_PCM_STATE_PREPARED 2 +#define MA_SND_PCM_STATE_RUNNING 3 +#define MA_SND_PCM_STATE_XRUN 4 +#define MA_SND_PCM_STATE_DRAINING 5 +#define MA_SND_PCM_STATE_PAUSED 6 +#define MA_SND_PCM_STATE_SUSPENDED 7 +#define MA_SND_PCM_STATE_DISCONNECTED 8 + +// snd_pcm_stream_t +#define MA_SND_PCM_STREAM_PLAYBACK 0 +#define MA_SND_PCM_STREAM_CAPTURE 1 + +// snd_pcm_format_t +#define MA_SND_PCM_FORMAT_UNKNOWN -1 +#define MA_SND_PCM_FORMAT_U8 1 +#define MA_SND_PCM_FORMAT_S16_LE 2 +#define MA_SND_PCM_FORMAT_S16_BE 3 +#define MA_SND_PCM_FORMAT_S24_LE 6 +#define MA_SND_PCM_FORMAT_S24_BE 7 +#define MA_SND_PCM_FORMAT_S32_LE 10 +#define MA_SND_PCM_FORMAT_S32_BE 11 +#define MA_SND_PCM_FORMAT_FLOAT_LE 14 +#define MA_SND_PCM_FORMAT_FLOAT_BE 15 +#define MA_SND_PCM_FORMAT_FLOAT64_LE 16 +#define MA_SND_PCM_FORMAT_FLOAT64_BE 17 +#define MA_SND_PCM_FORMAT_MU_LAW 20 +#define MA_SND_PCM_FORMAT_A_LAW 21 +#define MA_SND_PCM_FORMAT_S24_3LE 32 +#define MA_SND_PCM_FORMAT_S24_3BE 33 + +// snd_pcm_access_t +#define MA_SND_PCM_ACCESS_MMAP_INTERLEAVED 0 +#define MA_SND_PCM_ACCESS_MMAP_NONINTERLEAVED 1 +#define MA_SND_PCM_ACCESS_MMAP_COMPLEX 2 +#define MA_SND_PCM_ACCESS_RW_INTERLEAVED 3 +#define MA_SND_PCM_ACCESS_RW_NONINTERLEAVED 4 + +// Channel positions. +#define MA_SND_CHMAP_UNKNOWN 0 +#define MA_SND_CHMAP_NA 1 +#define MA_SND_CHMAP_MONO 2 +#define MA_SND_CHMAP_FL 3 +#define MA_SND_CHMAP_FR 4 +#define MA_SND_CHMAP_RL 5 +#define MA_SND_CHMAP_RR 6 +#define MA_SND_CHMAP_FC 7 +#define MA_SND_CHMAP_LFE 8 +#define MA_SND_CHMAP_SL 9 +#define MA_SND_CHMAP_SR 10 +#define MA_SND_CHMAP_RC 11 +#define MA_SND_CHMAP_FLC 12 +#define MA_SND_CHMAP_FRC 13 +#define MA_SND_CHMAP_RLC 14 +#define MA_SND_CHMAP_RRC 15 +#define MA_SND_CHMAP_FLW 16 +#define MA_SND_CHMAP_FRW 17 +#define MA_SND_CHMAP_FLH 18 +#define MA_SND_CHMAP_FCH 19 +#define MA_SND_CHMAP_FRH 20 +#define MA_SND_CHMAP_TC 21 +#define MA_SND_CHMAP_TFL 22 +#define MA_SND_CHMAP_TFR 23 +#define MA_SND_CHMAP_TFC 24 +#define MA_SND_CHMAP_TRL 25 +#define MA_SND_CHMAP_TRR 26 +#define MA_SND_CHMAP_TRC 27 +#define MA_SND_CHMAP_TFLC 28 +#define MA_SND_CHMAP_TFRC 29 +#define MA_SND_CHMAP_TSL 30 +#define MA_SND_CHMAP_TSR 31 +#define MA_SND_CHMAP_LLFE 32 +#define MA_SND_CHMAP_RLFE 33 +#define MA_SND_CHMAP_BC 34 +#define MA_SND_CHMAP_BLC 35 +#define MA_SND_CHMAP_BRC 36 + +// Open mode flags. +#define MA_SND_PCM_NO_AUTO_RESAMPLE 0x00010000 +#define MA_SND_PCM_NO_AUTO_CHANNELS 0x00020000 +#define MA_SND_PCM_NO_AUTO_FORMAT 0x00040000 +#endif + +typedef int (* ma_snd_pcm_open_proc) (ma_snd_pcm_t **pcm, const char *name, ma_snd_pcm_stream_t stream, int mode); +typedef int (* ma_snd_pcm_close_proc) (ma_snd_pcm_t *pcm); +typedef size_t (* ma_snd_pcm_hw_params_sizeof_proc) (void); +typedef int (* ma_snd_pcm_hw_params_any_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params); +typedef int (* ma_snd_pcm_hw_params_set_format_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, ma_snd_pcm_format_t val); +typedef int (* ma_snd_pcm_hw_params_set_format_first_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, ma_snd_pcm_format_t *format); +typedef void (* ma_snd_pcm_hw_params_get_format_mask_proc) (ma_snd_pcm_hw_params_t *params, ma_snd_pcm_format_mask_t *mask); +typedef int (* ma_snd_pcm_hw_params_set_channels_near_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, unsigned int *val); +typedef int (* ma_snd_pcm_hw_params_set_rate_resample_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, unsigned int val); +typedef int (* ma_snd_pcm_hw_params_set_rate_near_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, unsigned int *val, int *dir); +typedef int (* ma_snd_pcm_hw_params_set_buffer_size_near_proc)(ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, ma_snd_pcm_uframes_t *val); +typedef int (* ma_snd_pcm_hw_params_set_periods_near_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, unsigned int *val, int *dir); +typedef int (* ma_snd_pcm_hw_params_set_access_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, ma_snd_pcm_access_t _access); +typedef int (* ma_snd_pcm_hw_params_get_format_proc) (const ma_snd_pcm_hw_params_t *params, ma_snd_pcm_format_t *format); +typedef int (* ma_snd_pcm_hw_params_get_channels_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *val); +typedef int (* ma_snd_pcm_hw_params_get_channels_min_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *val); +typedef int (* ma_snd_pcm_hw_params_get_channels_max_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *val); +typedef int (* ma_snd_pcm_hw_params_get_rate_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *rate, int *dir); +typedef int (* ma_snd_pcm_hw_params_get_rate_min_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *rate, int *dir); +typedef int (* ma_snd_pcm_hw_params_get_rate_max_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *rate, int *dir); +typedef int (* ma_snd_pcm_hw_params_get_buffer_size_proc) (const ma_snd_pcm_hw_params_t *params, ma_snd_pcm_uframes_t *val); +typedef int (* ma_snd_pcm_hw_params_get_periods_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *val, int *dir); +typedef int (* ma_snd_pcm_hw_params_get_access_proc) (const ma_snd_pcm_hw_params_t *params, ma_snd_pcm_access_t *_access); +typedef int (* ma_snd_pcm_hw_params_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params); +typedef size_t (* ma_snd_pcm_sw_params_sizeof_proc) (void); +typedef int (* ma_snd_pcm_sw_params_current_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_sw_params_t *params); +typedef int (* ma_snd_pcm_sw_params_get_boundary_proc) (ma_snd_pcm_sw_params_t *params, ma_snd_pcm_uframes_t* val); +typedef int (* ma_snd_pcm_sw_params_set_avail_min_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_sw_params_t *params, ma_snd_pcm_uframes_t val); +typedef int (* ma_snd_pcm_sw_params_set_start_threshold_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_sw_params_t *params, ma_snd_pcm_uframes_t val); +typedef int (* ma_snd_pcm_sw_params_set_stop_threshold_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_sw_params_t *params, ma_snd_pcm_uframes_t val); +typedef int (* ma_snd_pcm_sw_params_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_sw_params_t *params); +typedef size_t (* ma_snd_pcm_format_mask_sizeof_proc) (void); +typedef int (* ma_snd_pcm_format_mask_test_proc) (const ma_snd_pcm_format_mask_t *mask, ma_snd_pcm_format_t val); +typedef ma_snd_pcm_chmap_t * (* ma_snd_pcm_get_chmap_proc) (ma_snd_pcm_t *pcm); +typedef int (* ma_snd_pcm_state_proc) (ma_snd_pcm_t *pcm); +typedef int (* ma_snd_pcm_prepare_proc) (ma_snd_pcm_t *pcm); +typedef int (* ma_snd_pcm_start_proc) (ma_snd_pcm_t *pcm); +typedef int (* ma_snd_pcm_drop_proc) (ma_snd_pcm_t *pcm); +typedef int (* ma_snd_pcm_drain_proc) (ma_snd_pcm_t *pcm); +typedef int (* ma_snd_device_name_hint_proc) (int card, const char *iface, void ***hints); +typedef char * (* ma_snd_device_name_get_hint_proc) (const void *hint, const char *id); +typedef int (* ma_snd_card_get_index_proc) (const char *name); +typedef int (* ma_snd_device_name_free_hint_proc) (void **hints); +typedef int (* ma_snd_pcm_mmap_begin_proc) (ma_snd_pcm_t *pcm, const ma_snd_pcm_channel_area_t **areas, ma_snd_pcm_uframes_t *offset, ma_snd_pcm_uframes_t *frames); +typedef ma_snd_pcm_sframes_t (* ma_snd_pcm_mmap_commit_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_uframes_t offset, ma_snd_pcm_uframes_t frames); +typedef int (* ma_snd_pcm_recover_proc) (ma_snd_pcm_t *pcm, int err, int silent); +typedef ma_snd_pcm_sframes_t (* ma_snd_pcm_readi_proc) (ma_snd_pcm_t *pcm, void *buffer, ma_snd_pcm_uframes_t size); +typedef ma_snd_pcm_sframes_t (* ma_snd_pcm_writei_proc) (ma_snd_pcm_t *pcm, const void *buffer, ma_snd_pcm_uframes_t size); +typedef ma_snd_pcm_sframes_t (* ma_snd_pcm_avail_proc) (ma_snd_pcm_t *pcm); +typedef ma_snd_pcm_sframes_t (* ma_snd_pcm_avail_update_proc) (ma_snd_pcm_t *pcm); +typedef int (* ma_snd_pcm_wait_proc) (ma_snd_pcm_t *pcm, int timeout); +typedef int (* ma_snd_pcm_info_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_info_t* info); +typedef size_t (* ma_snd_pcm_info_sizeof_proc) (); +typedef const char* (* ma_snd_pcm_info_get_name_proc) (const ma_snd_pcm_info_t* info); +typedef int (* ma_snd_config_update_free_global_proc) (); + +// This array specifies each of the common devices that can be used for both playback and capture. +const char* g_maCommonDeviceNamesALSA[] = { + "default", + "null", + "pulse", + "jack" +}; + +// This array allows us to blacklist specific playback devices. +const char* g_maBlacklistedPlaybackDeviceNamesALSA[] = { + "" +}; + +// This array allows us to blacklist specific capture devices. +const char* g_maBlacklistedCaptureDeviceNamesALSA[] = { + "" +}; + + +// This array allows miniaudio to control device-specific default buffer sizes. This uses a scaling factor. Order is important. If +// any part of the string is present in the device's name, the associated scale will be used. +static struct +{ + const char* name; + float scale; +} g_maDefaultBufferSizeScalesALSA[] = { + {"bcm2835 IEC958/HDMI", 2.0f}, + {"bcm2835 ALSA", 2.0f} +}; + +float ma_find_default_buffer_size_scale__alsa(const char* deviceName) +{ + if (deviceName == NULL) { + return 1; + } + + for (size_t i = 0; i < ma_countof(g_maDefaultBufferSizeScalesALSA); ++i) { + if (strstr(g_maDefaultBufferSizeScalesALSA[i].name, deviceName) != NULL) { + return g_maDefaultBufferSizeScalesALSA[i].scale; + } + } + + return 1; +} + +ma_snd_pcm_format_t ma_convert_ma_format_to_alsa_format(ma_format format) +{ + ma_snd_pcm_format_t ALSAFormats[] = { + MA_SND_PCM_FORMAT_UNKNOWN, // ma_format_unknown + MA_SND_PCM_FORMAT_U8, // ma_format_u8 + MA_SND_PCM_FORMAT_S16_LE, // ma_format_s16 + MA_SND_PCM_FORMAT_S24_3LE, // ma_format_s24 + MA_SND_PCM_FORMAT_S32_LE, // ma_format_s32 + MA_SND_PCM_FORMAT_FLOAT_LE // ma_format_f32 + }; + + if (ma_is_big_endian()) { + ALSAFormats[0] = MA_SND_PCM_FORMAT_UNKNOWN; + ALSAFormats[1] = MA_SND_PCM_FORMAT_U8; + ALSAFormats[2] = MA_SND_PCM_FORMAT_S16_BE; + ALSAFormats[3] = MA_SND_PCM_FORMAT_S24_3BE; + ALSAFormats[4] = MA_SND_PCM_FORMAT_S32_BE; + ALSAFormats[5] = MA_SND_PCM_FORMAT_FLOAT_BE; + } + + + return ALSAFormats[format]; +} + +ma_format ma_convert_alsa_format_to_ma_format(ma_snd_pcm_format_t formatALSA) +{ + if (ma_is_little_endian()) { + switch (formatALSA) { + case MA_SND_PCM_FORMAT_S16_LE: return ma_format_s16; + case MA_SND_PCM_FORMAT_S24_3LE: return ma_format_s24; + case MA_SND_PCM_FORMAT_S32_LE: return ma_format_s32; + case MA_SND_PCM_FORMAT_FLOAT_LE: return ma_format_f32; + default: break; + } + } else { + switch (formatALSA) { + case MA_SND_PCM_FORMAT_S16_BE: return ma_format_s16; + case MA_SND_PCM_FORMAT_S24_3BE: return ma_format_s24; + case MA_SND_PCM_FORMAT_S32_BE: return ma_format_s32; + case MA_SND_PCM_FORMAT_FLOAT_BE: return ma_format_f32; + default: break; + } + } + + // Endian agnostic. + switch (formatALSA) { + case MA_SND_PCM_FORMAT_U8: return ma_format_u8; + default: return ma_format_unknown; + } +} + +ma_channel ma_convert_alsa_channel_position_to_ma_channel(unsigned int alsaChannelPos) +{ + switch (alsaChannelPos) + { + case MA_SND_CHMAP_MONO: return MA_CHANNEL_MONO; + case MA_SND_CHMAP_FL: return MA_CHANNEL_FRONT_LEFT; + case MA_SND_CHMAP_FR: return MA_CHANNEL_FRONT_RIGHT; + case MA_SND_CHMAP_RL: return MA_CHANNEL_BACK_LEFT; + case MA_SND_CHMAP_RR: return MA_CHANNEL_BACK_RIGHT; + case MA_SND_CHMAP_FC: return MA_CHANNEL_FRONT_CENTER; + case MA_SND_CHMAP_LFE: return MA_CHANNEL_LFE; + case MA_SND_CHMAP_SL: return MA_CHANNEL_SIDE_LEFT; + case MA_SND_CHMAP_SR: return MA_CHANNEL_SIDE_RIGHT; + case MA_SND_CHMAP_RC: return MA_CHANNEL_BACK_CENTER; + case MA_SND_CHMAP_FLC: return MA_CHANNEL_FRONT_LEFT_CENTER; + case MA_SND_CHMAP_FRC: return MA_CHANNEL_FRONT_RIGHT_CENTER; + case MA_SND_CHMAP_RLC: return 0; + case MA_SND_CHMAP_RRC: return 0; + case MA_SND_CHMAP_FLW: return 0; + case MA_SND_CHMAP_FRW: return 0; + case MA_SND_CHMAP_FLH: return 0; + case MA_SND_CHMAP_FCH: return 0; + case MA_SND_CHMAP_FRH: return 0; + case MA_SND_CHMAP_TC: return MA_CHANNEL_TOP_CENTER; + case MA_SND_CHMAP_TFL: return MA_CHANNEL_TOP_FRONT_LEFT; + case MA_SND_CHMAP_TFR: return MA_CHANNEL_TOP_FRONT_RIGHT; + case MA_SND_CHMAP_TFC: return MA_CHANNEL_TOP_FRONT_CENTER; + case MA_SND_CHMAP_TRL: return MA_CHANNEL_TOP_BACK_LEFT; + case MA_SND_CHMAP_TRR: return MA_CHANNEL_TOP_BACK_RIGHT; + case MA_SND_CHMAP_TRC: return MA_CHANNEL_TOP_BACK_CENTER; + default: break; + } + + return 0; +} + +ma_bool32 ma_is_common_device_name__alsa(const char* name) +{ + for (size_t iName = 0; iName < ma_countof(g_maCommonDeviceNamesALSA); ++iName) { + if (ma_strcmp(name, g_maCommonDeviceNamesALSA[iName]) == 0) { + return MA_TRUE; + } + } + + return MA_FALSE; +} + + +ma_bool32 ma_is_playback_device_blacklisted__alsa(const char* name) +{ + for (size_t iName = 0; iName < ma_countof(g_maBlacklistedPlaybackDeviceNamesALSA); ++iName) { + if (ma_strcmp(name, g_maBlacklistedPlaybackDeviceNamesALSA[iName]) == 0) { + return MA_TRUE; + } + } + + return MA_FALSE; +} + +ma_bool32 ma_is_capture_device_blacklisted__alsa(const char* name) +{ + for (size_t iName = 0; iName < ma_countof(g_maBlacklistedCaptureDeviceNamesALSA); ++iName) { + if (ma_strcmp(name, g_maBlacklistedCaptureDeviceNamesALSA[iName]) == 0) { + return MA_TRUE; + } + } + + return MA_FALSE; +} + +ma_bool32 ma_is_device_blacklisted__alsa(ma_device_type deviceType, const char* name) +{ + if (deviceType == ma_device_type_playback) { + return ma_is_playback_device_blacklisted__alsa(name); + } else { + return ma_is_capture_device_blacklisted__alsa(name); + } +} + + +const char* ma_find_char(const char* str, char c, int* index) +{ + int i = 0; + for (;;) { + if (str[i] == '\0') { + if (index) *index = -1; + return NULL; + } + + if (str[i] == c) { + if (index) *index = i; + return str + i; + } + + i += 1; + } + + // Should never get here, but treat it as though the character was not found to make me feel + // better inside. + if (index) *index = -1; + return NULL; +} + +ma_bool32 ma_is_device_name_in_hw_format__alsa(const char* hwid) +{ + // This function is just checking whether or not hwid is in "hw:%d,%d" format. + + if (hwid == NULL) { + return MA_FALSE; + } + + if (hwid[0] != 'h' || hwid[1] != 'w' || hwid[2] != ':') { + return MA_FALSE; + } + + hwid += 3; + + int commaPos; + const char* dev = ma_find_char(hwid, ',', &commaPos); + if (dev == NULL) { + return MA_FALSE; + } else { + dev += 1; // Skip past the ",". + } + + // Check if the part between the ":" and the "," contains only numbers. If not, return false. + for (int i = 0; i < commaPos; ++i) { + if (hwid[i] < '0' || hwid[i] > '9') { + return MA_FALSE; + } + } + + // Check if everything after the "," is numeric. If not, return false. + int i = 0; + while (dev[i] != '\0') { + if (dev[i] < '0' || dev[i] > '9') { + return MA_FALSE; + } + i += 1; + } + + return MA_TRUE; +} + +int ma_convert_device_name_to_hw_format__alsa(ma_context* pContext, char* dst, size_t dstSize, const char* src) // Returns 0 on success, non-0 on error. +{ + // src should look something like this: "hw:CARD=I82801AAICH,DEV=0" + + if (dst == NULL) return -1; + if (dstSize < 7) return -1; // Absolute minimum size of the output buffer is 7 bytes. + + *dst = '\0'; // Safety. + if (src == NULL) return -1; + + // If the input name is already in "hw:%d,%d" format, just return that verbatim. + if (ma_is_device_name_in_hw_format__alsa(src)) { + return ma_strcpy_s(dst, dstSize, src); + } + + + int colonPos; + src = ma_find_char(src, ':', &colonPos); + if (src == NULL) { + return -1; // Couldn't find a colon + } + + char card[256]; + + int commaPos; + const char* dev = ma_find_char(src, ',', &commaPos); + if (dev == NULL) { + dev = "0"; + ma_strncpy_s(card, sizeof(card), src+6, (size_t)-1); // +6 = ":CARD=" + } else { + dev = dev + 5; // +5 = ",DEV=" + ma_strncpy_s(card, sizeof(card), src+6, commaPos-6); // +6 = ":CARD=" + } + + int cardIndex = ((ma_snd_card_get_index_proc)pContext->alsa.snd_card_get_index)(card); + if (cardIndex < 0) { + return -2; // Failed to retrieve the card index. + } + + //printf("TESTING: CARD=%s,DEV=%s\n", card, dev); + + + // Construction. + dst[0] = 'h'; dst[1] = 'w'; dst[2] = ':'; + if (ma_itoa_s(cardIndex, dst+3, dstSize-3, 10) != 0) { + return -3; + } + if (ma_strcat_s(dst, dstSize, ",") != 0) { + return -3; + } + if (ma_strcat_s(dst, dstSize, dev) != 0) { + return -3; + } + + return 0; +} + +ma_bool32 ma_does_id_exist_in_list__alsa(ma_device_id* pUniqueIDs, ma_uint32 count, const char* pHWID) +{ + ma_assert(pHWID != NULL); + + for (ma_uint32 i = 0; i < count; ++i) { + if (ma_strcmp(pUniqueIDs[i].alsa, pHWID) == 0) { + return MA_TRUE; + } + } + + return MA_FALSE; +} + + +ma_result ma_context_open_pcm__alsa(ma_context* pContext, ma_share_mode shareMode, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_snd_pcm_t** ppPCM) +{ + ma_assert(pContext != NULL); + ma_assert(ppPCM != NULL); + + *ppPCM = NULL; + + ma_snd_pcm_t* pPCM = NULL; + + ma_snd_pcm_stream_t stream = (deviceType == ma_device_type_playback) ? MA_SND_PCM_STREAM_PLAYBACK : MA_SND_PCM_STREAM_CAPTURE; + int openMode = MA_SND_PCM_NO_AUTO_RESAMPLE | MA_SND_PCM_NO_AUTO_CHANNELS | MA_SND_PCM_NO_AUTO_FORMAT; + + if (pDeviceID == NULL) { + // We're opening the default device. I don't know if trying anything other than "default" is necessary, but it makes + // me feel better to try as hard as we can get to get _something_ working. + const char* defaultDeviceNames[] = { + "default", + NULL, + NULL, + NULL, + NULL, + NULL, + NULL + }; + + if (shareMode == ma_share_mode_exclusive) { + defaultDeviceNames[1] = "hw"; + defaultDeviceNames[2] = "hw:0"; + defaultDeviceNames[3] = "hw:0,0"; + } else { + if (deviceType == ma_device_type_playback) { + defaultDeviceNames[1] = "dmix"; + defaultDeviceNames[2] = "dmix:0"; + defaultDeviceNames[3] = "dmix:0,0"; + } else { + defaultDeviceNames[1] = "dsnoop"; + defaultDeviceNames[2] = "dsnoop:0"; + defaultDeviceNames[3] = "dsnoop:0,0"; + } + defaultDeviceNames[4] = "hw"; + defaultDeviceNames[5] = "hw:0"; + defaultDeviceNames[6] = "hw:0,0"; + } + + ma_bool32 isDeviceOpen = MA_FALSE; + for (size_t i = 0; i < ma_countof(defaultDeviceNames); ++i) { // TODO: i = 1 is temporary for testing purposes. Needs to be i = 0. + if (defaultDeviceNames[i] != NULL && defaultDeviceNames[i][0] != '\0') { + if (((ma_snd_pcm_open_proc)pContext->alsa.snd_pcm_open)(&pPCM, defaultDeviceNames[i], stream, openMode) == 0) { + isDeviceOpen = MA_TRUE; + break; + } + } + } + + if (!isDeviceOpen) { + return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[ALSA] snd_pcm_open() failed when trying to open an appropriate default device.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + } else { + // We're trying to open a specific device. There's a few things to consider here: + // + // miniaudio recongnizes a special format of device id that excludes the "hw", "dmix", etc. prefix. It looks like this: ":0,0", ":0,1", etc. When + // an ID of this format is specified, it indicates to miniaudio that it can try different combinations of plugins ("hw", "dmix", etc.) until it + // finds an appropriate one that works. This comes in very handy when trying to open a device in shared mode ("dmix"), vs exclusive mode ("hw"). + + // May end up needing to make small adjustments to the ID, so make a copy. + ma_device_id deviceID = *pDeviceID; + + ma_bool32 isDeviceOpen = MA_FALSE; + if (deviceID.alsa[0] != ':') { + // The ID is not in ":0,0" format. Use the ID exactly as-is. + if (((ma_snd_pcm_open_proc)pContext->alsa.snd_pcm_open)(&pPCM, deviceID.alsa, stream, openMode) == 0) { + isDeviceOpen = MA_TRUE; + } + } else { + // The ID is in ":0,0" format. Try different plugins depending on the shared mode. + if (deviceID.alsa[1] == '\0') { + deviceID.alsa[0] = '\0'; // An ID of ":" should be converted to "". + } + + char hwid[256]; + if (shareMode == ma_share_mode_shared) { + if (deviceType == ma_device_type_playback) { + ma_strcpy_s(hwid, sizeof(hwid), "dmix"); + } else { + ma_strcpy_s(hwid, sizeof(hwid), "dsnoop"); + } + + if (ma_strcat_s(hwid, sizeof(hwid), deviceID.alsa) == 0) { + if (((ma_snd_pcm_open_proc)pContext->alsa.snd_pcm_open)(&pPCM, hwid, stream, openMode) == 0) { + isDeviceOpen = MA_TRUE; + } + } + } + + // If at this point we still don't have an open device it means we're either preferencing exclusive mode or opening with "dmix"/"dsnoop" failed. + if (!isDeviceOpen) { + ma_strcpy_s(hwid, sizeof(hwid), "hw"); + if (ma_strcat_s(hwid, sizeof(hwid), deviceID.alsa) == 0) { + if (((ma_snd_pcm_open_proc)pContext->alsa.snd_pcm_open)(&pPCM, hwid, stream, openMode) == 0) { + isDeviceOpen = MA_TRUE; + } + } + } + } + + if (!isDeviceOpen) { + return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[ALSA] snd_pcm_open() failed.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + } + + *ppPCM = pPCM; + return MA_SUCCESS; +} + + +ma_bool32 ma_context_is_device_id_equal__alsa(ma_context* pContext, const ma_device_id* pID0, const ma_device_id* pID1) +{ + ma_assert(pContext != NULL); + ma_assert(pID0 != NULL); + ma_assert(pID1 != NULL); + (void)pContext; + + return ma_strcmp(pID0->alsa, pID1->alsa) == 0; +} + +ma_result ma_context_enumerate_devices__alsa(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData) +{ + ma_assert(pContext != NULL); + ma_assert(callback != NULL); + + ma_bool32 cbResult = MA_TRUE; + + ma_mutex_lock(&pContext->alsa.internalDeviceEnumLock); + + char** ppDeviceHints; + if (((ma_snd_device_name_hint_proc)pContext->alsa.snd_device_name_hint)(-1, "pcm", (void***)&ppDeviceHints) < 0) { + ma_mutex_unlock(&pContext->alsa.internalDeviceEnumLock); + return MA_NO_BACKEND; + } + + ma_device_id* pUniqueIDs = NULL; + ma_uint32 uniqueIDCount = 0; + + char** ppNextDeviceHint = ppDeviceHints; + while (*ppNextDeviceHint != NULL) { + char* NAME = ((ma_snd_device_name_get_hint_proc)pContext->alsa.snd_device_name_get_hint)(*ppNextDeviceHint, "NAME"); + char* DESC = ((ma_snd_device_name_get_hint_proc)pContext->alsa.snd_device_name_get_hint)(*ppNextDeviceHint, "DESC"); + char* IOID = ((ma_snd_device_name_get_hint_proc)pContext->alsa.snd_device_name_get_hint)(*ppNextDeviceHint, "IOID"); + + ma_device_type deviceType = ma_device_type_playback; + if ((IOID == NULL || ma_strcmp(IOID, "Output") == 0)) { + deviceType = ma_device_type_playback; + } + if ((IOID != NULL && ma_strcmp(IOID, "Input" ) == 0)) { + deviceType = ma_device_type_capture; + } + + ma_bool32 stopEnumeration = MA_FALSE; +#if 0 + printf("NAME: %s\n", NAME); + printf("DESC: %s\n", DESC); + printf("IOID: %s\n", IOID); + + char hwid2[256]; + ma_convert_device_name_to_hw_format__alsa(pContext, hwid2, sizeof(hwid2), NAME); + printf("DEVICE ID: %s\n\n", hwid2); +#endif + + char hwid[sizeof(pUniqueIDs->alsa)]; + if (NAME != NULL) { + if (pContext->config.alsa.useVerboseDeviceEnumeration) { + // Verbose mode. Use the name exactly as-is. + ma_strncpy_s(hwid, sizeof(hwid), NAME, (size_t)-1); + } else { + // Simplified mode. Use ":%d,%d" format. + if (ma_convert_device_name_to_hw_format__alsa(pContext, hwid, sizeof(hwid), NAME) == 0) { + // At this point, hwid looks like "hw:0,0". In simplified enumeration mode, we actually want to strip off the + // plugin name so it looks like ":0,0". The reason for this is that this special format is detected at device + // initialization time and is used as an indicator to try and use the most appropriate plugin depending on the + // device type and sharing mode. + char* dst = hwid; + char* src = hwid+2; + while ((*dst++ = *src++)); + } else { + // Conversion to "hw:%d,%d" failed. Just use the name as-is. + ma_strncpy_s(hwid, sizeof(hwid), NAME, (size_t)-1); + } + + if (ma_does_id_exist_in_list__alsa(pUniqueIDs, uniqueIDCount, hwid)) { + goto next_device; // The device has already been enumerated. Move on to the next one. + } else { + // The device has not yet been enumerated. Make sure it's added to our list so that it's not enumerated again. + ma_device_id* pNewUniqueIDs = (ma_device_id*)ma_realloc(pUniqueIDs, sizeof(*pUniqueIDs) * (uniqueIDCount + 1)); + if (pNewUniqueIDs == NULL) { + goto next_device; // Failed to allocate memory. + } + + pUniqueIDs = pNewUniqueIDs; + ma_copy_memory(pUniqueIDs[uniqueIDCount].alsa, hwid, sizeof(hwid)); + uniqueIDCount += 1; + } + } + } else { + ma_zero_memory(hwid, sizeof(hwid)); + } + + ma_device_info deviceInfo; + ma_zero_object(&deviceInfo); + ma_strncpy_s(deviceInfo.id.alsa, sizeof(deviceInfo.id.alsa), hwid, (size_t)-1); + + // DESC is the friendly name. We treat this slightly differently depending on whether or not we are using verbose + // device enumeration. In verbose mode we want to take the entire description so that the end-user can distinguish + // between the subdevices of each card/dev pair. In simplified mode, however, we only want the first part of the + // description. + // + // The value in DESC seems to be split into two lines, with the first line being the name of the device and the + // second line being a description of the device. I don't like having the description be across two lines because + // it makes formatting ugly and annoying. I'm therefore deciding to put it all on a single line with the second line + // being put into parentheses. In simplified mode I'm just stripping the second line entirely. + if (DESC != NULL) { + int lfPos; + const char* line2 = ma_find_char(DESC, '\n', &lfPos); + if (line2 != NULL) { + line2 += 1; // Skip past the new-line character. + + if (pContext->config.alsa.useVerboseDeviceEnumeration) { + // Verbose mode. Put the second line in brackets. + ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), DESC, lfPos); + ma_strcat_s (deviceInfo.name, sizeof(deviceInfo.name), " ("); + ma_strcat_s (deviceInfo.name, sizeof(deviceInfo.name), line2); + ma_strcat_s (deviceInfo.name, sizeof(deviceInfo.name), ")"); + } else { + // Simplified mode. Strip the second line entirely. + ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), DESC, lfPos); + } + } else { + // There's no second line. Just copy the whole description. + ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), DESC, (size_t)-1); + } + } + + if (!ma_is_device_blacklisted__alsa(deviceType, NAME)) { + cbResult = callback(pContext, deviceType, &deviceInfo, pUserData); + } + + // Some devices are both playback and capture, but they are only enumerated by ALSA once. We need to fire the callback + // again for the other device type in this case. We do this for known devices. + if (cbResult) { + if (ma_is_common_device_name__alsa(NAME)) { + if (deviceType == ma_device_type_playback) { + if (!ma_is_capture_device_blacklisted__alsa(NAME)) { + cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData); + } + } else { + if (!ma_is_playback_device_blacklisted__alsa(NAME)) { + cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData); + } + } + } + } + + if (cbResult == MA_FALSE) { + stopEnumeration = MA_TRUE; + } + + next_device: + free(NAME); + free(DESC); + free(IOID); + ppNextDeviceHint += 1; + + // We need to stop enumeration if the callback returned false. + if (stopEnumeration) { + break; + } + } + + ma_free(pUniqueIDs); + ((ma_snd_device_name_free_hint_proc)pContext->alsa.snd_device_name_free_hint)((void**)ppDeviceHints); + + ma_mutex_unlock(&pContext->alsa.internalDeviceEnumLock); + + return MA_SUCCESS; +} + + +typedef struct +{ + ma_device_type deviceType; + const ma_device_id* pDeviceID; + ma_share_mode shareMode; + ma_device_info* pDeviceInfo; + ma_bool32 foundDevice; +} ma_context_get_device_info_enum_callback_data__alsa; + +ma_bool32 ma_context_get_device_info_enum_callback__alsa(ma_context* pContext, ma_device_type deviceType, const ma_device_info* pDeviceInfo, void* pUserData) +{ + ma_context_get_device_info_enum_callback_data__alsa* pData = (ma_context_get_device_info_enum_callback_data__alsa*)pUserData; + ma_assert(pData != NULL); + + if (pData->pDeviceID == NULL && ma_strcmp(pDeviceInfo->id.alsa, "default") == 0) { + ma_strncpy_s(pData->pDeviceInfo->name, sizeof(pData->pDeviceInfo->name), pDeviceInfo->name, (size_t)-1); + pData->foundDevice = MA_TRUE; + } else { + if (pData->deviceType == deviceType && ma_context_is_device_id_equal__alsa(pContext, pData->pDeviceID, &pDeviceInfo->id)) { + ma_strncpy_s(pData->pDeviceInfo->name, sizeof(pData->pDeviceInfo->name), pDeviceInfo->name, (size_t)-1); + pData->foundDevice = MA_TRUE; + } + } + + // Keep enumerating until we have found the device. + return !pData->foundDevice; +} + +ma_result ma_context_get_device_info__alsa(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_share_mode shareMode, ma_device_info* pDeviceInfo) +{ + ma_assert(pContext != NULL); + + // We just enumerate to find basic information about the device. + ma_context_get_device_info_enum_callback_data__alsa data; + data.deviceType = deviceType; + data.pDeviceID = pDeviceID; + data.shareMode = shareMode; + data.pDeviceInfo = pDeviceInfo; + data.foundDevice = MA_FALSE; + ma_result result = ma_context_enumerate_devices__alsa(pContext, ma_context_get_device_info_enum_callback__alsa, &data); + if (result != MA_SUCCESS) { + return result; + } + + if (!data.foundDevice) { + return MA_NO_DEVICE; + } + + + // For detailed info we need to open the device. + ma_snd_pcm_t* pPCM; + result = ma_context_open_pcm__alsa(pContext, shareMode, deviceType, pDeviceID, &pPCM); + if (result != MA_SUCCESS) { + return result; + } + + // We need to initialize a HW parameters object in order to know what formats are supported. + ma_snd_pcm_hw_params_t* pHWParams = (ma_snd_pcm_hw_params_t*)alloca(((ma_snd_pcm_hw_params_sizeof_proc)pContext->alsa.snd_pcm_hw_params_sizeof)()); + ma_zero_memory(pHWParams, ((ma_snd_pcm_hw_params_sizeof_proc)pContext->alsa.snd_pcm_hw_params_sizeof)()); + + if (((ma_snd_pcm_hw_params_any_proc)pContext->alsa.snd_pcm_hw_params_any)(pPCM, pHWParams) < 0) { + return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to initialize hardware parameters. snd_pcm_hw_params_any() failed.", MA_FAILED_TO_CONFIGURE_BACKEND_DEVICE); + } + + int sampleRateDir = 0; + + ((ma_snd_pcm_hw_params_get_channels_min_proc)pContext->alsa.snd_pcm_hw_params_get_channels_min)(pHWParams, &pDeviceInfo->minChannels); + ((ma_snd_pcm_hw_params_get_channels_max_proc)pContext->alsa.snd_pcm_hw_params_get_channels_max)(pHWParams, &pDeviceInfo->maxChannels); + ((ma_snd_pcm_hw_params_get_rate_min_proc)pContext->alsa.snd_pcm_hw_params_get_rate_min)(pHWParams, &pDeviceInfo->minSampleRate, &sampleRateDir); + ((ma_snd_pcm_hw_params_get_rate_max_proc)pContext->alsa.snd_pcm_hw_params_get_rate_max)(pHWParams, &pDeviceInfo->maxSampleRate, &sampleRateDir); + + // Formats. + ma_snd_pcm_format_mask_t* pFormatMask = (ma_snd_pcm_format_mask_t*)alloca(((ma_snd_pcm_format_mask_sizeof_proc)pContext->alsa.snd_pcm_format_mask_sizeof)()); + ma_zero_memory(pFormatMask, ((ma_snd_pcm_format_mask_sizeof_proc)pContext->alsa.snd_pcm_format_mask_sizeof)()); + ((ma_snd_pcm_hw_params_get_format_mask_proc)pContext->alsa.snd_pcm_hw_params_get_format_mask)(pHWParams, pFormatMask); + + pDeviceInfo->formatCount = 0; + if (((ma_snd_pcm_format_mask_test_proc)pContext->alsa.snd_pcm_format_mask_test)(pFormatMask, MA_SND_PCM_FORMAT_U8)) { + pDeviceInfo->formats[pDeviceInfo->formatCount++] = ma_format_u8; + } + if (((ma_snd_pcm_format_mask_test_proc)pContext->alsa.snd_pcm_format_mask_test)(pFormatMask, MA_SND_PCM_FORMAT_S16_LE)) { + pDeviceInfo->formats[pDeviceInfo->formatCount++] = ma_format_s16; + } + if (((ma_snd_pcm_format_mask_test_proc)pContext->alsa.snd_pcm_format_mask_test)(pFormatMask, MA_SND_PCM_FORMAT_S24_3LE)) { + pDeviceInfo->formats[pDeviceInfo->formatCount++] = ma_format_s24; + } + if (((ma_snd_pcm_format_mask_test_proc)pContext->alsa.snd_pcm_format_mask_test)(pFormatMask, MA_SND_PCM_FORMAT_S32_LE)) { + pDeviceInfo->formats[pDeviceInfo->formatCount++] = ma_format_s32; + } + if (((ma_snd_pcm_format_mask_test_proc)pContext->alsa.snd_pcm_format_mask_test)(pFormatMask, MA_SND_PCM_FORMAT_FLOAT_LE)) { + pDeviceInfo->formats[pDeviceInfo->formatCount++] = ma_format_f32; + } + + ((ma_snd_pcm_close_proc)pContext->alsa.snd_pcm_close)(pPCM); + return MA_SUCCESS; +} + + +#if 0 +// Waits for a number of frames to become available for either capture or playback. The return +// value is the number of frames available. +// +// This will return early if the main loop is broken with ma_device__break_main_loop(). +ma_uint32 ma_device__wait_for_frames__alsa(ma_device* pDevice, ma_bool32* pRequiresRestart) +{ + ma_assert(pDevice != NULL); + + if (pRequiresRestart) *pRequiresRestart = MA_FALSE; + + // I want it so that this function returns the period size in frames. We just wait until that number of frames are available and then return. + ma_uint32 periodSizeInFrames = pDevice->bufferSizeInFrames / pDevice->periods; + while (!pDevice->alsa.breakFromMainLoop) { + ma_snd_pcm_sframes_t framesAvailable = ((ma_snd_pcm_avail_update_proc)pDevice->pContext->alsa.snd_pcm_avail_update)((ma_snd_pcm_t*)pDevice->alsa.pPCM); + if (framesAvailable < 0) { + if (framesAvailable == -EPIPE) { + if (((ma_snd_pcm_recover_proc)pDevice->pContext->alsa.snd_pcm_recover)((ma_snd_pcm_t*)pDevice->alsa.pPCM, framesAvailable, MA_TRUE) < 0) { + return 0; + } + + // A device recovery means a restart for mmap mode. + if (pRequiresRestart) { + *pRequiresRestart = MA_TRUE; + } + + // Try again, but if it fails this time just return an error. + framesAvailable = ((ma_snd_pcm_avail_update_proc)pDevice->pContext->alsa.snd_pcm_avail_update)((ma_snd_pcm_t*)pDevice->alsa.pPCM); + if (framesAvailable < 0) { + return 0; + } + } + } + + if (framesAvailable >= periodSizeInFrames) { + return periodSizeInFrames; + } + + if (framesAvailable < periodSizeInFrames) { + // Less than a whole period is available so keep waiting. + int waitResult = ((ma_snd_pcm_wait_proc)pDevice->pContext->alsa.snd_pcm_wait)((ma_snd_pcm_t*)pDevice->alsa.pPCM, -1); + if (waitResult < 0) { + if (waitResult == -EPIPE) { + if (((ma_snd_pcm_recover_proc)pDevice->pContext->alsa.snd_pcm_recover)((ma_snd_pcm_t*)pDevice->alsa.pPCM, waitResult, MA_TRUE) < 0) { + return 0; + } + + // A device recovery means a restart for mmap mode. + if (pRequiresRestart) { + *pRequiresRestart = MA_TRUE; + } + } + } + } + } + + // We'll get here if the loop was terminated. Just return whatever's available. + ma_snd_pcm_sframes_t framesAvailable = ((ma_snd_pcm_avail_update_proc)pDevice->pContext->alsa.snd_pcm_avail_update)((ma_snd_pcm_t*)pDevice->alsa.pPCM); + if (framesAvailable < 0) { + return 0; + } + + return framesAvailable; +} + +ma_bool32 ma_device_read_from_client_and_write__alsa(ma_device* pDevice) +{ + ma_assert(pDevice != NULL); + if (!ma_device_is_started(pDevice) && ma_device__get_state(pDevice) != MA_STATE_STARTING) { + return MA_FALSE; + } + if (pDevice->alsa.breakFromMainLoop) { + return MA_FALSE; + } + + if (pDevice->alsa.isUsingMMap) { + // mmap. + ma_bool32 requiresRestart; + ma_uint32 framesAvailable = ma_device__wait_for_frames__alsa(pDevice, &requiresRestart); + if (framesAvailable == 0) { + return MA_FALSE; + } + + // Don't bother asking the client for more audio data if we're just stopping the device anyway. + if (pDevice->alsa.breakFromMainLoop) { + return MA_FALSE; + } + + const ma_snd_pcm_channel_area_t* pAreas; + ma_snd_pcm_uframes_t mappedOffset; + ma_snd_pcm_uframes_t mappedFrames = framesAvailable; + while (framesAvailable > 0) { + int result = ((ma_snd_pcm_mmap_begin_proc)pDevice->pContext->alsa.snd_pcm_mmap_begin)((ma_snd_pcm_t*)pDevice->alsa.pPCM, &pAreas, &mappedOffset, &mappedFrames); + if (result < 0) { + return MA_FALSE; + } + + if (mappedFrames > 0) { + void* pBuffer = (ma_uint8*)pAreas[0].addr + ((pAreas[0].first + (mappedOffset * pAreas[0].step)) / 8); + ma_device__read_frames_from_client(pDevice, mappedFrames, pBuffer); + } + + result = ((ma_snd_pcm_mmap_commit_proc)pDevice->pContext->alsa.snd_pcm_mmap_commit)((ma_snd_pcm_t*)pDevice->alsa.pPCM, mappedOffset, mappedFrames); + if (result < 0 || (ma_snd_pcm_uframes_t)result != mappedFrames) { + ((ma_snd_pcm_recover_proc)pDevice->pContext->alsa.snd_pcm_recover)((ma_snd_pcm_t*)pDevice->alsa.pPCM, result, MA_TRUE); + return MA_FALSE; + } + + if (requiresRestart) { + if (((ma_snd_pcm_start_proc)pDevice->pContext->alsa.snd_pcm_start)((ma_snd_pcm_t*)pDevice->alsa.pPCM) < 0) { + return MA_FALSE; + } + } + + if (framesAvailable >= mappedFrames) { + framesAvailable -= mappedFrames; + } else { + framesAvailable = 0; + } + } + } else { + // readi/writei. + while (!pDevice->alsa.breakFromMainLoop) { + ma_uint32 framesAvailable = ma_device__wait_for_frames__alsa(pDevice, NULL); + if (framesAvailable == 0) { + continue; + } + + // Don't bother asking the client for more audio data if we're just stopping the device anyway. + if (pDevice->alsa.breakFromMainLoop) { + return MA_FALSE; + } + + ma_device__read_frames_from_client(pDevice, framesAvailable, pDevice->alsa.pIntermediaryBuffer); + + ma_snd_pcm_sframes_t framesWritten = ((ma_snd_pcm_writei_proc)pDevice->pContext->alsa.snd_pcm_writei)((ma_snd_pcm_t*)pDevice->alsa.pPCM, pDevice->alsa.pIntermediaryBuffer, framesAvailable); + if (framesWritten < 0) { + if (framesWritten == -EAGAIN) { + continue; // Just keep trying... + } else if (framesWritten == -EPIPE) { + // Underrun. Just recover and try writing again. + if (((ma_snd_pcm_recover_proc)pDevice->pContext->alsa.snd_pcm_recover)((ma_snd_pcm_t*)pDevice->alsa.pPCM, framesWritten, MA_TRUE) < 0) { + ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to recover device after underrun.", MA_FAILED_TO_START_BACKEND_DEVICE); + return MA_FALSE; + } + + framesWritten = ((ma_snd_pcm_writei_proc)pDevice->pContext->alsa.snd_pcm_writei)((ma_snd_pcm_t*)pDevice->alsa.pPCM, pDevice->alsa.pIntermediaryBuffer, framesAvailable); + if (framesWritten < 0) { + ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to write data to the internal device.", MA_FAILED_TO_SEND_DATA_TO_DEVICE); + return MA_FALSE; + } + + break; // Success. + } else { + ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] snd_pcm_writei() failed when writing initial data.", MA_FAILED_TO_SEND_DATA_TO_DEVICE); + return MA_FALSE; + } + } else { + break; // Success. + } + } + } + + return MA_TRUE; +} + +ma_bool32 ma_device_read_and_send_to_client__alsa(ma_device* pDevice) +{ + ma_assert(pDevice != NULL); + if (!ma_device_is_started(pDevice)) { + return MA_FALSE; + } + if (pDevice->alsa.breakFromMainLoop) { + return MA_FALSE; + } + + ma_uint32 framesToSend = 0; + void* pBuffer = NULL; + if (pDevice->alsa.pIntermediaryBuffer == NULL) { + // mmap. + ma_bool32 requiresRestart; + ma_uint32 framesAvailable = ma_device__wait_for_frames__alsa(pDevice, &requiresRestart); + if (framesAvailable == 0) { + return MA_FALSE; + } + + const ma_snd_pcm_channel_area_t* pAreas; + ma_snd_pcm_uframes_t mappedOffset; + ma_snd_pcm_uframes_t mappedFrames = framesAvailable; + while (framesAvailable > 0) { + int result = ((ma_snd_pcm_mmap_begin_proc)pDevice->pContext->alsa.snd_pcm_mmap_begin)((ma_snd_pcm_t*)pDevice->alsa.pPCM, &pAreas, &mappedOffset, &mappedFrames); + if (result < 0) { + return MA_FALSE; + } + + if (mappedFrames > 0) { + void* pBuffer = (ma_uint8*)pAreas[0].addr + ((pAreas[0].first + (mappedOffset * pAreas[0].step)) / 8); + ma_device__send_frames_to_client(pDevice, mappedFrames, pBuffer); + } + + result = ((ma_snd_pcm_mmap_commit_proc)pDevice->pContext->alsa.snd_pcm_mmap_commit)((ma_snd_pcm_t*)pDevice->alsa.pPCM, mappedOffset, mappedFrames); + if (result < 0 || (ma_snd_pcm_uframes_t)result != mappedFrames) { + ((ma_snd_pcm_recover_proc)pDevice->pContext->alsa.snd_pcm_recover)((ma_snd_pcm_t*)pDevice->alsa.pPCM, result, MA_TRUE); + return MA_FALSE; + } + + if (requiresRestart) { + if (((ma_snd_pcm_start_proc)pDevice->pContext->alsa.snd_pcm_start)((ma_snd_pcm_t*)pDevice->alsa.pPCM) < 0) { + return MA_FALSE; + } + } + + if (framesAvailable >= mappedFrames) { + framesAvailable -= mappedFrames; + } else { + framesAvailable = 0; + } + } + } else { + // readi/writei. + ma_snd_pcm_sframes_t framesRead = 0; + while (!pDevice->alsa.breakFromMainLoop) { + ma_uint32 framesAvailable = ma_device__wait_for_frames__alsa(pDevice, NULL); + if (framesAvailable == 0) { + continue; + } + + framesRead = ((ma_snd_pcm_readi_proc)pDevice->pContext->alsa.snd_pcm_readi)((ma_snd_pcm_t*)pDevice->alsa.pPCM, pDevice->alsa.pIntermediaryBuffer, framesAvailable); + if (framesRead < 0) { + if (framesRead == -EAGAIN) { + continue; // Just keep trying... + } else if (framesRead == -EPIPE) { + // Overrun. Just recover and try reading again. + if (((ma_snd_pcm_recover_proc)pDevice->pContext->alsa.snd_pcm_recover)((ma_snd_pcm_t*)pDevice->alsa.pPCM, framesRead, MA_TRUE) < 0) { + ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to recover device after overrun.", MA_FAILED_TO_START_BACKEND_DEVICE); + return MA_FALSE; + } + + framesRead = ((ma_snd_pcm_readi_proc)pDevice->pContext->alsa.snd_pcm_readi)((ma_snd_pcm_t*)pDevice->alsa.pPCM, pDevice->alsa.pIntermediaryBuffer, framesAvailable); + if (framesRead < 0) { + ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to read data from the internal device.", MA_FAILED_TO_READ_DATA_FROM_DEVICE); + return MA_FALSE; + } + + break; // Success. + } else { + return MA_FALSE; + } + } else { + break; // Success. + } + } + + framesToSend = framesRead; + pBuffer = pDevice->alsa.pIntermediaryBuffer; + } + + if (framesToSend > 0) { + ma_device__send_frames_to_client(pDevice, framesToSend, pBuffer); + } + + return MA_TRUE; +} +#endif + +void ma_device_uninit__alsa(ma_device* pDevice) +{ + ma_assert(pDevice != NULL); + + if ((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture) { + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture); + } + + if ((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback) { + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback); + } +} + +ma_result ma_device_init_by_type__alsa(ma_context* pContext, const ma_device_config* pConfig, ma_device_type deviceType, ma_device* pDevice) +{ + ma_result result; + ma_snd_pcm_t* pPCM; + ma_bool32 isUsingMMap; + ma_snd_pcm_format_t formatALSA; + ma_share_mode shareMode; + ma_device_id* pDeviceID; + ma_format internalFormat; + ma_uint32 internalChannels; + ma_uint32 internalSampleRate; + ma_channel internalChannelMap[MA_MAX_CHANNELS]; + ma_uint32 internalBufferSizeInFrames; + ma_uint32 internalPeriods; + ma_snd_pcm_hw_params_t* pHWParams; + ma_snd_pcm_sw_params_t* pSWParams; + ma_snd_pcm_uframes_t bufferBoundary; + + ma_assert(pContext != NULL); + ma_assert(pConfig != NULL); + ma_assert(deviceType != ma_device_type_duplex); /* This function should only be called for playback _or_ capture, never duplex. */ + ma_assert(pDevice != NULL); + + formatALSA = ma_convert_ma_format_to_alsa_format((deviceType == ma_device_type_capture) ? pConfig->capture.format : pConfig->playback.format); + shareMode = (deviceType == ma_device_type_capture) ? pConfig->capture.shareMode : pConfig->playback.shareMode; + pDeviceID = (deviceType == ma_device_type_capture) ? pConfig->capture.pDeviceID : pConfig->playback.pDeviceID; + + result = ma_context_open_pcm__alsa(pContext, shareMode, deviceType, pDeviceID, &pPCM); + if (result != MA_SUCCESS) { + return result; + } + + /* If using the default buffer size we may want to apply some device-specific scaling for known devices that have peculiar latency characteristics */ + float bufferSizeScaleFactor = 1; + if (pDevice->usingDefaultBufferSize) { + ma_snd_pcm_info_t* pInfo = (ma_snd_pcm_info_t*)alloca(((ma_snd_pcm_info_sizeof_proc)pContext->alsa.snd_pcm_info_sizeof)()); + ma_zero_memory(pInfo, ((ma_snd_pcm_info_sizeof_proc)pContext->alsa.snd_pcm_info_sizeof)()); + + /* We may need to scale the size of the buffer depending on the device. */ + if (((ma_snd_pcm_info_proc)pContext->alsa.snd_pcm_info)(pPCM, pInfo) == 0) { + const char* deviceName = ((ma_snd_pcm_info_get_name_proc)pContext->alsa.snd_pcm_info_get_name)(pInfo); + if (deviceName != NULL) { + if (ma_strcmp(deviceName, "default") == 0) { + char** ppDeviceHints; + char** ppNextDeviceHint; + + /* It's the default device. We need to use DESC from snd_device_name_hint(). */ + if (((ma_snd_device_name_hint_proc)pContext->alsa.snd_device_name_hint)(-1, "pcm", (void***)&ppDeviceHints) < 0) { + return MA_NO_BACKEND; + } + + ppNextDeviceHint = ppDeviceHints; + while (*ppNextDeviceHint != NULL) { + char* NAME = ((ma_snd_device_name_get_hint_proc)pContext->alsa.snd_device_name_get_hint)(*ppNextDeviceHint, "NAME"); + char* DESC = ((ma_snd_device_name_get_hint_proc)pContext->alsa.snd_device_name_get_hint)(*ppNextDeviceHint, "DESC"); + char* IOID = ((ma_snd_device_name_get_hint_proc)pContext->alsa.snd_device_name_get_hint)(*ppNextDeviceHint, "IOID"); + + ma_bool32 foundDevice = MA_FALSE; + if ((deviceType == ma_device_type_playback && (IOID == NULL || ma_strcmp(IOID, "Output") == 0)) || + (deviceType == ma_device_type_capture && (IOID != NULL && ma_strcmp(IOID, "Input" ) == 0))) { + if (ma_strcmp(NAME, deviceName) == 0) { + bufferSizeScaleFactor = ma_find_default_buffer_size_scale__alsa(DESC); + foundDevice = MA_TRUE; + } + } + + free(NAME); + free(DESC); + free(IOID); + ppNextDeviceHint += 1; + + if (foundDevice) { + break; + } + } + + ((ma_snd_device_name_free_hint_proc)pContext->alsa.snd_device_name_free_hint)((void**)ppDeviceHints); + } else { + bufferSizeScaleFactor = ma_find_default_buffer_size_scale__alsa(deviceName); + } + } + } + } + + + /* Hardware parameters. */ + pHWParams = (ma_snd_pcm_hw_params_t*)alloca(((ma_snd_pcm_hw_params_sizeof_proc)pContext->alsa.snd_pcm_hw_params_sizeof)()); + ma_zero_memory(pHWParams, ((ma_snd_pcm_hw_params_sizeof_proc)pContext->alsa.snd_pcm_hw_params_sizeof)()); + + if (((ma_snd_pcm_hw_params_any_proc)pContext->alsa.snd_pcm_hw_params_any)(pPCM, pHWParams) < 0) { + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to initialize hardware parameters. snd_pcm_hw_params_any() failed.", MA_FAILED_TO_CONFIGURE_BACKEND_DEVICE); + } + + /* MMAP Mode. Try using interleaved MMAP access. If this fails, fall back to standard readi/writei. */ + isUsingMMap = MA_FALSE; +#if 0 /* NOTE: MMAP mode temporarily disabled. */ + if (deviceType != ma_device_type_capture) { /* <-- Disabling MMAP mode for capture devices because I apparently do not have a device that supports it which means I can't test it... Contributions welcome. */ + if (!pConfig->alsa.noMMap && ma_device__is_async(pDevice)) { + if (((ma_snd_pcm_hw_params_set_access_proc)pContext->alsa.snd_pcm_hw_params_set_access)(pPCM, pHWParams, MA_SND_PCM_ACCESS_MMAP_INTERLEAVED) == 0) { + pDevice->alsa.isUsingMMap = MA_TRUE; + } + } + } +#endif + + if (!isUsingMMap) { + if (((ma_snd_pcm_hw_params_set_access_proc)pContext->alsa.snd_pcm_hw_params_set_access)(pPCM, pHWParams, MA_SND_PCM_ACCESS_RW_INTERLEAVED) < 0) {; + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set access mode to neither SND_PCM_ACCESS_MMAP_INTERLEAVED nor SND_PCM_ACCESS_RW_INTERLEAVED. snd_pcm_hw_params_set_access() failed.", MA_FORMAT_NOT_SUPPORTED); + } + } + + /* + Most important properties first. The documentation for OSS (yes, I know this is ALSA!) recommends format, channels, then sample rate. I can't + find any documentation for ALSA specifically, so I'm going to copy the recommendation for OSS. + */ + + /* Format. */ + { + ma_snd_pcm_format_mask_t* pFormatMask; + + /* Try getting every supported format first. */ + pFormatMask = (ma_snd_pcm_format_mask_t*)alloca(((ma_snd_pcm_format_mask_sizeof_proc)pContext->alsa.snd_pcm_format_mask_sizeof)()); + ma_zero_memory(pFormatMask, ((ma_snd_pcm_format_mask_sizeof_proc)pContext->alsa.snd_pcm_format_mask_sizeof)()); + + ((ma_snd_pcm_hw_params_get_format_mask_proc)pContext->alsa.snd_pcm_hw_params_get_format_mask)(pHWParams, pFormatMask); + + /* + At this point we should have a list of supported formats, so now we need to find the best one. We first check if the requested format is + supported, and if so, use that one. If it's not supported, we just run though a list of formats and try to find the best one. + */ + if (!((ma_snd_pcm_format_mask_test_proc)pContext->alsa.snd_pcm_format_mask_test)(pFormatMask, formatALSA)) { + /* The requested format is not supported so now try running through the list of formats and return the best one. */ + ma_snd_pcm_format_t preferredFormatsALSA[] = { + MA_SND_PCM_FORMAT_S16_LE, /* ma_format_s16 */ + MA_SND_PCM_FORMAT_FLOAT_LE, /* ma_format_f32 */ + MA_SND_PCM_FORMAT_S32_LE, /* ma_format_s32 */ + MA_SND_PCM_FORMAT_S24_3LE, /* ma_format_s24 */ + MA_SND_PCM_FORMAT_U8 /* ma_format_u8 */ + }; + + if (ma_is_big_endian()) { + preferredFormatsALSA[0] = MA_SND_PCM_FORMAT_S16_BE; + preferredFormatsALSA[1] = MA_SND_PCM_FORMAT_FLOAT_BE; + preferredFormatsALSA[2] = MA_SND_PCM_FORMAT_S32_BE; + preferredFormatsALSA[3] = MA_SND_PCM_FORMAT_S24_3BE; + preferredFormatsALSA[4] = MA_SND_PCM_FORMAT_U8; + } + + formatALSA = MA_SND_PCM_FORMAT_UNKNOWN; + for (size_t i = 0; i < (sizeof(preferredFormatsALSA) / sizeof(preferredFormatsALSA[0])); ++i) { + if (((ma_snd_pcm_format_mask_test_proc)pContext->alsa.snd_pcm_format_mask_test)(pFormatMask, preferredFormatsALSA[i])) { + formatALSA = preferredFormatsALSA[i]; + break; + } + } + + if (formatALSA == MA_SND_PCM_FORMAT_UNKNOWN) { + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Format not supported. The device does not support any miniaudio formats.", MA_FORMAT_NOT_SUPPORTED); + } + } + + if (((ma_snd_pcm_hw_params_set_format_proc)pContext->alsa.snd_pcm_hw_params_set_format)(pPCM, pHWParams, formatALSA) < 0) { + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Format not supported. snd_pcm_hw_params_set_format() failed.", MA_FORMAT_NOT_SUPPORTED); + } + + internalFormat = ma_convert_alsa_format_to_ma_format(formatALSA); + if (internalFormat == ma_format_unknown) { + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] The chosen format is not supported by miniaudio.", MA_FORMAT_NOT_SUPPORTED); + } + } + + /* Channels. */ + { + unsigned int channels = (deviceType == ma_device_type_capture) ? pConfig->capture.channels : pConfig->playback.channels; + if (((ma_snd_pcm_hw_params_set_channels_near_proc)pContext->alsa.snd_pcm_hw_params_set_channels_near)(pPCM, pHWParams, &channels) < 0) { + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set channel count. snd_pcm_hw_params_set_channels_near() failed.", MA_FORMAT_NOT_SUPPORTED); + } + internalChannels = (ma_uint32)channels; + } + + /* Sample Rate */ + { + unsigned int sampleRate; + + /* + It appears there's either a bug in ALSA, a bug in some drivers, or I'm doing something silly; but having resampling enabled causes + problems with some device configurations when used in conjunction with MMAP access mode. To fix this problem we need to disable + resampling. + + To reproduce this problem, open the "plug:dmix" device, and set the sample rate to 44100. Internally, it looks like dmix uses a + sample rate of 48000. The hardware parameters will get set correctly with no errors, but it looks like the 44100 -> 48000 resampling + doesn't work properly - but only with MMAP access mode. You will notice skipping/crackling in the audio, and it'll run at a slightly + faster rate. + + miniaudio has built-in support for sample rate conversion (albeit low quality at the moment), so disabling resampling should be fine + for us. The only problem is that it won't be taking advantage of any kind of hardware-accelerated resampling and it won't be very + good quality until I get a chance to improve the quality of miniaudio's software sample rate conversion. + + I don't currently know if the dmix plugin is the only one with this error. Indeed, this is the only one I've been able to reproduce + this error with. In the future, we may want to restrict the disabling of resampling to only known bad plugins. + */ + ((ma_snd_pcm_hw_params_set_rate_resample_proc)pContext->alsa.snd_pcm_hw_params_set_rate_resample)(pPCM, pHWParams, 0); + + sampleRate = pConfig->sampleRate; + if (((ma_snd_pcm_hw_params_set_rate_near_proc)pContext->alsa.snd_pcm_hw_params_set_rate_near)(pPCM, pHWParams, &sampleRate, 0) < 0) { + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Sample rate not supported. snd_pcm_hw_params_set_rate_near() failed.", MA_FORMAT_NOT_SUPPORTED); + } + internalSampleRate = (ma_uint32)sampleRate; + } + + /* Buffer Size */ + { + ma_snd_pcm_uframes_t actualBufferSizeInFrames = pConfig->bufferSizeInFrames; + if (actualBufferSizeInFrames == 0) { + actualBufferSizeInFrames = ma_scale_buffer_size(ma_calculate_buffer_size_in_frames_from_milliseconds(pConfig->bufferSizeInMilliseconds, internalSampleRate), bufferSizeScaleFactor); + } + + if (((ma_snd_pcm_hw_params_set_buffer_size_near_proc)pContext->alsa.snd_pcm_hw_params_set_buffer_size_near)(pPCM, pHWParams, &actualBufferSizeInFrames) < 0) { + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set buffer size for device. snd_pcm_hw_params_set_buffer_size() failed.", MA_FORMAT_NOT_SUPPORTED); + } + internalBufferSizeInFrames = actualBufferSizeInFrames; + } + + /* Periods. */ + { + ma_uint32 periods = pConfig->periods; + if (((ma_snd_pcm_hw_params_set_periods_near_proc)pContext->alsa.snd_pcm_hw_params_set_periods_near)(pPCM, pHWParams, &periods, NULL) < 0) { + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set period count. snd_pcm_hw_params_set_periods_near() failed.", MA_FORMAT_NOT_SUPPORTED); + } + internalPeriods = periods; + } + + /* Apply hardware parameters. */ + if (((ma_snd_pcm_hw_params_proc)pContext->alsa.snd_pcm_hw_params)(pPCM, pHWParams) < 0) { + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set hardware parameters. snd_pcm_hw_params() failed.", MA_FAILED_TO_CONFIGURE_BACKEND_DEVICE); + } + + + /* Software parameters. */ + pSWParams = (ma_snd_pcm_sw_params_t*)alloca(((ma_snd_pcm_sw_params_sizeof_proc)pContext->alsa.snd_pcm_sw_params_sizeof)()); + ma_zero_memory(pSWParams, ((ma_snd_pcm_sw_params_sizeof_proc)pContext->alsa.snd_pcm_sw_params_sizeof)()); + + if (((ma_snd_pcm_sw_params_current_proc)pContext->alsa.snd_pcm_sw_params_current)(pPCM, pSWParams) != 0) { + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to initialize software parameters. snd_pcm_sw_params_current() failed.", MA_FAILED_TO_CONFIGURE_BACKEND_DEVICE); + } + + if (deviceType == ma_device_type_capture) { + if (((ma_snd_pcm_sw_params_set_avail_min_proc)pContext->alsa.snd_pcm_sw_params_set_avail_min)(pPCM, pSWParams, 1) != 0) { + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] snd_pcm_sw_params_set_avail_min() failed.", MA_FORMAT_NOT_SUPPORTED); + } + } else { + if (((ma_snd_pcm_sw_params_set_avail_min_proc)pContext->alsa.snd_pcm_sw_params_set_avail_min)(pPCM, pSWParams, 1) != 0) { + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] snd_pcm_sw_params_set_avail_min() failed.", MA_FORMAT_NOT_SUPPORTED); + } + } + + + if (((ma_snd_pcm_sw_params_get_boundary_proc)pContext->alsa.snd_pcm_sw_params_get_boundary)(pSWParams, &bufferBoundary) < 0) { + bufferBoundary = internalBufferSizeInFrames; + } + + //printf("TRACE: bufferBoundary=%ld\n", bufferBoundary); + + if (deviceType == ma_device_type_playback && !isUsingMMap) { /* Only playback devices in writei/readi mode need a start threshold. */ + /* + Subtle detail here with the start threshold. When in playback-only mode (no full-duplex) we can set the start threshold to + the size of a period. But for full-duplex we need to set it such that it is at least two periods. + */ + if (((ma_snd_pcm_sw_params_set_start_threshold_proc)pContext->alsa.snd_pcm_sw_params_set_start_threshold)(pPCM, pSWParams, internalBufferSizeInFrames) != 0) { + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set start threshold for playback device. snd_pcm_sw_params_set_start_threshold() failed.", MA_FAILED_TO_CONFIGURE_BACKEND_DEVICE); + } + if (((ma_snd_pcm_sw_params_set_stop_threshold_proc)pContext->alsa.snd_pcm_sw_params_set_stop_threshold)(pPCM, pSWParams, bufferBoundary) != 0) { /* Set to boundary to loop instead of stop in the event of an xrun. */ + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set stop threshold for playback device. snd_pcm_sw_params_set_stop_threshold() failed.", MA_FAILED_TO_CONFIGURE_BACKEND_DEVICE); + } + } + + if (((ma_snd_pcm_sw_params_proc)pContext->alsa.snd_pcm_sw_params)(pPCM, pSWParams) != 0) { + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set software parameters. snd_pcm_sw_params() failed.", MA_FAILED_TO_CONFIGURE_BACKEND_DEVICE); + } + + + /* Grab the internal channel map. For now we're not going to bother trying to change the channel map and instead just do it ourselves. */ + { + ma_snd_pcm_chmap_t* pChmap = ((ma_snd_pcm_get_chmap_proc)pContext->alsa.snd_pcm_get_chmap)(pPCM); + if (pChmap != NULL) { + /* There are cases where the returned channel map can have a different channel count than was returned by snd_pcm_hw_params_set_channels_near(). */ + if (pChmap->channels >= internalChannels) { + /* Drop excess channels. */ + for (ma_uint32 iChannel = 0; iChannel < internalChannels; ++iChannel) { + internalChannelMap[iChannel] = ma_convert_alsa_channel_position_to_ma_channel(pChmap->pos[iChannel]); + } + } else { + /* + Excess channels use defaults. Do an initial fill with defaults, overwrite the first pChmap->channels, validate to ensure there are no duplicate + channels. If validation fails, fall back to defaults. + */ + ma_bool32 isValid = MA_TRUE; + + /* Fill with defaults. */ + ma_get_standard_channel_map(ma_standard_channel_map_alsa, internalChannels, internalChannelMap); + + /* Overwrite first pChmap->channels channels. */ + for (ma_uint32 iChannel = 0; iChannel < pChmap->channels; ++iChannel) { + internalChannelMap[iChannel] = ma_convert_alsa_channel_position_to_ma_channel(pChmap->pos[iChannel]); + } + + /* Validate. */ + for (ma_uint32 i = 0; i < internalChannels && isValid; ++i) { + for (ma_uint32 j = i+1; j < internalChannels; ++j) { + if (internalChannelMap[i] == internalChannelMap[j]) { + isValid = MA_FALSE; + break; + } + } + } + + /* If our channel map is invalid, fall back to defaults. */ + if (!isValid) { + ma_get_standard_channel_map(ma_standard_channel_map_alsa, internalChannels, internalChannelMap); + } + } + + free(pChmap); + pChmap = NULL; + } else { + /* Could not retrieve the channel map. Fall back to a hard-coded assumption. */ + ma_get_standard_channel_map(ma_standard_channel_map_alsa, internalChannels, internalChannelMap); + } + } + + + /* We're done. Prepare the device. */ + if (((ma_snd_pcm_prepare_proc)pDevice->pContext->alsa.snd_pcm_prepare)(pPCM) < 0) { + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to prepare device.", MA_FAILED_TO_START_BACKEND_DEVICE); + } + + + if (deviceType == ma_device_type_capture) { + pDevice->alsa.pPCMCapture = (ma_ptr)pPCM; + pDevice->alsa.isUsingMMapCapture = isUsingMMap; + pDevice->capture.internalFormat = internalFormat; + pDevice->capture.internalChannels = internalChannels; + pDevice->capture.internalSampleRate = internalSampleRate; + ma_channel_map_copy(pDevice->capture.internalChannelMap, internalChannelMap, internalChannels); + pDevice->capture.internalBufferSizeInFrames = internalBufferSizeInFrames; + pDevice->capture.internalPeriods = internalPeriods; + } else { + pDevice->alsa.pPCMPlayback = (ma_ptr)pPCM; + pDevice->alsa.isUsingMMapPlayback = isUsingMMap; + pDevice->playback.internalFormat = internalFormat; + pDevice->playback.internalChannels = internalChannels; + pDevice->playback.internalSampleRate = internalSampleRate; + ma_channel_map_copy(pDevice->playback.internalChannelMap, internalChannelMap, internalChannels); + pDevice->playback.internalBufferSizeInFrames = internalBufferSizeInFrames; + pDevice->playback.internalPeriods = internalPeriods; + } + + return MA_SUCCESS; +} + +ma_result ma_device_init__alsa(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice) +{ + ma_assert(pDevice != NULL); + + ma_zero_object(&pDevice->alsa); + + if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) { + ma_result result = ma_device_init_by_type__alsa(pContext, pConfig, ma_device_type_capture, pDevice); + if (result != MA_SUCCESS) { + return result; + } + } + + if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) { + ma_result result = ma_device_init_by_type__alsa(pContext, pConfig, ma_device_type_playback, pDevice); + if (result != MA_SUCCESS) { + return result; + } + } + + return MA_SUCCESS; +} + +#if 0 +ma_result ma_device_start__alsa(ma_device* pDevice) +{ + ma_assert(pDevice != NULL); + + // Prepare the device first... + if (((ma_snd_pcm_prepare_proc)pDevice->pContext->alsa.snd_pcm_prepare)((ma_snd_pcm_t*)pDevice->alsa.pPCM) < 0) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to prepare device.", MA_FAILED_TO_START_BACKEND_DEVICE); + } + + // ... and then grab an initial chunk from the client. After this is done, the device should + // automatically start playing, since that's how we configured the software parameters. + if (pDevice->type == ma_device_type_playback) { + if (!ma_device_read_from_client_and_write__alsa(pDevice)) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to write initial chunk of data to the playback device.", MA_FAILED_TO_SEND_DATA_TO_DEVICE); + } + + // mmap mode requires an explicit start. + if (pDevice->alsa.isUsingMMap) { + if (((ma_snd_pcm_start_proc)pDevice->pContext->alsa.snd_pcm_start)((ma_snd_pcm_t*)pDevice->alsa.pPCM) < 0) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to start capture device.", MA_FAILED_TO_START_BACKEND_DEVICE); + } + } + } else { + if (((ma_snd_pcm_start_proc)pDevice->pContext->alsa.snd_pcm_start)((ma_snd_pcm_t*)pDevice->alsa.pPCM) < 0) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to start capture device.", MA_FAILED_TO_START_BACKEND_DEVICE); + } + } + + return MA_SUCCESS; +} +#endif + +ma_result ma_device_stop__alsa(ma_device* pDevice) +{ + ma_assert(pDevice != NULL); + + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + ((ma_snd_pcm_drain_proc)pDevice->pContext->alsa.snd_pcm_drain)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture); + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + /* Using drain instead of drop because ma_device_stop() is defined such that pending frames are processed before returning. */ + ((ma_snd_pcm_drain_proc)pDevice->pContext->alsa.snd_pcm_drain)((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback); + } + + + return MA_SUCCESS; +} + +ma_result ma_device_write__alsa(ma_device* pDevice, const void* pPCMFrames, ma_uint32 frameCount) +{ + ma_snd_pcm_sframes_t resultALSA; + ma_uint32 totalPCMFramesProcessed; + + ma_assert(pDevice != NULL); + ma_assert(pPCMFrames != NULL); + + //printf("TRACE: Enter write()\n"); + + totalPCMFramesProcessed = 0; + while (totalPCMFramesProcessed < frameCount) { + const void* pSrc = ma_offset_ptr(pPCMFrames, totalPCMFramesProcessed * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels)); + ma_uint32 framesRemaining = (frameCount - totalPCMFramesProcessed); + + //printf("TRACE: Writing %d frames (frameCount=%d)\n", framesRemaining, frameCount); + + resultALSA = ((ma_snd_pcm_writei_proc)pDevice->pContext->alsa.snd_pcm_writei)((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback, pSrc, framesRemaining); + if (resultALSA < 0) { + if (resultALSA == -EAGAIN) { + //printf("TRACE: EGAIN (write)\n"); + continue; /* Try again. */ + } else if (resultALSA == -EPIPE) { + //printf("TRACE: EPIPE (write)\n"); + + /* Underrun. Recover and try again. If this fails we need to return an error. */ + if (((ma_snd_pcm_recover_proc)pDevice->pContext->alsa.snd_pcm_recover)((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback, resultALSA, MA_TRUE) < 0) { /* MA_TRUE=silent (don't print anything on error). */ + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to recover device after underrun.", MA_FAILED_TO_START_BACKEND_DEVICE); + } + + /* + In my testing I have had a situation where writei() does not automatically restart the device even though I've set it + up as such in the software parameters. What will happen is writei() will block indefinitely even though the number of + frames is well beyond the auto-start threshold. To work around this I've needed to add an explicit start here. Not sure + if this is me just being stupid and not recovering the device properly, but this definitely feels like something isn't + quite right here. + */ + if (((ma_snd_pcm_start_proc)pDevice->pContext->alsa.snd_pcm_start)((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback) < 0) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to start device after underrun.", MA_FAILED_TO_START_BACKEND_DEVICE); + } + + resultALSA = ((ma_snd_pcm_writei_proc)pDevice->pContext->alsa.snd_pcm_writei)((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback, pSrc, framesRemaining); + if (resultALSA < 0) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to write data to device after underrun.", MA_FAILED_TO_START_BACKEND_DEVICE); + } + } + } + + totalPCMFramesProcessed += resultALSA; + } + + return MA_SUCCESS; +} + +ma_result ma_device_read__alsa(ma_device* pDevice, void* pPCMFrames, ma_uint32 frameCount) +{ + ma_snd_pcm_sframes_t resultALSA; + ma_uint32 totalPCMFramesProcessed; + + ma_assert(pDevice != NULL); + ma_assert(pPCMFrames != NULL); + + /* We need to explicitly start the device if it isn't already. */ + if (((ma_snd_pcm_state_proc)pDevice->pContext->alsa.snd_pcm_state)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture) != MA_SND_PCM_STATE_RUNNING) { + if (((ma_snd_pcm_start_proc)pDevice->pContext->alsa.snd_pcm_start)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture) < 0) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to start device in preparation for reading.", MA_FAILED_TO_START_BACKEND_DEVICE); + } + } + + totalPCMFramesProcessed = 0; + while (totalPCMFramesProcessed < frameCount) { + void* pDst = ma_offset_ptr(pPCMFrames, totalPCMFramesProcessed * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels)); + ma_uint32 framesRemaining = (frameCount - totalPCMFramesProcessed); + + //printf("TRACE: snd_pcm_readi(framesRemaining=%d)\n", framesRemaining); + + resultALSA = ((ma_snd_pcm_readi_proc)pDevice->pContext->alsa.snd_pcm_readi)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture, pDst, framesRemaining); + if (resultALSA < 0) { + if (resultALSA == -EAGAIN) { + //printf("TRACE: EGAIN (read)\n"); + continue; + } else if (resultALSA == -EPIPE) { + //printf("TRACE: EPIPE (read)\n"); + + /* Overrun. Recover and try again. If this fails we need to return an error. */ + if (((ma_snd_pcm_recover_proc)pDevice->pContext->alsa.snd_pcm_recover)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture, resultALSA, MA_TRUE) < 0) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to recover device after overrun.", MA_FAILED_TO_START_BACKEND_DEVICE); + } + + if (((ma_snd_pcm_start_proc)pDevice->pContext->alsa.snd_pcm_start)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture) < 0) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to start device after underrun.", MA_FAILED_TO_START_BACKEND_DEVICE); + } + + resultALSA = ((ma_snd_pcm_readi_proc)pDevice->pContext->alsa.snd_pcm_readi)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture, pDst, framesRemaining); + if (resultALSA < 0) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to read data from the internal device.", MA_FAILED_TO_READ_DATA_FROM_DEVICE); + } + } + } + + totalPCMFramesProcessed += resultALSA; + } + + return MA_SUCCESS; +} + +#if 0 +ma_result ma_device_break_main_loop__alsa(ma_device* pDevice) +{ + ma_assert(pDevice != NULL); + + pDevice->alsa.breakFromMainLoop = MA_TRUE; + return MA_SUCCESS; +} + +ma_result ma_device_main_loop__alsa(ma_device* pDevice) +{ + ma_assert(pDevice != NULL); + + pDevice->alsa.breakFromMainLoop = MA_FALSE; + if (pDevice->type == ma_device_type_playback) { + // Playback. Read from client, write to device. + while (!pDevice->alsa.breakFromMainLoop && ma_device_read_from_client_and_write__alsa(pDevice)) { + } + } else { + // Capture. Read from device, write to client. + while (!pDevice->alsa.breakFromMainLoop && ma_device_read_and_send_to_client__alsa(pDevice)) { + } + } + + return MA_SUCCESS; +} +#endif + +ma_result ma_context_uninit__alsa(ma_context* pContext) +{ + ma_assert(pContext != NULL); + ma_assert(pContext->backend == ma_backend_alsa); + + // Clean up memory for memory leak checkers. + ((ma_snd_config_update_free_global_proc)pContext->alsa.snd_config_update_free_global)(); + +#ifndef MA_NO_RUNTIME_LINKING + ma_dlclose(pContext->alsa.asoundSO); +#endif + + ma_mutex_uninit(&pContext->alsa.internalDeviceEnumLock); + + return MA_SUCCESS; +} + +ma_result ma_context_init__alsa(ma_context* pContext) +{ + ma_assert(pContext != NULL); + +#ifndef MA_NO_RUNTIME_LINKING + const char* libasoundNames[] = { + "libasound.so.2", + "libasound.so" + }; + + for (size_t i = 0; i < ma_countof(libasoundNames); ++i) { + pContext->alsa.asoundSO = ma_dlopen(libasoundNames[i]); + if (pContext->alsa.asoundSO != NULL) { + break; + } + } + + if (pContext->alsa.asoundSO == NULL) { +#ifdef MA_DEBUG_OUTPUT + printf("[ALSA] Failed to open shared object.\n"); +#endif + return MA_NO_BACKEND; + } + + pContext->alsa.snd_pcm_open = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_open"); + pContext->alsa.snd_pcm_close = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_close"); + pContext->alsa.snd_pcm_hw_params_sizeof = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_sizeof"); + pContext->alsa.snd_pcm_hw_params_any = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_any"); + pContext->alsa.snd_pcm_hw_params_set_format = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_set_format"); + pContext->alsa.snd_pcm_hw_params_set_format_first = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_set_format_first"); + pContext->alsa.snd_pcm_hw_params_get_format_mask = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_get_format_mask"); + pContext->alsa.snd_pcm_hw_params_set_channels_near = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_set_channels_near"); + pContext->alsa.snd_pcm_hw_params_set_rate_resample = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_set_rate_resample"); + pContext->alsa.snd_pcm_hw_params_set_rate_near = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_set_rate_near"); + pContext->alsa.snd_pcm_hw_params_set_buffer_size_near = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_set_buffer_size_near"); + pContext->alsa.snd_pcm_hw_params_set_periods_near = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_set_periods_near"); + pContext->alsa.snd_pcm_hw_params_set_access = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_set_access"); + pContext->alsa.snd_pcm_hw_params_get_format = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_get_format"); + pContext->alsa.snd_pcm_hw_params_get_channels = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_get_channels"); + pContext->alsa.snd_pcm_hw_params_get_channels_min = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_get_channels_min"); + pContext->alsa.snd_pcm_hw_params_get_channels_max = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_get_channels_max"); + pContext->alsa.snd_pcm_hw_params_get_rate = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_get_rate"); + pContext->alsa.snd_pcm_hw_params_get_rate_min = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_get_rate_min"); + pContext->alsa.snd_pcm_hw_params_get_rate_max = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_get_rate_max"); + pContext->alsa.snd_pcm_hw_params_get_buffer_size = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_get_buffer_size"); + pContext->alsa.snd_pcm_hw_params_get_periods = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_get_periods"); + pContext->alsa.snd_pcm_hw_params_get_access = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params_get_access"); + pContext->alsa.snd_pcm_hw_params = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_hw_params"); + pContext->alsa.snd_pcm_sw_params_sizeof = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_sw_params_sizeof"); + pContext->alsa.snd_pcm_sw_params_current = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_sw_params_current"); + pContext->alsa.snd_pcm_sw_params_get_boundary = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_sw_params_get_boundary"); + pContext->alsa.snd_pcm_sw_params_set_avail_min = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_sw_params_set_avail_min"); + pContext->alsa.snd_pcm_sw_params_set_start_threshold = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_sw_params_set_start_threshold"); + pContext->alsa.snd_pcm_sw_params_set_stop_threshold = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_sw_params_set_stop_threshold"); + pContext->alsa.snd_pcm_sw_params = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_sw_params"); + pContext->alsa.snd_pcm_format_mask_sizeof = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_format_mask_sizeof"); + pContext->alsa.snd_pcm_format_mask_test = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_format_mask_test"); + pContext->alsa.snd_pcm_get_chmap = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_get_chmap"); + pContext->alsa.snd_pcm_state = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_state"); + pContext->alsa.snd_pcm_prepare = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_prepare"); + pContext->alsa.snd_pcm_start = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_start"); + pContext->alsa.snd_pcm_drop = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_drop"); + pContext->alsa.snd_pcm_drain = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_drain"); + pContext->alsa.snd_device_name_hint = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_device_name_hint"); + pContext->alsa.snd_device_name_get_hint = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_device_name_get_hint"); + pContext->alsa.snd_card_get_index = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_card_get_index"); + pContext->alsa.snd_device_name_free_hint = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_device_name_free_hint"); + pContext->alsa.snd_pcm_mmap_begin = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_mmap_begin"); + pContext->alsa.snd_pcm_mmap_commit = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_mmap_commit"); + pContext->alsa.snd_pcm_recover = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_recover"); + pContext->alsa.snd_pcm_readi = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_readi"); + pContext->alsa.snd_pcm_writei = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_writei"); + pContext->alsa.snd_pcm_avail = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_avail"); + pContext->alsa.snd_pcm_avail_update = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_avail_update"); + pContext->alsa.snd_pcm_wait = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_wait"); + pContext->alsa.snd_pcm_info = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_info"); + pContext->alsa.snd_pcm_info_sizeof = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_info_sizeof"); + pContext->alsa.snd_pcm_info_get_name = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_info_get_name"); + pContext->alsa.snd_config_update_free_global = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_config_update_free_global"); +#else + // The system below is just for type safety. + ma_snd_pcm_open_proc _snd_pcm_open = snd_pcm_open; + ma_snd_pcm_close_proc _snd_pcm_close = snd_pcm_close; + ma_snd_pcm_hw_params_sizeof_proc _snd_pcm_hw_params_sizeof = snd_pcm_hw_params_sizeof; + ma_snd_pcm_hw_params_any_proc _snd_pcm_hw_params_any = snd_pcm_hw_params_any; + ma_snd_pcm_hw_params_set_format_proc _snd_pcm_hw_params_set_format = snd_pcm_hw_params_set_format; + ma_snd_pcm_hw_params_set_format_first_proc _snd_pcm_hw_params_set_format_first = snd_pcm_hw_params_set_format_first; + ma_snd_pcm_hw_params_get_format_mask_proc _snd_pcm_hw_params_get_format_mask = snd_pcm_hw_params_get_format_mask; + ma_snd_pcm_hw_params_set_channels_near_proc _snd_pcm_hw_params_set_channels_near = snd_pcm_hw_params_set_channels_near; + ma_snd_pcm_hw_params_set_rate_resample_proc _snd_pcm_hw_params_set_rate_resample = snd_pcm_hw_params_set_rate_resample; + ma_snd_pcm_hw_params_set_rate_near_proc _snd_pcm_hw_params_set_rate_near = snd_pcm_hw_params_set_rate_near; + ma_snd_pcm_hw_params_set_buffer_size_near_proc _snd_pcm_hw_params_set_buffer_size_near = snd_pcm_hw_params_set_buffer_size_near; + ma_snd_pcm_hw_params_set_periods_near_proc _snd_pcm_hw_params_set_periods_near = snd_pcm_hw_params_set_periods_near; + ma_snd_pcm_hw_params_set_access_proc _snd_pcm_hw_params_set_access = snd_pcm_hw_params_set_access; + ma_snd_pcm_hw_params_get_format_proc _snd_pcm_hw_params_get_format = snd_pcm_hw_params_get_format; + ma_snd_pcm_hw_params_get_channels_proc _snd_pcm_hw_params_get_channels = snd_pcm_hw_params_get_channels; + ma_snd_pcm_hw_params_get_channels_min_proc _snd_pcm_hw_params_get_channels_min = snd_pcm_hw_params_get_channels_min; + ma_snd_pcm_hw_params_get_channels_max_proc _snd_pcm_hw_params_get_channels_max = snd_pcm_hw_params_get_channels_max; + ma_snd_pcm_hw_params_get_rate_proc _snd_pcm_hw_params_get_rate = snd_pcm_hw_params_get_rate; + ma_snd_pcm_hw_params_get_rate_min_proc _snd_pcm_hw_params_get_rate_min = snd_pcm_hw_params_get_rate_min; + ma_snd_pcm_hw_params_get_rate_max_proc _snd_pcm_hw_params_get_rate_max = snd_pcm_hw_params_get_rate_max; + ma_snd_pcm_hw_params_get_buffer_size_proc _snd_pcm_hw_params_get_buffer_size = snd_pcm_hw_params_get_buffer_size; + ma_snd_pcm_hw_params_get_periods_proc _snd_pcm_hw_params_get_periods = snd_pcm_hw_params_get_periods; + ma_snd_pcm_hw_params_get_access_proc _snd_pcm_hw_params_get_access = snd_pcm_hw_params_get_access; + ma_snd_pcm_hw_params_proc _snd_pcm_hw_params = snd_pcm_hw_params; + ma_snd_pcm_sw_params_sizeof_proc _snd_pcm_sw_params_sizeof = snd_pcm_sw_params_sizeof; + ma_snd_pcm_sw_params_current_proc _snd_pcm_sw_params_current = snd_pcm_sw_params_current; + ma_snd_pcm_sw_params_get_boundary_proc _snd_pcm_sw_params_get_boundary = snd_pcm_sw_params_get_boundary; + ma_snd_pcm_sw_params_set_avail_min_proc _snd_pcm_sw_params_set_avail_min = snd_pcm_sw_params_set_avail_min; + ma_snd_pcm_sw_params_set_start_threshold_proc _snd_pcm_sw_params_set_start_threshold = snd_pcm_sw_params_set_start_threshold; + ma_snd_pcm_sw_params_set_stop_threshold_proc _snd_pcm_sw_params_set_stop_threshold = snd_pcm_sw_params_set_stop_threshold; + ma_snd_pcm_sw_params_proc _snd_pcm_sw_params = snd_pcm_sw_params; + ma_snd_pcm_format_mask_sizeof_proc _snd_pcm_format_mask_sizeof = snd_pcm_format_mask_sizeof; + ma_snd_pcm_format_mask_test_proc _snd_pcm_format_mask_test = snd_pcm_format_mask_test; + ma_snd_pcm_get_chmap_proc _snd_pcm_get_chmap = snd_pcm_get_chmap; + ma_snd_pcm_state_proc _snd_pcm_state = snd_pcm_state; + ma_snd_pcm_prepare_proc _snd_pcm_prepare = snd_pcm_prepare; + ma_snd_pcm_start_proc _snd_pcm_start = snd_pcm_start; + ma_snd_pcm_drop_proc _snd_pcm_drop = snd_pcm_drop; + ma_snd_pcm_drain_proc _snd_pcm_drain = snd_pcm_drain; + ma_snd_device_name_hint_proc _snd_device_name_hint = snd_device_name_hint; + ma_snd_device_name_get_hint_proc _snd_device_name_get_hint = snd_device_name_get_hint; + ma_snd_card_get_index_proc _snd_card_get_index = snd_card_get_index; + ma_snd_device_name_free_hint_proc _snd_device_name_free_hint = snd_device_name_free_hint; + ma_snd_pcm_mmap_begin_proc _snd_pcm_mmap_begin = snd_pcm_mmap_begin; + ma_snd_pcm_mmap_commit_proc _snd_pcm_mmap_commit = snd_pcm_mmap_commit; + ma_snd_pcm_recover_proc _snd_pcm_recover = snd_pcm_recover; + ma_snd_pcm_readi_proc _snd_pcm_readi = snd_pcm_readi; + ma_snd_pcm_writei_proc _snd_pcm_writei = snd_pcm_writei; + ma_snd_pcm_avail_proc _snd_pcm_avail = snd_pcm_avail; + ma_snd_pcm_avail_update_proc _snd_pcm_avail_update = snd_pcm_avail_update; + ma_snd_pcm_wait_proc _snd_pcm_wait = snd_pcm_wait; + ma_snd_pcm_info_proc _snd_pcm_info = snd_pcm_info; + ma_snd_pcm_info_sizeof_proc _snd_pcm_info_sizeof = snd_pcm_info_sizeof; + ma_snd_pcm_info_get_name_proc _snd_pcm_info_get_name = snd_pcm_info_get_name; + ma_snd_config_update_free_global_proc _snd_config_update_free_global = snd_config_update_free_global; + + pContext->alsa.snd_pcm_open = (ma_proc)_snd_pcm_open; + pContext->alsa.snd_pcm_close = (ma_proc)_snd_pcm_close; + pContext->alsa.snd_pcm_hw_params_sizeof = (ma_proc)_snd_pcm_hw_params_sizeof; + pContext->alsa.snd_pcm_hw_params_any = (ma_proc)_snd_pcm_hw_params_any; + pContext->alsa.snd_pcm_hw_params_set_format = (ma_proc)_snd_pcm_hw_params_set_format; + pContext->alsa.snd_pcm_hw_params_set_format_first = (ma_proc)_snd_pcm_hw_params_set_format_first; + pContext->alsa.snd_pcm_hw_params_get_format_mask = (ma_proc)_snd_pcm_hw_params_get_format_mask; + pContext->alsa.snd_pcm_hw_params_set_channels_near = (ma_proc)_snd_pcm_hw_params_set_channels_near; + pContext->alsa.snd_pcm_hw_params_set_rate_resample = (ma_proc)_snd_pcm_hw_params_set_rate_resample; + pContext->alsa.snd_pcm_hw_params_set_rate_near = (ma_proc)_snd_pcm_hw_params_set_rate_near; + pContext->alsa.snd_pcm_hw_params_set_buffer_size_near = (ma_proc)_snd_pcm_hw_params_set_buffer_size_near; + pContext->alsa.snd_pcm_hw_params_set_periods_near = (ma_proc)_snd_pcm_hw_params_set_periods_near; + pContext->alsa.snd_pcm_hw_params_set_access = (ma_proc)_snd_pcm_hw_params_set_access; + pContext->alsa.snd_pcm_hw_params_get_format = (ma_proc)_snd_pcm_hw_params_get_format; + pContext->alsa.snd_pcm_hw_params_get_channels = (ma_proc)_snd_pcm_hw_params_get_channels; + pContext->alsa.snd_pcm_hw_params_get_channels_min = (ma_proc)_snd_pcm_hw_params_get_channels_min; + pContext->alsa.snd_pcm_hw_params_get_channels_max = (ma_proc)_snd_pcm_hw_params_get_channels_max; + pContext->alsa.snd_pcm_hw_params_get_rate = (ma_proc)_snd_pcm_hw_params_get_rate; + pContext->alsa.snd_pcm_hw_params_get_buffer_size = (ma_proc)_snd_pcm_hw_params_get_buffer_size; + pContext->alsa.snd_pcm_hw_params_get_periods = (ma_proc)_snd_pcm_hw_params_get_periods; + pContext->alsa.snd_pcm_hw_params_get_access = (ma_proc)_snd_pcm_hw_params_get_access; + pContext->alsa.snd_pcm_hw_params = (ma_proc)_snd_pcm_hw_params; + pContext->alsa.snd_pcm_sw_params_sizeof = (ma_proc)_snd_pcm_sw_params_sizeof; + pContext->alsa.snd_pcm_sw_params_current = (ma_proc)_snd_pcm_sw_params_current; + pContext->alsa.snd_pcm_sw_params_get_boundary = (ma_proc)_snd_pcm_sw_params_get_boundary; + pContext->alsa.snd_pcm_sw_params_set_avail_min = (ma_proc)_snd_pcm_sw_params_set_avail_min; + pContext->alsa.snd_pcm_sw_params_set_start_threshold = (ma_proc)_snd_pcm_sw_params_set_start_threshold; + pContext->alsa.snd_pcm_sw_params_set_stop_threshold = (ma_proc)_snd_pcm_sw_params_set_stop_threshold; + pContext->alsa.snd_pcm_sw_params = (ma_proc)_snd_pcm_sw_params; + pContext->alsa.snd_pcm_format_mask_sizeof = (ma_proc)_snd_pcm_format_mask_sizeof; + pContext->alsa.snd_pcm_format_mask_test = (ma_proc)_snd_pcm_format_mask_test; + pContext->alsa.snd_pcm_get_chmap = (ma_proc)_snd_pcm_get_chmap; + pContext->alsa.snd_pcm_state = (ma_proc)_snd_pcm_state; + pContext->alsa.snd_pcm_prepare = (ma_proc)_snd_pcm_prepare; + pContext->alsa.snd_pcm_start = (ma_proc)_snd_pcm_start; + pContext->alsa.snd_pcm_drop = (ma_proc)_snd_pcm_drop; + pContext->alsa.snd_pcm_drain = (ma_proc)_snd_pcm_drain; + pContext->alsa.snd_device_name_hint = (ma_proc)_snd_device_name_hint; + pContext->alsa.snd_device_name_get_hint = (ma_proc)_snd_device_name_get_hint; + pContext->alsa.snd_card_get_index = (ma_proc)_snd_card_get_index; + pContext->alsa.snd_device_name_free_hint = (ma_proc)_snd_device_name_free_hint; + pContext->alsa.snd_pcm_mmap_begin = (ma_proc)_snd_pcm_mmap_begin; + pContext->alsa.snd_pcm_mmap_commit = (ma_proc)_snd_pcm_mmap_commit; + pContext->alsa.snd_pcm_recover = (ma_proc)_snd_pcm_recover; + pContext->alsa.snd_pcm_readi = (ma_proc)_snd_pcm_readi; + pContext->alsa.snd_pcm_writei = (ma_proc)_snd_pcm_writei; + pContext->alsa.snd_pcm_avail = (ma_proc)_snd_pcm_avail; + pContext->alsa.snd_pcm_avail_update = (ma_proc)_snd_pcm_avail_update; + pContext->alsa.snd_pcm_wait = (ma_proc)_snd_pcm_wait; + pContext->alsa.snd_pcm_info = (ma_proc)_snd_pcm_info; + pContext->alsa.snd_pcm_info_sizeof = (ma_proc)_snd_pcm_info_sizeof; + pContext->alsa.snd_pcm_info_get_name = (ma_proc)_snd_pcm_info_get_name; + pContext->alsa.snd_config_update_free_global = (ma_proc)_snd_config_update_free_global; +#endif + + if (ma_mutex_init(pContext, &pContext->alsa.internalDeviceEnumLock) != MA_SUCCESS) { + ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[ALSA] WARNING: Failed to initialize mutex for internal device enumeration.", MA_ERROR); + } + + pContext->onUninit = ma_context_uninit__alsa; + pContext->onDeviceIDEqual = ma_context_is_device_id_equal__alsa; + pContext->onEnumDevices = ma_context_enumerate_devices__alsa; + pContext->onGetDeviceInfo = ma_context_get_device_info__alsa; + pContext->onDeviceInit = ma_device_init__alsa; + pContext->onDeviceUninit = ma_device_uninit__alsa; + pContext->onDeviceStart = NULL; /*ma_device_start__alsa;*/ + pContext->onDeviceStop = ma_device_stop__alsa; + pContext->onDeviceWrite = ma_device_write__alsa; + pContext->onDeviceRead = ma_device_read__alsa; + + return MA_SUCCESS; +} +#endif // ALSA + + + +/////////////////////////////////////////////////////////////////////////////// +// +// PulseAudio Backend +// +/////////////////////////////////////////////////////////////////////////////// +#ifdef MA_HAS_PULSEAUDIO + +// It is assumed pulseaudio.h is available when compile-time linking is being used. We use this for type safety when using +// compile time linking (we don't have this luxury when using runtime linking without headers). +// +// When using compile time linking, each of our ma_* equivalents should use the sames types as defined by the header. The +// reason for this is that it allow us to take advantage of proper type safety. +#ifdef MA_NO_RUNTIME_LINKING +#include + +#define MA_PA_OK PA_OK +#define MA_PA_ERR_ACCESS PA_ERR_ACCESS +#define MA_PA_ERR_INVALID PA_ERR_INVALID +#define MA_PA_ERR_NOENTITY PA_ERR_NOENTITY + +#define MA_PA_CHANNELS_MAX PA_CHANNELS_MAX +#define MA_PA_RATE_MAX PA_RATE_MAX + +typedef pa_context_flags_t ma_pa_context_flags_t; +#define MA_PA_CONTEXT_NOFLAGS PA_CONTEXT_NOFLAGS +#define MA_PA_CONTEXT_NOAUTOSPAWN PA_CONTEXT_NOAUTOSPAWN +#define MA_PA_CONTEXT_NOFAIL PA_CONTEXT_NOFAIL + +typedef pa_stream_flags_t ma_pa_stream_flags_t; +#define MA_PA_STREAM_NOFLAGS PA_STREAM_NOFLAGS +#define MA_PA_STREAM_START_CORKED PA_STREAM_START_CORKED +#define MA_PA_STREAM_INTERPOLATE_TIMING PA_STREAM_INTERPOLATE_TIMING +#define MA_PA_STREAM_NOT_MONOTONIC PA_STREAM_NOT_MONOTONIC +#define MA_PA_STREAM_AUTO_TIMING_UPDATE PA_STREAM_AUTO_TIMING_UPDATE +#define MA_PA_STREAM_NO_REMAP_CHANNELS PA_STREAM_NO_REMAP_CHANNELS +#define MA_PA_STREAM_NO_REMIX_CHANNELS PA_STREAM_NO_REMIX_CHANNELS +#define MA_PA_STREAM_FIX_FORMAT PA_STREAM_FIX_FORMAT +#define MA_PA_STREAM_FIX_RATE PA_STREAM_FIX_RATE +#define MA_PA_STREAM_FIX_CHANNELS PA_STREAM_FIX_CHANNELS +#define MA_PA_STREAM_DONT_MOVE PA_STREAM_DONT_MOVE +#define MA_PA_STREAM_VARIABLE_RATE PA_STREAM_VARIABLE_RATE +#define MA_PA_STREAM_PEAK_DETECT PA_STREAM_PEAK_DETECT +#define MA_PA_STREAM_START_MUTED PA_STREAM_START_MUTED +#define MA_PA_STREAM_ADJUST_LATENCY PA_STREAM_ADJUST_LATENCY +#define MA_PA_STREAM_EARLY_REQUESTS PA_STREAM_EARLY_REQUESTS +#define MA_PA_STREAM_DONT_INHIBIT_AUTO_SUSPEND PA_STREAM_DONT_INHIBIT_AUTO_SUSPEND +#define MA_PA_STREAM_START_UNMUTED PA_STREAM_START_UNMUTED +#define MA_PA_STREAM_FAIL_ON_SUSPEND PA_STREAM_FAIL_ON_SUSPEND +#define MA_PA_STREAM_RELATIVE_VOLUME PA_STREAM_RELATIVE_VOLUME +#define MA_PA_STREAM_PASSTHROUGH PA_STREAM_PASSTHROUGH + +typedef pa_sink_flags_t ma_pa_sink_flags_t; +#define MA_PA_SINK_NOFLAGS PA_SINK_NOFLAGS +#define MA_PA_SINK_HW_VOLUME_CTRL PA_SINK_HW_VOLUME_CTRL +#define MA_PA_SINK_LATENCY PA_SINK_LATENCY +#define MA_PA_SINK_HARDWARE PA_SINK_HARDWARE +#define MA_PA_SINK_NETWORK PA_SINK_NETWORK +#define MA_PA_SINK_HW_MUTE_CTRL PA_SINK_HW_MUTE_CTRL +#define MA_PA_SINK_DECIBEL_VOLUME PA_SINK_DECIBEL_VOLUME +#define MA_PA_SINK_FLAT_VOLUME PA_SINK_FLAT_VOLUME +#define MA_PA_SINK_DYNAMIC_LATENCY PA_SINK_DYNAMIC_LATENCY +#define MA_PA_SINK_SET_FORMATS PA_SINK_SET_FORMATS + +typedef pa_source_flags_t ma_pa_source_flags_t; +#define MA_PA_SOURCE_NOFLAGS PA_SOURCE_NOFLAGS +#define MA_PA_SOURCE_HW_VOLUME_CTRL PA_SOURCE_HW_VOLUME_CTRL +#define MA_PA_SOURCE_LATENCY PA_SOURCE_LATENCY +#define MA_PA_SOURCE_HARDWARE PA_SOURCE_HARDWARE +#define MA_PA_SOURCE_NETWORK PA_SOURCE_NETWORK +#define MA_PA_SOURCE_HW_MUTE_CTRL PA_SOURCE_HW_MUTE_CTRL +#define MA_PA_SOURCE_DECIBEL_VOLUME PA_SOURCE_DECIBEL_VOLUME +#define MA_PA_SOURCE_DYNAMIC_LATENCY PA_SOURCE_DYNAMIC_LATENCY +#define MA_PA_SOURCE_FLAT_VOLUME PA_SOURCE_FLAT_VOLUME + +typedef pa_context_state_t ma_pa_context_state_t; +#define MA_PA_CONTEXT_UNCONNECTED PA_CONTEXT_UNCONNECTED +#define MA_PA_CONTEXT_CONNECTING PA_CONTEXT_CONNECTING +#define MA_PA_CONTEXT_AUTHORIZING PA_CONTEXT_AUTHORIZING +#define MA_PA_CONTEXT_SETTING_NAME PA_CONTEXT_SETTING_NAME +#define MA_PA_CONTEXT_READY PA_CONTEXT_READY +#define MA_PA_CONTEXT_FAILED PA_CONTEXT_FAILED +#define MA_PA_CONTEXT_TERMINATED PA_CONTEXT_TERMINATED + +typedef pa_stream_state_t ma_pa_stream_state_t; +#define MA_PA_STREAM_UNCONNECTED PA_STREAM_UNCONNECTED +#define MA_PA_STREAM_CREATING PA_STREAM_CREATING +#define MA_PA_STREAM_READY PA_STREAM_READY +#define MA_PA_STREAM_FAILED PA_STREAM_FAILED +#define MA_PA_STREAM_TERMINATED PA_STREAM_TERMINATED + +typedef pa_operation_state_t ma_pa_operation_state_t; +#define MA_PA_OPERATION_RUNNING PA_OPERATION_RUNNING +#define MA_PA_OPERATION_DONE PA_OPERATION_DONE +#define MA_PA_OPERATION_CANCELLED PA_OPERATION_CANCELLED + +typedef pa_sink_state_t ma_pa_sink_state_t; +#define MA_PA_SINK_INVALID_STATE PA_SINK_INVALID_STATE +#define MA_PA_SINK_RUNNING PA_SINK_RUNNING +#define MA_PA_SINK_IDLE PA_SINK_IDLE +#define MA_PA_SINK_SUSPENDED PA_SINK_SUSPENDED + +typedef pa_source_state_t ma_pa_source_state_t; +#define MA_PA_SOURCE_INVALID_STATE PA_SOURCE_INVALID_STATE +#define MA_PA_SOURCE_RUNNING PA_SOURCE_RUNNING +#define MA_PA_SOURCE_IDLE PA_SOURCE_IDLE +#define MA_PA_SOURCE_SUSPENDED PA_SOURCE_SUSPENDED + +typedef pa_seek_mode_t ma_pa_seek_mode_t; +#define MA_PA_SEEK_RELATIVE PA_SEEK_RELATIVE +#define MA_PA_SEEK_ABSOLUTE PA_SEEK_ABSOLUTE +#define MA_PA_SEEK_RELATIVE_ON_READ PA_SEEK_RELATIVE_ON_READ +#define MA_PA_SEEK_RELATIVE_END PA_SEEK_RELATIVE_END + +typedef pa_channel_position_t ma_pa_channel_position_t; +#define MA_PA_CHANNEL_POSITION_INVALID PA_CHANNEL_POSITION_INVALID +#define MA_PA_CHANNEL_POSITION_MONO PA_CHANNEL_POSITION_MONO +#define MA_PA_CHANNEL_POSITION_FRONT_LEFT PA_CHANNEL_POSITION_FRONT_LEFT +#define MA_PA_CHANNEL_POSITION_FRONT_RIGHT PA_CHANNEL_POSITION_FRONT_RIGHT +#define MA_PA_CHANNEL_POSITION_FRONT_CENTER PA_CHANNEL_POSITION_FRONT_CENTER +#define MA_PA_CHANNEL_POSITION_REAR_CENTER PA_CHANNEL_POSITION_REAR_CENTER +#define MA_PA_CHANNEL_POSITION_REAR_LEFT PA_CHANNEL_POSITION_REAR_LEFT +#define MA_PA_CHANNEL_POSITION_REAR_RIGHT PA_CHANNEL_POSITION_REAR_RIGHT +#define MA_PA_CHANNEL_POSITION_LFE PA_CHANNEL_POSITION_LFE +#define MA_PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER +#define MA_PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER +#define MA_PA_CHANNEL_POSITION_SIDE_LEFT PA_CHANNEL_POSITION_SIDE_LEFT +#define MA_PA_CHANNEL_POSITION_SIDE_RIGHT PA_CHANNEL_POSITION_SIDE_RIGHT +#define MA_PA_CHANNEL_POSITION_AUX0 PA_CHANNEL_POSITION_AUX0 +#define MA_PA_CHANNEL_POSITION_AUX1 PA_CHANNEL_POSITION_AUX1 +#define MA_PA_CHANNEL_POSITION_AUX2 PA_CHANNEL_POSITION_AUX2 +#define MA_PA_CHANNEL_POSITION_AUX3 PA_CHANNEL_POSITION_AUX3 +#define MA_PA_CHANNEL_POSITION_AUX4 PA_CHANNEL_POSITION_AUX4 +#define MA_PA_CHANNEL_POSITION_AUX5 PA_CHANNEL_POSITION_AUX5 +#define MA_PA_CHANNEL_POSITION_AUX6 PA_CHANNEL_POSITION_AUX6 +#define MA_PA_CHANNEL_POSITION_AUX7 PA_CHANNEL_POSITION_AUX7 +#define MA_PA_CHANNEL_POSITION_AUX8 PA_CHANNEL_POSITION_AUX8 +#define MA_PA_CHANNEL_POSITION_AUX9 PA_CHANNEL_POSITION_AUX9 +#define MA_PA_CHANNEL_POSITION_AUX10 PA_CHANNEL_POSITION_AUX10 +#define MA_PA_CHANNEL_POSITION_AUX11 PA_CHANNEL_POSITION_AUX11 +#define MA_PA_CHANNEL_POSITION_AUX12 PA_CHANNEL_POSITION_AUX12 +#define MA_PA_CHANNEL_POSITION_AUX13 PA_CHANNEL_POSITION_AUX13 +#define MA_PA_CHANNEL_POSITION_AUX14 PA_CHANNEL_POSITION_AUX14 +#define MA_PA_CHANNEL_POSITION_AUX15 PA_CHANNEL_POSITION_AUX15 +#define MA_PA_CHANNEL_POSITION_AUX16 PA_CHANNEL_POSITION_AUX16 +#define MA_PA_CHANNEL_POSITION_AUX17 PA_CHANNEL_POSITION_AUX17 +#define MA_PA_CHANNEL_POSITION_AUX18 PA_CHANNEL_POSITION_AUX18 +#define MA_PA_CHANNEL_POSITION_AUX19 PA_CHANNEL_POSITION_AUX19 +#define MA_PA_CHANNEL_POSITION_AUX20 PA_CHANNEL_POSITION_AUX20 +#define MA_PA_CHANNEL_POSITION_AUX21 PA_CHANNEL_POSITION_AUX21 +#define MA_PA_CHANNEL_POSITION_AUX22 PA_CHANNEL_POSITION_AUX22 +#define MA_PA_CHANNEL_POSITION_AUX23 PA_CHANNEL_POSITION_AUX23 +#define MA_PA_CHANNEL_POSITION_AUX24 PA_CHANNEL_POSITION_AUX24 +#define MA_PA_CHANNEL_POSITION_AUX25 PA_CHANNEL_POSITION_AUX25 +#define MA_PA_CHANNEL_POSITION_AUX26 PA_CHANNEL_POSITION_AUX26 +#define MA_PA_CHANNEL_POSITION_AUX27 PA_CHANNEL_POSITION_AUX27 +#define MA_PA_CHANNEL_POSITION_AUX28 PA_CHANNEL_POSITION_AUX28 +#define MA_PA_CHANNEL_POSITION_AUX29 PA_CHANNEL_POSITION_AUX29 +#define MA_PA_CHANNEL_POSITION_AUX30 PA_CHANNEL_POSITION_AUX30 +#define MA_PA_CHANNEL_POSITION_AUX31 PA_CHANNEL_POSITION_AUX31 +#define MA_PA_CHANNEL_POSITION_TOP_CENTER PA_CHANNEL_POSITION_TOP_CENTER +#define MA_PA_CHANNEL_POSITION_TOP_FRONT_LEFT PA_CHANNEL_POSITION_TOP_FRONT_LEFT +#define MA_PA_CHANNEL_POSITION_TOP_FRONT_RIGHT PA_CHANNEL_POSITION_TOP_FRONT_RIGHT +#define MA_PA_CHANNEL_POSITION_TOP_FRONT_CENTER PA_CHANNEL_POSITION_TOP_FRONT_CENTER +#define MA_PA_CHANNEL_POSITION_TOP_REAR_LEFT PA_CHANNEL_POSITION_TOP_REAR_LEFT +#define MA_PA_CHANNEL_POSITION_TOP_REAR_RIGHT PA_CHANNEL_POSITION_TOP_REAR_RIGHT +#define MA_PA_CHANNEL_POSITION_TOP_REAR_CENTER PA_CHANNEL_POSITION_TOP_REAR_CENTER +#define MA_PA_CHANNEL_POSITION_LEFT PA_CHANNEL_POSITION_LEFT +#define MA_PA_CHANNEL_POSITION_RIGHT PA_CHANNEL_POSITION_RIGHT +#define MA_PA_CHANNEL_POSITION_CENTER PA_CHANNEL_POSITION_CENTER +#define MA_PA_CHANNEL_POSITION_SUBWOOFER PA_CHANNEL_POSITION_SUBWOOFER + +typedef pa_channel_map_def_t ma_pa_channel_map_def_t; +#define MA_PA_CHANNEL_MAP_AIFF PA_CHANNEL_MAP_AIFF +#define MA_PA_CHANNEL_MAP_ALSA PA_CHANNEL_MAP_ALSA +#define MA_PA_CHANNEL_MAP_AUX PA_CHANNEL_MAP_AUX +#define MA_PA_CHANNEL_MAP_WAVEEX PA_CHANNEL_MAP_WAVEEX +#define MA_PA_CHANNEL_MAP_OSS PA_CHANNEL_MAP_OSS +#define MA_PA_CHANNEL_MAP_DEFAULT PA_CHANNEL_MAP_DEFAULT + +typedef pa_sample_format_t ma_pa_sample_format_t; +#define MA_PA_SAMPLE_INVALID PA_SAMPLE_INVALID +#define MA_PA_SAMPLE_U8 PA_SAMPLE_U8 +#define MA_PA_SAMPLE_ALAW PA_SAMPLE_ALAW +#define MA_PA_SAMPLE_ULAW PA_SAMPLE_ULAW +#define MA_PA_SAMPLE_S16LE PA_SAMPLE_S16LE +#define MA_PA_SAMPLE_S16BE PA_SAMPLE_S16BE +#define MA_PA_SAMPLE_FLOAT32LE PA_SAMPLE_FLOAT32LE +#define MA_PA_SAMPLE_FLOAT32BE PA_SAMPLE_FLOAT32BE +#define MA_PA_SAMPLE_S32LE PA_SAMPLE_S32LE +#define MA_PA_SAMPLE_S32BE PA_SAMPLE_S32BE +#define MA_PA_SAMPLE_S24LE PA_SAMPLE_S24LE +#define MA_PA_SAMPLE_S24BE PA_SAMPLE_S24BE +#define MA_PA_SAMPLE_S24_32LE PA_SAMPLE_S24_32LE +#define MA_PA_SAMPLE_S24_32BE PA_SAMPLE_S24_32BE + +typedef pa_mainloop ma_pa_mainloop; +typedef pa_mainloop_api ma_pa_mainloop_api; +typedef pa_context ma_pa_context; +typedef pa_operation ma_pa_operation; +typedef pa_stream ma_pa_stream; +typedef pa_spawn_api ma_pa_spawn_api; +typedef pa_buffer_attr ma_pa_buffer_attr; +typedef pa_channel_map ma_pa_channel_map; +typedef pa_cvolume ma_pa_cvolume; +typedef pa_sample_spec ma_pa_sample_spec; +typedef pa_sink_info ma_pa_sink_info; +typedef pa_source_info ma_pa_source_info; + +typedef pa_context_notify_cb_t ma_pa_context_notify_cb_t; +typedef pa_sink_info_cb_t ma_pa_sink_info_cb_t; +typedef pa_source_info_cb_t ma_pa_source_info_cb_t; +typedef pa_stream_success_cb_t ma_pa_stream_success_cb_t; +typedef pa_stream_request_cb_t ma_pa_stream_request_cb_t; +typedef pa_free_cb_t ma_pa_free_cb_t; +#else +#define MA_PA_OK 0 +#define MA_PA_ERR_ACCESS 1 +#define MA_PA_ERR_INVALID 2 +#define MA_PA_ERR_NOENTITY 5 + +#define MA_PA_CHANNELS_MAX 32 +#define MA_PA_RATE_MAX 384000 + +typedef int ma_pa_context_flags_t; +#define MA_PA_CONTEXT_NOFLAGS 0x00000000 +#define MA_PA_CONTEXT_NOAUTOSPAWN 0x00000001 +#define MA_PA_CONTEXT_NOFAIL 0x00000002 + +typedef int ma_pa_stream_flags_t; +#define MA_PA_STREAM_NOFLAGS 0x00000000 +#define MA_PA_STREAM_START_CORKED 0x00000001 +#define MA_PA_STREAM_INTERPOLATE_TIMING 0x00000002 +#define MA_PA_STREAM_NOT_MONOTONIC 0x00000004 +#define MA_PA_STREAM_AUTO_TIMING_UPDATE 0x00000008 +#define MA_PA_STREAM_NO_REMAP_CHANNELS 0x00000010 +#define MA_PA_STREAM_NO_REMIX_CHANNELS 0x00000020 +#define MA_PA_STREAM_FIX_FORMAT 0x00000040 +#define MA_PA_STREAM_FIX_RATE 0x00000080 +#define MA_PA_STREAM_FIX_CHANNELS 0x00000100 +#define MA_PA_STREAM_DONT_MOVE 0x00000200 +#define MA_PA_STREAM_VARIABLE_RATE 0x00000400 +#define MA_PA_STREAM_PEAK_DETECT 0x00000800 +#define MA_PA_STREAM_START_MUTED 0x00001000 +#define MA_PA_STREAM_ADJUST_LATENCY 0x00002000 +#define MA_PA_STREAM_EARLY_REQUESTS 0x00004000 +#define MA_PA_STREAM_DONT_INHIBIT_AUTO_SUSPEND 0x00008000 +#define MA_PA_STREAM_START_UNMUTED 0x00010000 +#define MA_PA_STREAM_FAIL_ON_SUSPEND 0x00020000 +#define MA_PA_STREAM_RELATIVE_VOLUME 0x00040000 +#define MA_PA_STREAM_PASSTHROUGH 0x00080000 + +typedef int ma_pa_sink_flags_t; +#define MA_PA_SINK_NOFLAGS 0x00000000 +#define MA_PA_SINK_HW_VOLUME_CTRL 0x00000001 +#define MA_PA_SINK_LATENCY 0x00000002 +#define MA_PA_SINK_HARDWARE 0x00000004 +#define MA_PA_SINK_NETWORK 0x00000008 +#define MA_PA_SINK_HW_MUTE_CTRL 0x00000010 +#define MA_PA_SINK_DECIBEL_VOLUME 0x00000020 +#define MA_PA_SINK_FLAT_VOLUME 0x00000040 +#define MA_PA_SINK_DYNAMIC_LATENCY 0x00000080 +#define MA_PA_SINK_SET_FORMATS 0x00000100 + +typedef int ma_pa_source_flags_t; +#define MA_PA_SOURCE_NOFLAGS 0x00000000 +#define MA_PA_SOURCE_HW_VOLUME_CTRL 0x00000001 +#define MA_PA_SOURCE_LATENCY 0x00000002 +#define MA_PA_SOURCE_HARDWARE 0x00000004 +#define MA_PA_SOURCE_NETWORK 0x00000008 +#define MA_PA_SOURCE_HW_MUTE_CTRL 0x00000010 +#define MA_PA_SOURCE_DECIBEL_VOLUME 0x00000020 +#define MA_PA_SOURCE_DYNAMIC_LATENCY 0x00000040 +#define MA_PA_SOURCE_FLAT_VOLUME 0x00000080 + +typedef int ma_pa_context_state_t; +#define MA_PA_CONTEXT_UNCONNECTED 0 +#define MA_PA_CONTEXT_CONNECTING 1 +#define MA_PA_CONTEXT_AUTHORIZING 2 +#define MA_PA_CONTEXT_SETTING_NAME 3 +#define MA_PA_CONTEXT_READY 4 +#define MA_PA_CONTEXT_FAILED 5 +#define MA_PA_CONTEXT_TERMINATED 6 + +typedef int ma_pa_stream_state_t; +#define MA_PA_STREAM_UNCONNECTED 0 +#define MA_PA_STREAM_CREATING 1 +#define MA_PA_STREAM_READY 2 +#define MA_PA_STREAM_FAILED 3 +#define MA_PA_STREAM_TERMINATED 4 + +typedef int ma_pa_operation_state_t; +#define MA_PA_OPERATION_RUNNING 0 +#define MA_PA_OPERATION_DONE 1 +#define MA_PA_OPERATION_CANCELLED 2 + +typedef int ma_pa_sink_state_t; +#define MA_PA_SINK_INVALID_STATE -1 +#define MA_PA_SINK_RUNNING 0 +#define MA_PA_SINK_IDLE 1 +#define MA_PA_SINK_SUSPENDED 2 + +typedef int ma_pa_source_state_t; +#define MA_PA_SOURCE_INVALID_STATE -1 +#define MA_PA_SOURCE_RUNNING 0 +#define MA_PA_SOURCE_IDLE 1 +#define MA_PA_SOURCE_SUSPENDED 2 + +typedef int ma_pa_seek_mode_t; +#define MA_PA_SEEK_RELATIVE 0 +#define MA_PA_SEEK_ABSOLUTE 1 +#define MA_PA_SEEK_RELATIVE_ON_READ 2 +#define MA_PA_SEEK_RELATIVE_END 3 + +typedef int ma_pa_channel_position_t; +#define MA_PA_CHANNEL_POSITION_INVALID -1 +#define MA_PA_CHANNEL_POSITION_MONO 0 +#define MA_PA_CHANNEL_POSITION_FRONT_LEFT 1 +#define MA_PA_CHANNEL_POSITION_FRONT_RIGHT 2 +#define MA_PA_CHANNEL_POSITION_FRONT_CENTER 3 +#define MA_PA_CHANNEL_POSITION_REAR_CENTER 4 +#define MA_PA_CHANNEL_POSITION_REAR_LEFT 5 +#define MA_PA_CHANNEL_POSITION_REAR_RIGHT 6 +#define MA_PA_CHANNEL_POSITION_LFE 7 +#define MA_PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER 8 +#define MA_PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER 9 +#define MA_PA_CHANNEL_POSITION_SIDE_LEFT 10 +#define MA_PA_CHANNEL_POSITION_SIDE_RIGHT 11 +#define MA_PA_CHANNEL_POSITION_AUX0 12 +#define MA_PA_CHANNEL_POSITION_AUX1 13 +#define MA_PA_CHANNEL_POSITION_AUX2 14 +#define MA_PA_CHANNEL_POSITION_AUX3 15 +#define MA_PA_CHANNEL_POSITION_AUX4 16 +#define MA_PA_CHANNEL_POSITION_AUX5 17 +#define MA_PA_CHANNEL_POSITION_AUX6 18 +#define MA_PA_CHANNEL_POSITION_AUX7 19 +#define MA_PA_CHANNEL_POSITION_AUX8 20 +#define MA_PA_CHANNEL_POSITION_AUX9 21 +#define MA_PA_CHANNEL_POSITION_AUX10 22 +#define MA_PA_CHANNEL_POSITION_AUX11 23 +#define MA_PA_CHANNEL_POSITION_AUX12 24 +#define MA_PA_CHANNEL_POSITION_AUX13 25 +#define MA_PA_CHANNEL_POSITION_AUX14 26 +#define MA_PA_CHANNEL_POSITION_AUX15 27 +#define MA_PA_CHANNEL_POSITION_AUX16 28 +#define MA_PA_CHANNEL_POSITION_AUX17 29 +#define MA_PA_CHANNEL_POSITION_AUX18 30 +#define MA_PA_CHANNEL_POSITION_AUX19 31 +#define MA_PA_CHANNEL_POSITION_AUX20 32 +#define MA_PA_CHANNEL_POSITION_AUX21 33 +#define MA_PA_CHANNEL_POSITION_AUX22 34 +#define MA_PA_CHANNEL_POSITION_AUX23 35 +#define MA_PA_CHANNEL_POSITION_AUX24 36 +#define MA_PA_CHANNEL_POSITION_AUX25 37 +#define MA_PA_CHANNEL_POSITION_AUX26 38 +#define MA_PA_CHANNEL_POSITION_AUX27 39 +#define MA_PA_CHANNEL_POSITION_AUX28 40 +#define MA_PA_CHANNEL_POSITION_AUX29 41 +#define MA_PA_CHANNEL_POSITION_AUX30 42 +#define MA_PA_CHANNEL_POSITION_AUX31 43 +#define MA_PA_CHANNEL_POSITION_TOP_CENTER 44 +#define MA_PA_CHANNEL_POSITION_TOP_FRONT_LEFT 45 +#define MA_PA_CHANNEL_POSITION_TOP_FRONT_RIGHT 46 +#define MA_PA_CHANNEL_POSITION_TOP_FRONT_CENTER 47 +#define MA_PA_CHANNEL_POSITION_TOP_REAR_LEFT 48 +#define MA_PA_CHANNEL_POSITION_TOP_REAR_RIGHT 49 +#define MA_PA_CHANNEL_POSITION_TOP_REAR_CENTER 50 +#define MA_PA_CHANNEL_POSITION_LEFT MA_PA_CHANNEL_POSITION_FRONT_LEFT +#define MA_PA_CHANNEL_POSITION_RIGHT MA_PA_CHANNEL_POSITION_FRONT_RIGHT +#define MA_PA_CHANNEL_POSITION_CENTER MA_PA_CHANNEL_POSITION_FRONT_CENTER +#define MA_PA_CHANNEL_POSITION_SUBWOOFER MA_PA_CHANNEL_POSITION_LFE + +typedef int ma_pa_channel_map_def_t; +#define MA_PA_CHANNEL_MAP_AIFF 0 +#define MA_PA_CHANNEL_MAP_ALSA 1 +#define MA_PA_CHANNEL_MAP_AUX 2 +#define MA_PA_CHANNEL_MAP_WAVEEX 3 +#define MA_PA_CHANNEL_MAP_OSS 4 +#define MA_PA_CHANNEL_MAP_DEFAULT MA_PA_CHANNEL_MAP_AIFF + +typedef int ma_pa_sample_format_t; +#define MA_PA_SAMPLE_INVALID -1 +#define MA_PA_SAMPLE_U8 0 +#define MA_PA_SAMPLE_ALAW 1 +#define MA_PA_SAMPLE_ULAW 2 +#define MA_PA_SAMPLE_S16LE 3 +#define MA_PA_SAMPLE_S16BE 4 +#define MA_PA_SAMPLE_FLOAT32LE 5 +#define MA_PA_SAMPLE_FLOAT32BE 6 +#define MA_PA_SAMPLE_S32LE 7 +#define MA_PA_SAMPLE_S32BE 8 +#define MA_PA_SAMPLE_S24LE 9 +#define MA_PA_SAMPLE_S24BE 10 +#define MA_PA_SAMPLE_S24_32LE 11 +#define MA_PA_SAMPLE_S24_32BE 12 + +typedef struct ma_pa_mainloop ma_pa_mainloop; +typedef struct ma_pa_mainloop_api ma_pa_mainloop_api; +typedef struct ma_pa_context ma_pa_context; +typedef struct ma_pa_operation ma_pa_operation; +typedef struct ma_pa_stream ma_pa_stream; +typedef struct ma_pa_spawn_api ma_pa_spawn_api; + +typedef struct +{ + ma_uint32 maxlength; + ma_uint32 tlength; + ma_uint32 prebuf; + ma_uint32 minreq; + ma_uint32 fragsize; +} ma_pa_buffer_attr; + +typedef struct +{ + ma_uint8 channels; + ma_pa_channel_position_t map[MA_PA_CHANNELS_MAX]; +} ma_pa_channel_map; + +typedef struct +{ + ma_uint8 channels; + ma_uint32 values[MA_PA_CHANNELS_MAX]; +} ma_pa_cvolume; + +typedef struct +{ + ma_pa_sample_format_t format; + ma_uint32 rate; + ma_uint8 channels; +} ma_pa_sample_spec; + +typedef struct +{ + const char* name; + ma_uint32 index; + const char* description; + ma_pa_sample_spec sample_spec; + ma_pa_channel_map channel_map; + ma_uint32 owner_module; + ma_pa_cvolume volume; + int mute; + ma_uint32 monitor_source; + const char* monitor_source_name; + ma_uint64 latency; + const char* driver; + ma_pa_sink_flags_t flags; + void* proplist; + ma_uint64 configured_latency; + ma_uint32 base_volume; + ma_pa_sink_state_t state; + ma_uint32 n_volume_steps; + ma_uint32 card; + ma_uint32 n_ports; + void** ports; + void* active_port; + ma_uint8 n_formats; + void** formats; +} ma_pa_sink_info; + +typedef struct +{ + const char *name; + ma_uint32 index; + const char *description; + ma_pa_sample_spec sample_spec; + ma_pa_channel_map channel_map; + ma_uint32 owner_module; + ma_pa_cvolume volume; + int mute; + ma_uint32 monitor_of_sink; + const char *monitor_of_sink_name; + ma_uint64 latency; + const char *driver; + ma_pa_source_flags_t flags; + void* proplist; + ma_uint64 configured_latency; + ma_uint32 base_volume; + ma_pa_source_state_t state; + ma_uint32 n_volume_steps; + ma_uint32 card; + ma_uint32 n_ports; + void** ports; + void* active_port; + ma_uint8 n_formats; + void** formats; +} ma_pa_source_info; + +typedef void (* ma_pa_context_notify_cb_t)(ma_pa_context* c, void* userdata); +typedef void (* ma_pa_sink_info_cb_t) (ma_pa_context* c, const ma_pa_sink_info* i, int eol, void* userdata); +typedef void (* ma_pa_source_info_cb_t) (ma_pa_context* c, const ma_pa_source_info* i, int eol, void* userdata); +typedef void (* ma_pa_stream_success_cb_t)(ma_pa_stream* s, int success, void* userdata); +typedef void (* ma_pa_stream_request_cb_t)(ma_pa_stream* s, size_t nbytes, void* userdata); +typedef void (* ma_pa_free_cb_t) (void* p); +#endif + + +typedef ma_pa_mainloop* (* ma_pa_mainloop_new_proc) (); +typedef void (* ma_pa_mainloop_free_proc) (ma_pa_mainloop* m); +typedef ma_pa_mainloop_api* (* ma_pa_mainloop_get_api_proc) (ma_pa_mainloop* m); +typedef int (* ma_pa_mainloop_iterate_proc) (ma_pa_mainloop* m, int block, int* retval); +typedef void (* ma_pa_mainloop_wakeup_proc) (ma_pa_mainloop* m); +typedef ma_pa_context* (* ma_pa_context_new_proc) (ma_pa_mainloop_api* mainloop, const char* name); +typedef void (* ma_pa_context_unref_proc) (ma_pa_context* c); +typedef int (* ma_pa_context_connect_proc) (ma_pa_context* c, const char* server, ma_pa_context_flags_t flags, const ma_pa_spawn_api* api); +typedef void (* ma_pa_context_disconnect_proc) (ma_pa_context* c); +typedef void (* ma_pa_context_set_state_callback_proc) (ma_pa_context* c, ma_pa_context_notify_cb_t cb, void* userdata); +typedef ma_pa_context_state_t (* ma_pa_context_get_state_proc) (ma_pa_context* c); +typedef ma_pa_operation* (* ma_pa_context_get_sink_info_list_proc) (ma_pa_context* c, ma_pa_sink_info_cb_t cb, void* userdata); +typedef ma_pa_operation* (* ma_pa_context_get_source_info_list_proc) (ma_pa_context* c, ma_pa_source_info_cb_t cb, void* userdata); +typedef ma_pa_operation* (* ma_pa_context_get_sink_info_by_name_proc) (ma_pa_context* c, const char* name, ma_pa_sink_info_cb_t cb, void* userdata); +typedef ma_pa_operation* (* ma_pa_context_get_source_info_by_name_proc)(ma_pa_context* c, const char* name, ma_pa_source_info_cb_t cb, void* userdata); +typedef void (* ma_pa_operation_unref_proc) (ma_pa_operation* o); +typedef ma_pa_operation_state_t (* ma_pa_operation_get_state_proc) (ma_pa_operation* o); +typedef ma_pa_channel_map* (* ma_pa_channel_map_init_extend_proc) (ma_pa_channel_map* m, unsigned channels, ma_pa_channel_map_def_t def); +typedef int (* ma_pa_channel_map_valid_proc) (const ma_pa_channel_map* m); +typedef int (* ma_pa_channel_map_compatible_proc) (const ma_pa_channel_map* m, const ma_pa_sample_spec* ss); +typedef ma_pa_stream* (* ma_pa_stream_new_proc) (ma_pa_context* c, const char* name, const ma_pa_sample_spec* ss, const ma_pa_channel_map* map); +typedef void (* ma_pa_stream_unref_proc) (ma_pa_stream* s); +typedef int (* ma_pa_stream_connect_playback_proc) (ma_pa_stream* s, const char* dev, const ma_pa_buffer_attr* attr, ma_pa_stream_flags_t flags, const ma_pa_cvolume* volume, ma_pa_stream* sync_stream); +typedef int (* ma_pa_stream_connect_record_proc) (ma_pa_stream* s, const char* dev, const ma_pa_buffer_attr* attr, ma_pa_stream_flags_t flags); +typedef int (* ma_pa_stream_disconnect_proc) (ma_pa_stream* s); +typedef ma_pa_stream_state_t (* ma_pa_stream_get_state_proc) (ma_pa_stream* s); +typedef const ma_pa_sample_spec* (* ma_pa_stream_get_sample_spec_proc) (ma_pa_stream* s); +typedef const ma_pa_channel_map* (* ma_pa_stream_get_channel_map_proc) (ma_pa_stream* s); +typedef const ma_pa_buffer_attr* (* ma_pa_stream_get_buffer_attr_proc) (ma_pa_stream* s); +typedef ma_pa_operation* (* ma_pa_stream_set_buffer_attr_proc) (ma_pa_stream* s, const ma_pa_buffer_attr* attr, ma_pa_stream_success_cb_t cb, void* userdata); +typedef const char* (* ma_pa_stream_get_device_name_proc) (ma_pa_stream* s); +typedef void (* ma_pa_stream_set_write_callback_proc) (ma_pa_stream* s, ma_pa_stream_request_cb_t cb, void* userdata); +typedef void (* ma_pa_stream_set_read_callback_proc) (ma_pa_stream* s, ma_pa_stream_request_cb_t cb, void* userdata); +typedef ma_pa_operation* (* ma_pa_stream_flush_proc) (ma_pa_stream* s, ma_pa_stream_success_cb_t cb, void* userdata); +typedef ma_pa_operation* (* ma_pa_stream_drain_proc) (ma_pa_stream* s, ma_pa_stream_success_cb_t cb, void* userdata); +typedef int (* ma_pa_stream_is_corked_proc) (ma_pa_stream* s); +typedef ma_pa_operation* (* ma_pa_stream_cork_proc) (ma_pa_stream* s, int b, ma_pa_stream_success_cb_t cb, void* userdata); +typedef ma_pa_operation* (* ma_pa_stream_trigger_proc) (ma_pa_stream* s, ma_pa_stream_success_cb_t cb, void* userdata); +typedef int (* ma_pa_stream_begin_write_proc) (ma_pa_stream* s, void** data, size_t* nbytes); +typedef int (* ma_pa_stream_write_proc) (ma_pa_stream* s, const void* data, size_t nbytes, ma_pa_free_cb_t free_cb, int64_t offset, ma_pa_seek_mode_t seek); +typedef int (* ma_pa_stream_peek_proc) (ma_pa_stream* s, const void** data, size_t* nbytes); +typedef int (* ma_pa_stream_drop_proc) (ma_pa_stream* s); +typedef size_t (* ma_pa_stream_writable_size_proc) (ma_pa_stream* s); +typedef size_t (* ma_pa_stream_readable_size_proc) (ma_pa_stream* s); + +typedef struct +{ + ma_uint32 count; + ma_uint32 capacity; + ma_device_info* pInfo; +} ma_pulse_device_enum_data; + +ma_result ma_result_from_pulse(int result) +{ + switch (result) { + case MA_PA_OK: return MA_SUCCESS; + case MA_PA_ERR_ACCESS: return MA_ACCESS_DENIED; + case MA_PA_ERR_INVALID: return MA_INVALID_ARGS; + case MA_PA_ERR_NOENTITY: return MA_NO_DEVICE; + default: return MA_ERROR; + } +} + +#if 0 +ma_pa_sample_format_t ma_format_to_pulse(ma_format format) +{ + if (ma_is_little_endian()) { + switch (format) { + case ma_format_s16: return MA_PA_SAMPLE_S16LE; + case ma_format_s24: return MA_PA_SAMPLE_S24LE; + case ma_format_s32: return MA_PA_SAMPLE_S32LE; + case ma_format_f32: return MA_PA_SAMPLE_FLOAT32LE; + default: break; + } + } else { + switch (format) { + case ma_format_s16: return MA_PA_SAMPLE_S16BE; + case ma_format_s24: return MA_PA_SAMPLE_S24BE; + case ma_format_s32: return MA_PA_SAMPLE_S32BE; + case ma_format_f32: return MA_PA_SAMPLE_FLOAT32BE; + default: break; + } + } + + // Endian agnostic. + switch (format) { + case ma_format_u8: return MA_PA_SAMPLE_U8; + default: return MA_PA_SAMPLE_INVALID; + } +} +#endif + +ma_format ma_format_from_pulse(ma_pa_sample_format_t format) +{ + if (ma_is_little_endian()) { + switch (format) { + case MA_PA_SAMPLE_S16LE: return ma_format_s16; + case MA_PA_SAMPLE_S24LE: return ma_format_s24; + case MA_PA_SAMPLE_S32LE: return ma_format_s32; + case MA_PA_SAMPLE_FLOAT32LE: return ma_format_f32; + default: break; + } + } else { + switch (format) { + case MA_PA_SAMPLE_S16BE: return ma_format_s16; + case MA_PA_SAMPLE_S24BE: return ma_format_s24; + case MA_PA_SAMPLE_S32BE: return ma_format_s32; + case MA_PA_SAMPLE_FLOAT32BE: return ma_format_f32; + default: break; + } + } + + // Endian agnostic. + switch (format) { + case MA_PA_SAMPLE_U8: return ma_format_u8; + default: return ma_format_unknown; + } +} + +ma_channel ma_channel_position_from_pulse(ma_pa_channel_position_t position) +{ + switch (position) + { + case MA_PA_CHANNEL_POSITION_INVALID: return MA_CHANNEL_NONE; + case MA_PA_CHANNEL_POSITION_MONO: return MA_CHANNEL_MONO; + case MA_PA_CHANNEL_POSITION_FRONT_LEFT: return MA_CHANNEL_FRONT_LEFT; + case MA_PA_CHANNEL_POSITION_FRONT_RIGHT: return MA_CHANNEL_FRONT_RIGHT; + case MA_PA_CHANNEL_POSITION_FRONT_CENTER: return MA_CHANNEL_FRONT_CENTER; + case MA_PA_CHANNEL_POSITION_REAR_CENTER: return MA_CHANNEL_BACK_CENTER; + case MA_PA_CHANNEL_POSITION_REAR_LEFT: return MA_CHANNEL_BACK_LEFT; + case MA_PA_CHANNEL_POSITION_REAR_RIGHT: return MA_CHANNEL_BACK_RIGHT; + case MA_PA_CHANNEL_POSITION_LFE: return MA_CHANNEL_LFE; + case MA_PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER: return MA_CHANNEL_FRONT_LEFT_CENTER; + case MA_PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER: return MA_CHANNEL_FRONT_RIGHT_CENTER; + case MA_PA_CHANNEL_POSITION_SIDE_LEFT: return MA_CHANNEL_SIDE_LEFT; + case MA_PA_CHANNEL_POSITION_SIDE_RIGHT: return MA_CHANNEL_SIDE_RIGHT; + case MA_PA_CHANNEL_POSITION_AUX0: return MA_CHANNEL_AUX_0; + case MA_PA_CHANNEL_POSITION_AUX1: return MA_CHANNEL_AUX_1; + case MA_PA_CHANNEL_POSITION_AUX2: return MA_CHANNEL_AUX_2; + case MA_PA_CHANNEL_POSITION_AUX3: return MA_CHANNEL_AUX_3; + case MA_PA_CHANNEL_POSITION_AUX4: return MA_CHANNEL_AUX_4; + case MA_PA_CHANNEL_POSITION_AUX5: return MA_CHANNEL_AUX_5; + case MA_PA_CHANNEL_POSITION_AUX6: return MA_CHANNEL_AUX_6; + case MA_PA_CHANNEL_POSITION_AUX7: return MA_CHANNEL_AUX_7; + case MA_PA_CHANNEL_POSITION_AUX8: return MA_CHANNEL_AUX_8; + case MA_PA_CHANNEL_POSITION_AUX9: return MA_CHANNEL_AUX_9; + case MA_PA_CHANNEL_POSITION_AUX10: return MA_CHANNEL_AUX_10; + case MA_PA_CHANNEL_POSITION_AUX11: return MA_CHANNEL_AUX_11; + case MA_PA_CHANNEL_POSITION_AUX12: return MA_CHANNEL_AUX_12; + case MA_PA_CHANNEL_POSITION_AUX13: return MA_CHANNEL_AUX_13; + case MA_PA_CHANNEL_POSITION_AUX14: return MA_CHANNEL_AUX_14; + case MA_PA_CHANNEL_POSITION_AUX15: return MA_CHANNEL_AUX_15; + case MA_PA_CHANNEL_POSITION_AUX16: return MA_CHANNEL_AUX_16; + case MA_PA_CHANNEL_POSITION_AUX17: return MA_CHANNEL_AUX_17; + case MA_PA_CHANNEL_POSITION_AUX18: return MA_CHANNEL_AUX_18; + case MA_PA_CHANNEL_POSITION_AUX19: return MA_CHANNEL_AUX_19; + case MA_PA_CHANNEL_POSITION_AUX20: return MA_CHANNEL_AUX_20; + case MA_PA_CHANNEL_POSITION_AUX21: return MA_CHANNEL_AUX_21; + case MA_PA_CHANNEL_POSITION_AUX22: return MA_CHANNEL_AUX_22; + case MA_PA_CHANNEL_POSITION_AUX23: return MA_CHANNEL_AUX_23; + case MA_PA_CHANNEL_POSITION_AUX24: return MA_CHANNEL_AUX_24; + case MA_PA_CHANNEL_POSITION_AUX25: return MA_CHANNEL_AUX_25; + case MA_PA_CHANNEL_POSITION_AUX26: return MA_CHANNEL_AUX_26; + case MA_PA_CHANNEL_POSITION_AUX27: return MA_CHANNEL_AUX_27; + case MA_PA_CHANNEL_POSITION_AUX28: return MA_CHANNEL_AUX_28; + case MA_PA_CHANNEL_POSITION_AUX29: return MA_CHANNEL_AUX_29; + case MA_PA_CHANNEL_POSITION_AUX30: return MA_CHANNEL_AUX_30; + case MA_PA_CHANNEL_POSITION_AUX31: return MA_CHANNEL_AUX_31; + case MA_PA_CHANNEL_POSITION_TOP_CENTER: return MA_CHANNEL_TOP_CENTER; + case MA_PA_CHANNEL_POSITION_TOP_FRONT_LEFT: return MA_CHANNEL_TOP_FRONT_LEFT; + case MA_PA_CHANNEL_POSITION_TOP_FRONT_RIGHT: return MA_CHANNEL_TOP_FRONT_RIGHT; + case MA_PA_CHANNEL_POSITION_TOP_FRONT_CENTER: return MA_CHANNEL_TOP_FRONT_CENTER; + case MA_PA_CHANNEL_POSITION_TOP_REAR_LEFT: return MA_CHANNEL_TOP_BACK_LEFT; + case MA_PA_CHANNEL_POSITION_TOP_REAR_RIGHT: return MA_CHANNEL_TOP_BACK_RIGHT; + case MA_PA_CHANNEL_POSITION_TOP_REAR_CENTER: return MA_CHANNEL_TOP_BACK_CENTER; + default: return MA_CHANNEL_NONE; + } +} + +#if 0 +ma_pa_channel_position_t ma_channel_position_to_pulse(ma_channel position) +{ + switch (position) + { + case MA_CHANNEL_NONE: return MA_PA_CHANNEL_POSITION_INVALID; + case MA_CHANNEL_FRONT_LEFT: return MA_PA_CHANNEL_POSITION_FRONT_LEFT; + case MA_CHANNEL_FRONT_RIGHT: return MA_PA_CHANNEL_POSITION_FRONT_RIGHT; + case MA_CHANNEL_FRONT_CENTER: return MA_PA_CHANNEL_POSITION_FRONT_CENTER; + case MA_CHANNEL_LFE: return MA_PA_CHANNEL_POSITION_LFE; + case MA_CHANNEL_BACK_LEFT: return MA_PA_CHANNEL_POSITION_REAR_LEFT; + case MA_CHANNEL_BACK_RIGHT: return MA_PA_CHANNEL_POSITION_REAR_RIGHT; + case MA_CHANNEL_FRONT_LEFT_CENTER: return MA_PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER; + case MA_CHANNEL_FRONT_RIGHT_CENTER: return MA_PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER; + case MA_CHANNEL_BACK_CENTER: return MA_PA_CHANNEL_POSITION_REAR_CENTER; + case MA_CHANNEL_SIDE_LEFT: return MA_PA_CHANNEL_POSITION_SIDE_LEFT; + case MA_CHANNEL_SIDE_RIGHT: return MA_PA_CHANNEL_POSITION_SIDE_RIGHT; + case MA_CHANNEL_TOP_CENTER: return MA_PA_CHANNEL_POSITION_TOP_CENTER; + case MA_CHANNEL_TOP_FRONT_LEFT: return MA_PA_CHANNEL_POSITION_TOP_FRONT_LEFT; + case MA_CHANNEL_TOP_FRONT_CENTER: return MA_PA_CHANNEL_POSITION_TOP_FRONT_CENTER; + case MA_CHANNEL_TOP_FRONT_RIGHT: return MA_PA_CHANNEL_POSITION_TOP_FRONT_RIGHT; + case MA_CHANNEL_TOP_BACK_LEFT: return MA_PA_CHANNEL_POSITION_TOP_REAR_LEFT; + case MA_CHANNEL_TOP_BACK_CENTER: return MA_PA_CHANNEL_POSITION_TOP_REAR_CENTER; + case MA_CHANNEL_TOP_BACK_RIGHT: return MA_PA_CHANNEL_POSITION_TOP_REAR_RIGHT; + case MA_CHANNEL_19: return MA_PA_CHANNEL_POSITION_AUX18; + case MA_CHANNEL_20: return MA_PA_CHANNEL_POSITION_AUX19; + case MA_CHANNEL_21: return MA_PA_CHANNEL_POSITION_AUX20; + case MA_CHANNEL_22: return MA_PA_CHANNEL_POSITION_AUX21; + case MA_CHANNEL_23: return MA_PA_CHANNEL_POSITION_AUX22; + case MA_CHANNEL_24: return MA_PA_CHANNEL_POSITION_AUX23; + case MA_CHANNEL_25: return MA_PA_CHANNEL_POSITION_AUX24; + case MA_CHANNEL_26: return MA_PA_CHANNEL_POSITION_AUX25; + case MA_CHANNEL_27: return MA_PA_CHANNEL_POSITION_AUX26; + case MA_CHANNEL_28: return MA_PA_CHANNEL_POSITION_AUX27; + case MA_CHANNEL_29: return MA_PA_CHANNEL_POSITION_AUX28; + case MA_CHANNEL_30: return MA_PA_CHANNEL_POSITION_AUX29; + case MA_CHANNEL_31: return MA_PA_CHANNEL_POSITION_AUX30; + case MA_CHANNEL_32: return MA_PA_CHANNEL_POSITION_AUX31; + default: return (ma_pa_channel_position_t)position; + } +} +#endif + +ma_result ma_wait_for_operation__pulse(ma_context* pContext, ma_pa_mainloop* pMainLoop, ma_pa_operation* pOP) +{ + ma_assert(pContext != NULL); + ma_assert(pMainLoop != NULL); + ma_assert(pOP != NULL); + + while (((ma_pa_operation_get_state_proc)pContext->pulse.pa_operation_get_state)(pOP) == MA_PA_OPERATION_RUNNING) { + int error = ((ma_pa_mainloop_iterate_proc)pContext->pulse.pa_mainloop_iterate)(pMainLoop, 1, NULL); + if (error < 0) { + return ma_result_from_pulse(error); + } + } + + return MA_SUCCESS; +} + +ma_result ma_device__wait_for_operation__pulse(ma_device* pDevice, ma_pa_operation* pOP) +{ + ma_assert(pDevice != NULL); + ma_assert(pOP != NULL); + + return ma_wait_for_operation__pulse(pDevice->pContext, (ma_pa_mainloop*)pDevice->pulse.pMainLoop, pOP); +} + + +ma_bool32 ma_context_is_device_id_equal__pulse(ma_context* pContext, const ma_device_id* pID0, const ma_device_id* pID1) +{ + ma_assert(pContext != NULL); + ma_assert(pID0 != NULL); + ma_assert(pID1 != NULL); + (void)pContext; + + return ma_strcmp(pID0->pulse, pID1->pulse) == 0; +} + + +typedef struct +{ + ma_context* pContext; + ma_enum_devices_callback_proc callback; + void* pUserData; + ma_bool32 isTerminated; +} ma_context_enumerate_devices_callback_data__pulse; + +void ma_context_enumerate_devices_sink_callback__pulse(ma_pa_context* pPulseContext, const ma_pa_sink_info* pSinkInfo, int endOfList, void* pUserData) +{ + ma_context_enumerate_devices_callback_data__pulse* pData = (ma_context_enumerate_devices_callback_data__pulse*)pUserData; + ma_assert(pData != NULL); + + if (endOfList || pData->isTerminated) { + return; + } + + ma_device_info deviceInfo; + ma_zero_object(&deviceInfo); + + // The name from PulseAudio is the ID for miniaudio. + if (pSinkInfo->name != NULL) { + ma_strncpy_s(deviceInfo.id.pulse, sizeof(deviceInfo.id.pulse), pSinkInfo->name, (size_t)-1); + } + + // The description from PulseAudio is the name for miniaudio. + if (pSinkInfo->description != NULL) { + ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), pSinkInfo->description, (size_t)-1); + } + + pData->isTerminated = !pData->callback(pData->pContext, ma_device_type_playback, &deviceInfo, pData->pUserData); +} + +void ma_context_enumerate_devices_source_callback__pulse(ma_pa_context* pPulseContext, const ma_pa_source_info* pSinkInfo, int endOfList, void* pUserData) +{ + ma_context_enumerate_devices_callback_data__pulse* pData = (ma_context_enumerate_devices_callback_data__pulse*)pUserData; + ma_assert(pData != NULL); + + if (endOfList || pData->isTerminated) { + return; + } + + ma_device_info deviceInfo; + ma_zero_object(&deviceInfo); + + // The name from PulseAudio is the ID for miniaudio. + if (pSinkInfo->name != NULL) { + ma_strncpy_s(deviceInfo.id.pulse, sizeof(deviceInfo.id.pulse), pSinkInfo->name, (size_t)-1); + } + + // The description from PulseAudio is the name for miniaudio. + if (pSinkInfo->description != NULL) { + ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), pSinkInfo->description, (size_t)-1); + } + + pData->isTerminated = !pData->callback(pData->pContext, ma_device_type_capture, &deviceInfo, pData->pUserData); +} + +ma_result ma_context_enumerate_devices__pulse(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData) +{ + ma_assert(pContext != NULL); + ma_assert(callback != NULL); + + ma_result result = MA_SUCCESS; + + ma_context_enumerate_devices_callback_data__pulse callbackData; + callbackData.pContext = pContext; + callbackData.callback = callback; + callbackData.pUserData = pUserData; + callbackData.isTerminated = MA_FALSE; + + ma_pa_operation* pOP = NULL; + + ma_pa_mainloop* pMainLoop = ((ma_pa_mainloop_new_proc)pContext->pulse.pa_mainloop_new)(); + if (pMainLoop == NULL) { + return MA_FAILED_TO_INIT_BACKEND; + } + + ma_pa_mainloop_api* pAPI = ((ma_pa_mainloop_get_api_proc)pContext->pulse.pa_mainloop_get_api)(pMainLoop); + if (pAPI == NULL) { + ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); + return MA_FAILED_TO_INIT_BACKEND; + } + + ma_pa_context* pPulseContext = ((ma_pa_context_new_proc)pContext->pulse.pa_context_new)(pAPI, pContext->config.pulse.pApplicationName); + if (pPulseContext == NULL) { + ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); + return MA_FAILED_TO_INIT_BACKEND; + } + + int error = ((ma_pa_context_connect_proc)pContext->pulse.pa_context_connect)(pPulseContext, pContext->config.pulse.pServerName, 0, NULL); + if (error != MA_PA_OK) { + ((ma_pa_context_unref_proc)pContext->pulse.pa_context_unref)(pPulseContext); + ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); + return ma_result_from_pulse(error); + } + + while (((ma_pa_context_get_state_proc)pContext->pulse.pa_context_get_state)(pPulseContext) != MA_PA_CONTEXT_READY) { + error = ((ma_pa_mainloop_iterate_proc)pContext->pulse.pa_mainloop_iterate)(pMainLoop, 1, NULL); + if (error < 0) { + result = ma_result_from_pulse(error); + goto done; + } + } + + + // Playback. + if (!callbackData.isTerminated) { + pOP = ((ma_pa_context_get_sink_info_list_proc)pContext->pulse.pa_context_get_sink_info_list)(pPulseContext, ma_context_enumerate_devices_sink_callback__pulse, &callbackData); + if (pOP == NULL) { + result = MA_ERROR; + goto done; + } + + result = ma_wait_for_operation__pulse(pContext, pMainLoop, pOP); + ((ma_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP); + if (result != MA_SUCCESS) { + goto done; + } + } + + + // Capture. + if (!callbackData.isTerminated) { + pOP = ((ma_pa_context_get_source_info_list_proc)pContext->pulse.pa_context_get_source_info_list)(pPulseContext, ma_context_enumerate_devices_source_callback__pulse, &callbackData); + if (pOP == NULL) { + result = MA_ERROR; + goto done; + } + + result = ma_wait_for_operation__pulse(pContext, pMainLoop, pOP); + ((ma_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP); + if (result != MA_SUCCESS) { + goto done; + } + } + +done: + ((ma_pa_context_disconnect_proc)pContext->pulse.pa_context_disconnect)(pPulseContext); + ((ma_pa_context_unref_proc)pContext->pulse.pa_context_unref)(pPulseContext); + ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); + return result; +} + + +typedef struct +{ + ma_device_info* pDeviceInfo; + ma_bool32 foundDevice; +} ma_context_get_device_info_callback_data__pulse; + +void ma_context_get_device_info_sink_callback__pulse(ma_pa_context* pPulseContext, const ma_pa_sink_info* pInfo, int endOfList, void* pUserData) +{ + if (endOfList > 0) { + return; + } + + ma_context_get_device_info_callback_data__pulse* pData = (ma_context_get_device_info_callback_data__pulse*)pUserData; + ma_assert(pData != NULL); + pData->foundDevice = MA_TRUE; + + if (pInfo->name != NULL) { + ma_strncpy_s(pData->pDeviceInfo->id.pulse, sizeof(pData->pDeviceInfo->id.pulse), pInfo->name, (size_t)-1); + } + + if (pInfo->description != NULL) { + ma_strncpy_s(pData->pDeviceInfo->name, sizeof(pData->pDeviceInfo->name), pInfo->description, (size_t)-1); + } + + pData->pDeviceInfo->minChannels = pInfo->sample_spec.channels; + pData->pDeviceInfo->maxChannels = pInfo->sample_spec.channels; + pData->pDeviceInfo->minSampleRate = pInfo->sample_spec.rate; + pData->pDeviceInfo->maxSampleRate = pInfo->sample_spec.rate; + pData->pDeviceInfo->formatCount = 1; + pData->pDeviceInfo->formats[0] = ma_format_from_pulse(pInfo->sample_spec.format); +} + +void ma_context_get_device_info_source_callback__pulse(ma_pa_context* pPulseContext, const ma_pa_source_info* pInfo, int endOfList, void* pUserData) +{ + if (endOfList > 0) { + return; + } + + ma_context_get_device_info_callback_data__pulse* pData = (ma_context_get_device_info_callback_data__pulse*)pUserData; + ma_assert(pData != NULL); + pData->foundDevice = MA_TRUE; + + if (pInfo->name != NULL) { + ma_strncpy_s(pData->pDeviceInfo->id.pulse, sizeof(pData->pDeviceInfo->id.pulse), pInfo->name, (size_t)-1); + } + + if (pInfo->description != NULL) { + ma_strncpy_s(pData->pDeviceInfo->name, sizeof(pData->pDeviceInfo->name), pInfo->description, (size_t)-1); + } + + pData->pDeviceInfo->minChannels = pInfo->sample_spec.channels; + pData->pDeviceInfo->maxChannels = pInfo->sample_spec.channels; + pData->pDeviceInfo->minSampleRate = pInfo->sample_spec.rate; + pData->pDeviceInfo->maxSampleRate = pInfo->sample_spec.rate; + pData->pDeviceInfo->formatCount = 1; + pData->pDeviceInfo->formats[0] = ma_format_from_pulse(pInfo->sample_spec.format); +} + +ma_result ma_context_get_device_info__pulse(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_share_mode shareMode, ma_device_info* pDeviceInfo) +{ + ma_assert(pContext != NULL); + + /* No exclusive mode with the PulseAudio backend. */ + if (shareMode == ma_share_mode_exclusive) { + return MA_SHARE_MODE_NOT_SUPPORTED; + } + + ma_result result = MA_SUCCESS; + + ma_context_get_device_info_callback_data__pulse callbackData; + callbackData.pDeviceInfo = pDeviceInfo; + callbackData.foundDevice = MA_FALSE; + + ma_pa_operation* pOP = NULL; + + ma_pa_mainloop* pMainLoop = ((ma_pa_mainloop_new_proc)pContext->pulse.pa_mainloop_new)(); + if (pMainLoop == NULL) { + return MA_FAILED_TO_INIT_BACKEND; + } + + ma_pa_mainloop_api* pAPI = ((ma_pa_mainloop_get_api_proc)pContext->pulse.pa_mainloop_get_api)(pMainLoop); + if (pAPI == NULL) { + ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); + return MA_FAILED_TO_INIT_BACKEND; + } + + ma_pa_context* pPulseContext = ((ma_pa_context_new_proc)pContext->pulse.pa_context_new)(pAPI, pContext->config.pulse.pApplicationName); + if (pPulseContext == NULL) { + ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); + return MA_FAILED_TO_INIT_BACKEND; + } + + int error = ((ma_pa_context_connect_proc)pContext->pulse.pa_context_connect)(pPulseContext, pContext->config.pulse.pServerName, 0, NULL); + if (error != MA_PA_OK) { + ((ma_pa_context_unref_proc)pContext->pulse.pa_context_unref)(pPulseContext); + ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); + return ma_result_from_pulse(error); + } + + while (((ma_pa_context_get_state_proc)pContext->pulse.pa_context_get_state)(pPulseContext) != MA_PA_CONTEXT_READY) { + error = ((ma_pa_mainloop_iterate_proc)pContext->pulse.pa_mainloop_iterate)(pMainLoop, 1, NULL); + if (error < 0) { + result = ma_result_from_pulse(error); + goto done; + } + } + + if (deviceType == ma_device_type_playback) { + pOP = ((ma_pa_context_get_sink_info_by_name_proc)pContext->pulse.pa_context_get_sink_info_by_name)(pPulseContext, pDeviceID->pulse, ma_context_get_device_info_sink_callback__pulse, &callbackData); + } else { + pOP = ((ma_pa_context_get_source_info_by_name_proc)pContext->pulse.pa_context_get_source_info_by_name)(pPulseContext, pDeviceID->pulse, ma_context_get_device_info_source_callback__pulse, &callbackData); + } + + if (pOP != NULL) { + ma_wait_for_operation__pulse(pContext, pMainLoop, pOP); + ((ma_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP); + } else { + result = MA_ERROR; + goto done; + } + + if (!callbackData.foundDevice) { + result = MA_NO_DEVICE; + goto done; + } + + +done: + ((ma_pa_context_disconnect_proc)pContext->pulse.pa_context_disconnect)(pPulseContext); + ((ma_pa_context_unref_proc)pContext->pulse.pa_context_unref)(pPulseContext); + ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); + return result; +} + + +void ma_pulse_device_state_callback(ma_pa_context* pPulseContext, void* pUserData) +{ + ma_device* pDevice = (ma_device*)pUserData; + ma_assert(pDevice != NULL); + + ma_context* pContext = pDevice->pContext; + ma_assert(pContext != NULL); + + pDevice->pulse.pulseContextState = ((ma_pa_context_get_state_proc)pContext->pulse.pa_context_get_state)(pPulseContext); +} + +void ma_device_sink_info_callback(ma_pa_context* pPulseContext, const ma_pa_sink_info* pInfo, int endOfList, void* pUserData) +{ + if (endOfList > 0) { + return; + } + + ma_pa_sink_info* pInfoOut = (ma_pa_sink_info*)pUserData; + ma_assert(pInfoOut != NULL); + + *pInfoOut = *pInfo; +} + +void ma_device_source_info_callback(ma_pa_context* pPulseContext, const ma_pa_source_info* pInfo, int endOfList, void* pUserData) +{ + if (endOfList > 0) { + return; + } + + ma_pa_source_info* pInfoOut = (ma_pa_source_info*)pUserData; + ma_assert(pInfoOut != NULL); + + *pInfoOut = *pInfo; +} + +void ma_device_sink_name_callback(ma_pa_context* pPulseContext, const ma_pa_sink_info* pInfo, int endOfList, void* pUserData) +{ + if (endOfList > 0) { + return; + } + + ma_device* pDevice = (ma_device*)pUserData; + ma_assert(pDevice != NULL); + + ma_strncpy_s(pDevice->playback.name, sizeof(pDevice->playback.name), pInfo->description, (size_t)-1); +} + +void ma_device_source_name_callback(ma_pa_context* pPulseContext, const ma_pa_source_info* pInfo, int endOfList, void* pUserData) +{ + if (endOfList > 0) { + return; + } + + ma_device* pDevice = (ma_device*)pUserData; + ma_assert(pDevice != NULL); + + ma_strncpy_s(pDevice->capture.name, sizeof(pDevice->capture.name), pInfo->description, (size_t)-1); +} + +void ma_device_uninit__pulse(ma_device* pDevice) +{ + ma_assert(pDevice != NULL); + + ma_context* pContext = pDevice->pContext; + ma_assert(pContext != NULL); + + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + ((ma_pa_stream_disconnect_proc)pContext->pulse.pa_stream_disconnect)((ma_pa_stream*)pDevice->pulse.pStreamCapture); + ((ma_pa_stream_unref_proc)pContext->pulse.pa_stream_unref)((ma_pa_stream*)pDevice->pulse.pStreamCapture); + } + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + ((ma_pa_stream_disconnect_proc)pContext->pulse.pa_stream_disconnect)((ma_pa_stream*)pDevice->pulse.pStreamPlayback); + ((ma_pa_stream_unref_proc)pContext->pulse.pa_stream_unref)((ma_pa_stream*)pDevice->pulse.pStreamPlayback); + } + + ((ma_pa_context_disconnect_proc)pContext->pulse.pa_context_disconnect)((ma_pa_context*)pDevice->pulse.pPulseContext); + ((ma_pa_context_unref_proc)pContext->pulse.pa_context_unref)((ma_pa_context*)pDevice->pulse.pPulseContext); + ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)((ma_pa_mainloop*)pDevice->pulse.pMainLoop); +} + +ma_pa_buffer_attr ma_device__pa_buffer_attr_new(ma_uint32 bufferSizeInFrames, ma_uint32 periods, const ma_pa_sample_spec* ss) +{ + ma_pa_buffer_attr attr; + attr.maxlength = bufferSizeInFrames * ma_get_bytes_per_sample(ma_format_from_pulse(ss->format)) * ss->channels; + attr.tlength = attr.maxlength / periods; + attr.prebuf = (ma_uint32)-1; + attr.minreq = attr.maxlength / periods; + attr.fragsize = attr.maxlength / periods; + + return attr; +} + +ma_pa_stream* ma_device__pa_stream_new__pulse(ma_device* pDevice, const char* pStreamName, const ma_pa_sample_spec* ss, const ma_pa_channel_map* cmap) +{ + static int g_StreamCounter = 0; + + char actualStreamName[256]; + if (pStreamName != NULL) { + ma_strncpy_s(actualStreamName, sizeof(actualStreamName), pStreamName, (size_t)-1); + } else { + ma_strcpy_s(actualStreamName, sizeof(actualStreamName), "miniaudio:"); + ma_itoa_s(g_StreamCounter, actualStreamName + 8, sizeof(actualStreamName)-8, 10); // 8 = strlen("miniaudio:") + } + g_StreamCounter += 1; + + return ((ma_pa_stream_new_proc)pDevice->pContext->pulse.pa_stream_new)((ma_pa_context*)pDevice->pulse.pPulseContext, actualStreamName, ss, cmap); +} + +ma_result ma_device_init__pulse(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice) +{ + (void)pContext; + + ma_assert(pDevice != NULL); + ma_zero_object(&pDevice->pulse); + + ma_result result = MA_SUCCESS; + int error = 0; + const char* devPlayback = NULL; + const char* devCapture = NULL; + + /* No exclusive mode with the PulseAudio backend. */ + if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pConfig->playback.shareMode == ma_share_mode_exclusive) || + ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pConfig->capture.shareMode == ma_share_mode_exclusive)) { + return MA_SHARE_MODE_NOT_SUPPORTED; + } + + if ((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pConfig->playback.pDeviceID != NULL) { + devPlayback = pConfig->playback.pDeviceID->pulse; + } + if ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pConfig->capture.pDeviceID != NULL) { + devCapture = pConfig->capture.pDeviceID->pulse; + } + + ma_uint32 bufferSizeInMilliseconds = pConfig->bufferSizeInMilliseconds; + if (bufferSizeInMilliseconds == 0) { + bufferSizeInMilliseconds = ma_calculate_buffer_size_in_milliseconds_from_frames(pConfig->bufferSizeInFrames, pConfig->sampleRate); + } + + ma_pa_sink_info sinkInfo; + ma_pa_source_info sourceInfo; + ma_pa_operation* pOP = NULL; + + ma_pa_sample_spec ss; + ma_pa_channel_map cmap; + ma_pa_buffer_attr attr; + + const ma_pa_sample_spec* pActualSS = NULL; + const ma_pa_channel_map* pActualCMap = NULL; + const ma_pa_buffer_attr* pActualAttr = NULL; + + + + pDevice->pulse.pMainLoop = ((ma_pa_mainloop_new_proc)pContext->pulse.pa_mainloop_new)(); + if (pDevice->pulse.pMainLoop == NULL) { + result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to create main loop for device.", MA_FAILED_TO_INIT_BACKEND); + goto on_error0; + } + + pDevice->pulse.pAPI = ((ma_pa_mainloop_get_api_proc)pContext->pulse.pa_mainloop_get_api)((ma_pa_mainloop*)pDevice->pulse.pMainLoop); + if (pDevice->pulse.pAPI == NULL) { + result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to retrieve PulseAudio main loop.", MA_FAILED_TO_INIT_BACKEND); + goto on_error1; + } + + pDevice->pulse.pPulseContext = ((ma_pa_context_new_proc)pContext->pulse.pa_context_new)((ma_pa_mainloop_api*)pDevice->pulse.pAPI, pContext->config.pulse.pApplicationName); + if (pDevice->pulse.pPulseContext == NULL) { + result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to create PulseAudio context for device.", MA_FAILED_TO_INIT_BACKEND); + goto on_error1; + } + + error = ((ma_pa_context_connect_proc)pContext->pulse.pa_context_connect)((ma_pa_context*)pDevice->pulse.pPulseContext, pContext->config.pulse.pServerName, (pContext->config.pulse.tryAutoSpawn) ? 0 : MA_PA_CONTEXT_NOAUTOSPAWN, NULL); + if (error != MA_PA_OK) { + result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to connect PulseAudio context.", ma_result_from_pulse(error)); + goto on_error2; + } + + + pDevice->pulse.pulseContextState = MA_PA_CONTEXT_UNCONNECTED; + ((ma_pa_context_set_state_callback_proc)pContext->pulse.pa_context_set_state_callback)((ma_pa_context*)pDevice->pulse.pPulseContext, ma_pulse_device_state_callback, pDevice); + + // Wait for PulseAudio to get itself ready before returning. + for (;;) { + if (pDevice->pulse.pulseContextState == MA_PA_CONTEXT_READY) { + break; + } else { + error = ((ma_pa_mainloop_iterate_proc)pContext->pulse.pa_mainloop_iterate)((ma_pa_mainloop*)pDevice->pulse.pMainLoop, 1, NULL); // 1 = block. + if (error < 0) { + result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] The PulseAudio main loop returned an error while connecting the PulseAudio context.", ma_result_from_pulse(error)); + goto on_error3; + } + continue; + } + + // An error may have occurred. + if (pDevice->pulse.pulseContextState == MA_PA_CONTEXT_FAILED || pDevice->pulse.pulseContextState == MA_PA_CONTEXT_TERMINATED) { + result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] An error occurred while connecting the PulseAudio context.", MA_ERROR); + goto on_error3; + } + + error = ((ma_pa_mainloop_iterate_proc)pContext->pulse.pa_mainloop_iterate)((ma_pa_mainloop*)pDevice->pulse.pMainLoop, 1, NULL); + if (error < 0) { + result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] The PulseAudio main loop returned an error while connecting the PulseAudio context.", ma_result_from_pulse(error)); + goto on_error3; + } + } + + if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) { + pOP = ((ma_pa_context_get_source_info_by_name_proc)pContext->pulse.pa_context_get_source_info_by_name)((ma_pa_context*)pDevice->pulse.pPulseContext, devCapture, ma_device_source_info_callback, &sourceInfo); + if (pOP != NULL) { + ma_device__wait_for_operation__pulse(pDevice, pOP); + ((ma_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP); + } else { + result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to retrieve source info for capture device.", ma_result_from_pulse(error)); + goto on_error3; + } + + ss = sourceInfo.sample_spec; + cmap = sourceInfo.channel_map; + + pDevice->capture.internalBufferSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(bufferSizeInMilliseconds, ss.rate); + pDevice->capture.internalPeriods = pConfig->periods; + + attr = ma_device__pa_buffer_attr_new(pDevice->capture.internalBufferSizeInFrames, pConfig->periods, &ss); + #ifdef MA_DEBUG_OUTPUT + printf("[PulseAudio] Capture attr: maxlength=%d, tlength=%d, prebuf=%d, minreq=%d, fragsize=%d; internalBufferSizeInFrames=%d\n", attr.maxlength, attr.tlength, attr.prebuf, attr.minreq, attr.fragsize, pDevice->capture.internalBufferSizeInFrames); + #endif + + pDevice->pulse.pStreamCapture = ma_device__pa_stream_new__pulse(pDevice, pConfig->pulse.pStreamNameCapture, &ss, &cmap); + if (pDevice->pulse.pStreamCapture == NULL) { + result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to create PulseAudio capture stream.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + goto on_error3; + } + + ma_pa_stream_flags_t streamFlags = MA_PA_STREAM_START_CORKED | MA_PA_STREAM_FIX_FORMAT | MA_PA_STREAM_FIX_RATE | MA_PA_STREAM_FIX_CHANNELS; + if (devCapture != NULL) { + streamFlags |= MA_PA_STREAM_DONT_MOVE; + } + + error = ((ma_pa_stream_connect_record_proc)pContext->pulse.pa_stream_connect_record)((ma_pa_stream*)pDevice->pulse.pStreamCapture, devCapture, &attr, streamFlags); + if (error != MA_PA_OK) { + result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to connect PulseAudio capture stream.", ma_result_from_pulse(error)); + goto on_error4; + } + + while (((ma_pa_stream_get_state_proc)pContext->pulse.pa_stream_get_state)((ma_pa_stream*)pDevice->pulse.pStreamCapture) != MA_PA_STREAM_READY) { + error = ((ma_pa_mainloop_iterate_proc)pContext->pulse.pa_mainloop_iterate)((ma_pa_mainloop*)pDevice->pulse.pMainLoop, 1, NULL); + if (error < 0) { + result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] The PulseAudio main loop returned an error while connecting the PulseAudio capture stream.", ma_result_from_pulse(error)); + goto on_error5; + } + } + + /* Internal format. */ + pActualSS = ((ma_pa_stream_get_sample_spec_proc)pContext->pulse.pa_stream_get_sample_spec)((ma_pa_stream*)pDevice->pulse.pStreamCapture); + if (pActualSS != NULL) { + /* If anything has changed between the requested and the actual sample spec, we need to update the buffer. */ + if (ss.format != pActualSS->format || ss.channels != pActualSS->channels || ss.rate != pActualSS->rate) { + attr = ma_device__pa_buffer_attr_new(pDevice->capture.internalBufferSizeInFrames, pConfig->periods, pActualSS); + + pOP = ((ma_pa_stream_set_buffer_attr_proc)pContext->pulse.pa_stream_set_buffer_attr)((ma_pa_stream*)pDevice->pulse.pStreamCapture, &attr, NULL, NULL); + if (pOP != NULL) { + ma_device__wait_for_operation__pulse(pDevice, pOP); + ((ma_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP); + } + } + + ss = *pActualSS; + } + + pDevice->capture.internalFormat = ma_format_from_pulse(ss.format); + pDevice->capture.internalChannels = ss.channels; + pDevice->capture.internalSampleRate = ss.rate; + + /* Internal channel map. */ + pActualCMap = ((ma_pa_stream_get_channel_map_proc)pContext->pulse.pa_stream_get_channel_map)((ma_pa_stream*)pDevice->pulse.pStreamCapture); + if (pActualCMap != NULL) { + cmap = *pActualCMap; + } + for (ma_uint32 iChannel = 0; iChannel < pDevice->capture.internalChannels; ++iChannel) { + pDevice->capture.internalChannelMap[iChannel] = ma_channel_position_from_pulse(cmap.map[iChannel]); + } + + /* Buffer. */ + pActualAttr = ((ma_pa_stream_get_buffer_attr_proc)pContext->pulse.pa_stream_get_buffer_attr)((ma_pa_stream*)pDevice->pulse.pStreamCapture); + if (pActualAttr != NULL) { + attr = *pActualAttr; + } + pDevice->capture.internalBufferSizeInFrames = attr.maxlength / (ma_get_bytes_per_sample(pDevice->capture.internalFormat) * pDevice->capture.internalChannels); + pDevice->capture.internalPeriods = attr.maxlength / attr.fragsize; + #ifdef MA_DEBUG_OUTPUT + printf("[PulseAudio] Capture actual attr: maxlength=%d, tlength=%d, prebuf=%d, minreq=%d, fragsize=%d; internalBufferSizeInFrames=%d\n", attr.maxlength, attr.tlength, attr.prebuf, attr.minreq, attr.fragsize, pDevice->capture.internalBufferSizeInFrames); + #endif + + /* Name. */ + devCapture = ((ma_pa_stream_get_device_name_proc)pContext->pulse.pa_stream_get_device_name)((ma_pa_stream*)pDevice->pulse.pStreamCapture); + if (devCapture != NULL) { + ma_pa_operation* pOP = ((ma_pa_context_get_source_info_by_name_proc)pContext->pulse.pa_context_get_source_info_by_name)((ma_pa_context*)pDevice->pulse.pPulseContext, devCapture, ma_device_source_name_callback, pDevice); + if (pOP != NULL) { + ma_device__wait_for_operation__pulse(pDevice, pOP); + ((ma_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP); + } + } + } + + if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) { + pOP = ((ma_pa_context_get_sink_info_by_name_proc)pContext->pulse.pa_context_get_sink_info_by_name)((ma_pa_context*)pDevice->pulse.pPulseContext, devPlayback, ma_device_sink_info_callback, &sinkInfo); + if (pOP != NULL) { + ma_device__wait_for_operation__pulse(pDevice, pOP); + ((ma_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP); + } else { + result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to retrieve sink info for playback device.", ma_result_from_pulse(error)); + goto on_error3; + } + + ss = sinkInfo.sample_spec; + cmap = sinkInfo.channel_map; + + pDevice->playback.internalBufferSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(bufferSizeInMilliseconds, ss.rate); + pDevice->playback.internalPeriods = pConfig->periods; + + attr = ma_device__pa_buffer_attr_new(pDevice->playback.internalBufferSizeInFrames, pConfig->periods, &ss); + #ifdef MA_DEBUG_OUTPUT + printf("[PulseAudio] Playback attr: maxlength=%d, tlength=%d, prebuf=%d, minreq=%d, fragsize=%d; internalBufferSizeInFrames=%d\n", attr.maxlength, attr.tlength, attr.prebuf, attr.minreq, attr.fragsize, pDevice->playback.internalBufferSizeInFrames); + #endif + + pDevice->pulse.pStreamPlayback = ma_device__pa_stream_new__pulse(pDevice, pConfig->pulse.pStreamNamePlayback, &ss, &cmap); + if (pDevice->pulse.pStreamPlayback == NULL) { + result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to create PulseAudio playback stream.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + goto on_error3; + } + + ma_pa_stream_flags_t streamFlags = MA_PA_STREAM_START_CORKED | MA_PA_STREAM_FIX_FORMAT | MA_PA_STREAM_FIX_RATE | MA_PA_STREAM_FIX_CHANNELS; + if (devPlayback != NULL) { + streamFlags |= MA_PA_STREAM_DONT_MOVE; + } + + error = ((ma_pa_stream_connect_playback_proc)pContext->pulse.pa_stream_connect_playback)((ma_pa_stream*)pDevice->pulse.pStreamPlayback, devPlayback, &attr, streamFlags, NULL, NULL); + if (error != MA_PA_OK) { + result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to connect PulseAudio playback stream.", ma_result_from_pulse(error)); + goto on_error6; + } + + while (((ma_pa_stream_get_state_proc)pContext->pulse.pa_stream_get_state)((ma_pa_stream*)pDevice->pulse.pStreamPlayback) != MA_PA_STREAM_READY) { + error = ((ma_pa_mainloop_iterate_proc)pContext->pulse.pa_mainloop_iterate)((ma_pa_mainloop*)pDevice->pulse.pMainLoop, 1, NULL); + if (error < 0) { + result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] The PulseAudio main loop returned an error while connecting the PulseAudio playback stream.", ma_result_from_pulse(error)); + goto on_error7; + } + } + + /* Internal format. */ + pActualSS = ((ma_pa_stream_get_sample_spec_proc)pContext->pulse.pa_stream_get_sample_spec)((ma_pa_stream*)pDevice->pulse.pStreamPlayback); + if (pActualSS != NULL) { + /* If anything has changed between the requested and the actual sample spec, we need to update the buffer. */ + if (ss.format != pActualSS->format || ss.channels != pActualSS->channels || ss.rate != pActualSS->rate) { + attr = ma_device__pa_buffer_attr_new(pDevice->playback.internalBufferSizeInFrames, pConfig->periods, pActualSS); + + pOP = ((ma_pa_stream_set_buffer_attr_proc)pContext->pulse.pa_stream_set_buffer_attr)((ma_pa_stream*)pDevice->pulse.pStreamPlayback, &attr, NULL, NULL); + if (pOP != NULL) { + ma_device__wait_for_operation__pulse(pDevice, pOP); + ((ma_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP); + } + } + + ss = *pActualSS; + } + + pDevice->playback.internalFormat = ma_format_from_pulse(ss.format); + pDevice->playback.internalChannels = ss.channels; + pDevice->playback.internalSampleRate = ss.rate; + + /* Internal channel map. */ + pActualCMap = ((ma_pa_stream_get_channel_map_proc)pContext->pulse.pa_stream_get_channel_map)((ma_pa_stream*)pDevice->pulse.pStreamPlayback); + if (pActualCMap != NULL) { + cmap = *pActualCMap; + } + for (ma_uint32 iChannel = 0; iChannel < pDevice->playback.internalChannels; ++iChannel) { + pDevice->playback.internalChannelMap[iChannel] = ma_channel_position_from_pulse(cmap.map[iChannel]); + } + + /* Buffer. */ + pActualAttr = ((ma_pa_stream_get_buffer_attr_proc)pContext->pulse.pa_stream_get_buffer_attr)((ma_pa_stream*)pDevice->pulse.pStreamPlayback); + if (pActualAttr != NULL) { + attr = *pActualAttr; + } + pDevice->playback.internalBufferSizeInFrames = attr.maxlength / (ma_get_bytes_per_sample(pDevice->playback.internalFormat) * pDevice->playback.internalChannels); + pDevice->playback.internalPeriods = /*pConfig->periods;*/attr.maxlength / attr.tlength; + #ifdef MA_DEBUG_OUTPUT + printf("[PulseAudio] Playback actual attr: maxlength=%d, tlength=%d, prebuf=%d, minreq=%d, fragsize=%d; internalBufferSizeInFrames=%d\n", attr.maxlength, attr.tlength, attr.prebuf, attr.minreq, attr.fragsize, pDevice->playback.internalBufferSizeInFrames); + #endif + + /* Name. */ + devPlayback = ((ma_pa_stream_get_device_name_proc)pContext->pulse.pa_stream_get_device_name)((ma_pa_stream*)pDevice->pulse.pStreamPlayback); + if (devPlayback != NULL) { + ma_pa_operation* pOP = ((ma_pa_context_get_sink_info_by_name_proc)pContext->pulse.pa_context_get_sink_info_by_name)((ma_pa_context*)pDevice->pulse.pPulseContext, devPlayback, ma_device_sink_name_callback, pDevice); + if (pOP != NULL) { + ma_device__wait_for_operation__pulse(pDevice, pOP); + ((ma_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP); + } + } + } + + return MA_SUCCESS; + + +on_error7: + if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) { + ((ma_pa_stream_disconnect_proc)pContext->pulse.pa_stream_disconnect)((ma_pa_stream*)pDevice->pulse.pStreamPlayback); + } +on_error6: + if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) { + ((ma_pa_stream_unref_proc)pContext->pulse.pa_stream_unref)((ma_pa_stream*)pDevice->pulse.pStreamPlayback); + } +on_error5: + if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) { + ((ma_pa_stream_disconnect_proc)pContext->pulse.pa_stream_disconnect)((ma_pa_stream*)pDevice->pulse.pStreamCapture); + } +on_error4: + if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) { + ((ma_pa_stream_unref_proc)pContext->pulse.pa_stream_unref)((ma_pa_stream*)pDevice->pulse.pStreamCapture); + } +on_error3: ((ma_pa_context_disconnect_proc)pContext->pulse.pa_context_disconnect)((ma_pa_context*)pDevice->pulse.pPulseContext); +on_error2: ((ma_pa_context_unref_proc)pContext->pulse.pa_context_unref)((ma_pa_context*)pDevice->pulse.pPulseContext); +on_error1: ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)((ma_pa_mainloop*)pDevice->pulse.pMainLoop); +on_error0: + return result; +} + + +void ma_pulse_operation_complete_callback(ma_pa_stream* pStream, int success, void* pUserData) +{ + ma_bool32* pIsSuccessful = (ma_bool32*)pUserData; + ma_assert(pIsSuccessful != NULL); + + *pIsSuccessful = (ma_bool32)success; +} + +ma_result ma_device__cork_stream__pulse(ma_device* pDevice, ma_device_type deviceType, int cork) +{ + ma_context* pContext = pDevice->pContext; + ma_assert(pContext != NULL); + + /* This should not be called with a duplex device type. */ + if (deviceType == ma_device_type_duplex) { + return MA_INVALID_ARGS; + } + + ma_bool32 wasSuccessful = MA_FALSE; + + ma_pa_stream* pStream = (ma_pa_stream*)((deviceType == ma_device_type_capture) ? pDevice->pulse.pStreamCapture : pDevice->pulse.pStreamPlayback); + ma_assert(pStream != NULL); + + ma_pa_operation* pOP = ((ma_pa_stream_cork_proc)pContext->pulse.pa_stream_cork)(pStream, cork, ma_pulse_operation_complete_callback, &wasSuccessful); + if (pOP == NULL) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to cork PulseAudio stream.", (cork == 0) ? MA_FAILED_TO_START_BACKEND_DEVICE : MA_FAILED_TO_STOP_BACKEND_DEVICE); + } + + ma_result result = ma_device__wait_for_operation__pulse(pDevice, pOP); + ((ma_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP); + + if (result != MA_SUCCESS) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] An error occurred while waiting for the PulseAudio stream to cork.", result); + } + + if (!wasSuccessful) { + if (cork) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to stop PulseAudio stream.", MA_FAILED_TO_STOP_BACKEND_DEVICE); + } else { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to start PulseAudio stream.", MA_FAILED_TO_START_BACKEND_DEVICE); + } + } + + return MA_SUCCESS; +} + +ma_result ma_device_stop__pulse(ma_device* pDevice) +{ + ma_result result; + ma_bool32 wasSuccessful; + ma_pa_operation* pOP; + + ma_assert(pDevice != NULL); + + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + result = ma_device__cork_stream__pulse(pDevice, ma_device_type_capture, 1); + if (result != MA_SUCCESS) { + return result; + } + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + /* The stream needs to be drained if it's a playback device. */ + pOP = ((ma_pa_stream_drain_proc)pDevice->pContext->pulse.pa_stream_drain)((ma_pa_stream*)pDevice->pulse.pStreamPlayback, ma_pulse_operation_complete_callback, &wasSuccessful); + if (pOP != NULL) { + ma_device__wait_for_operation__pulse(pDevice, pOP); + ((ma_pa_operation_unref_proc)pDevice->pContext->pulse.pa_operation_unref)(pOP); + } + + result = ma_device__cork_stream__pulse(pDevice, ma_device_type_playback, 1); + if (result != MA_SUCCESS) { + return result; + } + } + + return MA_SUCCESS; +} + +ma_result ma_device_write__pulse(ma_device* pDevice, const void* pPCMFrames, ma_uint32 frameCount) +{ + ma_assert(pDevice != NULL); + ma_assert(pPCMFrames != NULL); + ma_assert(frameCount > 0); + + /* The stream needs to be uncorked first. */ + if (((ma_pa_stream_is_corked_proc)pDevice->pContext->pulse.pa_stream_is_corked)((ma_pa_stream*)pDevice->pulse.pStreamPlayback)) { + ma_result result = ma_device__cork_stream__pulse(pDevice, ma_device_type_playback, 0); + if (result != MA_SUCCESS) { + return result; + } + } + + ma_uint32 totalFramesWritten = 0; + while (totalFramesWritten < frameCount) { + //printf("TRACE: Outer loop.\n"); + + /* Place the data into the mapped buffer if we have one. */ + if (pDevice->pulse.pMappedBufferPlayback != NULL && pDevice->pulse.mappedBufferFramesRemainingPlayback > 0) { + //printf("TRACE: Copying data.\n"); + + ma_uint32 bpf = ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels); + ma_uint32 mappedBufferFramesConsumed = pDevice->pulse.mappedBufferFramesCapacityPlayback - pDevice->pulse.mappedBufferFramesRemainingPlayback; + + void* pDst = (ma_uint8*)pDevice->pulse.pMappedBufferPlayback + (mappedBufferFramesConsumed * bpf); + const void* pSrc = (const ma_uint8*)pPCMFrames + (totalFramesWritten * bpf); + ma_uint32 framesToCopy = ma_min(pDevice->pulse.mappedBufferFramesRemainingPlayback, (frameCount - totalFramesWritten)); + ma_copy_memory(pDst, pSrc, framesToCopy * bpf); + + pDevice->pulse.mappedBufferFramesRemainingPlayback -= framesToCopy; + totalFramesWritten += framesToCopy; + } + + /* + Getting here means we've run out of data in the currently mapped chunk. We need to write this to the device and then try + mapping another chunk. If this fails we need to wait for space to become available. + */ + if (pDevice->pulse.mappedBufferFramesCapacityPlayback > 0 && pDevice->pulse.mappedBufferFramesRemainingPlayback == 0) { + size_t nbytes = pDevice->pulse.mappedBufferFramesCapacityPlayback * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels); + //printf("TRACE: Submitting data. %d\n", nbytes); + + int error = ((ma_pa_stream_write_proc)pDevice->pContext->pulse.pa_stream_write)((ma_pa_stream*)pDevice->pulse.pStreamPlayback, pDevice->pulse.pMappedBufferPlayback, nbytes, NULL, 0, MA_PA_SEEK_RELATIVE); + if (error < 0) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to write data to the PulseAudio stream.", ma_result_from_pulse(error)); + } + + pDevice->pulse.pMappedBufferPlayback = NULL; + pDevice->pulse.mappedBufferFramesRemainingPlayback = 0; + pDevice->pulse.mappedBufferFramesCapacityPlayback = 0; + } + + ma_assert(totalFramesWritten <= frameCount); + if (totalFramesWritten == frameCount) { + break; + } + + /* Getting here means we need to map a new buffer. If we don't have enough space we need to wait for more. */ + for (;;) { + //printf("TRACE: Inner loop.\n"); + + /* If the device has been corked, don't try to continue. */ + if (((ma_pa_stream_is_corked_proc)pDevice->pContext->pulse.pa_stream_is_corked)((ma_pa_stream*)pDevice->pulse.pStreamPlayback)) { + break; + } + + size_t writableSizeInBytes = ((ma_pa_stream_writable_size_proc)pDevice->pContext->pulse.pa_stream_writable_size)((ma_pa_stream*)pDevice->pulse.pStreamPlayback); + if (writableSizeInBytes != (size_t)-1) { + size_t periodSizeInBytes = (pDevice->playback.internalBufferSizeInFrames / pDevice->playback.internalPeriods) * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels); + if (writableSizeInBytes >= periodSizeInBytes) { + //printf("TRACE: Data available.\n"); + + /* Data is avaialable. */ + size_t bytesToMap = periodSizeInBytes; + int error = ((ma_pa_stream_begin_write_proc)pDevice->pContext->pulse.pa_stream_begin_write)((ma_pa_stream*)pDevice->pulse.pStreamPlayback, &pDevice->pulse.pMappedBufferPlayback, &bytesToMap); + if (error < 0) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to map write buffer.", ma_result_from_pulse(error)); + } + + pDevice->pulse.mappedBufferFramesCapacityPlayback = bytesToMap / ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels); + pDevice->pulse.mappedBufferFramesRemainingPlayback = pDevice->pulse.mappedBufferFramesCapacityPlayback; + + break; + } else { + /* No data available. Need to wait for more. */ + //printf("TRACE: Playback: pa_mainloop_iterate(). writableSizeInBytes=%d, periodSizeInBytes=%d\n", writableSizeInBytes, periodSizeInBytes); + + int error = ((ma_pa_mainloop_iterate_proc)pDevice->pContext->pulse.pa_mainloop_iterate)((ma_pa_mainloop*)pDevice->pulse.pMainLoop, 1, NULL); + if (error < 0) { + return ma_result_from_pulse(error); + } + + continue; + } + } else { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to query the stream's writable size.", MA_ERROR); + } + } + } + + return MA_SUCCESS; +} + +ma_result ma_device_read__pulse(ma_device* pDevice, void* pPCMFrames, ma_uint32 frameCount) +{ + ma_assert(pDevice != NULL); + ma_assert(pPCMFrames != NULL); + ma_assert(frameCount > 0); + + /* The stream needs to be uncorked first. */ + if (((ma_pa_stream_is_corked_proc)pDevice->pContext->pulse.pa_stream_is_corked)((ma_pa_stream*)pDevice->pulse.pStreamCapture)) { + ma_result result = ma_device__cork_stream__pulse(pDevice, ma_device_type_capture, 0); + if (result != MA_SUCCESS) { + return result; + } + } + + ma_uint32 totalFramesRead = 0; + while (totalFramesRead < frameCount) { + /* If a buffer is mapped we need to write to that first. Once it's consumed we reset the event and unmap it. */ + if (pDevice->pulse.pMappedBufferCapture != NULL && pDevice->pulse.mappedBufferFramesRemainingCapture > 0) { + ma_uint32 bpf = ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels); + ma_uint32 mappedBufferFramesConsumed = pDevice->pulse.mappedBufferFramesCapacityCapture - pDevice->pulse.mappedBufferFramesRemainingCapture; + + ma_uint32 framesToCopy = ma_min(pDevice->pulse.mappedBufferFramesRemainingCapture, (frameCount - totalFramesRead)); + void* pDst = (ma_uint8*)pPCMFrames + (totalFramesRead * bpf); + + /* + This little bit of logic here is specifically for PulseAudio and it's hole management. The buffer pointer will be set to NULL + when the current fragment is a hole. For a hole we just output silence. + */ + if (pDevice->pulse.pMappedBufferCapture != NULL) { + const void* pSrc = (const ma_uint8*)pDevice->pulse.pMappedBufferCapture + (mappedBufferFramesConsumed * bpf); + ma_copy_memory(pDst, pSrc, framesToCopy * bpf); + } else { + ma_zero_memory(pDst, framesToCopy * bpf); + } + + pDevice->pulse.mappedBufferFramesRemainingCapture -= framesToCopy; + totalFramesRead += framesToCopy; + } + + /* + Getting here means we've run out of data in the currently mapped chunk. We need to drop this from the device and then try + mapping another chunk. If this fails we need to wait for data to become available. + */ + if (pDevice->pulse.mappedBufferFramesCapacityCapture > 0 && pDevice->pulse.mappedBufferFramesRemainingCapture == 0) { + //printf("TRACE: Dropping fragment. %d\n", nbytes); + + int error = ((ma_pa_stream_drop_proc)pDevice->pContext->pulse.pa_stream_drop)((ma_pa_stream*)pDevice->pulse.pStreamCapture); + if (error != 0) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to drop fragment.", ma_result_from_pulse(error)); + } + + pDevice->pulse.pMappedBufferCapture = NULL; + pDevice->pulse.mappedBufferFramesRemainingCapture = 0; + pDevice->pulse.mappedBufferFramesCapacityCapture = 0; + } + + ma_assert(totalFramesRead <= frameCount); + if (totalFramesRead == frameCount) { + break; + } + + /* Getting here means we need to map a new buffer. If we don't have enough data we wait for more. */ + for (;;) { + //printf("TRACE: Inner loop.\n"); + + /* If the device has been corked, don't try to continue. */ + if (((ma_pa_stream_is_corked_proc)pDevice->pContext->pulse.pa_stream_is_corked)((ma_pa_stream*)pDevice->pulse.pStreamCapture)) { + break; + } + + size_t readableSizeInBytes = ((ma_pa_stream_readable_size_proc)pDevice->pContext->pulse.pa_stream_readable_size)((ma_pa_stream*)pDevice->pulse.pStreamCapture); + if (readableSizeInBytes != (size_t)-1) { + size_t periodSizeInBytes = (pDevice->capture.internalBufferSizeInFrames / pDevice->capture.internalPeriods) * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels); + if (readableSizeInBytes >= periodSizeInBytes) { + /* Data is avaialable. */ + size_t bytesMapped = (size_t)-1; + int error = ((ma_pa_stream_peek_proc)pDevice->pContext->pulse.pa_stream_peek)((ma_pa_stream*)pDevice->pulse.pStreamCapture, &pDevice->pulse.pMappedBufferCapture, &bytesMapped); + if (error < 0) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to peek capture buffer.", ma_result_from_pulse(error)); + } + + //printf("TRACE: Data available: bytesMapped=%d, readableSizeInBytes=%d, periodSizeInBytes=%d.\n", bytesMapped, readableSizeInBytes, periodSizeInBytes); + + if (pDevice->pulse.pMappedBufferCapture == NULL && bytesMapped == 0) { + /* Nothing available. This shouldn't happen because we checked earlier with pa_stream_readable_size(). I'm going to throw an error in this case. */ + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Nothing available after peeking capture buffer.", MA_ERROR); + } + + pDevice->pulse.mappedBufferFramesCapacityCapture = bytesMapped / ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels); + pDevice->pulse.mappedBufferFramesRemainingCapture = pDevice->pulse.mappedBufferFramesCapacityCapture; + + break; + } else { + /* No data available. Need to wait for more. */ + //printf("TRACE: Capture: pa_mainloop_iterate(). readableSizeInBytes=%d, periodSizeInBytes=%d\n", readableSizeInBytes, periodSizeInBytes); + + int error = ((ma_pa_mainloop_iterate_proc)pDevice->pContext->pulse.pa_mainloop_iterate)((ma_pa_mainloop*)pDevice->pulse.pMainLoop, 1, NULL); + if (error < 0) { + return ma_result_from_pulse(error); + } + + continue; + } + } else { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to query the stream's readable size.", MA_ERROR); + } + } + } + + return MA_SUCCESS; +} + + +ma_result ma_context_uninit__pulse(ma_context* pContext) +{ + ma_assert(pContext != NULL); + ma_assert(pContext->backend == ma_backend_pulseaudio); + +#ifndef MA_NO_RUNTIME_LINKING + ma_dlclose(pContext->pulse.pulseSO); +#endif + + return MA_SUCCESS; +} + +ma_result ma_context_init__pulse(ma_context* pContext) +{ + ma_assert(pContext != NULL); + +#ifndef MA_NO_RUNTIME_LINKING + // libpulse.so + const char* libpulseNames[] = { + "libpulse.so", + "libpulse.so.0" + }; + + for (size_t i = 0; i < ma_countof(libpulseNames); ++i) { + pContext->pulse.pulseSO = ma_dlopen(libpulseNames[i]); + if (pContext->pulse.pulseSO != NULL) { + break; + } + } + + if (pContext->pulse.pulseSO == NULL) { + return MA_NO_BACKEND; + } + + pContext->pulse.pa_mainloop_new = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_mainloop_new"); + pContext->pulse.pa_mainloop_free = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_mainloop_free"); + pContext->pulse.pa_mainloop_get_api = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_mainloop_get_api"); + pContext->pulse.pa_mainloop_iterate = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_mainloop_iterate"); + pContext->pulse.pa_mainloop_wakeup = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_mainloop_wakeup"); + pContext->pulse.pa_context_new = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_context_new"); + pContext->pulse.pa_context_unref = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_context_unref"); + pContext->pulse.pa_context_connect = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_context_connect"); + pContext->pulse.pa_context_disconnect = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_context_disconnect"); + pContext->pulse.pa_context_set_state_callback = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_context_set_state_callback"); + pContext->pulse.pa_context_get_state = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_context_get_state"); + pContext->pulse.pa_context_get_sink_info_list = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_context_get_sink_info_list"); + pContext->pulse.pa_context_get_source_info_list = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_context_get_source_info_list"); + pContext->pulse.pa_context_get_sink_info_by_name = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_context_get_sink_info_by_name"); + pContext->pulse.pa_context_get_source_info_by_name = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_context_get_source_info_by_name"); + pContext->pulse.pa_operation_unref = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_operation_unref"); + pContext->pulse.pa_operation_get_state = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_operation_get_state"); + pContext->pulse.pa_channel_map_init_extend = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_channel_map_init_extend"); + pContext->pulse.pa_channel_map_valid = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_channel_map_valid"); + pContext->pulse.pa_channel_map_compatible = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_channel_map_compatible"); + pContext->pulse.pa_stream_new = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_stream_new"); + pContext->pulse.pa_stream_unref = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_stream_unref"); + pContext->pulse.pa_stream_connect_playback = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_stream_connect_playback"); + pContext->pulse.pa_stream_connect_record = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_stream_connect_record"); + pContext->pulse.pa_stream_disconnect = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_stream_disconnect"); + pContext->pulse.pa_stream_get_state = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_stream_get_state"); + pContext->pulse.pa_stream_get_sample_spec = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_stream_get_sample_spec"); + pContext->pulse.pa_stream_get_channel_map = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_stream_get_channel_map"); + pContext->pulse.pa_stream_get_buffer_attr = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_stream_get_buffer_attr"); + pContext->pulse.pa_stream_set_buffer_attr = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_stream_set_buffer_attr"); + pContext->pulse.pa_stream_get_device_name = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_stream_get_device_name"); + pContext->pulse.pa_stream_set_write_callback = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_stream_set_write_callback"); + pContext->pulse.pa_stream_set_read_callback = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_stream_set_read_callback"); + pContext->pulse.pa_stream_flush = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_stream_flush"); + pContext->pulse.pa_stream_drain = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_stream_drain"); + pContext->pulse.pa_stream_is_corked = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_stream_is_corked"); + pContext->pulse.pa_stream_cork = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_stream_cork"); + pContext->pulse.pa_stream_trigger = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_stream_trigger"); + pContext->pulse.pa_stream_begin_write = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_stream_begin_write"); + pContext->pulse.pa_stream_write = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_stream_write"); + pContext->pulse.pa_stream_peek = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_stream_peek"); + pContext->pulse.pa_stream_drop = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_stream_drop"); + pContext->pulse.pa_stream_writable_size = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_stream_writable_size"); + pContext->pulse.pa_stream_readable_size = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_stream_readable_size"); +#else + // This strange assignment system is just for type safety. + ma_pa_mainloop_new_proc _pa_mainloop_new = pa_mainloop_new; + ma_pa_mainloop_free_proc _pa_mainloop_free = pa_mainloop_free; + ma_pa_mainloop_get_api_proc _pa_mainloop_get_api = pa_mainloop_get_api; + ma_pa_mainloop_iterate_proc _pa_mainloop_iterate = pa_mainloop_iterate; + ma_pa_mainloop_wakeup_proc _pa_mainloop_wakeup = pa_mainloop_wakeup; + ma_pa_context_new_proc _pa_context_new = pa_context_new; + ma_pa_context_unref_proc _pa_context_unref = pa_context_unref; + ma_pa_context_connect_proc _pa_context_connect = pa_context_connect; + ma_pa_context_disconnect_proc _pa_context_disconnect = pa_context_disconnect; + ma_pa_context_set_state_callback_proc _pa_context_set_state_callback = pa_context_set_state_callback; + ma_pa_context_get_state_proc _pa_context_get_state = pa_context_get_state; + ma_pa_context_get_sink_info_list_proc _pa_context_get_sink_info_list = pa_context_get_sink_info_list; + ma_pa_context_get_source_info_list_proc _pa_context_get_source_info_list = pa_context_get_source_info_list; + ma_pa_context_get_sink_info_by_name_proc _pa_context_get_sink_info_by_name = pa_context_get_sink_info_by_name; + ma_pa_context_get_source_info_by_name_proc _pa_context_get_source_info_by_name= pa_context_get_source_info_by_name; + ma_pa_operation_unref_proc _pa_operation_unref = pa_operation_unref; + ma_pa_operation_get_state_proc _pa_operation_get_state = pa_operation_get_state; + ma_pa_channel_map_init_extend_proc _pa_channel_map_init_extend = pa_channel_map_init_extend; + ma_pa_channel_map_valid_proc _pa_channel_map_valid = pa_channel_map_valid; + ma_pa_channel_map_compatible_proc _pa_channel_map_compatible = pa_channel_map_compatible; + ma_pa_stream_new_proc _pa_stream_new = pa_stream_new; + ma_pa_stream_unref_proc _pa_stream_unref = pa_stream_unref; + ma_pa_stream_connect_playback_proc _pa_stream_connect_playback = pa_stream_connect_playback; + ma_pa_stream_connect_record_proc _pa_stream_connect_record = pa_stream_connect_record; + ma_pa_stream_disconnect_proc _pa_stream_disconnect = pa_stream_disconnect; + ma_pa_stream_get_state_proc _pa_stream_get_state = pa_stream_get_state; + ma_pa_stream_get_sample_spec_proc _pa_stream_get_sample_spec = pa_stream_get_sample_spec; + ma_pa_stream_get_channel_map_proc _pa_stream_get_channel_map = pa_stream_get_channel_map; + ma_pa_stream_get_buffer_attr_proc _pa_stream_get_buffer_attr = pa_stream_get_buffer_attr; + ma_pa_stream_set_buffer_attr_proc _pa_stream_set_buffer_attr = pa_stream_set_buffer_attr; + ma_pa_stream_get_device_name_proc _pa_stream_get_device_name = pa_stream_get_device_name; + ma_pa_stream_set_write_callback_proc _pa_stream_set_write_callback = pa_stream_set_write_callback; + ma_pa_stream_set_read_callback_proc _pa_stream_set_read_callback = pa_stream_set_read_callback; + ma_pa_stream_flush_proc _pa_stream_flush = pa_stream_flush; + ma_pa_stream_drain_proc _pa_stream_drain = pa_stream_drain; + ma_pa_stream_ic_corked_proc _pa_stream_is_corked = pa_stream_is_corked; + ma_pa_stream_cork_proc _pa_stream_cork = pa_stream_cork; + ma_pa_stream_trigger_proc _pa_stream_trigger = pa_stream_trigger; + ma_pa_stream_begin_write_proc _pa_stream_begin_write = pa_stream_begin_write; + ma_pa_stream_write_proc _pa_stream_write = pa_stream_write; + ma_pa_stream_peek_proc _pa_stream_peek = pa_stream_peek; + ma_pa_stream_drop_proc _pa_stream_drop = pa_stream_drop; + ma_pa_stream_writable_size_proc _pa_stream_writable_size = pa_stream_writable_size; + ma_pa_stream_readable_size_proc _pa_stream_readable_size = pa_stream_readable_size; + + pContext->pulse.pa_mainloop_new = (ma_proc)_pa_mainloop_new; + pContext->pulse.pa_mainloop_free = (ma_proc)_pa_mainloop_free; + pContext->pulse.pa_mainloop_get_api = (ma_proc)_pa_mainloop_get_api; + pContext->pulse.pa_mainloop_iterate = (ma_proc)_pa_mainloop_iterate; + pContext->pulse.pa_mainloop_wakeup = (ma_proc)_pa_mainloop_wakeup; + pContext->pulse.pa_context_new = (ma_proc)_pa_context_new; + pContext->pulse.pa_context_unref = (ma_proc)_pa_context_unref; + pContext->pulse.pa_context_connect = (ma_proc)_pa_context_connect; + pContext->pulse.pa_context_disconnect = (ma_proc)_pa_context_disconnect; + pContext->pulse.pa_context_set_state_callback = (ma_proc)_pa_context_set_state_callback; + pContext->pulse.pa_context_get_state = (ma_proc)_pa_context_get_state; + pContext->pulse.pa_context_get_sink_info_list = (ma_proc)_pa_context_get_sink_info_list; + pContext->pulse.pa_context_get_source_info_list = (ma_proc)_pa_context_get_source_info_list; + pContext->pulse.pa_context_get_sink_info_by_name = (ma_proc)_pa_context_get_sink_info_by_name; + pContext->pulse.pa_context_get_source_info_by_name = (ma_proc)_pa_context_get_source_info_by_name; + pContext->pulse.pa_operation_unref = (ma_proc)_pa_operation_unref; + pContext->pulse.pa_operation_get_state = (ma_proc)_pa_operation_get_state; + pContext->pulse.pa_channel_map_init_extend = (ma_proc)_pa_channel_map_init_extend; + pContext->pulse.pa_channel_map_valid = (ma_proc)_pa_channel_map_valid; + pContext->pulse.pa_channel_map_compatible = (ma_proc)_pa_channel_map_compatible; + pContext->pulse.pa_stream_new = (ma_proc)_pa_stream_new; + pContext->pulse.pa_stream_unref = (ma_proc)_pa_stream_unref; + pContext->pulse.pa_stream_connect_playback = (ma_proc)_pa_stream_connect_playback; + pContext->pulse.pa_stream_connect_record = (ma_proc)_pa_stream_connect_record; + pContext->pulse.pa_stream_disconnect = (ma_proc)_pa_stream_disconnect; + pContext->pulse.pa_stream_get_state = (ma_proc)_pa_stream_get_state; + pContext->pulse.pa_stream_get_sample_spec = (ma_proc)_pa_stream_get_sample_spec; + pContext->pulse.pa_stream_get_channel_map = (ma_proc)_pa_stream_get_channel_map; + pContext->pulse.pa_stream_get_buffer_attr = (ma_proc)_pa_stream_get_buffer_attr; + pContext->pulse.pa_stream_set_buffer_attr = (ma_proc)_pa_stream_set_buffer_attr; + pContext->pulse.pa_stream_get_device_name = (ma_proc)_pa_stream_get_device_name; + pContext->pulse.pa_stream_set_write_callback = (ma_proc)_pa_stream_set_write_callback; + pContext->pulse.pa_stream_set_read_callback = (ma_proc)_pa_stream_set_read_callback; + pContext->pulse.pa_stream_flush = (ma_proc)_pa_stream_flush; + pContext->pulse.pa_stream_drain = (ma_proc)_pa_stream_drain; + pContext->pulse.pa_stream_is_corked = (ma_proc)_pa_stream_is_corked; + pContext->pulse.pa_stream_cork = (ma_proc)_pa_stream_cork; + pContext->pulse.pa_stream_trigger = (ma_proc)_pa_stream_trigger; + pContext->pulse.pa_stream_begin_write = (ma_proc)_pa_stream_begin_write; + pContext->pulse.pa_stream_write = (ma_proc)_pa_stream_write; + pContext->pulse.pa_stream_peek = (ma_proc)_pa_stream_peek; + pContext->pulse.pa_stream_drop = (ma_proc)_pa_stream_drop; + pContext->pulse.pa_stream_writable_size = (ma_proc)_pa_stream_writable_size; + pContext->pulse.pa_stream_readable_size = (ma_proc)_pa_stream_readable_size; +#endif + + pContext->onUninit = ma_context_uninit__pulse; + pContext->onDeviceIDEqual = ma_context_is_device_id_equal__pulse; + pContext->onEnumDevices = ma_context_enumerate_devices__pulse; + pContext->onGetDeviceInfo = ma_context_get_device_info__pulse; + pContext->onDeviceInit = ma_device_init__pulse; + pContext->onDeviceUninit = ma_device_uninit__pulse; + pContext->onDeviceStart = NULL; + pContext->onDeviceStop = ma_device_stop__pulse; + pContext->onDeviceWrite = ma_device_write__pulse; + pContext->onDeviceRead = ma_device_read__pulse; + + + // Although we have found the libpulse library, it doesn't necessarily mean PulseAudio is useable. We need to initialize + // and connect a dummy PulseAudio context to test PulseAudio's usability. + ma_pa_mainloop* pMainLoop = ((ma_pa_mainloop_new_proc)pContext->pulse.pa_mainloop_new)(); + if (pMainLoop == NULL) { + return MA_NO_BACKEND; + } + + ma_pa_mainloop_api* pAPI = ((ma_pa_mainloop_get_api_proc)pContext->pulse.pa_mainloop_get_api)(pMainLoop); + if (pAPI == NULL) { + ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); + return MA_NO_BACKEND; + } + + ma_pa_context* pPulseContext = ((ma_pa_context_new_proc)pContext->pulse.pa_context_new)(pAPI, pContext->config.pulse.pApplicationName); + if (pPulseContext == NULL) { + ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); + return MA_NO_BACKEND; + } + + int error = ((ma_pa_context_connect_proc)pContext->pulse.pa_context_connect)(pPulseContext, pContext->config.pulse.pServerName, 0, NULL); + if (error != MA_PA_OK) { + ((ma_pa_context_unref_proc)pContext->pulse.pa_context_unref)(pPulseContext); + ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); + return MA_NO_BACKEND; + } + + ((ma_pa_context_disconnect_proc)pContext->pulse.pa_context_disconnect)(pPulseContext); + ((ma_pa_context_unref_proc)pContext->pulse.pa_context_unref)(pPulseContext); + ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); + return MA_SUCCESS; +} +#endif + + +/////////////////////////////////////////////////////////////////////////////// +// +// JACK Backend +// +/////////////////////////////////////////////////////////////////////////////// +#ifdef MA_HAS_JACK + +// It is assumed jack.h is available when compile-time linking is being used. +#ifdef MA_NO_RUNTIME_LINKING +#include + +typedef jack_nframes_t ma_jack_nframes_t; +typedef jack_options_t ma_jack_options_t; +typedef jack_status_t ma_jack_status_t; +typedef jack_client_t ma_jack_client_t; +typedef jack_port_t ma_jack_port_t; +typedef JackProcessCallback ma_JackProcessCallback; +typedef JackBufferSizeCallback ma_JackBufferSizeCallback; +typedef JackShutdownCallback ma_JackShutdownCallback; +#define MA_JACK_DEFAULT_AUDIO_TYPE JACK_DEFAULT_AUDIO_TYPE +#define ma_JackNoStartServer JackNoStartServer +#define ma_JackPortIsInput JackPortIsInput +#define ma_JackPortIsOutput JackPortIsOutput +#define ma_JackPortIsPhysical JackPortIsPhysical +#else +typedef ma_uint32 ma_jack_nframes_t; +typedef int ma_jack_options_t; +typedef int ma_jack_status_t; +typedef struct ma_jack_client_t ma_jack_client_t; +typedef struct ma_jack_port_t ma_jack_port_t; +typedef int (* ma_JackProcessCallback) (ma_jack_nframes_t nframes, void* arg); +typedef int (* ma_JackBufferSizeCallback)(ma_jack_nframes_t nframes, void* arg); +typedef void (* ma_JackShutdownCallback) (void* arg); +#define MA_JACK_DEFAULT_AUDIO_TYPE "32 bit float mono audio" +#define ma_JackNoStartServer 1 +#define ma_JackPortIsInput 1 +#define ma_JackPortIsOutput 2 +#define ma_JackPortIsPhysical 4 +#endif + +typedef ma_jack_client_t* (* ma_jack_client_open_proc) (const char* client_name, ma_jack_options_t options, ma_jack_status_t* status, ...); +typedef int (* ma_jack_client_close_proc) (ma_jack_client_t* client); +typedef int (* ma_jack_client_name_size_proc) (); +typedef int (* ma_jack_set_process_callback_proc) (ma_jack_client_t* client, ma_JackProcessCallback process_callback, void* arg); +typedef int (* ma_jack_set_buffer_size_callback_proc)(ma_jack_client_t* client, ma_JackBufferSizeCallback bufsize_callback, void* arg); +typedef void (* ma_jack_on_shutdown_proc) (ma_jack_client_t* client, ma_JackShutdownCallback function, void* arg); +typedef ma_jack_nframes_t (* ma_jack_get_sample_rate_proc) (ma_jack_client_t* client); +typedef ma_jack_nframes_t (* ma_jack_get_buffer_size_proc) (ma_jack_client_t* client); +typedef const char** (* ma_jack_get_ports_proc) (ma_jack_client_t* client, const char* port_name_pattern, const char* type_name_pattern, unsigned long flags); +typedef int (* ma_jack_activate_proc) (ma_jack_client_t* client); +typedef int (* ma_jack_deactivate_proc) (ma_jack_client_t* client); +typedef int (* ma_jack_connect_proc) (ma_jack_client_t* client, const char* source_port, const char* destination_port); +typedef ma_jack_port_t* (* ma_jack_port_register_proc) (ma_jack_client_t* client, const char* port_name, const char* port_type, unsigned long flags, unsigned long buffer_size); +typedef const char* (* ma_jack_port_name_proc) (const ma_jack_port_t* port); +typedef void* (* ma_jack_port_get_buffer_proc) (ma_jack_port_t* port, ma_jack_nframes_t nframes); +typedef void (* ma_jack_free_proc) (void* ptr); + +ma_result ma_context_open_client__jack(ma_context* pContext, ma_jack_client_t** ppClient) +{ + ma_assert(pContext != NULL); + ma_assert(ppClient != NULL); + + if (ppClient) { + *ppClient = NULL; + } + + size_t maxClientNameSize = ((ma_jack_client_name_size_proc)pContext->jack.jack_client_name_size)(); // Includes null terminator. + + char clientName[256]; + ma_strncpy_s(clientName, ma_min(sizeof(clientName), maxClientNameSize), (pContext->config.jack.pClientName != NULL) ? pContext->config.jack.pClientName : "miniaudio", (size_t)-1); + + ma_jack_status_t status; + ma_jack_client_t* pClient = ((ma_jack_client_open_proc)pContext->jack.jack_client_open)(clientName, (pContext->config.jack.tryStartServer) ? 0 : ma_JackNoStartServer, &status, NULL); + if (pClient == NULL) { + return MA_FAILED_TO_OPEN_BACKEND_DEVICE; + } + + if (ppClient) { + *ppClient = pClient; + } + + return MA_SUCCESS; +} + +ma_bool32 ma_context_is_device_id_equal__jack(ma_context* pContext, const ma_device_id* pID0, const ma_device_id* pID1) +{ + ma_assert(pContext != NULL); + ma_assert(pID0 != NULL); + ma_assert(pID1 != NULL); + (void)pContext; + + return pID0->jack == pID1->jack; +} + +ma_result ma_context_enumerate_devices__jack(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData) +{ + ma_assert(pContext != NULL); + ma_assert(callback != NULL); + + ma_bool32 cbResult = MA_TRUE; + + // Playback. + if (cbResult) { + ma_device_info deviceInfo; + ma_zero_object(&deviceInfo); + ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); + cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData); + } + + // Capture. + if (cbResult) { + ma_device_info deviceInfo; + ma_zero_object(&deviceInfo); + ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); + cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData); + } + + return MA_SUCCESS; +} + +ma_result ma_context_get_device_info__jack(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_share_mode shareMode, ma_device_info* pDeviceInfo) +{ + ma_assert(pContext != NULL); + + (void)pContext; + + /* No exclusive mode with the JACK backend. */ + if (shareMode == ma_share_mode_exclusive) { + return MA_SHARE_MODE_NOT_SUPPORTED; + } + + if (pDeviceID != NULL && pDeviceID->jack != 0) { + return MA_NO_DEVICE; // Don't know the device. + } + + // Name / Description + if (deviceType == ma_device_type_playback) { + ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); + } else { + ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); + } + + // Jack only supports f32 and has a specific channel count and sample rate. + pDeviceInfo->formatCount = 1; + pDeviceInfo->formats[0] = ma_format_f32; + + // The channel count and sample rate can only be determined by opening the device. + ma_jack_client_t* pClient; + ma_result result = ma_context_open_client__jack(pContext, &pClient); + if (result != MA_SUCCESS) { + return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[JACK] Failed to open client.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + + pDeviceInfo->minSampleRate = ((ma_jack_get_sample_rate_proc)pContext->jack.jack_get_sample_rate)((ma_jack_client_t*)pClient); + pDeviceInfo->maxSampleRate = pDeviceInfo->minSampleRate; + + pDeviceInfo->minChannels = 0; + pDeviceInfo->maxChannels = 0; + + const char** ppPorts = ((ma_jack_get_ports_proc)pContext->jack.jack_get_ports)((ma_jack_client_t*)pClient, NULL, NULL, ma_JackPortIsPhysical | ((deviceType == ma_device_type_playback) ? ma_JackPortIsInput : ma_JackPortIsOutput)); + if (ppPorts == NULL) { + ((ma_jack_client_close_proc)pContext->jack.jack_client_close)((ma_jack_client_t*)pClient); + return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[JACK] Failed to query physical ports.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + + while (ppPorts[pDeviceInfo->minChannels] != NULL) { + pDeviceInfo->minChannels += 1; + pDeviceInfo->maxChannels += 1; + } + + ((ma_jack_free_proc)pContext->jack.jack_free)((void*)ppPorts); + ((ma_jack_client_close_proc)pContext->jack.jack_client_close)((ma_jack_client_t*)pClient); + + return MA_SUCCESS; +} + + +void ma_device_uninit__jack(ma_device* pDevice) +{ + ma_assert(pDevice != NULL); + + ma_context* pContext = pDevice->pContext; + ma_assert(pContext != NULL); + + if (pDevice->jack.pClient != NULL) { + ((ma_jack_client_close_proc)pContext->jack.jack_client_close)((ma_jack_client_t*)pDevice->jack.pClient); + } + + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + ma_free(pDevice->jack.pIntermediaryBufferCapture); + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + ma_free(pDevice->jack.pIntermediaryBufferPlayback); + } + + if (pDevice->type == ma_device_type_duplex) { + ma_pcm_rb_uninit(&pDevice->jack.duplexRB); + } +} + +void ma_device__jack_shutdown_callback(void* pUserData) +{ + // JACK died. Stop the device. + ma_device* pDevice = (ma_device*)pUserData; + ma_assert(pDevice != NULL); + + ma_device_stop(pDevice); +} + +int ma_device__jack_buffer_size_callback(ma_jack_nframes_t frameCount, void* pUserData) +{ + ma_device* pDevice = (ma_device*)pUserData; + ma_assert(pDevice != NULL); + + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + float* pNewBuffer = (float*)ma_realloc(pDevice->jack.pIntermediaryBufferCapture, frameCount * (pDevice->capture.internalChannels * ma_get_bytes_per_sample(pDevice->capture.internalFormat))); + if (pNewBuffer == NULL) { + return MA_OUT_OF_MEMORY; + } + + pDevice->jack.pIntermediaryBufferCapture = pNewBuffer; + pDevice->playback.internalBufferSizeInFrames = frameCount * pDevice->capture.internalPeriods; + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + float* pNewBuffer = (float*)ma_realloc(pDevice->jack.pIntermediaryBufferPlayback, frameCount * (pDevice->playback.internalChannels * ma_get_bytes_per_sample(pDevice->playback.internalFormat))); + if (pNewBuffer == NULL) { + return MA_OUT_OF_MEMORY; + } + + pDevice->jack.pIntermediaryBufferPlayback = pNewBuffer; + pDevice->playback.internalBufferSizeInFrames = frameCount * pDevice->playback.internalPeriods; + } + + return 0; +} + +int ma_device__jack_process_callback(ma_jack_nframes_t frameCount, void* pUserData) +{ + ma_device* pDevice = (ma_device*)pUserData; + ma_assert(pDevice != NULL); + + ma_context* pContext = pDevice->pContext; + ma_assert(pContext != NULL); + + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + // Channels need to be interleaved. + for (ma_uint32 iChannel = 0; iChannel < pDevice->capture.internalChannels; ++iChannel) { + const float* pSrc = (const float*)((ma_jack_port_get_buffer_proc)pContext->jack.jack_port_get_buffer)((ma_jack_port_t*)pDevice->jack.pPortsCapture[iChannel], frameCount); + if (pSrc != NULL) { + float* pDst = pDevice->jack.pIntermediaryBufferCapture + iChannel; + for (ma_jack_nframes_t iFrame = 0; iFrame < frameCount; ++iFrame) { + *pDst = *pSrc; + + pDst += pDevice->capture.internalChannels; + pSrc += 1; + } + } + } + + if (pDevice->type == ma_device_type_duplex) { + ma_device__handle_duplex_callback_capture(pDevice, frameCount, pDevice->jack.pIntermediaryBufferCapture, &pDevice->jack.duplexRB); + } else { + ma_device__send_frames_to_client(pDevice, frameCount, pDevice->jack.pIntermediaryBufferCapture); + } + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + if (pDevice->type == ma_device_type_duplex) { + ma_device__handle_duplex_callback_playback(pDevice, frameCount, pDevice->jack.pIntermediaryBufferPlayback, &pDevice->jack.duplexRB); + } else { + ma_device__read_frames_from_client(pDevice, frameCount, pDevice->jack.pIntermediaryBufferPlayback); + } + + // Channels need to be deinterleaved. + for (ma_uint32 iChannel = 0; iChannel < pDevice->playback.internalChannels; ++iChannel) { + float* pDst = (float*)((ma_jack_port_get_buffer_proc)pContext->jack.jack_port_get_buffer)((ma_jack_port_t*)pDevice->jack.pPortsPlayback[iChannel], frameCount); + if (pDst != NULL) { + const float* pSrc = pDevice->jack.pIntermediaryBufferPlayback + iChannel; + for (ma_jack_nframes_t iFrame = 0; iFrame < frameCount; ++iFrame) { + *pDst = *pSrc; + + pDst += 1; + pSrc += pDevice->playback.internalChannels; + } + } + } + } + + return 0; +} + +ma_result ma_device_init__jack(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice) +{ + ma_assert(pContext != NULL); + ma_assert(pConfig != NULL); + ma_assert(pDevice != NULL); + + (void)pContext; + + /* Only supporting default devices with JACK. */ + if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pConfig->playback.pDeviceID != NULL && pConfig->playback.pDeviceID->jack != 0) || + ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pConfig->capture.pDeviceID != NULL && pConfig->capture.pDeviceID->jack != 0)) { + return MA_NO_DEVICE; + } + + /* No exclusive mode with the JACK backend. */ + if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pConfig->playback.shareMode == ma_share_mode_exclusive) || + ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pConfig->capture.shareMode == ma_share_mode_exclusive)) { + return MA_SHARE_MODE_NOT_SUPPORTED; + } + + /* Open the client. */ + ma_result result = ma_context_open_client__jack(pContext, (ma_jack_client_t**)&pDevice->jack.pClient); + if (result != MA_SUCCESS) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[JACK] Failed to open client.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + + /* Callbacks. */ + if (((ma_jack_set_process_callback_proc)pContext->jack.jack_set_process_callback)((ma_jack_client_t*)pDevice->jack.pClient, ma_device__jack_process_callback, pDevice) != 0) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[JACK] Failed to set process callback.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + if (((ma_jack_set_buffer_size_callback_proc)pContext->jack.jack_set_buffer_size_callback)((ma_jack_client_t*)pDevice->jack.pClient, ma_device__jack_buffer_size_callback, pDevice) != 0) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[JACK] Failed to set buffer size callback.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + + ((ma_jack_on_shutdown_proc)pContext->jack.jack_on_shutdown)((ma_jack_client_t*)pDevice->jack.pClient, ma_device__jack_shutdown_callback, pDevice); + + + /* The buffer size in frames can change. */ + ma_uint32 periods = 2; + ma_uint32 bufferSizeInFrames = ((ma_jack_get_buffer_size_proc)pContext->jack.jack_get_buffer_size)((ma_jack_client_t*)pDevice->jack.pClient) * periods; + + if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) { + const char** ppPorts; + + pDevice->capture.internalFormat = ma_format_f32; + pDevice->capture.internalChannels = 0; + pDevice->capture.internalSampleRate = ((ma_jack_get_sample_rate_proc)pContext->jack.jack_get_sample_rate)((ma_jack_client_t*)pDevice->jack.pClient); + ma_get_standard_channel_map(ma_standard_channel_map_alsa, pDevice->capture.internalChannels, pDevice->capture.internalChannelMap); + + ppPorts = ((ma_jack_get_ports_proc)pContext->jack.jack_get_ports)((ma_jack_client_t*)pDevice->jack.pClient, NULL, NULL, ma_JackPortIsPhysical | ma_JackPortIsOutput); + if (ppPorts == NULL) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[JACK] Failed to query physical ports.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + + while (ppPorts[pDevice->capture.internalChannels] != NULL) { + char name[64]; + ma_strcpy_s(name, sizeof(name), "capture"); + ma_itoa_s((int)pDevice->capture.internalChannels, name+7, sizeof(name)-7, 10); // 7 = length of "capture" + + pDevice->jack.pPortsCapture[pDevice->capture.internalChannels] = ((ma_jack_port_register_proc)pContext->jack.jack_port_register)((ma_jack_client_t*)pDevice->jack.pClient, name, MA_JACK_DEFAULT_AUDIO_TYPE, ma_JackPortIsInput, 0); + if (pDevice->jack.pPortsCapture[pDevice->capture.internalChannels] == NULL) { + ((ma_jack_free_proc)pContext->jack.jack_free)((void*)ppPorts); + ma_device_uninit__jack(pDevice); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[JACK] Failed to register ports.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + + pDevice->capture.internalChannels += 1; + } + + ((ma_jack_free_proc)pContext->jack.jack_free)((void*)ppPorts); + + pDevice->capture.internalBufferSizeInFrames = bufferSizeInFrames; + pDevice->capture.internalPeriods = periods; + + pDevice->jack.pIntermediaryBufferCapture = (float*)ma_malloc((pDevice->capture.internalBufferSizeInFrames/pDevice->capture.internalPeriods) * (pDevice->capture.internalChannels * ma_get_bytes_per_sample(pDevice->capture.internalFormat))); + if (pDevice->jack.pIntermediaryBufferCapture == NULL) { + ma_device_uninit__jack(pDevice); + return MA_OUT_OF_MEMORY; + } + } + + if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) { + const char** ppPorts; + + pDevice->playback.internalFormat = ma_format_f32; + pDevice->playback.internalChannels = 0; + pDevice->playback.internalSampleRate = ((ma_jack_get_sample_rate_proc)pContext->jack.jack_get_sample_rate)((ma_jack_client_t*)pDevice->jack.pClient); + ma_get_standard_channel_map(ma_standard_channel_map_alsa, pDevice->playback.internalChannels, pDevice->playback.internalChannelMap); + + ppPorts = ((ma_jack_get_ports_proc)pContext->jack.jack_get_ports)((ma_jack_client_t*)pDevice->jack.pClient, NULL, NULL, ma_JackPortIsPhysical | ma_JackPortIsInput); + if (ppPorts == NULL) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[JACK] Failed to query physical ports.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + + while (ppPorts[pDevice->playback.internalChannels] != NULL) { + char name[64]; + ma_strcpy_s(name, sizeof(name), "playback"); + ma_itoa_s((int)pDevice->playback.internalChannels, name+8, sizeof(name)-8, 10); // 8 = length of "playback" + + pDevice->jack.pPortsPlayback[pDevice->playback.internalChannels] = ((ma_jack_port_register_proc)pContext->jack.jack_port_register)((ma_jack_client_t*)pDevice->jack.pClient, name, MA_JACK_DEFAULT_AUDIO_TYPE, ma_JackPortIsOutput, 0); + if (pDevice->jack.pPortsPlayback[pDevice->playback.internalChannels] == NULL) { + ((ma_jack_free_proc)pContext->jack.jack_free)((void*)ppPorts); + ma_device_uninit__jack(pDevice); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[JACK] Failed to register ports.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + + pDevice->playback.internalChannels += 1; + } + + ((ma_jack_free_proc)pContext->jack.jack_free)((void*)ppPorts); + + pDevice->playback.internalBufferSizeInFrames = bufferSizeInFrames; + pDevice->playback.internalPeriods = periods; + + pDevice->jack.pIntermediaryBufferPlayback = (float*)ma_malloc((pDevice->playback.internalBufferSizeInFrames/pDevice->playback.internalPeriods) * (pDevice->playback.internalChannels * ma_get_bytes_per_sample(pDevice->playback.internalFormat))); + if (pDevice->jack.pIntermediaryBufferPlayback == NULL) { + ma_device_uninit__jack(pDevice); + return MA_OUT_OF_MEMORY; + } + } + + if (pDevice->type == ma_device_type_duplex) { + ma_uint32 rbSizeInFrames = (ma_uint32)ma_calculate_frame_count_after_src(pDevice->sampleRate, pDevice->capture.internalSampleRate, pDevice->capture.internalBufferSizeInFrames); + result = ma_pcm_rb_init(pDevice->capture.format, pDevice->capture.channels, rbSizeInFrames, NULL, &pDevice->jack.duplexRB); + if (result != MA_SUCCESS) { + ma_device_uninit__jack(pDevice); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[JACK] Failed to initialize ring buffer.", result); + } + } + + return MA_SUCCESS; +} + + +ma_result ma_device_start__jack(ma_device* pDevice) +{ + ma_assert(pDevice != NULL); + + ma_context* pContext = pDevice->pContext; + ma_assert(pContext != NULL); + + int resultJACK = ((ma_jack_activate_proc)pContext->jack.jack_activate)((ma_jack_client_t*)pDevice->jack.pClient); + if (resultJACK != 0) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[JACK] Failed to activate the JACK client.", MA_FAILED_TO_START_BACKEND_DEVICE); + } + + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + const char** ppServerPorts = ((ma_jack_get_ports_proc)pContext->jack.jack_get_ports)((ma_jack_client_t*)pDevice->jack.pClient, NULL, NULL, ma_JackPortIsPhysical | ma_JackPortIsOutput); + if (ppServerPorts == NULL) { + ((ma_jack_deactivate_proc)pContext->jack.jack_deactivate)((ma_jack_client_t*)pDevice->jack.pClient); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[JACK] Failed to retrieve physical ports.", MA_ERROR); + } + + for (size_t i = 0; ppServerPorts[i] != NULL; ++i) { + const char* pServerPort = ppServerPorts[i]; + const char* pClientPort = ((ma_jack_port_name_proc)pContext->jack.jack_port_name)((ma_jack_port_t*)pDevice->jack.pPortsCapture[i]); + + resultJACK = ((ma_jack_connect_proc)pContext->jack.jack_connect)((ma_jack_client_t*)pDevice->jack.pClient, pServerPort, pClientPort); + if (resultJACK != 0) { + ((ma_jack_free_proc)pContext->jack.jack_free)((void*)ppServerPorts); + ((ma_jack_deactivate_proc)pContext->jack.jack_deactivate)((ma_jack_client_t*)pDevice->jack.pClient); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[JACK] Failed to connect ports.", MA_ERROR); + } + } + + ((ma_jack_free_proc)pContext->jack.jack_free)((void*)ppServerPorts); + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + const char** ppServerPorts = ((ma_jack_get_ports_proc)pContext->jack.jack_get_ports)((ma_jack_client_t*)pDevice->jack.pClient, NULL, NULL, ma_JackPortIsPhysical | ma_JackPortIsInput); + if (ppServerPorts == NULL) { + ((ma_jack_deactivate_proc)pContext->jack.jack_deactivate)((ma_jack_client_t*)pDevice->jack.pClient); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[JACK] Failed to retrieve physical ports.", MA_ERROR); + } + + for (size_t i = 0; ppServerPorts[i] != NULL; ++i) { + const char* pServerPort = ppServerPorts[i]; + const char* pClientPort = ((ma_jack_port_name_proc)pContext->jack.jack_port_name)((ma_jack_port_t*)pDevice->jack.pPortsPlayback[i]); + + resultJACK = ((ma_jack_connect_proc)pContext->jack.jack_connect)((ma_jack_client_t*)pDevice->jack.pClient, pClientPort, pServerPort); + if (resultJACK != 0) { + ((ma_jack_free_proc)pContext->jack.jack_free)((void*)ppServerPorts); + ((ma_jack_deactivate_proc)pContext->jack.jack_deactivate)((ma_jack_client_t*)pDevice->jack.pClient); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[JACK] Failed to connect ports.", MA_ERROR); + } + } + + ((ma_jack_free_proc)pContext->jack.jack_free)((void*)ppServerPorts); + } + + return MA_SUCCESS; +} + +ma_result ma_device_stop__jack(ma_device* pDevice) +{ + ma_assert(pDevice != NULL); + + ma_context* pContext = pDevice->pContext; + ma_assert(pContext != NULL); + + if (((ma_jack_deactivate_proc)pContext->jack.jack_deactivate)((ma_jack_client_t*)pDevice->jack.pClient) != 0) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[JACK] An error occurred when deactivating the JACK client.", MA_ERROR); + } + + ma_stop_proc onStop = pDevice->onStop; + if (onStop) { + onStop(pDevice); + } + + return MA_SUCCESS; +} + + +ma_result ma_context_uninit__jack(ma_context* pContext) +{ + ma_assert(pContext != NULL); + ma_assert(pContext->backend == ma_backend_jack); + +#ifndef MA_NO_RUNTIME_LINKING + ma_dlclose(pContext->jack.jackSO); +#endif + + return MA_SUCCESS; +} + +ma_result ma_context_init__jack(ma_context* pContext) +{ + ma_assert(pContext != NULL); + +#ifndef MA_NO_RUNTIME_LINKING + // libjack.so + const char* libjackNames[] = { +#ifdef MA_WIN32 + "libjack.dll" +#else + "libjack.so", + "libjack.so.0" +#endif + }; + + for (size_t i = 0; i < ma_countof(libjackNames); ++i) { + pContext->jack.jackSO = ma_dlopen(libjackNames[i]); + if (pContext->jack.jackSO != NULL) { + break; + } + } + + if (pContext->jack.jackSO == NULL) { + return MA_NO_BACKEND; + } + + pContext->jack.jack_client_open = (ma_proc)ma_dlsym(pContext->jack.jackSO, "jack_client_open"); + pContext->jack.jack_client_close = (ma_proc)ma_dlsym(pContext->jack.jackSO, "jack_client_close"); + pContext->jack.jack_client_name_size = (ma_proc)ma_dlsym(pContext->jack.jackSO, "jack_client_name_size"); + pContext->jack.jack_set_process_callback = (ma_proc)ma_dlsym(pContext->jack.jackSO, "jack_set_process_callback"); + pContext->jack.jack_set_buffer_size_callback = (ma_proc)ma_dlsym(pContext->jack.jackSO, "jack_set_buffer_size_callback"); + pContext->jack.jack_on_shutdown = (ma_proc)ma_dlsym(pContext->jack.jackSO, "jack_on_shutdown"); + pContext->jack.jack_get_sample_rate = (ma_proc)ma_dlsym(pContext->jack.jackSO, "jack_get_sample_rate"); + pContext->jack.jack_get_buffer_size = (ma_proc)ma_dlsym(pContext->jack.jackSO, "jack_get_buffer_size"); + pContext->jack.jack_get_ports = (ma_proc)ma_dlsym(pContext->jack.jackSO, "jack_get_ports"); + pContext->jack.jack_activate = (ma_proc)ma_dlsym(pContext->jack.jackSO, "jack_activate"); + pContext->jack.jack_deactivate = (ma_proc)ma_dlsym(pContext->jack.jackSO, "jack_deactivate"); + pContext->jack.jack_connect = (ma_proc)ma_dlsym(pContext->jack.jackSO, "jack_connect"); + pContext->jack.jack_port_register = (ma_proc)ma_dlsym(pContext->jack.jackSO, "jack_port_register"); + pContext->jack.jack_port_name = (ma_proc)ma_dlsym(pContext->jack.jackSO, "jack_port_name"); + pContext->jack.jack_port_get_buffer = (ma_proc)ma_dlsym(pContext->jack.jackSO, "jack_port_get_buffer"); + pContext->jack.jack_free = (ma_proc)ma_dlsym(pContext->jack.jackSO, "jack_free"); +#else + // This strange assignment system is here just to ensure type safety of miniaudio's function pointer + // types. If anything differs slightly the compiler should throw a warning. + ma_jack_client_open_proc _jack_client_open = jack_client_open; + ma_jack_client_close_proc _jack_client_close = jack_client_close; + ma_jack_client_name_size_proc _jack_client_name_size = jack_client_name_size; + ma_jack_set_process_callback_proc _jack_set_process_callback = jack_set_process_callback; + ma_jack_set_buffer_size_callback_proc _jack_set_buffer_size_callback = jack_set_buffer_size_callback; + ma_jack_on_shutdown_proc _jack_on_shutdown = jack_on_shutdown; + ma_jack_get_sample_rate_proc _jack_get_sample_rate = jack_get_sample_rate; + ma_jack_get_buffer_size_proc _jack_get_buffer_size = jack_get_buffer_size; + ma_jack_get_ports_proc _jack_get_ports = jack_get_ports; + ma_jack_activate_proc _jack_activate = jack_activate; + ma_jack_deactivate_proc _jack_deactivate = jack_deactivate; + ma_jack_connect_proc _jack_connect = jack_connect; + ma_jack_port_register_proc _jack_port_register = jack_port_register; + ma_jack_port_name_proc _jack_port_name = jack_port_name; + ma_jack_port_get_buffer_proc _jack_port_get_buffer = jack_port_get_buffer; + ma_jack_free_proc _jack_free = jack_free; + + pContext->jack.jack_client_open = (ma_proc)_jack_client_open; + pContext->jack.jack_client_close = (ma_proc)_jack_client_close; + pContext->jack.jack_client_name_size = (ma_proc)_jack_client_name_size; + pContext->jack.jack_set_process_callback = (ma_proc)_jack_set_process_callback; + pContext->jack.jack_set_buffer_size_callback = (ma_proc)_jack_set_buffer_size_callback; + pContext->jack.jack_on_shutdown = (ma_proc)_jack_on_shutdown; + pContext->jack.jack_get_sample_rate = (ma_proc)_jack_get_sample_rate; + pContext->jack.jack_get_buffer_size = (ma_proc)_jack_get_buffer_size; + pContext->jack.jack_get_ports = (ma_proc)_jack_get_ports; + pContext->jack.jack_activate = (ma_proc)_jack_activate; + pContext->jack.jack_deactivate = (ma_proc)_jack_deactivate; + pContext->jack.jack_connect = (ma_proc)_jack_connect; + pContext->jack.jack_port_register = (ma_proc)_jack_port_register; + pContext->jack.jack_port_name = (ma_proc)_jack_port_name; + pContext->jack.jack_port_get_buffer = (ma_proc)_jack_port_get_buffer; + pContext->jack.jack_free = (ma_proc)_jack_free; +#endif + + pContext->isBackendAsynchronous = MA_TRUE; + + pContext->onUninit = ma_context_uninit__jack; + pContext->onDeviceIDEqual = ma_context_is_device_id_equal__jack; + pContext->onEnumDevices = ma_context_enumerate_devices__jack; + pContext->onGetDeviceInfo = ma_context_get_device_info__jack; + pContext->onDeviceInit = ma_device_init__jack; + pContext->onDeviceUninit = ma_device_uninit__jack; + pContext->onDeviceStart = ma_device_start__jack; + pContext->onDeviceStop = ma_device_stop__jack; + + + // Getting here means the JACK library is installed, but it doesn't necessarily mean it's usable. We need to quickly test this by connecting + // a temporary client. + ma_jack_client_t* pDummyClient; + ma_result result = ma_context_open_client__jack(pContext, &pDummyClient); + if (result != MA_SUCCESS) { + return MA_NO_BACKEND; + } + + ((ma_jack_client_close_proc)pContext->jack.jack_client_close)((ma_jack_client_t*)pDummyClient); + return MA_SUCCESS; +} +#endif // JACK + + + +/////////////////////////////////////////////////////////////////////////////// +// +// Core Audio Backend +// +/////////////////////////////////////////////////////////////////////////////// +#ifdef MA_HAS_COREAUDIO +#include + +#if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE == 1 + #define MA_APPLE_MOBILE +#else + #define MA_APPLE_DESKTOP +#endif + +#if defined(MA_APPLE_DESKTOP) +#include +#else +#include +#endif + +#include + +// CoreFoundation +typedef Boolean (* ma_CFStringGetCString_proc)(CFStringRef theString, char* buffer, CFIndex bufferSize, CFStringEncoding encoding); + +// CoreAudio +#if defined(MA_APPLE_DESKTOP) +typedef OSStatus (* ma_AudioObjectGetPropertyData_proc)(AudioObjectID inObjectID, const AudioObjectPropertyAddress* inAddress, UInt32 inQualifierDataSize, const void* inQualifierData, UInt32* ioDataSize, void* outData); +typedef OSStatus (* ma_AudioObjectGetPropertyDataSize_proc)(AudioObjectID inObjectID, const AudioObjectPropertyAddress* inAddress, UInt32 inQualifierDataSize, const void* inQualifierData, UInt32* outDataSize); +typedef OSStatus (* ma_AudioObjectSetPropertyData_proc)(AudioObjectID inObjectID, const AudioObjectPropertyAddress* inAddress, UInt32 inQualifierDataSize, const void* inQualifierData, UInt32 inDataSize, const void* inData); +typedef OSStatus (* ma_AudioObjectAddPropertyListener_proc)(AudioObjectID inObjectID, const AudioObjectPropertyAddress* inAddress, AudioObjectPropertyListenerProc inListener, void* inClientData); +#endif + +// AudioToolbox +typedef AudioComponent (* ma_AudioComponentFindNext_proc)(AudioComponent inComponent, const AudioComponentDescription* inDesc); +typedef OSStatus (* ma_AudioComponentInstanceDispose_proc)(AudioComponentInstance inInstance); +typedef OSStatus (* ma_AudioComponentInstanceNew_proc)(AudioComponent inComponent, AudioComponentInstance* outInstance); +typedef OSStatus (* ma_AudioOutputUnitStart_proc)(AudioUnit inUnit); +typedef OSStatus (* ma_AudioOutputUnitStop_proc)(AudioUnit inUnit); +typedef OSStatus (* ma_AudioUnitAddPropertyListener_proc)(AudioUnit inUnit, AudioUnitPropertyID inID, AudioUnitPropertyListenerProc inProc, void* inProcUserData); +typedef OSStatus (* ma_AudioUnitGetPropertyInfo_proc)(AudioUnit inUnit, AudioUnitPropertyID inID, AudioUnitScope inScope, AudioUnitElement inElement, UInt32* outDataSize, Boolean* outWriteable); +typedef OSStatus (* ma_AudioUnitGetProperty_proc)(AudioUnit inUnit, AudioUnitPropertyID inID, AudioUnitScope inScope, AudioUnitElement inElement, void* outData, UInt32* ioDataSize); +typedef OSStatus (* ma_AudioUnitSetProperty_proc)(AudioUnit inUnit, AudioUnitPropertyID inID, AudioUnitScope inScope, AudioUnitElement inElement, const void* inData, UInt32 inDataSize); +typedef OSStatus (* ma_AudioUnitInitialize_proc)(AudioUnit inUnit); +typedef OSStatus (* ma_AudioUnitRender_proc)(AudioUnit inUnit, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp, UInt32 inOutputBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData); + + +#define MA_COREAUDIO_OUTPUT_BUS 0 +#define MA_COREAUDIO_INPUT_BUS 1 + +ma_result ma_device_reinit_internal__coreaudio(ma_device* pDevice, ma_device_type deviceType, ma_bool32 disposePreviousAudioUnit); + + +// Core Audio +// +// So far, Core Audio has been the worst backend to work with due to being both unintuitive and having almost no documentation +// apart from comments in the headers (which admittedly are quite good). For my own purposes, and for anybody out there whose +// needing to figure out how this darn thing works, I'm going to outline a few things here. +// +// Since miniaudio is a fairly low-level API, one of the things it needs is control over specific devices, and it needs to be +// able to identify whether or not it can be used as playback and/or capture. The AudioObject API is the only one I've seen +// that supports this level of detail. There was some public domain sample code I stumbled across that used the AudioComponent +// and AudioUnit APIs, but I couldn't see anything that gave low-level control over device selection and capabilities (the +// distinction between playback and capture in particular). Therefore, miniaudio is using the AudioObject API. +// +// Most (all?) functions in the AudioObject API take a AudioObjectID as it's input. This is the device identifier. When +// retrieving global information, such as the device list, you use kAudioObjectSystemObject. When retrieving device-specific +// data, you pass in the ID for that device. In order to retrieve device-specific IDs you need to enumerate over each of the +// devices. This is done using the AudioObjectGetPropertyDataSize() and AudioObjectGetPropertyData() APIs which seem to be +// the central APIs for retrieving information about the system and specific devices. +// +// To use the AudioObjectGetPropertyData() API you need to use the notion of a property address. A property address is a +// structure with three variables and is used to identify which property you are getting or setting. The first is the "selector" +// which is basically the specific property that you're wanting to retrieve or set. The second is the "scope", which is +// typically set to kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyScopeInput for input-specific properties and +// kAudioObjectPropertyScopeOutput for output-specific properties. The last is the "element" which is always set to +// kAudioObjectPropertyElementMaster in miniaudio's case. I don't know of any cases where this would be set to anything different. +// +// Back to the earlier issue of device retrieval, you first use the AudioObjectGetPropertyDataSize() API to retrieve the size +// of the raw data which is just a list of AudioDeviceID's. You use the kAudioObjectSystemObject AudioObjectID, and a property +// address with the kAudioHardwarePropertyDevices selector and the kAudioObjectPropertyScopeGlobal scope. Once you have the +// size, allocate a block of memory of that size and then call AudioObjectGetPropertyData(). The data is just a list of +// AudioDeviceID's so just do "dataSize/sizeof(AudioDeviceID)" to know the device count. + +ma_result ma_result_from_OSStatus(OSStatus status) +{ + switch (status) + { + case noErr: return MA_SUCCESS; + #if defined(MA_APPLE_DESKTOP) + case kAudioHardwareNotRunningError: return MA_DEVICE_NOT_STARTED; + case kAudioHardwareUnspecifiedError: return MA_ERROR; + case kAudioHardwareUnknownPropertyError: return MA_INVALID_ARGS; + case kAudioHardwareBadPropertySizeError: return MA_INVALID_OPERATION; + case kAudioHardwareIllegalOperationError: return MA_INVALID_OPERATION; + case kAudioHardwareBadObjectError: return MA_INVALID_ARGS; + case kAudioHardwareBadDeviceError: return MA_INVALID_ARGS; + case kAudioHardwareBadStreamError: return MA_INVALID_ARGS; + case kAudioHardwareUnsupportedOperationError: return MA_INVALID_OPERATION; + case kAudioDeviceUnsupportedFormatError: return MA_FORMAT_NOT_SUPPORTED; + case kAudioDevicePermissionsError: return MA_ACCESS_DENIED; + #endif + default: return MA_ERROR; + } +} + +#if 0 +ma_channel ma_channel_from_AudioChannelBitmap(AudioChannelBitmap bit) +{ + switch (bit) + { + case kAudioChannelBit_Left: return MA_CHANNEL_LEFT; + case kAudioChannelBit_Right: return MA_CHANNEL_RIGHT; + case kAudioChannelBit_Center: return MA_CHANNEL_FRONT_CENTER; + case kAudioChannelBit_LFEScreen: return MA_CHANNEL_LFE; + case kAudioChannelBit_LeftSurround: return MA_CHANNEL_BACK_LEFT; + case kAudioChannelBit_RightSurround: return MA_CHANNEL_BACK_RIGHT; + case kAudioChannelBit_LeftCenter: return MA_CHANNEL_FRONT_LEFT_CENTER; + case kAudioChannelBit_RightCenter: return MA_CHANNEL_FRONT_RIGHT_CENTER; + case kAudioChannelBit_CenterSurround: return MA_CHANNEL_BACK_CENTER; + case kAudioChannelBit_LeftSurroundDirect: return MA_CHANNEL_SIDE_LEFT; + case kAudioChannelBit_RightSurroundDirect: return MA_CHANNEL_SIDE_RIGHT; + case kAudioChannelBit_TopCenterSurround: return MA_CHANNEL_TOP_CENTER; + case kAudioChannelBit_VerticalHeightLeft: return MA_CHANNEL_TOP_FRONT_LEFT; + case kAudioChannelBit_VerticalHeightCenter: return MA_CHANNEL_TOP_FRONT_CENTER; + case kAudioChannelBit_VerticalHeightRight: return MA_CHANNEL_TOP_FRONT_RIGHT; + case kAudioChannelBit_TopBackLeft: return MA_CHANNEL_TOP_BACK_LEFT; + case kAudioChannelBit_TopBackCenter: return MA_CHANNEL_TOP_BACK_CENTER; + case kAudioChannelBit_TopBackRight: return MA_CHANNEL_TOP_BACK_RIGHT; + default: return MA_CHANNEL_NONE; + } +} +#endif + +ma_channel ma_channel_from_AudioChannelLabel(AudioChannelLabel label) +{ + switch (label) + { + case kAudioChannelLabel_Unknown: return MA_CHANNEL_NONE; + case kAudioChannelLabel_Unused: return MA_CHANNEL_NONE; + case kAudioChannelLabel_UseCoordinates: return MA_CHANNEL_NONE; + case kAudioChannelLabel_Left: return MA_CHANNEL_LEFT; + case kAudioChannelLabel_Right: return MA_CHANNEL_RIGHT; + case kAudioChannelLabel_Center: return MA_CHANNEL_FRONT_CENTER; + case kAudioChannelLabel_LFEScreen: return MA_CHANNEL_LFE; + case kAudioChannelLabel_LeftSurround: return MA_CHANNEL_BACK_LEFT; + case kAudioChannelLabel_RightSurround: return MA_CHANNEL_BACK_RIGHT; + case kAudioChannelLabel_LeftCenter: return MA_CHANNEL_FRONT_LEFT_CENTER; + case kAudioChannelLabel_RightCenter: return MA_CHANNEL_FRONT_RIGHT_CENTER; + case kAudioChannelLabel_CenterSurround: return MA_CHANNEL_BACK_CENTER; + case kAudioChannelLabel_LeftSurroundDirect: return MA_CHANNEL_SIDE_LEFT; + case kAudioChannelLabel_RightSurroundDirect: return MA_CHANNEL_SIDE_RIGHT; + case kAudioChannelLabel_TopCenterSurround: return MA_CHANNEL_TOP_CENTER; + case kAudioChannelLabel_VerticalHeightLeft: return MA_CHANNEL_TOP_FRONT_LEFT; + case kAudioChannelLabel_VerticalHeightCenter: return MA_CHANNEL_TOP_FRONT_CENTER; + case kAudioChannelLabel_VerticalHeightRight: return MA_CHANNEL_TOP_FRONT_RIGHT; + case kAudioChannelLabel_TopBackLeft: return MA_CHANNEL_TOP_BACK_LEFT; + case kAudioChannelLabel_TopBackCenter: return MA_CHANNEL_TOP_BACK_CENTER; + case kAudioChannelLabel_TopBackRight: return MA_CHANNEL_TOP_BACK_RIGHT; + case kAudioChannelLabel_RearSurroundLeft: return MA_CHANNEL_BACK_LEFT; + case kAudioChannelLabel_RearSurroundRight: return MA_CHANNEL_BACK_RIGHT; + case kAudioChannelLabel_LeftWide: return MA_CHANNEL_SIDE_LEFT; + case kAudioChannelLabel_RightWide: return MA_CHANNEL_SIDE_RIGHT; + case kAudioChannelLabel_LFE2: return MA_CHANNEL_LFE; + case kAudioChannelLabel_LeftTotal: return MA_CHANNEL_LEFT; + case kAudioChannelLabel_RightTotal: return MA_CHANNEL_RIGHT; + case kAudioChannelLabel_HearingImpaired: return MA_CHANNEL_NONE; + case kAudioChannelLabel_Narration: return MA_CHANNEL_MONO; + case kAudioChannelLabel_Mono: return MA_CHANNEL_MONO; + case kAudioChannelLabel_DialogCentricMix: return MA_CHANNEL_MONO; + case kAudioChannelLabel_CenterSurroundDirect: return MA_CHANNEL_BACK_CENTER; + case kAudioChannelLabel_Haptic: return MA_CHANNEL_NONE; + case kAudioChannelLabel_Ambisonic_W: return MA_CHANNEL_NONE; + case kAudioChannelLabel_Ambisonic_X: return MA_CHANNEL_NONE; + case kAudioChannelLabel_Ambisonic_Y: return MA_CHANNEL_NONE; + case kAudioChannelLabel_Ambisonic_Z: return MA_CHANNEL_NONE; + case kAudioChannelLabel_MS_Mid: return MA_CHANNEL_LEFT; + case kAudioChannelLabel_MS_Side: return MA_CHANNEL_RIGHT; + case kAudioChannelLabel_XY_X: return MA_CHANNEL_LEFT; + case kAudioChannelLabel_XY_Y: return MA_CHANNEL_RIGHT; + case kAudioChannelLabel_HeadphonesLeft: return MA_CHANNEL_LEFT; + case kAudioChannelLabel_HeadphonesRight: return MA_CHANNEL_RIGHT; + case kAudioChannelLabel_ClickTrack: return MA_CHANNEL_NONE; + case kAudioChannelLabel_ForeignLanguage: return MA_CHANNEL_NONE; + case kAudioChannelLabel_Discrete: return MA_CHANNEL_NONE; + case kAudioChannelLabel_Discrete_0: return MA_CHANNEL_AUX_0; + case kAudioChannelLabel_Discrete_1: return MA_CHANNEL_AUX_1; + case kAudioChannelLabel_Discrete_2: return MA_CHANNEL_AUX_2; + case kAudioChannelLabel_Discrete_3: return MA_CHANNEL_AUX_3; + case kAudioChannelLabel_Discrete_4: return MA_CHANNEL_AUX_4; + case kAudioChannelLabel_Discrete_5: return MA_CHANNEL_AUX_5; + case kAudioChannelLabel_Discrete_6: return MA_CHANNEL_AUX_6; + case kAudioChannelLabel_Discrete_7: return MA_CHANNEL_AUX_7; + case kAudioChannelLabel_Discrete_8: return MA_CHANNEL_AUX_8; + case kAudioChannelLabel_Discrete_9: return MA_CHANNEL_AUX_9; + case kAudioChannelLabel_Discrete_10: return MA_CHANNEL_AUX_10; + case kAudioChannelLabel_Discrete_11: return MA_CHANNEL_AUX_11; + case kAudioChannelLabel_Discrete_12: return MA_CHANNEL_AUX_12; + case kAudioChannelLabel_Discrete_13: return MA_CHANNEL_AUX_13; + case kAudioChannelLabel_Discrete_14: return MA_CHANNEL_AUX_14; + case kAudioChannelLabel_Discrete_15: return MA_CHANNEL_AUX_15; + case kAudioChannelLabel_Discrete_65535: return MA_CHANNEL_NONE; + + #if 0 // Introduced in a later version of macOS. + case kAudioChannelLabel_HOA_ACN: return MA_CHANNEL_NONE; + case kAudioChannelLabel_HOA_ACN_0: return MA_CHANNEL_AUX_0; + case kAudioChannelLabel_HOA_ACN_1: return MA_CHANNEL_AUX_1; + case kAudioChannelLabel_HOA_ACN_2: return MA_CHANNEL_AUX_2; + case kAudioChannelLabel_HOA_ACN_3: return MA_CHANNEL_AUX_3; + case kAudioChannelLabel_HOA_ACN_4: return MA_CHANNEL_AUX_4; + case kAudioChannelLabel_HOA_ACN_5: return MA_CHANNEL_AUX_5; + case kAudioChannelLabel_HOA_ACN_6: return MA_CHANNEL_AUX_6; + case kAudioChannelLabel_HOA_ACN_7: return MA_CHANNEL_AUX_7; + case kAudioChannelLabel_HOA_ACN_8: return MA_CHANNEL_AUX_8; + case kAudioChannelLabel_HOA_ACN_9: return MA_CHANNEL_AUX_9; + case kAudioChannelLabel_HOA_ACN_10: return MA_CHANNEL_AUX_10; + case kAudioChannelLabel_HOA_ACN_11: return MA_CHANNEL_AUX_11; + case kAudioChannelLabel_HOA_ACN_12: return MA_CHANNEL_AUX_12; + case kAudioChannelLabel_HOA_ACN_13: return MA_CHANNEL_AUX_13; + case kAudioChannelLabel_HOA_ACN_14: return MA_CHANNEL_AUX_14; + case kAudioChannelLabel_HOA_ACN_15: return MA_CHANNEL_AUX_15; + case kAudioChannelLabel_HOA_ACN_65024: return MA_CHANNEL_NONE; + #endif + + default: return MA_CHANNEL_NONE; + } +} + +ma_result ma_format_from_AudioStreamBasicDescription(const AudioStreamBasicDescription* pDescription, ma_format* pFormatOut) +{ + ma_assert(pDescription != NULL); + ma_assert(pFormatOut != NULL); + + *pFormatOut = ma_format_unknown; // Safety. + + // There's a few things miniaudio doesn't support. + if (pDescription->mFormatID != kAudioFormatLinearPCM) { + return MA_FORMAT_NOT_SUPPORTED; + } + + // We don't support any non-packed formats that are aligned high. + if ((pDescription->mFormatFlags & kLinearPCMFormatFlagIsAlignedHigh) != 0) { + return MA_FORMAT_NOT_SUPPORTED; + } + + // Only supporting native-endian. + if ((ma_is_little_endian() && (pDescription->mFormatFlags & kAudioFormatFlagIsBigEndian) != 0) || (ma_is_big_endian() && (pDescription->mFormatFlags & kAudioFormatFlagIsBigEndian) == 0)) { + return MA_FORMAT_NOT_SUPPORTED; + } + + // We are not currently supporting non-interleaved formats (this will be added in a future version of miniaudio). + //if ((pDescription->mFormatFlags & kAudioFormatFlagIsNonInterleaved) != 0) { + // return MA_FORMAT_NOT_SUPPORTED; + //} + + if ((pDescription->mFormatFlags & kLinearPCMFormatFlagIsFloat) != 0) { + if (pDescription->mBitsPerChannel == 32) { + *pFormatOut = ma_format_f32; + return MA_SUCCESS; + } + } else { + if ((pDescription->mFormatFlags & kLinearPCMFormatFlagIsSignedInteger) != 0) { + if (pDescription->mBitsPerChannel == 16) { + *pFormatOut = ma_format_s16; + return MA_SUCCESS; + } else if (pDescription->mBitsPerChannel == 24) { + if (pDescription->mBytesPerFrame == (pDescription->mBitsPerChannel/8 * pDescription->mChannelsPerFrame)) { + *pFormatOut = ma_format_s24; + return MA_SUCCESS; + } else { + if (pDescription->mBytesPerFrame/pDescription->mChannelsPerFrame == sizeof(ma_int32)) { + // TODO: Implement ma_format_s24_32. + //*pFormatOut = ma_format_s24_32; + //return MA_SUCCESS; + return MA_FORMAT_NOT_SUPPORTED; + } + } + } else if (pDescription->mBitsPerChannel == 32) { + *pFormatOut = ma_format_s32; + return MA_SUCCESS; + } + } else { + if (pDescription->mBitsPerChannel == 8) { + *pFormatOut = ma_format_u8; + return MA_SUCCESS; + } + } + } + + // Getting here means the format is not supported. + return MA_FORMAT_NOT_SUPPORTED; +} + +ma_result ma_get_channel_map_from_AudioChannelLayout(AudioChannelLayout* pChannelLayout, ma_channel channelMap[MA_MAX_CHANNELS]) +{ + ma_assert(pChannelLayout != NULL); + + if (pChannelLayout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelDescriptions) { + for (UInt32 iChannel = 0; iChannel < pChannelLayout->mNumberChannelDescriptions; ++iChannel) { + channelMap[iChannel] = ma_channel_from_AudioChannelLabel(pChannelLayout->mChannelDescriptions[iChannel].mChannelLabel); + } + } else +#if 0 + if (pChannelLayout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelBitmap) { + // This is the same kind of system that's used by Windows audio APIs. + UInt32 iChannel = 0; + AudioChannelBitmap bitmap = pChannelLayout->mChannelBitmap; + for (UInt32 iBit = 0; iBit < 32; ++iBit) { + AudioChannelBitmap bit = bitmap & (1 << iBit); + if (bit != 0) { + channelMap[iChannel++] = ma_channel_from_AudioChannelBit(bit); + } + } + } else +#endif + { + // Need to use the tag to determine the channel map. For now I'm just assuming a default channel map, but later on this should + // be updated to determine the mapping based on the tag. + UInt32 channelCount = AudioChannelLayoutTag_GetNumberOfChannels(pChannelLayout->mChannelLayoutTag); + switch (pChannelLayout->mChannelLayoutTag) + { + case kAudioChannelLayoutTag_Mono: + case kAudioChannelLayoutTag_Stereo: + case kAudioChannelLayoutTag_StereoHeadphones: + case kAudioChannelLayoutTag_MatrixStereo: + case kAudioChannelLayoutTag_MidSide: + case kAudioChannelLayoutTag_XY: + case kAudioChannelLayoutTag_Binaural: + case kAudioChannelLayoutTag_Ambisonic_B_Format: + { + ma_get_standard_channel_map(ma_standard_channel_map_default, channelCount, channelMap); + } break; + + case kAudioChannelLayoutTag_Octagonal: + { + channelMap[7] = MA_CHANNEL_SIDE_RIGHT; + channelMap[6] = MA_CHANNEL_SIDE_LEFT; + } // Intentional fallthrough. + case kAudioChannelLayoutTag_Hexagonal: + { + channelMap[5] = MA_CHANNEL_BACK_CENTER; + } // Intentional fallthrough. + case kAudioChannelLayoutTag_Pentagonal: + { + channelMap[4] = MA_CHANNEL_FRONT_CENTER; + } // Intentional fallghrough. + case kAudioChannelLayoutTag_Quadraphonic: + { + channelMap[3] = MA_CHANNEL_BACK_RIGHT; + channelMap[2] = MA_CHANNEL_BACK_LEFT; + channelMap[1] = MA_CHANNEL_RIGHT; + channelMap[0] = MA_CHANNEL_LEFT; + } break; + + // TODO: Add support for more tags here. + + default: + { + ma_get_standard_channel_map(ma_standard_channel_map_default, channelCount, channelMap); + } break; + } + } + + return MA_SUCCESS; +} + + +#if defined(MA_APPLE_DESKTOP) +ma_result ma_get_device_object_ids__coreaudio(ma_context* pContext, UInt32* pDeviceCount, AudioObjectID** ppDeviceObjectIDs) // NOTE: Free the returned buffer with ma_free(). +{ + ma_assert(pContext != NULL); + ma_assert(pDeviceCount != NULL); + ma_assert(ppDeviceObjectIDs != NULL); + (void)pContext; + + // Safety. + *pDeviceCount = 0; + *ppDeviceObjectIDs = NULL; + + AudioObjectPropertyAddress propAddressDevices; + propAddressDevices.mSelector = kAudioHardwarePropertyDevices; + propAddressDevices.mScope = kAudioObjectPropertyScopeGlobal; + propAddressDevices.mElement = kAudioObjectPropertyElementMaster; + + UInt32 deviceObjectsDataSize; + OSStatus status = ((ma_AudioObjectGetPropertyDataSize_proc)pContext->coreaudio.AudioObjectGetPropertyDataSize)(kAudioObjectSystemObject, &propAddressDevices, 0, NULL, &deviceObjectsDataSize); + if (status != noErr) { + return ma_result_from_OSStatus(status); + } + + AudioObjectID* pDeviceObjectIDs = (AudioObjectID*)ma_malloc(deviceObjectsDataSize); + if (pDeviceObjectIDs == NULL) { + return MA_OUT_OF_MEMORY; + } + + status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(kAudioObjectSystemObject, &propAddressDevices, 0, NULL, &deviceObjectsDataSize, pDeviceObjectIDs); + if (status != noErr) { + ma_free(pDeviceObjectIDs); + return ma_result_from_OSStatus(status); + } + + *pDeviceCount = deviceObjectsDataSize / sizeof(AudioObjectID); + *ppDeviceObjectIDs = pDeviceObjectIDs; + return MA_SUCCESS; +} + +ma_result ma_get_AudioObject_uid_as_CFStringRef(ma_context* pContext, AudioObjectID objectID, CFStringRef* pUID) +{ + ma_assert(pContext != NULL); + + AudioObjectPropertyAddress propAddress; + propAddress.mSelector = kAudioDevicePropertyDeviceUID; + propAddress.mScope = kAudioObjectPropertyScopeGlobal; + propAddress.mElement = kAudioObjectPropertyElementMaster; + + UInt32 dataSize = sizeof(*pUID); + OSStatus status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(objectID, &propAddress, 0, NULL, &dataSize, pUID); + if (status != noErr) { + return ma_result_from_OSStatus(status); + } + + return MA_SUCCESS; +} + +ma_result ma_get_AudioObject_uid(ma_context* pContext, AudioObjectID objectID, size_t bufferSize, char* bufferOut) +{ + ma_assert(pContext != NULL); + + CFStringRef uid; + ma_result result = ma_get_AudioObject_uid_as_CFStringRef(pContext, objectID, &uid); + if (result != MA_SUCCESS) { + return result; + } + + if (!((ma_CFStringGetCString_proc)pContext->coreaudio.CFStringGetCString)(uid, bufferOut, bufferSize, kCFStringEncodingUTF8)) { + return MA_ERROR; + } + + return MA_SUCCESS; +} + +ma_result ma_get_AudioObject_name(ma_context* pContext, AudioObjectID objectID, size_t bufferSize, char* bufferOut) +{ + ma_assert(pContext != NULL); + + AudioObjectPropertyAddress propAddress; + propAddress.mSelector = kAudioDevicePropertyDeviceNameCFString; + propAddress.mScope = kAudioObjectPropertyScopeGlobal; + propAddress.mElement = kAudioObjectPropertyElementMaster; + + CFStringRef deviceName = NULL; + UInt32 dataSize = sizeof(deviceName); + OSStatus status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(objectID, &propAddress, 0, NULL, &dataSize, &deviceName); + if (status != noErr) { + return ma_result_from_OSStatus(status); + } + + if (!((ma_CFStringGetCString_proc)pContext->coreaudio.CFStringGetCString)(deviceName, bufferOut, bufferSize, kCFStringEncodingUTF8)) { + return MA_ERROR; + } + + return MA_SUCCESS; +} + +ma_bool32 ma_does_AudioObject_support_scope(ma_context* pContext, AudioObjectID deviceObjectID, AudioObjectPropertyScope scope) +{ + ma_assert(pContext != NULL); + + // To know whether or not a device is an input device we need ot look at the stream configuration. If it has an output channel it's a + // playback device. + AudioObjectPropertyAddress propAddress; + propAddress.mSelector = kAudioDevicePropertyStreamConfiguration; + propAddress.mScope = scope; + propAddress.mElement = kAudioObjectPropertyElementMaster; + + UInt32 dataSize; + OSStatus status = ((ma_AudioObjectGetPropertyDataSize_proc)pContext->coreaudio.AudioObjectGetPropertyDataSize)(deviceObjectID, &propAddress, 0, NULL, &dataSize); + if (status != noErr) { + return MA_FALSE; + } + + AudioBufferList* pBufferList = (AudioBufferList*)ma_malloc(dataSize); + if (pBufferList == NULL) { + return MA_FALSE; // Out of memory. + } + + status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(deviceObjectID, &propAddress, 0, NULL, &dataSize, pBufferList); + if (status != noErr) { + ma_free(pBufferList); + return MA_FALSE; + } + + ma_bool32 isSupported = MA_FALSE; + if (pBufferList->mNumberBuffers > 0) { + isSupported = MA_TRUE; + } + + ma_free(pBufferList); + return isSupported; +} + +ma_bool32 ma_does_AudioObject_support_playback(ma_context* pContext, AudioObjectID deviceObjectID) +{ + return ma_does_AudioObject_support_scope(pContext, deviceObjectID, kAudioObjectPropertyScopeOutput); +} + +ma_bool32 ma_does_AudioObject_support_capture(ma_context* pContext, AudioObjectID deviceObjectID) +{ + return ma_does_AudioObject_support_scope(pContext, deviceObjectID, kAudioObjectPropertyScopeInput); +} + + +ma_result ma_get_AudioObject_stream_descriptions(ma_context* pContext, AudioObjectID deviceObjectID, ma_device_type deviceType, UInt32* pDescriptionCount, AudioStreamRangedDescription** ppDescriptions) // NOTE: Free the returned pointer with ma_free(). +{ + ma_assert(pContext != NULL); + ma_assert(pDescriptionCount != NULL); + ma_assert(ppDescriptions != NULL); + + // TODO: Experiment with kAudioStreamPropertyAvailablePhysicalFormats instead of (or in addition to) kAudioStreamPropertyAvailableVirtualFormats. My + // MacBook Pro uses s24/32 format, however, which miniaudio does not currently support. + AudioObjectPropertyAddress propAddress; + propAddress.mSelector = kAudioStreamPropertyAvailableVirtualFormats; //kAudioStreamPropertyAvailablePhysicalFormats; + propAddress.mScope = (deviceType == ma_device_type_playback) ? kAudioObjectPropertyScopeOutput : kAudioObjectPropertyScopeInput; + propAddress.mElement = kAudioObjectPropertyElementMaster; + + UInt32 dataSize; + OSStatus status = ((ma_AudioObjectGetPropertyDataSize_proc)pContext->coreaudio.AudioObjectGetPropertyDataSize)(deviceObjectID, &propAddress, 0, NULL, &dataSize); + if (status != noErr) { + return ma_result_from_OSStatus(status); + } + + AudioStreamRangedDescription* pDescriptions = (AudioStreamRangedDescription*)ma_malloc(dataSize); + if (pDescriptions == NULL) { + return MA_OUT_OF_MEMORY; + } + + status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(deviceObjectID, &propAddress, 0, NULL, &dataSize, pDescriptions); + if (status != noErr) { + ma_free(pDescriptions); + return ma_result_from_OSStatus(status); + } + + *pDescriptionCount = dataSize / sizeof(*pDescriptions); + *ppDescriptions = pDescriptions; + return MA_SUCCESS; +} + + +ma_result ma_get_AudioObject_channel_layout(ma_context* pContext, AudioObjectID deviceObjectID, ma_device_type deviceType, AudioChannelLayout** ppChannelLayout) // NOTE: Free the returned pointer with ma_free(). +{ + ma_assert(pContext != NULL); + ma_assert(ppChannelLayout != NULL); + + *ppChannelLayout = NULL; // Safety. + + AudioObjectPropertyAddress propAddress; + propAddress.mSelector = kAudioDevicePropertyPreferredChannelLayout; + propAddress.mScope = (deviceType == ma_device_type_playback) ? kAudioObjectPropertyScopeOutput : kAudioObjectPropertyScopeInput; + propAddress.mElement = kAudioObjectPropertyElementMaster; + + UInt32 dataSize; + OSStatus status = ((ma_AudioObjectGetPropertyDataSize_proc)pContext->coreaudio.AudioObjectGetPropertyDataSize)(deviceObjectID, &propAddress, 0, NULL, &dataSize); + if (status != noErr) { + return ma_result_from_OSStatus(status); + } + + AudioChannelLayout* pChannelLayout = (AudioChannelLayout*)ma_malloc(dataSize); + if (pChannelLayout == NULL) { + return MA_OUT_OF_MEMORY; + } + + status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(deviceObjectID, &propAddress, 0, NULL, &dataSize, pChannelLayout); + if (status != noErr) { + ma_free(pChannelLayout); + return ma_result_from_OSStatus(status); + } + + *ppChannelLayout = pChannelLayout; + return MA_SUCCESS; +} + +ma_result ma_get_AudioObject_channel_count(ma_context* pContext, AudioObjectID deviceObjectID, ma_device_type deviceType, ma_uint32* pChannelCount) +{ + ma_assert(pContext != NULL); + ma_assert(pChannelCount != NULL); + + *pChannelCount = 0; // Safety. + + AudioChannelLayout* pChannelLayout; + ma_result result = ma_get_AudioObject_channel_layout(pContext, deviceObjectID, deviceType, &pChannelLayout); + if (result != MA_SUCCESS) { + return result; + } + + if (pChannelLayout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelDescriptions) { + *pChannelCount = pChannelLayout->mNumberChannelDescriptions; + } else if (pChannelLayout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelBitmap) { + *pChannelCount = ma_count_set_bits(pChannelLayout->mChannelBitmap); + } else { + *pChannelCount = AudioChannelLayoutTag_GetNumberOfChannels(pChannelLayout->mChannelLayoutTag); + } + + ma_free(pChannelLayout); + return MA_SUCCESS; +} + +ma_result ma_get_AudioObject_channel_map(ma_context* pContext, AudioObjectID deviceObjectID, ma_device_type deviceType, ma_channel channelMap[MA_MAX_CHANNELS]) +{ + ma_assert(pContext != NULL); + + AudioChannelLayout* pChannelLayout; + ma_result result = ma_get_AudioObject_channel_layout(pContext, deviceObjectID, deviceType, &pChannelLayout); + if (result != MA_SUCCESS) { + return result; // Rather than always failing here, would it be more robust to simply assume a default? + } + + result = ma_get_channel_map_from_AudioChannelLayout(pChannelLayout, channelMap); + if (result != MA_SUCCESS) { + ma_free(pChannelLayout); + return result; + } + + ma_free(pChannelLayout); + return result; +} + +ma_result ma_get_AudioObject_sample_rates(ma_context* pContext, AudioObjectID deviceObjectID, ma_device_type deviceType, UInt32* pSampleRateRangesCount, AudioValueRange** ppSampleRateRanges) // NOTE: Free the returned pointer with ma_free(). +{ + ma_assert(pContext != NULL); + ma_assert(pSampleRateRangesCount != NULL); + ma_assert(ppSampleRateRanges != NULL); + + // Safety. + *pSampleRateRangesCount = 0; + *ppSampleRateRanges = NULL; + + AudioObjectPropertyAddress propAddress; + propAddress.mSelector = kAudioDevicePropertyAvailableNominalSampleRates; + propAddress.mScope = (deviceType == ma_device_type_playback) ? kAudioObjectPropertyScopeOutput : kAudioObjectPropertyScopeInput; + propAddress.mElement = kAudioObjectPropertyElementMaster; + + UInt32 dataSize; + OSStatus status = ((ma_AudioObjectGetPropertyDataSize_proc)pContext->coreaudio.AudioObjectGetPropertyDataSize)(deviceObjectID, &propAddress, 0, NULL, &dataSize); + if (status != noErr) { + return ma_result_from_OSStatus(status); + } + + AudioValueRange* pSampleRateRanges = (AudioValueRange*)ma_malloc(dataSize); + if (pSampleRateRanges == NULL) { + return MA_OUT_OF_MEMORY; + } + + status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(deviceObjectID, &propAddress, 0, NULL, &dataSize, pSampleRateRanges); + if (status != noErr) { + ma_free(pSampleRateRanges); + return ma_result_from_OSStatus(status); + } + + *pSampleRateRangesCount = dataSize / sizeof(*pSampleRateRanges); + *ppSampleRateRanges = pSampleRateRanges; + return MA_SUCCESS; +} + +ma_result ma_get_AudioObject_get_closest_sample_rate(ma_context* pContext, AudioObjectID deviceObjectID, ma_device_type deviceType, ma_uint32 sampleRateIn, ma_uint32* pSampleRateOut) +{ + ma_assert(pContext != NULL); + ma_assert(pSampleRateOut != NULL); + + *pSampleRateOut = 0; // Safety. + + UInt32 sampleRateRangeCount; + AudioValueRange* pSampleRateRanges; + ma_result result = ma_get_AudioObject_sample_rates(pContext, deviceObjectID, deviceType, &sampleRateRangeCount, &pSampleRateRanges); + if (result != MA_SUCCESS) { + return result; + } + + if (sampleRateRangeCount == 0) { + ma_free(pSampleRateRanges); + return MA_ERROR; // Should never hit this case should we? + } + + if (sampleRateIn == 0) { + // Search in order of miniaudio's preferred priority. + for (UInt32 iMALSampleRate = 0; iMALSampleRate < ma_countof(g_maStandardSampleRatePriorities); ++iMALSampleRate) { + ma_uint32 malSampleRate = g_maStandardSampleRatePriorities[iMALSampleRate]; + for (UInt32 iCASampleRate = 0; iCASampleRate < sampleRateRangeCount; ++iCASampleRate) { + AudioValueRange caSampleRate = pSampleRateRanges[iCASampleRate]; + if (caSampleRate.mMinimum <= malSampleRate && caSampleRate.mMaximum >= malSampleRate) { + *pSampleRateOut = malSampleRate; + ma_free(pSampleRateRanges); + return MA_SUCCESS; + } + } + } + + // If we get here it means none of miniaudio's standard sample rates matched any of the supported sample rates from the device. In this + // case we just fall back to the first one reported by Core Audio. + ma_assert(sampleRateRangeCount > 0); + + *pSampleRateOut = pSampleRateRanges[0].mMinimum; + ma_free(pSampleRateRanges); + return MA_SUCCESS; + } else { + // Find the closest match to this sample rate. + UInt32 currentAbsoluteDifference = INT32_MAX; + UInt32 iCurrentClosestRange = (UInt32)-1; + for (UInt32 iRange = 0; iRange < sampleRateRangeCount; ++iRange) { + if (pSampleRateRanges[iRange].mMinimum <= sampleRateIn && pSampleRateRanges[iRange].mMaximum >= sampleRateIn) { + *pSampleRateOut = sampleRateIn; + ma_free(pSampleRateRanges); + return MA_SUCCESS; + } else { + UInt32 absoluteDifference; + if (pSampleRateRanges[iRange].mMinimum > sampleRateIn) { + absoluteDifference = pSampleRateRanges[iRange].mMinimum - sampleRateIn; + } else { + absoluteDifference = sampleRateIn - pSampleRateRanges[iRange].mMaximum; + } + + if (currentAbsoluteDifference > absoluteDifference) { + currentAbsoluteDifference = absoluteDifference; + iCurrentClosestRange = iRange; + } + } + } + + ma_assert(iCurrentClosestRange != (UInt32)-1); + + *pSampleRateOut = pSampleRateRanges[iCurrentClosestRange].mMinimum; + ma_free(pSampleRateRanges); + return MA_SUCCESS; + } + + // Should never get here, but it would mean we weren't able to find any suitable sample rates. + //ma_free(pSampleRateRanges); + //return MA_ERROR; +} + + +ma_result ma_get_AudioObject_closest_buffer_size_in_frames(ma_context* pContext, AudioObjectID deviceObjectID, ma_device_type deviceType, ma_uint32 bufferSizeInFramesIn, ma_uint32* pBufferSizeInFramesOut) +{ + ma_assert(pContext != NULL); + ma_assert(pBufferSizeInFramesOut != NULL); + + *pBufferSizeInFramesOut = 0; // Safety. + + AudioObjectPropertyAddress propAddress; + propAddress.mSelector = kAudioDevicePropertyBufferFrameSizeRange; + propAddress.mScope = (deviceType == ma_device_type_playback) ? kAudioObjectPropertyScopeOutput : kAudioObjectPropertyScopeInput; + propAddress.mElement = kAudioObjectPropertyElementMaster; + + AudioValueRange bufferSizeRange; + UInt32 dataSize = sizeof(bufferSizeRange); + OSStatus status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(deviceObjectID, &propAddress, 0, NULL, &dataSize, &bufferSizeRange); + if (status != noErr) { + return ma_result_from_OSStatus(status); + } + + // This is just a clamp. + if (bufferSizeInFramesIn < bufferSizeRange.mMinimum) { + *pBufferSizeInFramesOut = (ma_uint32)bufferSizeRange.mMinimum; + } else if (bufferSizeInFramesIn > bufferSizeRange.mMaximum) { + *pBufferSizeInFramesOut = (ma_uint32)bufferSizeRange.mMaximum; + } else { + *pBufferSizeInFramesOut = bufferSizeInFramesIn; + } + + return MA_SUCCESS; +} + +ma_result ma_set_AudioObject_buffer_size_in_frames(ma_context* pContext, AudioObjectID deviceObjectID, ma_device_type deviceType, ma_uint32* pBufferSizeInOut) +{ + ma_assert(pContext != NULL); + + ma_uint32 chosenBufferSizeInFrames; + ma_result result = ma_get_AudioObject_closest_buffer_size_in_frames(pContext, deviceObjectID, deviceType, *pBufferSizeInOut, &chosenBufferSizeInFrames); + if (result != MA_SUCCESS) { + return result; + } + + // Try setting the size of the buffer... If this fails we just use whatever is currently set. + AudioObjectPropertyAddress propAddress; + propAddress.mSelector = kAudioDevicePropertyBufferFrameSize; + propAddress.mScope = (deviceType == ma_device_type_playback) ? kAudioObjectPropertyScopeOutput : kAudioObjectPropertyScopeInput; + propAddress.mElement = kAudioObjectPropertyElementMaster; + + ((ma_AudioObjectSetPropertyData_proc)pContext->coreaudio.AudioObjectSetPropertyData)(deviceObjectID, &propAddress, 0, NULL, sizeof(chosenBufferSizeInFrames), &chosenBufferSizeInFrames); + + // Get the actual size of the buffer. + UInt32 dataSize = sizeof(*pBufferSizeInOut); + OSStatus status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(deviceObjectID, &propAddress, 0, NULL, &dataSize, &chosenBufferSizeInFrames); + if (status != noErr) { + return ma_result_from_OSStatus(status); + } + + *pBufferSizeInOut = chosenBufferSizeInFrames; + return MA_SUCCESS; +} + + +ma_result ma_find_AudioObjectID(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, AudioObjectID* pDeviceObjectID) +{ + ma_assert(pContext != NULL); + ma_assert(pDeviceObjectID != NULL); + + // Safety. + *pDeviceObjectID = 0; + + if (pDeviceID == NULL) { + // Default device. + AudioObjectPropertyAddress propAddressDefaultDevice; + propAddressDefaultDevice.mScope = kAudioObjectPropertyScopeGlobal; + propAddressDefaultDevice.mElement = kAudioObjectPropertyElementMaster; + if (deviceType == ma_device_type_playback) { + propAddressDefaultDevice.mSelector = kAudioHardwarePropertyDefaultOutputDevice; + } else { + propAddressDefaultDevice.mSelector = kAudioHardwarePropertyDefaultInputDevice; + } + + UInt32 defaultDeviceObjectIDSize = sizeof(AudioObjectID); + AudioObjectID defaultDeviceObjectID; + OSStatus status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(kAudioObjectSystemObject, &propAddressDefaultDevice, 0, NULL, &defaultDeviceObjectIDSize, &defaultDeviceObjectID); + if (status == noErr) { + *pDeviceObjectID = defaultDeviceObjectID; + return MA_SUCCESS; + } + } else { + // Explicit device. + UInt32 deviceCount; + AudioObjectID* pDeviceObjectIDs; + ma_result result = ma_get_device_object_ids__coreaudio(pContext, &deviceCount, &pDeviceObjectIDs); + if (result != MA_SUCCESS) { + return result; + } + + for (UInt32 iDevice = 0; iDevice < deviceCount; ++iDevice) { + AudioObjectID deviceObjectID = pDeviceObjectIDs[iDevice]; + + char uid[256]; + if (ma_get_AudioObject_uid(pContext, deviceObjectID, sizeof(uid), uid) != MA_SUCCESS) { + continue; + } + + if (deviceType == ma_device_type_playback) { + if (ma_does_AudioObject_support_playback(pContext, deviceObjectID)) { + if (strcmp(uid, pDeviceID->coreaudio) == 0) { + *pDeviceObjectID = deviceObjectID; + return MA_SUCCESS; + } + } + } else { + if (ma_does_AudioObject_support_capture(pContext, deviceObjectID)) { + if (strcmp(uid, pDeviceID->coreaudio) == 0) { + *pDeviceObjectID = deviceObjectID; + return MA_SUCCESS; + } + } + } + } + } + + // If we get here it means we couldn't find the device. + return MA_NO_DEVICE; +} + + +ma_result ma_find_best_format__coreaudio(ma_context* pContext, AudioObjectID deviceObjectID, ma_device_type deviceType, ma_format format, ma_uint32 channels, ma_uint32 sampleRate, ma_bool32 usingDefaultFormat, ma_bool32 usingDefaultChannels, ma_bool32 usingDefaultSampleRate, AudioStreamBasicDescription* pFormat) +{ + UInt32 deviceFormatDescriptionCount; + AudioStreamRangedDescription* pDeviceFormatDescriptions; + ma_result result = ma_get_AudioObject_stream_descriptions(pContext, deviceObjectID, deviceType, &deviceFormatDescriptionCount, &pDeviceFormatDescriptions); + if (result != MA_SUCCESS) { + return result; + } + + ma_uint32 desiredSampleRate = sampleRate; + if (usingDefaultSampleRate) { + // When using the device's default sample rate, we get the highest priority standard rate supported by the device. Otherwise + // we just use the pre-set rate. + for (ma_uint32 iStandardRate = 0; iStandardRate < ma_countof(g_maStandardSampleRatePriorities); ++iStandardRate) { + ma_uint32 standardRate = g_maStandardSampleRatePriorities[iStandardRate]; + + ma_bool32 foundRate = MA_FALSE; + for (UInt32 iDeviceRate = 0; iDeviceRate < deviceFormatDescriptionCount; ++iDeviceRate) { + ma_uint32 deviceRate = (ma_uint32)pDeviceFormatDescriptions[iDeviceRate].mFormat.mSampleRate; + + if (deviceRate == standardRate) { + desiredSampleRate = standardRate; + foundRate = MA_TRUE; + break; + } + } + + if (foundRate) { + break; + } + } + } + + ma_uint32 desiredChannelCount = channels; + if (usingDefaultChannels) { + ma_get_AudioObject_channel_count(pContext, deviceObjectID, deviceType, &desiredChannelCount); // <-- Not critical if this fails. + } + + ma_format desiredFormat = format; + if (usingDefaultFormat) { + desiredFormat = g_maFormatPriorities[0]; + } + + // If we get here it means we don't have an exact match to what the client is asking for. We'll need to find the closest one. The next + // loop will check for formats that have the same sample rate to what we're asking for. If there is, we prefer that one in all cases. + AudioStreamBasicDescription bestDeviceFormatSoFar; + ma_zero_object(&bestDeviceFormatSoFar); + + ma_bool32 hasSupportedFormat = MA_FALSE; + for (UInt32 iFormat = 0; iFormat < deviceFormatDescriptionCount; ++iFormat) { + ma_format format; + ma_result formatResult = ma_format_from_AudioStreamBasicDescription(&pDeviceFormatDescriptions[iFormat].mFormat, &format); + if (formatResult == MA_SUCCESS && format != ma_format_unknown) { + hasSupportedFormat = MA_TRUE; + bestDeviceFormatSoFar = pDeviceFormatDescriptions[iFormat].mFormat; + break; + } + } + + if (!hasSupportedFormat) { + return MA_FORMAT_NOT_SUPPORTED; + } + + + for (UInt32 iFormat = 0; iFormat < deviceFormatDescriptionCount; ++iFormat) { + AudioStreamBasicDescription thisDeviceFormat = pDeviceFormatDescriptions[iFormat].mFormat; + + // If the format is not supported by miniaudio we need to skip this one entirely. + ma_format thisSampleFormat; + ma_result formatResult = ma_format_from_AudioStreamBasicDescription(&pDeviceFormatDescriptions[iFormat].mFormat, &thisSampleFormat); + if (formatResult != MA_SUCCESS || thisSampleFormat == ma_format_unknown) { + continue; // The format is not supported by miniaudio. Skip. + } + + ma_format bestSampleFormatSoFar; + ma_format_from_AudioStreamBasicDescription(&bestDeviceFormatSoFar, &bestSampleFormatSoFar); + + + // Getting here means the format is supported by miniaudio which makes this format a candidate. + if (thisDeviceFormat.mSampleRate != desiredSampleRate) { + // The sample rate does not match, but this format could still be usable, although it's a very low priority. If the best format + // so far has an equal sample rate we can just ignore this one. + if (bestDeviceFormatSoFar.mSampleRate == desiredSampleRate) { + continue; // The best sample rate so far has the same sample rate as what we requested which means it's still the best so far. Skip this format. + } else { + // In this case, neither the best format so far nor this one have the same sample rate. Check the channel count next. + if (thisDeviceFormat.mChannelsPerFrame != desiredChannelCount) { + // This format has a different sample rate _and_ a different channel count. + if (bestDeviceFormatSoFar.mChannelsPerFrame == desiredChannelCount) { + continue; // No change to the best format. + } else { + // Both this format and the best so far have different sample rates and different channel counts. Whichever has the + // best format is the new best. + if (ma_get_format_priority_index(thisSampleFormat) < ma_get_format_priority_index(bestSampleFormatSoFar)) { + bestDeviceFormatSoFar = thisDeviceFormat; + continue; + } else { + continue; // No change to the best format. + } + } + } else { + // This format has a different sample rate but the desired channel count. + if (bestDeviceFormatSoFar.mChannelsPerFrame == desiredChannelCount) { + // Both this format and the best so far have the desired channel count. Whichever has the best format is the new best. + if (ma_get_format_priority_index(thisSampleFormat) < ma_get_format_priority_index(bestSampleFormatSoFar)) { + bestDeviceFormatSoFar = thisDeviceFormat; + continue; + } else { + continue; // No change to the best format for now. + } + } else { + // This format has the desired channel count, but the best so far does not. We have a new best. + bestDeviceFormatSoFar = thisDeviceFormat; + continue; + } + } + } + } else { + // The sample rates match which makes this format a very high priority contender. If the best format so far has a different + // sample rate it needs to be replaced with this one. + if (bestDeviceFormatSoFar.mSampleRate != desiredSampleRate) { + bestDeviceFormatSoFar = thisDeviceFormat; + continue; + } else { + // In this case both this format and the best format so far have the same sample rate. Check the channel count next. + if (thisDeviceFormat.mChannelsPerFrame == desiredChannelCount) { + // In this case this format has the same channel count as what the client is requesting. If the best format so far has + // a different count, this one becomes the new best. + if (bestDeviceFormatSoFar.mChannelsPerFrame != desiredChannelCount) { + bestDeviceFormatSoFar = thisDeviceFormat; + continue; + } else { + // In this case both this format and the best so far have the ideal sample rate and channel count. Check the format. + if (thisSampleFormat == desiredFormat) { + bestDeviceFormatSoFar = thisDeviceFormat; + break; // Found the exact match. + } else { + // The formats are different. The new best format is the one with the highest priority format according to miniaudio. + if (ma_get_format_priority_index(thisSampleFormat) < ma_get_format_priority_index(bestSampleFormatSoFar)) { + bestDeviceFormatSoFar = thisDeviceFormat; + continue; + } else { + continue; // No change to the best format for now. + } + } + } + } else { + // In this case the channel count is different to what the client has requested. If the best so far has the same channel + // count as the requested count then it remains the best. + if (bestDeviceFormatSoFar.mChannelsPerFrame == desiredChannelCount) { + continue; + } else { + // This is the case where both have the same sample rate (good) but different channel counts. Right now both have about + // the same priority, but we need to compare the format now. + if (thisSampleFormat == bestSampleFormatSoFar) { + if (ma_get_format_priority_index(thisSampleFormat) < ma_get_format_priority_index(bestSampleFormatSoFar)) { + bestDeviceFormatSoFar = thisDeviceFormat; + continue; + } else { + continue; // No change to the best format for now. + } + } + } + } + } + } + } + + *pFormat = bestDeviceFormatSoFar; + return MA_SUCCESS; +} +#endif + +ma_result ma_get_AudioUnit_channel_map(ma_context* pContext, AudioUnit audioUnit, ma_device_type deviceType, ma_channel channelMap[MA_MAX_CHANNELS]) +{ + ma_assert(pContext != NULL); + + AudioUnitScope deviceScope; + AudioUnitElement deviceBus; + if (deviceType == ma_device_type_playback) { + deviceScope = kAudioUnitScope_Output; + deviceBus = MA_COREAUDIO_OUTPUT_BUS; + } else { + deviceScope = kAudioUnitScope_Input; + deviceBus = MA_COREAUDIO_INPUT_BUS; + } + + UInt32 channelLayoutSize; + OSStatus status = ((ma_AudioUnitGetPropertyInfo_proc)pContext->coreaudio.AudioUnitGetPropertyInfo)(audioUnit, kAudioUnitProperty_AudioChannelLayout, deviceScope, deviceBus, &channelLayoutSize, NULL); + if (status != noErr) { + return ma_result_from_OSStatus(status); + } + + AudioChannelLayout* pChannelLayout = (AudioChannelLayout*)ma_malloc(channelLayoutSize); + if (pChannelLayout == NULL) { + return MA_OUT_OF_MEMORY; + } + + status = ((ma_AudioUnitGetProperty_proc)pContext->coreaudio.AudioUnitGetProperty)(audioUnit, kAudioUnitProperty_AudioChannelLayout, deviceScope, deviceBus, pChannelLayout, &channelLayoutSize); + if (status != noErr) { + ma_free(pChannelLayout); + return ma_result_from_OSStatus(status); + } + + ma_result result = ma_get_channel_map_from_AudioChannelLayout(pChannelLayout, channelMap); + if (result != MA_SUCCESS) { + ma_free(pChannelLayout); + return result; + } + + ma_free(pChannelLayout); + return MA_SUCCESS; +} + +ma_bool32 ma_context_is_device_id_equal__coreaudio(ma_context* pContext, const ma_device_id* pID0, const ma_device_id* pID1) +{ + ma_assert(pContext != NULL); + ma_assert(pID0 != NULL); + ma_assert(pID1 != NULL); + (void)pContext; + + return strcmp(pID0->coreaudio, pID1->coreaudio) == 0; +} + +ma_result ma_context_enumerate_devices__coreaudio(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData) +{ + ma_assert(pContext != NULL); + ma_assert(callback != NULL); + +#if defined(MA_APPLE_DESKTOP) + UInt32 deviceCount; + AudioObjectID* pDeviceObjectIDs; + ma_result result = ma_get_device_object_ids__coreaudio(pContext, &deviceCount, &pDeviceObjectIDs); + if (result != MA_SUCCESS) { + return result; + } + + for (UInt32 iDevice = 0; iDevice < deviceCount; ++iDevice) { + AudioObjectID deviceObjectID = pDeviceObjectIDs[iDevice]; + + ma_device_info info; + ma_zero_object(&info); + if (ma_get_AudioObject_uid(pContext, deviceObjectID, sizeof(info.id.coreaudio), info.id.coreaudio) != MA_SUCCESS) { + continue; + } + if (ma_get_AudioObject_name(pContext, deviceObjectID, sizeof(info.name), info.name) != MA_SUCCESS) { + continue; + } + + if (ma_does_AudioObject_support_playback(pContext, deviceObjectID)) { + if (!callback(pContext, ma_device_type_playback, &info, pUserData)) { + break; + } + } + if (ma_does_AudioObject_support_capture(pContext, deviceObjectID)) { + if (!callback(pContext, ma_device_type_capture, &info, pUserData)) { + break; + } + } + } + + ma_free(pDeviceObjectIDs); +#else + // Only supporting default devices on non-Desktop platforms. + ma_device_info info; + + ma_zero_object(&info); + ma_strncpy_s(info.name, sizeof(info.name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); + if (!callback(pContext, ma_device_type_playback, &info, pUserData)) { + return MA_SUCCESS; + } + + ma_zero_object(&info); + ma_strncpy_s(info.name, sizeof(info.name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); + if (!callback(pContext, ma_device_type_capture, &info, pUserData)) { + return MA_SUCCESS; + } +#endif + + return MA_SUCCESS; +} + +ma_result ma_context_get_device_info__coreaudio(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_share_mode shareMode, ma_device_info* pDeviceInfo) +{ + ma_assert(pContext != NULL); + (void)pDeviceInfo; + + /* No exclusive mode with the Core Audio backend for now. */ + if (shareMode == ma_share_mode_exclusive) { + return MA_SHARE_MODE_NOT_SUPPORTED; + } + +#if defined(MA_APPLE_DESKTOP) + // Desktop + // ======= + AudioObjectID deviceObjectID; + ma_result result = ma_find_AudioObjectID(pContext, deviceType, pDeviceID, &deviceObjectID); + if (result != MA_SUCCESS) { + return result; + } + + result = ma_get_AudioObject_uid(pContext, deviceObjectID, sizeof(pDeviceInfo->id.coreaudio), pDeviceInfo->id.coreaudio); + if (result != MA_SUCCESS) { + return result; + } + + result = ma_get_AudioObject_name(pContext, deviceObjectID, sizeof(pDeviceInfo->name), pDeviceInfo->name); + if (result != MA_SUCCESS) { + return result; + } + + // Formats. + UInt32 streamDescriptionCount; + AudioStreamRangedDescription* pStreamDescriptions; + result = ma_get_AudioObject_stream_descriptions(pContext, deviceObjectID, deviceType, &streamDescriptionCount, &pStreamDescriptions); + if (result != MA_SUCCESS) { + return result; + } + + for (UInt32 iStreamDescription = 0; iStreamDescription < streamDescriptionCount; ++iStreamDescription) { + ma_format format; + result = ma_format_from_AudioStreamBasicDescription(&pStreamDescriptions[iStreamDescription].mFormat, &format); + if (result != MA_SUCCESS) { + continue; + } + + ma_assert(format != ma_format_unknown); + + // Make sure the format isn't already in the output list. + ma_bool32 exists = MA_FALSE; + for (ma_uint32 iOutputFormat = 0; iOutputFormat < pDeviceInfo->formatCount; ++iOutputFormat) { + if (pDeviceInfo->formats[iOutputFormat] == format) { + exists = MA_TRUE; + break; + } + } + + if (!exists) { + pDeviceInfo->formats[pDeviceInfo->formatCount++] = format; + } + } + + ma_free(pStreamDescriptions); + + + // Channels. + result = ma_get_AudioObject_channel_count(pContext, deviceObjectID, deviceType, &pDeviceInfo->minChannels); + if (result != MA_SUCCESS) { + return result; + } + pDeviceInfo->maxChannels = pDeviceInfo->minChannels; + + + // Sample rates. + UInt32 sampleRateRangeCount; + AudioValueRange* pSampleRateRanges; + result = ma_get_AudioObject_sample_rates(pContext, deviceObjectID, deviceType, &sampleRateRangeCount, &pSampleRateRanges); + if (result != MA_SUCCESS) { + return result; + } + + if (sampleRateRangeCount > 0) { + pDeviceInfo->minSampleRate = UINT32_MAX; + pDeviceInfo->maxSampleRate = 0; + for (UInt32 iSampleRate = 0; iSampleRate < sampleRateRangeCount; ++iSampleRate) { + if (pDeviceInfo->minSampleRate > pSampleRateRanges[iSampleRate].mMinimum) { + pDeviceInfo->minSampleRate = pSampleRateRanges[iSampleRate].mMinimum; + } + if (pDeviceInfo->maxSampleRate < pSampleRateRanges[iSampleRate].mMaximum) { + pDeviceInfo->maxSampleRate = pSampleRateRanges[iSampleRate].mMaximum; + } + } + } +#else + // Mobile + // ====== + if (deviceType == ma_device_type_playback) { + ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); + } else { + ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); + } + + // Retrieving device information is more annoying on mobile than desktop. For simplicity I'm locking this down to whatever format is + // reported on a temporary I/O unit. The problem, however, is that this doesn't return a value for the sample rate which we need to + // retrieve from the AVAudioSession shared instance. + AudioComponentDescription desc; + desc.componentType = kAudioUnitType_Output; + desc.componentSubType = kAudioUnitSubType_RemoteIO; + desc.componentManufacturer = kAudioUnitManufacturer_Apple; + desc.componentFlags = 0; + desc.componentFlagsMask = 0; + + AudioComponent component = ((ma_AudioComponentFindNext_proc)pContext->coreaudio.AudioComponentFindNext)(NULL, &desc); + if (component == NULL) { + return MA_FAILED_TO_INIT_BACKEND; + } + + AudioUnit audioUnit; + OSStatus status = ((ma_AudioComponentInstanceNew_proc)pContext->coreaudio.AudioComponentInstanceNew)(component, &audioUnit); + if (status != noErr) { + return ma_result_from_OSStatus(status); + } + + AudioUnitScope formatScope = (deviceType == ma_device_type_playback) ? kAudioUnitScope_Input : kAudioUnitScope_Output; + AudioUnitElement formatElement = (deviceType == ma_device_type_playback) ? MA_COREAUDIO_OUTPUT_BUS : MA_COREAUDIO_INPUT_BUS; + + AudioStreamBasicDescription bestFormat; + UInt32 propSize = sizeof(bestFormat); + status = ((ma_AudioUnitGetProperty_proc)pContext->coreaudio.AudioUnitGetProperty)(audioUnit, kAudioUnitProperty_StreamFormat, formatScope, formatElement, &bestFormat, &propSize); + if (status != noErr) { + ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(audioUnit); + return ma_result_from_OSStatus(status); + } + + ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(audioUnit); + audioUnit = NULL; + + + pDeviceInfo->minChannels = bestFormat.mChannelsPerFrame; + pDeviceInfo->maxChannels = bestFormat.mChannelsPerFrame; + + pDeviceInfo->formatCount = 1; + ma_result result = ma_format_from_AudioStreamBasicDescription(&bestFormat, &pDeviceInfo->formats[0]); + if (result != MA_SUCCESS) { + return result; + } + + // It looks like Apple are wanting to push the whole AVAudioSession thing. Thus, we need to use that to determine device settings. To do + // this we just get the shared instance and inspect. + @autoreleasepool { + AVAudioSession* pAudioSession = [AVAudioSession sharedInstance]; + ma_assert(pAudioSession != NULL); + + pDeviceInfo->minSampleRate = (ma_uint32)pAudioSession.sampleRate; + pDeviceInfo->maxSampleRate = pDeviceInfo->minSampleRate; + } +#endif + + return MA_SUCCESS; +} + + +void ma_device_uninit__coreaudio(ma_device* pDevice) +{ + ma_assert(pDevice != NULL); + ma_assert(ma_device__get_state(pDevice) == MA_STATE_UNINITIALIZED); + + if (pDevice->coreaudio.audioUnitCapture != NULL) { + ((ma_AudioComponentInstanceDispose_proc)pDevice->pContext->coreaudio.AudioComponentInstanceDispose)((AudioUnit)pDevice->coreaudio.audioUnitCapture); + } + if (pDevice->coreaudio.audioUnitPlayback != NULL) { + ((ma_AudioComponentInstanceDispose_proc)pDevice->pContext->coreaudio.AudioComponentInstanceDispose)((AudioUnit)pDevice->coreaudio.audioUnitPlayback); + } + + if (pDevice->coreaudio.pAudioBufferList) { + ma_free(pDevice->coreaudio.pAudioBufferList); + } + + if (pDevice->type == ma_device_type_duplex) { + ma_pcm_rb_uninit(&pDevice->coreaudio.duplexRB); + } +} + + +OSStatus ma_on_output__coreaudio(void* pUserData, AudioUnitRenderActionFlags* pActionFlags, const AudioTimeStamp* pTimeStamp, UInt32 busNumber, UInt32 frameCount, AudioBufferList* pBufferList) +{ + (void)pActionFlags; + (void)pTimeStamp; + (void)busNumber; + + ma_device* pDevice = (ma_device*)pUserData; + ma_assert(pDevice != NULL); + +#if defined(MA_DEBUG_OUTPUT) + printf("INFO: Output Callback: busNumber=%d, frameCount=%d, mNumberBuffers=%d\n", busNumber, frameCount, pBufferList->mNumberBuffers); +#endif + + // We need to check whether or not we are outputting interleaved or non-interleaved samples. The + // way we do this is slightly different for each type. + ma_stream_layout layout = ma_stream_layout_interleaved; + if (pBufferList->mBuffers[0].mNumberChannels != pDevice->playback.internalChannels) { + layout = ma_stream_layout_deinterleaved; + } + + if (layout == ma_stream_layout_interleaved) { + // For now we can assume everything is interleaved. + for (UInt32 iBuffer = 0; iBuffer < pBufferList->mNumberBuffers; ++iBuffer) { + if (pBufferList->mBuffers[iBuffer].mNumberChannels == pDevice->playback.internalChannels) { + ma_uint32 frameCountForThisBuffer = pBufferList->mBuffers[iBuffer].mDataByteSize / ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels); + if (frameCountForThisBuffer > 0) { + if (pDevice->type == ma_device_type_duplex) { + ma_device__handle_duplex_callback_playback(pDevice, frameCountForThisBuffer, pBufferList->mBuffers[iBuffer].mData, &pDevice->coreaudio.duplexRB); + } else { + ma_device__read_frames_from_client(pDevice, frameCountForThisBuffer, pBufferList->mBuffers[iBuffer].mData); + } + } + + #if defined(MA_DEBUG_OUTPUT) + printf(" frameCount=%d, mNumberChannels=%d, mDataByteSize=%d\n", frameCount, pBufferList->mBuffers[iBuffer].mNumberChannels, pBufferList->mBuffers[iBuffer].mDataByteSize); + #endif + } else { + // This case is where the number of channels in the output buffer do not match our internal channels. It could mean that it's + // not interleaved, in which case we can't handle right now since miniaudio does not yet support non-interleaved streams. We just + // output silence here. + ma_zero_memory(pBufferList->mBuffers[iBuffer].mData, pBufferList->mBuffers[iBuffer].mDataByteSize); + + #if defined(MA_DEBUG_OUTPUT) + printf(" WARNING: Outputting silence. frameCount=%d, mNumberChannels=%d, mDataByteSize=%d\n", frameCount, pBufferList->mBuffers[iBuffer].mNumberChannels, pBufferList->mBuffers[iBuffer].mDataByteSize); + #endif + } + } + } else { + // This is the deinterleaved case. We need to update each buffer in groups of internalChannels. This + // assumes each buffer is the same size. + ma_uint8 tempBuffer[4096]; + for (UInt32 iBuffer = 0; iBuffer < pBufferList->mNumberBuffers; iBuffer += pDevice->playback.internalChannels) { + ma_uint32 frameCountPerBuffer = pBufferList->mBuffers[iBuffer].mDataByteSize / ma_get_bytes_per_sample(pDevice->playback.internalFormat); + + ma_uint32 framesRemaining = frameCountPerBuffer; + while (framesRemaining > 0) { + ma_uint32 framesToRead = sizeof(tempBuffer) / ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels); + if (framesToRead > framesRemaining) { + framesToRead = framesRemaining; + } + + if (pDevice->type == ma_device_type_duplex) { + ma_device__handle_duplex_callback_playback(pDevice, framesToRead, tempBuffer, &pDevice->coreaudio.duplexRB); + } else { + ma_device__read_frames_from_client(pDevice, framesToRead, tempBuffer); + } + + void* ppDeinterleavedBuffers[MA_MAX_CHANNELS]; + for (ma_uint32 iChannel = 0; iChannel < pDevice->playback.internalChannels; ++iChannel) { + ppDeinterleavedBuffers[iChannel] = (void*)ma_offset_ptr(pBufferList->mBuffers[iBuffer].mData, (frameCountPerBuffer - framesRemaining) * ma_get_bytes_per_sample(pDevice->playback.internalFormat)); + } + + ma_deinterleave_pcm_frames(pDevice->playback.internalFormat, pDevice->playback.internalChannels, framesToRead, tempBuffer, ppDeinterleavedBuffers); + + framesRemaining -= framesToRead; + } + } + } + + return noErr; +} + +OSStatus ma_on_input__coreaudio(void* pUserData, AudioUnitRenderActionFlags* pActionFlags, const AudioTimeStamp* pTimeStamp, UInt32 busNumber, UInt32 frameCount, AudioBufferList* pUnusedBufferList) +{ + (void)pActionFlags; + (void)pTimeStamp; + (void)busNumber; + (void)frameCount; + (void)pUnusedBufferList; + + ma_device* pDevice = (ma_device*)pUserData; + ma_assert(pDevice != NULL); + + AudioBufferList* pRenderedBufferList = (AudioBufferList*)pDevice->coreaudio.pAudioBufferList; + ma_assert(pRenderedBufferList); + + // We need to check whether or not we are outputting interleaved or non-interleaved samples. The + // way we do this is slightly different for each type. + ma_stream_layout layout = ma_stream_layout_interleaved; + if (pRenderedBufferList->mBuffers[0].mNumberChannels != pDevice->capture.internalChannels) { + layout = ma_stream_layout_deinterleaved; + } + +#if defined(MA_DEBUG_OUTPUT) + printf("INFO: Input Callback: busNumber=%d, frameCount=%d, mNumberBuffers=%d\n", busNumber, frameCount, pRenderedBufferList->mNumberBuffers); +#endif + + OSStatus status = ((ma_AudioUnitRender_proc)pDevice->pContext->coreaudio.AudioUnitRender)((AudioUnit)pDevice->coreaudio.audioUnitCapture, pActionFlags, pTimeStamp, busNumber, frameCount, pRenderedBufferList); + if (status != noErr) { + #if defined(MA_DEBUG_OUTPUT) + printf(" ERROR: AudioUnitRender() failed with %d\n", status); + #endif + return status; + } + + if (layout == ma_stream_layout_interleaved) { + for (UInt32 iBuffer = 0; iBuffer < pRenderedBufferList->mNumberBuffers; ++iBuffer) { + if (pRenderedBufferList->mBuffers[iBuffer].mNumberChannels == pDevice->capture.internalChannels) { + if (pDevice->type == ma_device_type_duplex) { + ma_device__handle_duplex_callback_capture(pDevice, frameCount, pRenderedBufferList->mBuffers[iBuffer].mData, &pDevice->coreaudio.duplexRB); + } else { + ma_device__send_frames_to_client(pDevice, frameCount, pRenderedBufferList->mBuffers[iBuffer].mData); + } + #if defined(MA_DEBUG_OUTPUT) + printf(" mDataByteSize=%d\n", pRenderedBufferList->mBuffers[iBuffer].mDataByteSize); + #endif + } else { + // This case is where the number of channels in the output buffer do not match our internal channels. It could mean that it's + // not interleaved, in which case we can't handle right now since miniaudio does not yet support non-interleaved streams. + + ma_uint8 silentBuffer[4096]; + ma_zero_memory(silentBuffer, sizeof(silentBuffer)); + + ma_uint32 framesRemaining = frameCount; + while (framesRemaining > 0) { + ma_uint32 framesToSend = sizeof(silentBuffer) / ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels); + if (framesToSend > framesRemaining) { + framesToSend = framesRemaining; + } + + if (pDevice->type == ma_device_type_duplex) { + ma_device__handle_duplex_callback_capture(pDevice, framesToSend, silentBuffer, &pDevice->coreaudio.duplexRB); + } else { + ma_device__send_frames_to_client(pDevice, framesToSend, silentBuffer); + } + + framesRemaining -= framesToSend; + } + + #if defined(MA_DEBUG_OUTPUT) + printf(" WARNING: Outputting silence. frameCount=%d, mNumberChannels=%d, mDataByteSize=%d\n", frameCount, pRenderedBufferList->mBuffers[iBuffer].mNumberChannels, pRenderedBufferList->mBuffers[iBuffer].mDataByteSize); + #endif + } + } + } else { + // This is the deinterleaved case. We need to interleave the audio data before sending it to the client. This + // assumes each buffer is the same size. + ma_uint8 tempBuffer[4096]; + for (UInt32 iBuffer = 0; iBuffer < pRenderedBufferList->mNumberBuffers; iBuffer += pDevice->capture.internalChannels) { + ma_uint32 framesRemaining = frameCount; + while (framesRemaining > 0) { + ma_uint32 framesToSend = sizeof(tempBuffer) / ma_get_bytes_per_sample(pDevice->capture.internalFormat); + if (framesToSend > framesRemaining) { + framesToSend = framesRemaining; + } + + void* ppDeinterleavedBuffers[MA_MAX_CHANNELS]; + for (ma_uint32 iChannel = 0; iChannel < pDevice->capture.internalChannels; ++iChannel) { + ppDeinterleavedBuffers[iChannel] = (void*)ma_offset_ptr(pRenderedBufferList->mBuffers[iBuffer].mData, (frameCount - framesRemaining) * ma_get_bytes_per_sample(pDevice->capture.internalFormat)); + } + + ma_interleave_pcm_frames(pDevice->capture.internalFormat, pDevice->capture.internalChannels, framesToSend, (const void**)ppDeinterleavedBuffers, tempBuffer); + + if (pDevice->type == ma_device_type_duplex) { + ma_device__handle_duplex_callback_capture(pDevice, framesToSend, tempBuffer, &pDevice->coreaudio.duplexRB); + } else { + ma_device__send_frames_to_client(pDevice, framesToSend, tempBuffer); + } + + framesRemaining -= framesToSend; + } + } + } + + return noErr; +} + +void on_start_stop__coreaudio(void* pUserData, AudioUnit audioUnit, AudioUnitPropertyID propertyID, AudioUnitScope scope, AudioUnitElement element) +{ + (void)propertyID; + + ma_device* pDevice = (ma_device*)pUserData; + ma_assert(pDevice != NULL); + + // There's been a report of a deadlock here when triggered by ma_device_uninit(). It looks like + // AudioUnitGetProprty (called below) and AudioComponentInstanceDispose (called in ma_device_uninit) + // can try waiting on the same lock. I'm going to try working around this by not calling any Core + // Audio APIs in the callback when the device has been stopped or uninitialized. + if (ma_device__get_state(pDevice) == MA_STATE_UNINITIALIZED || ma_device__get_state(pDevice) == MA_STATE_STOPPING || ma_device__get_state(pDevice) == MA_STATE_STOPPED) { + ma_stop_proc onStop = pDevice->onStop; + if (onStop) { + onStop(pDevice); + } + + ma_event_signal(&pDevice->coreaudio.stopEvent); + } else { + UInt32 isRunning; + UInt32 isRunningSize = sizeof(isRunning); + OSStatus status = ((ma_AudioUnitGetProperty_proc)pDevice->pContext->coreaudio.AudioUnitGetProperty)(audioUnit, kAudioOutputUnitProperty_IsRunning, scope, element, &isRunning, &isRunningSize); + if (status != noErr) { + return; // Don't really know what to do in this case... just ignore it, I suppose... + } + + if (!isRunning) { + // The stop event is a bit annoying in Core Audio because it will be called when we automatically switch the default device. Some scenarios to consider: + // + // 1) When the device is unplugged, this will be called _before_ the default device change notification. + // 2) When the device is changed via the default device change notification, this will be called _after_ the switch. + // + // For case #1, we just check if there's a new default device available. If so, we just ignore the stop event. For case #2 we check a flag. + if (((audioUnit == pDevice->coreaudio.audioUnitPlayback) && pDevice->coreaudio.isDefaultPlaybackDevice) || + ((audioUnit == pDevice->coreaudio.audioUnitCapture) && pDevice->coreaudio.isDefaultCaptureDevice)) { + // It looks like the device is switching through an external event, such as the user unplugging the device or changing the default device + // via the operating system's sound settings. If we're re-initializing the device, we just terminate because we want the stopping of the + // device to be seamless to the client (we don't want them receiving the onStop event and thinking that the device has stopped when it + // hasn't!). + if (((audioUnit == pDevice->coreaudio.audioUnitPlayback) && pDevice->coreaudio.isSwitchingPlaybackDevice) || + ((audioUnit == pDevice->coreaudio.audioUnitCapture) && pDevice->coreaudio.isSwitchingCaptureDevice)) { + return; + } + + // Getting here means the device is not reinitializing which means it may have been unplugged. From what I can see, it looks like Core Audio + // will try switching to the new default device seamlessly. We need to somehow find a way to determine whether or not Core Audio will most + // likely be successful in switching to the new device. + // + // TODO: Try to predict if Core Audio will switch devices. If not, the onStop callback needs to be posted. + return; + } + + // Getting here means we need to stop the device. + ma_stop_proc onStop = pDevice->onStop; + if (onStop) { + onStop(pDevice); + } + } + } +} + +#if defined(MA_APPLE_DESKTOP) +OSStatus ma_default_device_changed__coreaudio(AudioObjectID objectID, UInt32 addressCount, const AudioObjectPropertyAddress* pAddresses, void* pUserData) +{ + (void)objectID; + + ma_device* pDevice = (ma_device*)pUserData; + ma_assert(pDevice != NULL); + + // Not sure if I really need to check this, but it makes me feel better. + if (addressCount == 0) { + return noErr; + } + + if (pAddresses[0].mSelector == kAudioHardwarePropertyDefaultOutputDevice) { + pDevice->coreaudio.isSwitchingPlaybackDevice = MA_TRUE; + ma_result reinitResult = ma_device_reinit_internal__coreaudio(pDevice, ma_device_type_playback, MA_TRUE); + pDevice->coreaudio.isSwitchingPlaybackDevice = MA_FALSE; + + if (reinitResult == MA_SUCCESS) { + ma_device__post_init_setup(pDevice, ma_device_type_playback); + + // Restart the device if required. If this fails we need to stop the device entirely. + if (ma_device__get_state(pDevice) == MA_STATE_STARTED) { + OSStatus status = ((ma_AudioOutputUnitStart_proc)pDevice->pContext->coreaudio.AudioOutputUnitStart)((AudioUnit)pDevice->coreaudio.audioUnitPlayback); + if (status != noErr) { + if (pDevice->type == ma_device_type_duplex) { + ((ma_AudioOutputUnitStop_proc)pDevice->pContext->coreaudio.AudioOutputUnitStop)((AudioUnit)pDevice->coreaudio.audioUnitCapture); + } + ma_device__set_state(pDevice, MA_STATE_STOPPED); + } + } + } + } + + if (pAddresses[0].mSelector == kAudioHardwarePropertyDefaultInputDevice) { + pDevice->coreaudio.isSwitchingPlaybackDevice = MA_TRUE; + ma_result reinitResult = ma_device_reinit_internal__coreaudio(pDevice, ma_device_type_capture, MA_TRUE); + pDevice->coreaudio.isSwitchingPlaybackDevice = MA_FALSE; + + if (reinitResult == MA_SUCCESS) { + ma_device__post_init_setup(pDevice, ma_device_type_capture); + + // Restart the device if required. If this fails we need to stop the device entirely. + if (ma_device__get_state(pDevice) == MA_STATE_STARTED) { + OSStatus status = ((ma_AudioOutputUnitStart_proc)pDevice->pContext->coreaudio.AudioOutputUnitStart)((AudioUnit)pDevice->coreaudio.audioUnitCapture); + if (status != noErr) { + if (pDevice->type == ma_device_type_duplex) { + ((ma_AudioOutputUnitStop_proc)pDevice->pContext->coreaudio.AudioOutputUnitStop)((AudioUnit)pDevice->coreaudio.audioUnitPlayback); + } + ma_device__set_state(pDevice, MA_STATE_STOPPED); + } + } + } + } + + return noErr; +} +#endif + +typedef struct +{ + // Input. + ma_format formatIn; + ma_uint32 channelsIn; + ma_uint32 sampleRateIn; + ma_channel channelMapIn[MA_MAX_CHANNELS]; + ma_uint32 bufferSizeInFramesIn; + ma_uint32 bufferSizeInMillisecondsIn; + ma_uint32 periodsIn; + ma_bool32 usingDefaultFormat; + ma_bool32 usingDefaultChannels; + ma_bool32 usingDefaultSampleRate; + ma_bool32 usingDefaultChannelMap; + ma_share_mode shareMode; + ma_bool32 registerStopEvent; + + // Output. +#if defined(MA_APPLE_DESKTOP) + AudioObjectID deviceObjectID; +#endif + AudioComponent component; + AudioUnit audioUnit; + AudioBufferList* pAudioBufferList; // Only used for input devices. + ma_format formatOut; + ma_uint32 channelsOut; + ma_uint32 sampleRateOut; + ma_channel channelMapOut[MA_MAX_CHANNELS]; + ma_uint32 bufferSizeInFramesOut; + ma_uint32 periodsOut; + char deviceName[256]; +} ma_device_init_internal_data__coreaudio; + +ma_result ma_device_init_internal__coreaudio(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_init_internal_data__coreaudio* pData, void* pDevice_DoNotReference) /* <-- pDevice is typed as void* intentionally so as to avoid accidentally referencing it. */ +{ + /* This API should only be used for a single device type: playback or capture. No full-duplex mode. */ + if (deviceType == ma_device_type_duplex) { + return MA_INVALID_ARGS; + } + + ma_assert(pContext != NULL); + ma_assert(deviceType == ma_device_type_playback || deviceType == ma_device_type_capture); + +#if defined(MA_APPLE_DESKTOP) + pData->deviceObjectID = 0; +#endif + pData->component = NULL; + pData->audioUnit = NULL; + pData->pAudioBufferList = NULL; + + ma_result result; + +#if defined(MA_APPLE_DESKTOP) + AudioObjectID deviceObjectID; + result = ma_find_AudioObjectID(pContext, deviceType, pDeviceID, &deviceObjectID); + if (result != MA_SUCCESS) { + return result; + } + + pData->deviceObjectID = deviceObjectID; +#endif + + // Core audio doesn't really use the notion of a period so we can leave this unmodified, but not too over the top. + pData->periodsOut = pData->periodsIn; + if (pData->periodsOut < 1) { + pData->periodsOut = 1; + } + if (pData->periodsOut > 16) { + pData->periodsOut = 16; + } + + + // Audio unit. + OSStatus status = ((ma_AudioComponentInstanceNew_proc)pContext->coreaudio.AudioComponentInstanceNew)(pContext->coreaudio.component, (AudioUnit*)&pData->audioUnit); + if (status != noErr) { + return ma_result_from_OSStatus(status); + } + + + // The input/output buses need to be explicitly enabled and disabled. We set the flag based on the output unit first, then we just swap it for input. + UInt32 enableIOFlag = 1; + if (deviceType == ma_device_type_capture) { + enableIOFlag = 0; + } + + status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, MA_COREAUDIO_OUTPUT_BUS, &enableIOFlag, sizeof(enableIOFlag)); + if (status != noErr) { + ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit); + return ma_result_from_OSStatus(status); + } + + enableIOFlag = (enableIOFlag == 0) ? 1 : 0; + status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, MA_COREAUDIO_INPUT_BUS, &enableIOFlag, sizeof(enableIOFlag)); + if (status != noErr) { + ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit); + return ma_result_from_OSStatus(status); + } + + + // Set the device to use with this audio unit. This is only used on desktop since we are using defaults on mobile. +#if defined(MA_APPLE_DESKTOP) + status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, (deviceType == ma_device_type_playback) ? MA_COREAUDIO_OUTPUT_BUS : MA_COREAUDIO_INPUT_BUS, &deviceObjectID, sizeof(AudioDeviceID)); + if (status != noErr) { + ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit); + return ma_result_from_OSStatus(result); + } +#endif + + // Format. This is the hardest part of initialization because there's a few variables to take into account. + // 1) The format must be supported by the device. + // 2) The format must be supported miniaudio. + // 3) There's a priority that miniaudio prefers. + // + // Ideally we would like to use a format that's as close to the hardware as possible so we can get as close to a passthrough as possible. The + // most important property is the sample rate. miniaudio can do format conversion for any sample rate and channel count, but cannot do the same + // for the sample data format. If the sample data format is not supported by miniaudio it must be ignored completely. + // + // On mobile platforms this is a bit different. We just force the use of whatever the audio unit's current format is set to. + AudioStreamBasicDescription bestFormat; + { + AudioUnitScope formatScope = (deviceType == ma_device_type_playback) ? kAudioUnitScope_Input : kAudioUnitScope_Output; + AudioUnitElement formatElement = (deviceType == ma_device_type_playback) ? MA_COREAUDIO_OUTPUT_BUS : MA_COREAUDIO_INPUT_BUS; + + #if defined(MA_APPLE_DESKTOP) + result = ma_find_best_format__coreaudio(pContext, deviceObjectID, deviceType, pData->formatIn, pData->channelsIn, pData->sampleRateIn, pData->usingDefaultFormat, pData->usingDefaultChannels, pData->usingDefaultSampleRate, &bestFormat); + if (result != MA_SUCCESS) { + ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit); + return result; + } + + // From what I can see, Apple's documentation implies that we should keep the sample rate consistent. + AudioStreamBasicDescription origFormat; + UInt32 origFormatSize = sizeof(origFormat); + if (deviceType == ma_device_type_playback) { + status = ((ma_AudioUnitGetProperty_proc)pContext->coreaudio.AudioUnitGetProperty)(pData->audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, MA_COREAUDIO_OUTPUT_BUS, &origFormat, &origFormatSize); + } else { + status = ((ma_AudioUnitGetProperty_proc)pContext->coreaudio.AudioUnitGetProperty)(pData->audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, MA_COREAUDIO_INPUT_BUS, &origFormat, &origFormatSize); + } + + if (status != noErr) { + ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit); + return result; + } + + bestFormat.mSampleRate = origFormat.mSampleRate; + + status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioUnitProperty_StreamFormat, formatScope, formatElement, &bestFormat, sizeof(bestFormat)); + if (status != noErr) { + // We failed to set the format, so fall back to the current format of the audio unit. + bestFormat = origFormat; + } + #else + UInt32 propSize = sizeof(bestFormat); + status = ((ma_AudioUnitGetProperty_proc)pContext->coreaudio.AudioUnitGetProperty)(pData->audioUnit, kAudioUnitProperty_StreamFormat, formatScope, formatElement, &bestFormat, &propSize); + if (status != noErr) { + ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit); + return ma_result_from_OSStatus(status); + } + + // Sample rate is a little different here because for some reason kAudioUnitProperty_StreamFormat returns 0... Oh well. We need to instead try + // setting the sample rate to what the user has requested and then just see the results of it. Need to use some Objective-C here for this since + // it depends on Apple's AVAudioSession API. To do this we just get the shared AVAudioSession instance and then set it. Note that from what I + // can tell, it looks like the sample rate is shared between playback and capture for everything. + @autoreleasepool { + AVAudioSession* pAudioSession = [AVAudioSession sharedInstance]; + ma_assert(pAudioSession != NULL); + + [pAudioSession setPreferredSampleRate:(double)pData->sampleRateIn error:nil]; + bestFormat.mSampleRate = pAudioSession.sampleRate; + } + + status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioUnitProperty_StreamFormat, formatScope, formatElement, &bestFormat, sizeof(bestFormat)); + if (status != noErr) { + ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit); + return ma_result_from_OSStatus(status); + } + #endif + + result = ma_format_from_AudioStreamBasicDescription(&bestFormat, &pData->formatOut); + if (result != MA_SUCCESS) { + ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit); + return result; + } + + if (pData->formatOut == ma_format_unknown) { + ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit); + return MA_FORMAT_NOT_SUPPORTED; + } + + pData->channelsOut = bestFormat.mChannelsPerFrame; + pData->sampleRateOut = bestFormat.mSampleRate; + } + + + // Internal channel map. This is weird in my testing. If I use the AudioObject to get the + // channel map, the channel descriptions are set to "Unknown" for some reason. To work around + // this it looks like retrieving it from the AudioUnit will work. However, and this is where + // it gets weird, it doesn't seem to work with capture devices, nor at all on iOS... Therefore + // I'm going to fall back to a default assumption in these cases. +#if defined(MA_APPLE_DESKTOP) + result = ma_get_AudioUnit_channel_map(pContext, pData->audioUnit, deviceType, pData->channelMapOut); + if (result != MA_SUCCESS) { + #if 0 + // Try falling back to the channel map from the AudioObject. + result = ma_get_AudioObject_channel_map(pContext, deviceObjectID, deviceType, pData->channelMapOut); + if (result != MA_SUCCESS) { + return result; + } + #else + // Fall back to default assumptions. + ma_get_standard_channel_map(ma_standard_channel_map_default, pData->channelsOut, pData->channelMapOut); + #endif + } +#else + // TODO: Figure out how to get the channel map using AVAudioSession. + ma_get_standard_channel_map(ma_standard_channel_map_default, pData->channelsOut, pData->channelMapOut); +#endif + + + // Buffer size. Not allowing this to be configurable on iOS. + ma_uint32 actualBufferSizeInFrames = pData->bufferSizeInFramesIn; + +#if defined(MA_APPLE_DESKTOP) + if (actualBufferSizeInFrames == 0) { + actualBufferSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(pData->bufferSizeInMillisecondsIn, pData->sampleRateOut); + } + + actualBufferSizeInFrames = actualBufferSizeInFrames / pData->periodsOut; + result = ma_set_AudioObject_buffer_size_in_frames(pContext, deviceObjectID, deviceType, &actualBufferSizeInFrames); + if (result != MA_SUCCESS) { + return result; + } + + pData->bufferSizeInFramesOut = actualBufferSizeInFrames * pData->periodsOut; +#else + actualBufferSizeInFrames = 4096; + pData->bufferSizeInFramesOut = actualBufferSizeInFrames; +#endif + + + + // During testing I discovered that the buffer size can be too big. You'll get an error like this: + // + // kAudioUnitErr_TooManyFramesToProcess : inFramesToProcess=4096, mMaxFramesPerSlice=512 + // + // Note how inFramesToProcess is smaller than mMaxFramesPerSlice. To fix, we need to set kAudioUnitProperty_MaximumFramesPerSlice to that + // of the size of our buffer, or do it the other way around and set our buffer size to the kAudioUnitProperty_MaximumFramesPerSlice. + { + /*AudioUnitScope propScope = (deviceType == ma_device_type_playback) ? kAudioUnitScope_Input : kAudioUnitScope_Output; + AudioUnitElement propBus = (deviceType == ma_device_type_playback) ? MA_COREAUDIO_OUTPUT_BUS : MA_COREAUDIO_INPUT_BUS; + + status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioUnitProperty_MaximumFramesPerSlice, propScope, propBus, &actualBufferSizeInFrames, sizeof(actualBufferSizeInFrames)); + if (status != noErr) { + ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit); + return ma_result_from_OSStatus(status); + }*/ + + status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 0, &actualBufferSizeInFrames, sizeof(actualBufferSizeInFrames)); + if (status != noErr) { + ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit); + return ma_result_from_OSStatus(status); + } + } + + // We need a buffer list if this is an input device. We render into this in the input callback. + if (deviceType == ma_device_type_capture) { + ma_bool32 isInterleaved = (bestFormat.mFormatFlags & kAudioFormatFlagIsNonInterleaved) == 0; + + size_t allocationSize = sizeof(AudioBufferList) - sizeof(AudioBuffer); // Subtract sizeof(AudioBuffer) because that part is dynamically sized. + if (isInterleaved) { + // Interleaved case. This is the simple case because we just have one buffer. + allocationSize += sizeof(AudioBuffer) * 1; + allocationSize += actualBufferSizeInFrames * ma_get_bytes_per_frame(pData->formatOut, pData->channelsOut); + } else { + // Non-interleaved case. This is the more complex case because there's more than one buffer. + allocationSize += sizeof(AudioBuffer) * pData->channelsOut; + allocationSize += actualBufferSizeInFrames * ma_get_bytes_per_sample(pData->formatOut) * pData->channelsOut; + } + + AudioBufferList* pBufferList = (AudioBufferList*)ma_malloc(allocationSize); + if (pBufferList == NULL) { + ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit); + return MA_OUT_OF_MEMORY; + } + + if (isInterleaved) { + pBufferList->mNumberBuffers = 1; + pBufferList->mBuffers[0].mNumberChannels = pData->channelsOut; + pBufferList->mBuffers[0].mDataByteSize = actualBufferSizeInFrames * ma_get_bytes_per_frame(pData->formatOut, pData->channelsOut); + pBufferList->mBuffers[0].mData = (ma_uint8*)pBufferList + sizeof(AudioBufferList); + } else { + pBufferList->mNumberBuffers = pData->channelsOut; + for (ma_uint32 iBuffer = 0; iBuffer < pBufferList->mNumberBuffers; ++iBuffer) { + pBufferList->mBuffers[iBuffer].mNumberChannels = 1; + pBufferList->mBuffers[iBuffer].mDataByteSize = actualBufferSizeInFrames * ma_get_bytes_per_sample(pData->formatOut); + pBufferList->mBuffers[iBuffer].mData = (ma_uint8*)pBufferList + ((sizeof(AudioBufferList) - sizeof(AudioBuffer)) + (sizeof(AudioBuffer) * pData->channelsOut)) + (actualBufferSizeInFrames * ma_get_bytes_per_sample(pData->formatOut) * iBuffer); + } + } + + pData->pAudioBufferList = pBufferList; + } + + // Callbacks. + AURenderCallbackStruct callbackInfo; + callbackInfo.inputProcRefCon = pDevice_DoNotReference; + if (deviceType == ma_device_type_playback) { + callbackInfo.inputProc = ma_on_output__coreaudio; + status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Global, MA_COREAUDIO_OUTPUT_BUS, &callbackInfo, sizeof(callbackInfo)); + if (status != noErr) { + ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit); + return ma_result_from_OSStatus(status); + } + } else { + callbackInfo.inputProc = ma_on_input__coreaudio; + status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Global, MA_COREAUDIO_INPUT_BUS, &callbackInfo, sizeof(callbackInfo)); + if (status != noErr) { + ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit); + return ma_result_from_OSStatus(status); + } + } + + // We need to listen for stop events. + if (pData->registerStopEvent) { + status = ((ma_AudioUnitAddPropertyListener_proc)pContext->coreaudio.AudioUnitAddPropertyListener)(pData->audioUnit, kAudioOutputUnitProperty_IsRunning, on_start_stop__coreaudio, pDevice_DoNotReference); + if (status != noErr) { + ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit); + return ma_result_from_OSStatus(status); + } + } + + // Initialize the audio unit. + status = ((ma_AudioUnitInitialize_proc)pContext->coreaudio.AudioUnitInitialize)(pData->audioUnit); + if (status != noErr) { + ma_free(pData->pAudioBufferList); + pData->pAudioBufferList = NULL; + ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit); + return ma_result_from_OSStatus(status); + } + + // Grab the name. +#if defined(MA_APPLE_DESKTOP) + ma_get_AudioObject_name(pContext, deviceObjectID, sizeof(pData->deviceName), pData->deviceName); +#else + if (deviceType == ma_device_type_playback) { + ma_strcpy_s(pData->deviceName, sizeof(pData->deviceName), MA_DEFAULT_PLAYBACK_DEVICE_NAME); + } else { + ma_strcpy_s(pData->deviceName, sizeof(pData->deviceName), MA_DEFAULT_CAPTURE_DEVICE_NAME); + } +#endif + + return result; +} + +ma_result ma_device_reinit_internal__coreaudio(ma_device* pDevice, ma_device_type deviceType, ma_bool32 disposePreviousAudioUnit) +{ + /* This should only be called for playback or capture, not duplex. */ + if (deviceType == ma_device_type_duplex) { + return MA_INVALID_ARGS; + } + + ma_device_init_internal_data__coreaudio data; + if (deviceType == ma_device_type_capture) { + data.formatIn = pDevice->capture.format; + data.channelsIn = pDevice->capture.channels; + data.sampleRateIn = pDevice->sampleRate; + ma_copy_memory(data.channelMapIn, pDevice->capture.channelMap, sizeof(pDevice->capture.channelMap)); + data.usingDefaultFormat = pDevice->capture.usingDefaultFormat; + data.usingDefaultChannels = pDevice->capture.usingDefaultChannels; + data.usingDefaultSampleRate = pDevice->usingDefaultSampleRate; + data.usingDefaultChannelMap = pDevice->capture.usingDefaultChannelMap; + data.shareMode = pDevice->capture.shareMode; + data.registerStopEvent = MA_TRUE; + + if (disposePreviousAudioUnit) { + ((ma_AudioOutputUnitStop_proc)pDevice->pContext->coreaudio.AudioOutputUnitStop)((AudioUnit)pDevice->coreaudio.audioUnitCapture); + ((ma_AudioComponentInstanceDispose_proc)pDevice->pContext->coreaudio.AudioComponentInstanceDispose)((AudioUnit)pDevice->coreaudio.audioUnitCapture); + } + if (pDevice->coreaudio.pAudioBufferList) { + ma_free(pDevice->coreaudio.pAudioBufferList); + } + + #if defined(MA_APPLE_DESKTOP) + pDevice->coreaudio.deviceObjectIDCapture = (ma_uint32)data.deviceObjectID; + #endif + pDevice->coreaudio.audioUnitCapture = (ma_ptr)data.audioUnit; + pDevice->coreaudio.pAudioBufferList = (ma_ptr)data.pAudioBufferList; + } + if (deviceType == ma_device_type_playback) { + data.formatIn = pDevice->playback.format; + data.channelsIn = pDevice->playback.channels; + data.sampleRateIn = pDevice->sampleRate; + ma_copy_memory(data.channelMapIn, pDevice->playback.channelMap, sizeof(pDevice->playback.channelMap)); + data.usingDefaultFormat = pDevice->playback.usingDefaultFormat; + data.usingDefaultChannels = pDevice->playback.usingDefaultChannels; + data.usingDefaultSampleRate = pDevice->usingDefaultSampleRate; + data.usingDefaultChannelMap = pDevice->playback.usingDefaultChannelMap; + data.shareMode = pDevice->playback.shareMode; + data.registerStopEvent = (pDevice->type != ma_device_type_duplex); + + if (disposePreviousAudioUnit) { + ((ma_AudioOutputUnitStop_proc)pDevice->pContext->coreaudio.AudioOutputUnitStop)((AudioUnit)pDevice->coreaudio.audioUnitPlayback); + ((ma_AudioComponentInstanceDispose_proc)pDevice->pContext->coreaudio.AudioComponentInstanceDispose)((AudioUnit)pDevice->coreaudio.audioUnitPlayback); + } + + #if defined(MA_APPLE_DESKTOP) + pDevice->coreaudio.deviceObjectIDPlayback = (ma_uint32)data.deviceObjectID; + #endif + pDevice->coreaudio.audioUnitPlayback = (ma_ptr)data.audioUnit; + } + data.bufferSizeInFramesIn = pDevice->coreaudio.originalBufferSizeInFrames; + data.bufferSizeInMillisecondsIn = pDevice->coreaudio.originalBufferSizeInMilliseconds; + data.periodsIn = pDevice->coreaudio.originalPeriods; + + ma_result result = ma_device_init_internal__coreaudio(pDevice->pContext, deviceType, NULL, &data, (void*)pDevice); + if (result != MA_SUCCESS) { + return result; + } + + return MA_SUCCESS; +} + + +ma_result ma_device_init__coreaudio(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice) +{ + (void)pConfig; + + ma_assert(pContext != NULL); + ma_assert(pConfig != NULL); + ma_assert(pDevice != NULL); + + /* No exclusive mode with the Core Audio backend for now. */ + if (((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pConfig->capture.shareMode == ma_share_mode_exclusive) || + ((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pConfig->playback.shareMode == ma_share_mode_exclusive)) { + return MA_SHARE_MODE_NOT_SUPPORTED; + } + + /* Capture needs to be initialized first. */ + if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) { + ma_device_init_internal_data__coreaudio data; + data.formatIn = pConfig->capture.format; + data.channelsIn = pConfig->capture.channels; + data.sampleRateIn = pConfig->sampleRate; + ma_copy_memory(data.channelMapIn, pConfig->capture.channelMap, sizeof(pConfig->capture.channelMap)); + data.usingDefaultFormat = pDevice->capture.usingDefaultFormat; + data.usingDefaultChannels = pDevice->capture.usingDefaultChannels; + data.usingDefaultSampleRate = pDevice->usingDefaultSampleRate; + data.usingDefaultChannelMap = pDevice->capture.usingDefaultChannelMap; + data.shareMode = pConfig->capture.shareMode; + data.bufferSizeInFramesIn = pConfig->bufferSizeInFrames; + data.bufferSizeInMillisecondsIn = pConfig->bufferSizeInMilliseconds; + data.registerStopEvent = MA_TRUE; + + ma_result result = ma_device_init_internal__coreaudio(pDevice->pContext, ma_device_type_capture, pConfig->capture.pDeviceID, &data, (void*)pDevice); + if (result != MA_SUCCESS) { + return result; + } + + pDevice->coreaudio.isDefaultCaptureDevice = (pConfig->capture.pDeviceID == NULL); + #if defined(MA_APPLE_DESKTOP) + pDevice->coreaudio.deviceObjectIDCapture = (ma_uint32)data.deviceObjectID; + #endif + pDevice->coreaudio.audioUnitCapture = (ma_ptr)data.audioUnit; + pDevice->coreaudio.pAudioBufferList = (ma_ptr)data.pAudioBufferList; + + pDevice->capture.internalFormat = data.formatOut; + pDevice->capture.internalChannels = data.channelsOut; + pDevice->capture.internalSampleRate = data.sampleRateOut; + ma_copy_memory(pDevice->capture.internalChannelMap, data.channelMapOut, sizeof(data.channelMapOut)); + pDevice->capture.internalBufferSizeInFrames = data.bufferSizeInFramesOut; + pDevice->capture.internalPeriods = data.periodsOut; + + // TODO: This needs to be made global. + #if defined(MA_APPLE_DESKTOP) + // If we are using the default device we'll need to listen for changes to the system's default device so we can seemlessly + // switch the device in the background. + if (pConfig->capture.pDeviceID == NULL) { + AudioObjectPropertyAddress propAddress; + propAddress.mSelector = kAudioHardwarePropertyDefaultInputDevice; + propAddress.mScope = kAudioObjectPropertyScopeGlobal; + propAddress.mElement = kAudioObjectPropertyElementMaster; + ((ma_AudioObjectAddPropertyListener_proc)pDevice->pContext->coreaudio.AudioObjectAddPropertyListener)(kAudioObjectSystemObject, &propAddress, &ma_default_device_changed__coreaudio, pDevice); + } + #endif + } + + /* Playback. */ + if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) { + ma_device_init_internal_data__coreaudio data; + data.formatIn = pConfig->playback.format; + data.channelsIn = pConfig->playback.channels; + data.sampleRateIn = pConfig->sampleRate; + ma_copy_memory(data.channelMapIn, pConfig->playback.channelMap, sizeof(pConfig->playback.channelMap)); + data.usingDefaultFormat = pDevice->playback.usingDefaultFormat; + data.usingDefaultChannels = pDevice->playback.usingDefaultChannels; + data.usingDefaultSampleRate = pDevice->usingDefaultSampleRate; + data.usingDefaultChannelMap = pDevice->playback.usingDefaultChannelMap; + data.shareMode = pConfig->playback.shareMode; + + /* In full-duplex mode we want the playback buffer to be the same size as the capture buffer. */ + if (pConfig->deviceType == ma_device_type_duplex) { + data.bufferSizeInFramesIn = pDevice->capture.internalBufferSizeInFrames; + data.periodsIn = pDevice->capture.internalPeriods; + data.registerStopEvent = MA_FALSE; + } else { + data.bufferSizeInFramesIn = pConfig->bufferSizeInFrames; + data.bufferSizeInMillisecondsIn = pConfig->bufferSizeInMilliseconds; + data.periodsIn = pConfig->periods; + data.registerStopEvent = MA_TRUE; + } + + ma_result result = ma_device_init_internal__coreaudio(pDevice->pContext, ma_device_type_playback, pConfig->playback.pDeviceID, &data, (void*)pDevice); + if (result != MA_SUCCESS) { + if (pConfig->deviceType == ma_device_type_duplex) { + ((ma_AudioComponentInstanceDispose_proc)pDevice->pContext->coreaudio.AudioComponentInstanceDispose)((AudioUnit)pDevice->coreaudio.audioUnitCapture); + if (pDevice->coreaudio.pAudioBufferList) { + ma_free(pDevice->coreaudio.pAudioBufferList); + } + } + return result; + } + + pDevice->coreaudio.isDefaultPlaybackDevice = (pConfig->playback.pDeviceID == NULL); + #if defined(MA_APPLE_DESKTOP) + pDevice->coreaudio.deviceObjectIDPlayback = (ma_uint32)data.deviceObjectID; + #endif + pDevice->coreaudio.audioUnitPlayback = (ma_ptr)data.audioUnit; + + pDevice->playback.internalFormat = data.formatOut; + pDevice->playback.internalChannels = data.channelsOut; + pDevice->playback.internalSampleRate = data.sampleRateOut; + ma_copy_memory(pDevice->playback.internalChannelMap, data.channelMapOut, sizeof(data.channelMapOut)); + pDevice->playback.internalBufferSizeInFrames = data.bufferSizeInFramesOut; + pDevice->playback.internalPeriods = data.periodsOut; + + // TODO: This needs to be made global. + #if defined(MA_APPLE_DESKTOP) + // If we are using the default device we'll need to listen for changes to the system's default device so we can seemlessly + // switch the device in the background. + if (pConfig->playback.pDeviceID == NULL) { + AudioObjectPropertyAddress propAddress; + propAddress.mSelector = kAudioHardwarePropertyDefaultOutputDevice; + propAddress.mScope = kAudioObjectPropertyScopeGlobal; + propAddress.mElement = kAudioObjectPropertyElementMaster; + ((ma_AudioObjectAddPropertyListener_proc)pDevice->pContext->coreaudio.AudioObjectAddPropertyListener)(kAudioObjectSystemObject, &propAddress, &ma_default_device_changed__coreaudio, pDevice); + } + #endif + } + + pDevice->coreaudio.originalBufferSizeInFrames = pConfig->bufferSizeInFrames; + pDevice->coreaudio.originalBufferSizeInMilliseconds = pConfig->bufferSizeInMilliseconds; + pDevice->coreaudio.originalPeriods = pConfig->periods; + + /* + When stopping the device, a callback is called on another thread. We need to wait for this callback + before returning from ma_device_stop(). This event is used for this. + */ + ma_event_init(pContext, &pDevice->coreaudio.stopEvent); + + /* Need a ring buffer for duplex mode. */ + if (pConfig->deviceType == ma_device_type_duplex) { + ma_uint32 rbSizeInFrames = (ma_uint32)ma_calculate_frame_count_after_src(pDevice->sampleRate, pDevice->capture.internalSampleRate, pDevice->capture.internalBufferSizeInFrames); + ma_result result = ma_pcm_rb_init(pDevice->capture.format, pDevice->capture.channels, rbSizeInFrames, NULL, &pDevice->coreaudio.duplexRB); + if (result != MA_SUCCESS) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[Core Audio] Failed to initialize ring buffer.", result); + } + } + + return MA_SUCCESS; +} + + +ma_result ma_device_start__coreaudio(ma_device* pDevice) +{ + ma_assert(pDevice != NULL); + + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + OSStatus status = ((ma_AudioOutputUnitStart_proc)pDevice->pContext->coreaudio.AudioOutputUnitStart)((AudioUnit)pDevice->coreaudio.audioUnitCapture); + if (status != noErr) { + return ma_result_from_OSStatus(status); + } + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + OSStatus status = ((ma_AudioOutputUnitStart_proc)pDevice->pContext->coreaudio.AudioOutputUnitStart)((AudioUnit)pDevice->coreaudio.audioUnitPlayback); + if (status != noErr) { + if (pDevice->type == ma_device_type_duplex) { + ((ma_AudioOutputUnitStop_proc)pDevice->pContext->coreaudio.AudioOutputUnitStop)((AudioUnit)pDevice->coreaudio.audioUnitCapture); + } + return ma_result_from_OSStatus(status); + } + } + + return MA_SUCCESS; +} + +ma_result ma_device_stop__coreaudio(ma_device* pDevice) +{ + ma_assert(pDevice != NULL); + + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + OSStatus status = ((ma_AudioOutputUnitStop_proc)pDevice->pContext->coreaudio.AudioOutputUnitStop)((AudioUnit)pDevice->coreaudio.audioUnitCapture); + if (status != noErr) { + return ma_result_from_OSStatus(status); + } + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + OSStatus status = ((ma_AudioOutputUnitStop_proc)pDevice->pContext->coreaudio.AudioOutputUnitStop)((AudioUnit)pDevice->coreaudio.audioUnitPlayback); + if (status != noErr) { + return ma_result_from_OSStatus(status); + } + } + + /* We need to wait for the callback to finish before returning. */ + ma_event_wait(&pDevice->coreaudio.stopEvent); + return MA_SUCCESS; +} + + +ma_result ma_context_uninit__coreaudio(ma_context* pContext) +{ + ma_assert(pContext != NULL); + ma_assert(pContext->backend == ma_backend_coreaudio); + +#if !defined(MA_NO_RUNTIME_LINKING) && !defined(MA_APPLE_MOBILE) + ma_dlclose(pContext->coreaudio.hAudioUnit); + ma_dlclose(pContext->coreaudio.hCoreAudio); + ma_dlclose(pContext->coreaudio.hCoreFoundation); +#endif + + (void)pContext; + return MA_SUCCESS; +} + +ma_result ma_context_init__coreaudio(ma_context* pContext) +{ + ma_assert(pContext != NULL); + +#if defined(MA_APPLE_MOBILE) + @autoreleasepool { + AVAudioSession* pAudioSession = [AVAudioSession sharedInstance]; + ma_assert(pAudioSession != NULL); + + [pAudioSession setCategory: AVAudioSessionCategoryPlayAndRecord error:nil]; + + // By default we want miniaudio to use the speakers instead of the receiver. In the future this may + // be customizable. + ma_bool32 useSpeakers = MA_TRUE; + if (useSpeakers) { + [pAudioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil]; + } + } +#endif + +#if !defined(MA_NO_RUNTIME_LINKING) && !defined(MA_APPLE_MOBILE) + pContext->coreaudio.hCoreFoundation = ma_dlopen("CoreFoundation.framework/CoreFoundation"); + if (pContext->coreaudio.hCoreFoundation == NULL) { + return MA_API_NOT_FOUND; + } + + pContext->coreaudio.CFStringGetCString = ma_dlsym(pContext->coreaudio.hCoreFoundation, "CFStringGetCString"); + + + pContext->coreaudio.hCoreAudio = ma_dlopen("CoreAudio.framework/CoreAudio"); + if (pContext->coreaudio.hCoreAudio == NULL) { + ma_dlclose(pContext->coreaudio.hCoreFoundation); + return MA_API_NOT_FOUND; + } + + pContext->coreaudio.AudioObjectGetPropertyData = ma_dlsym(pContext->coreaudio.hCoreAudio, "AudioObjectGetPropertyData"); + pContext->coreaudio.AudioObjectGetPropertyDataSize = ma_dlsym(pContext->coreaudio.hCoreAudio, "AudioObjectGetPropertyDataSize"); + pContext->coreaudio.AudioObjectSetPropertyData = ma_dlsym(pContext->coreaudio.hCoreAudio, "AudioObjectSetPropertyData"); + pContext->coreaudio.AudioObjectAddPropertyListener = ma_dlsym(pContext->coreaudio.hCoreAudio, "AudioObjectAddPropertyListener"); + + + // It looks like Apple has moved some APIs from AudioUnit into AudioToolbox on more recent versions of macOS. They are still + // defined in AudioUnit, but just in case they decide to remove them from there entirely I'm going to implement a fallback. + // The way it'll work is that it'll first try AudioUnit, and if the required symbols are not present there we'll fall back to + // AudioToolbox. + pContext->coreaudio.hAudioUnit = ma_dlopen("AudioUnit.framework/AudioUnit"); + if (pContext->coreaudio.hAudioUnit == NULL) { + ma_dlclose(pContext->coreaudio.hCoreAudio); + ma_dlclose(pContext->coreaudio.hCoreFoundation); + return MA_API_NOT_FOUND; + } + + if (ma_dlsym(pContext->coreaudio.hAudioUnit, "AudioComponentFindNext") == NULL) { + // Couldn't find the required symbols in AudioUnit, so fall back to AudioToolbox. + ma_dlclose(pContext->coreaudio.hAudioUnit); + pContext->coreaudio.hAudioUnit = ma_dlopen("AudioToolbox.framework/AudioToolbox"); + if (pContext->coreaudio.hAudioUnit == NULL) { + ma_dlclose(pContext->coreaudio.hCoreAudio); + ma_dlclose(pContext->coreaudio.hCoreFoundation); + return MA_API_NOT_FOUND; + } + } + + pContext->coreaudio.AudioComponentFindNext = ma_dlsym(pContext->coreaudio.hAudioUnit, "AudioComponentFindNext"); + pContext->coreaudio.AudioComponentInstanceDispose = ma_dlsym(pContext->coreaudio.hAudioUnit, "AudioComponentInstanceDispose"); + pContext->coreaudio.AudioComponentInstanceNew = ma_dlsym(pContext->coreaudio.hAudioUnit, "AudioComponentInstanceNew"); + pContext->coreaudio.AudioOutputUnitStart = ma_dlsym(pContext->coreaudio.hAudioUnit, "AudioOutputUnitStart"); + pContext->coreaudio.AudioOutputUnitStop = ma_dlsym(pContext->coreaudio.hAudioUnit, "AudioOutputUnitStop"); + pContext->coreaudio.AudioUnitAddPropertyListener = ma_dlsym(pContext->coreaudio.hAudioUnit, "AudioUnitAddPropertyListener"); + pContext->coreaudio.AudioUnitGetPropertyInfo = ma_dlsym(pContext->coreaudio.hAudioUnit, "AudioUnitGetPropertyInfo"); + pContext->coreaudio.AudioUnitGetProperty = ma_dlsym(pContext->coreaudio.hAudioUnit, "AudioUnitGetProperty"); + pContext->coreaudio.AudioUnitSetProperty = ma_dlsym(pContext->coreaudio.hAudioUnit, "AudioUnitSetProperty"); + pContext->coreaudio.AudioUnitInitialize = ma_dlsym(pContext->coreaudio.hAudioUnit, "AudioUnitInitialize"); + pContext->coreaudio.AudioUnitRender = ma_dlsym(pContext->coreaudio.hAudioUnit, "AudioUnitRender"); +#else + pContext->coreaudio.CFStringGetCString = (ma_proc)CFStringGetCString; + + #if defined(MA_APPLE_DESKTOP) + pContext->coreaudio.AudioObjectGetPropertyData = (ma_proc)AudioObjectGetPropertyData; + pContext->coreaudio.AudioObjectGetPropertyDataSize = (ma_proc)AudioObjectGetPropertyDataSize; + pContext->coreaudio.AudioObjectSetPropertyData = (ma_proc)AudioObjectSetPropertyData; + pContext->coreaudio.AudioObjectAddPropertyListener = (ma_proc)AudioObjectAddPropertyListener; + #endif + + pContext->coreaudio.AudioComponentFindNext = (ma_proc)AudioComponentFindNext; + pContext->coreaudio.AudioComponentInstanceDispose = (ma_proc)AudioComponentInstanceDispose; + pContext->coreaudio.AudioComponentInstanceNew = (ma_proc)AudioComponentInstanceNew; + pContext->coreaudio.AudioOutputUnitStart = (ma_proc)AudioOutputUnitStart; + pContext->coreaudio.AudioOutputUnitStop = (ma_proc)AudioOutputUnitStop; + pContext->coreaudio.AudioUnitAddPropertyListener = (ma_proc)AudioUnitAddPropertyListener; + pContext->coreaudio.AudioUnitGetPropertyInfo = (ma_proc)AudioUnitGetPropertyInfo; + pContext->coreaudio.AudioUnitGetProperty = (ma_proc)AudioUnitGetProperty; + pContext->coreaudio.AudioUnitSetProperty = (ma_proc)AudioUnitSetProperty; + pContext->coreaudio.AudioUnitInitialize = (ma_proc)AudioUnitInitialize; + pContext->coreaudio.AudioUnitRender = (ma_proc)AudioUnitRender; +#endif + + pContext->isBackendAsynchronous = MA_TRUE; + + pContext->onUninit = ma_context_uninit__coreaudio; + pContext->onDeviceIDEqual = ma_context_is_device_id_equal__coreaudio; + pContext->onEnumDevices = ma_context_enumerate_devices__coreaudio; + pContext->onGetDeviceInfo = ma_context_get_device_info__coreaudio; + pContext->onDeviceInit = ma_device_init__coreaudio; + pContext->onDeviceUninit = ma_device_uninit__coreaudio; + pContext->onDeviceStart = ma_device_start__coreaudio; + pContext->onDeviceStop = ma_device_stop__coreaudio; + + // Audio component. + AudioComponentDescription desc; + desc.componentType = kAudioUnitType_Output; +#if defined(MA_APPLE_DESKTOP) + desc.componentSubType = kAudioUnitSubType_HALOutput; +#else + desc.componentSubType = kAudioUnitSubType_RemoteIO; +#endif + desc.componentManufacturer = kAudioUnitManufacturer_Apple; + desc.componentFlags = 0; + desc.componentFlagsMask = 0; + + pContext->coreaudio.component = ((ma_AudioComponentFindNext_proc)pContext->coreaudio.AudioComponentFindNext)(NULL, &desc); + if (pContext->coreaudio.component == NULL) { +#if !defined(MA_NO_RUNTIME_LINKING) && !defined(MA_APPLE_MOBILE) + ma_dlclose(pContext->coreaudio.hAudioUnit); + ma_dlclose(pContext->coreaudio.hCoreAudio); + ma_dlclose(pContext->coreaudio.hCoreFoundation); +#endif + return MA_FAILED_TO_INIT_BACKEND; + } + + return MA_SUCCESS; +} +#endif // Core Audio + + + +/////////////////////////////////////////////////////////////////////////////// +// +// sndio Backend +// +/////////////////////////////////////////////////////////////////////////////// +#ifdef MA_HAS_SNDIO +#include +#include + +// Only supporting OpenBSD. This did not work very well at all on FreeBSD when I tried it. Not sure if this is due +// to miniaudio's implementation or if it's some kind of system configuration issue, but basically the default device +// just doesn't emit any sound, or at times you'll hear tiny pieces. I will consider enabling this when there's +// demand for it or if I can get it tested and debugged more thoroughly. + +//#if defined(__NetBSD__) || defined(__OpenBSD__) +//#include +//#endif +//#if defined(__FreeBSD__) || defined(__DragonFly__) +//#include +//#endif + +#define MA_SIO_DEVANY "default" +#define MA_SIO_PLAY 1 +#define MA_SIO_REC 2 +#define MA_SIO_NENC 8 +#define MA_SIO_NCHAN 8 +#define MA_SIO_NRATE 16 +#define MA_SIO_NCONF 4 + +struct ma_sio_hdl; // <-- Opaque + +struct ma_sio_par +{ + unsigned int bits; + unsigned int bps; + unsigned int sig; + unsigned int le; + unsigned int msb; + unsigned int rchan; + unsigned int pchan; + unsigned int rate; + unsigned int bufsz; + unsigned int xrun; + unsigned int round; + unsigned int appbufsz; + int __pad[3]; + unsigned int __magic; +}; + +struct ma_sio_enc +{ + unsigned int bits; + unsigned int bps; + unsigned int sig; + unsigned int le; + unsigned int msb; +}; + +struct ma_sio_conf +{ + unsigned int enc; + unsigned int rchan; + unsigned int pchan; + unsigned int rate; +}; + +struct ma_sio_cap +{ + struct ma_sio_enc enc[MA_SIO_NENC]; + unsigned int rchan[MA_SIO_NCHAN]; + unsigned int pchan[MA_SIO_NCHAN]; + unsigned int rate[MA_SIO_NRATE]; + int __pad[7]; + unsigned int nconf; + struct ma_sio_conf confs[MA_SIO_NCONF]; +}; + +typedef struct ma_sio_hdl* (* ma_sio_open_proc) (const char*, unsigned int, int); +typedef void (* ma_sio_close_proc) (struct ma_sio_hdl*); +typedef int (* ma_sio_setpar_proc) (struct ma_sio_hdl*, struct ma_sio_par*); +typedef int (* ma_sio_getpar_proc) (struct ma_sio_hdl*, struct ma_sio_par*); +typedef int (* ma_sio_getcap_proc) (struct ma_sio_hdl*, struct ma_sio_cap*); +typedef size_t (* ma_sio_write_proc) (struct ma_sio_hdl*, const void*, size_t); +typedef size_t (* ma_sio_read_proc) (struct ma_sio_hdl*, void*, size_t); +typedef int (* ma_sio_start_proc) (struct ma_sio_hdl*); +typedef int (* ma_sio_stop_proc) (struct ma_sio_hdl*); +typedef int (* ma_sio_initpar_proc)(struct ma_sio_par*); + +ma_format ma_format_from_sio_enc__sndio(unsigned int bits, unsigned int bps, unsigned int sig, unsigned int le, unsigned int msb) +{ + // We only support native-endian right now. + if ((ma_is_little_endian() && le == 0) || (ma_is_big_endian() && le == 1)) { + return ma_format_unknown; + } + + if (bits == 8 && bps == 1 && sig == 0) { + return ma_format_u8; + } + if (bits == 16 && bps == 2 && sig == 1) { + return ma_format_s16; + } + if (bits == 24 && bps == 3 && sig == 1) { + return ma_format_s24; + } + if (bits == 24 && bps == 4 && sig == 1 && msb == 0) { + //return ma_format_s24_32; + } + if (bits == 32 && bps == 4 && sig == 1) { + return ma_format_s32; + } + + return ma_format_unknown; +} + +ma_format ma_find_best_format_from_sio_cap__sndio(struct ma_sio_cap* caps) +{ + ma_assert(caps != NULL); + + ma_format bestFormat = ma_format_unknown; + for (unsigned int iConfig = 0; iConfig < caps->nconf; iConfig += 1) { + for (unsigned int iEncoding = 0; iEncoding < MA_SIO_NENC; iEncoding += 1) { + if ((caps->confs[iConfig].enc & (1UL << iEncoding)) == 0) { + continue; + } + + unsigned int bits = caps->enc[iEncoding].bits; + unsigned int bps = caps->enc[iEncoding].bps; + unsigned int sig = caps->enc[iEncoding].sig; + unsigned int le = caps->enc[iEncoding].le; + unsigned int msb = caps->enc[iEncoding].msb; + ma_format format = ma_format_from_sio_enc__sndio(bits, bps, sig, le, msb); + if (format == ma_format_unknown) { + continue; // Format not supported. + } + + if (bestFormat == ma_format_unknown) { + bestFormat = format; + } else { + if (ma_get_format_priority_index(bestFormat) > ma_get_format_priority_index(format)) { // <-- Lower = better. + bestFormat = format; + } + } + } + } + + return ma_format_unknown; +} + +ma_uint32 ma_find_best_channels_from_sio_cap__sndio(struct ma_sio_cap* caps, ma_device_type deviceType, ma_format requiredFormat) +{ + ma_assert(caps != NULL); + ma_assert(requiredFormat != ma_format_unknown); + + // Just pick whatever configuration has the most channels. + ma_uint32 maxChannels = 0; + for (unsigned int iConfig = 0; iConfig < caps->nconf; iConfig += 1) { + // The encoding should be of requiredFormat. + for (unsigned int iEncoding = 0; iEncoding < MA_SIO_NENC; iEncoding += 1) { + if ((caps->confs[iConfig].enc & (1UL << iEncoding)) == 0) { + continue; + } + + unsigned int bits = caps->enc[iEncoding].bits; + unsigned int bps = caps->enc[iEncoding].bps; + unsigned int sig = caps->enc[iEncoding].sig; + unsigned int le = caps->enc[iEncoding].le; + unsigned int msb = caps->enc[iEncoding].msb; + ma_format format = ma_format_from_sio_enc__sndio(bits, bps, sig, le, msb); + if (format != requiredFormat) { + continue; + } + + // Getting here means the format is supported. Iterate over each channel count and grab the biggest one. + for (unsigned int iChannel = 0; iChannel < MA_SIO_NCHAN; iChannel += 1) { + unsigned int chan = 0; + if (deviceType == ma_device_type_playback) { + chan = caps->confs[iConfig].pchan; + } else { + chan = caps->confs[iConfig].rchan; + } + + if ((chan & (1UL << iChannel)) == 0) { + continue; + } + + unsigned int channels; + if (deviceType == ma_device_type_playback) { + channels = caps->pchan[iChannel]; + } else { + channels = caps->rchan[iChannel]; + } + + if (maxChannels < channels) { + maxChannels = channels; + } + } + } + } + + return maxChannels; +} + +ma_uint32 ma_find_best_sample_rate_from_sio_cap__sndio(struct ma_sio_cap* caps, ma_device_type deviceType, ma_format requiredFormat, ma_uint32 requiredChannels) +{ + ma_assert(caps != NULL); + ma_assert(requiredFormat != ma_format_unknown); + ma_assert(requiredChannels > 0); + ma_assert(requiredChannels <= MA_MAX_CHANNELS); + + ma_uint32 firstSampleRate = 0; // <-- If the device does not support a standard rate we'll fall back to the first one that's found. + + ma_uint32 bestSampleRate = 0; + for (unsigned int iConfig = 0; iConfig < caps->nconf; iConfig += 1) { + // The encoding should be of requiredFormat. + for (unsigned int iEncoding = 0; iEncoding < MA_SIO_NENC; iEncoding += 1) { + if ((caps->confs[iConfig].enc & (1UL << iEncoding)) == 0) { + continue; + } + + unsigned int bits = caps->enc[iEncoding].bits; + unsigned int bps = caps->enc[iEncoding].bps; + unsigned int sig = caps->enc[iEncoding].sig; + unsigned int le = caps->enc[iEncoding].le; + unsigned int msb = caps->enc[iEncoding].msb; + ma_format format = ma_format_from_sio_enc__sndio(bits, bps, sig, le, msb); + if (format != requiredFormat) { + continue; + } + + // Getting here means the format is supported. Iterate over each channel count and grab the biggest one. + for (unsigned int iChannel = 0; iChannel < MA_SIO_NCHAN; iChannel += 1) { + unsigned int chan = 0; + if (deviceType == ma_device_type_playback) { + chan = caps->confs[iConfig].pchan; + } else { + chan = caps->confs[iConfig].rchan; + } + + if ((chan & (1UL << iChannel)) == 0) { + continue; + } + + unsigned int channels; + if (deviceType == ma_device_type_playback) { + channels = caps->pchan[iChannel]; + } else { + channels = caps->rchan[iChannel]; + } + + if (channels != requiredChannels) { + continue; + } + + // Getting here means we have found a compatible encoding/channel pair. + for (unsigned int iRate = 0; iRate < MA_SIO_NRATE; iRate += 1) { + ma_uint32 rate = (ma_uint32)caps->rate[iRate]; + + if (firstSampleRate == 0) { + firstSampleRate = rate; + } + + // Disregard this rate if it's not a standard one. + ma_uint32 ratePriority = ma_get_standard_sample_rate_priority_index(rate); + if (ratePriority == (ma_uint32)-1) { + continue; + } + + if (ma_get_standard_sample_rate_priority_index(bestSampleRate) > ratePriority) { // Lower = better. + bestSampleRate = rate; + } + } + } + } + } + + // If a standard sample rate was not found just fall back to the first one that was iterated. + if (bestSampleRate == 0) { + bestSampleRate = firstSampleRate; + } + + return bestSampleRate; +} + + +ma_bool32 ma_context_is_device_id_equal__sndio(ma_context* pContext, const ma_device_id* pID0, const ma_device_id* pID1) +{ + ma_assert(pContext != NULL); + ma_assert(pID0 != NULL); + ma_assert(pID1 != NULL); + (void)pContext; + + return ma_strcmp(pID0->sndio, pID1->sndio) == 0; +} + +ma_result ma_context_enumerate_devices__sndio(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData) +{ + ma_assert(pContext != NULL); + ma_assert(callback != NULL); + + // sndio doesn't seem to have a good device enumeration API, so I'm therefore only enumerating + // over default devices for now. + ma_bool32 isTerminating = MA_FALSE; + struct ma_sio_hdl* handle; + + // Playback. + if (!isTerminating) { + handle = ((ma_sio_open_proc)pContext->sndio.sio_open)(MA_SIO_DEVANY, MA_SIO_PLAY, 0); + if (handle != NULL) { + // Supports playback. + ma_device_info deviceInfo; + ma_zero_object(&deviceInfo); + ma_strcpy_s(deviceInfo.id.sndio, sizeof(deviceInfo.id.sndio), MA_SIO_DEVANY); + ma_strcpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_PLAYBACK_DEVICE_NAME); + + isTerminating = !callback(pContext, ma_device_type_playback, &deviceInfo, pUserData); + + ((ma_sio_close_proc)pContext->sndio.sio_close)(handle); + } + } + + // Capture. + if (!isTerminating) { + handle = ((ma_sio_open_proc)pContext->sndio.sio_open)(MA_SIO_DEVANY, MA_SIO_REC, 0); + if (handle != NULL) { + // Supports capture. + ma_device_info deviceInfo; + ma_zero_object(&deviceInfo); + ma_strcpy_s(deviceInfo.id.sndio, sizeof(deviceInfo.id.sndio), "default"); + ma_strcpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_CAPTURE_DEVICE_NAME); + + isTerminating = !callback(pContext, ma_device_type_capture, &deviceInfo, pUserData); + + ((ma_sio_close_proc)pContext->sndio.sio_close)(handle); + } + } + + return MA_SUCCESS; +} + +ma_result ma_context_get_device_info__sndio(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_share_mode shareMode, ma_device_info* pDeviceInfo) +{ + ma_assert(pContext != NULL); + (void)shareMode; + + // We need to open the device before we can get information about it. + char devid[256]; + if (pDeviceID == NULL) { + ma_strcpy_s(devid, sizeof(devid), MA_SIO_DEVANY); + ma_strcpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), (deviceType == ma_device_type_playback) ? MA_DEFAULT_PLAYBACK_DEVICE_NAME : MA_DEFAULT_CAPTURE_DEVICE_NAME); + } else { + ma_strcpy_s(devid, sizeof(devid), pDeviceID->sndio); + ma_strcpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), devid); + } + + struct ma_sio_hdl* handle = ((ma_sio_open_proc)pContext->sndio.sio_open)(devid, (deviceType == ma_device_type_playback) ? MA_SIO_PLAY : MA_SIO_REC, 0); + if (handle == NULL) { + return MA_NO_DEVICE; + } + + struct ma_sio_cap caps; + if (((ma_sio_getcap_proc)pContext->sndio.sio_getcap)(handle, &caps) == 0) { + return MA_ERROR; + } + + for (unsigned int iConfig = 0; iConfig < caps.nconf; iConfig += 1) { + // The main thing we care about is that the encoding is supported by miniaudio. If it is, we want to give + // preference to some formats over others. + for (unsigned int iEncoding = 0; iEncoding < MA_SIO_NENC; iEncoding += 1) { + if ((caps.confs[iConfig].enc & (1UL << iEncoding)) == 0) { + continue; + } + + unsigned int bits = caps.enc[iEncoding].bits; + unsigned int bps = caps.enc[iEncoding].bps; + unsigned int sig = caps.enc[iEncoding].sig; + unsigned int le = caps.enc[iEncoding].le; + unsigned int msb = caps.enc[iEncoding].msb; + ma_format format = ma_format_from_sio_enc__sndio(bits, bps, sig, le, msb); + if (format == ma_format_unknown) { + continue; // Format not supported. + } + + // Add this format if it doesn't already exist. + ma_bool32 formatExists = MA_FALSE; + for (ma_uint32 iExistingFormat = 0; iExistingFormat < pDeviceInfo->formatCount; iExistingFormat += 1) { + if (pDeviceInfo->formats[iExistingFormat] == format) { + formatExists = MA_TRUE; + break; + } + } + + if (!formatExists) { + pDeviceInfo->formats[pDeviceInfo->formatCount++] = format; + } + } + + // Channels. + for (unsigned int iChannel = 0; iChannel < MA_SIO_NCHAN; iChannel += 1) { + unsigned int chan = 0; + if (deviceType == ma_device_type_playback) { + chan = caps.confs[iConfig].pchan; + } else { + chan = caps.confs[iConfig].rchan; + } + + if ((chan & (1UL << iChannel)) == 0) { + continue; + } + + unsigned int channels; + if (deviceType == ma_device_type_playback) { + channels = caps.pchan[iChannel]; + } else { + channels = caps.rchan[iChannel]; + } + + if (pDeviceInfo->minChannels > channels) { + pDeviceInfo->minChannels = channels; + } + if (pDeviceInfo->maxChannels < channels) { + pDeviceInfo->maxChannels = channels; + } + } + + // Sample rates. + for (unsigned int iRate = 0; iRate < MA_SIO_NRATE; iRate += 1) { + if ((caps.confs[iConfig].rate & (1UL << iRate)) != 0) { + unsigned int rate = caps.rate[iRate]; + if (pDeviceInfo->minSampleRate > rate) { + pDeviceInfo->minSampleRate = rate; + } + if (pDeviceInfo->maxSampleRate < rate) { + pDeviceInfo->maxSampleRate = rate; + } + } + } + } + + ((ma_sio_close_proc)pContext->sndio.sio_close)(handle); + return MA_SUCCESS; +} + +void ma_device_uninit__sndio(ma_device* pDevice) +{ + ma_assert(pDevice != NULL); + + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + ((ma_sio_close_proc)pDevice->pContext->sndio.sio_close)((struct ma_sio_hdl*)pDevice->sndio.handleCapture); + } + + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + ((ma_sio_close_proc)pDevice->pContext->sndio.sio_close)((struct ma_sio_hdl*)pDevice->sndio.handlePlayback); + } +} + +ma_result ma_device_init_handle__sndio(ma_context* pContext, const ma_device_config* pConfig, ma_device_type deviceType, ma_device* pDevice) +{ + ma_result result; + const char* pDeviceName; + ma_ptr handle; + int openFlags = 0; + struct ma_sio_cap caps; + struct ma_sio_par par; + ma_device_id* pDeviceID; + ma_format format; + ma_uint32 channels; + ma_uint32 sampleRate; + ma_format internalFormat; + ma_uint32 internalChannels; + ma_uint32 internalSampleRate; + ma_uint32 internalBufferSizeInFrames; + ma_uint32 internalPeriods; + + ma_assert(pContext != NULL); + ma_assert(pConfig != NULL); + ma_assert(deviceType != ma_device_type_duplex); + ma_assert(pDevice != NULL); + + if (deviceType == ma_device_type_capture) { + openFlags = MA_SIO_REC; + pDeviceID = pConfig->capture.pDeviceID; + format = pConfig->capture.format; + channels = pConfig->capture.channels; + sampleRate = pConfig->sampleRate; + } else { + openFlags = MA_SIO_PLAY; + pDeviceID = pConfig->playback.pDeviceID; + format = pConfig->playback.format; + channels = pConfig->playback.channels; + sampleRate = pConfig->sampleRate; + } + + pDeviceName = MA_SIO_DEVANY; + if (pDeviceID != NULL) { + pDeviceName = pDeviceID->sndio; + } + + handle = (ma_ptr)((ma_sio_open_proc)pContext->sndio.sio_open)(pDeviceName, openFlags, 0); + if (handle == NULL) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[sndio] Failed to open device.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + + /* We need to retrieve the device caps to determine the most appropriate format to use. */ + if (((ma_sio_getcap_proc)pContext->sndio.sio_getcap)((struct ma_sio_hdl*)handle, &caps) == 0) { + ((ma_sio_close_proc)pContext->sndio.sio_close)((struct ma_sio_hdl*)handle); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[sndio] Failed to retrieve device caps.", MA_ERROR); + } + + /* + Note: sndio reports a huge range of available channels. This is inconvenient for us because there's no real + way, as far as I can tell, to get the _actual_ channel count of the device. I'm therefore restricting this + to the requested channels, regardless of whether or not the default channel count is requested. + + For hardware devices, I'm suspecting only a single channel count will be reported and we can safely use the + value returned by ma_find_best_channels_from_sio_cap__sndio(). + */ + if (deviceType == ma_device_type_capture) { + if (pDevice->capture.usingDefaultFormat) { + format = ma_find_best_format_from_sio_cap__sndio(&caps); + } + if (pDevice->capture.usingDefaultChannels) { + if (strlen(pDeviceName) > strlen("rsnd/") && strncmp(pDeviceName, "rsnd/", strlen("rsnd/")) == 0) { + channels = ma_find_best_channels_from_sio_cap__sndio(&caps, deviceType, format); + } + } + } else { + if (pDevice->playback.usingDefaultFormat) { + format = ma_find_best_format_from_sio_cap__sndio(&caps); + } + if (pDevice->playback.usingDefaultChannels) { + if (strlen(pDeviceName) > strlen("rsnd/") && strncmp(pDeviceName, "rsnd/", strlen("rsnd/")) == 0) { + channels = ma_find_best_channels_from_sio_cap__sndio(&caps, deviceType, format); + } + } + } + + if (pDevice->usingDefaultSampleRate) { + sampleRate = ma_find_best_sample_rate_from_sio_cap__sndio(&caps, pConfig->deviceType, format, channels); + } + + + ((ma_sio_initpar_proc)pDevice->pContext->sndio.sio_initpar)(&par); + par.msb = 0; + par.le = ma_is_little_endian(); + + switch (format) { + case ma_format_u8: + { + par.bits = 8; + par.bps = 1; + par.sig = 0; + } break; + + case ma_format_s24: + { + par.bits = 24; + par.bps = 3; + par.sig = 1; + } break; + + case ma_format_s32: + { + par.bits = 32; + par.bps = 4; + par.sig = 1; + } break; + + case ma_format_s16: + case ma_format_f32: + default: + { + par.bits = 16; + par.bps = 2; + par.sig = 1; + } break; + } + + if (deviceType == ma_device_type_capture) { + par.rchan = channels; + } else { + par.pchan = channels; + } + + par.rate = sampleRate; + + internalBufferSizeInFrames = pConfig->bufferSizeInFrames; + if (internalBufferSizeInFrames == 0) { + internalBufferSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(pConfig->bufferSizeInMilliseconds, par.rate); + } + + par.round = internalBufferSizeInFrames / pConfig->periods; + par.appbufsz = par.round * pConfig->periods; + + if (((ma_sio_setpar_proc)pContext->sndio.sio_setpar)((struct ma_sio_hdl*)handle, &par) == 0) { + ((ma_sio_close_proc)pContext->sndio.sio_close)((struct ma_sio_hdl*)handle); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[sndio] Failed to set buffer size.", MA_FORMAT_NOT_SUPPORTED); + } + if (((ma_sio_getpar_proc)pContext->sndio.sio_getpar)((struct ma_sio_hdl*)handle, &par) == 0) { + ((ma_sio_close_proc)pContext->sndio.sio_close)((struct ma_sio_hdl*)handle); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[sndio] Failed to retrieve buffer size.", MA_FORMAT_NOT_SUPPORTED); + } + + internalFormat = ma_format_from_sio_enc__sndio(par.bits, par.bps, par.sig, par.le, par.msb); + internalChannels = (deviceType == ma_device_type_capture) ? par.rchan : par.pchan; + internalSampleRate = par.rate; + internalPeriods = par.appbufsz / par.round; + internalBufferSizeInFrames = par.appbufsz; + + if (deviceType == ma_device_type_capture) { + pDevice->sndio.handleCapture = handle; + pDevice->capture.internalFormat = internalFormat; + pDevice->capture.internalChannels = internalChannels; + pDevice->capture.internalSampleRate = internalSampleRate; + ma_get_standard_channel_map(ma_standard_channel_map_sndio, pDevice->capture.internalChannels, pDevice->capture.internalChannelMap); + pDevice->capture.internalBufferSizeInFrames = internalBufferSizeInFrames; + pDevice->capture.internalPeriods = internalPeriods; + } else { + pDevice->sndio.handlePlayback = handle; + pDevice->playback.internalFormat = internalFormat; + pDevice->playback.internalChannels = internalChannels; + pDevice->playback.internalSampleRate = internalSampleRate; + ma_get_standard_channel_map(ma_standard_channel_map_sndio, pDevice->playback.internalChannels, pDevice->playback.internalChannelMap); + pDevice->playback.internalBufferSizeInFrames = internalBufferSizeInFrames; + pDevice->playback.internalPeriods = internalPeriods; + } + +#ifdef MA_DEBUG_OUTPUT + printf("DEVICE INFO\n"); + printf(" Format: %s\n", ma_get_format_name(internalFormat)); + printf(" Channels: %d\n", internalChannels); + printf(" Sample Rate: %d\n", internalSampleRate); + printf(" Buffer Size: %d\n", internalBufferSizeInFrames); + printf(" Periods: %d\n", internalPeriods); + printf(" appbufsz: %d\n", par.appbufsz); + printf(" round: %d\n", par.round); +#endif + + return MA_SUCCESS; +} + +ma_result ma_device_init__sndio(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice) +{ + ma_assert(pDevice != NULL); + + ma_zero_object(&pDevice->sndio); + + if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) { + ma_result result = ma_device_init_handle__sndio(pContext, pConfig, ma_device_type_capture, pDevice); + if (result != MA_SUCCESS) { + return result; + } + } + + if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) { + ma_result result = ma_device_init_handle__sndio(pContext, pConfig, ma_device_type_playback, pDevice); + if (result != MA_SUCCESS) { + return result; + } + } + + return MA_SUCCESS; +} + +ma_result ma_device_stop__sndio(ma_device* pDevice) +{ + ma_assert(pDevice != NULL); + + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + ((ma_sio_stop_proc)pDevice->pContext->sndio.sio_stop)((struct ma_sio_hdl*)pDevice->sndio.handleCapture); + ma_atomic_exchange_32(&pDevice->sndio.isStartedCapture, MA_FALSE); + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + ((ma_sio_stop_proc)pDevice->pContext->sndio.sio_stop)((struct ma_sio_hdl*)pDevice->sndio.handlePlayback); + ma_atomic_exchange_32(&pDevice->sndio.isStartedPlayback, MA_FALSE); + } + + return MA_SUCCESS; +} + +ma_result ma_device_write__sndio(ma_device* pDevice, const void* pPCMFrames, ma_uint32 frameCount) +{ + int result; + + if (!pDevice->sndio.isStartedPlayback) { + ((ma_sio_start_proc)pDevice->pContext->sndio.sio_start)((struct ma_sio_hdl*)pDevice->sndio.handlePlayback); /* <-- Doesn't actually playback until data is written. */ + ma_atomic_exchange_32(&pDevice->sndio.isStartedPlayback, MA_TRUE); + } + + result = ((ma_sio_write_proc)pDevice->pContext->sndio.sio_write)((struct ma_sio_hdl*)pDevice->sndio.handlePlayback, pPCMFrames, frameCount * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels)); + if (result == 0) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[sndio] Failed to send data from the client to the device.", MA_FAILED_TO_SEND_DATA_TO_DEVICE); + } + + return MA_SUCCESS; +} + +ma_result ma_device_read__sndio(ma_device* pDevice, void* pPCMFrames, ma_uint32 frameCount) +{ + int result; + + if (!pDevice->sndio.isStartedCapture) { + ((ma_sio_start_proc)pDevice->pContext->sndio.sio_start)((struct ma_sio_hdl*)pDevice->sndio.handleCapture); /* <-- Doesn't actually playback until data is written. */ + ma_atomic_exchange_32(&pDevice->sndio.isStartedCapture, MA_TRUE); + } + + result = ((ma_sio_read_proc)pDevice->pContext->sndio.sio_read)((struct ma_sio_hdl*)pDevice->sndio.handleCapture, pPCMFrames, frameCount * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels)); + if (result == 0) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[sndio] Failed to read data from the device to be sent to the device.", MA_FAILED_TO_SEND_DATA_TO_DEVICE); + } + + return MA_SUCCESS; +} + +ma_result ma_context_uninit__sndio(ma_context* pContext) +{ + ma_assert(pContext != NULL); + ma_assert(pContext->backend == ma_backend_sndio); + + (void)pContext; + return MA_SUCCESS; +} + +ma_result ma_context_init__sndio(ma_context* pContext) +{ + ma_assert(pContext != NULL); + +#ifndef MA_NO_RUNTIME_LINKING + // libpulse.so + const char* libsndioNames[] = { + "libsndio.so" + }; + + for (size_t i = 0; i < ma_countof(libsndioNames); ++i) { + pContext->sndio.sndioSO = ma_dlopen(libsndioNames[i]); + if (pContext->sndio.sndioSO != NULL) { + break; + } + } + + if (pContext->sndio.sndioSO == NULL) { + return MA_NO_BACKEND; + } + + pContext->sndio.sio_open = (ma_proc)ma_dlsym(pContext->sndio.sndioSO, "sio_open"); + pContext->sndio.sio_close = (ma_proc)ma_dlsym(pContext->sndio.sndioSO, "sio_close"); + pContext->sndio.sio_setpar = (ma_proc)ma_dlsym(pContext->sndio.sndioSO, "sio_setpar"); + pContext->sndio.sio_getpar = (ma_proc)ma_dlsym(pContext->sndio.sndioSO, "sio_getpar"); + pContext->sndio.sio_getcap = (ma_proc)ma_dlsym(pContext->sndio.sndioSO, "sio_getcap"); + pContext->sndio.sio_write = (ma_proc)ma_dlsym(pContext->sndio.sndioSO, "sio_write"); + pContext->sndio.sio_read = (ma_proc)ma_dlsym(pContext->sndio.sndioSO, "sio_read"); + pContext->sndio.sio_start = (ma_proc)ma_dlsym(pContext->sndio.sndioSO, "sio_start"); + pContext->sndio.sio_stop = (ma_proc)ma_dlsym(pContext->sndio.sndioSO, "sio_stop"); + pContext->sndio.sio_initpar = (ma_proc)ma_dlsym(pContext->sndio.sndioSO, "sio_initpar"); +#else + pContext->sndio.sio_open = sio_open; + pContext->sndio.sio_close = sio_close; + pContext->sndio.sio_setpar = sio_setpar; + pContext->sndio.sio_getpar = sio_getpar; + pContext->sndio.sio_getcap = sio_getcap; + pContext->sndio.sio_write = sio_write; + pContext->sndio.sio_read = sio_read; + pContext->sndio.sio_start = sio_start; + pContext->sndio.sio_stop = sio_stop; + pContext->sndio.sio_initpar = sio_initpar; +#endif + + pContext->onUninit = ma_context_uninit__sndio; + pContext->onDeviceIDEqual = ma_context_is_device_id_equal__sndio; + pContext->onEnumDevices = ma_context_enumerate_devices__sndio; + pContext->onGetDeviceInfo = ma_context_get_device_info__sndio; + pContext->onDeviceInit = ma_device_init__sndio; + pContext->onDeviceUninit = ma_device_uninit__sndio; + pContext->onDeviceStart = NULL; /* Not required for synchronous backends. */ + pContext->onDeviceStop = ma_device_stop__sndio; + pContext->onDeviceWrite = ma_device_write__sndio; + pContext->onDeviceRead = ma_device_read__sndio; + + return MA_SUCCESS; +} +#endif // sndio + + + +/////////////////////////////////////////////////////////////////////////////// +// +// audio(4) Backend +// +/////////////////////////////////////////////////////////////////////////////// +#ifdef MA_HAS_AUDIO4 +#include +#include +#include +#include +#include +#include +#include + +#if defined(__OpenBSD__) + #include + #if defined(OpenBSD) && OpenBSD >= 201709 + #define MA_AUDIO4_USE_NEW_API + #endif +#endif + +void ma_construct_device_id__audio4(char* id, size_t idSize, const char* base, int deviceIndex) +{ + ma_assert(id != NULL); + ma_assert(idSize > 0); + ma_assert(deviceIndex >= 0); + + size_t baseLen = strlen(base); + ma_assert(idSize > baseLen); + + ma_strcpy_s(id, idSize, base); + ma_itoa_s(deviceIndex, id+baseLen, idSize-baseLen, 10); +} + +ma_result ma_extract_device_index_from_id__audio4(const char* id, const char* base, int* pIndexOut) +{ + ma_assert(id != NULL); + ma_assert(base != NULL); + ma_assert(pIndexOut != NULL); + + size_t idLen = strlen(id); + size_t baseLen = strlen(base); + if (idLen <= baseLen) { + return MA_ERROR; // Doesn't look like the id starts with the base. + } + + if (strncmp(id, base, baseLen) != 0) { + return MA_ERROR; // ID does not begin with base. + } + + const char* deviceIndexStr = id + baseLen; + if (deviceIndexStr[0] == '\0') { + return MA_ERROR; // No index specified in the ID. + } + + if (pIndexOut) { + *pIndexOut = atoi(deviceIndexStr); + } + + return MA_SUCCESS; +} + +ma_bool32 ma_context_is_device_id_equal__audio4(ma_context* pContext, const ma_device_id* pID0, const ma_device_id* pID1) +{ + ma_assert(pContext != NULL); + ma_assert(pID0 != NULL); + ma_assert(pID1 != NULL); + (void)pContext; + + return ma_strcmp(pID0->audio4, pID1->audio4) == 0; +} + +#if !defined(MA_AUDIO4_USE_NEW_API) /* Old API */ +ma_format ma_format_from_encoding__audio4(unsigned int encoding, unsigned int precision) +{ + if (precision == 8 && (encoding == AUDIO_ENCODING_ULINEAR || encoding == AUDIO_ENCODING_ULINEAR || encoding == AUDIO_ENCODING_ULINEAR_LE || encoding == AUDIO_ENCODING_ULINEAR_BE)) { + return ma_format_u8; + } else { + if (ma_is_little_endian() && encoding == AUDIO_ENCODING_SLINEAR_LE) { + if (precision == 16) { + return ma_format_s16; + } else if (precision == 24) { + return ma_format_s24; + } else if (precision == 32) { + return ma_format_s32; + } + } else if (ma_is_big_endian() && encoding == AUDIO_ENCODING_SLINEAR_BE) { + if (precision == 16) { + return ma_format_s16; + } else if (precision == 24) { + return ma_format_s24; + } else if (precision == 32) { + return ma_format_s32; + } + } + } + + return ma_format_unknown; // Encoding not supported. +} + +void ma_encoding_from_format__audio4(ma_format format, unsigned int* pEncoding, unsigned int* pPrecision) +{ + ma_assert(format != ma_format_unknown); + ma_assert(pEncoding != NULL); + ma_assert(pPrecision != NULL); + + switch (format) + { + case ma_format_u8: + { + *pEncoding = AUDIO_ENCODING_ULINEAR; + *pPrecision = 8; + } break; + + case ma_format_s24: + { + *pEncoding = (ma_is_little_endian()) ? AUDIO_ENCODING_SLINEAR_LE : AUDIO_ENCODING_SLINEAR_BE; + *pPrecision = 24; + } break; + + case ma_format_s32: + { + *pEncoding = (ma_is_little_endian()) ? AUDIO_ENCODING_SLINEAR_LE : AUDIO_ENCODING_SLINEAR_BE; + *pPrecision = 32; + } break; + + case ma_format_s16: + case ma_format_f32: + default: + { + *pEncoding = (ma_is_little_endian()) ? AUDIO_ENCODING_SLINEAR_LE : AUDIO_ENCODING_SLINEAR_BE; + *pPrecision = 16; + } break; + } +} + +ma_format ma_format_from_prinfo__audio4(struct audio_prinfo* prinfo) +{ + return ma_format_from_encoding__audio4(prinfo->encoding, prinfo->precision); +} +#else +ma_format ma_format_from_swpar__audio4(struct audio_swpar* par) +{ + if (par->bits == 8 && par->bps == 1 && par->sig == 0) { + return ma_format_u8; + } + if (par->bits == 16 && par->bps == 2 && par->sig == 1 && par->le == ma_is_little_endian()) { + return ma_format_s16; + } + if (par->bits == 24 && par->bps == 3 && par->sig == 1 && par->le == ma_is_little_endian()) { + return ma_format_s24; + } + if (par->bits == 32 && par->bps == 4 && par->sig == 1 && par->le == ma_is_little_endian()) { + return ma_format_f32; + } + + // Format not supported. + return ma_format_unknown; +} +#endif + +ma_result ma_context_get_device_info_from_fd__audio4(ma_context* pContext, ma_device_type deviceType, int fd, ma_device_info* pInfoOut) +{ + ma_assert(pContext != NULL); + ma_assert(fd >= 0); + ma_assert(pInfoOut != NULL); + + (void)pContext; + (void)deviceType; + + audio_device_t fdDevice; + if (ioctl(fd, AUDIO_GETDEV, &fdDevice) < 0) { + return MA_ERROR; // Failed to retrieve device info. + } + + // Name. + ma_strcpy_s(pInfoOut->name, sizeof(pInfoOut->name), fdDevice.name); + +#if !defined(MA_AUDIO4_USE_NEW_API) + // Supported formats. We get this by looking at the encodings. + int counter = 0; + for (;;) { + audio_encoding_t encoding; + ma_zero_object(&encoding); + encoding.index = counter; + if (ioctl(fd, AUDIO_GETENC, &encoding) < 0) { + break; + } + + ma_format format = ma_format_from_encoding__audio4(encoding.encoding, encoding.precision); + if (format != ma_format_unknown) { + pInfoOut->formats[pInfoOut->formatCount++] = format; + } + + counter += 1; + } + + audio_info_t fdInfo; + if (ioctl(fd, AUDIO_GETINFO, &fdInfo) < 0) { + return MA_ERROR; + } + + if (deviceType == ma_device_type_playback) { + pInfoOut->minChannels = fdInfo.play.channels; + pInfoOut->maxChannels = fdInfo.play.channels; + pInfoOut->minSampleRate = fdInfo.play.sample_rate; + pInfoOut->maxSampleRate = fdInfo.play.sample_rate; + } else { + pInfoOut->minChannels = fdInfo.record.channels; + pInfoOut->maxChannels = fdInfo.record.channels; + pInfoOut->minSampleRate = fdInfo.record.sample_rate; + pInfoOut->maxSampleRate = fdInfo.record.sample_rate; + } +#else + struct audio_swpar fdPar; + if (ioctl(fd, AUDIO_GETPAR, &fdPar) < 0) { + return MA_ERROR; + } + + ma_format format = ma_format_from_swpar__audio4(&fdPar); + if (format == ma_format_unknown) { + return MA_FORMAT_NOT_SUPPORTED; + } + pInfoOut->formats[pInfoOut->formatCount++] = format; + + if (deviceType == ma_device_type_playback) { + pInfoOut->minChannels = fdPar.pchan; + pInfoOut->maxChannels = fdPar.pchan; + } else { + pInfoOut->minChannels = fdPar.rchan; + pInfoOut->maxChannels = fdPar.rchan; + } + + pInfoOut->minSampleRate = fdPar.rate; + pInfoOut->maxSampleRate = fdPar.rate; +#endif + + return MA_SUCCESS; +} + +ma_result ma_context_enumerate_devices__audio4(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData) +{ + ma_assert(pContext != NULL); + ma_assert(callback != NULL); + + const int maxDevices = 64; + + // Every device will be named "/dev/audioN", with a "/dev/audioctlN" equivalent. We use the "/dev/audioctlN" + // version here since we can open it even when another process has control of the "/dev/audioN" device. + char devpath[256]; + for (int iDevice = 0; iDevice < maxDevices; ++iDevice) { + ma_strcpy_s(devpath, sizeof(devpath), "/dev/audioctl"); + ma_itoa_s(iDevice, devpath+strlen(devpath), sizeof(devpath)-strlen(devpath), 10); + + struct stat st; + if (stat(devpath, &st) < 0) { + break; + } + + // The device exists, but we need to check if it's usable as playback and/or capture. + int fd; + ma_bool32 isTerminating = MA_FALSE; + + // Playback. + if (!isTerminating) { + fd = open(devpath, O_RDONLY, 0); + if (fd >= 0) { + // Supports playback. + ma_device_info deviceInfo; + ma_zero_object(&deviceInfo); + ma_construct_device_id__audio4(deviceInfo.id.audio4, sizeof(deviceInfo.id.audio4), "/dev/audio", iDevice); + if (ma_context_get_device_info_from_fd__audio4(pContext, ma_device_type_playback, fd, &deviceInfo) == MA_SUCCESS) { + isTerminating = !callback(pContext, ma_device_type_playback, &deviceInfo, pUserData); + } + + close(fd); + } + } + + // Capture. + if (!isTerminating) { + fd = open(devpath, O_WRONLY, 0); + if (fd >= 0) { + // Supports capture. + ma_device_info deviceInfo; + ma_zero_object(&deviceInfo); + ma_construct_device_id__audio4(deviceInfo.id.audio4, sizeof(deviceInfo.id.audio4), "/dev/audio", iDevice); + if (ma_context_get_device_info_from_fd__audio4(pContext, ma_device_type_capture, fd, &deviceInfo) == MA_SUCCESS) { + isTerminating = !callback(pContext, ma_device_type_capture, &deviceInfo, pUserData); + } + + close(fd); + } + } + + if (isTerminating) { + break; + } + } + + return MA_SUCCESS; +} + +ma_result ma_context_get_device_info__audio4(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_share_mode shareMode, ma_device_info* pDeviceInfo) +{ + ma_assert(pContext != NULL); + (void)shareMode; + + // We need to open the "/dev/audioctlN" device to get the info. To do this we need to extract the number + // from the device ID which will be in "/dev/audioN" format. + int fd = -1; + int deviceIndex = -1; + char ctlid[256]; + if (pDeviceID == NULL) { + // Default device. + ma_strcpy_s(ctlid, sizeof(ctlid), "/dev/audioctl"); + } else { + // Specific device. We need to convert from "/dev/audioN" to "/dev/audioctlN". + ma_result result = ma_extract_device_index_from_id__audio4(pDeviceID->audio4, "/dev/audio", &deviceIndex); + if (result != MA_SUCCESS) { + return result; + } + + ma_construct_device_id__audio4(ctlid, sizeof(ctlid), "/dev/audioctl", deviceIndex); + } + + fd = open(ctlid, (deviceType == ma_device_type_playback) ? O_WRONLY : O_RDONLY, 0); + if (fd == -1) { + return MA_NO_DEVICE; + } + + if (deviceIndex == -1) { + ma_strcpy_s(pDeviceInfo->id.audio4, sizeof(pDeviceInfo->id.audio4), "/dev/audio"); + } else { + ma_construct_device_id__audio4(pDeviceInfo->id.audio4, sizeof(pDeviceInfo->id.audio4), "/dev/audio", deviceIndex); + } + + ma_result result = ma_context_get_device_info_from_fd__audio4(pContext, deviceType, fd, pDeviceInfo); + + close(fd); + return result; +} + +void ma_device_uninit__audio4(ma_device* pDevice) +{ + ma_assert(pDevice != NULL); + + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + close(pDevice->audio4.fdCapture); + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + close(pDevice->audio4.fdPlayback); + } +} + +ma_result ma_device_init_fd__audio4(ma_context* pContext, const ma_device_config* pConfig, ma_device_type deviceType, ma_device* pDevice) +{ + const char* pDefaultDeviceNames[] = { + "/dev/audio", + "/dev/audio0" + }; + int fd; + int fdFlags = 0; +#if !defined(MA_AUDIO4_USE_NEW_API) /* Old API */ + audio_info_t fdInfo; +#else + struct audio_swpar fdPar; +#endif + ma_format internalFormat; + ma_uint32 internalChannels; + ma_uint32 internalSampleRate; + ma_uint32 internalBufferSizeInFrames; + ma_uint32 internalPeriods; + + ma_assert(pContext != NULL); + ma_assert(pConfig != NULL); + ma_assert(deviceType != ma_device_type_duplex); + ma_assert(pDevice != NULL); + + (void)pContext; + + /* The first thing to do is open the file. */ + if (deviceType == ma_device_type_capture) { + fdFlags = O_RDONLY; + } else { + fdFlags = O_WRONLY; + } + fdFlags |= O_NONBLOCK; + + if ((deviceType == ma_device_type_capture && pConfig->capture.pDeviceID == NULL) || (deviceType == ma_device_type_playback && pConfig->playback.pDeviceID == NULL)) { + /* Default device. */ + for (size_t iDevice = 0; iDevice < ma_countof(pDefaultDeviceNames); ++iDevice) { + fd = open(pDefaultDeviceNames[iDevice], fdFlags, 0); + if (fd != -1) { + break; + } + } + } else { + /* Specific device. */ + fd = open((deviceType == ma_device_type_capture) ? pConfig->capture.pDeviceID->audio4 : pConfig->playback.pDeviceID->audio4, fdFlags, 0); + } + + if (fd == -1) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[audio4] Failed to open device.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + +#if !defined(MA_AUDIO4_USE_NEW_API) /* Old API */ + AUDIO_INITINFO(&fdInfo); + + /* We get the driver to do as much of the data conversion as possible. */ + if (deviceType == ma_device_type_capture) { + fdInfo.mode = AUMODE_RECORD; + ma_encoding_from_format__audio4(pConfig->capture.format, &fdInfo.record.encoding, &fdInfo.record.precision); + fdInfo.record.channels = pConfig->capture.channels; + fdInfo.record.sample_rate = pConfig->sampleRate; + } else { + fdInfo.mode = AUMODE_PLAY; + ma_encoding_from_format__audio4(pConfig->playback.format, &fdInfo.play.encoding, &fdInfo.play.precision); + fdInfo.play.channels = pConfig->playback.channels; + fdInfo.play.sample_rate = pConfig->sampleRate; + } + + if (ioctl(fd, AUDIO_SETINFO, &fdInfo) < 0) { + close(fd); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[audio4] Failed to set device format. AUDIO_SETINFO failed.", MA_FORMAT_NOT_SUPPORTED); + } + + if (ioctl(fd, AUDIO_GETINFO, &fdInfo) < 0) { + close(fd); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[audio4] AUDIO_GETINFO failed.", MA_FORMAT_NOT_SUPPORTED); + } + + if (deviceType == ma_device_type_capture) { + internalFormat = ma_format_from_prinfo__audio4(&fdInfo.record); + internalChannels = fdInfo.record.channels; + internalSampleRate = fdInfo.record.sample_rate; + } else { + internalFormat = ma_format_from_prinfo__audio4(&fdInfo.play); + internalChannels = fdInfo.play.channels; + internalSampleRate = fdInfo.play.sample_rate; + } + + if (internalFormat == ma_format_unknown) { + close(fd); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[audio4] The device's internal device format is not supported by miniaudio. The device is unusable.", MA_FORMAT_NOT_SUPPORTED); + } + + /* Buffer. */ + { + ma_uint32 internalBufferSizeInBytes; + + internalBufferSizeInFrames = pConfig->bufferSizeInFrames; + if (internalBufferSizeInFrames == 0) { + internalBufferSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(pConfig->bufferSizeInMilliseconds, internalSampleRate); + } + + internalBufferSizeInBytes = internalBufferSizeInFrames * ma_get_bytes_per_frame(internalFormat, internalChannels); + if (internalBufferSizeInBytes < 16) { + internalBufferSizeInBytes = 16; + } + + internalPeriods = pConfig->periods; + if (internalPeriods < 2) { + internalPeriods = 2; + } + + /* What miniaudio calls a fragment, audio4 calls a block. */ + AUDIO_INITINFO(&fdInfo); + fdInfo.hiwat = internalPeriods; + fdInfo.lowat = internalPeriods-1; + fdInfo.blocksize = internalBufferSizeInBytes / internalPeriods; + if (ioctl(fd, AUDIO_SETINFO, &fdInfo) < 0) { + close(fd); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[audio4] Failed to set internal buffer size. AUDIO_SETINFO failed.", MA_FORMAT_NOT_SUPPORTED); + } + + internalPeriods = fdInfo.hiwat; + internalBufferSizeInFrames = (fdInfo.blocksize * fdInfo.hiwat) / ma_get_bytes_per_frame(internalFormat, internalChannels); + } +#else + /* We need to retrieve the format of the device so we can know the channel count and sample rate. Then we can calculate the buffer size. */ + if (ioctl(fd, AUDIO_GETPAR, &fdPar) < 0) { + close(fd); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[audio4] Failed to retrieve initial device parameters.", MA_FORMAT_NOT_SUPPORTED); + } + + internalFormat = ma_format_from_swpar__audio4(&fdPar); + internalChannels = (deviceType == ma_device_type_capture) ? fdPar.rchan : fdPar.pchan; + internalSampleRate = fdPar.rate; + + if (internalFormat == ma_format_unknown) { + close(fd); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[audio4] The device's internal device format is not supported by miniaudio. The device is unusable.", MA_FORMAT_NOT_SUPPORTED); + } + + /* Buffer. */ + { + ma_uint32 internalBufferSizeInBytes; + + internalBufferSizeInFrames = pConfig->bufferSizeInFrames; + if (internalBufferSizeInFrames == 0) { + internalBufferSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(pConfig->bufferSizeInMilliseconds, internalSampleRate); + } + + /* What miniaudio calls a fragment, audio4 calls a block. */ + internalBufferSizeInBytes = internalBufferSizeInFrames * ma_get_bytes_per_frame(internalFormat, internalChannels); + if (internalBufferSizeInBytes < 16) { + internalBufferSizeInBytes = 16; + } + + fdPar.nblks = pConfig->periods; + fdPar.round = internalBufferSizeInBytes / fdPar.nblks; + + if (ioctl(fd, AUDIO_SETPAR, &fdPar) < 0) { + close(fd); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[audio4] Failed to set device parameters.", MA_FORMAT_NOT_SUPPORTED); + } + + if (ioctl(fd, AUDIO_GETPAR, &fdPar) < 0) { + close(fd); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[audio4] Failed to retrieve actual device parameters.", MA_FORMAT_NOT_SUPPORTED); + } + } + + internalFormat = ma_format_from_swpar__audio4(&fdPar); + internalChannels = (deviceType == ma_device_type_capture) ? fdPar.rchan : fdPar.pchan; + internalSampleRate = fdPar.rate; + internalPeriods = fdPar.nblks; + internalBufferSizeInFrames = (fdPar.nblks * fdPar.round) / ma_get_bytes_per_frame(internalFormat, internalChannels); +#endif + + if (internalFormat == ma_format_unknown) { + close(fd); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[audio4] The device's internal device format is not supported by miniaudio. The device is unusable.", MA_FORMAT_NOT_SUPPORTED); + } + + if (deviceType == ma_device_type_capture) { + pDevice->audio4.fdCapture = fd; + pDevice->capture.internalFormat = internalFormat; + pDevice->capture.internalChannels = internalChannels; + pDevice->capture.internalSampleRate = internalSampleRate; + ma_get_standard_channel_map(ma_standard_channel_map_sound4, internalChannels, pDevice->capture.internalChannelMap); + pDevice->capture.internalBufferSizeInFrames = internalBufferSizeInFrames; + pDevice->capture.internalPeriods = internalPeriods; + } else { + pDevice->audio4.fdPlayback = fd; + pDevice->playback.internalFormat = internalFormat; + pDevice->playback.internalChannels = internalChannels; + pDevice->playback.internalSampleRate = internalSampleRate; + ma_get_standard_channel_map(ma_standard_channel_map_sound4, internalChannels, pDevice->playback.internalChannelMap); + pDevice->playback.internalBufferSizeInFrames = internalBufferSizeInFrames; + pDevice->playback.internalPeriods = internalPeriods; + } + + return MA_SUCCESS; +} + +ma_result ma_device_init__audio4(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice) +{ + ma_assert(pDevice != NULL); + + ma_zero_object(&pDevice->audio4); + + pDevice->audio4.fdCapture = -1; + pDevice->audio4.fdPlayback = -1; + + // The version of the operating system dictates whether or not the device is exclusive or shared. NetBSD + // introduced in-kernel mixing which means it's shared. All other BSD flavours are exclusive as far as + // I'm aware. +#if defined(__NetBSD_Version__) && __NetBSD_Version__ >= 800000000 + /* NetBSD 8.0+ */ + if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pConfig->playback.shareMode == ma_share_mode_exclusive) || + ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pConfig->capture.shareMode == ma_share_mode_exclusive)) { + return MA_SHARE_MODE_NOT_SUPPORTED; + } +#else + /* All other flavors. */ +#endif + + if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) { + ma_result result = ma_device_init_fd__audio4(pContext, pConfig, ma_device_type_capture, pDevice); + if (result != MA_SUCCESS) { + return result; + } + } + + if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) { + ma_result result = ma_device_init_fd__audio4(pContext, pConfig, ma_device_type_playback, pDevice); + if (result != MA_SUCCESS) { + if (pConfig->deviceType == ma_device_type_duplex) { + close(pDevice->audio4.fdCapture); + } + return result; + } + } + + return MA_SUCCESS; +} + +#if 0 +ma_result ma_device_start__audio4(ma_device* pDevice) +{ + ma_assert(pDevice != NULL); + + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + if (pDevice->audio4.fdCapture == -1) { + return MA_INVALID_ARGS; + } + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + if (pDevice->audio4.fdPlayback == -1) { + return MA_INVALID_ARGS; + } + } + + return MA_SUCCESS; +} +#endif + +ma_result ma_device_stop_fd__audio4(ma_device* pDevice, int fd) +{ + if (fd == -1) { + return MA_INVALID_ARGS; + } + +#if !defined(MA_AUDIO4_USE_NEW_API) + if (ioctl(fd, AUDIO_FLUSH, 0) < 0) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[audio4] Failed to stop device. AUDIO_FLUSH failed.", MA_FAILED_TO_STOP_BACKEND_DEVICE); + } +#else + if (ioctl(fd, AUDIO_STOP, 0) < 0) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[audio4] Failed to stop device. AUDIO_STOP failed.", MA_FAILED_TO_STOP_BACKEND_DEVICE); + } +#endif + + return MA_SUCCESS; +} + +ma_result ma_device_stop__audio4(ma_device* pDevice) +{ + ma_assert(pDevice != NULL); + + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + ma_result result = ma_device_stop_fd__audio4(pDevice, pDevice->audio4.fdCapture); + if (result != MA_SUCCESS) { + return result; + } + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + ma_result result = ma_device_stop_fd__audio4(pDevice, pDevice->audio4.fdPlayback); + if (result != MA_SUCCESS) { + return result; + } + } + + return MA_SUCCESS; +} + +ma_result ma_device_write__audio4(ma_device* pDevice, const void* pPCMFrames, ma_uint32 frameCount) +{ + int result = write(pDevice->audio4.fdPlayback, pPCMFrames, frameCount * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels)); + if (result < 0) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[audio4] Failed to write data to the device.", MA_FAILED_TO_SEND_DATA_TO_DEVICE); + } + + return MA_SUCCESS; +} + +ma_result ma_device_read__audio4(ma_device* pDevice, void* pPCMFrames, ma_uint32 frameCount) +{ + int result = read(pDevice->audio4.fdCapture, pPCMFrames, frameCount * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels)); + if (result < 0) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[audio4] Failed to read data from the device.", MA_FAILED_TO_READ_DATA_FROM_DEVICE); + } + + return MA_SUCCESS; +} + +ma_result ma_context_uninit__audio4(ma_context* pContext) +{ + ma_assert(pContext != NULL); + ma_assert(pContext->backend == ma_backend_audio4); + + (void)pContext; + return MA_SUCCESS; +} + +ma_result ma_context_init__audio4(ma_context* pContext) +{ + ma_assert(pContext != NULL); + + pContext->onUninit = ma_context_uninit__audio4; + pContext->onDeviceIDEqual = ma_context_is_device_id_equal__audio4; + pContext->onEnumDevices = ma_context_enumerate_devices__audio4; + pContext->onGetDeviceInfo = ma_context_get_device_info__audio4; + pContext->onDeviceInit = ma_device_init__audio4; + pContext->onDeviceUninit = ma_device_uninit__audio4; + pContext->onDeviceStart = NULL; + pContext->onDeviceStop = ma_device_stop__audio4; + pContext->onDeviceWrite = ma_device_write__audio4; + pContext->onDeviceRead = ma_device_read__audio4; + + return MA_SUCCESS; +} +#endif /* audio4 */ + + +/////////////////////////////////////////////////////////////////////////////// +// +// OSS Backend +// +/////////////////////////////////////////////////////////////////////////////// +#ifdef MA_HAS_OSS +#include +#include +#include +#include + +#ifndef SNDCTL_DSP_HALT +#define SNDCTL_DSP_HALT SNDCTL_DSP_RESET +#endif + +int ma_open_temp_device__oss() +{ + // The OSS sample code uses "/dev/mixer" as the device for getting system properties so I'm going to do the same. + int fd = open("/dev/mixer", O_RDONLY, 0); + if (fd >= 0) { + return fd; + } + + return -1; +} + +ma_result ma_context_open_device__oss(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_share_mode shareMode, int* pfd) +{ + ma_assert(pContext != NULL); + ma_assert(pfd != NULL); + (void)pContext; + + *pfd = -1; + + /* This function should only be called for playback or capture, not duplex. */ + if (deviceType == ma_device_type_duplex) { + return MA_INVALID_ARGS; + } + + const char* deviceName = "/dev/dsp"; + if (pDeviceID != NULL) { + deviceName = pDeviceID->oss; + } + + int flags = (deviceType == ma_device_type_playback) ? O_WRONLY : O_RDONLY; + if (shareMode == ma_share_mode_exclusive) { + flags |= O_EXCL; + } + + *pfd = open(deviceName, flags, 0); + if (*pfd == -1) { + return MA_FAILED_TO_OPEN_BACKEND_DEVICE; + } + + return MA_SUCCESS; +} + +ma_bool32 ma_context_is_device_id_equal__oss(ma_context* pContext, const ma_device_id* pID0, const ma_device_id* pID1) +{ + ma_assert(pContext != NULL); + ma_assert(pID0 != NULL); + ma_assert(pID1 != NULL); + (void)pContext; + + return ma_strcmp(pID0->oss, pID1->oss) == 0; +} + +ma_result ma_context_enumerate_devices__oss(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData) +{ + ma_assert(pContext != NULL); + ma_assert(callback != NULL); + + int fd = ma_open_temp_device__oss(); + if (fd == -1) { + return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[OSS] Failed to open a temporary device for retrieving system information used for device enumeration.", MA_NO_BACKEND); + } + + oss_sysinfo si; + int result = ioctl(fd, SNDCTL_SYSINFO, &si); + if (result != -1) { + for (int iAudioDevice = 0; iAudioDevice < si.numaudios; ++iAudioDevice) { + oss_audioinfo ai; + ai.dev = iAudioDevice; + result = ioctl(fd, SNDCTL_AUDIOINFO, &ai); + if (result != -1) { + if (ai.devnode[0] != '\0') { // <-- Can be blank, according to documentation. + ma_device_info deviceInfo; + ma_zero_object(&deviceInfo); + + // ID + ma_strncpy_s(deviceInfo.id.oss, sizeof(deviceInfo.id.oss), ai.devnode, (size_t)-1); + + // The human readable device name should be in the "ai.handle" variable, but it can + // sometimes be empty in which case we just fall back to "ai.name" which is less user + // friendly, but usually has a value. + if (ai.handle[0] != '\0') { + ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), ai.handle, (size_t)-1); + } else { + ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), ai.name, (size_t)-1); + } + + // The device can be both playback and capture. + ma_bool32 isTerminating = MA_FALSE; + if (!isTerminating && (ai.caps & PCM_CAP_OUTPUT) != 0) { + isTerminating = !callback(pContext, ma_device_type_playback, &deviceInfo, pUserData); + } + if (!isTerminating && (ai.caps & PCM_CAP_INPUT) != 0) { + isTerminating = !callback(pContext, ma_device_type_capture, &deviceInfo, pUserData); + } + + if (isTerminating) { + break; + } + } + } + } + } else { + close(fd); + return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[OSS] Failed to retrieve system information for device enumeration.", MA_NO_BACKEND); + } + + close(fd); + return MA_SUCCESS; +} + +ma_result ma_context_get_device_info__oss(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_share_mode shareMode, ma_device_info* pDeviceInfo) +{ + ma_assert(pContext != NULL); + (void)shareMode; + + // Handle the default device a little differently. + if (pDeviceID == NULL) { + if (deviceType == ma_device_type_playback) { + ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); + } else { + ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); + } + + return MA_SUCCESS; + } + + + // If we get here it means we are _not_ using the default device. + ma_bool32 foundDevice = MA_FALSE; + + int fdTemp = ma_open_temp_device__oss(); + if (fdTemp == -1) { + return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[OSS] Failed to open a temporary device for retrieving system information used for device enumeration.", MA_NO_BACKEND); + } + + oss_sysinfo si; + int result = ioctl(fdTemp, SNDCTL_SYSINFO, &si); + if (result != -1) { + for (int iAudioDevice = 0; iAudioDevice < si.numaudios; ++iAudioDevice) { + oss_audioinfo ai; + ai.dev = iAudioDevice; + result = ioctl(fdTemp, SNDCTL_AUDIOINFO, &ai); + if (result != -1) { + if (ma_strcmp(ai.devnode, pDeviceID->oss) == 0) { + // It has the same name, so now just confirm the type. + if ((deviceType == ma_device_type_playback && ((ai.caps & PCM_CAP_OUTPUT) != 0)) || + (deviceType == ma_device_type_capture && ((ai.caps & PCM_CAP_INPUT) != 0))) { + // ID + ma_strncpy_s(pDeviceInfo->id.oss, sizeof(pDeviceInfo->id.oss), ai.devnode, (size_t)-1); + + // The human readable device name should be in the "ai.handle" variable, but it can + // sometimes be empty in which case we just fall back to "ai.name" which is less user + // friendly, but usually has a value. + if (ai.handle[0] != '\0') { + ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), ai.handle, (size_t)-1); + } else { + ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), ai.name, (size_t)-1); + } + + pDeviceInfo->minChannels = ai.min_channels; + pDeviceInfo->maxChannels = ai.max_channels; + pDeviceInfo->minSampleRate = ai.min_rate; + pDeviceInfo->maxSampleRate = ai.max_rate; + pDeviceInfo->formatCount = 0; + + unsigned int formatMask; + if (deviceType == ma_device_type_playback) { + formatMask = ai.oformats; + } else { + formatMask = ai.iformats; + } + + if ((formatMask & AFMT_U8) != 0) { + pDeviceInfo->formats[pDeviceInfo->formatCount++] = ma_format_u8; + } + if (((formatMask & AFMT_S16_LE) != 0 && ma_is_little_endian()) || (AFMT_S16_BE && ma_is_big_endian())) { + pDeviceInfo->formats[pDeviceInfo->formatCount++] = ma_format_s16; + } + if (((formatMask & AFMT_S32_LE) != 0 && ma_is_little_endian()) || (AFMT_S32_BE && ma_is_big_endian())) { + pDeviceInfo->formats[pDeviceInfo->formatCount++] = ma_format_s32; + } + + foundDevice = MA_TRUE; + break; + } + } + } + } + } else { + close(fdTemp); + return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[OSS] Failed to retrieve system information for device enumeration.", MA_NO_BACKEND); + } + + + close(fdTemp); + + if (!foundDevice) { + return MA_NO_DEVICE; + } + + + return MA_SUCCESS; +} + +void ma_device_uninit__oss(ma_device* pDevice) +{ + ma_assert(pDevice != NULL); + + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + close(pDevice->oss.fdCapture); + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + close(pDevice->oss.fdPlayback); + } +} + +int ma_format_to_oss(ma_format format) +{ + int ossFormat = AFMT_U8; + switch (format) { + case ma_format_s16: ossFormat = (ma_is_little_endian()) ? AFMT_S16_LE : AFMT_S16_BE; break; + case ma_format_s24: ossFormat = (ma_is_little_endian()) ? AFMT_S32_LE : AFMT_S32_BE; break; + case ma_format_s32: ossFormat = (ma_is_little_endian()) ? AFMT_S32_LE : AFMT_S32_BE; break; + case ma_format_f32: ossFormat = (ma_is_little_endian()) ? AFMT_S16_LE : AFMT_S16_BE; break; + case ma_format_u8: + default: ossFormat = AFMT_U8; break; + } + + return ossFormat; +} + +ma_format ma_format_from_oss(int ossFormat) +{ + if (ossFormat == AFMT_U8) { + return ma_format_u8; + } else { + if (ma_is_little_endian()) { + switch (ossFormat) { + case AFMT_S16_LE: return ma_format_s16; + case AFMT_S32_LE: return ma_format_s32; + default: return ma_format_unknown; + } + } else { + switch (ossFormat) { + case AFMT_S16_BE: return ma_format_s16; + case AFMT_S32_BE: return ma_format_s32; + default: return ma_format_unknown; + } + } + } + + return ma_format_unknown; +} + +ma_result ma_device_init_fd__oss(ma_context* pContext, const ma_device_config* pConfig, ma_device_type deviceType, ma_device* pDevice) +{ + ma_result result; + int ossResult; + int fd; + const ma_device_id* pDeviceID = NULL; + ma_share_mode shareMode; + int ossFormat; + int ossChannels; + int ossSampleRate; + int ossFragment; + + ma_assert(pContext != NULL); + ma_assert(pConfig != NULL); + ma_assert(deviceType != ma_device_type_duplex); + ma_assert(pDevice != NULL); + + (void)pContext; + + if (deviceType == ma_device_type_capture) { + pDeviceID = pConfig->capture.pDeviceID; + shareMode = pConfig->capture.shareMode; + ossFormat = ma_format_to_oss(pConfig->capture.format); + ossChannels = (int)pConfig->capture.channels; + ossSampleRate = (int)pConfig->sampleRate; + } else { + pDeviceID = pConfig->playback.pDeviceID; + shareMode = pConfig->playback.shareMode; + ossFormat = ma_format_to_oss(pConfig->playback.format); + ossChannels = (int)pConfig->playback.channels; + ossSampleRate = (int)pConfig->sampleRate; + } + + result = ma_context_open_device__oss(pContext, deviceType, pDeviceID, shareMode, &fd); + if (result != MA_SUCCESS) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OSS] Failed to open device.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + + /* + The OSS documantation is very clear about the order we should be initializing the device's properties: + 1) Format + 2) Channels + 3) Sample rate. + */ + + /* Format. */ + ossResult = ioctl(fd, SNDCTL_DSP_SETFMT, &ossFormat); + if (ossResult == -1) { + close(fd); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OSS] Failed to set format.", MA_FORMAT_NOT_SUPPORTED); + } + + /* Channels. */ + ossResult = ioctl(fd, SNDCTL_DSP_CHANNELS, &ossChannels); + if (ossResult == -1) { + close(fd); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OSS] Failed to set channel count.", MA_FORMAT_NOT_SUPPORTED); + } + + /* Sample Rate. */ + ossResult = ioctl(fd, SNDCTL_DSP_SPEED, &ossSampleRate); + if (ossResult == -1) { + close(fd); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OSS] Failed to set sample rate.", MA_FORMAT_NOT_SUPPORTED); + } + + /* + Buffer. + + The documentation says that the fragment settings should be set as soon as possible, but I'm not sure if + it should be done before or after format/channels/rate. + + OSS wants the fragment size in bytes and a power of 2. When setting, we specify the power, not the actual + value. + */ + { + ma_uint32 fragmentSizeInBytes; + ma_uint32 bufferSizeInFrames; + ma_uint32 ossFragmentSizePower; + + bufferSizeInFrames = pConfig->bufferSizeInFrames; + if (bufferSizeInFrames == 0) { + bufferSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(pConfig->bufferSizeInMilliseconds, (ma_uint32)ossSampleRate); + } + + fragmentSizeInBytes = ma_round_to_power_of_2((bufferSizeInFrames / pConfig->periods) * ma_get_bytes_per_frame(ma_format_from_oss(ossFormat), ossChannels)); + if (fragmentSizeInBytes < 16) { + fragmentSizeInBytes = 16; + } + + ossFragmentSizePower = 4; + fragmentSizeInBytes >>= 4; + while (fragmentSizeInBytes >>= 1) { + ossFragmentSizePower += 1; + } + + ossFragment = (int)((pConfig->periods << 16) | ossFragmentSizePower); + ossResult = ioctl(fd, SNDCTL_DSP_SETFRAGMENT, &ossFragment); + if (ossResult == -1) { + close(fd); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OSS] Failed to set fragment size and period count.", MA_FORMAT_NOT_SUPPORTED); + } + } + + /* Internal settings. */ + if (deviceType == ma_device_type_capture) { + pDevice->oss.fdCapture = fd; + pDevice->capture.internalFormat = ma_format_from_oss(ossFormat); + pDevice->capture.internalChannels = ossChannels; + pDevice->capture.internalSampleRate = ossSampleRate; + ma_get_standard_channel_map(ma_standard_channel_map_sound4, pDevice->capture.internalChannels, pDevice->capture.internalChannelMap); + pDevice->capture.internalPeriods = (ma_uint32)(ossFragment >> 16); + pDevice->capture.internalBufferSizeInFrames = (((ma_uint32)(1 << (ossFragment & 0xFFFF))) * pDevice->capture.internalPeriods) / ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels); + + if (pDevice->capture.internalFormat == ma_format_unknown) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OSS] The device's internal format is not supported by miniaudio.", MA_FORMAT_NOT_SUPPORTED); + } + } else { + pDevice->oss.fdPlayback = fd; + pDevice->playback.internalFormat = ma_format_from_oss(ossFormat); + pDevice->playback.internalChannels = ossChannels; + pDevice->playback.internalSampleRate = ossSampleRate; + ma_get_standard_channel_map(ma_standard_channel_map_sound4, pDevice->playback.internalChannels, pDevice->playback.internalChannelMap); + pDevice->playback.internalPeriods = (ma_uint32)(ossFragment >> 16); + pDevice->playback.internalBufferSizeInFrames = (((ma_uint32)(1 << (ossFragment & 0xFFFF))) * pDevice->playback.internalPeriods) / ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels); + + if (pDevice->playback.internalFormat == ma_format_unknown) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OSS] The device's internal format is not supported by miniaudio.", MA_FORMAT_NOT_SUPPORTED); + } + } + + return MA_SUCCESS; +} + +ma_result ma_device_init__oss(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice) +{ + ma_assert(pContext != NULL); + ma_assert(pConfig != NULL); + ma_assert(pDevice != NULL); + + ma_zero_object(&pDevice->oss); + + if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) { + ma_result result = ma_device_init_fd__oss(pContext, pConfig, ma_device_type_capture, pDevice); + if (result != MA_SUCCESS) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OSS] Failed to open device.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + } + + if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) { + ma_result result = ma_device_init_fd__oss(pContext, pConfig, ma_device_type_playback, pDevice); + if (result != MA_SUCCESS) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OSS] Failed to open device.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + } + + return MA_SUCCESS; +} + +ma_result ma_device_stop__oss(ma_device* pDevice) +{ + ma_assert(pDevice != NULL); + + /* + We want to use SNDCTL_DSP_HALT. From the documentation: + + In multithreaded applications SNDCTL_DSP_HALT (SNDCTL_DSP_RESET) must only be called by the thread + that actually reads/writes the audio device. It must not be called by some master thread to kill the + audio thread. The audio thread will not stop or get any kind of notification that the device was + stopped by the master thread. The device gets stopped but the next read or write call will silently + restart the device. + + This is actually safe in our case, because this function is only ever called from within our worker + thread anyway. Just keep this in mind, though... + */ + + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + int result = ioctl(pDevice->oss.fdCapture, SNDCTL_DSP_HALT, 0); + if (result == -1) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OSS] Failed to stop device. SNDCTL_DSP_HALT failed.", MA_FAILED_TO_STOP_BACKEND_DEVICE); + } + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + int result = ioctl(pDevice->oss.fdPlayback, SNDCTL_DSP_HALT, 0); + if (result == -1) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OSS] Failed to stop device. SNDCTL_DSP_HALT failed.", MA_FAILED_TO_STOP_BACKEND_DEVICE); + } + } + + return MA_SUCCESS; +} + +ma_result ma_device_write__oss(ma_device* pDevice, const void* pPCMFrames, ma_uint32 frameCount) +{ + int resultOSS = write(pDevice->oss.fdPlayback, pPCMFrames, frameCount * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels)); + if (resultOSS < 0) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OSS] Failed to send data from the client to the device.", MA_FAILED_TO_SEND_DATA_TO_DEVICE); + } + + return MA_SUCCESS; +} + +ma_result ma_device_read__oss(ma_device* pDevice, void* pPCMFrames, ma_uint32 frameCount) +{ + int resultOSS = read(pDevice->oss.fdCapture, pPCMFrames, frameCount * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels)); + if (resultOSS < 0) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OSS] Failed to read data from the device to be sent to the client.", MA_FAILED_TO_READ_DATA_FROM_DEVICE); + } + + return MA_SUCCESS; +} + +ma_result ma_context_uninit__oss(ma_context* pContext) +{ + ma_assert(pContext != NULL); + ma_assert(pContext->backend == ma_backend_oss); + + (void)pContext; + return MA_SUCCESS; +} + +ma_result ma_context_init__oss(ma_context* pContext) +{ + ma_assert(pContext != NULL); + + /* Try opening a temporary device first so we can get version information. This is closed at the end. */ + int fd = ma_open_temp_device__oss(); + if (fd == -1) { + return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[OSS] Failed to open temporary device for retrieving system properties.", MA_NO_BACKEND); /* Looks liks OSS isn't installed, or there are no available devices. */ + } + + /* Grab the OSS version. */ + int ossVersion = 0; + int result = ioctl(fd, OSS_GETVERSION, &ossVersion); + if (result == -1) { + close(fd); + return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[OSS] Failed to retrieve OSS version.", MA_NO_BACKEND); + } + + pContext->oss.versionMajor = ((ossVersion & 0xFF0000) >> 16); + pContext->oss.versionMinor = ((ossVersion & 0x00FF00) >> 8); + + pContext->onUninit = ma_context_uninit__oss; + pContext->onDeviceIDEqual = ma_context_is_device_id_equal__oss; + pContext->onEnumDevices = ma_context_enumerate_devices__oss; + pContext->onGetDeviceInfo = ma_context_get_device_info__oss; + pContext->onDeviceInit = ma_device_init__oss; + pContext->onDeviceUninit = ma_device_uninit__oss; + pContext->onDeviceStart = NULL; /* Not required for synchronous backends. */ + pContext->onDeviceStop = ma_device_stop__oss; + pContext->onDeviceWrite = ma_device_write__oss; + pContext->onDeviceRead = ma_device_read__oss; + + close(fd); + return MA_SUCCESS; +} +#endif /* OSS */ + + +/////////////////////////////////////////////////////////////////////////////// +// +// AAudio Backend +// +/////////////////////////////////////////////////////////////////////////////// +#ifdef MA_HAS_AAUDIO +//#include + +#define MA_AAUDIO_UNSPECIFIED 0 + +typedef int32_t ma_aaudio_result_t; +typedef int32_t ma_aaudio_direction_t; +typedef int32_t ma_aaudio_sharing_mode_t; +typedef int32_t ma_aaudio_format_t; +typedef int32_t ma_aaudio_stream_state_t; +typedef int32_t ma_aaudio_performance_mode_t; +typedef int32_t ma_aaudio_data_callback_result_t; + +/* Result codes. miniaudio only cares about the success code. */ +#define MA_AAUDIO_OK 0 + +/* Directions. */ +#define MA_AAUDIO_DIRECTION_OUTPUT 0 +#define MA_AAUDIO_DIRECTION_INPUT 1 + +/* Sharing modes. */ +#define MA_AAUDIO_SHARING_MODE_EXCLUSIVE 0 +#define MA_AAUDIO_SHARING_MODE_SHARED 1 + +/* Formats. */ +#define MA_AAUDIO_FORMAT_PCM_I16 1 +#define MA_AAUDIO_FORMAT_PCM_FLOAT 2 + +/* Stream states. */ +#define MA_AAUDIO_STREAM_STATE_UNINITIALIZED 0 +#define MA_AAUDIO_STREAM_STATE_UNKNOWN 1 +#define MA_AAUDIO_STREAM_STATE_OPEN 2 +#define MA_AAUDIO_STREAM_STATE_STARTING 3 +#define MA_AAUDIO_STREAM_STATE_STARTED 4 +#define MA_AAUDIO_STREAM_STATE_PAUSING 5 +#define MA_AAUDIO_STREAM_STATE_PAUSED 6 +#define MA_AAUDIO_STREAM_STATE_FLUSHING 7 +#define MA_AAUDIO_STREAM_STATE_FLUSHED 8 +#define MA_AAUDIO_STREAM_STATE_STOPPING 9 +#define MA_AAUDIO_STREAM_STATE_STOPPED 10 +#define MA_AAUDIO_STREAM_STATE_CLOSING 11 +#define MA_AAUDIO_STREAM_STATE_CLOSED 12 +#define MA_AAUDIO_STREAM_STATE_DISCONNECTED 13 + +/* Performance modes. */ +#define MA_AAUDIO_PERFORMANCE_MODE_NONE 10 +#define MA_AAUDIO_PERFORMANCE_MODE_POWER_SAVING 11 +#define MA_AAUDIO_PERFORMANCE_MODE_LOW_LATENCY 12 + +/* Callback results. */ +#define MA_AAUDIO_CALLBACK_RESULT_CONTINUE 0 +#define MA_AAUDIO_CALLBACK_RESULT_STOP 1 + +/* Objects. */ +typedef struct ma_AAudioStreamBuilder_t* ma_AAudioStreamBuilder; +typedef struct ma_AAudioStream_t* ma_AAudioStream; + +typedef ma_aaudio_data_callback_result_t (*ma_AAudioStream_dataCallback)(ma_AAudioStream* pStream, void* pUserData, void* pAudioData, int32_t numFrames); + +typedef ma_aaudio_result_t (* MA_PFN_AAudio_createStreamBuilder) (ma_AAudioStreamBuilder** ppBuilder); +typedef ma_aaudio_result_t (* MA_PFN_AAudioStreamBuilder_delete) (ma_AAudioStreamBuilder* pBuilder); +typedef void (* MA_PFN_AAudioStreamBuilder_setDeviceId) (ma_AAudioStreamBuilder* pBuilder, int32_t deviceId); +typedef void (* MA_PFN_AAudioStreamBuilder_setDirection) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_direction_t direction); +typedef void (* MA_PFN_AAudioStreamBuilder_setSharingMode) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_sharing_mode_t sharingMode); +typedef void (* MA_PFN_AAudioStreamBuilder_setFormat) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_format_t format); +typedef void (* MA_PFN_AAudioStreamBuilder_setChannelCount) (ma_AAudioStreamBuilder* pBuilder, int32_t channelCount); +typedef void (* MA_PFN_AAudioStreamBuilder_setSampleRate) (ma_AAudioStreamBuilder* pBuilder, int32_t sampleRate); +typedef void (* MA_PFN_AAudioStreamBuilder_setBufferCapacityInFrames)(ma_AAudioStreamBuilder* pBuilder, int32_t numFrames); +typedef void (* MA_PFN_AAudioStreamBuilder_setFramesPerDataCallback) (ma_AAudioStreamBuilder* pBuilder, int32_t numFrames); +typedef void (* MA_PFN_AAudioStreamBuilder_setDataCallback) (ma_AAudioStreamBuilder* pBuilder, ma_AAudioStream_dataCallback callback, void* pUserData); +typedef void (* MA_PFN_AAudioStreamBuilder_setPerformanceMode) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_performance_mode_t mode); +typedef ma_aaudio_result_t (* MA_PFN_AAudioStreamBuilder_openStream) (ma_AAudioStreamBuilder* pBuilder, ma_AAudioStream** ppStream); +typedef ma_aaudio_result_t (* MA_PFN_AAudioStream_close) (ma_AAudioStream* pStream); +typedef ma_aaudio_stream_state_t (* MA_PFN_AAudioStream_getState) (ma_AAudioStream* pStream); +typedef ma_aaudio_result_t (* MA_PFN_AAudioStream_waitForStateChange) (ma_AAudioStream* pStream, ma_aaudio_stream_state_t inputState, ma_aaudio_stream_state_t* pNextState, int64_t timeoutInNanoseconds); +typedef ma_aaudio_format_t (* MA_PFN_AAudioStream_getFormat) (ma_AAudioStream* pStream); +typedef int32_t (* MA_PFN_AAudioStream_getChannelCount) (ma_AAudioStream* pStream); +typedef int32_t (* MA_PFN_AAudioStream_getSampleRate) (ma_AAudioStream* pStream); +typedef int32_t (* MA_PFN_AAudioStream_getBufferCapacityInFrames) (ma_AAudioStream* pStream); +typedef int32_t (* MA_PFN_AAudioStream_getFramesPerDataCallback) (ma_AAudioStream* pStream); +typedef int32_t (* MA_PFN_AAudioStream_getFramesPerBurst) (ma_AAudioStream* pStream); +typedef ma_aaudio_result_t (* MA_PFN_AAudioStream_requestStart) (ma_AAudioStream* pStream); +typedef ma_aaudio_result_t (* MA_PFN_AAudioStream_requestStop) (ma_AAudioStream* pStream); + +ma_result ma_result_from_aaudio(ma_aaudio_result_t resultAA) +{ + switch (resultAA) + { + case MA_AAUDIO_OK: return MA_SUCCESS; + default: break; + } + + return MA_ERROR; +} + +ma_aaudio_data_callback_result_t ma_stream_data_callback_capture__aaudio(ma_AAudioStream* pStream, void* pUserData, void* pAudioData, int32_t frameCount) +{ + ma_device* pDevice = (ma_device*)pUserData; + ma_assert(pDevice != NULL); + + if (pDevice->type == ma_device_type_duplex) { + ma_device__handle_duplex_callback_capture(pDevice, frameCount, pAudioData, &pDevice->aaudio.duplexRB); + } else { + ma_device__send_frames_to_client(pDevice, frameCount, pAudioData); /* Send directly to the client. */ + } + + (void)pStream; + return MA_AAUDIO_CALLBACK_RESULT_CONTINUE; +} + +ma_aaudio_data_callback_result_t ma_stream_data_callback_playback__aaudio(ma_AAudioStream* pStream, void* pUserData, void* pAudioData, int32_t frameCount) +{ + ma_device* pDevice = (ma_device*)pUserData; + ma_assert(pDevice != NULL); + + if (pDevice->type == ma_device_type_duplex) { + ma_device__handle_duplex_callback_playback(pDevice, frameCount, pAudioData, &pDevice->aaudio.duplexRB); + } else { + ma_device__read_frames_from_client(pDevice, frameCount, pAudioData); /* Read directly from the client. */ + } + + (void)pStream; + return MA_AAUDIO_CALLBACK_RESULT_CONTINUE; +} + +ma_result ma_open_stream__aaudio(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_share_mode shareMode, const ma_device_config* pConfig, const ma_device* pDevice, ma_AAudioStream** ppStream) +{ + ma_AAudioStreamBuilder* pBuilder; + ma_aaudio_result_t resultAA; + + ma_assert(deviceType != ma_device_type_duplex); /* This function should not be called for a full-duplex device type. */ + + *ppStream = NULL; + + resultAA = ((MA_PFN_AAudio_createStreamBuilder)pContext->aaudio.AAudio_createStreamBuilder)(&pBuilder); + if (resultAA != MA_AAUDIO_OK) { + return ma_result_from_aaudio(resultAA); + } + + if (pDeviceID != NULL) { + ((MA_PFN_AAudioStreamBuilder_setDeviceId)pContext->aaudio.AAudioStreamBuilder_setDeviceId)(pBuilder, pDeviceID->aaudio); + } + + ((MA_PFN_AAudioStreamBuilder_setDirection)pContext->aaudio.AAudioStreamBuilder_setDirection)(pBuilder, (deviceType == ma_device_type_playback) ? MA_AAUDIO_DIRECTION_OUTPUT : MA_AAUDIO_DIRECTION_INPUT); + ((MA_PFN_AAudioStreamBuilder_setSharingMode)pContext->aaudio.AAudioStreamBuilder_setSharingMode)(pBuilder, (shareMode == ma_share_mode_shared) ? MA_AAUDIO_SHARING_MODE_SHARED : MA_AAUDIO_SHARING_MODE_EXCLUSIVE); + + if (pConfig != NULL) { + if (pDevice == NULL || !pDevice->usingDefaultSampleRate) { + ((MA_PFN_AAudioStreamBuilder_setSampleRate)pContext->aaudio.AAudioStreamBuilder_setSampleRate)(pBuilder, pConfig->sampleRate); + } + + if (deviceType == ma_device_type_capture) { + if (pDevice == NULL || !pDevice->capture.usingDefaultChannels) { + ((MA_PFN_AAudioStreamBuilder_setChannelCount)pContext->aaudio.AAudioStreamBuilder_setChannelCount)(pBuilder, pConfig->capture.channels); + } + if (pDevice == NULL || !pDevice->capture.usingDefaultFormat) { + ((MA_PFN_AAudioStreamBuilder_setFormat)pContext->aaudio.AAudioStreamBuilder_setFormat)(pBuilder, (pConfig->capture.format == ma_format_s16) ? MA_AAUDIO_FORMAT_PCM_I16 : MA_AAUDIO_FORMAT_PCM_FLOAT); + } + } else { + if (pDevice == NULL || !pDevice->playback.usingDefaultChannels) { + ((MA_PFN_AAudioStreamBuilder_setChannelCount)pContext->aaudio.AAudioStreamBuilder_setChannelCount)(pBuilder, pConfig->playback.channels); + } + if (pDevice == NULL || !pDevice->playback.usingDefaultFormat) { + ((MA_PFN_AAudioStreamBuilder_setFormat)pContext->aaudio.AAudioStreamBuilder_setFormat)(pBuilder, (pConfig->playback.format == ma_format_s16) ? MA_AAUDIO_FORMAT_PCM_I16 : MA_AAUDIO_FORMAT_PCM_FLOAT); + } + } + + ma_uint32 bufferCapacityInFrames = pConfig->bufferSizeInFrames; + if (bufferCapacityInFrames == 0) { + bufferCapacityInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(pConfig->bufferSizeInMilliseconds, pConfig->sampleRate); + } + ((MA_PFN_AAudioStreamBuilder_setBufferCapacityInFrames)pContext->aaudio.AAudioStreamBuilder_setBufferCapacityInFrames)(pBuilder, bufferCapacityInFrames); + + ((MA_PFN_AAudioStreamBuilder_setFramesPerDataCallback)pContext->aaudio.AAudioStreamBuilder_setFramesPerDataCallback)(pBuilder, bufferCapacityInFrames / pConfig->periods); + + if (deviceType == ma_device_type_capture) { + ((MA_PFN_AAudioStreamBuilder_setDataCallback)pContext->aaudio.AAudioStreamBuilder_setDataCallback)(pBuilder, ma_stream_data_callback_capture__aaudio, (void*)pDevice); + } else { + ((MA_PFN_AAudioStreamBuilder_setDataCallback)pContext->aaudio.AAudioStreamBuilder_setDataCallback)(pBuilder, ma_stream_data_callback_playback__aaudio, (void*)pDevice); + } + + /* Not sure how this affects things, but since there's a mapping between miniaudio's performance profiles and AAudio's performance modes, let go ahead and set it. */ + ((MA_PFN_AAudioStreamBuilder_setPerformanceMode)pContext->aaudio.AAudioStreamBuilder_setPerformanceMode)(pBuilder, (pConfig->performanceProfile == ma_performance_profile_low_latency) ? MA_AAUDIO_PERFORMANCE_MODE_LOW_LATENCY : MA_AAUDIO_PERFORMANCE_MODE_NONE); + } + + resultAA = ((MA_PFN_AAudioStreamBuilder_openStream)pContext->aaudio.AAudioStreamBuilder_openStream)(pBuilder, ppStream); + if (resultAA != MA_AAUDIO_OK) { + *ppStream = NULL; + ((MA_PFN_AAudioStreamBuilder_delete)pContext->aaudio.AAudioStreamBuilder_delete)(pBuilder); + return ma_result_from_aaudio(resultAA); + } + + ((MA_PFN_AAudioStreamBuilder_delete)pContext->aaudio.AAudioStreamBuilder_delete)(pBuilder); + return MA_SUCCESS; +} + +ma_result ma_close_stream__aaudio(ma_context* pContext, ma_AAudioStream* pStream) +{ + return ma_result_from_aaudio(((MA_PFN_AAudioStream_close)pContext->aaudio.AAudioStream_close)(pStream)); +} + +ma_bool32 ma_has_default_device__aaudio(ma_context* pContext, ma_device_type deviceType) +{ + /* The only way to know this is to try creating a stream. */ + ma_AAudioStream* pStream; + ma_result result = ma_open_stream__aaudio(pContext, deviceType, NULL, ma_share_mode_shared, NULL, NULL, &pStream); + if (result != MA_SUCCESS) { + return MA_FALSE; + } + + ma_close_stream__aaudio(pContext, pStream); + return MA_TRUE; +} + +ma_result ma_wait_for_simple_state_transition__aaudio(ma_context* pContext, ma_AAudioStream* pStream, ma_aaudio_stream_state_t oldState, ma_aaudio_stream_state_t newState) +{ + ma_aaudio_stream_state_t actualNewState; + ma_aaudio_result_t resultAA = ((MA_PFN_AAudioStream_waitForStateChange)pContext->aaudio.AAudioStream_waitForStateChange)(pStream, oldState, &actualNewState, 5000000000); /* 5 second timeout. */ + if (resultAA != MA_AAUDIO_OK) { + return ma_result_from_aaudio(resultAA); + } + + if (newState != actualNewState) { + return MA_ERROR; /* Failed to transition into the expected state. */ + } + + return MA_SUCCESS; +} + + +ma_bool32 ma_context_is_device_id_equal__aaudio(ma_context* pContext, const ma_device_id* pID0, const ma_device_id* pID1) +{ + ma_assert(pContext != NULL); + ma_assert(pID0 != NULL); + ma_assert(pID1 != NULL); + (void)pContext; + + return pID0->aaudio == pID1->aaudio; +} + +ma_result ma_context_enumerate_devices__aaudio(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData) +{ + ma_bool32 cbResult = MA_TRUE; + + ma_assert(pContext != NULL); + ma_assert(callback != NULL); + + /* Unfortunately AAudio does not have an enumeration API. Therefore I'm only going to report default devices, but only if it can instantiate a stream. */ + + /* Playback. */ + if (cbResult) { + ma_device_info deviceInfo; + ma_zero_object(&deviceInfo); + deviceInfo.id.aaudio = MA_AAUDIO_UNSPECIFIED; + ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); + + if (ma_has_default_device__aaudio(pContext, ma_device_type_playback)) { + cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData); + } + } + + /* Capture. */ + if (cbResult) { + ma_device_info deviceInfo; + ma_zero_object(&deviceInfo); + deviceInfo.id.aaudio = MA_AAUDIO_UNSPECIFIED; + ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); + + if (ma_has_default_device__aaudio(pContext, ma_device_type_capture)) { + cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData); + } + } + + return MA_SUCCESS; +} + +ma_result ma_context_get_device_info__aaudio(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_share_mode shareMode, ma_device_info* pDeviceInfo) +{ + ma_AAudioStream* pStream; + ma_result result; + + ma_assert(pContext != NULL); + + /* No exclusive mode with AAudio. */ + if (shareMode == ma_share_mode_exclusive) { + return MA_SHARE_MODE_NOT_SUPPORTED; + } + + /* ID */ + if (pDeviceID != NULL) { + pDeviceInfo->id.aaudio = pDeviceID->aaudio; + } else { + pDeviceInfo->id.aaudio = MA_AAUDIO_UNSPECIFIED; + } + + /* Name */ + if (deviceType == ma_device_type_playback) { + ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); + } else { + ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); + } + + + /* We'll need to open the device to get accurate sample rate and channel count information. */ + result = ma_open_stream__aaudio(pContext, deviceType, pDeviceID, shareMode, NULL, NULL, &pStream); + if (result != MA_SUCCESS) { + return result; + } + + pDeviceInfo->minChannels = ((MA_PFN_AAudioStream_getChannelCount)pContext->aaudio.AAudioStream_getChannelCount)(pStream); + pDeviceInfo->maxChannels = pDeviceInfo->minChannels; + pDeviceInfo->minSampleRate = ((MA_PFN_AAudioStream_getSampleRate)pContext->aaudio.AAudioStream_getSampleRate)(pStream); + pDeviceInfo->maxSampleRate = pDeviceInfo->minSampleRate; + + ma_close_stream__aaudio(pContext, pStream); + pStream = NULL; + + + /* AAudio supports s16 and f32. */ + pDeviceInfo->formatCount = 2; + pDeviceInfo->formats[0] = ma_format_s16; + pDeviceInfo->formats[1] = ma_format_f32; + + return MA_SUCCESS; +} + + +void ma_device_uninit__aaudio(ma_device* pDevice) +{ + ma_assert(pDevice != NULL); + + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + ma_close_stream__aaudio(pDevice->pContext, (ma_AAudioStream*)pDevice->aaudio.pStreamCapture); + pDevice->aaudio.pStreamCapture = NULL; + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + ma_close_stream__aaudio(pDevice->pContext, (ma_AAudioStream*)pDevice->aaudio.pStreamPlayback); + pDevice->aaudio.pStreamPlayback = NULL; + } + + if (pDevice->type == ma_device_type_duplex) { + ma_pcm_rb_uninit(&pDevice->aaudio.duplexRB); + } +} + +ma_result ma_device_init__aaudio(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice) +{ + ma_result result; + + ma_assert(pDevice != NULL); + + /* No exclusive mode with AAudio. */ + if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pConfig->playback.shareMode == ma_share_mode_exclusive) || + ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pConfig->capture.shareMode == ma_share_mode_exclusive)) { + return MA_SHARE_MODE_NOT_SUPPORTED; + } + + /* We first need to try opening the stream. */ + if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) { + result = ma_open_stream__aaudio(pContext, ma_device_type_capture, pConfig->capture.pDeviceID, pConfig->capture.shareMode, pConfig, pDevice, (ma_AAudioStream**)&pDevice->aaudio.pStreamCapture); + if (result != MA_SUCCESS) { + return result; /* Failed to open the AAudio stream. */ + } + + pDevice->capture.internalFormat = (((MA_PFN_AAudioStream_getFormat)pContext->aaudio.AAudioStream_getFormat)((ma_AAudioStream*)pDevice->aaudio.pStreamCapture) == MA_AAUDIO_FORMAT_PCM_I16) ? ma_format_s16 : ma_format_f32; + pDevice->capture.internalChannels = ((MA_PFN_AAudioStream_getChannelCount)pContext->aaudio.AAudioStream_getChannelCount)((ma_AAudioStream*)pDevice->aaudio.pStreamCapture); + pDevice->capture.internalSampleRate = ((MA_PFN_AAudioStream_getSampleRate)pContext->aaudio.AAudioStream_getSampleRate)((ma_AAudioStream*)pDevice->aaudio.pStreamCapture); + ma_get_standard_channel_map(ma_standard_channel_map_default, pDevice->capture.internalChannels, pDevice->capture.internalChannelMap); /* <-- Cannot find info on channel order, so assuming a default. */ + pDevice->capture.internalBufferSizeInFrames = ((MA_PFN_AAudioStream_getBufferCapacityInFrames)pContext->aaudio.AAudioStream_getBufferCapacityInFrames)((ma_AAudioStream*)pDevice->aaudio.pStreamCapture); + + /* TODO: When synchronous reading and writing is supported, use AAudioStream_getFramesPerBurst() instead of AAudioStream_getFramesPerDataCallback(). Keep + * using AAudioStream_getFramesPerDataCallback() for asynchronous mode, though. */ + int32_t framesPerPeriod = ((MA_PFN_AAudioStream_getFramesPerDataCallback)pContext->aaudio.AAudioStream_getFramesPerDataCallback)((ma_AAudioStream*)pDevice->aaudio.pStreamCapture); + if (framesPerPeriod > 0) { + pDevice->capture.internalPeriods = 1; + } else { + pDevice->capture.internalPeriods = pDevice->capture.internalBufferSizeInFrames / framesPerPeriod; + } + } + + if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) { + result = ma_open_stream__aaudio(pContext, ma_device_type_playback, pConfig->playback.pDeviceID, pConfig->playback.shareMode, pConfig, pDevice, (ma_AAudioStream**)&pDevice->aaudio.pStreamPlayback); + if (result != MA_SUCCESS) { + return result; /* Failed to open the AAudio stream. */ + } + + pDevice->playback.internalFormat = (((MA_PFN_AAudioStream_getFormat)pContext->aaudio.AAudioStream_getFormat)((ma_AAudioStream*)pDevice->aaudio.pStreamPlayback) == MA_AAUDIO_FORMAT_PCM_I16) ? ma_format_s16 : ma_format_f32; + pDevice->playback.internalChannels = ((MA_PFN_AAudioStream_getChannelCount)pContext->aaudio.AAudioStream_getChannelCount)((ma_AAudioStream*)pDevice->aaudio.pStreamPlayback); + pDevice->playback.internalSampleRate = ((MA_PFN_AAudioStream_getSampleRate)pContext->aaudio.AAudioStream_getSampleRate)((ma_AAudioStream*)pDevice->aaudio.pStreamPlayback); + ma_get_standard_channel_map(ma_standard_channel_map_default, pDevice->playback.internalChannels, pDevice->playback.internalChannelMap); /* <-- Cannot find info on channel order, so assuming a default. */ + pDevice->playback.internalBufferSizeInFrames = ((MA_PFN_AAudioStream_getBufferCapacityInFrames)pContext->aaudio.AAudioStream_getBufferCapacityInFrames)((ma_AAudioStream*)pDevice->aaudio.pStreamPlayback); + + int32_t framesPerPeriod = ((MA_PFN_AAudioStream_getFramesPerDataCallback)pContext->aaudio.AAudioStream_getFramesPerDataCallback)((ma_AAudioStream*)pDevice->aaudio.pStreamPlayback); + if (framesPerPeriod > 0) { + pDevice->playback.internalPeriods = 1; + } else { + pDevice->playback.internalPeriods = pDevice->playback.internalBufferSizeInFrames / framesPerPeriod; + } + } + + if (pConfig->deviceType == ma_device_type_duplex) { + ma_uint32 rbSizeInFrames = (ma_uint32)ma_calculate_frame_count_after_src(pDevice->sampleRate, pDevice->capture.internalSampleRate, pDevice->capture.internalBufferSizeInFrames); + ma_result result = ma_pcm_rb_init(pDevice->capture.format, pDevice->capture.channels, rbSizeInFrames, NULL, &pDevice->aaudio.duplexRB); + if (result != MA_SUCCESS) { + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + ma_close_stream__aaudio(pDevice->pContext, (ma_AAudioStream*)pDevice->aaudio.pStreamCapture); + } + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + ma_close_stream__aaudio(pDevice->pContext, (ma_AAudioStream*)pDevice->aaudio.pStreamPlayback); + } + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[AAudio] Failed to initialize ring buffer.", result); + } + } + + return MA_SUCCESS; +} + +ma_result ma_device_start_stream__aaudio(ma_device* pDevice, ma_AAudioStream* pStream) +{ + ma_aaudio_result_t resultAA; + + ma_assert(pDevice != NULL); + + resultAA = ((MA_PFN_AAudioStream_requestStart)pDevice->pContext->aaudio.AAudioStream_requestStart)(pStream); + if (resultAA != MA_AAUDIO_OK) { + return ma_result_from_aaudio(resultAA); + } + + /* Do we actually need to wait for the device to transition into it's started state? */ + + /* The device should be in either a starting or started state. If it's not set to started we need to wait for it to transition. It should go from starting to started. */ + ma_aaudio_stream_state_t currentState = ((MA_PFN_AAudioStream_getState)pDevice->pContext->aaudio.AAudioStream_getState)(pStream); + if (currentState != MA_AAUDIO_STREAM_STATE_STARTED) { + ma_result result; + + if (currentState != MA_AAUDIO_STREAM_STATE_STARTING) { + return MA_ERROR; /* Expecting the stream to be a starting or started state. */ + } + + result = ma_wait_for_simple_state_transition__aaudio(pDevice->pContext, pStream, currentState, MA_AAUDIO_STREAM_STATE_STARTED); + if (result != MA_SUCCESS) { + return result; + } + } + + return MA_SUCCESS; +} + +ma_result ma_device_stop_stream__aaudio(ma_device* pDevice, ma_AAudioStream* pStream) +{ + ma_aaudio_result_t resultAA; + + ma_assert(pDevice != NULL); + + resultAA = ((MA_PFN_AAudioStream_requestStop)pDevice->pContext->aaudio.AAudioStream_requestStop)(pStream); + if (resultAA != MA_AAUDIO_OK) { + return ma_result_from_aaudio(resultAA); + } + + /* The device should be in either a stopping or stopped state. If it's not set to started we need to wait for it to transition. It should go from stopping to stopped. */ + ma_aaudio_stream_state_t currentState = ((MA_PFN_AAudioStream_getState)pDevice->pContext->aaudio.AAudioStream_getState)(pStream); + if (currentState != MA_AAUDIO_STREAM_STATE_STOPPED) { + ma_result result; + + if (currentState != MA_AAUDIO_STREAM_STATE_STOPPING) { + return MA_ERROR; /* Expecting the stream to be a stopping or stopped state. */ + } + + result = ma_wait_for_simple_state_transition__aaudio(pDevice->pContext, pStream, currentState, MA_AAUDIO_STREAM_STATE_STOPPED); + if (result != MA_SUCCESS) { + return result; + } + } + + return MA_SUCCESS; +} + +ma_result ma_device_start__aaudio(ma_device* pDevice) +{ + ma_assert(pDevice != NULL); + + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + ma_result result = ma_device_start_stream__aaudio(pDevice, (ma_AAudioStream*)pDevice->aaudio.pStreamCapture); + if (result != MA_SUCCESS) { + return result; + } + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + ma_result result = ma_device_start_stream__aaudio(pDevice, (ma_AAudioStream*)pDevice->aaudio.pStreamPlayback); + if (result != MA_SUCCESS) { + if (pDevice->type == ma_device_type_duplex) { + ma_device_stop_stream__aaudio(pDevice, (ma_AAudioStream*)pDevice->aaudio.pStreamCapture); + } + return result; + } + } + + return MA_SUCCESS; +} + +ma_result ma_device_stop__aaudio(ma_device* pDevice) +{ + ma_assert(pDevice != NULL); + + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + ma_result result = ma_device_stop_stream__aaudio(pDevice, (ma_AAudioStream*)pDevice->aaudio.pStreamCapture); + if (result != MA_SUCCESS) { + return result; + } + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + ma_result result = ma_device_stop_stream__aaudio(pDevice, (ma_AAudioStream*)pDevice->aaudio.pStreamPlayback); + if (result != MA_SUCCESS) { + return result; + } + } + + ma_stop_proc onStop = pDevice->onStop; + if (onStop) { + onStop(pDevice); + } + + return MA_SUCCESS; +} + + +ma_result ma_context_uninit__aaudio(ma_context* pContext) +{ + ma_assert(pContext != NULL); + ma_assert(pContext->backend == ma_backend_aaudio); + + ma_dlclose(pContext->aaudio.hAAudio); + pContext->aaudio.hAAudio = NULL; + + return MA_SUCCESS; +} + +ma_result ma_context_init__aaudio(ma_context* pContext) +{ + ma_assert(pContext != NULL); + (void)pContext; + + const char* libNames[] = { + "libaaudio.so" + }; + + for (size_t i = 0; i < ma_countof(libNames); ++i) { + pContext->aaudio.hAAudio = ma_dlopen(libNames[i]); + if (pContext->aaudio.hAAudio != NULL) { + break; + } + } + + if (pContext->aaudio.hAAudio == NULL) { + return MA_FAILED_TO_INIT_BACKEND; + } + + pContext->aaudio.AAudio_createStreamBuilder = (ma_proc)ma_dlsym(pContext->aaudio.hAAudio, "AAudio_createStreamBuilder"); + pContext->aaudio.AAudioStreamBuilder_delete = (ma_proc)ma_dlsym(pContext->aaudio.hAAudio, "AAudioStreamBuilder_delete"); + pContext->aaudio.AAudioStreamBuilder_setDeviceId = (ma_proc)ma_dlsym(pContext->aaudio.hAAudio, "AAudioStreamBuilder_setDeviceId"); + pContext->aaudio.AAudioStreamBuilder_setDirection = (ma_proc)ma_dlsym(pContext->aaudio.hAAudio, "AAudioStreamBuilder_setDirection"); + pContext->aaudio.AAudioStreamBuilder_setSharingMode = (ma_proc)ma_dlsym(pContext->aaudio.hAAudio, "AAudioStreamBuilder_setSharingMode"); + pContext->aaudio.AAudioStreamBuilder_setFormat = (ma_proc)ma_dlsym(pContext->aaudio.hAAudio, "AAudioStreamBuilder_setFormat"); + pContext->aaudio.AAudioStreamBuilder_setChannelCount = (ma_proc)ma_dlsym(pContext->aaudio.hAAudio, "AAudioStreamBuilder_setChannelCount"); + pContext->aaudio.AAudioStreamBuilder_setSampleRate = (ma_proc)ma_dlsym(pContext->aaudio.hAAudio, "AAudioStreamBuilder_setSampleRate"); + pContext->aaudio.AAudioStreamBuilder_setBufferCapacityInFrames = (ma_proc)ma_dlsym(pContext->aaudio.hAAudio, "AAudioStreamBuilder_setBufferCapacityInFrames"); + pContext->aaudio.AAudioStreamBuilder_setFramesPerDataCallback = (ma_proc)ma_dlsym(pContext->aaudio.hAAudio, "AAudioStreamBuilder_setFramesPerDataCallback"); + pContext->aaudio.AAudioStreamBuilder_setDataCallback = (ma_proc)ma_dlsym(pContext->aaudio.hAAudio, "AAudioStreamBuilder_setDataCallback"); + pContext->aaudio.AAudioStreamBuilder_setPerformanceMode = (ma_proc)ma_dlsym(pContext->aaudio.hAAudio, "AAudioStreamBuilder_setPerformanceMode"); + pContext->aaudio.AAudioStreamBuilder_openStream = (ma_proc)ma_dlsym(pContext->aaudio.hAAudio, "AAudioStreamBuilder_openStream"); + pContext->aaudio.AAudioStream_close = (ma_proc)ma_dlsym(pContext->aaudio.hAAudio, "AAudioStream_close"); + pContext->aaudio.AAudioStream_getState = (ma_proc)ma_dlsym(pContext->aaudio.hAAudio, "AAudioStream_getState"); + pContext->aaudio.AAudioStream_waitForStateChange = (ma_proc)ma_dlsym(pContext->aaudio.hAAudio, "AAudioStream_waitForStateChange"); + pContext->aaudio.AAudioStream_getFormat = (ma_proc)ma_dlsym(pContext->aaudio.hAAudio, "AAudioStream_getFormat"); + pContext->aaudio.AAudioStream_getChannelCount = (ma_proc)ma_dlsym(pContext->aaudio.hAAudio, "AAudioStream_getChannelCount"); + pContext->aaudio.AAudioStream_getSampleRate = (ma_proc)ma_dlsym(pContext->aaudio.hAAudio, "AAudioStream_getSampleRate"); + pContext->aaudio.AAudioStream_getBufferCapacityInFrames = (ma_proc)ma_dlsym(pContext->aaudio.hAAudio, "AAudioStream_getBufferCapacityInFrames"); + pContext->aaudio.AAudioStream_getFramesPerDataCallback = (ma_proc)ma_dlsym(pContext->aaudio.hAAudio, "AAudioStream_getFramesPerDataCallback"); + pContext->aaudio.AAudioStream_getFramesPerBurst = (ma_proc)ma_dlsym(pContext->aaudio.hAAudio, "AAudioStream_getFramesPerBurst"); + pContext->aaudio.AAudioStream_requestStart = (ma_proc)ma_dlsym(pContext->aaudio.hAAudio, "AAudioStream_requestStart"); + pContext->aaudio.AAudioStream_requestStop = (ma_proc)ma_dlsym(pContext->aaudio.hAAudio, "AAudioStream_requestStop"); + + pContext->isBackendAsynchronous = MA_TRUE; + + pContext->onUninit = ma_context_uninit__aaudio; + pContext->onDeviceIDEqual = ma_context_is_device_id_equal__aaudio; + pContext->onEnumDevices = ma_context_enumerate_devices__aaudio; + pContext->onGetDeviceInfo = ma_context_get_device_info__aaudio; + pContext->onDeviceInit = ma_device_init__aaudio; + pContext->onDeviceUninit = ma_device_uninit__aaudio; + pContext->onDeviceStart = ma_device_start__aaudio; + pContext->onDeviceStop = ma_device_stop__aaudio; + + return MA_SUCCESS; +} +#endif // AAudio + + +/////////////////////////////////////////////////////////////////////////////// +// +// OpenSL|ES Backend +// +/////////////////////////////////////////////////////////////////////////////// +#ifdef MA_HAS_OPENSL +#include +#ifdef MA_ANDROID +#include +#endif + +// OpenSL|ES has one-per-application objects :( +SLObjectItf g_maEngineObjectSL = NULL; +SLEngineItf g_maEngineSL = NULL; +ma_uint32 g_maOpenSLInitCounter = 0; + +#define MA_OPENSL_OBJ(p) (*((SLObjectItf)(p))) +#define MA_OPENSL_OUTPUTMIX(p) (*((SLOutputMixItf)(p))) +#define MA_OPENSL_PLAY(p) (*((SLPlayItf)(p))) +#define MA_OPENSL_RECORD(p) (*((SLRecordItf)(p))) + +#ifdef MA_ANDROID +#define MA_OPENSL_BUFFERQUEUE(p) (*((SLAndroidSimpleBufferQueueItf)(p))) +#else +#define MA_OPENSL_BUFFERQUEUE(p) (*((SLBufferQueueItf)(p))) +#endif + +// Converts an individual OpenSL-style channel identifier (SL_SPEAKER_FRONT_LEFT, etc.) to miniaudio. +ma_uint8 ma_channel_id_to_ma__opensl(SLuint32 id) +{ + switch (id) + { + case SL_SPEAKER_FRONT_LEFT: return MA_CHANNEL_FRONT_LEFT; + case SL_SPEAKER_FRONT_RIGHT: return MA_CHANNEL_FRONT_RIGHT; + case SL_SPEAKER_FRONT_CENTER: return MA_CHANNEL_FRONT_CENTER; + case SL_SPEAKER_LOW_FREQUENCY: return MA_CHANNEL_LFE; + case SL_SPEAKER_BACK_LEFT: return MA_CHANNEL_BACK_LEFT; + case SL_SPEAKER_BACK_RIGHT: return MA_CHANNEL_BACK_RIGHT; + case SL_SPEAKER_FRONT_LEFT_OF_CENTER: return MA_CHANNEL_FRONT_LEFT_CENTER; + case SL_SPEAKER_FRONT_RIGHT_OF_CENTER: return MA_CHANNEL_FRONT_RIGHT_CENTER; + case SL_SPEAKER_BACK_CENTER: return MA_CHANNEL_BACK_CENTER; + case SL_SPEAKER_SIDE_LEFT: return MA_CHANNEL_SIDE_LEFT; + case SL_SPEAKER_SIDE_RIGHT: return MA_CHANNEL_SIDE_RIGHT; + case SL_SPEAKER_TOP_CENTER: return MA_CHANNEL_TOP_CENTER; + case SL_SPEAKER_TOP_FRONT_LEFT: return MA_CHANNEL_TOP_FRONT_LEFT; + case SL_SPEAKER_TOP_FRONT_CENTER: return MA_CHANNEL_TOP_FRONT_CENTER; + case SL_SPEAKER_TOP_FRONT_RIGHT: return MA_CHANNEL_TOP_FRONT_RIGHT; + case SL_SPEAKER_TOP_BACK_LEFT: return MA_CHANNEL_TOP_BACK_LEFT; + case SL_SPEAKER_TOP_BACK_CENTER: return MA_CHANNEL_TOP_BACK_CENTER; + case SL_SPEAKER_TOP_BACK_RIGHT: return MA_CHANNEL_TOP_BACK_RIGHT; + default: return 0; + } +} + +// Converts an individual miniaudio channel identifier (MA_CHANNEL_FRONT_LEFT, etc.) to OpenSL-style. +SLuint32 ma_channel_id_to_opensl(ma_uint8 id) +{ + switch (id) + { + case MA_CHANNEL_MONO: return SL_SPEAKER_FRONT_CENTER; + case MA_CHANNEL_FRONT_LEFT: return SL_SPEAKER_FRONT_LEFT; + case MA_CHANNEL_FRONT_RIGHT: return SL_SPEAKER_FRONT_RIGHT; + case MA_CHANNEL_FRONT_CENTER: return SL_SPEAKER_FRONT_CENTER; + case MA_CHANNEL_LFE: return SL_SPEAKER_LOW_FREQUENCY; + case MA_CHANNEL_BACK_LEFT: return SL_SPEAKER_BACK_LEFT; + case MA_CHANNEL_BACK_RIGHT: return SL_SPEAKER_BACK_RIGHT; + case MA_CHANNEL_FRONT_LEFT_CENTER: return SL_SPEAKER_FRONT_LEFT_OF_CENTER; + case MA_CHANNEL_FRONT_RIGHT_CENTER: return SL_SPEAKER_FRONT_RIGHT_OF_CENTER; + case MA_CHANNEL_BACK_CENTER: return SL_SPEAKER_BACK_CENTER; + case MA_CHANNEL_SIDE_LEFT: return SL_SPEAKER_SIDE_LEFT; + case MA_CHANNEL_SIDE_RIGHT: return SL_SPEAKER_SIDE_RIGHT; + case MA_CHANNEL_TOP_CENTER: return SL_SPEAKER_TOP_CENTER; + case MA_CHANNEL_TOP_FRONT_LEFT: return SL_SPEAKER_TOP_FRONT_LEFT; + case MA_CHANNEL_TOP_FRONT_CENTER: return SL_SPEAKER_TOP_FRONT_CENTER; + case MA_CHANNEL_TOP_FRONT_RIGHT: return SL_SPEAKER_TOP_FRONT_RIGHT; + case MA_CHANNEL_TOP_BACK_LEFT: return SL_SPEAKER_TOP_BACK_LEFT; + case MA_CHANNEL_TOP_BACK_CENTER: return SL_SPEAKER_TOP_BACK_CENTER; + case MA_CHANNEL_TOP_BACK_RIGHT: return SL_SPEAKER_TOP_BACK_RIGHT; + default: return 0; + } +} + +// Converts a channel mapping to an OpenSL-style channel mask. +SLuint32 ma_channel_map_to_channel_mask__opensl(const ma_channel channelMap[MA_MAX_CHANNELS], ma_uint32 channels) +{ + SLuint32 channelMask = 0; + for (ma_uint32 iChannel = 0; iChannel < channels; ++iChannel) { + channelMask |= ma_channel_id_to_opensl(channelMap[iChannel]); + } + + return channelMask; +} + +// Converts an OpenSL-style channel mask to a miniaudio channel map. +void ma_channel_mask_to_channel_map__opensl(SLuint32 channelMask, ma_uint32 channels, ma_channel channelMap[MA_MAX_CHANNELS]) +{ + if (channels == 1 && channelMask == 0) { + channelMap[0] = MA_CHANNEL_MONO; + } else if (channels == 2 && channelMask == 0) { + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_RIGHT; + } else { + if (channels == 1 && (channelMask & SL_SPEAKER_FRONT_CENTER) != 0) { + channelMap[0] = MA_CHANNEL_MONO; + } else { + // Just iterate over each bit. + ma_uint32 iChannel = 0; + for (ma_uint32 iBit = 0; iBit < 32; ++iBit) { + SLuint32 bitValue = (channelMask & (1UL << iBit)); + if (bitValue != 0) { + // The bit is set. + channelMap[iChannel] = ma_channel_id_to_ma__opensl(bitValue); + iChannel += 1; + } + } + } + } +} + +SLuint32 ma_round_to_standard_sample_rate__opensl(SLuint32 samplesPerSec) +{ + if (samplesPerSec <= SL_SAMPLINGRATE_8) { + return SL_SAMPLINGRATE_8; + } + if (samplesPerSec <= SL_SAMPLINGRATE_11_025) { + return SL_SAMPLINGRATE_11_025; + } + if (samplesPerSec <= SL_SAMPLINGRATE_12) { + return SL_SAMPLINGRATE_12; + } + if (samplesPerSec <= SL_SAMPLINGRATE_16) { + return SL_SAMPLINGRATE_16; + } + if (samplesPerSec <= SL_SAMPLINGRATE_22_05) { + return SL_SAMPLINGRATE_22_05; + } + if (samplesPerSec <= SL_SAMPLINGRATE_24) { + return SL_SAMPLINGRATE_24; + } + if (samplesPerSec <= SL_SAMPLINGRATE_32) { + return SL_SAMPLINGRATE_32; + } + if (samplesPerSec <= SL_SAMPLINGRATE_44_1) { + return SL_SAMPLINGRATE_44_1; + } + if (samplesPerSec <= SL_SAMPLINGRATE_48) { + return SL_SAMPLINGRATE_48; + } + + // Android doesn't support more than 48000. +#ifndef MA_ANDROID + if (samplesPerSec <= SL_SAMPLINGRATE_64) { + return SL_SAMPLINGRATE_64; + } + if (samplesPerSec <= SL_SAMPLINGRATE_88_2) { + return SL_SAMPLINGRATE_88_2; + } + if (samplesPerSec <= SL_SAMPLINGRATE_96) { + return SL_SAMPLINGRATE_96; + } + if (samplesPerSec <= SL_SAMPLINGRATE_192) { + return SL_SAMPLINGRATE_192; + } +#endif + + return SL_SAMPLINGRATE_16; +} + + +ma_bool32 ma_context_is_device_id_equal__opensl(ma_context* pContext, const ma_device_id* pID0, const ma_device_id* pID1) +{ + ma_assert(pContext != NULL); + ma_assert(pID0 != NULL); + ma_assert(pID1 != NULL); + (void)pContext; + + return pID0->opensl == pID1->opensl; +} + +ma_result ma_context_enumerate_devices__opensl(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData) +{ + ma_assert(pContext != NULL); + ma_assert(callback != NULL); + + ma_assert(g_maOpenSLInitCounter > 0); /* <-- If you trigger this it means you've either not initialized the context, or you've uninitialized it and then attempted to enumerate devices. */ + if (g_maOpenSLInitCounter == 0) { + return MA_INVALID_OPERATION; + } + + // TODO: Test Me. + // + // This is currently untested, so for now we are just returning default devices. +#if 0 && !defined(MA_ANDROID) + ma_bool32 isTerminated = MA_FALSE; + + SLuint32 pDeviceIDs[128]; + SLint32 deviceCount = sizeof(pDeviceIDs) / sizeof(pDeviceIDs[0]); + + SLAudioIODeviceCapabilitiesItf deviceCaps; + SLresult resultSL = (*g_maEngineObjectSL)->GetInterface(g_maEngineObjectSL, SL_IID_AUDIOIODEVICECAPABILITIES, &deviceCaps); + if (resultSL != SL_RESULT_SUCCESS) { + // The interface may not be supported so just report a default device. + goto return_default_device; + } + + // Playback + if (!isTerminated) { + resultSL = (*deviceCaps)->GetAvailableAudioOutputs(deviceCaps, &deviceCount, pDeviceIDs); + if (resultSL != SL_RESULT_SUCCESS) { + return MA_NO_DEVICE; + } + + for (SLint32 iDevice = 0; iDevice < deviceCount; ++iDevice) { + ma_device_info deviceInfo; + ma_zero_object(&deviceInfo); + deviceInfo.id.opensl = pDeviceIDs[iDevice]; + + SLAudioOutputDescriptor desc; + resultSL = (*deviceCaps)->QueryAudioOutputCapabilities(deviceCaps, deviceInfo.id.opensl, &desc); + if (resultSL == SL_RESULT_SUCCESS) { + ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), (const char*)desc.pDeviceName, (size_t)-1); + + ma_bool32 cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData); + if (cbResult == MA_FALSE) { + isTerminated = MA_TRUE; + break; + } + } + } + } + + // Capture + if (!isTerminated) { + resultSL = (*deviceCaps)->GetAvailableAudioInputs(deviceCaps, &deviceCount, pDeviceIDs); + if (resultSL != SL_RESULT_SUCCESS) { + return MA_NO_DEVICE; + } + + for (SLint32 iDevice = 0; iDevice < deviceCount; ++iDevice) { + ma_device_info deviceInfo; + ma_zero_object(&deviceInfo); + deviceInfo.id.opensl = pDeviceIDs[iDevice]; + + SLAudioInputDescriptor desc; + resultSL = (*deviceCaps)->QueryAudioInputCapabilities(deviceCaps, deviceInfo.id.opensl, &desc); + if (resultSL == SL_RESULT_SUCCESS) { + ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), (const char*)desc.deviceName, (size_t)-1); + + ma_bool32 cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData); + if (cbResult == MA_FALSE) { + isTerminated = MA_TRUE; + break; + } + } + } + } + + return MA_SUCCESS; +#else + goto return_default_device; +#endif + +return_default_device:; + ma_bool32 cbResult = MA_TRUE; + + // Playback. + if (cbResult) { + ma_device_info deviceInfo; + ma_zero_object(&deviceInfo); + ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); + cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData); + } + + // Capture. + if (cbResult) { + ma_device_info deviceInfo; + ma_zero_object(&deviceInfo); + ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); + cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData); + } + + return MA_SUCCESS; +} + +ma_result ma_context_get_device_info__opensl(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_share_mode shareMode, ma_device_info* pDeviceInfo) +{ + ma_assert(pContext != NULL); + + ma_assert(g_maOpenSLInitCounter > 0); /* <-- If you trigger this it means you've either not initialized the context, or you've uninitialized it and then attempted to get device info. */ + if (g_maOpenSLInitCounter == 0) { + return MA_INVALID_OPERATION; + } + + /* No exclusive mode with OpenSL|ES. */ + if (shareMode == ma_share_mode_exclusive) { + return MA_SHARE_MODE_NOT_SUPPORTED; + } + + // TODO: Test Me. + // + // This is currently untested, so for now we are just returning default devices. +#if 0 && !defined(MA_ANDROID) + SLAudioIODeviceCapabilitiesItf deviceCaps; + SLresult resultSL = (*g_maEngineObjectSL)->GetInterface(g_maEngineObjectSL, SL_IID_AUDIOIODEVICECAPABILITIES, &deviceCaps); + if (resultSL != SL_RESULT_SUCCESS) { + // The interface may not be supported so just report a default device. + goto return_default_device; + } + + if (deviceType == ma_device_type_playback) { + SLAudioOutputDescriptor desc; + resultSL = (*deviceCaps)->QueryAudioOutputCapabilities(deviceCaps, pDeviceID->opensl, &desc); + if (resultSL != SL_RESULT_SUCCESS) { + return MA_NO_DEVICE; + } + + ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), (const char*)desc.pDeviceName, (size_t)-1); + } else { + SLAudioInputDescriptor desc; + resultSL = (*deviceCaps)->QueryAudioInputCapabilities(deviceCaps, pDeviceID->opensl, &desc); + if (resultSL != SL_RESULT_SUCCESS) { + return MA_NO_DEVICE; + } + + ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), (const char*)desc.deviceName, (size_t)-1); + } + + goto return_detailed_info; +#else + goto return_default_device; +#endif + +return_default_device: + if (pDeviceID != NULL) { + if ((deviceType == ma_device_type_playback && pDeviceID->opensl != SL_DEFAULTDEVICEID_AUDIOOUTPUT) || + (deviceType == ma_device_type_capture && pDeviceID->opensl != SL_DEFAULTDEVICEID_AUDIOINPUT)) { + return MA_NO_DEVICE; // Don't know the device. + } + } + + // Name / Description + if (deviceType == ma_device_type_playback) { + ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); + } else { + ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); + } + + goto return_detailed_info; + + +return_detailed_info: + + // For now we're just outputting a set of values that are supported by the API but not necessarily supported + // by the device natively. Later on we should work on this so that it more closely reflects the device's + // actual native format. + pDeviceInfo->minChannels = 1; + pDeviceInfo->maxChannels = 2; + pDeviceInfo->minSampleRate = 8000; + pDeviceInfo->maxSampleRate = 48000; + pDeviceInfo->formatCount = 2; + pDeviceInfo->formats[0] = ma_format_u8; + pDeviceInfo->formats[1] = ma_format_s16; +#if defined(MA_ANDROID) && __ANDROID_API__ >= 21 + pDeviceInfo->formats[pDeviceInfo->formatCount] = ma_format_f32; + pDeviceInfo->formatCount += 1; +#endif + + return MA_SUCCESS; +} + + +#ifdef MA_ANDROID +//void ma_buffer_queue_callback_capture__opensl_android(SLAndroidSimpleBufferQueueItf pBufferQueue, SLuint32 eventFlags, const void* pBuffer, SLuint32 bufferSize, SLuint32 dataUsed, void* pContext) +void ma_buffer_queue_callback_capture__opensl_android(SLAndroidSimpleBufferQueueItf pBufferQueue, void* pUserData) +{ + ma_device* pDevice = (ma_device*)pUserData; + ma_assert(pDevice != NULL); + + (void)pBufferQueue; + + // For now, don't do anything unless the buffer was fully processed. From what I can tell, it looks like + // OpenSL|ES 1.1 improves on buffer queues to the point that we could much more intelligently handle this, + // but unfortunately it looks like Android is only supporting OpenSL|ES 1.0.1 for now :( + + /* Don't do anything if the device is not started. */ + if (pDevice->state != MA_STATE_STARTED) { + return; + } + + size_t periodSizeInBytes = (pDevice->capture.internalBufferSizeInFrames / pDevice->capture.internalPeriods) * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels); + ma_uint8* pBuffer = pDevice->opensl.pBufferCapture + (pDevice->opensl.currentBufferIndexCapture * periodSizeInBytes); + + if (pDevice->type == ma_device_type_duplex) { + ma_device__handle_duplex_callback_capture(pDevice, (pDevice->capture.internalBufferSizeInFrames / pDevice->capture.internalPeriods), pBuffer, &pDevice->opensl.duplexRB); + } else { + ma_device__send_frames_to_client(pDevice, (pDevice->capture.internalBufferSizeInFrames / pDevice->capture.internalPeriods), pBuffer); + } + + SLresult resultSL = MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueueCapture)->Enqueue((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueueCapture, pBuffer, periodSizeInBytes); + if (resultSL != SL_RESULT_SUCCESS) { + return; + } + + pDevice->opensl.currentBufferIndexCapture = (pDevice->opensl.currentBufferIndexCapture + 1) % pDevice->capture.internalPeriods; +} + +void ma_buffer_queue_callback_playback__opensl_android(SLAndroidSimpleBufferQueueItf pBufferQueue, void* pUserData) +{ + ma_device* pDevice = (ma_device*)pUserData; + ma_assert(pDevice != NULL); + + (void)pBufferQueue; + + /* Don't do anything if the device is not started. */ + if (pDevice->state != MA_STATE_STARTED) { + return; + } + + size_t periodSizeInBytes = (pDevice->playback.internalBufferSizeInFrames / pDevice->playback.internalPeriods) * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels); + ma_uint8* pBuffer = pDevice->opensl.pBufferPlayback + (pDevice->opensl.currentBufferIndexPlayback * periodSizeInBytes); + + if (pDevice->type == ma_device_type_duplex) { + ma_device__handle_duplex_callback_playback(pDevice, (pDevice->playback.internalBufferSizeInFrames / pDevice->playback.internalPeriods), pBuffer, &pDevice->opensl.duplexRB); + } else { + ma_device__read_frames_from_client(pDevice, (pDevice->playback.internalBufferSizeInFrames / pDevice->playback.internalPeriods), pBuffer); + } + + SLresult resultSL = MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueuePlayback)->Enqueue((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueuePlayback, pBuffer, periodSizeInBytes); + if (resultSL != SL_RESULT_SUCCESS) { + return; + } + + pDevice->opensl.currentBufferIndexPlayback = (pDevice->opensl.currentBufferIndexPlayback + 1) % pDevice->playback.internalPeriods; +} +#endif + +void ma_device_uninit__opensl(ma_device* pDevice) +{ + ma_assert(pDevice != NULL); + + ma_assert(g_maOpenSLInitCounter > 0); /* <-- If you trigger this it means you've either not initialized the context, or you've uninitialized it before uninitializing the device. */ + if (g_maOpenSLInitCounter == 0) { + return; + } + + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + if (pDevice->opensl.pAudioRecorderObj) { + MA_OPENSL_OBJ(pDevice->opensl.pAudioRecorderObj)->Destroy((SLObjectItf)pDevice->opensl.pAudioRecorderObj); + } + + ma_free(pDevice->opensl.pBufferCapture); + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + if (pDevice->opensl.pAudioPlayerObj) { + MA_OPENSL_OBJ(pDevice->opensl.pAudioPlayerObj)->Destroy((SLObjectItf)pDevice->opensl.pAudioPlayerObj); + } + if (pDevice->opensl.pOutputMixObj) { + MA_OPENSL_OBJ(pDevice->opensl.pOutputMixObj)->Destroy((SLObjectItf)pDevice->opensl.pOutputMixObj); + } + + ma_free(pDevice->opensl.pBufferPlayback); + } + + if (pDevice->type == ma_device_type_duplex) { + ma_pcm_rb_uninit(&pDevice->opensl.duplexRB); + } +} + +#if defined(MA_ANDROID) && __ANDROID_API__ >= 21 +typedef SLAndroidDataFormat_PCM_EX ma_SLDataFormat_PCM; +#else +typedef SLDataFormat_PCM ma_SLDataFormat_PCM; +#endif + +ma_result ma_SLDataFormat_PCM_init__opensl(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, const ma_channel* channelMap, ma_SLDataFormat_PCM* pDataFormat) +{ +#if defined(MA_ANDROID) && __ANDROID_API__ >= 21 + if (format == ma_format_f32) { + pDataFormat->formatType = SL_ANDROID_DATAFORMAT_PCM_EX; + pDataFormat->representation = SL_ANDROID_PCM_REPRESENTATION_FLOAT; + } else { + pDataFormat->formatType = SL_DATAFORMAT_PCM; + } +#else + pDataFormat->formatType = SL_DATAFORMAT_PCM; +#endif + + pDataFormat->numChannels = channels; + ((SLDataFormat_PCM*)pDataFormat)->samplesPerSec = ma_round_to_standard_sample_rate__opensl(sampleRate * 1000); /* In millihertz. Annoyingly, the sample rate variable is named differently between SLAndroidDataFormat_PCM_EX and SLDataFormat_PCM */ + pDataFormat->bitsPerSample = ma_get_bytes_per_sample(format)*8; + pDataFormat->channelMask = ma_channel_map_to_channel_mask__opensl(channelMap, channels); + pDataFormat->endianness = (ma_is_little_endian()) ? SL_BYTEORDER_LITTLEENDIAN : SL_BYTEORDER_BIGENDIAN; + + /* + Android has a few restrictions on the format as documented here: https://developer.android.com/ndk/guides/audio/opensl-for-android.html + - Only mono and stereo is supported. + - Only u8 and s16 formats are supported. + - Maximum sample rate of 48000. + */ +#ifdef MA_ANDROID + if (pDataFormat->numChannels > 2) { + pDataFormat->numChannels = 2; + } +#if __ANDROID_API__ >= 21 + if (pDataFormat->formatType == SL_ANDROID_DATAFORMAT_PCM_EX) { + /* It's floating point. */ + ma_assert(pDataFormat->representation == SL_ANDROID_PCM_REPRESENTATION_FLOAT); + if (pDataFormat->bitsPerSample > 32) { + pDataFormat->bitsPerSample = 32; + } + } else { + if (pDataFormat->bitsPerSample > 16) { + pDataFormat->bitsPerSample = 16; + } + } +#else + if (pDataFormat->bitsPerSample > 16) { + pDataFormat->bitsPerSample = 16; + } +#endif + if (((SLDataFormat_PCM*)pDataFormat)->samplesPerSec > SL_SAMPLINGRATE_48) { + ((SLDataFormat_PCM*)pDataFormat)->samplesPerSec = SL_SAMPLINGRATE_48; + } +#endif + + pDataFormat->containerSize = pDataFormat->bitsPerSample; /* Always tightly packed for now. */ + + return MA_SUCCESS; +} + +ma_result ma_deconstruct_SLDataFormat_PCM__opensl(ma_SLDataFormat_PCM* pDataFormat, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap) +{ + ma_bool32 isFloatingPoint = MA_FALSE; +#if defined(MA_ANDROID) && __ANDROID_API__ >= 21 + if (pDataFormat->formatType == SL_ANDROID_DATAFORMAT_PCM_EX) { + ma_assert(pDataFormat->representation == SL_ANDROID_PCM_REPRESENTATION_FLOAT); + isFloatingPoint = MA_TRUE; + } +#endif + if (isFloatingPoint) { + if (pDataFormat->bitsPerSample == 32) { + *pFormat = ma_format_f32; + } + } else { + if (pDataFormat->bitsPerSample == 8) { + *pFormat = ma_format_u8; + } else if (pDataFormat->bitsPerSample == 16) { + *pFormat = ma_format_s16; + } else if (pDataFormat->bitsPerSample == 24) { + *pFormat = ma_format_s24; + } else if (pDataFormat->bitsPerSample == 32) { + *pFormat = ma_format_s32; + } + } + + *pChannels = pDataFormat->numChannels; + *pSampleRate = ((SLDataFormat_PCM*)pDataFormat)->samplesPerSec / 1000; + ma_channel_mask_to_channel_map__opensl(pDataFormat->channelMask, pDataFormat->numChannels, pChannelMap); + + return MA_SUCCESS; +} + +ma_result ma_device_init__opensl(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice) +{ + (void)pContext; + + ma_assert(g_maOpenSLInitCounter > 0); /* <-- If you trigger this it means you've either not initialized the context, or you've uninitialized it and then attempted to initialize a new device. */ + if (g_maOpenSLInitCounter == 0) { + return MA_INVALID_OPERATION; + } + + /* + For now, only supporting Android implementations of OpenSL|ES since that's the only one I've + been able to test with and I currently depend on Android-specific extensions (simple buffer + queues). + */ +#ifndef MA_ANDROID + return MA_NO_BACKEND; +#endif + + /* No exclusive mode with OpenSL|ES. */ + if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pConfig->playback.shareMode == ma_share_mode_exclusive) || + ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pConfig->capture.shareMode == ma_share_mode_exclusive)) { + return MA_SHARE_MODE_NOT_SUPPORTED; + } + + /* Now we can start initializing the device properly. */ + ma_assert(pDevice != NULL); + ma_zero_object(&pDevice->opensl); + + SLDataLocator_AndroidSimpleBufferQueue queue; + queue.locatorType = SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE; + queue.numBuffers = pConfig->periods; + + + if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) { + ma_SLDataFormat_PCM pcm; + ma_SLDataFormat_PCM_init__opensl(pConfig->capture.format, pConfig->capture.channels, pConfig->sampleRate, pConfig->capture.channelMap, &pcm); + + SLDataLocator_IODevice locatorDevice; + locatorDevice.locatorType = SL_DATALOCATOR_IODEVICE; + locatorDevice.deviceType = SL_IODEVICE_AUDIOINPUT; + locatorDevice.deviceID = (pConfig->capture.pDeviceID == NULL) ? SL_DEFAULTDEVICEID_AUDIOINPUT : pConfig->capture.pDeviceID->opensl; + locatorDevice.device = NULL; + + SLDataSource source; + source.pLocator = &locatorDevice; + source.pFormat = NULL; + + SLDataSink sink; + sink.pLocator = &queue; + sink.pFormat = (SLDataFormat_PCM*)&pcm; + + const SLInterfaceID itfIDs1[] = {SL_IID_ANDROIDSIMPLEBUFFERQUEUE}; + const SLboolean itfIDsRequired1[] = {SL_BOOLEAN_TRUE}; + SLresult resultSL = (*g_maEngineSL)->CreateAudioRecorder(g_maEngineSL, (SLObjectItf*)&pDevice->opensl.pAudioRecorderObj, &source, &sink, 1, itfIDs1, itfIDsRequired1); + if (resultSL == SL_RESULT_CONTENT_UNSUPPORTED) { + /* Unsupported format. Fall back to something safer and try again. If this fails, just abort. */ + pcm.formatType = SL_DATAFORMAT_PCM; + pcm.numChannels = 1; + ((SLDataFormat_PCM*)&pcm)->samplesPerSec = SL_SAMPLINGRATE_16; /* The name of the sample rate variable is different between SLAndroidDataFormat_PCM_EX and SLDataFormat_PCM. */ + pcm.bitsPerSample = 16; + pcm.containerSize = pcm.bitsPerSample; /* Always tightly packed for now. */ + pcm.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT; + resultSL = (*g_maEngineSL)->CreateAudioRecorder(g_maEngineSL, (SLObjectItf*)&pDevice->opensl.pAudioRecorderObj, &source, &sink, 1, itfIDs1, itfIDsRequired1); + } + + if (resultSL != SL_RESULT_SUCCESS) { + ma_device_uninit__opensl(pDevice); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to create audio recorder.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + + if (MA_OPENSL_OBJ(pDevice->opensl.pAudioRecorderObj)->Realize((SLObjectItf)pDevice->opensl.pAudioRecorderObj, SL_BOOLEAN_FALSE) != SL_RESULT_SUCCESS) { + ma_device_uninit__opensl(pDevice); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to realize audio recorder.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + + if (MA_OPENSL_OBJ(pDevice->opensl.pAudioRecorderObj)->GetInterface((SLObjectItf)pDevice->opensl.pAudioRecorderObj, SL_IID_RECORD, &pDevice->opensl.pAudioRecorder) != SL_RESULT_SUCCESS) { + ma_device_uninit__opensl(pDevice); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to retrieve SL_IID_RECORD interface.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + + if (MA_OPENSL_OBJ(pDevice->opensl.pAudioRecorderObj)->GetInterface((SLObjectItf)pDevice->opensl.pAudioRecorderObj, SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &pDevice->opensl.pBufferQueueCapture) != SL_RESULT_SUCCESS) { + ma_device_uninit__opensl(pDevice); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to retrieve SL_IID_ANDROIDSIMPLEBUFFERQUEUE interface.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + + if (MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueueCapture)->RegisterCallback((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueueCapture, ma_buffer_queue_callback_capture__opensl_android, pDevice) != SL_RESULT_SUCCESS) { + ma_device_uninit__opensl(pDevice); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to register buffer queue callback.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + + /* The internal format is determined by the "pcm" object. */ + ma_deconstruct_SLDataFormat_PCM__opensl(&pcm, &pDevice->capture.internalFormat, &pDevice->capture.internalChannels, &pDevice->capture.internalSampleRate, pDevice->capture.internalChannelMap); + + /* Buffer. */ + ma_uint32 bufferSizeInFrames = pConfig->bufferSizeInFrames; + if (bufferSizeInFrames == 0) { + bufferSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(pConfig->bufferSizeInMilliseconds, pDevice->capture.internalSampleRate); + } + pDevice->capture.internalPeriods = pConfig->periods; + pDevice->capture.internalBufferSizeInFrames = (bufferSizeInFrames / pDevice->capture.internalPeriods) * pDevice->capture.internalPeriods; + pDevice->opensl.currentBufferIndexCapture = 0; + + size_t bufferSizeInBytes = pDevice->capture.internalBufferSizeInFrames * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels); + pDevice->opensl.pBufferCapture = (ma_uint8*)ma_malloc(bufferSizeInBytes); + if (pDevice->opensl.pBufferCapture == NULL) { + ma_device_uninit__opensl(pDevice); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to allocate memory for data buffer.", MA_OUT_OF_MEMORY); + } + MA_ZERO_MEMORY(pDevice->opensl.pBufferCapture, bufferSizeInBytes); + } + + if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) { + ma_SLDataFormat_PCM pcm; + ma_SLDataFormat_PCM_init__opensl(pConfig->playback.format, pConfig->playback.channels, pConfig->sampleRate, pConfig->playback.channelMap, &pcm); + + SLresult resultSL = (*g_maEngineSL)->CreateOutputMix(g_maEngineSL, (SLObjectItf*)&pDevice->opensl.pOutputMixObj, 0, NULL, NULL); + if (resultSL != SL_RESULT_SUCCESS) { + ma_device_uninit__opensl(pDevice); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to create output mix.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + + if (MA_OPENSL_OBJ(pDevice->opensl.pOutputMixObj)->Realize((SLObjectItf)pDevice->opensl.pOutputMixObj, SL_BOOLEAN_FALSE)) { + ma_device_uninit__opensl(pDevice); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to realize output mix object.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + + if (MA_OPENSL_OBJ(pDevice->opensl.pOutputMixObj)->GetInterface((SLObjectItf)pDevice->opensl.pOutputMixObj, SL_IID_OUTPUTMIX, &pDevice->opensl.pOutputMix) != SL_RESULT_SUCCESS) { + ma_device_uninit__opensl(pDevice); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to retrieve SL_IID_OUTPUTMIX interface.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + + /* Set the output device. */ + if (pConfig->playback.pDeviceID != NULL) { + SLuint32 deviceID_OpenSL = pConfig->playback.pDeviceID->opensl; + MA_OPENSL_OUTPUTMIX(pDevice->opensl.pOutputMix)->ReRoute((SLOutputMixItf)pDevice->opensl.pOutputMix, 1, &deviceID_OpenSL); + } + + SLDataSource source; + source.pLocator = &queue; + source.pFormat = (SLDataFormat_PCM*)&pcm; + + SLDataLocator_OutputMix outmixLocator; + outmixLocator.locatorType = SL_DATALOCATOR_OUTPUTMIX; + outmixLocator.outputMix = (SLObjectItf)pDevice->opensl.pOutputMixObj; + + SLDataSink sink; + sink.pLocator = &outmixLocator; + sink.pFormat = NULL; + + const SLInterfaceID itfIDs1[] = {SL_IID_ANDROIDSIMPLEBUFFERQUEUE}; + const SLboolean itfIDsRequired1[] = {SL_BOOLEAN_TRUE}; + resultSL = (*g_maEngineSL)->CreateAudioPlayer(g_maEngineSL, (SLObjectItf*)&pDevice->opensl.pAudioPlayerObj, &source, &sink, 1, itfIDs1, itfIDsRequired1); + if (resultSL == SL_RESULT_CONTENT_UNSUPPORTED) { + /* Unsupported format. Fall back to something safer and try again. If this fails, just abort. */ + pcm.formatType = SL_DATAFORMAT_PCM; + pcm.numChannels = 2; + ((SLDataFormat_PCM*)&pcm)->samplesPerSec = SL_SAMPLINGRATE_16; + pcm.bitsPerSample = 16; + pcm.containerSize = pcm.bitsPerSample; /* Always tightly packed for now. */ + pcm.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT; + resultSL = (*g_maEngineSL)->CreateAudioPlayer(g_maEngineSL, (SLObjectItf*)&pDevice->opensl.pAudioPlayerObj, &source, &sink, 1, itfIDs1, itfIDsRequired1); + } + + if (resultSL != SL_RESULT_SUCCESS) { + ma_device_uninit__opensl(pDevice); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to create audio player.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + + if (MA_OPENSL_OBJ(pDevice->opensl.pAudioPlayerObj)->Realize((SLObjectItf)pDevice->opensl.pAudioPlayerObj, SL_BOOLEAN_FALSE) != SL_RESULT_SUCCESS) { + ma_device_uninit__opensl(pDevice); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to realize audio player.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + + if (MA_OPENSL_OBJ(pDevice->opensl.pAudioPlayerObj)->GetInterface((SLObjectItf)pDevice->opensl.pAudioPlayerObj, SL_IID_PLAY, &pDevice->opensl.pAudioPlayer) != SL_RESULT_SUCCESS) { + ma_device_uninit__opensl(pDevice); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to retrieve SL_IID_PLAY interface.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + + if (MA_OPENSL_OBJ(pDevice->opensl.pAudioPlayerObj)->GetInterface((SLObjectItf)pDevice->opensl.pAudioPlayerObj, SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &pDevice->opensl.pBufferQueuePlayback) != SL_RESULT_SUCCESS) { + ma_device_uninit__opensl(pDevice); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to retrieve SL_IID_ANDROIDSIMPLEBUFFERQUEUE interface.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + + if (MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueuePlayback)->RegisterCallback((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueuePlayback, ma_buffer_queue_callback_playback__opensl_android, pDevice) != SL_RESULT_SUCCESS) { + ma_device_uninit__opensl(pDevice); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to register buffer queue callback.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } + + /* The internal format is determined by the "pcm" object. */ + ma_deconstruct_SLDataFormat_PCM__opensl(&pcm, &pDevice->playback.internalFormat, &pDevice->playback.internalChannels, &pDevice->playback.internalSampleRate, pDevice->playback.internalChannelMap); + + /* Buffer. */ + ma_uint32 bufferSizeInFrames = pConfig->bufferSizeInFrames; + if (bufferSizeInFrames == 0) { + bufferSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(pConfig->bufferSizeInMilliseconds, pDevice->playback.internalSampleRate); + } + pDevice->playback.internalPeriods = pConfig->periods; + pDevice->playback.internalBufferSizeInFrames = (bufferSizeInFrames / pDevice->playback.internalPeriods) * pDevice->playback.internalPeriods; + pDevice->opensl.currentBufferIndexPlayback = 0; + + size_t bufferSizeInBytes = pDevice->playback.internalBufferSizeInFrames * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels); + pDevice->opensl.pBufferPlayback = (ma_uint8*)ma_malloc(bufferSizeInBytes); + if (pDevice->opensl.pBufferPlayback == NULL) { + ma_device_uninit__opensl(pDevice); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to allocate memory for data buffer.", MA_OUT_OF_MEMORY); + } + MA_ZERO_MEMORY(pDevice->opensl.pBufferPlayback, bufferSizeInBytes); + } + + if (pConfig->deviceType == ma_device_type_duplex) { + ma_uint32 rbSizeInFrames = (ma_uint32)ma_calculate_frame_count_after_src(pDevice->sampleRate, pDevice->capture.internalSampleRate, pDevice->capture.internalBufferSizeInFrames); + ma_result result = ma_pcm_rb_init(pDevice->capture.format, pDevice->capture.channels, rbSizeInFrames, NULL, &pDevice->opensl.duplexRB); + if (result != MA_SUCCESS) { + ma_device_uninit__opensl(pDevice); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to initialize ring buffer.", result); + } + } + + return MA_SUCCESS; +} + +ma_result ma_device_start__opensl(ma_device* pDevice) +{ + ma_assert(pDevice != NULL); + + ma_assert(g_maOpenSLInitCounter > 0); /* <-- If you trigger this it means you've either not initialized the context, or you've uninitialized it and then attempted to start the device. */ + if (g_maOpenSLInitCounter == 0) { + return MA_INVALID_OPERATION; + } + + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + SLresult resultSL = MA_OPENSL_RECORD(pDevice->opensl.pAudioRecorder)->SetRecordState((SLRecordItf)pDevice->opensl.pAudioRecorder, SL_RECORDSTATE_RECORDING); + if (resultSL != SL_RESULT_SUCCESS) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to start internal capture device.", MA_FAILED_TO_START_BACKEND_DEVICE); + } + + size_t periodSizeInBytes = (pDevice->capture.internalBufferSizeInFrames / pDevice->capture.internalPeriods) * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels); + for (ma_uint32 iPeriod = 0; iPeriod < pDevice->capture.internalPeriods; ++iPeriod) { + resultSL = MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueuePlayback)->Enqueue((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueueCapture, pDevice->opensl.pBufferCapture + (periodSizeInBytes * iPeriod), periodSizeInBytes); + if (resultSL != SL_RESULT_SUCCESS) { + MA_OPENSL_RECORD(pDevice->opensl.pAudioRecorder)->SetRecordState((SLRecordItf)pDevice->opensl.pAudioRecorder, SL_RECORDSTATE_STOPPED); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to enqueue buffer for capture device.", MA_FAILED_TO_START_BACKEND_DEVICE); + } + } + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + SLresult resultSL = MA_OPENSL_PLAY(pDevice->opensl.pAudioPlayer)->SetPlayState((SLPlayItf)pDevice->opensl.pAudioPlayer, SL_PLAYSTATE_PLAYING); + if (resultSL != SL_RESULT_SUCCESS) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to start internal playback device.", MA_FAILED_TO_START_BACKEND_DEVICE); + } + + /* In playback mode (no duplex) we need to load some initial buffers. In duplex mode we need to enqueu silent buffers. */ + if (pDevice->type == ma_device_type_duplex) { + MA_ZERO_MEMORY(pDevice->opensl.pBufferPlayback, pDevice->playback.internalBufferSizeInFrames * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels)); + } else { + ma_device__read_frames_from_client(pDevice, pDevice->playback.internalBufferSizeInFrames, pDevice->opensl.pBufferPlayback); + } + + size_t periodSizeInBytes = (pDevice->playback.internalBufferSizeInFrames / pDevice->playback.internalPeriods) * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels); + for (ma_uint32 iPeriod = 0; iPeriod < pDevice->playback.internalPeriods; ++iPeriod) { + resultSL = MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueuePlayback)->Enqueue((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueuePlayback, pDevice->opensl.pBufferPlayback + (periodSizeInBytes * iPeriod), periodSizeInBytes); + if (resultSL != SL_RESULT_SUCCESS) { + MA_OPENSL_PLAY(pDevice->opensl.pAudioPlayer)->SetPlayState((SLPlayItf)pDevice->opensl.pAudioPlayer, SL_PLAYSTATE_STOPPED); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to enqueue buffer for playback device.", MA_FAILED_TO_START_BACKEND_DEVICE); + } + } + } + + return MA_SUCCESS; +} + +ma_result ma_device_stop__opensl(ma_device* pDevice) +{ + ma_assert(pDevice != NULL); + + ma_assert(g_maOpenSLInitCounter > 0); /* <-- If you trigger this it means you've either not initialized the context, or you've uninitialized it before stopping/uninitializing the device. */ + if (g_maOpenSLInitCounter == 0) { + return MA_INVALID_OPERATION; + } + + /* TODO: Wait until all buffers have been processed. Hint: Maybe SLAndroidSimpleBufferQueue::GetState() could be used in a loop? */ + + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + SLresult resultSL = MA_OPENSL_RECORD(pDevice->opensl.pAudioRecorder)->SetRecordState((SLRecordItf)pDevice->opensl.pAudioRecorder, SL_RECORDSTATE_STOPPED); + if (resultSL != SL_RESULT_SUCCESS) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to stop internal capture device.", MA_FAILED_TO_STOP_BACKEND_DEVICE); + } + + MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueueCapture)->Clear((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueueCapture); + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + SLresult resultSL = MA_OPENSL_PLAY(pDevice->opensl.pAudioPlayer)->SetPlayState((SLPlayItf)pDevice->opensl.pAudioPlayer, SL_PLAYSTATE_STOPPED); + if (resultSL != SL_RESULT_SUCCESS) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to stop internal playback device.", MA_FAILED_TO_STOP_BACKEND_DEVICE); + } + + MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueuePlayback)->Clear((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueuePlayback); + } + + /* Make sure the client is aware that the device has stopped. There may be an OpenSL|ES callback for this, but I haven't found it. */ + ma_stop_proc onStop = pDevice->onStop; + if (onStop) { + onStop(pDevice); + } + + return MA_SUCCESS; +} + + +ma_result ma_context_uninit__opensl(ma_context* pContext) +{ + ma_assert(pContext != NULL); + ma_assert(pContext->backend == ma_backend_opensl); + (void)pContext; + + /* Uninit global data. */ + if (g_maOpenSLInitCounter > 0) { + if (ma_atomic_decrement_32(&g_maOpenSLInitCounter) == 0) { + (*g_maEngineObjectSL)->Destroy(g_maEngineObjectSL); + } + } + + return MA_SUCCESS; +} + +ma_result ma_context_init__opensl(ma_context* pContext) +{ + ma_assert(pContext != NULL); + (void)pContext; + + /* Initialize global data first if applicable. */ + if (ma_atomic_increment_32(&g_maOpenSLInitCounter) == 1) { + SLresult resultSL = slCreateEngine(&g_maEngineObjectSL, 0, NULL, 0, NULL, NULL); + if (resultSL != SL_RESULT_SUCCESS) { + ma_atomic_decrement_32(&g_maOpenSLInitCounter); + return MA_NO_BACKEND; + } + + (*g_maEngineObjectSL)->Realize(g_maEngineObjectSL, SL_BOOLEAN_FALSE); + + resultSL = (*g_maEngineObjectSL)->GetInterface(g_maEngineObjectSL, SL_IID_ENGINE, &g_maEngineSL); + if (resultSL != SL_RESULT_SUCCESS) { + (*g_maEngineObjectSL)->Destroy(g_maEngineObjectSL); + ma_atomic_decrement_32(&g_maOpenSLInitCounter); + return MA_NO_BACKEND; + } + } + + pContext->isBackendAsynchronous = MA_TRUE; + + pContext->onUninit = ma_context_uninit__opensl; + pContext->onDeviceIDEqual = ma_context_is_device_id_equal__opensl; + pContext->onEnumDevices = ma_context_enumerate_devices__opensl; + pContext->onGetDeviceInfo = ma_context_get_device_info__opensl; + pContext->onDeviceInit = ma_device_init__opensl; + pContext->onDeviceUninit = ma_device_uninit__opensl; + pContext->onDeviceStart = ma_device_start__opensl; + pContext->onDeviceStop = ma_device_stop__opensl; + + return MA_SUCCESS; +} +#endif /* OpenSL|ES */ + + +/////////////////////////////////////////////////////////////////////////////// +// +// Web Audio Backend +// +/////////////////////////////////////////////////////////////////////////////// +#ifdef MA_HAS_WEBAUDIO +#include + +ma_bool32 ma_is_capture_supported__webaudio() +{ + return EM_ASM_INT({ + return (navigator.mediaDevices !== undefined && navigator.mediaDevices.getUserMedia !== undefined); + }, 0) != 0; /* Must pass in a dummy argument for C99 compatibility. */ +} + +#ifdef __cplusplus +extern "C" { +#endif +EMSCRIPTEN_KEEPALIVE void ma_device_process_pcm_frames_capture__webaudio(ma_device* pDevice, int frameCount, float* pFrames) +{ + ma_result result; + + if (pDevice->type == ma_device_type_duplex) { + ma_device__handle_duplex_callback_capture(pDevice, (ma_uint32)frameCount, pFrames, &pDevice->webaudio.duplexRB); + } else { + ma_device__send_frames_to_client(pDevice, (ma_uint32)frameCount, pFrames); /* Send directly to the client. */ + } +} + +EMSCRIPTEN_KEEPALIVE void ma_device_process_pcm_frames_playback__webaudio(ma_device* pDevice, int frameCount, float* pFrames) +{ + if (pDevice->type == ma_device_type_duplex) { + ma_device__handle_duplex_callback_playback(pDevice, (ma_uint32)frameCount, pFrames, &pDevice->webaudio.duplexRB); + } else { + ma_device__read_frames_from_client(pDevice, (ma_uint32)frameCount, pFrames); /* Read directly from the device. */ + } +} +#ifdef __cplusplus +} +#endif + +ma_bool32 ma_context_is_device_id_equal__webaudio(ma_context* pContext, const ma_device_id* pID0, const ma_device_id* pID1) +{ + ma_assert(pContext != NULL); + ma_assert(pID0 != NULL); + ma_assert(pID1 != NULL); + (void)pContext; + + return ma_strcmp(pID0->webaudio, pID1->webaudio) == 0; +} + +ma_result ma_context_enumerate_devices__webaudio(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData) +{ + ma_assert(pContext != NULL); + ma_assert(callback != NULL); + + // Only supporting default devices for now. + ma_bool32 cbResult = MA_TRUE; + + // Playback. + if (cbResult) { + ma_device_info deviceInfo; + ma_zero_object(&deviceInfo); + ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); + cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData); + } + + // Capture. + if (cbResult) { + if (ma_is_capture_supported__webaudio()) { + ma_device_info deviceInfo; + ma_zero_object(&deviceInfo); + ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); + cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData); + } + } + + return MA_SUCCESS; +} + +ma_result ma_context_get_device_info__webaudio(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_share_mode shareMode, ma_device_info* pDeviceInfo) +{ + ma_assert(pContext != NULL); + + /* No exclusive mode with Web Audio. */ + if (shareMode == ma_share_mode_exclusive) { + return MA_SHARE_MODE_NOT_SUPPORTED; + } + + if (deviceType == ma_device_type_capture && !ma_is_capture_supported__webaudio()) { + return MA_NO_DEVICE; + } + + + ma_zero_memory(pDeviceInfo->id.webaudio, sizeof(pDeviceInfo->id.webaudio)); + + /* Only supporting default devices for now. */ + if (deviceType == ma_device_type_playback) { + ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); + } else { + ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); + } + + /* Web Audio can support any number of channels and sample rates. It only supports f32 formats, however. */ + pDeviceInfo->minChannels = 1; + pDeviceInfo->maxChannels = MA_MAX_CHANNELS; + if (pDeviceInfo->maxChannels > 32) { + pDeviceInfo->maxChannels = 32; /* Maximum output channel count is 32 for createScriptProcessor() (JavaScript). */ + } + + /* We can query the sample rate by just using a temporary audio context. */ + pDeviceInfo->minSampleRate = EM_ASM_INT({ + try { + var temp = new (window.AudioContext || window.webkitAudioContext)(); + var sampleRate = temp.sampleRate; + temp.close(); + return sampleRate; + } catch(e) { + return 0; + } + }, 0); /* Must pass in a dummy argument for C99 compatibility. */ + pDeviceInfo->maxSampleRate = pDeviceInfo->minSampleRate; + if (pDeviceInfo->minSampleRate == 0) { + return MA_NO_DEVICE; + } + + /* Web Audio only supports f32. */ + pDeviceInfo->formatCount = 1; + pDeviceInfo->formats[0] = ma_format_f32; + + return MA_SUCCESS; +} + + +void ma_device_uninit_by_index__webaudio(ma_device* pDevice, ma_device_type deviceType, int deviceIndex) +{ + ma_assert(pDevice != NULL); + + EM_ASM({ + var device = miniaudio.get_device_by_index($0); + + /* Make sure all nodes are disconnected and marked for collection. */ + if (device.scriptNode !== undefined) { + device.scriptNode.onaudioprocess = function(e) {}; /* We want to reset the callback to ensure it doesn't get called after AudioContext.close() has returned. Shouldn't happen since we're disconnecting, but just to be safe... */ + device.scriptNode.disconnect(); + device.scriptNode = undefined; + } + if (device.streamNode !== undefined) { + device.streamNode.disconnect(); + device.streamNode = undefined; + } + + /* + Stop the device. I think there is a chance the callback could get fired after calling this, hence why we want + to clear the callback before closing. + */ + device.webaudio.close(); + device.webaudio = undefined; + + /* Can't forget to free the intermediary buffer. This is the buffer that's shared between JavaScript and C. */ + if (device.intermediaryBuffer !== undefined) { + Module._free(device.intermediaryBuffer); + device.intermediaryBuffer = undefined; + device.intermediaryBufferView = undefined; + device.intermediaryBufferSizeInBytes = undefined; + } + + /* Make sure the device is untracked so the slot can be reused later. */ + miniaudio.untrack_device_by_index($0); + }, deviceIndex, deviceType); +} + +void ma_device_uninit__webaudio(ma_device* pDevice) +{ + ma_assert(pDevice != NULL); + + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + ma_device_uninit_by_index__webaudio(pDevice, ma_device_type_capture, pDevice->webaudio.indexCapture); + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + ma_device_uninit_by_index__webaudio(pDevice, ma_device_type_playback, pDevice->webaudio.indexPlayback); + } + + if (pDevice->type == ma_device_type_duplex) { + ma_pcm_rb_uninit(&pDevice->webaudio.duplexRB); + } +} + +ma_result ma_device_init_by_type__webaudio(ma_context* pContext, const ma_device_config* pConfig, ma_device_type deviceType, ma_device* pDevice) +{ + int deviceIndex; + ma_uint32 internalBufferSizeInFrames; + + ma_assert(pContext != NULL); + ma_assert(pConfig != NULL); + ma_assert(deviceType != ma_device_type_duplex); + ma_assert(pDevice != NULL); + + if (deviceType == ma_device_type_capture && !ma_is_capture_supported__webaudio()) { + return MA_NO_DEVICE; + } + + /* Try calculating an appropriate buffer size. */ + internalBufferSizeInFrames = pConfig->bufferSizeInFrames; + if (internalBufferSizeInFrames == 0) { + internalBufferSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(pConfig->bufferSizeInMilliseconds, pConfig->sampleRate); + } + + /* The size of the buffer must be a power of 2 and between 256 and 16384. */ + if (internalBufferSizeInFrames < 256) { + internalBufferSizeInFrames = 256; + } else if (internalBufferSizeInFrames > 16384) { + internalBufferSizeInFrames = 16384; + } else { + internalBufferSizeInFrames = ma_next_power_of_2(internalBufferSizeInFrames); + } + + /* We create the device on the JavaScript side and reference it using an index. We use this to make it possible to reference the device between JavaScript and C. */ + deviceIndex = EM_ASM_INT({ + var channels = $0; + var sampleRate = $1; + var bufferSize = $2; /* In PCM frames. */ + var isCapture = $3; + var pDevice = $4; + + if (typeof(miniaudio) === 'undefined') { + return -1; /* Context not initialized. */ + } + + var device = {}; + + /* The AudioContext must be created in a suspended state. */ + device.webaudio = new (window.AudioContext || window.webkitAudioContext)({sampleRate:sampleRate}); + device.webaudio.suspend(); + + /* + We need an intermediary buffer which we use for JavaScript and C interop. This buffer stores interleaved f32 PCM data. Because it's passed between + JavaScript and C it needs to be allocated and freed using Module._malloc() and Module._free(). + */ + device.intermediaryBufferSizeInBytes = channels * bufferSize * 4; + device.intermediaryBuffer = Module._malloc(device.intermediaryBufferSizeInBytes); + device.intermediaryBufferView = new Float32Array(Module.HEAPF32.buffer, device.intermediaryBuffer, device.intermediaryBufferSizeInBytes); + + /* + Both playback and capture devices use a ScriptProcessorNode for performing per-sample operations. + + ScriptProcessorNode is actually deprecated so this is likely to be temporary. The way this works for playback is very simple. You just set a callback + that's periodically fired, just like a normal audio callback function. But apparently this design is "flawed" and is now deprecated in favour of + something called AudioWorklets which _forces_ you to load a _separate_ .js file at run time... nice... Hopefully ScriptProcessorNode will continue to + work for years to come, but this may need to change to use AudioSourceBufferNode instead, which I think is what Emscripten uses for it's built-in SDL + implementation. I'll be avoiding that insane AudioWorklet API like the plague... + + For capture it is a bit unintuitive. We use the ScriptProccessorNode _only_ to get the raw PCM data. It is connected to an AudioContext just like the + playback case, however we just output silence to the AudioContext instead of passing any real data. It would make more sense to me to use the + MediaRecorder API, but unfortunately you need to specify a MIME time (Opus, Vorbis, etc.) for the binary blob that's returned to the client, but I've + been unable to figure out how to get this as raw PCM. The closes I can think is to use the MIME type for WAV files and just parse it, but I don't know + how well this would work. Although ScriptProccessorNode is deprecated, in practice it seems to have pretty good browser support so I'm leaving it like + this for now. If anything knows how I could get raw PCM data using the MediaRecorder API please let me know! + */ + device.scriptNode = device.webaudio.createScriptProcessor(bufferSize, channels, channels); + + if (isCapture) { + device.scriptNode.onaudioprocess = function(e) { + if (device.intermediaryBuffer === undefined) { + return; /* This means the device has been uninitialized. */ + } + + /* Make sure silence it output to the AudioContext destination. Not doing this will cause sound to come out of the speakers! */ + for (var iChannel = 0; iChannel < e.outputBuffer.numberOfChannels; ++iChannel) { + e.outputBuffer.getChannelData(iChannel).fill(0.0); + } + + /* There are some situations where we may want to send silence to the client. */ + var sendSilence = false; + if (device.streamNode === undefined) { + sendSilence = true; + } + + /* Sanity check. This will never happen, right? */ + if (e.inputBuffer.numberOfChannels != channels) { + console.log("Capture: Channel count mismatch. " + e.inputBufer.numberOfChannels + " != " + channels + ". Sending silence."); + sendSilence = true; + } + + /* This looped design guards against the situation where e.inputBuffer is a different size to the original buffer size. Should never happen in practice. */ + var totalFramesProcessed = 0; + while (totalFramesProcessed < e.inputBuffer.length) { + var framesRemaining = e.inputBuffer.length - totalFramesProcessed; + var framesToProcess = framesRemaining; + if (framesToProcess > (device.intermediaryBufferSizeInBytes/channels/4)) { + framesToProcess = (device.intermediaryBufferSizeInBytes/channels/4); + } + + /* We need to do the reverse of the playback case. We need to interleave the input data and copy it into the intermediary buffer. Then we send it to the client. */ + if (sendSilence) { + device.intermediaryBufferView.fill(0.0); + } else { + for (var iFrame = 0; iFrame < framesToProcess; ++iFrame) { + for (var iChannel = 0; iChannel < e.inputBuffer.numberOfChannels; ++iChannel) { + device.intermediaryBufferView[iFrame*channels + iChannel] = e.inputBuffer.getChannelData(iChannel)[totalFramesProcessed + iFrame]; + } + } + } + + /* Send data to the client from our intermediary buffer. */ + ccall("ma_device_process_pcm_frames_capture__webaudio", "undefined", ["number", "number", "number"], [pDevice, framesToProcess, device.intermediaryBuffer]); + + totalFramesProcessed += framesToProcess; + } + }; + + navigator.mediaDevices.getUserMedia({audio:true, video:false}) + .then(function(stream) { + device.streamNode = device.webaudio.createMediaStreamSource(stream); + device.streamNode.connect(device.scriptNode); + device.scriptNode.connect(device.webaudio.destination); + }) + .catch(function(error) { + /* I think this should output silence... */ + device.scriptNode.connect(device.webaudio.destination); + }); + } else { + device.scriptNode.onaudioprocess = function(e) { + if (device.intermediaryBuffer === undefined) { + return; /* This means the device has been uninitialized. */ + } + + var outputSilence = false; + + /* Sanity check. This will never happen, right? */ + if (e.outputBuffer.numberOfChannels != channels) { + console.log("Playback: Channel count mismatch. " + e.outputBufer.numberOfChannels + " != " + channels + ". Outputting silence."); + outputSilence = true; + return; + } + + /* This looped design guards against the situation where e.outputBuffer is a different size to the original buffer size. Should never happen in practice. */ + var totalFramesProcessed = 0; + while (totalFramesProcessed < e.outputBuffer.length) { + var framesRemaining = e.outputBuffer.length - totalFramesProcessed; + var framesToProcess = framesRemaining; + if (framesToProcess > (device.intermediaryBufferSizeInBytes/channels/4)) { + framesToProcess = (device.intermediaryBufferSizeInBytes/channels/4); + } + + /* Read data from the client into our intermediary buffer. */ + ccall("ma_device_process_pcm_frames_playback__webaudio", "undefined", ["number", "number", "number"], [pDevice, framesToProcess, device.intermediaryBuffer]); + + /* At this point we'll have data in our intermediary buffer which we now need to deinterleave and copy over to the output buffers. */ + if (outputSilence) { + for (var iChannel = 0; iChannel < e.outputBuffer.numberOfChannels; ++iChannel) { + e.outputBuffer.getChannelData(iChannel).fill(0.0); + } + } else { + for (var iChannel = 0; iChannel < e.outputBuffer.numberOfChannels; ++iChannel) { + for (var iFrame = 0; iFrame < framesToProcess; ++iFrame) { + e.outputBuffer.getChannelData(iChannel)[totalFramesProcessed + iFrame] = device.intermediaryBufferView[iFrame*channels + iChannel]; + } + } + } + + totalFramesProcessed += framesToProcess; + } + }; + + device.scriptNode.connect(device.webaudio.destination); + } + + return miniaudio.track_device(device); + }, (deviceType == ma_device_type_capture) ? pConfig->capture.channels : pConfig->playback.channels, pConfig->sampleRate, internalBufferSizeInFrames, deviceType == ma_device_type_capture, pDevice); + + if (deviceIndex < 0) { + return MA_FAILED_TO_OPEN_BACKEND_DEVICE; + } + + if (deviceType == ma_device_type_capture) { + pDevice->webaudio.indexCapture = deviceIndex; + pDevice->capture.internalFormat = ma_format_f32; + pDevice->capture.internalChannels = pConfig->capture.channels; + ma_get_standard_channel_map(ma_standard_channel_map_webaudio, pDevice->capture.internalChannels, pDevice->capture.internalChannelMap); + pDevice->capture.internalSampleRate = EM_ASM_INT({ return miniaudio.get_device_by_index($0).webaudio.sampleRate; }, deviceIndex); + pDevice->capture.internalBufferSizeInFrames = internalBufferSizeInFrames; + pDevice->capture.internalPeriods = 1; + } else { + pDevice->webaudio.indexPlayback = deviceIndex; + pDevice->playback.internalFormat = ma_format_f32; + pDevice->playback.internalChannels = pConfig->playback.channels; + ma_get_standard_channel_map(ma_standard_channel_map_webaudio, pDevice->playback.internalChannels, pDevice->playback.internalChannelMap); + pDevice->playback.internalSampleRate = EM_ASM_INT({ return miniaudio.get_device_by_index($0).webaudio.sampleRate; }, deviceIndex); + pDevice->playback.internalBufferSizeInFrames = internalBufferSizeInFrames; + pDevice->playback.internalPeriods = 1; + } + + return MA_SUCCESS; +} + +ma_result ma_device_init__webaudio(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice) +{ + ma_result result; + + /* No exclusive mode with Web Audio. */ + if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pConfig->playback.shareMode == ma_share_mode_exclusive) || + ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pConfig->capture.shareMode == ma_share_mode_exclusive)) { + return MA_SHARE_MODE_NOT_SUPPORTED; + } + + if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) { + result = ma_device_init_by_type__webaudio(pContext, pConfig, ma_device_type_capture, pDevice); + if (result != MA_SUCCESS) { + return result; + } + } + + if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) { + result = ma_device_init_by_type__webaudio(pContext, pConfig, ma_device_type_playback, pDevice); + if (result != MA_SUCCESS) { + if (pConfig->deviceType == ma_device_type_duplex) { + ma_device_uninit_by_index__webaudio(pDevice, ma_device_type_capture, pDevice->webaudio.indexCapture); + } + return result; + } + } + + /* + We need a ring buffer for moving data from the capture device to the playback device. The capture callback is the producer + and the playback callback is the consumer. The buffer needs to be large enough to hold internalBufferSizeInFrames based on + the external sample rate. + */ + if (pConfig->deviceType == ma_device_type_duplex) { + ma_uint32 rbSizeInFrames = (ma_uint32)ma_calculate_frame_count_after_src(pDevice->sampleRate, pDevice->capture.internalSampleRate, pDevice->capture.internalBufferSizeInFrames) * 2; + result = ma_pcm_rb_init(pDevice->capture.format, pDevice->capture.channels, rbSizeInFrames, NULL, &pDevice->webaudio.duplexRB); + if (result != MA_SUCCESS) { + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + ma_device_uninit_by_index__webaudio(pDevice, ma_device_type_capture, pDevice->webaudio.indexCapture); + } + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + ma_device_uninit_by_index__webaudio(pDevice, ma_device_type_playback, pDevice->webaudio.indexPlayback); + } + return result; + } + } + + return MA_SUCCESS; +} + +ma_result ma_device_start__webaudio(ma_device* pDevice) +{ + ma_assert(pDevice != NULL); + + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + EM_ASM({ + miniaudio.get_device_by_index($0).webaudio.resume(); + }, pDevice->webaudio.indexCapture); + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + EM_ASM({ + miniaudio.get_device_by_index($0).webaudio.resume(); + }, pDevice->webaudio.indexPlayback); + } + + return MA_SUCCESS; +} + +ma_result ma_device_stop__webaudio(ma_device* pDevice) +{ + ma_assert(pDevice != NULL); + + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + EM_ASM({ + miniaudio.get_device_by_index($0).webaudio.suspend(); + }, pDevice->webaudio.indexCapture); + } + + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + EM_ASM({ + miniaudio.get_device_by_index($0).webaudio.suspend(); + }, pDevice->webaudio.indexPlayback); + } + + ma_stop_proc onStop = pDevice->onStop; + if (onStop) { + onStop(pDevice); + } + + return MA_SUCCESS; +} + +ma_result ma_context_uninit__webaudio(ma_context* pContext) +{ + ma_assert(pContext != NULL); + ma_assert(pContext->backend == ma_backend_webaudio); + + /* Nothing needs to be done here. */ + (void)pContext; + + return MA_SUCCESS; +} + +ma_result ma_context_init__webaudio(ma_context* pContext) +{ + ma_assert(pContext != NULL); + + /* Here is where our global JavaScript object is initialized. */ + int resultFromJS = EM_ASM_INT({ + if ((window.AudioContext || window.webkitAudioContext) === undefined) { + return 0; /* Web Audio not supported. */ + } + + if (typeof(miniaudio) === 'undefined') { + miniaudio = {}; + miniaudio.devices = []; /* Device cache for mapping devices to indexes for JavaScript/C interop. */ + + miniaudio.track_device = function(device) { + /* Try inserting into a free slot first. */ + for (var iDevice = 0; iDevice < miniaudio.devices.length; ++iDevice) { + if (miniaudio.devices[iDevice] == null) { + miniaudio.devices[iDevice] = device; + return iDevice; + } + } + + /* Getting here means there is no empty slots in the array so we just push to the end. */ + miniaudio.devices.push(device); + return miniaudio.devices.length - 1; + }; + + miniaudio.untrack_device_by_index = function(deviceIndex) { + /* We just set the device's slot to null. The slot will get reused in the next call to ma_track_device. */ + miniaudio.devices[deviceIndex] = null; + + /* Trim the array if possible. */ + while (miniaudio.devices.length > 0) { + if (miniaudio.devices[miniaudio.devices.length-1] == null) { + miniaudio.devices.pop(); + } else { + break; + } + } + }; + + miniaudio.untrack_device = function(device) { + for (var iDevice = 0; iDevice < miniaudio.devices.length; ++iDevice) { + if (miniaudio.devices[iDevice] == device) { + return miniaudio.untrack_device_by_index(iDevice); + } + } + }; + + miniaudio.get_device_by_index = function(deviceIndex) { + return miniaudio.devices[deviceIndex]; + }; + } + + return 1; + }, 0); /* Must pass in a dummy argument for C99 compatibility. */ + + if (resultFromJS != 1) { + return MA_FAILED_TO_INIT_BACKEND; + } + + + pContext->isBackendAsynchronous = MA_TRUE; + + pContext->onUninit = ma_context_uninit__webaudio; + pContext->onDeviceIDEqual = ma_context_is_device_id_equal__webaudio; + pContext->onEnumDevices = ma_context_enumerate_devices__webaudio; + pContext->onGetDeviceInfo = ma_context_get_device_info__webaudio; + pContext->onDeviceInit = ma_device_init__webaudio; + pContext->onDeviceUninit = ma_device_uninit__webaudio; + pContext->onDeviceStart = ma_device_start__webaudio; + pContext->onDeviceStop = ma_device_stop__webaudio; + + return MA_SUCCESS; +} +#endif // Web Audio + + + +ma_bool32 ma__is_channel_map_valid(const ma_channel* channelMap, ma_uint32 channels) +{ + // A blank channel map should be allowed, in which case it should use an appropriate default which will depend on context. + if (channelMap[0] != MA_CHANNEL_NONE) { + if (channels == 0) { + return MA_FALSE; // No channels. + } + + // A channel cannot be present in the channel map more than once. + for (ma_uint32 iChannel = 0; iChannel < channels; ++iChannel) { + for (ma_uint32 jChannel = iChannel + 1; jChannel < channels; ++jChannel) { + if (channelMap[iChannel] == channelMap[jChannel]) { + return MA_FALSE; + } + } + } + } + + return MA_TRUE; +} + + +void ma_device__post_init_setup(ma_device* pDevice, ma_device_type deviceType) +{ + ma_assert(pDevice != NULL); + + if (deviceType == ma_device_type_capture || deviceType == ma_device_type_duplex) { + if (pDevice->capture.usingDefaultFormat) { + pDevice->capture.format = pDevice->capture.internalFormat; + } + if (pDevice->capture.usingDefaultChannels) { + pDevice->capture.channels = pDevice->capture.internalChannels; + } + if (pDevice->capture.usingDefaultChannelMap) { + if (pDevice->capture.internalChannels == pDevice->capture.channels) { + ma_channel_map_copy(pDevice->capture.channelMap, pDevice->capture.internalChannelMap, pDevice->capture.channels); + } else { + ma_get_standard_channel_map(ma_standard_channel_map_default, pDevice->capture.channels, pDevice->capture.channelMap); + } + } + } + + if (deviceType == ma_device_type_playback || deviceType == ma_device_type_duplex) { + if (pDevice->playback.usingDefaultFormat) { + pDevice->playback.format = pDevice->playback.internalFormat; + } + if (pDevice->playback.usingDefaultChannels) { + pDevice->playback.channels = pDevice->playback.internalChannels; + } + if (pDevice->playback.usingDefaultChannelMap) { + if (pDevice->playback.internalChannels == pDevice->playback.channels) { + ma_channel_map_copy(pDevice->playback.channelMap, pDevice->playback.internalChannelMap, pDevice->playback.channels); + } else { + ma_get_standard_channel_map(ma_standard_channel_map_default, pDevice->playback.channels, pDevice->playback.channelMap); + } + } + } + + if (pDevice->usingDefaultSampleRate) { + if (deviceType == ma_device_type_capture || deviceType == ma_device_type_duplex) { + pDevice->sampleRate = pDevice->capture.internalSampleRate; + } else { + pDevice->sampleRate = pDevice->playback.internalSampleRate; + } + } + + /* PCM converters. */ + if (deviceType == ma_device_type_capture || deviceType == ma_device_type_duplex) { + /* Converting from internal device format to public format. */ + ma_pcm_converter_config converterConfig = ma_pcm_converter_config_init_new(); + converterConfig.neverConsumeEndOfInput = MA_TRUE; + converterConfig.pUserData = pDevice; + converterConfig.formatIn = pDevice->capture.internalFormat; + converterConfig.channelsIn = pDevice->capture.internalChannels; + converterConfig.sampleRateIn = pDevice->capture.internalSampleRate; + ma_channel_map_copy(converterConfig.channelMapIn, pDevice->capture.internalChannelMap, pDevice->capture.internalChannels); + converterConfig.formatOut = pDevice->capture.format; + converterConfig.channelsOut = pDevice->capture.channels; + converterConfig.sampleRateOut = pDevice->sampleRate; + ma_channel_map_copy(converterConfig.channelMapOut, pDevice->capture.channelMap, pDevice->capture.channels); + converterConfig.onRead = ma_device__pcm_converter__on_read_from_buffer_capture; + ma_pcm_converter_init(&converterConfig, &pDevice->capture.converter); + } + + if (deviceType == ma_device_type_playback || deviceType == ma_device_type_duplex) { + /* Converting from public format to device format. */ + ma_pcm_converter_config converterConfig = ma_pcm_converter_config_init_new(); + converterConfig.neverConsumeEndOfInput = MA_TRUE; + converterConfig.pUserData = pDevice; + converterConfig.formatIn = pDevice->playback.format; + converterConfig.channelsIn = pDevice->playback.channels; + converterConfig.sampleRateIn = pDevice->sampleRate; + ma_channel_map_copy(converterConfig.channelMapIn, pDevice->playback.channelMap, pDevice->playback.channels); + converterConfig.formatOut = pDevice->playback.internalFormat; + converterConfig.channelsOut = pDevice->playback.internalChannels; + converterConfig.sampleRateOut = pDevice->playback.internalSampleRate; + ma_channel_map_copy(converterConfig.channelMapOut, pDevice->playback.internalChannelMap, pDevice->playback.internalChannels); + if (deviceType == ma_device_type_playback) { + if (pDevice->type == ma_device_type_playback) { + converterConfig.onRead = ma_device__on_read_from_client; + } else { + converterConfig.onRead = ma_device__pcm_converter__on_read_from_buffer_playback; + } + } else { + converterConfig.onRead = ma_device__pcm_converter__on_read_from_buffer_playback; + } + ma_pcm_converter_init(&converterConfig, &pDevice->playback.converter); + } +} + + +ma_thread_result MA_THREADCALL ma_worker_thread(void* pData) +{ + ma_device* pDevice = (ma_device*)pData; + ma_assert(pDevice != NULL); + +#ifdef MA_WIN32 + ma_CoInitializeEx(pDevice->pContext, NULL, MA_COINIT_VALUE); +#endif + + // When the device is being initialized it's initial state is set to MA_STATE_UNINITIALIZED. Before returning from + // ma_device_init(), the state needs to be set to something valid. In miniaudio the device's default state immediately + // after initialization is stopped, so therefore we need to mark the device as such. miniaudio will wait on the worker + // thread to signal an event to know when the worker thread is ready for action. + ma_device__set_state(pDevice, MA_STATE_STOPPED); + ma_event_signal(&pDevice->stopEvent); + + for (;;) { /* <-- This loop just keeps the thread alive. The main audio loop is inside. */ + // We wait on an event to know when something has requested that the device be started and the main loop entered. + ma_event_wait(&pDevice->wakeupEvent); + + // Default result code. + pDevice->workResult = MA_SUCCESS; + + // If the reason for the wake up is that we are terminating, just break from the loop. + if (ma_device__get_state(pDevice) == MA_STATE_UNINITIALIZED) { + break; + } + + // Getting to this point means the device is wanting to get started. The function that has requested that the device + // be started will be waiting on an event (pDevice->startEvent) which means we need to make sure we signal the event + // in both the success and error case. It's important that the state of the device is set _before_ signaling the event. + ma_assert(ma_device__get_state(pDevice) == MA_STATE_STARTING); + + /* Make sure the state is set appropriately. */ + ma_device__set_state(pDevice, MA_STATE_STARTED); + ma_event_signal(&pDevice->startEvent); + + if (pDevice->pContext->onDeviceMainLoop != NULL) { + pDevice->pContext->onDeviceMainLoop(pDevice); + } else { + /* When a device is using miniaudio's generic worker thread they must implement onDeviceRead or onDeviceWrite, depending on the device type. */ + ma_assert( + (pDevice->type == ma_device_type_playback && pDevice->pContext->onDeviceWrite != NULL) || + (pDevice->type == ma_device_type_capture && pDevice->pContext->onDeviceRead != NULL) || + (pDevice->type == ma_device_type_duplex && pDevice->pContext->onDeviceWrite != NULL && pDevice->pContext->onDeviceRead != NULL) + ); + + ma_uint32 periodSizeInFrames; + if (pDevice->type == ma_device_type_capture) { + ma_assert(pDevice->capture.internalBufferSizeInFrames >= pDevice->capture.internalPeriods); + periodSizeInFrames = pDevice->capture.internalBufferSizeInFrames / pDevice->capture.internalPeriods; + } else if (pDevice->type == ma_device_type_playback) { + ma_assert(pDevice->playback.internalBufferSizeInFrames >= pDevice->playback.internalPeriods); + periodSizeInFrames = pDevice->playback.internalBufferSizeInFrames / pDevice->playback.internalPeriods; + } else { + ma_assert(pDevice->capture.internalBufferSizeInFrames >= pDevice->capture.internalPeriods); + ma_assert(pDevice->playback.internalBufferSizeInFrames >= pDevice->playback.internalPeriods); + periodSizeInFrames = ma_min( + pDevice->capture.internalBufferSizeInFrames / pDevice->capture.internalPeriods, + pDevice->playback.internalBufferSizeInFrames / pDevice->playback.internalPeriods + ); + } + + /* + With the blocking API, the device is started automatically in read()/write(). All we need to do is enter the loop and just keep reading + or writing based on the period size. + */ + + /* Main Loop */ + ma_assert(periodSizeInFrames >= 1); + while (ma_device__get_state(pDevice) == MA_STATE_STARTED) { + ma_result result = MA_SUCCESS; + ma_uint32 totalFramesProcessed = 0; + + if (pDevice->type == ma_device_type_duplex) { + /* The process is device_read -> convert -> callback -> convert -> device_write. */ + ma_uint8 captureDeviceData[4096]; + ma_uint32 captureDeviceDataCapInFrames = sizeof(captureDeviceData) / ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels); + + while (totalFramesProcessed < periodSizeInFrames) { + ma_uint32 framesRemaining = periodSizeInFrames - totalFramesProcessed; + ma_uint32 framesToProcess = framesRemaining; + if (framesToProcess > captureDeviceDataCapInFrames) { + framesToProcess = captureDeviceDataCapInFrames; + } + + result = pDevice->pContext->onDeviceRead(pDevice, captureDeviceData, framesToProcess); + if (result != MA_SUCCESS) { + break; + } + + ma_device_callback_proc onData = pDevice->onData; + if (onData != NULL) { + pDevice->capture._dspFrameCount = framesToProcess; + pDevice->capture._dspFrames = captureDeviceData; + + /* We need to process every input frame. */ + for (;;) { + ma_uint8 capturedData[4096]; // In capture.format/channels format + ma_uint8 playbackData[4096]; // In playback.format/channels format + + ma_uint32 capturedDataCapInFrames = sizeof(capturedData) / ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels); + ma_uint32 playbackDataCapInFrames = sizeof(playbackData) / ma_get_bytes_per_frame(pDevice->playback.format, pDevice->playback.channels); + + ma_uint32 capturedFramesToTryProcessing = ma_min(capturedDataCapInFrames, playbackDataCapInFrames); + ma_uint32 capturedFramesToProcess = (ma_uint32)ma_pcm_converter_read(&pDevice->capture.converter, capturedData, capturedFramesToTryProcessing); + if (capturedFramesToProcess == 0) { + break; /* Don't fire the data callback with zero frames. */ + } + + onData(pDevice, playbackData, capturedData, capturedFramesToProcess); + + /* At this point the playbackData buffer should be holding data that needs to be written to the device. */ + pDevice->playback._dspFrameCount = capturedFramesToProcess; + pDevice->playback._dspFrames = playbackData; + for (;;) { + ma_uint8 playbackDeviceData[4096]; + + ma_uint32 playbackDeviceDataCapInFrames = sizeof(playbackDeviceData) / ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels); + ma_uint32 playbackDeviceFramesCount = (ma_uint32)ma_pcm_converter_read(&pDevice->playback.converter, playbackDeviceData, playbackDeviceDataCapInFrames); + if (playbackDeviceFramesCount == 0) { + break; + } + + result = pDevice->pContext->onDeviceWrite(pDevice, playbackDeviceData, playbackDeviceFramesCount); + if (result != MA_SUCCESS) { + break; + } + + if (playbackDeviceFramesCount < playbackDeviceDataCapInFrames) { + break; + } + } + + if (capturedFramesToProcess < capturedFramesToTryProcessing) { + break; + } + + /* In case an error happened from onDeviceWrite()... */ + if (result != MA_SUCCESS) { + break; + } + } + } + + totalFramesProcessed += framesToProcess; + } + } else { + ma_uint8 buffer[4096]; + ma_uint32 bufferSizeInFrames; + if (pDevice->type == ma_device_type_capture) { + bufferSizeInFrames = sizeof(buffer) / ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels); + } else { + bufferSizeInFrames = sizeof(buffer) / ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels); + } + + while (totalFramesProcessed < periodSizeInFrames) { + ma_uint32 framesRemaining = periodSizeInFrames - totalFramesProcessed; + ma_uint32 framesToProcess = framesRemaining; + if (framesToProcess > bufferSizeInFrames) { + framesToProcess = bufferSizeInFrames; + } + + if (pDevice->type == ma_device_type_playback) { + ma_device__read_frames_from_client(pDevice, framesToProcess, buffer); + result = pDevice->pContext->onDeviceWrite(pDevice, buffer, framesToProcess); + } else { + result = pDevice->pContext->onDeviceRead(pDevice, buffer, framesToProcess); + ma_device__send_frames_to_client(pDevice, framesToProcess, buffer); + } + + totalFramesProcessed += framesToProcess; + } + } + + /* Get out of the loop if read()/write() returned an error. It probably means the device has been stopped. */ + if (result != MA_SUCCESS) { + break; + } + } + } + + + // Getting here means we have broken from the main loop which happens the application has requested that device be stopped. Note that this + // may have actually already happened above if the device was lost and miniaudio has attempted to re-initialize the device. In this case we + // don't want to be doing this a second time. + if (ma_device__get_state(pDevice) != MA_STATE_UNINITIALIZED) { + if (pDevice->pContext->onDeviceStop) { + pDevice->pContext->onDeviceStop(pDevice); + } + } + + // After the device has stopped, make sure an event is posted. + ma_stop_proc onStop = pDevice->onStop; + if (onStop) { + onStop(pDevice); + } + + // A function somewhere is waiting for the device to have stopped for real so we need to signal an event to allow it to continue. Note that + // it's possible that the device has been uninitialized which means we need to _not_ change the status to stopped. We cannot go from an + // uninitialized state to stopped state. + if (ma_device__get_state(pDevice) != MA_STATE_UNINITIALIZED) { + ma_device__set_state(pDevice, MA_STATE_STOPPED); + ma_event_signal(&pDevice->stopEvent); + } + } + + // Make sure we aren't continuously waiting on a stop event. + ma_event_signal(&pDevice->stopEvent); // <-- Is this still needed? + +#ifdef MA_WIN32 + ma_CoUninitialize(pDevice->pContext); +#endif + + return (ma_thread_result)0; +} + + +// Helper for determining whether or not the given device is initialized. +ma_bool32 ma_device__is_initialized(ma_device* pDevice) +{ + if (pDevice == NULL) return MA_FALSE; + return ma_device__get_state(pDevice) != MA_STATE_UNINITIALIZED; +} + + +#ifdef MA_WIN32 +ma_result ma_context_uninit_backend_apis__win32(ma_context* pContext) +{ + ma_CoUninitialize(pContext); + ma_dlclose(pContext->win32.hUser32DLL); + ma_dlclose(pContext->win32.hOle32DLL); + ma_dlclose(pContext->win32.hAdvapi32DLL); + + return MA_SUCCESS; +} + +ma_result ma_context_init_backend_apis__win32(ma_context* pContext) +{ +#ifdef MA_WIN32_DESKTOP + // Ole32.dll + pContext->win32.hOle32DLL = ma_dlopen("ole32.dll"); + if (pContext->win32.hOle32DLL == NULL) { + return MA_FAILED_TO_INIT_BACKEND; + } + + pContext->win32.CoInitializeEx = (ma_proc)ma_dlsym(pContext->win32.hOle32DLL, "CoInitializeEx"); + pContext->win32.CoUninitialize = (ma_proc)ma_dlsym(pContext->win32.hOle32DLL, "CoUninitialize"); + pContext->win32.CoCreateInstance = (ma_proc)ma_dlsym(pContext->win32.hOle32DLL, "CoCreateInstance"); + pContext->win32.CoTaskMemFree = (ma_proc)ma_dlsym(pContext->win32.hOle32DLL, "CoTaskMemFree"); + pContext->win32.PropVariantClear = (ma_proc)ma_dlsym(pContext->win32.hOle32DLL, "PropVariantClear"); + pContext->win32.StringFromGUID2 = (ma_proc)ma_dlsym(pContext->win32.hOle32DLL, "StringFromGUID2"); + + + // User32.dll + pContext->win32.hUser32DLL = ma_dlopen("user32.dll"); + if (pContext->win32.hUser32DLL == NULL) { + return MA_FAILED_TO_INIT_BACKEND; + } + + pContext->win32.GetForegroundWindow = (ma_proc)ma_dlsym(pContext->win32.hUser32DLL, "GetForegroundWindow"); + pContext->win32.GetDesktopWindow = (ma_proc)ma_dlsym(pContext->win32.hUser32DLL, "GetDesktopWindow"); + + + // Advapi32.dll + pContext->win32.hAdvapi32DLL = ma_dlopen("advapi32.dll"); + if (pContext->win32.hAdvapi32DLL == NULL) { + return MA_FAILED_TO_INIT_BACKEND; + } + + pContext->win32.RegOpenKeyExA = (ma_proc)ma_dlsym(pContext->win32.hAdvapi32DLL, "RegOpenKeyExA"); + pContext->win32.RegCloseKey = (ma_proc)ma_dlsym(pContext->win32.hAdvapi32DLL, "RegCloseKey"); + pContext->win32.RegQueryValueExA = (ma_proc)ma_dlsym(pContext->win32.hAdvapi32DLL, "RegQueryValueExA"); +#endif + + ma_CoInitializeEx(pContext, NULL, MA_COINIT_VALUE); + return MA_SUCCESS; +} +#else +ma_result ma_context_uninit_backend_apis__nix(ma_context* pContext) +{ +#if defined(MA_USE_RUNTIME_LINKING_FOR_PTHREAD) && !defined(MA_NO_RUNTIME_LINKING) + ma_dlclose(pContext->posix.pthreadSO); +#else + (void)pContext; +#endif + + return MA_SUCCESS; +} + +ma_result ma_context_init_backend_apis__nix(ma_context* pContext) +{ + // pthread +#if defined(MA_USE_RUNTIME_LINKING_FOR_PTHREAD) && !defined(MA_NO_RUNTIME_LINKING) + const char* libpthreadFileNames[] = { + "libpthread.so", + "libpthread.so.0", + "libpthread.dylib" + }; + + for (size_t i = 0; i < sizeof(libpthreadFileNames) / sizeof(libpthreadFileNames[0]); ++i) { + pContext->posix.pthreadSO = ma_dlopen(libpthreadFileNames[i]); + if (pContext->posix.pthreadSO != NULL) { + break; + } + } + + if (pContext->posix.pthreadSO == NULL) { + return MA_FAILED_TO_INIT_BACKEND; + } + + pContext->posix.pthread_create = (ma_proc)ma_dlsym(pContext->posix.pthreadSO, "pthread_create"); + pContext->posix.pthread_join = (ma_proc)ma_dlsym(pContext->posix.pthreadSO, "pthread_join"); + pContext->posix.pthread_mutex_init = (ma_proc)ma_dlsym(pContext->posix.pthreadSO, "pthread_mutex_init"); + pContext->posix.pthread_mutex_destroy = (ma_proc)ma_dlsym(pContext->posix.pthreadSO, "pthread_mutex_destroy"); + pContext->posix.pthread_mutex_lock = (ma_proc)ma_dlsym(pContext->posix.pthreadSO, "pthread_mutex_lock"); + pContext->posix.pthread_mutex_unlock = (ma_proc)ma_dlsym(pContext->posix.pthreadSO, "pthread_mutex_unlock"); + pContext->posix.pthread_cond_init = (ma_proc)ma_dlsym(pContext->posix.pthreadSO, "pthread_cond_init"); + pContext->posix.pthread_cond_destroy = (ma_proc)ma_dlsym(pContext->posix.pthreadSO, "pthread_cond_destroy"); + pContext->posix.pthread_cond_wait = (ma_proc)ma_dlsym(pContext->posix.pthreadSO, "pthread_cond_wait"); + pContext->posix.pthread_cond_signal = (ma_proc)ma_dlsym(pContext->posix.pthreadSO, "pthread_cond_signal"); + pContext->posix.pthread_attr_init = (ma_proc)ma_dlsym(pContext->posix.pthreadSO, "pthread_attr_init"); + pContext->posix.pthread_attr_destroy = (ma_proc)ma_dlsym(pContext->posix.pthreadSO, "pthread_attr_destroy"); + pContext->posix.pthread_attr_setschedpolicy = (ma_proc)ma_dlsym(pContext->posix.pthreadSO, "pthread_attr_setschedpolicy"); + pContext->posix.pthread_attr_getschedparam = (ma_proc)ma_dlsym(pContext->posix.pthreadSO, "pthread_attr_getschedparam"); + pContext->posix.pthread_attr_setschedparam = (ma_proc)ma_dlsym(pContext->posix.pthreadSO, "pthread_attr_setschedparam"); +#else + pContext->posix.pthread_create = (ma_proc)pthread_create; + pContext->posix.pthread_join = (ma_proc)pthread_join; + pContext->posix.pthread_mutex_init = (ma_proc)pthread_mutex_init; + pContext->posix.pthread_mutex_destroy = (ma_proc)pthread_mutex_destroy; + pContext->posix.pthread_mutex_lock = (ma_proc)pthread_mutex_lock; + pContext->posix.pthread_mutex_unlock = (ma_proc)pthread_mutex_unlock; + pContext->posix.pthread_cond_init = (ma_proc)pthread_cond_init; + pContext->posix.pthread_cond_destroy = (ma_proc)pthread_cond_destroy; + pContext->posix.pthread_cond_wait = (ma_proc)pthread_cond_wait; + pContext->posix.pthread_cond_signal = (ma_proc)pthread_cond_signal; + pContext->posix.pthread_attr_init = (ma_proc)pthread_attr_init; + pContext->posix.pthread_attr_destroy = (ma_proc)pthread_attr_destroy; +#if !defined(__EMSCRIPTEN__) + pContext->posix.pthread_attr_setschedpolicy = (ma_proc)pthread_attr_setschedpolicy; + pContext->posix.pthread_attr_getschedparam = (ma_proc)pthread_attr_getschedparam; + pContext->posix.pthread_attr_setschedparam = (ma_proc)pthread_attr_setschedparam; +#endif +#endif + + return MA_SUCCESS; +} +#endif + +ma_result ma_context_init_backend_apis(ma_context* pContext) +{ + ma_result result; +#ifdef MA_WIN32 + result = ma_context_init_backend_apis__win32(pContext); +#else + result = ma_context_init_backend_apis__nix(pContext); +#endif + + return result; +} + +ma_result ma_context_uninit_backend_apis(ma_context* pContext) +{ + ma_result result; +#ifdef MA_WIN32 + result = ma_context_uninit_backend_apis__win32(pContext); +#else + result = ma_context_uninit_backend_apis__nix(pContext); +#endif + + return result; +} + + +ma_bool32 ma_context_is_backend_asynchronous(ma_context* pContext) +{ + return pContext->isBackendAsynchronous; +} + +ma_result ma_context_init(const ma_backend backends[], ma_uint32 backendCount, const ma_context_config* pConfig, ma_context* pContext) +{ + if (pContext == NULL) { + return MA_INVALID_ARGS; + } + + ma_zero_object(pContext); + + // Always make sure the config is set first to ensure properties are available as soon as possible. + if (pConfig != NULL) { + pContext->config = *pConfig; + } else { + pContext->config = ma_context_config_init(); + } + + // Backend APIs need to be initialized first. This is where external libraries will be loaded and linked. + ma_result result = ma_context_init_backend_apis(pContext); + if (result != MA_SUCCESS) { + return result; + } + + ma_backend defaultBackends[ma_backend_null+1]; + for (int i = 0; i <= ma_backend_null; ++i) { + defaultBackends[i] = (ma_backend)i; + } + + ma_backend* pBackendsToIterate = (ma_backend*)backends; + ma_uint32 backendsToIterateCount = backendCount; + if (pBackendsToIterate == NULL) { + pBackendsToIterate = (ma_backend*)defaultBackends; + backendsToIterateCount = ma_countof(defaultBackends); + } + + ma_assert(pBackendsToIterate != NULL); + + for (ma_uint32 iBackend = 0; iBackend < backendsToIterateCount; ++iBackend) { + ma_backend backend = pBackendsToIterate[iBackend]; + + result = MA_NO_BACKEND; + switch (backend) { + #ifdef MA_HAS_WASAPI + case ma_backend_wasapi: + { + result = ma_context_init__wasapi(pContext); + } break; + #endif + #ifdef MA_HAS_DSOUND + case ma_backend_dsound: + { + result = ma_context_init__dsound(pContext); + } break; + #endif + #ifdef MA_HAS_WINMM + case ma_backend_winmm: + { + result = ma_context_init__winmm(pContext); + } break; + #endif + #ifdef MA_HAS_ALSA + case ma_backend_alsa: + { + result = ma_context_init__alsa(pContext); + } break; + #endif + #ifdef MA_HAS_PULSEAUDIO + case ma_backend_pulseaudio: + { + result = ma_context_init__pulse(pContext); + } break; + #endif + #ifdef MA_HAS_JACK + case ma_backend_jack: + { + result = ma_context_init__jack(pContext); + } break; + #endif + #ifdef MA_HAS_COREAUDIO + case ma_backend_coreaudio: + { + result = ma_context_init__coreaudio(pContext); + } break; + #endif + #ifdef MA_HAS_SNDIO + case ma_backend_sndio: + { + result = ma_context_init__sndio(pContext); + } break; + #endif + #ifdef MA_HAS_AUDIO4 + case ma_backend_audio4: + { + result = ma_context_init__audio4(pContext); + } break; + #endif + #ifdef MA_HAS_OSS + case ma_backend_oss: + { + result = ma_context_init__oss(pContext); + } break; + #endif + #ifdef MA_HAS_AAUDIO + case ma_backend_aaudio: + { + result = ma_context_init__aaudio(pContext); + } break; + #endif + #ifdef MA_HAS_OPENSL + case ma_backend_opensl: + { + result = ma_context_init__opensl(pContext); + } break; + #endif + #ifdef MA_HAS_WEBAUDIO + case ma_backend_webaudio: + { + result = ma_context_init__webaudio(pContext); + } break; + #endif + #ifdef MA_HAS_NULL + case ma_backend_null: + { + result = ma_context_init__null(pContext); + } break; + #endif + + default: break; + } + + // If this iteration was successful, return. + if (result == MA_SUCCESS) { + result = ma_mutex_init(pContext, &pContext->deviceEnumLock); + if (result != MA_SUCCESS) { + ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_WARNING, "Failed to initialize mutex for device enumeration. ma_context_get_devices() is not thread safe.", MA_FAILED_TO_CREATE_MUTEX); + } + result = ma_mutex_init(pContext, &pContext->deviceInfoLock); + if (result != MA_SUCCESS) { + ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_WARNING, "Failed to initialize mutex for device info retrieval. ma_context_get_device_info() is not thread safe.", MA_FAILED_TO_CREATE_MUTEX); + } + +#ifdef MA_DEBUG_OUTPUT + printf("[miniaudio] Endian: %s\n", ma_is_little_endian() ? "LE" : "BE"); + printf("[miniaudio] SSE2: %s\n", ma_has_sse2() ? "YES" : "NO"); + printf("[miniaudio] AVX2: %s\n", ma_has_avx2() ? "YES" : "NO"); + printf("[miniaudio] AVX512F: %s\n", ma_has_avx512f() ? "YES" : "NO"); + printf("[miniaudio] NEON: %s\n", ma_has_neon() ? "YES" : "NO"); +#endif + + pContext->backend = backend; + return result; + } + } + + // If we get here it means an error occurred. + ma_zero_object(pContext); // Safety. + return MA_NO_BACKEND; +} + +ma_result ma_context_uninit(ma_context* pContext) +{ + if (pContext == NULL) { + return MA_INVALID_ARGS; + } + + pContext->onUninit(pContext); + + ma_context_uninit_backend_apis(pContext); + ma_mutex_uninit(&pContext->deviceEnumLock); + ma_mutex_uninit(&pContext->deviceInfoLock); + ma_free(pContext->pDeviceInfos); + + return MA_SUCCESS; +} + + +ma_result ma_context_enumerate_devices(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData) +{ + if (pContext == NULL || pContext->onEnumDevices == NULL || callback == NULL) { + return MA_INVALID_ARGS; + } + + ma_result result; + ma_mutex_lock(&pContext->deviceEnumLock); + { + result = pContext->onEnumDevices(pContext, callback, pUserData); + } + ma_mutex_unlock(&pContext->deviceEnumLock); + + return result; +} + + +ma_bool32 ma_context_get_devices__enum_callback(ma_context* pContext, ma_device_type deviceType, const ma_device_info* pInfo, void* pUserData) +{ + (void)pUserData; + + // We need to insert the device info into our main internal buffer. Where it goes depends on the device type. If it's a capture device + // it's just appended to the end. If it's a playback device it's inserted just before the first capture device. + + // First make sure we have room. Since the number of devices we add to the list is usually relatively small I've decided to use a + // simple fixed size increment for buffer expansion. + const ma_uint32 bufferExpansionCount = 2; + const ma_uint32 totalDeviceInfoCount = pContext->playbackDeviceInfoCount + pContext->captureDeviceInfoCount; + + if (pContext->deviceInfoCapacity >= totalDeviceInfoCount) { + ma_uint32 newCapacity = totalDeviceInfoCount + bufferExpansionCount; + ma_device_info* pNewInfos = (ma_device_info*)ma_realloc(pContext->pDeviceInfos, sizeof(*pContext->pDeviceInfos)*newCapacity); + if (pNewInfos == NULL) { + return MA_FALSE; // Out of memory. + } + + pContext->pDeviceInfos = pNewInfos; + pContext->deviceInfoCapacity = newCapacity; + } + + if (deviceType == ma_device_type_playback) { + // Playback. Insert just before the first capture device. + + // The first thing to do is move all of the capture devices down a slot. + ma_uint32 iFirstCaptureDevice = pContext->playbackDeviceInfoCount; + for (size_t iCaptureDevice = totalDeviceInfoCount; iCaptureDevice > iFirstCaptureDevice; --iCaptureDevice) { + pContext->pDeviceInfos[iCaptureDevice] = pContext->pDeviceInfos[iCaptureDevice-1]; + } + + // Now just insert where the first capture device was before moving it down a slot. + pContext->pDeviceInfos[iFirstCaptureDevice] = *pInfo; + pContext->playbackDeviceInfoCount += 1; + } else { + // Capture. Insert at the end. + pContext->pDeviceInfos[totalDeviceInfoCount] = *pInfo; + pContext->captureDeviceInfoCount += 1; + } + + return MA_TRUE; +} + +ma_result ma_context_get_devices(ma_context* pContext, ma_device_info** ppPlaybackDeviceInfos, ma_uint32* pPlaybackDeviceCount, ma_device_info** ppCaptureDeviceInfos, ma_uint32* pCaptureDeviceCount) +{ + // Safety. + if (ppPlaybackDeviceInfos != NULL) *ppPlaybackDeviceInfos = NULL; + if (pPlaybackDeviceCount != NULL) *pPlaybackDeviceCount = 0; + if (ppCaptureDeviceInfos != NULL) *ppCaptureDeviceInfos = NULL; + if (pCaptureDeviceCount != NULL) *pCaptureDeviceCount = 0; + + if (pContext == NULL || pContext->onEnumDevices == NULL) { + return MA_INVALID_ARGS; + } + + // Note that we don't use ma_context_enumerate_devices() here because we want to do locking at a higher level. + ma_result result; + ma_mutex_lock(&pContext->deviceEnumLock); + { + // Reset everything first. + pContext->playbackDeviceInfoCount = 0; + pContext->captureDeviceInfoCount = 0; + + // Now enumerate over available devices. + result = pContext->onEnumDevices(pContext, ma_context_get_devices__enum_callback, NULL); + if (result == MA_SUCCESS) { + // Playback devices. + if (ppPlaybackDeviceInfos != NULL) { + *ppPlaybackDeviceInfos = pContext->pDeviceInfos; + } + if (pPlaybackDeviceCount != NULL) { + *pPlaybackDeviceCount = pContext->playbackDeviceInfoCount; + } + + // Capture devices. + if (ppCaptureDeviceInfos != NULL) { + *ppCaptureDeviceInfos = pContext->pDeviceInfos + pContext->playbackDeviceInfoCount; // Capture devices come after playback devices. + } + if (pCaptureDeviceCount != NULL) { + *pCaptureDeviceCount = pContext->captureDeviceInfoCount; + } + } + } + ma_mutex_unlock(&pContext->deviceEnumLock); + + return result; +} + +ma_result ma_context_get_device_info(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_share_mode shareMode, ma_device_info* pDeviceInfo) +{ + // NOTE: Do not clear pDeviceInfo on entry. The reason is the pDeviceID may actually point to pDeviceInfo->id which will break things. + if (pContext == NULL || pDeviceInfo == NULL) { + return MA_INVALID_ARGS; + } + + ma_device_info deviceInfo; + ma_zero_object(&deviceInfo); + + // Help the backend out by copying over the device ID if we have one. + if (pDeviceID != NULL) { + ma_copy_memory(&deviceInfo.id, pDeviceID, sizeof(*pDeviceID)); + } + + // The backend may have an optimized device info retrieval function. If so, try that first. + if (pContext->onGetDeviceInfo != NULL) { + ma_result result; + ma_mutex_lock(&pContext->deviceInfoLock); + { + result = pContext->onGetDeviceInfo(pContext, deviceType, pDeviceID, shareMode, &deviceInfo); + } + ma_mutex_unlock(&pContext->deviceInfoLock); + + // Clamp ranges. + deviceInfo.minChannels = ma_max(deviceInfo.minChannels, MA_MIN_CHANNELS); + deviceInfo.maxChannels = ma_min(deviceInfo.maxChannels, MA_MAX_CHANNELS); + deviceInfo.minSampleRate = ma_max(deviceInfo.minSampleRate, MA_MIN_SAMPLE_RATE); + deviceInfo.maxSampleRate = ma_min(deviceInfo.maxSampleRate, MA_MAX_SAMPLE_RATE); + + *pDeviceInfo = deviceInfo; + return result; + } + + // Getting here means onGetDeviceInfo has not been set. + return MA_ERROR; +} + + +ma_result ma_device_init(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice) +{ + if (pContext == NULL) { + return ma_device_init_ex(NULL, 0, NULL, pConfig, pDevice); + } + if (pDevice == NULL) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "ma_device_init() called with invalid arguments (pDevice == NULL).", MA_INVALID_ARGS); + } + if (pConfig == NULL) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "ma_device_init() called with invalid arguments (pConfig == NULL).", MA_INVALID_ARGS); + } + + /* We need to make a copy of the config so we can set default values if they were left unset in the input config. */ + ma_device_config config = *pConfig; + + /* Basic config validation. */ + if (config.deviceType != ma_device_type_playback && config.deviceType != ma_device_type_capture && config.deviceType != ma_device_type_duplex) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "ma_device_init() called with an invalid config. Device type is invalid. Make sure the device type has been set in the config.", MA_INVALID_DEVICE_CONFIG); + } + + if (config.deviceType == ma_device_type_capture || config.deviceType == ma_device_type_duplex) { + if (config.capture.channels > MA_MAX_CHANNELS) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "ma_device_init() called with an invalid config. Capture channel count cannot exceed 32.", MA_INVALID_DEVICE_CONFIG); + } + if (!ma__is_channel_map_valid(config.capture.channelMap, config.capture.channels)) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "ma_device_init() called with invalid config. Capture channel map is invalid.", MA_INVALID_DEVICE_CONFIG); + } + } + + if (config.deviceType == ma_device_type_playback || config.deviceType == ma_device_type_duplex) { + if (config.playback.channels > MA_MAX_CHANNELS) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "ma_device_init() called with an invalid config. Playback channel count cannot exceed 32.", MA_INVALID_DEVICE_CONFIG); + } + if (!ma__is_channel_map_valid(config.playback.channelMap, config.playback.channels)) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "ma_device_init() called with invalid config. Playback channel map is invalid.", MA_INVALID_DEVICE_CONFIG); + } + } + + + ma_zero_object(pDevice); + pDevice->pContext = pContext; + + // Set the user data and log callback ASAP to ensure it is available for the entire initialization process. + pDevice->pUserData = config.pUserData; + pDevice->onData = config.dataCallback; + pDevice->onStop = config.stopCallback; + + if (((ma_uintptr)pDevice % sizeof(pDevice)) != 0) { + if (pContext->config.logCallback) { + pContext->config.logCallback(pContext, pDevice, MA_LOG_LEVEL_WARNING, "WARNING: ma_device_init() called for a device that is not properly aligned. Thread safety is not supported."); + } + } + + // When passing in 0 for the format/channels/rate/chmap it means the device will be using whatever is chosen by the backend. If everything is set + // to defaults it means the format conversion pipeline will run on a fast path where data transfer is just passed straight through to the backend. + if (config.sampleRate == 0) { + config.sampleRate = MA_DEFAULT_SAMPLE_RATE; + pDevice->usingDefaultSampleRate = MA_TRUE; + } + + if (config.capture.format == ma_format_unknown) { + config.capture.format = MA_DEFAULT_FORMAT; + pDevice->capture.usingDefaultFormat = MA_TRUE; + } + if (config.capture.channels == 0) { + config.capture.channels = MA_DEFAULT_CHANNELS; + pDevice->capture.usingDefaultChannels = MA_TRUE; + } + if (config.capture.channelMap[0] == MA_CHANNEL_NONE) { + pDevice->capture.usingDefaultChannelMap = MA_TRUE; + } + + if (config.playback.format == ma_format_unknown) { + config.playback.format = MA_DEFAULT_FORMAT; + pDevice->playback.usingDefaultFormat = MA_TRUE; + } + if (config.playback.channels == 0) { + config.playback.channels = MA_DEFAULT_CHANNELS; + pDevice->playback.usingDefaultChannels = MA_TRUE; + } + if (config.playback.channelMap[0] == MA_CHANNEL_NONE) { + pDevice->playback.usingDefaultChannelMap = MA_TRUE; + } + + + // Default buffer size. + if (config.bufferSizeInMilliseconds == 0 && config.bufferSizeInFrames == 0) { + config.bufferSizeInMilliseconds = (config.performanceProfile == ma_performance_profile_low_latency) ? MA_BASE_BUFFER_SIZE_IN_MILLISECONDS_LOW_LATENCY : MA_BASE_BUFFER_SIZE_IN_MILLISECONDS_CONSERVATIVE; + pDevice->usingDefaultBufferSize = MA_TRUE; + } + + // Default periods. + if (config.periods == 0) { + config.periods = MA_DEFAULT_PERIODS; + pDevice->usingDefaultPeriods = MA_TRUE; + } + + /* + Must have at least 3 periods for full-duplex mode. The idea is that the playback and capture positions hang out in the middle period, with the surrounding + periods acting as a buffer in case the capture and playback devices get's slightly out of sync. + */ + if (config.deviceType == ma_device_type_duplex && config.periods < 3) { + config.periods = 3; + } + + + pDevice->type = config.deviceType; + pDevice->sampleRate = config.sampleRate; + + pDevice->capture.shareMode = config.capture.shareMode; + pDevice->capture.format = config.capture.format; + pDevice->capture.channels = config.capture.channels; + ma_channel_map_copy(pDevice->capture.channelMap, config.capture.channelMap, config.capture.channels); + + pDevice->playback.shareMode = config.playback.shareMode; + pDevice->playback.format = config.playback.format; + pDevice->playback.channels = config.playback.channels; + ma_channel_map_copy(pDevice->playback.channelMap, config.playback.channelMap, config.playback.channels); + + + // The internal format, channel count and sample rate can be modified by the backend. + pDevice->capture.internalFormat = pDevice->capture.format; + pDevice->capture.internalChannels = pDevice->capture.channels; + pDevice->capture.internalSampleRate = pDevice->sampleRate; + ma_channel_map_copy(pDevice->capture.internalChannelMap, pDevice->capture.channelMap, pDevice->capture.channels); + + pDevice->playback.internalFormat = pDevice->playback.format; + pDevice->playback.internalChannels = pDevice->playback.channels; + pDevice->playback.internalSampleRate = pDevice->sampleRate; + ma_channel_map_copy(pDevice->playback.internalChannelMap, pDevice->playback.channelMap, pDevice->playback.channels); + + + if (ma_mutex_init(pContext, &pDevice->lock) != MA_SUCCESS) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "Failed to create mutex.", MA_FAILED_TO_CREATE_MUTEX); + } + + // When the device is started, the worker thread is the one that does the actual startup of the backend device. We + // use a semaphore to wait for the background thread to finish the work. The same applies for stopping the device. + // + // Each of these semaphores is released internally by the worker thread when the work is completed. The start + // semaphore is also used to wake up the worker thread. + if (ma_event_init(pContext, &pDevice->wakeupEvent) != MA_SUCCESS) { + ma_mutex_uninit(&pDevice->lock); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "Failed to create worker thread wakeup event.", MA_FAILED_TO_CREATE_EVENT); + } + if (ma_event_init(pContext, &pDevice->startEvent) != MA_SUCCESS) { + ma_event_uninit(&pDevice->wakeupEvent); + ma_mutex_uninit(&pDevice->lock); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "Failed to create worker thread start event.", MA_FAILED_TO_CREATE_EVENT); + } + if (ma_event_init(pContext, &pDevice->stopEvent) != MA_SUCCESS) { + ma_event_uninit(&pDevice->startEvent); + ma_event_uninit(&pDevice->wakeupEvent); + ma_mutex_uninit(&pDevice->lock); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "Failed to create worker thread stop event.", MA_FAILED_TO_CREATE_EVENT); + } + + + ma_result result = pContext->onDeviceInit(pContext, &config, pDevice); + if (result != MA_SUCCESS) { + return MA_NO_BACKEND; // The error message will have been posted with ma_post_error() by the source of the error so don't bother calling it here. + } + + ma_device__post_init_setup(pDevice, pConfig->deviceType); + + + // If the backend did not fill out a name for the device, try a generic method. + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + if (pDevice->capture.name[0] == '\0') { + if (ma_context__try_get_device_name_by_id(pContext, ma_device_type_capture, config.capture.pDeviceID, pDevice->capture.name, sizeof(pDevice->capture.name)) != MA_SUCCESS) { + ma_strncpy_s(pDevice->capture.name, sizeof(pDevice->capture.name), (config.capture.pDeviceID == NULL) ? MA_DEFAULT_CAPTURE_DEVICE_NAME : "Capture Device", (size_t)-1); + } + } + } + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + if (pDevice->playback.name[0] == '\0') { + if (ma_context__try_get_device_name_by_id(pContext, ma_device_type_playback, config.playback.pDeviceID, pDevice->playback.name, sizeof(pDevice->playback.name)) != MA_SUCCESS) { + ma_strncpy_s(pDevice->playback.name, sizeof(pDevice->playback.name), (config.playback.pDeviceID == NULL) ? MA_DEFAULT_PLAYBACK_DEVICE_NAME : "Playback Device", (size_t)-1); + } + } + } + + + // Some backends don't require the worker thread. + if (!ma_context_is_backend_asynchronous(pContext)) { + // The worker thread. + if (ma_thread_create(pContext, &pDevice->thread, ma_worker_thread, pDevice) != MA_SUCCESS) { + ma_device_uninit(pDevice); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "Failed to create worker thread.", MA_FAILED_TO_CREATE_THREAD); + } + + // Wait for the worker thread to put the device into it's stopped state for real. + ma_event_wait(&pDevice->stopEvent); + } else { + ma_device__set_state(pDevice, MA_STATE_STOPPED); + } + + +#ifdef MA_DEBUG_OUTPUT + printf("[%s]\n", ma_get_backend_name(pDevice->pContext->backend)); + if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { + printf(" %s (%s)\n", pDevice->capture.name, "Capture"); + printf(" Format: %s -> %s\n", ma_get_format_name(pDevice->capture.format), ma_get_format_name(pDevice->capture.internalFormat)); + printf(" Channels: %d -> %d\n", pDevice->capture.channels, pDevice->capture.internalChannels); + printf(" Sample Rate: %d -> %d\n", pDevice->sampleRate, pDevice->capture.internalSampleRate); + printf(" Buffer Size: %d/%d (%d)\n", pDevice->capture.internalBufferSizeInFrames, pDevice->capture.internalPeriods, (pDevice->capture.internalBufferSizeInFrames / pDevice->capture.internalPeriods)); + printf(" Conversion:\n"); + printf(" Pre Format Conversion: %s\n", pDevice->capture.converter.isPreFormatConversionRequired ? "YES" : "NO"); + printf(" Post Format Conversion: %s\n", pDevice->capture.converter.isPostFormatConversionRequired ? "YES" : "NO"); + printf(" Channel Routing: %s\n", pDevice->capture.converter.isChannelRoutingRequired ? "YES" : "NO"); + printf(" SRC: %s\n", pDevice->capture.converter.isSRCRequired ? "YES" : "NO"); + printf(" Channel Routing at Start: %s\n", pDevice->capture.converter.isChannelRoutingAtStart ? "YES" : "NO"); + printf(" Passthrough: %s\n", pDevice->capture.converter.isPassthrough ? "YES" : "NO"); + } + if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { + printf(" %s (%s)\n", pDevice->playback.name, "Playback"); + printf(" Format: %s -> %s\n", ma_get_format_name(pDevice->playback.format), ma_get_format_name(pDevice->playback.internalFormat)); + printf(" Channels: %d -> %d\n", pDevice->playback.channels, pDevice->playback.internalChannels); + printf(" Sample Rate: %d -> %d\n", pDevice->sampleRate, pDevice->playback.internalSampleRate); + printf(" Buffer Size: %d/%d (%d)\n", pDevice->playback.internalBufferSizeInFrames, pDevice->playback.internalPeriods, (pDevice->playback.internalBufferSizeInFrames / pDevice->playback.internalPeriods)); + printf(" Conversion:\n"); + printf(" Pre Format Conversion: %s\n", pDevice->playback.converter.isPreFormatConversionRequired ? "YES" : "NO"); + printf(" Post Format Conversion: %s\n", pDevice->playback.converter.isPostFormatConversionRequired ? "YES" : "NO"); + printf(" Channel Routing: %s\n", pDevice->playback.converter.isChannelRoutingRequired ? "YES" : "NO"); + printf(" SRC: %s\n", pDevice->playback.converter.isSRCRequired ? "YES" : "NO"); + printf(" Channel Routing at Start: %s\n", pDevice->playback.converter.isChannelRoutingAtStart ? "YES" : "NO"); + printf(" Passthrough: %s\n", pDevice->playback.converter.isPassthrough ? "YES" : "NO"); + } +#endif + + + ma_assert(ma_device__get_state(pDevice) == MA_STATE_STOPPED); + return MA_SUCCESS; +} + +ma_result ma_device_init_ex(const ma_backend backends[], ma_uint32 backendCount, const ma_context_config* pContextConfig, const ma_device_config* pConfig, ma_device* pDevice) +{ + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + ma_context* pContext = (ma_context*)ma_malloc(sizeof(*pContext)); + if (pContext == NULL) { + return MA_OUT_OF_MEMORY; + } + + ma_backend defaultBackends[ma_backend_null+1]; + for (int i = 0; i <= ma_backend_null; ++i) { + defaultBackends[i] = (ma_backend)i; + } + + ma_backend* pBackendsToIterate = (ma_backend*)backends; + ma_uint32 backendsToIterateCount = backendCount; + if (pBackendsToIterate == NULL) { + pBackendsToIterate = (ma_backend*)defaultBackends; + backendsToIterateCount = ma_countof(defaultBackends); + } + + ma_result result = MA_NO_BACKEND; + + for (ma_uint32 iBackend = 0; iBackend < backendsToIterateCount; ++iBackend) { + result = ma_context_init(&pBackendsToIterate[iBackend], 1, pContextConfig, pContext); + if (result == MA_SUCCESS) { + result = ma_device_init(pContext, pConfig, pDevice); + if (result == MA_SUCCESS) { + break; // Success. + } else { + ma_context_uninit(pContext); // Failure. + } + } + } + + if (result != MA_SUCCESS) { + ma_free(pContext); + return result; + } + + pDevice->isOwnerOfContext = MA_TRUE; + return result; +} + +void ma_device_uninit(ma_device* pDevice) +{ + if (!ma_device__is_initialized(pDevice)) { + return; + } + + // Make sure the device is stopped first. The backends will probably handle this naturally, + // but I like to do it explicitly for my own sanity. + if (ma_device_is_started(pDevice)) { + ma_device_stop(pDevice); + } + + // Putting the device into an uninitialized state will make the worker thread return. + ma_device__set_state(pDevice, MA_STATE_UNINITIALIZED); + + // Wake up the worker thread and wait for it to properly terminate. + if (!ma_context_is_backend_asynchronous(pDevice->pContext)) { + ma_event_signal(&pDevice->wakeupEvent); + ma_thread_wait(&pDevice->thread); + } + + pDevice->pContext->onDeviceUninit(pDevice); + + ma_event_uninit(&pDevice->stopEvent); + ma_event_uninit(&pDevice->startEvent); + ma_event_uninit(&pDevice->wakeupEvent); + ma_mutex_uninit(&pDevice->lock); + + if (pDevice->isOwnerOfContext) { + ma_context_uninit(pDevice->pContext); + ma_free(pDevice->pContext); + } + + ma_zero_object(pDevice); +} + +void ma_device_set_stop_callback(ma_device* pDevice, ma_stop_proc proc) +{ + if (pDevice == NULL) return; + ma_atomic_exchange_ptr(&pDevice->onStop, proc); +} + +ma_result ma_device_start(ma_device* pDevice) +{ + if (pDevice == NULL) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "ma_device_start() called with invalid arguments (pDevice == NULL).", MA_INVALID_ARGS); + } + + if (ma_device__get_state(pDevice) == MA_STATE_UNINITIALIZED) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "ma_device_start() called for an uninitialized device.", MA_DEVICE_NOT_INITIALIZED); + } + + /* + Starting the device doesn't do anything in synchronous mode because in that case it's started automatically with + ma_device_write() and ma_device_read(). It's best to return an error so that the application can be aware that + it's not doing it right. + */ + if (!ma_device__is_async(pDevice)) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "ma_device_start() called in synchronous mode. This should only be used in asynchronous/callback mode.", MA_DEVICE_NOT_INITIALIZED); + } + + ma_result result = MA_ERROR; + ma_mutex_lock(&pDevice->lock); + { + // Starting and stopping are wrapped in a mutex which means we can assert that the device is in a stopped or paused state. + ma_assert(ma_device__get_state(pDevice) == MA_STATE_STOPPED); + + ma_device__set_state(pDevice, MA_STATE_STARTING); + + // Asynchronous backends need to be handled differently. + if (ma_context_is_backend_asynchronous(pDevice->pContext)) { + result = pDevice->pContext->onDeviceStart(pDevice); + if (result == MA_SUCCESS) { + ma_device__set_state(pDevice, MA_STATE_STARTED); + } + } else { + // Synchronous backends are started by signaling an event that's being waited on in the worker thread. We first wake up the + // thread and then wait for the start event. + ma_event_signal(&pDevice->wakeupEvent); + + // Wait for the worker thread to finish starting the device. Note that the worker thread will be the one + // who puts the device into the started state. Don't call ma_device__set_state() here. + ma_event_wait(&pDevice->startEvent); + result = pDevice->workResult; + } + } + ma_mutex_unlock(&pDevice->lock); + + return result; +} + +ma_result ma_device_stop(ma_device* pDevice) +{ + if (pDevice == NULL) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "ma_device_stop() called with invalid arguments (pDevice == NULL).", MA_INVALID_ARGS); + } + + if (ma_device__get_state(pDevice) == MA_STATE_UNINITIALIZED) { + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "ma_device_stop() called for an uninitialized device.", MA_DEVICE_NOT_INITIALIZED); + } + + /* + Stopping is slightly different for synchronous mode. In this case it just tells the driver to stop the internal processing of the device. Also, + stopping in synchronous mode does not require state checking. + */ + if (!ma_device__is_async(pDevice)) { + if (pDevice->pContext->onDeviceStop) { + return pDevice->pContext->onDeviceStop(pDevice); + } + } + + ma_result result = MA_ERROR; + ma_mutex_lock(&pDevice->lock); + { + // Starting and stopping are wrapped in a mutex which means we can assert that the device is in a started or paused state. + ma_assert(ma_device__get_state(pDevice) == MA_STATE_STARTED); + + ma_device__set_state(pDevice, MA_STATE_STOPPING); + + // There's no need to wake up the thread like we do when starting. + + // Asynchronous backends need to be handled differently. + if (ma_context_is_backend_asynchronous(pDevice->pContext)) { + if (pDevice->pContext->onDeviceStop) { + result = pDevice->pContext->onDeviceStop(pDevice); + } else { + result = MA_SUCCESS; + } + + ma_device__set_state(pDevice, MA_STATE_STOPPED); + } else { + // Synchronous backends. + + // We need to wait for the worker thread to become available for work before returning. Note that the worker thread will be + // the one who puts the device into the stopped state. Don't call ma_device__set_state() here. + ma_event_wait(&pDevice->stopEvent); + result = MA_SUCCESS; + } + } + ma_mutex_unlock(&pDevice->lock); + + return result; +} + +ma_bool32 ma_device_is_started(ma_device* pDevice) +{ + if (pDevice == NULL) return MA_FALSE; + return ma_device__get_state(pDevice) == MA_STATE_STARTED; +} + + +ma_context_config ma_context_config_init() +{ + ma_context_config config; + ma_zero_object(&config); + + return config; +} + +ma_device_config ma_device_config_init(ma_device_type deviceType) +{ + ma_device_config config; + ma_zero_object(&config); + config.deviceType = deviceType; + + return config; +} +#endif // MA_NO_DEVICE_IO + + +void ma_get_standard_channel_map_microsoft(ma_uint32 channels, ma_channel channelMap[MA_MAX_CHANNELS]) +{ + // Based off the speaker configurations mentioned here: https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/ksmedia/ns-ksmedia-ksaudio_channel_config + switch (channels) + { + case 1: + { + channelMap[0] = MA_CHANNEL_MONO; + } break; + + case 2: + { + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_RIGHT; + } break; + + case 3: // Not defined, but best guess. + { + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_RIGHT; + channelMap[2] = MA_CHANNEL_FRONT_CENTER; + } break; + + case 4: + { +#ifndef MA_USE_QUAD_MICROSOFT_CHANNEL_MAP + // Surround. Using the Surround profile has the advantage of the 3rd channel (MA_CHANNEL_FRONT_CENTER) mapping nicely + // with higher channel counts. + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_RIGHT; + channelMap[2] = MA_CHANNEL_FRONT_CENTER; + channelMap[3] = MA_CHANNEL_BACK_CENTER; +#else + // Quad. + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_RIGHT; + channelMap[2] = MA_CHANNEL_BACK_LEFT; + channelMap[3] = MA_CHANNEL_BACK_RIGHT; +#endif + } break; + + case 5: // Not defined, but best guess. + { + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_RIGHT; + channelMap[2] = MA_CHANNEL_FRONT_CENTER; + channelMap[3] = MA_CHANNEL_BACK_LEFT; + channelMap[4] = MA_CHANNEL_BACK_RIGHT; + } break; + + case 6: + { + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_RIGHT; + channelMap[2] = MA_CHANNEL_FRONT_CENTER; + channelMap[3] = MA_CHANNEL_LFE; + channelMap[4] = MA_CHANNEL_SIDE_LEFT; + channelMap[5] = MA_CHANNEL_SIDE_RIGHT; + } break; + + case 7: // Not defined, but best guess. + { + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_RIGHT; + channelMap[2] = MA_CHANNEL_FRONT_CENTER; + channelMap[3] = MA_CHANNEL_LFE; + channelMap[4] = MA_CHANNEL_BACK_CENTER; + channelMap[5] = MA_CHANNEL_SIDE_LEFT; + channelMap[6] = MA_CHANNEL_SIDE_RIGHT; + } break; + + case 8: + default: + { + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_RIGHT; + channelMap[2] = MA_CHANNEL_FRONT_CENTER; + channelMap[3] = MA_CHANNEL_LFE; + channelMap[4] = MA_CHANNEL_BACK_LEFT; + channelMap[5] = MA_CHANNEL_BACK_RIGHT; + channelMap[6] = MA_CHANNEL_SIDE_LEFT; + channelMap[7] = MA_CHANNEL_SIDE_RIGHT; + } break; + } + + // Remainder. + if (channels > 8) { + for (ma_uint32 iChannel = 8; iChannel < MA_MAX_CHANNELS; ++iChannel) { + channelMap[iChannel] = (ma_channel)(MA_CHANNEL_AUX_0 + (iChannel-8)); + } + } +} + +void ma_get_standard_channel_map_alsa(ma_uint32 channels, ma_channel channelMap[MA_MAX_CHANNELS]) +{ + switch (channels) + { + case 1: + { + channelMap[0] = MA_CHANNEL_MONO; + } break; + + case 2: + { + channelMap[0] = MA_CHANNEL_LEFT; + channelMap[1] = MA_CHANNEL_RIGHT; + } break; + + case 3: + { + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_RIGHT; + channelMap[2] = MA_CHANNEL_FRONT_CENTER; + } break; + + case 4: + { + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_RIGHT; + channelMap[2] = MA_CHANNEL_BACK_LEFT; + channelMap[3] = MA_CHANNEL_BACK_RIGHT; + } break; + + case 5: + { + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_RIGHT; + channelMap[2] = MA_CHANNEL_BACK_LEFT; + channelMap[3] = MA_CHANNEL_BACK_RIGHT; + channelMap[4] = MA_CHANNEL_FRONT_CENTER; + } break; + + case 6: + { + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_RIGHT; + channelMap[2] = MA_CHANNEL_BACK_LEFT; + channelMap[3] = MA_CHANNEL_BACK_RIGHT; + channelMap[4] = MA_CHANNEL_FRONT_CENTER; + channelMap[5] = MA_CHANNEL_LFE; + } break; + + case 7: + { + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_RIGHT; + channelMap[2] = MA_CHANNEL_BACK_LEFT; + channelMap[3] = MA_CHANNEL_BACK_RIGHT; + channelMap[4] = MA_CHANNEL_FRONT_CENTER; + channelMap[5] = MA_CHANNEL_LFE; + channelMap[6] = MA_CHANNEL_BACK_CENTER; + } break; + + case 8: + default: + { + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_RIGHT; + channelMap[2] = MA_CHANNEL_BACK_LEFT; + channelMap[3] = MA_CHANNEL_BACK_RIGHT; + channelMap[4] = MA_CHANNEL_FRONT_CENTER; + channelMap[5] = MA_CHANNEL_LFE; + channelMap[6] = MA_CHANNEL_SIDE_LEFT; + channelMap[7] = MA_CHANNEL_SIDE_RIGHT; + } break; + } + + // Remainder. + if (channels > 8) { + for (ma_uint32 iChannel = 8; iChannel < MA_MAX_CHANNELS; ++iChannel) { + channelMap[iChannel] = (ma_channel)(MA_CHANNEL_AUX_0 + (iChannel-8)); + } + } +} + +void ma_get_standard_channel_map_rfc3551(ma_uint32 channels, ma_channel channelMap[MA_MAX_CHANNELS]) +{ + switch (channels) + { + case 1: + { + channelMap[0] = MA_CHANNEL_MONO; + } break; + + case 2: + { + channelMap[0] = MA_CHANNEL_LEFT; + channelMap[1] = MA_CHANNEL_RIGHT; + } break; + + case 3: + { + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_RIGHT; + channelMap[2] = MA_CHANNEL_FRONT_CENTER; + } break; + + case 4: + { + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_CENTER; + channelMap[2] = MA_CHANNEL_FRONT_RIGHT; + channelMap[3] = MA_CHANNEL_BACK_CENTER; + } break; + + case 5: + { + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_RIGHT; + channelMap[2] = MA_CHANNEL_FRONT_CENTER; + channelMap[3] = MA_CHANNEL_BACK_LEFT; + channelMap[4] = MA_CHANNEL_BACK_RIGHT; + } break; + + case 6: + { + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_SIDE_LEFT; + channelMap[2] = MA_CHANNEL_FRONT_CENTER; + channelMap[3] = MA_CHANNEL_FRONT_RIGHT; + channelMap[4] = MA_CHANNEL_SIDE_RIGHT; + channelMap[5] = MA_CHANNEL_BACK_CENTER; + } break; + } + + // Remainder. + if (channels > 8) { + for (ma_uint32 iChannel = 6; iChannel < MA_MAX_CHANNELS; ++iChannel) { + channelMap[iChannel] = (ma_channel)(MA_CHANNEL_AUX_0 + (iChannel-6)); + } + } +} + +void ma_get_standard_channel_map_flac(ma_uint32 channels, ma_channel channelMap[MA_MAX_CHANNELS]) +{ + switch (channels) + { + case 1: + { + channelMap[0] = MA_CHANNEL_MONO; + } break; + + case 2: + { + channelMap[0] = MA_CHANNEL_LEFT; + channelMap[1] = MA_CHANNEL_RIGHT; + } break; + + case 3: + { + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_RIGHT; + channelMap[2] = MA_CHANNEL_FRONT_CENTER; + } break; + + case 4: + { + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_RIGHT; + channelMap[2] = MA_CHANNEL_BACK_LEFT; + channelMap[3] = MA_CHANNEL_BACK_RIGHT; + } break; + + case 5: + { + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_RIGHT; + channelMap[2] = MA_CHANNEL_FRONT_CENTER; + channelMap[3] = MA_CHANNEL_BACK_LEFT; + channelMap[4] = MA_CHANNEL_BACK_RIGHT; + } break; + + case 6: + { + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_RIGHT; + channelMap[2] = MA_CHANNEL_FRONT_CENTER; + channelMap[3] = MA_CHANNEL_LFE; + channelMap[4] = MA_CHANNEL_BACK_LEFT; + channelMap[5] = MA_CHANNEL_BACK_RIGHT; + } break; + + case 7: + { + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_RIGHT; + channelMap[2] = MA_CHANNEL_FRONT_CENTER; + channelMap[3] = MA_CHANNEL_LFE; + channelMap[4] = MA_CHANNEL_BACK_CENTER; + channelMap[5] = MA_CHANNEL_SIDE_LEFT; + channelMap[6] = MA_CHANNEL_SIDE_RIGHT; + } break; + + case 8: + default: + { + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_RIGHT; + channelMap[2] = MA_CHANNEL_FRONT_CENTER; + channelMap[3] = MA_CHANNEL_LFE; + channelMap[4] = MA_CHANNEL_BACK_LEFT; + channelMap[5] = MA_CHANNEL_BACK_RIGHT; + channelMap[6] = MA_CHANNEL_SIDE_LEFT; + channelMap[7] = MA_CHANNEL_SIDE_RIGHT; + } break; + } + + // Remainder. + if (channels > 8) { + for (ma_uint32 iChannel = 8; iChannel < MA_MAX_CHANNELS; ++iChannel) { + channelMap[iChannel] = (ma_channel)(MA_CHANNEL_AUX_0 + (iChannel-8)); + } + } +} + +void ma_get_standard_channel_map_vorbis(ma_uint32 channels, ma_channel channelMap[MA_MAX_CHANNELS]) +{ + // In Vorbis' type 0 channel mapping, the first two channels are not always the standard left/right - it + // will have the center speaker where the right usually goes. Why?! + switch (channels) + { + case 1: + { + channelMap[0] = MA_CHANNEL_MONO; + } break; + + case 2: + { + channelMap[0] = MA_CHANNEL_LEFT; + channelMap[1] = MA_CHANNEL_RIGHT; + } break; + + case 3: + { + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_CENTER; + channelMap[2] = MA_CHANNEL_FRONT_RIGHT; + } break; + + case 4: + { + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_RIGHT; + channelMap[2] = MA_CHANNEL_BACK_LEFT; + channelMap[3] = MA_CHANNEL_BACK_RIGHT; + } break; + + case 5: + { + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_CENTER; + channelMap[2] = MA_CHANNEL_FRONT_RIGHT; + channelMap[3] = MA_CHANNEL_BACK_LEFT; + channelMap[4] = MA_CHANNEL_BACK_RIGHT; + } break; + + case 6: + { + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_CENTER; + channelMap[2] = MA_CHANNEL_FRONT_RIGHT; + channelMap[3] = MA_CHANNEL_BACK_LEFT; + channelMap[4] = MA_CHANNEL_BACK_RIGHT; + channelMap[5] = MA_CHANNEL_LFE; + } break; + + case 7: + { + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_CENTER; + channelMap[2] = MA_CHANNEL_FRONT_RIGHT; + channelMap[3] = MA_CHANNEL_SIDE_LEFT; + channelMap[4] = MA_CHANNEL_SIDE_RIGHT; + channelMap[5] = MA_CHANNEL_BACK_CENTER; + channelMap[6] = MA_CHANNEL_LFE; + } break; + + case 8: + default: + { + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_CENTER; + channelMap[2] = MA_CHANNEL_FRONT_RIGHT; + channelMap[3] = MA_CHANNEL_SIDE_LEFT; + channelMap[4] = MA_CHANNEL_SIDE_RIGHT; + channelMap[5] = MA_CHANNEL_BACK_LEFT; + channelMap[6] = MA_CHANNEL_BACK_RIGHT; + channelMap[7] = MA_CHANNEL_LFE; + } break; + } + + // Remainder. + if (channels > 8) { + for (ma_uint32 iChannel = 8; iChannel < MA_MAX_CHANNELS; ++iChannel) { + channelMap[iChannel] = (ma_channel)(MA_CHANNEL_AUX_0 + (iChannel-8)); + } + } +} + +void ma_get_standard_channel_map_sound4(ma_uint32 channels, ma_channel channelMap[MA_MAX_CHANNELS]) +{ + switch (channels) + { + case 1: + { + channelMap[0] = MA_CHANNEL_MONO; + } break; + + case 2: + { + channelMap[0] = MA_CHANNEL_LEFT; + channelMap[1] = MA_CHANNEL_RIGHT; + } break; + + case 3: + { + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_RIGHT; + channelMap[2] = MA_CHANNEL_BACK_CENTER; + } break; + + case 4: + { + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_RIGHT; + channelMap[2] = MA_CHANNEL_BACK_LEFT; + channelMap[3] = MA_CHANNEL_BACK_RIGHT; + } break; + + case 5: + { + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_RIGHT; + channelMap[2] = MA_CHANNEL_BACK_LEFT; + channelMap[3] = MA_CHANNEL_BACK_RIGHT; + channelMap[4] = MA_CHANNEL_FRONT_CENTER; + } break; + + case 6: + { + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_RIGHT; + channelMap[2] = MA_CHANNEL_BACK_LEFT; + channelMap[3] = MA_CHANNEL_BACK_RIGHT; + channelMap[4] = MA_CHANNEL_FRONT_CENTER; + channelMap[5] = MA_CHANNEL_LFE; + } break; + + case 7: + { + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_RIGHT; + channelMap[2] = MA_CHANNEL_BACK_LEFT; + channelMap[3] = MA_CHANNEL_BACK_RIGHT; + channelMap[4] = MA_CHANNEL_FRONT_CENTER; + channelMap[5] = MA_CHANNEL_BACK_CENTER; + channelMap[6] = MA_CHANNEL_LFE; + } break; + + case 8: + default: + { + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_RIGHT; + channelMap[2] = MA_CHANNEL_BACK_LEFT; + channelMap[3] = MA_CHANNEL_BACK_RIGHT; + channelMap[4] = MA_CHANNEL_FRONT_CENTER; + channelMap[5] = MA_CHANNEL_LFE; + channelMap[6] = MA_CHANNEL_SIDE_LEFT; + channelMap[7] = MA_CHANNEL_SIDE_RIGHT; + } break; + } + + // Remainder. + if (channels > 8) { + for (ma_uint32 iChannel = 8; iChannel < MA_MAX_CHANNELS; ++iChannel) { + channelMap[iChannel] = (ma_channel)(MA_CHANNEL_AUX_0 + (iChannel-8)); + } + } +} + +void ma_get_standard_channel_map_sndio(ma_uint32 channels, ma_channel channelMap[MA_MAX_CHANNELS]) +{ + switch (channels) + { + case 1: + { + channelMap[0] = MA_CHANNEL_MONO; + } break; + + case 2: + { + channelMap[0] = MA_CHANNEL_LEFT; + channelMap[1] = MA_CHANNEL_RIGHT; + } break; + + case 3: + { + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_RIGHT; + channelMap[2] = MA_CHANNEL_FRONT_CENTER; + } break; + + case 4: + { + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_RIGHT; + channelMap[2] = MA_CHANNEL_BACK_LEFT; + channelMap[3] = MA_CHANNEL_BACK_RIGHT; + } break; + + case 5: + { + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_RIGHT; + channelMap[2] = MA_CHANNEL_BACK_LEFT; + channelMap[3] = MA_CHANNEL_BACK_RIGHT; + channelMap[4] = MA_CHANNEL_FRONT_CENTER; + } break; + + case 6: + default: + { + channelMap[0] = MA_CHANNEL_FRONT_LEFT; + channelMap[1] = MA_CHANNEL_FRONT_RIGHT; + channelMap[2] = MA_CHANNEL_BACK_LEFT; + channelMap[3] = MA_CHANNEL_BACK_RIGHT; + channelMap[4] = MA_CHANNEL_FRONT_CENTER; + channelMap[5] = MA_CHANNEL_LFE; + } break; + } + + // Remainder. + if (channels > 6) { + for (ma_uint32 iChannel = 6; iChannel < MA_MAX_CHANNELS; ++iChannel) { + channelMap[iChannel] = (ma_channel)(MA_CHANNEL_AUX_0 + (iChannel-6)); + } + } +} + +void ma_get_standard_channel_map(ma_standard_channel_map standardChannelMap, ma_uint32 channels, ma_channel channelMap[MA_MAX_CHANNELS]) +{ + switch (standardChannelMap) + { + case ma_standard_channel_map_alsa: + { + ma_get_standard_channel_map_alsa(channels, channelMap); + } break; + + case ma_standard_channel_map_rfc3551: + { + ma_get_standard_channel_map_rfc3551(channels, channelMap); + } break; + + case ma_standard_channel_map_flac: + { + ma_get_standard_channel_map_flac(channels, channelMap); + } break; + + case ma_standard_channel_map_vorbis: + { + ma_get_standard_channel_map_vorbis(channels, channelMap); + } break; + + case ma_standard_channel_map_sound4: + { + ma_get_standard_channel_map_sound4(channels, channelMap); + } break; + + case ma_standard_channel_map_sndio: + { + ma_get_standard_channel_map_sndio(channels, channelMap); + } break; + + case ma_standard_channel_map_microsoft: + default: + { + ma_get_standard_channel_map_microsoft(channels, channelMap); + } break; + } +} + +void ma_channel_map_copy(ma_channel* pOut, const ma_channel* pIn, ma_uint32 channels) +{ + if (pOut != NULL && pIn != NULL && channels > 0) { + ma_copy_memory(pOut, pIn, sizeof(*pOut) * channels); + } +} + +ma_bool32 ma_channel_map_valid(ma_uint32 channels, const ma_channel channelMap[MA_MAX_CHANNELS]) +{ + if (channelMap == NULL) { + return MA_FALSE; + } + + // A channel count of 0 is invalid. + if (channels == 0) { + return MA_FALSE; + } + + // It does not make sense to have a mono channel when there is more than 1 channel. + if (channels > 1) { + for (ma_uint32 iChannel = 0; iChannel < channels; ++iChannel) { + if (channelMap[iChannel] == MA_CHANNEL_MONO) { + return MA_FALSE; + } + } + } + + return MA_TRUE; +} + +ma_bool32 ma_channel_map_equal(ma_uint32 channels, const ma_channel channelMapA[MA_MAX_CHANNELS], const ma_channel channelMapB[MA_MAX_CHANNELS]) +{ + if (channelMapA == channelMapB) { + return MA_FALSE; + } + + if (channels == 0 || channels > MA_MAX_CHANNELS) { + return MA_FALSE; + } + + for (ma_uint32 iChannel = 0; iChannel < channels; ++iChannel) { + if (channelMapA[iChannel] != channelMapB[iChannel]) { + return MA_FALSE; + } + } + + return MA_TRUE; +} + +ma_bool32 ma_channel_map_blank(ma_uint32 channels, const ma_channel channelMap[MA_MAX_CHANNELS]) +{ + for (ma_uint32 iChannel = 0; iChannel < channels; ++iChannel) { + if (channelMap[iChannel] != MA_CHANNEL_NONE) { + return MA_FALSE; + } + } + + return MA_TRUE; +} + +ma_bool32 ma_channel_map_contains_channel_position(ma_uint32 channels, const ma_channel channelMap[MA_MAX_CHANNELS], ma_channel channelPosition) +{ + for (ma_uint32 iChannel = 0; iChannel < channels; ++iChannel) { + if (channelMap[iChannel] == channelPosition) { + return MA_TRUE; + } + } + + return MA_FALSE; +} + + + + +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Format Conversion. +// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +//#define MA_USE_REFERENCE_CONVERSION_APIS 1 +//#define MA_USE_SSE + +void ma_copy_memory_64(void* dst, const void* src, ma_uint64 sizeInBytes) +{ +#if 0xFFFFFFFFFFFFFFFF <= MA_SIZE_MAX + ma_copy_memory(dst, src, (size_t)sizeInBytes); +#else + while (sizeInBytes > 0) { + ma_uint64 bytesToCopyNow = sizeInBytes; + if (bytesToCopyNow > MA_SIZE_MAX) { + bytesToCopyNow = MA_SIZE_MAX; + } + + ma_copy_memory(dst, src, (size_t)bytesToCopyNow); // Safe cast to size_t. + + sizeInBytes -= bytesToCopyNow; + dst = ( void*)(( ma_uint8*)dst + bytesToCopyNow); + src = (const void*)((const ma_uint8*)src + bytesToCopyNow); + } +#endif +} + +void ma_zero_memory_64(void* dst, ma_uint64 sizeInBytes) +{ +#if 0xFFFFFFFFFFFFFFFF <= MA_SIZE_MAX + ma_zero_memory(dst, (size_t)sizeInBytes); +#else + while (sizeInBytes > 0) { + ma_uint64 bytesToZeroNow = sizeInBytes; + if (bytesToZeroNow > MA_SIZE_MAX) { + bytesToZeroNow = MA_SIZE_MAX; + } + + ma_zero_memory(dst, (size_t)bytesToZeroNow); // Safe cast to size_t. + + sizeInBytes -= bytesToZeroNow; + dst = (void*)((ma_uint8*)dst + bytesToZeroNow); + } +#endif +} + + +// u8 +void ma_pcm_u8_to_u8(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + (void)ditherMode; + ma_copy_memory_64(dst, src, count * sizeof(ma_uint8)); +} + + +void ma_pcm_u8_to_s16__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + (void)ditherMode; + + ma_int16* dst_s16 = (ma_int16*)dst; + const ma_uint8* src_u8 = (const ma_uint8*)src; + + ma_uint64 i; + for (i = 0; i < count; i += 1) { + ma_int16 x = src_u8[i]; + x = x - 128; + x = x << 8; + dst_s16[i] = x; + } +} + +void ma_pcm_u8_to_s16__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_u8_to_s16__reference(dst, src, count, ditherMode); +} + +#if defined(MA_SUPPORT_SSE2) +void ma_pcm_u8_to_s16__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_u8_to_s16__optimized(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_AVX2) +void ma_pcm_u8_to_s16__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_u8_to_s16__optimized(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_AVX512) +void ma_pcm_u8_to_s16__avx512(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_u8_to_s16__avx2(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_NEON) +void ma_pcm_u8_to_s16__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_u8_to_s16__optimized(dst, src, count, ditherMode); +} +#endif + +void ma_pcm_u8_to_s16(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ +#ifdef MA_USE_REFERENCE_CONVERSION_APIS + ma_pcm_u8_to_s16__reference(dst, src, count, ditherMode); +#else + ma_pcm_u8_to_s16__optimized(dst, src, count, ditherMode); +#endif +} + + +void ma_pcm_u8_to_s24__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + (void)ditherMode; + + ma_uint8* dst_s24 = (ma_uint8*)dst; + const ma_uint8* src_u8 = (const ma_uint8*)src; + + ma_uint64 i; + for (i = 0; i < count; i += 1) { + ma_int16 x = src_u8[i]; + x = x - 128; + + dst_s24[i*3+0] = 0; + dst_s24[i*3+1] = 0; + dst_s24[i*3+2] = (ma_uint8)((ma_int8)x); + } +} + +void ma_pcm_u8_to_s24__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_u8_to_s24__reference(dst, src, count, ditherMode); +} + +#if defined(MA_SUPPORT_SSE2) +void ma_pcm_u8_to_s24__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_u8_to_s24__optimized(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_AVX2) +void ma_pcm_u8_to_s24__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_u8_to_s24__optimized(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_AVX512) +void ma_pcm_u8_to_s24__avx512(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_u8_to_s24__avx2(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_NEON) +void ma_pcm_u8_to_s24__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_u8_to_s24__optimized(dst, src, count, ditherMode); +} +#endif + +void ma_pcm_u8_to_s24(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ +#ifdef MA_USE_REFERENCE_CONVERSION_APIS + ma_pcm_u8_to_s24__reference(dst, src, count, ditherMode); +#else + ma_pcm_u8_to_s24__optimized(dst, src, count, ditherMode); +#endif +} + + +void ma_pcm_u8_to_s32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + (void)ditherMode; + + ma_int32* dst_s32 = (ma_int32*)dst; + const ma_uint8* src_u8 = (const ma_uint8*)src; + + ma_uint64 i; + for (i = 0; i < count; i += 1) { + ma_int32 x = src_u8[i]; + x = x - 128; + x = x << 24; + dst_s32[i] = x; + } +} + +void ma_pcm_u8_to_s32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_u8_to_s32__reference(dst, src, count, ditherMode); +} + +#if defined(MA_SUPPORT_SSE2) +void ma_pcm_u8_to_s32__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_u8_to_s32__optimized(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_AVX2) +void ma_pcm_u8_to_s32__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_u8_to_s32__optimized(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_AVX512) +void ma_pcm_u8_to_s32__avx512(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_u8_to_s32__avx2(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_NEON) +void ma_pcm_u8_to_s32__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_u8_to_s32__optimized(dst, src, count, ditherMode); +} +#endif + +void ma_pcm_u8_to_s32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ +#ifdef MA_USE_REFERENCE_CONVERSION_APIS + ma_pcm_u8_to_s32__reference(dst, src, count, ditherMode); +#else + ma_pcm_u8_to_s32__optimized(dst, src, count, ditherMode); +#endif +} + + +void ma_pcm_u8_to_f32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + (void)ditherMode; + + float* dst_f32 = (float*)dst; + const ma_uint8* src_u8 = (const ma_uint8*)src; + + ma_uint64 i; + for (i = 0; i < count; i += 1) { + float x = (float)src_u8[i]; + x = x * 0.00784313725490196078f; // 0..255 to 0..2 + x = x - 1; // 0..2 to -1..1 + + dst_f32[i] = x; + } +} + +void ma_pcm_u8_to_f32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_u8_to_f32__reference(dst, src, count, ditherMode); +} + +#if defined(MA_SUPPORT_SSE2) +void ma_pcm_u8_to_f32__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_u8_to_f32__optimized(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_AVX2) +void ma_pcm_u8_to_f32__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_u8_to_f32__optimized(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_AVX512) +void ma_pcm_u8_to_f32__avx512(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_u8_to_f32__avx2(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_NEON) +void ma_pcm_u8_to_f32__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_u8_to_f32__optimized(dst, src, count, ditherMode); +} +#endif + +void ma_pcm_u8_to_f32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ +#ifdef MA_USE_REFERENCE_CONVERSION_APIS + ma_pcm_u8_to_f32__reference(dst, src, count, ditherMode); +#else + ma_pcm_u8_to_f32__optimized(dst, src, count, ditherMode); +#endif +} + + + +void ma_pcm_interleave_u8__reference(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels) +{ + ma_uint8* dst_u8 = (ma_uint8*)dst; + const ma_uint8** src_u8 = (const ma_uint8**)src; + + ma_uint64 iFrame; + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + ma_uint32 iChannel; + for (iChannel = 0; iChannel < channels; iChannel += 1) { + dst_u8[iFrame*channels + iChannel] = src_u8[iChannel][iFrame]; + } + } +} + +void ma_pcm_interleave_u8__optimized(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels) +{ + ma_uint8* dst_u8 = (ma_uint8*)dst; + const ma_uint8** src_u8 = (const ma_uint8**)src; + + if (channels == 1) { + ma_copy_memory_64(dst, src[0], frameCount * sizeof(ma_uint8)); + } else if (channels == 2) { + ma_uint64 iFrame; + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + dst_u8[iFrame*2 + 0] = src_u8[0][iFrame]; + dst_u8[iFrame*2 + 1] = src_u8[1][iFrame]; + } + } else { + ma_uint64 iFrame; + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + ma_uint32 iChannel; + for (iChannel = 0; iChannel < channels; iChannel += 1) { + dst_u8[iFrame*channels + iChannel] = src_u8[iChannel][iFrame]; + } + } + } +} + +void ma_pcm_interleave_u8(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels) +{ +#ifdef MA_USE_REFERENCE_CONVERSION_APIS + ma_pcm_interleave_u8__reference(dst, src, frameCount, channels); +#else + ma_pcm_interleave_u8__optimized(dst, src, frameCount, channels); +#endif +} + + +void ma_pcm_deinterleave_u8__reference(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels) +{ + ma_uint8** dst_u8 = (ma_uint8**)dst; + const ma_uint8* src_u8 = (const ma_uint8*)src; + + ma_uint64 iFrame; + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + ma_uint32 iChannel; + for (iChannel = 0; iChannel < channels; iChannel += 1) { + dst_u8[iChannel][iFrame] = src_u8[iFrame*channels + iChannel]; + } + } +} + +void ma_pcm_deinterleave_u8__optimized(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels) +{ + ma_pcm_deinterleave_u8__reference(dst, src, frameCount, channels); +} + +void ma_pcm_deinterleave_u8(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels) +{ +#ifdef MA_USE_REFERENCE_CONVERSION_APIS + ma_pcm_deinterleave_u8__reference(dst, src, frameCount, channels); +#else + ma_pcm_deinterleave_u8__optimized(dst, src, frameCount, channels); +#endif +} + + +// s16 +void ma_pcm_s16_to_u8__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_uint8* dst_u8 = (ma_uint8*)dst; + const ma_int16* src_s16 = (const ma_int16*)src; + + if (ditherMode == ma_dither_mode_none) { + ma_uint64 i; + for (i = 0; i < count; i += 1) { + ma_int16 x = src_s16[i]; + x = x >> 8; + x = x + 128; + dst_u8[i] = (ma_uint8)x; + } + } else { + ma_uint64 i; + for (i = 0; i < count; i += 1) { + ma_int16 x = src_s16[i]; + + // Dither. Don't overflow. + ma_int32 dither = ma_dither_s32(ditherMode, -0x80, 0x7F); + if ((x + dither) <= 0x7FFF) { + x = (ma_int16)(x + dither); + } else { + x = 0x7FFF; + } + + x = x >> 8; + x = x + 128; + dst_u8[i] = (ma_uint8)x; + } + } +} + +void ma_pcm_s16_to_u8__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s16_to_u8__reference(dst, src, count, ditherMode); +} + +#if defined(MA_SUPPORT_SSE2) +void ma_pcm_s16_to_u8__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s16_to_u8__optimized(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_AVX2) +void ma_pcm_s16_to_u8__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s16_to_u8__optimized(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_AVX512) +void ma_pcm_s16_to_u8__avx512(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s16_to_u8__avx2(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_NEON) +void ma_pcm_s16_to_u8__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s16_to_u8__optimized(dst, src, count, ditherMode); +} +#endif + +void ma_pcm_s16_to_u8(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ +#ifdef MA_USE_REFERENCE_CONVERSION_APIS + ma_pcm_s16_to_u8__reference(dst, src, count, ditherMode); +#else + ma_pcm_s16_to_u8__optimized(dst, src, count, ditherMode); +#endif +} + + +void ma_pcm_s16_to_s16(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + (void)ditherMode; + ma_copy_memory_64(dst, src, count * sizeof(ma_int16)); +} + + +void ma_pcm_s16_to_s24__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + (void)ditherMode; + + ma_uint8* dst_s24 = (ma_uint8*)dst; + const ma_int16* src_s16 = (const ma_int16*)src; + + ma_uint64 i; + for (i = 0; i < count; i += 1) { + dst_s24[i*3+0] = 0; + dst_s24[i*3+1] = (ma_uint8)(src_s16[i] & 0xFF); + dst_s24[i*3+2] = (ma_uint8)(src_s16[i] >> 8); + } +} + +void ma_pcm_s16_to_s24__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s16_to_s24__reference(dst, src, count, ditherMode); +} + +#if defined(MA_SUPPORT_SSE2) +void ma_pcm_s16_to_s24__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s16_to_s24__optimized(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_AVX2) +void ma_pcm_s16_to_s24__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s16_to_s24__optimized(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_AVX512) +void ma_pcm_s16_to_s24__avx512(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s16_to_s24__avx2(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_NEON) +void ma_pcm_s16_to_s24__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s16_to_s24__optimized(dst, src, count, ditherMode); +} +#endif + +void ma_pcm_s16_to_s24(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ +#ifdef MA_USE_REFERENCE_CONVERSION_APIS + ma_pcm_s16_to_s24__reference(dst, src, count, ditherMode); +#else + ma_pcm_s16_to_s24__optimized(dst, src, count, ditherMode); +#endif +} + + +void ma_pcm_s16_to_s32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + (void)ditherMode; + + ma_int32* dst_s32 = (ma_int32*)dst; + const ma_int16* src_s16 = (const ma_int16*)src; + + ma_uint64 i; + for (i = 0; i < count; i += 1) { + dst_s32[i] = src_s16[i] << 16; + } +} + +void ma_pcm_s16_to_s32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s16_to_s32__reference(dst, src, count, ditherMode); +} + +#if defined(MA_SUPPORT_SSE2) +void ma_pcm_s16_to_s32__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s16_to_s32__optimized(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_AVX2) +void ma_pcm_s16_to_s32__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s16_to_s32__optimized(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_AVX512) +void ma_pcm_s16_to_s32__avx512(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s16_to_s32__avx2(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_NEON) +void ma_pcm_s16_to_s32__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s16_to_s32__optimized(dst, src, count, ditherMode); +} +#endif + +void ma_pcm_s16_to_s32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ +#ifdef MA_USE_REFERENCE_CONVERSION_APIS + ma_pcm_s16_to_s32__reference(dst, src, count, ditherMode); +#else + ma_pcm_s16_to_s32__optimized(dst, src, count, ditherMode); +#endif +} + + +void ma_pcm_s16_to_f32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + (void)ditherMode; + + float* dst_f32 = (float*)dst; + const ma_int16* src_s16 = (const ma_int16*)src; + + ma_uint64 i; + for (i = 0; i < count; i += 1) { + float x = (float)src_s16[i]; + +#if 0 + // The accurate way. + x = x + 32768.0f; // -32768..32767 to 0..65535 + x = x * 0.00003051804379339284f; // 0..65536 to 0..2 + x = x - 1; // 0..2 to -1..1 +#else + // The fast way. + x = x * 0.000030517578125f; // -32768..32767 to -1..0.999969482421875 +#endif + + dst_f32[i] = x; + } +} + +void ma_pcm_s16_to_f32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s16_to_f32__reference(dst, src, count, ditherMode); +} + +#if defined(MA_SUPPORT_SSE2) +void ma_pcm_s16_to_f32__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s16_to_f32__optimized(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_AVX2) +void ma_pcm_s16_to_f32__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s16_to_f32__optimized(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_AVX512) +void ma_pcm_s16_to_f32__avx512(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s16_to_f32__avx2(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_NEON) +void ma_pcm_s16_to_f32__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s16_to_f32__optimized(dst, src, count, ditherMode); +} +#endif + +void ma_pcm_s16_to_f32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ +#ifdef MA_USE_REFERENCE_CONVERSION_APIS + ma_pcm_s16_to_f32__reference(dst, src, count, ditherMode); +#else + ma_pcm_s16_to_f32__optimized(dst, src, count, ditherMode); +#endif +} + + +void ma_pcm_interleave_s16__reference(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels) +{ + ma_int16* dst_s16 = (ma_int16*)dst; + const ma_int16** src_s16 = (const ma_int16**)src; + + ma_uint64 iFrame; + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + ma_uint32 iChannel; + for (iChannel = 0; iChannel < channels; iChannel += 1) { + dst_s16[iFrame*channels + iChannel] = src_s16[iChannel][iFrame]; + } + } +} + +void ma_pcm_interleave_s16__optimized(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels) +{ + ma_pcm_interleave_s16__reference(dst, src, frameCount, channels); +} + +void ma_pcm_interleave_s16(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels) +{ +#ifdef MA_USE_REFERENCE_CONVERSION_APIS + ma_pcm_interleave_s16__reference(dst, src, frameCount, channels); +#else + ma_pcm_interleave_s16__optimized(dst, src, frameCount, channels); +#endif +} + + +void ma_pcm_deinterleave_s16__reference(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels) +{ + ma_int16** dst_s16 = (ma_int16**)dst; + const ma_int16* src_s16 = (const ma_int16*)src; + + ma_uint64 iFrame; + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + ma_uint32 iChannel; + for (iChannel = 0; iChannel < channels; iChannel += 1) { + dst_s16[iChannel][iFrame] = src_s16[iFrame*channels + iChannel]; + } + } +} + +void ma_pcm_deinterleave_s16__optimized(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels) +{ + ma_pcm_deinterleave_s16__reference(dst, src, frameCount, channels); +} + +void ma_pcm_deinterleave_s16(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels) +{ +#ifdef MA_USE_REFERENCE_CONVERSION_APIS + ma_pcm_deinterleave_s16__reference(dst, src, frameCount, channels); +#else + ma_pcm_deinterleave_s16__optimized(dst, src, frameCount, channels); +#endif +} + + +// s24 +void ma_pcm_s24_to_u8__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_uint8* dst_u8 = (ma_uint8*)dst; + const ma_uint8* src_s24 = (const ma_uint8*)src; + + if (ditherMode == ma_dither_mode_none) { + ma_uint64 i; + for (i = 0; i < count; i += 1) { + ma_int8 x = (ma_int8)src_s24[i*3 + 2] + 128; + dst_u8[i] = (ma_uint8)x; + } + } else { + ma_uint64 i; + for (i = 0; i < count; i += 1) { + ma_int32 x = (ma_int32)(((ma_uint32)(src_s24[i*3+0]) << 8) | ((ma_uint32)(src_s24[i*3+1]) << 16) | ((ma_uint32)(src_s24[i*3+2])) << 24); + + // Dither. Don't overflow. + ma_int32 dither = ma_dither_s32(ditherMode, -0x800000, 0x7FFFFF); + if ((ma_int64)x + dither <= 0x7FFFFFFF) { + x = x + dither; + } else { + x = 0x7FFFFFFF; + } + + x = x >> 24; + x = x + 128; + dst_u8[i] = (ma_uint8)x; + } + } +} + +void ma_pcm_s24_to_u8__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s24_to_u8__reference(dst, src, count, ditherMode); +} + +#if defined(MA_SUPPORT_SSE2) +void ma_pcm_s24_to_u8__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s24_to_u8__optimized(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_AVX2) +void ma_pcm_s24_to_u8__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s24_to_u8__optimized(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_AVX512) +void ma_pcm_s24_to_u8__avx512(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s24_to_u8__avx2(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_NEON) +void ma_pcm_s24_to_u8__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s24_to_u8__optimized(dst, src, count, ditherMode); +} +#endif + +void ma_pcm_s24_to_u8(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ +#ifdef MA_USE_REFERENCE_CONVERSION_APIS + ma_pcm_s24_to_u8__reference(dst, src, count, ditherMode); +#else + ma_pcm_s24_to_u8__optimized(dst, src, count, ditherMode); +#endif +} + + +void ma_pcm_s24_to_s16__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_int16* dst_s16 = (ma_int16*)dst; + const ma_uint8* src_s24 = (const ma_uint8*)src; + + if (ditherMode == ma_dither_mode_none) { + ma_uint64 i; + for (i = 0; i < count; i += 1) { + ma_uint16 dst_lo = ((ma_uint16)src_s24[i*3 + 1]); + ma_uint16 dst_hi = ((ma_uint16)src_s24[i*3 + 2]) << 8; + dst_s16[i] = (ma_int16)dst_lo | dst_hi; + } + } else { + ma_uint64 i; + for (i = 0; i < count; i += 1) { + ma_int32 x = (ma_int32)(((ma_uint32)(src_s24[i*3+0]) << 8) | ((ma_uint32)(src_s24[i*3+1]) << 16) | ((ma_uint32)(src_s24[i*3+2])) << 24); + + // Dither. Don't overflow. + ma_int32 dither = ma_dither_s32(ditherMode, -0x8000, 0x7FFF); + if ((ma_int64)x + dither <= 0x7FFFFFFF) { + x = x + dither; + } else { + x = 0x7FFFFFFF; + } + + x = x >> 16; + dst_s16[i] = (ma_int16)x; + } + } +} + +void ma_pcm_s24_to_s16__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s24_to_s16__reference(dst, src, count, ditherMode); +} + +#if defined(MA_SUPPORT_SSE2) +void ma_pcm_s24_to_s16__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s24_to_s16__optimized(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_AVX2) +void ma_pcm_s24_to_s16__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s24_to_s16__optimized(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_AVX512) +void ma_pcm_s24_to_s16__avx512(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s24_to_s16__avx2(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_NEON) +void ma_pcm_s24_to_s16__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s24_to_s16__optimized(dst, src, count, ditherMode); +} +#endif + +void ma_pcm_s24_to_s16(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ +#ifdef MA_USE_REFERENCE_CONVERSION_APIS + ma_pcm_s24_to_s16__reference(dst, src, count, ditherMode); +#else + ma_pcm_s24_to_s16__optimized(dst, src, count, ditherMode); +#endif +} + + +void ma_pcm_s24_to_s24(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + (void)ditherMode; + + ma_copy_memory_64(dst, src, count * 3); +} + + +void ma_pcm_s24_to_s32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + (void)ditherMode; + + ma_int32* dst_s32 = (ma_int32*)dst; + const ma_uint8* src_s24 = (const ma_uint8*)src; + + ma_uint64 i; + for (i = 0; i < count; i += 1) { + dst_s32[i] = (ma_int32)(((ma_uint32)(src_s24[i*3+0]) << 8) | ((ma_uint32)(src_s24[i*3+1]) << 16) | ((ma_uint32)(src_s24[i*3+2])) << 24); + } +} + +void ma_pcm_s24_to_s32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s24_to_s32__reference(dst, src, count, ditherMode); +} + +#if defined(MA_SUPPORT_SSE2) +void ma_pcm_s24_to_s32__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s24_to_s32__optimized(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_AVX2) +void ma_pcm_s24_to_s32__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s24_to_s32__optimized(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_AVX512) +void ma_pcm_s24_to_s32__avx512(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s24_to_s32__avx2(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_NEON) +void ma_pcm_s24_to_s32__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s24_to_s32__optimized(dst, src, count, ditherMode); +} +#endif + +void ma_pcm_s24_to_s32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ +#ifdef MA_USE_REFERENCE_CONVERSION_APIS + ma_pcm_s24_to_s32__reference(dst, src, count, ditherMode); +#else + ma_pcm_s24_to_s32__optimized(dst, src, count, ditherMode); +#endif +} + + +void ma_pcm_s24_to_f32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + (void)ditherMode; + + float* dst_f32 = (float*)dst; + const ma_uint8* src_s24 = (const ma_uint8*)src; + + ma_uint64 i; + for (i = 0; i < count; i += 1) { + float x = (float)(((ma_int32)(((ma_uint32)(src_s24[i*3+0]) << 8) | ((ma_uint32)(src_s24[i*3+1]) << 16) | ((ma_uint32)(src_s24[i*3+2])) << 24)) >> 8); + +#if 0 + // The accurate way. + x = x + 8388608.0f; // -8388608..8388607 to 0..16777215 + x = x * 0.00000011920929665621f; // 0..16777215 to 0..2 + x = x - 1; // 0..2 to -1..1 +#else + // The fast way. + x = x * 0.00000011920928955078125f; // -8388608..8388607 to -1..0.999969482421875 +#endif + + dst_f32[i] = x; + } +} + +void ma_pcm_s24_to_f32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s24_to_f32__reference(dst, src, count, ditherMode); +} + +#if defined(MA_SUPPORT_SSE2) +void ma_pcm_s24_to_f32__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s24_to_f32__optimized(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_AVX2) +void ma_pcm_s24_to_f32__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s24_to_f32__optimized(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_AVX512) +void ma_pcm_s24_to_f32__avx512(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s24_to_f32__avx2(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_NEON) +void ma_pcm_s24_to_f32__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s24_to_f32__optimized(dst, src, count, ditherMode); +} +#endif + +void ma_pcm_s24_to_f32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ +#ifdef MA_USE_REFERENCE_CONVERSION_APIS + ma_pcm_s24_to_f32__reference(dst, src, count, ditherMode); +#else + ma_pcm_s24_to_f32__optimized(dst, src, count, ditherMode); +#endif +} + + +void ma_pcm_interleave_s24__reference(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels) +{ + ma_uint8* dst8 = (ma_uint8*)dst; + const ma_uint8** src8 = (const ma_uint8**)src; + + ma_uint64 iFrame; + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + ma_uint32 iChannel; + for (iChannel = 0; iChannel < channels; iChannel += 1) { + dst8[iFrame*3*channels + iChannel*3 + 0] = src8[iChannel][iFrame*3 + 0]; + dst8[iFrame*3*channels + iChannel*3 + 1] = src8[iChannel][iFrame*3 + 1]; + dst8[iFrame*3*channels + iChannel*3 + 2] = src8[iChannel][iFrame*3 + 2]; + } + } +} + +void ma_pcm_interleave_s24__optimized(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels) +{ + ma_pcm_interleave_s24__reference(dst, src, frameCount, channels); +} + +void ma_pcm_interleave_s24(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels) +{ +#ifdef MA_USE_REFERENCE_CONVERSION_APIS + ma_pcm_interleave_s24__reference(dst, src, frameCount, channels); +#else + ma_pcm_interleave_s24__optimized(dst, src, frameCount, channels); +#endif +} + + +void ma_pcm_deinterleave_s24__reference(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels) +{ + ma_uint8** dst8 = (ma_uint8**)dst; + const ma_uint8* src8 = (const ma_uint8*)src; + + ma_uint32 iFrame; + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + ma_uint32 iChannel; + for (iChannel = 0; iChannel < channels; iChannel += 1) { + dst8[iChannel][iFrame*3 + 0] = src8[iFrame*3*channels + iChannel*3 + 0]; + dst8[iChannel][iFrame*3 + 1] = src8[iFrame*3*channels + iChannel*3 + 1]; + dst8[iChannel][iFrame*3 + 2] = src8[iFrame*3*channels + iChannel*3 + 2]; + } + } +} + +void ma_pcm_deinterleave_s24__optimized(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels) +{ + ma_pcm_deinterleave_s24__reference(dst, src, frameCount, channels); +} + +void ma_pcm_deinterleave_s24(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels) +{ +#ifdef MA_USE_REFERENCE_CONVERSION_APIS + ma_pcm_deinterleave_s24__reference(dst, src, frameCount, channels); +#else + ma_pcm_deinterleave_s24__optimized(dst, src, frameCount, channels); +#endif +} + + + +// s32 +void ma_pcm_s32_to_u8__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_uint8* dst_u8 = (ma_uint8*)dst; + const ma_int32* src_s32 = (const ma_int32*)src; + + if (ditherMode == ma_dither_mode_none) { + ma_uint64 i; + for (i = 0; i < count; i += 1) { + ma_int32 x = src_s32[i]; + x = x >> 24; + x = x + 128; + dst_u8[i] = (ma_uint8)x; + } + } else { + ma_uint64 i; + for (i = 0; i < count; i += 1) { + ma_int32 x = src_s32[i]; + + // Dither. Don't overflow. + ma_int32 dither = ma_dither_s32(ditherMode, -0x800000, 0x7FFFFF); + if ((ma_int64)x + dither <= 0x7FFFFFFF) { + x = x + dither; + } else { + x = 0x7FFFFFFF; + } + + x = x >> 24; + x = x + 128; + dst_u8[i] = (ma_uint8)x; + } + } +} + +void ma_pcm_s32_to_u8__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s32_to_u8__reference(dst, src, count, ditherMode); +} + +#if defined(MA_SUPPORT_SSE2) +void ma_pcm_s32_to_u8__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s32_to_u8__optimized(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_AVX2) +void ma_pcm_s32_to_u8__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s32_to_u8__optimized(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_AVX512) +void ma_pcm_s32_to_u8__avx512(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s32_to_u8__avx2(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_NEON) +void ma_pcm_s32_to_u8__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s32_to_u8__optimized(dst, src, count, ditherMode); +} +#endif + +void ma_pcm_s32_to_u8(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ +#ifdef MA_USE_REFERENCE_CONVERSION_APIS + ma_pcm_s32_to_u8__reference(dst, src, count, ditherMode); +#else + ma_pcm_s32_to_u8__optimized(dst, src, count, ditherMode); +#endif +} + + +void ma_pcm_s32_to_s16__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_int16* dst_s16 = (ma_int16*)dst; + const ma_int32* src_s32 = (const ma_int32*)src; + + if (ditherMode == ma_dither_mode_none) { + ma_uint64 i; + for (i = 0; i < count; i += 1) { + ma_int32 x = src_s32[i]; + x = x >> 16; + dst_s16[i] = (ma_int16)x; + } + } else { + ma_uint64 i; + for (i = 0; i < count; i += 1) { + ma_int32 x = src_s32[i]; + + // Dither. Don't overflow. + ma_int32 dither = ma_dither_s32(ditherMode, -0x8000, 0x7FFF); + if ((ma_int64)x + dither <= 0x7FFFFFFF) { + x = x + dither; + } else { + x = 0x7FFFFFFF; + } + + x = x >> 16; + dst_s16[i] = (ma_int16)x; + } + } +} + +void ma_pcm_s32_to_s16__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s32_to_s16__reference(dst, src, count, ditherMode); +} + +#if defined(MA_SUPPORT_SSE2) +void ma_pcm_s32_to_s16__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s32_to_s16__optimized(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_AVX2) +void ma_pcm_s32_to_s16__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s32_to_s16__optimized(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_AVX512) +void ma_pcm_s32_to_s16__avx512(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s32_to_s16__avx2(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_NEON) +void ma_pcm_s32_to_s16__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s32_to_s16__optimized(dst, src, count, ditherMode); +} +#endif + +void ma_pcm_s32_to_s16(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ +#ifdef MA_USE_REFERENCE_CONVERSION_APIS + ma_pcm_s32_to_s16__reference(dst, src, count, ditherMode); +#else + ma_pcm_s32_to_s16__optimized(dst, src, count, ditherMode); +#endif +} + + +void ma_pcm_s32_to_s24__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + (void)ditherMode; // No dithering for s32 -> s24. + + ma_uint8* dst_s24 = (ma_uint8*)dst; + const ma_int32* src_s32 = (const ma_int32*)src; + + ma_uint64 i; + for (i = 0; i < count; i += 1) { + ma_uint32 x = (ma_uint32)src_s32[i]; + dst_s24[i*3+0] = (ma_uint8)((x & 0x0000FF00) >> 8); + dst_s24[i*3+1] = (ma_uint8)((x & 0x00FF0000) >> 16); + dst_s24[i*3+2] = (ma_uint8)((x & 0xFF000000) >> 24); + } +} + +void ma_pcm_s32_to_s24__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s32_to_s24__reference(dst, src, count, ditherMode); +} + +#if defined(MA_SUPPORT_SSE2) +void ma_pcm_s32_to_s24__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s32_to_s24__optimized(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_AVX2) +void ma_pcm_s32_to_s24__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s32_to_s24__optimized(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_AVX512) +void ma_pcm_s32_to_s24__avx512(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s32_to_s24__avx2(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_NEON) +void ma_pcm_s32_to_s24__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s32_to_s24__optimized(dst, src, count, ditherMode); +} +#endif + +void ma_pcm_s32_to_s24(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ +#ifdef MA_USE_REFERENCE_CONVERSION_APIS + ma_pcm_s32_to_s24__reference(dst, src, count, ditherMode); +#else + ma_pcm_s32_to_s24__optimized(dst, src, count, ditherMode); +#endif +} + + +void ma_pcm_s32_to_s32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + (void)ditherMode; + + ma_copy_memory_64(dst, src, count * sizeof(ma_int32)); +} + + +void ma_pcm_s32_to_f32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + (void)ditherMode; // No dithering for s32 -> f32. + + float* dst_f32 = (float*)dst; + const ma_int32* src_s32 = (const ma_int32*)src; + + ma_uint64 i; + for (i = 0; i < count; i += 1) { + double x = src_s32[i]; + +#if 0 + x = x + 2147483648.0; + x = x * 0.0000000004656612873077392578125; + x = x - 1; +#else + x = x / 2147483648.0; +#endif + + dst_f32[i] = (float)x; + } +} + +void ma_pcm_s32_to_f32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s32_to_f32__reference(dst, src, count, ditherMode); +} + +#if defined(MA_SUPPORT_SSE2) +void ma_pcm_s32_to_f32__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s32_to_f32__optimized(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_AVX2) +void ma_pcm_s32_to_f32__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s32_to_f32__optimized(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_AVX512) +void ma_pcm_s32_to_f32__avx512(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s32_to_f32__avx2(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_NEON) +void ma_pcm_s32_to_f32__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_s32_to_f32__optimized(dst, src, count, ditherMode); +} +#endif + +void ma_pcm_s32_to_f32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ +#ifdef MA_USE_REFERENCE_CONVERSION_APIS + ma_pcm_s32_to_f32__reference(dst, src, count, ditherMode); +#else + ma_pcm_s32_to_f32__optimized(dst, src, count, ditherMode); +#endif +} + + +void ma_pcm_interleave_s32__reference(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels) +{ + ma_int32* dst_s32 = (ma_int32*)dst; + const ma_int32** src_s32 = (const ma_int32**)src; + + ma_uint64 iFrame; + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + ma_uint32 iChannel; + for (iChannel = 0; iChannel < channels; iChannel += 1) { + dst_s32[iFrame*channels + iChannel] = src_s32[iChannel][iFrame]; + } + } +} + +void ma_pcm_interleave_s32__optimized(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels) +{ + ma_pcm_interleave_s32__reference(dst, src, frameCount, channels); +} + +void ma_pcm_interleave_s32(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels) +{ +#ifdef MA_USE_REFERENCE_CONVERSION_APIS + ma_pcm_interleave_s32__reference(dst, src, frameCount, channels); +#else + ma_pcm_interleave_s32__optimized(dst, src, frameCount, channels); +#endif +} + + +void ma_pcm_deinterleave_s32__reference(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels) +{ + ma_int32** dst_s32 = (ma_int32**)dst; + const ma_int32* src_s32 = (const ma_int32*)src; + + ma_uint64 iFrame; + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + ma_uint32 iChannel; + for (iChannel = 0; iChannel < channels; iChannel += 1) { + dst_s32[iChannel][iFrame] = src_s32[iFrame*channels + iChannel]; + } + } +} + +void ma_pcm_deinterleave_s32__optimized(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels) +{ + ma_pcm_deinterleave_s32__reference(dst, src, frameCount, channels); +} + +void ma_pcm_deinterleave_s32(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels) +{ +#ifdef MA_USE_REFERENCE_CONVERSION_APIS + ma_pcm_deinterleave_s32__reference(dst, src, frameCount, channels); +#else + ma_pcm_deinterleave_s32__optimized(dst, src, frameCount, channels); +#endif +} + + +// f32 +void ma_pcm_f32_to_u8__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_uint8* dst_u8 = (ma_uint8*)dst; + const float* src_f32 = (const float*)src; + + float ditherMin = 0; + float ditherMax = 0; + if (ditherMode != ma_dither_mode_none) { + ditherMin = 1.0f / -128; + ditherMax = 1.0f / 127; + } + + ma_uint64 i; + for (i = 0; i < count; i += 1) { + float x = src_f32[i]; + x = x + ma_dither_f32(ditherMode, ditherMin, ditherMax); + x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); // clip + x = x + 1; // -1..1 to 0..2 + x = x * 127.5f; // 0..2 to 0..255 + + dst_u8[i] = (ma_uint8)x; + } +} + +void ma_pcm_f32_to_u8__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_f32_to_u8__reference(dst, src, count, ditherMode); +} + +#if defined(MA_SUPPORT_SSE2) +void ma_pcm_f32_to_u8__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_f32_to_u8__optimized(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_AVX2) +void ma_pcm_f32_to_u8__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_f32_to_u8__optimized(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_AVX512) +void ma_pcm_f32_to_u8__avx512(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_f32_to_u8__avx2(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_NEON) +void ma_pcm_f32_to_u8__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_f32_to_u8__optimized(dst, src, count, ditherMode); +} +#endif + +void ma_pcm_f32_to_u8(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ +#ifdef MA_USE_REFERENCE_CONVERSION_APIS + ma_pcm_f32_to_u8__reference(dst, src, count, ditherMode); +#else + ma_pcm_f32_to_u8__optimized(dst, src, count, ditherMode); +#endif +} + + +void ma_pcm_f32_to_s16__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_int16* dst_s16 = (ma_int16*)dst; + const float* src_f32 = (const float*)src; + + float ditherMin = 0; + float ditherMax = 0; + if (ditherMode != ma_dither_mode_none) { + ditherMin = 1.0f / -32768; + ditherMax = 1.0f / 32767; + } + + ma_uint64 i; + for (i = 0; i < count; i += 1) { + float x = src_f32[i]; + x = x + ma_dither_f32(ditherMode, ditherMin, ditherMax); + x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); // clip + +#if 0 + // The accurate way. + x = x + 1; // -1..1 to 0..2 + x = x * 32767.5f; // 0..2 to 0..65535 + x = x - 32768.0f; // 0...65535 to -32768..32767 +#else + // The fast way. + x = x * 32767.0f; // -1..1 to -32767..32767 +#endif + + dst_s16[i] = (ma_int16)x; + } +} + +void ma_pcm_f32_to_s16__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_int16* dst_s16 = (ma_int16*)dst; + const float* src_f32 = (const float*)src; + + float ditherMin = 0; + float ditherMax = 0; + if (ditherMode != ma_dither_mode_none) { + ditherMin = 1.0f / -32768; + ditherMax = 1.0f / 32767; + } + + ma_uint64 i = 0; + + // Unrolled. + ma_uint64 count4 = count >> 2; + for (ma_uint64 i4 = 0; i4 < count4; i4 += 1) { + float d0 = ma_dither_f32(ditherMode, ditherMin, ditherMax); + float d1 = ma_dither_f32(ditherMode, ditherMin, ditherMax); + float d2 = ma_dither_f32(ditherMode, ditherMin, ditherMax); + float d3 = ma_dither_f32(ditherMode, ditherMin, ditherMax); + + float x0 = src_f32[i+0]; + float x1 = src_f32[i+1]; + float x2 = src_f32[i+2]; + float x3 = src_f32[i+3]; + + x0 = x0 + d0; + x1 = x1 + d1; + x2 = x2 + d2; + x3 = x3 + d3; + + x0 = ((x0 < -1) ? -1 : ((x0 > 1) ? 1 : x0)); + x1 = ((x1 < -1) ? -1 : ((x1 > 1) ? 1 : x1)); + x2 = ((x2 < -1) ? -1 : ((x2 > 1) ? 1 : x2)); + x3 = ((x3 < -1) ? -1 : ((x3 > 1) ? 1 : x3)); + + x0 = x0 * 32767.0f; + x1 = x1 * 32767.0f; + x2 = x2 * 32767.0f; + x3 = x3 * 32767.0f; + + dst_s16[i+0] = (ma_int16)x0; + dst_s16[i+1] = (ma_int16)x1; + dst_s16[i+2] = (ma_int16)x2; + dst_s16[i+3] = (ma_int16)x3; + + i += 4; + } + + // Leftover. + for (; i < count; i += 1) { + float x = src_f32[i]; + x = x + ma_dither_f32(ditherMode, ditherMin, ditherMax); + x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); // clip + x = x * 32767.0f; // -1..1 to -32767..32767 + + dst_s16[i] = (ma_int16)x; + } +} + +#if defined(MA_SUPPORT_SSE2) +void ma_pcm_f32_to_s16__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + // Both the input and output buffers need to be aligned to 16 bytes. + if ((((ma_uintptr)dst & 15) != 0) || (((ma_uintptr)src & 15) != 0)) { + ma_pcm_f32_to_s16__optimized(dst, src, count, ditherMode); + return; + } + + ma_int16* dst_s16 = (ma_int16*)dst; + const float* src_f32 = (const float*)src; + + float ditherMin = 0; + float ditherMax = 0; + if (ditherMode != ma_dither_mode_none) { + ditherMin = 1.0f / -32768; + ditherMax = 1.0f / 32767; + } + + ma_uint64 i = 0; + + // SSE2. SSE allows us to output 8 s16's at a time which means our loop is unrolled 8 times. + ma_uint64 count8 = count >> 3; + for (ma_uint64 i8 = 0; i8 < count8; i8 += 1) { + __m128 d0; + __m128 d1; + if (ditherMode == ma_dither_mode_none) { + d0 = _mm_set1_ps(0); + d1 = _mm_set1_ps(0); + } else if (ditherMode == ma_dither_mode_rectangle) { + d0 = _mm_set_ps( + ma_dither_f32_rectangle(ditherMin, ditherMax), + ma_dither_f32_rectangle(ditherMin, ditherMax), + ma_dither_f32_rectangle(ditherMin, ditherMax), + ma_dither_f32_rectangle(ditherMin, ditherMax) + ); + d1 = _mm_set_ps( + ma_dither_f32_rectangle(ditherMin, ditherMax), + ma_dither_f32_rectangle(ditherMin, ditherMax), + ma_dither_f32_rectangle(ditherMin, ditherMax), + ma_dither_f32_rectangle(ditherMin, ditherMax) + ); + } else { + d0 = _mm_set_ps( + ma_dither_f32_triangle(ditherMin, ditherMax), + ma_dither_f32_triangle(ditherMin, ditherMax), + ma_dither_f32_triangle(ditherMin, ditherMax), + ma_dither_f32_triangle(ditherMin, ditherMax) + ); + d1 = _mm_set_ps( + ma_dither_f32_triangle(ditherMin, ditherMax), + ma_dither_f32_triangle(ditherMin, ditherMax), + ma_dither_f32_triangle(ditherMin, ditherMax), + ma_dither_f32_triangle(ditherMin, ditherMax) + ); + } + + __m128 x0 = *((__m128*)(src_f32 + i) + 0); + __m128 x1 = *((__m128*)(src_f32 + i) + 1); + + x0 = _mm_add_ps(x0, d0); + x1 = _mm_add_ps(x1, d1); + + x0 = _mm_mul_ps(x0, _mm_set1_ps(32767.0f)); + x1 = _mm_mul_ps(x1, _mm_set1_ps(32767.0f)); + + _mm_stream_si128(((__m128i*)(dst_s16 + i)), _mm_packs_epi32(_mm_cvttps_epi32(x0), _mm_cvttps_epi32(x1))); + + i += 8; + } + + + // Leftover. + for (; i < count; i += 1) { + float x = src_f32[i]; + x = x + ma_dither_f32(ditherMode, ditherMin, ditherMax); + x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); // clip + x = x * 32767.0f; // -1..1 to -32767..32767 + + dst_s16[i] = (ma_int16)x; + } +} +#endif +#if defined(MA_SUPPORT_AVX2) +void ma_pcm_f32_to_s16__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + // Both the input and output buffers need to be aligned to 32 bytes. + if ((((ma_uintptr)dst & 31) != 0) || (((ma_uintptr)src & 31) != 0)) { + ma_pcm_f32_to_s16__optimized(dst, src, count, ditherMode); + return; + } + + ma_int16* dst_s16 = (ma_int16*)dst; + const float* src_f32 = (const float*)src; + + float ditherMin = 0; + float ditherMax = 0; + if (ditherMode != ma_dither_mode_none) { + ditherMin = 1.0f / -32768; + ditherMax = 1.0f / 32767; + } + + ma_uint64 i = 0; + + // AVX2. AVX2 allows us to output 16 s16's at a time which means our loop is unrolled 16 times. + ma_uint64 count16 = count >> 4; + for (ma_uint64 i16 = 0; i16 < count16; i16 += 1) { + __m256 d0; + __m256 d1; + if (ditherMode == ma_dither_mode_none) { + d0 = _mm256_set1_ps(0); + d1 = _mm256_set1_ps(0); + } else if (ditherMode == ma_dither_mode_rectangle) { + d0 = _mm256_set_ps( + ma_dither_f32_rectangle(ditherMin, ditherMax), + ma_dither_f32_rectangle(ditherMin, ditherMax), + ma_dither_f32_rectangle(ditherMin, ditherMax), + ma_dither_f32_rectangle(ditherMin, ditherMax), + ma_dither_f32_rectangle(ditherMin, ditherMax), + ma_dither_f32_rectangle(ditherMin, ditherMax), + ma_dither_f32_rectangle(ditherMin, ditherMax), + ma_dither_f32_rectangle(ditherMin, ditherMax) + ); + d1 = _mm256_set_ps( + ma_dither_f32_rectangle(ditherMin, ditherMax), + ma_dither_f32_rectangle(ditherMin, ditherMax), + ma_dither_f32_rectangle(ditherMin, ditherMax), + ma_dither_f32_rectangle(ditherMin, ditherMax), + ma_dither_f32_rectangle(ditherMin, ditherMax), + ma_dither_f32_rectangle(ditherMin, ditherMax), + ma_dither_f32_rectangle(ditherMin, ditherMax), + ma_dither_f32_rectangle(ditherMin, ditherMax) + ); + } else { + d0 = _mm256_set_ps( + ma_dither_f32_triangle(ditherMin, ditherMax), + ma_dither_f32_triangle(ditherMin, ditherMax), + ma_dither_f32_triangle(ditherMin, ditherMax), + ma_dither_f32_triangle(ditherMin, ditherMax), + ma_dither_f32_triangle(ditherMin, ditherMax), + ma_dither_f32_triangle(ditherMin, ditherMax), + ma_dither_f32_triangle(ditherMin, ditherMax), + ma_dither_f32_triangle(ditherMin, ditherMax) + ); + d1 = _mm256_set_ps( + ma_dither_f32_triangle(ditherMin, ditherMax), + ma_dither_f32_triangle(ditherMin, ditherMax), + ma_dither_f32_triangle(ditherMin, ditherMax), + ma_dither_f32_triangle(ditherMin, ditherMax), + ma_dither_f32_triangle(ditherMin, ditherMax), + ma_dither_f32_triangle(ditherMin, ditherMax), + ma_dither_f32_triangle(ditherMin, ditherMax), + ma_dither_f32_triangle(ditherMin, ditherMax) + ); + } + + __m256 x0 = *((__m256*)(src_f32 + i) + 0); + __m256 x1 = *((__m256*)(src_f32 + i) + 1); + + x0 = _mm256_add_ps(x0, d0); + x1 = _mm256_add_ps(x1, d1); + + x0 = _mm256_mul_ps(x0, _mm256_set1_ps(32767.0f)); + x1 = _mm256_mul_ps(x1, _mm256_set1_ps(32767.0f)); + + // Computing the final result is a little more complicated for AVX2 than SSE2. + __m256i i0 = _mm256_cvttps_epi32(x0); + __m256i i1 = _mm256_cvttps_epi32(x1); + __m256i p0 = _mm256_permute2x128_si256(i0, i1, 0 | 32); + __m256i p1 = _mm256_permute2x128_si256(i0, i1, 1 | 48); + __m256i r = _mm256_packs_epi32(p0, p1); + + _mm256_stream_si256(((__m256i*)(dst_s16 + i)), r); + + i += 16; + } + + + // Leftover. + for (; i < count; i += 1) { + float x = src_f32[i]; + x = x + ma_dither_f32(ditherMode, ditherMin, ditherMax); + x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); // clip + x = x * 32767.0f; // -1..1 to -32767..32767 + + dst_s16[i] = (ma_int16)x; + } +} +#endif +#if defined(MA_SUPPORT_AVX512) +void ma_pcm_f32_to_s16__avx512(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + // TODO: Convert this from AVX to AVX-512. + ma_pcm_f32_to_s16__avx2(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_NEON) +void ma_pcm_f32_to_s16__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + // Both the input and output buffers need to be aligned to 16 bytes. + if ((((ma_uintptr)dst & 15) != 0) || (((ma_uintptr)src & 15) != 0)) { + ma_pcm_f32_to_s16__optimized(dst, src, count, ditherMode); + return; + } + + ma_int16* dst_s16 = (ma_int16*)dst; + const float* src_f32 = (const float*)src; + + float ditherMin = 0; + float ditherMax = 0; + if (ditherMode != ma_dither_mode_none) { + ditherMin = 1.0f / -32768; + ditherMax = 1.0f / 32767; + } + + ma_uint64 i = 0; + + // NEON. NEON allows us to output 8 s16's at a time which means our loop is unrolled 8 times. + ma_uint64 count8 = count >> 3; + for (ma_uint64 i8 = 0; i8 < count8; i8 += 1) { + float32x4_t d0; + float32x4_t d1; + if (ditherMode == ma_dither_mode_none) { + d0 = vmovq_n_f32(0); + d1 = vmovq_n_f32(0); + } else if (ditherMode == ma_dither_mode_rectangle) { + float d0v[4]; + d0v[0] = ma_dither_f32_rectangle(ditherMin, ditherMax); + d0v[1] = ma_dither_f32_rectangle(ditherMin, ditherMax); + d0v[2] = ma_dither_f32_rectangle(ditherMin, ditherMax); + d0v[3] = ma_dither_f32_rectangle(ditherMin, ditherMax); + d0 = vld1q_f32(d0v); + + float d1v[4]; + d1v[0] = ma_dither_f32_rectangle(ditherMin, ditherMax); + d1v[1] = ma_dither_f32_rectangle(ditherMin, ditherMax); + d1v[2] = ma_dither_f32_rectangle(ditherMin, ditherMax); + d1v[3] = ma_dither_f32_rectangle(ditherMin, ditherMax); + d1 = vld1q_f32(d1v); + } else { + float d0v[4]; + d0v[0] = ma_dither_f32_triangle(ditherMin, ditherMax); + d0v[1] = ma_dither_f32_triangle(ditherMin, ditherMax); + d0v[2] = ma_dither_f32_triangle(ditherMin, ditherMax); + d0v[3] = ma_dither_f32_triangle(ditherMin, ditherMax); + d0 = vld1q_f32(d0v); + + float d1v[4]; + d1v[0] = ma_dither_f32_triangle(ditherMin, ditherMax); + d1v[1] = ma_dither_f32_triangle(ditherMin, ditherMax); + d1v[2] = ma_dither_f32_triangle(ditherMin, ditherMax); + d1v[3] = ma_dither_f32_triangle(ditherMin, ditherMax); + d1 = vld1q_f32(d1v); + } + + float32x4_t x0 = *((float32x4_t*)(src_f32 + i) + 0); + float32x4_t x1 = *((float32x4_t*)(src_f32 + i) + 1); + + x0 = vaddq_f32(x0, d0); + x1 = vaddq_f32(x1, d1); + + x0 = vmulq_n_f32(x0, 32767.0f); + x1 = vmulq_n_f32(x1, 32767.0f); + + int32x4_t i0 = vcvtq_s32_f32(x0); + int32x4_t i1 = vcvtq_s32_f32(x1); + *((int16x8_t*)(dst_s16 + i)) = vcombine_s16(vqmovn_s32(i0), vqmovn_s32(i1)); + + i += 8; + } + + + // Leftover. + for (; i < count; i += 1) { + float x = src_f32[i]; + x = x + ma_dither_f32(ditherMode, ditherMin, ditherMax); + x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); // clip + x = x * 32767.0f; // -1..1 to -32767..32767 + + dst_s16[i] = (ma_int16)x; + } +} +#endif + +void ma_pcm_f32_to_s16(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ +#ifdef MA_USE_REFERENCE_CONVERSION_APIS + ma_pcm_f32_to_s16__reference(dst, src, count, ditherMode); +#else + ma_pcm_f32_to_s16__optimized(dst, src, count, ditherMode); +#endif +} + + +void ma_pcm_f32_to_s24__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + (void)ditherMode; // No dithering for f32 -> s24. + + ma_uint8* dst_s24 = (ma_uint8*)dst; + const float* src_f32 = (const float*)src; + + ma_uint64 i; + for (i = 0; i < count; i += 1) { + float x = src_f32[i]; + x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); // clip + +#if 0 + // The accurate way. + x = x + 1; // -1..1 to 0..2 + x = x * 8388607.5f; // 0..2 to 0..16777215 + x = x - 8388608.0f; // 0..16777215 to -8388608..8388607 +#else + // The fast way. + x = x * 8388607.0f; // -1..1 to -8388607..8388607 +#endif + + ma_int32 r = (ma_int32)x; + dst_s24[(i*3)+0] = (ma_uint8)((r & 0x0000FF) >> 0); + dst_s24[(i*3)+1] = (ma_uint8)((r & 0x00FF00) >> 8); + dst_s24[(i*3)+2] = (ma_uint8)((r & 0xFF0000) >> 16); + } +} + +void ma_pcm_f32_to_s24__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_f32_to_s24__reference(dst, src, count, ditherMode); +} + +#if defined(MA_SUPPORT_SSE2) +void ma_pcm_f32_to_s24__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_f32_to_s24__optimized(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_AVX2) +void ma_pcm_f32_to_s24__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_f32_to_s24__optimized(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_AVX512) +void ma_pcm_f32_to_s24__avx512(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_f32_to_s24__avx2(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_NEON) +void ma_pcm_f32_to_s24__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_f32_to_s24__optimized(dst, src, count, ditherMode); +} +#endif + +void ma_pcm_f32_to_s24(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ +#ifdef MA_USE_REFERENCE_CONVERSION_APIS + ma_pcm_f32_to_s24__reference(dst, src, count, ditherMode); +#else + ma_pcm_f32_to_s24__optimized(dst, src, count, ditherMode); +#endif +} + + +void ma_pcm_f32_to_s32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + (void)ditherMode; // No dithering for f32 -> s32. + + ma_int32* dst_s32 = (ma_int32*)dst; + const float* src_f32 = (const float*)src; + + ma_uint32 i; + for (i = 0; i < count; i += 1) { + double x = src_f32[i]; + x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); // clip + +#if 0 + // The accurate way. + x = x + 1; // -1..1 to 0..2 + x = x * 2147483647.5; // 0..2 to 0..4294967295 + x = x - 2147483648.0; // 0...4294967295 to -2147483648..2147483647 +#else + // The fast way. + x = x * 2147483647.0; // -1..1 to -2147483647..2147483647 +#endif + + dst_s32[i] = (ma_int32)x; + } +} + +void ma_pcm_f32_to_s32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_f32_to_s32__reference(dst, src, count, ditherMode); +} + +#if defined(MA_SUPPORT_SSE2) +void ma_pcm_f32_to_s32__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_f32_to_s32__optimized(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_AVX2) +void ma_pcm_f32_to_s32__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_f32_to_s32__optimized(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_AVX512) +void ma_pcm_f32_to_s32__avx512(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_f32_to_s32__avx2(dst, src, count, ditherMode); +} +#endif +#if defined(MA_SUPPORT_NEON) +void ma_pcm_f32_to_s32__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + ma_pcm_f32_to_s32__optimized(dst, src, count, ditherMode); +} +#endif + +void ma_pcm_f32_to_s32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ +#ifdef MA_USE_REFERENCE_CONVERSION_APIS + ma_pcm_f32_to_s32__reference(dst, src, count, ditherMode); +#else + ma_pcm_f32_to_s32__optimized(dst, src, count, ditherMode); +#endif +} + + +void ma_pcm_f32_to_f32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) +{ + (void)ditherMode; + + ma_copy_memory_64(dst, src, count * sizeof(float)); +} + + +void ma_pcm_interleave_f32__reference(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels) +{ + float* dst_f32 = (float*)dst; + const float** src_f32 = (const float**)src; + + ma_uint64 iFrame; + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + ma_uint32 iChannel; + for (iChannel = 0; iChannel < channels; iChannel += 1) { + dst_f32[iFrame*channels + iChannel] = src_f32[iChannel][iFrame]; + } + } +} + +void ma_pcm_interleave_f32__optimized(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels) +{ + ma_pcm_interleave_f32__reference(dst, src, frameCount, channels); +} + +void ma_pcm_interleave_f32(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels) +{ +#ifdef MA_USE_REFERENCE_CONVERSION_APIS + ma_pcm_interleave_f32__reference(dst, src, frameCount, channels); +#else + ma_pcm_interleave_f32__optimized(dst, src, frameCount, channels); +#endif +} + + +void ma_pcm_deinterleave_f32__reference(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels) +{ + float** dst_f32 = (float**)dst; + const float* src_f32 = (const float*)src; + + ma_uint64 iFrame; + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + ma_uint32 iChannel; + for (iChannel = 0; iChannel < channels; iChannel += 1) { + dst_f32[iChannel][iFrame] = src_f32[iFrame*channels + iChannel]; + } + } +} + +void ma_pcm_deinterleave_f32__optimized(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels) +{ + ma_pcm_deinterleave_f32__reference(dst, src, frameCount, channels); +} + +void ma_pcm_deinterleave_f32(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels) +{ +#ifdef MA_USE_REFERENCE_CONVERSION_APIS + ma_pcm_deinterleave_f32__reference(dst, src, frameCount, channels); +#else + ma_pcm_deinterleave_f32__optimized(dst, src, frameCount, channels); +#endif +} + + +void ma_format_converter_init_callbacks__default(ma_format_converter* pConverter) +{ + ma_assert(pConverter != NULL); + + switch (pConverter->config.formatIn) + { + case ma_format_u8: + { + if (pConverter->config.formatOut == ma_format_u8) { + pConverter->onConvertPCM = ma_pcm_u8_to_u8; + } else if (pConverter->config.formatOut == ma_format_s16) { + pConverter->onConvertPCM = ma_pcm_u8_to_s16; + } else if (pConverter->config.formatOut == ma_format_s24) { + pConverter->onConvertPCM = ma_pcm_u8_to_s24; + } else if (pConverter->config.formatOut == ma_format_s32) { + pConverter->onConvertPCM = ma_pcm_u8_to_s32; + } else if (pConverter->config.formatOut == ma_format_f32) { + pConverter->onConvertPCM = ma_pcm_u8_to_f32; + } + } break; + + case ma_format_s16: + { + if (pConverter->config.formatOut == ma_format_u8) { + pConverter->onConvertPCM = ma_pcm_s16_to_u8; + } else if (pConverter->config.formatOut == ma_format_s16) { + pConverter->onConvertPCM = ma_pcm_s16_to_s16; + } else if (pConverter->config.formatOut == ma_format_s24) { + pConverter->onConvertPCM = ma_pcm_s16_to_s24; + } else if (pConverter->config.formatOut == ma_format_s32) { + pConverter->onConvertPCM = ma_pcm_s16_to_s32; + } else if (pConverter->config.formatOut == ma_format_f32) { + pConverter->onConvertPCM = ma_pcm_s16_to_f32; + } + } break; + + case ma_format_s24: + { + if (pConverter->config.formatOut == ma_format_u8) { + pConverter->onConvertPCM = ma_pcm_s24_to_u8; + } else if (pConverter->config.formatOut == ma_format_s16) { + pConverter->onConvertPCM = ma_pcm_s24_to_s16; + } else if (pConverter->config.formatOut == ma_format_s24) { + pConverter->onConvertPCM = ma_pcm_s24_to_s24; + } else if (pConverter->config.formatOut == ma_format_s32) { + pConverter->onConvertPCM = ma_pcm_s24_to_s32; + } else if (pConverter->config.formatOut == ma_format_f32) { + pConverter->onConvertPCM = ma_pcm_s24_to_f32; + } + } break; + + case ma_format_s32: + { + if (pConverter->config.formatOut == ma_format_u8) { + pConverter->onConvertPCM = ma_pcm_s32_to_u8; + } else if (pConverter->config.formatOut == ma_format_s16) { + pConverter->onConvertPCM = ma_pcm_s32_to_s16; + } else if (pConverter->config.formatOut == ma_format_s24) { + pConverter->onConvertPCM = ma_pcm_s32_to_s24; + } else if (pConverter->config.formatOut == ma_format_s32) { + pConverter->onConvertPCM = ma_pcm_s32_to_s32; + } else if (pConverter->config.formatOut == ma_format_f32) { + pConverter->onConvertPCM = ma_pcm_s32_to_f32; + } + } break; + + case ma_format_f32: + default: + { + if (pConverter->config.formatOut == ma_format_u8) { + pConverter->onConvertPCM = ma_pcm_f32_to_u8; + } else if (pConverter->config.formatOut == ma_format_s16) { + pConverter->onConvertPCM = ma_pcm_f32_to_s16; + } else if (pConverter->config.formatOut == ma_format_s24) { + pConverter->onConvertPCM = ma_pcm_f32_to_s24; + } else if (pConverter->config.formatOut == ma_format_s32) { + pConverter->onConvertPCM = ma_pcm_f32_to_s32; + } else if (pConverter->config.formatOut == ma_format_f32) { + pConverter->onConvertPCM = ma_pcm_f32_to_f32; + } + } break; + } +} + +#if defined(MA_SUPPORT_SSE2) +void ma_format_converter_init_callbacks__sse2(ma_format_converter* pConverter) +{ + ma_assert(pConverter != NULL); + + switch (pConverter->config.formatIn) + { + case ma_format_u8: + { + if (pConverter->config.formatOut == ma_format_u8) { + pConverter->onConvertPCM = ma_pcm_u8_to_u8; + } else if (pConverter->config.formatOut == ma_format_s16) { + pConverter->onConvertPCM = ma_pcm_u8_to_s16__sse2; + } else if (pConverter->config.formatOut == ma_format_s24) { + pConverter->onConvertPCM = ma_pcm_u8_to_s24__sse2; + } else if (pConverter->config.formatOut == ma_format_s32) { + pConverter->onConvertPCM = ma_pcm_u8_to_s32__sse2; + } else if (pConverter->config.formatOut == ma_format_f32) { + pConverter->onConvertPCM = ma_pcm_u8_to_f32__sse2; + } + } break; + + case ma_format_s16: + { + if (pConverter->config.formatOut == ma_format_u8) { + pConverter->onConvertPCM = ma_pcm_s16_to_u8__sse2; + } else if (pConverter->config.formatOut == ma_format_s16) { + pConverter->onConvertPCM = ma_pcm_s16_to_s16; + } else if (pConverter->config.formatOut == ma_format_s24) { + pConverter->onConvertPCM = ma_pcm_s16_to_s24__sse2; + } else if (pConverter->config.formatOut == ma_format_s32) { + pConverter->onConvertPCM = ma_pcm_s16_to_s32__sse2; + } else if (pConverter->config.formatOut == ma_format_f32) { + pConverter->onConvertPCM = ma_pcm_s16_to_f32__sse2; + } + } break; + + case ma_format_s24: + { + if (pConverter->config.formatOut == ma_format_u8) { + pConverter->onConvertPCM = ma_pcm_s24_to_u8__sse2; + } else if (pConverter->config.formatOut == ma_format_s16) { + pConverter->onConvertPCM = ma_pcm_s24_to_s16__sse2; + } else if (pConverter->config.formatOut == ma_format_s24) { + pConverter->onConvertPCM = ma_pcm_s24_to_s24; + } else if (pConverter->config.formatOut == ma_format_s32) { + pConverter->onConvertPCM = ma_pcm_s24_to_s32__sse2; + } else if (pConverter->config.formatOut == ma_format_f32) { + pConverter->onConvertPCM = ma_pcm_s24_to_f32__sse2; + } + } break; + + case ma_format_s32: + { + if (pConverter->config.formatOut == ma_format_u8) { + pConverter->onConvertPCM = ma_pcm_s32_to_u8__sse2; + } else if (pConverter->config.formatOut == ma_format_s16) { + pConverter->onConvertPCM = ma_pcm_s32_to_s16__sse2; + } else if (pConverter->config.formatOut == ma_format_s24) { + pConverter->onConvertPCM = ma_pcm_s32_to_s24__sse2; + } else if (pConverter->config.formatOut == ma_format_s32) { + pConverter->onConvertPCM = ma_pcm_s32_to_s32; + } else if (pConverter->config.formatOut == ma_format_f32) { + pConverter->onConvertPCM = ma_pcm_s32_to_f32__sse2; + } + } break; + + case ma_format_f32: + default: + { + if (pConverter->config.formatOut == ma_format_u8) { + pConverter->onConvertPCM = ma_pcm_f32_to_u8__sse2; + } else if (pConverter->config.formatOut == ma_format_s16) { + pConverter->onConvertPCM = ma_pcm_f32_to_s16__sse2; + } else if (pConverter->config.formatOut == ma_format_s24) { + pConverter->onConvertPCM = ma_pcm_f32_to_s24__sse2; + } else if (pConverter->config.formatOut == ma_format_s32) { + pConverter->onConvertPCM = ma_pcm_f32_to_s32__sse2; + } else if (pConverter->config.formatOut == ma_format_f32) { + pConverter->onConvertPCM = ma_pcm_f32_to_f32; + } + } break; + } +} +#endif + +#if defined(MA_SUPPORT_AVX2) +void ma_format_converter_init_callbacks__avx2(ma_format_converter* pConverter) +{ + ma_assert(pConverter != NULL); + + switch (pConverter->config.formatIn) + { + case ma_format_u8: + { + if (pConverter->config.formatOut == ma_format_u8) { + pConverter->onConvertPCM = ma_pcm_u8_to_u8; + } else if (pConverter->config.formatOut == ma_format_s16) { + pConverter->onConvertPCM = ma_pcm_u8_to_s16__avx2; + } else if (pConverter->config.formatOut == ma_format_s24) { + pConverter->onConvertPCM = ma_pcm_u8_to_s24__avx2; + } else if (pConverter->config.formatOut == ma_format_s32) { + pConverter->onConvertPCM = ma_pcm_u8_to_s32__avx2; + } else if (pConverter->config.formatOut == ma_format_f32) { + pConverter->onConvertPCM = ma_pcm_u8_to_f32__avx2; + } + } break; + + case ma_format_s16: + { + if (pConverter->config.formatOut == ma_format_u8) { + pConverter->onConvertPCM = ma_pcm_s16_to_u8__avx2; + } else if (pConverter->config.formatOut == ma_format_s16) { + pConverter->onConvertPCM = ma_pcm_s16_to_s16; + } else if (pConverter->config.formatOut == ma_format_s24) { + pConverter->onConvertPCM = ma_pcm_s16_to_s24__avx2; + } else if (pConverter->config.formatOut == ma_format_s32) { + pConverter->onConvertPCM = ma_pcm_s16_to_s32__avx2; + } else if (pConverter->config.formatOut == ma_format_f32) { + pConverter->onConvertPCM = ma_pcm_s16_to_f32__avx2; + } + } break; + + case ma_format_s24: + { + if (pConverter->config.formatOut == ma_format_u8) { + pConverter->onConvertPCM = ma_pcm_s24_to_u8__avx2; + } else if (pConverter->config.formatOut == ma_format_s16) { + pConverter->onConvertPCM = ma_pcm_s24_to_s16__avx2; + } else if (pConverter->config.formatOut == ma_format_s24) { + pConverter->onConvertPCM = ma_pcm_s24_to_s24; + } else if (pConverter->config.formatOut == ma_format_s32) { + pConverter->onConvertPCM = ma_pcm_s24_to_s32__avx2; + } else if (pConverter->config.formatOut == ma_format_f32) { + pConverter->onConvertPCM = ma_pcm_s24_to_f32__avx2; + } + } break; + + case ma_format_s32: + { + if (pConverter->config.formatOut == ma_format_u8) { + pConverter->onConvertPCM = ma_pcm_s32_to_u8__avx2; + } else if (pConverter->config.formatOut == ma_format_s16) { + pConverter->onConvertPCM = ma_pcm_s32_to_s16__avx2; + } else if (pConverter->config.formatOut == ma_format_s24) { + pConverter->onConvertPCM = ma_pcm_s32_to_s24__avx2; + } else if (pConverter->config.formatOut == ma_format_s32) { + pConverter->onConvertPCM = ma_pcm_s32_to_s32; + } else if (pConverter->config.formatOut == ma_format_f32) { + pConverter->onConvertPCM = ma_pcm_s32_to_f32__avx2; + } + } break; + + case ma_format_f32: + default: + { + if (pConverter->config.formatOut == ma_format_u8) { + pConverter->onConvertPCM = ma_pcm_f32_to_u8__avx2; + } else if (pConverter->config.formatOut == ma_format_s16) { + pConverter->onConvertPCM = ma_pcm_f32_to_s16__avx2; + } else if (pConverter->config.formatOut == ma_format_s24) { + pConverter->onConvertPCM = ma_pcm_f32_to_s24__avx2; + } else if (pConverter->config.formatOut == ma_format_s32) { + pConverter->onConvertPCM = ma_pcm_f32_to_s32__avx2; + } else if (pConverter->config.formatOut == ma_format_f32) { + pConverter->onConvertPCM = ma_pcm_f32_to_f32; + } + } break; + } +} +#endif + +#if defined(MA_SUPPORT_AVX512) +void ma_format_converter_init_callbacks__avx512(ma_format_converter* pConverter) +{ + ma_assert(pConverter != NULL); + + switch (pConverter->config.formatIn) + { + case ma_format_u8: + { + if (pConverter->config.formatOut == ma_format_u8) { + pConverter->onConvertPCM = ma_pcm_u8_to_u8; + } else if (pConverter->config.formatOut == ma_format_s16) { + pConverter->onConvertPCM = ma_pcm_u8_to_s16__avx512; + } else if (pConverter->config.formatOut == ma_format_s24) { + pConverter->onConvertPCM = ma_pcm_u8_to_s24__avx512; + } else if (pConverter->config.formatOut == ma_format_s32) { + pConverter->onConvertPCM = ma_pcm_u8_to_s32__avx512; + } else if (pConverter->config.formatOut == ma_format_f32) { + pConverter->onConvertPCM = ma_pcm_u8_to_f32__avx512; + } + } break; + + case ma_format_s16: + { + if (pConverter->config.formatOut == ma_format_u8) { + pConverter->onConvertPCM = ma_pcm_s16_to_u8__avx512; + } else if (pConverter->config.formatOut == ma_format_s16) { + pConverter->onConvertPCM = ma_pcm_s16_to_s16; + } else if (pConverter->config.formatOut == ma_format_s24) { + pConverter->onConvertPCM = ma_pcm_s16_to_s24__avx512; + } else if (pConverter->config.formatOut == ma_format_s32) { + pConverter->onConvertPCM = ma_pcm_s16_to_s32__avx512; + } else if (pConverter->config.formatOut == ma_format_f32) { + pConverter->onConvertPCM = ma_pcm_s16_to_f32__avx512; + } + } break; + + case ma_format_s24: + { + if (pConverter->config.formatOut == ma_format_u8) { + pConverter->onConvertPCM = ma_pcm_s24_to_u8__avx512; + } else if (pConverter->config.formatOut == ma_format_s16) { + pConverter->onConvertPCM = ma_pcm_s24_to_s16__avx512; + } else if (pConverter->config.formatOut == ma_format_s24) { + pConverter->onConvertPCM = ma_pcm_s24_to_s24; + } else if (pConverter->config.formatOut == ma_format_s32) { + pConverter->onConvertPCM = ma_pcm_s24_to_s32__avx512; + } else if (pConverter->config.formatOut == ma_format_f32) { + pConverter->onConvertPCM = ma_pcm_s24_to_f32__avx512; + } + } break; + + case ma_format_s32: + { + if (pConverter->config.formatOut == ma_format_u8) { + pConverter->onConvertPCM = ma_pcm_s32_to_u8__avx512; + } else if (pConverter->config.formatOut == ma_format_s16) { + pConverter->onConvertPCM = ma_pcm_s32_to_s16__avx512; + } else if (pConverter->config.formatOut == ma_format_s24) { + pConverter->onConvertPCM = ma_pcm_s32_to_s24__avx512; + } else if (pConverter->config.formatOut == ma_format_s32) { + pConverter->onConvertPCM = ma_pcm_s32_to_s32; + } else if (pConverter->config.formatOut == ma_format_f32) { + pConverter->onConvertPCM = ma_pcm_s32_to_f32__avx512; + } + } break; + + case ma_format_f32: + default: + { + if (pConverter->config.formatOut == ma_format_u8) { + pConverter->onConvertPCM = ma_pcm_f32_to_u8__avx512; + } else if (pConverter->config.formatOut == ma_format_s16) { + pConverter->onConvertPCM = ma_pcm_f32_to_s16__avx512; + } else if (pConverter->config.formatOut == ma_format_s24) { + pConverter->onConvertPCM = ma_pcm_f32_to_s24__avx512; + } else if (pConverter->config.formatOut == ma_format_s32) { + pConverter->onConvertPCM = ma_pcm_f32_to_s32__avx512; + } else if (pConverter->config.formatOut == ma_format_f32) { + pConverter->onConvertPCM = ma_pcm_f32_to_f32; + } + } break; + } +} +#endif + +#if defined(MA_SUPPORT_NEON) +void ma_format_converter_init_callbacks__neon(ma_format_converter* pConverter) +{ + ma_assert(pConverter != NULL); + + switch (pConverter->config.formatIn) + { + case ma_format_u8: + { + if (pConverter->config.formatOut == ma_format_u8) { + pConverter->onConvertPCM = ma_pcm_u8_to_u8; + } else if (pConverter->config.formatOut == ma_format_s16) { + pConverter->onConvertPCM = ma_pcm_u8_to_s16__neon; + } else if (pConverter->config.formatOut == ma_format_s24) { + pConverter->onConvertPCM = ma_pcm_u8_to_s24__neon; + } else if (pConverter->config.formatOut == ma_format_s32) { + pConverter->onConvertPCM = ma_pcm_u8_to_s32__neon; + } else if (pConverter->config.formatOut == ma_format_f32) { + pConverter->onConvertPCM = ma_pcm_u8_to_f32__neon; + } + } break; + + case ma_format_s16: + { + if (pConverter->config.formatOut == ma_format_u8) { + pConverter->onConvertPCM = ma_pcm_s16_to_u8__neon; + } else if (pConverter->config.formatOut == ma_format_s16) { + pConverter->onConvertPCM = ma_pcm_s16_to_s16; + } else if (pConverter->config.formatOut == ma_format_s24) { + pConverter->onConvertPCM = ma_pcm_s16_to_s24__neon; + } else if (pConverter->config.formatOut == ma_format_s32) { + pConverter->onConvertPCM = ma_pcm_s16_to_s32__neon; + } else if (pConverter->config.formatOut == ma_format_f32) { + pConverter->onConvertPCM = ma_pcm_s16_to_f32__neon; + } + } break; + + case ma_format_s24: + { + if (pConverter->config.formatOut == ma_format_u8) { + pConverter->onConvertPCM = ma_pcm_s24_to_u8__neon; + } else if (pConverter->config.formatOut == ma_format_s16) { + pConverter->onConvertPCM = ma_pcm_s24_to_s16__neon; + } else if (pConverter->config.formatOut == ma_format_s24) { + pConverter->onConvertPCM = ma_pcm_s24_to_s24; + } else if (pConverter->config.formatOut == ma_format_s32) { + pConverter->onConvertPCM = ma_pcm_s24_to_s32__neon; + } else if (pConverter->config.formatOut == ma_format_f32) { + pConverter->onConvertPCM = ma_pcm_s24_to_f32__neon; + } + } break; + + case ma_format_s32: + { + if (pConverter->config.formatOut == ma_format_u8) { + pConverter->onConvertPCM = ma_pcm_s32_to_u8__neon; + } else if (pConverter->config.formatOut == ma_format_s16) { + pConverter->onConvertPCM = ma_pcm_s32_to_s16__neon; + } else if (pConverter->config.formatOut == ma_format_s24) { + pConverter->onConvertPCM = ma_pcm_s32_to_s24__neon; + } else if (pConverter->config.formatOut == ma_format_s32) { + pConverter->onConvertPCM = ma_pcm_s32_to_s32; + } else if (pConverter->config.formatOut == ma_format_f32) { + pConverter->onConvertPCM = ma_pcm_s32_to_f32__neon; + } + } break; + + case ma_format_f32: + default: + { + if (pConverter->config.formatOut == ma_format_u8) { + pConverter->onConvertPCM = ma_pcm_f32_to_u8__neon; + } else if (pConverter->config.formatOut == ma_format_s16) { + pConverter->onConvertPCM = ma_pcm_f32_to_s16__neon; + } else if (pConverter->config.formatOut == ma_format_s24) { + pConverter->onConvertPCM = ma_pcm_f32_to_s24__neon; + } else if (pConverter->config.formatOut == ma_format_s32) { + pConverter->onConvertPCM = ma_pcm_f32_to_s32__neon; + } else if (pConverter->config.formatOut == ma_format_f32) { + pConverter->onConvertPCM = ma_pcm_f32_to_f32; + } + } break; + } +} +#endif + +ma_result ma_format_converter_init(const ma_format_converter_config* pConfig, ma_format_converter* pConverter) +{ + if (pConverter == NULL) { + return MA_INVALID_ARGS; + } + ma_zero_object(pConverter); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + + pConverter->config = *pConfig; + + // SIMD + pConverter->useSSE2 = ma_has_sse2() && !pConfig->noSSE2; + pConverter->useAVX2 = ma_has_avx2() && !pConfig->noAVX2; + pConverter->useAVX512 = ma_has_avx512f() && !pConfig->noAVX512; + pConverter->useNEON = ma_has_neon() && !pConfig->noNEON; + +#if defined(MA_SUPPORT_AVX512) + if (pConverter->useAVX512) { + ma_format_converter_init_callbacks__avx512(pConverter); + } else +#endif +#if defined(MA_SUPPORT_AVX2) + if (pConverter->useAVX2) { + ma_format_converter_init_callbacks__avx2(pConverter); + } else +#endif +#if defined(MA_SUPPORT_SSE2) + if (pConverter->useSSE2) { + ma_format_converter_init_callbacks__sse2(pConverter); + } else +#endif +#if defined(MA_SUPPORT_NEON) + if (pConverter->useNEON) { + ma_format_converter_init_callbacks__neon(pConverter); + } else +#endif + { + ma_format_converter_init_callbacks__default(pConverter); + } + + switch (pConfig->formatOut) + { + case ma_format_u8: + { + pConverter->onInterleavePCM = ma_pcm_interleave_u8; + pConverter->onDeinterleavePCM = ma_pcm_deinterleave_u8; + } break; + case ma_format_s16: + { + pConverter->onInterleavePCM = ma_pcm_interleave_s16; + pConverter->onDeinterleavePCM = ma_pcm_deinterleave_s16; + } break; + case ma_format_s24: + { + pConverter->onInterleavePCM = ma_pcm_interleave_s24; + pConverter->onDeinterleavePCM = ma_pcm_deinterleave_s24; + } break; + case ma_format_s32: + { + pConverter->onInterleavePCM = ma_pcm_interleave_s32; + pConverter->onDeinterleavePCM = ma_pcm_deinterleave_s32; + } break; + case ma_format_f32: + default: + { + pConverter->onInterleavePCM = ma_pcm_interleave_f32; + pConverter->onDeinterleavePCM = ma_pcm_deinterleave_f32; + } break; + } + + return MA_SUCCESS; +} + +ma_uint64 ma_format_converter_read(ma_format_converter* pConverter, ma_uint64 frameCount, void* pFramesOut, void* pUserData) +{ + if (pConverter == NULL || pFramesOut == NULL) { + return 0; + } + + ma_uint64 totalFramesRead = 0; + ma_uint32 sampleSizeIn = ma_get_bytes_per_sample(pConverter->config.formatIn); + ma_uint32 sampleSizeOut = ma_get_bytes_per_sample(pConverter->config.formatOut); + //ma_uint32 frameSizeIn = sampleSizeIn * pConverter->config.channels; + ma_uint32 frameSizeOut = sampleSizeOut * pConverter->config.channels; + ma_uint8* pNextFramesOut = (ma_uint8*)pFramesOut; + + if (pConverter->config.onRead != NULL) { + // Input data is interleaved. + if (pConverter->config.formatIn == pConverter->config.formatOut) { + // Pass through. + while (totalFramesRead < frameCount) { + ma_uint64 framesRemaining = (frameCount - totalFramesRead); + ma_uint64 framesToReadRightNow = framesRemaining; + if (framesToReadRightNow > 0xFFFFFFFF) { + framesToReadRightNow = 0xFFFFFFFF; + } + + ma_uint32 framesJustRead = (ma_uint32)pConverter->config.onRead(pConverter, (ma_uint32)framesToReadRightNow, pNextFramesOut, pUserData); + if (framesJustRead == 0) { + break; + } + + totalFramesRead += framesJustRead; + pNextFramesOut += framesJustRead * frameSizeOut; + + if (framesJustRead < framesToReadRightNow) { + break; + } + } + } else { + // Conversion required. + MA_ALIGN(MA_SIMD_ALIGNMENT) ma_uint8 temp[MA_MAX_CHANNELS * MA_MAX_PCM_SAMPLE_SIZE_IN_BYTES * 128]; + ma_assert(sizeof(temp) <= 0xFFFFFFFF); + + ma_uint32 maxFramesToReadAtATime = sizeof(temp) / sampleSizeIn / pConverter->config.channels; + + while (totalFramesRead < frameCount) { + ma_uint64 framesRemaining = (frameCount - totalFramesRead); + ma_uint64 framesToReadRightNow = framesRemaining; + if (framesToReadRightNow > maxFramesToReadAtATime) { + framesToReadRightNow = maxFramesToReadAtATime; + } + + ma_uint32 framesJustRead = (ma_uint32)pConverter->config.onRead(pConverter, (ma_uint32)framesToReadRightNow, temp, pUserData); + if (framesJustRead == 0) { + break; + } + + pConverter->onConvertPCM(pNextFramesOut, temp, framesJustRead*pConverter->config.channels, pConverter->config.ditherMode); + + totalFramesRead += framesJustRead; + pNextFramesOut += framesJustRead * frameSizeOut; + + if (framesJustRead < framesToReadRightNow) { + break; + } + } + } + } else { + // Input data is deinterleaved. If a conversion is required we need to do an intermediary step. + MA_ALIGN(MA_SIMD_ALIGNMENT) ma_uint8 tempSamplesOfOutFormat[MA_MAX_CHANNELS * MA_MAX_PCM_SAMPLE_SIZE_IN_BYTES * 128]; + ma_assert(sizeof(tempSamplesOfOutFormat) <= 0xFFFFFFFFF); + + void* ppTempSamplesOfOutFormat[MA_MAX_CHANNELS]; + size_t splitBufferSizeOut; + ma_split_buffer(tempSamplesOfOutFormat, sizeof(tempSamplesOfOutFormat), pConverter->config.channels, MA_SIMD_ALIGNMENT, (void**)&ppTempSamplesOfOutFormat, &splitBufferSizeOut); + + ma_uint32 maxFramesToReadAtATime = (ma_uint32)(splitBufferSizeOut / sampleSizeIn); + + while (totalFramesRead < frameCount) { + ma_uint64 framesRemaining = (frameCount - totalFramesRead); + ma_uint64 framesToReadRightNow = framesRemaining; + if (framesToReadRightNow > maxFramesToReadAtATime) { + framesToReadRightNow = maxFramesToReadAtATime; + } + + ma_uint32 framesJustRead = 0; + + if (pConverter->config.formatIn == pConverter->config.formatOut) { + // Only interleaving. + framesJustRead = (ma_uint32)pConverter->config.onReadDeinterleaved(pConverter, (ma_uint32)framesToReadRightNow, ppTempSamplesOfOutFormat, pUserData); + if (framesJustRead == 0) { + break; + } + } else { + // Interleaving + Conversion. Convert first, then interleave. + MA_ALIGN(MA_SIMD_ALIGNMENT) ma_uint8 tempSamplesOfInFormat[MA_MAX_CHANNELS * MA_MAX_PCM_SAMPLE_SIZE_IN_BYTES * 128]; + + void* ppTempSamplesOfInFormat[MA_MAX_CHANNELS]; + size_t splitBufferSizeIn; + ma_split_buffer(tempSamplesOfInFormat, sizeof(tempSamplesOfInFormat), pConverter->config.channels, MA_SIMD_ALIGNMENT, (void**)&ppTempSamplesOfInFormat, &splitBufferSizeIn); + + if (framesToReadRightNow > (splitBufferSizeIn / sampleSizeIn)) { + framesToReadRightNow = (splitBufferSizeIn / sampleSizeIn); + } + + framesJustRead = (ma_uint32)pConverter->config.onReadDeinterleaved(pConverter, (ma_uint32)framesToReadRightNow, ppTempSamplesOfInFormat, pUserData); + if (framesJustRead == 0) { + break; + } + + for (ma_uint32 iChannel = 0; iChannel < pConverter->config.channels; iChannel += 1) { + pConverter->onConvertPCM(ppTempSamplesOfOutFormat[iChannel], ppTempSamplesOfInFormat[iChannel], framesJustRead, pConverter->config.ditherMode); + } + } + + pConverter->onInterleavePCM(pNextFramesOut, (const void**)ppTempSamplesOfOutFormat, framesJustRead, pConverter->config.channels); + + totalFramesRead += framesJustRead; + pNextFramesOut += framesJustRead * frameSizeOut; + + if (framesJustRead < framesToReadRightNow) { + break; + } + } + } + + return totalFramesRead; +} + +ma_uint64 ma_format_converter_read_deinterleaved(ma_format_converter* pConverter, ma_uint64 frameCount, void** ppSamplesOut, void* pUserData) +{ + if (pConverter == NULL || ppSamplesOut == NULL) { + return 0; + } + + ma_uint64 totalFramesRead = 0; + ma_uint32 sampleSizeIn = ma_get_bytes_per_sample(pConverter->config.formatIn); + ma_uint32 sampleSizeOut = ma_get_bytes_per_sample(pConverter->config.formatOut); + + ma_uint8* ppNextSamplesOut[MA_MAX_CHANNELS]; + ma_copy_memory(ppNextSamplesOut, ppSamplesOut, sizeof(void*) * pConverter->config.channels); + + if (pConverter->config.onRead != NULL) { + // Input data is interleaved. + MA_ALIGN(MA_SIMD_ALIGNMENT) ma_uint8 tempSamplesOfOutFormat[MA_MAX_CHANNELS * MA_MAX_PCM_SAMPLE_SIZE_IN_BYTES * 128]; + ma_assert(sizeof(tempSamplesOfOutFormat) <= 0xFFFFFFFF); + + ma_uint32 maxFramesToReadAtATime = sizeof(tempSamplesOfOutFormat) / sampleSizeIn / pConverter->config.channels; + + while (totalFramesRead < frameCount) { + ma_uint64 framesRemaining = (frameCount - totalFramesRead); + ma_uint64 framesToReadRightNow = framesRemaining; + if (framesToReadRightNow > maxFramesToReadAtATime) { + framesToReadRightNow = maxFramesToReadAtATime; + } + + ma_uint32 framesJustRead = 0; + + if (pConverter->config.formatIn == pConverter->config.formatOut) { + // Only de-interleaving. + framesJustRead = (ma_uint32)pConverter->config.onRead(pConverter, (ma_uint32)framesToReadRightNow, tempSamplesOfOutFormat, pUserData); + if (framesJustRead == 0) { + break; + } + } else { + // De-interleaving + Conversion. Convert first, then de-interleave. + MA_ALIGN(MA_SIMD_ALIGNMENT) ma_uint8 tempSamplesOfInFormat[sizeof(tempSamplesOfOutFormat)]; + + framesJustRead = (ma_uint32)pConverter->config.onRead(pConverter, (ma_uint32)framesToReadRightNow, tempSamplesOfInFormat, pUserData); + if (framesJustRead == 0) { + break; + } + + pConverter->onConvertPCM(tempSamplesOfOutFormat, tempSamplesOfInFormat, framesJustRead * pConverter->config.channels, pConverter->config.ditherMode); + } + + pConverter->onDeinterleavePCM((void**)ppNextSamplesOut, tempSamplesOfOutFormat, framesJustRead, pConverter->config.channels); + + totalFramesRead += framesJustRead; + for (ma_uint32 iChannel = 0; iChannel < pConverter->config.channels; ++iChannel) { + ppNextSamplesOut[iChannel] += framesJustRead * sampleSizeOut; + } + + if (framesJustRead < framesToReadRightNow) { + break; + } + } + } else { + // Input data is deinterleaved. + if (pConverter->config.formatIn == pConverter->config.formatOut) { + // Pass through. + while (totalFramesRead < frameCount) { + ma_uint64 framesRemaining = (frameCount - totalFramesRead); + ma_uint64 framesToReadRightNow = framesRemaining; + if (framesToReadRightNow > 0xFFFFFFFF) { + framesToReadRightNow = 0xFFFFFFFF; + } + + ma_uint32 framesJustRead = (ma_uint32)pConverter->config.onReadDeinterleaved(pConverter, (ma_uint32)framesToReadRightNow, (void**)ppNextSamplesOut, pUserData); + if (framesJustRead == 0) { + break; + } + + totalFramesRead += framesJustRead; + for (ma_uint32 iChannel = 0; iChannel < pConverter->config.channels; ++iChannel) { + ppNextSamplesOut[iChannel] += framesJustRead * sampleSizeOut; + } + + if (framesJustRead < framesToReadRightNow) { + break; + } + } + } else { + // Conversion required. + MA_ALIGN(MA_SIMD_ALIGNMENT) ma_uint8 temp[MA_MAX_CHANNELS][MA_MAX_PCM_SAMPLE_SIZE_IN_BYTES * 128]; + ma_assert(sizeof(temp) <= 0xFFFFFFFF); + + void* ppTemp[MA_MAX_CHANNELS]; + size_t splitBufferSize; + ma_split_buffer(temp, sizeof(temp), pConverter->config.channels, MA_SIMD_ALIGNMENT, (void**)&ppTemp, &splitBufferSize); + + ma_uint32 maxFramesToReadAtATime = (ma_uint32)(splitBufferSize / sampleSizeIn); + + while (totalFramesRead < frameCount) { + ma_uint64 framesRemaining = (frameCount - totalFramesRead); + ma_uint64 framesToReadRightNow = framesRemaining; + if (framesToReadRightNow > maxFramesToReadAtATime) { + framesToReadRightNow = maxFramesToReadAtATime; + } + + ma_uint32 framesJustRead = (ma_uint32)pConverter->config.onReadDeinterleaved(pConverter, (ma_uint32)framesToReadRightNow, ppTemp, pUserData); + if (framesJustRead == 0) { + break; + } + + for (ma_uint32 iChannel = 0; iChannel < pConverter->config.channels; iChannel += 1) { + pConverter->onConvertPCM(ppNextSamplesOut[iChannel], ppTemp[iChannel], framesJustRead, pConverter->config.ditherMode); + ppNextSamplesOut[iChannel] += framesJustRead * sampleSizeOut; + } + + totalFramesRead += framesJustRead; + + if (framesJustRead < framesToReadRightNow) { + break; + } + } + } + } + + return totalFramesRead; +} + + +ma_format_converter_config ma_format_converter_config_init_new() +{ + ma_format_converter_config config; + ma_zero_object(&config); + + return config; +} + +ma_format_converter_config ma_format_converter_config_init(ma_format formatIn, ma_format formatOut, ma_uint32 channels, ma_format_converter_read_proc onRead, void* pUserData) +{ + ma_format_converter_config config = ma_format_converter_config_init_new(); + config.formatIn = formatIn; + config.formatOut = formatOut; + config.channels = channels; + config.onRead = onRead; + config.onReadDeinterleaved = NULL; + config.pUserData = pUserData; + + return config; +} + +ma_format_converter_config ma_format_converter_config_init_deinterleaved(ma_format formatIn, ma_format formatOut, ma_uint32 channels, ma_format_converter_read_deinterleaved_proc onReadDeinterleaved, void* pUserData) +{ + ma_format_converter_config config = ma_format_converter_config_init(formatIn, formatOut, channels, NULL, pUserData); + config.onReadDeinterleaved = onReadDeinterleaved; + + return config; +} + + + +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Channel Routing +// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +// -X = Left, +X = Right +// -Y = Bottom, +Y = Top +// -Z = Front, +Z = Back +typedef struct +{ + float x; + float y; + float z; +} ma_vec3; + +static MA_INLINE ma_vec3 ma_vec3f(float x, float y, float z) +{ + ma_vec3 r; + r.x = x; + r.y = y; + r.z = z; + + return r; +} + +static MA_INLINE ma_vec3 ma_vec3_add(ma_vec3 a, ma_vec3 b) +{ + return ma_vec3f( + a.x + b.x, + a.y + b.y, + a.z + b.z + ); +} + +static MA_INLINE ma_vec3 ma_vec3_sub(ma_vec3 a, ma_vec3 b) +{ + return ma_vec3f( + a.x - b.x, + a.y - b.y, + a.z - b.z + ); +} + +static MA_INLINE ma_vec3 ma_vec3_mul(ma_vec3 a, ma_vec3 b) +{ + return ma_vec3f( + a.x * b.x, + a.y * b.y, + a.z * b.z + ); +} + +static MA_INLINE ma_vec3 ma_vec3_div(ma_vec3 a, ma_vec3 b) +{ + return ma_vec3f( + a.x / b.x, + a.y / b.y, + a.z / b.z + ); +} + +static MA_INLINE float ma_vec3_dot(ma_vec3 a, ma_vec3 b) +{ + return a.x*b.x + a.y*b.y + a.z*b.z; +} + +static MA_INLINE float ma_vec3_length2(ma_vec3 a) +{ + return ma_vec3_dot(a, a); +} + +static MA_INLINE float ma_vec3_length(ma_vec3 a) +{ + return (float)sqrt(ma_vec3_length2(a)); +} + +static MA_INLINE ma_vec3 ma_vec3_normalize(ma_vec3 a) +{ + float len = 1 / ma_vec3_length(a); + + ma_vec3 r; + r.x = a.x * len; + r.y = a.y * len; + r.z = a.z * len; + + return r; +} + +static MA_INLINE float ma_vec3_distance(ma_vec3 a, ma_vec3 b) +{ + return ma_vec3_length(ma_vec3_sub(a, b)); +} + + +#define MA_PLANE_LEFT 0 +#define MA_PLANE_RIGHT 1 +#define MA_PLANE_FRONT 2 +#define MA_PLANE_BACK 3 +#define MA_PLANE_BOTTOM 4 +#define MA_PLANE_TOP 5 + +float g_maChannelPlaneRatios[MA_CHANNEL_POSITION_COUNT][6] = { + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_NONE + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_MONO + { 0.5f, 0.0f, 0.5f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_FRONT_LEFT + { 0.0f, 0.5f, 0.5f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_FRONT_RIGHT + { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_FRONT_CENTER + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_LFE + { 0.5f, 0.0f, 0.0f, 0.5f, 0.0f, 0.0f}, // MA_CHANNEL_BACK_LEFT + { 0.0f, 0.5f, 0.0f, 0.5f, 0.0f, 0.0f}, // MA_CHANNEL_BACK_RIGHT + { 0.25f, 0.0f, 0.75f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_FRONT_LEFT_CENTER + { 0.0f, 0.25f, 0.75f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_FRONT_RIGHT_CENTER + { 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f}, // MA_CHANNEL_BACK_CENTER + { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_SIDE_LEFT + { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_SIDE_RIGHT + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f}, // MA_CHANNEL_TOP_CENTER + { 0.33f, 0.0f, 0.33f, 0.0f, 0.0f, 0.34f}, // MA_CHANNEL_TOP_FRONT_LEFT + { 0.0f, 0.0f, 0.5f, 0.0f, 0.0f, 0.5f}, // MA_CHANNEL_TOP_FRONT_CENTER + { 0.0f, 0.33f, 0.33f, 0.0f, 0.0f, 0.34f}, // MA_CHANNEL_TOP_FRONT_RIGHT + { 0.33f, 0.0f, 0.0f, 0.33f, 0.0f, 0.34f}, // MA_CHANNEL_TOP_BACK_LEFT + { 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, 0.5f}, // MA_CHANNEL_TOP_BACK_CENTER + { 0.0f, 0.33f, 0.0f, 0.33f, 0.0f, 0.34f}, // MA_CHANNEL_TOP_BACK_RIGHT + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_0 + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_1 + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_2 + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_3 + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_4 + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_5 + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_6 + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_7 + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_8 + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_9 + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_10 + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_11 + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_12 + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_13 + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_14 + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_15 + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_16 + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_17 + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_18 + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_19 + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_20 + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_21 + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_22 + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_23 + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_24 + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_25 + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_26 + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_27 + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_28 + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_29 + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_30 + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_31 +}; + +float ma_calculate_channel_position_planar_weight(ma_channel channelPositionA, ma_channel channelPositionB) +{ + // Imagine the following simplified example: You have a single input speaker which is the front/left speaker which you want to convert to + // the following output configuration: + // + // - front/left + // - side/left + // - back/left + // + // The front/left output is easy - it the same speaker position so it receives the full contribution of the front/left input. The amount + // of contribution to apply to the side/left and back/left speakers, however, is a bit more complicated. + // + // Imagine the front/left speaker as emitting audio from two planes - the front plane and the left plane. You can think of the front/left + // speaker emitting half of it's total volume from the front, and the other half from the left. Since part of it's volume is being emitted + // from the left side, and the side/left and back/left channels also emit audio from the left plane, one would expect that they would + // receive some amount of contribution from front/left speaker. The amount of contribution depends on how many planes are shared between + // the two speakers. Note that in the examples below I've added a top/front/left speaker as an example just to show how the math works + // across 3 spatial dimensions. + // + // The first thing to do is figure out how each speaker's volume is spread over each of plane: + // - front/left: 2 planes (front and left) = 1/2 = half it's total volume on each plane + // - side/left: 1 plane (left only) = 1/1 = entire volume from left plane + // - back/left: 2 planes (back and left) = 1/2 = half it's total volume on each plane + // - top/front/left: 3 planes (top, front and left) = 1/3 = one third it's total volume on each plane + // + // The amount of volume each channel contributes to each of it's planes is what controls how much it is willing to given and take to other + // channels on the same plane. The volume that is willing to the given by one channel is multiplied by the volume that is willing to be + // taken by the other to produce the final contribution. + + // Contribution = Sum(Volume to Give * Volume to Take) + float contribution = + g_maChannelPlaneRatios[channelPositionA][0] * g_maChannelPlaneRatios[channelPositionB][0] + + g_maChannelPlaneRatios[channelPositionA][1] * g_maChannelPlaneRatios[channelPositionB][1] + + g_maChannelPlaneRatios[channelPositionA][2] * g_maChannelPlaneRatios[channelPositionB][2] + + g_maChannelPlaneRatios[channelPositionA][3] * g_maChannelPlaneRatios[channelPositionB][3] + + g_maChannelPlaneRatios[channelPositionA][4] * g_maChannelPlaneRatios[channelPositionB][4] + + g_maChannelPlaneRatios[channelPositionA][5] * g_maChannelPlaneRatios[channelPositionB][5]; + + return contribution; +} + +float ma_channel_router__calculate_input_channel_planar_weight(const ma_channel_router* pRouter, ma_channel channelPositionIn, ma_channel channelPositionOut) +{ + ma_assert(pRouter != NULL); + (void)pRouter; + + return ma_calculate_channel_position_planar_weight(channelPositionIn, channelPositionOut); +} + +ma_bool32 ma_channel_router__is_spatial_channel_position(const ma_channel_router* pRouter, ma_channel channelPosition) +{ + ma_assert(pRouter != NULL); + (void)pRouter; + + if (channelPosition == MA_CHANNEL_NONE || channelPosition == MA_CHANNEL_MONO || channelPosition == MA_CHANNEL_LFE) { + return MA_FALSE; + } + + for (int i = 0; i < 6; ++i) { + if (g_maChannelPlaneRatios[channelPosition][i] != 0) { + return MA_TRUE; + } + } + + return MA_FALSE; +} + +ma_result ma_channel_router_init(const ma_channel_router_config* pConfig, ma_channel_router* pRouter) +{ + if (pRouter == NULL) { + return MA_INVALID_ARGS; + } + + ma_zero_object(pRouter); + + if (pConfig == NULL) { + return MA_INVALID_ARGS; + } + if (pConfig->onReadDeinterleaved == NULL) { + return MA_INVALID_ARGS; + } + + if (!ma_channel_map_valid(pConfig->channelsIn, pConfig->channelMapIn)) { + return MA_INVALID_ARGS; // Invalid input channel map. + } + if (!ma_channel_map_valid(pConfig->channelsOut, pConfig->channelMapOut)) { + return MA_INVALID_ARGS; // Invalid output channel map. + } + + pRouter->config = *pConfig; + + // SIMD + pRouter->useSSE2 = ma_has_sse2() && !pConfig->noSSE2; + pRouter->useAVX2 = ma_has_avx2() && !pConfig->noAVX2; + pRouter->useAVX512 = ma_has_avx512f() && !pConfig->noAVX512; + pRouter->useNEON = ma_has_neon() && !pConfig->noNEON; + + // If the input and output channels and channel maps are the same we should use a passthrough. + if (pRouter->config.channelsIn == pRouter->config.channelsOut) { + if (ma_channel_map_equal(pRouter->config.channelsIn, pRouter->config.channelMapIn, pRouter->config.channelMapOut)) { + pRouter->isPassthrough = MA_TRUE; + } + if (ma_channel_map_blank(pRouter->config.channelsIn, pRouter->config.channelMapIn) || ma_channel_map_blank(pRouter->config.channelsOut, pRouter->config.channelMapOut)) { + pRouter->isPassthrough = MA_TRUE; + } + } + + // Here is where we do a bit of pre-processing to know how each channel should be combined to make up the output. Rules: + // + // 1) If it's a passthrough, do nothing - it's just a simple memcpy(). + // 2) If the channel counts are the same and every channel position in the input map is present in the output map, use a + // simple shuffle. An example might be different 5.1 channel layouts. + // 3) Otherwise channels are blended based on spatial locality. + if (!pRouter->isPassthrough) { + if (pRouter->config.channelsIn == pRouter->config.channelsOut) { + ma_bool32 areAllChannelPositionsPresent = MA_TRUE; + for (ma_uint32 iChannelIn = 0; iChannelIn < pRouter->config.channelsIn; ++iChannelIn) { + ma_bool32 isInputChannelPositionInOutput = MA_FALSE; + for (ma_uint32 iChannelOut = 0; iChannelOut < pRouter->config.channelsOut; ++iChannelOut) { + if (pRouter->config.channelMapIn[iChannelIn] == pRouter->config.channelMapOut[iChannelOut]) { + isInputChannelPositionInOutput = MA_TRUE; + break; + } + } + + if (!isInputChannelPositionInOutput) { + areAllChannelPositionsPresent = MA_FALSE; + break; + } + } + + if (areAllChannelPositionsPresent) { + pRouter->isSimpleShuffle = MA_TRUE; + + // All the router will be doing is rearranging channels which means all we need to do is use a shuffling table which is just + // a mapping between the index of the input channel to the index of the output channel. + for (ma_uint32 iChannelIn = 0; iChannelIn < pRouter->config.channelsIn; ++iChannelIn) { + for (ma_uint32 iChannelOut = 0; iChannelOut < pRouter->config.channelsOut; ++iChannelOut) { + if (pRouter->config.channelMapIn[iChannelIn] == pRouter->config.channelMapOut[iChannelOut]) { + pRouter->shuffleTable[iChannelIn] = (ma_uint8)iChannelOut; + break; + } + } + } + } + } + } + + + // Here is where weights are calculated. Note that we calculate the weights at all times, even when using a passthrough and simple + // shuffling. We use different algorithms for calculating weights depending on our mixing mode. + // + // In simple mode we don't do any blending (except for converting between mono, which is done in a later step). Instead we just + // map 1:1 matching channels. In this mode, if no channels in the input channel map correspond to anything in the output channel + // map, nothing will be heard! + + // In all cases we need to make sure all channels that are present in both channel maps have a 1:1 mapping. + for (ma_uint32 iChannelIn = 0; iChannelIn < pRouter->config.channelsIn; ++iChannelIn) { + ma_channel channelPosIn = pRouter->config.channelMapIn[iChannelIn]; + + for (ma_uint32 iChannelOut = 0; iChannelOut < pRouter->config.channelsOut; ++iChannelOut) { + ma_channel channelPosOut = pRouter->config.channelMapOut[iChannelOut]; + + if (channelPosIn == channelPosOut) { + pRouter->config.weights[iChannelIn][iChannelOut] = 1; + } + } + } + + // The mono channel is accumulated on all other channels, except LFE. Make sure in this loop we exclude output mono channels since + // they were handled in the pass above. + for (ma_uint32 iChannelIn = 0; iChannelIn < pRouter->config.channelsIn; ++iChannelIn) { + ma_channel channelPosIn = pRouter->config.channelMapIn[iChannelIn]; + + if (channelPosIn == MA_CHANNEL_MONO) { + for (ma_uint32 iChannelOut = 0; iChannelOut < pRouter->config.channelsOut; ++iChannelOut) { + ma_channel channelPosOut = pRouter->config.channelMapOut[iChannelOut]; + + if (channelPosOut != MA_CHANNEL_NONE && channelPosOut != MA_CHANNEL_MONO && channelPosOut != MA_CHANNEL_LFE) { + pRouter->config.weights[iChannelIn][iChannelOut] = 1; + } + } + } + } + + // The output mono channel is the average of all non-none, non-mono and non-lfe input channels. + { + ma_uint32 len = 0; + for (ma_uint32 iChannelIn = 0; iChannelIn < pRouter->config.channelsIn; ++iChannelIn) { + ma_channel channelPosIn = pRouter->config.channelMapIn[iChannelIn]; + + if (channelPosIn != MA_CHANNEL_NONE && channelPosIn != MA_CHANNEL_MONO && channelPosIn != MA_CHANNEL_LFE) { + len += 1; + } + } + + if (len > 0) { + float monoWeight = 1.0f / len; + + for (ma_uint32 iChannelOut = 0; iChannelOut < pRouter->config.channelsOut; ++iChannelOut) { + ma_channel channelPosOut = pRouter->config.channelMapOut[iChannelOut]; + + if (channelPosOut == MA_CHANNEL_MONO) { + for (ma_uint32 iChannelIn = 0; iChannelIn < pRouter->config.channelsIn; ++iChannelIn) { + ma_channel channelPosIn = pRouter->config.channelMapIn[iChannelIn]; + + if (channelPosIn != MA_CHANNEL_NONE && channelPosIn != MA_CHANNEL_MONO && channelPosIn != MA_CHANNEL_LFE) { + pRouter->config.weights[iChannelIn][iChannelOut] += monoWeight; + } + } + } + } + } + } + + + // Input and output channels that are not present on the other side need to be blended in based on spatial locality. + switch (pRouter->config.mixingMode) + { + case ma_channel_mix_mode_rectangular: + { + // Unmapped input channels. + for (ma_uint32 iChannelIn = 0; iChannelIn < pRouter->config.channelsIn; ++iChannelIn) { + ma_channel channelPosIn = pRouter->config.channelMapIn[iChannelIn]; + + if (ma_channel_router__is_spatial_channel_position(pRouter, channelPosIn)) { + if (!ma_channel_map_contains_channel_position(pRouter->config.channelsOut, pRouter->config.channelMapOut, channelPosIn)) { + for (ma_uint32 iChannelOut = 0; iChannelOut < pRouter->config.channelsOut; ++iChannelOut) { + ma_channel channelPosOut = pRouter->config.channelMapOut[iChannelOut]; + + if (ma_channel_router__is_spatial_channel_position(pRouter, channelPosOut)) { + float weight = 0; + if (pRouter->config.mixingMode == ma_channel_mix_mode_planar_blend) { + weight = ma_channel_router__calculate_input_channel_planar_weight(pRouter, channelPosIn, channelPosOut); + } + + // Only apply the weight if we haven't already got some contribution from the respective channels. + if (pRouter->config.weights[iChannelIn][iChannelOut] == 0) { + pRouter->config.weights[iChannelIn][iChannelOut] = weight; + } + } + } + } + } + } + + // Unmapped output channels. + for (ma_uint32 iChannelOut = 0; iChannelOut < pRouter->config.channelsOut; ++iChannelOut) { + ma_channel channelPosOut = pRouter->config.channelMapOut[iChannelOut]; + + if (ma_channel_router__is_spatial_channel_position(pRouter, channelPosOut)) { + if (!ma_channel_map_contains_channel_position(pRouter->config.channelsIn, pRouter->config.channelMapIn, channelPosOut)) { + for (ma_uint32 iChannelIn = 0; iChannelIn < pRouter->config.channelsIn; ++iChannelIn) { + ma_channel channelPosIn = pRouter->config.channelMapIn[iChannelIn]; + + if (ma_channel_router__is_spatial_channel_position(pRouter, channelPosIn)) { + float weight = 0; + if (pRouter->config.mixingMode == ma_channel_mix_mode_planar_blend) { + weight = ma_channel_router__calculate_input_channel_planar_weight(pRouter, channelPosIn, channelPosOut); + } + + // Only apply the weight if we haven't already got some contribution from the respective channels. + if (pRouter->config.weights[iChannelIn][iChannelOut] == 0) { + pRouter->config.weights[iChannelIn][iChannelOut] = weight; + } + } + } + } + } + } + } break; + + case ma_channel_mix_mode_custom_weights: + case ma_channel_mix_mode_simple: + default: + { + /* Fallthrough. */ + } break; + } + + return MA_SUCCESS; +} + +static MA_INLINE ma_bool32 ma_channel_router__can_use_sse2(ma_channel_router* pRouter, const float* pSamplesOut, const float* pSamplesIn) +{ + return pRouter->useSSE2 && (((ma_uintptr)pSamplesOut & 15) == 0) && (((ma_uintptr)pSamplesIn & 15) == 0); +} + +static MA_INLINE ma_bool32 ma_channel_router__can_use_avx2(ma_channel_router* pRouter, const float* pSamplesOut, const float* pSamplesIn) +{ + return pRouter->useAVX2 && (((ma_uintptr)pSamplesOut & 31) == 0) && (((ma_uintptr)pSamplesIn & 31) == 0); +} + +static MA_INLINE ma_bool32 ma_channel_router__can_use_avx512(ma_channel_router* pRouter, const float* pSamplesOut, const float* pSamplesIn) +{ + return pRouter->useAVX512 && (((ma_uintptr)pSamplesOut & 63) == 0) && (((ma_uintptr)pSamplesIn & 63) == 0); +} + +static MA_INLINE ma_bool32 ma_channel_router__can_use_neon(ma_channel_router* pRouter, const float* pSamplesOut, const float* pSamplesIn) +{ + return pRouter->useNEON && (((ma_uintptr)pSamplesOut & 15) == 0) && (((ma_uintptr)pSamplesIn & 15) == 0); +} + +void ma_channel_router__do_routing(ma_channel_router* pRouter, ma_uint64 frameCount, float** ppSamplesOut, const float** ppSamplesIn) +{ + ma_assert(pRouter != NULL); + ma_assert(pRouter->isPassthrough == MA_FALSE); + + if (pRouter->isSimpleShuffle) { + // A shuffle is just a re-arrangement of channels and does not require any arithmetic. + ma_assert(pRouter->config.channelsIn == pRouter->config.channelsOut); + for (ma_uint32 iChannelIn = 0; iChannelIn < pRouter->config.channelsIn; ++iChannelIn) { + ma_uint32 iChannelOut = pRouter->shuffleTable[iChannelIn]; + ma_copy_memory_64(ppSamplesOut[iChannelOut], ppSamplesIn[iChannelIn], frameCount * sizeof(float)); + } + } else { + // This is the more complicated case. Each of the output channels is accumulated with 0 or more input channels. + + // Clear. + for (ma_uint32 iChannelOut = 0; iChannelOut < pRouter->config.channelsOut; ++iChannelOut) { + ma_zero_memory_64(ppSamplesOut[iChannelOut], frameCount * sizeof(float)); + } + + // Accumulate. + for (ma_uint32 iChannelIn = 0; iChannelIn < pRouter->config.channelsIn; ++iChannelIn) { + for (ma_uint32 iChannelOut = 0; iChannelOut < pRouter->config.channelsOut; ++iChannelOut) { + ma_uint64 iFrame = 0; +#if defined(MA_SUPPORT_NEON) + if (ma_channel_router__can_use_neon(pRouter, ppSamplesOut[iChannelOut], ppSamplesIn[iChannelIn])) { + float32x4_t weight = vmovq_n_f32(pRouter->config.weights[iChannelIn][iChannelOut]); + + ma_uint64 frameCount4 = frameCount/4; + for (ma_uint64 iFrame4 = 0; iFrame4 < frameCount4; iFrame4 += 1) { + float32x4_t* pO = (float32x4_t*)ppSamplesOut[iChannelOut] + iFrame4; + float32x4_t* pI = (float32x4_t*)ppSamplesIn [iChannelIn ] + iFrame4; + *pO = vaddq_f32(*pO, vmulq_f32(*pI, weight)); + } + + iFrame += frameCount4*4; + } + else +#endif +#if defined(MA_SUPPORT_AVX512) + if (ma_channel_router__can_use_avx512(pRouter, ppSamplesOut[iChannelOut], ppSamplesIn[iChannelIn])) { + __m512 weight = _mm512_set1_ps(pRouter->config.weights[iChannelIn][iChannelOut]); + + ma_uint64 frameCount16 = frameCount/16; + for (ma_uint64 iFrame16 = 0; iFrame16 < frameCount16; iFrame16 += 1) { + __m512* pO = (__m512*)ppSamplesOut[iChannelOut] + iFrame16; + __m512* pI = (__m512*)ppSamplesIn [iChannelIn ] + iFrame16; + *pO = _mm512_add_ps(*pO, _mm512_mul_ps(*pI, weight)); + } + + iFrame += frameCount16*16; + } + else +#endif +#if defined(MA_SUPPORT_AVX2) + if (ma_channel_router__can_use_avx2(pRouter, ppSamplesOut[iChannelOut], ppSamplesIn[iChannelIn])) { + __m256 weight = _mm256_set1_ps(pRouter->config.weights[iChannelIn][iChannelOut]); + + ma_uint64 frameCount8 = frameCount/8; + for (ma_uint64 iFrame8 = 0; iFrame8 < frameCount8; iFrame8 += 1) { + __m256* pO = (__m256*)ppSamplesOut[iChannelOut] + iFrame8; + __m256* pI = (__m256*)ppSamplesIn [iChannelIn ] + iFrame8; + *pO = _mm256_add_ps(*pO, _mm256_mul_ps(*pI, weight)); + } + + iFrame += frameCount8*8; + } + else +#endif +#if defined(MA_SUPPORT_SSE2) + if (ma_channel_router__can_use_sse2(pRouter, ppSamplesOut[iChannelOut], ppSamplesIn[iChannelIn])) { + __m128 weight = _mm_set1_ps(pRouter->config.weights[iChannelIn][iChannelOut]); + + ma_uint64 frameCount4 = frameCount/4; + for (ma_uint64 iFrame4 = 0; iFrame4 < frameCount4; iFrame4 += 1) { + __m128* pO = (__m128*)ppSamplesOut[iChannelOut] + iFrame4; + __m128* pI = (__m128*)ppSamplesIn [iChannelIn ] + iFrame4; + *pO = _mm_add_ps(*pO, _mm_mul_ps(*pI, weight)); + } + + iFrame += frameCount4*4; + } else +#endif + { // Reference. + float weight0 = pRouter->config.weights[iChannelIn][iChannelOut]; + float weight1 = pRouter->config.weights[iChannelIn][iChannelOut]; + float weight2 = pRouter->config.weights[iChannelIn][iChannelOut]; + float weight3 = pRouter->config.weights[iChannelIn][iChannelOut]; + + ma_uint64 frameCount4 = frameCount/4; + for (ma_uint64 iFrame4 = 0; iFrame4 < frameCount4; iFrame4 += 1) { + ppSamplesOut[iChannelOut][iFrame+0] += ppSamplesIn[iChannelIn][iFrame+0] * weight0; + ppSamplesOut[iChannelOut][iFrame+1] += ppSamplesIn[iChannelIn][iFrame+1] * weight1; + ppSamplesOut[iChannelOut][iFrame+2] += ppSamplesIn[iChannelIn][iFrame+2] * weight2; + ppSamplesOut[iChannelOut][iFrame+3] += ppSamplesIn[iChannelIn][iFrame+3] * weight3; + iFrame += 4; + } + } + + // Leftover. + for (; iFrame < frameCount; ++iFrame) { + ppSamplesOut[iChannelOut][iFrame] += ppSamplesIn[iChannelIn][iFrame] * pRouter->config.weights[iChannelIn][iChannelOut]; + } + } + } + } +} + +ma_uint64 ma_channel_router_read_deinterleaved(ma_channel_router* pRouter, ma_uint64 frameCount, void** ppSamplesOut, void* pUserData) +{ + if (pRouter == NULL || ppSamplesOut == NULL) { + return 0; + } + + // Fast path for a passthrough. + if (pRouter->isPassthrough) { + if (frameCount <= 0xFFFFFFFF) { + return (ma_uint32)pRouter->config.onReadDeinterleaved(pRouter, (ma_uint32)frameCount, ppSamplesOut, pUserData); + } else { + float* ppNextSamplesOut[MA_MAX_CHANNELS]; + ma_copy_memory(ppNextSamplesOut, ppSamplesOut, sizeof(float*) * pRouter->config.channelsOut); + + ma_uint64 totalFramesRead = 0; + while (totalFramesRead < frameCount) { + ma_uint64 framesRemaining = (frameCount - totalFramesRead); + ma_uint64 framesToReadRightNow = framesRemaining; + if (framesToReadRightNow > 0xFFFFFFFF) { + framesToReadRightNow = 0xFFFFFFFF; + } + + ma_uint32 framesJustRead = (ma_uint32)pRouter->config.onReadDeinterleaved(pRouter, (ma_uint32)framesToReadRightNow, (void**)ppNextSamplesOut, pUserData); + if (framesJustRead == 0) { + break; + } + + totalFramesRead += framesJustRead; + for (ma_uint32 iChannel = 0; iChannel < pRouter->config.channelsOut; ++iChannel) { + ppNextSamplesOut[iChannel] += framesJustRead; + } + + if (framesJustRead < framesToReadRightNow) { + break; + } + } + } + } + + // Slower path for a non-passthrough. + float* ppNextSamplesOut[MA_MAX_CHANNELS]; + ma_copy_memory(ppNextSamplesOut, ppSamplesOut, sizeof(float*) * pRouter->config.channelsOut); + + MA_ALIGN(MA_SIMD_ALIGNMENT) float temp[MA_MAX_CHANNELS * 256]; + ma_assert(sizeof(temp) <= 0xFFFFFFFF); + + float* ppTemp[MA_MAX_CHANNELS]; + size_t maxBytesToReadPerFrameEachIteration; + ma_split_buffer(temp, sizeof(temp), pRouter->config.channelsIn, MA_SIMD_ALIGNMENT, (void**)&ppTemp, &maxBytesToReadPerFrameEachIteration); + + size_t maxFramesToReadEachIteration = maxBytesToReadPerFrameEachIteration/sizeof(float); + + ma_uint64 totalFramesRead = 0; + while (totalFramesRead < frameCount) { + ma_uint64 framesRemaining = (frameCount - totalFramesRead); + ma_uint64 framesToReadRightNow = framesRemaining; + if (framesToReadRightNow > maxFramesToReadEachIteration) { + framesToReadRightNow = maxFramesToReadEachIteration; + } + + ma_uint32 framesJustRead = pRouter->config.onReadDeinterleaved(pRouter, (ma_uint32)framesToReadRightNow, (void**)ppTemp, pUserData); + if (framesJustRead == 0) { + break; + } + + ma_channel_router__do_routing(pRouter, framesJustRead, (float**)ppNextSamplesOut, (const float**)ppTemp); // <-- Real work is done here. + + totalFramesRead += framesJustRead; + if (totalFramesRead < frameCount) { + for (ma_uint32 iChannel = 0; iChannel < pRouter->config.channelsIn; iChannel += 1) { + ppNextSamplesOut[iChannel] += framesJustRead; + } + } + + if (framesJustRead < framesToReadRightNow) { + break; + } + } + + return totalFramesRead; +} + +ma_channel_router_config ma_channel_router_config_init(ma_uint32 channelsIn, const ma_channel channelMapIn[MA_MAX_CHANNELS], ma_uint32 channelsOut, const ma_channel channelMapOut[MA_MAX_CHANNELS], ma_channel_mix_mode mixingMode, ma_channel_router_read_deinterleaved_proc onRead, void* pUserData) +{ + ma_channel_router_config config; + ma_zero_object(&config); + + config.channelsIn = channelsIn; + for (ma_uint32 iChannel = 0; iChannel < channelsIn; ++iChannel) { + config.channelMapIn[iChannel] = channelMapIn[iChannel]; + } + + config.channelsOut = channelsOut; + for (ma_uint32 iChannel = 0; iChannel < channelsOut; ++iChannel) { + config.channelMapOut[iChannel] = channelMapOut[iChannel]; + } + + config.mixingMode = mixingMode; + config.onReadDeinterleaved = onRead; + config.pUserData = pUserData; + + return config; +} + + + +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// +// SRC +// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +#define ma_floorf(x) ((float)floor((double)(x))) +#define ma_sinf(x) ((float)sin((double)(x))) +#define ma_cosf(x) ((float)cos((double)(x))) + +static MA_INLINE double ma_sinc(double x) +{ + if (x != 0) { + return sin(MA_PI_D*x) / (MA_PI_D*x); + } else { + return 1; + } +} + +#define ma_sincf(x) ((float)ma_sinc((double)(x))) + + +ma_uint64 ma_src_read_deinterleaved__passthrough(ma_src* pSRC, ma_uint64 frameCount, void** ppSamplesOut, void* pUserData); +ma_uint64 ma_src_read_deinterleaved__linear(ma_src* pSRC, ma_uint64 frameCount, void** ppSamplesOut, void* pUserData); +ma_uint64 ma_src_read_deinterleaved__sinc(ma_src* pSRC, ma_uint64 frameCount, void** ppSamplesOut, void* pUserData); + +void ma_src__build_sinc_table__sinc(ma_src* pSRC) +{ + ma_assert(pSRC != NULL); + + pSRC->sinc.table[0] = 1.0f; + for (ma_uint32 i = 1; i < ma_countof(pSRC->sinc.table); i += 1) { + double x = i*MA_PI_D / MA_SRC_SINC_LOOKUP_TABLE_RESOLUTION; + pSRC->sinc.table[i] = (float)(sin(x)/x); + } +} + +void ma_src__build_sinc_table__rectangular(ma_src* pSRC) +{ + // This is the same as the base sinc table. + ma_src__build_sinc_table__sinc(pSRC); +} + +void ma_src__build_sinc_table__hann(ma_src* pSRC) +{ + ma_src__build_sinc_table__sinc(pSRC); + + for (ma_uint32 i = 0; i < ma_countof(pSRC->sinc.table); i += 1) { + double x = pSRC->sinc.table[i]; + double N = MA_SRC_SINC_MAX_WINDOW_WIDTH*2; + double n = ((double)(i) / MA_SRC_SINC_LOOKUP_TABLE_RESOLUTION) + MA_SRC_SINC_MAX_WINDOW_WIDTH; + double w = 0.5 * (1 - cos((2*MA_PI_D*n) / (N))); + + pSRC->sinc.table[i] = (float)(x * w); + } +} + +ma_result ma_src_init(const ma_src_config* pConfig, ma_src* pSRC) +{ + if (pSRC == NULL) { + return MA_INVALID_ARGS; + } + + ma_zero_object(pSRC); + + if (pConfig == NULL || pConfig->onReadDeinterleaved == NULL) { + return MA_INVALID_ARGS; + } + if (pConfig->channels == 0 || pConfig->channels > MA_MAX_CHANNELS) { + return MA_INVALID_ARGS; + } + + pSRC->config = *pConfig; + + // SIMD + pSRC->useSSE2 = ma_has_sse2() && !pConfig->noSSE2; + pSRC->useAVX2 = ma_has_avx2() && !pConfig->noAVX2; + pSRC->useAVX512 = ma_has_avx512f() && !pConfig->noAVX512; + pSRC->useNEON = ma_has_neon() && !pConfig->noNEON; + + if (pSRC->config.algorithm == ma_src_algorithm_sinc) { + // Make sure the window width within bounds. + if (pSRC->config.sinc.windowWidth == 0) { + pSRC->config.sinc.windowWidth = MA_SRC_SINC_DEFAULT_WINDOW_WIDTH; + } + if (pSRC->config.sinc.windowWidth < MA_SRC_SINC_MIN_WINDOW_WIDTH) { + pSRC->config.sinc.windowWidth = MA_SRC_SINC_MIN_WINDOW_WIDTH; + } + if (pSRC->config.sinc.windowWidth > MA_SRC_SINC_MAX_WINDOW_WIDTH) { + pSRC->config.sinc.windowWidth = MA_SRC_SINC_MAX_WINDOW_WIDTH; + } + + // Set up the lookup table. + switch (pSRC->config.sinc.windowFunction) { + case ma_src_sinc_window_function_hann: ma_src__build_sinc_table__hann(pSRC); break; + case ma_src_sinc_window_function_rectangular: ma_src__build_sinc_table__rectangular(pSRC); break; + default: return MA_INVALID_ARGS; // <-- Hitting this means the window function is unknown to miniaudio. + } + } + + return MA_SUCCESS; +} + +ma_result ma_src_set_sample_rate(ma_src* pSRC, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut) +{ + if (pSRC == NULL) { + return MA_INVALID_ARGS; + } + + // Must have a sample rate of > 0. + if (sampleRateIn == 0 || sampleRateOut == 0) { + return MA_INVALID_ARGS; + } + + ma_atomic_exchange_32(&pSRC->config.sampleRateIn, sampleRateIn); + ma_atomic_exchange_32(&pSRC->config.sampleRateOut, sampleRateOut); + + return MA_SUCCESS; +} + +ma_uint64 ma_src_read_deinterleaved(ma_src* pSRC, ma_uint64 frameCount, void** ppSamplesOut, void* pUserData) +{ + if (pSRC == NULL || frameCount == 0 || ppSamplesOut == NULL) { + return 0; + } + + ma_src_algorithm algorithm = pSRC->config.algorithm; + + // Can use a function pointer for this. + switch (algorithm) { + case ma_src_algorithm_none: return ma_src_read_deinterleaved__passthrough(pSRC, frameCount, ppSamplesOut, pUserData); + case ma_src_algorithm_linear: return ma_src_read_deinterleaved__linear( pSRC, frameCount, ppSamplesOut, pUserData); + case ma_src_algorithm_sinc: return ma_src_read_deinterleaved__sinc( pSRC, frameCount, ppSamplesOut, pUserData); + default: break; + } + + // Should never get here. + return 0; +} + +ma_uint64 ma_src_read_deinterleaved__passthrough(ma_src* pSRC, ma_uint64 frameCount, void** ppSamplesOut, void* pUserData) +{ + if (frameCount <= 0xFFFFFFFF) { + return pSRC->config.onReadDeinterleaved(pSRC, (ma_uint32)frameCount, ppSamplesOut, pUserData); + } else { + float* ppNextSamplesOut[MA_MAX_CHANNELS]; + for (ma_uint32 iChannel = 0; iChannel < pSRC->config.channels; ++iChannel) { + ppNextSamplesOut[iChannel] = (float*)ppSamplesOut[iChannel]; + } + + ma_uint64 totalFramesRead = 0; + while (totalFramesRead < frameCount) { + ma_uint64 framesRemaining = frameCount - totalFramesRead; + ma_uint64 framesToReadRightNow = framesRemaining; + if (framesToReadRightNow > 0xFFFFFFFF) { + framesToReadRightNow = 0xFFFFFFFF; + } + + ma_uint32 framesJustRead = (ma_uint32)pSRC->config.onReadDeinterleaved(pSRC, (ma_uint32)framesToReadRightNow, (void**)ppNextSamplesOut, pUserData); + if (framesJustRead == 0) { + break; + } + + totalFramesRead += framesJustRead; + for (ma_uint32 iChannel = 0; iChannel < pSRC->config.channels; ++iChannel) { + ppNextSamplesOut[iChannel] += framesJustRead; + } + + if (framesJustRead < framesToReadRightNow) { + break; + } + } + + return totalFramesRead; + } +} + +ma_uint64 ma_src_read_deinterleaved__linear(ma_src* pSRC, ma_uint64 frameCount, void** ppSamplesOut, void* pUserData) +{ + ma_assert(pSRC != NULL); + ma_assert(frameCount > 0); + ma_assert(ppSamplesOut != NULL); + + float* ppNextSamplesOut[MA_MAX_CHANNELS]; + ma_copy_memory(ppNextSamplesOut, ppSamplesOut, sizeof(void*) * pSRC->config.channels); + + + float factor = (float)pSRC->config.sampleRateIn / pSRC->config.sampleRateOut; + + ma_uint32 maxFrameCountPerChunkIn = ma_countof(pSRC->linear.input[0]); + + ma_uint64 totalFramesRead = 0; + while (totalFramesRead < frameCount) { + ma_uint64 framesRemaining = frameCount - totalFramesRead; + ma_uint64 framesToRead = framesRemaining; + if (framesToRead > 16384) { + framesToRead = 16384; // <-- Keep this small because we're using 32-bit floats for calculating sample positions and I don't want to run out of precision with huge sample counts. + } + + + // Read Input Data + // =============== + float tBeg = pSRC->linear.timeIn; + float tEnd = tBeg + (framesToRead*factor); + + ma_uint32 framesToReadFromClient = (ma_uint32)(tEnd) + 1 + 1; // +1 to make tEnd 1-based and +1 because we always need to an extra sample for interpolation. + if (framesToReadFromClient >= maxFrameCountPerChunkIn) { + framesToReadFromClient = maxFrameCountPerChunkIn; + } + + float* ppSamplesFromClient[MA_MAX_CHANNELS]; + for (ma_uint32 iChannel = 0; iChannel < pSRC->config.channels; ++iChannel) { + ppSamplesFromClient[iChannel] = pSRC->linear.input[iChannel] + pSRC->linear.leftoverFrames; + } + + ma_uint32 framesReadFromClient = 0; + if (framesToReadFromClient > pSRC->linear.leftoverFrames) { + framesReadFromClient = (ma_uint32)pSRC->config.onReadDeinterleaved(pSRC, (ma_uint32)framesToReadFromClient - pSRC->linear.leftoverFrames, (void**)ppSamplesFromClient, pUserData); + } + + framesReadFromClient += pSRC->linear.leftoverFrames; // <-- You can sort of think of it as though we've re-read the leftover samples from the client. + if (framesReadFromClient < 2) { + break; + } + + for (ma_uint32 iChannel = 0; iChannel < pSRC->config.channels; ++iChannel) { + ppSamplesFromClient[iChannel] = pSRC->linear.input[iChannel]; + } + + + // Write Output Data + // ================= + + // At this point we have a bunch of frames that the client has given to us for processing. From this we can determine the maximum number of output frames + // that can be processed from this input. We want to output as many samples as possible from our input data. + float tAvailable = framesReadFromClient - tBeg - 1; // Subtract 1 because the last input sample is needed for interpolation and cannot be included in the output sample count calculation. + + ma_uint32 maxOutputFramesToRead = (ma_uint32)(tAvailable / factor); + if (maxOutputFramesToRead == 0) { + maxOutputFramesToRead = 1; + } + if (maxOutputFramesToRead > framesToRead) { + maxOutputFramesToRead = (ma_uint32)framesToRead; + } + + // Output frames are always read in groups of 4 because I'm planning on using this as a reference for some SIMD-y stuff later. + ma_uint32 maxOutputFramesToRead4 = maxOutputFramesToRead/4; + for (ma_uint32 iChannel = 0; iChannel < pSRC->config.channels; ++iChannel) { + float t0 = pSRC->linear.timeIn + factor*0; + float t1 = pSRC->linear.timeIn + factor*1; + float t2 = pSRC->linear.timeIn + factor*2; + float t3 = pSRC->linear.timeIn + factor*3; + + for (ma_uint32 iFrameOut = 0; iFrameOut < maxOutputFramesToRead4; iFrameOut += 1) { + float iPrevSample0 = (float)floor(t0); + float iPrevSample1 = (float)floor(t1); + float iPrevSample2 = (float)floor(t2); + float iPrevSample3 = (float)floor(t3); + + float iNextSample0 = iPrevSample0 + 1; + float iNextSample1 = iPrevSample1 + 1; + float iNextSample2 = iPrevSample2 + 1; + float iNextSample3 = iPrevSample3 + 1; + + float alpha0 = t0 - iPrevSample0; + float alpha1 = t1 - iPrevSample1; + float alpha2 = t2 - iPrevSample2; + float alpha3 = t3 - iPrevSample3; + + float prevSample0 = ppSamplesFromClient[iChannel][(ma_uint32)iPrevSample0]; + float prevSample1 = ppSamplesFromClient[iChannel][(ma_uint32)iPrevSample1]; + float prevSample2 = ppSamplesFromClient[iChannel][(ma_uint32)iPrevSample2]; + float prevSample3 = ppSamplesFromClient[iChannel][(ma_uint32)iPrevSample3]; + + float nextSample0 = ppSamplesFromClient[iChannel][(ma_uint32)iNextSample0]; + float nextSample1 = ppSamplesFromClient[iChannel][(ma_uint32)iNextSample1]; + float nextSample2 = ppSamplesFromClient[iChannel][(ma_uint32)iNextSample2]; + float nextSample3 = ppSamplesFromClient[iChannel][(ma_uint32)iNextSample3]; + + ppNextSamplesOut[iChannel][iFrameOut*4 + 0] = ma_mix_f32_fast(prevSample0, nextSample0, alpha0); + ppNextSamplesOut[iChannel][iFrameOut*4 + 1] = ma_mix_f32_fast(prevSample1, nextSample1, alpha1); + ppNextSamplesOut[iChannel][iFrameOut*4 + 2] = ma_mix_f32_fast(prevSample2, nextSample2, alpha2); + ppNextSamplesOut[iChannel][iFrameOut*4 + 3] = ma_mix_f32_fast(prevSample3, nextSample3, alpha3); + + t0 += factor*4; + t1 += factor*4; + t2 += factor*4; + t3 += factor*4; + } + + float t = pSRC->linear.timeIn + (factor*maxOutputFramesToRead4*4); + for (ma_uint32 iFrameOut = (maxOutputFramesToRead4*4); iFrameOut < maxOutputFramesToRead; iFrameOut += 1) { + float iPrevSample = (float)floor(t); + float iNextSample = iPrevSample + 1; + float alpha = t - iPrevSample; + + ma_assert(iPrevSample < ma_countof(pSRC->linear.input[iChannel])); + ma_assert(iNextSample < ma_countof(pSRC->linear.input[iChannel])); + + float prevSample = ppSamplesFromClient[iChannel][(ma_uint32)iPrevSample]; + float nextSample = ppSamplesFromClient[iChannel][(ma_uint32)iNextSample]; + + ppNextSamplesOut[iChannel][iFrameOut] = ma_mix_f32_fast(prevSample, nextSample, alpha); + + t += factor; + } + + ppNextSamplesOut[iChannel] += maxOutputFramesToRead; + } + + totalFramesRead += maxOutputFramesToRead; + + + // Residual + // ======== + float tNext = pSRC->linear.timeIn + (maxOutputFramesToRead*factor); + + pSRC->linear.timeIn = tNext; + ma_assert(tNext <= framesReadFromClient+1); + + ma_uint32 iNextFrame = (ma_uint32)floor(tNext); + pSRC->linear.leftoverFrames = framesReadFromClient - iNextFrame; + pSRC->linear.timeIn = tNext - iNextFrame; + + for (ma_uint32 iChannel = 0; iChannel < pSRC->config.channels; ++iChannel) { + for (ma_uint32 iFrame = 0; iFrame < pSRC->linear.leftoverFrames; ++iFrame) { + float sample = ppSamplesFromClient[iChannel][framesReadFromClient-pSRC->linear.leftoverFrames + iFrame]; + ppSamplesFromClient[iChannel][iFrame] = sample; + } + } + + + // Exit the loop if we've found everything from the client. + if (framesReadFromClient < framesToReadFromClient) { + break; + } + } + + return totalFramesRead; +} + + +ma_src_config ma_src_config_init_new() +{ + ma_src_config config; + ma_zero_object(&config); + + return config; +} + +ma_src_config ma_src_config_init(ma_uint32 sampleRateIn, ma_uint32 sampleRateOut, ma_uint32 channels, ma_src_read_deinterleaved_proc onReadDeinterleaved, void* pUserData) +{ + ma_src_config config = ma_src_config_init_new(); + config.sampleRateIn = sampleRateIn; + config.sampleRateOut = sampleRateOut; + config.channels = channels; + config.onReadDeinterleaved = onReadDeinterleaved; + config.pUserData = pUserData; + + return config; +} + + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Sinc Sample Rate Conversion +// =========================== +// +// The sinc SRC algorithm uses a windowed sinc to perform interpolation of samples. Currently, miniaudio's implementation supports rectangular and Hann window +// methods. +// +// Whenever an output sample is being computed, it looks at a sub-section of the input samples. I've called this sub-section in the code below the "window", +// which I realize is a bit ambigous with the mathematical "window", but it works for me when I need to conceptualize things in my head. The window is made up +// of two halves. The first half contains past input samples (initialized to zero), and the second half contains future input samples. As time moves forward +// and input samples are consumed, the window moves forward. The larger the window, the better the quality at the expense of slower processing. The window is +// limited the range [MA_SRC_SINC_MIN_WINDOW_WIDTH, MA_SRC_SINC_MAX_WINDOW_WIDTH] and defaults to MA_SRC_SINC_DEFAULT_WINDOW_WIDTH. +// +// Input samples are cached for efficiency (to prevent frequently requesting tiny numbers of samples from the client). When the window gets to the end of the +// cache, it's moved back to the start, and more samples are read from the client. If the client has no more data to give, the cache is filled with zeros and +// the last of the input samples will be consumed. Once the last of the input samples have been consumed, no more samples will be output. +// +// +// When reading output samples, we always first read whatever is already in the input cache. Only when the cache has been fully consumed do we read more data +// from the client. +// +// To access samples in the input buffer you do so relative to the window. When the window itself is at position 0, the first item in the buffer is accessed +// with "windowPos + windowWidth". Generally, to access any sample relative to the window you do "windowPos + windowWidth + sampleIndexRelativeToWindow". +// +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +// Comment this to disable interpolation of table lookups. Less accurate, but faster. +#define MA_USE_SINC_TABLE_INTERPOLATION + +// Retrieves a sample from the input buffer's window. Values >= 0 retrieve future samples. Negative values return past samples. +static MA_INLINE float ma_src_sinc__get_input_sample_from_window(const ma_src* pSRC, ma_uint32 channel, ma_uint32 windowPosInSamples, ma_int32 sampleIndex) +{ + ma_assert(pSRC != NULL); + ma_assert(channel < pSRC->config.channels); + ma_assert(sampleIndex >= -(ma_int32)pSRC->config.sinc.windowWidth); + ma_assert(sampleIndex < (ma_int32)pSRC->config.sinc.windowWidth); + + // The window should always be contained within the input cache. + ma_assert(windowPosInSamples < ma_countof(pSRC->sinc.input[0]) - pSRC->config.sinc.windowWidth); + + return pSRC->sinc.input[channel][windowPosInSamples + pSRC->config.sinc.windowWidth + sampleIndex]; +} + +static MA_INLINE float ma_src_sinc__interpolation_factor(const ma_src* pSRC, float x) +{ + ma_assert(pSRC != NULL); + + float xabs = (float)fabs(x); + //if (xabs >= MA_SRC_SINC_MAX_WINDOW_WIDTH /*pSRC->config.sinc.windowWidth*/) { + // xabs = 1; // <-- A non-zero integer will always return 0. + //} + + xabs = xabs * MA_SRC_SINC_LOOKUP_TABLE_RESOLUTION; + ma_int32 ixabs = (ma_int32)xabs; + +#if defined(MA_USE_SINC_TABLE_INTERPOLATION) + float a = xabs - ixabs; + return ma_mix_f32_fast(pSRC->sinc.table[ixabs], pSRC->sinc.table[ixabs+1], a); +#else + return pSRC->sinc.table[ixabs]; +#endif +} + +#if defined(MA_SUPPORT_SSE2) +static MA_INLINE __m128 ma_fabsf_sse2(__m128 x) +{ + return _mm_and_ps(_mm_castsi128_ps(_mm_set1_epi32(0x7FFFFFFF)), x); +} + +static MA_INLINE __m128 ma_truncf_sse2(__m128 x) +{ + return _mm_cvtepi32_ps(_mm_cvttps_epi32(x)); +} + +static MA_INLINE __m128 ma_src_sinc__interpolation_factor__sse2(const ma_src* pSRC, __m128 x) +{ + //__m128 windowWidth128 = _mm_set1_ps(MA_SRC_SINC_MAX_WINDOW_WIDTH); + __m128 resolution128 = _mm_set1_ps(MA_SRC_SINC_LOOKUP_TABLE_RESOLUTION); + //__m128 one = _mm_set1_ps(1); + + __m128 xabs = ma_fabsf_sse2(x); + + // if (MA_SRC_SINC_MAX_WINDOW_WIDTH <= xabs) xabs = 1 else xabs = xabs; + //__m128 xcmp = _mm_cmp_ps(windowWidth128, xabs, 2); // 2 = Less than or equal = _mm_cmple_ps. + //xabs = _mm_or_ps(_mm_and_ps(one, xcmp), _mm_andnot_ps(xcmp, xabs)); // xabs = (xcmp) ? 1 : xabs; + + xabs = _mm_mul_ps(xabs, resolution128); + __m128i ixabs = _mm_cvttps_epi32(xabs); + + int* ixabsv = (int*)&ixabs; + + __m128 lo = _mm_set_ps( + pSRC->sinc.table[ixabsv[3]], + pSRC->sinc.table[ixabsv[2]], + pSRC->sinc.table[ixabsv[1]], + pSRC->sinc.table[ixabsv[0]] + ); + + __m128 hi = _mm_set_ps( + pSRC->sinc.table[ixabsv[3]+1], + pSRC->sinc.table[ixabsv[2]+1], + pSRC->sinc.table[ixabsv[1]+1], + pSRC->sinc.table[ixabsv[0]+1] + ); + + __m128 a = _mm_sub_ps(xabs, _mm_cvtepi32_ps(ixabs)); + __m128 r = ma_mix_f32_fast__sse2(lo, hi, a); + + return r; +} +#endif + +#if defined(MA_SUPPORT_AVX2) +static MA_INLINE __m256 ma_fabsf_avx2(__m256 x) +{ + return _mm256_and_ps(_mm256_castsi256_ps(_mm256_set1_epi32(0x7FFFFFFF)), x); +} + +#if 0 +static MA_INLINE __m256 ma_src_sinc__interpolation_factor__avx2(const ma_src* pSRC, __m256 x) +{ + //__m256 windowWidth256 = _mm256_set1_ps(MA_SRC_SINC_MAX_WINDOW_WIDTH); + __m256 resolution256 = _mm256_set1_ps(MA_SRC_SINC_LOOKUP_TABLE_RESOLUTION); + //__m256 one = _mm256_set1_ps(1); + + __m256 xabs = ma_fabsf_avx2(x); + + // if (MA_SRC_SINC_MAX_WINDOW_WIDTH <= xabs) xabs = 1 else xabs = xabs; + //__m256 xcmp = _mm256_cmp_ps(windowWidth256, xabs, 2); // 2 = Less than or equal = _mm_cmple_ps. + //xabs = _mm256_or_ps(_mm256_and_ps(one, xcmp), _mm256_andnot_ps(xcmp, xabs)); // xabs = (xcmp) ? 1 : xabs; + + xabs = _mm256_mul_ps(xabs, resolution256); + + __m256i ixabs = _mm256_cvttps_epi32(xabs); + __m256 a = _mm256_sub_ps(xabs, _mm256_cvtepi32_ps(ixabs)); + + + int* ixabsv = (int*)&ixabs; + + __m256 lo = _mm256_set_ps( + pSRC->sinc.table[ixabsv[7]], + pSRC->sinc.table[ixabsv[6]], + pSRC->sinc.table[ixabsv[5]], + pSRC->sinc.table[ixabsv[4]], + pSRC->sinc.table[ixabsv[3]], + pSRC->sinc.table[ixabsv[2]], + pSRC->sinc.table[ixabsv[1]], + pSRC->sinc.table[ixabsv[0]] + ); + + __m256 hi = _mm256_set_ps( + pSRC->sinc.table[ixabsv[7]+1], + pSRC->sinc.table[ixabsv[6]+1], + pSRC->sinc.table[ixabsv[5]+1], + pSRC->sinc.table[ixabsv[4]+1], + pSRC->sinc.table[ixabsv[3]+1], + pSRC->sinc.table[ixabsv[2]+1], + pSRC->sinc.table[ixabsv[1]+1], + pSRC->sinc.table[ixabsv[0]+1] + ); + + __m256 r = ma_mix_f32_fast__avx2(lo, hi, a); + + return r; +} +#endif + +#endif + +#if defined(MA_SUPPORT_NEON) +static MA_INLINE float32x4_t ma_fabsf_neon(float32x4_t x) +{ + return vabdq_f32(vmovq_n_f32(0), x); +} + +static MA_INLINE float32x4_t ma_src_sinc__interpolation_factor__neon(const ma_src* pSRC, float32x4_t x) +{ + float32x4_t xabs = ma_fabsf_neon(x); + xabs = vmulq_n_f32(xabs, MA_SRC_SINC_LOOKUP_TABLE_RESOLUTION); + + int32x4_t ixabs = vcvtq_s32_f32(xabs); + + int* ixabsv = (int*)&ixabs; + + float lo[4]; + lo[0] = pSRC->sinc.table[ixabsv[0]]; + lo[1] = pSRC->sinc.table[ixabsv[1]]; + lo[2] = pSRC->sinc.table[ixabsv[2]]; + lo[3] = pSRC->sinc.table[ixabsv[3]]; + + float hi[4]; + hi[0] = pSRC->sinc.table[ixabsv[0]+1]; + hi[1] = pSRC->sinc.table[ixabsv[1]+1]; + hi[2] = pSRC->sinc.table[ixabsv[2]+1]; + hi[3] = pSRC->sinc.table[ixabsv[3]+1]; + + float32x4_t a = vsubq_f32(xabs, vcvtq_f32_s32(ixabs)); + float32x4_t r = ma_mix_f32_fast__neon(vld1q_f32(lo), vld1q_f32(hi), a); + + return r; +} +#endif + +ma_uint64 ma_src_read_deinterleaved__sinc(ma_src* pSRC, ma_uint64 frameCount, void** ppSamplesOut, void* pUserData) +{ + ma_assert(pSRC != NULL); + ma_assert(frameCount > 0); + ma_assert(ppSamplesOut != NULL); + + float factor = (float)pSRC->config.sampleRateIn / pSRC->config.sampleRateOut; + float inverseFactor = 1/factor; + + ma_int32 windowWidth = (ma_int32)pSRC->config.sinc.windowWidth; + ma_int32 windowWidth2 = windowWidth*2; + + // There are cases where it's actually more efficient to increase the window width so that it's aligned with the respective + // SIMD pipeline being used. + ma_int32 windowWidthSIMD = windowWidth; + if (pSRC->useNEON) { + windowWidthSIMD = (windowWidthSIMD + 1) & ~(1); + } else if (pSRC->useAVX512) { + windowWidthSIMD = (windowWidthSIMD + 7) & ~(7); + } else if (pSRC->useAVX2) { + windowWidthSIMD = (windowWidthSIMD + 3) & ~(3); + } else if (pSRC->useSSE2) { + windowWidthSIMD = (windowWidthSIMD + 1) & ~(1); + } + + ma_int32 windowWidthSIMD2 = windowWidthSIMD*2; + (void)windowWidthSIMD2; // <-- Silence a warning when SIMD is disabled. + + float* ppNextSamplesOut[MA_MAX_CHANNELS]; + ma_copy_memory(ppNextSamplesOut, ppSamplesOut, sizeof(void*) * pSRC->config.channels); + + float _windowSamplesUnaligned[MA_SRC_SINC_MAX_WINDOW_WIDTH*2 + MA_SIMD_ALIGNMENT]; + float* windowSamples = (float*)(((ma_uintptr)_windowSamplesUnaligned + MA_SIMD_ALIGNMENT-1) & ~(MA_SIMD_ALIGNMENT-1)); + ma_zero_memory(windowSamples, MA_SRC_SINC_MAX_WINDOW_WIDTH*2 * sizeof(float)); + + float _iWindowFUnaligned[MA_SRC_SINC_MAX_WINDOW_WIDTH*2 + MA_SIMD_ALIGNMENT]; + float* iWindowF = (float*)(((ma_uintptr)_iWindowFUnaligned + MA_SIMD_ALIGNMENT-1) & ~(MA_SIMD_ALIGNMENT-1)); + ma_zero_memory(iWindowF, MA_SRC_SINC_MAX_WINDOW_WIDTH*2 * sizeof(float)); + for (ma_int32 i = 0; i < windowWidth2; ++i) { + iWindowF[i] = (float)(i - windowWidth); + } + + ma_uint64 totalOutputFramesRead = 0; + while (totalOutputFramesRead < frameCount) { + // The maximum number of frames we can read this iteration depends on how many input samples we have available to us. This is the number + // of input samples between the end of the window and the end of the cache. + ma_uint32 maxInputSamplesAvailableInCache = ma_countof(pSRC->sinc.input[0]) - (pSRC->config.sinc.windowWidth*2) - pSRC->sinc.windowPosInSamples; + if (maxInputSamplesAvailableInCache > pSRC->sinc.inputFrameCount) { + maxInputSamplesAvailableInCache = pSRC->sinc.inputFrameCount; + } + + // Never consume the tail end of the input data if requested. + if (pSRC->config.neverConsumeEndOfInput) { + if (maxInputSamplesAvailableInCache >= pSRC->config.sinc.windowWidth) { + maxInputSamplesAvailableInCache -= pSRC->config.sinc.windowWidth; + } else { + maxInputSamplesAvailableInCache = 0; + } + } + + float timeInBeg = pSRC->sinc.timeIn; + float timeInEnd = (float)(pSRC->sinc.windowPosInSamples + maxInputSamplesAvailableInCache); + + ma_assert(timeInBeg >= 0); + ma_assert(timeInBeg <= timeInEnd); + + ma_uint64 maxOutputFramesToRead = (ma_uint64)(((timeInEnd - timeInBeg) * inverseFactor)); + + ma_uint64 outputFramesRemaining = frameCount - totalOutputFramesRead; + ma_uint64 outputFramesToRead = outputFramesRemaining; + if (outputFramesToRead > maxOutputFramesToRead) { + outputFramesToRead = maxOutputFramesToRead; + } + + for (ma_uint32 iChannel = 0; iChannel < pSRC->config.channels; iChannel += 1) { + // Do SRC. + float timeIn = timeInBeg; + for (ma_uint32 iSample = 0; iSample < outputFramesToRead; iSample += 1) { + float sampleOut = 0; + float iTimeInF = ma_floorf(timeIn); + ma_uint32 iTimeIn = (ma_uint32)iTimeInF; + + ma_int32 iWindow = 0; + + // Pre-load the window samples into an aligned buffer to begin with. Need to put these into an aligned buffer to make SIMD easier. + windowSamples[0] = 0; // <-- The first sample is always zero. + for (ma_int32 i = 1; i < windowWidth2; ++i) { + windowSamples[i] = pSRC->sinc.input[iChannel][iTimeIn + i]; + } + +#if defined(MA_SUPPORT_AVX2) || defined(MA_SUPPORT_AVX512) + if (pSRC->useAVX2 || pSRC->useAVX512) { + __m256i ixabs[MA_SRC_SINC_MAX_WINDOW_WIDTH*2/8]; + __m256 a[MA_SRC_SINC_MAX_WINDOW_WIDTH*2/8]; + __m256 resolution256 = _mm256_set1_ps(MA_SRC_SINC_LOOKUP_TABLE_RESOLUTION); + + __m256 t = _mm256_set1_ps((timeIn - iTimeInF)); + __m256 r = _mm256_set1_ps(0); + + ma_int32 windowWidth8 = windowWidthSIMD2 >> 3; + for (ma_int32 iWindow8 = 0; iWindow8 < windowWidth8; iWindow8 += 1) { + __m256 w = *((__m256*)iWindowF + iWindow8); + + __m256 xabs = _mm256_sub_ps(t, w); + xabs = ma_fabsf_avx2(xabs); + xabs = _mm256_mul_ps(xabs, resolution256); + + ixabs[iWindow8] = _mm256_cvttps_epi32(xabs); + a[iWindow8] = _mm256_sub_ps(xabs, _mm256_cvtepi32_ps(ixabs[iWindow8])); + } + + for (ma_int32 iWindow8 = 0; iWindow8 < windowWidth8; iWindow8 += 1) { + int* ixabsv = (int*)&ixabs[iWindow8]; + + __m256 lo = _mm256_set_ps( + pSRC->sinc.table[ixabsv[7]], + pSRC->sinc.table[ixabsv[6]], + pSRC->sinc.table[ixabsv[5]], + pSRC->sinc.table[ixabsv[4]], + pSRC->sinc.table[ixabsv[3]], + pSRC->sinc.table[ixabsv[2]], + pSRC->sinc.table[ixabsv[1]], + pSRC->sinc.table[ixabsv[0]] + ); + + __m256 hi = _mm256_set_ps( + pSRC->sinc.table[ixabsv[7]+1], + pSRC->sinc.table[ixabsv[6]+1], + pSRC->sinc.table[ixabsv[5]+1], + pSRC->sinc.table[ixabsv[4]+1], + pSRC->sinc.table[ixabsv[3]+1], + pSRC->sinc.table[ixabsv[2]+1], + pSRC->sinc.table[ixabsv[1]+1], + pSRC->sinc.table[ixabsv[0]+1] + ); + + __m256 s = *((__m256*)windowSamples + iWindow8); + r = _mm256_add_ps(r, _mm256_mul_ps(s, ma_mix_f32_fast__avx2(lo, hi, a[iWindow8]))); + } + + // Horizontal add. + __m256 x = _mm256_hadd_ps(r, _mm256_permute2f128_ps(r, r, 1)); + x = _mm256_hadd_ps(x, x); + x = _mm256_hadd_ps(x, x); + sampleOut += _mm_cvtss_f32(_mm256_castps256_ps128(x)); + + iWindow += windowWidth8 * 8; + } + else +#endif +#if defined(MA_SUPPORT_SSE2) + if (pSRC->useSSE2) { + __m128 t = _mm_set1_ps((timeIn - iTimeInF)); + __m128 r = _mm_set1_ps(0); + + ma_int32 windowWidth4 = windowWidthSIMD2 >> 2; + for (ma_int32 iWindow4 = 0; iWindow4 < windowWidth4; iWindow4 += 1) { + __m128* s = (__m128*)windowSamples + iWindow4; + __m128* w = (__m128*)iWindowF + iWindow4; + + __m128 a = ma_src_sinc__interpolation_factor__sse2(pSRC, _mm_sub_ps(t, *w)); + r = _mm_add_ps(r, _mm_mul_ps(*s, a)); + } + + sampleOut += ((float*)(&r))[0]; + sampleOut += ((float*)(&r))[1]; + sampleOut += ((float*)(&r))[2]; + sampleOut += ((float*)(&r))[3]; + + iWindow += windowWidth4 * 4; + } + else +#endif +#if defined(MA_SUPPORT_NEON) + if (pSRC->useNEON) { + float32x4_t t = vmovq_n_f32((timeIn - iTimeInF)); + float32x4_t r = vmovq_n_f32(0); + + ma_int32 windowWidth4 = windowWidthSIMD2 >> 2; + for (ma_int32 iWindow4 = 0; iWindow4 < windowWidth4; iWindow4 += 1) { + float32x4_t* s = (float32x4_t*)windowSamples + iWindow4; + float32x4_t* w = (float32x4_t*)iWindowF + iWindow4; + + float32x4_t a = ma_src_sinc__interpolation_factor__neon(pSRC, vsubq_f32(t, *w)); + r = vaddq_f32(r, vmulq_f32(*s, a)); + } + + sampleOut += ((float*)(&r))[0]; + sampleOut += ((float*)(&r))[1]; + sampleOut += ((float*)(&r))[2]; + sampleOut += ((float*)(&r))[3]; + + iWindow += windowWidth4 * 4; + } + else +#endif + { + iWindow += 1; // The first one is a dummy for SIMD alignment purposes. Skip it. + } + + // Non-SIMD/Reference implementation. + float t = (timeIn - iTimeIn); + for (; iWindow < windowWidth2; iWindow += 1) { + float s = windowSamples[iWindow]; + float w = iWindowF[iWindow]; + + float a = ma_src_sinc__interpolation_factor(pSRC, (t - w)); + float r = s * a; + + sampleOut += r; + } + + ppNextSamplesOut[iChannel][iSample] = (float)sampleOut; + + timeIn += factor; + } + + ppNextSamplesOut[iChannel] += outputFramesToRead; + } + + totalOutputFramesRead += outputFramesToRead; + + ma_uint32 prevWindowPosInSamples = pSRC->sinc.windowPosInSamples; + + pSRC->sinc.timeIn += (outputFramesToRead * factor); + pSRC->sinc.windowPosInSamples = (ma_uint32)pSRC->sinc.timeIn; + pSRC->sinc.inputFrameCount -= pSRC->sinc.windowPosInSamples - prevWindowPosInSamples; + + // If the window has reached a point where we cannot read a whole output sample it needs to be moved back to the start. + ma_uint32 availableOutputFrames = (ma_uint32)((timeInEnd - pSRC->sinc.timeIn) * inverseFactor); + + if (availableOutputFrames == 0) { + size_t samplesToMove = ma_countof(pSRC->sinc.input[0]) - pSRC->sinc.windowPosInSamples; + + pSRC->sinc.timeIn -= ma_floorf(pSRC->sinc.timeIn); + pSRC->sinc.windowPosInSamples = 0; + + // Move everything from the end of the cache up to the front. + for (ma_uint32 iChannel = 0; iChannel < pSRC->config.channels; iChannel += 1) { + memmove(pSRC->sinc.input[iChannel], pSRC->sinc.input[iChannel] + ma_countof(pSRC->sinc.input[iChannel]) - samplesToMove, samplesToMove * sizeof(*pSRC->sinc.input[iChannel])); + } + } + + // Read more data from the client if required. + if (pSRC->isEndOfInputLoaded) { + pSRC->isEndOfInputLoaded = MA_FALSE; + break; + } + + // Everything beyond this point is reloading. If we're at the end of the input data we do _not_ want to try reading any more in this function call. If the + // caller wants to keep trying, they can reload their internal data sources and call this function again. We should never be + ma_assert(pSRC->isEndOfInputLoaded == MA_FALSE); + + if (pSRC->sinc.inputFrameCount <= pSRC->config.sinc.windowWidth || availableOutputFrames == 0) { + float* ppInputDst[MA_MAX_CHANNELS] = {0}; + for (ma_uint32 iChannel = 0; iChannel < pSRC->config.channels; iChannel += 1) { + ppInputDst[iChannel] = pSRC->sinc.input[iChannel] + pSRC->config.sinc.windowWidth + pSRC->sinc.inputFrameCount; + } + + // Now read data from the client. + ma_uint32 framesToReadFromClient = ma_countof(pSRC->sinc.input[0]) - (pSRC->config.sinc.windowWidth + pSRC->sinc.inputFrameCount); + + ma_uint32 framesReadFromClient = 0; + if (framesToReadFromClient > 0) { + framesReadFromClient = pSRC->config.onReadDeinterleaved(pSRC, framesToReadFromClient, (void**)ppInputDst, pUserData); + } + + if (framesReadFromClient != framesToReadFromClient) { + pSRC->isEndOfInputLoaded = MA_TRUE; + } else { + pSRC->isEndOfInputLoaded = MA_FALSE; + } + + if (framesReadFromClient != 0) { + pSRC->sinc.inputFrameCount += framesReadFromClient; + } else { + // We couldn't get anything more from the client. If no more output samples can be computed from the available input samples + // we need to return. + if (pSRC->config.neverConsumeEndOfInput) { + if ((pSRC->sinc.inputFrameCount * inverseFactor) <= pSRC->config.sinc.windowWidth) { + break; + } + } else { + if ((pSRC->sinc.inputFrameCount * inverseFactor) < 1) { + break; + } + } + } + + // Anything left over in the cache must be set to zero. + ma_uint32 leftoverFrames = ma_countof(pSRC->sinc.input[0]) - (pSRC->config.sinc.windowWidth + pSRC->sinc.inputFrameCount); + if (leftoverFrames > 0) { + for (ma_uint32 iChannel = 0; iChannel < pSRC->config.channels; iChannel += 1) { + ma_zero_memory(pSRC->sinc.input[iChannel] + pSRC->config.sinc.windowWidth + pSRC->sinc.inputFrameCount, leftoverFrames * sizeof(float)); + } + } + } + } + + return totalOutputFramesRead; +} + + + +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// +// FORMAT CONVERSION +// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +void ma_pcm_convert(void* pOut, ma_format formatOut, const void* pIn, ma_format formatIn, ma_uint64 sampleCount, ma_dither_mode ditherMode) +{ + if (formatOut == formatIn) { + ma_copy_memory_64(pOut, pIn, sampleCount * ma_get_bytes_per_sample(formatOut)); + return; + } + + switch (formatIn) + { + case ma_format_u8: + { + switch (formatOut) + { + case ma_format_s16: ma_pcm_u8_to_s16(pOut, pIn, sampleCount, ditherMode); return; + case ma_format_s24: ma_pcm_u8_to_s24(pOut, pIn, sampleCount, ditherMode); return; + case ma_format_s32: ma_pcm_u8_to_s32(pOut, pIn, sampleCount, ditherMode); return; + case ma_format_f32: ma_pcm_u8_to_f32(pOut, pIn, sampleCount, ditherMode); return; + default: break; + } + } break; + + case ma_format_s16: + { + switch (formatOut) + { + case ma_format_u8: ma_pcm_s16_to_u8( pOut, pIn, sampleCount, ditherMode); return; + case ma_format_s24: ma_pcm_s16_to_s24(pOut, pIn, sampleCount, ditherMode); return; + case ma_format_s32: ma_pcm_s16_to_s32(pOut, pIn, sampleCount, ditherMode); return; + case ma_format_f32: ma_pcm_s16_to_f32(pOut, pIn, sampleCount, ditherMode); return; + default: break; + } + } break; + + case ma_format_s24: + { + switch (formatOut) + { + case ma_format_u8: ma_pcm_s24_to_u8( pOut, pIn, sampleCount, ditherMode); return; + case ma_format_s16: ma_pcm_s24_to_s16(pOut, pIn, sampleCount, ditherMode); return; + case ma_format_s32: ma_pcm_s24_to_s32(pOut, pIn, sampleCount, ditherMode); return; + case ma_format_f32: ma_pcm_s24_to_f32(pOut, pIn, sampleCount, ditherMode); return; + default: break; + } + } break; + + case ma_format_s32: + { + switch (formatOut) + { + case ma_format_u8: ma_pcm_s32_to_u8( pOut, pIn, sampleCount, ditherMode); return; + case ma_format_s16: ma_pcm_s32_to_s16(pOut, pIn, sampleCount, ditherMode); return; + case ma_format_s24: ma_pcm_s32_to_s24(pOut, pIn, sampleCount, ditherMode); return; + case ma_format_f32: ma_pcm_s32_to_f32(pOut, pIn, sampleCount, ditherMode); return; + default: break; + } + } break; + + case ma_format_f32: + { + switch (formatOut) + { + case ma_format_u8: ma_pcm_f32_to_u8( pOut, pIn, sampleCount, ditherMode); return; + case ma_format_s16: ma_pcm_f32_to_s16(pOut, pIn, sampleCount, ditherMode); return; + case ma_format_s24: ma_pcm_f32_to_s24(pOut, pIn, sampleCount, ditherMode); return; + case ma_format_s32: ma_pcm_f32_to_s32(pOut, pIn, sampleCount, ditherMode); return; + default: break; + } + } break; + + default: break; + } +} + +void ma_deinterleave_pcm_frames(ma_format format, ma_uint32 channels, ma_uint64 frameCount, const void* pInterleavedPCMFrames, void** ppDeinterleavedPCMFrames) +{ + if (pInterleavedPCMFrames == NULL || ppDeinterleavedPCMFrames == NULL) { + return; // Invalid args. + } + + // For efficiency we do this per format. + switch (format) { + case ma_format_s16: + { + const ma_int16* pSrcS16 = (const ma_int16*)pInterleavedPCMFrames; + for (ma_uint64 iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) { + for (ma_uint32 iChannel = 0; iChannel < channels; ++iChannel) { + ma_int16* pDstS16 = (ma_int16*)ppDeinterleavedPCMFrames[iChannel]; + pDstS16[iPCMFrame] = pSrcS16[iPCMFrame*channels+iChannel]; + } + } + } break; + + case ma_format_f32: + { + const float* pSrcF32 = (const float*)pInterleavedPCMFrames; + for (ma_uint64 iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) { + for (ma_uint32 iChannel = 0; iChannel < channels; ++iChannel) { + float* pDstF32 = (float*)ppDeinterleavedPCMFrames[iChannel]; + pDstF32[iPCMFrame] = pSrcF32[iPCMFrame*channels+iChannel]; + } + } + } break; + + default: + { + ma_uint32 sampleSizeInBytes = ma_get_bytes_per_sample(format); + + for (ma_uint64 iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) { + for (ma_uint32 iChannel = 0; iChannel < channels; ++iChannel) { + void* pDst = ma_offset_ptr(ppDeinterleavedPCMFrames[iChannel], iPCMFrame*sampleSizeInBytes); + const void* pSrc = ma_offset_ptr(pInterleavedPCMFrames, (iPCMFrame*channels+iChannel)*sampleSizeInBytes); + memcpy(pDst, pSrc, sampleSizeInBytes); + } + } + } break; + } +} + +void ma_interleave_pcm_frames(ma_format format, ma_uint32 channels, ma_uint64 frameCount, const void** ppDeinterleavedPCMFrames, void* pInterleavedPCMFrames) +{ + switch (format) + { + case ma_format_s16: + { + ma_int16* pDstS16 = (ma_int16*)pInterleavedPCMFrames; + for (ma_uint64 iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) { + for (ma_uint32 iChannel = 0; iChannel < channels; ++iChannel) { + const ma_int16* pSrcS16 = (const ma_int16*)ppDeinterleavedPCMFrames[iChannel]; + pDstS16[iPCMFrame*channels+iChannel] = pSrcS16[iPCMFrame]; + } + } + } break; + + case ma_format_f32: + { + float* pDstF32 = (float*)pInterleavedPCMFrames; + for (ma_uint64 iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) { + for (ma_uint32 iChannel = 0; iChannel < channels; ++iChannel) { + const float* pSrcF32 = (const float*)ppDeinterleavedPCMFrames[iChannel]; + pDstF32[iPCMFrame*channels+iChannel] = pSrcF32[iPCMFrame]; + } + } + } break; + + default: + { + ma_uint32 sampleSizeInBytes = ma_get_bytes_per_sample(format); + + for (ma_uint64 iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) { + for (ma_uint32 iChannel = 0; iChannel < channels; ++iChannel) { + void* pDst = ma_offset_ptr(pInterleavedPCMFrames, (iPCMFrame*channels+iChannel)*sampleSizeInBytes); + const void* pSrc = ma_offset_ptr(ppDeinterleavedPCMFrames[iChannel], iPCMFrame*sampleSizeInBytes); + memcpy(pDst, pSrc, sampleSizeInBytes); + } + } + } break; + } +} + + + +typedef struct +{ + ma_pcm_converter* pDSP; + void* pUserDataForClient; +} ma_pcm_converter_callback_data; + +ma_uint32 ma_pcm_converter__pre_format_converter_on_read(ma_format_converter* pConverter, ma_uint32 frameCount, void* pFramesOut, void* pUserData) +{ + (void)pConverter; + + ma_pcm_converter_callback_data* pData = (ma_pcm_converter_callback_data*)pUserData; + ma_assert(pData != NULL); + + ma_pcm_converter* pDSP = pData->pDSP; + ma_assert(pDSP != NULL); + + return pDSP->onRead(pDSP, pFramesOut, frameCount, pData->pUserDataForClient); +} + +ma_uint32 ma_pcm_converter__post_format_converter_on_read(ma_format_converter* pConverter, ma_uint32 frameCount, void* pFramesOut, void* pUserData) +{ + (void)pConverter; + + ma_pcm_converter_callback_data* pData = (ma_pcm_converter_callback_data*)pUserData; + ma_assert(pData != NULL); + + ma_pcm_converter* pDSP = pData->pDSP; + ma_assert(pDSP != NULL); + + // When this version of this callback is used it means we're reading directly from the client. + ma_assert(pDSP->isPreFormatConversionRequired == MA_FALSE); + ma_assert(pDSP->isChannelRoutingRequired == MA_FALSE); + ma_assert(pDSP->isSRCRequired == MA_FALSE); + + return pDSP->onRead(pDSP, pFramesOut, frameCount, pData->pUserDataForClient); +} + +ma_uint32 ma_pcm_converter__post_format_converter_on_read_deinterleaved(ma_format_converter* pConverter, ma_uint32 frameCount, void** ppSamplesOut, void* pUserData) +{ + (void)pConverter; + + ma_pcm_converter_callback_data* pData = (ma_pcm_converter_callback_data*)pUserData; + ma_assert(pData != NULL); + + ma_pcm_converter* pDSP = pData->pDSP; + ma_assert(pDSP != NULL); + + if (!pDSP->isChannelRoutingAtStart) { + return (ma_uint32)ma_channel_router_read_deinterleaved(&pDSP->channelRouter, frameCount, ppSamplesOut, pUserData); + } else { + if (pDSP->isSRCRequired) { + return (ma_uint32)ma_src_read_deinterleaved(&pDSP->src, frameCount, ppSamplesOut, pUserData); + } else { + return (ma_uint32)ma_channel_router_read_deinterleaved(&pDSP->channelRouter, frameCount, ppSamplesOut, pUserData); + } + } +} + +ma_uint32 ma_pcm_converter__src_on_read_deinterleaved(ma_src* pSRC, ma_uint32 frameCount, void** ppSamplesOut, void* pUserData) +{ + (void)pSRC; + + ma_pcm_converter_callback_data* pData = (ma_pcm_converter_callback_data*)pUserData; + ma_assert(pData != NULL); + + ma_pcm_converter* pDSP = pData->pDSP; + ma_assert(pDSP != NULL); + + // If the channel routing stage is at the front we need to read from that. Otherwise we read from the pre format converter. + if (pDSP->isChannelRoutingAtStart) { + return (ma_uint32)ma_channel_router_read_deinterleaved(&pDSP->channelRouter, frameCount, ppSamplesOut, pUserData); + } else { + return (ma_uint32)ma_format_converter_read_deinterleaved(&pDSP->formatConverterIn, frameCount, ppSamplesOut, pUserData); + } +} + +ma_uint32 ma_pcm_converter__channel_router_on_read_deinterleaved(ma_channel_router* pRouter, ma_uint32 frameCount, void** ppSamplesOut, void* pUserData) +{ + (void)pRouter; + + ma_pcm_converter_callback_data* pData = (ma_pcm_converter_callback_data*)pUserData; + ma_assert(pData != NULL); + + ma_pcm_converter* pDSP = pData->pDSP; + ma_assert(pDSP != NULL); + + // If the channel routing stage is at the front of the pipeline we read from the pre format converter. Otherwise we read from the sample rate converter. + if (pDSP->isChannelRoutingAtStart) { + return (ma_uint32)ma_format_converter_read_deinterleaved(&pDSP->formatConverterIn, frameCount, ppSamplesOut, pUserData); + } else { + if (pDSP->isSRCRequired) { + return (ma_uint32)ma_src_read_deinterleaved(&pDSP->src, frameCount, ppSamplesOut, pUserData); + } else { + return (ma_uint32)ma_format_converter_read_deinterleaved(&pDSP->formatConverterIn, frameCount, ppSamplesOut, pUserData); + } + } +} + +ma_result ma_pcm_converter_init(const ma_pcm_converter_config* pConfig, ma_pcm_converter* pDSP) +{ + if (pDSP == NULL) { + return MA_INVALID_ARGS; + } + + ma_zero_object(pDSP); + pDSP->onRead = pConfig->onRead; + pDSP->pUserData = pConfig->pUserData; + pDSP->isDynamicSampleRateAllowed = pConfig->allowDynamicSampleRate; + + + // In general, this is the pipeline used for data conversion. Note that this can actually change which is explained later. + // + // Pre Format Conversion -> Sample Rate Conversion -> Channel Routing -> Post Format Conversion + // + // Pre Format Conversion + // --------------------- + // This is where the sample data is converted to a format that's usable by the later stages in the pipeline. Input data + // is converted to deinterleaved floating-point. + // + // Channel Routing + // --------------- + // Channel routing is where stereo is converted to 5.1, mono is converted to stereo, etc. This stage depends on the + // pre format conversion stage. + // + // Sample Rate Conversion + // ---------------------- + // Sample rate conversion depends on the pre format conversion stage and as the name implies performs sample rate conversion. + // + // Post Format Conversion + // ---------------------- + // This stage is where our deinterleaved floating-point data from the previous stages are converted to the requested output + // format. + // + // + // Optimizations + // ------------- + // Sometimes the conversion pipeline is rearranged for efficiency. The first obvious optimization is to eliminate unnecessary + // stages in the pipeline. When no channel routing nor sample rate conversion is necessary, the entire pipeline is optimized + // down to just this: + // + // Post Format Conversion + // + // When sample rate conversion is not unnecessary: + // + // Pre Format Conversion -> Channel Routing -> Post Format Conversion + // + // When channel routing is unnecessary: + // + // Pre Format Conversion -> Sample Rate Conversion -> Post Format Conversion + // + // A slightly less obvious optimization is used depending on whether or not we are increasing or decreasing the number of + // channels. Because everything in the pipeline works on a per-channel basis, the efficiency of the pipeline is directly + // proportionate to the number of channels that need to be processed. Therefore, it's can be more efficient to move the + // channel conversion stage to an earlier or later stage. When the channel count is being reduced, we move the channel + // conversion stage to the start of the pipeline so that later stages can work on a smaller number of channels at a time. + // Otherwise, we move the channel conversion stage to the end of the pipeline. When reducing the channel count, the pipeline + // will look like this: + // + // Pre Format Conversion -> Channel Routing -> Sample Rate Conversion -> Post Format Conversion + // + // Notice how the Channel Routing and Sample Rate Conversion stages are swapped so that the SRC stage has less data to process. + + // First we need to determine what's required and what's not. + if (pConfig->sampleRateIn != pConfig->sampleRateOut || pConfig->allowDynamicSampleRate) { + pDSP->isSRCRequired = MA_TRUE; + } + if (pConfig->channelsIn != pConfig->channelsOut || !ma_channel_map_equal(pConfig->channelsIn, pConfig->channelMapIn, pConfig->channelMapOut)) { + pDSP->isChannelRoutingRequired = MA_TRUE; + } + + // If neither a sample rate conversion nor channel conversion is necessary we can skip the pre format conversion. + if (!pDSP->isSRCRequired && !pDSP->isChannelRoutingRequired) { + // We don't need a pre format conversion stage, but we may still need a post format conversion stage. + if (pConfig->formatIn != pConfig->formatOut) { + pDSP->isPostFormatConversionRequired = MA_TRUE; + } + } else { + pDSP->isPreFormatConversionRequired = MA_TRUE; + pDSP->isPostFormatConversionRequired = MA_TRUE; + } + + // Use a passthrough if none of the stages are being used. + if (!pDSP->isPreFormatConversionRequired && !pDSP->isPostFormatConversionRequired && !pDSP->isChannelRoutingRequired && !pDSP->isSRCRequired) { + pDSP->isPassthrough = MA_TRUE; + } + + // Move the channel conversion stage to the start of the pipeline if we are reducing the channel count. + if (pConfig->channelsOut < pConfig->channelsIn) { + pDSP->isChannelRoutingAtStart = MA_TRUE; + } + + + // We always initialize every stage of the pipeline regardless of whether or not the stage is used because it simplifies + // a few things when it comes to dynamically changing properties post-initialization. + ma_result result = MA_SUCCESS; + + // Pre format conversion. + { + ma_format_converter_config preFormatConverterConfig = ma_format_converter_config_init( + pConfig->formatIn, + ma_format_f32, + pConfig->channelsIn, + ma_pcm_converter__pre_format_converter_on_read, + pDSP + ); + preFormatConverterConfig.ditherMode = pConfig->ditherMode; + preFormatConverterConfig.noSSE2 = pConfig->noSSE2; + preFormatConverterConfig.noAVX2 = pConfig->noAVX2; + preFormatConverterConfig.noAVX512 = pConfig->noAVX512; + preFormatConverterConfig.noNEON = pConfig->noNEON; + + result = ma_format_converter_init(&preFormatConverterConfig, &pDSP->formatConverterIn); + if (result != MA_SUCCESS) { + return result; + } + } + + // Post format conversion. The exact configuration for this depends on whether or not we are reading data directly from the client + // or from an earlier stage in the pipeline. + { + ma_format_converter_config postFormatConverterConfig = ma_format_converter_config_init_new(); + postFormatConverterConfig.formatIn = pConfig->formatIn; + postFormatConverterConfig.formatOut = pConfig->formatOut; + postFormatConverterConfig.channels = pConfig->channelsOut; + postFormatConverterConfig.ditherMode = pConfig->ditherMode; + postFormatConverterConfig.noSSE2 = pConfig->noSSE2; + postFormatConverterConfig.noAVX2 = pConfig->noAVX2; + postFormatConverterConfig.noAVX512 = pConfig->noAVX512; + postFormatConverterConfig.noNEON = pConfig->noNEON; + if (pDSP->isPreFormatConversionRequired) { + postFormatConverterConfig.onReadDeinterleaved = ma_pcm_converter__post_format_converter_on_read_deinterleaved; + postFormatConverterConfig.formatIn = ma_format_f32; + } else { + postFormatConverterConfig.onRead = ma_pcm_converter__post_format_converter_on_read; + } + + result = ma_format_converter_init(&postFormatConverterConfig, &pDSP->formatConverterOut); + if (result != MA_SUCCESS) { + return result; + } + } + + // SRC + { + ma_src_config srcConfig = ma_src_config_init( + pConfig->sampleRateIn, + pConfig->sampleRateOut, + ((pConfig->channelsIn < pConfig->channelsOut) ? pConfig->channelsIn : pConfig->channelsOut), + ma_pcm_converter__src_on_read_deinterleaved, + pDSP + ); + srcConfig.algorithm = pConfig->srcAlgorithm; + srcConfig.neverConsumeEndOfInput = pConfig->neverConsumeEndOfInput; + srcConfig.noSSE2 = pConfig->noSSE2; + srcConfig.noAVX2 = pConfig->noAVX2; + srcConfig.noAVX512 = pConfig->noAVX512; + srcConfig.noNEON = pConfig->noNEON; + ma_copy_memory(&srcConfig.sinc, &pConfig->sinc, sizeof(pConfig->sinc)); + + result = ma_src_init(&srcConfig, &pDSP->src); + if (result != MA_SUCCESS) { + return result; + } + } + + // Channel conversion + { + ma_channel_router_config routerConfig = ma_channel_router_config_init( + pConfig->channelsIn, + pConfig->channelMapIn, + pConfig->channelsOut, + pConfig->channelMapOut, + pConfig->channelMixMode, + ma_pcm_converter__channel_router_on_read_deinterleaved, + pDSP); + routerConfig.noSSE2 = pConfig->noSSE2; + routerConfig.noAVX2 = pConfig->noAVX2; + routerConfig.noAVX512 = pConfig->noAVX512; + routerConfig.noNEON = pConfig->noNEON; + + result = ma_channel_router_init(&routerConfig, &pDSP->channelRouter); + if (result != MA_SUCCESS) { + return result; + } + } + + return MA_SUCCESS; +} + + +ma_result ma_pcm_converter_refresh_sample_rate(ma_pcm_converter* pDSP) +{ + // The SRC stage will already have been initialized so we can just set it there. + ma_src_set_sample_rate(&pDSP->src, pDSP->src.config.sampleRateIn, pDSP->src.config.sampleRateOut); + return MA_SUCCESS; +} + +ma_result ma_pcm_converter_set_input_sample_rate(ma_pcm_converter* pDSP, ma_uint32 sampleRateIn) +{ + if (pDSP == NULL) { + return MA_INVALID_ARGS; + } + + // Must have a sample rate of > 0. + if (sampleRateIn == 0) { + return MA_INVALID_ARGS; + } + + // Must have been initialized with allowDynamicSampleRate. + if (!pDSP->isDynamicSampleRateAllowed) { + return MA_INVALID_OPERATION; + } + + ma_atomic_exchange_32(&pDSP->src.config.sampleRateIn, sampleRateIn); + return ma_pcm_converter_refresh_sample_rate(pDSP); +} + +ma_result ma_pcm_converter_set_output_sample_rate(ma_pcm_converter* pDSP, ma_uint32 sampleRateOut) +{ + if (pDSP == NULL) { + return MA_INVALID_ARGS; + } + + // Must have a sample rate of > 0. + if (sampleRateOut == 0) { + return MA_INVALID_ARGS; + } + + // Must have been initialized with allowDynamicSampleRate. + if (!pDSP->isDynamicSampleRateAllowed) { + return MA_INVALID_OPERATION; + } + + ma_atomic_exchange_32(&pDSP->src.config.sampleRateOut, sampleRateOut); + return ma_pcm_converter_refresh_sample_rate(pDSP); +} + +ma_result ma_pcm_converter_set_sample_rate(ma_pcm_converter* pDSP, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut) +{ + if (pDSP == NULL) { + return MA_INVALID_ARGS; + } + + // Must have a sample rate of > 0. + if (sampleRateIn == 0 || sampleRateOut == 0) { + return MA_INVALID_ARGS; + } + + // Must have been initialized with allowDynamicSampleRate. + if (!pDSP->isDynamicSampleRateAllowed) { + return MA_INVALID_OPERATION; + } + + ma_atomic_exchange_32(&pDSP->src.config.sampleRateIn, sampleRateIn); + ma_atomic_exchange_32(&pDSP->src.config.sampleRateOut, sampleRateOut); + + return ma_pcm_converter_refresh_sample_rate(pDSP); +} + +ma_uint64 ma_pcm_converter_read(ma_pcm_converter* pDSP, void* pFramesOut, ma_uint64 frameCount) +{ + if (pDSP == NULL || pFramesOut == NULL) { + return 0; + } + + // Fast path. + if (pDSP->isPassthrough) { + if (frameCount <= 0xFFFFFFFF) { + return (ma_uint32)pDSP->onRead(pDSP, pFramesOut, (ma_uint32)frameCount, pDSP->pUserData); + } else { + ma_uint8* pNextFramesOut = (ma_uint8*)pFramesOut; + + ma_uint64 totalFramesRead = 0; + while (totalFramesRead < frameCount) { + ma_uint64 framesRemaining = (frameCount - totalFramesRead); + ma_uint64 framesToReadRightNow = framesRemaining; + if (framesToReadRightNow > 0xFFFFFFFF) { + framesToReadRightNow = 0xFFFFFFFF; + } + + ma_uint32 framesRead = pDSP->onRead(pDSP, pNextFramesOut, (ma_uint32)framesToReadRightNow, pDSP->pUserData); + if (framesRead == 0) { + break; + } + + pNextFramesOut += framesRead * pDSP->channelRouter.config.channelsOut * ma_get_bytes_per_sample(pDSP->formatConverterOut.config.formatOut); + totalFramesRead += framesRead; + } + + return totalFramesRead; + } + } + + // Slower path. The real work is done here. To do this all we need to do is read from the last stage in the pipeline. + ma_assert(pDSP->isPostFormatConversionRequired == MA_TRUE); + + ma_pcm_converter_callback_data data; + data.pDSP = pDSP; + data.pUserDataForClient = pDSP->pUserData; + return ma_format_converter_read(&pDSP->formatConverterOut, frameCount, pFramesOut, &data); +} + + +typedef struct +{ + const void* pDataIn; + ma_format formatIn; + ma_uint32 channelsIn; + ma_uint64 totalFrameCount; + ma_uint64 iNextFrame; + ma_bool32 isFeedingZeros; // When set to true, feeds the DSP zero samples. +} ma_convert_frames__data; + +ma_uint32 ma_convert_frames__on_read(ma_pcm_converter* pDSP, void* pFramesOut, ma_uint32 frameCount, void* pUserData) +{ + (void)pDSP; + + ma_convert_frames__data* pData = (ma_convert_frames__data*)pUserData; + ma_assert(pData != NULL); + ma_assert(pData->totalFrameCount >= pData->iNextFrame); + + ma_uint32 framesToRead = frameCount; + ma_uint64 framesRemaining = (pData->totalFrameCount - pData->iNextFrame); + if (framesToRead > framesRemaining) { + framesToRead = (ma_uint32)framesRemaining; + } + + ma_uint32 frameSizeInBytes = ma_get_bytes_per_frame(pData->formatIn, pData->channelsIn); + + if (!pData->isFeedingZeros) { + ma_copy_memory(pFramesOut, (const ma_uint8*)pData->pDataIn + (frameSizeInBytes * pData->iNextFrame), frameSizeInBytes * framesToRead); + } else { + ma_zero_memory(pFramesOut, frameSizeInBytes * framesToRead); + } + + pData->iNextFrame += framesToRead; + return framesToRead; +} + +ma_pcm_converter_config ma_pcm_converter_config_init_new() +{ + ma_pcm_converter_config config; + ma_zero_object(&config); + + return config; +} + +ma_pcm_converter_config ma_pcm_converter_config_init(ma_format formatIn, ma_uint32 channelsIn, ma_uint32 sampleRateIn, ma_format formatOut, ma_uint32 channelsOut, ma_uint32 sampleRateOut, ma_pcm_converter_read_proc onRead, void* pUserData) +{ + return ma_pcm_converter_config_init_ex(formatIn, channelsIn, sampleRateIn, NULL, formatOut, channelsOut, sampleRateOut, NULL, onRead, pUserData); +} + +ma_pcm_converter_config ma_pcm_converter_config_init_ex(ma_format formatIn, ma_uint32 channelsIn, ma_uint32 sampleRateIn, ma_channel channelMapIn[MA_MAX_CHANNELS], ma_format formatOut, ma_uint32 channelsOut, ma_uint32 sampleRateOut, ma_channel channelMapOut[MA_MAX_CHANNELS], ma_pcm_converter_read_proc onRead, void* pUserData) +{ + ma_pcm_converter_config config; + ma_zero_object(&config); + config.formatIn = formatIn; + config.channelsIn = channelsIn; + config.sampleRateIn = sampleRateIn; + config.formatOut = formatOut; + config.channelsOut = channelsOut; + config.sampleRateOut = sampleRateOut; + if (channelMapIn != NULL) { + ma_copy_memory(config.channelMapIn, channelMapIn, sizeof(config.channelMapIn)); + } + if (channelMapOut != NULL) { + ma_copy_memory(config.channelMapOut, channelMapOut, sizeof(config.channelMapOut)); + } + config.onRead = onRead; + config.pUserData = pUserData; + + return config; +} + + + +ma_uint64 ma_convert_frames(void* pOut, ma_format formatOut, ma_uint32 channelsOut, ma_uint32 sampleRateOut, const void* pIn, ma_format formatIn, ma_uint32 channelsIn, ma_uint32 sampleRateIn, ma_uint64 frameCount) +{ + ma_channel channelMapOut[MA_MAX_CHANNELS]; + ma_get_standard_channel_map(ma_standard_channel_map_default, channelsOut, channelMapOut); + + ma_channel channelMapIn[MA_MAX_CHANNELS]; + ma_get_standard_channel_map(ma_standard_channel_map_default, channelsIn, channelMapIn); + + return ma_convert_frames_ex(pOut, formatOut, channelsOut, sampleRateOut, channelMapOut, pIn, formatIn, channelsIn, sampleRateIn, channelMapIn, frameCount); +} + +ma_uint64 ma_convert_frames_ex(void* pOut, ma_format formatOut, ma_uint32 channelsOut, ma_uint32 sampleRateOut, ma_channel channelMapOut[MA_MAX_CHANNELS], const void* pIn, ma_format formatIn, ma_uint32 channelsIn, ma_uint32 sampleRateIn, ma_channel channelMapIn[MA_MAX_CHANNELS], ma_uint64 frameCount) +{ + if (frameCount == 0) { + return 0; + } + + ma_uint64 frameCountOut = ma_calculate_frame_count_after_src(sampleRateOut, sampleRateIn, frameCount); + if (pOut == NULL) { + return frameCountOut; + } + + ma_convert_frames__data data; + data.pDataIn = pIn; + data.formatIn = formatIn; + data.channelsIn = channelsIn; + data.totalFrameCount = frameCount; + data.iNextFrame = 0; + data.isFeedingZeros = MA_FALSE; + + ma_pcm_converter_config config; + ma_zero_object(&config); + + config.formatIn = formatIn; + config.channelsIn = channelsIn; + config.sampleRateIn = sampleRateIn; + if (channelMapIn != NULL) { + ma_channel_map_copy(config.channelMapIn, channelMapIn, channelsIn); + } else { + ma_get_standard_channel_map(ma_standard_channel_map_default, config.channelsIn, config.channelMapIn); + } + + config.formatOut = formatOut; + config.channelsOut = channelsOut; + config.sampleRateOut = sampleRateOut; + if (channelMapOut != NULL) { + ma_channel_map_copy(config.channelMapOut, channelMapOut, channelsOut); + } else { + ma_get_standard_channel_map(ma_standard_channel_map_default, config.channelsOut, config.channelMapOut); + } + + config.onRead = ma_convert_frames__on_read; + config.pUserData = &data; + + ma_pcm_converter dsp; + if (ma_pcm_converter_init(&config, &dsp) != MA_SUCCESS) { + return 0; + } + + // Always output our computed frame count. There is a chance the sample rate conversion routine may not output the last sample + // due to precision issues with 32-bit floats, in which case we should feed the DSP zero samples so it can generate that last + // frame. + ma_uint64 totalFramesRead = ma_pcm_converter_read(&dsp, pOut, frameCountOut); + if (totalFramesRead < frameCountOut) { + ma_uint32 bpf = ma_get_bytes_per_frame(formatIn, channelsIn); + + data.isFeedingZeros = MA_TRUE; + data.totalFrameCount = 0xFFFFFFFFFFFFFFFF; + data.pDataIn = NULL; + + while (totalFramesRead < frameCountOut) { + ma_uint64 framesToRead = (frameCountOut - totalFramesRead); + ma_assert(framesToRead > 0); + + ma_uint64 framesJustRead = ma_pcm_converter_read(&dsp, ma_offset_ptr(pOut, totalFramesRead * bpf), framesToRead); + totalFramesRead += framesJustRead; + + if (framesJustRead < framesToRead) { + break; + } + } + + // At this point we should have output every sample, but just to be super duper sure, just fill the rest with zeros. + if (totalFramesRead < frameCountOut) { + ma_zero_memory_64(ma_offset_ptr(pOut, totalFramesRead * bpf), ((frameCountOut - totalFramesRead) * bpf)); + totalFramesRead = frameCountOut; + } + } + + ma_assert(totalFramesRead == frameCountOut); + return totalFramesRead; +} + + +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Ring Buffer +// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +MA_INLINE ma_uint32 ma_rb__extract_offset_in_bytes(ma_uint32 encodedOffset) +{ + return encodedOffset & 0x7FFFFFFF; +} + +MA_INLINE ma_uint32 ma_rb__extract_offset_loop_flag(ma_uint32 encodedOffset) +{ + return encodedOffset & 0x80000000; +} + +MA_INLINE void* ma_rb__get_read_ptr(ma_rb* pRB) +{ + ma_assert(pRB != NULL); + return ma_offset_ptr(pRB->pBuffer, ma_rb__extract_offset_in_bytes(pRB->encodedReadOffset)); +} + +MA_INLINE void* ma_rb__get_write_ptr(ma_rb* pRB) +{ + ma_assert(pRB != NULL); + return ma_offset_ptr(pRB->pBuffer, ma_rb__extract_offset_in_bytes(pRB->encodedWriteOffset)); +} + +MA_INLINE ma_uint32 ma_rb__construct_offset(ma_uint32 offsetInBytes, ma_uint32 offsetLoopFlag) +{ + return offsetLoopFlag | offsetInBytes; +} + +MA_INLINE void ma_rb__deconstruct_offset(ma_uint32 encodedOffset, ma_uint32* pOffsetInBytes, ma_uint32* pOffsetLoopFlag) +{ + ma_assert(pOffsetInBytes != NULL); + ma_assert(pOffsetLoopFlag != NULL); + + *pOffsetInBytes = ma_rb__extract_offset_in_bytes(encodedOffset); + *pOffsetLoopFlag = ma_rb__extract_offset_loop_flag(encodedOffset); +} + + +ma_result ma_rb_init_ex(size_t subbufferSizeInBytes, size_t subbufferCount, size_t subbufferStrideInBytes, void* pOptionalPreallocatedBuffer, ma_rb* pRB) +{ + if (pRB == NULL) { + return MA_INVALID_ARGS; + } + + if (subbufferSizeInBytes == 0 || subbufferCount == 0) { + return MA_INVALID_ARGS; + } + + const ma_uint32 maxSubBufferSize = 0x7FFFFFFF - (MA_SIMD_ALIGNMENT-1); + if (subbufferSizeInBytes > maxSubBufferSize) { + return MA_INVALID_ARGS; // Maximum buffer size is ~2GB. The most significant bit is a flag for use internally. + } + + + ma_zero_object(pRB); + pRB->subbufferSizeInBytes = (ma_uint32)subbufferSizeInBytes; + pRB->subbufferCount = (ma_uint32)subbufferCount; + + if (pOptionalPreallocatedBuffer != NULL) { + pRB->subbufferStrideInBytes = (ma_uint32)subbufferStrideInBytes; + pRB->pBuffer = pOptionalPreallocatedBuffer; + } else { + // Here is where we allocate our own buffer. We always want to align this to MA_SIMD_ALIGNMENT for future SIMD optimization opportunity. To do this + // we need to make sure the stride is a multiple of MA_SIMD_ALIGNMENT. + pRB->subbufferStrideInBytes = (pRB->subbufferSizeInBytes + (MA_SIMD_ALIGNMENT-1)) & ~MA_SIMD_ALIGNMENT; + + size_t bufferSizeInBytes = (size_t)pRB->subbufferCount*pRB->subbufferStrideInBytes; + pRB->pBuffer = ma_aligned_malloc(bufferSizeInBytes, MA_SIMD_ALIGNMENT); + if (pRB->pBuffer == NULL) { + return MA_OUT_OF_MEMORY; + } + + ma_zero_memory(pRB->pBuffer, bufferSizeInBytes); + pRB->ownsBuffer = MA_TRUE; + } + + return MA_SUCCESS; +} + +ma_result ma_rb_init(size_t bufferSizeInBytes, void* pOptionalPreallocatedBuffer, ma_rb* pRB) +{ + return ma_rb_init_ex(bufferSizeInBytes, 1, 0, pOptionalPreallocatedBuffer, pRB); +} + +void ma_rb_uninit(ma_rb* pRB) +{ + if (pRB == NULL) { + return; + } + + if (pRB->ownsBuffer) { + ma_aligned_free(pRB->pBuffer); + } +} + +ma_result ma_rb_acquire_read(ma_rb* pRB, size_t* pSizeInBytes, void** ppBufferOut) +{ + if (pRB == NULL || pSizeInBytes == NULL || ppBufferOut == NULL) { + return MA_INVALID_ARGS; + } + + // The returned buffer should never move ahead of the write pointer. + ma_uint32 writeOffset = pRB->encodedWriteOffset; + ma_uint32 writeOffsetInBytes; + ma_uint32 writeOffsetLoopFlag; + ma_rb__deconstruct_offset(writeOffset, &writeOffsetInBytes, &writeOffsetLoopFlag); + + ma_uint32 readOffset = pRB->encodedReadOffset; + ma_uint32 readOffsetInBytes; + ma_uint32 readOffsetLoopFlag; + ma_rb__deconstruct_offset(readOffset, &readOffsetInBytes, &readOffsetLoopFlag); + + // The number of bytes available depends on whether or not the read and write pointers are on the same loop iteration. If so, we + // can only read up to the write pointer. If not, we can only read up to the end of the buffer. + size_t bytesAvailable; + if (readOffsetLoopFlag == writeOffsetLoopFlag) { + bytesAvailable = writeOffsetInBytes - readOffsetInBytes; + } else { + bytesAvailable = pRB->subbufferSizeInBytes - readOffsetInBytes; + } + + size_t bytesRequested = *pSizeInBytes; + if (bytesRequested > bytesAvailable) { + bytesRequested = bytesAvailable; + } + + *pSizeInBytes = bytesRequested; + (*ppBufferOut) = ma_rb__get_read_ptr(pRB); + + return MA_SUCCESS; +} + +ma_result ma_rb_commit_read(ma_rb* pRB, size_t sizeInBytes, void* pBufferOut) +{ + if (pRB == NULL) { + return MA_INVALID_ARGS; + } + + // Validate the buffer. + if (pBufferOut != ma_rb__get_read_ptr(pRB)) { + return MA_INVALID_ARGS; + } + + ma_uint32 readOffset = pRB->encodedReadOffset; + ma_uint32 readOffsetInBytes; + ma_uint32 readOffsetLoopFlag; + ma_rb__deconstruct_offset(readOffset, &readOffsetInBytes, &readOffsetLoopFlag); + + // Check that sizeInBytes is correct. It should never go beyond the end of the buffer. + ma_uint32 newReadOffsetInBytes = (ma_uint32)(readOffsetInBytes + sizeInBytes); + if (newReadOffsetInBytes > pRB->subbufferSizeInBytes) { + return MA_INVALID_ARGS; // <-- sizeInBytes will cause the read offset to overflow. + } + + // Move the read pointer back to the start if necessary. + ma_uint32 newReadOffsetLoopFlag = readOffsetLoopFlag; + if (newReadOffsetInBytes == pRB->subbufferSizeInBytes) { + newReadOffsetInBytes = 0; + newReadOffsetLoopFlag ^= 0x80000000; + } + + ma_atomic_exchange_32(&pRB->encodedReadOffset, ma_rb__construct_offset(newReadOffsetLoopFlag, newReadOffsetInBytes)); + return MA_SUCCESS; +} + +ma_result ma_rb_acquire_write(ma_rb* pRB, size_t* pSizeInBytes, void** ppBufferOut) +{ + if (pRB == NULL || pSizeInBytes == NULL || ppBufferOut == NULL) { + return MA_INVALID_ARGS; + } + + // The returned buffer should never overtake the read buffer. + ma_uint32 readOffset = pRB->encodedReadOffset; + ma_uint32 readOffsetInBytes; + ma_uint32 readOffsetLoopFlag; + ma_rb__deconstruct_offset(readOffset, &readOffsetInBytes, &readOffsetLoopFlag); + + ma_uint32 writeOffset = pRB->encodedWriteOffset; + ma_uint32 writeOffsetInBytes; + ma_uint32 writeOffsetLoopFlag; + ma_rb__deconstruct_offset(writeOffset, &writeOffsetInBytes, &writeOffsetLoopFlag); + + // In the case of writing, if the write pointer and the read pointer are on the same loop iteration we can only + // write up to the end of the buffer. Otherwise we can only write up to the read pointer. The write pointer should + // never overtake the read pointer. + size_t bytesAvailable; + if (writeOffsetLoopFlag == readOffsetLoopFlag) { + bytesAvailable = pRB->subbufferSizeInBytes - writeOffsetInBytes; + } else { + bytesAvailable = readOffsetInBytes - writeOffsetInBytes; + } + + size_t bytesRequested = *pSizeInBytes; + if (bytesRequested > bytesAvailable) { + bytesRequested = bytesAvailable; + } + + *pSizeInBytes = bytesRequested; + *ppBufferOut = ma_rb__get_write_ptr(pRB); + + // Clear the buffer if desired. + if (pRB->clearOnWriteAcquire) { + ma_zero_memory(*ppBufferOut, *pSizeInBytes); + } + + return MA_SUCCESS; +} + +ma_result ma_rb_commit_write(ma_rb* pRB, size_t sizeInBytes, void* pBufferOut) +{ + if (pRB == NULL) { + return MA_INVALID_ARGS; + } + + // Validate the buffer. + if (pBufferOut != ma_rb__get_write_ptr(pRB)) { + return MA_INVALID_ARGS; + } + + ma_uint32 writeOffset = pRB->encodedWriteOffset; + ma_uint32 writeOffsetInBytes; + ma_uint32 writeOffsetLoopFlag; + ma_rb__deconstruct_offset(writeOffset, &writeOffsetInBytes, &writeOffsetLoopFlag); + + // Check that sizeInBytes is correct. It should never go beyond the end of the buffer. + ma_uint32 newWriteOffsetInBytes = (ma_uint32)(writeOffsetInBytes + sizeInBytes); + if (newWriteOffsetInBytes > pRB->subbufferSizeInBytes) { + return MA_INVALID_ARGS; // <-- sizeInBytes will cause the read offset to overflow. + } + + // Move the read pointer back to the start if necessary. + ma_uint32 newWriteOffsetLoopFlag = writeOffsetLoopFlag; + if (newWriteOffsetInBytes == pRB->subbufferSizeInBytes) { + newWriteOffsetInBytes = 0; + newWriteOffsetLoopFlag ^= 0x80000000; + } + + ma_atomic_exchange_32(&pRB->encodedWriteOffset, ma_rb__construct_offset(newWriteOffsetLoopFlag, newWriteOffsetInBytes)); + return MA_SUCCESS; +} + +ma_result ma_rb_seek_read(ma_rb* pRB, size_t offsetInBytes) +{ + if (pRB == NULL || offsetInBytes > pRB->subbufferSizeInBytes) { + return MA_INVALID_ARGS; + } + + ma_uint32 readOffset = pRB->encodedReadOffset; + ma_uint32 readOffsetInBytes; + ma_uint32 readOffsetLoopFlag; + ma_rb__deconstruct_offset(readOffset, &readOffsetInBytes, &readOffsetLoopFlag); + + ma_uint32 writeOffset = pRB->encodedWriteOffset; + ma_uint32 writeOffsetInBytes; + ma_uint32 writeOffsetLoopFlag; + ma_rb__deconstruct_offset(writeOffset, &writeOffsetInBytes, &writeOffsetLoopFlag); + + ma_uint32 newReadOffsetInBytes = readOffsetInBytes; + ma_uint32 newReadOffsetLoopFlag = readOffsetLoopFlag; + + // We cannot go past the write buffer. + if (readOffsetLoopFlag == writeOffsetLoopFlag) { + if ((readOffsetInBytes + offsetInBytes) > writeOffsetInBytes) { + newReadOffsetInBytes = writeOffsetInBytes; + } else { + newReadOffsetInBytes = (ma_uint32)(readOffsetInBytes + offsetInBytes); + } + } else { + // May end up looping. + if ((readOffsetInBytes + offsetInBytes) >= pRB->subbufferSizeInBytes) { + newReadOffsetInBytes = (ma_uint32)(readOffsetInBytes + offsetInBytes) - pRB->subbufferSizeInBytes; + newReadOffsetLoopFlag ^= 0x80000000; /* <-- Looped. */ + } else { + newReadOffsetInBytes = (ma_uint32)(readOffsetInBytes + offsetInBytes); + } + } + + ma_atomic_exchange_32(&pRB->encodedReadOffset, ma_rb__construct_offset(newReadOffsetInBytes, newReadOffsetLoopFlag)); + return MA_SUCCESS; +} + +ma_result ma_rb_seek_write(ma_rb* pRB, size_t offsetInBytes) +{ + if (pRB == NULL) { + return MA_INVALID_ARGS; + } + + ma_uint32 readOffset = pRB->encodedReadOffset; + ma_uint32 readOffsetInBytes; + ma_uint32 readOffsetLoopFlag; + ma_rb__deconstruct_offset(readOffset, &readOffsetInBytes, &readOffsetLoopFlag); + + ma_uint32 writeOffset = pRB->encodedWriteOffset; + ma_uint32 writeOffsetInBytes; + ma_uint32 writeOffsetLoopFlag; + ma_rb__deconstruct_offset(writeOffset, &writeOffsetInBytes, &writeOffsetLoopFlag); + + ma_uint32 newWriteOffsetInBytes = writeOffsetInBytes; + ma_uint32 newWriteOffsetLoopFlag = writeOffsetLoopFlag; + + // We cannot go past the write buffer. + if (readOffsetLoopFlag == writeOffsetLoopFlag) { + // May end up looping. + if ((writeOffsetInBytes + offsetInBytes) >= pRB->subbufferSizeInBytes) { + newWriteOffsetInBytes = (ma_uint32)(writeOffsetInBytes + offsetInBytes) - pRB->subbufferSizeInBytes; + newWriteOffsetLoopFlag ^= 0x80000000; /* <-- Looped. */ + } else { + newWriteOffsetInBytes = (ma_uint32)(writeOffsetInBytes + offsetInBytes); + } + } else { + if ((writeOffsetInBytes + offsetInBytes) > readOffsetInBytes) { + newWriteOffsetInBytes = readOffsetInBytes; + } else { + newWriteOffsetInBytes = (ma_uint32)(writeOffsetInBytes + offsetInBytes); + } + } + + ma_atomic_exchange_32(&pRB->encodedWriteOffset, ma_rb__construct_offset(newWriteOffsetInBytes, newWriteOffsetLoopFlag)); + return MA_SUCCESS; +} + +ma_int32 ma_rb_pointer_distance(ma_rb* pRB) +{ + if (pRB == NULL) { + return 0; + } + + ma_uint32 readOffset = pRB->encodedReadOffset; + ma_uint32 readOffsetInBytes; + ma_uint32 readOffsetLoopFlag; + ma_rb__deconstruct_offset(readOffset, &readOffsetInBytes, &readOffsetLoopFlag); + + ma_uint32 writeOffset = pRB->encodedWriteOffset; + ma_uint32 writeOffsetInBytes; + ma_uint32 writeOffsetLoopFlag; + ma_rb__deconstruct_offset(writeOffset, &writeOffsetInBytes, &writeOffsetLoopFlag); + + if (readOffsetLoopFlag == writeOffsetLoopFlag) { + return writeOffsetInBytes - readOffsetInBytes; + } else { + return writeOffsetInBytes + (pRB->subbufferSizeInBytes - readOffsetInBytes); + } +} + +size_t ma_rb_get_subbuffer_size(ma_rb* pRB) +{ + if (pRB == NULL) { + return 0; + } + + return pRB->subbufferSizeInBytes; +} + +size_t ma_rb_get_subbuffer_stride(ma_rb* pRB) +{ + if (pRB == NULL) { + return 0; + } + + if (pRB->subbufferStrideInBytes == 0) { + return (size_t)pRB->subbufferSizeInBytes; + } + + return (size_t)pRB->subbufferStrideInBytes; +} + +size_t ma_rb_get_subbuffer_offset(ma_rb* pRB, size_t subbufferIndex) +{ + if (pRB == NULL) { + return 0; + } + + return subbufferIndex * ma_rb_get_subbuffer_stride(pRB); +} + +void* ma_rb_get_subbuffer_ptr(ma_rb* pRB, size_t subbufferIndex, void* pBuffer) +{ + if (pRB == NULL) { + return NULL; + } + + return ma_offset_ptr(pBuffer, ma_rb_get_subbuffer_offset(pRB, subbufferIndex)); +} + + +static MA_INLINE ma_uint32 ma_pcm_rb_get_bpf(ma_pcm_rb* pRB) +{ + ma_assert(pRB != NULL); + + return ma_get_bytes_per_frame(pRB->format, pRB->channels); +} + +ma_result ma_pcm_rb_init_ex(ma_format format, ma_uint32 channels, ma_uint32 subbufferSizeInFrames, ma_uint32 subbufferCount, ma_uint32 subbufferStrideInFrames, void* pOptionalPreallocatedBuffer, ma_pcm_rb* pRB) +{ + if (pRB == NULL) { + return MA_INVALID_ARGS; + } + + ma_zero_object(pRB); + + ma_uint32 bpf = ma_get_bytes_per_frame(format, channels); + if (bpf == 0) { + return MA_INVALID_ARGS; + } + + ma_result result = ma_rb_init_ex(subbufferSizeInFrames*bpf, subbufferCount, subbufferStrideInFrames*bpf, pOptionalPreallocatedBuffer, &pRB->rb); + if (result != MA_SUCCESS) { + return result; + } + + pRB->format = format; + pRB->channels = channels; + + return MA_SUCCESS; +} + +ma_result ma_pcm_rb_init(ma_format format, ma_uint32 channels, ma_uint32 bufferSizeInFrames, void* pOptionalPreallocatedBuffer, ma_pcm_rb* pRB) +{ + return ma_pcm_rb_init_ex(format, channels, bufferSizeInFrames, 1, 0, pOptionalPreallocatedBuffer, pRB); +} + +void ma_pcm_rb_uninit(ma_pcm_rb* pRB) +{ + if (pRB == NULL) { + return; + } + + ma_rb_uninit(&pRB->rb); +} + +ma_result ma_pcm_rb_acquire_read(ma_pcm_rb* pRB, ma_uint32* pSizeInFrames, void** ppBufferOut) +{ + size_t sizeInBytes; + ma_result result; + + if (pRB == NULL || pSizeInFrames == NULL) { + return MA_INVALID_ARGS; + } + + sizeInBytes = *pSizeInFrames * ma_pcm_rb_get_bpf(pRB); + + result = ma_rb_acquire_read(&pRB->rb, &sizeInBytes, ppBufferOut); + if (result != MA_SUCCESS) { + return result; + } + + *pSizeInFrames = (ma_uint32)(sizeInBytes / (size_t)ma_pcm_rb_get_bpf(pRB)); + return MA_SUCCESS; +} + +ma_result ma_pcm_rb_commit_read(ma_pcm_rb* pRB, ma_uint32 sizeInFrames, void* pBufferOut) +{ + if (pRB == NULL) { + return MA_INVALID_ARGS; + } + + return ma_rb_commit_read(&pRB->rb, sizeInFrames * ma_pcm_rb_get_bpf(pRB), pBufferOut); +} + +ma_result ma_pcm_rb_acquire_write(ma_pcm_rb* pRB, ma_uint32* pSizeInFrames, void** ppBufferOut) +{ + size_t sizeInBytes; + ma_result result; + + if (pRB == NULL) { + return MA_INVALID_ARGS; + } + + sizeInBytes = *pSizeInFrames * ma_pcm_rb_get_bpf(pRB); + + result = ma_rb_acquire_write(&pRB->rb, &sizeInBytes, ppBufferOut); + if (result != MA_SUCCESS) { + return result; + } + + *pSizeInFrames = (ma_uint32)(sizeInBytes / ma_pcm_rb_get_bpf(pRB)); + return MA_SUCCESS; +} + +ma_result ma_pcm_rb_commit_write(ma_pcm_rb* pRB, ma_uint32 sizeInFrames, void* pBufferOut) +{ + if (pRB == NULL) { + return MA_INVALID_ARGS; + } + + return ma_rb_commit_write(&pRB->rb, sizeInFrames * ma_pcm_rb_get_bpf(pRB), pBufferOut); +} + +ma_result ma_pcm_rb_seek_read(ma_pcm_rb* pRB, ma_uint32 offsetInFrames) +{ + if (pRB == NULL) { + return MA_INVALID_ARGS; + } + + return ma_rb_seek_read(&pRB->rb, offsetInFrames * ma_pcm_rb_get_bpf(pRB)); +} + +ma_result ma_pcm_rb_seek_write(ma_pcm_rb* pRB, ma_uint32 offsetInFrames) +{ + if (pRB == NULL) { + return MA_INVALID_ARGS; + } + + return ma_rb_seek_write(&pRB->rb, offsetInFrames * ma_pcm_rb_get_bpf(pRB)); +} + +ma_int32 ma_pcm_rb_pointer_disance(ma_pcm_rb* pRB) +{ + if (pRB == NULL) { + return MA_INVALID_ARGS; + } + + return ma_rb_pointer_distance(&pRB->rb) / ma_pcm_rb_get_bpf(pRB); +} + +ma_uint32 ma_pcm_rb_get_subbuffer_size(ma_pcm_rb* pRB) +{ + if (pRB == NULL) { + return 0; + } + + return (ma_uint32)(ma_rb_get_subbuffer_size(&pRB->rb) / ma_pcm_rb_get_bpf(pRB)); +} + +ma_uint32 ma_pcm_rb_get_subbuffer_stride(ma_pcm_rb* pRB) +{ + if (pRB == NULL) { + return 0; + } + + return (ma_uint32)(ma_rb_get_subbuffer_stride(&pRB->rb) / ma_pcm_rb_get_bpf(pRB)); +} + +ma_uint32 ma_pcm_rb_get_subbuffer_offset(ma_pcm_rb* pRB, ma_uint32 subbufferIndex) +{ + if (pRB == NULL) { + return 0; + } + + return (ma_uint32)(ma_rb_get_subbuffer_offset(&pRB->rb, subbufferIndex) / ma_pcm_rb_get_bpf(pRB)); +} + +void* ma_pcm_rb_get_subbuffer_ptr(ma_pcm_rb* pRB, ma_uint32 subbufferIndex, void* pBuffer) +{ + if (pRB == NULL) { + return NULL; + } + + return ma_rb_get_subbuffer_ptr(&pRB->rb, subbufferIndex, pBuffer); +} + + + +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Miscellaneous Helpers +// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +void* ma_malloc(size_t sz) +{ + return MA_MALLOC(sz); +} + +void* ma_realloc(void* p, size_t sz) +{ + return MA_REALLOC(p, sz); +} + +void ma_free(void* p) +{ + MA_FREE(p); +} + +void* ma_aligned_malloc(size_t sz, size_t alignment) +{ + if (alignment == 0) { + return 0; + } + + size_t extraBytes = alignment-1 + sizeof(void*); + + void* pUnaligned = ma_malloc(sz + extraBytes); + if (pUnaligned == NULL) { + return NULL; + } + + void* pAligned = (void*)(((ma_uintptr)pUnaligned + extraBytes) & ~((ma_uintptr)(alignment-1))); + ((void**)pAligned)[-1] = pUnaligned; + + return pAligned; +} + +void ma_aligned_free(void* p) +{ + ma_free(((void**)p)[-1]); +} + +const char* ma_get_format_name(ma_format format) +{ + switch (format) + { + case ma_format_unknown: return "Unknown"; + case ma_format_u8: return "8-bit Unsigned Integer"; + case ma_format_s16: return "16-bit Signed Integer"; + case ma_format_s24: return "24-bit Signed Integer (Tightly Packed)"; + case ma_format_s32: return "32-bit Signed Integer"; + case ma_format_f32: return "32-bit IEEE Floating Point"; + default: return "Invalid"; + } +} + +void ma_blend_f32(float* pOut, float* pInA, float* pInB, float factor, ma_uint32 channels) +{ + for (ma_uint32 i = 0; i < channels; ++i) { + pOut[i] = ma_mix_f32(pInA[i], pInB[i], factor); + } +} + + +ma_uint32 ma_get_bytes_per_sample(ma_format format) +{ + ma_uint32 sizes[] = { + 0, // unknown + 1, // u8 + 2, // s16 + 3, // s24 + 4, // s32 + 4, // f32 + }; + return sizes[format]; +} + + +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// +// DECODING +// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +#ifndef MA_NO_DECODING + +size_t ma_decoder_read_bytes(ma_decoder* pDecoder, void* pBufferOut, size_t bytesToRead) +{ + ma_assert(pDecoder != NULL); + ma_assert(pBufferOut != NULL); + + size_t bytesRead = pDecoder->onRead(pDecoder, pBufferOut, bytesToRead); + pDecoder->readPointer += bytesRead; + + return bytesRead; +} + +ma_bool32 ma_decoder_seek_bytes(ma_decoder* pDecoder, int byteOffset, ma_seek_origin origin) +{ + ma_assert(pDecoder != NULL); + + ma_bool32 wasSuccessful = pDecoder->onSeek(pDecoder, byteOffset, origin); + if (wasSuccessful) { + if (origin == ma_seek_origin_start) { + pDecoder->readPointer = (ma_uint64)byteOffset; + } else { + pDecoder->readPointer += byteOffset; + } + } + + return wasSuccessful; +} + +ma_bool32 ma_decoder_seek_bytes_64(ma_decoder* pDecoder, ma_uint64 byteOffset, ma_seek_origin origin) +{ + ma_assert(pDecoder != NULL); + + if (origin == ma_seek_origin_start) { + ma_uint64 bytesToSeekThisIteration = 0x7FFFFFFF; + if (bytesToSeekThisIteration > byteOffset) { + bytesToSeekThisIteration = byteOffset; + } + + if (!ma_decoder_seek_bytes(pDecoder, (int)bytesToSeekThisIteration, ma_seek_origin_start)) { + return MA_FALSE; + } + + byteOffset -= bytesToSeekThisIteration; + } + + /* Getting here means we need to seek relative to the current position. */ + while (byteOffset > 0) { + ma_uint64 bytesToSeekThisIteration = 0x7FFFFFFF; + if (bytesToSeekThisIteration > byteOffset) { + bytesToSeekThisIteration = byteOffset; + } + + if (!ma_decoder_seek_bytes(pDecoder, (int)bytesToSeekThisIteration, ma_seek_origin_current)) { + return MA_FALSE; + } + + byteOffset -= bytesToSeekThisIteration; + } + + return MA_TRUE; +} + + +ma_decoder_config ma_decoder_config_init(ma_format outputFormat, ma_uint32 outputChannels, ma_uint32 outputSampleRate) +{ + ma_decoder_config config; + ma_zero_object(&config); + config.format = outputFormat; + config.channels = outputChannels; + config.sampleRate = outputSampleRate; + ma_get_standard_channel_map(ma_standard_channel_map_default, config.channels, config.channelMap); + + return config; +} + +ma_decoder_config ma_decoder_config_init_copy(const ma_decoder_config* pConfig) +{ + ma_decoder_config config; + if (pConfig != NULL) { + config = *pConfig; + } else { + ma_zero_object(&config); + } + + return config; +} + +ma_result ma_decoder__init_dsp(ma_decoder* pDecoder, const ma_decoder_config* pConfig, ma_pcm_converter_read_proc onRead) +{ + ma_assert(pDecoder != NULL); + + // Output format. + if (pConfig->format == ma_format_unknown) { + pDecoder->outputFormat = pDecoder->internalFormat; + } else { + pDecoder->outputFormat = pConfig->format; + } + + if (pConfig->channels == 0) { + pDecoder->outputChannels = pDecoder->internalChannels; + } else { + pDecoder->outputChannels = pConfig->channels; + } + + if (pConfig->sampleRate == 0) { + pDecoder->outputSampleRate = pDecoder->internalSampleRate; + } else { + pDecoder->outputSampleRate = pConfig->sampleRate; + } + + if (ma_channel_map_blank(pDecoder->outputChannels, pConfig->channelMap)) { + ma_get_standard_channel_map(ma_standard_channel_map_default, pDecoder->outputChannels, pDecoder->outputChannelMap); + } else { + ma_copy_memory(pDecoder->outputChannelMap, pConfig->channelMap, sizeof(pConfig->channelMap)); + } + + + // DSP. + ma_pcm_converter_config dspConfig = ma_pcm_converter_config_init_ex( + pDecoder->internalFormat, pDecoder->internalChannels, pDecoder->internalSampleRate, pDecoder->internalChannelMap, + pDecoder->outputFormat, pDecoder->outputChannels, pDecoder->outputSampleRate, pDecoder->outputChannelMap, + onRead, pDecoder); + dspConfig.channelMixMode = pConfig->channelMixMode; + dspConfig.ditherMode = pConfig->ditherMode; + dspConfig.srcAlgorithm = pConfig->srcAlgorithm; + dspConfig.sinc = pConfig->src.sinc; + + return ma_pcm_converter_init(&dspConfig, &pDecoder->dsp); +} + +// WAV +#ifdef dr_wav_h +#define MA_HAS_WAV + +size_t ma_decoder_internal_on_read__wav(void* pUserData, void* pBufferOut, size_t bytesToRead) +{ + ma_decoder* pDecoder = (ma_decoder*)pUserData; + ma_assert(pDecoder != NULL); + + return ma_decoder_read_bytes(pDecoder, pBufferOut, bytesToRead); +} + +drwav_bool32 ma_decoder_internal_on_seek__wav(void* pUserData, int offset, drwav_seek_origin origin) +{ + ma_decoder* pDecoder = (ma_decoder*)pUserData; + ma_assert(pDecoder != NULL); + + return ma_decoder_seek_bytes(pDecoder, offset, (origin == drwav_seek_origin_start) ? ma_seek_origin_start : ma_seek_origin_current); +} + +ma_uint32 ma_decoder_internal_on_read_pcm_frames__wav(ma_pcm_converter* pDSP, void* pSamplesOut, ma_uint32 frameCount, void* pUserData) +{ + (void)pDSP; + + ma_decoder* pDecoder = (ma_decoder*)pUserData; + ma_assert(pDecoder != NULL); + + drwav* pWav = (drwav*)pDecoder->pInternalDecoder; + ma_assert(pWav != NULL); + + switch (pDecoder->internalFormat) { + case ma_format_s16: return (ma_uint32)drwav_read_pcm_frames_s16(pWav, frameCount, (drwav_int16*)pSamplesOut); + case ma_format_s32: return (ma_uint32)drwav_read_pcm_frames_s32(pWav, frameCount, (drwav_int32*)pSamplesOut); + case ma_format_f32: return (ma_uint32)drwav_read_pcm_frames_f32(pWav, frameCount, (float*)pSamplesOut); + default: break; + } + + // Should never get here. If we do, it means the internal format was not set correctly at initialization time. + ma_assert(MA_FALSE); + return 0; +} + +ma_result ma_decoder_internal_on_seek_to_pcm_frame__wav(ma_decoder* pDecoder, ma_uint64 frameIndex) +{ + drwav* pWav = (drwav*)pDecoder->pInternalDecoder; + ma_assert(pWav != NULL); + + drwav_bool32 result = drwav_seek_to_pcm_frame(pWav, frameIndex); + if (result) { + return MA_SUCCESS; + } else { + return MA_ERROR; + } +} + +ma_result ma_decoder_internal_on_uninit__wav(ma_decoder* pDecoder) +{ + drwav_close((drwav*)pDecoder->pInternalDecoder); + return MA_SUCCESS; +} + +ma_result ma_decoder_init_wav__internal(const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_assert(pConfig != NULL); + ma_assert(pDecoder != NULL); + + // Try opening the decoder first. + drwav* pWav = drwav_open(ma_decoder_internal_on_read__wav, ma_decoder_internal_on_seek__wav, pDecoder); + if (pWav == NULL) { + return MA_ERROR; + } + + // If we get here it means we successfully initialized the WAV decoder. We can now initialize the rest of the ma_decoder. + pDecoder->onSeekToPCMFrame = ma_decoder_internal_on_seek_to_pcm_frame__wav; + pDecoder->onUninit = ma_decoder_internal_on_uninit__wav; + pDecoder->pInternalDecoder = pWav; + + // Try to be as optimal as possible for the internal format. If miniaudio does not support a format we will fall back to f32. + pDecoder->internalFormat = ma_format_unknown; + switch (pWav->translatedFormatTag) { + case DR_WAVE_FORMAT_PCM: + { + if (pWav->bitsPerSample == 8) { + pDecoder->internalFormat = ma_format_s16; + } else if (pWav->bitsPerSample == 16) { + pDecoder->internalFormat = ma_format_s16; + } else if (pWav->bitsPerSample == 32) { + pDecoder->internalFormat = ma_format_s32; + } + } break; + + case DR_WAVE_FORMAT_IEEE_FLOAT: + { + if (pWav->bitsPerSample == 32) { + pDecoder->internalFormat = ma_format_f32; + } + } break; + + case DR_WAVE_FORMAT_ALAW: + case DR_WAVE_FORMAT_MULAW: + case DR_WAVE_FORMAT_ADPCM: + case DR_WAVE_FORMAT_DVI_ADPCM: + { + pDecoder->internalFormat = ma_format_s16; + } break; + } + + if (pDecoder->internalFormat == ma_format_unknown) { + pDecoder->internalFormat = ma_format_f32; + } + + pDecoder->internalChannels = pWav->channels; + pDecoder->internalSampleRate = pWav->sampleRate; + ma_get_standard_channel_map(ma_standard_channel_map_microsoft, pDecoder->internalChannels, pDecoder->internalChannelMap); + + ma_result result = ma_decoder__init_dsp(pDecoder, pConfig, ma_decoder_internal_on_read_pcm_frames__wav); + if (result != MA_SUCCESS) { + drwav_close(pWav); + return result; + } + + return MA_SUCCESS; +} +#endif + +// FLAC +#ifdef dr_flac_h +#define MA_HAS_FLAC + +size_t ma_decoder_internal_on_read__flac(void* pUserData, void* pBufferOut, size_t bytesToRead) +{ + ma_decoder* pDecoder = (ma_decoder*)pUserData; + ma_assert(pDecoder != NULL); + + return ma_decoder_read_bytes(pDecoder, pBufferOut, bytesToRead); +} + +drflac_bool32 ma_decoder_internal_on_seek__flac(void* pUserData, int offset, drflac_seek_origin origin) +{ + ma_decoder* pDecoder = (ma_decoder*)pUserData; + ma_assert(pDecoder != NULL); + + return ma_decoder_seek_bytes(pDecoder, offset, (origin == drflac_seek_origin_start) ? ma_seek_origin_start : ma_seek_origin_current); +} + +ma_uint32 ma_decoder_internal_on_read_pcm_frames__flac(ma_pcm_converter* pDSP, void* pSamplesOut, ma_uint32 frameCount, void* pUserData) +{ + (void)pDSP; + + ma_decoder* pDecoder = (ma_decoder*)pUserData; + ma_assert(pDecoder != NULL); + + drflac* pFlac = (drflac*)pDecoder->pInternalDecoder; + ma_assert(pFlac != NULL); + + switch (pDecoder->internalFormat) { + case ma_format_s16: return (ma_uint32)drflac_read_pcm_frames_s16(pFlac, frameCount, (drflac_int16*)pSamplesOut); + case ma_format_s32: return (ma_uint32)drflac_read_pcm_frames_s32(pFlac, frameCount, (drflac_int32*)pSamplesOut); + case ma_format_f32: return (ma_uint32)drflac_read_pcm_frames_f32(pFlac, frameCount, (float*)pSamplesOut); + default: break; + } + + // Should never get here. If we do, it means the internal format was not set correctly at initialization time. + ma_assert(MA_FALSE); + return 0; +} + +ma_result ma_decoder_internal_on_seek_to_pcm_frame__flac(ma_decoder* pDecoder, ma_uint64 frameIndex) +{ + drflac* pFlac = (drflac*)pDecoder->pInternalDecoder; + ma_assert(pFlac != NULL); + + drflac_bool32 result = drflac_seek_to_pcm_frame(pFlac, frameIndex); + if (result) { + return MA_SUCCESS; + } else { + return MA_ERROR; + } +} + +ma_result ma_decoder_internal_on_uninit__flac(ma_decoder* pDecoder) +{ + drflac_close((drflac*)pDecoder->pInternalDecoder); + return MA_SUCCESS; +} + +ma_result ma_decoder_init_flac__internal(const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_assert(pConfig != NULL); + ma_assert(pDecoder != NULL); + + // Try opening the decoder first. + drflac* pFlac = drflac_open(ma_decoder_internal_on_read__flac, ma_decoder_internal_on_seek__flac, pDecoder); + if (pFlac == NULL) { + return MA_ERROR; + } + + // If we get here it means we successfully initialized the FLAC decoder. We can now initialize the rest of the ma_decoder. + pDecoder->onSeekToPCMFrame = ma_decoder_internal_on_seek_to_pcm_frame__flac; + pDecoder->onUninit = ma_decoder_internal_on_uninit__flac; + pDecoder->pInternalDecoder = pFlac; + + // dr_flac supports reading as s32, s16 and f32. Try to do a one-to-one mapping if possible, but fall back to s32 if not. s32 is the "native" FLAC format + // since it's the only one that's truly lossless. + pDecoder->internalFormat = ma_format_s32; + if (pConfig->format == ma_format_s16) { + pDecoder->internalFormat = ma_format_s16; + } else if (pConfig->format == ma_format_f32) { + pDecoder->internalFormat = ma_format_f32; + } + + pDecoder->internalChannels = pFlac->channels; + pDecoder->internalSampleRate = pFlac->sampleRate; + ma_get_standard_channel_map(ma_standard_channel_map_flac, pDecoder->internalChannels, pDecoder->internalChannelMap); + + ma_result result = ma_decoder__init_dsp(pDecoder, pConfig, ma_decoder_internal_on_read_pcm_frames__flac); + if (result != MA_SUCCESS) { + drflac_close(pFlac); + return result; + } + + return MA_SUCCESS; +} +#endif + +// Vorbis +#ifdef STB_VORBIS_INCLUDE_STB_VORBIS_H +#define MA_HAS_VORBIS + +// The size in bytes of each chunk of data to read from the Vorbis stream. +#define MA_VORBIS_DATA_CHUNK_SIZE 4096 + +typedef struct +{ + stb_vorbis* pInternalVorbis; + ma_uint8* pData; + size_t dataSize; + size_t dataCapacity; + ma_uint32 framesConsumed; // The number of frames consumed in ppPacketData. + ma_uint32 framesRemaining; // The number of frames remaining in ppPacketData. + float** ppPacketData; +} ma_vorbis_decoder; + +ma_uint32 ma_vorbis_decoder_read_pcm_frames(ma_vorbis_decoder* pVorbis, ma_decoder* pDecoder, void* pSamplesOut, ma_uint32 frameCount) +{ + ma_assert(pVorbis != NULL); + ma_assert(pDecoder != NULL); + + float* pSamplesOutF = (float*)pSamplesOut; + + ma_uint32 totalFramesRead = 0; + while (frameCount > 0) { + // Read from the in-memory buffer first. + while (pVorbis->framesRemaining > 0 && frameCount > 0) { + for (ma_uint32 iChannel = 0; iChannel < pDecoder->internalChannels; ++iChannel) { + pSamplesOutF[0] = pVorbis->ppPacketData[iChannel][pVorbis->framesConsumed]; + pSamplesOutF += 1; + } + + pVorbis->framesConsumed += 1; + pVorbis->framesRemaining -= 1; + frameCount -= 1; + totalFramesRead += 1; + } + + if (frameCount == 0) { + break; + } + + ma_assert(pVorbis->framesRemaining == 0); + + // We've run out of cached frames, so decode the next packet and continue iteration. + do + { + if (pVorbis->dataSize > INT_MAX) { + break; // Too big. + } + + int samplesRead = 0; + int consumedDataSize = stb_vorbis_decode_frame_pushdata(pVorbis->pInternalVorbis, pVorbis->pData, (int)pVorbis->dataSize, NULL, (float***)&pVorbis->ppPacketData, &samplesRead); + if (consumedDataSize != 0) { + size_t leftoverDataSize = (pVorbis->dataSize - (size_t)consumedDataSize); + for (size_t i = 0; i < leftoverDataSize; ++i) { + pVorbis->pData[i] = pVorbis->pData[i + consumedDataSize]; + } + + pVorbis->dataSize = leftoverDataSize; + pVorbis->framesConsumed = 0; + pVorbis->framesRemaining = samplesRead; + break; + } else { + // Need more data. If there's any room in the existing buffer allocation fill that first. Otherwise expand. + if (pVorbis->dataCapacity == pVorbis->dataSize) { + // No room. Expand. + pVorbis->dataCapacity += MA_VORBIS_DATA_CHUNK_SIZE; + ma_uint8* pNewData = (ma_uint8*)ma_realloc(pVorbis->pData, pVorbis->dataCapacity); + if (pNewData == NULL) { + return totalFramesRead; // Out of memory. + } + + pVorbis->pData = pNewData; + } + + // Fill in a chunk. + size_t bytesRead = ma_decoder_read_bytes(pDecoder, pVorbis->pData + pVorbis->dataSize, (pVorbis->dataCapacity - pVorbis->dataSize)); + if (bytesRead == 0) { + return totalFramesRead; // Error reading more data. + } + + pVorbis->dataSize += bytesRead; + } + } while (MA_TRUE); + } + + return totalFramesRead; +} + +ma_result ma_vorbis_decoder_seek_to_pcm_frame(ma_vorbis_decoder* pVorbis, ma_decoder* pDecoder, ma_uint64 frameIndex) +{ + ma_assert(pVorbis != NULL); + ma_assert(pDecoder != NULL); + + // This is terribly inefficient because stb_vorbis does not have a good seeking solution with it's push API. Currently this just performs + // a full decode right from the start of the stream. Later on I'll need to write a layer that goes through all of the Ogg pages until we + // find the one containing the sample we need. Then we know exactly where to seek for stb_vorbis. + if (!ma_decoder_seek_bytes(pDecoder, 0, ma_seek_origin_start)) { + return MA_ERROR; + } + + stb_vorbis_flush_pushdata(pVorbis->pInternalVorbis); + pVorbis->framesConsumed = 0; + pVorbis->framesRemaining = 0; + pVorbis->dataSize = 0; + + float buffer[4096]; + while (frameIndex > 0) { + ma_uint32 framesToRead = ma_countof(buffer)/pDecoder->internalChannels; + if (framesToRead > frameIndex) { + framesToRead = (ma_uint32)frameIndex; + } + + ma_uint32 framesRead = ma_vorbis_decoder_read_pcm_frames(pVorbis, pDecoder, buffer, framesToRead); + if (framesRead == 0) { + return MA_ERROR; + } + + frameIndex -= framesRead; + } + + return MA_SUCCESS; +} + + +ma_result ma_decoder_internal_on_seek_to_pcm_frame__vorbis(ma_decoder* pDecoder, ma_uint64 frameIndex) +{ + ma_assert(pDecoder != NULL); + + ma_vorbis_decoder* pVorbis = (ma_vorbis_decoder*)pDecoder->pInternalDecoder; + ma_assert(pVorbis != NULL); + + return ma_vorbis_decoder_seek_to_pcm_frame(pVorbis, pDecoder, frameIndex); +} + +ma_result ma_decoder_internal_on_uninit__vorbis(ma_decoder* pDecoder) +{ + ma_vorbis_decoder* pVorbis = (ma_vorbis_decoder*)pDecoder->pInternalDecoder; + ma_assert(pVorbis != NULL); + + stb_vorbis_close(pVorbis->pInternalVorbis); + ma_free(pVorbis->pData); + ma_free(pVorbis); + + return MA_SUCCESS; +} + +ma_uint32 ma_decoder_internal_on_read_pcm_frames__vorbis(ma_pcm_converter* pDSP, void* pSamplesOut, ma_uint32 frameCount, void* pUserData) +{ + (void)pDSP; + + ma_decoder* pDecoder = (ma_decoder*)pUserData; + ma_assert(pDecoder != NULL); + ma_assert(pDecoder->internalFormat == ma_format_f32); + + ma_vorbis_decoder* pVorbis = (ma_vorbis_decoder*)pDecoder->pInternalDecoder; + ma_assert(pVorbis != NULL); + + return ma_vorbis_decoder_read_pcm_frames(pVorbis, pDecoder, pSamplesOut, frameCount); +} + +ma_result ma_decoder_init_vorbis__internal(const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_assert(pConfig != NULL); + ma_assert(pDecoder != NULL); + + stb_vorbis* pInternalVorbis = NULL; + + // We grow the buffer in chunks. + size_t dataSize = 0; + size_t dataCapacity = 0; + ma_uint8* pData = NULL; + do + { + // Allocate memory for a new chunk. + dataCapacity += MA_VORBIS_DATA_CHUNK_SIZE; + ma_uint8* pNewData = (ma_uint8*)ma_realloc(pData, dataCapacity); + if (pNewData == NULL) { + ma_free(pData); + return MA_OUT_OF_MEMORY; + } + + pData = pNewData; + + // Fill in a chunk. + size_t bytesRead = ma_decoder_read_bytes(pDecoder, pData + dataSize, (dataCapacity - dataSize)); + if (bytesRead == 0) { + return MA_ERROR; + } + + dataSize += bytesRead; + if (dataSize > INT_MAX) { + return MA_ERROR; // Too big. + } + + int vorbisError = 0; + int consumedDataSize = 0; + pInternalVorbis = stb_vorbis_open_pushdata(pData, (int)dataSize, &consumedDataSize, &vorbisError, NULL); + if (pInternalVorbis != NULL) { + // If we get here it means we were able to open the stb_vorbis decoder. There may be some leftover bytes in our buffer, so + // we need to move those bytes down to the front of the buffer since they'll be needed for future decoding. + size_t leftoverDataSize = (dataSize - (size_t)consumedDataSize); + for (size_t i = 0; i < leftoverDataSize; ++i) { + pData[i] = pData[i + consumedDataSize]; + } + + dataSize = leftoverDataSize; + break; // Success. + } else { + if (vorbisError == VORBIS_need_more_data) { + continue; + } else { + return MA_ERROR; // Failed to open the stb_vorbis decoder. + } + } + } while (MA_TRUE); + + + // If we get here it means we successfully opened the Vorbis decoder. + stb_vorbis_info vorbisInfo = stb_vorbis_get_info(pInternalVorbis); + + // Don't allow more than MA_MAX_CHANNELS channels. + if (vorbisInfo.channels > MA_MAX_CHANNELS) { + stb_vorbis_close(pInternalVorbis); + ma_free(pData); + return MA_ERROR; // Too many channels. + } + + size_t vorbisDataSize = sizeof(ma_vorbis_decoder) + sizeof(float)*vorbisInfo.max_frame_size; + ma_vorbis_decoder* pVorbis = (ma_vorbis_decoder*)ma_malloc(vorbisDataSize); + if (pVorbis == NULL) { + stb_vorbis_close(pInternalVorbis); + ma_free(pData); + return MA_OUT_OF_MEMORY; + } + + ma_zero_memory(pVorbis, vorbisDataSize); + pVorbis->pInternalVorbis = pInternalVorbis; + pVorbis->pData = pData; + pVorbis->dataSize = dataSize; + pVorbis->dataCapacity = dataCapacity; + + pDecoder->onSeekToPCMFrame = ma_decoder_internal_on_seek_to_pcm_frame__vorbis; + pDecoder->onUninit = ma_decoder_internal_on_uninit__vorbis; + pDecoder->pInternalDecoder = pVorbis; + + // The internal format is always f32. + pDecoder->internalFormat = ma_format_f32; + pDecoder->internalChannels = vorbisInfo.channels; + pDecoder->internalSampleRate = vorbisInfo.sample_rate; + ma_get_standard_channel_map(ma_standard_channel_map_vorbis, pDecoder->internalChannels, pDecoder->internalChannelMap); + + ma_result result = ma_decoder__init_dsp(pDecoder, pConfig, ma_decoder_internal_on_read_pcm_frames__vorbis); + if (result != MA_SUCCESS) { + stb_vorbis_close(pVorbis->pInternalVorbis); + ma_free(pVorbis->pData); + ma_free(pVorbis); + return result; + } + + return MA_SUCCESS; +} +#endif + +// MP3 +#ifdef dr_mp3_h +#define MA_HAS_MP3 + +size_t ma_decoder_internal_on_read__mp3(void* pUserData, void* pBufferOut, size_t bytesToRead) +{ + ma_decoder* pDecoder = (ma_decoder*)pUserData; + ma_assert(pDecoder != NULL); + + return ma_decoder_read_bytes(pDecoder, pBufferOut, bytesToRead); +} + +drmp3_bool32 ma_decoder_internal_on_seek__mp3(void* pUserData, int offset, drmp3_seek_origin origin) +{ + ma_decoder* pDecoder = (ma_decoder*)pUserData; + ma_assert(pDecoder != NULL); + + return ma_decoder_seek_bytes(pDecoder, offset, (origin == drmp3_seek_origin_start) ? ma_seek_origin_start : ma_seek_origin_current); +} + +ma_uint32 ma_decoder_internal_on_read_pcm_frames__mp3(ma_pcm_converter* pDSP, void* pSamplesOut, ma_uint32 frameCount, void* pUserData) +{ + (void)pDSP; + + ma_decoder* pDecoder = (ma_decoder*)pUserData; + ma_assert(pDecoder != NULL); + ma_assert(pDecoder->internalFormat == ma_format_f32); + + drmp3* pMP3 = (drmp3*)pDecoder->pInternalDecoder; + ma_assert(pMP3 != NULL); + + return (ma_uint32)drmp3_read_pcm_frames_f32(pMP3, frameCount, (float*)pSamplesOut); +} + +ma_result ma_decoder_internal_on_seek_to_pcm_frame__mp3(ma_decoder* pDecoder, ma_uint64 frameIndex) +{ + drmp3* pMP3 = (drmp3*)pDecoder->pInternalDecoder; + ma_assert(pMP3 != NULL); + + drmp3_bool32 result = drmp3_seek_to_pcm_frame(pMP3, frameIndex); + if (result) { + return MA_SUCCESS; + } else { + return MA_ERROR; + } +} + +ma_result ma_decoder_internal_on_uninit__mp3(ma_decoder* pDecoder) +{ + drmp3_uninit((drmp3*)pDecoder->pInternalDecoder); + ma_free(pDecoder->pInternalDecoder); + return MA_SUCCESS; +} + +ma_result ma_decoder_init_mp3__internal(const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_assert(pConfig != NULL); + ma_assert(pDecoder != NULL); + + drmp3* pMP3 = (drmp3*)ma_malloc(sizeof(*pMP3)); + if (pMP3 == NULL) { + return MA_OUT_OF_MEMORY; + } + + // Try opening the decoder first. MP3 can have variable sample rates (it's per frame/packet). We therefore need + // to use some smarts to determine the most appropriate internal sample rate. These are the rules we're going + // to use: + // + // Sample Rates + // 1) If an output sample rate is specified in pConfig we just use that. Otherwise; + // 2) Fall back to 44100. + // + // The internal channel count is always stereo, and the internal format is always f32. + drmp3_config mp3Config; + ma_zero_object(&mp3Config); + mp3Config.outputChannels = 2; + mp3Config.outputSampleRate = (pConfig->sampleRate != 0) ? pConfig->sampleRate : 44100; + if (!drmp3_init(pMP3, ma_decoder_internal_on_read__mp3, ma_decoder_internal_on_seek__mp3, pDecoder, &mp3Config)) { + return MA_ERROR; + } + + // If we get here it means we successfully initialized the MP3 decoder. We can now initialize the rest of the ma_decoder. + pDecoder->onSeekToPCMFrame = ma_decoder_internal_on_seek_to_pcm_frame__mp3; + pDecoder->onUninit = ma_decoder_internal_on_uninit__mp3; + pDecoder->pInternalDecoder = pMP3; + + // Internal format. + pDecoder->internalFormat = ma_format_f32; + pDecoder->internalChannels = pMP3->channels; + pDecoder->internalSampleRate = pMP3->sampleRate; + ma_get_standard_channel_map(ma_standard_channel_map_default, pDecoder->internalChannels, pDecoder->internalChannelMap); + + ma_result result = ma_decoder__init_dsp(pDecoder, pConfig, ma_decoder_internal_on_read_pcm_frames__mp3); + if (result != MA_SUCCESS) { + ma_free(pMP3); + return result; + } + + return MA_SUCCESS; +} +#endif + +// Raw +ma_uint32 ma_decoder_internal_on_read_pcm_frames__raw(ma_pcm_converter* pDSP, void* pSamplesOut, ma_uint32 frameCount, void* pUserData) +{ + (void)pDSP; + + ma_decoder* pDecoder = (ma_decoder*)pUserData; + ma_assert(pDecoder != NULL); + + // For raw decoding we just read directly from the decoder's callbacks. + ma_uint32 bpf = ma_get_bytes_per_frame(pDecoder->internalFormat, pDecoder->internalChannels); + return (ma_uint32)ma_decoder_read_bytes(pDecoder, pSamplesOut, frameCount * bpf) / bpf; +} + +ma_result ma_decoder_internal_on_seek_to_pcm_frame__raw(ma_decoder* pDecoder, ma_uint64 frameIndex) +{ + ma_assert(pDecoder != NULL); + + if (pDecoder->onSeek == NULL) { + return MA_ERROR; + } + + ma_bool32 result = MA_FALSE; + + // The callback uses a 32 bit integer whereas we use a 64 bit unsigned integer. We just need to continuously seek until we're at the correct position. + ma_uint64 totalBytesToSeek = frameIndex * ma_get_bytes_per_frame(pDecoder->internalFormat, pDecoder->internalChannels); + if (totalBytesToSeek < 0x7FFFFFFF) { + // Simple case. + result = ma_decoder_seek_bytes(pDecoder, (int)(frameIndex * ma_get_bytes_per_frame(pDecoder->internalFormat, pDecoder->internalChannels)), ma_seek_origin_start); + } else { + // Complex case. Start by doing a seek relative to the start. Then keep looping using offset seeking. + result = ma_decoder_seek_bytes(pDecoder, 0x7FFFFFFF, ma_seek_origin_start); + if (result == MA_TRUE) { + totalBytesToSeek -= 0x7FFFFFFF; + + while (totalBytesToSeek > 0) { + ma_uint64 bytesToSeekThisIteration = totalBytesToSeek; + if (bytesToSeekThisIteration > 0x7FFFFFFF) { + bytesToSeekThisIteration = 0x7FFFFFFF; + } + + result = ma_decoder_seek_bytes(pDecoder, (int)bytesToSeekThisIteration, ma_seek_origin_current); + if (result != MA_TRUE) { + break; + } + + totalBytesToSeek -= bytesToSeekThisIteration; + } + } + } + + if (result) { + return MA_SUCCESS; + } else { + return MA_ERROR; + } +} + +ma_result ma_decoder_internal_on_uninit__raw(ma_decoder* pDecoder) +{ + (void)pDecoder; + return MA_SUCCESS; +} + +ma_result ma_decoder_init_raw__internal(const ma_decoder_config* pConfigIn, const ma_decoder_config* pConfigOut, ma_decoder* pDecoder) +{ + ma_assert(pConfigIn != NULL); + ma_assert(pConfigOut != NULL); + ma_assert(pDecoder != NULL); + + pDecoder->onSeekToPCMFrame = ma_decoder_internal_on_seek_to_pcm_frame__raw; + pDecoder->onUninit = ma_decoder_internal_on_uninit__raw; + + // Internal format. + pDecoder->internalFormat = pConfigIn->format; + pDecoder->internalChannels = pConfigIn->channels; + pDecoder->internalSampleRate = pConfigIn->sampleRate; + ma_channel_map_copy(pDecoder->internalChannelMap, pConfigIn->channelMap, pConfigIn->channels); + + ma_result result = ma_decoder__init_dsp(pDecoder, pConfigOut, ma_decoder_internal_on_read_pcm_frames__raw); + if (result != MA_SUCCESS) { + return result; + } + + return MA_SUCCESS; +} + +ma_result ma_decoder__preinit(ma_decoder_read_proc onRead, ma_decoder_seek_proc onSeek, void* pUserData, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_assert(pConfig != NULL); + + if (pDecoder == NULL) { + return MA_INVALID_ARGS; + } + + ma_zero_object(pDecoder); + + if (onRead == NULL || onSeek == NULL) { + return MA_INVALID_ARGS; + } + + pDecoder->onRead = onRead; + pDecoder->onSeek = onSeek; + pDecoder->pUserData = pUserData; + + (void)pConfig; + return MA_SUCCESS; +} + +ma_result ma_decoder_init_wav(ma_decoder_read_proc onRead, ma_decoder_seek_proc onSeek, void* pUserData, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_decoder_config config = ma_decoder_config_init_copy(pConfig); + + ma_result result = ma_decoder__preinit(onRead, onSeek, pUserData, &config, pDecoder); + if (result != MA_SUCCESS) { + return result; + } + +#ifdef MA_HAS_WAV + return ma_decoder_init_wav__internal(&config, pDecoder); +#else + return MA_NO_BACKEND; +#endif +} + +ma_result ma_decoder_init_flac(ma_decoder_read_proc onRead, ma_decoder_seek_proc onSeek, void* pUserData, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_decoder_config config = ma_decoder_config_init_copy(pConfig); + + ma_result result = ma_decoder__preinit(onRead, onSeek, pUserData, &config, pDecoder); + if (result != MA_SUCCESS) { + return result; + } + +#ifdef MA_HAS_FLAC + return ma_decoder_init_flac__internal(&config, pDecoder); +#else + return MA_NO_BACKEND; +#endif +} + +ma_result ma_decoder_init_vorbis(ma_decoder_read_proc onRead, ma_decoder_seek_proc onSeek, void* pUserData, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_decoder_config config = ma_decoder_config_init_copy(pConfig); + + ma_result result = ma_decoder__preinit(onRead, onSeek, pUserData, &config, pDecoder); + if (result != MA_SUCCESS) { + return result; + } + +#ifdef MA_HAS_VORBIS + return ma_decoder_init_vorbis__internal(&config, pDecoder); +#else + return MA_NO_BACKEND; +#endif +} + +ma_result ma_decoder_init_mp3(ma_decoder_read_proc onRead, ma_decoder_seek_proc onSeek, void* pUserData, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_decoder_config config = ma_decoder_config_init_copy(pConfig); + + ma_result result = ma_decoder__preinit(onRead, onSeek, pUserData, &config, pDecoder); + if (result != MA_SUCCESS) { + return result; + } + +#ifdef MA_HAS_MP3 + return ma_decoder_init_mp3__internal(&config, pDecoder); +#else + return MA_NO_BACKEND; +#endif +} + +ma_result ma_decoder_init_raw(ma_decoder_read_proc onRead, ma_decoder_seek_proc onSeek, void* pUserData, const ma_decoder_config* pConfigIn, const ma_decoder_config* pConfigOut, ma_decoder* pDecoder) +{ + ma_decoder_config config = ma_decoder_config_init_copy(pConfigOut); + + ma_result result = ma_decoder__preinit(onRead, onSeek, pUserData, &config, pDecoder); + if (result != MA_SUCCESS) { + return result; + } + + return ma_decoder_init_raw__internal(pConfigIn, &config, pDecoder); +} + +ma_result ma_decoder_init__internal(ma_decoder_read_proc onRead, ma_decoder_seek_proc onSeek, void* pUserData, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_assert(pConfig != NULL); + ma_assert(pDecoder != NULL); + + // Silence some warnings in the case that we don't have any decoder backends enabled. + (void)onRead; + (void)onSeek; + (void)pUserData; + (void)pConfig; + (void)pDecoder; + + // We use trial and error to open a decoder. + ma_result result = MA_NO_BACKEND; + +#ifdef MA_HAS_WAV + if (result != MA_SUCCESS) { + result = ma_decoder_init_wav__internal(pConfig, pDecoder); + if (result != MA_SUCCESS) { + onSeek(pDecoder, 0, ma_seek_origin_start); + } + } +#endif +#ifdef MA_HAS_FLAC + if (result != MA_SUCCESS) { + result = ma_decoder_init_flac__internal(pConfig, pDecoder); + if (result != MA_SUCCESS) { + onSeek(pDecoder, 0, ma_seek_origin_start); + } + } +#endif +#ifdef MA_HAS_VORBIS + if (result != MA_SUCCESS) { + result = ma_decoder_init_vorbis__internal(pConfig, pDecoder); + if (result != MA_SUCCESS) { + onSeek(pDecoder, 0, ma_seek_origin_start); + } + } +#endif +#ifdef MA_HAS_MP3 + if (result != MA_SUCCESS) { + result = ma_decoder_init_mp3__internal(pConfig, pDecoder); + if (result != MA_SUCCESS) { + onSeek(pDecoder, 0, ma_seek_origin_start); + } + } +#endif + + if (result != MA_SUCCESS) { + return result; + } + + return result; +} + +ma_result ma_decoder_init(ma_decoder_read_proc onRead, ma_decoder_seek_proc onSeek, void* pUserData, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_decoder_config config = ma_decoder_config_init_copy(pConfig); + + ma_result result = ma_decoder__preinit(onRead, onSeek, pUserData, &config, pDecoder); + if (result != MA_SUCCESS) { + return result; + } + + return ma_decoder_init__internal(onRead, onSeek, pUserData, &config, pDecoder); +} + + +size_t ma_decoder__on_read_memory(ma_decoder* pDecoder, void* pBufferOut, size_t bytesToRead) +{ + ma_assert(pDecoder->memory.dataSize >= pDecoder->memory.currentReadPos); + + size_t bytesRemaining = pDecoder->memory.dataSize - pDecoder->memory.currentReadPos; + if (bytesToRead > bytesRemaining) { + bytesToRead = bytesRemaining; + } + + if (bytesToRead > 0) { + ma_copy_memory(pBufferOut, pDecoder->memory.pData + pDecoder->memory.currentReadPos, bytesToRead); + pDecoder->memory.currentReadPos += bytesToRead; + } + + return bytesToRead; +} + +ma_bool32 ma_decoder__on_seek_memory(ma_decoder* pDecoder, int byteOffset, ma_seek_origin origin) +{ + if (origin == ma_seek_origin_current) { + if (byteOffset > 0) { + if (pDecoder->memory.currentReadPos + byteOffset > pDecoder->memory.dataSize) { + byteOffset = (int)(pDecoder->memory.dataSize - pDecoder->memory.currentReadPos); // Trying to seek too far forward. + } + } else { + if (pDecoder->memory.currentReadPos < (size_t)-byteOffset) { + byteOffset = -(int)pDecoder->memory.currentReadPos; // Trying to seek too far backwards. + } + } + + // This will never underflow thanks to the clamps above. + pDecoder->memory.currentReadPos += byteOffset; + } else { + if ((ma_uint32)byteOffset <= pDecoder->memory.dataSize) { + pDecoder->memory.currentReadPos = byteOffset; + } else { + pDecoder->memory.currentReadPos = pDecoder->memory.dataSize; // Trying to seek too far forward. + } + } + + return MA_TRUE; +} + +ma_result ma_decoder__preinit_memory(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_result result = ma_decoder__preinit(ma_decoder__on_read_memory, ma_decoder__on_seek_memory, NULL, pConfig, pDecoder); + if (result != MA_SUCCESS) { + return result; + } + + if (pData == NULL || dataSize == 0) { + return MA_INVALID_ARGS; + } + + pDecoder->memory.pData = (const ma_uint8*)pData; + pDecoder->memory.dataSize = dataSize; + pDecoder->memory.currentReadPos = 0; + + (void)pConfig; + return MA_SUCCESS; +} + +ma_result ma_decoder_init_memory(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_decoder_config config = ma_decoder_config_init_copy(pConfig); // Make sure the config is not NULL. + + ma_result result = ma_decoder__preinit_memory(pData, dataSize, &config, pDecoder); + if (result != MA_SUCCESS) { + return result; + } + + return ma_decoder_init__internal(ma_decoder__on_read_memory, ma_decoder__on_seek_memory, NULL, &config, pDecoder); +} + +ma_result ma_decoder_init_memory_wav(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_decoder_config config = ma_decoder_config_init_copy(pConfig); // Make sure the config is not NULL. + + ma_result result = ma_decoder__preinit_memory(pData, dataSize, &config, pDecoder); + if (result != MA_SUCCESS) { + return result; + } + +#ifdef MA_HAS_WAV + return ma_decoder_init_wav__internal(&config, pDecoder); +#else + return MA_NO_BACKEND; +#endif +} + +ma_result ma_decoder_init_memory_flac(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_decoder_config config = ma_decoder_config_init_copy(pConfig); // Make sure the config is not NULL. + + ma_result result = ma_decoder__preinit_memory(pData, dataSize, &config, pDecoder); + if (result != MA_SUCCESS) { + return result; + } + +#ifdef MA_HAS_FLAC + return ma_decoder_init_flac__internal(&config, pDecoder); +#else + return MA_NO_BACKEND; +#endif +} + +ma_result ma_decoder_init_memory_vorbis(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_decoder_config config = ma_decoder_config_init_copy(pConfig); // Make sure the config is not NULL. + + ma_result result = ma_decoder__preinit_memory(pData, dataSize, &config, pDecoder); + if (result != MA_SUCCESS) { + return result; + } + +#ifdef MA_HAS_VORBIS + return ma_decoder_init_vorbis__internal(&config, pDecoder); +#else + return MA_NO_BACKEND; +#endif +} + +ma_result ma_decoder_init_memory_mp3(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_decoder_config config = ma_decoder_config_init_copy(pConfig); // Make sure the config is not NULL. + + ma_result result = ma_decoder__preinit_memory(pData, dataSize, &config, pDecoder); + if (result != MA_SUCCESS) { + return result; + } + +#ifdef MA_HAS_MP3 + return ma_decoder_init_mp3__internal(&config, pDecoder); +#else + return MA_NO_BACKEND; +#endif +} + +ma_result ma_decoder_init_memory_raw(const void* pData, size_t dataSize, const ma_decoder_config* pConfigIn, const ma_decoder_config* pConfigOut, ma_decoder* pDecoder) +{ + ma_decoder_config config = ma_decoder_config_init_copy(pConfigOut); // Make sure the config is not NULL. + + ma_result result = ma_decoder__preinit_memory(pData, dataSize, &config, pDecoder); + if (result != MA_SUCCESS) { + return result; + } + + return ma_decoder_init_raw__internal(pConfigIn, &config, pDecoder); +} + +#ifndef MA_NO_STDIO +#include +#if !defined(_MSC_VER) && !defined(__DMC__) +#include // For strcasecmp(). +#endif + +const char* ma_path_file_name(const char* path) +{ + if (path == NULL) { + return NULL; + } + + const char* fileName = path; + + // We just loop through the path until we find the last slash. + while (path[0] != '\0') { + if (path[0] == '/' || path[0] == '\\') { + fileName = path; + } + + path += 1; + } + + // At this point the file name is sitting on a slash, so just move forward. + while (fileName[0] != '\0' && (fileName[0] == '/' || fileName[0] == '\\')) { + fileName += 1; + } + + return fileName; +} + +const char* ma_path_extension(const char* path) +{ + if (path == NULL) { + path = ""; + } + + const char* extension = ma_path_file_name(path); + const char* lastOccurance = NULL; + + // Just find the last '.' and return. + while (extension[0] != '\0') { + if (extension[0] == '.') { + extension += 1; + lastOccurance = extension; + } + + extension += 1; + } + + return (lastOccurance != NULL) ? lastOccurance : extension; +} + +ma_bool32 ma_path_extension_equal(const char* path, const char* extension) +{ + if (path == NULL || extension == NULL) { + return MA_FALSE; + } + + const char* ext1 = extension; + const char* ext2 = ma_path_extension(path); + +#if defined(_MSC_VER) || defined(__DMC__) + return _stricmp(ext1, ext2) == 0; +#else + return strcasecmp(ext1, ext2) == 0; +#endif +} + +size_t ma_decoder__on_read_stdio(ma_decoder* pDecoder, void* pBufferOut, size_t bytesToRead) +{ + return fread(pBufferOut, 1, bytesToRead, (FILE*)pDecoder->pUserData); +} + +ma_bool32 ma_decoder__on_seek_stdio(ma_decoder* pDecoder, int byteOffset, ma_seek_origin origin) +{ + return fseek((FILE*)pDecoder->pUserData, byteOffset, (origin == ma_seek_origin_current) ? SEEK_CUR : SEEK_SET) == 0; +} + +ma_result ma_decoder__preinit_file(const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + if (pDecoder == NULL) { + return MA_INVALID_ARGS; + } + + ma_zero_object(pDecoder); + + if (pFilePath == NULL || pFilePath[0] == '\0') { + return MA_INVALID_ARGS; + } + + FILE* pFile; +#if defined(_MSC_VER) && _MSC_VER >= 1400 + if (fopen_s(&pFile, pFilePath, "rb") != 0) { + return MA_ERROR; + } +#else + pFile = fopen(pFilePath, "rb"); + if (pFile == NULL) { + return MA_ERROR; + } +#endif + + // We need to manually set the user data so the calls to ma_decoder__on_seek_stdio() succeed. + pDecoder->pUserData = pFile; + + (void)pConfig; + return MA_SUCCESS; +} + +ma_result ma_decoder_init_file(const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_result result = ma_decoder__preinit_file(pFilePath, pConfig, pDecoder); // This sets pDecoder->pUserData to a FILE*. + if (result != MA_SUCCESS) { + return result; + } + + // WAV + if (ma_path_extension_equal(pFilePath, "wav")) { + result = ma_decoder_init_wav(ma_decoder__on_read_stdio, ma_decoder__on_seek_stdio, pDecoder->pUserData, pConfig, pDecoder); + if (result == MA_SUCCESS) { + return MA_SUCCESS; + } + + ma_decoder__on_seek_stdio(pDecoder, 0, ma_seek_origin_start); + } + + // FLAC + if (ma_path_extension_equal(pFilePath, "flac")) { + result = ma_decoder_init_flac(ma_decoder__on_read_stdio, ma_decoder__on_seek_stdio, pDecoder->pUserData, pConfig, pDecoder); + if (result == MA_SUCCESS) { + return MA_SUCCESS; + } + + ma_decoder__on_seek_stdio(pDecoder, 0, ma_seek_origin_start); + } + + // MP3 + if (ma_path_extension_equal(pFilePath, "mp3")) { + result = ma_decoder_init_mp3(ma_decoder__on_read_stdio, ma_decoder__on_seek_stdio, pDecoder->pUserData, pConfig, pDecoder); + if (result == MA_SUCCESS) { + return MA_SUCCESS; + } + + ma_decoder__on_seek_stdio(pDecoder, 0, ma_seek_origin_start); + } + + // Trial and error. + return ma_decoder_init(ma_decoder__on_read_stdio, ma_decoder__on_seek_stdio, pDecoder->pUserData, pConfig, pDecoder); +} + +ma_result ma_decoder_init_file_wav(const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_result result = ma_decoder__preinit_file(pFilePath, pConfig, pDecoder); + if (result != MA_SUCCESS) { + return result; + } + + return ma_decoder_init_wav(ma_decoder__on_read_stdio, ma_decoder__on_seek_stdio, pDecoder->pUserData, pConfig, pDecoder); +} + +ma_result ma_decoder_init_file_flac(const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_result result = ma_decoder__preinit_file(pFilePath, pConfig, pDecoder); + if (result != MA_SUCCESS) { + return result; + } + + return ma_decoder_init_flac(ma_decoder__on_read_stdio, ma_decoder__on_seek_stdio, pDecoder->pUserData, pConfig, pDecoder); +} + +ma_result ma_decoder_init_file_vorbis(const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_result result = ma_decoder__preinit_file(pFilePath, pConfig, pDecoder); + if (result != MA_SUCCESS) { + return result; + } + + return ma_decoder_init_vorbis(ma_decoder__on_read_stdio, ma_decoder__on_seek_stdio, pDecoder->pUserData, pConfig, pDecoder); +} + +ma_result ma_decoder_init_file_mp3(const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder) +{ + ma_result result = ma_decoder__preinit_file(pFilePath, pConfig, pDecoder); + if (result != MA_SUCCESS) { + return result; + } + + return ma_decoder_init_mp3(ma_decoder__on_read_stdio, ma_decoder__on_seek_stdio, pDecoder->pUserData, pConfig, pDecoder); +} +#endif + +ma_result ma_decoder_uninit(ma_decoder* pDecoder) +{ + if (pDecoder == NULL) { + return MA_INVALID_ARGS; + } + + if (pDecoder->onUninit) { + pDecoder->onUninit(pDecoder); + } + +#ifndef MA_NO_STDIO + // If we have a file handle, close it. + if (pDecoder->onRead == ma_decoder__on_read_stdio) { + fclose((FILE*)pDecoder->pUserData); + } +#endif + + return MA_SUCCESS; +} + +ma_uint64 ma_decoder_read_pcm_frames(ma_decoder* pDecoder, void* pFramesOut, ma_uint64 frameCount) +{ + if (pDecoder == NULL) return 0; + + return ma_pcm_converter_read(&pDecoder->dsp, pFramesOut, frameCount); +} + +ma_result ma_decoder_seek_to_pcm_frame(ma_decoder* pDecoder, ma_uint64 frameIndex) +{ + if (pDecoder == NULL) return 0; + + if (pDecoder->onSeekToPCMFrame) { + return pDecoder->onSeekToPCMFrame(pDecoder, frameIndex); + } + + // Should never get here, but if we do it means onSeekToPCMFrame was not set by the backend. + return MA_INVALID_ARGS; +} + + +ma_result ma_decoder__full_decode_and_uninit(ma_decoder* pDecoder, ma_decoder_config* pConfigOut, ma_uint64* pFrameCountOut, void** ppPCMFramesOut) +{ + ma_assert(pDecoder != NULL); + + ma_uint64 totalFrameCount = 0; + ma_uint64 bpf = ma_get_bytes_per_frame(pDecoder->outputFormat, pDecoder->outputChannels); + + // The frame count is unknown until we try reading. Thus, we just run in a loop. + ma_uint64 dataCapInFrames = 0; + void* pPCMFramesOut = NULL; + for (;;) { + // Make room if there's not enough. + if (totalFrameCount == dataCapInFrames) { + ma_uint64 newDataCapInFrames = dataCapInFrames*2; + if (newDataCapInFrames == 0) { + newDataCapInFrames = 4096; + } + + if ((newDataCapInFrames * bpf) > MA_SIZE_MAX) { + ma_free(pPCMFramesOut); + return MA_TOO_LARGE; + } + + + void* pNewPCMFramesOut = (void*)ma_realloc(pPCMFramesOut, (size_t)(newDataCapInFrames * bpf)); + if (pNewPCMFramesOut == NULL) { + ma_free(pPCMFramesOut); + return MA_OUT_OF_MEMORY; + } + + dataCapInFrames = newDataCapInFrames; + pPCMFramesOut = pNewPCMFramesOut; + } + + ma_uint64 frameCountToTryReading = dataCapInFrames - totalFrameCount; + ma_assert(frameCountToTryReading > 0); + + ma_uint64 framesJustRead = ma_decoder_read_pcm_frames(pDecoder, (ma_uint8*)pPCMFramesOut + (totalFrameCount * bpf), frameCountToTryReading); + totalFrameCount += framesJustRead; + + if (framesJustRead < frameCountToTryReading) { + break; + } + } + + + if (pConfigOut != NULL) { + pConfigOut->format = pDecoder->outputFormat; + pConfigOut->channels = pDecoder->outputChannels; + pConfigOut->sampleRate = pDecoder->outputSampleRate; + ma_channel_map_copy(pConfigOut->channelMap, pDecoder->outputChannelMap, pDecoder->outputChannels); + } + + if (ppPCMFramesOut != NULL) { + *ppPCMFramesOut = pPCMFramesOut; + } else { + ma_free(pPCMFramesOut); + } + + if (pFrameCountOut != NULL) { + *pFrameCountOut = totalFrameCount; + } + + ma_decoder_uninit(pDecoder); + return MA_SUCCESS; +} + +#ifndef MA_NO_STDIO +ma_result ma_decode_file(const char* pFilePath, ma_decoder_config* pConfig, ma_uint64* pFrameCountOut, void** ppPCMFramesOut) +{ + if (pFrameCountOut != NULL) { + *pFrameCountOut = 0; + } + if (ppPCMFramesOut != NULL) { + *ppPCMFramesOut = NULL; + } + + if (pFilePath == NULL) { + return MA_INVALID_ARGS; + } + + ma_decoder_config config = ma_decoder_config_init_copy(pConfig); + + ma_decoder decoder; + ma_result result = ma_decoder_init_file(pFilePath, &config, &decoder); + if (result != MA_SUCCESS) { + return result; + } + + return ma_decoder__full_decode_and_uninit(&decoder, pConfig, pFrameCountOut, ppPCMFramesOut); +} +#endif + +ma_result ma_decode_memory(const void* pData, size_t dataSize, ma_decoder_config* pConfig, ma_uint64* pFrameCountOut, void** ppPCMFramesOut) +{ + if (pFrameCountOut != NULL) { + *pFrameCountOut = 0; + } + if (ppPCMFramesOut != NULL) { + *ppPCMFramesOut = NULL; + } + + if (pData == NULL || dataSize == 0) { + return MA_INVALID_ARGS; + } + + ma_decoder_config config = ma_decoder_config_init_copy(pConfig); + + ma_decoder decoder; + ma_result result = ma_decoder_init_memory(pData, dataSize, &config, &decoder); + if (result != MA_SUCCESS) { + return result; + } + + return ma_decoder__full_decode_and_uninit(&decoder, pConfig, pFrameCountOut, ppPCMFramesOut); +} + +#endif // MA_NO_DECODING + + + + +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// +// GENERATION +// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +ma_result ma_sine_wave_init(double amplitude, double periodsPerSecond, ma_uint32 sampleRate, ma_sine_wave* pSineWave) +{ + if (pSineWave == NULL) { + return MA_INVALID_ARGS; + } + ma_zero_object(pSineWave); + + if (amplitude == 0 || periodsPerSecond == 0) { + return MA_INVALID_ARGS; + } + + if (amplitude > 1) { + amplitude = 1; + } + if (amplitude < -1) { + amplitude = -1; + } + + pSineWave->amplitude = amplitude; + pSineWave->periodsPerSecond = periodsPerSecond; + pSineWave->delta = MA_TAU_D / sampleRate; + pSineWave->time = 0; + + return MA_SUCCESS; +} + +ma_uint64 ma_sine_wave_read_f32(ma_sine_wave* pSineWave, ma_uint64 count, float* pSamples) +{ + return ma_sine_wave_read_f32_ex(pSineWave, count, 1, ma_stream_layout_interleaved, &pSamples); +} + +ma_uint64 ma_sine_wave_read_f32_ex(ma_sine_wave* pSineWave, ma_uint64 frameCount, ma_uint32 channels, ma_stream_layout layout, float** ppFrames) +{ + if (pSineWave == NULL) { + return 0; + } + + if (ppFrames != NULL) { + for (ma_uint64 iFrame = 0; iFrame < frameCount; iFrame += 1) { + float s = (float)(sin(pSineWave->time * pSineWave->periodsPerSecond) * pSineWave->amplitude); + pSineWave->time += pSineWave->delta; + + if (layout == ma_stream_layout_interleaved) { + for (ma_uint32 iChannel = 0; iChannel < channels; iChannel += 1) { + ppFrames[0][iFrame*channels + iChannel] = s; + } + } else { + for (ma_uint32 iChannel = 0; iChannel < channels; iChannel += 1) { + ppFrames[iChannel][iFrame] = s; + } + } + } + } else { + pSineWave->time += pSineWave->delta * frameCount; + } + + return frameCount; +} + +#if defined(_MSC_VER) + #pragma warning(pop) +#endif + +#endif /* MINIAUDIO_IMPLEMENTATION */ + +/* +BACKEND IMPLEMENTATION GUIDLINES +================================ +Context +------- +- Run-time linking if possible. +- Set whether or not it's an asynchronous backend + +Device +------ +- If a full-duplex device is requested and the backend does not support full duplex devices, have ma_device_init__[backend]() + return MA_DEVICE_TYPE_NOT_SUPPORTED. +- If exclusive mode is requested, but the backend does not support it, return MA_SHARE_MODE_NOT_SUPPORTED. If practical, try + not to fall back to a different share mode - give the client exactly what they asked for. Some backends, such as ALSA, may + not have a practical way to distinguish between the two. +- If pDevice->usingDefault* is set, prefer the device's native value if the backend supports it. Otherwise use the relevant + value from the config. +- If the configs buffer size in frames is 0, set it based on the buffer size in milliseconds, keeping in mind to handle the + case when the default sample rate is being used where practical. +- Backends must set the following members of pDevice before returning successfully from ma_device_init__[backend](): + - internalFormat + - internalChannels + - internalSampleRate + - internalChannelMap + - bufferSizeInFrames + - periods +*/ + +/* +REVISION HISTORY +================ + +v0.9 - 2019-03-06 + - Rebranded to "miniaudio". All namespaces have been renamed from "mal" to "ma". + - API CHANGE: ma_device_init() and ma_device_config_init() have changed significantly: + - The device type, device ID and user data pointer have moved from ma_device_init() to the config. + - All variations of ma_device_config_init_*() have been removed in favor of just ma_device_config_init(). + - ma_device_config_init() now takes only one parameter which is the device type. All other properties need + to be set on the returned object directly. + - The onDataCallback and onStopCallback members of ma_device_config have been renamed to "dataCallback" + and "stopCallback". + - The ID of the physical device is now split into two: one for the playback device and the other for the + capture device. This is required for full-duplex. These are named "pPlaybackDeviceID" and "pCaptureDeviceID". + - API CHANGE: The data callback has changed. It now uses a unified callback for all device types rather than + being separate for each. It now takes two pointers - one containing input data and the other output data. This + design in required for full-duplex. The return value is now void instead of the number of frames written. The + new callback looks like the following: + void data_callback(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount); + - API CHANGE: Remove the log callback parameter from ma_context_config_init(). With this change, + ma_context_config_init() now takes no parameters and the log callback is set via the structure directly. The + new policy for config initialization is that only mandatory settings are passed in to *_config_init(). The + "onLog" member of ma_context_config has been renamed to "logCallback". + - API CHANGE: Remove ma_device_get_buffer_size_in_bytes(). + - API CHANGE: Rename decoding APIs to "pcm_frames" convention. + - mal_decoder_read() -> ma_decoder_read_pcm_frames() + - mal_decoder_seek_to_frame() -> ma_decoder_seek_to_pcm_frame() + - API CHANGE: Rename sine wave reading APIs to f32 convention. + - mal_sine_wave_read() -> ma_sine_wave_read_f32() + - mal_sine_wave_read_ex() -> ma_sine_wave_read_f32_ex() + - API CHANGE: Remove some deprecated APIs + - mal_device_set_recv_callback() + - mal_device_set_send_callback() + - mal_src_set_input_sample_rate() + - mal_src_set_output_sample_rate() + - API CHANGE: Add log level to the log callback. New signature: + - void on_log(ma_context* pContext, ma_device* pDevice, ma_uint32 logLevel, const char* message) + - API CHANGE: Changes to result codes. Constants have changed and unused codes have been removed. If you're + a binding mainainer you will need to update your result code constants. + - API CHANGE: Change the order of the ma_backend enums to priority order. If you are a binding maintainer, you + will need to update. + - API CHANGE: Rename mal_dsp to ma_pcm_converter. All functions have been renamed from mal_dsp_*() to + ma_pcm_converter_*(). All structures have been renamed from mal_dsp* to ma_pcm_converter*. + - API CHANGE: Reorder parameters of ma_decoder_read_pcm_frames() to be consistent with the new parameter order scheme. + - The resampling algorithm has been changed from sinc to linear. The rationale for this is that the sinc implementation + is too inefficient right now. This will hopefully be improved at a later date. + - Device initialization will no longer fall back to shared mode if exclusive mode is requested but is unusable. + With this change, if you request an device in exclusive mode, but exclusive mode is not supported, it will not + automatically fall back to shared mode. The client will need to reinitialize the device in shared mode if that's + what they want. + - Add ring buffer API. This is ma_rb and ma_pcm_rb, the difference being that ma_rb operates on bytes and + ma_pcm_rb operates on PCM frames. + - Add Web Audio backend. This is used when compiling with Emscripten. The SDL backend, which was previously + used for web support, will be removed in a future version. + - Add AAudio backend (Android Audio). This is the new priority backend for Android. Support for AAudio starts + with Android 8. OpenSL|ES is used as a fallback for older versions of Android. + - Remove OpenAL and SDL backends. + - Fix a possible deadlock when rapidly stopping the device after it has started. + - Update documentation. + - Change licensing to a choice of public domain _or_ MIT-0 (No Attribution). + +v0.8.14 - 2018-12-16 + - Core Audio: Fix a bug where the device state is not set correctly after stopping. + - Add support for custom weights to the channel router. + - Update decoders to use updated APIs in dr_flac, dr_mp3 and dr_wav. + +v0.8.13 - 2018-12-04 + - Core Audio: Fix a bug with channel mapping. + - Fix a bug with channel routing where the back/left and back/right channels have the wrong weight. + +v0.8.12 - 2018-11-27 + - Drop support for SDL 1.2. The Emscripten build now requires "-s USE_SDL=2". + - Fix a linking error with ALSA. + - Fix a bug on iOS where the device name is not set correctly. + +v0.8.11 - 2018-11-21 + - iOS bug fixes. + - Minor tweaks to PulseAudio. + +v0.8.10 - 2018-10-21 + - Core Audio: Fix a hang when uninitializing a device. + - Fix a bug where an incorrect value is returned from ma_device_stop(). + +v0.8.9 - 2018-09-28 + - Fix a bug with the SDL backend where device initialization fails. + +v0.8.8 - 2018-09-14 + - Fix Linux build with the ALSA backend. + - Minor documentation fix. + +v0.8.7 - 2018-09-12 + - Fix a bug with UWP detection. + +v0.8.6 - 2018-08-26 + - Automatically switch the internal device when the default device is unplugged. Note that this is still in the + early stages and not all backends handle this the same way. As of this version, this will not detect a default + device switch when changed from the operating system's audio preferences (unless the backend itself handles + this automatically). This is not supported in exclusive mode. + - WASAPI and Core Audio: Add support for stream routing. When the application is using a default device and the + user switches the default device via the operating system's audio preferences, miniaudio will automatically switch + the internal device to the new default. This is not supported in exclusive mode. + - WASAPI: Add support for hardware offloading via IAudioClient2. Only supported on Windows 8 and newer. + - WASAPI: Add support for low-latency shared mode via IAudioClient3. Only supported on Windows 10 and newer. + - Add support for compiling the UWP build as C. + - mal_device_set_recv_callback() and mal_device_set_send_callback() have been deprecated. You must now set this + when the device is initialized with mal_device_init*(). These will be removed in version 0.9.0. + +v0.8.5 - 2018-08-12 + - Add support for specifying the size of a device's buffer in milliseconds. You can still set the buffer size in + frames if that suits you. When bufferSizeInFrames is 0, bufferSizeInMilliseconds will be used. If both are non-0 + then bufferSizeInFrames will take priority. If both are set to 0 the default buffer size is used. + - Add support for the audio(4) backend to OpenBSD. + - Fix a bug with the ALSA backend that was causing problems on Raspberry Pi. This significantly improves the + Raspberry Pi experience. + - Fix a bug where an incorrect number of samples is returned from sinc resampling. + - Add support for setting the value to be passed to internal calls to CoInitializeEx(). + - WASAPI and WinMM: Stop the device when it is unplugged. + +v0.8.4 - 2018-08-06 + - Add sndio backend for OpenBSD. + - Add audio(4) backend for NetBSD. + - Drop support for the OSS backend on everything except FreeBSD and DragonFly BSD. + - Formats are now native-endian (were previously little-endian). + - Mark some APIs as deprecated: + - mal_src_set_input_sample_rate() and mal_src_set_output_sample_rate() are replaced with mal_src_set_sample_rate(). + - mal_dsp_set_input_sample_rate() and mal_dsp_set_output_sample_rate() are replaced with mal_dsp_set_sample_rate(). + - Fix a bug when capturing using the WASAPI backend. + - Fix some aliasing issues with resampling, specifically when increasing the sample rate. + - Fix warnings. + +v0.8.3 - 2018-07-15 + - Fix a crackling bug when resampling in capture mode. + - Core Audio: Fix a bug where capture does not work. + - ALSA: Fix a bug where the worker thread can get stuck in an infinite loop. + - PulseAudio: Fix a bug where mal_context_init() succeeds when PulseAudio is unusable. + - JACK: Fix a bug where mal_context_init() succeeds when JACK is unusable. + +v0.8.2 - 2018-07-07 + - Fix a bug on macOS with Core Audio where the internal callback is not called. + +v0.8.1 - 2018-07-06 + - Fix compilation errors and warnings. + +v0.8 - 2018-07-05 + - Changed MA_IMPLEMENTATION to MINI_AL_IMPLEMENTATION for consistency with other libraries. The old + way is still supported for now, but you should update as it may be removed in the future. + - API CHANGE: Replace device enumeration APIs. mal_enumerate_devices() has been replaced with + mal_context_get_devices(). An additional low-level device enumration API has been introduced called + mal_context_enumerate_devices() which uses a callback to report devices. + - API CHANGE: Rename mal_get_sample_size_in_bytes() to mal_get_bytes_per_sample() and add + mal_get_bytes_per_frame(). + - API CHANGE: Replace mal_device_config.preferExclusiveMode with ma_device_config.shareMode. + - This new config can be set to mal_share_mode_shared (default) or ma_share_mode_exclusive. + - API CHANGE: Remove excludeNullDevice from mal_context_config.alsa. + - API CHANGE: Rename MA_MAX_SAMPLE_SIZE_IN_BYTES to MA_MAX_PCM_SAMPLE_SIZE_IN_BYTES. + - API CHANGE: Change the default channel mapping to the standard Microsoft mapping. + - API CHANGE: Remove backend-specific result codes. + - API CHANGE: Changes to the format conversion APIs (mal_pcm_f32_to_s16(), etc.) + - Add support for Core Audio (Apple). + - Add support for PulseAudio. + - This is the highest priority backend on Linux (higher priority than ALSA) since it is commonly + installed by default on many of the popular distros and offer's more seamless integration on + platforms where PulseAudio is used. In addition, if PulseAudio is installed and running (which + is extremely common), it's better to just use PulseAudio directly rather than going through the + "pulse" ALSA plugin (which is what the "default" ALSA device is likely set to). + - Add support for JACK. + - Remove dependency on asound.h for the ALSA backend. This means the ALSA development packages are no + longer required to build miniaudio. + - Remove dependency on dsound.h for the DirectSound backend. This fixes build issues with some + distributions of MinGW. + - Remove dependency on audioclient.h for the WASAPI backend. This fixes build issues with some + distributions of MinGW. + - Add support for dithering to format conversion. + - Add support for configuring the priority of the worker thread. + - Add a sine wave generator. + - Improve efficiency of sample rate conversion. + - Introduce the notion of standard channel maps. Use mal_get_standard_channel_map(). + - Introduce the notion of default device configurations. A default config uses the same configuration + as the backend's internal device, and as such results in a pass-through data transmission pipeline. + - Add support for passing in NULL for the device config in mal_device_init(), which uses a default + config. This requires manually calling mal_device_set_send/recv_callback(). + - Add support for decoding from raw PCM data (mal_decoder_init_raw(), etc.) + - Make mal_device_init_ex() more robust. + - Make some APIs more const-correct. + - Fix errors with SDL detection on Apple platforms. + - Fix errors with OpenAL detection. + - Fix some memory leaks. + - Fix a bug with opening decoders from memory. + - Early work on SSE2, AVX2 and NEON optimizations. + - Miscellaneous bug fixes. + - Documentation updates. + +v0.7 - 2018-02-25 + - API CHANGE: Change mal_src_read_frames() and mal_dsp_read_frames() to use 64-bit sample counts. + - Add decoder APIs for loading WAV, FLAC, Vorbis and MP3 files. + - Allow opening of devices without a context. + - In this case the context is created and managed internally by the device. + - Change the default channel mapping to the same as that used by FLAC. + - Fix build errors with macOS. + +v0.6c - 2018-02-12 + - Fix build errors with BSD/OSS. + +v0.6b - 2018-02-03 + - Fix some warnings when compiling with Visual C++. + +v0.6a - 2018-01-26 + - Fix errors with channel mixing when increasing the channel count. + - Improvements to the build system for the OpenAL backend. + - Documentation fixes. + +v0.6 - 2017-12-08 + - API CHANGE: Expose and improve mutex APIs. If you were using the mutex APIs before this version you'll + need to update. + - API CHANGE: SRC and DSP callbacks now take a pointer to a mal_src and ma_dsp object respectively. + - API CHANGE: Improvements to event and thread APIs. These changes make these APIs more consistent. + - Add support for SDL and Emscripten. + - Simplify the build system further for when development packages for various backends are not installed. + With this change, when the compiler supports __has_include, backends without the relevant development + packages installed will be ignored. This fixes the build for old versions of MinGW. + - Fixes to the Android build. + - Add mal_convert_frames(). This is a high-level helper API for performing a one-time, bulk conversion of + audio data to a different format. + - Improvements to f32 -> u8/s16/s24/s32 conversion routines. + - Fix a bug where the wrong value is returned from mal_device_start() for the OpenSL backend. + - Fixes and improvements for Raspberry Pi. + - Warning fixes. + +v0.5 - 2017-11-11 + - API CHANGE: The mal_context_init() function now takes a pointer to a ma_context_config object for + configuring the context. The works in the same kind of way as the device config. The rationale for this + change is to give applications better control over context-level properties, add support for backend- + specific configurations, and support extensibility without breaking the API. + - API CHANGE: The alsa.preferPlugHW device config variable has been removed since it's not really useful for + anything anymore. + - ALSA: By default, device enumeration will now only enumerate over unique card/device pairs. Applications + can enable verbose device enumeration by setting the alsa.useVerboseDeviceEnumeration context config + variable. + - ALSA: When opening a device in shared mode (the default), the dmix/dsnoop plugin will be prioritized. If + this fails it will fall back to the hw plugin. With this change the preferExclusiveMode config is now + honored. Note that this does not happen when alsa.useVerboseDeviceEnumeration is set to true (see above) + which is by design. + - ALSA: Add support for excluding the "null" device using the alsa.excludeNullDevice context config variable. + - ALSA: Fix a bug with channel mapping which causes an assertion to fail. + - Fix errors with enumeration when pInfo is set to NULL. + - OSS: Fix a bug when starting a device when the client sends 0 samples for the initial buffer fill. + +v0.4 - 2017-11-05 + - API CHANGE: The log callback is now per-context rather than per-device and as is thus now passed to + mal_context_init(). The rationale for this change is that it allows applications to capture diagnostic + messages at the context level. Previously this was only available at the device level. + - API CHANGE: The device config passed to mal_device_init() is now const. + - Added support for OSS which enables support on BSD platforms. + - Added support for WinMM (waveOut/waveIn). + - Added support for UWP (Universal Windows Platform) applications. Currently C++ only. + - Added support for exclusive mode for selected backends. Currently supported on WASAPI. + - POSIX builds no longer require explicit linking to libpthread (-lpthread). + - ALSA: Explicit linking to libasound (-lasound) is no longer required. + - ALSA: Latency improvements. + - ALSA: Use MMAP mode where available. This can be disabled with the alsa.noMMap config. + - ALSA: Use "hw" devices instead of "plughw" devices by default. This can be disabled with the + alsa.preferPlugHW config. + - WASAPI is now the highest priority backend on Windows platforms. + - Fixed an error with sample rate conversion which was causing crackling when capturing. + - Improved error handling. + - Improved compiler support. + - Miscellaneous bug fixes. + +v0.3 - 2017-06-19 + - API CHANGE: Introduced the notion of a context. The context is the highest level object and is required for + enumerating and creating devices. Now, applications must first create a context, and then use that to + enumerate and create devices. The reason for this change is to ensure device enumeration and creation is + tied to the same backend. In addition, some backends are better suited to this design. + - API CHANGE: Removed the rewinding APIs because they're too inconsistent across the different backends, hard + to test and maintain, and just generally unreliable. + - Added helper APIs for initializing mal_device_config objects. + - Null Backend: Fixed a crash when recording. + - Fixed build for UWP. + - Added support for f32 formats to the OpenSL|ES backend. + - Added initial implementation of the WASAPI backend. + - Added initial implementation of the OpenAL backend. + - Added support for low quality linear sample rate conversion. + - Added early support for basic channel mapping. + +v0.2 - 2016-10-28 + - API CHANGE: Add user data pointer as the last parameter to mal_device_init(). The rationale for this + change is to ensure the logging callback has access to the user data during initialization. + - API CHANGE: Have device configuration properties be passed to mal_device_init() via a structure. Rationale: + 1) The number of parameters is just getting too much. + 2) It makes it a bit easier to add new configuration properties in the future. In particular, there's a + chance there will be support added for backend-specific properties. + - Dropped support for f64, A-law and Mu-law formats since they just aren't common enough to justify the + added maintenance cost. + - DirectSound: Increased the default buffer size for capture devices. + - Added initial implementation of the OpenSL|ES backend. + +v0.1 - 2016-10-21 + - Initial versioned release. +*/ + + +/* +This software is available as a choice of the following licenses. Choose +whichever you prefer. + +=============================================================================== +ALTERNATIVE 1 - Public Domain (www.unlicense.org) +=============================================================================== +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. + +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +For more information, please refer to + +=============================================================================== +ALTERNATIVE 2 - MIT No Attribution +=============================================================================== +Copyright 2019 David Reid + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ diff --git a/src/raudio.c b/src/raudio.c index d24cc8e6..2d59302e 100644 --- a/src/raudio.c +++ b/src/raudio.c @@ -1,6 +1,6 @@ /********************************************************************************************** * -* raudio - A simple and easy-to-use audio library based on mini_al +* raudio - A simple and easy-to-use audio library based on miniaudio * * FEATURES: * - Manage audio device (init/close) @@ -26,7 +26,7 @@ * supported by default, to remove support, just comment unrequired #define in this module * * DEPENDENCIES: -* mini_al.h - Audio device management lib (https://github.com/dr-soft/mini_al) +* miniaudio.h - Audio device management lib (https://github.com/dr-soft/miniaudio) * stb_vorbis.h - Ogg audio files loading (http://www.nothings.org/stb_vorbis/) * dr_mp3.h - MP3 audio file loading (https://github.com/mackron/dr_libs) * dr_flac.h - FLAC audio file loading (https://github.com/mackron/dr_libs) @@ -35,7 +35,7 @@ * * CONTRIBUTORS: * David Reid (github: @mackron) (Nov. 2017): -* - Complete port to mini_al library +* - Complete port to miniaudio library * * Joshua Reisenauer (github: @kd7tck) (2015) * - XM audio module support (jar_xm) @@ -77,11 +77,9 @@ #include "utils.h" // Required for: fopen() Android mapping #endif -#define MAL_NO_SDL -#define MAL_NO_JACK -#define MAL_NO_OPENAL -#define MINI_AL_IMPLEMENTATION -#include "external/mini_al.h" // mini_al audio library +#define MA_NO_JACK +#define MINIAUDIO_IMPLEMENTATION +#include "external/miniaudio.h" // miniaudio library #undef PlaySound // Win32 API: windows.h > mmsystem.h defines PlaySound macro #include // Required for: malloc(), free() @@ -208,9 +206,9 @@ void TraceLog(int msgType, const char *text, ...); // Show trace lo #endif //---------------------------------------------------------------------------------- -// mini_al AudioBuffer Functionality +// miniaudio AudioBuffer Functionality //---------------------------------------------------------------------------------- -#define DEVICE_FORMAT mal_format_f32 +#define DEVICE_FORMAT ma_format_f32 #define DEVICE_CHANNELS 2 #define DEVICE_SAMPLE_RATE 44100 @@ -220,7 +218,7 @@ typedef enum { AUDIO_BUFFER_USAGE_STATIC = 0, AUDIO_BUFFER_USAGE_STREAM } AudioB // NOTE: Slightly different logic is used when feeding data to the playback device depending on whether or not data is streamed typedef struct rAudioBuffer rAudioBuffer; struct rAudioBuffer { - mal_dsp dsp; // Required for format conversion + ma_pcm_converter dsp; // Required for format conversion float volume; float pitch; bool playing; @@ -239,26 +237,26 @@ struct rAudioBuffer { // NOTE: This system should probably be redesigned #define AudioBuffer rAudioBuffer -// mini_al global variables -static mal_context context; -static mal_device device; -static mal_mutex audioLock; -static bool isAudioInitialized = MAL_FALSE; +// miniaudio global variables +static ma_context context; +static ma_device device; +static ma_mutex audioLock; +static bool isAudioInitialized = MA_FALSE; static float masterVolume = 1.0f; // Audio buffers are tracked in a linked list static AudioBuffer *firstAudioBuffer = NULL; static AudioBuffer *lastAudioBuffer = NULL; -// mini_al functions declaration -static void OnLog(mal_context *pContext, mal_device *pDevice, const char *message); -static mal_uint32 OnSendAudioDataToDevice(mal_device *pDevice, mal_uint32 frameCount, void *pFramesOut); -static mal_uint32 OnAudioBufferDSPRead(mal_dsp *pDSP, mal_uint32 frameCount, void *pFramesOut, void *pUserData); -static void MixAudioFrames(float *framesOut, const float *framesIn, mal_uint32 frameCount, float localVolume); +// miniaudio functions declaration +static void OnLog(ma_context *pContext, ma_device *pDevice, ma_uint32 logLevel, const char *message); +static void OnSendAudioDataToDevice(ma_device *pDevice, void *pFramesOut, const void *pFramesInput, ma_uint32 frameCount); +static ma_uint32 OnAudioBufferDSPRead(ma_pcm_converter *pDSP, void *pFramesOut, ma_uint32 frameCount, void *pUserData); +static void MixAudioFrames(float *framesOut, const float *framesIn, ma_uint32 frameCount, float localVolume); // AudioBuffer management functions declaration // NOTE: Those functions are not exposed by raylib... for the moment -AudioBuffer *CreateAudioBuffer(mal_format format, mal_uint32 channels, mal_uint32 sampleRate, mal_uint32 bufferSizeInFrames, AudioBufferUsage usage); +AudioBuffer *CreateAudioBuffer(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, ma_uint32 bufferSizeInFrames, AudioBufferUsage usage); void DeleteAudioBuffer(AudioBuffer *audioBuffer); bool IsAudioBufferPlaying(AudioBuffer *audioBuffer); void PlayAudioBuffer(AudioBuffer *audioBuffer); @@ -270,35 +268,34 @@ void SetAudioBufferPitch(AudioBuffer *audioBuffer, float pitch); void TrackAudioBuffer(AudioBuffer *audioBuffer); void UntrackAudioBuffer(AudioBuffer *audioBuffer); - // Log callback function -static void OnLog(mal_context *pContext, mal_device *pDevice, const char *message) +static void OnLog(ma_context *pContext, ma_device *pDevice, ma_uint32 logLevel, const char *message) { (void)pContext; (void)pDevice; - TraceLog(LOG_ERROR, message); // All log messages from mini_al are errors + TraceLog(LOG_ERROR, message); // All log messages from miniaudio are errors } // Sending audio data to device callback function -static mal_uint32 OnSendAudioDataToDevice(mal_device *pDevice, mal_uint32 frameCount, void *pFramesOut) +static void OnSendAudioDataToDevice(ma_device *pDevice, void *pFramesOut, const void *pFramesInput, ma_uint32 frameCount) { // This is where all of the mixing takes place. (void)pDevice; // Mixing is basically just an accumulation. We need to initialize the output buffer to 0. - memset(pFramesOut, 0, frameCount*pDevice->channels*mal_get_bytes_per_sample(pDevice->format)); + memset(pFramesOut, 0, frameCount*pDevice->playback.channels*ma_get_bytes_per_sample(pDevice->playback.format)); // Using a mutex here for thread-safety which makes things not real-time. This is unlikely to be necessary for this project, but may // want to consider how you might want to avoid this. - mal_mutex_lock(&audioLock); + ma_mutex_lock(&audioLock); { for (AudioBuffer *audioBuffer = firstAudioBuffer; audioBuffer != NULL; audioBuffer = audioBuffer->next) { // Ignore stopped or paused sounds. if (!audioBuffer->playing || audioBuffer->paused) continue; - mal_uint32 framesRead = 0; + ma_uint32 framesRead = 0; for (;;) { if (framesRead > frameCount) @@ -310,21 +307,21 @@ static mal_uint32 OnSendAudioDataToDevice(mal_device *pDevice, mal_uint32 frameC if (framesRead == frameCount) break; // Just read as much data as we can from the stream. - mal_uint32 framesToRead = (frameCount - framesRead); + ma_uint32 framesToRead = (frameCount - framesRead); while (framesToRead > 0) { float tempBuffer[1024]; // 512 frames for stereo. - mal_uint32 framesToReadRightNow = framesToRead; + ma_uint32 framesToReadRightNow = framesToRead; if (framesToReadRightNow > sizeof(tempBuffer)/sizeof(tempBuffer[0])/DEVICE_CHANNELS) { framesToReadRightNow = sizeof(tempBuffer)/sizeof(tempBuffer[0])/DEVICE_CHANNELS; } - mal_uint32 framesJustRead = (mal_uint32)mal_dsp_read(&audioBuffer->dsp, framesToReadRightNow, tempBuffer, audioBuffer->dsp.pUserData); + ma_uint32 framesJustRead = (ma_uint32)ma_pcm_converter_read(&audioBuffer->dsp, tempBuffer, framesToReadRightNow); if (framesJustRead > 0) { - float *framesOut = (float *)pFramesOut + (framesRead*device.channels); + float *framesOut = (float *)pFramesOut + (framesRead*device.playback.channels); float *framesIn = tempBuffer; MixAudioFrames(framesOut, framesIn, framesJustRead, audioBuffer->volume); @@ -357,18 +354,16 @@ static mal_uint32 OnSendAudioDataToDevice(mal_device *pDevice, mal_uint32 frameC } } - mal_mutex_unlock(&audioLock); - - return frameCount; // We always output the same number of frames that were originally requested. + ma_mutex_unlock(&audioLock); } // DSP read from audio buffer callback function -static mal_uint32 OnAudioBufferDSPRead(mal_dsp *pDSP, mal_uint32 frameCount, void *pFramesOut, void *pUserData) +static ma_uint32 OnAudioBufferDSPRead(ma_pcm_converter *pDSP, void *pFramesOut, ma_uint32 frameCount, void *pUserData) { AudioBuffer *audioBuffer = (AudioBuffer *)pUserData; - mal_uint32 subBufferSizeInFrames = (audioBuffer->bufferSizeInFrames > 1)? audioBuffer->bufferSizeInFrames/2 : audioBuffer->bufferSizeInFrames; - mal_uint32 currentSubBufferIndex = audioBuffer->frameCursorPos/subBufferSizeInFrames; + ma_uint32 subBufferSizeInFrames = (audioBuffer->bufferSizeInFrames > 1)? audioBuffer->bufferSizeInFrames/2 : audioBuffer->bufferSizeInFrames; + ma_uint32 currentSubBufferIndex = audioBuffer->frameCursorPos/subBufferSizeInFrames; if (currentSubBufferIndex > 1) { @@ -381,10 +376,10 @@ static mal_uint32 OnAudioBufferDSPRead(mal_dsp *pDSP, mal_uint32 frameCount, voi isSubBufferProcessed[0] = audioBuffer->isSubBufferProcessed[0]; isSubBufferProcessed[1] = audioBuffer->isSubBufferProcessed[1]; - mal_uint32 frameSizeInBytes = mal_get_bytes_per_sample(audioBuffer->dsp.formatConverterIn.config.formatIn)*audioBuffer->dsp.formatConverterIn.config.channels; + ma_uint32 frameSizeInBytes = ma_get_bytes_per_sample(audioBuffer->dsp.formatConverterIn.config.formatIn)*audioBuffer->dsp.formatConverterIn.config.channels; // Fill out every frame until we find a buffer that's marked as processed. Then fill the remainder with 0. - mal_uint32 framesRead = 0; + ma_uint32 framesRead = 0; for (;;) { // We break from this loop differently depending on the buffer's usage. For static buffers, we simply fill as much data as we can. For @@ -398,21 +393,21 @@ static mal_uint32 OnAudioBufferDSPRead(mal_dsp *pDSP, mal_uint32 frameCount, voi if (isSubBufferProcessed[currentSubBufferIndex]) break; } - mal_uint32 totalFramesRemaining = (frameCount - framesRead); + ma_uint32 totalFramesRemaining = (frameCount - framesRead); if (totalFramesRemaining == 0) break; - mal_uint32 framesRemainingInOutputBuffer; + ma_uint32 framesRemainingInOutputBuffer; if (audioBuffer->usage == AUDIO_BUFFER_USAGE_STATIC) { framesRemainingInOutputBuffer = audioBuffer->bufferSizeInFrames - audioBuffer->frameCursorPos; } else { - mal_uint32 firstFrameIndexOfThisSubBuffer = subBufferSizeInFrames * currentSubBufferIndex; + ma_uint32 firstFrameIndexOfThisSubBuffer = subBufferSizeInFrames * currentSubBufferIndex; framesRemainingInOutputBuffer = subBufferSizeInFrames - (audioBuffer->frameCursorPos - firstFrameIndexOfThisSubBuffer); } - mal_uint32 framesToRead = totalFramesRemaining; + ma_uint32 framesToRead = totalFramesRemaining; if (framesToRead > framesRemainingInOutputBuffer) framesToRead = framesRemainingInOutputBuffer; memcpy((unsigned char *)pFramesOut + (framesRead*frameSizeInBytes), audioBuffer->buffer + (audioBuffer->frameCursorPos*frameSizeInBytes), framesToRead*frameSizeInBytes); @@ -437,7 +432,7 @@ static mal_uint32 OnAudioBufferDSPRead(mal_dsp *pDSP, mal_uint32 frameCount, voi } // Zero-fill excess. - mal_uint32 totalFramesRemaining = (frameCount - framesRead); + ma_uint32 totalFramesRemaining = (frameCount - framesRead); if (totalFramesRemaining > 0) { memset((unsigned char *)pFramesOut + (framesRead*frameSizeInBytes), 0, totalFramesRemaining*frameSizeInBytes); @@ -453,14 +448,14 @@ static mal_uint32 OnAudioBufferDSPRead(mal_dsp *pDSP, mal_uint32 frameCount, voi // This is the main mixing function. Mixing is pretty simple in this project - it's just an accumulation. // NOTE: framesOut is both an input and an output. It will be initially filled with zeros outside of this function. -static void MixAudioFrames(float *framesOut, const float *framesIn, mal_uint32 frameCount, float localVolume) +static void MixAudioFrames(float *framesOut, const float *framesIn, ma_uint32 frameCount, float localVolume) { - for (mal_uint32 iFrame = 0; iFrame < frameCount; ++iFrame) + for (ma_uint32 iFrame = 0; iFrame < frameCount; ++iFrame) { - for (mal_uint32 iChannel = 0; iChannel < device.channels; ++iChannel) + for (ma_uint32 iChannel = 0; iChannel < device.playback.channels; ++iChannel) { - float *frameOut = framesOut + (iFrame*device.channels); - const float *frameIn = framesIn + (iFrame*device.channels); + float *frameOut = framesOut + (iFrame*device.playback.channels); + const float *frameIn = framesIn + (iFrame*device.playback.channels); frameOut[iChannel] += frameIn[iChannel]*masterVolume*localVolume; } @@ -474,54 +469,64 @@ static void MixAudioFrames(float *framesOut, const float *framesIn, mal_uint32 f void InitAudioDevice(void) { // Context. - mal_context_config contextConfig = mal_context_config_init(OnLog); - mal_result result = mal_context_init(NULL, 0, &contextConfig, &context); - if (result != MAL_SUCCESS) + ma_context_config contextConfig = ma_context_config_init(); + contextConfig.logCallback = OnLog; + ma_result result = ma_context_init(NULL, 0, &contextConfig, &context); + if (result != MA_SUCCESS) { TraceLog(LOG_ERROR, "Failed to initialize audio context"); return; } // Device. Using the default device. Format is floating point because it simplifies mixing. - mal_device_config deviceConfig = mal_device_config_init(DEVICE_FORMAT, DEVICE_CHANNELS, DEVICE_SAMPLE_RATE, NULL, OnSendAudioDataToDevice); - - result = mal_device_init(&context, mal_device_type_playback, NULL, &deviceConfig, NULL, &device); - if (result != MAL_SUCCESS) + ma_device_config config = ma_device_config_init(ma_device_type_playback); + config.playback.pDeviceID = NULL; // NULL for the default playback device. + config.playback.format = DEVICE_FORMAT; + config.playback.channels = DEVICE_CHANNELS; + config.capture.pDeviceID = NULL; // NULL for the default capture device. + config.capture.format = ma_format_s16; + config.capture.channels = 1; + config.sampleRate = DEVICE_SAMPLE_RATE; + config.dataCallback = OnSendAudioDataToDevice; + config.pUserData = NULL; + + result = ma_device_init(&context, &config, &device); + if (result != MA_SUCCESS) { TraceLog(LOG_ERROR, "Failed to initialize audio playback device"); - mal_context_uninit(&context); + ma_context_uninit(&context); return; } // Keep the device running the whole time. May want to consider doing something a bit smarter and only have the device running // while there's at least one sound being played. - result = mal_device_start(&device); - if (result != MAL_SUCCESS) + result = ma_device_start(&device); + if (result != MA_SUCCESS) { TraceLog(LOG_ERROR, "Failed to start audio playback device"); - mal_device_uninit(&device); - mal_context_uninit(&context); + ma_device_uninit(&device); + ma_context_uninit(&context); return; } // Mixing happens on a seperate thread which means we need to synchronize. I'm using a mutex here to make things simple, but may // want to look at something a bit smarter later on to keep everything real-time, if that's necessary. - if (mal_mutex_init(&context, &audioLock) != MAL_SUCCESS) + if (ma_mutex_init(&context, &audioLock) != MA_SUCCESS) { TraceLog(LOG_ERROR, "Failed to create mutex for audio mixing"); - mal_device_uninit(&device); - mal_context_uninit(&context); + ma_device_uninit(&device); + ma_context_uninit(&context); return; } - TraceLog(LOG_INFO, "Audio device initialized successfully: %s", device.name); - TraceLog(LOG_INFO, "Audio backend: mini_al / %s", mal_get_backend_name(context.backend)); - TraceLog(LOG_INFO, "Audio format: %s -> %s", mal_get_format_name(device.format), mal_get_format_name(device.internalFormat)); - TraceLog(LOG_INFO, "Audio channels: %d -> %d", device.channels, device.internalChannels); - TraceLog(LOG_INFO, "Audio sample rate: %d -> %d", device.sampleRate, device.internalSampleRate); - TraceLog(LOG_INFO, "Audio buffer size: %d", device.bufferSizeInFrames); - - isAudioInitialized = MAL_TRUE; + TraceLog(LOG_INFO, "Audio device initialized successfully"); + TraceLog(LOG_INFO, "Audio backend: miniaudio / %s", ma_get_backend_name(context.backend)); + TraceLog(LOG_INFO, "Audio format: %s -> %s", ma_get_format_name(device.playback.format), ma_get_format_name(device.playback.internalFormat)); + TraceLog(LOG_INFO, "Audio channels: %d -> %d", device.playback.channels, device.playback.internalChannels); + TraceLog(LOG_INFO, "Audio sample rate: %d -> %d", device.sampleRate, device.playback.internalSampleRate); + TraceLog(LOG_INFO, "Audio buffer size: %d", device.playback.internalBufferSizeInFrames); + + isAudioInitialized = MA_TRUE; } // Close the audio device for all contexts @@ -533,9 +538,9 @@ void CloseAudioDevice(void) return; } - mal_mutex_uninit(&audioLock); - mal_device_uninit(&device); - mal_context_uninit(&context); + ma_mutex_uninit(&audioLock); + ma_device_uninit(&device); + ma_context_uninit(&context); TraceLog(LOG_INFO, "Audio device closed successfully"); } @@ -560,9 +565,9 @@ void SetMasterVolume(float volume) //---------------------------------------------------------------------------------- // Create a new audio buffer. Initially filled with silence -AudioBuffer *CreateAudioBuffer(mal_format format, mal_uint32 channels, mal_uint32 sampleRate, mal_uint32 bufferSizeInFrames, AudioBufferUsage usage) +AudioBuffer *CreateAudioBuffer(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, ma_uint32 bufferSizeInFrames, AudioBufferUsage usage) { - AudioBuffer *audioBuffer = (AudioBuffer *)calloc(sizeof(*audioBuffer) + (bufferSizeInFrames*channels*mal_get_bytes_per_sample(format)), 1); + AudioBuffer *audioBuffer = (AudioBuffer *)calloc(sizeof(*audioBuffer) + (bufferSizeInFrames*channels*ma_get_bytes_per_sample(format)), 1); if (audioBuffer == NULL) { TraceLog(LOG_ERROR, "CreateAudioBuffer() : Failed to allocate memory for audio buffer"); @@ -570,7 +575,7 @@ AudioBuffer *CreateAudioBuffer(mal_format format, mal_uint32 channels, mal_uint3 } // We run audio data through a format converter. - mal_dsp_config dspConfig; + ma_pcm_converter_config dspConfig; memset(&dspConfig, 0, sizeof(dspConfig)); dspConfig.formatIn = format; dspConfig.formatOut = DEVICE_FORMAT; @@ -580,9 +585,10 @@ AudioBuffer *CreateAudioBuffer(mal_format format, mal_uint32 channels, mal_uint3 dspConfig.sampleRateOut = DEVICE_SAMPLE_RATE; dspConfig.onRead = OnAudioBufferDSPRead; dspConfig.pUserData = audioBuffer; - dspConfig.allowDynamicSampleRate = MAL_TRUE; // <-- Required for pitch shifting. - mal_result resultMAL = mal_dsp_init(&dspConfig, &audioBuffer->dsp); - if (resultMAL != MAL_SUCCESS) + dspConfig.allowDynamicSampleRate = MA_TRUE; // <-- Required for pitch shifting. + ma_result result = ma_pcm_converter_init(&dspConfig, &audioBuffer->dsp); + + if (result != MA_SUCCESS) { TraceLog(LOG_ERROR, "CreateAudioBuffer() : Failed to create data conversion pipeline"); free(audioBuffer); @@ -712,20 +718,20 @@ void SetAudioBufferPitch(AudioBuffer *audioBuffer, float pitch) return; } - float pitchMul = pitch / audioBuffer->pitch; + float pitchMul = pitch/audioBuffer->pitch; // Pitching is just an adjustment of the sample rate. Note that this changes the duration of the sound - higher pitches // will make the sound faster; lower pitches make it slower. - mal_uint32 newOutputSampleRate = (mal_uint32)((float)audioBuffer->dsp.src.config.sampleRateOut / pitchMul); + ma_uint32 newOutputSampleRate = (ma_uint32)((float)audioBuffer->dsp.src.config.sampleRateOut / pitchMul); audioBuffer->pitch *= (float)audioBuffer->dsp.src.config.sampleRateOut / newOutputSampleRate; - mal_dsp_set_output_sample_rate(&audioBuffer->dsp, newOutputSampleRate); + ma_pcm_converter_set_output_sample_rate(&audioBuffer->dsp, newOutputSampleRate); } // Track audio buffer to linked list next position void TrackAudioBuffer(AudioBuffer *audioBuffer) { - mal_mutex_lock(&audioLock); + ma_mutex_lock(&audioLock); { if (firstAudioBuffer == NULL) firstAudioBuffer = audioBuffer; @@ -738,13 +744,13 @@ void TrackAudioBuffer(AudioBuffer *audioBuffer) lastAudioBuffer = audioBuffer; } - mal_mutex_unlock(&audioLock); + ma_mutex_unlock(&audioLock); } // Untrack audio buffer from linked list void UntrackAudioBuffer(AudioBuffer *audioBuffer) { - mal_mutex_lock(&audioLock); + ma_mutex_lock(&audioLock); { if (audioBuffer->prev == NULL) firstAudioBuffer = audioBuffer->next; @@ -757,7 +763,7 @@ void UntrackAudioBuffer(AudioBuffer *audioBuffer) audioBuffer->next = NULL; } - mal_mutex_unlock(&audioLock); + ma_mutex_unlock(&audioLock); } //---------------------------------------------------------------------------------- @@ -828,7 +834,7 @@ Sound LoadSoundFromWave(Wave wave) if (wave.data != NULL) { - // When using mini_al we need to do our own mixing. To simplify this we need convert the format of each sound to be consistent with + // When using miniaudio we need to do our own mixing. To simplify this we need convert the format of each sound to be consistent with // the format used to open the playback device. We can do this two ways: // // 1) Convert the whole sound in one go at load time (here). @@ -836,16 +842,16 @@ Sound LoadSoundFromWave(Wave wave) // // I have decided on the first option because it offloads work required for the format conversion to the to the loading stage. // The downside to this is that it uses more memory if the original sound is u8 or s16. - mal_format formatIn = ((wave.sampleSize == 8)? mal_format_u8 : ((wave.sampleSize == 16)? mal_format_s16 : mal_format_f32)); - mal_uint32 frameCountIn = wave.sampleCount/wave.channels; + ma_format formatIn = ((wave.sampleSize == 8)? ma_format_u8 : ((wave.sampleSize == 16)? ma_format_s16 : ma_format_f32)); + ma_uint32 frameCountIn = wave.sampleCount/wave.channels; - mal_uint32 frameCount = (mal_uint32)mal_convert_frames(NULL, DEVICE_FORMAT, DEVICE_CHANNELS, DEVICE_SAMPLE_RATE, NULL, formatIn, wave.channels, wave.sampleRate, frameCountIn); + ma_uint32 frameCount = (ma_uint32)ma_convert_frames(NULL, DEVICE_FORMAT, DEVICE_CHANNELS, DEVICE_SAMPLE_RATE, NULL, formatIn, wave.channels, wave.sampleRate, frameCountIn); if (frameCount == 0) TraceLog(LOG_WARNING, "LoadSoundFromWave() : Failed to get frame count for format conversion"); AudioBuffer* audioBuffer = CreateAudioBuffer(DEVICE_FORMAT, DEVICE_CHANNELS, DEVICE_SAMPLE_RATE, frameCount, AUDIO_BUFFER_USAGE_STATIC); if (audioBuffer == NULL) TraceLog(LOG_WARNING, "LoadSoundFromWave() : Failed to create audio buffer"); - frameCount = (mal_uint32)mal_convert_frames(audioBuffer->buffer, audioBuffer->dsp.formatConverterIn.config.formatIn, audioBuffer->dsp.formatConverterIn.config.channels, audioBuffer->dsp.src.config.sampleRateIn, wave.data, formatIn, wave.channels, wave.sampleRate, frameCountIn); + frameCount = (ma_uint32)ma_convert_frames(audioBuffer->buffer, audioBuffer->dsp.formatConverterIn.config.formatIn, audioBuffer->dsp.formatConverterIn.config.channels, audioBuffer->dsp.src.config.sampleRateIn, wave.data, formatIn, wave.channels, wave.sampleRate, frameCountIn); if (frameCount == 0) TraceLog(LOG_WARNING, "LoadSoundFromWave() : Format conversion failed"); sound.audioBuffer = audioBuffer; @@ -885,7 +891,7 @@ void UpdateSound(Sound sound, const void *data, int samplesCount) StopAudioBuffer(audioBuffer); // TODO: May want to lock/unlock this since this data buffer is read at mixing time. - memcpy(audioBuffer->buffer, data, samplesCount*audioBuffer->dsp.formatConverterIn.config.channels*mal_get_bytes_per_sample(audioBuffer->dsp.formatConverterIn.config.formatIn)); + memcpy(audioBuffer->buffer, data, samplesCount*audioBuffer->dsp.formatConverterIn.config.channels*ma_get_bytes_per_sample(audioBuffer->dsp.formatConverterIn.config.formatIn)); } // Export wave data to file @@ -999,12 +1005,12 @@ void SetSoundPitch(Sound sound, float pitch) // Convert wave data to desired format void WaveFormat(Wave *wave, int sampleRate, int sampleSize, int channels) { - mal_format formatIn = ((wave->sampleSize == 8)? mal_format_u8 : ((wave->sampleSize == 16)? mal_format_s16 : mal_format_f32)); - mal_format formatOut = (( sampleSize == 8)? mal_format_u8 : (( sampleSize == 16)? mal_format_s16 : mal_format_f32)); + ma_format formatIn = ((wave->sampleSize == 8)? ma_format_u8 : ((wave->sampleSize == 16)? ma_format_s16 : ma_format_f32)); + ma_format formatOut = (( sampleSize == 8)? ma_format_u8 : (( sampleSize == 16)? ma_format_s16 : ma_format_f32)); - mal_uint32 frameCountIn = wave->sampleCount; // Is wave->sampleCount actually the frame count? That terminology needs to change, if so. + ma_uint32 frameCountIn = wave->sampleCount; // Is wave->sampleCount actually the frame count? That terminology needs to change, if so. - mal_uint32 frameCount = (mal_uint32)mal_convert_frames(NULL, formatOut, channels, sampleRate, NULL, formatIn, wave->channels, wave->sampleRate, frameCountIn); + ma_uint32 frameCount = (ma_uint32)ma_convert_frames(NULL, formatOut, channels, sampleRate, NULL, formatIn, wave->channels, wave->sampleRate, frameCountIn); if (frameCount == 0) { TraceLog(LOG_ERROR, "WaveFormat() : Failed to get frame count for format conversion."); @@ -1013,7 +1019,7 @@ void WaveFormat(Wave *wave, int sampleRate, int sampleSize, int channels) void *data = malloc(frameCount*channels*(sampleSize/8)); - frameCount = (mal_uint32)mal_convert_frames(data, formatOut, channels, sampleRate, wave->data, formatIn, wave->channels, wave->sampleRate, frameCountIn); + frameCount = (ma_uint32)ma_convert_frames(data, formatOut, channels, sampleRate, wave->data, formatIn, wave->channels, wave->sampleRate, frameCountIn); if (frameCount == 0) { TraceLog(LOG_ERROR, "WaveFormat() : Format conversion failed."); @@ -1288,7 +1294,7 @@ void PlayMusicStream(Music music) // // NOTE: In case window is minimized, music stream is stopped, // // just make sure to play again on window restore // if (IsMusicPlaying(music)) PlayMusicStream(music); - mal_uint32 frameCursorPos = audioBuffer->frameCursorPos; + ma_uint32 frameCursorPos = audioBuffer->frameCursorPos; PlayAudioStream(music->stream); // <-- This resets the cursor position. @@ -1513,10 +1519,10 @@ AudioStream InitAudioStream(unsigned int sampleRate, unsigned int sampleSize, un stream.channels = 1; // Fallback to mono channel } - mal_format formatIn = ((stream.sampleSize == 8)? mal_format_u8 : ((stream.sampleSize == 16)? mal_format_s16 : mal_format_f32)); + ma_format formatIn = ((stream.sampleSize == 8)? ma_format_u8 : ((stream.sampleSize == 16)? ma_format_s16 : ma_format_f32)); // The size of a streaming buffer must be at least double the size of a period. - unsigned int periodSize = device.bufferSizeInFrames/device.periods; + unsigned int periodSize = device.playback.internalBufferSizeInFrames/device.playback.internalPeriods; unsigned int subBufferSize = AUDIO_BUFFER_SIZE; if (subBufferSize < periodSize) subBufferSize = periodSize; @@ -1557,7 +1563,7 @@ void UpdateAudioStream(AudioStream stream, const void *data, int samplesCount) if (audioBuffer->isSubBufferProcessed[0] || audioBuffer->isSubBufferProcessed[1]) { - mal_uint32 subBufferToUpdate; + ma_uint32 subBufferToUpdate; if (audioBuffer->isSubBufferProcessed[0] && audioBuffer->isSubBufferProcessed[1]) { @@ -1571,21 +1577,21 @@ void UpdateAudioStream(AudioStream stream, const void *data, int samplesCount) subBufferToUpdate = (audioBuffer->isSubBufferProcessed[0])? 0 : 1; } - mal_uint32 subBufferSizeInFrames = audioBuffer->bufferSizeInFrames/2; + ma_uint32 subBufferSizeInFrames = audioBuffer->bufferSizeInFrames/2; unsigned char *subBuffer = audioBuffer->buffer + ((subBufferSizeInFrames*stream.channels*(stream.sampleSize/8))*subBufferToUpdate); // Does this API expect a whole buffer to be updated in one go? Assuming so, but if not will need to change this logic. - if (subBufferSizeInFrames >= (mal_uint32)samplesCount/stream.channels) + if (subBufferSizeInFrames >= (ma_uint32)samplesCount/stream.channels) { - mal_uint32 framesToWrite = subBufferSizeInFrames; + ma_uint32 framesToWrite = subBufferSizeInFrames; - if (framesToWrite > ((mal_uint32)samplesCount/stream.channels)) framesToWrite = (mal_uint32)samplesCount/stream.channels; + if (framesToWrite > ((ma_uint32)samplesCount/stream.channels)) framesToWrite = (ma_uint32)samplesCount/stream.channels; - mal_uint32 bytesToWrite = framesToWrite*stream.channels*(stream.sampleSize/8); + ma_uint32 bytesToWrite = framesToWrite*stream.channels*(stream.sampleSize/8); memcpy(subBuffer, data, bytesToWrite); // Any leftover frames should be filled with zeros. - mal_uint32 leftoverFrameCount = subBufferSizeInFrames - framesToWrite; + ma_uint32 leftoverFrameCount = subBufferSizeInFrames - framesToWrite; if (leftoverFrameCount > 0) { diff --git a/src/raudio.h b/src/raudio.h index f9c22ff2..f98d68ff 100644 --- a/src/raudio.h +++ b/src/raudio.h @@ -11,7 +11,7 @@ * - Manage raw audio context * * DEPENDENCIES: -* mini_al.h - Audio device management lib (https://github.com/dr-soft/mini_al) +* miniaudio.h - Audio device management lib (https://github.com/dr-soft/miniaudio) * stb_vorbis.h - Ogg audio files loading (http://www.nothings.org/stb_vorbis/) * dr_mp3.h - MP3 audio file loading (https://github.com/mackron/dr_libs) * dr_flac.h - FLAC audio file loading (https://github.com/mackron/dr_libs) -- cgit v1.2.3 From 477ea4d6606aa4659549f786935096942f187b37 Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 12 Mar 2019 16:00:26 +0100 Subject: Support external config flags --- src/core.c | 2 ++ src/rlgl.h | 5 ++++- src/textures.c | 13 +++++++++++++ src/utils.c | 8 ++++++-- 4 files changed, 25 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/core.c b/src/core.c index e6852eef..55b6ba82 100644 --- a/src/core.c +++ b/src/core.c @@ -92,6 +92,8 @@ // Check if config flags have been externally provided on compilation line #if !defined(EXTERNAL_CONFIG_FLAGS) #include "config.h" // Defines module configuration flags +#else + #define RAYLIB_VERSION "2.5" #endif #if (defined(__linux__) || defined(PLATFORM_WEB)) && _POSIX_C_SOURCE < 199309L diff --git a/src/rlgl.h b/src/rlgl.h index b8895a08..00658fa1 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -563,7 +563,10 @@ int GetPixelDataSize(int width, int height, int format);// Get pixel data size i #define SUPPORT_VR_SIMULATOR #define SUPPORT_DISTORTION_SHADER #else - #include "config.h" // rlgl module configuration + // Check if config flags have been externally provided on compilation line + #if !defined(EXTERNAL_CONFIG_FLAGS) + #include "config.h" // Defines module configuration flags + #endif #endif #include // Required for: fopen(), fclose(), fread()... [Used only on LoadText()] diff --git a/src/textures.c b/src/textures.c index 01c9b2f5..95cb4eb5 100644 --- a/src/textures.c +++ b/src/textures.c @@ -181,6 +181,15 @@ static Image LoadASTC(const char *fileName); // Load ASTC file Image LoadImage(const char *fileName) { Image image = { 0 }; + +#if defined(SUPPORT_FILEFORMAT_PNG) || \ + defined(SUPPORT_FILEFORMAT_BMP) || \ + defined(SUPPORT_FILEFORMAT_TGA) || \ + defined(SUPPORT_FILEFORMAT_GIF) || \ + defined(SUPPORT_FILEFORMAT_PIC) || \ + defined(SUPPORT_FILEFORMAT_PSD) +#define STBI_REQUIRED +#endif #if defined(SUPPORT_FILEFORMAT_PNG) if ((IsFileExtension(fileName, ".png")) @@ -207,6 +216,7 @@ Image LoadImage(const char *fileName) #endif ) { +#if defined(STBI_REQUIRED) int imgWidth = 0; int imgHeight = 0; int imgBpp = 0; @@ -229,6 +239,7 @@ Image LoadImage(const char *fileName) else if (imgBpp == 3) image.format = UNCOMPRESSED_R8G8B8; else if (imgBpp == 4) image.format = UNCOMPRESSED_R8G8B8A8; } +#endif } #if defined(SUPPORT_FILEFORMAT_HDR) else if (IsFileExtension(fileName, ".hdr")) @@ -1403,6 +1414,8 @@ void ImageResizeCanvas(Image *image, int newWidth,int newHeight, int offsetX, in else { // TODO: ImageCrop(), define proper cropping rectangle + + UnloadImage(imTemp); } } diff --git a/src/utils.c b/src/utils.c index b31ce6ae..6b174354 100644 --- a/src/utils.c +++ b/src/utils.c @@ -30,9 +30,13 @@ * **********************************************************************************************/ -#include "config.h" - #include "raylib.h" // WARNING: Required for: LogType enum + +// Check if config flags have been externally provided on compilation line +#if !defined(EXTERNAL_CONFIG_FLAGS) + #include "config.h" // Defines module configuration flags +#endif + #include "utils.h" #if defined(PLATFORM_ANDROID) -- cgit v1.2.3 From 32e6a419c1938234d1f0ea70ee2abd4f0640784e Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 12 Mar 2019 16:29:41 +0100 Subject: Reorder one flag --- src/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/Makefile b/src/Makefile index ff9dc99e..4fbe1668 100644 --- a/src/Makefile +++ b/src/Makefile @@ -509,7 +509,7 @@ core.o : core.c raylib.h rlgl.h utils.h raymath.h camera.h gestures.h # Compile rglfw module rglfw.o : rglfw.c - $(CC) $(GLFW_CFLAGS) -c $< $(CFLAGS) $(INCLUDE_PATHS) -D$(PLATFORM) -D$(GRAPHICS) + $(CC) -c $< $(CFLAGS) $(GLFW_CFLAGS) $(INCLUDE_PATHS) -D$(PLATFORM) -D$(GRAPHICS) # Compile shapes module shapes.o : shapes.c raylib.h rlgl.h -- cgit v1.2.3 From 5e8427a8b53dfe5b9525626da2093eba8f9c8da9 Mon Sep 17 00:00:00 2001 From: Ray Date: Wed, 13 Mar 2019 10:07:01 +0100 Subject: REDESIGNED: GetFileNameWithoutExt() Removed possible memory leak when using this function --- src/core.c | 48 ++++++++++++++++++------------------------------ 1 file changed, 18 insertions(+), 30 deletions(-) (limited to 'src') diff --git a/src/core.c b/src/core.c index 55b6ba82..c30c243d 100644 --- a/src/core.c +++ b/src/core.c @@ -180,15 +180,14 @@ //#define GLFW_EXPOSE_NATIVE_COCOA // WARNING: Fails due to type redefinition #include // Required for: glfwGetCocoaWindow() - #endif #endif #if defined(__linux__) - #include // for NAME_MAX and PATH_MAX defines - #define MAX_FILEPATH_LENGTH PATH_MAX // Use Linux define (4096) + #include // for NAME_MAX and PATH_MAX defines + #define MAX_FILEPATH_LENGTH PATH_MAX // Use Linux define (4096) #else - #define MAX_FILEPATH_LENGTH 256 // Use common value + #define MAX_FILEPATH_LENGTH 512 // Use common value #endif #if defined(PLATFORM_ANDROID) @@ -1676,37 +1675,26 @@ const char *GetFileName(const char *filePath) // Get filename string without extension (memory should be freed) const char *GetFileNameWithoutExt(const char *filePath) { - char *result, *lastDot, *lastSep; - - char nameDot = '.'; // Default filename to extension separator character - char pathSep = '/'; // Default filepath separator character - - // Error checks and allocate string - if (filePath == NULL) return NULL; - - // Try to allocate new string, same size as original - // NOTE: By default strlen() does not count the '\0' character - if ((result = (char *)malloc(strlen(filePath) + 1)) == NULL) return NULL; - - strcpy(result, filePath); // Make a copy of the string - - // NOTE: strrchr() returns a pointer to the last occurrence of character - lastDot = strrchr(result, nameDot); - lastSep = (pathSep == 0)? NULL : strrchr(result, pathSep); - - if (lastDot != NULL) // Check if it has an extension separator... + #define MAX_FILENAMEWITHOUTEXT_LENGTH 64 + + static char fileName[MAX_FILENAMEWITHOUTEXT_LENGTH]; + memset(fileName, 0, MAX_FILENAMEWITHOUTEXT_LENGTH); + + strcpy(fileName, GetFileName(filePath)); // Get filename with extension + + int len = strlen(fileName); + + for (int i = 0; (i < len) && (i < MAX_FILENAMEWITHOUTEXT_LENGTH); i++) { - if (lastSep != NULL) // ...and it's before the extenstion separator... + if (fileName[i] == '.') { - if (lastSep < lastDot) - { - *lastDot = '\0'; // ...then remove it - } + // NOTE: We break on first '.' found + fileName[i] = '\0'; + break; } - else *lastDot = '\0'; // Has extension separator with no path separator } - return result; // Return the modified string + return fileName; } // Get directory for a given fileName (with path) -- cgit v1.2.3 From ff1bcfb2faaf6bfca99ed4b2b2816ba0d24d7647 Mon Sep 17 00:00:00 2001 From: Ray Date: Wed, 13 Mar 2019 10:26:33 +0100 Subject: Remove comment --- src/core.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/core.c b/src/core.c index c30c243d..2018b3b0 100644 --- a/src/core.c +++ b/src/core.c @@ -3439,7 +3439,7 @@ static void WindowDropCallback(GLFWwindow *window, int count, const char **paths for (int i = 0; i < count; i++) { - dropFilesPath[i] = (char *)malloc(sizeof(char)*MAX_FILEPATH_LENGTH); // Max path length using MAX_FILEPATH_LENGTH set to 256 char + dropFilesPath[i] = (char *)malloc(sizeof(char)*MAX_FILEPATH_LENGTH); strcpy(dropFilesPath[i], paths[i]); } -- cgit v1.2.3 From cbfa35a39e2075431aa84ed0c476c39ff3e30adc Mon Sep 17 00:00:00 2001 From: Ray Date: Fri, 15 Mar 2019 00:56:02 +0100 Subject: REVIEW: ImageResizeCanvas() -WIP- --- src/textures.c | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/textures.c b/src/textures.c index 95cb4eb5..070c83f3 100644 --- a/src/textures.c +++ b/src/textures.c @@ -1398,24 +1398,23 @@ void ImageResizeNN(Image *image,int newWidth,int newHeight) // NOTE: Resize offset is relative to the top-left corner of the original image void ImageResizeCanvas(Image *image, int newWidth,int newHeight, int offsetX, int offsetY, Color color) { - Image imTemp = GenImageColor(newWidth, newHeight, color); - Rectangle srcRec = { 0.0f, 0.0f, (float)image->width, (float)image->height }; - Rectangle dstRec = { (float)offsetX, (float)offsetY, (float)srcRec.width, (float)srcRec.height }; - // TODO: Review different scaling situations if ((newWidth > image->width) && (newHeight > image->height)) { + Image imTemp = GenImageColor(newWidth, newHeight, color); + Rectangle srcRec = { 0.0f, 0.0f, (float)image->width, (float)image->height }; + Rectangle dstRec = { (float)offsetX, (float)offsetY, (float)srcRec.width, (float)srcRec.height }; + ImageDraw(&imTemp, *image, srcRec, dstRec); ImageFormat(&imTemp, image->format); UnloadImage(*image); *image = imTemp; } - else + else if ((newWidth < image->width) && (newHeight < image->height)) { - // TODO: ImageCrop(), define proper cropping rectangle - - UnloadImage(imTemp); + Rectangle crop = { (float)offsetX, (float)offsetY, newWidth, newHeight }; + ImageCrop(image, crop); } } -- cgit v1.2.3 From 29d1323bd12b0c8155d8c2a9c2830a002ebc608b Mon Sep 17 00:00:00 2001 From: Ray Date: Fri, 15 Mar 2019 13:34:09 +0100 Subject: Work on ImageResizeCanvas() --- src/textures.c | 61 ++++++++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 47 insertions(+), 14 deletions(-) (limited to 'src') diff --git a/src/textures.c b/src/textures.c index 070c83f3..7c942f18 100644 --- a/src/textures.c +++ b/src/textures.c @@ -1399,22 +1399,55 @@ void ImageResizeNN(Image *image,int newWidth,int newHeight) void ImageResizeCanvas(Image *image, int newWidth,int newHeight, int offsetX, int offsetY, Color color) { // TODO: Review different scaling situations - - if ((newWidth > image->width) && (newHeight > image->height)) + + if ((newWidth != image->width) || (newHeight != image->height)) { - Image imTemp = GenImageColor(newWidth, newHeight, color); - Rectangle srcRec = { 0.0f, 0.0f, (float)image->width, (float)image->height }; - Rectangle dstRec = { (float)offsetX, (float)offsetY, (float)srcRec.width, (float)srcRec.height }; + if ((newWidth > image->width) && (newHeight > image->height)) + { + Image imTemp = GenImageColor(newWidth, newHeight, color); + + Rectangle srcRec = { 0.0f, 0.0f, (float)image->width, (float)image->height }; + Rectangle dstRec = { (float)offsetX, (float)offsetY, (float)srcRec.width, (float)srcRec.height }; + + ImageDraw(&imTemp, *image, srcRec, dstRec); + ImageFormat(&imTemp, image->format); + UnloadImage(*image); + *image = imTemp; + } + else if ((newWidth < image->width) && (newHeight < image->height)) + { + Rectangle crop = { (float)offsetX, (float)offsetY, newWidth, newHeight }; + ImageCrop(image, crop); + } + else // One side is bigger and the other is smaller + { + Image imTemp = GenImageColor(newWidth, newHeight, color); + + Rectangle srcRec = { 0.0f, 0.0f, (float)image->width, (float)image->height }; + Rectangle dstRec = { (float)offsetX, (float)offsetY, (float)newWidth, (float)newHeight }; + + if (newWidth < image->width) + { + srcRec.x = offsetX; + srcRec.width = newWidth; + + dstRec.x = 0.0f; + } + + if (newHeight < image->height) + { + srcRec.y = offsetY; + srcRec.height = newHeight; + + dstRec.y = 0.0f; + } - ImageDraw(&imTemp, *image, srcRec, dstRec); - ImageFormat(&imTemp, image->format); - UnloadImage(*image); - *image = imTemp; - } - else if ((newWidth < image->width) && (newHeight < image->height)) - { - Rectangle crop = { (float)offsetX, (float)offsetY, newWidth, newHeight }; - ImageCrop(image, crop); + // TODO: ImageDraw() could be buggy? + ImageDraw(&imTemp, *image, srcRec, dstRec); + ImageFormat(&imTemp, image->format); + UnloadImage(*image); + *image = imTemp; + } } } -- cgit v1.2.3 From a61d3ad5122e860e21211c8bacd30f560d71f3da Mon Sep 17 00:00:00 2001 From: raysan5 Date: Sat, 16 Mar 2019 13:00:46 +0100 Subject: SetWindowIcon() redesigned Now core does not depend on textures module directly, only through text module. --- src/core.c | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) (limited to 'src') diff --git a/src/core.c b/src/core.c index 2018b3b0..aab60f13 100644 --- a/src/core.c +++ b/src/core.c @@ -780,24 +780,23 @@ void ToggleFullscreen(void) } // Set icon for window (only PLATFORM_DESKTOP) +// NOTE: Image must be in RGBA format, 8bit per channel void SetWindowIcon(Image image) { #if defined(PLATFORM_DESKTOP) - Image imicon = ImageCopy(image); - ImageFormat(&imicon, UNCOMPRESSED_R8G8B8A8); - - GLFWimage icon[1] = { 0 }; - - icon[0].width = imicon.width; - icon[0].height = imicon.height; - icon[0].pixels = (unsigned char *)imicon.data; + if (image.format == UNCOMPRESSED_R8G8B8A8) + { + GLFWimage icon[1] = { 0 }; - // NOTE 1: We only support one image icon - // NOTE 2: The specified image data is copied before this function returns - glfwSetWindowIcon(window, 1, icon); + icon[0].width = image.width; + icon[0].height = image.height; + icon[0].pixels = (unsigned char *)image.data; - // TODO: Support multi-image icons --> image.mipmaps - UnloadImage(imicon); + // NOTE 1: We only support one image icon + // NOTE 2: The specified image data is copied before this function returns + glfwSetWindowIcon(window, 1, icon); + } + else TraceLog(LOG_WARNING, "Window icon image must be in R8G8B8A8 pixel format"); #endif } -- cgit v1.2.3 From 2a92d6af3e63fcc47d1030c1274223afb4163a4b Mon Sep 17 00:00:00 2001 From: raysan5 Date: Sat, 16 Mar 2019 13:02:16 +0100 Subject: Support no-audio no-models modules compilation Renamed flags for convenience. --- src/CMakeLists.txt | 2 +- src/Makefile | 14 ++++++++------ 2 files changed, 9 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 104d6d2d..c65a4996 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -49,7 +49,7 @@ if(USE_AUDIO) set(sources ${raylib_sources}) else() MESSAGE(STATUS "Audio Backend: None (-DUSE_AUDIO=OFF)") - set(INCLUDE_AUDIO_MODULE 0) + set(RAYLIB_MODULE_AUDIO 0) list(REMOVE_ITEM raylib_sources ${CMAKE_CURRENT_SOURCE_DIR}/raudio.c) set(sources ${raylib_sources}) endif() diff --git a/src/Makefile b/src/Makefile index 4fbe1668..e483c64f 100644 --- a/src/Makefile +++ b/src/Makefile @@ -59,9 +59,10 @@ RAYLIB_LIBTYPE ?= STATIC # Build mode for library: DEBUG or RELEASE RAYLIB_BUILD_MODE ?= RELEASE -# Included raylib audio module on compilation -# NOTE: Some programs like tools could not require audio support -INCLUDE_AUDIO_MODULE ?= TRUE +# Include raylib modules on compilation +# NOTE: Some programs like tools could not require those modules +RAYLIB_MODULE_AUDIO ?= TRUE +RAYLIB_MODULE_MODELS ?= TRUE # Use external GLFW library instead of rglfw module # TODO: Review usage of examples on Linux. @@ -393,7 +394,6 @@ OBJS = core.o \ shapes.o \ textures.o \ text.o \ - models.o \ utils.o ifeq ($(PLATFORM),PLATFORM_DESKTOP) @@ -401,8 +401,10 @@ ifeq ($(PLATFORM),PLATFORM_DESKTOP) OBJS += rglfw.o endif endif - -ifeq ($(INCLUDE_AUDIO_MODULE),TRUE) +ifeq ($(RAYLIB_MODULE_MODELS),TRUE) + OBJS += models.o +endif +ifeq ($(RAYLIB_MODULE_AUDIO),TRUE) OBJS += raudio.o endif -- cgit v1.2.3 From f02a0334d8f86277916c52b274a0c7c21b6b9cd0 Mon Sep 17 00:00:00 2001 From: raysan5 Date: Sun, 17 Mar 2019 11:58:02 +0100 Subject: ADDED: GetScreenData() --- src/raylib.h | 1 + src/textures.c | 16 ++++++++++++++-- 2 files changed, 15 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/raylib.h b/src/raylib.h index ccdb4aab..c72f0682 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -1095,6 +1095,7 @@ RLAPI Color *GetImageData(Image image); RLAPI Vector4 *GetImageDataNormalized(Image image); // Get pixel data from image as Vector4 array (float normalized) RLAPI int GetPixelDataSize(int width, int height, int format); // Get pixel data size in bytes (image or texture) RLAPI Image GetTextureData(Texture2D texture); // Get pixel data from GPU texture and return an Image +RLAPI Image GetScreenData(void); // Get pixel data from screen buffer and return an Image (screenshot) RLAPI void UpdateTexture(Texture2D texture, const void *pixels); // Update GPU texture with new data // Image manipulation functions diff --git a/src/textures.c b/src/textures.c index 7c942f18..38995f11 100644 --- a/src/textures.c +++ b/src/textures.c @@ -740,6 +740,20 @@ Image GetTextureData(Texture2D texture) return image; } +// Get pixel data from GPU frontbuffer and return an Image (screenshot) +RLAPI Image GetScreenData(void) +{ + Image image = { 0 }; + + image.width = GetScreenWidth(); + image.height = GetScreenHeight(); + image.mipmaps = 1; + image.format = UNCOMPRESSED_R8G8B8A8; + image.data = rlReadScreenPixels(image.width, image.height); + + return image; +} + // Update GPU texture with new data // NOTE: pixels data must match texture.format void UpdateTexture(Texture2D texture, const void *pixels) @@ -1168,8 +1182,6 @@ void ImageAlphaPremultiply(Image *image) ImageFormat(image, prevFormat); } - - #if defined(SUPPORT_IMAGE_MANIPULATION) // Load cubemap from image, multiple image cubemap layouts supported TextureCubemap LoadTextureCubemap(Image image, int layoutType) -- cgit v1.2.3 From 0bbf857b00ab111749aa7ae22d942108ef06455f Mon Sep 17 00:00:00 2001 From: raysan5 Date: Sun, 17 Mar 2019 12:21:51 +0100 Subject: Review build release path, default to src directory --- src/Makefile | 35 +++-------------------------------- 1 file changed, 3 insertions(+), 32 deletions(-) (limited to 'src') diff --git a/src/Makefile b/src/Makefile index e483c64f..c579f9a7 100644 --- a/src/Makefile +++ b/src/Makefile @@ -42,7 +42,7 @@ .PHONY: all clean install uninstall # Define required raylib variables -RAYLIB_VERSION = 2.0.0 +RAYLIB_VERSION = 2.4.0 RAYLIB_API_VERSION = 2 # See below for alternatives. @@ -180,34 +180,10 @@ ifeq ($(PLATFORM),PLATFORM_ANDROID) endif endif -# RAYLIB_RELEASE_PATH points to library build path, right now +# Define output directory for compiled library, defaults to src directory +# NOTE: If externally provided, make sure directory exists RAYLIB_RELEASE_PATH ?= $(RAYLIB_PATH)/src -# Define output directory for compiled library -ifeq ($(PLATFORM),PLATFORM_DESKTOP) - ifeq ($(PLATFORM_OS),WINDOWS) - RAYLIB_RELEASE_PATH = $(RAYLIB_PATH)\mingw\i686-w64-mingw32\lib - endif - ifeq ($(PLATFORM_OS),LINUX) - RAYLIB_RELEASE_PATH = $(RAYLIB_PATH)/src - endif - ifeq ($(PLATFORM_OS),OSX) - RAYLIB_RELEASE_PATH = $(RAYLIB_PATH)/src - endif - ifeq ($(PLATFORM_OS),BSD) - RAYLIB_RELEASE_PATH = $(RAYLIB_PATH)/src - endif -endif -ifeq ($(PLATFORM),PLATFORM_RPI) - RAYLIB_RELEASE_PATH = $(RAYLIB_PATH)/src -endif -ifeq ($(PLATFORM),PLATFORM_WEB) - RAYLIB_RELEASE_PATH = $(RAYLIB_PATH)/src -endif -ifeq ($(PLATFORM),PLATFORM_ANDROID) - RAYLIB_RELEASE_PATH = $(RAYLIB_PATH)/src/android/$(ANDROID_ARCH_NAME) -endif - # Define raylib graphics api depending on selected platform ifeq ($(PLATFORM),PLATFORM_DESKTOP) # By default use OpenGL 3.3 on desktop platforms @@ -444,11 +420,6 @@ ifeq ($(PLATFORM),PLATFORM_WEB) emcc -O1 $(OBJS) -o $(RAYLIB_RELEASE_PATH)/libraylib.bc @echo "raylib library generated (libraylib.bc)!" else - ifeq ($(PLATFORM_OS),WINDOWS) - if not exist $(RAYLIB_RELEASE_PATH) mkdir $(RAYLIB_RELEASE_PATH) - else - mkdir -p $(RAYLIB_RELEASE_PATH) - endif ifeq ($(RAYLIB_LIBTYPE),SHARED) ifeq ($(PLATFORM),PLATFORM_DESKTOP) ifeq ($(PLATFORM_OS),WINDOWS) -- cgit v1.2.3 From aa00d77110397ec6bda28815fd5a19a19e53988b Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 18 Mar 2019 18:46:39 +0100 Subject: Support additional modules building -WIP- The idea is supporting additional raygui and physac modules building with raylib but those modules are distributed as header-only libraries and it makes a bit dificult to build them inside raylib... --- src/Makefile | 36 ++++++++++++++++++++++++++++++++---- 1 file changed, 32 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/Makefile b/src/Makefile index c579f9a7..e2fe6c5d 100644 --- a/src/Makefile +++ b/src/Makefile @@ -63,6 +63,11 @@ RAYLIB_BUILD_MODE ?= RELEASE # NOTE: Some programs like tools could not require those modules RAYLIB_MODULE_AUDIO ?= TRUE RAYLIB_MODULE_MODELS ?= TRUE +RAYLIB_MODULE_RAYGUI ?= FALSE +RAYLIB_MODULE_PHYSAC ?= FALSE + +RAYLIB_MODULE_RAYGUI_PATH ?= . +RAYLIB_MODULE_PHYSAC_PATH ?= . # Use external GLFW library instead of rglfw module # TODO: Review usage of examples on Linux. @@ -180,6 +185,9 @@ ifeq ($(PLATFORM),PLATFORM_ANDROID) endif endif +# Define raylib source code path +RAYLIB_SRC_PATH ?= $(RAYLIB_PATH)/src + # Define output directory for compiled library, defaults to src directory # NOTE: If externally provided, make sure directory exists RAYLIB_RELEASE_PATH ?= $(RAYLIB_PATH)/src @@ -383,6 +391,12 @@ endif ifeq ($(RAYLIB_MODULE_AUDIO),TRUE) OBJS += raudio.o endif +ifeq ($(RAYLIB_MODULE_RAYGUI),TRUE) + OBJS += raygui.o +endif +ifeq ($(RAYLIB_MODULE_PHYSAC),TRUE) + OBJS += physac.o +endif ifeq ($(PLATFORM),PLATFORM_ANDROID) OBJS += external/android/native_app_glue/android_native_app_glue.o @@ -496,6 +510,10 @@ textures.o : textures.c raylib.h rlgl.h utils.h text.o : text.c raylib.h utils.h $(CC) -c $< $(CFLAGS) $(INCLUDE_PATHS) -D$(PLATFORM) -D$(GRAPHICS) +# Compile utils module +utils.o : utils.c utils.h + $(CC) -c $< $(CFLAGS) $(INCLUDE_PATHS) -D$(PLATFORM) + # Compile models module models.o : models.c raylib.h rlgl.h raymath.h $(CC) -c $< $(CFLAGS) $(INCLUDE_PATHS) -D$(PLATFORM) -D$(GRAPHICS) @@ -503,10 +521,20 @@ models.o : models.c raylib.h rlgl.h raymath.h # Compile audio module raudio.o : raudio.c raylib.h $(CC) -c $< $(CFLAGS) $(INCLUDE_PATHS) -D$(PLATFORM) - -# Compile utils module -utils.o : utils.c utils.h - $(CC) -c $< $(CFLAGS) $(INCLUDE_PATHS) -D$(PLATFORM) + +# Compile raygui module +# NOTE: raygui header should be distributed with raylib.h +raygui.o : raygui.c raygui.h + @echo #define RAYGUI_IMPLEMENTATION > raygui.c + @echo #include "$(RAYLIB_MODULE_RAYGUI_PATH)/raygui.h" > raygui.c + $(CC) -c $< $(CFLAGS) $(INCLUDE_PATHS) -D$(PLATFORM) -DRAYGUI_IMPLEMENTATION + +# Compile physac module +# NOTE: physac header should be distributed with raylib.h +physac.o : physac.c physac.h + @echo #define PHYSAC_IMPLEMENTATION > physac.c + @echo #include "$(RAYLIB_MODULE_PHYSAC_PATH)/physac.h" > physac.c + $(CC) -c $< $(CFLAGS) $(INCLUDE_PATHS) -D$(PLATFORM) -DRAYGUI_IMPLEMENTATION # Install generated and needed files to desired directories. -- cgit v1.2.3 From c001bdb2de49522441b97380d7ee2721f95d438a Mon Sep 17 00:00:00 2001 From: Ray Date: Wed, 20 Mar 2019 10:57:41 +0100 Subject: Checking issue with sound volume It seems individual sound volume level is not set... --- src/raudio.c | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/raudio.c b/src/raudio.c index 2d59302e..1c153009 100644 --- a/src/raudio.c +++ b/src/raudio.c @@ -457,7 +457,7 @@ static void MixAudioFrames(float *framesOut, const float *framesIn, ma_uint32 fr float *frameOut = framesOut + (iFrame*device.playback.channels); const float *frameIn = framesIn + (iFrame*device.playback.channels); - frameOut[iChannel] += frameIn[iChannel]*masterVolume*localVolume; + frameOut[iChannel] += (frameIn[iChannel]*masterVolume*localVolume); } } } @@ -595,11 +595,11 @@ AudioBuffer *CreateAudioBuffer(ma_format format, ma_uint32 channels, ma_uint32 s return NULL; } - audioBuffer->volume = 1; - audioBuffer->pitch = 1; - audioBuffer->playing = 0; - audioBuffer->paused = 0; - audioBuffer->looping = 0; + audioBuffer->volume = 1.0f; + audioBuffer->pitch = 1.0f; + audioBuffer->playing = false; + audioBuffer->paused = false; + audioBuffer->looping = false; audioBuffer->usage = usage; audioBuffer->bufferSizeInFrames = bufferSizeInFrames; audioBuffer->frameCursorPos = 0; @@ -702,7 +702,7 @@ void SetAudioBufferVolume(AudioBuffer *audioBuffer, float volume) { if (audioBuffer == NULL) { - TraceLog(LOG_ERROR, "SetAudioBufferVolume() : No audio buffer"); + TraceLog(LOG_WARNING, "SetAudioBufferVolume() : No audio buffer"); return; } @@ -714,7 +714,7 @@ void SetAudioBufferPitch(AudioBuffer *audioBuffer, float pitch) { if (audioBuffer == NULL) { - TraceLog(LOG_ERROR, "SetAudioBufferPitch() : No audio buffer"); + TraceLog(LOG_WARNING, "SetAudioBufferPitch() : No audio buffer"); return; } -- cgit v1.2.3 From 7524fdc3e1815245841cbfb0193f4dc234916de0 Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 25 Mar 2019 12:30:20 +0100 Subject: Review gestures disable flag --- src/core.c | 56 +++++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 41 insertions(+), 15 deletions(-) (limited to 'src') diff --git a/src/core.c b/src/core.c index aab60f13..7e807ed4 100644 --- a/src/core.c +++ b/src/core.c @@ -3684,7 +3684,6 @@ static int32_t AndroidInputCallback(struct android_app *app, AInputEvent *event) ProcessGestureEvent(gestureEvent); } #else - // Support only simple touch position if (flags == AMOTION_EVENT_ACTION_DOWN) { @@ -3788,6 +3787,7 @@ static EM_BOOL EmscriptenTouchCallback(int eventType, const EmscriptenTouchEvent } */ +#if defined(SUPPORT_GESTURES_SYSTEM) GestureEvent gestureEvent; // Register touch actions @@ -3822,6 +3822,17 @@ static EM_BOOL EmscriptenTouchCallback(int eventType, const EmscriptenTouchEvent // Gesture data is sent to gestures system for processing ProcessGestureEvent(gestureEvent); +#else + // Support only simple touch position + if (eventType == EMSCRIPTEN_EVENT_TOUCHSTART) + { + // Get first touch position + touchPosition[0] = (Vector2){ touchEvent->touches[0].targetX, touchEvent->touches[0].targetY }; + + touchPosition[0].x /= (float)GetScreenWidth(); + touchPosition[0].y /= (float)GetScreenHeight(); + } +#endif return 1; } @@ -4242,9 +4253,10 @@ static void EventThreadSpawn(char *device) static void *EventThread(void *arg) { struct input_event event; - GestureEvent gestureEvent; InputEventWorker *worker = (InputEventWorker *)arg; - bool GestureNeedsUpdate = false; + + int touchAction = -1; + bool gestureUpdate = false; while (!windowShouldClose) { @@ -4257,16 +4269,18 @@ static void *EventThread(void *arg) { mousePosition.x += event.value; touchPosition[0].x = mousePosition.x; - gestureEvent.touchAction = TOUCH_MOVE; - GestureNeedsUpdate = true; + + touchAction = TOUCH_MOVE; + gestureUpdate = true; } if (event.code == REL_Y) { mousePosition.y += event.value; touchPosition[0].y = mousePosition.y; - gestureEvent.touchAction = TOUCH_MOVE; - GestureNeedsUpdate = true; + + touchAction = TOUCH_MOVE; + gestureUpdate = true; } if (event.code == REL_WHEEL) @@ -4282,15 +4296,17 @@ static void *EventThread(void *arg) if (event.code == ABS_X) { mousePosition.x = (event.value - worker->absRange.x)*screenWidth/worker->absRange.width; // Scale acording to absRange - gestureEvent.touchAction = TOUCH_MOVE; - GestureNeedsUpdate = true; + + touchAction = TOUCH_MOVE; + gestureUpdate = true; } if (event.code == ABS_Y) { mousePosition.y = (event.value - worker->absRange.y)*screenHeight/worker->absRange.height; // Scale acording to absRange - gestureEvent.touchAction = TOUCH_MOVE; - GestureNeedsUpdate = true; + + touchAction = TOUCH_MOVE; + gestureUpdate = true; } // Multitouch movement @@ -4328,9 +4344,10 @@ static void *EventThread(void *arg) if ((event.code == BTN_TOUCH) || (event.code == BTN_LEFT)) { currentMouseStateEvdev[MOUSE_LEFT_BUTTON] = event.value; - if (event.value > 0) gestureEvent.touchAction = TOUCH_DOWN; - else gestureEvent.touchAction = TOUCH_UP; - GestureNeedsUpdate = true; + + if (event.value > 0) touchAction = TOUCH_DOWN; + else touchAction = TOUCH_UP; + gestureUpdate = true; } if (event.code == BTN_RIGHT) currentMouseStateEvdev[MOUSE_RIGHT_BUTTON] = event.value; @@ -4346,22 +4363,31 @@ static void *EventThread(void *arg) if (mousePosition.y > screenHeight/mouseScale.y) mousePosition.y = screenHeight/mouseScale.y; // Gesture update - if (GestureNeedsUpdate) + if (gestureUpdate) { +#if defined(SUPPORT_GESTURES_SYSTEM) + GestureEvent gestureEvent = { 0 }; + gestureEvent.pointCount = 0; + gestureEvent.touchAction = touchAction; + if (touchPosition[0].x >= 0) gestureEvent.pointCount++; if (touchPosition[1].x >= 0) gestureEvent.pointCount++; if (touchPosition[2].x >= 0) gestureEvent.pointCount++; if (touchPosition[3].x >= 0) gestureEvent.pointCount++; + gestureEvent.pointerId[0] = 0; gestureEvent.pointerId[1] = 1; gestureEvent.pointerId[2] = 2; gestureEvent.pointerId[3] = 3; + gestureEvent.position[0] = touchPosition[0]; gestureEvent.position[1] = touchPosition[1]; gestureEvent.position[2] = touchPosition[2]; gestureEvent.position[3] = touchPosition[3]; + ProcessGestureEvent(gestureEvent); +#endif } } else -- cgit v1.2.3 From 165ced94286073a708d69119e8e8fde381710da2 Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 28 Mar 2019 13:03:25 +0100 Subject: Small tweak --- src/shapes.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/shapes.c b/src/shapes.c index fd28f3a3..af683f2e 100644 --- a/src/shapes.c +++ b/src/shapes.c @@ -214,7 +214,7 @@ void DrawCircleSector(Vector2 center, float radius, int startAngle, int endAngle rlDisableTexture(); #else - if (rlCheckBufferLimit(3*((360/CIRCLE_SECTOR_LENGTH)/2))) rlglDraw(); + if (rlCheckBufferLimit(3*360/CIRCLE_SECTOR_LENGTH)) rlglDraw(); rlBegin(RL_TRIANGLES); for (int i = startAngle; i < endAngle; i += CIRCLE_SECTOR_LENGTH) @@ -239,7 +239,7 @@ void DrawCircleGradient(int centerX, int centerY, float radius, Color color1, Co for (int i = 0; i < 360; i += 10) { rlColor4ub(color1.r, color1.g, color1.b, color1.a); - rlVertex2i(centerX, centerY); + rlVertex2f(centerX, centerY); rlColor4ub(color2.r, color2.g, color2.b, color2.a); rlVertex2f(centerX + sinf(DEG2RAD*i)*radius, centerY + cosf(DEG2RAD*i)*radius); rlColor4ub(color2.r, color2.g, color2.b, color2.a); -- cgit v1.2.3 From 186d34827af93ec760c81a2abea09991c01556b3 Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 28 Mar 2019 18:05:32 +0100 Subject: Align LINES and TRIANGLES drawing When drawing LINES or TRIANGLES, vertex are accumulated in same buffer as QUADS and new draw calls are registered but QUADS drawing uses an index buffer for optimization, so, when adding LINES/TRIANGLES vertices we need to make sure next draw calls for QUADS keep aligned with indices buffer. To get that we just add some alignment vertex at the end of the LINES/TRIANGLES draw calls, to make them multiple of 4 vertex. --- src/rlgl.h | 59 ++++++++++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 46 insertions(+), 13 deletions(-) (limited to 'src') diff --git a/src/rlgl.h b/src/rlgl.h index 00658fa1..d4faec18 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -728,6 +728,7 @@ typedef struct DynamicBuffer { typedef struct DrawCall { int mode; // Drawing mode: LINES, TRIANGLES, QUADS int vertexCount; // Number of vertex of the draw + int vertexAlignment; // Number of vertex required for index alignment (LINES, TRIANGLES) //unsigned int vaoId; // Vertex Array id to be used on the draw //unsigned int shaderId; // Shader id to be used on the draw unsigned int textureId; // Texture id to be used on the draw @@ -1123,7 +1124,27 @@ void rlBegin(int mode) // NOTE: In all three cases, vertex are accumulated over default internal vertex buffer if (draws[drawsCounter - 1].mode != mode) { - if (draws[drawsCounter - 1].vertexCount > 0) drawsCounter++; + if (draws[drawsCounter - 1].vertexCount > 0) + { + // Make sure current draws[i].vertexCount is aligned a multiple of 4, + // that way, following QUADS drawing will keep aligned with index processing + // It implies adding some extra alignment vertex at the end of the draw, + // those vertex are not processed but they are considered as an additional offset + // for the next set of vertex to be drawn + if (draws[drawsCounter - 1].mode == RL_LINES) draws[drawsCounter - 1].vertexAlignment = ((draws[drawsCounter - 1].vertexCount < 4)? draws[drawsCounter - 1].vertexCount : draws[drawsCounter - 1].vertexCount%4); + else if (draws[drawsCounter - 1].mode == RL_TRIANGLES) draws[drawsCounter - 1].vertexAlignment = ((draws[drawsCounter - 1].vertexCount < 4)? 1 : (4 - (draws[drawsCounter - 1].vertexCount%4))); + + if (rlCheckBufferLimit(draws[drawsCounter - 1].vertexAlignment)) rlglDraw(); + else + { + vertexData[currentBuffer].vCounter += draws[drawsCounter - 1].vertexAlignment; + vertexData[currentBuffer].cCounter += draws[drawsCounter - 1].vertexAlignment; + vertexData[currentBuffer].tcCounter += draws[drawsCounter - 1].vertexAlignment; + + drawsCounter++; + } + } + if (drawsCounter >= MAX_DRAWCALL_REGISTERED) rlglDraw(); draws[drawsCounter - 1].mode = mode; @@ -1135,15 +1156,6 @@ void rlBegin(int mode) // Finish vertex providing void rlEnd(void) { - // Make sure current draws[i].vertexCount is multiple of 4, to align with index processing - // NOTE: It implies adding some extra vertex at the end of the draw, those vertex will be - // processed but are placed in a single point to not result in a fragment output... - // TODO: System could be improved (a bit) just storing every draw alignment value - // and adding it to vertexOffset on drawing... maybe in a future... - int vertexCount = draws[drawsCounter - 1].vertexCount; - int vertexToAlign = (vertexCount >= 4)? vertexCount%4 : (4 - vertexCount%4); - for (int i = 0; i < vertexToAlign; i++) rlVertex3f(-1, -1, -1); - // Make sure vertexCount is the same for vertices, texcoords, colors and normals // NOTE: In OpenGL 1.1, one glColor call can be made for all the subsequent glVertex calls @@ -1283,7 +1295,27 @@ void rlEnableTexture(unsigned int id) #if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) if (draws[drawsCounter - 1].textureId != id) { - if (draws[drawsCounter - 1].vertexCount > 0) drawsCounter++; + if (draws[drawsCounter - 1].vertexCount > 0) + { + // Make sure current draws[i].vertexCount is aligned a multiple of 4, + // that way, following QUADS drawing will keep aligned with index processing + // It implies adding some extra alignment vertex at the end of the draw, + // those vertex are not processed but they are considered as an additional offset + // for the next set of vertex to be drawn + if (draws[drawsCounter - 1].mode == RL_LINES) draws[drawsCounter - 1].vertexAlignment = ((draws[drawsCounter - 1].vertexCount < 4)? draws[drawsCounter - 1].vertexCount : draws[drawsCounter - 1].vertexCount%4); + else if (draws[drawsCounter - 1].mode == RL_TRIANGLES) draws[drawsCounter - 1].vertexAlignment = ((draws[drawsCounter - 1].vertexCount < 4)? 1 : (4 - (draws[drawsCounter - 1].vertexCount%4))); + + if (rlCheckBufferLimit(draws[drawsCounter - 1].vertexAlignment)) rlglDraw(); + else + { + vertexData[currentBuffer].vCounter += draws[drawsCounter - 1].vertexAlignment; + vertexData[currentBuffer].cCounter += draws[drawsCounter - 1].vertexAlignment; + vertexData[currentBuffer].tcCounter += draws[drawsCounter - 1].vertexAlignment; + + drawsCounter++; + } + } + if (drawsCounter >= MAX_DRAWCALL_REGISTERED) rlglDraw(); draws[drawsCounter - 1].textureId = id; @@ -1682,6 +1714,7 @@ void rlglInit(int width, int height) { draws[i].mode = RL_QUADS; draws[i].vertexCount = 0; + draws[i].vertexAlignment = 0; //draws[i].vaoId = 0; //draws[i].shaderId = 0; draws[i].textureId = defaultTextureId; @@ -4190,8 +4223,8 @@ static void DrawBuffersDefault(void) glDrawElements(GL_TRIANGLES, draws[i].vertexCount/4*6, GL_UNSIGNED_SHORT, (GLvoid *)(sizeof(GLushort)*vertexOffset/4*6)); #endif } - - vertexOffset += draws[i].vertexCount; + + vertexOffset += (draws[i].vertexCount + draws[i].vertexAlignment); } if (!vaoSupported) -- cgit v1.2.3 From 88dfd2ab236a28db3cf1e3715b9e98a426de48d6 Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 28 Mar 2019 18:53:41 +0100 Subject: REDESIGNED: DrawCircleSector() --- src/raylib.h | 2 +- src/shapes.c | 72 ++++++++++++++++++++++++++++++++++++++++++++++++------------ 2 files changed, 59 insertions(+), 15 deletions(-) (limited to 'src') diff --git a/src/raylib.h b/src/raylib.h index c72f0682..5db50c04 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -1043,7 +1043,7 @@ RLAPI void DrawLineV(Vector2 startPos, Vector2 endPos, Color color); RLAPI void DrawLineEx(Vector2 startPos, Vector2 endPos, float thick, Color color); // Draw a line defining thickness RLAPI void DrawLineBezier(Vector2 startPos, Vector2 endPos, float thick, Color color); // Draw a line using cubic-bezier curves in-out RLAPI void DrawCircle(int centerX, int centerY, float radius, Color color); // Draw a color-filled circle -RLAPI void DrawCircleSector(Vector2 center, float radius, int startAngle, int endAngle, Color color); // Draw a piece of a circle +RLAPI void DrawCircleSector(Vector2 center, float radius, int startAngle, int endAngle, int segments, Color color); // Draw a piece of a circle RLAPI void DrawCircleGradient(int centerX, int centerY, float radius, Color color1, Color color2); // Draw a gradient-filled circle RLAPI void DrawCircleV(Vector2 center, float radius, Color color); // Draw a color-filled circle (Vector version) RLAPI void DrawCircleLines(int centerX, int centerY, float radius, Color color); // Draw circle outline diff --git a/src/shapes.c b/src/shapes.c index af683f2e..5d93078b 100644 --- a/src/shapes.c +++ b/src/shapes.c @@ -183,18 +183,40 @@ void DrawCircle(int centerX, int centerY, float radius, Color color) } // Draw a piece of a circle -// TODO: Support better angle resolution (now limited to CIRCLE_SECTOR_LENGTH) -void DrawCircleSector(Vector2 center, float radius, int startAngle, int endAngle, Color color) +void DrawCircleSector(Vector2 center, float radius, int startAngle, int endAngle, int segments, Color color) { - #define CIRCLE_SECTOR_LENGTH 10 - + // Function expects (endAngle > startAngle) + if (endAngle < startAngle) + { + // Swap values + int tmp = startAngle; + startAngle = endAngle; + endAngle = tmp; + } + + if (segments < 4) + { + // Calculate how many segments we need to draw a smooth circle, taken from https://stackoverflow.com/a/2244088 + #define CIRCLE_ERROR_RATE 0.5f + + // Calculate the maximum angle between segments based on the error rate. + float th = acosf(2*powf(1 - CIRCLE_ERROR_RATE/radius, 2) - 1); + segments = (endAngle - startAngle)*ceilf(2*PI/th)/360; + + if (segments <= 0) segments = 4; + } + + float stepLength = (float)(endAngle - startAngle)/(float)segments; + float angle = startAngle; + #if defined(SUPPORT_QUADS_DRAW_MODE) - if (rlCheckBufferLimit(4*((360/CIRCLE_SECTOR_LENGTH)/2))) rlglDraw(); + if (rlCheckBufferLimit(4*segments/2)) rlglDraw(); rlEnableTexture(GetShapesTexture().id); rlBegin(RL_QUADS); - for (int i = startAngle; i < endAngle; i += CIRCLE_SECTOR_LENGTH*2) + // NOTE: Every QUAD actually represents two segments + for (int i = 0; i < segments/2; i++) { rlColor4ub(color.r, color.g, color.b, color.a); @@ -202,28 +224,50 @@ void DrawCircleSector(Vector2 center, float radius, int startAngle, int endAngle rlVertex2f(center.x, center.y); rlTexCoord2f(recTexShapes.x/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); - rlVertex2f(center.x + sinf(DEG2RAD*i)*radius, center.y + cosf(DEG2RAD*i)*radius); + rlVertex2f(center.x + sinf(DEG2RAD*angle)*radius, center.y + cosf(DEG2RAD*angle)*radius); + + rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); + rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength))*radius, center.y + cosf(DEG2RAD*(angle + stepLength))*radius); + + rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, recTexShapes.y/texShapes.height); + rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength*2))*radius, center.y + cosf(DEG2RAD*(angle + stepLength*2))*radius); + + angle += (stepLength*2); + } + + // NOTE: In case number of segments is odd, we add one last piece to the cake + if (segments%2) + { + rlColor4ub(color.r, color.g, color.b, color.a); + + rlTexCoord2f(recTexShapes.x/texShapes.width, recTexShapes.y/texShapes.height); + rlVertex2f(center.x, center.y); + rlTexCoord2f(recTexShapes.x/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); + rlVertex2f(center.x + sinf(DEG2RAD*angle)*radius, center.y + cosf(DEG2RAD*angle)*radius); + rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); - rlVertex2f(center.x + sinf(DEG2RAD*(i + CIRCLE_SECTOR_LENGTH))*radius, center.y + cosf(DEG2RAD*(i + CIRCLE_SECTOR_LENGTH))*radius); + rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength))*radius, center.y + cosf(DEG2RAD*(angle + stepLength))*radius); rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, recTexShapes.y/texShapes.height); - rlVertex2f(center.x + sinf(DEG2RAD*(i + CIRCLE_SECTOR_LENGTH*2))*radius, center.y + cosf(DEG2RAD*(i + CIRCLE_SECTOR_LENGTH*2))*radius); + rlVertex2f(center.x, center.y); } rlEnd(); rlDisableTexture(); #else - if (rlCheckBufferLimit(3*360/CIRCLE_SECTOR_LENGTH)) rlglDraw(); + if (rlCheckBufferLimit(3*segments)) rlglDraw(); rlBegin(RL_TRIANGLES); - for (int i = startAngle; i < endAngle; i += CIRCLE_SECTOR_LENGTH) + for (int i = 0; i < segments; i++) { rlColor4ub(color.r, color.g, color.b, color.a); rlVertex2f(center.x, center.y); - rlVertex2f(center.x + sinf(DEG2RAD*i)*radius, center.y + cosf(DEG2RAD*i)*radius); - rlVertex2f(center.x + sinf(DEG2RAD*(i + CIRCLE_SECTOR_LENGTH))*radius, center.y + cosf(DEG2RAD*(i + CIRCLE_SECTOR_LENGTH))*radius); + rlVertex2f(center.x + sinf(DEG2RAD*angle)*radius, center.y + cosf(DEG2RAD*angle)*radius); + rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength))*radius, center.y + cosf(DEG2RAD*(angle + stepLength))*radius); + + angle += stepLength; } rlEnd(); #endif @@ -252,7 +296,7 @@ void DrawCircleGradient(int centerX, int centerY, float radius, Color color1, Co // NOTE: On OpenGL 3.3 and ES2 we use QUADS to avoid drawing order issues (view rlglDraw) void DrawCircleV(Vector2 center, float radius, Color color) { - DrawCircleSector(center, radius, 0, 360, color); + DrawCircleSector(center, radius, 0, 360, 36, color); } // Draw circle outline -- cgit v1.2.3 From b1e914bbf317cad17eeb3b161dc04c0a7ec78d0d Mon Sep 17 00:00:00 2001 From: Berni8k Date: Thu, 28 Mar 2019 19:46:39 +0100 Subject: RaspberryPi Keyboard input with evdev Based on pull request from user "DarkElvenAngel", better integrated with the current event system and enhanced with buffer to help with fast typing at low framerates. --- src/core.c | 85 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 77 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/core.c b/src/core.c index 7e807ed4..d70d0827 100644 --- a/src/core.c +++ b/src/core.c @@ -361,6 +361,15 @@ typedef struct { static InputEventWorker eventWorkers[10]; // List of worker threads for every monitored "/dev/input/event" +typedef struct{ + int Contents[8]; + char Head; + char Tail; +} KeyEventFifo; + +static KeyEventFifo lastKeyPressedEvdev; // Buffer for holding keydown events as they arrive (Needed due to multitreading of event workers) +static char currentKeyStateEvdev[512] = { 0 }; // Registers current frame key state from event based driver (Needs to be seperate because the legacy console based method clears keys on every frame) + #endif #if defined(PLATFORM_WEB) static bool toggleCursorLock = false; // Ask for cursor pointer lock on next click @@ -470,7 +479,7 @@ static EM_BOOL EmscriptenGamepadCallback(int eventType, const EmscriptenGamepadE static void InitKeyboard(void); // Init raw keyboard system (standard input reading) static void ProcessKeyboard(void); // Process keyboard events static void RestoreKeyboard(void); // Restore keyboard system -static void InitMouse(void); // Mouse initialization (including mouse thread) +static void InitEvdevInput(void); // Mouse initialization (including mouse thread) static void EventThreadSpawn(char *device); // Identifies a input device and spawns a thread to handle it if needed static void *EventThread(void *arg); // Input device events reading thread static void InitGamepad(void); // Init raw gamepad input @@ -590,7 +599,7 @@ void InitWindow(int width, int height, const char *title) #if defined(PLATFORM_RPI) // Init raw input system - InitMouse(); // Mouse init + InitEvdevInput(); // Mouse init InitKeyboard(); // Keyboard init InitGamepad(); // Gamepad init #endif @@ -3054,8 +3063,16 @@ static void PollInputEvents(void) #endif #if defined(PLATFORM_RPI) + // Register previous keys states - for (int i = 0; i < 512; i++) previousKeyState[i] = currentKeyState[i]; + for (int i = 0; i < 512; i++)previousKeyState[i] = currentKeyState[i]; + + // Grab a keypress from the evdev fifo if avalable + if(lastKeyPressedEvdev.Head != lastKeyPressedEvdev.Tail) + { + lastKeyPressed = lastKeyPressedEvdev.Contents[lastKeyPressedEvdev.Tail]; // Read the key from the buffer + lastKeyPressedEvdev.Tail = (lastKeyPressedEvdev.Tail + 1) & 0x07; // Increment the tail pointer forwards and binary wraparound after 7 (fifo is 8 elements long) + } // Register previous mouse states previousMouseWheelY = currentMouseWheelY; @@ -3211,10 +3228,10 @@ static void PollInputEvents(void) #endif #if defined(PLATFORM_RPI) - // NOTE: Mouse input events polling is done asynchonously in another pthread - MouseThread() + // NOTE: Mouse input events polling is done asynchonously in another pthread - EventThread() // NOTE: Keyboard reading could be done using input_event(s) reading or just read from stdin, - // we use method 2 (stdin) but maybe in a future we should change to method 1... + // we now use both methods inside here. 2nd method is still used for legacy purposes (Allows for input trough SSH console) ProcessKeyboard(); // NOTE: Gamepad (Joystick) input events polling is done asynchonously in another pthread - GamepadThread() @@ -3921,6 +3938,9 @@ static void ProcessKeyboard(void) // Reset pressed keys array (it will be filled below) for (int i = 0; i < 512; i++) currentKeyState[i] = 0; + // Check keys from event input workers (This is the new keyboard reading method) + for (int i = 0; i < 512; i++)currentKeyState[i] = currentKeyStateEvdev[i]; + // Fill all read bytes (looking for keys) for (int i = 0; i < bufferByteCount; i++) { @@ -4021,8 +4041,8 @@ static void RestoreKeyboard(void) ioctl(STDIN_FILENO, KDSKBMODE, defaultKeyboardMode); } -// Mouse initialization (including mouse thread) -static void InitMouse(void) +// Initialise user input from evdev(/dev/input/event) this means mouse, keyboard or gamepad devices +static void InitEvdevInput(void) { char path[MAX_FILEPATH_LENGTH]; DIR *directory; @@ -4034,6 +4054,11 @@ static void InitMouse(void) touchPosition[i].x = -1; touchPosition[i].y = -1; } + // Reset keypress buffer + lastKeyPressedEvdev.Head = 0; + lastKeyPressedEvdev.Tail = 0; + // Reset keyboard key state + for (int i = 0; i < 512; i++) currentKeyStateEvdev[i] = 0; // Open the linux directory of "/dev/input" directory = opendir(DEFAULT_EVDEV_PATH); @@ -4202,7 +4227,7 @@ static void EventThreadSpawn(char *device) // Decide what to do with the device //------------------------------------------------------------------------------------------------------- - if (worker->isTouch || worker->isMouse) + if (worker->isTouch || worker->isMouse || worker->isKeyboard) { // Looks like a interesting device TraceLog(LOG_INFO, "Opening input device [%s] (%s%s%s%s%s)", device, @@ -4252,14 +4277,35 @@ static void EventThreadSpawn(char *device) // Input device events reading thread static void *EventThread(void *arg) { + // Scancode to keycode mapping for US keyboards + // TODO: Proabobly replace this with a keymap from the X11 to get the correct regional map for the keyboard (Currently non US keyboards will have the wrong mapping for some keys) + static const int keymap_US[] = + {0,256,49,50,51,52,53,54,55,56,57,48,45,61,259,258,81,87,69,82,84, + 89,85,73,79,80,91,93,257,341,65,83,68,70,71,72,74,75,76,59,39,96, + 340,92,90,88,67,86,66,78,77,44,46,47,344,332,342,32,280,290,291, + 292,293,294,295,296,297,298,299,282,281,327,328,329,333,324,325, + 326,334,321,322,323,320,330,0,85,86,300,301,89,90,91,92,93,94,95, + 335,345,331,283,346,101,268,265,266,263,262,269,264,267,260,261, + 112,113,114,115,116,117,118,119,120,121,122,123,124,125,347,127, + 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, + 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, + 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175, + 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, + 192,193,194,0,0,0,0,0,200,201,202,203,204,205,206,207,208,209,210, + 211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226, + 227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242, + 243,244,245,246,247,248,0,0,0,0,0,0,0,}; + struct input_event event; InputEventWorker *worker = (InputEventWorker *)arg; int touchAction = -1; bool gestureUpdate = false; + int keycode; while (!windowShouldClose) { + // Try to read data from the device and only continue if successful if (read(worker->fd, &event, sizeof(event)) == (int)sizeof(event)) { // Relative movement parsing @@ -4341,6 +4387,8 @@ static void *EventThread(void *arg) // Button parsing if (event.type == EV_KEY) { + + // Mouse button parsing if ((event.code == BTN_TOUCH) || (event.code == BTN_LEFT)) { currentMouseStateEvdev[MOUSE_LEFT_BUTTON] = event.value; @@ -4353,6 +4401,27 @@ static void *EventThread(void *arg) if (event.code == BTN_RIGHT) currentMouseStateEvdev[MOUSE_RIGHT_BUTTON] = event.value; if (event.code == BTN_MIDDLE) currentMouseStateEvdev[MOUSE_MIDDLE_BUTTON] = event.value; + + // Keyboard button parsing + if((event.code >= 1) && (event.code <= 255)) //Keyboard keys appear for codes 1 to 255 + { + keycode = keymap_US[event.code & 0xFF]; // The code we get is a scancode so we look up the apropriate keycode + // Make sure we got a valid keycode + if((keycode > 0) && (keycode < sizeof(currentKeyState))) + { + // Store the key information for raylib to later use + currentKeyStateEvdev[keycode] = event.value; + if(event.value > 0) + { + // Add the key int the fifo + lastKeyPressedEvdev.Contents[lastKeyPressedEvdev.Head] = keycode; // Put the data at the front of the fifo snake + lastKeyPressedEvdev.Head = (lastKeyPressedEvdev.Head + 1) & 0x07; // Increment the head pointer forwards and binary wraparound after 7 (fifo is 8 elements long) + // TODO: This fifo is not fully threadsafe with multiple writers, so multiple keyboards hitting a key at the exact same time could miss a key (double write to head before it was incremented) + } + TraceLog(LOG_DEBUG, "KEY%s ScanCode: %4i KeyCode: %4i",event.value == 0 ? "UP":"DOWN", event.code, keycode); + } + } + } // Screen confinement -- cgit v1.2.3 From ea96d0afea630cb5f174a5d433f46f722522fbb3 Mon Sep 17 00:00:00 2001 From: Berni8k Date: Thu, 28 Mar 2019 20:38:13 +0100 Subject: Fixes compile error when SUPPORT_GESTURES_SYSTEM is undefined on RPi --- src/core.c | 40 +++++++++++++++++++++++++--------------- 1 file changed, 25 insertions(+), 15 deletions(-) (limited to 'src') diff --git a/src/core.c b/src/core.c index d70d0827..7cfa6f8b 100644 --- a/src/core.c +++ b/src/core.c @@ -4315,18 +4315,22 @@ static void *EventThread(void *arg) { mousePosition.x += event.value; touchPosition[0].x = mousePosition.x; - - touchAction = TOUCH_MOVE; - gestureUpdate = true; + + #if defined(SUPPORT_GESTURES_SYSTEM) + touchAction = TOUCH_MOVE; + gestureUpdate = true; + #endif } if (event.code == REL_Y) { mousePosition.y += event.value; touchPosition[0].y = mousePosition.y; - - touchAction = TOUCH_MOVE; - gestureUpdate = true; + + #if defined(SUPPORT_GESTURES_SYSTEM) + touchAction = TOUCH_MOVE; + gestureUpdate = true; + #endif } if (event.code == REL_WHEEL) @@ -4342,17 +4346,21 @@ static void *EventThread(void *arg) if (event.code == ABS_X) { mousePosition.x = (event.value - worker->absRange.x)*screenWidth/worker->absRange.width; // Scale acording to absRange - - touchAction = TOUCH_MOVE; - gestureUpdate = true; + + #if defined(SUPPORT_GESTURES_SYSTEM) + touchAction = TOUCH_MOVE; + gestureUpdate = true; + #endif } if (event.code == ABS_Y) { mousePosition.y = (event.value - worker->absRange.y)*screenHeight/worker->absRange.height; // Scale acording to absRange - - touchAction = TOUCH_MOVE; - gestureUpdate = true; + + #if defined(SUPPORT_GESTURES_SYSTEM) + touchAction = TOUCH_MOVE; + gestureUpdate = true; + #endif } // Multitouch movement @@ -4393,9 +4401,11 @@ static void *EventThread(void *arg) { currentMouseStateEvdev[MOUSE_LEFT_BUTTON] = event.value; - if (event.value > 0) touchAction = TOUCH_DOWN; - else touchAction = TOUCH_UP; - gestureUpdate = true; + #if defined(SUPPORT_GESTURES_SYSTEM) + if (event.value > 0) touchAction = TOUCH_DOWN; + else touchAction = TOUCH_UP; + gestureUpdate = true; + #endif } if (event.code == BTN_RIGHT) currentMouseStateEvdev[MOUSE_RIGHT_BUTTON] = event.value; -- cgit v1.2.3 From 69656cb090a53705c515975c127405af87d4f15d Mon Sep 17 00:00:00 2001 From: Ray Date: Fri, 29 Mar 2019 12:23:02 +0100 Subject: Added comment --- src/core.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/core.c b/src/core.c index 7cfa6f8b..7f2f7f1c 100644 --- a/src/core.c +++ b/src/core.c @@ -1164,7 +1164,7 @@ void BeginMode2D(Camera2D camera) Matrix matTransform = MatrixMultiply(MatrixMultiply(matOrigin, MatrixMultiply(matScale, matRotation)), matTranslation); - rlMultMatrixf(MatrixToFloat(matTransform)); + rlMultMatrixf(MatrixToFloat(matTransform)); // Apply transformation to modelview } // Ends 2D mode with custom camera -- cgit v1.2.3 From 876c64b1e530b4b9826eef8fcfc5c3bc567c6be8 Mon Sep 17 00:00:00 2001 From: Ray Date: Fri, 29 Mar 2019 12:27:50 +0100 Subject: WARNING: This could break something If we have no data to update/draw, we avoid update/draw. On `DrawBuffersDefault()` if no vertes data is available nothing is drawn but some globals: vertexData, projection, modelview, draws... are reseted. There shouldn't be any problem if we don't touch those globals in case no vertex have been processed but, just in case, I warn about it. --- src/rlgl.h | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/rlgl.h b/src/rlgl.h index d4faec18..49ab1de5 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -1786,8 +1786,12 @@ void rlglClose(void) void rlglDraw(void) { #if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - UpdateBuffersDefault(); - DrawBuffersDefault(); // NOTE: Stereo rendering is checked inside + // Only process data if we have data to process + if (vertexData[currentBuffer].vCounter > 0) + { + UpdateBuffersDefault(); + DrawBuffersDefault(); // NOTE: Stereo rendering is checked inside + } #endif } -- cgit v1.2.3 From ab9c6da26f79796a04ca79401617a7244ec9c2a8 Mon Sep 17 00:00:00 2001 From: Demizdor Date: Fri, 29 Mar 2019 16:22:09 +0200 Subject: Added DrawRing(), DrawRingLines() and DrawCircleSectorLines() --- src/raylib.h | 3 + src/shapes.c | 240 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 243 insertions(+) (limited to 'src') diff --git a/src/raylib.h b/src/raylib.h index 5db50c04..2f3b7be2 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -1044,9 +1044,12 @@ RLAPI void DrawLineEx(Vector2 startPos, Vector2 endPos, float thick, Color color RLAPI void DrawLineBezier(Vector2 startPos, Vector2 endPos, float thick, Color color); // Draw a line using cubic-bezier curves in-out RLAPI void DrawCircle(int centerX, int centerY, float radius, Color color); // Draw a color-filled circle RLAPI void DrawCircleSector(Vector2 center, float radius, int startAngle, int endAngle, int segments, Color color); // Draw a piece of a circle +RLAPI void DrawCircleSectorLines(Vector2 center, float radius, int startAngle, int endAngle, int segments, Color color); // Draw circle sector outline RLAPI void DrawCircleGradient(int centerX, int centerY, float radius, Color color1, Color color2); // Draw a gradient-filled circle RLAPI void DrawCircleV(Vector2 center, float radius, Color color); // Draw a color-filled circle (Vector version) RLAPI void DrawCircleLines(int centerX, int centerY, float radius, Color color); // Draw circle outline +RLAPI void DrawRing(Vector2 center, float innerRadius, float outerRadius, int startAngle, int endAngle, int segments, Color color); // Draw ring +RLAPI void DrawRingLines(Vector2 center, float innerRadius, float outerRadius, int startAngle, int endAngle, int segments, Color color); // Draw ring outline RLAPI void DrawRectangle(int posX, int posY, int width, int height, Color color); // Draw a color-filled rectangle RLAPI void DrawRectangleV(Vector2 position, Vector2 size, Color color); // Draw a color-filled rectangle (Vector version) RLAPI void DrawRectangleRec(Rectangle rec, Color color); // Draw a color-filled rectangle diff --git a/src/shapes.c b/src/shapes.c index 5d93078b..7e8c0f4b 100644 --- a/src/shapes.c +++ b/src/shapes.c @@ -185,6 +185,8 @@ void DrawCircle(int centerX, int centerY, float radius, Color color) // Draw a piece of a circle void DrawCircleSector(Vector2 center, float radius, int startAngle, int endAngle, int segments, Color color) { + if(radius == 0) return; // Check this or we'll get a div by zero error otherwise + // Function expects (endAngle > startAngle) if (endAngle < startAngle) { @@ -273,6 +275,70 @@ void DrawCircleSector(Vector2 center, float radius, int startAngle, int endAngle #endif } +void DrawCircleSectorLines(Vector2 center, float radius, int startAngle, int endAngle, int segments, Color color) +{ + if(radius == 0) return; // Check this or we'll get a div by zero error otherwise + + // Function expects (endAngle > startAngle) + if (endAngle < startAngle) + { + // Swap values + int tmp = startAngle; + startAngle = endAngle; + endAngle = tmp; + } + + if (segments < 4) + { + // Calculate how many segments we need to draw a smooth circle, taken from https://stackoverflow.com/a/2244088 + #ifndef CIRCLE_ERROR_RATE + #define CIRCLE_ERROR_RATE 0.5f + #endif + + // Calculate the maximum angle between segments based on the error rate. + float th = acosf(2*powf(1 - CIRCLE_ERROR_RATE/radius, 2) - 1); + segments = (endAngle - startAngle)*ceilf(2*PI/th)/360; + + if (segments <= 0) segments = 4; + } + + float stepLength = (float)(endAngle - startAngle)/(float)segments; + float angle = startAngle; + + // Hide the cap lines when the circle is full + bool showCapLines = true; + int limit = 2*(segments + 2); + if((endAngle - startAngle) % 360 == 0) { limit = 2*segments; showCapLines = false; } + + if (rlCheckBufferLimit(limit)) rlglDraw(); + + rlBegin(RL_LINES); + if(showCapLines) + { + rlColor4ub(color.r, color.g, color.b, color.a); + rlVertex2f(center.x, center.y); + rlVertex2f(center.x + sinf(DEG2RAD*angle)*radius, center.y + cosf(DEG2RAD*angle)*radius); + } + + for (int i = 0; i < segments; i++) + { + rlColor4ub(color.r, color.g, color.b, color.a); + + rlVertex2f(center.x + sinf(DEG2RAD*angle)*radius, center.y + cosf(DEG2RAD*angle)*radius); + rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength))*radius, center.y + cosf(DEG2RAD*(angle + stepLength))*radius); + + angle += stepLength; + } + + if(showCapLines) + { + rlColor4ub(color.r, color.g, color.b, color.a); + rlVertex2f(center.x, center.y); + rlVertex2f(center.x + sinf(DEG2RAD*angle)*radius, center.y + cosf(DEG2RAD*angle)*radius); + } + rlEnd(); +} + // Draw a gradient-filled circle // NOTE: Gradient goes from center (color1) to border (color2) void DrawCircleGradient(int centerX, int centerY, float radius, Color color1, Color color2) @@ -316,6 +382,180 @@ void DrawCircleLines(int centerX, int centerY, float radius, Color color) rlEnd(); } +void DrawRing(Vector2 center, float innerRadius, float outerRadius, int startAngle, int endAngle, int segments, Color color) +{ + if(startAngle == endAngle) return; + + // Function expects (outerRadius > innerRadius) + if(outerRadius < innerRadius) + { + float tmp = outerRadius; + outerRadius = innerRadius; + innerRadius = tmp; + if(outerRadius == 0) return; // Check this or we'll get a div by zero error otherwise + } + + // Function expects (endAngle > startAngle) + if (endAngle < startAngle) + { + // Swap values + int tmp = startAngle; + startAngle = endAngle; + endAngle = tmp; + } + + if (segments < 4) + { + // Calculate how many segments we need to draw a smooth circle, taken from https://stackoverflow.com/a/2244088 + #ifndef CIRCLE_ERROR_RATE + #define CIRCLE_ERROR_RATE 0.5f + #endif + // Calculate the maximum angle between segments based on the error rate. + float th = acosf(2*powf(1 - CIRCLE_ERROR_RATE/outerRadius, 2) - 1); + segments = (endAngle - startAngle)*ceilf(2*PI/th)/360; + + if (segments <= 0) segments = 4; + } + + // Not a ring + if(innerRadius == 0) + { + DrawCircleSector(center, outerRadius, startAngle, endAngle, segments, color); + return; + } + + float stepLength = (float)(endAngle - startAngle)/(float)segments; + float angle = startAngle; + +#if defined(SUPPORT_QUADS_DRAW_MODE) + if (rlCheckBufferLimit(4*segments)) rlglDraw(); + + rlEnableTexture(GetShapesTexture().id); + + rlBegin(RL_QUADS); + for (int i = 0; i < segments; i++) + { + rlColor4ub(color.r, color.g, color.b, color.a); + + rlTexCoord2f(recTexShapes.x/texShapes.width, recTexShapes.y/texShapes.height); + rlVertex2f(center.x + sinf(DEG2RAD*angle)*innerRadius, center.y + cosf(DEG2RAD*angle)*innerRadius); + + rlTexCoord2f(recTexShapes.x/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); + rlVertex2f(center.x + sinf(DEG2RAD*angle)*outerRadius, center.y + cosf(DEG2RAD*angle)*outerRadius); + + rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); + rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength))*outerRadius, center.y + cosf(DEG2RAD*(angle + stepLength))*outerRadius); + + rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, recTexShapes.y/texShapes.height); + rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength))*innerRadius, center.y + cosf(DEG2RAD*(angle + stepLength))*innerRadius); + + angle += stepLength; + } + rlEnd(); + + rlDisableTexture(); +#else + if (rlCheckBufferLimit(6*segments)) rlglDraw(); + + rlBegin(RL_TRIANGLES); + for (int i = 0; i < segments; i++) + { + rlColor4ub(color.r, color.g, color.b, color.a); + + rlVertex2f(center.x + sinf(DEG2RAD*angle)*innerRadius, center.y + cosf(DEG2RAD*angle)*innerRadius); + rlVertex2f(center.x + sinf(DEG2RAD*angle)*outerRadius, center.y + cosf(DEG2RAD*angle)*outerRadius); + rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength))*innerRadius, center.y + cosf(DEG2RAD*(angle + stepLength))*innerRadius); + + rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength))*innerRadius, center.y + cosf(DEG2RAD*(angle + stepLength))*innerRadius); + rlVertex2f(center.x + sinf(DEG2RAD*angle)*outerRadius, center.y + cosf(DEG2RAD*angle)*outerRadius); + rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength))*outerRadius, center.y + cosf(DEG2RAD*(angle + stepLength))*outerRadius); + + angle += stepLength; + } + rlEnd(); +#endif +} + +void DrawRingLines(Vector2 center, float innerRadius, float outerRadius, int startAngle, int endAngle, int segments, Color color) +{ + if(startAngle == endAngle) return; + + // Function expects (outerRadius > innerRadius) + if(outerRadius < innerRadius) + { + float tmp = outerRadius; + outerRadius = innerRadius; + innerRadius = tmp; + if(outerRadius == 0) return; // Check this or we'll get a div by zero error otherwise + } + + // Function expects (endAngle > startAngle) + if (endAngle < startAngle) + { + // Swap values + int tmp = startAngle; + startAngle = endAngle; + endAngle = tmp; + } + + if (segments < 4) + { + // Calculate how many segments we need to draw a smooth circle, taken from https://stackoverflow.com/a/2244088 + #ifndef CIRCLE_ERROR_RATE + #define CIRCLE_ERROR_RATE 0.5f + #endif + // Calculate the maximum angle between segments based on the error rate. + float th = acosf(2*powf(1 - CIRCLE_ERROR_RATE/outerRadius, 2) - 1); + segments = (endAngle - startAngle)*ceilf(2*PI/th)/360; + + if (segments <= 0) segments = 4; + } + + if(innerRadius == 0) + { + DrawCircleSectorLines(center, outerRadius, startAngle, endAngle, segments, color); + return; + } + + float stepLength = (float)(endAngle - startAngle)/(float)segments; + float angle = startAngle; + + bool showCapLines = true; + int limit = 4*(segments + 1); + if((endAngle - startAngle) % 360 == 0) { limit = 4*segments; showCapLines = false; } + + if (rlCheckBufferLimit(limit)) rlglDraw(); + + rlBegin(RL_LINES); + if(showCapLines) + { + rlColor4ub(color.r, color.g, color.b, color.a); + rlVertex2f(center.x + sinf(DEG2RAD*angle)*outerRadius, center.y + cosf(DEG2RAD*angle)*outerRadius); + rlVertex2f(center.x + sinf(DEG2RAD*angle)*innerRadius, center.y + cosf(DEG2RAD*angle)*innerRadius); + } + + for (int i = 0; i < segments; i++) + { + rlColor4ub(color.r, color.g, color.b, color.a); + + rlVertex2f(center.x + sinf(DEG2RAD*angle)*outerRadius, center.y + cosf(DEG2RAD*angle)*outerRadius); + rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength))*outerRadius, center.y + cosf(DEG2RAD*(angle + stepLength))*outerRadius); + + rlVertex2f(center.x + sinf(DEG2RAD*angle)*innerRadius, center.y + cosf(DEG2RAD*angle)*innerRadius); + rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength))*innerRadius, center.y + cosf(DEG2RAD*(angle + stepLength))*innerRadius); + + angle += stepLength; + } + + if(showCapLines) + { + rlColor4ub(color.r, color.g, color.b, color.a); + rlVertex2f(center.x + sinf(DEG2RAD*angle)*outerRadius, center.y + cosf(DEG2RAD*angle)*outerRadius); + rlVertex2f(center.x + sinf(DEG2RAD*angle)*innerRadius, center.y + cosf(DEG2RAD*angle)*innerRadius); + } + rlEnd(); +} + // Draw a color-filled rectangle void DrawRectangle(int posX, int posY, int width, int height, Color color) { -- cgit v1.2.3 From a643dc4ca016ce5791608852ab1357f2d94ebe9b Mon Sep 17 00:00:00 2001 From: Ray Date: Fri, 29 Mar 2019 16:48:23 +0100 Subject: WARNING: Redesigned model struct for multi-meshes This is quite a big change, Model struct has been redesigned to support multiple meshes and multiple materials, most 3d fileformats contain multiple meshes and reference multiple materials. Consequently, multiple functions have been reviewed. LoadOBJ(), LoadIQM(), LoadGLFT() now return a Model. Current LoadOBJ() is not valid anymore, actually, tinyobj_loader_c library is considered for replacement. --- src/external/tinyobj_loader_c.h | 1583 +++++++++++++++++++++++++++++++++++++++ src/models.c | 155 ++-- src/raylib.h | 21 +- 3 files changed, 1685 insertions(+), 74 deletions(-) create mode 100644 src/external/tinyobj_loader_c.h (limited to 'src') diff --git a/src/external/tinyobj_loader_c.h b/src/external/tinyobj_loader_c.h new file mode 100644 index 00000000..e9d015ff --- /dev/null +++ b/src/external/tinyobj_loader_c.h @@ -0,0 +1,1583 @@ +/* + The MIT License (MIT) + + Copyright (c) 2016 - 2019 Syoyo Fujita and many contributors. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + */ +#ifndef TINOBJ_LOADER_C_H_ +#define TINOBJ_LOADER_C_H_ + +/* @todo { Remove stddef dependency. size_t? } */ +#include + +typedef struct { + char *name; + + float ambient[3]; + float diffuse[3]; + float specular[3]; + float transmittance[3]; + float emission[3]; + float shininess; + float ior; /* index of refraction */ + float dissolve; /* 1 == opaque; 0 == fully transparent */ + /* illumination model (see http://www.fileformat.info/format/material/) */ + int illum; + + int pad0; + + char *ambient_texname; /* map_Ka */ + char *diffuse_texname; /* map_Kd */ + char *specular_texname; /* map_Ks */ + char *specular_highlight_texname; /* map_Ns */ + char *bump_texname; /* map_bump, bump */ + char *displacement_texname; /* disp */ + char *alpha_texname; /* map_d */ +} tinyobj_material_t; + +typedef struct { + char *name; /* group name or object name. */ + unsigned int face_offset; + unsigned int length; +} tinyobj_shape_t; + +typedef struct { int v_idx, vt_idx, vn_idx; } tinyobj_vertex_index_t; + +typedef struct { + unsigned int num_vertices; + unsigned int num_normals; + unsigned int num_texcoords; + unsigned int num_faces; + unsigned int num_face_num_verts; + + int pad0; + + float *vertices; + float *normals; + float *texcoords; + tinyobj_vertex_index_t *faces; + int *face_num_verts; + int *material_ids; +} tinyobj_attrib_t; + + +#define TINYOBJ_FLAG_TRIANGULATE (1 << 0) + +#define TINYOBJ_INVALID_INDEX (0x80000000) + +#define TINYOBJ_SUCCESS (0) +#define TINYOBJ_ERROR_EMPTY (-1) +#define TINYOBJ_ERROR_INVALID_PARAMETER (-2) +#define TINYOBJ_ERROR_FILE_OPERATION (-3) + +/* Parse wavefront .obj(.obj string data is expanded to linear char array `buf') + * flags are combination of TINYOBJ_FLAG_*** + * Returns TINYOBJ_SUCCESS if things goes well. + * Returns TINYOBJ_ERR_*** when there is an error. + */ +extern int tinyobj_parse_obj(tinyobj_attrib_t *attrib, tinyobj_shape_t **shapes, + size_t *num_shapes, tinyobj_material_t **materials, + size_t *num_materials, const char *buf, size_t len, + unsigned int flags); +extern int tinyobj_parse_mtl_file(tinyobj_material_t **materials_out, + size_t *num_materials_out, + const char *filename); + +extern void tinyobj_attrib_init(tinyobj_attrib_t *attrib); +extern void tinyobj_attrib_free(tinyobj_attrib_t *attrib); +extern void tinyobj_shapes_free(tinyobj_shape_t *shapes, size_t num_shapes); +extern void tinyobj_materials_free(tinyobj_material_t *materials, + size_t num_materials); + +#ifdef TINYOBJ_LOADER_C_IMPLEMENTATION +#include +#include +#include +#include + +#if defined(TINYOBJ_MALLOC) && defined(TINYOBJ_REALLOC) && defined(TINYOBJ_CALLOC) && defined(TINYOBJ_FREE) +/* ok */ +#elif !defined(TINYOBJ_MALLOC) && !defined(TINYOBJ_REALLOC) && !defined(TINYOBJ_CALLOC) && !defined(TINYOBJ_FREE) +/* ok */ +#else +#error "Must define all or none of TINYOBJ_MALLOC, TINYOBJ_REALLOC, TINYOBJ_CALLOC and TINYOBJ_FREE." +#endif + +#ifndef TINYOBJ_MALLOC +#include +#define TINYOBJ_MALLOC malloc +#define TINYOBJ_REALLOC realloc +#define TINYOBJ_CALLOC calloc +#define TINYOBJ_FREE free +#endif + +#define TINYOBJ_MAX_FACES_PER_F_LINE (16) + +#define IS_SPACE(x) (((x) == ' ') || ((x) == '\t')) +#define IS_DIGIT(x) ((unsigned int)((x) - '0') < (unsigned int)(10)) +#define IS_NEW_LINE(x) (((x) == '\r') || ((x) == '\n') || ((x) == '\0')) + +static void skip_space(const char **token) { + while ((*token)[0] == ' ' || (*token)[0] == '\t') { + (*token)++; + } +} + +static void skip_space_and_cr(const char **token) { + while ((*token)[0] == ' ' || (*token)[0] == '\t' || (*token)[0] == '\r') { + (*token)++; + } +} + +static int until_space(const char *token) { + const char *p = token; + while (p[0] != '\0' && p[0] != ' ' && p[0] != '\t' && p[0] != '\r') { + p++; + } + + return (int)(p - token); +} + +static size_t length_until_newline(const char *token, size_t n) { + size_t len = 0; + + /* Assume token[n-1] = '\0' */ + for (len = 0; len < n - 1; len++) { + if (token[len] == '\n') { + break; + } + if ((token[len] == '\r') && ((len < (n - 2)) && (token[len + 1] != '\n'))) { + break; + } + } + + return len; +} + +static size_t length_until_line_feed(const char *token, size_t n) { + size_t len = 0; + + /* Assume token[n-1] = '\0' */ + for (len = 0; len < n; len++) { + if ((token[len] == '\n') || (token[len] == '\r')) { + break; + } + } + + return len; +} + +/* http://stackoverflow.com/questions/5710091/how-does-atoi-function-in-c-work +*/ +static int my_atoi(const char *c) { + int value = 0; + int sign = 1; + if (*c == '+' || *c == '-') { + if (*c == '-') sign = -1; + c++; + } + while (((*c) >= '0') && ((*c) <= '9')) { /* isdigit(*c) */ + value *= 10; + value += (int)(*c - '0'); + c++; + } + return value * sign; +} + +/* Make index zero-base, and also support relative index. */ +static int fixIndex(int idx, size_t n) { + if (idx > 0) return idx - 1; + if (idx == 0) return 0; + return (int)n + idx; /* negative value = relative */ +} + +/* Parse raw triples: i, i/j/k, i//k, i/j */ +static tinyobj_vertex_index_t parseRawTriple(const char **token) { + tinyobj_vertex_index_t vi; + /* 0x80000000 = -2147483648 = invalid */ + vi.v_idx = (int)(0x80000000); + vi.vn_idx = (int)(0x80000000); + vi.vt_idx = (int)(0x80000000); + + vi.v_idx = my_atoi((*token)); + while ((*token)[0] != '\0' && (*token)[0] != '/' && (*token)[0] != ' ' && + (*token)[0] != '\t' && (*token)[0] != '\r') { + (*token)++; + } + if ((*token)[0] != '/') { + return vi; + } + (*token)++; + + /* i//k */ + if ((*token)[0] == '/') { + (*token)++; + vi.vn_idx = my_atoi((*token)); + while ((*token)[0] != '\0' && (*token)[0] != '/' && (*token)[0] != ' ' && + (*token)[0] != '\t' && (*token)[0] != '\r') { + (*token)++; + } + return vi; + } + + /* i/j/k or i/j */ + vi.vt_idx = my_atoi((*token)); + while ((*token)[0] != '\0' && (*token)[0] != '/' && (*token)[0] != ' ' && + (*token)[0] != '\t' && (*token)[0] != '\r') { + (*token)++; + } + if ((*token)[0] != '/') { + return vi; + } + + /* i/j/k */ + (*token)++; /* skip '/' */ + vi.vn_idx = my_atoi((*token)); + while ((*token)[0] != '\0' && (*token)[0] != '/' && (*token)[0] != ' ' && + (*token)[0] != '\t' && (*token)[0] != '\r') { + (*token)++; + } + return vi; +} + +static int parseInt(const char **token) { + int i = 0; + skip_space(token); + i = my_atoi((*token)); + (*token) += until_space((*token)); + return i; +} + +/* + * Tries to parse a floating point number located at s. + * + * s_end should be a location in the string where reading should absolutely + * stop. For example at the end of the string, to prevent buffer overflows. + * + * Parses the following EBNF grammar: + * sign = "+" | "-" ; + * END = ? anything not in digit ? + * digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ; + * integer = [sign] , digit , {digit} ; + * decimal = integer , ["." , integer] ; + * float = ( decimal , END ) | ( decimal , ("E" | "e") , integer , END ) ; + * + * Valid strings are for example: + * -0 +3.1417e+2 -0.0E-3 1.0324 -1.41 11e2 + * + * If the parsing is a success, result is set to the parsed value and true + * is returned. + * + * The function is greedy and will parse until any of the following happens: + * - a non-conforming character is encountered. + * - s_end is reached. + * + * The following situations triggers a failure: + * - s >= s_end. + * - parse failure. + */ +static int tryParseDouble(const char *s, const char *s_end, double *result) { + double mantissa = 0.0; + /* This exponent is base 2 rather than 10. + * However the exponent we parse is supposed to be one of ten, + * thus we must take care to convert the exponent/and or the + * mantissa to a * 2^E, where a is the mantissa and E is the + * exponent. + * To get the final double we will use ldexp, it requires the + * exponent to be in base 2. + */ + int exponent = 0; + + /* NOTE: THESE MUST BE DECLARED HERE SINCE WE ARE NOT ALLOWED + * TO JUMP OVER DEFINITIONS. + */ + char sign = '+'; + char exp_sign = '+'; + char const *curr = s; + + /* How many characters were read in a loop. */ + int read = 0; + /* Tells whether a loop terminated due to reaching s_end. */ + int end_not_reached = 0; + + /* + BEGIN PARSING. + */ + + if (s >= s_end) { + return 0; /* fail */ + } + + /* Find out what sign we've got. */ + if (*curr == '+' || *curr == '-') { + sign = *curr; + curr++; + } else if (IS_DIGIT(*curr)) { /* Pass through. */ + } else { + goto fail; + } + + /* Read the integer part. */ + end_not_reached = (curr != s_end); + while (end_not_reached && IS_DIGIT(*curr)) { + mantissa *= 10; + mantissa += (int)(*curr - 0x30); + curr++; + read++; + end_not_reached = (curr != s_end); + } + + /* We must make sure we actually got something. */ + if (read == 0) goto fail; + /* We allow numbers of form "#", "###" etc. */ + if (!end_not_reached) goto assemble; + + /* Read the decimal part. */ + if (*curr == '.') { + curr++; + read = 1; + end_not_reached = (curr != s_end); + while (end_not_reached && IS_DIGIT(*curr)) { + /* pow(10.0, -read) */ + double frac_value = 1.0; + int f; + for (f = 0; f < read; f++) { + frac_value *= 0.1; + } + mantissa += (int)(*curr - 0x30) * frac_value; + read++; + curr++; + end_not_reached = (curr != s_end); + } + } else if (*curr == 'e' || *curr == 'E') { + } else { + goto assemble; + } + + if (!end_not_reached) goto assemble; + + /* Read the exponent part. */ + if (*curr == 'e' || *curr == 'E') { + curr++; + /* Figure out if a sign is present and if it is. */ + end_not_reached = (curr != s_end); + if (end_not_reached && (*curr == '+' || *curr == '-')) { + exp_sign = *curr; + curr++; + } else if (IS_DIGIT(*curr)) { /* Pass through. */ + } else { + /* Empty E is not allowed. */ + goto fail; + } + + read = 0; + end_not_reached = (curr != s_end); + while (end_not_reached && IS_DIGIT(*curr)) { + exponent *= 10; + exponent += (int)(*curr - 0x30); + curr++; + read++; + end_not_reached = (curr != s_end); + } + if (read == 0) goto fail; + } + +assemble : + + { + double a = 1.0; /* = pow(5.0, exponent); */ + double b = 1.0; /* = 2.0^exponent */ + int i; + for (i = 0; i < exponent; i++) { + a = a * 5.0; + } + + for (i = 0; i < exponent; i++) { + b = b * 2.0; + } + + if (exp_sign == '-') { + a = 1.0 / a; + b = 1.0 / b; + } + + *result = + /* (sign == '+' ? 1 : -1) * ldexp(mantissa * pow(5.0, exponent), + exponent); */ + (sign == '+' ? 1 : -1) * (mantissa * a * b); + } + + return 1; +fail: + return 0; +} + +static float parseFloat(const char **token) { + const char *end; + double val = 0.0; + float f = 0.0f; + skip_space(token); + end = (*token) + until_space((*token)); + val = 0.0; + tryParseDouble((*token), end, &val); + f = (float)(val); + (*token) = end; + return f; +} + +static void parseFloat2(float *x, float *y, const char **token) { + (*x) = parseFloat(token); + (*y) = parseFloat(token); +} + +static void parseFloat3(float *x, float *y, float *z, const char **token) { + (*x) = parseFloat(token); + (*y) = parseFloat(token); + (*z) = parseFloat(token); +} + +static char *my_strdup(const char *s, size_t max_length) { + char *d; + size_t len; + + if (s == NULL) return NULL; + + /* Do not consider CRLF line ending(#19) */ + len = length_until_line_feed(s, max_length); + /* len = strlen(s); */ + + /* trim line ending and append '\0' */ + d = (char *)TINYOBJ_MALLOC(len + 1); /* + '\0' */ + memcpy(d, s, (size_t)(len)); + d[len] = '\0'; + + return d; +} + +static char *my_strndup(const char *s, size_t len) { + char *d; + size_t slen; + + if (s == NULL) return NULL; + if (len == 0) return NULL; + + d = (char *)TINYOBJ_MALLOC(len + 1); /* + '\0' */ + slen = strlen(s); + if (slen < len) { + memcpy(d, s, slen); + d[slen] = '\0'; + } else { + memcpy(d, s, len); + d[len] = '\0'; + } + + return d; +} + +char *dynamic_fgets(char **buf, size_t *size, FILE *file) { + char *offset; + char *ret; + size_t old_size; + + if (!(ret = fgets(*buf, (int)*size, file))) { + return ret; + } + + if (NULL != strchr(*buf, '\n')) { + return ret; + } + + do { + old_size = *size; + *size *= 2; + *buf = (char*)TINYOBJ_REALLOC(*buf, *size); + offset = &((*buf)[old_size - 1]); + + ret = fgets(offset, (int)(old_size + 1), file); + } while(ret && (NULL == strchr(*buf, '\n'))); + + return ret; +} + +static void initMaterial(tinyobj_material_t *material) { + int i; + material->name = NULL; + material->ambient_texname = NULL; + material->diffuse_texname = NULL; + material->specular_texname = NULL; + material->specular_highlight_texname = NULL; + material->bump_texname = NULL; + material->displacement_texname = NULL; + material->alpha_texname = NULL; + for (i = 0; i < 3; i++) { + material->ambient[i] = 0.f; + material->diffuse[i] = 0.f; + material->specular[i] = 0.f; + material->transmittance[i] = 0.f; + material->emission[i] = 0.f; + } + material->illum = 0; + material->dissolve = 1.f; + material->shininess = 1.f; + material->ior = 1.f; +} + +/* Implementation of string to int hashtable */ + +#define HASH_TABLE_ERROR 1 +#define HASH_TABLE_SUCCESS 0 + +#define HASH_TABLE_DEFAULT_SIZE 10 + +typedef struct hash_table_entry_t +{ + unsigned long hash; + int filled; + int pad0; + long value; + + struct hash_table_entry_t* next; +} hash_table_entry_t; + +typedef struct +{ + unsigned long* hashes; + hash_table_entry_t* entries; + size_t capacity; + size_t n; +} hash_table_t; + +static unsigned long hash_djb2(const unsigned char* str) +{ + unsigned long hash = 5381; + int c; + + while ((c = *str++)) { + hash = ((hash << 5) + hash) + (unsigned long)(c); + } + + return hash; +} + +static void create_hash_table(size_t start_capacity, hash_table_t* hash_table) +{ + if (start_capacity < 1) + start_capacity = HASH_TABLE_DEFAULT_SIZE; + hash_table->hashes = (unsigned long*) TINYOBJ_MALLOC(start_capacity * sizeof(unsigned long)); + hash_table->entries = (hash_table_entry_t*) TINYOBJ_CALLOC(start_capacity, sizeof(hash_table_entry_t)); + hash_table->capacity = start_capacity; + hash_table->n = 0; +} + +static void destroy_hash_table(hash_table_t* hash_table) +{ + TINYOBJ_FREE(hash_table->entries); + TINYOBJ_FREE(hash_table->hashes); +} + +/* Insert with quadratic probing */ +static int hash_table_insert_value(unsigned long hash, long value, hash_table_t* hash_table) +{ + /* Insert value */ + size_t start_index = hash % hash_table->capacity; + size_t index = start_index; + hash_table_entry_t* start_entry = hash_table->entries + start_index; + size_t i; + hash_table_entry_t* entry; + + for (i = 1; hash_table->entries[index].filled; i++) + { + if (i >= hash_table->capacity) + return HASH_TABLE_ERROR; + index = (start_index + (i * i)) % hash_table->capacity; + } + + entry = hash_table->entries + index; + entry->hash = hash; + entry->filled = 1; + entry->value = value; + + if (index != start_index) { + /* This is a new entry, but not the start entry, hence we need to add a next pointer to our entry */ + entry->next = start_entry->next; + start_entry->next = entry; + } + + return HASH_TABLE_SUCCESS; +} + +static int hash_table_insert(unsigned long hash, long value, hash_table_t* hash_table) +{ + int ret = hash_table_insert_value(hash, value, hash_table); + if (ret == HASH_TABLE_SUCCESS) + { + hash_table->hashes[hash_table->n] = hash; + hash_table->n++; + } + return ret; +} + +static hash_table_entry_t* hash_table_find(unsigned long hash, hash_table_t* hash_table) +{ + hash_table_entry_t* entry = hash_table->entries + (hash % hash_table->capacity); + while (entry) + { + if (entry->hash == hash && entry->filled) + { + return entry; + } + entry = entry->next; + } + return NULL; +} + +static void hash_table_maybe_grow(size_t new_n, hash_table_t* hash_table) +{ + size_t new_capacity; + hash_table_t new_hash_table; + size_t i; + + if (new_n <= hash_table->capacity) { + return; + } + new_capacity = 2 * ((2 * hash_table->capacity) > new_n ? hash_table->capacity : new_n); + /* Create a new hash table. We're not calling create_hash_table because we want to realloc the hash array */ + new_hash_table.hashes = hash_table->hashes = (unsigned long*) TINYOBJ_REALLOC((void*) hash_table->hashes, sizeof(unsigned long) * new_capacity); + new_hash_table.entries = (hash_table_entry_t*) TINYOBJ_CALLOC(new_capacity, sizeof(hash_table_entry_t)); + new_hash_table.capacity = new_capacity; + new_hash_table.n = hash_table->n; + + /* Rehash */ + for (i = 0; i < hash_table->capacity; i++) + { + hash_table_entry_t* entry = hash_table_find(hash_table->hashes[i], hash_table); + hash_table_insert_value(hash_table->hashes[i], entry->value, &new_hash_table); + } + + TINYOBJ_FREE(hash_table->entries); + (*hash_table) = new_hash_table; +} + +static int hash_table_exists(const char* name, hash_table_t* hash_table) +{ + return hash_table_find(hash_djb2((const unsigned char*)name), hash_table) != NULL; +} + +static void hash_table_set(const char* name, size_t val, hash_table_t* hash_table) +{ + /* Hash name */ + unsigned long hash = hash_djb2((const unsigned char *)name); + + hash_table_entry_t* entry = hash_table_find(hash, hash_table); + if (entry) + { + entry->value = (long)val; + return; + } + + /* Expand if necessary + * Grow until the element has been added + */ + do + { + hash_table_maybe_grow(hash_table->n + 1, hash_table); + } + while (hash_table_insert(hash, (long)val, hash_table) != HASH_TABLE_SUCCESS); +} + +static long hash_table_get(const char* name, hash_table_t* hash_table) +{ + hash_table_entry_t* ret = hash_table_find(hash_djb2((const unsigned char*)(name)), hash_table); + return ret->value; +} + +static tinyobj_material_t *tinyobj_material_add(tinyobj_material_t *prev, + size_t num_materials, + tinyobj_material_t *new_mat) { + tinyobj_material_t *dst; + dst = (tinyobj_material_t *)TINYOBJ_REALLOC( + prev, sizeof(tinyobj_material_t) * (num_materials + 1)); + + dst[num_materials] = (*new_mat); /* Just copy pointer for char* members */ + return dst; +} + +static int tinyobj_parse_and_index_mtl_file(tinyobj_material_t **materials_out, + size_t *num_materials_out, + const char *filename, + hash_table_t* material_table) { + tinyobj_material_t material; + size_t buffer_size = 128; + char *linebuf; + FILE *fp; + size_t num_materials = 0; + tinyobj_material_t *materials = NULL; + int has_previous_material = 0; + const char *line_end = NULL; + + if (materials_out == NULL) { + return TINYOBJ_ERROR_INVALID_PARAMETER; + } + + if (num_materials_out == NULL) { + return TINYOBJ_ERROR_INVALID_PARAMETER; + } + + (*materials_out) = NULL; + (*num_materials_out) = 0; + + fp = fopen(filename, "r"); + if (!fp) { + fprintf(stderr, "TINYOBJ: Error reading file '%s': %s (%d)\n", filename, strerror(errno), errno); + return TINYOBJ_ERROR_FILE_OPERATION; + } + + /* Create a default material */ + initMaterial(&material); + + linebuf = (char*)TINYOBJ_MALLOC(buffer_size); + while (NULL != dynamic_fgets(&linebuf, &buffer_size, fp)) { + const char *token = linebuf; + + line_end = token + strlen(token); + + /* Skip leading space. */ + token += strspn(token, " \t"); + + assert(token); + if (token[0] == '\0') continue; /* empty line */ + + if (token[0] == '#') continue; /* comment line */ + + /* new mtl */ + if ((0 == strncmp(token, "newmtl", 6)) && IS_SPACE((token[6]))) { + char namebuf[4096]; + + /* flush previous material. */ + if (has_previous_material) { + materials = tinyobj_material_add(materials, num_materials, &material); + num_materials++; + } else { + has_previous_material = 1; + } + + /* initial temporary material */ + initMaterial(&material); + + /* set new mtl name */ + token += 7; +#ifdef _MSC_VER + sscanf_s(token, "%s", namebuf, (unsigned)_countof(namebuf)); +#else + sscanf(token, "%s", namebuf); +#endif + material.name = my_strdup(namebuf, (size_t) (line_end - token)); + + /* Add material to material table */ + if (material_table) + hash_table_set(material.name, num_materials, material_table); + + continue; + } + + /* ambient */ + if (token[0] == 'K' && token[1] == 'a' && IS_SPACE((token[2]))) { + float r, g, b; + token += 2; + parseFloat3(&r, &g, &b, &token); + material.ambient[0] = r; + material.ambient[1] = g; + material.ambient[2] = b; + continue; + } + + /* diffuse */ + if (token[0] == 'K' && token[1] == 'd' && IS_SPACE((token[2]))) { + float r, g, b; + token += 2; + parseFloat3(&r, &g, &b, &token); + material.diffuse[0] = r; + material.diffuse[1] = g; + material.diffuse[2] = b; + continue; + } + + /* specular */ + if (token[0] == 'K' && token[1] == 's' && IS_SPACE((token[2]))) { + float r, g, b; + token += 2; + parseFloat3(&r, &g, &b, &token); + material.specular[0] = r; + material.specular[1] = g; + material.specular[2] = b; + continue; + } + + /* transmittance */ + if (token[0] == 'K' && token[1] == 't' && IS_SPACE((token[2]))) { + float r, g, b; + token += 2; + parseFloat3(&r, &g, &b, &token); + material.transmittance[0] = r; + material.transmittance[1] = g; + material.transmittance[2] = b; + continue; + } + + /* ior(index of refraction) */ + if (token[0] == 'N' && token[1] == 'i' && IS_SPACE((token[2]))) { + token += 2; + material.ior = parseFloat(&token); + continue; + } + + /* emission */ + if (token[0] == 'K' && token[1] == 'e' && IS_SPACE(token[2])) { + float r, g, b; + token += 2; + parseFloat3(&r, &g, &b, &token); + material.emission[0] = r; + material.emission[1] = g; + material.emission[2] = b; + continue; + } + + /* shininess */ + if (token[0] == 'N' && token[1] == 's' && IS_SPACE(token[2])) { + token += 2; + material.shininess = parseFloat(&token); + continue; + } + + /* illum model */ + if (0 == strncmp(token, "illum", 5) && IS_SPACE(token[5])) { + token += 6; + material.illum = parseInt(&token); + continue; + } + + /* dissolve */ + if ((token[0] == 'd' && IS_SPACE(token[1]))) { + token += 1; + material.dissolve = parseFloat(&token); + continue; + } + if (token[0] == 'T' && token[1] == 'r' && IS_SPACE(token[2])) { + token += 2; + /* Invert value of Tr(assume Tr is in range [0, 1]) */ + material.dissolve = 1.0f - parseFloat(&token); + continue; + } + + /* ambient texture */ + if ((0 == strncmp(token, "map_Ka", 6)) && IS_SPACE(token[6])) { + token += 7; + material.ambient_texname = my_strdup(token, (size_t) (line_end - token)); + continue; + } + + /* diffuse texture */ + if ((0 == strncmp(token, "map_Kd", 6)) && IS_SPACE(token[6])) { + token += 7; + material.diffuse_texname = my_strdup(token, (size_t) (line_end - token)); + continue; + } + + /* specular texture */ + if ((0 == strncmp(token, "map_Ks", 6)) && IS_SPACE(token[6])) { + token += 7; + material.specular_texname = my_strdup(token, (size_t) (line_end - token)); + continue; + } + + /* specular highlight texture */ + if ((0 == strncmp(token, "map_Ns", 6)) && IS_SPACE(token[6])) { + token += 7; + material.specular_highlight_texname = my_strdup(token, (size_t) (line_end - token)); + continue; + } + + /* bump texture */ + if ((0 == strncmp(token, "map_bump", 8)) && IS_SPACE(token[8])) { + token += 9; + material.bump_texname = my_strdup(token, (size_t) (line_end - token)); + continue; + } + + /* alpha texture */ + if ((0 == strncmp(token, "map_d", 5)) && IS_SPACE(token[5])) { + token += 6; + material.alpha_texname = my_strdup(token, (size_t) (line_end - token)); + continue; + } + + /* bump texture */ + if ((0 == strncmp(token, "bump", 4)) && IS_SPACE(token[4])) { + token += 5; + material.bump_texname = my_strdup(token, (size_t) (line_end - token)); + continue; + } + + /* displacement texture */ + if ((0 == strncmp(token, "disp", 4)) && IS_SPACE(token[4])) { + token += 5; + material.displacement_texname = my_strdup(token, (size_t) (line_end - token)); + continue; + } + + /* @todo { unknown parameter } */ + } + + if (material.name) { + /* Flush last material element */ + materials = tinyobj_material_add(materials, num_materials, &material); + num_materials++; + } + + (*num_materials_out) = num_materials; + (*materials_out) = materials; + + if (linebuf) { + TINYOBJ_FREE(linebuf); + } + + return TINYOBJ_SUCCESS; +} + +int tinyobj_parse_mtl_file(tinyobj_material_t **materials_out, + size_t *num_materials_out, + const char *filename) { + return tinyobj_parse_and_index_mtl_file(materials_out, num_materials_out, filename, NULL); +} + + +typedef enum { + COMMAND_EMPTY, + COMMAND_V, + COMMAND_VN, + COMMAND_VT, + COMMAND_F, + COMMAND_G, + COMMAND_O, + COMMAND_USEMTL, + COMMAND_MTLLIB + +} CommandType; + +typedef struct { + float vx, vy, vz; + float nx, ny, nz; + float tx, ty; + + /* @todo { Use dynamic array } */ + tinyobj_vertex_index_t f[TINYOBJ_MAX_FACES_PER_F_LINE]; + size_t num_f; + + int f_num_verts[TINYOBJ_MAX_FACES_PER_F_LINE]; + size_t num_f_num_verts; + + const char *group_name; + unsigned int group_name_len; + int pad0; + + const char *object_name; + unsigned int object_name_len; + int pad1; + + const char *material_name; + unsigned int material_name_len; + int pad2; + + const char *mtllib_name; + unsigned int mtllib_name_len; + + CommandType type; +} Command; + +static int parseLine(Command *command, const char *p, size_t p_len, + int triangulate) { + char linebuf[4096]; + const char *token; + assert(p_len < 4095); + + memcpy(linebuf, p, p_len); + linebuf[p_len] = '\0'; + + token = linebuf; + + command->type = COMMAND_EMPTY; + + /* Skip leading space. */ + skip_space(&token); + + assert(token); + if (token[0] == '\0') { /* empty line */ + return 0; + } + + if (token[0] == '#') { /* comment line */ + return 0; + } + + /* vertex */ + if (token[0] == 'v' && IS_SPACE((token[1]))) { + float x, y, z; + token += 2; + parseFloat3(&x, &y, &z, &token); + command->vx = x; + command->vy = y; + command->vz = z; + command->type = COMMAND_V; + return 1; + } + + /* normal */ + if (token[0] == 'v' && token[1] == 'n' && IS_SPACE((token[2]))) { + float x, y, z; + token += 3; + parseFloat3(&x, &y, &z, &token); + command->nx = x; + command->ny = y; + command->nz = z; + command->type = COMMAND_VN; + return 1; + } + + /* texcoord */ + if (token[0] == 'v' && token[1] == 't' && IS_SPACE((token[2]))) { + float x, y; + token += 3; + parseFloat2(&x, &y, &token); + command->tx = x; + command->ty = y; + command->type = COMMAND_VT; + return 1; + } + + /* face */ + if (token[0] == 'f' && IS_SPACE((token[1]))) { + size_t num_f = 0; + + tinyobj_vertex_index_t f[TINYOBJ_MAX_FACES_PER_F_LINE]; + token += 2; + skip_space(&token); + + while (!IS_NEW_LINE(token[0])) { + tinyobj_vertex_index_t vi = parseRawTriple(&token); + skip_space_and_cr(&token); + + f[num_f] = vi; + num_f++; + } + + command->type = COMMAND_F; + + if (triangulate) { + size_t k; + size_t n = 0; + + tinyobj_vertex_index_t i0 = f[0]; + tinyobj_vertex_index_t i1; + tinyobj_vertex_index_t i2 = f[1]; + + assert(3 * num_f < TINYOBJ_MAX_FACES_PER_F_LINE); + + for (k = 2; k < num_f; k++) { + i1 = i2; + i2 = f[k]; + command->f[3 * n + 0] = i0; + command->f[3 * n + 1] = i1; + command->f[3 * n + 2] = i2; + + command->f_num_verts[n] = 3; + n++; + } + command->num_f = 3 * n; + command->num_f_num_verts = n; + + } else { + size_t k = 0; + assert(num_f < TINYOBJ_MAX_FACES_PER_F_LINE); + for (k = 0; k < num_f; k++) { + command->f[k] = f[k]; + } + + command->num_f = num_f; + command->f_num_verts[0] = (int)num_f; + command->num_f_num_verts = 1; + } + + return 1; + } + + /* use mtl */ + if ((0 == strncmp(token, "usemtl", 6)) && IS_SPACE((token[6]))) { + token += 7; + + skip_space(&token); + command->material_name = p + (token - linebuf); + command->material_name_len = (unsigned int)length_until_newline( + token, (p_len - (size_t)(token - linebuf)) + 1); + command->type = COMMAND_USEMTL; + + return 1; + } + + /* load mtl */ + if ((0 == strncmp(token, "mtllib", 6)) && IS_SPACE((token[6]))) { + /* By specification, `mtllib` should be appear only once in .obj */ + token += 7; + + skip_space(&token); + command->mtllib_name = p + (token - linebuf); + command->mtllib_name_len = (unsigned int)length_until_newline( + token, p_len - (size_t)(token - linebuf)) + + 1; + command->type = COMMAND_MTLLIB; + + return 1; + } + + /* group name */ + if (token[0] == 'g' && IS_SPACE((token[1]))) { + /* @todo { multiple group name. } */ + token += 2; + + command->group_name = p + (token - linebuf); + command->group_name_len = (unsigned int)length_until_newline( + token, p_len - (size_t)(token - linebuf)) + + 1; + command->type = COMMAND_G; + + return 1; + } + + /* object name */ + if (token[0] == 'o' && IS_SPACE((token[1]))) { + /* @todo { multiple object name? } */ + token += 2; + + command->object_name = p + (token - linebuf); + command->object_name_len = (unsigned int)length_until_newline( + token, p_len - (size_t)(token - linebuf)) + + 1; + command->type = COMMAND_O; + + return 1; + } + + return 0; +} + +typedef struct { + size_t pos; + size_t len; +} LineInfo; + +static int is_line_ending(const char *p, size_t i, size_t end_i) { + if (p[i] == '\0') return 1; + if (p[i] == '\n') return 1; /* this includes \r\n */ + if (p[i] == '\r') { + if (((i + 1) < end_i) && (p[i + 1] != '\n')) { /* detect only \r case */ + return 1; + } + } + return 0; +} + +int tinyobj_parse_obj(tinyobj_attrib_t *attrib, tinyobj_shape_t **shapes, + size_t *num_shapes, tinyobj_material_t **materials_out, + size_t *num_materials_out, const char *buf, size_t len, + unsigned int flags) { + LineInfo *line_infos = NULL; + Command *commands = NULL; + size_t num_lines = 0; + + size_t num_v = 0; + size_t num_vn = 0; + size_t num_vt = 0; + size_t num_f = 0; + size_t num_faces = 0; + + int mtllib_line_index = -1; + + tinyobj_material_t *materials = NULL; + size_t num_materials = 0; + + hash_table_t material_table; + + if (len < 1) return TINYOBJ_ERROR_INVALID_PARAMETER; + if (attrib == NULL) return TINYOBJ_ERROR_INVALID_PARAMETER; + if (shapes == NULL) return TINYOBJ_ERROR_INVALID_PARAMETER; + if (num_shapes == NULL) return TINYOBJ_ERROR_INVALID_PARAMETER; + if (buf == NULL) return TINYOBJ_ERROR_INVALID_PARAMETER; + if (materials_out == NULL) return TINYOBJ_ERROR_INVALID_PARAMETER; + if (num_materials_out == NULL) return TINYOBJ_ERROR_INVALID_PARAMETER; + + tinyobj_attrib_init(attrib); + /* 1. Find '\n' and create line data. */ + { + size_t i; + size_t end_idx = len; + size_t prev_pos = 0; + size_t line_no = 0; + size_t last_line_ending = 0; + + /* Count # of lines. */ + for (i = 0; i < end_idx; i++) { + if (is_line_ending(buf, i, end_idx)) { + num_lines++; + last_line_ending = i; + } + } + /* The last char from the input may not be a line + * ending character so add an extra line if there + * are more characters after the last line ending + * that was found. */ + if (end_idx - last_line_ending > 0) { + num_lines++; + } + + if (num_lines == 0) return TINYOBJ_ERROR_EMPTY; + + line_infos = (LineInfo *)TINYOBJ_MALLOC(sizeof(LineInfo) * num_lines); + + /* Fill line infos. */ + for (i = 0; i < end_idx; i++) { + if (is_line_ending(buf, i, end_idx)) { + line_infos[line_no].pos = prev_pos; + line_infos[line_no].len = i - prev_pos; + prev_pos = i + 1; + line_no++; + } + } + if (end_idx - last_line_ending > 0) { + line_infos[line_no].pos = prev_pos; + line_infos[line_no].len = end_idx - 1 - last_line_ending; + } + } + + commands = (Command *)TINYOBJ_MALLOC(sizeof(Command) * num_lines); + + create_hash_table(HASH_TABLE_DEFAULT_SIZE, &material_table); + + /* 2. parse each line */ + { + size_t i = 0; + for (i = 0; i < num_lines; i++) { + int ret = parseLine(&commands[i], &buf[line_infos[i].pos], + line_infos[i].len, flags & TINYOBJ_FLAG_TRIANGULATE); + if (ret) { + if (commands[i].type == COMMAND_V) { + num_v++; + } else if (commands[i].type == COMMAND_VN) { + num_vn++; + } else if (commands[i].type == COMMAND_VT) { + num_vt++; + } else if (commands[i].type == COMMAND_F) { + num_f += commands[i].num_f; + num_faces += commands[i].num_f_num_verts; + } + + if (commands[i].type == COMMAND_MTLLIB) { + mtllib_line_index = (int)i; + } + } + } + } + + /* line_infos are not used anymore. Release memory. */ + if (line_infos) { + TINYOBJ_FREE(line_infos); + } + + /* Load material(if exits) */ + if (mtllib_line_index >= 0 && commands[mtllib_line_index].mtllib_name && + commands[mtllib_line_index].mtllib_name_len > 0) { + char *filename = my_strndup(commands[mtllib_line_index].mtllib_name, + commands[mtllib_line_index].mtllib_name_len); + + int ret = tinyobj_parse_and_index_mtl_file(&materials, &num_materials, filename, &material_table); + + if (ret != TINYOBJ_SUCCESS) { + /* warning. */ + fprintf(stderr, "TINYOBJ: Failed to parse material file '%s': %d\n", filename, ret); + } + + TINYOBJ_FREE(filename); + + } + + /* Construct attributes */ + + { + size_t v_count = 0; + size_t n_count = 0; + size_t t_count = 0; + size_t f_count = 0; + size_t face_count = 0; + int material_id = -1; /* -1 = default unknown material. */ + size_t i = 0; + + attrib->vertices = (float *)TINYOBJ_MALLOC(sizeof(float) * num_v * 3); + attrib->num_vertices = (unsigned int)num_v; + attrib->normals = (float *)TINYOBJ_MALLOC(sizeof(float) * num_vn * 3); + attrib->num_normals = (unsigned int)num_vn; + attrib->texcoords = (float *)TINYOBJ_MALLOC(sizeof(float) * num_vt * 2); + attrib->num_texcoords = (unsigned int)num_vt; + attrib->faces = (tinyobj_vertex_index_t *)TINYOBJ_MALLOC( + sizeof(tinyobj_vertex_index_t) * num_f); + attrib->num_faces = (unsigned int)num_f; + attrib->face_num_verts = (int *)TINYOBJ_MALLOC(sizeof(int) * num_faces); + attrib->material_ids = (int *)TINYOBJ_MALLOC(sizeof(int) * num_faces); + attrib->num_face_num_verts = (unsigned int)num_faces; + + for (i = 0; i < num_lines; i++) { + if (commands[i].type == COMMAND_EMPTY) { + continue; + } else if (commands[i].type == COMMAND_USEMTL) { + /* @todo + if (commands[t][i].material_name && + commands[t][i].material_name_len > 0) { + std::string material_name(commands[t][i].material_name, + commands[t][i].material_name_len); + + if (material_map.find(material_name) != material_map.end()) { + material_id = material_map[material_name]; + } else { + // Assign invalid material ID + material_id = -1; + } + } + */ + if (commands[i].material_name && + commands[i].material_name_len >0) + { + /* Create a null terminated string */ + char* material_name_null_term = (char*) TINYOBJ_MALLOC(commands[i].material_name_len + 1); + memcpy((void*) material_name_null_term, (const void*) commands[i].material_name, commands[i].material_name_len); + material_name_null_term[commands[i].material_name_len - 1] = 0; + + if (hash_table_exists(material_name_null_term, &material_table)) + material_id = (int)hash_table_get(material_name_null_term, &material_table); + else + material_id = -1; + + TINYOBJ_FREE(material_name_null_term); + } + } else if (commands[i].type == COMMAND_V) { + attrib->vertices[3 * v_count + 0] = commands[i].vx; + attrib->vertices[3 * v_count + 1] = commands[i].vy; + attrib->vertices[3 * v_count + 2] = commands[i].vz; + v_count++; + } else if (commands[i].type == COMMAND_VN) { + attrib->normals[3 * n_count + 0] = commands[i].nx; + attrib->normals[3 * n_count + 1] = commands[i].ny; + attrib->normals[3 * n_count + 2] = commands[i].nz; + n_count++; + } else if (commands[i].type == COMMAND_VT) { + attrib->texcoords[2 * t_count + 0] = commands[i].tx; + attrib->texcoords[2 * t_count + 1] = commands[i].ty; + t_count++; + } else if (commands[i].type == COMMAND_F) { + size_t k = 0; + for (k = 0; k < commands[i].num_f; k++) { + tinyobj_vertex_index_t vi = commands[i].f[k]; + int v_idx = fixIndex(vi.v_idx, v_count); + int vn_idx = fixIndex(vi.vn_idx, n_count); + int vt_idx = fixIndex(vi.vt_idx, t_count); + attrib->faces[f_count + k].v_idx = v_idx; + attrib->faces[f_count + k].vn_idx = vn_idx; + attrib->faces[f_count + k].vt_idx = vt_idx; + } + + for (k = 0; k < commands[i].num_f_num_verts; k++) { + attrib->material_ids[face_count + k] = material_id; + attrib->face_num_verts[face_count + k] = commands[i].f_num_verts[k]; + } + + f_count += commands[i].num_f; + face_count += commands[i].num_f_num_verts; + } + } + } + + /* 5. Construct shape information. */ + { + unsigned int face_count = 0; + size_t i = 0; + size_t n = 0; + size_t shape_idx = 0; + + const char *shape_name = NULL; + unsigned int shape_name_len = 0; + const char *prev_shape_name = NULL; + unsigned int prev_shape_name_len = 0; + unsigned int prev_shape_face_offset = 0; + unsigned int prev_face_offset = 0; + tinyobj_shape_t prev_shape = {NULL, 0, 0}; + + /* Find the number of shapes in .obj */ + for (i = 0; i < num_lines; i++) { + if (commands[i].type == COMMAND_O || commands[i].type == COMMAND_G) { + n++; + } + } + + /* Allocate array of shapes with maximum possible size(+1 for unnamed + * group/object). + * Actual # of shapes found in .obj is determined in the later */ + (*shapes) = (tinyobj_shape_t*)TINYOBJ_MALLOC(sizeof(tinyobj_shape_t) * (n + 1)); + + for (i = 0; i < num_lines; i++) { + if (commands[i].type == COMMAND_O || commands[i].type == COMMAND_G) { + if (commands[i].type == COMMAND_O) { + shape_name = commands[i].object_name; + shape_name_len = commands[i].object_name_len; + } else { + shape_name = commands[i].group_name; + shape_name_len = commands[i].group_name_len; + } + + if (face_count == 0) { + /* 'o' or 'g' appears before any 'f' */ + prev_shape_name = shape_name; + prev_shape_name_len = shape_name_len; + prev_shape_face_offset = face_count; + prev_face_offset = face_count; + } else { + if (shape_idx == 0) { + /* 'o' or 'g' after some 'v' lines. */ + (*shapes)[shape_idx].name = my_strndup( + prev_shape_name, prev_shape_name_len); /* may be NULL */ + (*shapes)[shape_idx].face_offset = prev_shape.face_offset; + (*shapes)[shape_idx].length = face_count - prev_face_offset; + shape_idx++; + + prev_face_offset = face_count; + + } else { + if ((face_count - prev_face_offset) > 0) { + (*shapes)[shape_idx].name = + my_strndup(prev_shape_name, prev_shape_name_len); + (*shapes)[shape_idx].face_offset = prev_face_offset; + (*shapes)[shape_idx].length = face_count - prev_face_offset; + shape_idx++; + prev_face_offset = face_count; + } + } + + /* Record shape info for succeeding 'o' or 'g' command. */ + prev_shape_name = shape_name; + prev_shape_name_len = shape_name_len; + prev_shape_face_offset = face_count; + } + } + if (commands[i].type == COMMAND_F) { + face_count++; + } + } + + if ((face_count - prev_face_offset) > 0) { + size_t length = face_count - prev_shape_face_offset; + if (length > 0) { + (*shapes)[shape_idx].name = + my_strndup(prev_shape_name, prev_shape_name_len); + (*shapes)[shape_idx].face_offset = prev_face_offset; + (*shapes)[shape_idx].length = face_count - prev_face_offset; + shape_idx++; + } + } else { + /* Guess no 'v' line occurrence after 'o' or 'g', so discards current + * shape information. */ + } + + (*num_shapes) = shape_idx; + } + + if (commands) { + TINYOBJ_FREE(commands); + } + + destroy_hash_table(&material_table); + + (*materials_out) = materials; + (*num_materials_out) = num_materials; + + return TINYOBJ_SUCCESS; +} + +void tinyobj_attrib_init(tinyobj_attrib_t *attrib) { + attrib->vertices = NULL; + attrib->num_vertices = 0; + attrib->normals = NULL; + attrib->num_normals = 0; + attrib->texcoords = NULL; + attrib->num_texcoords = 0; + attrib->faces = NULL; + attrib->num_faces = 0; + attrib->face_num_verts = NULL; + attrib->num_face_num_verts = 0; + attrib->material_ids = NULL; +} + +void tinyobj_attrib_free(tinyobj_attrib_t *attrib) { + if (attrib->vertices) TINYOBJ_FREE(attrib->vertices); + if (attrib->normals) TINYOBJ_FREE(attrib->normals); + if (attrib->texcoords) TINYOBJ_FREE(attrib->texcoords); + if (attrib->faces) TINYOBJ_FREE(attrib->faces); + if (attrib->face_num_verts) TINYOBJ_FREE(attrib->face_num_verts); + if (attrib->material_ids) TINYOBJ_FREE(attrib->material_ids); +} + +void tinyobj_shapes_free(tinyobj_shape_t *shapes, size_t num_shapes) { + size_t i; + if (shapes == NULL) return; + + for (i = 0; i < num_shapes; i++) { + if (shapes[i].name) TINYOBJ_FREE(shapes[i].name); + } + + TINYOBJ_FREE(shapes); +} + +void tinyobj_materials_free(tinyobj_material_t *materials, + size_t num_materials) { + size_t i; + if (materials == NULL) return; + + for (i = 0; i < num_materials; i++) { + if (materials[i].name) TINYOBJ_FREE(materials[i].name); + if (materials[i].ambient_texname) TINYOBJ_FREE(materials[i].ambient_texname); + if (materials[i].diffuse_texname) TINYOBJ_FREE(materials[i].diffuse_texname); + if (materials[i].specular_texname) TINYOBJ_FREE(materials[i].specular_texname); + if (materials[i].specular_highlight_texname) + TINYOBJ_FREE(materials[i].specular_highlight_texname); + if (materials[i].bump_texname) TINYOBJ_FREE(materials[i].bump_texname); + if (materials[i].displacement_texname) + TINYOBJ_FREE(materials[i].displacement_texname); + if (materials[i].alpha_texname) TINYOBJ_FREE(materials[i].alpha_texname); + } + + TINYOBJ_FREE(materials); +} +#endif /* TINYOBJ_LOADER_C_IMPLEMENTATION */ + +#endif /* TINOBJ_LOADER_C_H_ */ diff --git a/src/models.c b/src/models.c index a5dbf5e7..c9d92315 100644 --- a/src/models.c +++ b/src/models.c @@ -52,6 +52,11 @@ #include "rlgl.h" // raylib OpenGL abstraction layer to OpenGL 1.1, 2.1, 3.3+ or ES2 +#if defined(SUPPORT_FILEFORMAT_OBJ) + #define TINYOBJ_LOADER_C_IMPLEMENTATION + #include "external/tinyobj_loader_c.h" // OBJ file format loading +#endif + #if defined(SUPPORT_FILEFORMAT_IQM) #define RIQM_IMPLEMENTATION #include "external/riqm.h" // IQM file format loading @@ -86,16 +91,16 @@ // Module specific Functions Declaration //---------------------------------------------------------------------------------- #if defined(SUPPORT_FILEFORMAT_OBJ) -static Mesh LoadOBJ(const char *fileName); // Load OBJ mesh data +static Model LoadOBJ(const char *fileName); // Load OBJ mesh data #endif #if defined(SUPPORT_FILEFORMAT_MTL) static Material LoadMTL(const char *fileName); // Load MTL material data #endif #if defined(SUPPORT_FILEFORMAT_GLTF) -static Mesh LoadIQM(const char *fileName); // Load IQM mesh data +static Model LoadIQM(const char *fileName); // Load IQM mesh data #endif #if defined(SUPPORT_FILEFORMAT_GLTF) -static Mesh LoadGLTF(const char *fileName); // Load GLTF mesh data +static Model LoadGLTF(const char *fileName); // Load GLTF mesh data #endif //---------------------------------------------------------------------------------- @@ -618,9 +623,18 @@ Model LoadModel(const char *fileName) { Model model = { 0 }; - model.mesh = LoadMesh(fileName); - model.transform = MatrixIdentity(); - model.material = LoadMaterialDefault(); +#if defined(SUPPORT_FILEFORMAT_OBJ) + if (IsFileExtension(fileName, ".obj")) model = LoadOBJ(fileName); +#endif +#if defined(SUPPORT_FILEFORMAT_GLTF) + if (IsFileExtension(fileName, ".gltf")) model = LoadGLTF(fileName); +#endif +#if defined(SUPPORT_FILEFORMAT_IQM) + if (IsFileExtension(fileName, ".iqm")) model = LoadIQM(fileName); +#endif + + if (model.meshCount == 0) TraceLog(LOG_WARNING, "[%s] No meshes can be loaded", fileName); + if (model.materialCount == 0) TraceLog(LOG_WARNING, "[%s] No materials can be loaded", fileName); return model; } @@ -633,9 +647,18 @@ Model LoadModelFromMesh(Mesh mesh) { Model model = { 0 }; - model.mesh = mesh; model.transform = MatrixIdentity(); - model.material = LoadMaterialDefault(); + + model.meshCount = 1; + model.meshes = (Mesh *)malloc(model.meshCount*sizeof(Mesh)); + model.meshes[0] = mesh; + + model.materialCount = 1; + model.materials = (Material *)malloc(model.materialCount*sizeof(Material)); + model.materials[0] = LoadMaterialDefault(); + + model.meshMaterial = (int *)malloc(model.meshCount*sizeof(int)); + model.meshMaterial[0] = 0; // First material index return model; } @@ -643,10 +666,11 @@ Model LoadModelFromMesh(Mesh mesh) // Unload model from memory (RAM and/or VRAM) void UnloadModel(Model model) { - UnloadMesh(&model.mesh); - UnloadMaterial(model.material); + for (int i = 0; i < model.meshCount; i++) UnloadMesh(&model.meshes[i]); + for (int i = 0; i < model.materialCount; i++) UnloadMaterial(model.materials[i]); + free(model.meshMaterial); - TraceLog(LOG_INFO, "Unloaded model data (mesh and material) from RAM and VRAM"); + TraceLog(LOG_INFO, "Unloaded model data from RAM and VRAM"); } // Load mesh from file @@ -655,12 +679,8 @@ Mesh LoadMesh(const char *fileName) { Mesh mesh = { 0 }; -#if defined(SUPPORT_FILEFORMAT_OBJ) - if (IsFileExtension(fileName, ".obj")) mesh = LoadOBJ(fileName); -#else - TraceLog(LOG_WARNING, "[%s] Mesh fileformat not supported, it can't be loaded", fileName); -#endif - + // TODO: Review this function, should still exist? + #if defined(SUPPORT_MESH_GENERATION) if (mesh.vertexCount == 0) { @@ -1855,9 +1875,12 @@ void DrawModelEx(Model model, Vector3 position, Vector3 rotationAxis, float rota //Matrix matModel = MatrixMultiply(model.transform, matTransform); // Transform to world-space coordinates model.transform = MatrixMultiply(model.transform, matTransform); - model.material.maps[MAP_DIFFUSE].color = tint; // TODO: Multiply tint color by diffuse color? - rlDrawMesh(model.mesh, model.material, model.transform); + for (int i = 0; i < model.meshCount; i++) + { + model.materials[model.meshMaterial[i]].maps[MAP_DIFFUSE].color = tint; + rlDrawMesh(model.meshes[i], model.materials[model.meshMaterial[i]], model.transform); + } } // Draw a model wires (with texture if set) @@ -2079,41 +2102,45 @@ RayHitInfo GetCollisionRayModel(Ray ray, Model *model) { RayHitInfo result = { 0 }; - // If mesh doesn't have vertex data on CPU, can't test it. - if (!model->mesh.vertices) return result; - - // model->mesh.triangleCount may not be set, vertexCount is more reliable - int triangleCount = model->mesh.vertexCount/3; - - // Test against all triangles in mesh - for (int i = 0; i < triangleCount; i++) + for (int i = 0; i < model->meshCount; i++) { - Vector3 a, b, c; - Vector3 *vertdata = (Vector3 *)model->mesh.vertices; - - if (model->mesh.indices) - { - a = vertdata[model->mesh.indices[i*3 + 0]]; - b = vertdata[model->mesh.indices[i*3 + 1]]; - c = vertdata[model->mesh.indices[i*3 + 2]]; - } - else + // Check if meshhas vertex data on CPU for testing + if (model->meshes[i].vertices != NULL) { - a = vertdata[i*3 + 0]; - b = vertdata[i*3 + 1]; - c = vertdata[i*3 + 2]; - } + // model->mesh.triangleCount may not be set, vertexCount is more reliable + int triangleCount = model->meshes[i].vertexCount/3; + + // Test against all triangles in mesh + for (int i = 0; i < triangleCount; i++) + { + Vector3 a, b, c; + Vector3 *vertdata = (Vector3 *)model->meshes[i].vertices; - a = Vector3Transform(a, model->transform); - b = Vector3Transform(b, model->transform); - c = Vector3Transform(c, model->transform); + if (model->meshes[i].indices) + { + a = vertdata[model->meshes[i].indices[i*3 + 0]]; + b = vertdata[model->meshes[i].indices[i*3 + 1]]; + c = vertdata[model->meshes[i].indices[i*3 + 2]]; + } + else + { + a = vertdata[i*3 + 0]; + b = vertdata[i*3 + 1]; + c = vertdata[i*3 + 2]; + } - RayHitInfo triHitInfo = GetCollisionRayTriangle(ray, a, b, c); + a = Vector3Transform(a, model->transform); + b = Vector3Transform(b, model->transform); + c = Vector3Transform(c, model->transform); - if (triHitInfo.hit) - { - // Save the closest hit triangle - if ((!result.hit) || (result.distance > triHitInfo.distance)) result = triHitInfo; + RayHitInfo triHitInfo = GetCollisionRayTriangle(ray, a, b, c); + + if (triHitInfo.hit) + { + // Save the closest hit triangle + if ((!result.hit) || (result.distance > triHitInfo.distance)) result = triHitInfo; + } + } } } @@ -2329,10 +2356,13 @@ void MeshBinormals(Mesh *mesh) #if defined(SUPPORT_FILEFORMAT_OBJ) // Load OBJ mesh data -static Mesh LoadOBJ(const char *fileName) +static Model LoadOBJ(const char *fileName) { - Mesh mesh = { 0 }; + Model model = { 0 }; + // TODO: Use tinyobj_loader_c library + +/* char dataType = 0; char comments[200]; @@ -2568,11 +2598,12 @@ static Mesh LoadOBJ(const char *fileName) free(midVertices); free(midNormals); free(midTexCoords); +*/ // NOTE: At this point we have all vertex, texcoord, normal data for the model in mesh struct TraceLog(LOG_INFO, "[%s] Model loaded successfully in RAM (CPU)", fileName); - return mesh; + return model; } #endif @@ -2743,21 +2774,21 @@ static Material LoadMTL(const char *fileName) #if defined(SUPPORT_FILEFORMAT_GLTF) // Load IQM mesh data -static Mesh LoadIQM(const char *fileName) +static Model LoadIQM(const char *fileName) { - Mesh mesh = { 0 }; + Model model = { 0 }; // TODO: Load IQM file - return mesh; + return model; } #endif #if defined(SUPPORT_FILEFORMAT_GLTF) // Load glTF mesh data -static Mesh LoadGLTF(const char *fileName) +static Model LoadGLTF(const char *fileName) { - Mesh mesh = { 0 }; + Model model = { 0 }; // glTF file loading FILE *gltfFile = fopen(fileName, "rb"); @@ -2765,7 +2796,7 @@ static Mesh LoadGLTF(const char *fileName) if (gltfFile == NULL) { TraceLog(LOG_WARNING, "[%s] glTF file could not be opened", fileName); - return mesh; + return model; } fseek(gltfFile, 0, SEEK_END); @@ -2790,15 +2821,15 @@ static Mesh LoadGLTF(const char *fileName) printf("Version: %d\n", data.version); printf("Meshes: %lu\n", data.meshes_count); - // TODO: Process glTF data and map to mesh + // TODO: Process glTF data and map to model - // NOTE: data.buffers[] and data.images[] should be loaded - // using buffers[n].uri and images[n].uri... or use cgltf_load_buffers(&options, data, fileName); + // NOTE: data.buffers[] should be loaded to model.meshes and data.images[] should be loaded to model.materials + // Use buffers[n].uri and images[n].uri... or use cgltf_load_buffers(&options, data, fileName); cgltf_free(&data); } else TraceLog(LOG_WARNING, "[%s] glTF data could not be loaded", fileName); - return mesh; + return model; } #endif diff --git a/src/raylib.h b/src/raylib.h index 5db50c04..1a344306 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -339,18 +339,15 @@ typedef struct Material { // Model type typedef struct Model { - Mesh mesh; // Vertex data buffers (RAM and VRAM) Matrix transform; // Local transform matrix - Material material; // Shader and textures data - /* - Mesh *meshes; // Vertex data buffers (RAM and VRAM) - int meshCount; - - Material *materials; // Shader and textures data - int materialCount; - - int *meshMaterial; // Material assigned to every mesh - */ + + int meshCount; // Number of meshes + Mesh *meshes; // Meshes array + + int materialCount; // Number of materials + Material *materials; // Materials array + + int *meshMaterial; // Mesh material number } Model; // Ray type (useful for raycast) @@ -1226,7 +1223,7 @@ RLAPI void DrawGizmo(Vector3 position); //------------------------------------------------------------------------------------ // Model loading/unloading functions -RLAPI Model LoadModel(const char *fileName); // Load model from files (mesh and material) +RLAPI Model LoadModel(const char *fileName); // Load model from files (meshes and materials) RLAPI Model LoadModelFromMesh(Mesh mesh); // Load model from generated mesh RLAPI void UnloadModel(Model model); // Unload model from memory (RAM and/or VRAM) -- cgit v1.2.3 From 8a73c5d0b403264ebd66cb5a2e1b21f91f6991b0 Mon Sep 17 00:00:00 2001 From: Ray Date: Fri, 29 Mar 2019 17:15:22 +0100 Subject: Replace custom OBJ/MTL implementations by tinyobj_loader -WIP- --- src/models.c | 495 +++++++++++------------------------------------------------ 1 file changed, 89 insertions(+), 406 deletions(-) (limited to 'src') diff --git a/src/models.c b/src/models.c index c9d92315..ec2713ed 100644 --- a/src/models.c +++ b/src/models.c @@ -52,9 +52,9 @@ #include "rlgl.h" // raylib OpenGL abstraction layer to OpenGL 1.1, 2.1, 3.3+ or ES2 -#if defined(SUPPORT_FILEFORMAT_OBJ) +#if defined(SUPPORT_FILEFORMAT_OBJ) || defined(SUPPORT_FILEFORMAT_MTL) #define TINYOBJ_LOADER_C_IMPLEMENTATION - #include "external/tinyobj_loader_c.h" // OBJ file format loading + #include "external/tinyobj_loader_c.h" // OBJ/MTL file formats loading #endif #if defined(SUPPORT_FILEFORMAT_IQM) @@ -93,9 +93,6 @@ #if defined(SUPPORT_FILEFORMAT_OBJ) static Model LoadOBJ(const char *fileName); // Load OBJ mesh data #endif -#if defined(SUPPORT_FILEFORMAT_MTL) -static Material LoadMTL(const char *fileName); // Load MTL material data -#endif #if defined(SUPPORT_FILEFORMAT_GLTF) static Model LoadIQM(const char *fileName); // Load IQM mesh data #endif @@ -1811,7 +1808,17 @@ Material LoadMaterial(const char *fileName) Material material = { 0 }; #if defined(SUPPORT_FILEFORMAT_MTL) - if (IsFileExtension(fileName, ".mtl")) material = LoadMTL(fileName); + if (IsFileExtension(fileName, ".mtl")) + { + tinyobj_material_t *materials; + int materialCount = 0; + + int result = tinyobj_parse_mtl_file(&materials, &materialCount, fileName); + + // TODO: Process materials to return + + tinyobj_materials_free(materials, materialCount); + } #else TraceLog(LOG_WARNING, "[%s] Material fileformat not supported, it can't be loaded", fileName); #endif @@ -2359,419 +2366,95 @@ void MeshBinormals(Mesh *mesh) static Model LoadOBJ(const char *fileName) { Model model = { 0 }; - - // TODO: Use tinyobj_loader_c library -/* - char dataType = 0; - char comments[200]; - - int vertexCount = 0; - int normalCount = 0; - int texcoordCount = 0; - int triangleCount = 0; - - FILE *objFile; - - objFile = fopen(fileName, "rt"); - - if (objFile == NULL) - { - TraceLog(LOG_WARNING, "[%s] OBJ file could not be opened", fileName); - return mesh; - } - - // First reading pass: Get vertexCount, normalCount, texcoordCount, triangleCount - // NOTE: vertex, texcoords and normals could be optimized (to be used indexed on faces definition) - // NOTE: faces MUST be defined as TRIANGLES (3 vertex per face) - while (!feof(objFile)) - { - dataType = 0; - fscanf(objFile, "%c", &dataType); - - switch (dataType) - { - case '#': // Comments - case 'o': // Object name (One OBJ file can contain multible named meshes) - case 'g': // Group name - case 's': // Smoothing level - case 'm': // mtllib [external .mtl file name] - case 'u': // usemtl [material name] - { - fgets(comments, 200, objFile); - } break; - case 'v': - { - fscanf(objFile, "%c", &dataType); - - if (dataType == 't') // Read texCoord - { - texcoordCount++; - fgets(comments, 200, objFile); - } - else if (dataType == 'n') // Read normals - { - normalCount++; - fgets(comments, 200, objFile); - } - else // Read vertex - { - vertexCount++; - fgets(comments, 200, objFile); - } - } break; - case 'f': - { - triangleCount++; - fgets(comments, 200, objFile); - } break; - default: break; - } - } - - TraceLog(LOG_DEBUG, "[%s] Model vertices: %i", fileName, vertexCount); - TraceLog(LOG_DEBUG, "[%s] Model texcoords: %i", fileName, texcoordCount); - TraceLog(LOG_DEBUG, "[%s] Model normals: %i", fileName, normalCount); - TraceLog(LOG_DEBUG, "[%s] Model triangles: %i", fileName, triangleCount); - - // Once we know the number of vertices to store, we create required arrays - Vector3 *midVertices = (Vector3 *)malloc(vertexCount*sizeof(Vector3)); - Vector3 *midNormals = NULL; - if (normalCount > 0) midNormals = (Vector3 *)malloc(normalCount*sizeof(Vector3)); - Vector2 *midTexCoords = NULL; - if (texcoordCount > 0) midTexCoords = (Vector2 *)malloc(texcoordCount*sizeof(Vector2)); - - int countVertex = 0; - int countNormals = 0; - int countTexCoords = 0; - - rewind(objFile); // Return to the beginning of the file, to read again - - // Second reading pass: Get vertex data to fill intermediate arrays - // NOTE: This second pass is required in case of multiple meshes defined in same OBJ - // TODO: Consider that different meshes can have different vertex data available (position, texcoords, normals) - while (!feof(objFile)) - { - fscanf(objFile, "%c", &dataType); - - switch (dataType) - { - case '#': case 'o': case 'g': case 's': case 'm': case 'u': case 'f': fgets(comments, 200, objFile); break; - case 'v': - { - fscanf(objFile, "%c", &dataType); - - if (dataType == 't') // Read texCoord - { - fscanf(objFile, "%f %f%*[^\n]s\n", &midTexCoords[countTexCoords].x, &midTexCoords[countTexCoords].y); - countTexCoords++; - - fscanf(objFile, "%c", &dataType); - } - else if (dataType == 'n') // Read normals - { - fscanf(objFile, "%f %f %f", &midNormals[countNormals].x, &midNormals[countNormals].y, &midNormals[countNormals].z); - countNormals++; - - fscanf(objFile, "%c", &dataType); - } - else // Read vertex - { - fscanf(objFile, "%f %f %f", &midVertices[countVertex].x, &midVertices[countVertex].y, &midVertices[countVertex].z); - countVertex++; - - fscanf(objFile, "%c", &dataType); - } - } break; - default: break; - } - } - - // At this point all vertex data (v, vt, vn) has been gathered on midVertices, midTexCoords, midNormals - // Now we can organize that data into our Mesh struct - - mesh.vertexCount = triangleCount*3; - - // Additional arrays to store vertex data as floats - mesh.vertices = (float *)malloc(mesh.vertexCount*3*sizeof(float)); - mesh.texcoords = (float *)malloc(mesh.vertexCount*2*sizeof(float)); - mesh.normals = (float *)malloc(mesh.vertexCount*3*sizeof(float)); - mesh.colors = NULL; - - int vCounter = 0; // Used to count vertices float by float - int tcCounter = 0; // Used to count texcoords float by float - int nCounter = 0; // Used to count normals float by float - - int vCount[3], vtCount[3], vnCount[3]; // Used to store triangle indices for v, vt, vn - - rewind(objFile); // Return to the beginning of the file, to read again - - if (normalCount == 0) TraceLog(LOG_INFO, "[%s] No normals data on OBJ, normals will be generated from faces data", fileName); + tinyobj_attrib_t attrib; + tinyobj_shape_t *meshes = NULL; + int meshCount = 0; + + tinyobj_material_t *materials = NULL; + int materialCount = 0; - // Third reading pass: Get faces (triangles) data and fill VertexArray - while (!feof(objFile)) + int dataLength = 0; + const char *data = get_file_data(&dataLength, fileName); + + if (data != NULL) { - fscanf(objFile, "%c", &dataType); - - switch (dataType) + unsigned int flags = TINYOBJ_FLAG_TRIANGULATE; + int ret = tinyobj_parse_obj(&attrib, &meshes, &meshCount, &materials, &materialCount, data, dataLength, flags); + + if (ret != TINYOBJ_SUCCESS) TraceLog(LOG_WARNING, "[%s] Model data could not be loaded", fileName); + else TraceLog(LOG_INFO, "[%s] Model data loaded successfully: %i meshes / %i materials", fileName, meshCount, materialCount); + + for (int i = 0; i < meshCount; i++) { - case '#': case 'o': case 'g': case 's': case 'm': case 'u': case 'v': fgets(comments, 200, objFile); break; - case 'f': - { - // NOTE: It could be that OBJ does not have normals or texcoords defined! - - if ((normalCount == 0) && (texcoordCount == 0)) fscanf(objFile, "%i %i %i", &vCount[0], &vCount[1], &vCount[2]); - else if (normalCount == 0) fscanf(objFile, "%i/%i %i/%i %i/%i", &vCount[0], &vtCount[0], &vCount[1], &vtCount[1], &vCount[2], &vtCount[2]); - else if (texcoordCount == 0) fscanf(objFile, "%i//%i %i//%i %i//%i", &vCount[0], &vnCount[0], &vCount[1], &vnCount[1], &vCount[2], &vnCount[2]); - else fscanf(objFile, "%i/%i/%i %i/%i/%i %i/%i/%i", &vCount[0], &vtCount[0], &vnCount[0], &vCount[1], &vtCount[1], &vnCount[1], &vCount[2], &vtCount[2], &vnCount[2]); - - mesh.vertices[vCounter] = midVertices[vCount[0]-1].x; - mesh.vertices[vCounter + 1] = midVertices[vCount[0]-1].y; - mesh.vertices[vCounter + 2] = midVertices[vCount[0]-1].z; - vCounter += 3; - mesh.vertices[vCounter] = midVertices[vCount[1]-1].x; - mesh.vertices[vCounter + 1] = midVertices[vCount[1]-1].y; - mesh.vertices[vCounter + 2] = midVertices[vCount[1]-1].z; - vCounter += 3; - mesh.vertices[vCounter] = midVertices[vCount[2]-1].x; - mesh.vertices[vCounter + 1] = midVertices[vCount[2]-1].y; - mesh.vertices[vCounter + 2] = midVertices[vCount[2]-1].z; - vCounter += 3; - - if (normalCount > 0) - { - mesh.normals[nCounter] = midNormals[vnCount[0]-1].x; - mesh.normals[nCounter + 1] = midNormals[vnCount[0]-1].y; - mesh.normals[nCounter + 2] = midNormals[vnCount[0]-1].z; - nCounter += 3; - mesh.normals[nCounter] = midNormals[vnCount[1]-1].x; - mesh.normals[nCounter + 1] = midNormals[vnCount[1]-1].y; - mesh.normals[nCounter + 2] = midNormals[vnCount[1]-1].z; - nCounter += 3; - mesh.normals[nCounter] = midNormals[vnCount[2]-1].x; - mesh.normals[nCounter + 1] = midNormals[vnCount[2]-1].y; - mesh.normals[nCounter + 2] = midNormals[vnCount[2]-1].z; - nCounter += 3; - } - else - { - // If normals not defined, they are calculated from the 3 vertices [N = (V2 - V1) x (V3 - V1)] - Vector3 norm = Vector3CrossProduct(Vector3Subtract(midVertices[vCount[1]-1], midVertices[vCount[0]-1]), Vector3Subtract(midVertices[vCount[2]-1], midVertices[vCount[0]-1])); - norm = Vector3Normalize(norm); - - mesh.normals[nCounter] = norm.x; - mesh.normals[nCounter + 1] = norm.y; - mesh.normals[nCounter + 2] = norm.z; - nCounter += 3; - mesh.normals[nCounter] = norm.x; - mesh.normals[nCounter + 1] = norm.y; - mesh.normals[nCounter + 2] = norm.z; - nCounter += 3; - mesh.normals[nCounter] = norm.x; - mesh.normals[nCounter + 1] = norm.y; - mesh.normals[nCounter + 2] = norm.z; - nCounter += 3; - } - - if (texcoordCount > 0) - { - // NOTE: If using negative texture coordinates with a texture filter of GL_CLAMP_TO_EDGE doesn't work! - // NOTE: Texture coordinates are Y flipped upside-down - mesh.texcoords[tcCounter] = midTexCoords[vtCount[0]-1].x; - mesh.texcoords[tcCounter + 1] = 1.0f - midTexCoords[vtCount[0]-1].y; - tcCounter += 2; - mesh.texcoords[tcCounter] = midTexCoords[vtCount[1]-1].x; - mesh.texcoords[tcCounter + 1] = 1.0f - midTexCoords[vtCount[1]-1].y; - tcCounter += 2; - mesh.texcoords[tcCounter] = midTexCoords[vtCount[2]-1].x; - mesh.texcoords[tcCounter + 1] = 1.0f - midTexCoords[vtCount[2]-1].y; - tcCounter += 2; - } - } break; - default: break; + printf("shape[%d] name = %s\n", i, meshes[i].name); } + + /* + // Data reference to process + typedef struct { + char *name; + + float ambient[3]; + float diffuse[3]; + float specular[3]; + float transmittance[3]; + float emission[3]; + float shininess; + float ior; // index of refraction + float dissolve; // 1 == opaque; 0 == fully transparent + // illumination model (see http://www.fileformat.info/format/material/) + int illum; + + int pad0; + + char *ambient_texname; // map_Ka + char *diffuse_texname; // map_Kd + char *specular_texname; // map_Ks + char *specular_highlight_texname; // map_Ns + char *bump_texname; // map_bump, bump + char *displacement_texname; // disp + char *alpha_texname; // map_d + } tinyobj_material_t; + + typedef struct { + char *name; // group name or object name + unsigned int face_offset; + unsigned int length; + } tinyobj_shape_t; + + typedef struct { int v_idx, vt_idx, vn_idx; } tinyobj_vertex_index_t; + + typedef struct { + unsigned int num_vertices; + unsigned int num_normals; + unsigned int num_texcoords; + unsigned int num_faces; + unsigned int num_face_num_verts; + + int pad0; + + float *vertices; + float *normals; + float *texcoords; + tinyobj_vertex_index_t *faces; + int *face_num_verts; + int *material_ids; + } tinyobj_attrib_t; + */ + + tinyobj_attrib_free(&attrib); + tinyobj_shapes_free(meshes, meshCount); + tinyobj_materials_free(materials, materialCount); } - fclose(objFile); - - // Now we can free temp mid* arrays - free(midVertices); - free(midNormals); - free(midTexCoords); -*/ - - // NOTE: At this point we have all vertex, texcoord, normal data for the model in mesh struct + // NOTE: At this point we have all model data loaded TraceLog(LOG_INFO, "[%s] Model loaded successfully in RAM (CPU)", fileName); return model; } #endif -#if defined(SUPPORT_FILEFORMAT_MTL) -// Load MTL material data (specs: http://paulbourke.net/dataformats/mtl/) -// NOTE: Texture map parameters are not supported -static Material LoadMTL(const char *fileName) -{ - #define MAX_BUFFER_SIZE 128 - - Material material = { 0 }; - - char buffer[MAX_BUFFER_SIZE]; - Vector3 color = { 1.0f, 1.0f, 1.0f }; - char mapFileName[128]; - int result = 0; - - FILE *mtlFile; - - mtlFile = fopen(fileName, "rt"); - - if (mtlFile == NULL) - { - TraceLog(LOG_WARNING, "[%s] MTL file could not be opened", fileName); - return material; - } - - while (!feof(mtlFile)) - { - fgets(buffer, MAX_BUFFER_SIZE, mtlFile); - - switch (buffer[0]) - { - case 'n': // newmtl string Material name. Begins a new material description. - { - // TODO: Support multiple materials in a single .mtl - sscanf(buffer, "newmtl %127s", mapFileName); - } - case 'i': // illum int Illumination model - { - // illum = 1 if specular disabled - // illum = 2 if specular enabled (lambertian model) - // ... - } - case 'K': // Ka, Kd, Ks, Ke - { - switch (buffer[1]) - { - case 'a': // Ka float float float Ambient color (RGB) - { - sscanf(buffer, "Ka %f %f %f", &color.x, &color.y, &color.z); - // TODO: Support ambient color - //material.colAmbient.r = (unsigned char)(color.x*255); - //material.colAmbient.g = (unsigned char)(color.y*255); - //material.colAmbient.b = (unsigned char)(color.z*255); - } break; - case 'd': // Kd float float float Diffuse color (RGB) - { - sscanf(buffer, "Kd %f %f %f", &color.x, &color.y, &color.z); - material.maps[MAP_DIFFUSE].color.r = (unsigned char)(color.x*255); - material.maps[MAP_DIFFUSE].color.g = (unsigned char)(color.y*255); - material.maps[MAP_DIFFUSE].color.b = (unsigned char)(color.z*255); - } break; - case 's': // Ks float float float Specular color (RGB) - { - sscanf(buffer, "Ks %f %f %f", &color.x, &color.y, &color.z); - material.maps[MAP_SPECULAR].color.r = (unsigned char)(color.x*255); - material.maps[MAP_SPECULAR].color.g = (unsigned char)(color.y*255); - material.maps[MAP_SPECULAR].color.b = (unsigned char)(color.z*255); - } break; - case 'e': // Ke float float float Emmisive color (RGB) - { - // TODO: Support Ke? - } break; - default: break; - } - } break; - case 'N': // Ns, Ni - { - if (buffer[1] == 's') // Ns int Shininess (specular exponent). Ranges from 0 to 1000. - { - int shininess = 0; - sscanf(buffer, "Ns %i", &shininess); - - //material.params[PARAM_GLOSSINES] = (float)shininess; - } - else if (buffer[1] == 'i') // Ni int Refraction index. - { - // Not supported... - } - } break; - case 'm': // map_Kd, map_Ks, map_Ka, map_Bump, map_d - { - switch (buffer[4]) - { - case 'K': // Color texture maps - { - if (buffer[5] == 'd') // map_Kd string Diffuse color texture map. - { - result = sscanf(buffer, "map_Kd %127s", mapFileName); - if (result != EOF) material.maps[MAP_DIFFUSE].texture = LoadTexture(mapFileName); - } - else if (buffer[5] == 's') // map_Ks string Specular color texture map. - { - result = sscanf(buffer, "map_Ks %127s", mapFileName); - if (result != EOF) material.maps[MAP_SPECULAR].texture = LoadTexture(mapFileName); - } - else if (buffer[5] == 'a') // map_Ka string Ambient color texture map. - { - // Not supported... - } - } break; - case 'B': // map_Bump string Bump texture map. - { - result = sscanf(buffer, "map_Bump %127s", mapFileName); - if (result != EOF) material.maps[MAP_NORMAL].texture = LoadTexture(mapFileName); - } break; - case 'b': // map_bump string Bump texture map. - { - result = sscanf(buffer, "map_bump %127s", mapFileName); - if (result != EOF) material.maps[MAP_NORMAL].texture = LoadTexture(mapFileName); - } break; - case 'd': // map_d string Opacity texture map. - { - // Not supported... - } break; - default: break; - } - } break; - case 'd': // d, disp - { - if (buffer[1] == ' ') // d float Dissolve factor. d is inverse of Tr - { - float alpha = 1.0f; - sscanf(buffer, "d %f", &alpha); - material.maps[MAP_DIFFUSE].color.a = (unsigned char)(alpha*255); - } - else if (buffer[1] == 'i') // disp string Displacement map - { - // Not supported... - } - } break; - case 'b': // bump string Bump texture map - { - result = sscanf(buffer, "bump %127s", mapFileName); - if (result != EOF) material.maps[MAP_NORMAL].texture = LoadTexture(mapFileName); - } break; - case 'T': // Tr float Transparency Tr (alpha). Tr is inverse of d - { - float ialpha = 0.0f; - sscanf(buffer, "Tr %f", &ialpha); - material.maps[MAP_DIFFUSE].color.a = (unsigned char)((1.0f - ialpha)*255); - - } break; - case 'r': // refl string Reflection texture map - default: break; - } - } - - fclose(mtlFile); - - // NOTE: At this point we have all material data - TraceLog(LOG_INFO, "[%s] Material loaded successfully", fileName); - - return material; -} -#endif - #if defined(SUPPORT_FILEFORMAT_GLTF) // Load IQM mesh data static Model LoadIQM(const char *fileName) -- cgit v1.2.3 From 19debd2b4e44cee494c882cb8d338dc1847ae5b5 Mon Sep 17 00:00:00 2001 From: Ray Date: Fri, 29 Mar 2019 17:28:10 +0100 Subject: Review some warnings --- src/models.c | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/models.c b/src/models.c index ec2713ed..6f3fa73f 100644 --- a/src/models.c +++ b/src/models.c @@ -1811,7 +1811,7 @@ Material LoadMaterial(const char *fileName) if (IsFileExtension(fileName, ".mtl")) { tinyobj_material_t *materials; - int materialCount = 0; + unsigned int materialCount = 0; int result = tinyobj_parse_mtl_file(&materials, &materialCount, fileName); @@ -2369,14 +2369,29 @@ static Model LoadOBJ(const char *fileName) tinyobj_attrib_t attrib; tinyobj_shape_t *meshes = NULL; - int meshCount = 0; + unsigned int meshCount = 0; tinyobj_material_t *materials = NULL; - int materialCount = 0; + unsigned int materialCount = 0; int dataLength = 0; - const char *data = get_file_data(&dataLength, fileName); + char *data = NULL; + // Load model data + FILE *objFile = fopen(fileName, "rb"); + + if (objFile != NULL) + { + fseek(objFile, 0, SEEK_END); + long dataLength = ftell(objFile); // Get file size + fseek(objFile, 0, SEEK_SET); // Reset file pointer + + data = (char *)malloc(dataLength); + + fread(data, dataLength, 1, objFile); + fclose(objFile); + } + if (data != NULL) { unsigned int flags = TINYOBJ_FLAG_TRIANGULATE; -- cgit v1.2.3 From 6f371dab0807ccc81038b3eccfb9c6090ec07d16 Mon Sep 17 00:00:00 2001 From: Ray Date: Fri, 29 Mar 2019 19:43:27 +0100 Subject: Some formatting review --- src/shapes.c | 42 +++++++++++++++++++++++------------------- 1 file changed, 23 insertions(+), 19 deletions(-) (limited to 'src') diff --git a/src/shapes.c b/src/shapes.c index 7e8c0f4b..8c1eb1f0 100644 --- a/src/shapes.c +++ b/src/shapes.c @@ -185,8 +185,8 @@ void DrawCircle(int centerX, int centerY, float radius, Color color) // Draw a piece of a circle void DrawCircleSector(Vector2 center, float radius, int startAngle, int endAngle, int segments, Color color) { - if(radius == 0) return; // Check this or we'll get a div by zero error otherwise - + if (radius <= 0.0f) radius = 0.1f; // Avoid div by zero + // Function expects (endAngle > startAngle) if (endAngle < startAngle) { @@ -277,7 +277,7 @@ void DrawCircleSector(Vector2 center, float radius, int startAngle, int endAngle void DrawCircleSectorLines(Vector2 center, float radius, int startAngle, int endAngle, int segments, Color color) { - if(radius == 0) return; // Check this or we'll get a div by zero error otherwise + if (radius <= 0.0f) radius = 0.1f; // Avoid div by zero issue // Function expects (endAngle > startAngle) if (endAngle < startAngle) @@ -308,12 +308,12 @@ void DrawCircleSectorLines(Vector2 center, float radius, int startAngle, int end // Hide the cap lines when the circle is full bool showCapLines = true; int limit = 2*(segments + 2); - if((endAngle - startAngle) % 360 == 0) { limit = 2*segments; showCapLines = false; } + if ((endAngle - startAngle)%360 == 0) { limit = 2*segments; showCapLines = false; } if (rlCheckBufferLimit(limit)) rlglDraw(); rlBegin(RL_LINES); - if(showCapLines) + if (showCapLines) { rlColor4ub(color.r, color.g, color.b, color.a); rlVertex2f(center.x, center.y); @@ -330,7 +330,7 @@ void DrawCircleSectorLines(Vector2 center, float radius, int startAngle, int end angle += stepLength; } - if(showCapLines) + if (showCapLines) { rlColor4ub(color.r, color.g, color.b, color.a); rlVertex2f(center.x, center.y); @@ -384,15 +384,16 @@ void DrawCircleLines(int centerX, int centerY, float radius, Color color) void DrawRing(Vector2 center, float innerRadius, float outerRadius, int startAngle, int endAngle, int segments, Color color) { - if(startAngle == endAngle) return; + if (startAngle == endAngle) return; // Function expects (outerRadius > innerRadius) - if(outerRadius < innerRadius) + if (outerRadius < innerRadius) { float tmp = outerRadius; outerRadius = innerRadius; innerRadius = tmp; - if(outerRadius == 0) return; // Check this or we'll get a div by zero error otherwise + + if (outerRadius <= 0.0f) outerRadius = 0.1f; } // Function expects (endAngle > startAngle) @@ -408,8 +409,9 @@ void DrawRing(Vector2 center, float innerRadius, float outerRadius, int startAng { // Calculate how many segments we need to draw a smooth circle, taken from https://stackoverflow.com/a/2244088 #ifndef CIRCLE_ERROR_RATE - #define CIRCLE_ERROR_RATE 0.5f + #define CIRCLE_ERROR_RATE 0.5f #endif + // Calculate the maximum angle between segments based on the error rate. float th = acosf(2*powf(1 - CIRCLE_ERROR_RATE/outerRadius, 2) - 1); segments = (endAngle - startAngle)*ceilf(2*PI/th)/360; @@ -418,7 +420,7 @@ void DrawRing(Vector2 center, float innerRadius, float outerRadius, int startAng } // Not a ring - if(innerRadius == 0) + if (innerRadius <= 0.0f) { DrawCircleSector(center, outerRadius, startAngle, endAngle, segments, color); return; @@ -478,15 +480,16 @@ void DrawRing(Vector2 center, float innerRadius, float outerRadius, int startAng void DrawRingLines(Vector2 center, float innerRadius, float outerRadius, int startAngle, int endAngle, int segments, Color color) { - if(startAngle == endAngle) return; + if (startAngle == endAngle) return; // Function expects (outerRadius > innerRadius) - if(outerRadius < innerRadius) + if (outerRadius < innerRadius) { float tmp = outerRadius; outerRadius = innerRadius; innerRadius = tmp; - if(outerRadius == 0) return; // Check this or we'll get a div by zero error otherwise + + if (outerRadius <= 0.0f) outerRadius = 0.1f; } // Function expects (endAngle > startAngle) @@ -502,8 +505,9 @@ void DrawRingLines(Vector2 center, float innerRadius, float outerRadius, int sta { // Calculate how many segments we need to draw a smooth circle, taken from https://stackoverflow.com/a/2244088 #ifndef CIRCLE_ERROR_RATE - #define CIRCLE_ERROR_RATE 0.5f + #define CIRCLE_ERROR_RATE 0.5f #endif + // Calculate the maximum angle between segments based on the error rate. float th = acosf(2*powf(1 - CIRCLE_ERROR_RATE/outerRadius, 2) - 1); segments = (endAngle - startAngle)*ceilf(2*PI/th)/360; @@ -511,7 +515,7 @@ void DrawRingLines(Vector2 center, float innerRadius, float outerRadius, int sta if (segments <= 0) segments = 4; } - if(innerRadius == 0) + if (innerRadius <= 0.0f) { DrawCircleSectorLines(center, outerRadius, startAngle, endAngle, segments, color); return; @@ -522,12 +526,12 @@ void DrawRingLines(Vector2 center, float innerRadius, float outerRadius, int sta bool showCapLines = true; int limit = 4*(segments + 1); - if((endAngle - startAngle) % 360 == 0) { limit = 4*segments; showCapLines = false; } + if ((endAngle - startAngle)%360 == 0) { limit = 4*segments; showCapLines = false; } if (rlCheckBufferLimit(limit)) rlglDraw(); rlBegin(RL_LINES); - if(showCapLines) + if (showCapLines) { rlColor4ub(color.r, color.g, color.b, color.a); rlVertex2f(center.x + sinf(DEG2RAD*angle)*outerRadius, center.y + cosf(DEG2RAD*angle)*outerRadius); @@ -547,7 +551,7 @@ void DrawRingLines(Vector2 center, float innerRadius, float outerRadius, int sta angle += stepLength; } - if(showCapLines) + if (showCapLines) { rlColor4ub(color.r, color.g, color.b, color.a); rlVertex2f(center.x + sinf(DEG2RAD*angle)*outerRadius, center.y + cosf(DEG2RAD*angle)*outerRadius); -- cgit v1.2.3 From a197f40bb4bd5a644ad54bef756d7f435977df9d Mon Sep 17 00:00:00 2001 From: Ray Date: Fri, 29 Mar 2019 20:22:30 +0100 Subject: Default to white cube mesh if not loaded --- src/models.c | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/models.c b/src/models.c index 6f3fa73f..2893fd2f 100644 --- a/src/models.c +++ b/src/models.c @@ -630,8 +630,25 @@ Model LoadModel(const char *fileName) if (IsFileExtension(fileName, ".iqm")) model = LoadIQM(fileName); #endif - if (model.meshCount == 0) TraceLog(LOG_WARNING, "[%s] No meshes can be loaded", fileName); - if (model.materialCount == 0) TraceLog(LOG_WARNING, "[%s] No materials can be loaded", fileName); + if (model.meshCount == 0) + { + TraceLog(LOG_WARNING, "[%s] No meshes can be loaded, default to cube mesh", fileName); + + model.meshCount = 1; + model.meshes = (Mesh *)malloc(model.meshCount*sizeof(Mesh)); + model.meshes[0] = GenMeshCube(1.0f, 1.0f, 1.0f); + } + + if (model.materialCount == 0) + { + TraceLog(LOG_WARNING, "[%s] No materials can be loaded, default to white material", fileName); + + model.materialCount = 1; + model.materials = (Material *)malloc(model.materialCount*sizeof(Material)); + model.materials[0] = LoadMaterialDefault(); + + model.meshMaterial = (int *)calloc(model.meshCount, sizeof(int)); + } return model; } -- cgit v1.2.3 From a28023b58f172559228a07da29d8cac417d2e6bd Mon Sep 17 00:00:00 2001 From: Demizdor Date: Sat, 30 Mar 2019 22:18:29 +0200 Subject: Added DrawRoundedRect() --- src/raylib.h | 1 + src/shapes.c | 194 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 195 insertions(+) (limited to 'src') diff --git a/src/raylib.h b/src/raylib.h index 085f36f6..0a8351c0 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -1056,6 +1056,7 @@ RLAPI void DrawRectangleGradientH(int posX, int posY, int width, int height, Col RLAPI void DrawRectangleGradientEx(Rectangle rec, Color col1, Color col2, Color col3, Color col4); // Draw a gradient-filled rectangle with custom vertex colors RLAPI void DrawRectangleLines(int posX, int posY, int width, int height, Color color); // Draw rectangle outline RLAPI void DrawRectangleLinesEx(Rectangle rec, int lineThick, Color color); // Draw rectangle outline with extended parameters +RLAPI void DrawRoundedRect(Rectangle rec, float roundness, int segments, Color color); // Draw rectangle with rounded edges RLAPI void DrawTriangle(Vector2 v1, Vector2 v2, Vector2 v3, Color color); // Draw a color-filled triangle RLAPI void DrawTriangleLines(Vector2 v1, Vector2 v2, Vector2 v3, Color color); // Draw triangle outline RLAPI void DrawPoly(Vector2 center, int sides, float radius, float rotation, Color color); // Draw a regular polygon (Vector version) diff --git a/src/shapes.c b/src/shapes.c index 8c1eb1f0..9eb690d3 100644 --- a/src/shapes.c +++ b/src/shapes.c @@ -698,6 +698,200 @@ void DrawRectangleLinesEx(Rectangle rec, int lineThick, Color color) DrawRectangle( (int)rec.x, (int)(rec.y + lineThick), lineThick, (int)(rec.height - lineThick*2), color); } +// Draw rectangle with rounded edges. +void DrawRoundedRect(Rectangle rec, float roundness, int segments, Color color) +{ + // Not a rounded rectangle + // NOTE: Make sure we have at least 1px space left to render the rectangles near the corners + if(roundness <= 0.0f || rec.width <= 1 || rec.height <= 1 ) + { + DrawRectangleRec(rec, color); + return; + } + + if(roundness >= 1.0f) roundness = 1.0f; + + // Calculate corner radius + // NOTE: Make sure we have at least 1px space left to render the rectangles near the corners + float radius = rec.width > rec.height ? ((rec.height-1)*roundness)/2 : ((rec.width-1)*roundness)/2; + if(radius <= 0.0f) return; + + // Calculate number of segments to use for the corners + if (segments < 4) + { + // Calculate how many segments we need to draw a smooth circle, taken from https://stackoverflow.com/a/2244088 + #ifndef CIRCLE_ERROR_RATE + #define CIRCLE_ERROR_RATE 0.5f + #endif + // Calculate the maximum angle between segments based on the error rate. + float th = acosf(2*powf(1 - CIRCLE_ERROR_RATE/radius, 2) - 1); + segments = ceilf(2*PI/th)/4; + if (segments <= 0) segments = 4; + } + + float stepLength = 90.0f/(float)segments; + + /* Quick sketch to make sense of all of this (there are 9 parts to draw, also mark the 12 points we'll use below) + * Not my best attempt at ASCII art, just preted it's a rounded rectangle :) + * P0 P1 + * ____________________ + * /| |\ + * /1| 2 |3\ + *P7 /__|____________________|__\ P2 + * | |P8 P9| | + * | 8 | 9 | 4 | + * | __|____________________|__ | + *P6 \ |P11 P10| / P3 + * \7| 6 |5/ + * \|____________________|/ + * P5 P4 + */ + + const Vector2 point[12] = { // coordinates of the 12 points that define the rounded rect (the idea here is to make things easier) + {(float)rec.x + radius, rec.y}, {(float)(rec.x + rec.width) - radius, rec.y}, { rec.x + rec.width, (float)rec.y + radius }, // PO, P1, P2 + {rec.x + rec.width, (float)(rec.y + rec.height) - radius}, {(float)(rec.x + rec.width) - radius, rec.y + rec.height}, // P3, P4 + {(float)rec.x + radius, rec.y + rec.height}, { rec.x, (float)(rec.y + rec.height) - radius}, {rec.x, (float)rec.y + radius}, // P5, P6, P7 + {(float)rec.x + radius, (float)rec.y + radius}, {(float)(rec.x + rec.width) - radius, (float)rec.y + radius}, // P8, P9 + {(float)(rec.x + rec.width) - radius, (float)(rec.y + rec.height) - radius}, {(float)rec.x + radius, (float)(rec.y + rec.height) - radius} // P10, P11 + }; + +#if defined(SUPPORT_QUADS_DRAW_MODE) + if (rlCheckBufferLimit(16*segments/2 + 5*4)) rlglDraw(); + + rlBegin(RL_QUADS); + // Draw all of the 4 corners: [1] Upper Left Corner, [3] Upper Right Corner, [5] Lower Right Corner, [7] Lower Left Corner + const Vector2 centers[4] = { point[8], point[9], point[10], point[11] }; + const float angles[4] = {180.0f, 90.0f, 0.0f, 270.0f }; + for(int k = 0; k < 4; ++k) // Hope the compiler is smart enough to unroll this loop + { + float angle = angles[k]; + const Vector2 center = centers[k]; + // NOTE: Every QUAD actually represents two segments + for (int i = 0; i < segments/2; i++) + { + rlColor4ub(color.r, color.g, color.b, color.a); + rlVertex2f(center.x, center.y); + rlVertex2f(center.x + sinf(DEG2RAD*angle)*radius, center.y + cosf(DEG2RAD*angle)*radius); + rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength))*radius, center.y + cosf(DEG2RAD*(angle + stepLength))*radius); + rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength*2))*radius, center.y + cosf(DEG2RAD*(angle + stepLength*2))*radius); + angle += (stepLength*2); + } + // NOTE: In case number of segments is odd, we add one last piece to the cake + if (segments%2) + { + rlColor4ub(color.r, color.g, color.b, color.a); + rlVertex2f(center.x, center.y); + rlVertex2f(center.x + sinf(DEG2RAD*angle)*radius, center.y + cosf(DEG2RAD*angle)*radius); + rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength))*radius, center.y + cosf(DEG2RAD*(angle + stepLength))*radius); + rlVertex2f(center.x, center.y); + } + } + + // [2] Upper Rectangle + rlColor4ub(color.r, color.g, color.b, color.a); + rlVertex2f(point[0].x, point[0].y); + rlVertex2f(point[8].x, point[8].y); + rlVertex2f(point[9].x, point[9].y); + rlVertex2f(point[1].x, point[1].y); + + // [4] Right Rectangle + rlColor4ub(color.r, color.g, color.b, color.a); + rlVertex2f(point[2].x, point[2].y); + rlVertex2f(point[9].x, point[9].y); + rlVertex2f(point[10].x, point[10].y); + rlVertex2f(point[3].x, point[3].y); + + // [6] Bottom Rectangle + rlColor4ub(color.r, color.g, color.b, color.a); + rlVertex2f(point[11].x, point[11].y); + rlVertex2f(point[5].x, point[5].y); + rlVertex2f(point[4].x, point[4].y); + rlVertex2f(point[10].x, point[10].y); + + // [8] Left Rectangle + rlColor4ub(color.r, color.g, color.b, color.a); + rlVertex2f(point[7].x, point[7].y); + rlVertex2f(point[6].x, point[6].y); + rlVertex2f(point[11].x, point[11].y); + rlVertex2f(point[8].x, point[8].y); + + // [9] Middle Rectangle + rlColor4ub(color.r, color.g, color.b, color.a); + rlVertex2f(point[8].x, point[8].y); + rlVertex2f(point[11].x, point[11].y); + rlVertex2f(point[10].x, point[10].y); + rlVertex2f(point[9].x, point[9].y); + + rlEnd(); +#else + if (rlCheckBufferLimit(12*segments + 5*6)) rlglDraw(); // 4 corners with 3 vertices per segment + 5 rectangles with 6 vertices each + + rlBegin(RL_TRIANGLES); + // Draw all of the 4 corners: [1] Upper Left Corner, [3] Upper Right Corner, [5] Lower Right Corner, [7] Lower Left Corner + const Vector2 centers[4] = { point[8], point[9], point[10], point[11] }; + const float angles[4] = {180.0f, 90.0f, 0.0f, 270.0f }; + for(int k = 0; k < 4; ++k) // Hope the compiler is smart enough to unroll this loop + { + float angle = angles[k]; + const Vector2 center = centers[k]; + for (int i = 0; i < segments; i++) + { + rlColor4ub(color.r, color.g, color.b, color.a); + rlVertex2f(center.x, center.y); + rlVertex2f(center.x + sinf(DEG2RAD*angle)*radius, center.y + cosf(DEG2RAD*angle)*radius); + rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength))*radius, center.y + cosf(DEG2RAD*(angle + stepLength))*radius); + angle += stepLength; + } + } + + // [2] Upper Rectangle + rlColor4ub(color.r, color.g, color.b, color.a); + rlVertex2f(point[0].x, point[0].y); + rlVertex2f(point[8].x, point[8].y); + rlVertex2f(point[9].x, point[9].y); + rlVertex2f(point[1].x, point[1].y); + rlVertex2f(point[0].x, point[0].y); + rlVertex2f(point[9].x, point[9].y); + + // [4] Right Rectangle + rlColor4ub(color.r, color.g, color.b, color.a); + rlVertex2f(point[9].x, point[9].y); + rlVertex2f(point[10].x, point[10].y); + rlVertex2f(point[3].x, point[3].y); + rlVertex2f(point[2].x, point[2].y); + rlVertex2f(point[9].x, point[9].y); + rlVertex2f(point[3].x, point[3].y); + + // [6] Bottom Rectangle + rlColor4ub(color.r, color.g, color.b, color.a); + rlVertex2f(point[11].x, point[11].y); + rlVertex2f(point[5].x, point[5].y); + rlVertex2f(point[4].x, point[4].y); + rlVertex2f(point[10].x, point[10].y); + rlVertex2f(point[11].x, point[11].y); + rlVertex2f(point[4].x, point[4].y); + + // [8] Left Rectangle + rlColor4ub(color.r, color.g, color.b, color.a); + rlVertex2f(point[7].x, point[7].y); + rlVertex2f(point[6].x, point[6].y); + rlVertex2f(point[11].x, point[11].y); + rlVertex2f(point[8].x, point[8].y); + rlVertex2f(point[7].x, point[7].y); + rlVertex2f(point[11].x, point[11].y); + + // [9] Middle Rectangle + rlColor4ub(color.r, color.g, color.b, color.a); + rlVertex2f(point[8].x, point[8].y); + rlVertex2f(point[11].x, point[11].y); + rlVertex2f(point[10].x, point[10].y); + rlVertex2f(point[9].x, point[9].y); + rlVertex2f(point[8].x, point[8].y); + rlVertex2f(point[10].x, point[10].y); + rlEnd(); +#endif +} + // Draw a triangle void DrawTriangle(Vector2 v1, Vector2 v2, Vector2 v3, Color color) { -- cgit v1.2.3 From 1415d514ba9fc2b21ce99ceb2f21e7d6dc492219 Mon Sep 17 00:00:00 2001 From: Vlad Adrian Date: Sun, 31 Mar 2019 13:20:45 +0300 Subject: Update raylib.h --- src/raylib.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/raylib.h b/src/raylib.h index 0a8351c0..1ad719bd 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -1056,7 +1056,8 @@ RLAPI void DrawRectangleGradientH(int posX, int posY, int width, int height, Col RLAPI void DrawRectangleGradientEx(Rectangle rec, Color col1, Color col2, Color col3, Color col4); // Draw a gradient-filled rectangle with custom vertex colors RLAPI void DrawRectangleLines(int posX, int posY, int width, int height, Color color); // Draw rectangle outline RLAPI void DrawRectangleLinesEx(Rectangle rec, int lineThick, Color color); // Draw rectangle outline with extended parameters -RLAPI void DrawRoundedRect(Rectangle rec, float roundness, int segments, Color color); // Draw rectangle with rounded edges +RLAPI void DrawRoundedRect(Rectangle rec, float roundness, int segments, Color color); // Draw rectangle with rounded edges +RLAPI void DrawRoundedRectLines(Rectangle rec, float roundness, int segments, int lineThick, Color color); // Draw rounded rectangle outline RLAPI void DrawTriangle(Vector2 v1, Vector2 v2, Vector2 v3, Color color); // Draw a color-filled triangle RLAPI void DrawTriangleLines(Vector2 v1, Vector2 v2, Vector2 v3, Color color); // Draw triangle outline RLAPI void DrawPoly(Vector2 center, int sides, float radius, float rotation, Color color); // Draw a regular polygon (Vector version) -- cgit v1.2.3 From ecbd17910d7769ec9628576b7e49afac6c56722b Mon Sep 17 00:00:00 2001 From: Vlad Adrian Date: Sun, 31 Mar 2019 13:22:50 +0300 Subject: Added `DrawRoundedRectLines()` --- src/shapes.c | 207 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 207 insertions(+) (limited to 'src') diff --git a/src/shapes.c b/src/shapes.c index 9eb690d3..f25ed76f 100644 --- a/src/shapes.c +++ b/src/shapes.c @@ -892,6 +892,213 @@ void DrawRoundedRect(Rectangle rec, float roundness, int segments, Color color) #endif } +// Draw rounded rectangle outline +void DrawRoundedRectLines(Rectangle rec, float roundness, int segments, int lineThick, Color color) +{ + // Not a rounded rectangle + // NOTE: Make sure we have at least 1px space left to render the rectangles near the corners + if(roundness <= 0.0f || rec.width <= 1 || rec.height <= 1 ) + { + DrawRectangleLinesEx(rec, lineThick, color); + return; + } + + if(roundness >= 1.0f) roundness = 1.0f; + + // Calculate corner radius + // NOTE: Make sure we have at least 1px space left to render the rectangles near the corners + float radius = rec.width > rec.height ? ((rec.height-1)*roundness)/2 : ((rec.width-1)*roundness)/2; + if(radius <= 0.0f) return; + if(lineThick > radius-1) lineThick = radius - 1; + + // Calculate number of segments to use for the corners + if (segments < 4) + { + // Calculate how many segments we need to draw a smooth circle, taken from https://stackoverflow.com/a/2244088 + #ifndef CIRCLE_ERROR_RATE + #define CIRCLE_ERROR_RATE 0.5f + #endif + // Calculate the maximum angle between segments based on the error rate. + float th = acosf(2*powf(1 - CIRCLE_ERROR_RATE/radius, 2) - 1); + segments = ceilf(2*PI/th)/4; + if (segments <= 0) segments = 4; + } + + float stepLength = 90.0f/(float)segments; + const float outerRadius = radius, innerRadius = radius - (float)lineThick; + + /* Quick sketch to make sense of all of this (mark the 16 + 4(corner centers P16-19) points we'll use below) + * Not my best attempt at ASCII art, just preted it's rounded rectangle :) + * P0 P1 + * ==================== + * // P8 P9 \\ + * // \\ + *P7 // P15 P10 \\ P2 + * || *P16 P17* || + * || || + * || P14 P11 || + *P6 \\ *P19 P18* // P3 + * \\ // + * \\ P13 P12 // + * ==================== + * P5 P4 + */ + const Vector2 point[16] = { + {(float)rec.x + outerRadius, rec.y}, {(float)(rec.x + rec.width) - outerRadius, rec.y}, { rec.x + rec.width, (float)rec.y + outerRadius }, // PO, P1, P2 + {rec.x + rec.width, (float)(rec.y + rec.height) - outerRadius}, {(float)(rec.x + rec.width) - outerRadius, rec.y + rec.height}, // P3, P4 + {(float)rec.x + outerRadius, rec.y + rec.height}, { rec.x, (float)(rec.y + rec.height) - outerRadius}, {rec.x, (float)rec.y + outerRadius}, // P5, P6, P7 + {(float)rec.x + outerRadius, rec.y + lineThick}, {(float)(rec.x + rec.width) - outerRadius, rec.y + lineThick}, // P8, P9 + { rec.x + rec.width - lineThick, (float)rec.y + outerRadius }, {rec.x + rec.width - lineThick, (float)(rec.y + rec.height) - outerRadius}, // P10, P11 + {(float)(rec.x + rec.width) - outerRadius, rec.y + rec.height - lineThick}, {(float)rec.x + outerRadius, rec.y + rec.height - lineThick}, // P12, P13 + { rec.x + lineThick, (float)(rec.y + rec.height) - outerRadius}, {rec.x + lineThick, (float)rec.y + outerRadius} // P14, P15 + }; + const Vector2 centers[4] = { + {(float)rec.x + outerRadius, (float)rec.y + outerRadius}, {(float)(rec.x + rec.width) - outerRadius, (float)rec.y + outerRadius}, // P16, P17 + {(float)(rec.x + rec.width) - outerRadius, (float)(rec.y + rec.height) - outerRadius}, {(float)rec.x + outerRadius, (float)(rec.y + rec.height) - outerRadius} // P18, P19 + }; + const float angles[4] = {180.0f, 90.0f, 0.0f, 270.0f }; + + if(lineThick > 1) + { +#if defined(SUPPORT_QUADS_DRAW_MODE) + if (rlCheckBufferLimit(4*4*segments + 4*4)) rlglDraw(); // 4 corners with 4 vertices for each segment + 4 rectangles with 4 vertices each + rlBegin(RL_QUADS); + // Draw all of the 4 corners first: Upper Left Corner, Upper Right Corner, Lower Right Corner, Lower Left Corner + for(int k = 0; k < 4; ++k) // Hope the compiler is smart enough to unroll this loop + { + float angle = angles[k]; + const Vector2 center = centers[k]; + for (int i = 0; i < segments; i++) + { + rlColor4ub(color.r, color.g, color.b, color.a); + rlVertex2f(center.x + sinf(DEG2RAD*angle)*innerRadius, center.y + cosf(DEG2RAD*angle)*innerRadius); + rlVertex2f(center.x + sinf(DEG2RAD*angle)*outerRadius, center.y + cosf(DEG2RAD*angle)*outerRadius); + rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength))*outerRadius, center.y + cosf(DEG2RAD*(angle + stepLength))*outerRadius); + rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength))*innerRadius, center.y + cosf(DEG2RAD*(angle + stepLength))*innerRadius); + + angle += stepLength; + } + } + // Upper rectangle + rlColor4ub(color.r, color.g, color.b, color.a); + rlVertex2f(point[0].x, point[0].y); + rlVertex2f(point[8].x, point[8].y); + rlVertex2f(point[9].x, point[9].y); + rlVertex2f(point[1].x, point[1].y); + + // Right rectangle + rlColor4ub(color.r, color.g, color.b, color.a); + rlVertex2f(point[2].x, point[2].y); + rlVertex2f(point[10].x, point[10].y); + rlVertex2f(point[11].x, point[11].y); + rlVertex2f(point[3].x, point[3].y); + + // Lower rectangle + rlColor4ub(color.r, color.g, color.b, color.a); + rlVertex2f(point[13].x, point[13].y); + rlVertex2f(point[5].x, point[5].y); + rlVertex2f(point[4].x, point[4].y); + rlVertex2f(point[12].x, point[12].y); + + // Left rectangle + rlColor4ub(color.r, color.g, color.b, color.a); + rlVertex2f(point[15].x, point[15].y); + rlVertex2f(point[7].x, point[7].y); + rlVertex2f(point[6].x, point[6].y); + rlVertex2f(point[14].x, point[14].y); + + rlEnd(); +#else + if (rlCheckBufferLimit(4*6*segments + 4*6)) rlglDraw(); // 4 corners with 6(2*3) vertices for each segment + 4 rectangles with 6 vertices each + rlBegin(RL_TRIANGLES); + // Draw all of the 4 corners first: Upper Left Corner, Upper Right Corner, Lower Right Corner, Lower Left Corner + for(int k = 0; k < 4; ++k) // Hope the compiler is smart enough to unroll this loop + { + float angle = angles[k]; + const Vector2 center = centers[k]; + for (int i = 0; i < segments; i++) + { + rlColor4ub(color.r, color.g, color.b, color.a); + + rlVertex2f(center.x + sinf(DEG2RAD*angle)*innerRadius, center.y + cosf(DEG2RAD*angle)*innerRadius); + rlVertex2f(center.x + sinf(DEG2RAD*angle)*outerRadius, center.y + cosf(DEG2RAD*angle)*outerRadius); + rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength))*innerRadius, center.y + cosf(DEG2RAD*(angle + stepLength))*innerRadius); + + rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength))*innerRadius, center.y + cosf(DEG2RAD*(angle + stepLength))*innerRadius); + rlVertex2f(center.x + sinf(DEG2RAD*angle)*outerRadius, center.y + cosf(DEG2RAD*angle)*outerRadius); + rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength))*outerRadius, center.y + cosf(DEG2RAD*(angle + stepLength))*outerRadius); + + angle += stepLength; + } + } + + // Upper rectangle + rlColor4ub(color.r, color.g, color.b, color.a); + rlVertex2f(point[0].x, point[0].y); + rlVertex2f(point[8].x, point[8].y); + rlVertex2f(point[9].x, point[9].y); + rlVertex2f(point[1].x, point[1].y); + rlVertex2f(point[0].x, point[0].y); + rlVertex2f(point[9].x, point[9].y); + + // Right rectangle + rlColor4ub(color.r, color.g, color.b, color.a); + rlVertex2f(point[10].x, point[10].y); + rlVertex2f(point[11].x, point[11].y); + rlVertex2f(point[3].x, point[3].y); + rlVertex2f(point[2].x, point[2].y); + rlVertex2f(point[10].x, point[10].y); + rlVertex2f(point[3].x, point[3].y); + + // Lower rectangle + rlColor4ub(color.r, color.g, color.b, color.a); + rlVertex2f(point[13].x, point[13].y); + rlVertex2f(point[5].x, point[5].y); + rlVertex2f(point[4].x, point[4].y); + rlVertex2f(point[12].x, point[12].y); + rlVertex2f(point[13].x, point[13].y); + rlVertex2f(point[4].x, point[4].y); + + // Left rectangle + rlColor4ub(color.r, color.g, color.b, color.a); + rlVertex2f(point[7].x, point[7].y); + rlVertex2f(point[6].x, point[6].y); + rlVertex2f(point[14].x, point[14].y); + rlVertex2f(point[15].x, point[15].y); + rlVertex2f(point[7].x, point[7].y); + rlVertex2f(point[14].x, point[14].y); + rlEnd(); +#endif + } + else + { + // Use LINES to draw the outline + if (rlCheckBufferLimit(8*segments + 4*2)) rlglDraw(); // 4 corners with 2 vertices for each segment + 4 rectangles with 2 vertices each + rlBegin(RL_LINES); + // Draw all of the 4 corners first: Upper Left Corner, Upper Right Corner, Lower Right Corner, Lower Left Corner + for(int k = 0; k < 4; ++k) // Hope the compiler is smart enough to unroll this loop + { + float angle = angles[k]; + const Vector2 center = centers[k]; + for (int i = 0; i < segments; i++) + { + rlColor4ub(color.r, color.g, color.b, color.a); + rlVertex2f(center.x + sinf(DEG2RAD*angle)*outerRadius, center.y + cosf(DEG2RAD*angle)*outerRadius); + rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength))*outerRadius, center.y + cosf(DEG2RAD*(angle + stepLength))*outerRadius); + angle += stepLength; + } + } + // And now the remaining 4 lines + for(int i=0; i<8; i+=2) + { + rlColor4ub(color.r, color.g, color.b, color.a); + rlVertex2f(point[i].x, point[i].y); + rlVertex2f(point[i+1].x, point[i+1].y); + } + rlEnd(); + } +} + // Draw a triangle void DrawTriangle(Vector2 v1, Vector2 v2, Vector2 v3, Color color) { -- cgit v1.2.3 From eda982e2612fb08bef951692e9e80cb3a36d9731 Mon Sep 17 00:00:00 2001 From: Demizdor Date: Sun, 31 Mar 2019 16:15:40 +0300 Subject: Reimplemented DrawRoundedRectLines() --- src/shapes.c | 46 ++++++++++++++++++++-------------------------- 1 file changed, 20 insertions(+), 26 deletions(-) (limited to 'src') diff --git a/src/shapes.c b/src/shapes.c index f25ed76f..879d2a10 100644 --- a/src/shapes.c +++ b/src/shapes.c @@ -702,8 +702,7 @@ void DrawRectangleLinesEx(Rectangle rec, int lineThick, Color color) void DrawRoundedRect(Rectangle rec, float roundness, int segments, Color color) { // Not a rounded rectangle - // NOTE: Make sure we have at least 1px space left to render the rectangles near the corners - if(roundness <= 0.0f || rec.width <= 1 || rec.height <= 1 ) + if(roundness <= 0.0f || rec.width < 1 || rec.height < 1 ) { DrawRectangleRec(rec, color); return; @@ -712,8 +711,7 @@ void DrawRoundedRect(Rectangle rec, float roundness, int segments, Color color) if(roundness >= 1.0f) roundness = 1.0f; // Calculate corner radius - // NOTE: Make sure we have at least 1px space left to render the rectangles near the corners - float radius = rec.width > rec.height ? ((rec.height-1)*roundness)/2 : ((rec.width-1)*roundness)/2; + float radius = rec.width > rec.height ? (rec.height*roundness)/2 : (rec.width*roundness)/2; if(radius <= 0.0f) return; // Calculate number of segments to use for the corners @@ -732,7 +730,7 @@ void DrawRoundedRect(Rectangle rec, float roundness, int segments, Color color) float stepLength = 90.0f/(float)segments; /* Quick sketch to make sense of all of this (there are 9 parts to draw, also mark the 12 points we'll use below) - * Not my best attempt at ASCII art, just preted it's a rounded rectangle :) + * Not my best attempt at ASCII art, just preted it's rounded rectangle :) * P0 P1 * ____________________ * /| |\ @@ -754,14 +752,14 @@ void DrawRoundedRect(Rectangle rec, float roundness, int segments, Color color) {(float)rec.x + radius, (float)rec.y + radius}, {(float)(rec.x + rec.width) - radius, (float)rec.y + radius}, // P8, P9 {(float)(rec.x + rec.width) - radius, (float)(rec.y + rec.height) - radius}, {(float)rec.x + radius, (float)(rec.y + rec.height) - radius} // P10, P11 }; + const Vector2 centers[4] = { point[8], point[9], point[10], point[11] }; + const float angles[4] = {180.0f, 90.0f, 0.0f, 270.0f }; #if defined(SUPPORT_QUADS_DRAW_MODE) if (rlCheckBufferLimit(16*segments/2 + 5*4)) rlglDraw(); rlBegin(RL_QUADS); // Draw all of the 4 corners: [1] Upper Left Corner, [3] Upper Right Corner, [5] Lower Right Corner, [7] Lower Left Corner - const Vector2 centers[4] = { point[8], point[9], point[10], point[11] }; - const float angles[4] = {180.0f, 90.0f, 0.0f, 270.0f }; for(int k = 0; k < 4; ++k) // Hope the compiler is smart enough to unroll this loop { float angle = angles[k]; @@ -828,8 +826,6 @@ void DrawRoundedRect(Rectangle rec, float roundness, int segments, Color color) rlBegin(RL_TRIANGLES); // Draw all of the 4 corners: [1] Upper Left Corner, [3] Upper Right Corner, [5] Lower Right Corner, [7] Lower Left Corner - const Vector2 centers[4] = { point[8], point[9], point[10], point[11] }; - const float angles[4] = {180.0f, 90.0f, 0.0f, 270.0f }; for(int k = 0; k < 4; ++k) // Hope the compiler is smart enough to unroll this loop { float angle = angles[k]; @@ -895,21 +891,19 @@ void DrawRoundedRect(Rectangle rec, float roundness, int segments, Color color) // Draw rounded rectangle outline void DrawRoundedRectLines(Rectangle rec, float roundness, int segments, int lineThick, Color color) { + if(lineThick < 0) lineThick = 0; // Not a rounded rectangle - // NOTE: Make sure we have at least 1px space left to render the rectangles near the corners - if(roundness <= 0.0f || rec.width <= 1 || rec.height <= 1 ) + if(roundness <= 0.0f ) { - DrawRectangleLinesEx(rec, lineThick, color); + DrawRectangleLinesEx((Rectangle){rec.x-lineThick, rec.y-lineThick, rec.width+2*lineThick, rec.height+2*lineThick}, lineThick, color); return; } if(roundness >= 1.0f) roundness = 1.0f; // Calculate corner radius - // NOTE: Make sure we have at least 1px space left to render the rectangles near the corners - float radius = rec.width > rec.height ? ((rec.height-1)*roundness)/2 : ((rec.width-1)*roundness)/2; + float radius = rec.width > rec.height ? (rec.height*roundness)/2 : (rec.width*roundness)/2; if(radius <= 0.0f) return; - if(lineThick > radius-1) lineThick = radius - 1; // Calculate number of segments to use for the corners if (segments < 4) @@ -920,12 +914,12 @@ void DrawRoundedRectLines(Rectangle rec, float roundness, int segments, int line #endif // Calculate the maximum angle between segments based on the error rate. float th = acosf(2*powf(1 - CIRCLE_ERROR_RATE/radius, 2) - 1); - segments = ceilf(2*PI/th)/4; + segments = ceilf(2*PI/th)/2; if (segments <= 0) segments = 4; } float stepLength = 90.0f/(float)segments; - const float outerRadius = radius, innerRadius = radius - (float)lineThick; + const float outerRadius = radius + (float)lineThick, innerRadius = radius; /* Quick sketch to make sense of all of this (mark the 16 + 4(corner centers P16-19) points we'll use below) * Not my best attempt at ASCII art, just preted it's rounded rectangle :) @@ -944,17 +938,17 @@ void DrawRoundedRectLines(Rectangle rec, float roundness, int segments, int line * P5 P4 */ const Vector2 point[16] = { - {(float)rec.x + outerRadius, rec.y}, {(float)(rec.x + rec.width) - outerRadius, rec.y}, { rec.x + rec.width, (float)rec.y + outerRadius }, // PO, P1, P2 - {rec.x + rec.width, (float)(rec.y + rec.height) - outerRadius}, {(float)(rec.x + rec.width) - outerRadius, rec.y + rec.height}, // P3, P4 - {(float)rec.x + outerRadius, rec.y + rec.height}, { rec.x, (float)(rec.y + rec.height) - outerRadius}, {rec.x, (float)rec.y + outerRadius}, // P5, P6, P7 - {(float)rec.x + outerRadius, rec.y + lineThick}, {(float)(rec.x + rec.width) - outerRadius, rec.y + lineThick}, // P8, P9 - { rec.x + rec.width - lineThick, (float)rec.y + outerRadius }, {rec.x + rec.width - lineThick, (float)(rec.y + rec.height) - outerRadius}, // P10, P11 - {(float)(rec.x + rec.width) - outerRadius, rec.y + rec.height - lineThick}, {(float)rec.x + outerRadius, rec.y + rec.height - lineThick}, // P12, P13 - { rec.x + lineThick, (float)(rec.y + rec.height) - outerRadius}, {rec.x + lineThick, (float)rec.y + outerRadius} // P14, P15 + {(float)rec.x + innerRadius, rec.y - lineThick}, {(float)(rec.x + rec.width) - innerRadius, rec.y - lineThick}, { rec.x + rec.width + lineThick, (float)rec.y + innerRadius }, // PO, P1, P2 + {rec.x + rec.width + lineThick, (float)(rec.y + rec.height) - innerRadius}, {(float)(rec.x + rec.width) - innerRadius, rec.y + rec.height + lineThick}, // P3, P4 + {(float)rec.x + innerRadius, rec.y + rec.height + lineThick}, { rec.x - lineThick, (float)(rec.y + rec.height) - innerRadius}, {rec.x - lineThick, (float)rec.y + innerRadius}, // P5, P6, P7 + {(float)rec.x + innerRadius, rec.y}, {(float)(rec.x + rec.width) - innerRadius, rec.y}, // P8, P9 + { rec.x + rec.width, (float)rec.y + innerRadius }, {rec.x + rec.width, (float)(rec.y + rec.height) - innerRadius}, // P10, P11 + {(float)(rec.x + rec.width) - innerRadius, rec.y + rec.height}, {(float)rec.x + innerRadius, rec.y + rec.height}, // P12, P13 + { rec.x, (float)(rec.y + rec.height) - innerRadius}, {rec.x, (float)rec.y + innerRadius} // P14, P15 }; const Vector2 centers[4] = { - {(float)rec.x + outerRadius, (float)rec.y + outerRadius}, {(float)(rec.x + rec.width) - outerRadius, (float)rec.y + outerRadius}, // P16, P17 - {(float)(rec.x + rec.width) - outerRadius, (float)(rec.y + rec.height) - outerRadius}, {(float)rec.x + outerRadius, (float)(rec.y + rec.height) - outerRadius} // P18, P19 + {(float)rec.x + innerRadius, (float)rec.y + innerRadius}, {(float)(rec.x + rec.width) - innerRadius, (float)rec.y + innerRadius}, // P16, P17 + {(float)(rec.x + rec.width) - innerRadius, (float)(rec.y + rec.height) - innerRadius}, {(float)rec.x + innerRadius, (float)(rec.y + rec.height) - innerRadius} // P18, P19 }; const float angles[4] = {180.0f, 90.0f, 0.0f, 270.0f }; -- cgit v1.2.3 From 3e806ad9d4bc2131b2d8bf9c68e5e30a2b9b8e64 Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 1 Apr 2019 00:15:45 +0200 Subject: Reviewed data assignation --- src/external/tinyobj_loader_c.h | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/external/tinyobj_loader_c.h b/src/external/tinyobj_loader_c.h index e9d015ff..ae975829 100644 --- a/src/external/tinyobj_loader_c.h +++ b/src/external/tinyobj_loader_c.h @@ -1342,12 +1342,13 @@ int tinyobj_parse_obj(tinyobj_attrib_t *attrib, tinyobj_shape_t **shapes, attrib->num_normals = (unsigned int)num_vn; attrib->texcoords = (float *)TINYOBJ_MALLOC(sizeof(float) * num_vt * 2); attrib->num_texcoords = (unsigned int)num_vt; - attrib->faces = (tinyobj_vertex_index_t *)TINYOBJ_MALLOC( - sizeof(tinyobj_vertex_index_t) * num_f); - attrib->num_faces = (unsigned int)num_f; + attrib->faces = (tinyobj_vertex_index_t *)TINYOBJ_MALLOC(sizeof(tinyobj_vertex_index_t) * num_f); attrib->face_num_verts = (int *)TINYOBJ_MALLOC(sizeof(int) * num_faces); + + attrib->num_faces = (unsigned int)num_faces; + attrib->num_face_num_verts = (unsigned int)num_f; + attrib->material_ids = (int *)TINYOBJ_MALLOC(sizeof(int) * num_faces); - attrib->num_face_num_verts = (unsigned int)num_faces; for (i = 0; i < num_lines; i++) { if (commands[i].type == COMMAND_EMPTY) { -- cgit v1.2.3 From fe702cd6a2d1aeb23c47c3db412311e2b04c9b7c Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 1 Apr 2019 00:16:56 +0200 Subject: Implementing LoadOBJ() -WIP- It seems obj loading is working ok but there is some problem with drawing... --- src/models.c | 173 +++++++++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 140 insertions(+), 33 deletions(-) (limited to 'src') diff --git a/src/models.c b/src/models.c index 2893fd2f..68f5f6be 100644 --- a/src/models.c +++ b/src/models.c @@ -2400,55 +2400,113 @@ static Model LoadOBJ(const char *fileName) if (objFile != NULL) { fseek(objFile, 0, SEEK_END); - long dataLength = ftell(objFile); // Get file size - fseek(objFile, 0, SEEK_SET); // Reset file pointer + long length = ftell(objFile); // Get file size + fseek(objFile, 0, SEEK_SET); // Reset file pointer - data = (char *)malloc(dataLength); + data = (char *)malloc(length); - fread(data, dataLength, 1, objFile); + fread(data, length, 1, objFile); + dataLength = length; fclose(objFile); } - if (data != NULL) + if (data != NULL) { unsigned int flags = TINYOBJ_FLAG_TRIANGULATE; int ret = tinyobj_parse_obj(&attrib, &meshes, &meshCount, &materials, &materialCount, data, dataLength, flags); if (ret != TINYOBJ_SUCCESS) TraceLog(LOG_WARNING, "[%s] Model data could not be loaded", fileName); else TraceLog(LOG_INFO, "[%s] Model data loaded successfully: %i meshes / %i materials", fileName, meshCount, materialCount); - - for (int i = 0; i < meshCount; i++) + + // Init model meshes array + model.meshCount = meshCount; + model.meshes = (Mesh *)malloc(model.meshCount*sizeof(Mesh)); + + // Init model materials array + model.materialCount = materialCount; + model.materials = (Material *)malloc(model.materialCount*sizeof(Material)); + + // Init model meshes + for (int m = 0; m < 1; m++) { - printf("shape[%d] name = %s\n", i, meshes[i].name); + printf("num_vertices: %i\n", attrib.num_vertices); + printf("num_normals: %i\n", attrib.num_normals); + printf("num_texcoords: %i\n", attrib.num_texcoords); + printf("num_faces: %i\n", attrib.num_faces); + printf("num_face_num_verts: %i\n", attrib.num_face_num_verts); + + Mesh mesh = { 0 }; + memset(&mesh, 0, sizeof(Mesh)); + mesh.vertexCount = attrib.num_faces*3; + mesh.triangleCount = attrib.num_faces; + mesh.vertices = (float *)malloc(mesh.vertexCount*3*sizeof(float)); + mesh.texcoords = (float *)malloc(mesh.vertexCount*2*sizeof(float)); + mesh.normals = (float *)malloc(mesh.vertexCount*3*sizeof(float)); + + int faceOffset = 0; + + int vCount = 0; + int vtCount = 0; + int vnCount = 0; + + /* + for (int i = 0; i < attrib.num_vertices*3; i++) printf("%2.2f, ", attrib.vertices[i]); + printf("\n"); + for (int i = 0; i < attrib.num_texcoords*2; i++) printf("%2.2f, ", attrib.texcoords[i]); + printf("\n"); + for (int i = 0; i < attrib.num_normals*3; i++) printf("%2.2f, ", attrib.normals[i]); + printf("\n"); + + tinyobj_vertex_index_t idx0 = attrib.faces[0]; + tinyobj_vertex_index_t idx1 = attrib.faces[1]; + tinyobj_vertex_index_t idx2 = attrib.faces[2]; + + for (int v = 0; v < 3; v++) { printf("%2.2f, ", attrib.vertices[idx0.v_idx*3 + v]); } printf("\n"); + for (int v = 0; v < 3; v++) { printf("%2.2f, ", attrib.vertices[idx1.v_idx*3 + v]); } printf("\n"); + for (int v = 0; v < 3; v++) { printf("%2.2f, ", attrib.vertices[idx2.v_idx*3 + v]); } printf("\n\n"); + + idx0 = attrib.faces[3 + 0]; + idx1 = attrib.faces[3 + 1]; + idx2 = attrib.faces[3 + 2]; + + for (int v = 0; v < 3; v++) { printf("%2.2f, ", attrib.vertices[idx0.v_idx*3 + v]); } printf("\n"); + for (int v = 0; v < 3; v++) { printf("%2.2f, ", attrib.vertices[idx1.v_idx*3 + v]); } printf("\n"); + for (int v = 0; v < 3; v++) { printf("%2.2f, ", attrib.vertices[idx2.v_idx*3 + v]); } printf("\n\n"); +*/ + for (int f = 0; f < attrib.num_faces; f++) + { + tinyobj_vertex_index_t idx0 = attrib.faces[3*f + 0]; + tinyobj_vertex_index_t idx1 = attrib.faces[3*f + 1]; + tinyobj_vertex_index_t idx2 = attrib.faces[3*f + 2]; + + // printf("Face index: v %i/%i/%i . vt %i/%i/%i . vn %i/%i/%i\n", + // idx0.v_idx, idx1.v_idx, idx2.v_idx, + // idx0.vt_idx, idx1.vt_idx, idx2.vt_idx, + // idx0.vn_idx, idx1.vn_idx, idx2.vn_idx); + + for (int v = 0; v < 3; v++) { mesh.vertices[vCount + v] = attrib.vertices[idx0.v_idx*3 + v]; } vCount +=3; + for (int v = 0; v < 3; v++) { mesh.vertices[vCount + v] = attrib.vertices[idx1.v_idx*3 + v]; } vCount +=3; + for (int v = 0; v < 3; v++) { mesh.vertices[vCount + v] = attrib.vertices[idx2.v_idx*3 + v]; } vCount +=3; + + for (int v = 0; v < 2; v++) { mesh.texcoords[vtCount + v] = attrib.texcoords[idx0.vt_idx*2 + v]; } vtCount += 2; + for (int v = 0; v < 2; v++) { mesh.texcoords[vtCount + v] = attrib.texcoords[idx1.vt_idx*2 + v]; } vtCount += 2; + for (int v = 0; v < 2; v++) { mesh.texcoords[vtCount + v] = attrib.texcoords[idx2.vt_idx*2 + v]; } vtCount += 2; + + for (int v = 0; v < 3; v++) { mesh.normals[vnCount + v] = attrib.normals[idx0.vn_idx*3 + v]; } vnCount +=3; + for (int v = 0; v < 3; v++) { mesh.normals[vnCount + v] = attrib.normals[idx1.vn_idx*3 + v]; } vnCount +=3; + for (int v = 0; v < 3; v++) { mesh.normals[vnCount + v] = attrib.normals[idx2.vn_idx*3 + v]; } vnCount +=3; + } + + printf("vCount: %i\n", vCount); + printf("vtCount: %i\n", vtCount); + printf("vnCount: %i\n", vnCount); + + model.meshes[m] = mesh; // Assign mesh data to model + rlLoadMesh(&model.meshes[m], false); // Upload vertex data to GPU (static mesh) } /* // Data reference to process - typedef struct { - char *name; - - float ambient[3]; - float diffuse[3]; - float specular[3]; - float transmittance[3]; - float emission[3]; - float shininess; - float ior; // index of refraction - float dissolve; // 1 == opaque; 0 == fully transparent - // illumination model (see http://www.fileformat.info/format/material/) - int illum; - - int pad0; - - char *ambient_texname; // map_Ka - char *diffuse_texname; // map_Kd - char *specular_texname; // map_Ks - char *specular_highlight_texname; // map_Ns - char *bump_texname; // map_bump, bump - char *displacement_texname; // disp - char *alpha_texname; // map_d - } tinyobj_material_t; - typedef struct { char *name; // group name or object name unsigned int face_offset; @@ -2469,11 +2527,60 @@ static Model LoadOBJ(const char *fileName) float *vertices; float *normals; float *texcoords; + tinyobj_vertex_index_t *faces; int *face_num_verts; + int *material_ids; } tinyobj_attrib_t; */ + + // Init model materials + for (int m = 0; m < materialCount; m++) + { + /* + typedef struct { + char *name; + + float ambient[3]; + float diffuse[3]; + float specular[3]; + float transmittance[3]; + float emission[3]; + float shininess; + float ior; // index of refraction + float dissolve; // 1 == opaque; 0 == fully transparent + // illumination model (see http://www.fileformat.info/format/material/) + int illum; + + int pad0; + + char *ambient_texname; // map_Ka + char *diffuse_texname; // map_Kd + char *specular_texname; // map_Ks + char *specular_highlight_texname; // map_Ns + char *bump_texname; // map_bump, bump + char *displacement_texname; // disp + char *alpha_texname; // map_d + } tinyobj_material_t; + */ + + /* + // Material texture map + typedef struct MaterialMap { + Texture2D texture; // Material map texture + Color color; // Material map color + float value; // Material map value + } MaterialMap; + + // Material type (generic) + typedef struct Material { + Shader shader; // Material shader + MaterialMap maps[MAX_MATERIAL_MAPS]; // Material maps + float *params; // Material generic parameters (if required) + } Material; + */ + } tinyobj_attrib_free(&attrib); tinyobj_shapes_free(meshes, meshCount); -- cgit v1.2.3 From e5edbb7104795e9936a275a8c53caf5026ab497f Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 1 Apr 2019 12:17:29 +0200 Subject: Reviewed OBJ loading implementation -WIP- One mesh files can be loaded correctly MISSING: - Multimesh OBJ loading - Materials loading --- src/models.c | 131 +++++++++++++++++++---------------------------------------- 1 file changed, 41 insertions(+), 90 deletions(-) (limited to 'src') diff --git a/src/models.c b/src/models.c index 68f5f6be..b1c56e48 100644 --- a/src/models.c +++ b/src/models.c @@ -635,7 +635,7 @@ Model LoadModel(const char *fileName) TraceLog(LOG_WARNING, "[%s] No meshes can be loaded, default to cube mesh", fileName); model.meshCount = 1; - model.meshes = (Mesh *)malloc(model.meshCount*sizeof(Mesh)); + model.meshes = (Mesh *)calloc(model.meshCount, sizeof(Mesh)); model.meshes[0] = GenMeshCube(1.0f, 1.0f, 1.0f); } @@ -644,7 +644,7 @@ Model LoadModel(const char *fileName) TraceLog(LOG_WARNING, "[%s] No materials can be loaded, default to white material", fileName); model.materialCount = 1; - model.materials = (Material *)malloc(model.materialCount*sizeof(Material)); + model.materials = (Material *)calloc(model.materialCount, sizeof(Material)); model.materials[0] = LoadMaterialDefault(); model.meshMaterial = (int *)calloc(model.meshCount, sizeof(int)); @@ -1879,7 +1879,7 @@ void UnloadMaterial(Material material) void DrawModel(Model model, Vector3 position, float scale, Color tint) { Vector3 vScale = { scale, scale, scale }; - Vector3 rotationAxis = { 0.0f, 0.0f, 0.0f }; + Vector3 rotationAxis = { 0.0f, 1.0f, 0.0f }; DrawModelEx(model, position, rotationAxis, 0.0f, vScale, tint); } @@ -1896,8 +1896,6 @@ void DrawModelEx(Model model, Vector3 position, Vector3 rotationAxis, float rota Matrix matTransform = MatrixMultiply(MatrixMultiply(matScale, matRotation), matTranslation); // Combine model transformation matrix (model.transform) with matrix generated by function parameters (matTransform) - //Matrix matModel = MatrixMultiply(model.transform, matTransform); // Transform to world-space coordinates - model.transform = MatrixMultiply(model.transform, matTransform); for (int i = 0; i < model.meshCount; i++) @@ -2126,25 +2124,25 @@ RayHitInfo GetCollisionRayModel(Ray ray, Model *model) { RayHitInfo result = { 0 }; - for (int i = 0; i < model->meshCount; i++) + for (int m = 0; m < model->meshCount; m++) { // Check if meshhas vertex data on CPU for testing - if (model->meshes[i].vertices != NULL) + if (model->meshes[m].vertices != NULL) { // model->mesh.triangleCount may not be set, vertexCount is more reliable - int triangleCount = model->meshes[i].vertexCount/3; + int triangleCount = model->meshes[m].vertexCount/3; // Test against all triangles in mesh for (int i = 0; i < triangleCount; i++) { Vector3 a, b, c; - Vector3 *vertdata = (Vector3 *)model->meshes[i].vertices; + Vector3 *vertdata = (Vector3 *)model->meshes[m].vertices; - if (model->meshes[i].indices) + if (model->meshes[m].indices) { - a = vertdata[model->meshes[i].indices[i*3 + 0]]; - b = vertdata[model->meshes[i].indices[i*3 + 1]]; - c = vertdata[model->meshes[i].indices[i*3 + 2]]; + a = vertdata[model->meshes[m].indices[i*3 + 0]]; + b = vertdata[model->meshes[m].indices[i*3 + 1]]; + c = vertdata[model->meshes[m].indices[i*3 + 2]]; } else { @@ -2260,6 +2258,8 @@ BoundingBox MeshBoundingBox(Mesh mesh) // Get min and max vertex to construct bounds (AABB) Vector3 minVertex = { 0 }; Vector3 maxVertex = { 0 }; + + printf("Mesh vertex count: %i\n", mesh.vertexCount); if (mesh.vertices != NULL) { @@ -2274,7 +2274,7 @@ BoundingBox MeshBoundingBox(Mesh mesh) } // Create the bounding box - BoundingBox box; + BoundingBox box = { 0 }; box.min = minVertex; box.max = maxVertex; @@ -2383,17 +2383,18 @@ void MeshBinormals(Mesh *mesh) static Model LoadOBJ(const char *fileName) { Model model = { 0 }; - + model.transform = MatrixIdentity(); + tinyobj_attrib_t attrib; tinyobj_shape_t *meshes = NULL; unsigned int meshCount = 0; - + tinyobj_material_t *materials = NULL; unsigned int materialCount = 0; int dataLength = 0; char *data = NULL; - + // Load model data FILE *objFile = fopen(fileName, "rb"); @@ -2425,16 +2426,21 @@ static Model LoadOBJ(const char *fileName) // Init model materials array model.materialCount = materialCount; model.materials = (Material *)malloc(model.materialCount*sizeof(Material)); + model.meshMaterial = (int *)calloc(model.meshCount, sizeof(int)); + + /* + // Multiple meshes data reference + // NOTE: They are provided as a faces offset + typedef struct { + char *name; // group name or object name + unsigned int face_offset; + unsigned int length; + } tinyobj_shape_t; + */ // Init model meshes for (int m = 0; m < 1; m++) { - printf("num_vertices: %i\n", attrib.num_vertices); - printf("num_normals: %i\n", attrib.num_normals); - printf("num_texcoords: %i\n", attrib.num_texcoords); - printf("num_faces: %i\n", attrib.num_faces); - printf("num_face_num_verts: %i\n", attrib.num_face_num_verts); - Mesh mesh = { 0 }; memset(&mesh, 0, sizeof(Mesh)); mesh.vertexCount = attrib.num_faces*3; @@ -2443,98 +2449,43 @@ static Model LoadOBJ(const char *fileName) mesh.texcoords = (float *)malloc(mesh.vertexCount*2*sizeof(float)); mesh.normals = (float *)malloc(mesh.vertexCount*3*sizeof(float)); - int faceOffset = 0; - int vCount = 0; int vtCount = 0; int vnCount = 0; - /* - for (int i = 0; i < attrib.num_vertices*3; i++) printf("%2.2f, ", attrib.vertices[i]); - printf("\n"); - for (int i = 0; i < attrib.num_texcoords*2; i++) printf("%2.2f, ", attrib.texcoords[i]); - printf("\n"); - for (int i = 0; i < attrib.num_normals*3; i++) printf("%2.2f, ", attrib.normals[i]); - printf("\n"); - - tinyobj_vertex_index_t idx0 = attrib.faces[0]; - tinyobj_vertex_index_t idx1 = attrib.faces[1]; - tinyobj_vertex_index_t idx2 = attrib.faces[2]; - - for (int v = 0; v < 3; v++) { printf("%2.2f, ", attrib.vertices[idx0.v_idx*3 + v]); } printf("\n"); - for (int v = 0; v < 3; v++) { printf("%2.2f, ", attrib.vertices[idx1.v_idx*3 + v]); } printf("\n"); - for (int v = 0; v < 3; v++) { printf("%2.2f, ", attrib.vertices[idx2.v_idx*3 + v]); } printf("\n\n"); - - idx0 = attrib.faces[3 + 0]; - idx1 = attrib.faces[3 + 1]; - idx2 = attrib.faces[3 + 2]; - - for (int v = 0; v < 3; v++) { printf("%2.2f, ", attrib.vertices[idx0.v_idx*3 + v]); } printf("\n"); - for (int v = 0; v < 3; v++) { printf("%2.2f, ", attrib.vertices[idx1.v_idx*3 + v]); } printf("\n"); - for (int v = 0; v < 3; v++) { printf("%2.2f, ", attrib.vertices[idx2.v_idx*3 + v]); } printf("\n\n"); -*/ for (int f = 0; f < attrib.num_faces; f++) { + // Get indices for the face tinyobj_vertex_index_t idx0 = attrib.faces[3*f + 0]; tinyobj_vertex_index_t idx1 = attrib.faces[3*f + 1]; tinyobj_vertex_index_t idx2 = attrib.faces[3*f + 2]; - // printf("Face index: v %i/%i/%i . vt %i/%i/%i . vn %i/%i/%i\n", - // idx0.v_idx, idx1.v_idx, idx2.v_idx, - // idx0.vt_idx, idx1.vt_idx, idx2.vt_idx, - // idx0.vn_idx, idx1.vn_idx, idx2.vn_idx); + // TraceLog(LOG_DEBUG, "Face %i index: v %i/%i/%i . vt %i/%i/%i . vn %i/%i/%i\n", f, idx0.v_idx, idx1.v_idx, idx2.v_idx, idx0.vt_idx, idx1.vt_idx, idx2.vt_idx, idx0.vn_idx, idx1.vn_idx, idx2.vn_idx); + // Fill vertices buffer (float) using vertex index of the face for (int v = 0; v < 3; v++) { mesh.vertices[vCount + v] = attrib.vertices[idx0.v_idx*3 + v]; } vCount +=3; for (int v = 0; v < 3; v++) { mesh.vertices[vCount + v] = attrib.vertices[idx1.v_idx*3 + v]; } vCount +=3; for (int v = 0; v < 3; v++) { mesh.vertices[vCount + v] = attrib.vertices[idx2.v_idx*3 + v]; } vCount +=3; - for (int v = 0; v < 2; v++) { mesh.texcoords[vtCount + v] = attrib.texcoords[idx0.vt_idx*2 + v]; } vtCount += 2; - for (int v = 0; v < 2; v++) { mesh.texcoords[vtCount + v] = attrib.texcoords[idx1.vt_idx*2 + v]; } vtCount += 2; - for (int v = 0; v < 2; v++) { mesh.texcoords[vtCount + v] = attrib.texcoords[idx2.vt_idx*2 + v]; } vtCount += 2; + // Fill texcoords buffer (float) using vertex index of the face + // NOTE: Y-coordinate must be flipped upside-down + mesh.texcoords[vtCount + 0] = attrib.texcoords[idx0.vt_idx*2 + 0]; + mesh.texcoords[vtCount + 1] = 1.0f - attrib.texcoords[idx0.vt_idx*2 + 1]; vtCount += 2; + mesh.texcoords[vtCount + 0] = attrib.texcoords[idx1.vt_idx*2 + 0]; + mesh.texcoords[vtCount + 1] = 1.0f - attrib.texcoords[idx1.vt_idx*2 + 1]; vtCount += 2; + mesh.texcoords[vtCount + 0] = attrib.texcoords[idx2.vt_idx*2 + 0]; + mesh.texcoords[vtCount + 1] = 1.0f - attrib.texcoords[idx2.vt_idx*2 + 1]; vtCount += 2; + // Fill normals buffer (float) using vertex index of the face for (int v = 0; v < 3; v++) { mesh.normals[vnCount + v] = attrib.normals[idx0.vn_idx*3 + v]; } vnCount +=3; for (int v = 0; v < 3; v++) { mesh.normals[vnCount + v] = attrib.normals[idx1.vn_idx*3 + v]; } vnCount +=3; for (int v = 0; v < 3; v++) { mesh.normals[vnCount + v] = attrib.normals[idx2.vn_idx*3 + v]; } vnCount +=3; } - - printf("vCount: %i\n", vCount); - printf("vtCount: %i\n", vtCount); - printf("vnCount: %i\n", vnCount); model.meshes[m] = mesh; // Assign mesh data to model rlLoadMesh(&model.meshes[m], false); // Upload vertex data to GPU (static mesh) } - - /* - // Data reference to process - typedef struct { - char *name; // group name or object name - unsigned int face_offset; - unsigned int length; - } tinyobj_shape_t; - - typedef struct { int v_idx, vt_idx, vn_idx; } tinyobj_vertex_index_t; - - typedef struct { - unsigned int num_vertices; - unsigned int num_normals; - unsigned int num_texcoords; - unsigned int num_faces; - unsigned int num_face_num_verts; - int pad0; - - float *vertices; - float *normals; - float *texcoords; - - tinyobj_vertex_index_t *faces; - int *face_num_verts; - - int *material_ids; - } tinyobj_attrib_t; - */ - // Init model materials for (int m = 0; m < materialCount; m++) { -- cgit v1.2.3 From 86212e84628e589701c7934affd83685ff3e8ae9 Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 1 Apr 2019 12:41:32 +0200 Subject: Support material loading from OBJ/MTL --- src/models.c | 37 ++++++++++++++++++++++--------------- 1 file changed, 22 insertions(+), 15 deletions(-) (limited to 'src') diff --git a/src/models.c b/src/models.c index b1c56e48..9fb08d82 100644 --- a/src/models.c +++ b/src/models.c @@ -2484,11 +2484,18 @@ static Model LoadOBJ(const char *fileName) model.meshes[m] = mesh; // Assign mesh data to model rlLoadMesh(&model.meshes[m], false); // Upload vertex data to GPU (static mesh) + + // Assign mesh material for current mesh + model.meshMaterial[m] = attrib.material_ids[m]; } // Init model materials for (int m = 0; m < materialCount; m++) { + // Init material to default + // NOTE: Uses default shader, only MAP_DIFFUSE supported + model.materials[m] = LoadMaterialDefault(); + /* typedef struct { char *name; @@ -2516,21 +2523,21 @@ static Model LoadOBJ(const char *fileName) } tinyobj_material_t; */ - /* - // Material texture map - typedef struct MaterialMap { - Texture2D texture; // Material map texture - Color color; // Material map color - float value; // Material map value - } MaterialMap; - - // Material type (generic) - typedef struct Material { - Shader shader; // Material shader - MaterialMap maps[MAX_MATERIAL_MAPS]; // Material maps - float *params; // Material generic parameters (if required) - } Material; - */ + model.materials[m].maps[MAP_DIFFUSE].texture = LoadTexture(materials[m].diffuse_texname); //char *diffuse_texname; // map_Kd + model.materials[m].maps[MAP_DIFFUSE].color = (Color){ (float)(materials[m].diffuse[0]*255.0f), (float)(materials[m].diffuse[1]*255.0f), (float)(materials[m].diffuse[2]*255.0f), 255 }; //float diffuse[3]; + model.materials[m].maps[MAP_DIFFUSE].value = 0.0f; + + model.materials[m].maps[MAP_SPECULAR].texture = LoadTexture(materials[m].specular_texname); //char *specular_texname; // map_Ks + model.materials[m].maps[MAP_SPECULAR].color = (Color){ (float)(materials[m].specular[0]*255.0f), (float)(materials[m].specular[1]*255.0f), (float)(materials[m].specular[2]*255.0f), 255 }; //float specular[3]; + model.materials[m].maps[MAP_SPECULAR].value = 0.0f; + + model.materials[m].maps[MAP_NORMAL].texture = LoadTexture(materials[m].bump_texname); //char *bump_texname; // map_bump, bump + model.materials[m].maps[MAP_NORMAL].color = WHITE; + model.materials[m].maps[MAP_NORMAL].value = materials[m].shininess; + + model.materials[m].maps[MAP_EMISSION].color = (Color){ (float)(materials[m].emission[0]*255.0f), (float)(materials[m].emission[1]*255.0f), (float)(materials[m].emission[2]*255.0f), 255 }; //float emission[3]; + + model.materials[m].maps[MAP_HEIGHT].texture = LoadTexture(materials[m].displacement_texname); //char *displacement_texname; // disp } tinyobj_attrib_free(&attrib); -- cgit v1.2.3 From f1cbdd6b3af5dc51cef306cbbc4619c7b6ed548a Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 1 Apr 2019 18:22:56 +0200 Subject: Corrected some issues - Support compiling for OpenGL 1.1 - Free meshes/materials memory after usage... --- src/models.c | 3 +++ src/rlgl.h | 19 ++++++++++++++++--- 2 files changed, 19 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/models.c b/src/models.c index 9fb08d82..7c266843 100644 --- a/src/models.c +++ b/src/models.c @@ -682,6 +682,9 @@ void UnloadModel(Model model) { for (int i = 0; i < model.meshCount; i++) UnloadMesh(&model.meshes[i]); for (int i = 0; i < model.materialCount; i++) UnloadMaterial(model.materials[i]); + + free(model.meshes); + free(model.materials); free(model.meshMaterial); TraceLog(LOG_INFO, "Unloaded model data from RAM and VRAM"); diff --git a/src/rlgl.h b/src/rlgl.h index 49ab1de5..9e9394db 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -2036,6 +2036,8 @@ unsigned int rlLoadTexture(void *data, int width, int height, int format, int mi unsigned int rlLoadTextureDepth(int width, int height, int bits, bool useRenderBuffer) { unsigned int id = 0; + +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) unsigned int glInternalFormat = GL_DEPTH_COMPONENT16; if ((bits != 16) && (bits != 24) && (bits != 32)) bits = 16; @@ -2081,6 +2083,7 @@ unsigned int rlLoadTextureDepth(int width, int height, int bits, bool useRenderB glBindRenderbuffer(GL_RENDERBUFFER, 0); } +#endif return id; } @@ -2092,7 +2095,8 @@ unsigned int rlLoadTextureCubemap(void *data, int size, int format) { unsigned int cubemapId = 0; unsigned int dataSize = GetPixelDataSize(size, size, format); - + +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) glGenTextures(1, &cubemapId); glBindTexture(GL_TEXTURE_CUBE_MAP, cubemapId); @@ -2137,6 +2141,7 @@ unsigned int rlLoadTextureCubemap(void *data, int size, int format) #endif glBindTexture(GL_TEXTURE_CUBE_MAP, 0); +#endif return cubemapId; } @@ -2221,9 +2226,9 @@ RenderTexture2D rlLoadRenderTexture(int width, int height, int format, int depth { RenderTexture2D target = { 0 }; +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) if (useDepthTexture && texDepthSupported) target.depthTexture = true; -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) // Create the framebuffer object glGenFramebuffers(1, &target.id); glBindFramebuffer(GL_FRAMEBUFFER, target.id); @@ -2274,6 +2279,7 @@ RenderTexture2D rlLoadRenderTexture(int width, int height, int format, int depth // NOTE: Attach type: 0-Color, 1-Depth renderbuffer, 2-Depth texture void rlRenderTextureAttach(RenderTexture2D target, unsigned int id, int attachType) { +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) glBindFramebuffer(GL_FRAMEBUFFER, target.id); if (attachType == 0) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, id, 0); @@ -2284,11 +2290,15 @@ void rlRenderTextureAttach(RenderTexture2D target, unsigned int id, int attachTy } glBindFramebuffer(GL_FRAMEBUFFER, 0); +#endif } // Verify render texture is complete bool rlRenderTextureComplete(RenderTexture target) { + bool result = false; + +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) glBindFramebuffer(GL_FRAMEBUFFER, target.id); GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); @@ -2309,7 +2319,10 @@ bool rlRenderTextureComplete(RenderTexture target) glBindFramebuffer(GL_FRAMEBUFFER, 0); - return (status == GL_FRAMEBUFFER_COMPLETE); + result = (status == GL_FRAMEBUFFER_COMPLETE); +#endif + + return result; } // Generate mipmap data for selected texture -- cgit v1.2.3 From 22dece2935ae0fcd67f0d040bdb3f95318495908 Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 4 Apr 2019 13:32:17 +0200 Subject: Animated vertex renaming --- src/rlgl.h | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/rlgl.h b/src/rlgl.h index 9e9394db..8cc4c590 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -205,8 +205,8 @@ typedef unsigned char byte; unsigned short *indices;// vertex indices (in case vertex data comes indexed) // Animation vertex data - float *baseVertices; // Vertex base position (required to apply bones transformations) - float *baseNormals; // Vertex base normals (required to apply bones transformations) + float *animVertices; // Animated vertex positions (after bones transformations) + float *animNormals; // Animated normals (after bones transformations) float *weightBias; // Vertex weight bias int *weightId; // Vertex weight id @@ -455,6 +455,7 @@ void rlDeleteVertexArrays(unsigned int id); // Unload vertex data (V void rlDeleteBuffers(unsigned int id); // Unload vertex data (VBO) from GPU memory void rlClearColor(byte r, byte g, byte b, byte a); // Clear color buffer with color void rlClearScreenBuffers(void); // Clear used screen buffers (color and depth) +void rlUpdateBuffer(int bufferId, void *data, int dataSize); // Update GPU buffer with new data //------------------------------------------------------------------------------------ // Functions Declaration - rlgl functionality @@ -1501,6 +1502,13 @@ void rlClearScreenBuffers(void) //glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); // Stencil buffer not used... } +// Update GPU buffer with new data +void rlUpdateBuffer(int bufferId, void *data, int dataSize) +{ + glBindBuffer(GL_ARRAY_BUFFER, bufferId); + glBufferSubData(GL_ARRAY_BUFFER, 0, dataSize, data); +} + //---------------------------------------------------------------------------------- // Module Functions Definition - rlgl Functions //---------------------------------------------------------------------------------- @@ -2788,10 +2796,10 @@ void rlUnloadMesh(Mesh *mesh) free(mesh->texcoords2); free(mesh->indices); - free(mesh->baseVertices); - free(mesh->baseNormals); - free(mesh->weightBias); - free(mesh->weightId); + free(mesh->animVertices); + free(mesh->animNormals); + free(mesh->boneWeights); + free(mesh->boneIds); rlDeleteBuffers(mesh->vboId[0]); // vertex rlDeleteBuffers(mesh->vboId[1]); // texcoords -- cgit v1.2.3 From d89d24c5e8930c18a93a6403e26914a9e2b23b84 Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 4 Apr 2019 13:33:54 +0200 Subject: BIG UPDATE: Support model animations! --- src/config.h | 6 +- src/models.c | 382 +++++++++++++++++++++++++++++++++++++++++++++++++++++------ src/raylib.h | 45 +++++-- 3 files changed, 383 insertions(+), 50 deletions(-) (limited to 'src') diff --git a/src/config.h b/src/config.h index d45ff707..4174ed71 100644 --- a/src/config.h +++ b/src/config.h @@ -66,10 +66,10 @@ //------------------------------------------------------------------------------------ // Draw rectangle shapes using font texture white character instead of default white texture // Allows drawing rectangles and text with a single draw call, very useful for GUI systems! -#define SUPPORT_FONT_TEXTURE +#define SUPPORT_FONT_TEXTURE 1 // Use QUADS instead of TRIANGLES for drawing when possible // Some lines-based shapes could still use lines -#define SUPPORT_QUADS_DRAW_MODE +#define SUPPORT_QUADS_DRAW_MODE 1 //------------------------------------------------------------------------------------ // Module: textures - Configuration Flags @@ -114,6 +114,8 @@ // Selected desired model fileformats to be supported for loading #define SUPPORT_FILEFORMAT_OBJ 1 #define SUPPORT_FILEFORMAT_MTL 1 +#define SUPPORT_FILEFORMAT_IQM 1 +#define SUPPORT_FILEFORMAT_GLTF 1 // Support procedural mesh generation functions, uses external par_shapes.h library // NOTE: Some generated meshes DO NOT include generated texture coordinates #define SUPPORT_MESH_GENERATION 1 diff --git a/src/models.c b/src/models.c index 7c266843..632aca2b 100644 --- a/src/models.c +++ b/src/models.c @@ -57,11 +57,6 @@ #include "external/tinyobj_loader_c.h" // OBJ/MTL file formats loading #endif -#if defined(SUPPORT_FILEFORMAT_IQM) - #define RIQM_IMPLEMENTATION - #include "external/riqm.h" // IQM file format loading -#endif - #if defined(SUPPORT_FILEFORMAT_GLTF) #define CGLTF_IMPLEMENTATION #include "external/cgltf.h" // glTF file format loading @@ -629,6 +624,9 @@ Model LoadModel(const char *fileName) #if defined(SUPPORT_FILEFORMAT_IQM) if (IsFileExtension(fileName, ".iqm")) model = LoadIQM(fileName); #endif + + // Make sure model transform is set to identity matrix! + model.transform = MatrixIdentity(); if (model.meshCount == 0) { @@ -638,7 +636,12 @@ Model LoadModel(const char *fileName) model.meshes = (Mesh *)calloc(model.meshCount, sizeof(Mesh)); model.meshes[0] = GenMeshCube(1.0f, 1.0f, 1.0f); } - + else + { + // Upload vertex data to GPU (static mesh) + for (int i = 0; i < model.meshCount; i++) rlLoadMesh(&model.meshes[i], false); + } + if (model.materialCount == 0) { TraceLog(LOG_WARNING, "[%s] No materials can be loaded, default to white material", fileName); @@ -686,30 +689,12 @@ void UnloadModel(Model model) free(model.meshes); free(model.materials); free(model.meshMaterial); - - TraceLog(LOG_INFO, "Unloaded model data from RAM and VRAM"); -} - -// Load mesh from file -// NOTE: Mesh data loaded in CPU and GPU -Mesh LoadMesh(const char *fileName) -{ - Mesh mesh = { 0 }; - - // TODO: Review this function, should still exist? -#if defined(SUPPORT_MESH_GENERATION) - if (mesh.vertexCount == 0) - { - TraceLog(LOG_WARNING, "Mesh could not be loaded! Let's load a cube to replace it!"); - mesh = GenMeshCube(1.0f, 1.0f, 1.0f); - } - else rlLoadMesh(&mesh, false); // Upload vertex data to GPU (static mesh) -#else - rlLoadMesh(&mesh, false); // Upload vertex data to GPU (static mesh) -#endif + // Unload animation data + free(model.bones); + free(model.bindPose); - return mesh; + TraceLog(LOG_INFO, "Unloaded model data from RAM and VRAM"); } // Unload mesh from memory (RAM and/or VRAM) @@ -2386,7 +2371,6 @@ void MeshBinormals(Mesh *mesh) static Model LoadOBJ(const char *fileName) { Model model = { 0 }; - model.transform = MatrixIdentity(); tinyobj_attrib_t attrib; tinyobj_shape_t *meshes = NULL; @@ -2486,8 +2470,7 @@ static Model LoadOBJ(const char *fileName) } model.meshes[m] = mesh; // Assign mesh data to model - rlLoadMesh(&model.meshes[m], false); // Upload vertex data to GPU (static mesh) - + // Assign mesh material for current mesh model.meshMaterial[m] = attrib.material_ids[m]; } @@ -2555,13 +2538,336 @@ static Model LoadOBJ(const char *fileName) } #endif -#if defined(SUPPORT_FILEFORMAT_GLTF) +#if defined(SUPPORT_FILEFORMAT_IQM) // Load IQM mesh data static Model LoadIQM(const char *fileName) { + #define IQM_MAGIC "INTERQUAKEMODEL" // IQM file magic number + #define IQM_VERSION 2 // only IQM version 2 supported + + #define BONE_NAME_LENGTH 32 // BoneInfo name string length + #define MESH_NAME_LENGTH 32 // Mesh name string length + + // IQM file structs + //----------------------------------------------------------------------------------- + typedef struct IQMHeader { + char magic[16]; + unsigned int version; + unsigned int filesize; + unsigned int flags; + unsigned int num_text, ofs_text; + unsigned int num_meshes, ofs_meshes; + unsigned int num_vertexarrays, num_vertexes, ofs_vertexarrays; + unsigned int num_triangles, ofs_triangles, ofs_adjacency; + unsigned int num_joints, ofs_joints; + unsigned int num_poses, ofs_poses; + unsigned int num_anims, ofs_anims; + unsigned int num_frames, num_framechannels, ofs_frames, ofs_bounds; + unsigned int num_comment, ofs_comment; + unsigned int num_extensions, ofs_extensions; + } IQMHeader; + + typedef struct IQMMesh { + unsigned int name; + unsigned int material; + unsigned int first_vertex, num_vertexes; + unsigned int first_triangle, num_triangles; + } IQMMesh; + + typedef struct IQMTriangle { + unsigned int vertex[3]; + } IQMTriangle; + + // NOTE: Adjacency unused by default + typedef struct IQMAdjacency { + unsigned int triangle[3]; + } IQMAdjacency; + + typedef struct IQMJoint { + unsigned int name; + int parent; + float translate[3], rotate[4], scale[3]; + } IQMJoint; + + typedef struct IQMPose { + int parent; + unsigned int mask; + float channeloffset[10]; + float channelscale[10]; + } IQMPose; + + typedef struct IQMAnim { + unsigned int name; + unsigned int first_frame, num_frames; + float framerate; + unsigned int flags; + } IQMAnim; + + typedef struct IQMVertexArray { + unsigned int type; + unsigned int flags; + unsigned int format; + unsigned int size; + unsigned int offset; + } IQMVertexArray; + + // NOTE: Bounds unused by default + typedef struct IQMBounds { + float bbmin[3], bbmax[3]; + float xyradius, radius; + } IQMBounds; + //----------------------------------------------------------------------------------- + + // IQM vertex data types + typedef enum { + IQM_POSITION = 0, + IQM_TEXCOORD = 1, + IQM_NORMAL = 2, + IQM_TANGENT = 3, // NOTE: Tangents unused by default + IQM_BLENDINDEXES = 4, + IQM_BLENDWEIGHTS = 5, + IQM_COLOR = 6, // NOTE: Vertex colors unused by default + IQM_CUSTOM = 0x10 // NOTE: Custom vertex values unused by default + } IQMVertexType; + Model model = { 0 }; - // TODO: Load IQM file + FILE *iqmFile; + IQMHeader iqm; + + IQMMesh *imesh; + IQMTriangle *tri; + IQMVertexArray *va; + IQMJoint *ijoint; + + float *vertex = NULL; + float *normal = NULL; + float *text = NULL; + char *blendi = NULL; + unsigned char *blendw = NULL; + + iqmFile = fopen(fileName, "rb"); + + if (iqmFile == NULL) + { + TraceLog(LOG_WARNING, "[%s] IQM file could not be opened", fileName); + return model; + } + + fread(&iqm,sizeof(IQMHeader), 1, iqmFile); // Read IQM header + + if (strncmp(iqm.magic, IQM_MAGIC, sizeof(IQM_MAGIC))) + { + TraceLog(LOG_WARNING, "[%s] IQM file does not seem to be valid", fileName); + fclose(iqmFile); + return model; + } + + if (iqm.version != IQM_VERSION) + { + TraceLog(LOG_WARNING, "[%s] IQM file version is not supported (%i).", fileName, iqm.version); + fclose(iqmFile); + return model; + } + + // Meshes data processing + imesh = malloc(sizeof(IQMMesh)*iqm.num_meshes); + fseek(iqmFile, iqm.ofs_meshes, SEEK_SET); + fread(imesh, sizeof(IQMMesh)*iqm.num_meshes, 1, iqmFile); + + model.meshCount = iqm.num_meshes; + model.meshes = malloc(sizeof(Mesh)*iqm.num_meshes); + + char name[MESH_NAME_LENGTH]; + + for (int i = 0; i < iqm.num_meshes; i++) + { + fseek(iqmFile,iqm.ofs_text+imesh[i].name,SEEK_SET); + fread(name, sizeof(char)*MESH_NAME_LENGTH, 1, iqmFile); // Mesh name not used... + model.meshes[i].vertexCount = imesh[i].num_vertexes; + + model.meshes[i].vertices = malloc(sizeof(float)*imesh[i].num_vertexes*3); // Default vertex positions + model.meshes[i].normals = malloc(sizeof(float)*imesh[i].num_vertexes*3); // Default vertex normals + model.meshes[i].texcoords = malloc(sizeof(float)*imesh[i].num_vertexes*2); // Default vertex texcoords + + model.meshes[i].boneIds = malloc(sizeof(int)*imesh[i].num_vertexes*4); // Up-to 4 bones supported! + model.meshes[i].boneWeights = malloc(sizeof(float)*imesh[i].num_vertexes*4); // Up-to 4 bones supported! + + model.meshes[i].triangleCount = imesh[i].num_triangles; + model.meshes[i].indices = malloc(sizeof(unsigned short)*imesh[i].num_triangles*3); + + // Animated verted data, what we actually process for rendering + // NOTE: Animated vertex should be re-uploaded to GPU (if not using GPU skinning) + model.meshes[i].animVertices = malloc(sizeof(float)*imesh[i].num_vertexes*3); + model.meshes[i].animNormals = malloc(sizeof(float)*imesh[i].num_vertexes*3); + } + + // Triangles data processing + tri = malloc(sizeof(IQMTriangle)*iqm.num_triangles); + fseek(iqmFile, iqm.ofs_triangles, SEEK_SET); + fread(tri, sizeof(IQMTriangle)*iqm.num_triangles, 1, iqmFile); + + for (int m = 0; m < iqm.num_meshes; m++) + { + int tcounter = 0; + + for (int i = imesh[m].first_triangle; i < imesh[m].first_triangle+imesh[m].num_triangles; i++) + { + // IQM triangles are stored counter clockwise, but raylib sets opengl to clockwise drawing, so we swap them around + model.meshes[m].indices[tcounter+2] = tri[i].vertex[0] - imesh[m].first_vertex; + model.meshes[m].indices[tcounter+1] = tri[i].vertex[1] - imesh[m].first_vertex; + model.meshes[m].indices[tcounter] = tri[i].vertex[2] - imesh[m].first_vertex; + tcounter += 3; + } + } + + // Vertex arrays data processing + va = malloc(sizeof(IQMVertexArray)*iqm.num_vertexarrays); + fseek(iqmFile, iqm.ofs_vertexarrays, SEEK_SET); + fread(va, sizeof(IQMVertexArray)*iqm.num_vertexarrays, 1, iqmFile); + + for (int i = 0; i < iqm.num_vertexarrays; i++) + { + switch (va[i].type) + { + case IQM_POSITION: + { + vertex = malloc(sizeof(float)*iqm.num_vertexes*3); + fseek(iqmFile, va[i].offset, SEEK_SET); + fread(vertex, sizeof(float)*iqm.num_vertexes*3, 1, iqmFile); + + for (int m = 0; m < iqm.num_meshes; m++) + { + int vCounter = 0; + for (int i = imesh[m].first_vertex*3; i < (imesh[m].first_vertex + imesh[m].num_vertexes)*3; i++) + { + model.meshes[m].vertices[vCounter] = vertex[i]; + model.meshes[m].animVertices[vCounter] = vertex[i]; + vCounter++; + } + } + } break; + case IQM_NORMAL: + { + normal = malloc(sizeof(float)*iqm.num_vertexes*3); + fseek(iqmFile, va[i].offset, SEEK_SET); + fread(normal, sizeof(float)*iqm.num_vertexes*3, 1, iqmFile); + + for (int m = 0; m < iqm.num_meshes; m++) + { + int vCounter = 0; + for (int i = imesh[m].first_vertex*3; i < (imesh[m].first_vertex + imesh[m].num_vertexes)*3; i++) + { + model.meshes[m].normals[vCounter] = normal[i]; + model.meshes[m].animNormals[vCounter] = normal[i]; + vCounter++; + } + } + } break; + case IQM_TEXCOORD: + { + text = malloc(sizeof(float)*iqm.num_vertexes*2); + fseek(iqmFile, va[i].offset, SEEK_SET); + fread(text, sizeof(float)*iqm.num_vertexes*2, 1, iqmFile); + + for (int m = 0; m < iqm.num_meshes; m++) + { + int vCounter = 0; + for (int i = imesh[m].first_vertex*2; i < (imesh[m].first_vertex + imesh[m].num_vertexes)*2; i++) + { + model.meshes[m].texcoords[vCounter] = text[i]; + vCounter++; + } + } + } break; + case IQM_BLENDINDEXES: + { + blendi = malloc(sizeof(char)*iqm.num_vertexes*4); + fseek(iqmFile, va[i].offset, SEEK_SET); + fread(blendi, sizeof(char)*iqm.num_vertexes*4, 1, iqmFile); + + for (int m = 0; m < iqm.num_meshes; m++) + { + int boneCounter = 0; + for (int i = imesh[m].first_vertex*4; i < (imesh[m].first_vertex + imesh[m].num_vertexes)*4; i++) + { + model.meshes[m].boneIds[boneCounter] = blendi[i]; + boneCounter++; + } + } + } break; + case IQM_BLENDWEIGHTS: + { + blendw = malloc(sizeof(unsigned char)*iqm.num_vertexes*4); + fseek(iqmFile,va[i].offset,SEEK_SET); + fread(blendw,sizeof(unsigned char)*iqm.num_vertexes*4,1,iqmFile); + + for (int m = 0; m < iqm.num_meshes; m++) + { + int boneCounter = 0; + for (int i = imesh[m].first_vertex*4; i < (imesh[m].first_vertex + imesh[m].num_vertexes)*4; i++) + { + model.meshes[m].boneWeights[boneCounter] = blendw[i]/255.0f; + boneCounter++; + } + } + } break; + } + } + + // Bones (joints) data processing + ijoint = malloc(sizeof(IQMJoint)*iqm.num_joints); + fseek(iqmFile, iqm.ofs_joints, SEEK_SET); + fread(ijoint, sizeof(IQMJoint)*iqm.num_joints, 1, iqmFile); + + model.boneCount = iqm.num_joints; + model.bones = malloc(sizeof(BoneInfo)*iqm.num_joints); + model.bindPose = malloc(sizeof(Transform)*iqm.num_joints); + + for (int i = 0; i < iqm.num_joints; i++) + { + // Bones + model.bones[i].parent = ijoint[i].parent; + fseek(iqmFile, iqm.ofs_text + ijoint[i].name, SEEK_SET); + fread(model.bones[i].name,sizeof(char)*BONE_NAME_LENGTH, 1, iqmFile); + + // Bind pose (base pose) + model.bindPose[i].translation.x = ijoint[i].translate[0]; + model.bindPose[i].translation.y = ijoint[i].translate[1]; + model.bindPose[i].translation.z = ijoint[i].translate[2]; + + model.bindPose[i].rotation.x = ijoint[i].rotate[0]; + model.bindPose[i].rotation.y = ijoint[i].rotate[1]; + model.bindPose[i].rotation.z = ijoint[i].rotate[2]; + model.bindPose[i].rotation.w = ijoint[i].rotate[3]; + + model.bindPose[i].scale.x = ijoint[i].scale[0]; + model.bindPose[i].scale.y = ijoint[i].scale[1]; + model.bindPose[i].scale.z = ijoint[i].scale[2]; + } + + // Build bind pose from parent joints + for (int i = 0; i < model.boneCount; i++) + { + if (model.bones[i].parent >= 0) + { + model.bindPose[i].rotation = QuaternionMultiply(model.bindPose[model.bones[i].parent].rotation, model.bindPose[i].rotation); + model.bindPose[i].translation = Vector3RotateByQuaternion(model.bindPose[i].translation, model.bindPose[model.bones[i].parent].rotation); + model.bindPose[i].translation = Vector3Add(model.bindPose[i].translation, model.bindPose[model.bones[i].parent].translation); + model.bindPose[i].scale = Vector3MultiplyV(model.bindPose[i].scale, model.bindPose[model.bones[i].parent].scale); + } + } + + fclose(iqmFile); + free(imesh); + free(tri); + free(va); + free(vertex); + free(normal); + free(text); + free(blendi); + free(blendw); + free(ijoint); return model; } @@ -2593,23 +2899,23 @@ static Model LoadGLTF(const char *fileName) // glTF data loading cgltf_options options = {0}; - cgltf_data data; + cgltf_data *data; cgltf_result result = cgltf_parse(&options, buffer, size, &data); free(buffer); if (result == cgltf_result_success) { - printf("Type: %u\n", data.file_type); - printf("Version: %d\n", data.version); - printf("Meshes: %lu\n", data.meshes_count); + // printf("Type: %u\n", data.file_type); + // printf("Version: %d\n", data.version); + // printf("Meshes: %lu\n", data.meshes_count); // TODO: Process glTF data and map to model // NOTE: data.buffers[] should be loaded to model.meshes and data.images[] should be loaded to model.materials // Use buffers[n].uri and images[n].uri... or use cgltf_load_buffers(&options, data, fileName); - cgltf_free(&data); + cgltf_free(data); } else TraceLog(LOG_WARNING, "[%s] glTF data could not be loaded", fileName); diff --git a/src/raylib.h b/src/raylib.h index 085f36f6..9607191b 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -307,10 +307,10 @@ typedef struct Mesh { unsigned short *indices;// Vertex indices (in case vertex data comes indexed) // Animation vertex data - float *baseVertices; // Vertex base position (required to apply bones transformations) - float *baseNormals; // Vertex base normals (required to apply bones transformations) - float *weightBias; // Vertex weight bias - int *weightId; // Vertex weight id + float *animVertices; // Animated vertex positions (after bones transformations) + float *animNormals; // Animated normals (after bones transformations) + int *boneIds; // Vertex bone ids, up to 4 bones influence by vertex (skinning) + float *boneWeights; // Vertex bone weight, up to 4 bones influence by vertex (skinning) // OpenGL identifiers unsigned int vaoId; // OpenGL Vertex Array Object id @@ -337,6 +337,19 @@ typedef struct Material { float *params; // Material generic parameters (if required) } Material; +// Transformation properties +typedef struct Transform { + Vector3 translation; // Translation + Quaternion rotation; // Rotation + Vector3 scale; // Scale +} Transform; + +// Bone information +typedef struct BoneInfo { + char name[32]; // Bone name + int parent; // Bone parent +} BoneInfo; + // Model type typedef struct Model { Matrix transform; // Local transform matrix @@ -346,10 +359,23 @@ typedef struct Model { int materialCount; // Number of materials Material *materials; // Materials array - int *meshMaterial; // Mesh material number + + // Animation data + int boneCount; // Number of bones + BoneInfo *bones; // Bones information (skeleton) + Transform *bindPose; // Bones base transformation (pose) } Model; +// Model animation +typedef struct ModelAnimation { + int boneCount; // Number of bones + BoneInfo *bones; // Bones information (skeleton) + + int frameCount; // Number of animation frames + Transform **framePoses; // Poses array by frame +} ModelAnimation; + // Ray type (useful for raycast) typedef struct Ray { Vector3 position; // Ray position (origin) @@ -1228,17 +1254,16 @@ RLAPI void DrawGizmo(Vector3 position); // Model loading/unloading functions RLAPI Model LoadModel(const char *fileName); // Load model from files (meshes and materials) RLAPI Model LoadModelFromMesh(Mesh mesh); // Load model from generated mesh +//RLAPI void LoadModelAnimations(const char fileName, ModelAnimation *anims, int *animsCount); // Load model animations from file +//RLAPI void UpdateModelAnimation(Model model, ModelAnimation anim, int frame); // Update model animation pose RLAPI void UnloadModel(Model model); // Unload model from memory (RAM and/or VRAM) -// Mesh loading/unloading functions -RLAPI Mesh LoadMesh(const char *fileName); // Load mesh from file -RLAPI void UnloadMesh(Mesh *mesh); // Unload mesh from memory (RAM and/or VRAM) -RLAPI void ExportMesh(Mesh mesh, const char *fileName); // Export mesh data to file - // Mesh manipulation functions RLAPI BoundingBox MeshBoundingBox(Mesh mesh); // Compute mesh bounding box limits RLAPI void MeshTangents(Mesh *mesh); // Compute mesh tangents RLAPI void MeshBinormals(Mesh *mesh); // Compute mesh binormals +RLAPI void UnloadMesh(Mesh *mesh); // Unload mesh from memory (RAM and/or VRAM) +RLAPI void ExportMesh(Mesh mesh, const char *fileName); // Export mesh data to file // Mesh generation functions RLAPI Mesh GenMeshPoly(int sides, float radius); // Generate polygonal mesh -- cgit v1.2.3 From 3e1e7d740fd378df03346e309ba187b6f7a20daa Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 4 Apr 2019 13:50:28 +0200 Subject: Review merged PR formatting Removed trail spaces --- src/shapes.c | 266 +++++++++++++++++++++++++++++++---------------------------- 1 file changed, 139 insertions(+), 127 deletions(-) (limited to 'src') diff --git a/src/shapes.c b/src/shapes.c index 879d2a10..b7f7e3df 100644 --- a/src/shapes.c +++ b/src/shapes.c @@ -186,31 +186,31 @@ void DrawCircle(int centerX, int centerY, float radius, Color color) void DrawCircleSector(Vector2 center, float radius, int startAngle, int endAngle, int segments, Color color) { if (radius <= 0.0f) radius = 0.1f; // Avoid div by zero - + // Function expects (endAngle > startAngle) - if (endAngle < startAngle) + if (endAngle < startAngle) { // Swap values int tmp = startAngle; startAngle = endAngle; endAngle = tmp; } - + if (segments < 4) { // Calculate how many segments we need to draw a smooth circle, taken from https://stackoverflow.com/a/2244088 #define CIRCLE_ERROR_RATE 0.5f - + // Calculate the maximum angle between segments based on the error rate. float th = acosf(2*powf(1 - CIRCLE_ERROR_RATE/radius, 2) - 1); segments = (endAngle - startAngle)*ceilf(2*PI/th)/360; - + if (segments <= 0) segments = 4; } - + float stepLength = (float)(endAngle - startAngle)/(float)segments; float angle = startAngle; - + #if defined(SUPPORT_QUADS_DRAW_MODE) if (rlCheckBufferLimit(4*segments/2)) rlglDraw(); @@ -227,16 +227,16 @@ void DrawCircleSector(Vector2 center, float radius, int startAngle, int endAngle rlTexCoord2f(recTexShapes.x/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); rlVertex2f(center.x + sinf(DEG2RAD*angle)*radius, center.y + cosf(DEG2RAD*angle)*radius); - + rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength))*radius, center.y + cosf(DEG2RAD*(angle + stepLength))*radius); rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, recTexShapes.y/texShapes.height); rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength*2))*radius, center.y + cosf(DEG2RAD*(angle + stepLength*2))*radius); - + angle += (stepLength*2); } - + // NOTE: In case number of segments is odd, we add one last piece to the cake if (segments%2) { @@ -247,7 +247,7 @@ void DrawCircleSector(Vector2 center, float radius, int startAngle, int endAngle rlTexCoord2f(recTexShapes.x/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); rlVertex2f(center.x + sinf(DEG2RAD*angle)*radius, center.y + cosf(DEG2RAD*angle)*radius); - + rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength))*radius, center.y + cosf(DEG2RAD*(angle + stepLength))*radius); @@ -268,7 +268,7 @@ void DrawCircleSector(Vector2 center, float radius, int startAngle, int endAngle rlVertex2f(center.x, center.y); rlVertex2f(center.x + sinf(DEG2RAD*angle)*radius, center.y + cosf(DEG2RAD*angle)*radius); rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength))*radius, center.y + cosf(DEG2RAD*(angle + stepLength))*radius); - + angle += stepLength; } rlEnd(); @@ -278,40 +278,40 @@ void DrawCircleSector(Vector2 center, float radius, int startAngle, int endAngle void DrawCircleSectorLines(Vector2 center, float radius, int startAngle, int endAngle, int segments, Color color) { if (radius <= 0.0f) radius = 0.1f; // Avoid div by zero issue - + // Function expects (endAngle > startAngle) - if (endAngle < startAngle) + if (endAngle < startAngle) { // Swap values int tmp = startAngle; startAngle = endAngle; endAngle = tmp; } - + if (segments < 4) { // Calculate how many segments we need to draw a smooth circle, taken from https://stackoverflow.com/a/2244088 #ifndef CIRCLE_ERROR_RATE #define CIRCLE_ERROR_RATE 0.5f #endif - + // Calculate the maximum angle between segments based on the error rate. float th = acosf(2*powf(1 - CIRCLE_ERROR_RATE/radius, 2) - 1); segments = (endAngle - startAngle)*ceilf(2*PI/th)/360; - + if (segments <= 0) segments = 4; } - + float stepLength = (float)(endAngle - startAngle)/(float)segments; float angle = startAngle; - + // Hide the cap lines when the circle is full bool showCapLines = true; int limit = 2*(segments + 2); if ((endAngle - startAngle)%360 == 0) { limit = 2*segments; showCapLines = false; } - + if (rlCheckBufferLimit(limit)) rlglDraw(); - + rlBegin(RL_LINES); if (showCapLines) { @@ -319,17 +319,17 @@ void DrawCircleSectorLines(Vector2 center, float radius, int startAngle, int end rlVertex2f(center.x, center.y); rlVertex2f(center.x + sinf(DEG2RAD*angle)*radius, center.y + cosf(DEG2RAD*angle)*radius); } - + for (int i = 0; i < segments; i++) { rlColor4ub(color.r, color.g, color.b, color.a); - + rlVertex2f(center.x + sinf(DEG2RAD*angle)*radius, center.y + cosf(DEG2RAD*angle)*radius); rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength))*radius, center.y + cosf(DEG2RAD*(angle + stepLength))*radius); - + angle += stepLength; } - + if (showCapLines) { rlColor4ub(color.r, color.g, color.b, color.a); @@ -385,55 +385,55 @@ void DrawCircleLines(int centerX, int centerY, float radius, Color color) void DrawRing(Vector2 center, float innerRadius, float outerRadius, int startAngle, int endAngle, int segments, Color color) { if (startAngle == endAngle) return; - + // Function expects (outerRadius > innerRadius) if (outerRadius < innerRadius) { float tmp = outerRadius; outerRadius = innerRadius; innerRadius = tmp; - + if (outerRadius <= 0.0f) outerRadius = 0.1f; } - + // Function expects (endAngle > startAngle) - if (endAngle < startAngle) + if (endAngle < startAngle) { // Swap values int tmp = startAngle; startAngle = endAngle; endAngle = tmp; } - + if (segments < 4) { // Calculate how many segments we need to draw a smooth circle, taken from https://stackoverflow.com/a/2244088 #ifndef CIRCLE_ERROR_RATE #define CIRCLE_ERROR_RATE 0.5f #endif - + // Calculate the maximum angle between segments based on the error rate. float th = acosf(2*powf(1 - CIRCLE_ERROR_RATE/outerRadius, 2) - 1); segments = (endAngle - startAngle)*ceilf(2*PI/th)/360; - + if (segments <= 0) segments = 4; } - + // Not a ring - if (innerRadius <= 0.0f) + if (innerRadius <= 0.0f) { DrawCircleSector(center, outerRadius, startAngle, endAngle, segments, color); return; } - + float stepLength = (float)(endAngle - startAngle)/(float)segments; float angle = startAngle; - + #if defined(SUPPORT_QUADS_DRAW_MODE) if (rlCheckBufferLimit(4*segments)) rlglDraw(); rlEnableTexture(GetShapesTexture().id); - + rlBegin(RL_QUADS); for (int i = 0; i < segments; i++) { @@ -444,13 +444,13 @@ void DrawRing(Vector2 center, float innerRadius, float outerRadius, int startAng rlTexCoord2f(recTexShapes.x/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); rlVertex2f(center.x + sinf(DEG2RAD*angle)*outerRadius, center.y + cosf(DEG2RAD*angle)*outerRadius); - + rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength))*outerRadius, center.y + cosf(DEG2RAD*(angle + stepLength))*outerRadius); rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, recTexShapes.y/texShapes.height); rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength))*innerRadius, center.y + cosf(DEG2RAD*(angle + stepLength))*innerRadius); - + angle += stepLength; } rlEnd(); @@ -463,15 +463,15 @@ void DrawRing(Vector2 center, float innerRadius, float outerRadius, int startAng for (int i = 0; i < segments; i++) { rlColor4ub(color.r, color.g, color.b, color.a); - + rlVertex2f(center.x + sinf(DEG2RAD*angle)*innerRadius, center.y + cosf(DEG2RAD*angle)*innerRadius); rlVertex2f(center.x + sinf(DEG2RAD*angle)*outerRadius, center.y + cosf(DEG2RAD*angle)*outerRadius); rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength))*innerRadius, center.y + cosf(DEG2RAD*(angle + stepLength))*innerRadius); - + rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength))*innerRadius, center.y + cosf(DEG2RAD*(angle + stepLength))*innerRadius); rlVertex2f(center.x + sinf(DEG2RAD*angle)*outerRadius, center.y + cosf(DEG2RAD*angle)*outerRadius); rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength))*outerRadius, center.y + cosf(DEG2RAD*(angle + stepLength))*outerRadius); - + angle += stepLength; } rlEnd(); @@ -481,55 +481,55 @@ void DrawRing(Vector2 center, float innerRadius, float outerRadius, int startAng void DrawRingLines(Vector2 center, float innerRadius, float outerRadius, int startAngle, int endAngle, int segments, Color color) { if (startAngle == endAngle) return; - + // Function expects (outerRadius > innerRadius) if (outerRadius < innerRadius) { float tmp = outerRadius; outerRadius = innerRadius; innerRadius = tmp; - + if (outerRadius <= 0.0f) outerRadius = 0.1f; } - + // Function expects (endAngle > startAngle) - if (endAngle < startAngle) + if (endAngle < startAngle) { // Swap values int tmp = startAngle; startAngle = endAngle; endAngle = tmp; } - + if (segments < 4) { // Calculate how many segments we need to draw a smooth circle, taken from https://stackoverflow.com/a/2244088 #ifndef CIRCLE_ERROR_RATE #define CIRCLE_ERROR_RATE 0.5f #endif - + // Calculate the maximum angle between segments based on the error rate. float th = acosf(2*powf(1 - CIRCLE_ERROR_RATE/outerRadius, 2) - 1); segments = (endAngle - startAngle)*ceilf(2*PI/th)/360; - + if (segments <= 0) segments = 4; } - - if (innerRadius <= 0.0f) + + if (innerRadius <= 0.0f) { DrawCircleSectorLines(center, outerRadius, startAngle, endAngle, segments, color); return; } - + float stepLength = (float)(endAngle - startAngle)/(float)segments; - float angle = startAngle; - + float angle = startAngle; + bool showCapLines = true; int limit = 4*(segments + 1); if ((endAngle - startAngle)%360 == 0) { limit = 4*segments; showCapLines = false; } - + if (rlCheckBufferLimit(limit)) rlglDraw(); - + rlBegin(RL_LINES); if (showCapLines) { @@ -537,20 +537,20 @@ void DrawRingLines(Vector2 center, float innerRadius, float outerRadius, int sta rlVertex2f(center.x + sinf(DEG2RAD*angle)*outerRadius, center.y + cosf(DEG2RAD*angle)*outerRadius); rlVertex2f(center.x + sinf(DEG2RAD*angle)*innerRadius, center.y + cosf(DEG2RAD*angle)*innerRadius); } - + for (int i = 0; i < segments; i++) { rlColor4ub(color.r, color.g, color.b, color.a); - + rlVertex2f(center.x + sinf(DEG2RAD*angle)*outerRadius, center.y + cosf(DEG2RAD*angle)*outerRadius); rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength))*outerRadius, center.y + cosf(DEG2RAD*(angle + stepLength))*outerRadius); - + rlVertex2f(center.x + sinf(DEG2RAD*angle)*innerRadius, center.y + cosf(DEG2RAD*angle)*innerRadius); rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength))*innerRadius, center.y + cosf(DEG2RAD*(angle + stepLength))*innerRadius); - + angle += stepLength; } - + if (showCapLines) { rlColor4ub(color.r, color.g, color.b, color.a); @@ -698,22 +698,22 @@ void DrawRectangleLinesEx(Rectangle rec, int lineThick, Color color) DrawRectangle( (int)rec.x, (int)(rec.y + lineThick), lineThick, (int)(rec.height - lineThick*2), color); } -// Draw rectangle with rounded edges. -void DrawRoundedRect(Rectangle rec, float roundness, int segments, Color color) +// Draw rectangle with rounded edges +void DrawRectangleRounded(Rectangle rec, float roundness, int segments, Color color) { // Not a rounded rectangle - if(roundness <= 0.0f || rec.width < 1 || rec.height < 1 ) + if ((roundness <= 0.0f) || (rec.width < 1) || (rec.height < 1 )) { DrawRectangleRec(rec, color); return; } - - if(roundness >= 1.0f) roundness = 1.0f; - + + if (roundness >= 1.0f) roundness = 1.0f; + // Calculate corner radius - float radius = rec.width > rec.height ? (rec.height*roundness)/2 : (rec.width*roundness)/2; - if(radius <= 0.0f) return; - + float radius = (rec.width > rec.height)? (rec.height*roundness)/2 : (rec.width*roundness)/2; + if (radius <= 0.0f) return; + // Calculate number of segments to use for the corners if (segments < 4) { @@ -726,9 +726,9 @@ void DrawRoundedRect(Rectangle rec, float roundness, int segments, Color color) segments = ceilf(2*PI/th)/4; if (segments <= 0) segments = 4; } - + float stepLength = 90.0f/(float)segments; - + /* Quick sketch to make sense of all of this (there are 9 parts to draw, also mark the 12 points we'll use below) * Not my best attempt at ASCII art, just preted it's rounded rectangle :) * P0 P1 @@ -744,7 +744,7 @@ void DrawRoundedRect(Rectangle rec, float roundness, int segments, Color color) * \|____________________|/ * P5 P4 */ - + const Vector2 point[12] = { // coordinates of the 12 points that define the rounded rect (the idea here is to make things easier) {(float)rec.x + radius, rec.y}, {(float)(rec.x + rec.width) - radius, rec.y}, { rec.x + rec.width, (float)rec.y + radius }, // PO, P1, P2 {rec.x + rec.width, (float)(rec.y + rec.height) - radius}, {(float)(rec.x + rec.width) - radius, rec.y + rec.height}, // P3, P4 @@ -752,15 +752,16 @@ void DrawRoundedRect(Rectangle rec, float roundness, int segments, Color color) {(float)rec.x + radius, (float)rec.y + radius}, {(float)(rec.x + rec.width) - radius, (float)rec.y + radius}, // P8, P9 {(float)(rec.x + rec.width) - radius, (float)(rec.y + rec.height) - radius}, {(float)rec.x + radius, (float)(rec.y + rec.height) - radius} // P10, P11 }; + const Vector2 centers[4] = { point[8], point[9], point[10], point[11] }; - const float angles[4] = {180.0f, 90.0f, 0.0f, 270.0f }; + const float angles[4] = { 180.0f, 90.0f, 0.0f, 270.0f }; #if defined(SUPPORT_QUADS_DRAW_MODE) if (rlCheckBufferLimit(16*segments/2 + 5*4)) rlglDraw(); - + rlBegin(RL_QUADS); - // Draw all of the 4 corners: [1] Upper Left Corner, [3] Upper Right Corner, [5] Lower Right Corner, [7] Lower Left Corner - for(int k = 0; k < 4; ++k) // Hope the compiler is smart enough to unroll this loop + // Draw all of the 4 corners: [1] Upper Left Corner, [3] Upper Right Corner, [5] Lower Right Corner, [7] Lower Left Corner + for (int k = 0; k < 4; ++k) // Hope the compiler is smart enough to unroll this loop { float angle = angles[k]; const Vector2 center = centers[k]; @@ -784,49 +785,49 @@ void DrawRoundedRect(Rectangle rec, float roundness, int segments, Color color) rlVertex2f(center.x, center.y); } } - + // [2] Upper Rectangle rlColor4ub(color.r, color.g, color.b, color.a); rlVertex2f(point[0].x, point[0].y); rlVertex2f(point[8].x, point[8].y); rlVertex2f(point[9].x, point[9].y); rlVertex2f(point[1].x, point[1].y); - + // [4] Right Rectangle rlColor4ub(color.r, color.g, color.b, color.a); rlVertex2f(point[2].x, point[2].y); rlVertex2f(point[9].x, point[9].y); rlVertex2f(point[10].x, point[10].y); rlVertex2f(point[3].x, point[3].y); - + // [6] Bottom Rectangle rlColor4ub(color.r, color.g, color.b, color.a); rlVertex2f(point[11].x, point[11].y); rlVertex2f(point[5].x, point[5].y); rlVertex2f(point[4].x, point[4].y); rlVertex2f(point[10].x, point[10].y); - + // [8] Left Rectangle rlColor4ub(color.r, color.g, color.b, color.a); rlVertex2f(point[7].x, point[7].y); rlVertex2f(point[6].x, point[6].y); rlVertex2f(point[11].x, point[11].y); rlVertex2f(point[8].x, point[8].y); - + // [9] Middle Rectangle rlColor4ub(color.r, color.g, color.b, color.a); rlVertex2f(point[8].x, point[8].y); rlVertex2f(point[11].x, point[11].y); rlVertex2f(point[10].x, point[10].y); rlVertex2f(point[9].x, point[9].y); - + rlEnd(); #else if (rlCheckBufferLimit(12*segments + 5*6)) rlglDraw(); // 4 corners with 3 vertices per segment + 5 rectangles with 6 vertices each - + rlBegin(RL_TRIANGLES); - // Draw all of the 4 corners: [1] Upper Left Corner, [3] Upper Right Corner, [5] Lower Right Corner, [7] Lower Left Corner - for(int k = 0; k < 4; ++k) // Hope the compiler is smart enough to unroll this loop + // Draw all of the 4 corners: [1] Upper Left Corner, [3] Upper Right Corner, [5] Lower Right Corner, [7] Lower Left Corner + for (int k = 0; k < 4; ++k) // Hope the compiler is smart enough to unroll this loop { float angle = angles[k]; const Vector2 center = centers[k]; @@ -848,7 +849,7 @@ void DrawRoundedRect(Rectangle rec, float roundness, int segments, Color color) rlVertex2f(point[1].x, point[1].y); rlVertex2f(point[0].x, point[0].y); rlVertex2f(point[9].x, point[9].y); - + // [4] Right Rectangle rlColor4ub(color.r, color.g, color.b, color.a); rlVertex2f(point[9].x, point[9].y); @@ -857,7 +858,7 @@ void DrawRoundedRect(Rectangle rec, float roundness, int segments, Color color) rlVertex2f(point[2].x, point[2].y); rlVertex2f(point[9].x, point[9].y); rlVertex2f(point[3].x, point[3].y); - + // [6] Bottom Rectangle rlColor4ub(color.r, color.g, color.b, color.a); rlVertex2f(point[11].x, point[11].y); @@ -866,7 +867,7 @@ void DrawRoundedRect(Rectangle rec, float roundness, int segments, Color color) rlVertex2f(point[10].x, point[10].y); rlVertex2f(point[11].x, point[11].y); rlVertex2f(point[4].x, point[4].y); - + // [8] Left Rectangle rlColor4ub(color.r, color.g, color.b, color.a); rlVertex2f(point[7].x, point[7].y); @@ -875,7 +876,7 @@ void DrawRoundedRect(Rectangle rec, float roundness, int segments, Color color) rlVertex2f(point[8].x, point[8].y); rlVertex2f(point[7].x, point[7].y); rlVertex2f(point[11].x, point[11].y); - + // [9] Middle Rectangle rlColor4ub(color.r, color.g, color.b, color.a); rlVertex2f(point[8].x, point[8].y); @@ -888,23 +889,24 @@ void DrawRoundedRect(Rectangle rec, float roundness, int segments, Color color) #endif } -// Draw rounded rectangle outline -void DrawRoundedRectLines(Rectangle rec, float roundness, int segments, int lineThick, Color color) +// Draw rectangle with rounded edges outline +void DrawRectangleRoundedLines(Rectangle rec, float roundness, int segments, int lineThick, Color color) { - if(lineThick < 0) lineThick = 0; + if (lineThick < 0) lineThick = 0; + // Not a rounded rectangle - if(roundness <= 0.0f ) + if (roundness <= 0.0f) { DrawRectangleLinesEx((Rectangle){rec.x-lineThick, rec.y-lineThick, rec.width+2*lineThick, rec.height+2*lineThick}, lineThick, color); return; } - - if(roundness >= 1.0f) roundness = 1.0f; - + + if (roundness >= 1.0f) roundness = 1.0f; + // Calculate corner radius - float radius = rec.width > rec.height ? (rec.height*roundness)/2 : (rec.width*roundness)/2; - if(radius <= 0.0f) return; - + float radius = (rec.width > rec.height)? (rec.height*roundness)/2 : (rec.width*roundness)/2; + if (radius <= 0.0f) return; + // Calculate number of segments to use for the corners if (segments < 4) { @@ -917,10 +919,10 @@ void DrawRoundedRectLines(Rectangle rec, float roundness, int segments, int line segments = ceilf(2*PI/th)/2; if (segments <= 0) segments = 4; } - + float stepLength = 90.0f/(float)segments; const float outerRadius = radius + (float)lineThick, innerRadius = radius; - + /* Quick sketch to make sense of all of this (mark the 16 + 4(corner centers P16-19) points we'll use below) * Not my best attempt at ASCII art, just preted it's rounded rectangle :) * P0 P1 @@ -937,7 +939,7 @@ void DrawRoundedRectLines(Rectangle rec, float roundness, int segments, int line * ==================== * P5 P4 */ - const Vector2 point[16] = { + const Vector2 point[16] = { {(float)rec.x + innerRadius, rec.y - lineThick}, {(float)(rec.x + rec.width) - innerRadius, rec.y - lineThick}, { rec.x + rec.width + lineThick, (float)rec.y + innerRadius }, // PO, P1, P2 {rec.x + rec.width + lineThick, (float)(rec.y + rec.height) - innerRadius}, {(float)(rec.x + rec.width) - innerRadius, rec.y + rec.height + lineThick}, // P3, P4 {(float)rec.x + innerRadius, rec.y + rec.height + lineThick}, { rec.x - lineThick, (float)(rec.y + rec.height) - innerRadius}, {rec.x - lineThick, (float)rec.y + innerRadius}, // P5, P6, P7 @@ -946,22 +948,25 @@ void DrawRoundedRectLines(Rectangle rec, float roundness, int segments, int line {(float)(rec.x + rec.width) - innerRadius, rec.y + rec.height}, {(float)rec.x + innerRadius, rec.y + rec.height}, // P12, P13 { rec.x, (float)(rec.y + rec.height) - innerRadius}, {rec.x, (float)rec.y + innerRadius} // P14, P15 }; - const Vector2 centers[4] = { + + const Vector2 centers[4] = { {(float)rec.x + innerRadius, (float)rec.y + innerRadius}, {(float)(rec.x + rec.width) - innerRadius, (float)rec.y + innerRadius}, // P16, P17 - {(float)(rec.x + rec.width) - innerRadius, (float)(rec.y + rec.height) - innerRadius}, {(float)rec.x + innerRadius, (float)(rec.y + rec.height) - innerRadius} // P18, P19 + {(float)(rec.x + rec.width) - innerRadius, (float)(rec.y + rec.height) - innerRadius}, {(float)rec.x + innerRadius, (float)(rec.y + rec.height) - innerRadius} // P18, P19 }; - const float angles[4] = {180.0f, 90.0f, 0.0f, 270.0f }; - - if(lineThick > 1) + + const float angles[4] = { 180.0f, 90.0f, 0.0f, 270.0f }; + + if (lineThick > 1) { #if defined(SUPPORT_QUADS_DRAW_MODE) if (rlCheckBufferLimit(4*4*segments + 4*4)) rlglDraw(); // 4 corners with 4 vertices for each segment + 4 rectangles with 4 vertices each + rlBegin(RL_QUADS); // Draw all of the 4 corners first: Upper Left Corner, Upper Right Corner, Lower Right Corner, Lower Left Corner - for(int k = 0; k < 4; ++k) // Hope the compiler is smart enough to unroll this loop + for (int k = 0; k < 4; ++k) // Hope the compiler is smart enough to unroll this loop { float angle = angles[k]; - const Vector2 center = centers[k]; + const Vector2 center = centers[k]; for (int i = 0; i < segments; i++) { rlColor4ub(color.r, color.g, color.b, color.a); @@ -969,63 +974,67 @@ void DrawRoundedRectLines(Rectangle rec, float roundness, int segments, int line rlVertex2f(center.x + sinf(DEG2RAD*angle)*outerRadius, center.y + cosf(DEG2RAD*angle)*outerRadius); rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength))*outerRadius, center.y + cosf(DEG2RAD*(angle + stepLength))*outerRadius); rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength))*innerRadius, center.y + cosf(DEG2RAD*(angle + stepLength))*innerRadius); - + angle += stepLength; } } + // Upper rectangle rlColor4ub(color.r, color.g, color.b, color.a); rlVertex2f(point[0].x, point[0].y); rlVertex2f(point[8].x, point[8].y); rlVertex2f(point[9].x, point[9].y); rlVertex2f(point[1].x, point[1].y); - + // Right rectangle rlColor4ub(color.r, color.g, color.b, color.a); rlVertex2f(point[2].x, point[2].y); rlVertex2f(point[10].x, point[10].y); rlVertex2f(point[11].x, point[11].y); rlVertex2f(point[3].x, point[3].y); - + // Lower rectangle rlColor4ub(color.r, color.g, color.b, color.a); rlVertex2f(point[13].x, point[13].y); rlVertex2f(point[5].x, point[5].y); rlVertex2f(point[4].x, point[4].y); rlVertex2f(point[12].x, point[12].y); - + // Left rectangle rlColor4ub(color.r, color.g, color.b, color.a); rlVertex2f(point[15].x, point[15].y); rlVertex2f(point[7].x, point[7].y); rlVertex2f(point[6].x, point[6].y); rlVertex2f(point[14].x, point[14].y); - + rlEnd(); #else if (rlCheckBufferLimit(4*6*segments + 4*6)) rlglDraw(); // 4 corners with 6(2*3) vertices for each segment + 4 rectangles with 6 vertices each + rlBegin(RL_TRIANGLES); - // Draw all of the 4 corners first: Upper Left Corner, Upper Right Corner, Lower Right Corner, Lower Left Corner - for(int k = 0; k < 4; ++k) // Hope the compiler is smart enough to unroll this loop + + // Draw all of the 4 corners first: Upper Left Corner, Upper Right Corner, Lower Right Corner, Lower Left Corner + for (int k = 0; k < 4; ++k) // Hope the compiler is smart enough to unroll this loop { float angle = angles[k]; const Vector2 center = centers[k]; + for (int i = 0; i < segments; i++) { rlColor4ub(color.r, color.g, color.b, color.a); - + rlVertex2f(center.x + sinf(DEG2RAD*angle)*innerRadius, center.y + cosf(DEG2RAD*angle)*innerRadius); rlVertex2f(center.x + sinf(DEG2RAD*angle)*outerRadius, center.y + cosf(DEG2RAD*angle)*outerRadius); rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength))*innerRadius, center.y + cosf(DEG2RAD*(angle + stepLength))*innerRadius); - + rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength))*innerRadius, center.y + cosf(DEG2RAD*(angle + stepLength))*innerRadius); rlVertex2f(center.x + sinf(DEG2RAD*angle)*outerRadius, center.y + cosf(DEG2RAD*angle)*outerRadius); rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength))*outerRadius, center.y + cosf(DEG2RAD*(angle + stepLength))*outerRadius); - + angle += stepLength; } } - + // Upper rectangle rlColor4ub(color.r, color.g, color.b, color.a); rlVertex2f(point[0].x, point[0].y); @@ -1034,7 +1043,7 @@ void DrawRoundedRectLines(Rectangle rec, float roundness, int segments, int line rlVertex2f(point[1].x, point[1].y); rlVertex2f(point[0].x, point[0].y); rlVertex2f(point[9].x, point[9].y); - + // Right rectangle rlColor4ub(color.r, color.g, color.b, color.a); rlVertex2f(point[10].x, point[10].y); @@ -1043,7 +1052,7 @@ void DrawRoundedRectLines(Rectangle rec, float roundness, int segments, int line rlVertex2f(point[2].x, point[2].y); rlVertex2f(point[10].x, point[10].y); rlVertex2f(point[3].x, point[3].y); - + // Lower rectangle rlColor4ub(color.r, color.g, color.b, color.a); rlVertex2f(point[13].x, point[13].y); @@ -1052,7 +1061,7 @@ void DrawRoundedRectLines(Rectangle rec, float roundness, int segments, int line rlVertex2f(point[12].x, point[12].y); rlVertex2f(point[13].x, point[13].y); rlVertex2f(point[4].x, point[4].y); - + // Left rectangle rlColor4ub(color.r, color.g, color.b, color.a); rlVertex2f(point[7].x, point[7].y); @@ -1068,12 +1077,15 @@ void DrawRoundedRectLines(Rectangle rec, float roundness, int segments, int line { // Use LINES to draw the outline if (rlCheckBufferLimit(8*segments + 4*2)) rlglDraw(); // 4 corners with 2 vertices for each segment + 4 rectangles with 2 vertices each + rlBegin(RL_LINES); + // Draw all of the 4 corners first: Upper Left Corner, Upper Right Corner, Lower Right Corner, Lower Left Corner - for(int k = 0; k < 4; ++k) // Hope the compiler is smart enough to unroll this loop + for (int k = 0; k < 4; ++k) // Hope the compiler is smart enough to unroll this loop { float angle = angles[k]; const Vector2 center = centers[k]; + for (int i = 0; i < segments; i++) { rlColor4ub(color.r, color.g, color.b, color.a); @@ -1083,11 +1095,11 @@ void DrawRoundedRectLines(Rectangle rec, float roundness, int segments, int line } } // And now the remaining 4 lines - for(int i=0; i<8; i+=2) + for(int i = 0; i < 8; i += 2) { rlColor4ub(color.r, color.g, color.b, color.a); rlVertex2f(point[i].x, point[i].y); - rlVertex2f(point[i+1].x, point[i+1].y); + rlVertex2f(point[i + 1].x, point[i + 1].y); } rlEnd(); } -- cgit v1.2.3 From a103086443b3d3a3a94ec52ef19ec9be68a0069c Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 4 Apr 2019 13:50:52 +0200 Subject: Removed trail spaces --- src/core.c | 32 ++++++++++++------------ src/models.c | 78 +++++++++++++++++++++++++++++----------------------------- src/raudio.c | 4 +-- src/raylib.h | 14 +++++------ src/rlgl.h | 28 ++++++++++----------- src/textures.c | 18 +++++++------- 6 files changed, 87 insertions(+), 87 deletions(-) (limited to 'src') diff --git a/src/core.c b/src/core.c index 7f2f7f1c..acc87292 100644 --- a/src/core.c +++ b/src/core.c @@ -760,7 +760,7 @@ bool IsWindowResized(void) return windowResized; #else return false; -#endif +#endif } // Check if window is currently hidden @@ -1684,14 +1684,14 @@ const char *GetFileName(const char *filePath) const char *GetFileNameWithoutExt(const char *filePath) { #define MAX_FILENAMEWITHOUTEXT_LENGTH 64 - + static char fileName[MAX_FILENAMEWITHOUTEXT_LENGTH]; memset(fileName, 0, MAX_FILENAMEWITHOUTEXT_LENGTH); - + strcpy(fileName, GetFileName(filePath)); // Get filename with extension - + int len = strlen(fileName); - + for (int i = 0; (i < len) && (i < MAX_FILENAMEWITHOUTEXT_LENGTH); i++) { if (fileName[i] == '.') @@ -3154,7 +3154,7 @@ static void PollInputEvents(void) gamepadAxisCount = axisCount; } } - + windowResized = false; #if defined(SUPPORT_EVENTS_WAITING) @@ -3433,7 +3433,7 @@ static void WindowSizeCallback(GLFWwindow *window, int width, int height) currentHeight = height; // NOTE: Postprocessing texture is not scaled to new size - + windowResized = true; } @@ -4279,7 +4279,7 @@ static void *EventThread(void *arg) { // Scancode to keycode mapping for US keyboards // TODO: Proabobly replace this with a keymap from the X11 to get the correct regional map for the keyboard (Currently non US keyboards will have the wrong mapping for some keys) - static const int keymap_US[] = + static const int keymap_US[] = {0,256,49,50,51,52,53,54,55,56,57,48,45,61,259,258,81,87,69,82,84, 89,85,73,79,80,91,93,257,341,65,83,68,70,71,72,74,75,76,59,39,96, 340,92,90,88,67,86,66,78,77,44,46,47,344,332,342,32,280,290,291, @@ -4298,7 +4298,7 @@ static void *EventThread(void *arg) struct input_event event; InputEventWorker *worker = (InputEventWorker *)arg; - + int touchAction = -1; bool gestureUpdate = false; int keycode; @@ -4400,7 +4400,7 @@ static void *EventThread(void *arg) if ((event.code == BTN_TOUCH) || (event.code == BTN_LEFT)) { currentMouseStateEvdev[MOUSE_LEFT_BUTTON] = event.value; - + #if defined(SUPPORT_GESTURES_SYSTEM) if (event.value > 0) touchAction = TOUCH_DOWN; else touchAction = TOUCH_UP; @@ -4415,9 +4415,9 @@ static void *EventThread(void *arg) // Keyboard button parsing if((event.code >= 1) && (event.code <= 255)) //Keyboard keys appear for codes 1 to 255 { - keycode = keymap_US[event.code & 0xFF]; // The code we get is a scancode so we look up the apropriate keycode + keycode = keymap_US[event.code & 0xFF]; // The code we get is a scancode so we look up the apropriate keycode // Make sure we got a valid keycode - if((keycode > 0) && (keycode < sizeof(currentKeyState))) + if((keycode > 0) && (keycode < sizeof(currentKeyState))) { // Store the key information for raylib to later use currentKeyStateEvdev[keycode] = event.value; @@ -4449,22 +4449,22 @@ static void *EventThread(void *arg) gestureEvent.pointCount = 0; gestureEvent.touchAction = touchAction; - + if (touchPosition[0].x >= 0) gestureEvent.pointCount++; if (touchPosition[1].x >= 0) gestureEvent.pointCount++; if (touchPosition[2].x >= 0) gestureEvent.pointCount++; if (touchPosition[3].x >= 0) gestureEvent.pointCount++; - + gestureEvent.pointerId[0] = 0; gestureEvent.pointerId[1] = 1; gestureEvent.pointerId[2] = 2; gestureEvent.pointerId[3] = 3; - + gestureEvent.position[0] = touchPosition[0]; gestureEvent.position[1] = touchPosition[1]; gestureEvent.position[2] = touchPosition[2]; gestureEvent.position[3] = touchPosition[3]; - + ProcessGestureEvent(gestureEvent); #endif } diff --git a/src/models.c b/src/models.c index 632aca2b..239ab5d8 100644 --- a/src/models.c +++ b/src/models.c @@ -624,19 +624,19 @@ Model LoadModel(const char *fileName) #if defined(SUPPORT_FILEFORMAT_IQM) if (IsFileExtension(fileName, ".iqm")) model = LoadIQM(fileName); #endif - + // Make sure model transform is set to identity matrix! model.transform = MatrixIdentity(); - if (model.meshCount == 0) + if (model.meshCount == 0) { TraceLog(LOG_WARNING, "[%s] No meshes can be loaded, default to cube mesh", fileName); - + model.meshCount = 1; model.meshes = (Mesh *)calloc(model.meshCount, sizeof(Mesh)); model.meshes[0] = GenMeshCube(1.0f, 1.0f, 1.0f); } - else + else { // Upload vertex data to GPU (static mesh) for (int i = 0; i < model.meshCount; i++) rlLoadMesh(&model.meshes[i], false); @@ -645,11 +645,11 @@ Model LoadModel(const char *fileName) if (model.materialCount == 0) { TraceLog(LOG_WARNING, "[%s] No materials can be loaded, default to white material", fileName); - + model.materialCount = 1; model.materials = (Material *)calloc(model.materialCount, sizeof(Material)); model.materials[0] = LoadMaterialDefault(); - + model.meshMaterial = (int *)calloc(model.meshCount, sizeof(int)); } @@ -665,15 +665,15 @@ Model LoadModelFromMesh(Mesh mesh) Model model = { 0 }; model.transform = MatrixIdentity(); - + model.meshCount = 1; model.meshes = (Mesh *)malloc(model.meshCount*sizeof(Mesh)); model.meshes[0] = mesh; - + model.materialCount = 1; model.materials = (Material *)malloc(model.materialCount*sizeof(Material)); model.materials[0] = LoadMaterialDefault(); - + model.meshMaterial = (int *)malloc(model.meshCount*sizeof(int)); model.meshMaterial[0] = 0; // First material index @@ -685,11 +685,11 @@ void UnloadModel(Model model) { for (int i = 0; i < model.meshCount; i++) UnloadMesh(&model.meshes[i]); for (int i = 0; i < model.materialCount; i++) UnloadMaterial(model.materials[i]); - + free(model.meshes); free(model.materials); free(model.meshMaterial); - + // Unload animation data free(model.bones); free(model.bindPose); @@ -1817,11 +1817,11 @@ Material LoadMaterial(const char *fileName) { tinyobj_material_t *materials; unsigned int materialCount = 0; - + int result = tinyobj_parse_mtl_file(&materials, &materialCount, fileName); - + // TODO: Process materials to return - + tinyobj_materials_free(materials, materialCount); } #else @@ -1886,7 +1886,7 @@ void DrawModelEx(Model model, Vector3 position, Vector3 rotationAxis, float rota // Combine model transformation matrix (model.transform) with matrix generated by function parameters (matTransform) model.transform = MatrixMultiply(model.transform, matTransform); - for (int i = 0; i < model.meshCount; i++) + for (int i = 0; i < model.meshCount; i++) { model.materials[model.meshMaterial[i]].maps[MAP_DIFFUSE].color = tint; rlDrawMesh(model.meshes[i], model.materials[model.meshMaterial[i]], model.transform); @@ -2246,7 +2246,7 @@ BoundingBox MeshBoundingBox(Mesh mesh) // Get min and max vertex to construct bounds (AABB) Vector3 minVertex = { 0 }; Vector3 maxVertex = { 0 }; - + printf("Mesh vertex count: %i\n", mesh.vertexCount); if (mesh.vertices != NULL) @@ -2402,20 +2402,20 @@ static Model LoadOBJ(const char *fileName) { unsigned int flags = TINYOBJ_FLAG_TRIANGULATE; int ret = tinyobj_parse_obj(&attrib, &meshes, &meshCount, &materials, &materialCount, data, dataLength, flags); - + if (ret != TINYOBJ_SUCCESS) TraceLog(LOG_WARNING, "[%s] Model data could not be loaded", fileName); else TraceLog(LOG_INFO, "[%s] Model data loaded successfully: %i meshes / %i materials", fileName, meshCount, materialCount); - + // Init model meshes array model.meshCount = meshCount; model.meshes = (Mesh *)malloc(model.meshCount*sizeof(Mesh)); - + // Init model materials array model.materialCount = materialCount; model.materials = (Material *)malloc(model.materialCount*sizeof(Material)); model.meshMaterial = (int *)calloc(model.meshCount, sizeof(int)); - - /* + + /* // Multiple meshes data reference // NOTE: They are provided as a faces offset typedef struct { @@ -2424,7 +2424,7 @@ static Model LoadOBJ(const char *fileName) unsigned int length; } tinyobj_shape_t; */ - + // Init model meshes for (int m = 0; m < 1; m++) { @@ -2435,25 +2435,25 @@ static Model LoadOBJ(const char *fileName) mesh.vertices = (float *)malloc(mesh.vertexCount*3*sizeof(float)); mesh.texcoords = (float *)malloc(mesh.vertexCount*2*sizeof(float)); mesh.normals = (float *)malloc(mesh.vertexCount*3*sizeof(float)); - + int vCount = 0; int vtCount = 0; int vnCount = 0; - + for (int f = 0; f < attrib.num_faces; f++) { // Get indices for the face tinyobj_vertex_index_t idx0 = attrib.faces[3*f + 0]; tinyobj_vertex_index_t idx1 = attrib.faces[3*f + 1]; tinyobj_vertex_index_t idx2 = attrib.faces[3*f + 2]; - + // TraceLog(LOG_DEBUG, "Face %i index: v %i/%i/%i . vt %i/%i/%i . vn %i/%i/%i\n", f, idx0.v_idx, idx1.v_idx, idx2.v_idx, idx0.vt_idx, idx1.vt_idx, idx2.vt_idx, idx0.vn_idx, idx1.vn_idx, idx2.vn_idx); - + // Fill vertices buffer (float) using vertex index of the face for (int v = 0; v < 3; v++) { mesh.vertices[vCount + v] = attrib.vertices[idx0.v_idx*3 + v]; } vCount +=3; for (int v = 0; v < 3; v++) { mesh.vertices[vCount + v] = attrib.vertices[idx1.v_idx*3 + v]; } vCount +=3; for (int v = 0; v < 3; v++) { mesh.vertices[vCount + v] = attrib.vertices[idx2.v_idx*3 + v]; } vCount +=3; - + // Fill texcoords buffer (float) using vertex index of the face // NOTE: Y-coordinate must be flipped upside-down mesh.texcoords[vtCount + 0] = attrib.texcoords[idx0.vt_idx*2 + 0]; @@ -2462,7 +2462,7 @@ static Model LoadOBJ(const char *fileName) mesh.texcoords[vtCount + 1] = 1.0f - attrib.texcoords[idx1.vt_idx*2 + 1]; vtCount += 2; mesh.texcoords[vtCount + 0] = attrib.texcoords[idx2.vt_idx*2 + 0]; mesh.texcoords[vtCount + 1] = 1.0f - attrib.texcoords[idx2.vt_idx*2 + 1]; vtCount += 2; - + // Fill normals buffer (float) using vertex index of the face for (int v = 0; v < 3; v++) { mesh.normals[vnCount + v] = attrib.normals[idx0.vn_idx*3 + v]; } vnCount +=3; for (int v = 0; v < 3; v++) { mesh.normals[vnCount + v] = attrib.normals[idx1.vn_idx*3 + v]; } vnCount +=3; @@ -2481,7 +2481,7 @@ static Model LoadOBJ(const char *fileName) // Init material to default // NOTE: Uses default shader, only MAP_DIFFUSE supported model.materials[m] = LoadMaterialDefault(); - + /* typedef struct { char *name; @@ -2508,19 +2508,19 @@ static Model LoadOBJ(const char *fileName) char *alpha_texname; // map_d } tinyobj_material_t; */ - + model.materials[m].maps[MAP_DIFFUSE].texture = LoadTexture(materials[m].diffuse_texname); //char *diffuse_texname; // map_Kd model.materials[m].maps[MAP_DIFFUSE].color = (Color){ (float)(materials[m].diffuse[0]*255.0f), (float)(materials[m].diffuse[1]*255.0f), (float)(materials[m].diffuse[2]*255.0f), 255 }; //float diffuse[3]; model.materials[m].maps[MAP_DIFFUSE].value = 0.0f; - + model.materials[m].maps[MAP_SPECULAR].texture = LoadTexture(materials[m].specular_texname); //char *specular_texname; // map_Ks model.materials[m].maps[MAP_SPECULAR].color = (Color){ (float)(materials[m].specular[0]*255.0f), (float)(materials[m].specular[1]*255.0f), (float)(materials[m].specular[2]*255.0f), 255 }; //float specular[3]; model.materials[m].maps[MAP_SPECULAR].value = 0.0f; - + model.materials[m].maps[MAP_NORMAL].texture = LoadTexture(materials[m].bump_texname); //char *bump_texname; // map_bump, bump model.materials[m].maps[MAP_NORMAL].color = WHITE; model.materials[m].maps[MAP_NORMAL].value = materials[m].shininess; - + model.materials[m].maps[MAP_EMISSION].color = (Color){ (float)(materials[m].emission[0]*255.0f), (float)(materials[m].emission[1]*255.0f), (float)(materials[m].emission[2]*255.0f), 255 }; //float emission[3]; model.materials[m].maps[MAP_HEIGHT].texture = LoadTexture(materials[m].displacement_texname); //char *displacement_texname; // disp @@ -2579,7 +2579,7 @@ static Model LoadIQM(const char *fileName) } IQMTriangle; // NOTE: Adjacency unused by default - typedef struct IQMAdjacency { + typedef struct IQMAdjacency { unsigned int triangle[3]; } IQMAdjacency; @@ -2677,7 +2677,7 @@ static Model LoadIQM(const char *fileName) model.meshCount = iqm.num_meshes; model.meshes = malloc(sizeof(Mesh)*iqm.num_meshes); - + char name[MESH_NAME_LENGTH]; for (int i = 0; i < iqm.num_meshes; i++) @@ -2685,17 +2685,17 @@ static Model LoadIQM(const char *fileName) fseek(iqmFile,iqm.ofs_text+imesh[i].name,SEEK_SET); fread(name, sizeof(char)*MESH_NAME_LENGTH, 1, iqmFile); // Mesh name not used... model.meshes[i].vertexCount = imesh[i].num_vertexes; - + model.meshes[i].vertices = malloc(sizeof(float)*imesh[i].num_vertexes*3); // Default vertex positions model.meshes[i].normals = malloc(sizeof(float)*imesh[i].num_vertexes*3); // Default vertex normals model.meshes[i].texcoords = malloc(sizeof(float)*imesh[i].num_vertexes*2); // Default vertex texcoords - + model.meshes[i].boneIds = malloc(sizeof(int)*imesh[i].num_vertexes*4); // Up-to 4 bones supported! model.meshes[i].boneWeights = malloc(sizeof(float)*imesh[i].num_vertexes*4); // Up-to 4 bones supported! - + model.meshes[i].triangleCount = imesh[i].num_triangles; model.meshes[i].indices = malloc(sizeof(unsigned short)*imesh[i].num_triangles*3); - + // Animated verted data, what we actually process for rendering // NOTE: Animated vertex should be re-uploaded to GPU (if not using GPU skinning) model.meshes[i].animVertices = malloc(sizeof(float)*imesh[i].num_vertexes*3); diff --git a/src/raudio.c b/src/raudio.c index 1c153009..d360b2d3 100644 --- a/src/raudio.c +++ b/src/raudio.c @@ -525,7 +525,7 @@ void InitAudioDevice(void) TraceLog(LOG_INFO, "Audio channels: %d -> %d", device.playback.channels, device.playback.internalChannels); TraceLog(LOG_INFO, "Audio sample rate: %d -> %d", device.sampleRate, device.playback.internalSampleRate); TraceLog(LOG_INFO, "Audio buffer size: %d", device.playback.internalBufferSizeInFrames); - + isAudioInitialized = MA_TRUE; } @@ -587,7 +587,7 @@ AudioBuffer *CreateAudioBuffer(ma_format format, ma_uint32 channels, ma_uint32 s dspConfig.pUserData = audioBuffer; dspConfig.allowDynamicSampleRate = MA_TRUE; // <-- Required for pitch shifting. ma_result result = ma_pcm_converter_init(&dspConfig, &audioBuffer->dsp); - + if (result != MA_SUCCESS) { TraceLog(LOG_ERROR, "CreateAudioBuffer() : Failed to create data conversion pipeline"); diff --git a/src/raylib.h b/src/raylib.h index 93965038..c365fa47 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -339,7 +339,7 @@ typedef struct Material { // Transformation properties typedef struct Transform { - Vector3 translation; // Translation + Vector3 translation; // Translation Quaternion rotation; // Rotation Vector3 scale; // Scale } Transform; @@ -353,14 +353,14 @@ typedef struct BoneInfo { // Model type typedef struct Model { Matrix transform; // Local transform matrix - + int meshCount; // Number of meshes Mesh *meshes; // Meshes array int materialCount; // Number of materials Material *materials; // Materials array int *meshMaterial; // Mesh material number - + // Animation data int boneCount; // Number of bones BoneInfo *bones; // Bones information (skeleton) @@ -371,7 +371,7 @@ typedef struct Model { typedef struct ModelAnimation { int boneCount; // Number of bones BoneInfo *bones; // Bones information (skeleton) - + int frameCount; // Number of animation frames Transform **framePoses; // Poses array by frame } ModelAnimation; @@ -1082,8 +1082,8 @@ RLAPI void DrawRectangleGradientH(int posX, int posY, int width, int height, Col RLAPI void DrawRectangleGradientEx(Rectangle rec, Color col1, Color col2, Color col3, Color col4); // Draw a gradient-filled rectangle with custom vertex colors RLAPI void DrawRectangleLines(int posX, int posY, int width, int height, Color color); // Draw rectangle outline RLAPI void DrawRectangleLinesEx(Rectangle rec, int lineThick, Color color); // Draw rectangle outline with extended parameters -RLAPI void DrawRoundedRect(Rectangle rec, float roundness, int segments, Color color); // Draw rectangle with rounded edges -RLAPI void DrawRoundedRectLines(Rectangle rec, float roundness, int segments, int lineThick, Color color); // Draw rounded rectangle outline +RLAPI void DrawRectangleRounded(Rectangle rec, float roundness, int segments, Color color); // Draw rectangle with rounded edges +RLAPI void DrawRectangleRoundedLines(Rectangle rec, float roundness, int segments, int lineThick, Color color); // Draw rectangle with rounded edges outline RLAPI void DrawTriangle(Vector2 v1, Vector2 v2, Vector2 v3, Color color); // Draw a color-filled triangle RLAPI void DrawTriangleLines(Vector2 v1, Vector2 v2, Vector2 v3, Color color); // Draw triangle outline RLAPI void DrawPoly(Vector2 center, int sides, float radius, float rotation, Color color); // Draw a regular polygon (Vector version) @@ -1201,7 +1201,7 @@ RLAPI void DrawFPS(int posX, int posY); RLAPI void DrawText(const char *text, int posX, int posY, int fontSize, Color color); // Draw text (using default font) RLAPI void DrawTextEx(Font font, const char *text, Vector2 position, float fontSize, float spacing, Color tint); // Draw text using font and additional parameters RLAPI void DrawTextRec(Font font, const char *text, Rectangle rec, float fontSize, float spacing, bool wordWrap, Color tint); // Draw text using font inside rectangle limits -RLAPI void DrawTextRecEx(Font font, const char *text, Rectangle rec, float fontSize, float spacing, bool wordWrap, Color tint, +RLAPI void DrawTextRecEx(Font font, const char *text, Rectangle rec, float fontSize, float spacing, bool wordWrap, Color tint, int selectStart, int selectLength, Color selectText, Color selectBack); // Draw text using font inside rectangle limits with support for text selection // Text misc. functions diff --git a/src/rlgl.h b/src/rlgl.h index 8cc4c590..3f305462 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -1130,22 +1130,22 @@ void rlBegin(int mode) // Make sure current draws[i].vertexCount is aligned a multiple of 4, // that way, following QUADS drawing will keep aligned with index processing // It implies adding some extra alignment vertex at the end of the draw, - // those vertex are not processed but they are considered as an additional offset + // those vertex are not processed but they are considered as an additional offset // for the next set of vertex to be drawn if (draws[drawsCounter - 1].mode == RL_LINES) draws[drawsCounter - 1].vertexAlignment = ((draws[drawsCounter - 1].vertexCount < 4)? draws[drawsCounter - 1].vertexCount : draws[drawsCounter - 1].vertexCount%4); else if (draws[drawsCounter - 1].mode == RL_TRIANGLES) draws[drawsCounter - 1].vertexAlignment = ((draws[drawsCounter - 1].vertexCount < 4)? 1 : (4 - (draws[drawsCounter - 1].vertexCount%4))); - + if (rlCheckBufferLimit(draws[drawsCounter - 1].vertexAlignment)) rlglDraw(); else { vertexData[currentBuffer].vCounter += draws[drawsCounter - 1].vertexAlignment; vertexData[currentBuffer].cCounter += draws[drawsCounter - 1].vertexAlignment; vertexData[currentBuffer].tcCounter += draws[drawsCounter - 1].vertexAlignment; - + drawsCounter++; } } - + if (drawsCounter >= MAX_DRAWCALL_REGISTERED) rlglDraw(); draws[drawsCounter - 1].mode = mode; @@ -1301,22 +1301,22 @@ void rlEnableTexture(unsigned int id) // Make sure current draws[i].vertexCount is aligned a multiple of 4, // that way, following QUADS drawing will keep aligned with index processing // It implies adding some extra alignment vertex at the end of the draw, - // those vertex are not processed but they are considered as an additional offset + // those vertex are not processed but they are considered as an additional offset // for the next set of vertex to be drawn if (draws[drawsCounter - 1].mode == RL_LINES) draws[drawsCounter - 1].vertexAlignment = ((draws[drawsCounter - 1].vertexCount < 4)? draws[drawsCounter - 1].vertexCount : draws[drawsCounter - 1].vertexCount%4); else if (draws[drawsCounter - 1].mode == RL_TRIANGLES) draws[drawsCounter - 1].vertexAlignment = ((draws[drawsCounter - 1].vertexCount < 4)? 1 : (4 - (draws[drawsCounter - 1].vertexCount%4))); - + if (rlCheckBufferLimit(draws[drawsCounter - 1].vertexAlignment)) rlglDraw(); else { vertexData[currentBuffer].vCounter += draws[drawsCounter - 1].vertexAlignment; vertexData[currentBuffer].cCounter += draws[drawsCounter - 1].vertexAlignment; vertexData[currentBuffer].tcCounter += draws[drawsCounter - 1].vertexAlignment; - + drawsCounter++; } } - + if (drawsCounter >= MAX_DRAWCALL_REGISTERED) rlglDraw(); draws[drawsCounter - 1].textureId = id; @@ -2044,7 +2044,7 @@ unsigned int rlLoadTexture(void *data, int width, int height, int format, int mi unsigned int rlLoadTextureDepth(int width, int height, int bits, bool useRenderBuffer) { unsigned int id = 0; - + #if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) unsigned int glInternalFormat = GL_DEPTH_COMPONENT16; @@ -2103,7 +2103,7 @@ unsigned int rlLoadTextureCubemap(void *data, int size, int format) { unsigned int cubemapId = 0; unsigned int dataSize = GetPixelDataSize(size, size, format); - + #if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) glGenTextures(1, &cubemapId); glBindTexture(GL_TEXTURE_CUBE_MAP, cubemapId); @@ -2305,7 +2305,7 @@ void rlRenderTextureAttach(RenderTexture2D target, unsigned int id, int attachTy bool rlRenderTextureComplete(RenderTexture target) { bool result = false; - + #if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) glBindFramebuffer(GL_FRAMEBUFFER, target.id); @@ -4196,7 +4196,7 @@ static void DrawBuffersDefault(void) glUniformMatrix4fv(currentShader.locs[LOC_MATRIX_MVP], 1, false, MatrixToFloat(matMVP)); glUniform4f(currentShader.locs[LOC_COLOR_DIFFUSE], 1.0f, 1.0f, 1.0f, 1.0f); glUniform1i(currentShader.locs[LOC_MAP_DIFFUSE], 0); // Provided value refers to the texture unit (active) - + // TODO: Support additional texture units on custom shader //if (currentShader->locs[LOC_MAP_SPECULAR] > 0) glUniform1i(currentShader.locs[LOC_MAP_SPECULAR], 1); //if (currentShader->locs[LOC_MAP_NORMAL] > 0) glUniform1i(currentShader.locs[LOC_MAP_NORMAL], 2); @@ -4231,7 +4231,7 @@ static void DrawBuffersDefault(void) for (int i = 0; i < drawsCounter; i++) { glBindTexture(GL_TEXTURE_2D, draws[i].textureId); - + // TODO: Find some way to bind additional textures --> Use global texture IDs? Register them on draw[i]? //if (currentShader->locs[LOC_MAP_SPECULAR] > 0) { glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, textureUnit1_id); } //if (currentShader->locs[LOC_MAP_SPECULAR] > 0) { glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, textureUnit2_id); } @@ -4248,7 +4248,7 @@ static void DrawBuffersDefault(void) glDrawElements(GL_TRIANGLES, draws[i].vertexCount/4*6, GL_UNSIGNED_SHORT, (GLvoid *)(sizeof(GLushort)*vertexOffset/4*6)); #endif } - + vertexOffset += (draws[i].vertexCount + draws[i].vertexAlignment); } diff --git a/src/textures.c b/src/textures.c index 38995f11..cd0bd208 100644 --- a/src/textures.c +++ b/src/textures.c @@ -181,7 +181,7 @@ static Image LoadASTC(const char *fileName); // Load ASTC file Image LoadImage(const char *fileName) { Image image = { 0 }; - + #if defined(SUPPORT_FILEFORMAT_PNG) || \ defined(SUPPORT_FILEFORMAT_BMP) || \ defined(SUPPORT_FILEFORMAT_TGA) || \ @@ -744,7 +744,7 @@ Image GetTextureData(Texture2D texture) RLAPI Image GetScreenData(void) { Image image = { 0 }; - + image.width = GetScreenWidth(); image.height = GetScreenHeight(); image.mipmaps = 1; @@ -1411,13 +1411,13 @@ void ImageResizeNN(Image *image,int newWidth,int newHeight) void ImageResizeCanvas(Image *image, int newWidth,int newHeight, int offsetX, int offsetY, Color color) { // TODO: Review different scaling situations - + if ((newWidth != image->width) || (newHeight != image->height)) { if ((newWidth > image->width) && (newHeight > image->height)) { Image imTemp = GenImageColor(newWidth, newHeight, color); - + Rectangle srcRec = { 0.0f, 0.0f, (float)image->width, (float)image->height }; Rectangle dstRec = { (float)offsetX, (float)offsetY, (float)srcRec.width, (float)srcRec.height }; @@ -1434,23 +1434,23 @@ void ImageResizeCanvas(Image *image, int newWidth,int newHeight, int offsetX, in else // One side is bigger and the other is smaller { Image imTemp = GenImageColor(newWidth, newHeight, color); - + Rectangle srcRec = { 0.0f, 0.0f, (float)image->width, (float)image->height }; Rectangle dstRec = { (float)offsetX, (float)offsetY, (float)newWidth, (float)newHeight }; - + if (newWidth < image->width) { srcRec.x = offsetX; srcRec.width = newWidth; - + dstRec.x = 0.0f; } - + if (newHeight < image->height) { srcRec.y = offsetY; srcRec.height = newHeight; - + dstRec.y = 0.0f; } -- cgit v1.2.3 From 28b9de661d49911f7c5b7996576c7faeea0684d5 Mon Sep 17 00:00:00 2001 From: Ray Date: Fri, 5 Apr 2019 13:12:54 +0200 Subject: Minor tweaks --- src/core.c | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) (limited to 'src') diff --git a/src/core.c b/src/core.c index acc87292..b0c0658d 100644 --- a/src/core.c +++ b/src/core.c @@ -3191,7 +3191,7 @@ static void PollInputEvents(void) } else currentGamepadState[i][j] = 0; - //printf("Gamepad %d, button %d: Digital: %d, Analog: %g\n", gamepadState.index, j, gamepadState.digitalButton[j], gamepadState.analogButton[j]); + //TraceLog(LOG_DEBUG, "Gamepad %d, button %d: Digital: %d, Analog: %g", gamepadState.index, j, gamepadState.digitalButton[j], gamepadState.analogButton[j]); } // Register axis data for every connected gamepad @@ -3792,14 +3792,14 @@ static EM_BOOL EmscriptenTouchCallback(int eventType, const EmscriptenTouchEvent y = touchEvent->touches[i].canvasY; } - printf("%s, numTouches: %d %s%s%s%s\n", emscripten_event_type_to_string(eventType), event->numTouches, + TraceLog(LOG_DEBUG, "%s, numTouches: %d %s%s%s%s", emscripten_event_type_to_string(eventType), event->numTouches, event->ctrlKey? " CTRL" : "", event->shiftKey? " SHIFT" : "", event->altKey? " ALT" : "", event->metaKey? " META" : ""); for (int i = 0; i < event->numTouches; ++i) { const EmscriptenTouchPoint *t = &event->touches[i]; - printf(" %ld: screen: (%ld,%ld), client: (%ld,%ld), page: (%ld,%ld), isChanged: %d, onTarget: %d, canvas: (%ld, %ld)\n", + TraceLog(LOG_DEBUG, " %ld: screen: (%ld,%ld), client: (%ld,%ld), page: (%ld,%ld), isChanged: %d, onTarget: %d, canvas: (%ld, %ld)", t->identifier, t->screenX, t->screenY, t->clientX, t->clientY, t->pageX, t->pageY, t->isChanged, t->onTarget, t->canvasX, t->canvasY); } */ @@ -3858,12 +3858,12 @@ static EM_BOOL EmscriptenTouchCallback(int eventType, const EmscriptenTouchEvent static EM_BOOL EmscriptenGamepadCallback(int eventType, const EmscriptenGamepadEvent *gamepadEvent, void *userData) { /* - printf("%s: timeStamp: %g, connected: %d, index: %ld, numAxes: %d, numButtons: %d, id: \"%s\", mapping: \"%s\"\n", + TraceLog(LOG_DEBUG, "%s: timeStamp: %g, connected: %d, index: %ld, numAxes: %d, numButtons: %d, id: \"%s\", mapping: \"%s\"", eventType != 0? emscripten_event_type_to_string(eventType) : "Gamepad state", gamepadEvent->timestamp, gamepadEvent->connected, gamepadEvent->index, gamepadEvent->numAxes, gamepadEvent->numButtons, gamepadEvent->id, gamepadEvent->mapping); - for(int i = 0; i < gamepadEvent->numAxes; ++i) printf("Axis %d: %g\n", i, gamepadEvent->axis[i]); - for(int i = 0; i < gamepadEvent->numButtons; ++i) printf("Button %d: Digital: %d, Analog: %g\n", i, gamepadEvent->digitalButton[i], gamepadEvent->analogButton[i]); + for(int i = 0; i < gamepadEvent->numAxes; ++i) TraceLog(LOG_DEBUG, "Axis %d: %g", i, gamepadEvent->axis[i]); + for(int i = 0; i < gamepadEvent->numButtons; ++i) TraceLog(LOG_DEBUG, "Button %d: Digital: %d, Analog: %g", i, gamepadEvent->digitalButton[i], gamepadEvent->analogButton[i]); */ if ((gamepadEvent->connected) && (gamepadEvent->index < MAX_GAMEPADS)) gamepadReady[gamepadEvent->index] = true; @@ -3939,17 +3939,13 @@ static void ProcessKeyboard(void) for (int i = 0; i < 512; i++) currentKeyState[i] = 0; // Check keys from event input workers (This is the new keyboard reading method) - for (int i = 0; i < 512; i++)currentKeyState[i] = currentKeyStateEvdev[i]; + for (int i = 0; i < 512; i++) currentKeyState[i] = currentKeyStateEvdev[i]; // Fill all read bytes (looking for keys) for (int i = 0; i < bufferByteCount; i++) { TraceLog(LOG_DEBUG, "Bytes on keysBuffer: %i", bufferByteCount); - //printf("Key(s) bytes: "); - //for (int i = 0; i < bufferByteCount; i++) printf("0x%02x ", keysBuffer[i]); - //printf("\n"); - // NOTE: If (key == 0x1b), depending on next key, it could be a special keymap code! // Up -> 1b 5b 41 / Left -> 1b 5b 44 / Right -> 1b 5b 43 / Down -> 1b 5b 42 if (keysBuffer[i] == 0x1b) -- cgit v1.2.3 From a728376cdf8e76c33e36dc3be3b18d99d38be758 Mon Sep 17 00:00:00 2001 From: Ray Date: Fri, 5 Apr 2019 13:13:10 +0200 Subject: Rename enum type --- src/rlgl.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/rlgl.h b/src/rlgl.h index 3f305462..3d433377 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -386,7 +386,7 @@ typedef unsigned char byte; MAP_IRRADIANCE, // NOTE: Uses GL_TEXTURE_CUBE_MAP MAP_PREFILTER, // NOTE: Uses GL_TEXTURE_CUBE_MAP MAP_BRDF - } TexmapIndex; + } MaterialMapType; #define MAP_DIFFUSE MAP_ALBEDO #define MAP_SPECULAR MAP_METALNESS -- cgit v1.2.3 From 92733d6695e0cdab3b42972f2cd6ed48d98ec689 Mon Sep 17 00:00:00 2001 From: Ray Date: Fri, 5 Apr 2019 13:15:56 +0200 Subject: BIG UPDATE: New models functions for animations! Multiple functions added and some reviewed to adapt to the new multi-mesh, multi-material and animated models. --- src/models.c | 652 ++++++++++++++++++++++++++++++++++++++++++++--------------- src/raylib.h | 33 +-- 2 files changed, 514 insertions(+), 171 deletions(-) (limited to 'src') diff --git a/src/models.c b/src/models.c index 239ab5d8..e437a0ab 100644 --- a/src/models.c +++ b/src/models.c @@ -697,6 +697,18 @@ void UnloadModel(Model model) TraceLog(LOG_INFO, "Unloaded model data from RAM and VRAM"); } +// Load meshes from model file +Mesh *LoadMeshes(const char *fileName, int *meshCount) +{ + Mesh *meshes = NULL; + int count = 0; + + // TODO: Load meshes from file (OBJ, IQM, GLTF) + + *meshCount = count; + return meshes; +} + // Unload mesh from memory (RAM and/or VRAM) void UnloadMesh(Mesh *mesh) { @@ -759,6 +771,386 @@ void ExportMesh(Mesh mesh, const char *fileName) else TraceLog(LOG_WARNING, "Mesh could not be exported."); } +// Load materials from model file +Material *LoadMaterials(const char *fileName, int *materialCount) +{ + Material *materials = NULL; + unsigned int count = 0; + + // TODO: Support IQM and GLTF for materials parsing + +#if defined(SUPPORT_FILEFORMAT_MTL) + if (IsFileExtension(fileName, ".mtl")) + { + tinyobj_material_t *mats; + + int result = tinyobj_parse_mtl_file(&mats, &count, fileName); + + // TODO: Process materials to return + + tinyobj_materials_free(mats, count); + } +#else + TraceLog(LOG_WARNING, "[%s] Materials file not supported", fileName); +#endif + + // Set materials shader to default (DIFFUSE, SPECULAR, NORMAL) + for (int i = 0; i < count; i++) materials[i].shader = GetShaderDefault(); + + *materialCount = count; + return materials; +} + +// Load default material (Supports: DIFFUSE, SPECULAR, NORMAL maps) +Material LoadMaterialDefault(void) +{ + Material material = { 0 }; + + material.shader = GetShaderDefault(); + material.maps[MAP_DIFFUSE].texture = GetTextureDefault(); // White texture (1x1 pixel) + //material.maps[MAP_NORMAL].texture; // NOTE: By default, not set + //material.maps[MAP_SPECULAR].texture; // NOTE: By default, not set + + material.maps[MAP_DIFFUSE].color = WHITE; // Diffuse color + material.maps[MAP_SPECULAR].color = WHITE; // Specular color + + return material; +} + +// Unload material from memory +void UnloadMaterial(Material material) +{ + // Unload material shader (avoid unloading default shader, managed by raylib) + if (material.shader.id != GetShaderDefault().id) UnloadShader(material.shader); + + // Unload loaded texture maps (avoid unloading default texture, managed by raylib) + for (int i = 0; i < MAX_MATERIAL_MAPS; i++) + { + if (material.maps[i].texture.id != GetTextureDefault().id) rlDeleteTextures(material.maps[i].texture.id); + } +} + +// Set texture for a material map type (MAP_DIFFUSE, MAP_SPECULAR...) +// NOTE: Previous texture should be manually unloaded +void SetMaterialTexture(Material *material, int mapType, Texture2D texture) +{ + material->maps[mapType].texture = texture; +} + +// Set the material for a mesh +void SetModelMeshMaterial(Model *model, int meshId, int materialId) +{ + if (meshId >= model->meshCount) TraceLog(LOG_WARNING, "Mesh id greater than mesh count"); + else if (materialId >= model->materialCount) TraceLog(LOG_WARNING,"Material id greater than material count"); + else model->meshMaterial[meshId] = materialId; +} + +// Load model animations from file +ModelAnimation *LoadModelAnimations(const char *filename, int *animCount) +{ + ModelAnimation *animations = (ModelAnimation *)malloc(1*sizeof(ModelAnimation)); + int count = 1; + + #define IQM_MAGIC "INTERQUAKEMODEL" // IQM file magic number + #define IQM_VERSION 2 // only IQM version 2 supported + + typedef struct IQMHeader { + char magic[16]; + unsigned int version; + unsigned int filesize; + unsigned int flags; + unsigned int num_text, ofs_text; + unsigned int num_meshes, ofs_meshes; + unsigned int num_vertexarrays, num_vertexes, ofs_vertexarrays; + unsigned int num_triangles, ofs_triangles, ofs_adjacency; + unsigned int num_joints, ofs_joints; + unsigned int num_poses, ofs_poses; + unsigned int num_anims, ofs_anims; + unsigned int num_frames, num_framechannels, ofs_frames, ofs_bounds; + unsigned int num_comment, ofs_comment; + unsigned int num_extensions, ofs_extensions; + } IQMHeader; + + typedef struct IQMPose { + int parent; + unsigned int mask; + float channeloffset[10]; + float channelscale[10]; + } IQMPose; + + typedef struct IQMAnim { + unsigned int name; + unsigned int first_frame, num_frames; + float framerate; + unsigned int flags; + } IQMAnim; + + ModelAnimation animation = { 0 }; + + FILE *iqmFile; + IQMHeader iqm; + + iqmFile = fopen(filename,"rb"); + + if (!iqmFile) + { + TraceLog(LOG_ERROR, "[%s] Unable to open file", filename); + } + + // header + fread(&iqm, sizeof(IQMHeader), 1, iqmFile); + + if (strncmp(iqm.magic, IQM_MAGIC, sizeof(IQM_MAGIC))) + { + TraceLog(LOG_ERROR, "Magic Number \"%s\"does not match.", iqm.magic); + fclose(iqmFile); + } + + if (iqm.version != IQM_VERSION) + { + TraceLog(LOG_ERROR, "IQM version %i is incorrect.", iqm.version); + fclose(iqmFile); + } + + // header + if (iqm.num_anims > 1) TraceLog(LOG_WARNING, "More than 1 animation in file, only the first one will be loaded"); + + // bones + IQMPose *poses; + poses = malloc(sizeof(IQMPose)*iqm.num_poses); + fseek(iqmFile, iqm.ofs_poses, SEEK_SET); + fread(poses, sizeof(IQMPose)*iqm.num_poses, 1, iqmFile); + + animation.boneCount = iqm.num_poses; + animation.bones = malloc(sizeof(BoneInfo)*iqm.num_poses); + + for (int j = 0; j < iqm.num_poses; j++) + { + strcpy(animation.bones[j].name, "ANIMJOINTNAME"); + animation.bones[j].parent = poses[j].parent; + } + + // animations + IQMAnim anim = {0}; + fseek(iqmFile, iqm.ofs_anims, SEEK_SET); + fread(&anim, sizeof(IQMAnim), 1, iqmFile); + + animation.frameCount = anim.num_frames; + //animation.framerate = anim.framerate; + + // frameposes + unsigned short *framedata = malloc(sizeof(unsigned short)*iqm.num_frames*iqm.num_framechannels); + fseek(iqmFile, iqm.ofs_frames, SEEK_SET); + fread(framedata, sizeof(unsigned short)*iqm.num_frames*iqm.num_framechannels, 1, iqmFile); + + animation.framePoses = malloc(sizeof(Transform*)*anim.num_frames); + for (int j = 0; j < anim.num_frames; j++) animation.framePoses[j] = malloc(sizeof(Transform)*iqm.num_poses); + + int dcounter = anim.first_frame*iqm.num_framechannels; + + for (int frame = 0; frame < anim.num_frames; frame++) + { + for (int i = 0; i < iqm.num_poses; i++) + { + animation.framePoses[frame][i].translation.x = poses[i].channeloffset[0]; + + if (poses[i].mask & 0x01) + { + animation.framePoses[frame][i].translation.x += framedata[dcounter]*poses[i].channelscale[0]; + dcounter++; + } + + animation.framePoses[frame][i].translation.y = poses[i].channeloffset[1]; + + if (poses[i].mask & 0x02) + { + animation.framePoses[frame][i].translation.y += framedata[dcounter]*poses[i].channelscale[1]; + dcounter++; + } + + animation.framePoses[frame][i].translation.z = poses[i].channeloffset[2]; + + if (poses[i].mask & 0x04) + { + animation.framePoses[frame][i].translation.z += framedata[dcounter]*poses[i].channelscale[2]; + dcounter++; + } + + animation.framePoses[frame][i].rotation.x = poses[i].channeloffset[3]; + + if (poses[i].mask & 0x08) + { + animation.framePoses[frame][i].rotation.x += framedata[dcounter]*poses[i].channelscale[3]; + dcounter++; + } + + animation.framePoses[frame][i].rotation.y = poses[i].channeloffset[4]; + + if (poses[i].mask & 0x10) + { + animation.framePoses[frame][i].rotation.y += framedata[dcounter]*poses[i].channelscale[4]; + dcounter++; + } + + animation.framePoses[frame][i].rotation.z = poses[i].channeloffset[5]; + + if (poses[i].mask & 0x20) + { + animation.framePoses[frame][i].rotation.z += framedata[dcounter]*poses[i].channelscale[5]; + dcounter++; + } + + animation.framePoses[frame][i].rotation.w = poses[i].channeloffset[6]; + + if (poses[i].mask & 0x40) + { + animation.framePoses[frame][i].rotation.w += framedata[dcounter]*poses[i].channelscale[6]; + dcounter++; + } + + animation.framePoses[frame][i].scale.x = poses[i].channeloffset[7]; + + if (poses[i].mask & 0x80) + { + animation.framePoses[frame][i].scale.x += framedata[dcounter]*poses[i].channelscale[7]; + dcounter++; + } + + animation.framePoses[frame][i].scale.y = poses[i].channeloffset[8]; + + if (poses[i].mask & 0x100) + { + animation.framePoses[frame][i].scale.y += framedata[dcounter]*poses[i].channelscale[8]; + dcounter++; + } + + animation.framePoses[frame][i].scale.z = poses[i].channeloffset[9]; + + if (poses[i].mask & 0x200) + { + animation.framePoses[frame][i].scale.z += framedata[dcounter]*poses[i].channelscale[9]; + dcounter++; + } + + animation.framePoses[frame][i].rotation = QuaternionNormalize(animation.framePoses[frame][i].rotation); + } + } + + // Build frameposes + for (int frame = 0; frame < anim.num_frames; frame++) + { + for (int i = 0; i < animation.boneCount; i++) + { + if (animation.bones[i].parent >= 0) + { + animation.framePoses[frame][i].rotation = QuaternionMultiply(animation.framePoses[frame][animation.bones[i].parent].rotation, animation.framePoses[frame][i].rotation); + animation.framePoses[frame][i].translation = Vector3RotateByQuaternion(animation.framePoses[frame][i].translation, animation.framePoses[frame][animation.bones[i].parent].rotation); + animation.framePoses[frame][i].translation = Vector3Add(animation.framePoses[frame][i].translation, animation.framePoses[frame][animation.bones[i].parent].translation); + animation.framePoses[frame][i].scale = Vector3MultiplyV(animation.framePoses[frame][i].scale, animation.framePoses[frame][animation.bones[i].parent].scale); + } + } + } + + free(framedata); + free(poses); + + fclose(iqmFile); + + animations[0] = animation; + + *animCount = count; + return animations; +} + +// Update model animated vertex data (positions and normals) for a given frame +// NOTE: Updated data is uploaded to GPU +void UpdateModelAnimation(Model model, ModelAnimation anim, int frame) +{ + if (frame >= anim.frameCount) frame = frame%anim.frameCount; + + for (int m = 0; m < model.meshCount; m++) + { + Vector3 animVertex = { 0 }; + Vector3 animNormal = { 0 }; + + Vector3 inTranslation = { 0 }; + Quaternion inRotation = { 0 }; + Vector3 inScale = { 0 }; + + Vector3 outTranslation = { 0 }; + Quaternion outRotation = { 0 }; + Vector3 outScale = { 0 }; + + int vCounter = 0; + int boneCounter = 0; + int boneId = 0; + + for (int i = 0; i < model.meshes[m].vertexCount; i++) + { + boneId = model.meshes[m].boneIds[boneCounter]; + inTranslation = model.bindPose[boneId].translation; + inRotation = model.bindPose[boneId].rotation; + inScale = model.bindPose[boneId].scale; + outTranslation = anim.framePoses[frame][boneId].translation; + outRotation = anim.framePoses[frame][boneId].rotation; + outScale = anim.framePoses[frame][boneId].scale; + + // Vertices processing + // NOTE: We use meshes.vertices (default vertex position) to calculate meshes.animVertices (animated vertex position) + animVertex = (Vector3){ model.meshes[m].vertices[vCounter], model.meshes[m].vertices[vCounter + 1], model.meshes[m].vertices[vCounter + 2] }; + animVertex = Vector3MultiplyV(animVertex, outScale); + animVertex = Vector3Subtract(animVertex, inTranslation); + animVertex = Vector3RotateByQuaternion(animVertex, QuaternionMultiply(outRotation, QuaternionInvert(inRotation))); + animVertex = Vector3Add(animVertex, outTranslation); + model.meshes[m].animVertices[vCounter] = animVertex.x; + model.meshes[m].animVertices[vCounter + 1] = animVertex.y; + model.meshes[m].animVertices[vCounter + 2] = animVertex.z; + + // Normals processing + // NOTE: We use meshes.baseNormals (default normal) to calculate meshes.normals (animated normals) + animNormal = (Vector3){ model.meshes[m].normals[vCounter], model.meshes[m].normals[vCounter + 1], model.meshes[m].normals[vCounter + 2] }; + animNormal = Vector3RotateByQuaternion(animNormal, QuaternionMultiply(outRotation, QuaternionInvert(inRotation))); + model.meshes[m].animNormals[vCounter] = animNormal.x; + model.meshes[m].animNormals[vCounter + 1] = animNormal.y; + model.meshes[m].animNormals[vCounter + 2] = animNormal.z; + vCounter += 3; + + boneCounter += 4; + } + + // Upload new vertex data to GPU for model drawing + rlUpdateBuffer(model.meshes[m].vboId[0], model.meshes[m].animVertices, model.meshes[m].vertexCount*3*sizeof(float)); // Update vertex position + rlUpdateBuffer(model.meshes[m].vboId[2], model.meshes[m].animVertices, model.meshes[m].vertexCount*3*sizeof(float)); // Update vertex normals + } +} + +// Unload animation data +void UnloadModelAnimation(ModelAnimation anim) +{ + for (int i = 0; i < anim.frameCount; i++) free(anim.framePoses[i]); + + free(anim.bones); + free(anim.framePoses); +} + +// Check model animation skeleton match +// NOTE: Only number of bones and parent connections are checked +bool IsModelAnimationValid(Model model, ModelAnimation anim) +{ + int result = true; + + if (model.boneCount != anim.boneCount) result = false; + else + { + for (int i = 0; i < model.boneCount; i++) + { + if (model.bones[i].parent != anim.bones[i].parent) { result = false; break; } + } + } + + return result; +} + #if defined(SUPPORT_MESH_GENERATION) // Generate polygonal mesh Mesh GenMeshPoly(int sides, float radius) @@ -1807,59 +2199,124 @@ Mesh GenMeshCubicmap(Image cubicmap, Vector3 cubeSize) } #endif // SUPPORT_MESH_GENERATION -// Load material data (from file) -Material LoadMaterial(const char *fileName) +// Compute mesh bounding box limits +// NOTE: minVertex and maxVertex should be transformed by model transform matrix +BoundingBox MeshBoundingBox(Mesh mesh) { - Material material = { 0 }; + // Get min and max vertex to construct bounds (AABB) + Vector3 minVertex = { 0 }; + Vector3 maxVertex = { 0 }; -#if defined(SUPPORT_FILEFORMAT_MTL) - if (IsFileExtension(fileName, ".mtl")) + if (mesh.vertices != NULL) { - tinyobj_material_t *materials; - unsigned int materialCount = 0; - - int result = tinyobj_parse_mtl_file(&materials, &materialCount, fileName); - - // TODO: Process materials to return + minVertex = (Vector3){ mesh.vertices[0], mesh.vertices[1], mesh.vertices[2] }; + maxVertex = (Vector3){ mesh.vertices[0], mesh.vertices[1], mesh.vertices[2] }; - tinyobj_materials_free(materials, materialCount); + for (int i = 1; i < mesh.vertexCount; i++) + { + minVertex = Vector3Min(minVertex, (Vector3){ mesh.vertices[i*3], mesh.vertices[i*3 + 1], mesh.vertices[i*3 + 2] }); + maxVertex = Vector3Max(maxVertex, (Vector3){ mesh.vertices[i*3], mesh.vertices[i*3 + 1], mesh.vertices[i*3 + 2] }); + } } -#else - TraceLog(LOG_WARNING, "[%s] Material fileformat not supported, it can't be loaded", fileName); -#endif - // Our material uses the default shader (DIFFUSE, SPECULAR, NORMAL) - material.shader = GetShaderDefault(); + // Create the bounding box + BoundingBox box = { 0 }; + box.min = minVertex; + box.max = maxVertex; - return material; + return box; } -// Load default material (Supports: DIFFUSE, SPECULAR, NORMAL maps) -Material LoadMaterialDefault(void) +// Compute mesh tangents +// NOTE: To calculate mesh tangents and binormals we need mesh vertex positions and texture coordinates +// Implementation base don: https://answers.unity.com/questions/7789/calculating-tangents-vector4.html +void MeshTangents(Mesh *mesh) { - Material material = { 0 }; + if (mesh->tangents == NULL) mesh->tangents = (float *)malloc(mesh->vertexCount*4*sizeof(float)); + else TraceLog(LOG_WARNING, "Mesh tangents already exist"); - material.shader = GetShaderDefault(); - material.maps[MAP_DIFFUSE].texture = GetTextureDefault(); // White texture (1x1 pixel) - //material.maps[MAP_NORMAL].texture; // NOTE: By default, not set - //material.maps[MAP_SPECULAR].texture; // NOTE: By default, not set + Vector3 *tan1 = (Vector3 *)malloc(mesh->vertexCount*sizeof(Vector3)); + Vector3 *tan2 = (Vector3 *)malloc(mesh->vertexCount*sizeof(Vector3)); - material.maps[MAP_DIFFUSE].color = WHITE; // Diffuse color - material.maps[MAP_SPECULAR].color = WHITE; // Specular color + for (int i = 0; i < mesh->vertexCount; i += 3) + { + // Get triangle vertices + Vector3 v1 = { mesh->vertices[(i + 0)*3 + 0], mesh->vertices[(i + 0)*3 + 1], mesh->vertices[(i + 0)*3 + 2] }; + Vector3 v2 = { mesh->vertices[(i + 1)*3 + 0], mesh->vertices[(i + 1)*3 + 1], mesh->vertices[(i + 1)*3 + 2] }; + Vector3 v3 = { mesh->vertices[(i + 2)*3 + 0], mesh->vertices[(i + 2)*3 + 1], mesh->vertices[(i + 2)*3 + 2] }; - return material; + // Get triangle texcoords + Vector2 uv1 = { mesh->texcoords[(i + 0)*2 + 0], mesh->texcoords[(i + 0)*2 + 1] }; + Vector2 uv2 = { mesh->texcoords[(i + 1)*2 + 0], mesh->texcoords[(i + 1)*2 + 1] }; + Vector2 uv3 = { mesh->texcoords[(i + 2)*2 + 0], mesh->texcoords[(i + 2)*2 + 1] }; + + float x1 = v2.x - v1.x; + float y1 = v2.y - v1.y; + float z1 = v2.z - v1.z; + float x2 = v3.x - v1.x; + float y2 = v3.y - v1.y; + float z2 = v3.z - v1.z; + + float s1 = uv2.x - uv1.x; + float t1 = uv2.y - uv1.y; + float s2 = uv3.x - uv1.x; + float t2 = uv3.y - uv1.y; + + float div = s1*t2 - s2*t1; + float r = (div == 0.0f)? 0.0f : 1.0f/div; + + Vector3 sdir = { (t2*x1 - t1*x2)*r, (t2*y1 - t1*y2)*r, (t2*z1 - t1*z2)*r }; + Vector3 tdir = { (s1*x2 - s2*x1)*r, (s1*y2 - s2*y1)*r, (s1*z2 - s2*z1)*r }; + + tan1[i + 0] = sdir; + tan1[i + 1] = sdir; + tan1[i + 2] = sdir; + + tan2[i + 0] = tdir; + tan2[i + 1] = tdir; + tan2[i + 2] = tdir; + } + + // Compute tangents considering normals + for (int i = 0; i < mesh->vertexCount; ++i) + { + Vector3 normal = { mesh->normals[i*3 + 0], mesh->normals[i*3 + 1], mesh->normals[i*3 + 2] }; + Vector3 tangent = tan1[i]; + + // TODO: Review, not sure if tangent computation is right, just used reference proposed maths... + #if defined(COMPUTE_TANGENTS_METHOD_01) + Vector3 tmp = Vector3Subtract(tangent, Vector3Multiply(normal, Vector3DotProduct(normal, tangent))); + tmp = Vector3Normalize(tmp); + mesh->tangents[i*4 + 0] = tmp.x; + mesh->tangents[i*4 + 1] = tmp.y; + mesh->tangents[i*4 + 2] = tmp.z; + mesh->tangents[i*4 + 3] = 1.0f; + #else + Vector3OrthoNormalize(&normal, &tangent); + mesh->tangents[i*4 + 0] = tangent.x; + mesh->tangents[i*4 + 1] = tangent.y; + mesh->tangents[i*4 + 2] = tangent.z; + mesh->tangents[i*4 + 3] = (Vector3DotProduct(Vector3CrossProduct(normal, tangent), tan2[i]) < 0.0f)? -1.0f : 1.0f; + #endif + } + + free(tan1); + free(tan2); + + TraceLog(LOG_INFO, "Tangents computed for mesh"); } -// Unload material from memory -void UnloadMaterial(Material material) +// Compute mesh binormals (aka bitangent) +void MeshBinormals(Mesh *mesh) { - // Unload material shader (avoid unloading default shader, managed by raylib) - if (material.shader.id != GetShaderDefault().id) UnloadShader(material.shader); - - // Unload loaded texture maps (avoid unloading default texture, managed by raylib) - for (int i = 0; i < MAX_MATERIAL_MAPS; i++) + for (int i = 0; i < mesh->vertexCount; i++) { - if (material.maps[i].texture.id != GetTextureDefault().id) rlDeleteTextures(material.maps[i].texture.id); + Vector3 normal = { mesh->normals[i*3 + 0], mesh->normals[i*3 + 1], mesh->normals[i*3 + 2] }; + Vector3 tangent = { mesh->tangents[i*4 + 0], mesh->tangents[i*4 + 1], mesh->tangents[i*4 + 2] }; + float tangentW = mesh->tangents[i*4 + 3]; + + // TODO: Register computed binormal in mesh->binormal? + // Vector3 binormal = Vector3Multiply(Vector3CrossProduct(normal, tangent), tangentW); } } @@ -2239,129 +2696,6 @@ RayHitInfo GetCollisionRayGround(Ray ray, float groundHeight) return result; } -// Compute mesh bounding box limits -// NOTE: minVertex and maxVertex should be transformed by model transform matrix -BoundingBox MeshBoundingBox(Mesh mesh) -{ - // Get min and max vertex to construct bounds (AABB) - Vector3 minVertex = { 0 }; - Vector3 maxVertex = { 0 }; - - printf("Mesh vertex count: %i\n", mesh.vertexCount); - - if (mesh.vertices != NULL) - { - minVertex = (Vector3){ mesh.vertices[0], mesh.vertices[1], mesh.vertices[2] }; - maxVertex = (Vector3){ mesh.vertices[0], mesh.vertices[1], mesh.vertices[2] }; - - for (int i = 1; i < mesh.vertexCount; i++) - { - minVertex = Vector3Min(minVertex, (Vector3){ mesh.vertices[i*3], mesh.vertices[i*3 + 1], mesh.vertices[i*3 + 2] }); - maxVertex = Vector3Max(maxVertex, (Vector3){ mesh.vertices[i*3], mesh.vertices[i*3 + 1], mesh.vertices[i*3 + 2] }); - } - } - - // Create the bounding box - BoundingBox box = { 0 }; - box.min = minVertex; - box.max = maxVertex; - - return box; -} - -// Compute mesh tangents -// NOTE: To calculate mesh tangents and binormals we need mesh vertex positions and texture coordinates -// Implementation base don: https://answers.unity.com/questions/7789/calculating-tangents-vector4.html -void MeshTangents(Mesh *mesh) -{ - if (mesh->tangents == NULL) mesh->tangents = (float *)malloc(mesh->vertexCount*4*sizeof(float)); - else TraceLog(LOG_WARNING, "Mesh tangents already exist"); - - Vector3 *tan1 = (Vector3 *)malloc(mesh->vertexCount*sizeof(Vector3)); - Vector3 *tan2 = (Vector3 *)malloc(mesh->vertexCount*sizeof(Vector3)); - - for (int i = 0; i < mesh->vertexCount; i += 3) - { - // Get triangle vertices - Vector3 v1 = { mesh->vertices[(i + 0)*3 + 0], mesh->vertices[(i + 0)*3 + 1], mesh->vertices[(i + 0)*3 + 2] }; - Vector3 v2 = { mesh->vertices[(i + 1)*3 + 0], mesh->vertices[(i + 1)*3 + 1], mesh->vertices[(i + 1)*3 + 2] }; - Vector3 v3 = { mesh->vertices[(i + 2)*3 + 0], mesh->vertices[(i + 2)*3 + 1], mesh->vertices[(i + 2)*3 + 2] }; - - // Get triangle texcoords - Vector2 uv1 = { mesh->texcoords[(i + 0)*2 + 0], mesh->texcoords[(i + 0)*2 + 1] }; - Vector2 uv2 = { mesh->texcoords[(i + 1)*2 + 0], mesh->texcoords[(i + 1)*2 + 1] }; - Vector2 uv3 = { mesh->texcoords[(i + 2)*2 + 0], mesh->texcoords[(i + 2)*2 + 1] }; - - float x1 = v2.x - v1.x; - float y1 = v2.y - v1.y; - float z1 = v2.z - v1.z; - float x2 = v3.x - v1.x; - float y2 = v3.y - v1.y; - float z2 = v3.z - v1.z; - - float s1 = uv2.x - uv1.x; - float t1 = uv2.y - uv1.y; - float s2 = uv3.x - uv1.x; - float t2 = uv3.y - uv1.y; - - float div = s1*t2 - s2*t1; - float r = (div == 0.0f)? 0.0f : 1.0f/div; - - Vector3 sdir = { (t2*x1 - t1*x2)*r, (t2*y1 - t1*y2)*r, (t2*z1 - t1*z2)*r }; - Vector3 tdir = { (s1*x2 - s2*x1)*r, (s1*y2 - s2*y1)*r, (s1*z2 - s2*z1)*r }; - - tan1[i + 0] = sdir; - tan1[i + 1] = sdir; - tan1[i + 2] = sdir; - - tan2[i + 0] = tdir; - tan2[i + 1] = tdir; - tan2[i + 2] = tdir; - } - - // Compute tangents considering normals - for (int i = 0; i < mesh->vertexCount; ++i) - { - Vector3 normal = { mesh->normals[i*3 + 0], mesh->normals[i*3 + 1], mesh->normals[i*3 + 2] }; - Vector3 tangent = tan1[i]; - - // TODO: Review, not sure if tangent computation is right, just used reference proposed maths... - #if defined(COMPUTE_TANGENTS_METHOD_01) - Vector3 tmp = Vector3Subtract(tangent, Vector3Multiply(normal, Vector3DotProduct(normal, tangent))); - tmp = Vector3Normalize(tmp); - mesh->tangents[i*4 + 0] = tmp.x; - mesh->tangents[i*4 + 1] = tmp.y; - mesh->tangents[i*4 + 2] = tmp.z; - mesh->tangents[i*4 + 3] = 1.0f; - #else - Vector3OrthoNormalize(&normal, &tangent); - mesh->tangents[i*4 + 0] = tangent.x; - mesh->tangents[i*4 + 1] = tangent.y; - mesh->tangents[i*4 + 2] = tangent.z; - mesh->tangents[i*4 + 3] = (Vector3DotProduct(Vector3CrossProduct(normal, tangent), tan2[i]) < 0.0f)? -1.0f : 1.0f; - #endif - } - - free(tan1); - free(tan2); - - TraceLog(LOG_INFO, "Tangents computed for mesh"); -} - -// Compute mesh binormals (aka bitangent) -void MeshBinormals(Mesh *mesh) -{ - for (int i = 0; i < mesh->vertexCount; i++) - { - Vector3 normal = { mesh->normals[i*3 + 0], mesh->normals[i*3 + 1], mesh->normals[i*3 + 2] }; - Vector3 tangent = { mesh->tangents[i*4 + 0], mesh->tangents[i*4 + 1], mesh->tangents[i*4 + 2] }; - float tangentW = mesh->tangents[i*4 + 3]; - - // TODO: Register computed binormal in mesh->binormal? - // Vector3 binormal = Vector3Multiply(Vector3CrossProduct(normal, tangent), tangentW); - } -} - //---------------------------------------------------------------------------------- // Module specific Functions Definition //---------------------------------------------------------------------------------- diff --git a/src/raylib.h b/src/raylib.h index c365fa47..55943baf 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -752,7 +752,7 @@ typedef enum { MAP_IRRADIANCE, // NOTE: Uses GL_TEXTURE_CUBE_MAP MAP_PREFILTER, // NOTE: Uses GL_TEXTURE_CUBE_MAP MAP_BRDF -} TexmapIndex; +} MaterialMapType; #define MAP_DIFFUSE MAP_ALBEDO #define MAP_SPECULAR MAP_METALNESS @@ -1256,16 +1256,25 @@ RLAPI void DrawGizmo(Vector3 position); // Model loading/unloading functions RLAPI Model LoadModel(const char *fileName); // Load model from files (meshes and materials) RLAPI Model LoadModelFromMesh(Mesh mesh); // Load model from generated mesh -//RLAPI void LoadModelAnimations(const char fileName, ModelAnimation *anims, int *animsCount); // Load model animations from file -//RLAPI void UpdateModelAnimation(Model model, ModelAnimation anim, int frame); // Update model animation pose RLAPI void UnloadModel(Model model); // Unload model from memory (RAM and/or VRAM) -// Mesh manipulation functions -RLAPI BoundingBox MeshBoundingBox(Mesh mesh); // Compute mesh bounding box limits -RLAPI void MeshTangents(Mesh *mesh); // Compute mesh tangents -RLAPI void MeshBinormals(Mesh *mesh); // Compute mesh binormals -RLAPI void UnloadMesh(Mesh *mesh); // Unload mesh from memory (RAM and/or VRAM) +// Mesh loading/unloading functions +RLAPI Mesh *LoadMeshes(const char *fileName, int *meshCount); // Load meshes from model file RLAPI void ExportMesh(Mesh mesh, const char *fileName); // Export mesh data to file +RLAPI void UnloadMesh(Mesh *mesh); // Unload mesh from memory (RAM and/or VRAM) + +// Material loading/unloading functions +RLAPI Material *LoadMaterials(const char *fileName, int *materialCount); // Load materials from model file +RLAPI Material LoadMaterialDefault(void); // Load default material (Supports: DIFFUSE, SPECULAR, NORMAL maps) +RLAPI void UnloadMaterial(Material material); // Unload material from GPU memory (VRAM) +RLAPI void SetMaterialTexture(Material *material, int mapType, Texture2D texture); // Set texture for a material map type (MAP_DIFFUSE, MAP_SPECULAR...) +RLAPI void SetModelMeshMaterial(Model *model, int meshId, int materialId); // Set material for a mesh + +// Model animations loading/unloading functions +RLAPI ModelAnimation *LoadModelAnimations(const char *fileName, int *animsCount); // Load model animations from file +RLAPI void UpdateModelAnimation(Model model, ModelAnimation anim, int frame); // Update model animation pose +RLAPI void UnloadModelAnimation(ModelAnimation anim); // Unload animation data +RLAPI bool IsModelAnimationValid(Model model, ModelAnimation anim); // Check model animation skeleton match // Mesh generation functions RLAPI Mesh GenMeshPoly(int sides, float radius); // Generate polygonal mesh @@ -1279,10 +1288,10 @@ RLAPI Mesh GenMeshKnot(float radius, float size, int radSeg, int sides); RLAPI Mesh GenMeshHeightmap(Image heightmap, Vector3 size); // Generate heightmap mesh from image data RLAPI Mesh GenMeshCubicmap(Image cubicmap, Vector3 cubeSize); // Generate cubes-based map mesh from image data -// Material loading/unloading functions -RLAPI Material LoadMaterial(const char *fileName); // Load material from file -RLAPI Material LoadMaterialDefault(void); // Load default material (Supports: DIFFUSE, SPECULAR, NORMAL maps) -RLAPI void UnloadMaterial(Material material); // Unload material from GPU memory (VRAM) +// Mesh manipulation functions +RLAPI BoundingBox MeshBoundingBox(Mesh mesh); // Compute mesh bounding box limits +RLAPI void MeshTangents(Mesh *mesh); // Compute mesh tangents +RLAPI void MeshBinormals(Mesh *mesh); // Compute mesh binormals // Model drawing functions RLAPI void DrawModel(Model model, Vector3 position, float scale, Color tint); // Draw a model (with texture if set) -- cgit v1.2.3 From 0f9fe34c3a9228eaa3ffdb3be3f52ba586d1ddfa Mon Sep 17 00:00:00 2001 From: Ray Date: Fri, 5 Apr 2019 13:44:04 +0200 Subject: Start setting things up for raylib 2.5 --- src/config.h | 2 +- src/raylib.rc | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/config.h b/src/config.h index 4174ed71..561bcfd3 100644 --- a/src/config.h +++ b/src/config.h @@ -25,7 +25,7 @@ * **********************************************************************************************/ -#define RAYLIB_VERSION "2.4-dev" +#define RAYLIB_VERSION "2.5-dev" // Edit to control what features Makefile'd raylib is compiled with #if defined(RAYLIB_CMAKE) diff --git a/src/raylib.rc b/src/raylib.rc index 2aaa5e26..c2fdfa46 100644 --- a/src/raylib.rc +++ b/src/raylib.rc @@ -1,8 +1,8 @@ GLFW_ICON ICON "raylib.ico" 1 VERSIONINFO -FILEVERSION 2,0,0,0 -PRODUCTVERSION 2,0,0,0 +FILEVERSION 2,5,0,0 +PRODUCTVERSION 2,5,0,0 BEGIN BLOCK "StringFileInfo" BEGIN @@ -11,12 +11,12 @@ BEGIN BEGIN //VALUE "CompanyName", "raylib technologies" VALUE "FileDescription", "Created using raylib (www.raylib.com)" - VALUE "FileVersion", "2.0.0" + VALUE "FileVersion", "2.5.0" VALUE "InternalName", "raylib app" - VALUE "LegalCopyright", "(c) 2018 Ramon Santamaria - @raysan5" + VALUE "LegalCopyright", "(c) 2019 Ramon Santamaria (@raysan5)" //VALUE "OriginalFilename", "raylib_app.exe" VALUE "ProductName", "raylib game" - VALUE "ProductVersion", "2.0.0" + VALUE "ProductVersion", "2.5.0" END END BLOCK "VarFileInfo" -- cgit v1.2.3 From c600dd07668f301fc1a986326d807f341e6ecb78 Mon Sep 17 00:00:00 2001 From: Ray Date: Fri, 5 Apr 2019 16:43:09 +0200 Subject: Review PBR shaders Issue was related to vertex tangent attibutes not uploaded to GPU, a quick solution was implemented for new vertex attributes loading for already existing meshes... I don't like it specially but it will work for now. --- src/models.c | 3 +++ src/rlgl.h | 24 ++++++++++++++++++++++++ 2 files changed, 27 insertions(+) (limited to 'src') diff --git a/src/models.c b/src/models.c index e437a0ab..7a9acdf7 100644 --- a/src/models.c +++ b/src/models.c @@ -2302,6 +2302,9 @@ void MeshTangents(Mesh *mesh) free(tan1); free(tan2); + + // Load a new tangent attributes buffer + mesh->vboId[LOC_VERTEX_TANGENT] = rlLoadAttribBuffer(mesh->vaoId, LOC_VERTEX_TANGENT, mesh->tangents, mesh->vertexCount*4*sizeof(float), false); TraceLog(LOG_INFO, "Tangents computed for mesh"); } diff --git a/src/rlgl.h b/src/rlgl.h index 3d433377..bf50ad0d 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -456,6 +456,7 @@ void rlDeleteBuffers(unsigned int id); // Unload vertex data (V void rlClearColor(byte r, byte g, byte b, byte a); // Clear color buffer with color void rlClearScreenBuffers(void); // Clear used screen buffers (color and depth) void rlUpdateBuffer(int bufferId, void *data, int dataSize); // Update GPU buffer with new data +unsigned int rlLoadAttribBuffer(unsigned int vaoId, int shaderLoc, void *buffer, int size, bool dynamic); // Load a new attributes buffer //------------------------------------------------------------------------------------ // Functions Declaration - rlgl functionality @@ -2532,6 +2533,29 @@ void rlLoadMesh(Mesh *mesh, bool dynamic) #endif } +// Load a new attributes buffer +unsigned int rlLoadAttribBuffer(unsigned int vaoId, int shaderLoc, void *buffer, int size, bool dynamic) +{ + unsigned int id = 0; + +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + int drawHint = GL_STATIC_DRAW; + if (dynamic) drawHint = GL_DYNAMIC_DRAW; + + if (vaoSupported) glBindVertexArray(vaoId); + + glGenBuffers(1, &id); + glBindBuffer(GL_ARRAY_BUFFER, id); + glBufferData(GL_ARRAY_BUFFER, size, buffer, drawHint); + glVertexAttribPointer(shaderLoc, 2, GL_FLOAT, 0, 0, 0); + glEnableVertexAttribArray(shaderLoc); + + if (vaoSupported) glBindVertexArray(0); +#endif + + return id; +} + // Update vertex data on GPU (upload new data to one buffer) void rlUpdateMesh(Mesh mesh, int buffer, int numVertex) { -- cgit v1.2.3 From 9282b8ba83909b353fd34a9f584597338c1928bd Mon Sep 17 00:00:00 2001 From: Ray Date: Fri, 5 Apr 2019 17:08:46 +0200 Subject: ADDED: SetShaderValueTexture() Some tweaks --- src/raylib.h | 3 ++- src/rlgl.h | 16 ++++++++++++++-- 2 files changed, 16 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/raylib.h b/src/raylib.h index 55943baf..dc864b8d 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -1331,7 +1331,8 @@ RLAPI Texture2D GetTextureDefault(void); // Get RLAPI int GetShaderLocation(Shader shader, const char *uniformName); // Get shader uniform location RLAPI void SetShaderValue(Shader shader, int uniformLoc, const void *value, int uniformType); // Set shader uniform value RLAPI void SetShaderValueV(Shader shader, int uniformLoc, const void *value, int uniformType, int count); // Set shader uniform value vector -RLAPI void SetShaderValueMatrix(Shader shader, int uniformLoc, Matrix mat); // Set shader uniform value (matrix 4x4) +RLAPI void SetShaderValueMatrix(Shader shader, int uniformLoc, Matrix mat); // Set shader uniform value (matrix 4x4) +RLAPI void SetShaderValueTexture(Shader shader, int uniformLoc, Texture2D texture); // Set shader uniform value for texture RLAPI void SetMatrixProjection(Matrix proj); // Set a custom projection matrix (replaces internal projection matrix) RLAPI void SetMatrixModelview(Matrix view); // Set a custom modelview matrix (replaces internal modelview matrix) RLAPI Matrix GetMatrixModelview(); // Get internal modelview matrix diff --git a/src/rlgl.h b/src/rlgl.h index bf50ad0d..81f39d68 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -207,8 +207,8 @@ typedef unsigned char byte; // Animation vertex data float *animVertices; // Animated vertex positions (after bones transformations) float *animNormals; // Animated normals (after bones transformations) - float *weightBias; // Vertex weight bias - int *weightId; // Vertex weight id + int *boneIds; // Vertex bone ids, up to 4 bones influence by vertex (skinning) + float *boneWeights; // Vertex bone weight, up to 4 bones influence by vertex (skinning) // OpenGL identifiers unsigned int vaoId; // OpenGL Vertex Array Object id @@ -3169,6 +3169,18 @@ void SetShaderValueMatrix(Shader shader, int uniformLoc, Matrix mat) #endif } +// Set shader uniform value for texture +void SetShaderValueTexture(Shader shader, int uniformLoc, Texture2D texture) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + glUseProgram(shader.id); + + glUniform1i(uniformLoc, texture.id); + + //glUseProgram(0); +#endif +} + // Set a custom projection matrix (replaces internal projection matrix) void SetMatrixProjection(Matrix proj) { -- cgit v1.2.3 From f21761fbbb02f0b58b5b54342f0c3ad3abc0003e Mon Sep 17 00:00:00 2001 From: ChillerDragon Date: Sun, 7 Apr 2019 17:49:12 +0200 Subject: Happy new year 2019 --- src/Makefile | 2 +- src/core.c | 2 +- src/gestures.h | 2 +- src/models.c | 2 +- src/raylib.h | 2 +- src/rglfw.c | 2 +- src/rlgl.h | 2 +- src/shapes.c | 2 +- src/text.c | 2 +- src/textures.c | 2 +- src/utils.c | 2 +- src/utils.h | 2 +- 12 files changed, 12 insertions(+), 12 deletions(-) (limited to 'src') diff --git a/src/Makefile b/src/Makefile index e2fe6c5d..0217c198 100644 --- a/src/Makefile +++ b/src/Makefile @@ -14,7 +14,7 @@ # Many thanks to Milan Nikolic (@gen2brain) for implementing Android platform pipeline. # Many thanks to Emanuele Petriglia for his contribution on GNU/Linux pipeline. # -# Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +# Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) # # 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 diff --git a/src/core.c b/src/core.c index b0c0658d..42db214f 100644 --- a/src/core.c +++ b/src/core.c @@ -68,7 +68,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * 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. diff --git a/src/gestures.h b/src/gestures.h index a4546eb1..36775333 100644 --- a/src/gestures.h +++ b/src/gestures.h @@ -24,7 +24,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * 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. diff --git a/src/models.c b/src/models.c index 7a9acdf7..07f8203b 100644 --- a/src/models.c +++ b/src/models.c @@ -17,7 +17,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * 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. diff --git a/src/raylib.h b/src/raylib.h index dc864b8d..dade7aba 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -49,7 +49,7 @@ * raylib is licensed under an unmodified zlib/libpng license, which is an OSI-certified, * BSD-like license that allows static linking with closed source software: * -* Copyright (c) 2013-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2013-2019 Ramon Santamaria (@raysan5) * * 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. diff --git a/src/rglfw.c b/src/rglfw.c index 853c5200..3463bb96 100644 --- a/src/rglfw.c +++ b/src/rglfw.c @@ -7,7 +7,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2017-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2017-2019 Ramon Santamaria (@raysan5) * * 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. diff --git a/src/rlgl.h b/src/rlgl.h index 81f39d68..3e428241 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -42,7 +42,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * 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. diff --git a/src/shapes.c b/src/shapes.c index b7f7e3df..fbc70fc4 100644 --- a/src/shapes.c +++ b/src/shapes.c @@ -14,7 +14,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * 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. diff --git a/src/text.c b/src/text.c index d44cdd11..cd7a6802 100644 --- a/src/text.c +++ b/src/text.c @@ -17,7 +17,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * 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. diff --git a/src/textures.c b/src/textures.c index cd0bd208..5189b635 100644 --- a/src/textures.c +++ b/src/textures.c @@ -38,7 +38,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * 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. diff --git a/src/utils.c b/src/utils.c index 6b174354..10cce9b9 100644 --- a/src/utils.c +++ b/src/utils.c @@ -11,7 +11,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * 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. diff --git a/src/utils.h b/src/utils.h index 08b33962..d7ab8829 100644 --- a/src/utils.h +++ b/src/utils.h @@ -5,7 +5,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * 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. -- cgit v1.2.3 From b8ada4b877497cf31aad0efdec41c032fc686552 Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 8 Apr 2019 12:25:13 +0200 Subject: Review creation years --- src/config.h | 2 +- src/core.c | 2 +- src/models.c | 2 +- src/raudio.c | 2 +- src/shapes.c | 2 +- src/text.c | 2 +- src/textures.c | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/config.h b/src/config.h index 561bcfd3..dc30eeb2 100644 --- a/src/config.h +++ b/src/config.h @@ -6,7 +6,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2018 Ahmad Fatoum & Ramon Santamaria (@raysan5) +* Copyright (c) 2018-2019 Ahmad Fatoum & Ramon Santamaria (@raysan5) * * 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. diff --git a/src/core.c b/src/core.c index 42db214f..32773a0d 100644 --- a/src/core.c +++ b/src/core.c @@ -68,7 +68,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) +* Copyright (c) 2013-2019 Ramon Santamaria (@raysan5) * * 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. diff --git a/src/models.c b/src/models.c index 07f8203b..d5e74e33 100644 --- a/src/models.c +++ b/src/models.c @@ -17,7 +17,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) +* Copyright (c) 2013-2019 Ramon Santamaria (@raysan5) * * 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. diff --git a/src/raudio.c b/src/raudio.c index d360b2d3..636d15b8 100644 --- a/src/raudio.c +++ b/src/raudio.c @@ -46,7 +46,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) +* Copyright (c) 2013-2019 Ramon Santamaria (@raysan5) * * 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. diff --git a/src/shapes.c b/src/shapes.c index fbc70fc4..f407f0d2 100644 --- a/src/shapes.c +++ b/src/shapes.c @@ -14,7 +14,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) +* Copyright (c) 2013-2019 Ramon Santamaria (@raysan5) * * 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. diff --git a/src/text.c b/src/text.c index cd7a6802..c07f807a 100644 --- a/src/text.c +++ b/src/text.c @@ -17,7 +17,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) +* Copyright (c) 2013-2019 Ramon Santamaria (@raysan5) * * 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. diff --git a/src/textures.c b/src/textures.c index 5189b635..169f8f86 100644 --- a/src/textures.c +++ b/src/textures.c @@ -38,7 +38,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) +* Copyright (c) 2013-2019 Ramon Santamaria (@raysan5) * * 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. -- cgit v1.2.3 From 61181f2c49b823f691b42c6de63a5f9f130e18d6 Mon Sep 17 00:00:00 2001 From: myd7349 Date: Fri, 5 Apr 2019 10:56:47 +0800 Subject: Fix CMake support on Win32 --- src/CMakeLists.txt | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index c65a4996..c24853a1 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -188,6 +188,11 @@ if(SHARED) PUBLIC ${GRAPHICS} ) + target_compile_definitions(raylib + PRIVATE $ + INTERFACE $ + ) + set(PKG_CONFIG_LIBS_EXTRA "") set_property(TARGET raylib PROPERTY POSITION_INDEPENDENT_CODE ON) @@ -214,7 +219,9 @@ if(SHARED) if (WIN32) install( TARGETS raylib - RUNTIME DESTINATION "lib" + ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}" + LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}" + RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" PUBLIC_HEADER DESTINATION "include" ) else() -- cgit v1.2.3 From 32ccecb8ca1f141e6b8e20007e795c58108cb899 Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 9 Apr 2019 13:23:51 +0200 Subject: Start working on glTF loading... --- src/models.c | 60 +++++++++++++++++++++++++++++++++++++++++------------------- 1 file changed, 41 insertions(+), 19 deletions(-) (limited to 'src') diff --git a/src/models.c b/src/models.c index d5e74e33..73f8b940 100644 --- a/src/models.c +++ b/src/models.c @@ -3013,30 +3013,30 @@ static Model LoadIQM(const char *fileName) fread(imesh, sizeof(IQMMesh)*iqm.num_meshes, 1, iqmFile); model.meshCount = iqm.num_meshes; - model.meshes = malloc(sizeof(Mesh)*iqm.num_meshes); + model.meshes = malloc(model.meshCount*sizeof(Mesh)); char name[MESH_NAME_LENGTH]; - for (int i = 0; i < iqm.num_meshes; i++) + for (int i = 0; i < model.meshCount; i++) { fseek(iqmFile,iqm.ofs_text+imesh[i].name,SEEK_SET); fread(name, sizeof(char)*MESH_NAME_LENGTH, 1, iqmFile); // Mesh name not used... model.meshes[i].vertexCount = imesh[i].num_vertexes; - model.meshes[i].vertices = malloc(sizeof(float)*imesh[i].num_vertexes*3); // Default vertex positions - model.meshes[i].normals = malloc(sizeof(float)*imesh[i].num_vertexes*3); // Default vertex normals - model.meshes[i].texcoords = malloc(sizeof(float)*imesh[i].num_vertexes*2); // Default vertex texcoords + model.meshes[i].vertices = malloc(sizeof(float)*model.meshes[i].vertexCount*3); // Default vertex positions + model.meshes[i].normals = malloc(sizeof(float)*model.meshes[i].vertexCount*3); // Default vertex normals + model.meshes[i].texcoords = malloc(sizeof(float)*model.meshes[i].vertexCount*2); // Default vertex texcoords - model.meshes[i].boneIds = malloc(sizeof(int)*imesh[i].num_vertexes*4); // Up-to 4 bones supported! - model.meshes[i].boneWeights = malloc(sizeof(float)*imesh[i].num_vertexes*4); // Up-to 4 bones supported! + model.meshes[i].boneIds = malloc(sizeof(int)*model.meshes[i].vertexCount*4); // Up-to 4 bones supported! + model.meshes[i].boneWeights = malloc(sizeof(float)*model.meshes[i].vertexCount*4); // Up-to 4 bones supported! model.meshes[i].triangleCount = imesh[i].num_triangles; - model.meshes[i].indices = malloc(sizeof(unsigned short)*imesh[i].num_triangles*3); + model.meshes[i].indices = malloc(sizeof(unsigned short)*model.meshes[i].triangleCount*3); // Animated verted data, what we actually process for rendering // NOTE: Animated vertex should be re-uploaded to GPU (if not using GPU skinning) - model.meshes[i].animVertices = malloc(sizeof(float)*imesh[i].num_vertexes*3); - model.meshes[i].animNormals = malloc(sizeof(float)*imesh[i].num_vertexes*3); + model.meshes[i].animVertices = malloc(sizeof(float)*model.meshes[i].vertexCount*3); + model.meshes[i].animNormals = malloc(sizeof(float)*model.meshes[i].vertexCount*3); } // Triangles data processing @@ -3044,15 +3044,15 @@ static Model LoadIQM(const char *fileName) fseek(iqmFile, iqm.ofs_triangles, SEEK_SET); fread(tri, sizeof(IQMTriangle)*iqm.num_triangles, 1, iqmFile); - for (int m = 0; m < iqm.num_meshes; m++) + for (int m = 0; m < model.meshCount; m++) { int tcounter = 0; - for (int i = imesh[m].first_triangle; i < imesh[m].first_triangle+imesh[m].num_triangles; i++) + for (int i = imesh[m].first_triangle; i < (imesh[m].first_triangle + imesh[m].num_triangles); i++) { // IQM triangles are stored counter clockwise, but raylib sets opengl to clockwise drawing, so we swap them around - model.meshes[m].indices[tcounter+2] = tri[i].vertex[0] - imesh[m].first_vertex; - model.meshes[m].indices[tcounter+1] = tri[i].vertex[1] - imesh[m].first_vertex; + model.meshes[m].indices[tcounter + 2] = tri[i].vertex[0] - imesh[m].first_vertex; + model.meshes[m].indices[tcounter + 1] = tri[i].vertex[1] - imesh[m].first_vertex; model.meshes[m].indices[tcounter] = tri[i].vertex[2] - imesh[m].first_vertex; tcounter += 3; } @@ -3235,7 +3235,7 @@ static Model LoadGLTF(const char *fileName) fclose(gltfFile); // glTF data loading - cgltf_options options = {0}; + cgltf_options options = { 0 }; cgltf_data *data; cgltf_result result = cgltf_parse(&options, buffer, size, &data); @@ -3243,11 +3243,33 @@ static Model LoadGLTF(const char *fileName) if (result == cgltf_result_success) { - // printf("Type: %u\n", data.file_type); - // printf("Version: %d\n", data.version); - // printf("Meshes: %lu\n", data.meshes_count); + TraceLog(LOG_INFO, "[%s][%s] Model meshes/materials: %i/%i", (data->file_type == 2)? "glb" : "gltf", data->meshes_count, data->materials_count); + + // Read data buffers + result = cgltf_load_buffers(&options, data, fileName); + + // Process glTF data and map to model + model.meshCount = data->meshes_count; + model.meshes = malloc(model.meshCount*sizeof(Mesh)); + + for (int i = 0; i < model.meshCount; i++) + { + // NOTE: Only support meshes defined by triangle primitives + //if (data->meshes[i].primitives[n].type == cgltf_primitive_type_triangles) + { + // data.meshes[i].name not used + model.meshes[i].vertexCount = data->meshes[i].primitives_count*3; + model.meshes[i].triangleCount = data->meshes[i].primitives_count; + // data.meshes[i].weights not used (array of weights to be applied to the Morph Targets) + + model.meshes[i].vertices = malloc(sizeof(float)*model.meshes[i].vertexCount*3); // Default vertex positions + model.meshes[i].normals = malloc(sizeof(float)*model.meshes[i].vertexCount*3); // Default vertex normals + model.meshes[i].texcoords = malloc(sizeof(float)*model.meshes[i].vertexCount*2); // Default vertex texcoords + + model.meshes[i].indices = malloc(sizeof(unsigned short)*model.meshes[i].triangleCount*3); - // TODO: Process glTF data and map to model + } + } // NOTE: data.buffers[] should be loaded to model.meshes and data.images[] should be loaded to model.materials // Use buffers[n].uri and images[n].uri... or use cgltf_load_buffers(&options, data, fileName); -- cgit v1.2.3 From f939f6abc2796fa019134e9d6c80cf7d0252eb76 Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 9 Apr 2019 13:23:56 +0200 Subject: Update Makefile --- src/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/Makefile b/src/Makefile index 0217c198..997f041c 100644 --- a/src/Makefile +++ b/src/Makefile @@ -155,7 +155,7 @@ endif ifeq ($(PLATFORM),PLATFORM_WEB) # Emscripten required variables EMSDK_PATH = C:/emsdk - EMSCRIPTEN_VERSION ?= 1.38.21 + EMSCRIPTEN_VERSION ?= 1.38.30 CLANG_VERSION = e$(EMSCRIPTEN_VERSION)_64bit PYTHON_VERSION = 2.7.13.1_64bit\python-2.7.13.amd64 NODE_VERSION = 8.9.1_64bit -- cgit v1.2.3 From 148eefb9bb67a4b72bb90ea9a740db3cc3c081d3 Mon Sep 17 00:00:00 2001 From: myd7349 Date: Tue, 9 Apr 2019 20:41:40 +0800 Subject: Resolve CI failure with MinGW --- src/CMakeLists.txt | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index c24853a1..7b69e0f9 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -188,10 +188,12 @@ if(SHARED) PUBLIC ${GRAPHICS} ) - target_compile_definitions(raylib + if(MSVC) + target_compile_definitions(raylib PRIVATE $ INTERFACE $ - ) + ) + endif() set(PKG_CONFIG_LIBS_EXTRA "") -- cgit v1.2.3 From 802afe8fe533bc66a6ebd2810090b08d1f635991 Mon Sep 17 00:00:00 2001 From: Ray Date: Wed, 10 Apr 2019 00:34:46 +0200 Subject: Replaced size_t by unsigned int --- src/external/tinyobj_loader_c.h | 174 ++++++++++++++++++++-------------------- 1 file changed, 87 insertions(+), 87 deletions(-) (limited to 'src') diff --git a/src/external/tinyobj_loader_c.h b/src/external/tinyobj_loader_c.h index ae975829..846784fa 100644 --- a/src/external/tinyobj_loader_c.h +++ b/src/external/tinyobj_loader_c.h @@ -24,8 +24,8 @@ #ifndef TINOBJ_LOADER_C_H_ #define TINOBJ_LOADER_C_H_ -/* @todo { Remove stddef dependency. size_t? } */ -#include +/* @todo { Remove stddef dependency. unsigned int? } ---> RAY: DONE. */ +//#include typedef struct { char *name; @@ -93,18 +93,18 @@ typedef struct { * Returns TINYOBJ_ERR_*** when there is an error. */ extern int tinyobj_parse_obj(tinyobj_attrib_t *attrib, tinyobj_shape_t **shapes, - size_t *num_shapes, tinyobj_material_t **materials, - size_t *num_materials, const char *buf, size_t len, + unsigned int *num_shapes, tinyobj_material_t **materials, + unsigned int *num_materials, const char *buf, unsigned int len, unsigned int flags); extern int tinyobj_parse_mtl_file(tinyobj_material_t **materials_out, - size_t *num_materials_out, + unsigned int *num_materials_out, const char *filename); extern void tinyobj_attrib_init(tinyobj_attrib_t *attrib); extern void tinyobj_attrib_free(tinyobj_attrib_t *attrib); -extern void tinyobj_shapes_free(tinyobj_shape_t *shapes, size_t num_shapes); +extern void tinyobj_shapes_free(tinyobj_shape_t *shapes, unsigned int num_shapes); extern void tinyobj_materials_free(tinyobj_material_t *materials, - size_t num_materials); + unsigned int num_materials); #ifdef TINYOBJ_LOADER_C_IMPLEMENTATION #include @@ -155,8 +155,8 @@ static int until_space(const char *token) { return (int)(p - token); } -static size_t length_until_newline(const char *token, size_t n) { - size_t len = 0; +static unsigned int length_until_newline(const char *token, unsigned int n) { + unsigned int len = 0; /* Assume token[n-1] = '\0' */ for (len = 0; len < n - 1; len++) { @@ -171,8 +171,8 @@ static size_t length_until_newline(const char *token, size_t n) { return len; } -static size_t length_until_line_feed(const char *token, size_t n) { - size_t len = 0; +static unsigned int length_until_line_feed(const char *token, unsigned int n) { + unsigned int len = 0; /* Assume token[n-1] = '\0' */ for (len = 0; len < n; len++) { @@ -202,7 +202,7 @@ static int my_atoi(const char *c) { } /* Make index zero-base, and also support relative index. */ -static int fixIndex(int idx, size_t n) { +static int fixIndex(int idx, unsigned int n) { if (idx > 0) return idx - 1; if (idx == 0) return 0; return (int)n + idx; /* negative value = relative */ @@ -453,9 +453,9 @@ static void parseFloat3(float *x, float *y, float *z, const char **token) { (*z) = parseFloat(token); } -static char *my_strdup(const char *s, size_t max_length) { +static char *my_strdup(const char *s, unsigned int max_length) { char *d; - size_t len; + unsigned int len; if (s == NULL) return NULL; @@ -465,15 +465,15 @@ static char *my_strdup(const char *s, size_t max_length) { /* trim line ending and append '\0' */ d = (char *)TINYOBJ_MALLOC(len + 1); /* + '\0' */ - memcpy(d, s, (size_t)(len)); + memcpy(d, s, (unsigned int)(len)); d[len] = '\0'; return d; } -static char *my_strndup(const char *s, size_t len) { +static char *my_strndup(const char *s, unsigned int len) { char *d; - size_t slen; + unsigned int slen; if (s == NULL) return NULL; if (len == 0) return NULL; @@ -491,10 +491,10 @@ static char *my_strndup(const char *s, size_t len) { return d; } -char *dynamic_fgets(char **buf, size_t *size, FILE *file) { +char *dynamic_fgets(char **buf, unsigned int *size, FILE *file) { char *offset; char *ret; - size_t old_size; + unsigned int old_size; if (!(ret = fgets(*buf, (int)*size, file))) { return ret; @@ -560,8 +560,8 @@ typedef struct { unsigned long* hashes; hash_table_entry_t* entries; - size_t capacity; - size_t n; + unsigned int capacity; + unsigned int n; } hash_table_t; static unsigned long hash_djb2(const unsigned char* str) @@ -576,7 +576,7 @@ static unsigned long hash_djb2(const unsigned char* str) return hash; } -static void create_hash_table(size_t start_capacity, hash_table_t* hash_table) +static void create_hash_table(unsigned int start_capacity, hash_table_t* hash_table) { if (start_capacity < 1) start_capacity = HASH_TABLE_DEFAULT_SIZE; @@ -596,10 +596,10 @@ static void destroy_hash_table(hash_table_t* hash_table) static int hash_table_insert_value(unsigned long hash, long value, hash_table_t* hash_table) { /* Insert value */ - size_t start_index = hash % hash_table->capacity; - size_t index = start_index; + unsigned int start_index = hash % hash_table->capacity; + unsigned int index = start_index; hash_table_entry_t* start_entry = hash_table->entries + start_index; - size_t i; + unsigned int i; hash_table_entry_t* entry; for (i = 1; hash_table->entries[index].filled; i++) @@ -648,11 +648,11 @@ static hash_table_entry_t* hash_table_find(unsigned long hash, hash_table_t* has return NULL; } -static void hash_table_maybe_grow(size_t new_n, hash_table_t* hash_table) +static void hash_table_maybe_grow(unsigned int new_n, hash_table_t* hash_table) { - size_t new_capacity; + unsigned int new_capacity; hash_table_t new_hash_table; - size_t i; + unsigned int i; if (new_n <= hash_table->capacity) { return; @@ -680,7 +680,7 @@ static int hash_table_exists(const char* name, hash_table_t* hash_table) return hash_table_find(hash_djb2((const unsigned char*)name), hash_table) != NULL; } -static void hash_table_set(const char* name, size_t val, hash_table_t* hash_table) +static void hash_table_set(const char* name, unsigned int val, hash_table_t* hash_table) { /* Hash name */ unsigned long hash = hash_djb2((const unsigned char *)name); @@ -709,7 +709,7 @@ static long hash_table_get(const char* name, hash_table_t* hash_table) } static tinyobj_material_t *tinyobj_material_add(tinyobj_material_t *prev, - size_t num_materials, + unsigned int num_materials, tinyobj_material_t *new_mat) { tinyobj_material_t *dst; dst = (tinyobj_material_t *)TINYOBJ_REALLOC( @@ -720,14 +720,14 @@ static tinyobj_material_t *tinyobj_material_add(tinyobj_material_t *prev, } static int tinyobj_parse_and_index_mtl_file(tinyobj_material_t **materials_out, - size_t *num_materials_out, + unsigned int *num_materials_out, const char *filename, hash_table_t* material_table) { tinyobj_material_t material; - size_t buffer_size = 128; + unsigned int buffer_size = 128; char *linebuf; FILE *fp; - size_t num_materials = 0; + unsigned int num_materials = 0; tinyobj_material_t *materials = NULL; int has_previous_material = 0; const char *line_end = NULL; @@ -788,7 +788,7 @@ static int tinyobj_parse_and_index_mtl_file(tinyobj_material_t **materials_out, #else sscanf(token, "%s", namebuf); #endif - material.name = my_strdup(namebuf, (size_t) (line_end - token)); + material.name = my_strdup(namebuf, (unsigned int) (line_end - token)); /* Add material to material table */ if (material_table) @@ -889,56 +889,56 @@ static int tinyobj_parse_and_index_mtl_file(tinyobj_material_t **materials_out, /* ambient texture */ if ((0 == strncmp(token, "map_Ka", 6)) && IS_SPACE(token[6])) { token += 7; - material.ambient_texname = my_strdup(token, (size_t) (line_end - token)); + material.ambient_texname = my_strdup(token, (unsigned int) (line_end - token)); continue; } /* diffuse texture */ if ((0 == strncmp(token, "map_Kd", 6)) && IS_SPACE(token[6])) { token += 7; - material.diffuse_texname = my_strdup(token, (size_t) (line_end - token)); + material.diffuse_texname = my_strdup(token, (unsigned int) (line_end - token)); continue; } /* specular texture */ if ((0 == strncmp(token, "map_Ks", 6)) && IS_SPACE(token[6])) { token += 7; - material.specular_texname = my_strdup(token, (size_t) (line_end - token)); + material.specular_texname = my_strdup(token, (unsigned int) (line_end - token)); continue; } /* specular highlight texture */ if ((0 == strncmp(token, "map_Ns", 6)) && IS_SPACE(token[6])) { token += 7; - material.specular_highlight_texname = my_strdup(token, (size_t) (line_end - token)); + material.specular_highlight_texname = my_strdup(token, (unsigned int) (line_end - token)); continue; } /* bump texture */ if ((0 == strncmp(token, "map_bump", 8)) && IS_SPACE(token[8])) { token += 9; - material.bump_texname = my_strdup(token, (size_t) (line_end - token)); + material.bump_texname = my_strdup(token, (unsigned int) (line_end - token)); continue; } /* alpha texture */ if ((0 == strncmp(token, "map_d", 5)) && IS_SPACE(token[5])) { token += 6; - material.alpha_texname = my_strdup(token, (size_t) (line_end - token)); + material.alpha_texname = my_strdup(token, (unsigned int) (line_end - token)); continue; } /* bump texture */ if ((0 == strncmp(token, "bump", 4)) && IS_SPACE(token[4])) { token += 5; - material.bump_texname = my_strdup(token, (size_t) (line_end - token)); + material.bump_texname = my_strdup(token, (unsigned int) (line_end - token)); continue; } /* displacement texture */ if ((0 == strncmp(token, "disp", 4)) && IS_SPACE(token[4])) { token += 5; - material.displacement_texname = my_strdup(token, (size_t) (line_end - token)); + material.displacement_texname = my_strdup(token, (unsigned int) (line_end - token)); continue; } @@ -962,7 +962,7 @@ static int tinyobj_parse_and_index_mtl_file(tinyobj_material_t **materials_out, } int tinyobj_parse_mtl_file(tinyobj_material_t **materials_out, - size_t *num_materials_out, + unsigned int *num_materials_out, const char *filename) { return tinyobj_parse_and_index_mtl_file(materials_out, num_materials_out, filename, NULL); } @@ -988,10 +988,10 @@ typedef struct { /* @todo { Use dynamic array } */ tinyobj_vertex_index_t f[TINYOBJ_MAX_FACES_PER_F_LINE]; - size_t num_f; + unsigned int num_f; int f_num_verts[TINYOBJ_MAX_FACES_PER_F_LINE]; - size_t num_f_num_verts; + unsigned int num_f_num_verts; const char *group_name; unsigned int group_name_len; @@ -1011,7 +1011,7 @@ typedef struct { CommandType type; } Command; -static int parseLine(Command *command, const char *p, size_t p_len, +static int parseLine(Command *command, const char *p, unsigned int p_len, int triangulate) { char linebuf[4096]; const char *token; @@ -1073,7 +1073,7 @@ static int parseLine(Command *command, const char *p, size_t p_len, /* face */ if (token[0] == 'f' && IS_SPACE((token[1]))) { - size_t num_f = 0; + unsigned int num_f = 0; tinyobj_vertex_index_t f[TINYOBJ_MAX_FACES_PER_F_LINE]; token += 2; @@ -1090,8 +1090,8 @@ static int parseLine(Command *command, const char *p, size_t p_len, command->type = COMMAND_F; if (triangulate) { - size_t k; - size_t n = 0; + unsigned int k; + unsigned int n = 0; tinyobj_vertex_index_t i0 = f[0]; tinyobj_vertex_index_t i1; @@ -1113,7 +1113,7 @@ static int parseLine(Command *command, const char *p, size_t p_len, command->num_f_num_verts = n; } else { - size_t k = 0; + unsigned int k = 0; assert(num_f < TINYOBJ_MAX_FACES_PER_F_LINE); for (k = 0; k < num_f; k++) { command->f[k] = f[k]; @@ -1134,7 +1134,7 @@ static int parseLine(Command *command, const char *p, size_t p_len, skip_space(&token); command->material_name = p + (token - linebuf); command->material_name_len = (unsigned int)length_until_newline( - token, (p_len - (size_t)(token - linebuf)) + 1); + token, (p_len - (unsigned int)(token - linebuf)) + 1); command->type = COMMAND_USEMTL; return 1; @@ -1148,7 +1148,7 @@ static int parseLine(Command *command, const char *p, size_t p_len, skip_space(&token); command->mtllib_name = p + (token - linebuf); command->mtllib_name_len = (unsigned int)length_until_newline( - token, p_len - (size_t)(token - linebuf)) + + token, p_len - (unsigned int)(token - linebuf)) + 1; command->type = COMMAND_MTLLIB; @@ -1162,7 +1162,7 @@ static int parseLine(Command *command, const char *p, size_t p_len, command->group_name = p + (token - linebuf); command->group_name_len = (unsigned int)length_until_newline( - token, p_len - (size_t)(token - linebuf)) + + token, p_len - (unsigned int)(token - linebuf)) + 1; command->type = COMMAND_G; @@ -1176,7 +1176,7 @@ static int parseLine(Command *command, const char *p, size_t p_len, command->object_name = p + (token - linebuf); command->object_name_len = (unsigned int)length_until_newline( - token, p_len - (size_t)(token - linebuf)) + + token, p_len - (unsigned int)(token - linebuf)) + 1; command->type = COMMAND_O; @@ -1187,11 +1187,11 @@ static int parseLine(Command *command, const char *p, size_t p_len, } typedef struct { - size_t pos; - size_t len; + unsigned int pos; + unsigned int len; } LineInfo; -static int is_line_ending(const char *p, size_t i, size_t end_i) { +static int is_line_ending(const char *p, unsigned int i, unsigned int end_i) { if (p[i] == '\0') return 1; if (p[i] == '\n') return 1; /* this includes \r\n */ if (p[i] == '\r') { @@ -1203,23 +1203,23 @@ static int is_line_ending(const char *p, size_t i, size_t end_i) { } int tinyobj_parse_obj(tinyobj_attrib_t *attrib, tinyobj_shape_t **shapes, - size_t *num_shapes, tinyobj_material_t **materials_out, - size_t *num_materials_out, const char *buf, size_t len, + unsigned int *num_shapes, tinyobj_material_t **materials_out, + unsigned int *num_materials_out, const char *buf, unsigned int len, unsigned int flags) { LineInfo *line_infos = NULL; Command *commands = NULL; - size_t num_lines = 0; + unsigned int num_lines = 0; - size_t num_v = 0; - size_t num_vn = 0; - size_t num_vt = 0; - size_t num_f = 0; - size_t num_faces = 0; + unsigned int num_v = 0; + unsigned int num_vn = 0; + unsigned int num_vt = 0; + unsigned int num_f = 0; + unsigned int num_faces = 0; int mtllib_line_index = -1; tinyobj_material_t *materials = NULL; - size_t num_materials = 0; + unsigned int num_materials = 0; hash_table_t material_table; @@ -1234,11 +1234,11 @@ int tinyobj_parse_obj(tinyobj_attrib_t *attrib, tinyobj_shape_t **shapes, tinyobj_attrib_init(attrib); /* 1. Find '\n' and create line data. */ { - size_t i; - size_t end_idx = len; - size_t prev_pos = 0; - size_t line_no = 0; - size_t last_line_ending = 0; + unsigned int i; + unsigned int end_idx = len; + unsigned int prev_pos = 0; + unsigned int line_no = 0; + unsigned int last_line_ending = 0; /* Count # of lines. */ for (i = 0; i < end_idx; i++) { @@ -1280,7 +1280,7 @@ int tinyobj_parse_obj(tinyobj_attrib_t *attrib, tinyobj_shape_t **shapes, /* 2. parse each line */ { - size_t i = 0; + unsigned int i = 0; for (i = 0; i < num_lines; i++) { int ret = parseLine(&commands[i], &buf[line_infos[i].pos], line_infos[i].len, flags & TINYOBJ_FLAG_TRIANGULATE); @@ -1328,13 +1328,13 @@ int tinyobj_parse_obj(tinyobj_attrib_t *attrib, tinyobj_shape_t **shapes, /* Construct attributes */ { - size_t v_count = 0; - size_t n_count = 0; - size_t t_count = 0; - size_t f_count = 0; - size_t face_count = 0; + unsigned int v_count = 0; + unsigned int n_count = 0; + unsigned int t_count = 0; + unsigned int f_count = 0; + unsigned int face_count = 0; int material_id = -1; /* -1 = default unknown material. */ - size_t i = 0; + unsigned int i = 0; attrib->vertices = (float *)TINYOBJ_MALLOC(sizeof(float) * num_v * 3); attrib->num_vertices = (unsigned int)num_v; @@ -1398,7 +1398,7 @@ int tinyobj_parse_obj(tinyobj_attrib_t *attrib, tinyobj_shape_t **shapes, attrib->texcoords[2 * t_count + 1] = commands[i].ty; t_count++; } else if (commands[i].type == COMMAND_F) { - size_t k = 0; + unsigned int k = 0; for (k = 0; k < commands[i].num_f; k++) { tinyobj_vertex_index_t vi = commands[i].f[k]; int v_idx = fixIndex(vi.v_idx, v_count); @@ -1423,9 +1423,9 @@ int tinyobj_parse_obj(tinyobj_attrib_t *attrib, tinyobj_shape_t **shapes, /* 5. Construct shape information. */ { unsigned int face_count = 0; - size_t i = 0; - size_t n = 0; - size_t shape_idx = 0; + unsigned int i = 0; + unsigned int n = 0; + unsigned int shape_idx = 0; const char *shape_name = NULL; unsigned int shape_name_len = 0; @@ -1497,7 +1497,7 @@ int tinyobj_parse_obj(tinyobj_attrib_t *attrib, tinyobj_shape_t **shapes, } if ((face_count - prev_face_offset) > 0) { - size_t length = face_count - prev_shape_face_offset; + unsigned int length = face_count - prev_shape_face_offset; if (length > 0) { (*shapes)[shape_idx].name = my_strndup(prev_shape_name, prev_shape_name_len); @@ -1548,8 +1548,8 @@ void tinyobj_attrib_free(tinyobj_attrib_t *attrib) { if (attrib->material_ids) TINYOBJ_FREE(attrib->material_ids); } -void tinyobj_shapes_free(tinyobj_shape_t *shapes, size_t num_shapes) { - size_t i; +void tinyobj_shapes_free(tinyobj_shape_t *shapes, unsigned int num_shapes) { + unsigned int i; if (shapes == NULL) return; for (i = 0; i < num_shapes; i++) { @@ -1560,8 +1560,8 @@ void tinyobj_shapes_free(tinyobj_shape_t *shapes, size_t num_shapes) { } void tinyobj_materials_free(tinyobj_material_t *materials, - size_t num_materials) { - size_t i; + unsigned int num_materials) { + unsigned int i; if (materials == NULL) return; for (i = 0; i < num_materials; i++) { -- cgit v1.2.3 From 21092266b57f9f444c51905fceb4eda1dd7f83c3 Mon Sep 17 00:00:00 2001 From: Ray Date: Wed, 10 Apr 2019 00:44:24 +0200 Subject: Check textures available before loading --- src/models.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/models.c b/src/models.c index 73f8b940..f10df262 100644 --- a/src/models.c +++ b/src/models.c @@ -2846,21 +2846,21 @@ static Model LoadOBJ(const char *fileName) } tinyobj_material_t; */ - model.materials[m].maps[MAP_DIFFUSE].texture = LoadTexture(materials[m].diffuse_texname); //char *diffuse_texname; // map_Kd + if (materials[m].diffuse_texname != NULL) model.materials[m].maps[MAP_DIFFUSE].texture = LoadTexture(materials[m].diffuse_texname); //char *diffuse_texname; // map_Kd model.materials[m].maps[MAP_DIFFUSE].color = (Color){ (float)(materials[m].diffuse[0]*255.0f), (float)(materials[m].diffuse[1]*255.0f), (float)(materials[m].diffuse[2]*255.0f), 255 }; //float diffuse[3]; model.materials[m].maps[MAP_DIFFUSE].value = 0.0f; - model.materials[m].maps[MAP_SPECULAR].texture = LoadTexture(materials[m].specular_texname); //char *specular_texname; // map_Ks + if (materials[m].specular_texname != NULL) model.materials[m].maps[MAP_SPECULAR].texture = LoadTexture(materials[m].specular_texname); //char *specular_texname; // map_Ks model.materials[m].maps[MAP_SPECULAR].color = (Color){ (float)(materials[m].specular[0]*255.0f), (float)(materials[m].specular[1]*255.0f), (float)(materials[m].specular[2]*255.0f), 255 }; //float specular[3]; model.materials[m].maps[MAP_SPECULAR].value = 0.0f; - model.materials[m].maps[MAP_NORMAL].texture = LoadTexture(materials[m].bump_texname); //char *bump_texname; // map_bump, bump + if (materials[m].bump_texname != NULL) model.materials[m].maps[MAP_NORMAL].texture = LoadTexture(materials[m].bump_texname); //char *bump_texname; // map_bump, bump model.materials[m].maps[MAP_NORMAL].color = WHITE; model.materials[m].maps[MAP_NORMAL].value = materials[m].shininess; model.materials[m].maps[MAP_EMISSION].color = (Color){ (float)(materials[m].emission[0]*255.0f), (float)(materials[m].emission[1]*255.0f), (float)(materials[m].emission[2]*255.0f), 255 }; //float emission[3]; - model.materials[m].maps[MAP_HEIGHT].texture = LoadTexture(materials[m].displacement_texname); //char *displacement_texname; // disp + if (materials[m].displacement_texname != NULL) model.materials[m].maps[MAP_HEIGHT].texture = LoadTexture(materials[m].displacement_texname); //char *displacement_texname; // disp } tinyobj_attrib_free(&attrib); -- cgit v1.2.3 From 45c820eeb4e4f559b09c382df5a7808fb1c95115 Mon Sep 17 00:00:00 2001 From: Ray Date: Wed, 10 Apr 2019 22:39:42 +0200 Subject: Set default white texture for diffuse mat --- src/models.c | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src') diff --git a/src/models.c b/src/models.c index f10df262..d8508492 100644 --- a/src/models.c +++ b/src/models.c @@ -2846,6 +2846,8 @@ static Model LoadOBJ(const char *fileName) } tinyobj_material_t; */ + model.materials[m].maps[MAP_DIFFUSE].texture = GetTextureDefault(); // Get default texture, in case no texture is defined + if (materials[m].diffuse_texname != NULL) model.materials[m].maps[MAP_DIFFUSE].texture = LoadTexture(materials[m].diffuse_texname); //char *diffuse_texname; // map_Kd model.materials[m].maps[MAP_DIFFUSE].color = (Color){ (float)(materials[m].diffuse[0]*255.0f), (float)(materials[m].diffuse[1]*255.0f), (float)(materials[m].diffuse[2]*255.0f), 255 }; //float diffuse[3]; model.materials[m].maps[MAP_DIFFUSE].value = 0.0f; -- cgit v1.2.3 From 6168a4ca376d26dcac8a19967987280ed399f337 Mon Sep 17 00:00:00 2001 From: Ray Date: Wed, 10 Apr 2019 23:50:48 +0200 Subject: Comments review --- src/raylib.h | 54 ++++++++++++++++++++++++++++-------------------------- 1 file changed, 28 insertions(+), 26 deletions(-) (limited to 'src') diff --git a/src/raylib.h b/src/raylib.h index dade7aba..e4e41a15 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -4,19 +4,20 @@ * * FEATURES: * - NO external dependencies, all required libraries included with raylib -* - Multiple platforms support: Windows, Linux, FreeBSD, OpenBSD, NetBSD, DragonFly, MacOS, UWP, Android, Raspberry Pi, HTML5. +* - Multiplatform: Windows, Linux, FreeBSD, OpenBSD, NetBSD, DragonFly, MacOS, UWP, Android, Raspberry Pi, HTML5. * - Written in plain C code (C99) in PascalCase/camelCase notation * - Hardware accelerated with OpenGL (1.1, 2.1, 3.3 or ES2 - choose at compile) * - Unique OpenGL abstraction layer (usable as standalone module): [rlgl] -* - Powerful fonts module with Fonts support (XNA fonts, AngelCode fonts, TTF) +* - Powerful fonts module (XNA SpriteFonts, BMFonts, TTF) * - Outstanding texture formats support, including compressed formats (DXT, ETC, ASTC) * - Full 3d support for 3d Shapes, Models, Billboards, Heightmaps and more! * - Flexible Materials system, supporting classic maps and PBR maps +* - Skeletal Animation support (CPU bones-based animation) * - Shaders support, including Model shaders and Postprocessing shaders * - Powerful math module for Vector, Matrix and Quaternion operations: [raymath] * - Audio loading and playing with streaming support (WAV, OGG, MP3, FLAC, XM, MOD) * - VR stereo rendering with configurable HMD device parameters -* - Complete bindings to LUA (raylib-lua) and Go (raylib-go) +* - Bindings to multiple programming languages available! * * NOTES: * One custom font is loaded by default when InitWindow() [core] @@ -24,24 +25,26 @@ * If using OpenGL 3.3 or ES2, several vertex buffers (VAO/VBO) are created to manage lines-triangles-quads * * DEPENDENCIES (included): -* rglfw (github.com/glfw/glfw) for window/context management and input (only PLATFORM_DESKTOP) [core] -* glad (github.com/Dav1dde/glad) for OpenGL extensions loading (3.3 Core profile, only PLATFORM_DESKTOP) [rlgl] -* mini_al (github.com/dr-soft/mini_al) for audio device/context management [audio] +* [core] rglfw (github.com/glfw/glfw) for window/context management and input (only PLATFORM_DESKTOP) +* [rlgl] glad (github.com/Dav1dde/glad) for OpenGL extensions loading (3.3 Core profile, only PLATFORM_DESKTOP) +* [raudio] miniaudio (github.com/dr-soft/miniaudio) for audio device/context management * * OPTIONAL DEPENDENCIES (included): -* stb_image (Sean Barret) for images loading (BMP, TGA, PNG, JPEG, HDR...) [textures] -* stb_image_resize (Sean Barret) for image resizing algorythms [textures] -* stb_image_write (Sean Barret) for image writting (PNG) [utils] -* stb_truetype (Sean Barret) for ttf fonts loading [text] -* stb_rect_pack (Sean Barret) for rectangles packing [text] -* stb_vorbis (Sean Barret) for OGG audio loading [audio] -* stb_perlin (Sean Barret) for Perlin noise image generation [textures] -* par_shapes (Philip Rideout) for parametric 3d shapes generation [models] -* jar_xm (Joshua Reisenauer) for XM audio module loading [audio] -* jar_mod (Joshua Reisenauer) for MOD audio module loading [audio] -* dr_flac (David Reid) for FLAC audio file loading [audio] -* dr_mp3 (David Reid) for MP3 audio file loading [audio] -* rgif (Charlie Tangora, Ramon Santamaria) for GIF recording [core] +* [core] rgif (Charlie Tangora, Ramon Santamaria) for GIF recording +* [textures] stb_image (Sean Barret) for images loading (BMP, TGA, PNG, JPEG, HDR...) +* [textures] stb_image_write (Sean Barret) for image writting (BMP, TGA, PNG, JPG) +* [textures] stb_image_resize (Sean Barret) for image resizing algorythms +* [textures] stb_perlin (Sean Barret) for Perlin noise image generation +* [text] stb_truetype (Sean Barret) for ttf fonts loading +* [text] stb_rect_pack (Sean Barret) for rectangles packing +* [models] par_shapes (Philip Rideout) for parametric 3d shapes generation +* [models] tinyobj_loader_c (Syoyo Fujita) for models loading (OBJ, MTL) +* [models] cgltf (Johannes Kuhlmann) for models loading (glTF) +* [raudio] stb_vorbis (Sean Barret) for OGG audio loading +* [raudio] dr_flac (David Reid) for FLAC audio file loading +* [raudio] dr_mp3 (David Reid) for MP3 audio file loading +* [raudio] jar_xm (Joshua Reisenauer) for XM audio module loading +* [raudio] jar_mod (Joshua Reisenauer) for MOD audio module loading * * * LICENSE: zlib/libpng @@ -144,13 +147,6 @@ //---------------------------------------------------------------------------------- // Structures Definition //---------------------------------------------------------------------------------- -// Boolean type -#if defined(__STDC__) && __STDC_VERSION__ >= 199901L - #include -#elif !defined(__cplusplus) && !defined(bool) - typedef enum { false, true } bool; -#endif - // Vector2 type typedef struct Vector2 { float x; @@ -453,6 +449,12 @@ typedef struct VrStereoConfig { //---------------------------------------------------------------------------------- // Enumerators Definition //---------------------------------------------------------------------------------- +// Boolean type +#if defined(__STDC__) && __STDC_VERSION__ >= 199901L + #include +#elif !defined(__cplusplus) && !defined(bool) + typedef enum { false, true } bool; +#endif // System config flags // NOTE: Used for bit masks -- cgit v1.2.3 From 1934f2a2f404b08a9dd5541a5407262b6fc4bb6a Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 11 Apr 2019 00:11:11 +0200 Subject: Some tweaks --- src/raylib.h | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) (limited to 'src') diff --git a/src/raylib.h b/src/raylib.h index e4e41a15..e8d927cb 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -26,7 +26,7 @@ * * DEPENDENCIES (included): * [core] rglfw (github.com/glfw/glfw) for window/context management and input (only PLATFORM_DESKTOP) -* [rlgl] glad (github.com/Dav1dde/glad) for OpenGL extensions loading (3.3 Core profile, only PLATFORM_DESKTOP) +* [rlgl] glad (github.com/Dav1dde/glad) for OpenGL 3.3 extensions loading (only PLATFORM_DESKTOP) * [raudio] miniaudio (github.com/dr-soft/miniaudio) for audio device/context management * * OPTIONAL DEPENDENCIES (included): @@ -147,6 +147,13 @@ //---------------------------------------------------------------------------------- // Structures Definition //---------------------------------------------------------------------------------- +// Boolean type +#if defined(__STDC__) && __STDC_VERSION__ >= 199901L + #include +#elif !defined(__cplusplus) && !defined(bool) + typedef enum { false, true } bool; +#endif + // Vector2 type typedef struct Vector2 { float x; @@ -449,13 +456,6 @@ typedef struct VrStereoConfig { //---------------------------------------------------------------------------------- // Enumerators Definition //---------------------------------------------------------------------------------- -// Boolean type -#if defined(__STDC__) && __STDC_VERSION__ >= 199901L - #include -#elif !defined(__cplusplus) && !defined(bool) - typedef enum { false, true } bool; -#endif - // System config flags // NOTE: Used for bit masks typedef enum { @@ -471,14 +471,14 @@ typedef enum { // Trace log type typedef enum { - LOG_ALL, // Display all logs + LOG_ALL = 0, // Display all logs LOG_TRACE, LOG_DEBUG, LOG_INFO, LOG_WARNING, LOG_ERROR, LOG_FATAL, - LOG_NONE // Disable logging + LOG_NONE // Disable logging } TraceLogType; // Keyboard keys -- cgit v1.2.3 From 5bfa67535040ed1cb717908d9f259db0c302d9e6 Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 11 Apr 2019 13:53:01 +0200 Subject: Review VR simulator mechanism - No default VR device parameteres inside raylib - VR device parameter should be provided by user - VR distortion shader should be provided by user --- src/config.h | 2 - src/raylib.h | 30 +---- src/rlgl.h | 414 +++++++++++++++++------------------------------------------ 3 files changed, 124 insertions(+), 322 deletions(-) (limited to 'src') diff --git a/src/config.h b/src/config.h index dc30eeb2..2ea4b438 100644 --- a/src/config.h +++ b/src/config.h @@ -57,8 +57,6 @@ //------------------------------------------------------------------------------------ // Support VR simulation functionality (stereo rendering) #define SUPPORT_VR_SIMULATOR 1 -// Include stereo rendering distortion shader (shader_distortion.h) -#define SUPPORT_DISTORTION_SHADER 1 //------------------------------------------------------------------------------------ diff --git a/src/raylib.h b/src/raylib.h index e8d927cb..73661f58 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -443,16 +443,6 @@ typedef struct VrDeviceInfo { float chromaAbCorrection[4]; // HMD chromatic aberration correction parameters } VrDeviceInfo; -// VR Stereo rendering configuration for simulator -typedef struct VrStereoConfig { - RenderTexture2D stereoFbo; // VR stereo rendering framebuffer - Shader distortionShader; // VR stereo rendering distortion shader - Matrix eyesProjection[2]; // VR stereo rendering eyes projection matrices - Matrix eyesViewOffset[2]; // VR stereo rendering eyes view offset matrices - int eyeViewportRight[4]; // VR stereo rendering right eye viewport [x, y, w, h] - int eyeViewportLeft[4]; // VR stereo rendering left eye viewport [x, y, w, h] -} VrStereoConfig; - //---------------------------------------------------------------------------------- // Enumerators Definition //---------------------------------------------------------------------------------- @@ -860,16 +850,6 @@ typedef enum { CAMERA_ORTHOGRAPHIC } CameraType; -// Head Mounted Display devices -typedef enum { - HMD_DEFAULT_DEVICE = 0, - HMD_OCULUS_RIFT_DK2, - HMD_OCULUS_RIFT_CV1, - HMD_OCULUS_GO, - HMD_VALVE_HTC_VIVE, - HMD_SONY_PSVR -} VrDeviceType; - // Type of n-patch typedef enum { NPT_9PATCH = 0, // Npatch defined by 3x3 tiles @@ -1330,7 +1310,7 @@ RLAPI Shader GetShaderDefault(void); // Get RLAPI Texture2D GetTextureDefault(void); // Get default texture // Shader configuration functions -RLAPI int GetShaderLocation(Shader shader, const char *uniformName); // Get shader uniform location +RLAPI int GetShaderLocation(Shader shader, const char *uniformName); // Get shader uniform location RLAPI void SetShaderValue(Shader shader, int uniformLoc, const void *value, int uniformType); // Set shader uniform value RLAPI void SetShaderValueV(Shader shader, int uniformLoc, const void *value, int uniformType, int count); // Set shader uniform value vector RLAPI void SetShaderValueMatrix(Shader shader, int uniformLoc, Matrix mat); // Set shader uniform value (matrix 4x4) @@ -1344,7 +1324,7 @@ RLAPI Matrix GetMatrixModelview(); // Get RLAPI Texture2D GenTextureCubemap(Shader shader, Texture2D skyHDR, int size); // Generate cubemap texture from HDR texture RLAPI Texture2D GenTextureIrradiance(Shader shader, Texture2D cubemap, int size); // Generate irradiance texture using cubemap data RLAPI Texture2D GenTexturePrefilter(Shader shader, Texture2D cubemap, int size); // Generate prefilter texture using cubemap data -RLAPI Texture2D GenTextureBRDF(Shader shader, int size); // Generate BRDF texture using cubemap data +RLAPI Texture2D GenTextureBRDF(Shader shader, int size); // Generate BRDF texture // Shading begin/end functions RLAPI void BeginShaderMode(Shader shader); // Begin custom shader drawing @@ -1355,10 +1335,10 @@ RLAPI void BeginScissorMode(int x, int y, int width, int height); // Beg RLAPI void EndScissorMode(void); // End scissor mode // VR control functions -RLAPI VrDeviceInfo GetVrDeviceInfo(int vrDeviceType); // Get VR device information for some standard devices -RLAPI void InitVrSimulator(VrDeviceInfo info); // Init VR simulator for selected device parameters -RLAPI void UpdateVrTracking(Camera *camera); // Update VR tracking (position and orientation) and camera +RLAPI void InitVrSimulator(void); // Init VR simulator for selected device parameters RLAPI void CloseVrSimulator(void); // Close VR simulator for current device +RLAPI void UpdateVrTracking(Camera *camera); // Update VR tracking (position and orientation) and camera +RLAPI void SetVrConfiguration(VrDeviceInfo info, Shader distortion); // Set stereo rendering configuration parameters RLAPI bool IsVrSimulatorReady(void); // Detect if VR simulator is ready RLAPI void ToggleVrMode(void); // Enable/Disable VR experience RLAPI void BeginVrDrawing(void); // Begin VR simulator stereo rendering diff --git a/src/rlgl.h b/src/rlgl.h index 3e428241..5c0d2823 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -32,9 +32,6 @@ * #define SUPPORT_VR_SIMULATOR * Support VR simulation functionality (stereo rendering) * -* #define SUPPORT_DISTORTION_SHADER -* Include stereo rendering distortion shader (embedded) -* * DEPENDENCIES: * raymath - 3D math functionality (Vector3, Matrix, Quaternion) * GLAD - OpenGL extensions loading (OpenGL 3.3 Core only) @@ -263,7 +260,6 @@ typedef unsigned char byte; // VR Stereo rendering configuration for simulator typedef struct VrStereoConfig { - RenderTexture2D stereoFbo; // VR stereo rendering framebuffer Shader distortionShader; // VR stereo rendering distortion shader Matrix eyesProjection[2]; // VR stereo rendering eyes projection matrices Matrix eyesViewOffset[2]; // VR stereo rendering eyes view offset matrices @@ -390,16 +386,6 @@ typedef unsigned char byte; #define MAP_DIFFUSE MAP_ALBEDO #define MAP_SPECULAR MAP_METALNESS - - // VR Head Mounted Display devices - typedef enum { - HMD_DEFAULT_DEVICE = 0, - HMD_OCULUS_RIFT_DK2, - HMD_OCULUS_RIFT_CV1, - HMD_OCULUS_GO, - HMD_VALVE_HTC_VIVE, - HMD_SONY_PSVR - } VrDevice; #endif #if defined(__cplusplus) @@ -534,14 +520,14 @@ void BeginBlendMode(int mode); // Begin blending mode (alpha, void EndBlendMode(void); // End blending mode (reset to default: alpha blending) // VR control functions -VrDeviceInfo GetVrDeviceInfo(int vrDeviceType); // Get VR device information for some standard devices -void InitVrSimulator(VrDeviceInfo info); // Init VR simulator for selected device parameters -void UpdateVrTracking(Camera *camera); // Update VR tracking (position and orientation) and camera -void CloseVrSimulator(void); // Close VR simulator for current device -bool IsVrSimulatorReady(void); // Detect if VR simulator is ready -void ToggleVrMode(void); // Enable/Disable VR experience -void BeginVrDrawing(void); // Begin VR simulator stereo rendering -void EndVrDrawing(void); // End VR simulator stereo rendering +RLAPI void InitVrSimulator(void); // Init VR simulator for selected device parameters +RLAPI void CloseVrSimulator(void); // Close VR simulator for current device +RLAPI void UpdateVrTracking(Camera *camera); // Update VR tracking (position and orientation) and camera +RLAPI void SetVrConfiguration(VrDeviceInfo info, Shader distortion); // Set stereo rendering configuration parameters +RLAPI bool IsVrSimulatorReady(void); // Detect if VR simulator is ready +RLAPI void ToggleVrMode(void); // Enable/Disable VR experience +RLAPI void BeginVrDrawing(void); // Begin VR simulator stereo rendering +RLAPI void EndVrDrawing(void); // End VR simulator stereo rendering void TraceLog(int msgType, const char *text, ...); // Show trace log messages (LOG_INFO, LOG_WARNING, LOG_ERROR, LOG_DEBUG) int GetPixelDataSize(int width, int height, int format);// Get pixel data size in bytes (image or texture) @@ -561,10 +547,7 @@ int GetPixelDataSize(int width, int height, int format);// Get pixel data size i #if defined(RLGL_IMPLEMENTATION) -#if defined(RLGL_STANDALONE) - #define SUPPORT_VR_SIMULATOR - #define SUPPORT_DISTORTION_SHADER -#else +#if !defined(RLGL_STANDALONE) // Check if config flags have been externally provided on compilation line #if !defined(EXTERNAL_CONFIG_FLAGS) #include "config.h" // Defines module configuration flags @@ -740,88 +723,20 @@ typedef struct DrawCall { //Matrix modelview; // Modelview matrix for this draw } DrawCall; +#if defined(SUPPORT_VR_SIMULATOR) +// VR Stereo rendering configuration for simulator +typedef struct VrStereoConfig { + Shader distortionShader; // VR stereo rendering distortion shader + Matrix eyesProjection[2]; // VR stereo rendering eyes projection matrices + Matrix eyesViewOffset[2]; // VR stereo rendering eyes view offset matrices + int eyeViewportRight[4]; // VR stereo rendering right eye viewport [x, y, w, h] + int eyeViewportLeft[4]; // VR stereo rendering left eye viewport [x, y, w, h] +} VrStereoConfig; +#endif + //---------------------------------------------------------------------------------- // Global Variables Definition //---------------------------------------------------------------------------------- -#if !defined(GRAPHICS_API_OPENGL_11) && defined(SUPPORT_DISTORTION_SHADER) - // Distortion shader embedded - static char distortionFShaderStr[] = - #if defined(GRAPHICS_API_OPENGL_21) - "#version 120 \n" - #elif defined(GRAPHICS_API_OPENGL_ES2) - "#version 100 \n" - "precision mediump float; \n" // precision required for OpenGL ES2 (WebGL) - #endif - #if defined(GRAPHICS_API_OPENGL_ES2) || defined(GRAPHICS_API_OPENGL_21) - "varying vec2 fragTexCoord; \n" - "varying vec4 fragColor; \n" - #elif defined(GRAPHICS_API_OPENGL_33) - "#version 330 \n" - "in vec2 fragTexCoord; \n" - "in vec4 fragColor; \n" - "out vec4 finalColor; \n" - #endif - "uniform sampler2D texture0; \n" - #if defined(GRAPHICS_API_OPENGL_ES2) || defined(GRAPHICS_API_OPENGL_21) - "uniform vec2 leftLensCenter; \n" - "uniform vec2 rightLensCenter; \n" - "uniform vec2 leftScreenCenter; \n" - "uniform vec2 rightScreenCenter; \n" - "uniform vec2 scale; \n" - "uniform vec2 scaleIn; \n" - "uniform vec4 hmdWarpParam; \n" - "uniform vec4 chromaAbParam; \n" - #elif defined(GRAPHICS_API_OPENGL_33) - "uniform vec2 leftLensCenter = vec2(0.288, 0.5); \n" - "uniform vec2 rightLensCenter = vec2(0.712, 0.5); \n" - "uniform vec2 leftScreenCenter = vec2(0.25, 0.5); \n" - "uniform vec2 rightScreenCenter = vec2(0.75, 0.5); \n" - "uniform vec2 scale = vec2(0.25, 0.45); \n" - "uniform vec2 scaleIn = vec2(4, 2.2222); \n" - "uniform vec4 hmdWarpParam = vec4(1, 0.22, 0.24, 0); \n" - "uniform vec4 chromaAbParam = vec4(0.996, -0.004, 1.014, 0.0); \n" - #endif - "void main() \n" - "{ \n" - " vec2 lensCenter = fragTexCoord.x < 0.5? leftLensCenter : rightLensCenter; \n" - " vec2 screenCenter = fragTexCoord.x < 0.5? leftScreenCenter : rightScreenCenter; \n" - " vec2 theta = (fragTexCoord - lensCenter)*scaleIn; \n" - " float rSq = theta.x*theta.x + theta.y*theta.y; \n" - " vec2 theta1 = theta*(hmdWarpParam.x + hmdWarpParam.y*rSq + hmdWarpParam.z*rSq*rSq + hmdWarpParam.w*rSq*rSq*rSq); \n" - " vec2 thetaBlue = theta1*(chromaAbParam.z + chromaAbParam.w*rSq); \n" - " vec2 tcBlue = lensCenter + scale*thetaBlue; \n" - " if (any(bvec2(clamp(tcBlue, screenCenter - vec2(0.25, 0.5), screenCenter + vec2(0.25, 0.5)) - tcBlue))) \n" - " { \n" - #if defined(GRAPHICS_API_OPENGL_ES2) || defined(GRAPHICS_API_OPENGL_21) - " gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0); \n" - #elif defined(GRAPHICS_API_OPENGL_33) - " finalColor = vec4(0.0, 0.0, 0.0, 1.0); \n" - #endif - " } \n" - " else \n" - " { \n" - #if defined(GRAPHICS_API_OPENGL_ES2) || defined(GRAPHICS_API_OPENGL_21) - " float blue = texture2D(texture0, tcBlue).b; \n" - " vec2 tcGreen = lensCenter + scale*theta1; \n" - " float green = texture2D(texture0, tcGreen).g; \n" - #elif defined(GRAPHICS_API_OPENGL_33) - " float blue = texture(texture0, tcBlue).b; \n" - " vec2 tcGreen = lensCenter + scale*theta1; \n" - " float green = texture(texture0, tcGreen).g; \n" - #endif - " vec2 thetaRed = theta1*(chromaAbParam.x + chromaAbParam.y*rSq); \n" - " vec2 tcRed = lensCenter + scale*thetaRed; \n" - #if defined(GRAPHICS_API_OPENGL_ES2) || defined(GRAPHICS_API_OPENGL_21) - " float red = texture2D(texture0, tcRed).r; \n" - " gl_FragColor = vec4(red, green, blue, 1.0); \n" - #elif defined(GRAPHICS_API_OPENGL_33) - " float red = texture(texture0, tcRed).r; \n" - " finalColor = vec4(red, green, blue, 1.0); \n" - #endif - " } \n" - "} \n"; -#endif - #if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) static Matrix stack[MAX_MATRIX_STACK_SIZE] = { 0 }; static int stackCounter = 0; @@ -891,6 +806,7 @@ static PFNGLDELETEVERTEXARRAYSOESPROC glDeleteVertexArrays; #if defined(SUPPORT_VR_SIMULATOR) // VR global variables static VrStereoConfig vrConfig = { 0 }; // VR stereo configuration for simulator +static RenderTexture2D stereoFbo; // VR stereo rendering framebuffer static bool vrSimulatorReady = false; // VR simulator ready flag static bool vrStereoRender = false; // VR stereo rendering enabled/disabled flag // NOTE: This flag is useful to render data over stereo image (i.e. FPS) @@ -924,7 +840,6 @@ static void GenDrawCube(void); // Generate and draw cube static void GenDrawQuad(void); // Generate and draw quad #if defined(SUPPORT_VR_SIMULATOR) -static VrStereoConfig SetStereoConfig(VrDeviceInfo info, Shader distortion); // Configure stereo rendering (including distortion shader) with HMD device parameters static void SetStereoView(int eye, Matrix matProjection, Matrix matModelView); // Set internal projection and modelview matrix depending on eye #endif @@ -3577,101 +3492,17 @@ void EndScissorMode(void) } #if defined(SUPPORT_VR_SIMULATOR) -// Get VR device information for some standard devices -VrDeviceInfo GetVrDeviceInfo(int vrDeviceType) -{ - VrDeviceInfo hmd = { 0 }; // Current VR device info - - switch (vrDeviceType) - { - case HMD_DEFAULT_DEVICE: - case HMD_OCULUS_RIFT_CV1: - { - // Oculus Rift CV1 parameters - // NOTE: CV1 represents a complete HMD redesign compared to previous versions, - // new Fresnel-hybrid-asymmetric lenses have been added and, consequently, - // previous parameters (DK2) and distortion shader (DK2) doesn't work any more. - // I just defined a set of parameters for simulator that approximate to CV1 stereo rendering - // but result is not the same obtained with Oculus PC SDK. - hmd.hResolution = 2160; // HMD horizontal resolution in pixels - hmd.vResolution = 1200; // HMD vertical resolution in pixels - hmd.hScreenSize = 0.133793f; // HMD horizontal size in meters - hmd.vScreenSize = 0.0669f; // HMD vertical size in meters - hmd.vScreenCenter = 0.04678f; // HMD screen center in meters - hmd.eyeToScreenDistance = 0.041f; // HMD distance between eye and display in meters - hmd.lensSeparationDistance = 0.07f; // HMD lens separation distance in meters - hmd.interpupillaryDistance = 0.07f; // HMD IPD (distance between pupils) in meters - hmd.lensDistortionValues[0] = 1.0f; // HMD lens distortion constant parameter 0 - hmd.lensDistortionValues[1] = 0.22f; // HMD lens distortion constant parameter 1 - hmd.lensDistortionValues[2] = 0.24f; // HMD lens distortion constant parameter 2 - hmd.lensDistortionValues[3] = 0.0f; // HMD lens distortion constant parameter 3 - hmd.chromaAbCorrection[0] = 0.996f; // HMD chromatic aberration correction parameter 0 - hmd.chromaAbCorrection[1] = -0.004f; // HMD chromatic aberration correction parameter 1 - hmd.chromaAbCorrection[2] = 1.014f; // HMD chromatic aberration correction parameter 2 - hmd.chromaAbCorrection[3] = 0.0f; // HMD chromatic aberration correction parameter 3 - - TraceLog(LOG_INFO, "Initializing VR Simulator (Oculus Rift CV1)"); - } break; - case HMD_OCULUS_RIFT_DK2: - { - // Oculus Rift DK2 parameters - hmd.hResolution = 1280; // HMD horizontal resolution in pixels - hmd.vResolution = 800; // HMD vertical resolution in pixels - hmd.hScreenSize = 0.14976f; // HMD horizontal size in meters - hmd.vScreenSize = 0.09356f; // HMD vertical size in meters - hmd.vScreenCenter = 0.04678f; // HMD screen center in meters - hmd.eyeToScreenDistance = 0.041f; // HMD distance between eye and display in meters - hmd.lensSeparationDistance = 0.0635f; // HMD lens separation distance in meters - hmd.interpupillaryDistance = 0.064f; // HMD IPD (distance between pupils) in meters - hmd.lensDistortionValues[0] = 1.0f; // HMD lens distortion constant parameter 0 - hmd.lensDistortionValues[1] = 0.22f; // HMD lens distortion constant parameter 1 - hmd.lensDistortionValues[2] = 0.24f; // HMD lens distortion constant parameter 2 - hmd.lensDistortionValues[3] = 0.0f; // HMD lens distortion constant parameter 3 - hmd.chromaAbCorrection[0] = 0.996f; // HMD chromatic aberration correction parameter 0 - hmd.chromaAbCorrection[1] = -0.004f; // HMD chromatic aberration correction parameter 1 - hmd.chromaAbCorrection[2] = 1.014f; // HMD chromatic aberration correction parameter 2 - hmd.chromaAbCorrection[3] = 0.0f; // HMD chromatic aberration correction parameter 3 - - TraceLog(LOG_INFO, "Initializing VR Simulator (Oculus Rift DK2)"); - } break; - case HMD_OCULUS_GO: - { - // TODO: Provide device display and lens parameters - } - case HMD_VALVE_HTC_VIVE: - { - // TODO: Provide device display and lens parameters - } - case HMD_SONY_PSVR: - { - // TODO: Provide device display and lens parameters - } - default: break; - } - - return hmd; -} - // Init VR simulator for selected device parameters -// NOTE: It modifies the global variable: VrStereoConfig vrConfig -void InitVrSimulator(VrDeviceInfo info) +// NOTE: It modifies the global variable: stereoFbo +void InitVrSimulator(void) { #if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - Shader distortion = { 0 }; - -#if defined(SUPPORT_DISTORTION_SHADER) - // Load distortion shader - distortion = LoadShaderCode(NULL, distortionFShaderStr); - if (distortion.id > 0) SetShaderDefaultLocations(&distortion); -#endif - - // Set VR configutarion parameters, including distortion shader - vrConfig = SetStereoConfig(info, distortion); - + // Initialize framebuffer and textures for stereo rendering + // NOTE: Screen size should match HMD aspect ratio + stereoFbo = rlLoadRenderTexture(screenWidth, screenHeight, UNCOMPRESSED_R8G8B8A8, 24, false); + vrSimulatorReady = true; -#endif - -#if defined(GRAPHICS_API_OPENGL_11) +#else TraceLog(LOG_WARNING, "VR Simulator not supported on OpenGL 1.1"); #endif } @@ -3687,14 +3518,90 @@ void UpdateVrTracking(Camera *camera) void CloseVrSimulator(void) { #if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if (vrSimulatorReady) + if (vrSimulatorReady) rlDeleteRenderTextures(stereoFbo); // Unload stereo framebuffer and texture +#endif +} + +// Set stereo rendering configuration parameters +void SetVrConfiguration(VrDeviceInfo hmd, Shader distortion) +{ + // Reset vrConfig for a new values assignment + memset(&vrConfig, 0, sizeof(vrConfig)); + + // Assign distortion shader + vrConfig.distortionShader = distortion; + + // Compute aspect ratio + float aspect = ((float)hmd.hResolution*0.5f)/(float)hmd.vResolution; + + // Compute lens parameters + float lensShift = (hmd.hScreenSize*0.25f - hmd.lensSeparationDistance*0.5f)/hmd.hScreenSize; + float leftLensCenter[2] = { 0.25f + lensShift, 0.5f }; + float rightLensCenter[2] = { 0.75f - lensShift, 0.5f }; + float leftScreenCenter[2] = { 0.25f, 0.5f }; + float rightScreenCenter[2] = { 0.75f, 0.5f }; + + // Compute distortion scale parameters + // NOTE: To get lens max radius, lensShift must be normalized to [-1..1] + float lensRadius = (float)fabs(-1.0f - 4.0f*lensShift); + float lensRadiusSq = lensRadius*lensRadius; + float distortionScale = hmd.lensDistortionValues[0] + + hmd.lensDistortionValues[1]*lensRadiusSq + + hmd.lensDistortionValues[2]*lensRadiusSq*lensRadiusSq + + hmd.lensDistortionValues[3]*lensRadiusSq*lensRadiusSq*lensRadiusSq; + + TraceLog(LOG_DEBUG, "VR: Distortion Scale: %f", distortionScale); + + float normScreenWidth = 0.5f; + float normScreenHeight = 1.0f; + float scaleIn[2] = { 2.0f/normScreenWidth, 2.0f/normScreenHeight/aspect }; + float scale[2] = { normScreenWidth*0.5f/distortionScale, normScreenHeight*0.5f*aspect/distortionScale }; + + TraceLog(LOG_DEBUG, "VR: Distortion Shader: LeftLensCenter = { %f, %f }", leftLensCenter[0], leftLensCenter[1]); + TraceLog(LOG_DEBUG, "VR: Distortion Shader: RightLensCenter = { %f, %f }", rightLensCenter[0], rightLensCenter[1]); + TraceLog(LOG_DEBUG, "VR: Distortion Shader: Scale = { %f, %f }", scale[0], scale[1]); + TraceLog(LOG_DEBUG, "VR: Distortion Shader: ScaleIn = { %f, %f }", scaleIn[0], scaleIn[1]); + + // Fovy is normally computed with: 2*atan2(hmd.vScreenSize, 2*hmd.eyeToScreenDistance) + // ...but with lens distortion it is increased (see Oculus SDK Documentation) + //float fovy = 2.0f*atan2(hmd.vScreenSize*0.5f*distortionScale, hmd.eyeToScreenDistance); // Really need distortionScale? + float fovy = 2.0f*(float)atan2(hmd.vScreenSize*0.5f, hmd.eyeToScreenDistance); + + // Compute camera projection matrices + float projOffset = 4.0f*lensShift; // Scaled to projection space coordinates [-1..1] + Matrix proj = MatrixPerspective(fovy, aspect, 0.01, 1000.0); + vrConfig.eyesProjection[0] = MatrixMultiply(proj, MatrixTranslate(projOffset, 0.0f, 0.0f)); + vrConfig.eyesProjection[1] = MatrixMultiply(proj, MatrixTranslate(-projOffset, 0.0f, 0.0f)); + + // Compute camera transformation matrices + // NOTE: Camera movement might seem more natural if we model the head. + // Our axis of rotation is the base of our head, so we might want to add + // some y (base of head to eye level) and -z (center of head to eye protrusion) to the camera positions. + vrConfig.eyesViewOffset[0] = MatrixTranslate(-hmd.interpupillaryDistance*0.5f, 0.075f, 0.045f); + vrConfig.eyesViewOffset[1] = MatrixTranslate(hmd.interpupillaryDistance*0.5f, 0.075f, 0.045f); + + // Compute eyes Viewports + vrConfig.eyeViewportRight[2] = hmd.hResolution/2; + vrConfig.eyeViewportRight[3] = hmd.vResolution; + + vrConfig.eyeViewportLeft[0] = hmd.hResolution/2; + vrConfig.eyeViewportLeft[1] = 0; + vrConfig.eyeViewportLeft[2] = hmd.hResolution/2; + vrConfig.eyeViewportLeft[3] = hmd.vResolution; + + if (vrConfig.distortionShader.id > 0) { - rlDeleteRenderTextures(vrConfig.stereoFbo); // Unload stereo framebuffer and texture - #if defined(SUPPORT_DISTORTION_SHADER) - UnloadShader(vrConfig.distortionShader); // Unload distortion shader - #endif + // Update distortion shader with lens and distortion-scale parameters + SetShaderValue(vrConfig.distortionShader, GetShaderLocation(vrConfig.distortionShader, "leftLensCenter"), leftLensCenter, UNIFORM_VEC2); + SetShaderValue(vrConfig.distortionShader, GetShaderLocation(vrConfig.distortionShader, "rightLensCenter"), rightLensCenter, UNIFORM_VEC2); + SetShaderValue(vrConfig.distortionShader, GetShaderLocation(vrConfig.distortionShader, "leftScreenCenter"), leftScreenCenter, UNIFORM_VEC2); + SetShaderValue(vrConfig.distortionShader, GetShaderLocation(vrConfig.distortionShader, "rightScreenCenter"), rightScreenCenter, UNIFORM_VEC2); + + SetShaderValue(vrConfig.distortionShader, GetShaderLocation(vrConfig.distortionShader, "scale"), scale, UNIFORM_VEC2); + SetShaderValue(vrConfig.distortionShader, GetShaderLocation(vrConfig.distortionShader, "scaleIn"), scaleIn, UNIFORM_VEC2); + SetShaderValue(vrConfig.distortionShader, GetShaderLocation(vrConfig.distortionShader, "hmdWarpParam"), hmd.lensDistortionValues, UNIFORM_VEC4); + SetShaderValue(vrConfig.distortionShader, GetShaderLocation(vrConfig.distortionShader, "chromaAbParam"), hmd.chromaAbCorrection, UNIFORM_VEC4); } -#endif } // Detect if VR simulator is running @@ -3733,7 +3640,7 @@ void BeginVrDrawing(void) if (vrSimulatorReady) { // Setup framebuffer for stereo rendering - rlEnableRenderTexture(vrConfig.stereoFbo.id); + rlEnableRenderTexture(stereoFbo.id); // NOTE: If your application is configured to treat the texture as a linear format (e.g. GL_RGBA) // and performs linear-to-gamma conversion in GLSL or does not care about gamma-correction, then: @@ -3771,13 +3678,11 @@ void EndVrDrawing(void) rlMatrixMode(RL_MODELVIEW); // Enable internal modelview matrix rlLoadIdentity(); // Reset internal modelview matrix -#if defined(SUPPORT_DISTORTION_SHADER) - // Draw RenderTexture (stereoFbo) using distortion shader - currentShader = vrConfig.distortionShader; -#else - currentShader = GetShaderDefault(); -#endif - rlEnableTexture(vrConfig.stereoFbo.texture.id); + // Draw RenderTexture (stereoFbo) using distortion shader if available + if (vrConfig.distortionShader.id > 0) currentShader = vrConfig.distortionShader; + else currentShader = GetShaderDefault(); + + rlEnableTexture(stereoFbo.texture.id); rlPushMatrix(); rlBegin(RL_QUADS); @@ -3790,15 +3695,15 @@ void EndVrDrawing(void) // Bottom-right corner for texture and quad rlTexCoord2f(0.0f, 0.0f); - rlVertex2f(0.0f, (float)vrConfig.stereoFbo.texture.height); + rlVertex2f(0.0f, (float)stereoFbo.texture.height); // Top-right corner for texture and quad rlTexCoord2f(1.0f, 0.0f); - rlVertex2f( (float)vrConfig.stereoFbo.texture.width, (float)vrConfig.stereoFbo.texture.height); + rlVertex2f( (float)stereoFbo.texture.width, (float)stereoFbo.texture.height); // Top-left corner for texture and quad rlTexCoord2f(1.0f, 1.0f); - rlVertex2f( (float)vrConfig.stereoFbo.texture.width, 0.0f); + rlVertex2f( (float)stereoFbo.texture.width, 0.0f); rlEnd(); rlPopMatrix(); @@ -4472,87 +4377,6 @@ static void GenDrawCube(void) } #if defined(SUPPORT_VR_SIMULATOR) -// Configure stereo rendering (including distortion shader) with HMD device parameters -static VrStereoConfig SetStereoConfig(VrDeviceInfo hmd, Shader distortion) -{ - VrStereoConfig config = { 0 }; - - // Initialize framebuffer and textures for stereo rendering - // NOTE: Screen size should match HMD aspect ratio - config.stereoFbo = rlLoadRenderTexture(screenWidth, screenHeight, UNCOMPRESSED_R8G8B8A8, 24, false); - - // Assign distortion shader - config.distortionShader = distortion; - - // Compute aspect ratio - float aspect = ((float)hmd.hResolution*0.5f)/(float)hmd.vResolution; - - // Compute lens parameters - float lensShift = (hmd.hScreenSize*0.25f - hmd.lensSeparationDistance*0.5f)/hmd.hScreenSize; - float leftLensCenter[2] = { 0.25f + lensShift, 0.5f }; - float rightLensCenter[2] = { 0.75f - lensShift, 0.5f }; - float leftScreenCenter[2] = { 0.25f, 0.5f }; - float rightScreenCenter[2] = { 0.75f, 0.5f }; - - // Compute distortion scale parameters - // NOTE: To get lens max radius, lensShift must be normalized to [-1..1] - float lensRadius = (float)fabs(-1.0f - 4.0f*lensShift); - float lensRadiusSq = lensRadius*lensRadius; - float distortionScale = hmd.lensDistortionValues[0] + - hmd.lensDistortionValues[1]*lensRadiusSq + - hmd.lensDistortionValues[2]*lensRadiusSq*lensRadiusSq + - hmd.lensDistortionValues[3]*lensRadiusSq*lensRadiusSq*lensRadiusSq; - - TraceLog(LOG_DEBUG, "VR: Distortion Scale: %f", distortionScale); - - float normScreenWidth = 0.5f; - float normScreenHeight = 1.0f; - float scaleIn[2] = { 2.0f/normScreenWidth, 2.0f/normScreenHeight/aspect }; - float scale[2] = { normScreenWidth*0.5f/distortionScale, normScreenHeight*0.5f*aspect/distortionScale }; - - TraceLog(LOG_DEBUG, "VR: Distortion Shader: LeftLensCenter = { %f, %f }", leftLensCenter[0], leftLensCenter[1]); - TraceLog(LOG_DEBUG, "VR: Distortion Shader: RightLensCenter = { %f, %f }", rightLensCenter[0], rightLensCenter[1]); - TraceLog(LOG_DEBUG, "VR: Distortion Shader: Scale = { %f, %f }", scale[0], scale[1]); - TraceLog(LOG_DEBUG, "VR: Distortion Shader: ScaleIn = { %f, %f }", scaleIn[0], scaleIn[1]); - - // Fovy is normally computed with: 2*atan2(hmd.vScreenSize, 2*hmd.eyeToScreenDistance) - // ...but with lens distortion it is increased (see Oculus SDK Documentation) - //float fovy = 2.0f*atan2(hmd.vScreenSize*0.5f*distortionScale, hmd.eyeToScreenDistance); // Really need distortionScale? - float fovy = 2.0f*(float)atan2(hmd.vScreenSize*0.5f, hmd.eyeToScreenDistance); - - // Compute camera projection matrices - float projOffset = 4.0f*lensShift; // Scaled to projection space coordinates [-1..1] - Matrix proj = MatrixPerspective(fovy, aspect, 0.01, 1000.0); - config.eyesProjection[0] = MatrixMultiply(proj, MatrixTranslate(projOffset, 0.0f, 0.0f)); - config.eyesProjection[1] = MatrixMultiply(proj, MatrixTranslate(-projOffset, 0.0f, 0.0f)); - - // Compute camera transformation matrices - // NOTE: Camera movement might seem more natural if we model the head. - // Our axis of rotation is the base of our head, so we might want to add - // some y (base of head to eye level) and -z (center of head to eye protrusion) to the camera positions. - config.eyesViewOffset[0] = MatrixTranslate(-hmd.interpupillaryDistance*0.5f, 0.075f, 0.045f); - config.eyesViewOffset[1] = MatrixTranslate(hmd.interpupillaryDistance*0.5f, 0.075f, 0.045f); - - // Compute eyes Viewports - //config.eyeViewportRight[0] = (int[4]){ 0, 0, hmd.hResolution/2, hmd.vResolution }; - //config.eyeViewportLeft[0] = (int[4]){ hmd.hResolution/2, 0, hmd.hResolution/2, hmd.vResolution }; - -#if defined(SUPPORT_DISTORTION_SHADER) - // Update distortion shader with lens and distortion-scale parameters - SetShaderValue(config.distortionShader, GetShaderLocation(config.distortionShader, "leftLensCenter"), leftLensCenter, UNIFORM_VEC2); - SetShaderValue(config.distortionShader, GetShaderLocation(config.distortionShader, "rightLensCenter"), rightLensCenter, UNIFORM_VEC2); - SetShaderValue(config.distortionShader, GetShaderLocation(config.distortionShader, "leftScreenCenter"), leftScreenCenter, UNIFORM_VEC2); - SetShaderValue(config.distortionShader, GetShaderLocation(config.distortionShader, "rightScreenCenter"), rightScreenCenter, UNIFORM_VEC2); - - SetShaderValue(config.distortionShader, GetShaderLocation(config.distortionShader, "scale"), scale, UNIFORM_VEC2); - SetShaderValue(config.distortionShader, GetShaderLocation(config.distortionShader, "scaleIn"), scaleIn, UNIFORM_VEC2); - SetShaderValue(config.distortionShader, GetShaderLocation(config.distortionShader, "hmdWarpParam"), hmd.lensDistortionValues, UNIFORM_VEC4); - SetShaderValue(config.distortionShader, GetShaderLocation(config.distortionShader, "chromaAbParam"), hmd.chromaAbCorrection, UNIFORM_VEC4); -#endif - - return config; -} - // Set internal projection and modelview matrix depending on eyes tracking data static void SetStereoView(int eye, Matrix matProjection, Matrix matModelView) { -- cgit v1.2.3 From a28dfd4a7b479b0ad8248fe0e25c5e8ce3d9d3cf Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 11 Apr 2019 15:54:10 +0200 Subject: Corrected standalone usage --- src/rlgl.h | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/rlgl.h b/src/rlgl.h index 5c0d2823..a4a481f2 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -520,14 +520,14 @@ void BeginBlendMode(int mode); // Begin blending mode (alpha, void EndBlendMode(void); // End blending mode (reset to default: alpha blending) // VR control functions -RLAPI void InitVrSimulator(void); // Init VR simulator for selected device parameters -RLAPI void CloseVrSimulator(void); // Close VR simulator for current device -RLAPI void UpdateVrTracking(Camera *camera); // Update VR tracking (position and orientation) and camera -RLAPI void SetVrConfiguration(VrDeviceInfo info, Shader distortion); // Set stereo rendering configuration parameters -RLAPI bool IsVrSimulatorReady(void); // Detect if VR simulator is ready -RLAPI void ToggleVrMode(void); // Enable/Disable VR experience -RLAPI void BeginVrDrawing(void); // Begin VR simulator stereo rendering -RLAPI void EndVrDrawing(void); // End VR simulator stereo rendering +void InitVrSimulator(void); // Init VR simulator for selected device parameters +void CloseVrSimulator(void); // Close VR simulator for current device +void UpdateVrTracking(Camera *camera); // Update VR tracking (position and orientation) and camera +void SetVrConfiguration(VrDeviceInfo info, Shader distortion); // Set stereo rendering configuration parameters +bool IsVrSimulatorReady(void); // Detect if VR simulator is ready +void ToggleVrMode(void); // Enable/Disable VR experience +void BeginVrDrawing(void); // Begin VR simulator stereo rendering +void EndVrDrawing(void); // End VR simulator stereo rendering void TraceLog(int msgType, const char *text, ...); // Show trace log messages (LOG_INFO, LOG_WARNING, LOG_ERROR, LOG_DEBUG) int GetPixelDataSize(int width, int height, int format);// Get pixel data size in bytes (image or texture) -- cgit v1.2.3 From 01367fcb1e1c9e00a74cbbe146d415fd64110d30 Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 11 Apr 2019 16:11:54 +0200 Subject: Review cubemap generation --- src/rlgl.h | 6 +++--- src/textures.c | 6 ++---- 2 files changed, 5 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/rlgl.h b/src/rlgl.h index a4a481f2..048c75da 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -2027,10 +2027,10 @@ unsigned int rlLoadTextureCubemap(void *data, int size, int format) unsigned int glInternalFormat, glFormat, glType; rlGetGlTextureFormats(format, &glInternalFormat, &glFormat, &glType); - // Load cubemap faces - for (unsigned int i = 0; i < 6; i++) + if (glInternalFormat != -1) { - if (glInternalFormat != -1) + // Load cubemap faces + for (unsigned int i = 0; i < 6; i++) { if (format < COMPRESSED_DXT1_RGB) glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, size, size, 0, glFormat, glType, (unsigned char *)data + i*dataSize); #if !defined(GRAPHICS_API_OPENGL_11) diff --git a/src/textures.c b/src/textures.c index 169f8f86..7059fabb 100644 --- a/src/textures.c +++ b/src/textures.c @@ -1206,12 +1206,9 @@ TextureCubemap LoadTextureCubemap(Image image, int layoutType) cubemap.height = cubemap.width; } - int size = cubemap.width; - if (layoutType != CUBEMAP_AUTO_DETECT) { - //unsigned int dataSize = GetPixelDataSize(size, size, format); - //void *facesData = malloc(size*size*dataSize*6); // Get memory for 6 faces in a column + int size = cubemap.width; Image faces = { 0 }; // Vertical column image Rectangle faceRecs[6] = { 0 }; // Face source rectangles @@ -1225,6 +1222,7 @@ TextureCubemap LoadTextureCubemap(Image image, int layoutType) else if (layoutType == CUBEMAP_PANORAMA) { // TODO: Convert panorama image to square faces... + // Ref: https://github.com/denivip/panorama/blob/master/panorama.cpp } else { -- cgit v1.2.3 From 30d51ec26ca8f00bd691c570a78b8eb2e41fa817 Mon Sep 17 00:00:00 2001 From: Ray Date: Fri, 12 Apr 2019 11:29:01 +0200 Subject: Reorganize struct --- src/raylib.h | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/raylib.h b/src/raylib.h index 73661f58..4162454e 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -288,12 +288,6 @@ typedef struct Camera2D { float zoom; // Camera zoom (scaling), should be 1.0f by default } Camera2D; -// Bounding box type -typedef struct BoundingBox { - Vector3 min; // Minimum vertex box-corner - Vector3 max; // Maximum vertex box-corner -} BoundingBox; - // Vertex data definning a mesh // NOTE: Data stored in CPU memory (and GPU) typedef struct Mesh { @@ -393,6 +387,12 @@ typedef struct RayHitInfo { Vector3 normal; // Surface normal of hit } RayHitInfo; +// Bounding box type +typedef struct BoundingBox { + Vector3 min; // Minimum vertex box-corner + Vector3 max; // Maximum vertex box-corner +} BoundingBox; + // Wave type, defines audio wave data typedef struct Wave { unsigned int sampleCount; // Number of samples @@ -1237,7 +1237,7 @@ RLAPI void DrawGizmo(Vector3 position); // Model loading/unloading functions RLAPI Model LoadModel(const char *fileName); // Load model from files (meshes and materials) -RLAPI Model LoadModelFromMesh(Mesh mesh); // Load model from generated mesh +RLAPI Model LoadModelFromMesh(Mesh mesh); // Load model from generated mesh (default material) RLAPI void UnloadModel(Model model); // Unload model from memory (RAM and/or VRAM) // Mesh loading/unloading functions -- cgit v1.2.3 From 4e58d4102c0f466730971e7f7cd685b7359343ab Mon Sep 17 00:00:00 2001 From: Ray Date: Fri, 12 Apr 2019 13:29:37 +0200 Subject: Corrected typo --- src/raylib.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/raylib.h b/src/raylib.h index 4162454e..6d42cfd1 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -925,7 +925,7 @@ RLAPI Ray GetMouseRay(Vector2 mousePosition, Camera camera); // Returns a r RLAPI Vector2 GetWorldToScreen(Vector3 position, Camera camera); // Returns the screen space position for a 3d world space position RLAPI Matrix GetCameraMatrix(Camera camera); // Returns camera transform matrix (view matrix) -// timing-related functions +// Timing-related functions RLAPI void SetTargetFPS(int fps); // Set target FPS (maximum) RLAPI int GetFPS(void); // Returns current FPS RLAPI float GetFrameTime(void); // Returns time in seconds for last frame drawn -- cgit v1.2.3 From df90ba6e463e5689039821fe93ea93d0a996b035 Mon Sep 17 00:00:00 2001 From: Ray Date: Fri, 12 Apr 2019 13:31:05 +0200 Subject: WARNING: Added GLFW hint to support hi-DPI This needs to be tested on a hi-DPI monitor, probably requiring a FLAG to enable it would be a good idea... --- src/core.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/core.c b/src/core.c index 32773a0d..e8316213 100644 --- a/src/core.c +++ b/src/core.c @@ -2347,7 +2347,7 @@ static bool InitGraphicsDevice(int width, int height) displayHeight = screenHeight; #endif // defined(PLATFORM_WEB) - glfwDefaultWindowHints(); // Set default windows hints: + glfwDefaultWindowHints(); // Set default windows hints: //glfwWindowHint(GLFW_RED_BITS, 8); // Framebuffer red color component bits //glfwWindowHint(GLFW_GREEN_BITS, 8); // Framebuffer green color component bits //glfwWindowHint(GLFW_BLUE_BITS, 8); // Framebuffer blue color component bits @@ -2356,6 +2356,7 @@ static bool InitGraphicsDevice(int width, int height) //glfwWindowHint(GLFW_REFRESH_RATE, 0); // Refresh rate for fullscreen window //glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API); // OpenGL API to use. Alternative: GLFW_OPENGL_ES_API //glfwWindowHint(GLFW_AUX_BUFFERS, 0); // Number of auxiliar buffers + glfwWindowHint(GLFW_SCALE_TO_MONITOR, GLFW_TRUE); // Scale content area based on the monitor content scale where window is placed on // Check some Window creation flags if (configFlags & FLAG_WINDOW_HIDDEN) glfwWindowHint(GLFW_VISIBLE, GL_FALSE); // Visible window -- cgit v1.2.3 From fc5dd5d99fb233879885cd02da5010d81f37d0b0 Mon Sep 17 00:00:00 2001 From: Ray Date: Fri, 12 Apr 2019 13:44:16 +0200 Subject: FLAG not supported on web GLFW implementation --- src/core.c | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src') diff --git a/src/core.c b/src/core.c index e8316213..ba41c773 100644 --- a/src/core.c +++ b/src/core.c @@ -2356,7 +2356,9 @@ static bool InitGraphicsDevice(int width, int height) //glfwWindowHint(GLFW_REFRESH_RATE, 0); // Refresh rate for fullscreen window //glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API); // OpenGL API to use. Alternative: GLFW_OPENGL_ES_API //glfwWindowHint(GLFW_AUX_BUFFERS, 0); // Number of auxiliar buffers +#if defined(PLATFORM_DESKTOP) glfwWindowHint(GLFW_SCALE_TO_MONITOR, GLFW_TRUE); // Scale content area based on the monitor content scale where window is placed on +#endif // Check some Window creation flags if (configFlags & FLAG_WINDOW_HIDDEN) glfwWindowHint(GLFW_VISIBLE, GL_FALSE); // Visible window -- cgit v1.2.3 From 7cc8faf7daa1e3d0f742bbc118b9705b0546e072 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B6rn=20Wahlstrand?= Date: Fri, 12 Apr 2019 21:41:30 +0200 Subject: Use typedef rather than #define in order to avoid issues in application code --- src/raylib.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/raylib.h b/src/raylib.h index 6d42cfd1..0afa69d0 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -278,7 +278,7 @@ typedef struct Camera3D { int type; // Camera type, defines projection type: CAMERA_PERSPECTIVE or CAMERA_ORTHOGRAPHIC } Camera3D; -#define Camera Camera3D // Camera type fallback, defaults to Camera3D +typedef Camera3D Camera; // Camera type fallback, defaults to Camera3D // Camera2D type, defines a 2d camera typedef struct Camera2D { -- cgit v1.2.3 From 310d1d15890618f21c7e90d0c98b4f208c9c64ff Mon Sep 17 00:00:00 2001 From: flashjaysan Date: Sat, 13 Apr 2019 14:35:07 +0200 Subject: Update raymath.h Removed a useless semicolon. --- src/raymath.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/raymath.h b/src/raymath.h index 33116532..389a430f 100644 --- a/src/raymath.h +++ b/src/raymath.h @@ -447,7 +447,7 @@ RMDEF Vector3 Vector3Transform(Vector3 v, Matrix mat) result.z = mat.m2*x + mat.m6*y + mat.m10*z + mat.m14; return result; -}; +} // Transform a vector by quaternion rotation RMDEF Vector3 Vector3RotateByQuaternion(Vector3 v, Quaternion q) -- cgit v1.2.3 From 8c22f685d168000eabfc994a09c3a2a61f7f633f Mon Sep 17 00:00:00 2001 From: Ray Date: Sun, 14 Apr 2019 22:29:14 +0200 Subject: Check buffer overflow --- src/models.c | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) (limited to 'src') diff --git a/src/models.c b/src/models.c index d8508492..631c4942 100644 --- a/src/models.c +++ b/src/models.c @@ -295,6 +295,8 @@ void DrawCubeTexture(Texture2D texture, Vector3 position, float width, float hei float x = position.x; float y = position.y; float z = position.z; + + if (rlCheckBufferLimit(36)) rlglDraw(); rlEnableTexture(texture.id); @@ -357,6 +359,9 @@ void DrawSphere(Vector3 centerPos, float radius, Color color) // Draw sphere with extended parameters void DrawSphereEx(Vector3 centerPos, float radius, int rings, int slices, Color color) { + int numVertex = (rings + 2)*slices*6; + if (rlCheckBufferLimit(numVertex)) rlglDraw(); + rlPushMatrix(); // NOTE: Transformation is applied in inverse order (scale -> translate) rlTranslatef(centerPos.x, centerPos.y, centerPos.z); @@ -397,6 +402,9 @@ void DrawSphereEx(Vector3 centerPos, float radius, int rings, int slices, Color // Draw sphere wires void DrawSphereWires(Vector3 centerPos, float radius, int rings, int slices, Color color) { + int numVertex = (rings + 2)*slices*6; + if (rlCheckBufferLimit(numVertex)) rlglDraw(); + rlPushMatrix(); // NOTE: Transformation is applied in inverse order (scale -> translate) rlTranslatef(centerPos.x, centerPos.y, centerPos.z); @@ -440,6 +448,9 @@ void DrawSphereWires(Vector3 centerPos, float radius, int rings, int slices, Col void DrawCylinder(Vector3 position, float radiusTop, float radiusBottom, float height, int sides, Color color) { if (sides < 3) sides = 3; + + int numVertex = sides*6; + if (rlCheckBufferLimit(numVertex)) rlglDraw(); rlPushMatrix(); rlTranslatef(position.x, position.y, position.z); @@ -496,6 +507,9 @@ void DrawCylinder(Vector3 position, float radiusTop, float radiusBottom, float h void DrawCylinderWires(Vector3 position, float radiusTop, float radiusBottom, float height, int sides, Color color) { if (sides < 3) sides = 3; + + int numVertex = sides*8; + if (rlCheckBufferLimit(numVertex)) rlglDraw(); rlPushMatrix(); rlTranslatef(position.x, position.y, position.z); @@ -524,6 +538,8 @@ void DrawCylinderWires(Vector3 position, float radiusTop, float radiusBottom, fl // Draw a plane void DrawPlane(Vector3 centerPos, Vector2 size, Color color) { + if (rlCheckBufferLimit(4)) rlglDraw(); + // NOTE: Plane is always created on XZ ground rlPushMatrix(); rlTranslatef(centerPos.x, centerPos.y, centerPos.z); @@ -560,6 +576,8 @@ void DrawGrid(int slices, float spacing) { int halfSlices = slices/2; + if (rlCheckBufferLimit(slices*4)) rlglDraw(); + rlBegin(RL_LINES); for (int i = -halfSlices; i <= halfSlices; i++) { -- cgit v1.2.3 From f3a5a6871d4ec005026817e5f2579a6f55938dc2 Mon Sep 17 00:00:00 2001 From: Demizdor Date: Sun, 21 Apr 2019 12:27:46 +0300 Subject: Initial unicode implementation for UTF8 encoded text --- src/raylib.h | 2 + src/text.c | 205 +++++++++++++++++++++++++++++++++++++++++------------------ 2 files changed, 145 insertions(+), 62 deletions(-) (limited to 'src') diff --git a/src/raylib.h b/src/raylib.h index 0afa69d0..6a5f0ef8 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -1190,11 +1190,13 @@ RLAPI void DrawTextRecEx(Font font, const char *text, Rectangle rec, float fontS RLAPI int MeasureText(const char *text, int fontSize); // Measure string width for default font RLAPI Vector2 MeasureTextEx(Font font, const char *text, float fontSize, float spacing); // Measure string size for Font RLAPI int GetGlyphIndex(Font font, int character); // Get index position for a unicode character on font +RLAPI int GetNextCodepoint(const char* text, int* count); // Returns next codepoint in a UTF8 encoded `text` or 0x3f(`?`) on failure. `count` will hold the total number of bytes processed. // Text strings management functions // NOTE: Some strings allocate memory internally for returned strings, just be careful! RLAPI bool TextIsEqual(const char *text1, const char *text2); // Check if two text string are equal RLAPI unsigned int TextLength(const char *text); // Get text length, checks for '\0' ending +RLAPI unsigned int TextCountCodepoints(const char *text); // Get total number of characters(codepoints) in a UTF8 encoded `text` until '\0' is found. RLAPI const char *TextFormat(const char *text, ...); // Text formatting with variables (sprintf style) RLAPI const char *TextSubtext(const char *text, int position, int length); // Get a piece of a text string RLAPI const char *TextReplace(char *text, const char *replace, const char *by); // Replace text string (memory should be freed!) diff --git a/src/text.c b/src/text.c index c07f807a..bd9e09f0 100644 --- a/src/text.c +++ b/src/text.c @@ -719,6 +719,97 @@ void DrawFPS(int posX, int posY) DrawText(TextFormat("%2i FPS", fps), posX, posY, 20, LIME); } +// Returns next codepoint in a UTF8 encoded `text` scanning until '\0' is found. When a invalid UTF8 byte is encountered we exit as soon +// as possible and a `?`(0x3f) codepoint is returned. `count` will hold the total number of bytes processed. +// NOTE: the standard says U+FFFD should be returned in case of errors but that character is not supported by the default font in raylib +// TODO: optimize this code for speed!! +int GetNextCodepoint(const char* text, int* count) +{ +/* + UTF8 specs from https://www.ietf.org/rfc/rfc3629.txt + + Char. number range | UTF-8 octet sequence + (hexadecimal) | (binary) + --------------------+--------------------------------------------- + 0000 0000-0000 007F | 0xxxxxxx + 0000 0080-0000 07FF | 110xxxxx 10xxxxxx + 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx + 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx +*/ + + // NOTE: on decode errors we return as soon as possible + + int c = 0x3f; // Codepoint (defaults to `?`) + int o = (unsigned char)(text[0]); // The first UTF8 octet + *count = 1; + + if( o <= 0x7f ) + { + // Only one octet (ASCII range x00-7F) + c = text[0]; + } + else if((o & 0xe0) == 0xc0) + { + // Two octets + // [0]xC2-DF [1]UTF8-tail(x80-BF) + unsigned char o1 = text[1]; + if(o1 == '\0' || (o1 >> 6) != 2 ) {*count = 2; return c; } // Unexpected sequence + if(o >= 0xc2 && o <= 0xdf) + { + c = ((o & 0x1f) << 6) | (o1 & 0x3f); + *count = 2; + } + } + else if( (o & 0xf0) == 0xe0 ) + { + // Three octets + unsigned char o1 = text[1], o2 = '\0'; + if(o1 == '\0' || (o1 >> 6) != 2) { *count = 2; return c; } // Unexpected sequence + o2 = text[2]; + if(o2 == '\0' || (o2 >> 6) != 2) {*count = 3; return c; } // Unexpected sequence + + /* [0]xE0 [1]xA0-BF [2]UTF8-tail(x80-BF) + [0]xE1-EC [1]UTF8-tail [2]UTF8-tail(x80-BF) + [0]xED [1]x80-9F [2]UTF8-tail(x80-BF) + [0]xEE-EF [1]UTF8-tail [2]UTF8-tail(x80-BF) + */ + + if((o == 0xe0 && !(o1 >= 0xa0 && o1 <= 0xbf)) || (o == 0xed && !(o1 >= 0x80 && o1 <= 0x9f)) ) {*count = 2; return c;} + if(o >= 0xe0 && 0 <= 0xef) + { + c = ((o & 0xf) << 12) | ((o1 & 0x3f) << 6) | (o2 & 0x3f); + *count = 3; + } + } + else if( (o & 0xf8) == 0xf0 ) + { + // Four octets + if(o > 0xf4) return c; + + unsigned char o1 = text[1], o2 = '\0', o3 = '\0'; + if(o1 == '\0' || (o1 >> 6) != 2) { *count = 2; return c; } // Unexpected sequence + o2 = text[2]; + if(o2 == '\0' || (o2 >> 6) != 2) { *count = 3; return c; } // Unexpected sequence + o3 = text[3]; + if(o3 == '\0' || (o3 >> 6) != 2) { *count = 4; return c; } // Unexpected sequence + + /* [0]xF0 [1]x90-BF [2]UTF8-tail [3]UTF8-tail + [0]xF1-F3 [1]UTF8-tail [2]UTF8-tail [3]UTF8-tail + [0]xF4 [1]x80-8F [2]UTF8-tail [3]UTF8-tail + */ + if((o == 0xf0 && !(o1 >= 0x90 && o1 <= 0xbf)) || (o == 0xf4 && !( o1 >= 0x80 && o1 <= 0x8f)) ) { *count = 2; return c; } // Unexpected sequence + if( o >= 0xf0) + { + c = ((o & 0x7) << 18) | ((o1 & 0x3f) << 12) | ((o2 & 0x3f) << 6) | (o3 & 0x3f); + *count = 4; + } + } + + if(c > 0x10ffff) c = 0x3f; // Codepoints after U+10ffff are invalid + return c; +} + + // Draw text (using default font) // NOTE: fontSize work like in any drawing program but if fontSize is lower than font-base-size, then font-base-size is used // NOTE: chars spacing is proportional to fontSize @@ -746,17 +837,22 @@ void DrawTextEx(Font font, const char *text, Vector2 position, float fontSize, f int textOffsetY = 0; // Required for line break! float scaleFactor = 0.0f; - unsigned char letter = 0; // Current character + int letter = 0; // Current character int index = 0; // Index position in sprite font scaleFactor = fontSize/font.baseSize; - // NOTE: Some ugly hacks are made to support Latin-1 Extended characters directly - // written in C code files (codified by default as UTF-8) - for (int i = 0; i < length; i++) { - if ((unsigned char)text[i] == '\n') + int next = 1; + letter = GetNextCodepoint(&text[i], &next); + // NOTE: normally we exit the decoding sequence as soon as a bad byte is found (and return 0x3f) + // but we need to draw all of the bad bytes using the '?' symbol so to not skip any we set `next = 1` + if(letter == 0x3f) next = 1; + index = GetGlyphIndex(font, letter); + i += next - 1; + + if (letter == '\n') { // NOTE: Fixed line spacing of 1.5 lines textOffsetY += (int)((font.baseSize + font.baseSize/2)*scaleFactor); @@ -764,23 +860,7 @@ void DrawTextEx(Font font, const char *text, Vector2 position, float fontSize, f } else { - if ((unsigned char)text[i] == 0xc2) // UTF-8 encoding identification HACK! - { - // Support UTF-8 encoded values from [0xc2 0x80] -> [0xc2 0xbf](ยฟ) - letter = (unsigned char)text[i + 1]; - index = GetGlyphIndex(font, (int)letter); - i++; - } - else if ((unsigned char)text[i] == 0xc3) // UTF-8 encoding identification HACK! - { - // Support UTF-8 encoded values from [0xc3 0x80](ร€) -> [0xc3 0xbf](รฟ) - letter = (unsigned char)text[i + 1]; - index = GetGlyphIndex(font, (int)letter + 64); - i++; - } - else index = GetGlyphIndex(font, (unsigned char)text[i]); - - if ((unsigned char)text[i] != ' ') + if (letter != ' ') { DrawTexturePro(font.texture, font.chars[index].rec, (Rectangle){ position.x + textOffsetX + font.chars[index].offsetX*scaleFactor, @@ -810,7 +890,7 @@ void DrawTextRecEx(Font font, const char *text, Rectangle rec, float fontSize, f int textOffsetY = 0; // Required for line break! float scaleFactor = 0.0f; - unsigned char letter = 0; // Current character + int letter = 0; // Current character int index = 0; // Index position in sprite font scaleFactor = fontSize/font.baseSize; @@ -823,26 +903,16 @@ void DrawTextRecEx(Font font, const char *text, Rectangle rec, float fontSize, f for (int i = 0; i < length; i++) { int glyphWidth = 0; - letter = (unsigned char)text[i]; + int next = 1; + letter = GetNextCodepoint(&text[i], &next); + // NOTE: normally we exit the decoding sequence as soon as a bad byte is found (and return 0x3f) + // but we need to draw all of the bad bytes using the '?' symbol so to not skip any we set `next = 1` + if(letter == 0x3f) next = 1; + index = GetGlyphIndex(font, letter); + i += next - 1; if (letter != '\n') - { - if ((unsigned char)text[i] == 0xc2) // UTF-8 encoding identification HACK! - { - // Support UTF-8 encoded values from [0xc2 0x80] -> [0xc2 0xbf](ยฟ) - letter = (unsigned char)text[i + 1]; - index = GetGlyphIndex(font, (int)letter); - i++; - } - else if ((unsigned char)text[i] == 0xc3) // UTF-8 encoding identification HACK! - { - // Support UTF-8 encoded values from [0xc3 0x80](ร€) -> [0xc3 0xbf](รฟ) - letter = (unsigned char)text[i + 1]; - index = GetGlyphIndex(font, (int)letter + 64); - i++; - } - else index = GetGlyphIndex(font, (unsigned char)text[i]); - + { glyphWidth = (font.chars[index].advanceX == 0)? (int)(font.chars[index].rec.width*scaleFactor + spacing): (int)(font.chars[index].advanceX*scaleFactor + spacing); @@ -858,13 +928,15 @@ void DrawTextRecEx(Font font, const char *text, Rectangle rec, float fontSize, f // the container. if (state == MEASURE_STATE) { + // TODO: there are multiple types of `spaces` in UNICODE, maybe it's a good idea to add support for more + // see: http://jkorpela.fi/chars/spaces.html if ((letter == ' ') || (letter == '\t') || (letter == '\n')) endLine = i; if ((textOffsetX + glyphWidth + 1) >= rec.width) { endLine = (endLine < 1)? i : endLine; - if (i == endLine) endLine -= 1; - if ((startLine + 1) == endLine) endLine = i - 1; + if (i == endLine) endLine -= next; + if ((startLine + next) == endLine) endLine = i - next; state = !state; } else if ((i + 1) == length) @@ -972,31 +1044,23 @@ Vector2 MeasureTextEx(Font font, const char *text, float fontSize, float spacing float textHeight = (float)font.baseSize; float scaleFactor = fontSize/(float)font.baseSize; - unsigned char letter = 0; // Current character + int letter = 0; // Current character int index = 0; // Index position in sprite font for (int i = 0; i < len; i++) { lenCounter++; - - if (text[i] != '\n') + + int next = 1; + letter = GetNextCodepoint(&text[i], &next); + // NOTE: normally we exit the decoding sequence as soon as a bad byte is found (and return 0x3f) + // but we need to draw all of the bad bytes using the '?' symbol so to not skip any we set `next = 1` + if(letter == 0x3f) next = 1; + i += next - 1; + + if (letter != '\n') { - if ((unsigned char)text[i] == 0xc2) // UTF-8 encoding identification - { - // Support UTF-8 encoded values from [0xc2 0x80] -> [0xc2 0xbf](ยฟ) - letter = (unsigned char)text[i + 1]; - index = GetGlyphIndex(font, (int)letter); - i++; - } - else if ((unsigned char)text[i] == 0xc3) // UTF-8 encoding identification - { - // Support UTF-8 encoded values from [0xc3 0x80](ร€) -> [0xc3 0xbf](รฟ) - letter = (unsigned char)text[i + 1]; - index = GetGlyphIndex(font, (int)letter + 64); - i++; - } - else index = GetGlyphIndex(font, (unsigned char)text[i]); - + index = GetGlyphIndex(font, letter); if (font.chars[index].advanceX != 0) textWidth += font.chars[index].advanceX; else textWidth += (font.chars[index].rec.width + font.chars[index].offsetX); } @@ -1065,6 +1129,23 @@ unsigned int TextLength(const char *text) return length; } +// Returns total number of characters(codepoints) in a UTF8 encoded `text` until `\0` is found. +// NOTE: If a invalid UTF8 sequence is encountered a `?`(0x3f) codepoint is counted instead. +unsigned int TextCountCodepoints(const char *text) +{ + unsigned int len = 0; + char* ptr = (char*)&text[0]; + while(*ptr != '\0') + { + int next = 0; + int letter = GetNextCodepoint(ptr, &next); + if(letter == 0x3f) ptr += 1; + else ptr += next; + ++len; + } + return len; +} + // Formatting of text with variables to 'embed' const char *TextFormat(const char *text, ...) { -- cgit v1.2.3 From 2249f123045208fa66c8c1c423020ffcf7eef284 Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 22 Apr 2019 18:25:30 +0200 Subject: Expose rlgl functions on shared libraries --- src/rlgl.h | 198 ++++++++++++++++++++++++++++++++----------------------------- 1 file changed, 103 insertions(+), 95 deletions(-) (limited to 'src') diff --git a/src/rlgl.h b/src/rlgl.h index 048c75da..0356858a 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -64,6 +64,14 @@ #if defined(RLGL_STANDALONE) #define RAYMATH_STANDALONE #define RAYMATH_HEADER_ONLY + + #if defined(_WIN32) && defined(BUILD_LIBTYPE_SHARED) + #define RLAPI __declspec(dllexport) // We are building raylib as a Win32 shared library (.dll) + #elif defined(_WIN32) && defined(USE_LIBTYPE_SHARED) + #define RLAPI __declspec(dllimport) // We are using raylib as a Win32 shared library (.dll) + #else + #define RLAPI // We are building or using raylib as a static library (or Linux shared library) + #endif #else #include "raylib.h" // Required for: Model, Shader, Texture2D, TraceLog() #endif @@ -395,90 +403,90 @@ extern "C" { // Prevents name mangling of functions //------------------------------------------------------------------------------------ // Functions Declaration - Matrix operations //------------------------------------------------------------------------------------ -void rlMatrixMode(int mode); // Choose the current matrix to be transformed -void rlPushMatrix(void); // Push the current matrix to stack -void rlPopMatrix(void); // Pop lattest inserted matrix from stack -void rlLoadIdentity(void); // Reset current matrix to identity matrix -void rlTranslatef(float x, float y, float z); // Multiply the current matrix by a translation matrix -void rlRotatef(float angleDeg, float x, float y, float z); // Multiply the current matrix by a rotation matrix -void rlScalef(float x, float y, float z); // Multiply the current matrix by a scaling matrix -void rlMultMatrixf(float *matf); // Multiply the current matrix by another matrix -void rlFrustum(double left, double right, double bottom, double top, double near, double far); -void rlOrtho(double left, double right, double bottom, double top, double near, double far); -void rlViewport(int x, int y, int width, int height); // Set the viewport area +RLAPI void rlMatrixMode(int mode); // Choose the current matrix to be transformed +RLAPI void rlPushMatrix(void); // Push the current matrix to stack +RLAPI void rlPopMatrix(void); // Pop lattest inserted matrix from stack +RLAPI void rlLoadIdentity(void); // Reset current matrix to identity matrix +RLAPI void rlTranslatef(float x, float y, float z); // Multiply the current matrix by a translation matrix +RLAPI void rlRotatef(float angleDeg, float x, float y, float z); // Multiply the current matrix by a rotation matrix +RLAPI void rlScalef(float x, float y, float z); // Multiply the current matrix by a scaling matrix +RLAPI void rlMultMatrixf(float *matf); // Multiply the current matrix by another matrix +RLAPI void rlFrustum(double left, double right, double bottom, double top, double near, double far); +RLAPI void rlOrtho(double left, double right, double bottom, double top, double near, double far); +RLAPI void rlViewport(int x, int y, int width, int height); // Set the viewport area //------------------------------------------------------------------------------------ // Functions Declaration - Vertex level operations //------------------------------------------------------------------------------------ -void rlBegin(int mode); // Initialize drawing mode (how to organize vertex) -void rlEnd(void); // Finish vertex providing -void rlVertex2i(int x, int y); // Define one vertex (position) - 2 int -void rlVertex2f(float x, float y); // Define one vertex (position) - 2 float -void rlVertex3f(float x, float y, float z); // Define one vertex (position) - 3 float -void rlTexCoord2f(float x, float y); // Define one vertex (texture coordinate) - 2 float -void rlNormal3f(float x, float y, float z); // Define one vertex (normal) - 3 float -void rlColor4ub(byte r, byte g, byte b, byte a); // Define one vertex (color) - 4 byte -void rlColor3f(float x, float y, float z); // Define one vertex (color) - 3 float -void rlColor4f(float x, float y, float z, float w); // Define one vertex (color) - 4 float +RLAPI void rlBegin(int mode); // Initialize drawing mode (how to organize vertex) +RLAPI void rlEnd(void); // Finish vertex providing +RLAPI void rlVertex2i(int x, int y); // Define one vertex (position) - 2 int +RLAPI void rlVertex2f(float x, float y); // Define one vertex (position) - 2 float +RLAPI void rlVertex3f(float x, float y, float z); // Define one vertex (position) - 3 float +RLAPI void rlTexCoord2f(float x, float y); // Define one vertex (texture coordinate) - 2 float +RLAPI void rlNormal3f(float x, float y, float z); // Define one vertex (normal) - 3 float +RLAPI void rlColor4ub(byte r, byte g, byte b, byte a); // Define one vertex (color) - 4 byte +RLAPI void rlColor3f(float x, float y, float z); // Define one vertex (color) - 3 float +RLAPI void rlColor4f(float x, float y, float z, float w); // Define one vertex (color) - 4 float //------------------------------------------------------------------------------------ // Functions Declaration - OpenGL equivalent functions (common to 1.1, 3.3+, ES2) // NOTE: This functions are used to completely abstract raylib code from OpenGL layer //------------------------------------------------------------------------------------ -void rlEnableTexture(unsigned int id); // Enable texture usage -void rlDisableTexture(void); // Disable texture usage -void rlTextureParameters(unsigned int id, int param, int value); // Set texture parameters (filter, wrap) -void rlEnableRenderTexture(unsigned int id); // Enable render texture (fbo) -void rlDisableRenderTexture(void); // Disable render texture (fbo), return to default framebuffer -void rlEnableDepthTest(void); // Enable depth test -void rlDisableDepthTest(void); // Disable depth test -void rlEnableWireMode(void); // Enable wire mode -void rlDisableWireMode(void); // Disable wire mode -void rlDeleteTextures(unsigned int id); // Delete OpenGL texture from GPU -void rlDeleteRenderTextures(RenderTexture2D target); // Delete render textures (fbo) from GPU -void rlDeleteShader(unsigned int id); // Delete OpenGL shader program from GPU -void rlDeleteVertexArrays(unsigned int id); // Unload vertex data (VAO) from GPU memory -void rlDeleteBuffers(unsigned int id); // Unload vertex data (VBO) from GPU memory -void rlClearColor(byte r, byte g, byte b, byte a); // Clear color buffer with color -void rlClearScreenBuffers(void); // Clear used screen buffers (color and depth) -void rlUpdateBuffer(int bufferId, void *data, int dataSize); // Update GPU buffer with new data -unsigned int rlLoadAttribBuffer(unsigned int vaoId, int shaderLoc, void *buffer, int size, bool dynamic); // Load a new attributes buffer +RLAPI void rlEnableTexture(unsigned int id); // Enable texture usage +RLAPI void rlDisableTexture(void); // Disable texture usage +RLAPI void rlTextureParameters(unsigned int id, int param, int value); // Set texture parameters (filter, wrap) +RLAPI void rlEnableRenderTexture(unsigned int id); // Enable render texture (fbo) +RLAPI void rlDisableRenderTexture(void); // Disable render texture (fbo), return to default framebuffer +RLAPI void rlEnableDepthTest(void); // Enable depth test +RLAPI void rlDisableDepthTest(void); // Disable depth test +RLAPI void rlEnableWireMode(void); // Enable wire mode +RLAPI void rlDisableWireMode(void); // Disable wire mode +RLAPI void rlDeleteTextures(unsigned int id); // Delete OpenGL texture from GPU +RLAPI void rlDeleteRenderTextures(RenderTexture2D target); // Delete render textures (fbo) from GPU +RLAPI void rlDeleteShader(unsigned int id); // Delete OpenGL shader program from GPU +RLAPI void rlDeleteVertexArrays(unsigned int id); // Unload vertex data (VAO) from GPU memory +RLAPI void rlDeleteBuffers(unsigned int id); // Unload vertex data (VBO) from GPU memory +RLAPI void rlClearColor(byte r, byte g, byte b, byte a); // Clear color buffer with color +RLAPI void rlClearScreenBuffers(void); // Clear used screen buffers (color and depth) +RLAPI void rlUpdateBuffer(int bufferId, void *data, int dataSize); // Update GPU buffer with new data +RLAPI unsigned int rlLoadAttribBuffer(unsigned int vaoId, int shaderLoc, void *buffer, int size, bool dynamic); // Load a new attributes buffer //------------------------------------------------------------------------------------ // Functions Declaration - rlgl functionality //------------------------------------------------------------------------------------ -void rlglInit(int width, int height); // Initialize rlgl (buffers, shaders, textures, states) -void rlglClose(void); // De-inititialize rlgl (buffers, shaders, textures) -void rlglDraw(void); // Update and draw default internal buffers +RLAPI void rlglInit(int width, int height); // Initialize rlgl (buffers, shaders, textures, states) +RLAPI void rlglClose(void); // De-inititialize rlgl (buffers, shaders, textures) +RLAPI void rlglDraw(void); // Update and draw default internal buffers -int rlGetVersion(void); // Returns current OpenGL version -bool rlCheckBufferLimit(int vCount); // Check internal buffer overflow for a given number of vertex -void rlSetDebugMarker(const char *text); // Set debug marker for analysis -void rlLoadExtensions(void *loader); // Load OpenGL extensions -Vector3 rlUnproject(Vector3 source, Matrix proj, Matrix view); // Get world coordinates from screen coordinates +RLAPI int rlGetVersion(void); // Returns current OpenGL version +RLAPI bool rlCheckBufferLimit(int vCount); // Check internal buffer overflow for a given number of vertex +RLAPI void rlSetDebugMarker(const char *text); // Set debug marker for analysis +RLAPI void rlLoadExtensions(void *loader); // Load OpenGL extensions +RLAPI Vector3 rlUnproject(Vector3 source, Matrix proj, Matrix view); // Get world coordinates from screen coordinates // Textures data management -unsigned int rlLoadTexture(void *data, int width, int height, int format, int mipmapCount); // Load texture in GPU -unsigned int rlLoadTextureDepth(int width, int height, int bits, bool useRenderBuffer); // Load depth texture/renderbuffer (to be attached to fbo) -unsigned int rlLoadTextureCubemap(void *data, int size, int format); // Load texture cubemap -void rlUpdateTexture(unsigned int id, int width, int height, int format, const void *data); // Update GPU texture with new data -void rlGetGlTextureFormats(int format, unsigned int *glInternalFormat, unsigned int *glFormat, unsigned int *glType); // Get OpenGL internal formats -void rlUnloadTexture(unsigned int id); // Unload texture from GPU memory +RLAPI unsigned int rlLoadTexture(void *data, int width, int height, int format, int mipmapCount); // Load texture in GPU +RLAPI unsigned int rlLoadTextureDepth(int width, int height, int bits, bool useRenderBuffer); // Load depth texture/renderbuffer (to be attached to fbo) +RLAPI unsigned int rlLoadTextureCubemap(void *data, int size, int format); // Load texture cubemap +RLAPI void rlUpdateTexture(unsigned int id, int width, int height, int format, const void *data); // Update GPU texture with new data +RLAPI void rlGetGlTextureFormats(int format, unsigned int *glInternalFormat, unsigned int *glFormat, unsigned int *glType); // Get OpenGL internal formats +RLAPI void rlUnloadTexture(unsigned int id); // Unload texture from GPU memory -void rlGenerateMipmaps(Texture2D *texture); // Generate mipmap data for selected texture -void *rlReadTexturePixels(Texture2D texture); // Read texture pixel data -unsigned char *rlReadScreenPixels(int width, int height); // Read screen pixel data (color buffer) +RLAPI void rlGenerateMipmaps(Texture2D *texture); // Generate mipmap data for selected texture +RLAPI void *rlReadTexturePixels(Texture2D texture); // Read texture pixel data +RLAPI unsigned char *rlReadScreenPixels(int width, int height); // Read screen pixel data (color buffer) // Render texture management (fbo) -RenderTexture2D rlLoadRenderTexture(int width, int height, int format, int depthBits, bool useDepthTexture); // Load a render texture (with color and depth attachments) -void rlRenderTextureAttach(RenderTexture target, unsigned int id, int attachType); // Attach texture/renderbuffer to an fbo -bool rlRenderTextureComplete(RenderTexture target); // Verify render texture is complete +RLAPI RenderTexture2D rlLoadRenderTexture(int width, int height, int format, int depthBits, bool useDepthTexture); // Load a render texture (with color and depth attachments) +RLAPI void rlRenderTextureAttach(RenderTexture target, unsigned int id, int attachType); // Attach texture/renderbuffer to an fbo +RLAPI bool rlRenderTextureComplete(RenderTexture target); // Verify render texture is complete // Vertex data management -void rlLoadMesh(Mesh *mesh, bool dynamic); // Upload vertex data into GPU and provided VAO/VBO ids -void rlUpdateMesh(Mesh mesh, int buffer, int numVertex); // Update vertex data on GPU (upload new data to one buffer) -void rlDrawMesh(Mesh mesh, Material material, Matrix transform); // Draw a 3d mesh with material and transform -void rlUnloadMesh(Mesh *mesh); // Unload mesh data from CPU and GPU +RLAPI void rlLoadMesh(Mesh *mesh, bool dynamic); // Upload vertex data into GPU and provided VAO/VBO ids +RLAPI void rlUpdateMesh(Mesh mesh, int buffer, int numVertex); // Update vertex data on GPU (upload new data to one buffer) +RLAPI void rlDrawMesh(Mesh mesh, Material material, Matrix transform); // Draw a 3d mesh with material and transform +RLAPI void rlUnloadMesh(Mesh *mesh); // Unload mesh data from CPU and GPU // NOTE: There is a set of shader related functions that are available to end user, // to avoid creating function wrappers through core module, they have been directly declared in raylib.h @@ -489,48 +497,48 @@ void rlUnloadMesh(Mesh *mesh); // Unload me // NOTE: This functions are useless when using OpenGL 1.1 //------------------------------------------------------------------------------------ // Shader loading/unloading functions -char *LoadText(const char *fileName); // Load chars array from text file -Shader LoadShader(const char *vsFileName, const char *fsFileName); // Load shader from files and bind default locations -Shader LoadShaderCode(char *vsCode, char *fsCode); // Load shader from code strings and bind default locations -void UnloadShader(Shader shader); // Unload shader from GPU memory (VRAM) +RLAPI char *LoadText(const char *fileName); // Load chars array from text file +RLAPI Shader LoadShader(const char *vsFileName, const char *fsFileName); // Load shader from files and bind default locations +RLAPI Shader LoadShaderCode(char *vsCode, char *fsCode); // Load shader from code strings and bind default locations +RLAPI void UnloadShader(Shader shader); // Unload shader from GPU memory (VRAM) -Shader GetShaderDefault(void); // Get default shader -Texture2D GetTextureDefault(void); // Get default texture +RLAPI Shader GetShaderDefault(void); // Get default shader +RLAPI Texture2D GetTextureDefault(void); // Get default texture // Shader configuration functions -int GetShaderLocation(Shader shader, const char *uniformName); // Get shader uniform location -void SetShaderValue(Shader shader, int uniformLoc, const void *value, int uniformType); // Set shader uniform value -void SetShaderValueV(Shader shader, int uniformLoc, const void *value, int uniformType, int count); // Set shader uniform value vector -void SetShaderValueMatrix(Shader shader, int uniformLoc, Matrix mat); // Set shader uniform value (matrix 4x4) -void SetMatrixProjection(Matrix proj); // Set a custom projection matrix (replaces internal projection matrix) -void SetMatrixModelview(Matrix view); // Set a custom modelview matrix (replaces internal modelview matrix) -Matrix GetMatrixModelview(); // Get internal modelview matrix +RLAPI int GetShaderLocation(Shader shader, const char *uniformName); // Get shader uniform location +RLAPI void SetShaderValue(Shader shader, int uniformLoc, const void *value, int uniformType); // Set shader uniform value +RLAPI void SetShaderValueV(Shader shader, int uniformLoc, const void *value, int uniformType, int count); // Set shader uniform value vector +RLAPI void SetShaderValueMatrix(Shader shader, int uniformLoc, Matrix mat); // Set shader uniform value (matrix 4x4) +RLAPI void SetMatrixProjection(Matrix proj); // Set a custom projection matrix (replaces internal projection matrix) +RLAPI void SetMatrixModelview(Matrix view); // Set a custom modelview matrix (replaces internal modelview matrix) +RLAPI Matrix GetMatrixModelview(); // Get internal modelview matrix // Texture maps generation (PBR) // NOTE: Required shaders should be provided -Texture2D GenTextureCubemap(Shader shader, Texture2D skyHDR, int size); // Generate cubemap texture from HDR texture -Texture2D GenTextureIrradiance(Shader shader, Texture2D cubemap, int size); // Generate irradiance texture using cubemap data -Texture2D GenTexturePrefilter(Shader shader, Texture2D cubemap, int size); // Generate prefilter texture using cubemap data -Texture2D GenTextureBRDF(Shader shader, int size); // Generate BRDF texture using cubemap data +RLAPI Texture2D GenTextureCubemap(Shader shader, Texture2D skyHDR, int size); // Generate cubemap texture from HDR texture +RLAPI Texture2D GenTextureIrradiance(Shader shader, Texture2D cubemap, int size); // Generate irradiance texture using cubemap data +RLAPI Texture2D GenTexturePrefilter(Shader shader, Texture2D cubemap, int size); // Generate prefilter texture using cubemap data +RLAPI Texture2D GenTextureBRDF(Shader shader, int size); // Generate BRDF texture using cubemap data // Shading begin/end functions -void BeginShaderMode(Shader shader); // Begin custom shader drawing -void EndShaderMode(void); // End custom shader drawing (use default shader) -void BeginBlendMode(int mode); // Begin blending mode (alpha, additive, multiplied) -void EndBlendMode(void); // End blending mode (reset to default: alpha blending) +RLAPI void BeginShaderMode(Shader shader); // Begin custom shader drawing +RLAPI void EndShaderMode(void); // End custom shader drawing (use default shader) +RLAPI void BeginBlendMode(int mode); // Begin blending mode (alpha, additive, multiplied) +RLAPI void EndBlendMode(void); // End blending mode (reset to default: alpha blending) // VR control functions -void InitVrSimulator(void); // Init VR simulator for selected device parameters -void CloseVrSimulator(void); // Close VR simulator for current device -void UpdateVrTracking(Camera *camera); // Update VR tracking (position and orientation) and camera -void SetVrConfiguration(VrDeviceInfo info, Shader distortion); // Set stereo rendering configuration parameters -bool IsVrSimulatorReady(void); // Detect if VR simulator is ready -void ToggleVrMode(void); // Enable/Disable VR experience -void BeginVrDrawing(void); // Begin VR simulator stereo rendering -void EndVrDrawing(void); // End VR simulator stereo rendering - -void TraceLog(int msgType, const char *text, ...); // Show trace log messages (LOG_INFO, LOG_WARNING, LOG_ERROR, LOG_DEBUG) -int GetPixelDataSize(int width, int height, int format);// Get pixel data size in bytes (image or texture) +RLAPI void InitVrSimulator(void); // Init VR simulator for selected device parameters +RLAPI void CloseVrSimulator(void); // Close VR simulator for current device +RLAPI void UpdateVrTracking(Camera *camera); // Update VR tracking (position and orientation) and camera +RLAPI void SetVrConfiguration(VrDeviceInfo info, Shader distortion); // Set stereo rendering configuration parameters +RLAPI bool IsVrSimulatorReady(void); // Detect if VR simulator is ready +RLAPI void ToggleVrMode(void); // Enable/Disable VR experience +RLAPI void BeginVrDrawing(void); // Begin VR simulator stereo rendering +RLAPI void EndVrDrawing(void); // End VR simulator stereo rendering + +RLAPI void TraceLog(int msgType, const char *text, ...); // Show trace log messages (LOG_INFO, LOG_WARNING, LOG_ERROR, LOG_DEBUG) +RLAPI int GetPixelDataSize(int width, int height, int format);// Get pixel data size in bytes (image or texture) #endif #if defined(__cplusplus) -- cgit v1.2.3 From 152b7471e9bd750f28f3fe494ba4e30affe23a47 Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 22 Apr 2019 18:46:05 +0200 Subject: Comment HiDPI window request At least until a proper solution is found! --- src/core.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/core.c b/src/core.c index ba41c773..6bb54c51 100644 --- a/src/core.c +++ b/src/core.c @@ -2357,7 +2357,8 @@ static bool InitGraphicsDevice(int width, int height) //glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API); // OpenGL API to use. Alternative: GLFW_OPENGL_ES_API //glfwWindowHint(GLFW_AUX_BUFFERS, 0); // Number of auxiliar buffers #if defined(PLATFORM_DESKTOP) - glfwWindowHint(GLFW_SCALE_TO_MONITOR, GLFW_TRUE); // Scale content area based on the monitor content scale where window is placed on + // TODO: If using external GLFW, it requires latest GLFW 3.3 for this functionality + //glfwWindowHint(GLFW_SCALE_TO_MONITOR, GLFW_TRUE); // Scale content area based on the monitor content scale where window is placed on #endif // Check some Window creation flags -- cgit v1.2.3 From cd934c9f669f22dc49304a722c8acd36b94b9321 Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 22 Apr 2019 19:00:43 +0200 Subject: Update GLFW to 3.3.1 --- src/external/glfw/CMake/amd64-mingw32msvc.cmake | 13 - src/external/glfw/CMake/i586-mingw32msvc.cmake | 13 - src/external/glfw/CMake/i686-pc-mingw32.cmake | 13 - .../glfw/CMake/i686-w64-mingw32-clang.cmake | 13 + src/external/glfw/CMake/i686-w64-mingw32.cmake | 2 +- src/external/glfw/CMake/modules/FindVulkan.cmake | 41 - .../glfw/CMake/x86_64-w64-mingw32-clang.cmake | 13 + src/external/glfw/CMake/x86_64-w64-mingw32.cmake | 2 +- src/external/glfw/CMakeLists.txt | 41 +- src/external/glfw/README.md | 214 +- src/external/glfw/deps/KHR/khrplatform.h | 282 - src/external/glfw/deps/glad.c | 1678 ----- src/external/glfw/deps/glad/gl.h | 3840 ++++++++++ src/external/glfw/deps/glad/glad.h | 3680 ---------- src/external/glfw/deps/glad/khrplatform.h | 282 + src/external/glfw/deps/glad/vk_platform.h | 92 + src/external/glfw/deps/glad/vulkan.h | 3480 ++++++++++ src/external/glfw/deps/glad_gl.c | 1791 +++++ src/external/glfw/deps/glad_vulkan.c | 593 ++ src/external/glfw/deps/vulkan/vk_platform.h | 92 - src/external/glfw/deps/vulkan/vulkan.h | 73 - src/external/glfw/deps/vulkan/vulkan_core.h | 7334 -------------------- src/external/glfw/include/GLFW/glfw3.h | 261 +- src/external/glfw/include/GLFW/glfw3native.h | 2 +- src/external/glfw/src/CMakeLists.txt | 6 +- src/external/glfw/src/cocoa_init.m | 209 +- src/external/glfw/src/cocoa_joystick.h | 2 +- src/external/glfw/src/cocoa_joystick.m | 37 +- src/external/glfw/src/cocoa_monitor.m | 108 +- src/external/glfw/src/cocoa_platform.h | 32 +- src/external/glfw/src/cocoa_window.m | 510 +- src/external/glfw/src/context.c | 2 +- src/external/glfw/src/egl_context.c | 4 +- src/external/glfw/src/egl_context.h | 2 +- src/external/glfw/src/glx_context.c | 4 +- src/external/glfw/src/glx_context.h | 2 +- src/external/glfw/src/init.c | 2 +- src/external/glfw/src/input.c | 63 +- src/external/glfw/src/internal.h | 7 +- src/external/glfw/src/linux_joystick.c | 2 +- src/external/glfw/src/mappings.h | 2 +- src/external/glfw/src/mappings.h.in | 2 +- src/external/glfw/src/monitor.c | 27 +- src/external/glfw/src/nsgl_context.h | 18 +- src/external/glfw/src/nsgl_context.m | 102 +- src/external/glfw/src/null_init.c | 2 +- src/external/glfw/src/null_joystick.c | 2 +- src/external/glfw/src/null_joystick.h | 2 +- src/external/glfw/src/null_monitor.c | 8 +- src/external/glfw/src/null_platform.h | 2 +- src/external/glfw/src/null_window.c | 11 +- src/external/glfw/src/osmesa_context.c | 6 +- src/external/glfw/src/osmesa_context.h | 2 +- src/external/glfw/src/posix_thread.c | 2 +- src/external/glfw/src/posix_thread.h | 2 +- src/external/glfw/src/posix_time.c | 2 +- src/external/glfw/src/posix_time.h | 2 +- src/external/glfw/src/vulkan.c | 2 +- src/external/glfw/src/wgl_context.c | 179 +- src/external/glfw/src/wgl_context.h | 2 +- src/external/glfw/src/win32_init.c | 40 +- src/external/glfw/src/win32_joystick.c | 6 +- src/external/glfw/src/win32_joystick.h | 2 +- src/external/glfw/src/win32_monitor.c | 19 +- src/external/glfw/src/win32_platform.h | 11 +- src/external/glfw/src/win32_thread.c | 2 +- src/external/glfw/src/win32_time.c | 2 +- src/external/glfw/src/win32_window.c | 138 +- src/external/glfw/src/window.c | 20 +- src/external/glfw/src/wl_init.c | 8 +- src/external/glfw/src/wl_monitor.c | 17 +- src/external/glfw/src/wl_platform.h | 3 +- src/external/glfw/src/wl_window.c | 49 +- src/external/glfw/src/x11_init.c | 8 +- src/external/glfw/src/x11_monitor.c | 99 +- src/external/glfw/src/x11_platform.h | 4 +- src/external/glfw/src/x11_window.c | 110 +- src/external/glfw/src/xkb_unicode.c | 2 +- 78 files changed, 11613 insertions(+), 14141 deletions(-) delete mode 100644 src/external/glfw/CMake/amd64-mingw32msvc.cmake delete mode 100644 src/external/glfw/CMake/i586-mingw32msvc.cmake delete mode 100644 src/external/glfw/CMake/i686-pc-mingw32.cmake create mode 100644 src/external/glfw/CMake/i686-w64-mingw32-clang.cmake delete mode 100644 src/external/glfw/CMake/modules/FindVulkan.cmake create mode 100644 src/external/glfw/CMake/x86_64-w64-mingw32-clang.cmake delete mode 100644 src/external/glfw/deps/KHR/khrplatform.h delete mode 100644 src/external/glfw/deps/glad.c create mode 100644 src/external/glfw/deps/glad/gl.h delete mode 100644 src/external/glfw/deps/glad/glad.h create mode 100644 src/external/glfw/deps/glad/khrplatform.h create mode 100644 src/external/glfw/deps/glad/vk_platform.h create mode 100644 src/external/glfw/deps/glad/vulkan.h create mode 100644 src/external/glfw/deps/glad_gl.c create mode 100644 src/external/glfw/deps/glad_vulkan.c delete mode 100644 src/external/glfw/deps/vulkan/vk_platform.h delete mode 100644 src/external/glfw/deps/vulkan/vulkan.h delete mode 100644 src/external/glfw/deps/vulkan/vulkan_core.h (limited to 'src') diff --git a/src/external/glfw/CMake/amd64-mingw32msvc.cmake b/src/external/glfw/CMake/amd64-mingw32msvc.cmake deleted file mode 100644 index c264ff0d..00000000 --- a/src/external/glfw/CMake/amd64-mingw32msvc.cmake +++ /dev/null @@ -1,13 +0,0 @@ -# Define the environment for cross compiling from Linux to Win64 -SET(CMAKE_SYSTEM_NAME Windows) -SET(CMAKE_SYSTEM_VERSION 1) -SET(CMAKE_C_COMPILER "amd64-mingw32msvc-gcc") -SET(CMAKE_CXX_COMPILER "amd64-mingw32msvc-g++") -SET(CMAKE_RC_COMPILER "amd64-mingw32msvc-windres") -SET(CMAKE_RANLIB "amd64-mingw32msvc-ranlib") - -# Configure the behaviour of the find commands -SET(CMAKE_FIND_ROOT_PATH "/usr/amd64-mingw32msvc") -SET(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) -SET(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) -SET(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) diff --git a/src/external/glfw/CMake/i586-mingw32msvc.cmake b/src/external/glfw/CMake/i586-mingw32msvc.cmake deleted file mode 100644 index c871e5be..00000000 --- a/src/external/glfw/CMake/i586-mingw32msvc.cmake +++ /dev/null @@ -1,13 +0,0 @@ -# Define the environment for cross compiling from Linux to Win32 -SET(CMAKE_SYSTEM_NAME Windows) -SET(CMAKE_SYSTEM_VERSION 1) -SET(CMAKE_C_COMPILER "i586-mingw32msvc-gcc") -SET(CMAKE_CXX_COMPILER "i586-mingw32msvc-g++") -SET(CMAKE_RC_COMPILER "i586-mingw32msvc-windres") -SET(CMAKE_RANLIB "i586-mingw32msvc-ranlib") - -# Configure the behaviour of the find commands -SET(CMAKE_FIND_ROOT_PATH "/usr/i586-mingw32msvc") -SET(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) -SET(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) -SET(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) diff --git a/src/external/glfw/CMake/i686-pc-mingw32.cmake b/src/external/glfw/CMake/i686-pc-mingw32.cmake deleted file mode 100644 index b657d944..00000000 --- a/src/external/glfw/CMake/i686-pc-mingw32.cmake +++ /dev/null @@ -1,13 +0,0 @@ -# Define the environment for cross compiling from Linux to Win32 -SET(CMAKE_SYSTEM_NAME Windows) # Target system name -SET(CMAKE_SYSTEM_VERSION 1) -SET(CMAKE_C_COMPILER "i686-pc-mingw32-gcc") -SET(CMAKE_CXX_COMPILER "i686-pc-mingw32-g++") -SET(CMAKE_RC_COMPILER "i686-pc-mingw32-windres") -SET(CMAKE_RANLIB "i686-pc-mingw32-ranlib") - -#Configure the behaviour of the find commands -SET(CMAKE_FIND_ROOT_PATH "/opt/mingw/usr/i686-pc-mingw32") -SET(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) -SET(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) -SET(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) diff --git a/src/external/glfw/CMake/i686-w64-mingw32-clang.cmake b/src/external/glfw/CMake/i686-w64-mingw32-clang.cmake new file mode 100644 index 00000000..8726b238 --- /dev/null +++ b/src/external/glfw/CMake/i686-w64-mingw32-clang.cmake @@ -0,0 +1,13 @@ +# Define the environment for cross-compiling with 32-bit MinGW-w64 Clang +SET(CMAKE_SYSTEM_NAME Windows) # Target system name +SET(CMAKE_SYSTEM_VERSION 1) +SET(CMAKE_C_COMPILER "i686-w64-mingw32-clang") +SET(CMAKE_CXX_COMPILER "i686-w64-mingw32-clang++") +SET(CMAKE_RC_COMPILER "i686-w64-mingw32-windres") +SET(CMAKE_RANLIB "i686-w64-mingw32-ranlib") + +# Configure the behaviour of the find commands +SET(CMAKE_FIND_ROOT_PATH "/usr/i686-w64-mingw32") +SET(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) +SET(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) +SET(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) diff --git a/src/external/glfw/CMake/i686-w64-mingw32.cmake b/src/external/glfw/CMake/i686-w64-mingw32.cmake index bbd9f895..2ca4dcd9 100644 --- a/src/external/glfw/CMake/i686-w64-mingw32.cmake +++ b/src/external/glfw/CMake/i686-w64-mingw32.cmake @@ -1,4 +1,4 @@ -# Define the environment for cross compiling from Linux to Win32 +# Define the environment for cross-compiling with 32-bit MinGW-w64 GCC SET(CMAKE_SYSTEM_NAME Windows) # Target system name SET(CMAKE_SYSTEM_VERSION 1) SET(CMAKE_C_COMPILER "i686-w64-mingw32-gcc") diff --git a/src/external/glfw/CMake/modules/FindVulkan.cmake b/src/external/glfw/CMake/modules/FindVulkan.cmake deleted file mode 100644 index 5004356b..00000000 --- a/src/external/glfw/CMake/modules/FindVulkan.cmake +++ /dev/null @@ -1,41 +0,0 @@ -# Find Vulkan -# -# VULKAN_INCLUDE_DIR -# VULKAN_LIBRARY -# VULKAN_FOUND - -if (WIN32) - find_path(VULKAN_INCLUDE_DIR NAMES vulkan/vulkan.h HINTS - "$ENV{VULKAN_SDK}/Include" - "$ENV{VK_SDK_PATH}/Include") - if (CMAKE_SIZEOF_VOID_P EQUAL 8) - find_library(VULKAN_LIBRARY NAMES vulkan-1 HINTS - "$ENV{VULKAN_SDK}/Lib" - "$ENV{VULKAN_SDK}/Bin" - "$ENV{VK_SDK_PATH}/Bin") - find_library(VULKAN_STATIC_LIBRARY NAMES vkstatic.1 HINTS - "$ENV{VULKAN_SDK}/Lib" - "$ENV{VULKAN_SDK}/Bin" - "$ENV{VK_SDK_PATH}/Bin") - else() - find_library(VULKAN_LIBRARY NAMES vulkan-1 HINTS - "$ENV{VULKAN_SDK}/Lib32" - "$ENV{VULKAN_SDK}/Bin32" - "$ENV{VK_SDK_PATH}/Bin32") - find_library(VULKAN_STATIC_LIBRARY NAMES vkstatic.1 HINTS - "$ENV{VULKAN_SDK}/Lib32" - "$ENV{VULKAN_SDK}/Bin32" - "$ENV{VK_SDK_PATH}/Bin32") - endif() -else() - find_path(VULKAN_INCLUDE_DIR NAMES vulkan/vulkan.h HINTS - "$ENV{VULKAN_SDK}/include") - find_library(VULKAN_LIBRARY NAMES vulkan HINTS - "$ENV{VULKAN_SDK}/lib") -endif() - -include(FindPackageHandleStandardArgs) -find_package_handle_standard_args(Vulkan DEFAULT_MSG VULKAN_LIBRARY VULKAN_INCLUDE_DIR) - -mark_as_advanced(VULKAN_INCLUDE_DIR VULKAN_LIBRARY VULKAN_STATIC_LIBRARY) - diff --git a/src/external/glfw/CMake/x86_64-w64-mingw32-clang.cmake b/src/external/glfw/CMake/x86_64-w64-mingw32-clang.cmake new file mode 100644 index 00000000..60f7914d --- /dev/null +++ b/src/external/glfw/CMake/x86_64-w64-mingw32-clang.cmake @@ -0,0 +1,13 @@ +# Define the environment for cross-compiling with 64-bit MinGW-w64 Clang +SET(CMAKE_SYSTEM_NAME Windows) # Target system name +SET(CMAKE_SYSTEM_VERSION 1) +SET(CMAKE_C_COMPILER "x86_64-w64-mingw32-clang") +SET(CMAKE_CXX_COMPILER "x86_64-w64-mingw32-clang++") +SET(CMAKE_RC_COMPILER "x86_64-w64-mingw32-windres") +SET(CMAKE_RANLIB "x86_64-w64-mingw32-ranlib") + +# Configure the behaviour of the find commands +SET(CMAKE_FIND_ROOT_PATH "/usr/x86_64-w64-mingw32") +SET(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) +SET(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) +SET(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) diff --git a/src/external/glfw/CMake/x86_64-w64-mingw32.cmake b/src/external/glfw/CMake/x86_64-w64-mingw32.cmake index e629e457..063e845a 100644 --- a/src/external/glfw/CMake/x86_64-w64-mingw32.cmake +++ b/src/external/glfw/CMake/x86_64-w64-mingw32.cmake @@ -1,4 +1,4 @@ -# Define the environment for cross compiling from Linux to Win32 +# Define the environment for cross-compiling with 64-bit MinGW-w64 GCC SET(CMAKE_SYSTEM_NAME Windows) # Target system name SET(CMAKE_SYSTEM_VERSION 1) SET(CMAKE_C_COMPILER "x86_64-w64-mingw32-gcc") diff --git a/src/external/glfw/CMakeLists.txt b/src/external/glfw/CMakeLists.txt index 8393f448..061618ee 100644 --- a/src/external/glfw/CMakeLists.txt +++ b/src/external/glfw/CMakeLists.txt @@ -10,7 +10,7 @@ endif() set(GLFW_VERSION_MAJOR "3") set(GLFW_VERSION_MINOR "3") -set(GLFW_VERSION_PATCH "0") +set(GLFW_VERSION_PATCH "1") set(GLFW_VERSION_EXTRA "") set(GLFW_VERSION "${GLFW_VERSION_MAJOR}.${GLFW_VERSION_MINOR}") set(GLFW_VERSION_FULL "${GLFW_VERSION}.${GLFW_VERSION_PATCH}${GLFW_VERSION_EXTRA}") @@ -22,7 +22,7 @@ option(GLFW_BUILD_EXAMPLES "Build the GLFW example programs" ON) option(GLFW_BUILD_TESTS "Build the GLFW test programs" ON) option(GLFW_BUILD_DOCS "Build the GLFW documentation" ON) option(GLFW_INSTALL "Generate installation target" ON) -option(GLFW_VULKAN_STATIC "Use the Vulkan loader statically linked into application" OFF) +option(GLFW_VULKAN_STATIC "Assume the Vulkan loader is linked with the application" OFF) include(GNUInstallDirs) @@ -54,13 +54,17 @@ else() endif() if (GLFW_VULKAN_STATIC) + if (BUILD_SHARED_LIBS) + # If you absolutely must do this, remove this line and add the Vulkan + # loader static library via the CMAKE_SHARED_LINKER_FLAGS + message(FATAL_ERROR "You are trying to link the Vulkan loader static library into the GLFW shared library") + endif() set(_GLFW_VULKAN_STATIC 1) endif() list(APPEND CMAKE_MODULE_PATH "${GLFW_SOURCE_DIR}/CMake/modules") find_package(Threads REQUIRED) -find_package(Vulkan) if (GLFW_BUILD_DOCS) set(DOXYGEN_SKIP_DOT TRUE) @@ -157,24 +161,6 @@ else() message(FATAL_ERROR "No supported platform was detected") endif() -#-------------------------------------------------------------------- -# Add Vulkan static library if requested -#-------------------------------------------------------------------- -if (GLFW_VULKAN_STATIC) - if (VULKAN_FOUND AND VULKAN_STATIC_LIBRARY) - list(APPEND glfw_LIBRARIES "${VULKAN_STATIC_LIBRARY}") - if (BUILD_SHARED_LIBS) - message(WARNING "Linking Vulkan loader static library into GLFW") - endif() - else() - if (BUILD_SHARED_LIBS OR GLFW_BUILD_EXAMPLES OR GLFW_BUILD_TESTS) - message(FATAL_ERROR "Vulkan loader static library not found") - else() - message(WARNING "Vulkan loader static library not found") - endif() - endif() -endif() - #-------------------------------------------------------------------- # Find and add Unix math and time libraries #-------------------------------------------------------------------- @@ -306,16 +292,21 @@ if (_GLFW_COCOA) set(glfw_PKG_LIBS "-framework Cocoa -framework IOKit -framework CoreFoundation -framework CoreVideo") endif() +#-------------------------------------------------------------------- +# Add the Vulkan loader as a dependency if necessary +#-------------------------------------------------------------------- +if (GLFW_VULKAN_STATIC) + list(APPEND glfw_PKG_DEPS "vulkan") +endif() + #-------------------------------------------------------------------- # Export GLFW library dependencies #-------------------------------------------------------------------- foreach(arg ${glfw_PKG_DEPS}) - set(GLFW_PKG_DEPS "${GLFW_PKG_DEPS} ${arg}" CACHE INTERNAL - "GLFW pkg-config Requires.private") + set(GLFW_PKG_DEPS "${GLFW_PKG_DEPS} ${arg}") endforeach() foreach(arg ${glfw_PKG_LIBS}) - set(GLFW_PKG_LIBS "${GLFW_PKG_LIBS} ${arg}" CACHE INTERNAL - "GLFW pkg-config Libs.private") + set(GLFW_PKG_LIBS "${GLFW_PKG_LIBS} ${arg}") endforeach() #-------------------------------------------------------------------- diff --git a/src/external/glfw/README.md b/src/external/glfw/README.md index 86024bd3..3fce2f8c 100644 --- a/src/external/glfw/README.md +++ b/src/external/glfw/README.md @@ -10,24 +10,22 @@ GLFW is an Open Source, multi-platform library for OpenGL, OpenGL ES and Vulkan application development. It provides a simple, platform-independent API for creating windows, contexts and surfaces, reading input, handling events, etc. -GLFW natively supports Windows, macOS and Linux and other Unix-like systems. -An experimental implementation for the Wayland protocol is available but not -yet officially supported. +GLFW natively supports Windows, macOS and Linux and other Unix-like systems. On +Linux both X11 and Wayland is supported. GLFW is licensed under the [zlib/libpng license](http://www.glfw.org/license.html). -The latest stable release is version 3.2.1. - -See the [downloads](http://www.glfw.org/download.html) page for details and -files, or fetch the `latest` branch, which always points to the latest stable -release. Each release starting with 3.0 also has a corresponding [annotated +You can [download](http://www.glfw.org/download.html) the latest stable release +as source or Windows binaries, or fetch the `latest` branch from GitHub. Each +release starting with 3.0 also has a corresponding [annotated tag](https://github.com/glfw/glfw/releases) with source and binary archives. -The [version history](http://www.glfw.org/changelog.html) lists all user-visible -changes for every release. -This is a development branch for version 3.3, which is _not yet described_. -Pre-release documentation is available [here](http://www.glfw.org/docs/3.3/). +The [documentation](http://www.glfw.org/docs/latest/) is available online and is +included in all source and binary archives. See the [release +notes](https://www.glfw.org/docs/latest/news.html) for new features, caveats and +deprecations in the latest release. For more details see the [version +history](http://www.glfw.org/changelog.html). The `master` branch is the stable integration branch and _should_ always compile and run on all supported platforms, although details of newly added features may @@ -44,9 +42,10 @@ guide](http://www.glfw.org/docs/latest/moving.html) for moving to the GLFW ## Compiling GLFW -GLFW itself requires only the headers and libraries for your window system. It -does not need the headers for any context creation API (WGL, GLX, EGL, NSGL, -OSMesa) or rendering API (OpenGL, OpenGL ES, Vulkan) to enable support for them. +GLFW itself requires only the headers and libraries for your OS and window +system. It does not need the headers for any context creation API (WGL, GLX, +EGL, NSGL, OSMesa) or rendering API (OpenGL, OpenGL ES, Vulkan) to enable +support for them. GLFW supports compilation on Windows with Visual C++ 2010 and later, MinGW and MinGW-w64, on macOS with Clang and on Linux and other Unix-like systems with GCC @@ -75,7 +74,7 @@ more information. ## System requirements -GLFW supports Windows XP and later and macOS 10.7 and later. Linux and other +GLFW supports Windows XP and later and macOS 10.8 and later. Linux and other Unix-like systems running the X Window System are supported even without a desktop environment or modern extensions, although some features require a running window or clipboard manager. The OSMesa backend requires Mesa 6.3. @@ -98,17 +97,12 @@ located in the `deps/` directory. with command-line options - [TinyCThread](https://github.com/tinycthread/tinycthread) for threaded examples - - An OpenGL 3.2 core loader generated by - [glad](https://github.com/Dav1dde/glad) for examples using modern OpenGL + - [glad2](https://github.com/Dav1dde/glad) for loading OpenGL and Vulkan + functions - [linmath.h](https://github.com/datenwolf/linmath.h) for linear algebra in examples - [Nuklear](https://github.com/vurtun/nuklear) for test and example UI - [stb\_image\_write](https://github.com/nothings/stb) for writing images to disk - - [Vulkan headers](https://www.khronos.org/registry/vulkan/) for Vulkan tests - -The Vulkan example additionally requires the LunarG Vulkan SDK to be installed, -or it will not be included in the build. On macOS you need to provide the path -to the SDK manually as it has no standard installation location. The documentation is generated with [Doxygen](http://doxygen.org/) if CMake can find that tool. @@ -124,174 +118,7 @@ information on what to include when reporting a bug. ## Changelog -- Added `glfwGetError` function for querying the last error code and its - description (#970) -- Added `glfwUpdateGamepadMappings` function for importing gamepad mappings in - SDL\_GameControllerDB format (#900) -- Added `glfwJoystickIsGamepad` function for querying whether a joystick has - a gamepad mapping (#900) -- Added `glfwGetJoystickGUID` function for querying the SDL compatible GUID of - a joystick (#900) -- Added `glfwGetGamepadName` function for querying the name provided by the - gamepad mapping (#900) -- Added `glfwGetGamepadState` function, `GLFW_GAMEPAD_*` and `GLFWgamepadstate` - for retrieving gamepad input state (#900) -- Added `glfwGetWindowContentScale`, `glfwGetMonitorContentScale` and - `glfwSetWindowContentScaleCallback` for DPI-aware rendering - (#235,#439,#677,#845,#898) -- Added `glfwRequestWindowAttention` function for requesting attention from the - user (#732,#988) -- Added `glfwGetKeyScancode` function that allows retrieving platform dependent - scancodes for keys (#830) -- Added `glfwSetWindowMaximizeCallback` and `GLFWwindowmaximizefun` for - receiving window maximization events (#778) -- Added `glfwSetWindowAttrib` function for changing window attributes (#537) -- Added `glfwGetJoystickHats` function for querying joystick hats - (#889,#906,#934) -- Added `glfwInitHint` for setting initialization hints -- Added `glfwWindowHintString` for setting string type window hints (#893,#1139) -- Added `glfwGetWindowOpacity` and `glfwSetWindowOpacity` for controlling whole - window transparency (#1089) -- Added `glfwSetMonitorUserPointer` and `glfwGetMonitorUserPointer` for - per-monitor user pointers -- Added `glfwSetJoystickUserPointer` and `glfwGetJoystickUserPointer` for - per-joystick user pointers -- Added `glfwGetX11SelectionString` and `glfwSetX11SelectionString` - functions for accessing X11 primary selection (#894,#1056) -- Added headless [OSMesa](http://mesa3d.org/osmesa.html) backend (#850) -- Added definition of `GLAPIENTRY` to public header -- Added `GLFW_TRANSPARENT_FRAMEBUFFER` window hint and attribute for controlling - per-pixel framebuffer transparency (#197,#663,#715,#723,#1078) -- Added `GLFW_HOVERED` window attribute for polling cursor hover state (#1166) -- Added `GLFW_CENTER_CURSOR` window hint for controlling cursor centering - (#749,#842) -- Added `GLFW_FOCUS_ON_SHOW` window hint and attribute to control input focus - on calling show window (#1189) -- Added `GLFW_SCALE_TO_MONITOR` window hint for automatic window resizing - (#676,#1115) -- Added `GLFW_JOYSTICK_HAT_BUTTONS` init hint (#889) -- Added `GLFW_LOCK_KEY_MODS` input mode and `GLFW_MOD_*_LOCK` mod bits (#946) -- Added macOS specific `GLFW_COCOA_RETINA_FRAMEBUFFER` window hint -- Added macOS specific `GLFW_COCOA_FRAME_NAME` window hint (#195) -- Added macOS specific `GLFW_COCOA_GRAPHICS_SWITCHING` window hint (#377,#935) -- Added macOS specific `GLFW_COCOA_CHDIR_RESOURCES` init hint -- Added macOS specific `GLFW_COCOA_MENUBAR` init hint -- Added X11 specific `GLFW_X11_CLASS_NAME` and `GLFW_X11_INSTANCE_NAME` window - hints (#893,#1139) -- Added `GLFW_INCLUDE_ES32` for including the OpenGL ES 3.2 header -- Added `GLFW_OSMESA_CONTEXT_API` for creating OpenGL contexts with - [OSMesa](https://www.mesa3d.org/osmesa.html) (#281) -- Added `GenerateMappings.cmake` script for updating gamepad mappings -- Export CMake `GLFW_PKG_DEPS` and `GLFW_PKG_LIBS` to parent scope for use - in client pkg-configs (#1307) -- Added a `glfw_objlib` CMake OBJECT library target for embedding into static - libraries (#1307) -- Made `glfwCreateWindowSurface` emit an error when the window has a context - (#1194,#1205) -- Deprecated window parameter of clipboard string functions -- Deprecated charmods callback -- Removed `GLFW_USE_RETINA` compile-time option -- Removed `GLFW_USE_CHDIR` compile-time option -- Removed `GLFW_USE_MENUBAR` compile-time option -- Bugfix: Calling `glfwMaximizeWindow` on a full screen window was not ignored -- Bugfix: `GLFW_INCLUDE_VULKAN` could not be combined with the corresponding - OpenGL and OpenGL ES header macros -- Bugfix: `glfwGetInstanceProcAddress` returned `NULL` for - `vkGetInstanceProcAddr` when `_GLFW_VULKAN_STATIC` was enabled -- Bugfix: Invalid library paths were used in test and example CMake files (#930) -- Bugfix: The scancode for synthetic key release events was always zero -- Bugfix: The generated Doxyfile did not handle paths with spaces (#1081) -- Bugfix: The gamma ramp generated by `glfwSetGamma` did not use the monitor - ramp size (#1387,#1388) -- [Win32] Added system error strings to relevant GLFW error descriptions (#733) -- [Win32] Moved to `WM_INPUT` for disabled cursor mode motion input (#125) -- [Win32] Removed XInput circular deadzone from joystick axis data (#1045) -- [Win32] Bugfix: Undecorated windows could not be iconified by the user (#861) -- [Win32] Bugfix: Deadzone logic could underflow with some controllers (#910) -- [Win32] Bugfix: Bitness test in `FindVulkan.cmake` was VS specific (#928) -- [Win32] Bugfix: `glfwVulkanSupported` emitted an error on systems with - a loader but no ICD (#916) -- [Win32] Bugfix: Non-iconified full sreeen windows did not prevent screen - blanking or password enabled screensavers (#851) -- [Win32] Bugfix: Mouse capture logic lost secondary release messages (#954) -- [Win32] Bugfix: The 32-bit Vulkan loader library static was not searched for -- [Win32] Bugfix: Vulkan libraries have a new path as of SDK 1.0.42.0 (#956) -- [Win32] Bugfix: Monitors with no display devices were not enumerated (#960) -- [Win32] Bugfix: Monitor events were not emitted (#784) -- [Win32] Bugfix: The Cygwin DLL was installed to the wrong directory (#1035) -- [Win32] Bugfix: Normalization of axis data via XInput was incorrect (#1045) -- [Win32] Bugfix: `glfw3native.h` would undefine a foreign `APIENTRY` (#1062) -- [Win32] Bugfix: Disabled cursor mode prevented use of caption buttons - (#650,#1071) -- [Win32] Bugfix: Returned key names did not match other platforms (#943) -- [Win32] Bugfix: Undecorated windows did not maximize to workarea (#899) -- [Win32] Bugfix: Window was resized twice when entering full screen (#1085) -- [Win32] Bugfix: The HID device notification was not unregistered (#1170) -- [Win32] Bugfix: `glfwCreateWindow` activated window even with `GLFW_FOCUSED` - hint set to false (#1179,#1180) -- [Win32] Bugfix: The keypad equals key was reported as `GLFW_KEY_UNKNOWN` - (#1315,#1316) -- [Win32] Bugfix: A title bar would be drawn over undecorated windows in some - circumstances (#1383) -- [X11] Moved to XI2 `XI_RawMotion` for disable cursor mode motion input (#125) -- [X11] Replaced `_GLFW_HAS_XF86VM` compile-time option with dynamic loading -- [X11] Bugfix: `glfwGetVideoMode` would segfault on Cygwin/X -- [X11] Bugfix: Dynamic X11 library loading did not use full sonames (#941) -- [X11] Bugfix: Window creation on 64-bit would read past top of stack (#951) -- [X11] Bugfix: XDND support had multiple non-conformance issues (#968) -- [X11] Bugfix: The RandR monitor path was disabled despite working RandR (#972) -- [X11] Bugfix: IM-duplicated key events would leak at low polling rates (#747) -- [X11] Bugfix: Gamma ramp setting via RandR did not validate ramp size -- [X11] Bugfix: Key name string encoding depended on current locale (#981,#983) -- [X11] Bugfix: Incremental reading of selections was not supported (#275) -- [X11] Bugfix: Selection I/O reported but did not support `COMPOUND_TEXT` -- [X11] Bugfix: Latin-1 text read from selections was not converted to UTF-8 -- [X11] Bugfix: NVidia EGL would segfault if unloaded before closing the display -- [X11] Bugfix: Checking window maximized attrib could crash some WMs (#1356) -- [X11] Bugfix: Update cursor position on enter event (#1366) -- [Linux] Added workaround for missing `SYN_DROPPED` in pre-2.6.39 kernel - headers (#1196) -- [Linux] Moved to evdev for joystick input (#906,#1005) -- [Linux] Bugfix: Event processing did not detect joystick disconnection (#932) -- [Linux] Bugfix: The joystick device path could be truncated (#1025) -- [Linux] Bugfix: `glfwInit` would fail if inotify creation failed (#833) -- [Linux] Bugfix: `strdup` was used without any required feature macro (#1055) -- [Cocoa] Added support for Vulkan window surface creation via - [MoltenVK](https://moltengl.com/moltenvk/) (#870) -- [Cocoa] Added support for loading a `MainMenu.nib` when available -- [Cocoa] Bugfix: Disabling window aspect ratio would assert (#852) -- [Cocoa] Bugfix: Window creation failed to set first responder (#876,#883) -- [Cocoa] Bugfix: Removed use of deprecated `CGDisplayIOServicePort` function - (#165,#192,#508,#511) -- [Cocoa] Bugfix: Disabled use of deprecated `CGDisplayModeCopyPixelEncoding` - function on macOS 10.12+ -- [Cocoa] Bugfix: Running in AppSandbox would emit warnings (#816,#882) -- [Cocoa] Bugfix: Windows created after the first were not cascaded (#195) -- [Cocoa] Bugfix: Leaving video mode with `glfwSetWindowMonitor` would set - incorrect position and size (#748) -- [Cocoa] Bugfix: Iconified full screen windows could not be restored (#848) -- [Cocoa] Bugfix: Value range was ignored for joystick hats and buttons (#888) -- [Cocoa] Bugfix: Full screen framebuffer was incorrectly sized for some video - modes (#682) -- [Cocoa] Bugfix: A string object for IME was updated non-idiomatically (#1050) -- [Cocoa] Bugfix: A hidden or disabled cursor would become visible when a user - notification was shown (#971,#1028) -- [Cocoa] Bugfix: Some characters did not repeat due to Press and Hold (#1010) -- [Cocoa] Bugfix: Window title was lost when full screen or undecorated (#1082) -- [Cocoa] Bugfix: Window was resized twice when entering full screen (#1085) -- [Cocoa] Bugfix: Duplicate size events were not filtered (#1085) -- [Cocoa] Bugfix: Event polling did not initialize AppKit if necessary (#1218) -- [Cocoa] Bugfix: OpenGL rendering was not initially visible on 10.14 - (#1334,#1346) -- [Cocoa] Bugfix: Caps Lock did not generate any key events (#1368,#1373) -- [WGL] Added support for `WGL_EXT_colorspace` for OpenGL ES contexts -- [WGL] Added support for `WGL_ARB_create_context_no_error` -- [GLX] Added support for `GLX_ARB_create_context_no_error` -- [GLX] Bugfix: Context creation could segfault if no GLXFBConfigs were - available (#1040) -- [EGL] Added support for `EGL_KHR_get_all_proc_addresses` (#871) -- [EGL] Added support for `EGL_KHR_context_flush_control` -- [EGL] Bugfix: The test for `EGL_RGB_BUFFER` was invalid +User-visible changes since the last release. ## Contact @@ -337,6 +164,7 @@ skills. - Ian Clarkson - Michaล‚ Cichoล„ - Lambert Clara + - Anna Clarke - Yaron Cohen-Tal - Omar Cornut - Andrew Corrigan @@ -395,6 +223,7 @@ skills. - Hans Mackowiak - ะ”ะผะธั‚ั€ะธ ะœะฐะปั‹ัˆะตะฒ - Zbigniew Mandziejewicz + - Adam Marcus - Cรฉlestin Marot - Kyle McDonald - David Medlock @@ -429,10 +258,12 @@ skills. - Cyril Pichard - Keith Pitt - Stanislav Podgorskiy + - Nathan Poirier - Alexandre Pretyman - przemekmirek - Philip Rideout - Eddie Ringle + - Max Risuhin - Jorge Rodriguez - Ed Ropple - Aleksey Rybalkin @@ -447,6 +278,7 @@ skills. - Dmitri Shuralyov - Daniel Skorupski - Bradley Smith + - Cliff Smolinsky - Patrick Snape - Erlend Sogge Heggen - Julian Squires diff --git a/src/external/glfw/deps/KHR/khrplatform.h b/src/external/glfw/deps/KHR/khrplatform.h deleted file mode 100644 index c9e6f17d..00000000 --- a/src/external/glfw/deps/KHR/khrplatform.h +++ /dev/null @@ -1,282 +0,0 @@ -#ifndef __khrplatform_h_ -#define __khrplatform_h_ - -/* -** Copyright (c) 2008-2009 The Khronos Group Inc. -** -** Permission is hereby granted, free of charge, to any person obtaining a -** copy of this software and/or associated documentation files (the -** "Materials"), to deal in the Materials without restriction, including -** without limitation the rights to use, copy, modify, merge, publish, -** distribute, sublicense, and/or sell copies of the Materials, and to -** permit persons to whom the Materials are furnished to do so, subject to -** the following conditions: -** -** The above copyright notice and this permission notice shall be included -** in all copies or substantial portions of the Materials. -** -** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. -*/ - -/* Khronos platform-specific types and definitions. - * - * $Revision: 23298 $ on $Date: 2013-09-30 17:07:13 -0700 (Mon, 30 Sep 2013) $ - * - * Adopters may modify this file to suit their platform. Adopters are - * encouraged to submit platform specific modifications to the Khronos - * group so that they can be included in future versions of this file. - * Please submit changes by sending them to the public Khronos Bugzilla - * (http://khronos.org/bugzilla) by filing a bug against product - * "Khronos (general)" component "Registry". - * - * A predefined template which fills in some of the bug fields can be - * reached using http://tinyurl.com/khrplatform-h-bugreport, but you - * must create a Bugzilla login first. - * - * - * See the Implementer's Guidelines for information about where this file - * should be located on your system and for more details of its use: - * http://www.khronos.org/registry/implementers_guide.pdf - * - * This file should be included as - * #include - * by Khronos client API header files that use its types and defines. - * - * The types in khrplatform.h should only be used to define API-specific types. - * - * Types defined in khrplatform.h: - * khronos_int8_t signed 8 bit - * khronos_uint8_t unsigned 8 bit - * khronos_int16_t signed 16 bit - * khronos_uint16_t unsigned 16 bit - * khronos_int32_t signed 32 bit - * khronos_uint32_t unsigned 32 bit - * khronos_int64_t signed 64 bit - * khronos_uint64_t unsigned 64 bit - * khronos_intptr_t signed same number of bits as a pointer - * khronos_uintptr_t unsigned same number of bits as a pointer - * khronos_ssize_t signed size - * khronos_usize_t unsigned size - * khronos_float_t signed 32 bit floating point - * khronos_time_ns_t unsigned 64 bit time in nanoseconds - * khronos_utime_nanoseconds_t unsigned time interval or absolute time in - * nanoseconds - * khronos_stime_nanoseconds_t signed time interval in nanoseconds - * khronos_boolean_enum_t enumerated boolean type. This should - * only be used as a base type when a client API's boolean type is - * an enum. Client APIs which use an integer or other type for - * booleans cannot use this as the base type for their boolean. - * - * Tokens defined in khrplatform.h: - * - * KHRONOS_FALSE, KHRONOS_TRUE Enumerated boolean false/true values. - * - * KHRONOS_SUPPORT_INT64 is 1 if 64 bit integers are supported; otherwise 0. - * KHRONOS_SUPPORT_FLOAT is 1 if floats are supported; otherwise 0. - * - * Calling convention macros defined in this file: - * KHRONOS_APICALL - * KHRONOS_APIENTRY - * KHRONOS_APIATTRIBUTES - * - * These may be used in function prototypes as: - * - * KHRONOS_APICALL void KHRONOS_APIENTRY funcname( - * int arg1, - * int arg2) KHRONOS_APIATTRIBUTES; - */ - -/*------------------------------------------------------------------------- - * Definition of KHRONOS_APICALL - *------------------------------------------------------------------------- - * This precedes the return type of the function in the function prototype. - */ -#if defined(_WIN32) && !defined(__SCITECH_SNAP__) -# define KHRONOS_APICALL __declspec(dllimport) -#elif defined (__SYMBIAN32__) -# define KHRONOS_APICALL IMPORT_C -#else -# define KHRONOS_APICALL -#endif - -/*------------------------------------------------------------------------- - * Definition of KHRONOS_APIENTRY - *------------------------------------------------------------------------- - * This follows the return type of the function and precedes the function - * name in the function prototype. - */ -#if defined(_WIN32) && !defined(_WIN32_WCE) && !defined(__SCITECH_SNAP__) - /* Win32 but not WinCE */ -# define KHRONOS_APIENTRY __stdcall -#else -# define KHRONOS_APIENTRY -#endif - -/*------------------------------------------------------------------------- - * Definition of KHRONOS_APIATTRIBUTES - *------------------------------------------------------------------------- - * This follows the closing parenthesis of the function prototype arguments. - */ -#if defined (__ARMCC_2__) -#define KHRONOS_APIATTRIBUTES __softfp -#else -#define KHRONOS_APIATTRIBUTES -#endif - -/*------------------------------------------------------------------------- - * basic type definitions - *-----------------------------------------------------------------------*/ -#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(__GNUC__) || defined(__SCO__) || defined(__USLC__) - - -/* - * Using - */ -#include -typedef int32_t khronos_int32_t; -typedef uint32_t khronos_uint32_t; -typedef int64_t khronos_int64_t; -typedef uint64_t khronos_uint64_t; -#define KHRONOS_SUPPORT_INT64 1 -#define KHRONOS_SUPPORT_FLOAT 1 - -#elif defined(__VMS ) || defined(__sgi) - -/* - * Using - */ -#include -typedef int32_t khronos_int32_t; -typedef uint32_t khronos_uint32_t; -typedef int64_t khronos_int64_t; -typedef uint64_t khronos_uint64_t; -#define KHRONOS_SUPPORT_INT64 1 -#define KHRONOS_SUPPORT_FLOAT 1 - -#elif defined(_WIN32) && !defined(__SCITECH_SNAP__) - -/* - * Win32 - */ -typedef __int32 khronos_int32_t; -typedef unsigned __int32 khronos_uint32_t; -typedef __int64 khronos_int64_t; -typedef unsigned __int64 khronos_uint64_t; -#define KHRONOS_SUPPORT_INT64 1 -#define KHRONOS_SUPPORT_FLOAT 1 - -#elif defined(__sun__) || defined(__digital__) - -/* - * Sun or Digital - */ -typedef int khronos_int32_t; -typedef unsigned int khronos_uint32_t; -#if defined(__arch64__) || defined(_LP64) -typedef long int khronos_int64_t; -typedef unsigned long int khronos_uint64_t; -#else -typedef long long int khronos_int64_t; -typedef unsigned long long int khronos_uint64_t; -#endif /* __arch64__ */ -#define KHRONOS_SUPPORT_INT64 1 -#define KHRONOS_SUPPORT_FLOAT 1 - -#elif 0 - -/* - * Hypothetical platform with no float or int64 support - */ -typedef int khronos_int32_t; -typedef unsigned int khronos_uint32_t; -#define KHRONOS_SUPPORT_INT64 0 -#define KHRONOS_SUPPORT_FLOAT 0 - -#else - -/* - * Generic fallback - */ -#include -typedef int32_t khronos_int32_t; -typedef uint32_t khronos_uint32_t; -typedef int64_t khronos_int64_t; -typedef uint64_t khronos_uint64_t; -#define KHRONOS_SUPPORT_INT64 1 -#define KHRONOS_SUPPORT_FLOAT 1 - -#endif - - -/* - * Types that are (so far) the same on all platforms - */ -typedef signed char khronos_int8_t; -typedef unsigned char khronos_uint8_t; -typedef signed short int khronos_int16_t; -typedef unsigned short int khronos_uint16_t; - -/* - * Types that differ between LLP64 and LP64 architectures - in LLP64, - * pointers are 64 bits, but 'long' is still 32 bits. Win64 appears - * to be the only LLP64 architecture in current use. - */ -#ifdef _WIN64 -typedef signed long long int khronos_intptr_t; -typedef unsigned long long int khronos_uintptr_t; -typedef signed long long int khronos_ssize_t; -typedef unsigned long long int khronos_usize_t; -#else -typedef signed long int khronos_intptr_t; -typedef unsigned long int khronos_uintptr_t; -typedef signed long int khronos_ssize_t; -typedef unsigned long int khronos_usize_t; -#endif - -#if KHRONOS_SUPPORT_FLOAT -/* - * Float type - */ -typedef float khronos_float_t; -#endif - -#if KHRONOS_SUPPORT_INT64 -/* Time types - * - * These types can be used to represent a time interval in nanoseconds or - * an absolute Unadjusted System Time. Unadjusted System Time is the number - * of nanoseconds since some arbitrary system event (e.g. since the last - * time the system booted). The Unadjusted System Time is an unsigned - * 64 bit value that wraps back to 0 every 584 years. Time intervals - * may be either signed or unsigned. - */ -typedef khronos_uint64_t khronos_utime_nanoseconds_t; -typedef khronos_int64_t khronos_stime_nanoseconds_t; -#endif - -/* - * Dummy value used to pad enum types to 32 bits. - */ -#ifndef KHRONOS_MAX_ENUM -#define KHRONOS_MAX_ENUM 0x7FFFFFFF -#endif - -/* - * Enumerated boolean type - * - * Values other than zero should be considered to be true. Therefore - * comparisons should not be made against KHRONOS_TRUE. - */ -typedef enum { - KHRONOS_FALSE = 0, - KHRONOS_TRUE = 1, - KHRONOS_BOOLEAN_ENUM_FORCE_SIZE = KHRONOS_MAX_ENUM -} khronos_boolean_enum_t; - -#endif /* __khrplatform_h_ */ diff --git a/src/external/glfw/deps/glad.c b/src/external/glfw/deps/glad.c deleted file mode 100644 index 10b0a00e..00000000 --- a/src/external/glfw/deps/glad.c +++ /dev/null @@ -1,1678 +0,0 @@ -/* - - OpenGL loader generated by glad 0.1.12a0 on Fri Sep 23 13:36:15 2016. - - Language/Generator: C/C++ - Specification: gl - APIs: gl=3.2 - Profile: compatibility - Extensions: - GL_ARB_multisample, - GL_ARB_robustness, - GL_KHR_debug - Loader: False - Local files: False - Omit khrplatform: False - - Commandline: - --profile="compatibility" --api="gl=3.2" --generator="c" --spec="gl" --no-loader --extensions="GL_ARB_multisample,GL_ARB_robustness,GL_KHR_debug" - Online: - http://glad.dav1d.de/#profile=compatibility&language=c&specification=gl&api=gl%3D3.2&extensions=GL_ARB_multisample&extensions=GL_ARB_robustness&extensions=GL_KHR_debug -*/ - -#include -#include -#include -#include - -struct gladGLversionStruct GLVersion; - -#if defined(GL_ES_VERSION_3_0) || defined(GL_VERSION_3_0) -#define _GLAD_IS_SOME_NEW_VERSION 1 -#endif - -static int max_loaded_major; -static int max_loaded_minor; - -static const char *exts = NULL; -static int num_exts_i = 0; -static const char **exts_i = NULL; - -static int get_exts(void) { -#ifdef _GLAD_IS_SOME_NEW_VERSION - if(max_loaded_major < 3) { -#endif - exts = (const char *)glGetString(GL_EXTENSIONS); -#ifdef _GLAD_IS_SOME_NEW_VERSION - } else { - int index; - - num_exts_i = 0; - glGetIntegerv(GL_NUM_EXTENSIONS, &num_exts_i); - if (num_exts_i > 0) { - exts_i = (const char **)realloc((void *)exts_i, num_exts_i * sizeof *exts_i); - } - - if (exts_i == NULL) { - return 0; - } - - for(index = 0; index < num_exts_i; index++) { - exts_i[index] = (const char*)glGetStringi(GL_EXTENSIONS, index); - } - } -#endif - return 1; -} - -static void free_exts(void) { - if (exts_i != NULL) { - free((char **)exts_i); - exts_i = NULL; - } -} - -static int has_ext(const char *ext) { -#ifdef _GLAD_IS_SOME_NEW_VERSION - if(max_loaded_major < 3) { -#endif - const char *extensions; - const char *loc; - const char *terminator; - extensions = exts; - if(extensions == NULL || ext == NULL) { - return 0; - } - - while(1) { - loc = strstr(extensions, ext); - if(loc == NULL) { - return 0; - } - - terminator = loc + strlen(ext); - if((loc == extensions || *(loc - 1) == ' ') && - (*terminator == ' ' || *terminator == '\0')) { - return 1; - } - extensions = terminator; - } -#ifdef _GLAD_IS_SOME_NEW_VERSION - } else { - int index; - - for(index = 0; index < num_exts_i; index++) { - const char *e = exts_i[index]; - - if(strcmp(e, ext) == 0) { - return 1; - } - } - } -#endif - - return 0; -} -int GLAD_GL_VERSION_1_0; -int GLAD_GL_VERSION_1_1; -int GLAD_GL_VERSION_1_2; -int GLAD_GL_VERSION_1_3; -int GLAD_GL_VERSION_1_4; -int GLAD_GL_VERSION_1_5; -int GLAD_GL_VERSION_2_0; -int GLAD_GL_VERSION_2_1; -int GLAD_GL_VERSION_3_0; -int GLAD_GL_VERSION_3_1; -int GLAD_GL_VERSION_3_2; -PFNGLCOPYTEXIMAGE1DPROC glad_glCopyTexImage1D; -PFNGLVERTEXATTRIBI3UIPROC glad_glVertexAttribI3ui; -PFNGLWINDOWPOS2SPROC glad_glWindowPos2s; -PFNGLWINDOWPOS2IPROC glad_glWindowPos2i; -PFNGLWINDOWPOS2FPROC glad_glWindowPos2f; -PFNGLWINDOWPOS2DPROC glad_glWindowPos2d; -PFNGLVERTEX2FVPROC glad_glVertex2fv; -PFNGLINDEXIPROC glad_glIndexi; -PFNGLFRAMEBUFFERRENDERBUFFERPROC glad_glFramebufferRenderbuffer; -PFNGLRECTDVPROC glad_glRectdv; -PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC glad_glCompressedTexSubImage3D; -PFNGLEVALCOORD2DPROC glad_glEvalCoord2d; -PFNGLEVALCOORD2FPROC glad_glEvalCoord2f; -PFNGLINDEXDPROC glad_glIndexd; -PFNGLVERTEXATTRIB1SVPROC glad_glVertexAttrib1sv; -PFNGLINDEXFPROC glad_glIndexf; -PFNGLLINEWIDTHPROC glad_glLineWidth; -PFNGLGETINTEGERI_VPROC glad_glGetIntegeri_v; -PFNGLGETMAPFVPROC glad_glGetMapfv; -PFNGLINDEXSPROC glad_glIndexs; -PFNGLCOMPILESHADERPROC glad_glCompileShader; -PFNGLGETTRANSFORMFEEDBACKVARYINGPROC glad_glGetTransformFeedbackVarying; -PFNGLWINDOWPOS2IVPROC glad_glWindowPos2iv; -PFNGLINDEXFVPROC glad_glIndexfv; -PFNGLFOGIVPROC glad_glFogiv; -PFNGLSTENCILMASKSEPARATEPROC glad_glStencilMaskSeparate; -PFNGLRASTERPOS2FVPROC glad_glRasterPos2fv; -PFNGLLIGHTMODELIVPROC glad_glLightModeliv; -PFNGLCOLOR4UIPROC glad_glColor4ui; -PFNGLSECONDARYCOLOR3FVPROC glad_glSecondaryColor3fv; -PFNGLFOGFVPROC glad_glFogfv; -PFNGLENABLEIPROC glad_glEnablei; -PFNGLVERTEX4IVPROC glad_glVertex4iv; -PFNGLEVALCOORD1FVPROC glad_glEvalCoord1fv; -PFNGLWINDOWPOS2SVPROC glad_glWindowPos2sv; -PFNGLCREATESHADERPROC glad_glCreateShader; -PFNGLISBUFFERPROC glad_glIsBuffer; -PFNGLGETMULTISAMPLEFVPROC glad_glGetMultisamplefv; -PFNGLGENRENDERBUFFERSPROC glad_glGenRenderbuffers; -PFNGLCOPYTEXSUBIMAGE2DPROC glad_glCopyTexSubImage2D; -PFNGLCOMPRESSEDTEXIMAGE2DPROC glad_glCompressedTexImage2D; -PFNGLVERTEXATTRIB1FPROC glad_glVertexAttrib1f; -PFNGLBLENDFUNCSEPARATEPROC glad_glBlendFuncSeparate; -PFNGLVERTEX4FVPROC glad_glVertex4fv; -PFNGLBINDTEXTUREPROC glad_glBindTexture; -PFNGLVERTEXATTRIB1SPROC glad_glVertexAttrib1s; -PFNGLTEXCOORD2FVPROC glad_glTexCoord2fv; -PFNGLSAMPLEMASKIPROC glad_glSampleMaski; -PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC glad_glDrawRangeElementsBaseVertex; -PFNGLTEXCOORD4FVPROC glad_glTexCoord4fv; -PFNGLUNIFORMMATRIX3X2FVPROC glad_glUniformMatrix3x2fv; -PFNGLPOINTSIZEPROC glad_glPointSize; -PFNGLVERTEXATTRIB2DVPROC glad_glVertexAttrib2dv; -PFNGLDELETEPROGRAMPROC glad_glDeleteProgram; -PFNGLCOLOR4BVPROC glad_glColor4bv; -PFNGLRASTERPOS2FPROC glad_glRasterPos2f; -PFNGLRASTERPOS2DPROC glad_glRasterPos2d; -PFNGLLOADIDENTITYPROC glad_glLoadIdentity; -PFNGLRASTERPOS2IPROC glad_glRasterPos2i; -PFNGLRENDERBUFFERSTORAGEPROC glad_glRenderbufferStorage; -PFNGLUNIFORMMATRIX4X3FVPROC glad_glUniformMatrix4x3fv; -PFNGLCOLOR3BPROC glad_glColor3b; -PFNGLCLEARBUFFERFVPROC glad_glClearBufferfv; -PFNGLEDGEFLAGPROC glad_glEdgeFlag; -PFNGLVERTEX3DPROC glad_glVertex3d; -PFNGLVERTEX3FPROC glad_glVertex3f; -PFNGLVERTEX3IPROC glad_glVertex3i; -PFNGLCOLOR3IPROC glad_glColor3i; -PFNGLUNIFORM3FPROC glad_glUniform3f; -PFNGLVERTEXATTRIB4UBVPROC glad_glVertexAttrib4ubv; -PFNGLCOLOR3SPROC glad_glColor3s; -PFNGLVERTEX3SPROC glad_glVertex3s; -PFNGLCOLORMASKIPROC glad_glColorMaski; -PFNGLCLEARBUFFERFIPROC glad_glClearBufferfi; -PFNGLTEXCOORD1IVPROC glad_glTexCoord1iv; -PFNGLBLITFRAMEBUFFERPROC glad_glBlitFramebuffer; -PFNGLVERTEXATTRIB3FPROC glad_glVertexAttrib3f; -PFNGLVERTEX2IVPROC glad_glVertex2iv; -PFNGLCOLOR3SVPROC glad_glColor3sv; -PFNGLGETVERTEXATTRIBDVPROC glad_glGetVertexAttribdv; -PFNGLUNIFORMMATRIX3X4FVPROC glad_glUniformMatrix3x4fv; -PFNGLNORMALPOINTERPROC glad_glNormalPointer; -PFNGLVERTEX4SVPROC glad_glVertex4sv; -PFNGLPASSTHROUGHPROC glad_glPassThrough; -PFNGLFOGIPROC glad_glFogi; -PFNGLBEGINPROC glad_glBegin; -PFNGLEVALCOORD2DVPROC glad_glEvalCoord2dv; -PFNGLCOLOR3UBVPROC glad_glColor3ubv; -PFNGLVERTEXPOINTERPROC glad_glVertexPointer; -PFNGLSECONDARYCOLOR3UIVPROC glad_glSecondaryColor3uiv; -PFNGLDELETEFRAMEBUFFERSPROC glad_glDeleteFramebuffers; -PFNGLDRAWARRAYSPROC glad_glDrawArrays; -PFNGLUNIFORM1UIPROC glad_glUniform1ui; -PFNGLMULTITEXCOORD1DPROC glad_glMultiTexCoord1d; -PFNGLMULTITEXCOORD1FPROC glad_glMultiTexCoord1f; -PFNGLLIGHTFVPROC glad_glLightfv; -PFNGLVERTEXATTRIB3DPROC glad_glVertexAttrib3d; -PFNGLCLEARPROC glad_glClear; -PFNGLMULTITEXCOORD1IPROC glad_glMultiTexCoord1i; -PFNGLGETACTIVEUNIFORMNAMEPROC glad_glGetActiveUniformName; -PFNGLMULTITEXCOORD1SPROC glad_glMultiTexCoord1s; -PFNGLISENABLEDPROC glad_glIsEnabled; -PFNGLSTENCILOPPROC glad_glStencilOp; -PFNGLGETQUERYOBJECTUIVPROC glad_glGetQueryObjectuiv; -PFNGLFRAMEBUFFERTEXTURE2DPROC glad_glFramebufferTexture2D; -PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC glad_glGetFramebufferAttachmentParameteriv; -PFNGLTRANSLATEFPROC glad_glTranslatef; -PFNGLVERTEXATTRIB4NUBPROC glad_glVertexAttrib4Nub; -PFNGLTRANSLATEDPROC glad_glTranslated; -PFNGLTEXCOORD3SVPROC glad_glTexCoord3sv; -PFNGLGETFRAGDATALOCATIONPROC glad_glGetFragDataLocation; -PFNGLTEXIMAGE1DPROC glad_glTexImage1D; -PFNGLTEXPARAMETERIVPROC glad_glTexParameteriv; -PFNGLSECONDARYCOLOR3BVPROC glad_glSecondaryColor3bv; -PFNGLGETMATERIALFVPROC glad_glGetMaterialfv; -PFNGLGETTEXIMAGEPROC glad_glGetTexImage; -PFNGLFOGCOORDFVPROC glad_glFogCoordfv; -PFNGLPIXELMAPUIVPROC glad_glPixelMapuiv; -PFNGLGETSHADERINFOLOGPROC glad_glGetShaderInfoLog; -PFNGLGENFRAMEBUFFERSPROC glad_glGenFramebuffers; -PFNGLINDEXSVPROC glad_glIndexsv; -PFNGLGETATTACHEDSHADERSPROC glad_glGetAttachedShaders; -PFNGLISRENDERBUFFERPROC glad_glIsRenderbuffer; -PFNGLVERTEX3IVPROC glad_glVertex3iv; -PFNGLBITMAPPROC glad_glBitmap; -PFNGLMATERIALIPROC glad_glMateriali; -PFNGLISVERTEXARRAYPROC glad_glIsVertexArray; -PFNGLDISABLEVERTEXATTRIBARRAYPROC glad_glDisableVertexAttribArray; -PFNGLGETQUERYIVPROC glad_glGetQueryiv; -PFNGLTEXCOORD4FPROC glad_glTexCoord4f; -PFNGLTEXCOORD4DPROC glad_glTexCoord4d; -PFNGLTEXCOORD4IPROC glad_glTexCoord4i; -PFNGLMATERIALFPROC glad_glMaterialf; -PFNGLTEXCOORD4SPROC glad_glTexCoord4s; -PFNGLGETUNIFORMINDICESPROC glad_glGetUniformIndices; -PFNGLISSHADERPROC glad_glIsShader; -PFNGLMULTITEXCOORD2SPROC glad_glMultiTexCoord2s; -PFNGLVERTEXATTRIBI4UBVPROC glad_glVertexAttribI4ubv; -PFNGLVERTEX3DVPROC glad_glVertex3dv; -PFNGLGETINTEGER64VPROC glad_glGetInteger64v; -PFNGLPOINTPARAMETERIVPROC glad_glPointParameteriv; -PFNGLENABLEPROC glad_glEnable; -PFNGLGETACTIVEUNIFORMSIVPROC glad_glGetActiveUniformsiv; -PFNGLCOLOR4FVPROC glad_glColor4fv; -PFNGLTEXCOORD1FVPROC glad_glTexCoord1fv; -PFNGLTEXCOORD2SVPROC glad_glTexCoord2sv; -PFNGLVERTEXATTRIB4DVPROC glad_glVertexAttrib4dv; -PFNGLMULTITEXCOORD1DVPROC glad_glMultiTexCoord1dv; -PFNGLMULTITEXCOORD2IPROC glad_glMultiTexCoord2i; -PFNGLTEXCOORD3FVPROC glad_glTexCoord3fv; -PFNGLSECONDARYCOLOR3USVPROC glad_glSecondaryColor3usv; -PFNGLTEXGENFPROC glad_glTexGenf; -PFNGLGETPOINTERVPROC glad_glGetPointerv; -PFNGLPOLYGONOFFSETPROC glad_glPolygonOffset; -PFNGLGETUNIFORMUIVPROC glad_glGetUniformuiv; -PFNGLNORMAL3FVPROC glad_glNormal3fv; -PFNGLSECONDARYCOLOR3SPROC glad_glSecondaryColor3s; -PFNGLDEPTHRANGEPROC glad_glDepthRange; -PFNGLFRUSTUMPROC glad_glFrustum; -PFNGLMULTITEXCOORD4SVPROC glad_glMultiTexCoord4sv; -PFNGLDRAWBUFFERPROC glad_glDrawBuffer; -PFNGLPUSHMATRIXPROC glad_glPushMatrix; -PFNGLRASTERPOS3FVPROC glad_glRasterPos3fv; -PFNGLORTHOPROC glad_glOrtho; -PFNGLDRAWELEMENTSINSTANCEDPROC glad_glDrawElementsInstanced; -PFNGLWINDOWPOS3SVPROC glad_glWindowPos3sv; -PFNGLCLEARINDEXPROC glad_glClearIndex; -PFNGLMAP1DPROC glad_glMap1d; -PFNGLMAP1FPROC glad_glMap1f; -PFNGLFLUSHPROC glad_glFlush; -PFNGLGETRENDERBUFFERPARAMETERIVPROC glad_glGetRenderbufferParameteriv; -PFNGLINDEXIVPROC glad_glIndexiv; -PFNGLRASTERPOS3SVPROC glad_glRasterPos3sv; -PFNGLGETVERTEXATTRIBPOINTERVPROC glad_glGetVertexAttribPointerv; -PFNGLPIXELZOOMPROC glad_glPixelZoom; -PFNGLFENCESYNCPROC glad_glFenceSync; -PFNGLDELETEVERTEXARRAYSPROC glad_glDeleteVertexArrays; -PFNGLVERTEXATTRIB3SVPROC glad_glVertexAttrib3sv; -PFNGLBEGINCONDITIONALRENDERPROC glad_glBeginConditionalRender; -PFNGLDRAWELEMENTSBASEVERTEXPROC glad_glDrawElementsBaseVertex; -PFNGLGETTEXLEVELPARAMETERIVPROC glad_glGetTexLevelParameteriv; -PFNGLLIGHTIPROC glad_glLighti; -PFNGLLIGHTFPROC glad_glLightf; -PFNGLGETATTRIBLOCATIONPROC glad_glGetAttribLocation; -PFNGLSTENCILFUNCSEPARATEPROC glad_glStencilFuncSeparate; -PFNGLCLAMPCOLORPROC glad_glClampColor; -PFNGLUNIFORM4IVPROC glad_glUniform4iv; -PFNGLCLEARSTENCILPROC glad_glClearStencil; -PFNGLMULTITEXCOORD3FVPROC glad_glMultiTexCoord3fv; -PFNGLGETPIXELMAPUIVPROC glad_glGetPixelMapuiv; -PFNGLGENTEXTURESPROC glad_glGenTextures; -PFNGLTEXCOORD4IVPROC glad_glTexCoord4iv; -PFNGLGETTEXPARAMETERIUIVPROC glad_glGetTexParameterIuiv; -PFNGLINDEXPOINTERPROC glad_glIndexPointer; -PFNGLVERTEXATTRIB4NBVPROC glad_glVertexAttrib4Nbv; -PFNGLISSYNCPROC glad_glIsSync; -PFNGLVERTEX2FPROC glad_glVertex2f; -PFNGLVERTEX2DPROC glad_glVertex2d; -PFNGLDELETERENDERBUFFERSPROC glad_glDeleteRenderbuffers; -PFNGLUNIFORM2IPROC glad_glUniform2i; -PFNGLMAPGRID2DPROC glad_glMapGrid2d; -PFNGLMAPGRID2FPROC glad_glMapGrid2f; -PFNGLVERTEX2IPROC glad_glVertex2i; -PFNGLVERTEXATTRIBPOINTERPROC glad_glVertexAttribPointer; -PFNGLFRAMEBUFFERTEXTURELAYERPROC glad_glFramebufferTextureLayer; -PFNGLVERTEX2SPROC glad_glVertex2s; -PFNGLNORMAL3BVPROC glad_glNormal3bv; -PFNGLVERTEXATTRIB4NUIVPROC glad_glVertexAttrib4Nuiv; -PFNGLFLUSHMAPPEDBUFFERRANGEPROC glad_glFlushMappedBufferRange; -PFNGLSECONDARYCOLOR3SVPROC glad_glSecondaryColor3sv; -PFNGLVERTEX3SVPROC glad_glVertex3sv; -PFNGLGENQUERIESPROC glad_glGenQueries; -PFNGLGETPIXELMAPFVPROC glad_glGetPixelMapfv; -PFNGLTEXENVFPROC glad_glTexEnvf; -PFNGLTEXSUBIMAGE3DPROC glad_glTexSubImage3D; -PFNGLGETINTEGER64I_VPROC glad_glGetInteger64i_v; -PFNGLFOGCOORDDPROC glad_glFogCoordd; -PFNGLFOGCOORDFPROC glad_glFogCoordf; -PFNGLCOPYTEXIMAGE2DPROC glad_glCopyTexImage2D; -PFNGLTEXENVIPROC glad_glTexEnvi; -PFNGLMULTITEXCOORD1IVPROC glad_glMultiTexCoord1iv; -PFNGLISENABLEDIPROC glad_glIsEnabledi; -PFNGLVERTEXATTRIBI2IPROC glad_glVertexAttribI2i; -PFNGLMULTITEXCOORD2DVPROC glad_glMultiTexCoord2dv; -PFNGLUNIFORM2IVPROC glad_glUniform2iv; -PFNGLVERTEXATTRIB1FVPROC glad_glVertexAttrib1fv; -PFNGLUNIFORM4UIVPROC glad_glUniform4uiv; -PFNGLMATRIXMODEPROC glad_glMatrixMode; -PFNGLFEEDBACKBUFFERPROC glad_glFeedbackBuffer; -PFNGLGETMAPIVPROC glad_glGetMapiv; -PFNGLFRAMEBUFFERTEXTURE1DPROC glad_glFramebufferTexture1D; -PFNGLGETSHADERIVPROC glad_glGetShaderiv; -PFNGLMULTITEXCOORD2DPROC glad_glMultiTexCoord2d; -PFNGLMULTITEXCOORD2FPROC glad_glMultiTexCoord2f; -PFNGLBINDFRAGDATALOCATIONPROC glad_glBindFragDataLocation; -PFNGLPRIORITIZETEXTURESPROC glad_glPrioritizeTextures; -PFNGLCALLLISTPROC glad_glCallList; -PFNGLSECONDARYCOLOR3UBVPROC glad_glSecondaryColor3ubv; -PFNGLGETDOUBLEVPROC glad_glGetDoublev; -PFNGLMULTITEXCOORD3IVPROC glad_glMultiTexCoord3iv; -PFNGLVERTEXATTRIB1DPROC glad_glVertexAttrib1d; -PFNGLLIGHTMODELFPROC glad_glLightModelf; -PFNGLGETUNIFORMIVPROC glad_glGetUniformiv; -PFNGLVERTEX2SVPROC glad_glVertex2sv; -PFNGLLIGHTMODELIPROC glad_glLightModeli; -PFNGLWINDOWPOS3IVPROC glad_glWindowPos3iv; -PFNGLUNIFORM3FVPROC glad_glUniform3fv; -PFNGLPIXELSTOREIPROC glad_glPixelStorei; -PFNGLCALLLISTSPROC glad_glCallLists; -PFNGLMAPBUFFERPROC glad_glMapBuffer; -PFNGLSECONDARYCOLOR3DPROC glad_glSecondaryColor3d; -PFNGLTEXCOORD3IPROC glad_glTexCoord3i; -PFNGLMULTITEXCOORD4FVPROC glad_glMultiTexCoord4fv; -PFNGLRASTERPOS3IPROC glad_glRasterPos3i; -PFNGLSECONDARYCOLOR3BPROC glad_glSecondaryColor3b; -PFNGLRASTERPOS3DPROC glad_glRasterPos3d; -PFNGLRASTERPOS3FPROC glad_glRasterPos3f; -PFNGLCOMPRESSEDTEXIMAGE3DPROC glad_glCompressedTexImage3D; -PFNGLTEXCOORD3FPROC glad_glTexCoord3f; -PFNGLDELETESYNCPROC glad_glDeleteSync; -PFNGLCOPYTEXSUBIMAGE3DPROC glad_glCopyTexSubImage3D; -PFNGLTEXIMAGE2DMULTISAMPLEPROC glad_glTexImage2DMultisample; -PFNGLGETVERTEXATTRIBIVPROC glad_glGetVertexAttribiv; -PFNGLMULTIDRAWELEMENTSPROC glad_glMultiDrawElements; -PFNGLVERTEXATTRIB3FVPROC glad_glVertexAttrib3fv; -PFNGLTEXCOORD3SPROC glad_glTexCoord3s; -PFNGLUNIFORM3IVPROC glad_glUniform3iv; -PFNGLRASTERPOS3SPROC glad_glRasterPos3s; -PFNGLPOLYGONMODEPROC glad_glPolygonMode; -PFNGLDRAWBUFFERSPROC glad_glDrawBuffers; -PFNGLGETACTIVEUNIFORMBLOCKIVPROC glad_glGetActiveUniformBlockiv; -PFNGLARETEXTURESRESIDENTPROC glad_glAreTexturesResident; -PFNGLISLISTPROC glad_glIsList; -PFNGLRASTERPOS2SVPROC glad_glRasterPos2sv; -PFNGLRASTERPOS4SVPROC glad_glRasterPos4sv; -PFNGLCOLOR4SPROC glad_glColor4s; -PFNGLUSEPROGRAMPROC glad_glUseProgram; -PFNGLLINESTIPPLEPROC glad_glLineStipple; -PFNGLMULTITEXCOORD1SVPROC glad_glMultiTexCoord1sv; -PFNGLGETPROGRAMINFOLOGPROC glad_glGetProgramInfoLog; -PFNGLGETBUFFERPARAMETERIVPROC glad_glGetBufferParameteriv; -PFNGLMULTITEXCOORD2IVPROC glad_glMultiTexCoord2iv; -PFNGLUNIFORMMATRIX2X4FVPROC glad_glUniformMatrix2x4fv; -PFNGLBINDVERTEXARRAYPROC glad_glBindVertexArray; -PFNGLCOLOR4BPROC glad_glColor4b; -PFNGLSECONDARYCOLOR3FPROC glad_glSecondaryColor3f; -PFNGLCOLOR4FPROC glad_glColor4f; -PFNGLCOLOR4DPROC glad_glColor4d; -PFNGLCOLOR4IPROC glad_glColor4i; -PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC glad_glMultiDrawElementsBaseVertex; -PFNGLRASTERPOS3IVPROC glad_glRasterPos3iv; -PFNGLVERTEX2DVPROC glad_glVertex2dv; -PFNGLTEXCOORD4SVPROC glad_glTexCoord4sv; -PFNGLUNIFORM2UIVPROC glad_glUniform2uiv; -PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC glad_glCompressedTexSubImage1D; -PFNGLFINISHPROC glad_glFinish; -PFNGLGETBOOLEANVPROC glad_glGetBooleanv; -PFNGLDELETESHADERPROC glad_glDeleteShader; -PFNGLDRAWELEMENTSPROC glad_glDrawElements; -PFNGLRASTERPOS2SPROC glad_glRasterPos2s; -PFNGLGETMAPDVPROC glad_glGetMapdv; -PFNGLVERTEXATTRIB4NSVPROC glad_glVertexAttrib4Nsv; -PFNGLMATERIALFVPROC glad_glMaterialfv; -PFNGLVIEWPORTPROC glad_glViewport; -PFNGLUNIFORM1UIVPROC glad_glUniform1uiv; -PFNGLTRANSFORMFEEDBACKVARYINGSPROC glad_glTransformFeedbackVaryings; -PFNGLINDEXDVPROC glad_glIndexdv; -PFNGLTEXCOORD3DPROC glad_glTexCoord3d; -PFNGLTEXCOORD3IVPROC glad_glTexCoord3iv; -PFNGLVERTEXATTRIBI3IPROC glad_glVertexAttribI3i; -PFNGLCLEARDEPTHPROC glad_glClearDepth; -PFNGLVERTEXATTRIBI4USVPROC glad_glVertexAttribI4usv; -PFNGLTEXPARAMETERFPROC glad_glTexParameterf; -PFNGLTEXPARAMETERIPROC glad_glTexParameteri; -PFNGLGETSHADERSOURCEPROC glad_glGetShaderSource; -PFNGLTEXBUFFERPROC glad_glTexBuffer; -PFNGLPOPNAMEPROC glad_glPopName; -PFNGLVALIDATEPROGRAMPROC glad_glValidateProgram; -PFNGLPIXELSTOREFPROC glad_glPixelStoref; -PFNGLUNIFORM3UIVPROC glad_glUniform3uiv; -PFNGLRASTERPOS4FVPROC glad_glRasterPos4fv; -PFNGLEVALCOORD1DVPROC glad_glEvalCoord1dv; -PFNGLRECTIPROC glad_glRecti; -PFNGLCOLOR4UBPROC glad_glColor4ub; -PFNGLMULTTRANSPOSEMATRIXFPROC glad_glMultTransposeMatrixf; -PFNGLRECTFPROC glad_glRectf; -PFNGLRECTDPROC glad_glRectd; -PFNGLNORMAL3SVPROC glad_glNormal3sv; -PFNGLNEWLISTPROC glad_glNewList; -PFNGLCOLOR4USPROC glad_glColor4us; -PFNGLLINKPROGRAMPROC glad_glLinkProgram; -PFNGLHINTPROC glad_glHint; -PFNGLRECTSPROC glad_glRects; -PFNGLTEXCOORD2DVPROC glad_glTexCoord2dv; -PFNGLRASTERPOS4IVPROC glad_glRasterPos4iv; -PFNGLGETSTRINGPROC glad_glGetString; -PFNGLEDGEFLAGVPROC glad_glEdgeFlagv; -PFNGLDETACHSHADERPROC glad_glDetachShader; -PFNGLSCALEFPROC glad_glScalef; -PFNGLENDQUERYPROC glad_glEndQuery; -PFNGLSCALEDPROC glad_glScaled; -PFNGLEDGEFLAGPOINTERPROC glad_glEdgeFlagPointer; -PFNGLCOPYPIXELSPROC glad_glCopyPixels; -PFNGLVERTEXATTRIBI2UIPROC glad_glVertexAttribI2ui; -PFNGLPOPATTRIBPROC glad_glPopAttrib; -PFNGLDELETETEXTURESPROC glad_glDeleteTextures; -PFNGLSTENCILOPSEPARATEPROC glad_glStencilOpSeparate; -PFNGLDELETEQUERIESPROC glad_glDeleteQueries; -PFNGLVERTEXATTRIB4FPROC glad_glVertexAttrib4f; -PFNGLVERTEXATTRIB4DPROC glad_glVertexAttrib4d; -PFNGLINITNAMESPROC glad_glInitNames; -PFNGLGETBUFFERPARAMETERI64VPROC glad_glGetBufferParameteri64v; -PFNGLCOLOR3DVPROC glad_glColor3dv; -PFNGLVERTEXATTRIBI1IPROC glad_glVertexAttribI1i; -PFNGLGETTEXPARAMETERIVPROC glad_glGetTexParameteriv; -PFNGLWAITSYNCPROC glad_glWaitSync; -PFNGLVERTEXATTRIB4SPROC glad_glVertexAttrib4s; -PFNGLCOLORMATERIALPROC glad_glColorMaterial; -PFNGLSAMPLECOVERAGEPROC glad_glSampleCoverage; -PFNGLUNIFORM1FPROC glad_glUniform1f; -PFNGLGETVERTEXATTRIBFVPROC glad_glGetVertexAttribfv; -PFNGLRENDERMODEPROC glad_glRenderMode; -PFNGLGETCOMPRESSEDTEXIMAGEPROC glad_glGetCompressedTexImage; -PFNGLWINDOWPOS2DVPROC glad_glWindowPos2dv; -PFNGLUNIFORM1IPROC glad_glUniform1i; -PFNGLGETACTIVEATTRIBPROC glad_glGetActiveAttrib; -PFNGLUNIFORM3IPROC glad_glUniform3i; -PFNGLPIXELTRANSFERIPROC glad_glPixelTransferi; -PFNGLTEXSUBIMAGE2DPROC glad_glTexSubImage2D; -PFNGLDISABLEPROC glad_glDisable; -PFNGLLOGICOPPROC glad_glLogicOp; -PFNGLEVALPOINT2PROC glad_glEvalPoint2; -PFNGLPIXELTRANSFERFPROC glad_glPixelTransferf; -PFNGLSECONDARYCOLOR3IPROC glad_glSecondaryColor3i; -PFNGLUNIFORM4UIPROC glad_glUniform4ui; -PFNGLCOLOR3FPROC glad_glColor3f; -PFNGLBINDFRAMEBUFFERPROC glad_glBindFramebuffer; -PFNGLGETTEXENVFVPROC glad_glGetTexEnvfv; -PFNGLRECTFVPROC glad_glRectfv; -PFNGLCULLFACEPROC glad_glCullFace; -PFNGLGETLIGHTFVPROC glad_glGetLightfv; -PFNGLCOLOR3DPROC glad_glColor3d; -PFNGLTEXGENDPROC glad_glTexGend; -PFNGLTEXGENIPROC glad_glTexGeni; -PFNGLMULTITEXCOORD3SPROC glad_glMultiTexCoord3s; -PFNGLGETSTRINGIPROC glad_glGetStringi; -PFNGLMULTITEXCOORD3IPROC glad_glMultiTexCoord3i; -PFNGLMULTITEXCOORD3FPROC glad_glMultiTexCoord3f; -PFNGLMULTITEXCOORD3DPROC glad_glMultiTexCoord3d; -PFNGLATTACHSHADERPROC glad_glAttachShader; -PFNGLFOGCOORDDVPROC glad_glFogCoorddv; -PFNGLUNIFORMMATRIX2X3FVPROC glad_glUniformMatrix2x3fv; -PFNGLGETTEXGENFVPROC glad_glGetTexGenfv; -PFNGLFOGCOORDPOINTERPROC glad_glFogCoordPointer; -PFNGLPROVOKINGVERTEXPROC glad_glProvokingVertex; -PFNGLFRAMEBUFFERTEXTURE3DPROC glad_glFramebufferTexture3D; -PFNGLTEXGENIVPROC glad_glTexGeniv; -PFNGLRASTERPOS2DVPROC glad_glRasterPos2dv; -PFNGLSECONDARYCOLOR3DVPROC glad_glSecondaryColor3dv; -PFNGLCLIENTACTIVETEXTUREPROC glad_glClientActiveTexture; -PFNGLVERTEXATTRIBI4SVPROC glad_glVertexAttribI4sv; -PFNGLSECONDARYCOLOR3USPROC glad_glSecondaryColor3us; -PFNGLTEXENVFVPROC glad_glTexEnvfv; -PFNGLREADBUFFERPROC glad_glReadBuffer; -PFNGLTEXPARAMETERIUIVPROC glad_glTexParameterIuiv; -PFNGLDRAWARRAYSINSTANCEDPROC glad_glDrawArraysInstanced; -PFNGLGENERATEMIPMAPPROC glad_glGenerateMipmap; -PFNGLWINDOWPOS3FVPROC glad_glWindowPos3fv; -PFNGLLIGHTMODELFVPROC glad_glLightModelfv; -PFNGLDELETELISTSPROC glad_glDeleteLists; -PFNGLGETCLIPPLANEPROC glad_glGetClipPlane; -PFNGLVERTEX4DVPROC glad_glVertex4dv; -PFNGLTEXCOORD2DPROC glad_glTexCoord2d; -PFNGLPOPMATRIXPROC glad_glPopMatrix; -PFNGLTEXCOORD2FPROC glad_glTexCoord2f; -PFNGLCOLOR4IVPROC glad_glColor4iv; -PFNGLINDEXUBVPROC glad_glIndexubv; -PFNGLUNMAPBUFFERPROC glad_glUnmapBuffer; -PFNGLTEXCOORD2IPROC glad_glTexCoord2i; -PFNGLRASTERPOS4DPROC glad_glRasterPos4d; -PFNGLRASTERPOS4FPROC glad_glRasterPos4f; -PFNGLVERTEXATTRIB3SPROC glad_glVertexAttrib3s; -PFNGLTEXCOORD2SPROC glad_glTexCoord2s; -PFNGLBINDRENDERBUFFERPROC glad_glBindRenderbuffer; -PFNGLVERTEX3FVPROC glad_glVertex3fv; -PFNGLTEXCOORD4DVPROC glad_glTexCoord4dv; -PFNGLMATERIALIVPROC glad_glMaterialiv; -PFNGLISPROGRAMPROC glad_glIsProgram; -PFNGLVERTEXATTRIB4BVPROC glad_glVertexAttrib4bv; -PFNGLVERTEX4SPROC glad_glVertex4s; -PFNGLVERTEXATTRIB4FVPROC glad_glVertexAttrib4fv; -PFNGLNORMAL3DVPROC glad_glNormal3dv; -PFNGLUNIFORM4IPROC glad_glUniform4i; -PFNGLACTIVETEXTUREPROC glad_glActiveTexture; -PFNGLENABLEVERTEXATTRIBARRAYPROC glad_glEnableVertexAttribArray; -PFNGLROTATEDPROC glad_glRotated; -PFNGLROTATEFPROC glad_glRotatef; -PFNGLVERTEX4IPROC glad_glVertex4i; -PFNGLREADPIXELSPROC glad_glReadPixels; -PFNGLVERTEXATTRIBI3IVPROC glad_glVertexAttribI3iv; -PFNGLLOADNAMEPROC glad_glLoadName; -PFNGLUNIFORM4FPROC glad_glUniform4f; -PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC glad_glRenderbufferStorageMultisample; -PFNGLGENVERTEXARRAYSPROC glad_glGenVertexArrays; -PFNGLSHADEMODELPROC glad_glShadeModel; -PFNGLMAPGRID1DPROC glad_glMapGrid1d; -PFNGLGETUNIFORMFVPROC glad_glGetUniformfv; -PFNGLMAPGRID1FPROC glad_glMapGrid1f; -PFNGLDISABLECLIENTSTATEPROC glad_glDisableClientState; -PFNGLMULTITEXCOORD3SVPROC glad_glMultiTexCoord3sv; -PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC glad_glDrawElementsInstancedBaseVertex; -PFNGLSECONDARYCOLORPOINTERPROC glad_glSecondaryColorPointer; -PFNGLALPHAFUNCPROC glad_glAlphaFunc; -PFNGLUNIFORM1IVPROC glad_glUniform1iv; -PFNGLMULTITEXCOORD4IVPROC glad_glMultiTexCoord4iv; -PFNGLGETQUERYOBJECTIVPROC glad_glGetQueryObjectiv; -PFNGLSTENCILFUNCPROC glad_glStencilFunc; -PFNGLMULTITEXCOORD1FVPROC glad_glMultiTexCoord1fv; -PFNGLUNIFORMBLOCKBINDINGPROC glad_glUniformBlockBinding; -PFNGLCOLOR4UIVPROC glad_glColor4uiv; -PFNGLRECTIVPROC glad_glRectiv; -PFNGLRASTERPOS3DVPROC glad_glRasterPos3dv; -PFNGLEVALMESH2PROC glad_glEvalMesh2; -PFNGLEVALMESH1PROC glad_glEvalMesh1; -PFNGLTEXCOORDPOINTERPROC glad_glTexCoordPointer; -PFNGLVERTEXATTRIB4NUBVPROC glad_glVertexAttrib4Nubv; -PFNGLVERTEXATTRIBI4IVPROC glad_glVertexAttribI4iv; -PFNGLEVALCOORD2FVPROC glad_glEvalCoord2fv; -PFNGLCOLOR4UBVPROC glad_glColor4ubv; -PFNGLLOADTRANSPOSEMATRIXDPROC glad_glLoadTransposeMatrixd; -PFNGLLOADTRANSPOSEMATRIXFPROC glad_glLoadTransposeMatrixf; -PFNGLVERTEXATTRIBI4IPROC glad_glVertexAttribI4i; -PFNGLRASTERPOS2IVPROC glad_glRasterPos2iv; -PFNGLGETBUFFERSUBDATAPROC glad_glGetBufferSubData; -PFNGLTEXENVIVPROC glad_glTexEnviv; -PFNGLBLENDEQUATIONSEPARATEPROC glad_glBlendEquationSeparate; -PFNGLVERTEXATTRIBI1UIPROC glad_glVertexAttribI1ui; -PFNGLGENBUFFERSPROC glad_glGenBuffers; -PFNGLSELECTBUFFERPROC glad_glSelectBuffer; -PFNGLVERTEXATTRIB2SVPROC glad_glVertexAttrib2sv; -PFNGLPUSHATTRIBPROC glad_glPushAttrib; -PFNGLVERTEXATTRIBIPOINTERPROC glad_glVertexAttribIPointer; -PFNGLBLENDFUNCPROC glad_glBlendFunc; -PFNGLCREATEPROGRAMPROC glad_glCreateProgram; -PFNGLTEXIMAGE3DPROC glad_glTexImage3D; -PFNGLISFRAMEBUFFERPROC glad_glIsFramebuffer; -PFNGLLIGHTIVPROC glad_glLightiv; -PFNGLPRIMITIVERESTARTINDEXPROC glad_glPrimitiveRestartIndex; -PFNGLTEXGENFVPROC glad_glTexGenfv; -PFNGLENDPROC glad_glEnd; -PFNGLDELETEBUFFERSPROC glad_glDeleteBuffers; -PFNGLSCISSORPROC glad_glScissor; -PFNGLCLIPPLANEPROC glad_glClipPlane; -PFNGLPUSHNAMEPROC glad_glPushName; -PFNGLTEXGENDVPROC glad_glTexGendv; -PFNGLINDEXUBPROC glad_glIndexub; -PFNGLSECONDARYCOLOR3IVPROC glad_glSecondaryColor3iv; -PFNGLRASTERPOS4IPROC glad_glRasterPos4i; -PFNGLMULTTRANSPOSEMATRIXDPROC glad_glMultTransposeMatrixd; -PFNGLCLEARCOLORPROC glad_glClearColor; -PFNGLVERTEXATTRIB4UIVPROC glad_glVertexAttrib4uiv; -PFNGLNORMAL3SPROC glad_glNormal3s; -PFNGLVERTEXATTRIB4NIVPROC glad_glVertexAttrib4Niv; -PFNGLCLEARBUFFERIVPROC glad_glClearBufferiv; -PFNGLPOINTPARAMETERIPROC glad_glPointParameteri; -PFNGLBLENDCOLORPROC glad_glBlendColor; -PFNGLWINDOWPOS3DPROC glad_glWindowPos3d; -PFNGLVERTEXATTRIBI2UIVPROC glad_glVertexAttribI2uiv; -PFNGLUNIFORM3UIPROC glad_glUniform3ui; -PFNGLCOLOR4DVPROC glad_glColor4dv; -PFNGLVERTEXATTRIBI4UIVPROC glad_glVertexAttribI4uiv; -PFNGLPOINTPARAMETERFVPROC glad_glPointParameterfv; -PFNGLUNIFORM2FVPROC glad_glUniform2fv; -PFNGLSECONDARYCOLOR3UBPROC glad_glSecondaryColor3ub; -PFNGLSECONDARYCOLOR3UIPROC glad_glSecondaryColor3ui; -PFNGLTEXCOORD3DVPROC glad_glTexCoord3dv; -PFNGLBINDBUFFERRANGEPROC glad_glBindBufferRange; -PFNGLNORMAL3IVPROC glad_glNormal3iv; -PFNGLWINDOWPOS3SPROC glad_glWindowPos3s; -PFNGLPOINTPARAMETERFPROC glad_glPointParameterf; -PFNGLGETVERTEXATTRIBIUIVPROC glad_glGetVertexAttribIuiv; -PFNGLWINDOWPOS3IPROC glad_glWindowPos3i; -PFNGLMULTITEXCOORD4SPROC glad_glMultiTexCoord4s; -PFNGLWINDOWPOS3FPROC glad_glWindowPos3f; -PFNGLCOLOR3USPROC glad_glColor3us; -PFNGLCOLOR3UIVPROC glad_glColor3uiv; -PFNGLVERTEXATTRIB4NUSVPROC glad_glVertexAttrib4Nusv; -PFNGLGETLIGHTIVPROC glad_glGetLightiv; -PFNGLDEPTHFUNCPROC glad_glDepthFunc; -PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC glad_glCompressedTexSubImage2D; -PFNGLLISTBASEPROC glad_glListBase; -PFNGLMULTITEXCOORD4FPROC glad_glMultiTexCoord4f; -PFNGLCOLOR3UBPROC glad_glColor3ub; -PFNGLMULTITEXCOORD4DPROC glad_glMultiTexCoord4d; -PFNGLVERTEXATTRIBI4BVPROC glad_glVertexAttribI4bv; -PFNGLGETTEXPARAMETERFVPROC glad_glGetTexParameterfv; -PFNGLCOLOR3UIPROC glad_glColor3ui; -PFNGLMULTITEXCOORD4IPROC glad_glMultiTexCoord4i; -PFNGLGETPOLYGONSTIPPLEPROC glad_glGetPolygonStipple; -PFNGLCLIENTWAITSYNCPROC glad_glClientWaitSync; -PFNGLVERTEXATTRIBI4UIPROC glad_glVertexAttribI4ui; -PFNGLMULTITEXCOORD4DVPROC glad_glMultiTexCoord4dv; -PFNGLCOLORMASKPROC glad_glColorMask; -PFNGLTEXPARAMETERIIVPROC glad_glTexParameterIiv; -PFNGLBLENDEQUATIONPROC glad_glBlendEquation; -PFNGLGETUNIFORMLOCATIONPROC glad_glGetUniformLocation; -PFNGLRASTERPOS4SPROC glad_glRasterPos4s; -PFNGLENDTRANSFORMFEEDBACKPROC glad_glEndTransformFeedback; -PFNGLVERTEXATTRIB4USVPROC glad_glVertexAttrib4usv; -PFNGLMULTITEXCOORD3DVPROC glad_glMultiTexCoord3dv; -PFNGLCOLOR4SVPROC glad_glColor4sv; -PFNGLPOPCLIENTATTRIBPROC glad_glPopClientAttrib; -PFNGLBEGINTRANSFORMFEEDBACKPROC glad_glBeginTransformFeedback; -PFNGLFOGFPROC glad_glFogf; -PFNGLVERTEXATTRIBI1IVPROC glad_glVertexAttribI1iv; -PFNGLCOLOR3IVPROC glad_glColor3iv; -PFNGLCOMPRESSEDTEXIMAGE1DPROC glad_glCompressedTexImage1D; -PFNGLCOPYTEXSUBIMAGE1DPROC glad_glCopyTexSubImage1D; -PFNGLTEXCOORD1IPROC glad_glTexCoord1i; -PFNGLCHECKFRAMEBUFFERSTATUSPROC glad_glCheckFramebufferStatus; -PFNGLTEXCOORD1DPROC glad_glTexCoord1d; -PFNGLTEXCOORD1FPROC glad_glTexCoord1f; -PFNGLENDCONDITIONALRENDERPROC glad_glEndConditionalRender; -PFNGLENABLECLIENTSTATEPROC glad_glEnableClientState; -PFNGLBINDATTRIBLOCATIONPROC glad_glBindAttribLocation; -PFNGLUNIFORMMATRIX4X2FVPROC glad_glUniformMatrix4x2fv; -PFNGLMULTITEXCOORD2SVPROC glad_glMultiTexCoord2sv; -PFNGLVERTEXATTRIB1DVPROC glad_glVertexAttrib1dv; -PFNGLDRAWRANGEELEMENTSPROC glad_glDrawRangeElements; -PFNGLTEXCOORD1SPROC glad_glTexCoord1s; -PFNGLBINDBUFFERBASEPROC glad_glBindBufferBase; -PFNGLBUFFERSUBDATAPROC glad_glBufferSubData; -PFNGLVERTEXATTRIB4IVPROC glad_glVertexAttrib4iv; -PFNGLGENLISTSPROC glad_glGenLists; -PFNGLCOLOR3BVPROC glad_glColor3bv; -PFNGLMAPBUFFERRANGEPROC glad_glMapBufferRange; -PFNGLFRAMEBUFFERTEXTUREPROC glad_glFramebufferTexture; -PFNGLGETTEXGENDVPROC glad_glGetTexGendv; -PFNGLMULTIDRAWARRAYSPROC glad_glMultiDrawArrays; -PFNGLENDLISTPROC glad_glEndList; -PFNGLUNIFORM2UIPROC glad_glUniform2ui; -PFNGLVERTEXATTRIBI2IVPROC glad_glVertexAttribI2iv; -PFNGLCOLOR3USVPROC glad_glColor3usv; -PFNGLWINDOWPOS2FVPROC glad_glWindowPos2fv; -PFNGLDISABLEIPROC glad_glDisablei; -PFNGLINDEXMASKPROC glad_glIndexMask; -PFNGLPUSHCLIENTATTRIBPROC glad_glPushClientAttrib; -PFNGLSHADERSOURCEPROC glad_glShaderSource; -PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC glad_glGetActiveUniformBlockName; -PFNGLVERTEXATTRIBI3UIVPROC glad_glVertexAttribI3uiv; -PFNGLCLEARACCUMPROC glad_glClearAccum; -PFNGLGETSYNCIVPROC glad_glGetSynciv; -PFNGLUNIFORM2FPROC glad_glUniform2f; -PFNGLBEGINQUERYPROC glad_glBeginQuery; -PFNGLGETUNIFORMBLOCKINDEXPROC glad_glGetUniformBlockIndex; -PFNGLBINDBUFFERPROC glad_glBindBuffer; -PFNGLMAP2DPROC glad_glMap2d; -PFNGLMAP2FPROC glad_glMap2f; -PFNGLVERTEX4DPROC glad_glVertex4d; -PFNGLUNIFORMMATRIX2FVPROC glad_glUniformMatrix2fv; -PFNGLTEXCOORD1SVPROC glad_glTexCoord1sv; -PFNGLBUFFERDATAPROC glad_glBufferData; -PFNGLEVALPOINT1PROC glad_glEvalPoint1; -PFNGLGETTEXPARAMETERIIVPROC glad_glGetTexParameterIiv; -PFNGLTEXCOORD1DVPROC glad_glTexCoord1dv; -PFNGLGETERRORPROC glad_glGetError; -PFNGLGETTEXENVIVPROC glad_glGetTexEnviv; -PFNGLGETPROGRAMIVPROC glad_glGetProgramiv; -PFNGLGETFLOATVPROC glad_glGetFloatv; -PFNGLTEXSUBIMAGE1DPROC glad_glTexSubImage1D; -PFNGLMULTITEXCOORD2FVPROC glad_glMultiTexCoord2fv; -PFNGLVERTEXATTRIB2FVPROC glad_glVertexAttrib2fv; -PFNGLEVALCOORD1DPROC glad_glEvalCoord1d; -PFNGLGETTEXLEVELPARAMETERFVPROC glad_glGetTexLevelParameterfv; -PFNGLEVALCOORD1FPROC glad_glEvalCoord1f; -PFNGLPIXELMAPFVPROC glad_glPixelMapfv; -PFNGLGETPIXELMAPUSVPROC glad_glGetPixelMapusv; -PFNGLGETINTEGERVPROC glad_glGetIntegerv; -PFNGLACCUMPROC glad_glAccum; -PFNGLGETBUFFERPOINTERVPROC glad_glGetBufferPointerv; -PFNGLGETVERTEXATTRIBIIVPROC glad_glGetVertexAttribIiv; -PFNGLRASTERPOS4DVPROC glad_glRasterPos4dv; -PFNGLTEXCOORD2IVPROC glad_glTexCoord2iv; -PFNGLISQUERYPROC glad_glIsQuery; -PFNGLVERTEXATTRIB4SVPROC glad_glVertexAttrib4sv; -PFNGLWINDOWPOS3DVPROC glad_glWindowPos3dv; -PFNGLTEXIMAGE2DPROC glad_glTexImage2D; -PFNGLSTENCILMASKPROC glad_glStencilMask; -PFNGLDRAWPIXELSPROC glad_glDrawPixels; -PFNGLMULTMATRIXDPROC glad_glMultMatrixd; -PFNGLMULTMATRIXFPROC glad_glMultMatrixf; -PFNGLISTEXTUREPROC glad_glIsTexture; -PFNGLGETMATERIALIVPROC glad_glGetMaterialiv; -PFNGLUNIFORM1FVPROC glad_glUniform1fv; -PFNGLLOADMATRIXFPROC glad_glLoadMatrixf; -PFNGLLOADMATRIXDPROC glad_glLoadMatrixd; -PFNGLTEXPARAMETERFVPROC glad_glTexParameterfv; -PFNGLUNIFORMMATRIX3FVPROC glad_glUniformMatrix3fv; -PFNGLVERTEX4FPROC glad_glVertex4f; -PFNGLRECTSVPROC glad_glRectsv; -PFNGLCOLOR4USVPROC glad_glColor4usv; -PFNGLPOLYGONSTIPPLEPROC glad_glPolygonStipple; -PFNGLINTERLEAVEDARRAYSPROC glad_glInterleavedArrays; -PFNGLNORMAL3IPROC glad_glNormal3i; -PFNGLNORMAL3FPROC glad_glNormal3f; -PFNGLNORMAL3DPROC glad_glNormal3d; -PFNGLNORMAL3BPROC glad_glNormal3b; -PFNGLPIXELMAPUSVPROC glad_glPixelMapusv; -PFNGLGETTEXGENIVPROC glad_glGetTexGeniv; -PFNGLARRAYELEMENTPROC glad_glArrayElement; -PFNGLCOPYBUFFERSUBDATAPROC glad_glCopyBufferSubData; -PFNGLVERTEXATTRIBI1UIVPROC glad_glVertexAttribI1uiv; -PFNGLVERTEXATTRIB2DPROC glad_glVertexAttrib2d; -PFNGLVERTEXATTRIB2FPROC glad_glVertexAttrib2f; -PFNGLVERTEXATTRIB3DVPROC glad_glVertexAttrib3dv; -PFNGLDEPTHMASKPROC glad_glDepthMask; -PFNGLVERTEXATTRIB2SPROC glad_glVertexAttrib2s; -PFNGLCOLOR3FVPROC glad_glColor3fv; -PFNGLTEXIMAGE3DMULTISAMPLEPROC glad_glTexImage3DMultisample; -PFNGLUNIFORMMATRIX4FVPROC glad_glUniformMatrix4fv; -PFNGLUNIFORM4FVPROC glad_glUniform4fv; -PFNGLGETACTIVEUNIFORMPROC glad_glGetActiveUniform; -PFNGLCOLORPOINTERPROC glad_glColorPointer; -PFNGLFRONTFACEPROC glad_glFrontFace; -PFNGLGETBOOLEANI_VPROC glad_glGetBooleani_v; -PFNGLCLEARBUFFERUIVPROC glad_glClearBufferuiv; -int GLAD_GL_KHR_debug; -int GLAD_GL_ARB_robustness; -int GLAD_GL_ARB_multisample; -PFNGLSAMPLECOVERAGEARBPROC glad_glSampleCoverageARB; -PFNGLGETGRAPHICSRESETSTATUSARBPROC glad_glGetGraphicsResetStatusARB; -PFNGLGETNTEXIMAGEARBPROC glad_glGetnTexImageARB; -PFNGLREADNPIXELSARBPROC glad_glReadnPixelsARB; -PFNGLGETNCOMPRESSEDTEXIMAGEARBPROC glad_glGetnCompressedTexImageARB; -PFNGLGETNUNIFORMFVARBPROC glad_glGetnUniformfvARB; -PFNGLGETNUNIFORMIVARBPROC glad_glGetnUniformivARB; -PFNGLGETNUNIFORMUIVARBPROC glad_glGetnUniformuivARB; -PFNGLGETNUNIFORMDVARBPROC glad_glGetnUniformdvARB; -PFNGLGETNMAPDVARBPROC glad_glGetnMapdvARB; -PFNGLGETNMAPFVARBPROC glad_glGetnMapfvARB; -PFNGLGETNMAPIVARBPROC glad_glGetnMapivARB; -PFNGLGETNPIXELMAPFVARBPROC glad_glGetnPixelMapfvARB; -PFNGLGETNPIXELMAPUIVARBPROC glad_glGetnPixelMapuivARB; -PFNGLGETNPIXELMAPUSVARBPROC glad_glGetnPixelMapusvARB; -PFNGLGETNPOLYGONSTIPPLEARBPROC glad_glGetnPolygonStippleARB; -PFNGLGETNCOLORTABLEARBPROC glad_glGetnColorTableARB; -PFNGLGETNCONVOLUTIONFILTERARBPROC glad_glGetnConvolutionFilterARB; -PFNGLGETNSEPARABLEFILTERARBPROC glad_glGetnSeparableFilterARB; -PFNGLGETNHISTOGRAMARBPROC glad_glGetnHistogramARB; -PFNGLGETNMINMAXARBPROC glad_glGetnMinmaxARB; -PFNGLDEBUGMESSAGECONTROLPROC glad_glDebugMessageControl; -PFNGLDEBUGMESSAGEINSERTPROC glad_glDebugMessageInsert; -PFNGLDEBUGMESSAGECALLBACKPROC glad_glDebugMessageCallback; -PFNGLGETDEBUGMESSAGELOGPROC glad_glGetDebugMessageLog; -PFNGLPUSHDEBUGGROUPPROC glad_glPushDebugGroup; -PFNGLPOPDEBUGGROUPPROC glad_glPopDebugGroup; -PFNGLOBJECTLABELPROC glad_glObjectLabel; -PFNGLGETOBJECTLABELPROC glad_glGetObjectLabel; -PFNGLOBJECTPTRLABELPROC glad_glObjectPtrLabel; -PFNGLGETOBJECTPTRLABELPROC glad_glGetObjectPtrLabel; -PFNGLDEBUGMESSAGECONTROLKHRPROC glad_glDebugMessageControlKHR; -PFNGLDEBUGMESSAGEINSERTKHRPROC glad_glDebugMessageInsertKHR; -PFNGLDEBUGMESSAGECALLBACKKHRPROC glad_glDebugMessageCallbackKHR; -PFNGLGETDEBUGMESSAGELOGKHRPROC glad_glGetDebugMessageLogKHR; -PFNGLPUSHDEBUGGROUPKHRPROC glad_glPushDebugGroupKHR; -PFNGLPOPDEBUGGROUPKHRPROC glad_glPopDebugGroupKHR; -PFNGLOBJECTLABELKHRPROC glad_glObjectLabelKHR; -PFNGLGETOBJECTLABELKHRPROC glad_glGetObjectLabelKHR; -PFNGLOBJECTPTRLABELKHRPROC glad_glObjectPtrLabelKHR; -PFNGLGETOBJECTPTRLABELKHRPROC glad_glGetObjectPtrLabelKHR; -PFNGLGETPOINTERVKHRPROC glad_glGetPointervKHR; -static void load_GL_VERSION_1_0(GLADloadproc load) { - if(!GLAD_GL_VERSION_1_0) return; - glad_glCullFace = (PFNGLCULLFACEPROC)load("glCullFace"); - glad_glFrontFace = (PFNGLFRONTFACEPROC)load("glFrontFace"); - glad_glHint = (PFNGLHINTPROC)load("glHint"); - glad_glLineWidth = (PFNGLLINEWIDTHPROC)load("glLineWidth"); - glad_glPointSize = (PFNGLPOINTSIZEPROC)load("glPointSize"); - glad_glPolygonMode = (PFNGLPOLYGONMODEPROC)load("glPolygonMode"); - glad_glScissor = (PFNGLSCISSORPROC)load("glScissor"); - glad_glTexParameterf = (PFNGLTEXPARAMETERFPROC)load("glTexParameterf"); - glad_glTexParameterfv = (PFNGLTEXPARAMETERFVPROC)load("glTexParameterfv"); - glad_glTexParameteri = (PFNGLTEXPARAMETERIPROC)load("glTexParameteri"); - glad_glTexParameteriv = (PFNGLTEXPARAMETERIVPROC)load("glTexParameteriv"); - glad_glTexImage1D = (PFNGLTEXIMAGE1DPROC)load("glTexImage1D"); - glad_glTexImage2D = (PFNGLTEXIMAGE2DPROC)load("glTexImage2D"); - glad_glDrawBuffer = (PFNGLDRAWBUFFERPROC)load("glDrawBuffer"); - glad_glClear = (PFNGLCLEARPROC)load("glClear"); - glad_glClearColor = (PFNGLCLEARCOLORPROC)load("glClearColor"); - glad_glClearStencil = (PFNGLCLEARSTENCILPROC)load("glClearStencil"); - glad_glClearDepth = (PFNGLCLEARDEPTHPROC)load("glClearDepth"); - glad_glStencilMask = (PFNGLSTENCILMASKPROC)load("glStencilMask"); - glad_glColorMask = (PFNGLCOLORMASKPROC)load("glColorMask"); - glad_glDepthMask = (PFNGLDEPTHMASKPROC)load("glDepthMask"); - glad_glDisable = (PFNGLDISABLEPROC)load("glDisable"); - glad_glEnable = (PFNGLENABLEPROC)load("glEnable"); - glad_glFinish = (PFNGLFINISHPROC)load("glFinish"); - glad_glFlush = (PFNGLFLUSHPROC)load("glFlush"); - glad_glBlendFunc = (PFNGLBLENDFUNCPROC)load("glBlendFunc"); - glad_glLogicOp = (PFNGLLOGICOPPROC)load("glLogicOp"); - glad_glStencilFunc = (PFNGLSTENCILFUNCPROC)load("glStencilFunc"); - glad_glStencilOp = (PFNGLSTENCILOPPROC)load("glStencilOp"); - glad_glDepthFunc = (PFNGLDEPTHFUNCPROC)load("glDepthFunc"); - glad_glPixelStoref = (PFNGLPIXELSTOREFPROC)load("glPixelStoref"); - glad_glPixelStorei = (PFNGLPIXELSTOREIPROC)load("glPixelStorei"); - glad_glReadBuffer = (PFNGLREADBUFFERPROC)load("glReadBuffer"); - glad_glReadPixels = (PFNGLREADPIXELSPROC)load("glReadPixels"); - glad_glGetBooleanv = (PFNGLGETBOOLEANVPROC)load("glGetBooleanv"); - glad_glGetDoublev = (PFNGLGETDOUBLEVPROC)load("glGetDoublev"); - glad_glGetError = (PFNGLGETERRORPROC)load("glGetError"); - glad_glGetFloatv = (PFNGLGETFLOATVPROC)load("glGetFloatv"); - glad_glGetIntegerv = (PFNGLGETINTEGERVPROC)load("glGetIntegerv"); - glad_glGetString = (PFNGLGETSTRINGPROC)load("glGetString"); - glad_glGetTexImage = (PFNGLGETTEXIMAGEPROC)load("glGetTexImage"); - glad_glGetTexParameterfv = (PFNGLGETTEXPARAMETERFVPROC)load("glGetTexParameterfv"); - glad_glGetTexParameteriv = (PFNGLGETTEXPARAMETERIVPROC)load("glGetTexParameteriv"); - glad_glGetTexLevelParameterfv = (PFNGLGETTEXLEVELPARAMETERFVPROC)load("glGetTexLevelParameterfv"); - glad_glGetTexLevelParameteriv = (PFNGLGETTEXLEVELPARAMETERIVPROC)load("glGetTexLevelParameteriv"); - glad_glIsEnabled = (PFNGLISENABLEDPROC)load("glIsEnabled"); - glad_glDepthRange = (PFNGLDEPTHRANGEPROC)load("glDepthRange"); - glad_glViewport = (PFNGLVIEWPORTPROC)load("glViewport"); - glad_glNewList = (PFNGLNEWLISTPROC)load("glNewList"); - glad_glEndList = (PFNGLENDLISTPROC)load("glEndList"); - glad_glCallList = (PFNGLCALLLISTPROC)load("glCallList"); - glad_glCallLists = (PFNGLCALLLISTSPROC)load("glCallLists"); - glad_glDeleteLists = (PFNGLDELETELISTSPROC)load("glDeleteLists"); - glad_glGenLists = (PFNGLGENLISTSPROC)load("glGenLists"); - glad_glListBase = (PFNGLLISTBASEPROC)load("glListBase"); - glad_glBegin = (PFNGLBEGINPROC)load("glBegin"); - glad_glBitmap = (PFNGLBITMAPPROC)load("glBitmap"); - glad_glColor3b = (PFNGLCOLOR3BPROC)load("glColor3b"); - glad_glColor3bv = (PFNGLCOLOR3BVPROC)load("glColor3bv"); - glad_glColor3d = (PFNGLCOLOR3DPROC)load("glColor3d"); - glad_glColor3dv = (PFNGLCOLOR3DVPROC)load("glColor3dv"); - glad_glColor3f = (PFNGLCOLOR3FPROC)load("glColor3f"); - glad_glColor3fv = (PFNGLCOLOR3FVPROC)load("glColor3fv"); - glad_glColor3i = (PFNGLCOLOR3IPROC)load("glColor3i"); - glad_glColor3iv = (PFNGLCOLOR3IVPROC)load("glColor3iv"); - glad_glColor3s = (PFNGLCOLOR3SPROC)load("glColor3s"); - glad_glColor3sv = (PFNGLCOLOR3SVPROC)load("glColor3sv"); - glad_glColor3ub = (PFNGLCOLOR3UBPROC)load("glColor3ub"); - glad_glColor3ubv = (PFNGLCOLOR3UBVPROC)load("glColor3ubv"); - glad_glColor3ui = (PFNGLCOLOR3UIPROC)load("glColor3ui"); - glad_glColor3uiv = (PFNGLCOLOR3UIVPROC)load("glColor3uiv"); - glad_glColor3us = (PFNGLCOLOR3USPROC)load("glColor3us"); - glad_glColor3usv = (PFNGLCOLOR3USVPROC)load("glColor3usv"); - glad_glColor4b = (PFNGLCOLOR4BPROC)load("glColor4b"); - glad_glColor4bv = (PFNGLCOLOR4BVPROC)load("glColor4bv"); - glad_glColor4d = (PFNGLCOLOR4DPROC)load("glColor4d"); - glad_glColor4dv = (PFNGLCOLOR4DVPROC)load("glColor4dv"); - glad_glColor4f = (PFNGLCOLOR4FPROC)load("glColor4f"); - glad_glColor4fv = (PFNGLCOLOR4FVPROC)load("glColor4fv"); - glad_glColor4i = (PFNGLCOLOR4IPROC)load("glColor4i"); - glad_glColor4iv = (PFNGLCOLOR4IVPROC)load("glColor4iv"); - glad_glColor4s = (PFNGLCOLOR4SPROC)load("glColor4s"); - glad_glColor4sv = (PFNGLCOLOR4SVPROC)load("glColor4sv"); - glad_glColor4ub = (PFNGLCOLOR4UBPROC)load("glColor4ub"); - glad_glColor4ubv = (PFNGLCOLOR4UBVPROC)load("glColor4ubv"); - glad_glColor4ui = (PFNGLCOLOR4UIPROC)load("glColor4ui"); - glad_glColor4uiv = (PFNGLCOLOR4UIVPROC)load("glColor4uiv"); - glad_glColor4us = (PFNGLCOLOR4USPROC)load("glColor4us"); - glad_glColor4usv = (PFNGLCOLOR4USVPROC)load("glColor4usv"); - glad_glEdgeFlag = (PFNGLEDGEFLAGPROC)load("glEdgeFlag"); - glad_glEdgeFlagv = (PFNGLEDGEFLAGVPROC)load("glEdgeFlagv"); - glad_glEnd = (PFNGLENDPROC)load("glEnd"); - glad_glIndexd = (PFNGLINDEXDPROC)load("glIndexd"); - glad_glIndexdv = (PFNGLINDEXDVPROC)load("glIndexdv"); - glad_glIndexf = (PFNGLINDEXFPROC)load("glIndexf"); - glad_glIndexfv = (PFNGLINDEXFVPROC)load("glIndexfv"); - glad_glIndexi = (PFNGLINDEXIPROC)load("glIndexi"); - glad_glIndexiv = (PFNGLINDEXIVPROC)load("glIndexiv"); - glad_glIndexs = (PFNGLINDEXSPROC)load("glIndexs"); - glad_glIndexsv = (PFNGLINDEXSVPROC)load("glIndexsv"); - glad_glNormal3b = (PFNGLNORMAL3BPROC)load("glNormal3b"); - glad_glNormal3bv = (PFNGLNORMAL3BVPROC)load("glNormal3bv"); - glad_glNormal3d = (PFNGLNORMAL3DPROC)load("glNormal3d"); - glad_glNormal3dv = (PFNGLNORMAL3DVPROC)load("glNormal3dv"); - glad_glNormal3f = (PFNGLNORMAL3FPROC)load("glNormal3f"); - glad_glNormal3fv = (PFNGLNORMAL3FVPROC)load("glNormal3fv"); - glad_glNormal3i = (PFNGLNORMAL3IPROC)load("glNormal3i"); - glad_glNormal3iv = (PFNGLNORMAL3IVPROC)load("glNormal3iv"); - glad_glNormal3s = (PFNGLNORMAL3SPROC)load("glNormal3s"); - glad_glNormal3sv = (PFNGLNORMAL3SVPROC)load("glNormal3sv"); - glad_glRasterPos2d = (PFNGLRASTERPOS2DPROC)load("glRasterPos2d"); - glad_glRasterPos2dv = (PFNGLRASTERPOS2DVPROC)load("glRasterPos2dv"); - glad_glRasterPos2f = (PFNGLRASTERPOS2FPROC)load("glRasterPos2f"); - glad_glRasterPos2fv = (PFNGLRASTERPOS2FVPROC)load("glRasterPos2fv"); - glad_glRasterPos2i = (PFNGLRASTERPOS2IPROC)load("glRasterPos2i"); - glad_glRasterPos2iv = (PFNGLRASTERPOS2IVPROC)load("glRasterPos2iv"); - glad_glRasterPos2s = (PFNGLRASTERPOS2SPROC)load("glRasterPos2s"); - glad_glRasterPos2sv = (PFNGLRASTERPOS2SVPROC)load("glRasterPos2sv"); - glad_glRasterPos3d = (PFNGLRASTERPOS3DPROC)load("glRasterPos3d"); - glad_glRasterPos3dv = (PFNGLRASTERPOS3DVPROC)load("glRasterPos3dv"); - glad_glRasterPos3f = (PFNGLRASTERPOS3FPROC)load("glRasterPos3f"); - glad_glRasterPos3fv = (PFNGLRASTERPOS3FVPROC)load("glRasterPos3fv"); - glad_glRasterPos3i = (PFNGLRASTERPOS3IPROC)load("glRasterPos3i"); - glad_glRasterPos3iv = (PFNGLRASTERPOS3IVPROC)load("glRasterPos3iv"); - glad_glRasterPos3s = (PFNGLRASTERPOS3SPROC)load("glRasterPos3s"); - glad_glRasterPos3sv = (PFNGLRASTERPOS3SVPROC)load("glRasterPos3sv"); - glad_glRasterPos4d = (PFNGLRASTERPOS4DPROC)load("glRasterPos4d"); - glad_glRasterPos4dv = (PFNGLRASTERPOS4DVPROC)load("glRasterPos4dv"); - glad_glRasterPos4f = (PFNGLRASTERPOS4FPROC)load("glRasterPos4f"); - glad_glRasterPos4fv = (PFNGLRASTERPOS4FVPROC)load("glRasterPos4fv"); - glad_glRasterPos4i = (PFNGLRASTERPOS4IPROC)load("glRasterPos4i"); - glad_glRasterPos4iv = (PFNGLRASTERPOS4IVPROC)load("glRasterPos4iv"); - glad_glRasterPos4s = (PFNGLRASTERPOS4SPROC)load("glRasterPos4s"); - glad_glRasterPos4sv = (PFNGLRASTERPOS4SVPROC)load("glRasterPos4sv"); - glad_glRectd = (PFNGLRECTDPROC)load("glRectd"); - glad_glRectdv = (PFNGLRECTDVPROC)load("glRectdv"); - glad_glRectf = (PFNGLRECTFPROC)load("glRectf"); - glad_glRectfv = (PFNGLRECTFVPROC)load("glRectfv"); - glad_glRecti = (PFNGLRECTIPROC)load("glRecti"); - glad_glRectiv = (PFNGLRECTIVPROC)load("glRectiv"); - glad_glRects = (PFNGLRECTSPROC)load("glRects"); - glad_glRectsv = (PFNGLRECTSVPROC)load("glRectsv"); - glad_glTexCoord1d = (PFNGLTEXCOORD1DPROC)load("glTexCoord1d"); - glad_glTexCoord1dv = (PFNGLTEXCOORD1DVPROC)load("glTexCoord1dv"); - glad_glTexCoord1f = (PFNGLTEXCOORD1FPROC)load("glTexCoord1f"); - glad_glTexCoord1fv = (PFNGLTEXCOORD1FVPROC)load("glTexCoord1fv"); - glad_glTexCoord1i = (PFNGLTEXCOORD1IPROC)load("glTexCoord1i"); - glad_glTexCoord1iv = (PFNGLTEXCOORD1IVPROC)load("glTexCoord1iv"); - glad_glTexCoord1s = (PFNGLTEXCOORD1SPROC)load("glTexCoord1s"); - glad_glTexCoord1sv = (PFNGLTEXCOORD1SVPROC)load("glTexCoord1sv"); - glad_glTexCoord2d = (PFNGLTEXCOORD2DPROC)load("glTexCoord2d"); - glad_glTexCoord2dv = (PFNGLTEXCOORD2DVPROC)load("glTexCoord2dv"); - glad_glTexCoord2f = (PFNGLTEXCOORD2FPROC)load("glTexCoord2f"); - glad_glTexCoord2fv = (PFNGLTEXCOORD2FVPROC)load("glTexCoord2fv"); - glad_glTexCoord2i = (PFNGLTEXCOORD2IPROC)load("glTexCoord2i"); - glad_glTexCoord2iv = (PFNGLTEXCOORD2IVPROC)load("glTexCoord2iv"); - glad_glTexCoord2s = (PFNGLTEXCOORD2SPROC)load("glTexCoord2s"); - glad_glTexCoord2sv = (PFNGLTEXCOORD2SVPROC)load("glTexCoord2sv"); - glad_glTexCoord3d = (PFNGLTEXCOORD3DPROC)load("glTexCoord3d"); - glad_glTexCoord3dv = (PFNGLTEXCOORD3DVPROC)load("glTexCoord3dv"); - glad_glTexCoord3f = (PFNGLTEXCOORD3FPROC)load("glTexCoord3f"); - glad_glTexCoord3fv = (PFNGLTEXCOORD3FVPROC)load("glTexCoord3fv"); - glad_glTexCoord3i = (PFNGLTEXCOORD3IPROC)load("glTexCoord3i"); - glad_glTexCoord3iv = (PFNGLTEXCOORD3IVPROC)load("glTexCoord3iv"); - glad_glTexCoord3s = (PFNGLTEXCOORD3SPROC)load("glTexCoord3s"); - glad_glTexCoord3sv = (PFNGLTEXCOORD3SVPROC)load("glTexCoord3sv"); - glad_glTexCoord4d = (PFNGLTEXCOORD4DPROC)load("glTexCoord4d"); - glad_glTexCoord4dv = (PFNGLTEXCOORD4DVPROC)load("glTexCoord4dv"); - glad_glTexCoord4f = (PFNGLTEXCOORD4FPROC)load("glTexCoord4f"); - glad_glTexCoord4fv = (PFNGLTEXCOORD4FVPROC)load("glTexCoord4fv"); - glad_glTexCoord4i = (PFNGLTEXCOORD4IPROC)load("glTexCoord4i"); - glad_glTexCoord4iv = (PFNGLTEXCOORD4IVPROC)load("glTexCoord4iv"); - glad_glTexCoord4s = (PFNGLTEXCOORD4SPROC)load("glTexCoord4s"); - glad_glTexCoord4sv = (PFNGLTEXCOORD4SVPROC)load("glTexCoord4sv"); - glad_glVertex2d = (PFNGLVERTEX2DPROC)load("glVertex2d"); - glad_glVertex2dv = (PFNGLVERTEX2DVPROC)load("glVertex2dv"); - glad_glVertex2f = (PFNGLVERTEX2FPROC)load("glVertex2f"); - glad_glVertex2fv = (PFNGLVERTEX2FVPROC)load("glVertex2fv"); - glad_glVertex2i = (PFNGLVERTEX2IPROC)load("glVertex2i"); - glad_glVertex2iv = (PFNGLVERTEX2IVPROC)load("glVertex2iv"); - glad_glVertex2s = (PFNGLVERTEX2SPROC)load("glVertex2s"); - glad_glVertex2sv = (PFNGLVERTEX2SVPROC)load("glVertex2sv"); - glad_glVertex3d = (PFNGLVERTEX3DPROC)load("glVertex3d"); - glad_glVertex3dv = (PFNGLVERTEX3DVPROC)load("glVertex3dv"); - glad_glVertex3f = (PFNGLVERTEX3FPROC)load("glVertex3f"); - glad_glVertex3fv = (PFNGLVERTEX3FVPROC)load("glVertex3fv"); - glad_glVertex3i = (PFNGLVERTEX3IPROC)load("glVertex3i"); - glad_glVertex3iv = (PFNGLVERTEX3IVPROC)load("glVertex3iv"); - glad_glVertex3s = (PFNGLVERTEX3SPROC)load("glVertex3s"); - glad_glVertex3sv = (PFNGLVERTEX3SVPROC)load("glVertex3sv"); - glad_glVertex4d = (PFNGLVERTEX4DPROC)load("glVertex4d"); - glad_glVertex4dv = (PFNGLVERTEX4DVPROC)load("glVertex4dv"); - glad_glVertex4f = (PFNGLVERTEX4FPROC)load("glVertex4f"); - glad_glVertex4fv = (PFNGLVERTEX4FVPROC)load("glVertex4fv"); - glad_glVertex4i = (PFNGLVERTEX4IPROC)load("glVertex4i"); - glad_glVertex4iv = (PFNGLVERTEX4IVPROC)load("glVertex4iv"); - glad_glVertex4s = (PFNGLVERTEX4SPROC)load("glVertex4s"); - glad_glVertex4sv = (PFNGLVERTEX4SVPROC)load("glVertex4sv"); - glad_glClipPlane = (PFNGLCLIPPLANEPROC)load("glClipPlane"); - glad_glColorMaterial = (PFNGLCOLORMATERIALPROC)load("glColorMaterial"); - glad_glFogf = (PFNGLFOGFPROC)load("glFogf"); - glad_glFogfv = (PFNGLFOGFVPROC)load("glFogfv"); - glad_glFogi = (PFNGLFOGIPROC)load("glFogi"); - glad_glFogiv = (PFNGLFOGIVPROC)load("glFogiv"); - glad_glLightf = (PFNGLLIGHTFPROC)load("glLightf"); - glad_glLightfv = (PFNGLLIGHTFVPROC)load("glLightfv"); - glad_glLighti = (PFNGLLIGHTIPROC)load("glLighti"); - glad_glLightiv = (PFNGLLIGHTIVPROC)load("glLightiv"); - glad_glLightModelf = (PFNGLLIGHTMODELFPROC)load("glLightModelf"); - glad_glLightModelfv = (PFNGLLIGHTMODELFVPROC)load("glLightModelfv"); - glad_glLightModeli = (PFNGLLIGHTMODELIPROC)load("glLightModeli"); - glad_glLightModeliv = (PFNGLLIGHTMODELIVPROC)load("glLightModeliv"); - glad_glLineStipple = (PFNGLLINESTIPPLEPROC)load("glLineStipple"); - glad_glMaterialf = (PFNGLMATERIALFPROC)load("glMaterialf"); - glad_glMaterialfv = (PFNGLMATERIALFVPROC)load("glMaterialfv"); - glad_glMateriali = (PFNGLMATERIALIPROC)load("glMateriali"); - glad_glMaterialiv = (PFNGLMATERIALIVPROC)load("glMaterialiv"); - glad_glPolygonStipple = (PFNGLPOLYGONSTIPPLEPROC)load("glPolygonStipple"); - glad_glShadeModel = (PFNGLSHADEMODELPROC)load("glShadeModel"); - glad_glTexEnvf = (PFNGLTEXENVFPROC)load("glTexEnvf"); - glad_glTexEnvfv = (PFNGLTEXENVFVPROC)load("glTexEnvfv"); - glad_glTexEnvi = (PFNGLTEXENVIPROC)load("glTexEnvi"); - glad_glTexEnviv = (PFNGLTEXENVIVPROC)load("glTexEnviv"); - glad_glTexGend = (PFNGLTEXGENDPROC)load("glTexGend"); - glad_glTexGendv = (PFNGLTEXGENDVPROC)load("glTexGendv"); - glad_glTexGenf = (PFNGLTEXGENFPROC)load("glTexGenf"); - glad_glTexGenfv = (PFNGLTEXGENFVPROC)load("glTexGenfv"); - glad_glTexGeni = (PFNGLTEXGENIPROC)load("glTexGeni"); - glad_glTexGeniv = (PFNGLTEXGENIVPROC)load("glTexGeniv"); - glad_glFeedbackBuffer = (PFNGLFEEDBACKBUFFERPROC)load("glFeedbackBuffer"); - glad_glSelectBuffer = (PFNGLSELECTBUFFERPROC)load("glSelectBuffer"); - glad_glRenderMode = (PFNGLRENDERMODEPROC)load("glRenderMode"); - glad_glInitNames = (PFNGLINITNAMESPROC)load("glInitNames"); - glad_glLoadName = (PFNGLLOADNAMEPROC)load("glLoadName"); - glad_glPassThrough = (PFNGLPASSTHROUGHPROC)load("glPassThrough"); - glad_glPopName = (PFNGLPOPNAMEPROC)load("glPopName"); - glad_glPushName = (PFNGLPUSHNAMEPROC)load("glPushName"); - glad_glClearAccum = (PFNGLCLEARACCUMPROC)load("glClearAccum"); - glad_glClearIndex = (PFNGLCLEARINDEXPROC)load("glClearIndex"); - glad_glIndexMask = (PFNGLINDEXMASKPROC)load("glIndexMask"); - glad_glAccum = (PFNGLACCUMPROC)load("glAccum"); - glad_glPopAttrib = (PFNGLPOPATTRIBPROC)load("glPopAttrib"); - glad_glPushAttrib = (PFNGLPUSHATTRIBPROC)load("glPushAttrib"); - glad_glMap1d = (PFNGLMAP1DPROC)load("glMap1d"); - glad_glMap1f = (PFNGLMAP1FPROC)load("glMap1f"); - glad_glMap2d = (PFNGLMAP2DPROC)load("glMap2d"); - glad_glMap2f = (PFNGLMAP2FPROC)load("glMap2f"); - glad_glMapGrid1d = (PFNGLMAPGRID1DPROC)load("glMapGrid1d"); - glad_glMapGrid1f = (PFNGLMAPGRID1FPROC)load("glMapGrid1f"); - glad_glMapGrid2d = (PFNGLMAPGRID2DPROC)load("glMapGrid2d"); - glad_glMapGrid2f = (PFNGLMAPGRID2FPROC)load("glMapGrid2f"); - glad_glEvalCoord1d = (PFNGLEVALCOORD1DPROC)load("glEvalCoord1d"); - glad_glEvalCoord1dv = (PFNGLEVALCOORD1DVPROC)load("glEvalCoord1dv"); - glad_glEvalCoord1f = (PFNGLEVALCOORD1FPROC)load("glEvalCoord1f"); - glad_glEvalCoord1fv = (PFNGLEVALCOORD1FVPROC)load("glEvalCoord1fv"); - glad_glEvalCoord2d = (PFNGLEVALCOORD2DPROC)load("glEvalCoord2d"); - glad_glEvalCoord2dv = (PFNGLEVALCOORD2DVPROC)load("glEvalCoord2dv"); - glad_glEvalCoord2f = (PFNGLEVALCOORD2FPROC)load("glEvalCoord2f"); - glad_glEvalCoord2fv = (PFNGLEVALCOORD2FVPROC)load("glEvalCoord2fv"); - glad_glEvalMesh1 = (PFNGLEVALMESH1PROC)load("glEvalMesh1"); - glad_glEvalPoint1 = (PFNGLEVALPOINT1PROC)load("glEvalPoint1"); - glad_glEvalMesh2 = (PFNGLEVALMESH2PROC)load("glEvalMesh2"); - glad_glEvalPoint2 = (PFNGLEVALPOINT2PROC)load("glEvalPoint2"); - glad_glAlphaFunc = (PFNGLALPHAFUNCPROC)load("glAlphaFunc"); - glad_glPixelZoom = (PFNGLPIXELZOOMPROC)load("glPixelZoom"); - glad_glPixelTransferf = (PFNGLPIXELTRANSFERFPROC)load("glPixelTransferf"); - glad_glPixelTransferi = (PFNGLPIXELTRANSFERIPROC)load("glPixelTransferi"); - glad_glPixelMapfv = (PFNGLPIXELMAPFVPROC)load("glPixelMapfv"); - glad_glPixelMapuiv = (PFNGLPIXELMAPUIVPROC)load("glPixelMapuiv"); - glad_glPixelMapusv = (PFNGLPIXELMAPUSVPROC)load("glPixelMapusv"); - glad_glCopyPixels = (PFNGLCOPYPIXELSPROC)load("glCopyPixels"); - glad_glDrawPixels = (PFNGLDRAWPIXELSPROC)load("glDrawPixels"); - glad_glGetClipPlane = (PFNGLGETCLIPPLANEPROC)load("glGetClipPlane"); - glad_glGetLightfv = (PFNGLGETLIGHTFVPROC)load("glGetLightfv"); - glad_glGetLightiv = (PFNGLGETLIGHTIVPROC)load("glGetLightiv"); - glad_glGetMapdv = (PFNGLGETMAPDVPROC)load("glGetMapdv"); - glad_glGetMapfv = (PFNGLGETMAPFVPROC)load("glGetMapfv"); - glad_glGetMapiv = (PFNGLGETMAPIVPROC)load("glGetMapiv"); - glad_glGetMaterialfv = (PFNGLGETMATERIALFVPROC)load("glGetMaterialfv"); - glad_glGetMaterialiv = (PFNGLGETMATERIALIVPROC)load("glGetMaterialiv"); - glad_glGetPixelMapfv = (PFNGLGETPIXELMAPFVPROC)load("glGetPixelMapfv"); - glad_glGetPixelMapuiv = (PFNGLGETPIXELMAPUIVPROC)load("glGetPixelMapuiv"); - glad_glGetPixelMapusv = (PFNGLGETPIXELMAPUSVPROC)load("glGetPixelMapusv"); - glad_glGetPolygonStipple = (PFNGLGETPOLYGONSTIPPLEPROC)load("glGetPolygonStipple"); - glad_glGetTexEnvfv = (PFNGLGETTEXENVFVPROC)load("glGetTexEnvfv"); - glad_glGetTexEnviv = (PFNGLGETTEXENVIVPROC)load("glGetTexEnviv"); - glad_glGetTexGendv = (PFNGLGETTEXGENDVPROC)load("glGetTexGendv"); - glad_glGetTexGenfv = (PFNGLGETTEXGENFVPROC)load("glGetTexGenfv"); - glad_glGetTexGeniv = (PFNGLGETTEXGENIVPROC)load("glGetTexGeniv"); - glad_glIsList = (PFNGLISLISTPROC)load("glIsList"); - glad_glFrustum = (PFNGLFRUSTUMPROC)load("glFrustum"); - glad_glLoadIdentity = (PFNGLLOADIDENTITYPROC)load("glLoadIdentity"); - glad_glLoadMatrixf = (PFNGLLOADMATRIXFPROC)load("glLoadMatrixf"); - glad_glLoadMatrixd = (PFNGLLOADMATRIXDPROC)load("glLoadMatrixd"); - glad_glMatrixMode = (PFNGLMATRIXMODEPROC)load("glMatrixMode"); - glad_glMultMatrixf = (PFNGLMULTMATRIXFPROC)load("glMultMatrixf"); - glad_glMultMatrixd = (PFNGLMULTMATRIXDPROC)load("glMultMatrixd"); - glad_glOrtho = (PFNGLORTHOPROC)load("glOrtho"); - glad_glPopMatrix = (PFNGLPOPMATRIXPROC)load("glPopMatrix"); - glad_glPushMatrix = (PFNGLPUSHMATRIXPROC)load("glPushMatrix"); - glad_glRotated = (PFNGLROTATEDPROC)load("glRotated"); - glad_glRotatef = (PFNGLROTATEFPROC)load("glRotatef"); - glad_glScaled = (PFNGLSCALEDPROC)load("glScaled"); - glad_glScalef = (PFNGLSCALEFPROC)load("glScalef"); - glad_glTranslated = (PFNGLTRANSLATEDPROC)load("glTranslated"); - glad_glTranslatef = (PFNGLTRANSLATEFPROC)load("glTranslatef"); -} -static void load_GL_VERSION_1_1(GLADloadproc load) { - if(!GLAD_GL_VERSION_1_1) return; - glad_glDrawArrays = (PFNGLDRAWARRAYSPROC)load("glDrawArrays"); - glad_glDrawElements = (PFNGLDRAWELEMENTSPROC)load("glDrawElements"); - glad_glGetPointerv = (PFNGLGETPOINTERVPROC)load("glGetPointerv"); - glad_glPolygonOffset = (PFNGLPOLYGONOFFSETPROC)load("glPolygonOffset"); - glad_glCopyTexImage1D = (PFNGLCOPYTEXIMAGE1DPROC)load("glCopyTexImage1D"); - glad_glCopyTexImage2D = (PFNGLCOPYTEXIMAGE2DPROC)load("glCopyTexImage2D"); - glad_glCopyTexSubImage1D = (PFNGLCOPYTEXSUBIMAGE1DPROC)load("glCopyTexSubImage1D"); - glad_glCopyTexSubImage2D = (PFNGLCOPYTEXSUBIMAGE2DPROC)load("glCopyTexSubImage2D"); - glad_glTexSubImage1D = (PFNGLTEXSUBIMAGE1DPROC)load("glTexSubImage1D"); - glad_glTexSubImage2D = (PFNGLTEXSUBIMAGE2DPROC)load("glTexSubImage2D"); - glad_glBindTexture = (PFNGLBINDTEXTUREPROC)load("glBindTexture"); - glad_glDeleteTextures = (PFNGLDELETETEXTURESPROC)load("glDeleteTextures"); - glad_glGenTextures = (PFNGLGENTEXTURESPROC)load("glGenTextures"); - glad_glIsTexture = (PFNGLISTEXTUREPROC)load("glIsTexture"); - glad_glArrayElement = (PFNGLARRAYELEMENTPROC)load("glArrayElement"); - glad_glColorPointer = (PFNGLCOLORPOINTERPROC)load("glColorPointer"); - glad_glDisableClientState = (PFNGLDISABLECLIENTSTATEPROC)load("glDisableClientState"); - glad_glEdgeFlagPointer = (PFNGLEDGEFLAGPOINTERPROC)load("glEdgeFlagPointer"); - glad_glEnableClientState = (PFNGLENABLECLIENTSTATEPROC)load("glEnableClientState"); - glad_glIndexPointer = (PFNGLINDEXPOINTERPROC)load("glIndexPointer"); - glad_glInterleavedArrays = (PFNGLINTERLEAVEDARRAYSPROC)load("glInterleavedArrays"); - glad_glNormalPointer = (PFNGLNORMALPOINTERPROC)load("glNormalPointer"); - glad_glTexCoordPointer = (PFNGLTEXCOORDPOINTERPROC)load("glTexCoordPointer"); - glad_glVertexPointer = (PFNGLVERTEXPOINTERPROC)load("glVertexPointer"); - glad_glAreTexturesResident = (PFNGLARETEXTURESRESIDENTPROC)load("glAreTexturesResident"); - glad_glPrioritizeTextures = (PFNGLPRIORITIZETEXTURESPROC)load("glPrioritizeTextures"); - glad_glIndexub = (PFNGLINDEXUBPROC)load("glIndexub"); - glad_glIndexubv = (PFNGLINDEXUBVPROC)load("glIndexubv"); - glad_glPopClientAttrib = (PFNGLPOPCLIENTATTRIBPROC)load("glPopClientAttrib"); - glad_glPushClientAttrib = (PFNGLPUSHCLIENTATTRIBPROC)load("glPushClientAttrib"); -} -static void load_GL_VERSION_1_2(GLADloadproc load) { - if(!GLAD_GL_VERSION_1_2) return; - glad_glDrawRangeElements = (PFNGLDRAWRANGEELEMENTSPROC)load("glDrawRangeElements"); - glad_glTexImage3D = (PFNGLTEXIMAGE3DPROC)load("glTexImage3D"); - glad_glTexSubImage3D = (PFNGLTEXSUBIMAGE3DPROC)load("glTexSubImage3D"); - glad_glCopyTexSubImage3D = (PFNGLCOPYTEXSUBIMAGE3DPROC)load("glCopyTexSubImage3D"); -} -static void load_GL_VERSION_1_3(GLADloadproc load) { - if(!GLAD_GL_VERSION_1_3) return; - glad_glActiveTexture = (PFNGLACTIVETEXTUREPROC)load("glActiveTexture"); - glad_glSampleCoverage = (PFNGLSAMPLECOVERAGEPROC)load("glSampleCoverage"); - glad_glCompressedTexImage3D = (PFNGLCOMPRESSEDTEXIMAGE3DPROC)load("glCompressedTexImage3D"); - glad_glCompressedTexImage2D = (PFNGLCOMPRESSEDTEXIMAGE2DPROC)load("glCompressedTexImage2D"); - glad_glCompressedTexImage1D = (PFNGLCOMPRESSEDTEXIMAGE1DPROC)load("glCompressedTexImage1D"); - glad_glCompressedTexSubImage3D = (PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC)load("glCompressedTexSubImage3D"); - glad_glCompressedTexSubImage2D = (PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC)load("glCompressedTexSubImage2D"); - glad_glCompressedTexSubImage1D = (PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC)load("glCompressedTexSubImage1D"); - glad_glGetCompressedTexImage = (PFNGLGETCOMPRESSEDTEXIMAGEPROC)load("glGetCompressedTexImage"); - glad_glClientActiveTexture = (PFNGLCLIENTACTIVETEXTUREPROC)load("glClientActiveTexture"); - glad_glMultiTexCoord1d = (PFNGLMULTITEXCOORD1DPROC)load("glMultiTexCoord1d"); - glad_glMultiTexCoord1dv = (PFNGLMULTITEXCOORD1DVPROC)load("glMultiTexCoord1dv"); - glad_glMultiTexCoord1f = (PFNGLMULTITEXCOORD1FPROC)load("glMultiTexCoord1f"); - glad_glMultiTexCoord1fv = (PFNGLMULTITEXCOORD1FVPROC)load("glMultiTexCoord1fv"); - glad_glMultiTexCoord1i = (PFNGLMULTITEXCOORD1IPROC)load("glMultiTexCoord1i"); - glad_glMultiTexCoord1iv = (PFNGLMULTITEXCOORD1IVPROC)load("glMultiTexCoord1iv"); - glad_glMultiTexCoord1s = (PFNGLMULTITEXCOORD1SPROC)load("glMultiTexCoord1s"); - glad_glMultiTexCoord1sv = (PFNGLMULTITEXCOORD1SVPROC)load("glMultiTexCoord1sv"); - glad_glMultiTexCoord2d = (PFNGLMULTITEXCOORD2DPROC)load("glMultiTexCoord2d"); - glad_glMultiTexCoord2dv = (PFNGLMULTITEXCOORD2DVPROC)load("glMultiTexCoord2dv"); - glad_glMultiTexCoord2f = (PFNGLMULTITEXCOORD2FPROC)load("glMultiTexCoord2f"); - glad_glMultiTexCoord2fv = (PFNGLMULTITEXCOORD2FVPROC)load("glMultiTexCoord2fv"); - glad_glMultiTexCoord2i = (PFNGLMULTITEXCOORD2IPROC)load("glMultiTexCoord2i"); - glad_glMultiTexCoord2iv = (PFNGLMULTITEXCOORD2IVPROC)load("glMultiTexCoord2iv"); - glad_glMultiTexCoord2s = (PFNGLMULTITEXCOORD2SPROC)load("glMultiTexCoord2s"); - glad_glMultiTexCoord2sv = (PFNGLMULTITEXCOORD2SVPROC)load("glMultiTexCoord2sv"); - glad_glMultiTexCoord3d = (PFNGLMULTITEXCOORD3DPROC)load("glMultiTexCoord3d"); - glad_glMultiTexCoord3dv = (PFNGLMULTITEXCOORD3DVPROC)load("glMultiTexCoord3dv"); - glad_glMultiTexCoord3f = (PFNGLMULTITEXCOORD3FPROC)load("glMultiTexCoord3f"); - glad_glMultiTexCoord3fv = (PFNGLMULTITEXCOORD3FVPROC)load("glMultiTexCoord3fv"); - glad_glMultiTexCoord3i = (PFNGLMULTITEXCOORD3IPROC)load("glMultiTexCoord3i"); - glad_glMultiTexCoord3iv = (PFNGLMULTITEXCOORD3IVPROC)load("glMultiTexCoord3iv"); - glad_glMultiTexCoord3s = (PFNGLMULTITEXCOORD3SPROC)load("glMultiTexCoord3s"); - glad_glMultiTexCoord3sv = (PFNGLMULTITEXCOORD3SVPROC)load("glMultiTexCoord3sv"); - glad_glMultiTexCoord4d = (PFNGLMULTITEXCOORD4DPROC)load("glMultiTexCoord4d"); - glad_glMultiTexCoord4dv = (PFNGLMULTITEXCOORD4DVPROC)load("glMultiTexCoord4dv"); - glad_glMultiTexCoord4f = (PFNGLMULTITEXCOORD4FPROC)load("glMultiTexCoord4f"); - glad_glMultiTexCoord4fv = (PFNGLMULTITEXCOORD4FVPROC)load("glMultiTexCoord4fv"); - glad_glMultiTexCoord4i = (PFNGLMULTITEXCOORD4IPROC)load("glMultiTexCoord4i"); - glad_glMultiTexCoord4iv = (PFNGLMULTITEXCOORD4IVPROC)load("glMultiTexCoord4iv"); - glad_glMultiTexCoord4s = (PFNGLMULTITEXCOORD4SPROC)load("glMultiTexCoord4s"); - glad_glMultiTexCoord4sv = (PFNGLMULTITEXCOORD4SVPROC)load("glMultiTexCoord4sv"); - glad_glLoadTransposeMatrixf = (PFNGLLOADTRANSPOSEMATRIXFPROC)load("glLoadTransposeMatrixf"); - glad_glLoadTransposeMatrixd = (PFNGLLOADTRANSPOSEMATRIXDPROC)load("glLoadTransposeMatrixd"); - glad_glMultTransposeMatrixf = (PFNGLMULTTRANSPOSEMATRIXFPROC)load("glMultTransposeMatrixf"); - glad_glMultTransposeMatrixd = (PFNGLMULTTRANSPOSEMATRIXDPROC)load("glMultTransposeMatrixd"); -} -static void load_GL_VERSION_1_4(GLADloadproc load) { - if(!GLAD_GL_VERSION_1_4) return; - glad_glBlendFuncSeparate = (PFNGLBLENDFUNCSEPARATEPROC)load("glBlendFuncSeparate"); - glad_glMultiDrawArrays = (PFNGLMULTIDRAWARRAYSPROC)load("glMultiDrawArrays"); - glad_glMultiDrawElements = (PFNGLMULTIDRAWELEMENTSPROC)load("glMultiDrawElements"); - glad_glPointParameterf = (PFNGLPOINTPARAMETERFPROC)load("glPointParameterf"); - glad_glPointParameterfv = (PFNGLPOINTPARAMETERFVPROC)load("glPointParameterfv"); - glad_glPointParameteri = (PFNGLPOINTPARAMETERIPROC)load("glPointParameteri"); - glad_glPointParameteriv = (PFNGLPOINTPARAMETERIVPROC)load("glPointParameteriv"); - glad_glFogCoordf = (PFNGLFOGCOORDFPROC)load("glFogCoordf"); - glad_glFogCoordfv = (PFNGLFOGCOORDFVPROC)load("glFogCoordfv"); - glad_glFogCoordd = (PFNGLFOGCOORDDPROC)load("glFogCoordd"); - glad_glFogCoorddv = (PFNGLFOGCOORDDVPROC)load("glFogCoorddv"); - glad_glFogCoordPointer = (PFNGLFOGCOORDPOINTERPROC)load("glFogCoordPointer"); - glad_glSecondaryColor3b = (PFNGLSECONDARYCOLOR3BPROC)load("glSecondaryColor3b"); - glad_glSecondaryColor3bv = (PFNGLSECONDARYCOLOR3BVPROC)load("glSecondaryColor3bv"); - glad_glSecondaryColor3d = (PFNGLSECONDARYCOLOR3DPROC)load("glSecondaryColor3d"); - glad_glSecondaryColor3dv = (PFNGLSECONDARYCOLOR3DVPROC)load("glSecondaryColor3dv"); - glad_glSecondaryColor3f = (PFNGLSECONDARYCOLOR3FPROC)load("glSecondaryColor3f"); - glad_glSecondaryColor3fv = (PFNGLSECONDARYCOLOR3FVPROC)load("glSecondaryColor3fv"); - glad_glSecondaryColor3i = (PFNGLSECONDARYCOLOR3IPROC)load("glSecondaryColor3i"); - glad_glSecondaryColor3iv = (PFNGLSECONDARYCOLOR3IVPROC)load("glSecondaryColor3iv"); - glad_glSecondaryColor3s = (PFNGLSECONDARYCOLOR3SPROC)load("glSecondaryColor3s"); - glad_glSecondaryColor3sv = (PFNGLSECONDARYCOLOR3SVPROC)load("glSecondaryColor3sv"); - glad_glSecondaryColor3ub = (PFNGLSECONDARYCOLOR3UBPROC)load("glSecondaryColor3ub"); - glad_glSecondaryColor3ubv = (PFNGLSECONDARYCOLOR3UBVPROC)load("glSecondaryColor3ubv"); - glad_glSecondaryColor3ui = (PFNGLSECONDARYCOLOR3UIPROC)load("glSecondaryColor3ui"); - glad_glSecondaryColor3uiv = (PFNGLSECONDARYCOLOR3UIVPROC)load("glSecondaryColor3uiv"); - glad_glSecondaryColor3us = (PFNGLSECONDARYCOLOR3USPROC)load("glSecondaryColor3us"); - glad_glSecondaryColor3usv = (PFNGLSECONDARYCOLOR3USVPROC)load("glSecondaryColor3usv"); - glad_glSecondaryColorPointer = (PFNGLSECONDARYCOLORPOINTERPROC)load("glSecondaryColorPointer"); - glad_glWindowPos2d = (PFNGLWINDOWPOS2DPROC)load("glWindowPos2d"); - glad_glWindowPos2dv = (PFNGLWINDOWPOS2DVPROC)load("glWindowPos2dv"); - glad_glWindowPos2f = (PFNGLWINDOWPOS2FPROC)load("glWindowPos2f"); - glad_glWindowPos2fv = (PFNGLWINDOWPOS2FVPROC)load("glWindowPos2fv"); - glad_glWindowPos2i = (PFNGLWINDOWPOS2IPROC)load("glWindowPos2i"); - glad_glWindowPos2iv = (PFNGLWINDOWPOS2IVPROC)load("glWindowPos2iv"); - glad_glWindowPos2s = (PFNGLWINDOWPOS2SPROC)load("glWindowPos2s"); - glad_glWindowPos2sv = (PFNGLWINDOWPOS2SVPROC)load("glWindowPos2sv"); - glad_glWindowPos3d = (PFNGLWINDOWPOS3DPROC)load("glWindowPos3d"); - glad_glWindowPos3dv = (PFNGLWINDOWPOS3DVPROC)load("glWindowPos3dv"); - glad_glWindowPos3f = (PFNGLWINDOWPOS3FPROC)load("glWindowPos3f"); - glad_glWindowPos3fv = (PFNGLWINDOWPOS3FVPROC)load("glWindowPos3fv"); - glad_glWindowPos3i = (PFNGLWINDOWPOS3IPROC)load("glWindowPos3i"); - glad_glWindowPos3iv = (PFNGLWINDOWPOS3IVPROC)load("glWindowPos3iv"); - glad_glWindowPos3s = (PFNGLWINDOWPOS3SPROC)load("glWindowPos3s"); - glad_glWindowPos3sv = (PFNGLWINDOWPOS3SVPROC)load("glWindowPos3sv"); - glad_glBlendColor = (PFNGLBLENDCOLORPROC)load("glBlendColor"); - glad_glBlendEquation = (PFNGLBLENDEQUATIONPROC)load("glBlendEquation"); -} -static void load_GL_VERSION_1_5(GLADloadproc load) { - if(!GLAD_GL_VERSION_1_5) return; - glad_glGenQueries = (PFNGLGENQUERIESPROC)load("glGenQueries"); - glad_glDeleteQueries = (PFNGLDELETEQUERIESPROC)load("glDeleteQueries"); - glad_glIsQuery = (PFNGLISQUERYPROC)load("glIsQuery"); - glad_glBeginQuery = (PFNGLBEGINQUERYPROC)load("glBeginQuery"); - glad_glEndQuery = (PFNGLENDQUERYPROC)load("glEndQuery"); - glad_glGetQueryiv = (PFNGLGETQUERYIVPROC)load("glGetQueryiv"); - glad_glGetQueryObjectiv = (PFNGLGETQUERYOBJECTIVPROC)load("glGetQueryObjectiv"); - glad_glGetQueryObjectuiv = (PFNGLGETQUERYOBJECTUIVPROC)load("glGetQueryObjectuiv"); - glad_glBindBuffer = (PFNGLBINDBUFFERPROC)load("glBindBuffer"); - glad_glDeleteBuffers = (PFNGLDELETEBUFFERSPROC)load("glDeleteBuffers"); - glad_glGenBuffers = (PFNGLGENBUFFERSPROC)load("glGenBuffers"); - glad_glIsBuffer = (PFNGLISBUFFERPROC)load("glIsBuffer"); - glad_glBufferData = (PFNGLBUFFERDATAPROC)load("glBufferData"); - glad_glBufferSubData = (PFNGLBUFFERSUBDATAPROC)load("glBufferSubData"); - glad_glGetBufferSubData = (PFNGLGETBUFFERSUBDATAPROC)load("glGetBufferSubData"); - glad_glMapBuffer = (PFNGLMAPBUFFERPROC)load("glMapBuffer"); - glad_glUnmapBuffer = (PFNGLUNMAPBUFFERPROC)load("glUnmapBuffer"); - glad_glGetBufferParameteriv = (PFNGLGETBUFFERPARAMETERIVPROC)load("glGetBufferParameteriv"); - glad_glGetBufferPointerv = (PFNGLGETBUFFERPOINTERVPROC)load("glGetBufferPointerv"); -} -static void load_GL_VERSION_2_0(GLADloadproc load) { - if(!GLAD_GL_VERSION_2_0) return; - glad_glBlendEquationSeparate = (PFNGLBLENDEQUATIONSEPARATEPROC)load("glBlendEquationSeparate"); - glad_glDrawBuffers = (PFNGLDRAWBUFFERSPROC)load("glDrawBuffers"); - glad_glStencilOpSeparate = (PFNGLSTENCILOPSEPARATEPROC)load("glStencilOpSeparate"); - glad_glStencilFuncSeparate = (PFNGLSTENCILFUNCSEPARATEPROC)load("glStencilFuncSeparate"); - glad_glStencilMaskSeparate = (PFNGLSTENCILMASKSEPARATEPROC)load("glStencilMaskSeparate"); - glad_glAttachShader = (PFNGLATTACHSHADERPROC)load("glAttachShader"); - glad_glBindAttribLocation = (PFNGLBINDATTRIBLOCATIONPROC)load("glBindAttribLocation"); - glad_glCompileShader = (PFNGLCOMPILESHADERPROC)load("glCompileShader"); - glad_glCreateProgram = (PFNGLCREATEPROGRAMPROC)load("glCreateProgram"); - glad_glCreateShader = (PFNGLCREATESHADERPROC)load("glCreateShader"); - glad_glDeleteProgram = (PFNGLDELETEPROGRAMPROC)load("glDeleteProgram"); - glad_glDeleteShader = (PFNGLDELETESHADERPROC)load("glDeleteShader"); - glad_glDetachShader = (PFNGLDETACHSHADERPROC)load("glDetachShader"); - glad_glDisableVertexAttribArray = (PFNGLDISABLEVERTEXATTRIBARRAYPROC)load("glDisableVertexAttribArray"); - glad_glEnableVertexAttribArray = (PFNGLENABLEVERTEXATTRIBARRAYPROC)load("glEnableVertexAttribArray"); - glad_glGetActiveAttrib = (PFNGLGETACTIVEATTRIBPROC)load("glGetActiveAttrib"); - glad_glGetActiveUniform = (PFNGLGETACTIVEUNIFORMPROC)load("glGetActiveUniform"); - glad_glGetAttachedShaders = (PFNGLGETATTACHEDSHADERSPROC)load("glGetAttachedShaders"); - glad_glGetAttribLocation = (PFNGLGETATTRIBLOCATIONPROC)load("glGetAttribLocation"); - glad_glGetProgramiv = (PFNGLGETPROGRAMIVPROC)load("glGetProgramiv"); - glad_glGetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC)load("glGetProgramInfoLog"); - glad_glGetShaderiv = (PFNGLGETSHADERIVPROC)load("glGetShaderiv"); - glad_glGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC)load("glGetShaderInfoLog"); - glad_glGetShaderSource = (PFNGLGETSHADERSOURCEPROC)load("glGetShaderSource"); - glad_glGetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC)load("glGetUniformLocation"); - glad_glGetUniformfv = (PFNGLGETUNIFORMFVPROC)load("glGetUniformfv"); - glad_glGetUniformiv = (PFNGLGETUNIFORMIVPROC)load("glGetUniformiv"); - glad_glGetVertexAttribdv = (PFNGLGETVERTEXATTRIBDVPROC)load("glGetVertexAttribdv"); - glad_glGetVertexAttribfv = (PFNGLGETVERTEXATTRIBFVPROC)load("glGetVertexAttribfv"); - glad_glGetVertexAttribiv = (PFNGLGETVERTEXATTRIBIVPROC)load("glGetVertexAttribiv"); - glad_glGetVertexAttribPointerv = (PFNGLGETVERTEXATTRIBPOINTERVPROC)load("glGetVertexAttribPointerv"); - glad_glIsProgram = (PFNGLISPROGRAMPROC)load("glIsProgram"); - glad_glIsShader = (PFNGLISSHADERPROC)load("glIsShader"); - glad_glLinkProgram = (PFNGLLINKPROGRAMPROC)load("glLinkProgram"); - glad_glShaderSource = (PFNGLSHADERSOURCEPROC)load("glShaderSource"); - glad_glUseProgram = (PFNGLUSEPROGRAMPROC)load("glUseProgram"); - glad_glUniform1f = (PFNGLUNIFORM1FPROC)load("glUniform1f"); - glad_glUniform2f = (PFNGLUNIFORM2FPROC)load("glUniform2f"); - glad_glUniform3f = (PFNGLUNIFORM3FPROC)load("glUniform3f"); - glad_glUniform4f = (PFNGLUNIFORM4FPROC)load("glUniform4f"); - glad_glUniform1i = (PFNGLUNIFORM1IPROC)load("glUniform1i"); - glad_glUniform2i = (PFNGLUNIFORM2IPROC)load("glUniform2i"); - glad_glUniform3i = (PFNGLUNIFORM3IPROC)load("glUniform3i"); - glad_glUniform4i = (PFNGLUNIFORM4IPROC)load("glUniform4i"); - glad_glUniform1fv = (PFNGLUNIFORM1FVPROC)load("glUniform1fv"); - glad_glUniform2fv = (PFNGLUNIFORM2FVPROC)load("glUniform2fv"); - glad_glUniform3fv = (PFNGLUNIFORM3FVPROC)load("glUniform3fv"); - glad_glUniform4fv = (PFNGLUNIFORM4FVPROC)load("glUniform4fv"); - glad_glUniform1iv = (PFNGLUNIFORM1IVPROC)load("glUniform1iv"); - glad_glUniform2iv = (PFNGLUNIFORM2IVPROC)load("glUniform2iv"); - glad_glUniform3iv = (PFNGLUNIFORM3IVPROC)load("glUniform3iv"); - glad_glUniform4iv = (PFNGLUNIFORM4IVPROC)load("glUniform4iv"); - glad_glUniformMatrix2fv = (PFNGLUNIFORMMATRIX2FVPROC)load("glUniformMatrix2fv"); - glad_glUniformMatrix3fv = (PFNGLUNIFORMMATRIX3FVPROC)load("glUniformMatrix3fv"); - glad_glUniformMatrix4fv = (PFNGLUNIFORMMATRIX4FVPROC)load("glUniformMatrix4fv"); - glad_glValidateProgram = (PFNGLVALIDATEPROGRAMPROC)load("glValidateProgram"); - glad_glVertexAttrib1d = (PFNGLVERTEXATTRIB1DPROC)load("glVertexAttrib1d"); - glad_glVertexAttrib1dv = (PFNGLVERTEXATTRIB1DVPROC)load("glVertexAttrib1dv"); - glad_glVertexAttrib1f = (PFNGLVERTEXATTRIB1FPROC)load("glVertexAttrib1f"); - glad_glVertexAttrib1fv = (PFNGLVERTEXATTRIB1FVPROC)load("glVertexAttrib1fv"); - glad_glVertexAttrib1s = (PFNGLVERTEXATTRIB1SPROC)load("glVertexAttrib1s"); - glad_glVertexAttrib1sv = (PFNGLVERTEXATTRIB1SVPROC)load("glVertexAttrib1sv"); - glad_glVertexAttrib2d = (PFNGLVERTEXATTRIB2DPROC)load("glVertexAttrib2d"); - glad_glVertexAttrib2dv = (PFNGLVERTEXATTRIB2DVPROC)load("glVertexAttrib2dv"); - glad_glVertexAttrib2f = (PFNGLVERTEXATTRIB2FPROC)load("glVertexAttrib2f"); - glad_glVertexAttrib2fv = (PFNGLVERTEXATTRIB2FVPROC)load("glVertexAttrib2fv"); - glad_glVertexAttrib2s = (PFNGLVERTEXATTRIB2SPROC)load("glVertexAttrib2s"); - glad_glVertexAttrib2sv = (PFNGLVERTEXATTRIB2SVPROC)load("glVertexAttrib2sv"); - glad_glVertexAttrib3d = (PFNGLVERTEXATTRIB3DPROC)load("glVertexAttrib3d"); - glad_glVertexAttrib3dv = (PFNGLVERTEXATTRIB3DVPROC)load("glVertexAttrib3dv"); - glad_glVertexAttrib3f = (PFNGLVERTEXATTRIB3FPROC)load("glVertexAttrib3f"); - glad_glVertexAttrib3fv = (PFNGLVERTEXATTRIB3FVPROC)load("glVertexAttrib3fv"); - glad_glVertexAttrib3s = (PFNGLVERTEXATTRIB3SPROC)load("glVertexAttrib3s"); - glad_glVertexAttrib3sv = (PFNGLVERTEXATTRIB3SVPROC)load("glVertexAttrib3sv"); - glad_glVertexAttrib4Nbv = (PFNGLVERTEXATTRIB4NBVPROC)load("glVertexAttrib4Nbv"); - glad_glVertexAttrib4Niv = (PFNGLVERTEXATTRIB4NIVPROC)load("glVertexAttrib4Niv"); - glad_glVertexAttrib4Nsv = (PFNGLVERTEXATTRIB4NSVPROC)load("glVertexAttrib4Nsv"); - glad_glVertexAttrib4Nub = (PFNGLVERTEXATTRIB4NUBPROC)load("glVertexAttrib4Nub"); - glad_glVertexAttrib4Nubv = (PFNGLVERTEXATTRIB4NUBVPROC)load("glVertexAttrib4Nubv"); - glad_glVertexAttrib4Nuiv = (PFNGLVERTEXATTRIB4NUIVPROC)load("glVertexAttrib4Nuiv"); - glad_glVertexAttrib4Nusv = (PFNGLVERTEXATTRIB4NUSVPROC)load("glVertexAttrib4Nusv"); - glad_glVertexAttrib4bv = (PFNGLVERTEXATTRIB4BVPROC)load("glVertexAttrib4bv"); - glad_glVertexAttrib4d = (PFNGLVERTEXATTRIB4DPROC)load("glVertexAttrib4d"); - glad_glVertexAttrib4dv = (PFNGLVERTEXATTRIB4DVPROC)load("glVertexAttrib4dv"); - glad_glVertexAttrib4f = (PFNGLVERTEXATTRIB4FPROC)load("glVertexAttrib4f"); - glad_glVertexAttrib4fv = (PFNGLVERTEXATTRIB4FVPROC)load("glVertexAttrib4fv"); - glad_glVertexAttrib4iv = (PFNGLVERTEXATTRIB4IVPROC)load("glVertexAttrib4iv"); - glad_glVertexAttrib4s = (PFNGLVERTEXATTRIB4SPROC)load("glVertexAttrib4s"); - glad_glVertexAttrib4sv = (PFNGLVERTEXATTRIB4SVPROC)load("glVertexAttrib4sv"); - glad_glVertexAttrib4ubv = (PFNGLVERTEXATTRIB4UBVPROC)load("glVertexAttrib4ubv"); - glad_glVertexAttrib4uiv = (PFNGLVERTEXATTRIB4UIVPROC)load("glVertexAttrib4uiv"); - glad_glVertexAttrib4usv = (PFNGLVERTEXATTRIB4USVPROC)load("glVertexAttrib4usv"); - glad_glVertexAttribPointer = (PFNGLVERTEXATTRIBPOINTERPROC)load("glVertexAttribPointer"); -} -static void load_GL_VERSION_2_1(GLADloadproc load) { - if(!GLAD_GL_VERSION_2_1) return; - glad_glUniformMatrix2x3fv = (PFNGLUNIFORMMATRIX2X3FVPROC)load("glUniformMatrix2x3fv"); - glad_glUniformMatrix3x2fv = (PFNGLUNIFORMMATRIX3X2FVPROC)load("glUniformMatrix3x2fv"); - glad_glUniformMatrix2x4fv = (PFNGLUNIFORMMATRIX2X4FVPROC)load("glUniformMatrix2x4fv"); - glad_glUniformMatrix4x2fv = (PFNGLUNIFORMMATRIX4X2FVPROC)load("glUniformMatrix4x2fv"); - glad_glUniformMatrix3x4fv = (PFNGLUNIFORMMATRIX3X4FVPROC)load("glUniformMatrix3x4fv"); - glad_glUniformMatrix4x3fv = (PFNGLUNIFORMMATRIX4X3FVPROC)load("glUniformMatrix4x3fv"); -} -static void load_GL_VERSION_3_0(GLADloadproc load) { - if(!GLAD_GL_VERSION_3_0) return; - glad_glColorMaski = (PFNGLCOLORMASKIPROC)load("glColorMaski"); - glad_glGetBooleani_v = (PFNGLGETBOOLEANI_VPROC)load("glGetBooleani_v"); - glad_glGetIntegeri_v = (PFNGLGETINTEGERI_VPROC)load("glGetIntegeri_v"); - glad_glEnablei = (PFNGLENABLEIPROC)load("glEnablei"); - glad_glDisablei = (PFNGLDISABLEIPROC)load("glDisablei"); - glad_glIsEnabledi = (PFNGLISENABLEDIPROC)load("glIsEnabledi"); - glad_glBeginTransformFeedback = (PFNGLBEGINTRANSFORMFEEDBACKPROC)load("glBeginTransformFeedback"); - glad_glEndTransformFeedback = (PFNGLENDTRANSFORMFEEDBACKPROC)load("glEndTransformFeedback"); - glad_glBindBufferRange = (PFNGLBINDBUFFERRANGEPROC)load("glBindBufferRange"); - glad_glBindBufferBase = (PFNGLBINDBUFFERBASEPROC)load("glBindBufferBase"); - glad_glTransformFeedbackVaryings = (PFNGLTRANSFORMFEEDBACKVARYINGSPROC)load("glTransformFeedbackVaryings"); - glad_glGetTransformFeedbackVarying = (PFNGLGETTRANSFORMFEEDBACKVARYINGPROC)load("glGetTransformFeedbackVarying"); - glad_glClampColor = (PFNGLCLAMPCOLORPROC)load("glClampColor"); - glad_glBeginConditionalRender = (PFNGLBEGINCONDITIONALRENDERPROC)load("glBeginConditionalRender"); - glad_glEndConditionalRender = (PFNGLENDCONDITIONALRENDERPROC)load("glEndConditionalRender"); - glad_glVertexAttribIPointer = (PFNGLVERTEXATTRIBIPOINTERPROC)load("glVertexAttribIPointer"); - glad_glGetVertexAttribIiv = (PFNGLGETVERTEXATTRIBIIVPROC)load("glGetVertexAttribIiv"); - glad_glGetVertexAttribIuiv = (PFNGLGETVERTEXATTRIBIUIVPROC)load("glGetVertexAttribIuiv"); - glad_glVertexAttribI1i = (PFNGLVERTEXATTRIBI1IPROC)load("glVertexAttribI1i"); - glad_glVertexAttribI2i = (PFNGLVERTEXATTRIBI2IPROC)load("glVertexAttribI2i"); - glad_glVertexAttribI3i = (PFNGLVERTEXATTRIBI3IPROC)load("glVertexAttribI3i"); - glad_glVertexAttribI4i = (PFNGLVERTEXATTRIBI4IPROC)load("glVertexAttribI4i"); - glad_glVertexAttribI1ui = (PFNGLVERTEXATTRIBI1UIPROC)load("glVertexAttribI1ui"); - glad_glVertexAttribI2ui = (PFNGLVERTEXATTRIBI2UIPROC)load("glVertexAttribI2ui"); - glad_glVertexAttribI3ui = (PFNGLVERTEXATTRIBI3UIPROC)load("glVertexAttribI3ui"); - glad_glVertexAttribI4ui = (PFNGLVERTEXATTRIBI4UIPROC)load("glVertexAttribI4ui"); - glad_glVertexAttribI1iv = (PFNGLVERTEXATTRIBI1IVPROC)load("glVertexAttribI1iv"); - glad_glVertexAttribI2iv = (PFNGLVERTEXATTRIBI2IVPROC)load("glVertexAttribI2iv"); - glad_glVertexAttribI3iv = (PFNGLVERTEXATTRIBI3IVPROC)load("glVertexAttribI3iv"); - glad_glVertexAttribI4iv = (PFNGLVERTEXATTRIBI4IVPROC)load("glVertexAttribI4iv"); - glad_glVertexAttribI1uiv = (PFNGLVERTEXATTRIBI1UIVPROC)load("glVertexAttribI1uiv"); - glad_glVertexAttribI2uiv = (PFNGLVERTEXATTRIBI2UIVPROC)load("glVertexAttribI2uiv"); - glad_glVertexAttribI3uiv = (PFNGLVERTEXATTRIBI3UIVPROC)load("glVertexAttribI3uiv"); - glad_glVertexAttribI4uiv = (PFNGLVERTEXATTRIBI4UIVPROC)load("glVertexAttribI4uiv"); - glad_glVertexAttribI4bv = (PFNGLVERTEXATTRIBI4BVPROC)load("glVertexAttribI4bv"); - glad_glVertexAttribI4sv = (PFNGLVERTEXATTRIBI4SVPROC)load("glVertexAttribI4sv"); - glad_glVertexAttribI4ubv = (PFNGLVERTEXATTRIBI4UBVPROC)load("glVertexAttribI4ubv"); - glad_glVertexAttribI4usv = (PFNGLVERTEXATTRIBI4USVPROC)load("glVertexAttribI4usv"); - glad_glGetUniformuiv = (PFNGLGETUNIFORMUIVPROC)load("glGetUniformuiv"); - glad_glBindFragDataLocation = (PFNGLBINDFRAGDATALOCATIONPROC)load("glBindFragDataLocation"); - glad_glGetFragDataLocation = (PFNGLGETFRAGDATALOCATIONPROC)load("glGetFragDataLocation"); - glad_glUniform1ui = (PFNGLUNIFORM1UIPROC)load("glUniform1ui"); - glad_glUniform2ui = (PFNGLUNIFORM2UIPROC)load("glUniform2ui"); - glad_glUniform3ui = (PFNGLUNIFORM3UIPROC)load("glUniform3ui"); - glad_glUniform4ui = (PFNGLUNIFORM4UIPROC)load("glUniform4ui"); - glad_glUniform1uiv = (PFNGLUNIFORM1UIVPROC)load("glUniform1uiv"); - glad_glUniform2uiv = (PFNGLUNIFORM2UIVPROC)load("glUniform2uiv"); - glad_glUniform3uiv = (PFNGLUNIFORM3UIVPROC)load("glUniform3uiv"); - glad_glUniform4uiv = (PFNGLUNIFORM4UIVPROC)load("glUniform4uiv"); - glad_glTexParameterIiv = (PFNGLTEXPARAMETERIIVPROC)load("glTexParameterIiv"); - glad_glTexParameterIuiv = (PFNGLTEXPARAMETERIUIVPROC)load("glTexParameterIuiv"); - glad_glGetTexParameterIiv = (PFNGLGETTEXPARAMETERIIVPROC)load("glGetTexParameterIiv"); - glad_glGetTexParameterIuiv = (PFNGLGETTEXPARAMETERIUIVPROC)load("glGetTexParameterIuiv"); - glad_glClearBufferiv = (PFNGLCLEARBUFFERIVPROC)load("glClearBufferiv"); - glad_glClearBufferuiv = (PFNGLCLEARBUFFERUIVPROC)load("glClearBufferuiv"); - glad_glClearBufferfv = (PFNGLCLEARBUFFERFVPROC)load("glClearBufferfv"); - glad_glClearBufferfi = (PFNGLCLEARBUFFERFIPROC)load("glClearBufferfi"); - glad_glGetStringi = (PFNGLGETSTRINGIPROC)load("glGetStringi"); - glad_glIsRenderbuffer = (PFNGLISRENDERBUFFERPROC)load("glIsRenderbuffer"); - glad_glBindRenderbuffer = (PFNGLBINDRENDERBUFFERPROC)load("glBindRenderbuffer"); - glad_glDeleteRenderbuffers = (PFNGLDELETERENDERBUFFERSPROC)load("glDeleteRenderbuffers"); - glad_glGenRenderbuffers = (PFNGLGENRENDERBUFFERSPROC)load("glGenRenderbuffers"); - glad_glRenderbufferStorage = (PFNGLRENDERBUFFERSTORAGEPROC)load("glRenderbufferStorage"); - glad_glGetRenderbufferParameteriv = (PFNGLGETRENDERBUFFERPARAMETERIVPROC)load("glGetRenderbufferParameteriv"); - glad_glIsFramebuffer = (PFNGLISFRAMEBUFFERPROC)load("glIsFramebuffer"); - glad_glBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC)load("glBindFramebuffer"); - glad_glDeleteFramebuffers = (PFNGLDELETEFRAMEBUFFERSPROC)load("glDeleteFramebuffers"); - glad_glGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC)load("glGenFramebuffers"); - glad_glCheckFramebufferStatus = (PFNGLCHECKFRAMEBUFFERSTATUSPROC)load("glCheckFramebufferStatus"); - glad_glFramebufferTexture1D = (PFNGLFRAMEBUFFERTEXTURE1DPROC)load("glFramebufferTexture1D"); - glad_glFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC)load("glFramebufferTexture2D"); - glad_glFramebufferTexture3D = (PFNGLFRAMEBUFFERTEXTURE3DPROC)load("glFramebufferTexture3D"); - glad_glFramebufferRenderbuffer = (PFNGLFRAMEBUFFERRENDERBUFFERPROC)load("glFramebufferRenderbuffer"); - glad_glGetFramebufferAttachmentParameteriv = (PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC)load("glGetFramebufferAttachmentParameteriv"); - glad_glGenerateMipmap = (PFNGLGENERATEMIPMAPPROC)load("glGenerateMipmap"); - glad_glBlitFramebuffer = (PFNGLBLITFRAMEBUFFERPROC)load("glBlitFramebuffer"); - glad_glRenderbufferStorageMultisample = (PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC)load("glRenderbufferStorageMultisample"); - glad_glFramebufferTextureLayer = (PFNGLFRAMEBUFFERTEXTURELAYERPROC)load("glFramebufferTextureLayer"); - glad_glMapBufferRange = (PFNGLMAPBUFFERRANGEPROC)load("glMapBufferRange"); - glad_glFlushMappedBufferRange = (PFNGLFLUSHMAPPEDBUFFERRANGEPROC)load("glFlushMappedBufferRange"); - glad_glBindVertexArray = (PFNGLBINDVERTEXARRAYPROC)load("glBindVertexArray"); - glad_glDeleteVertexArrays = (PFNGLDELETEVERTEXARRAYSPROC)load("glDeleteVertexArrays"); - glad_glGenVertexArrays = (PFNGLGENVERTEXARRAYSPROC)load("glGenVertexArrays"); - glad_glIsVertexArray = (PFNGLISVERTEXARRAYPROC)load("glIsVertexArray"); -} -static void load_GL_VERSION_3_1(GLADloadproc load) { - if(!GLAD_GL_VERSION_3_1) return; - glad_glDrawArraysInstanced = (PFNGLDRAWARRAYSINSTANCEDPROC)load("glDrawArraysInstanced"); - glad_glDrawElementsInstanced = (PFNGLDRAWELEMENTSINSTANCEDPROC)load("glDrawElementsInstanced"); - glad_glTexBuffer = (PFNGLTEXBUFFERPROC)load("glTexBuffer"); - glad_glPrimitiveRestartIndex = (PFNGLPRIMITIVERESTARTINDEXPROC)load("glPrimitiveRestartIndex"); - glad_glCopyBufferSubData = (PFNGLCOPYBUFFERSUBDATAPROC)load("glCopyBufferSubData"); - glad_glGetUniformIndices = (PFNGLGETUNIFORMINDICESPROC)load("glGetUniformIndices"); - glad_glGetActiveUniformsiv = (PFNGLGETACTIVEUNIFORMSIVPROC)load("glGetActiveUniformsiv"); - glad_glGetActiveUniformName = (PFNGLGETACTIVEUNIFORMNAMEPROC)load("glGetActiveUniformName"); - glad_glGetUniformBlockIndex = (PFNGLGETUNIFORMBLOCKINDEXPROC)load("glGetUniformBlockIndex"); - glad_glGetActiveUniformBlockiv = (PFNGLGETACTIVEUNIFORMBLOCKIVPROC)load("glGetActiveUniformBlockiv"); - glad_glGetActiveUniformBlockName = (PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC)load("glGetActiveUniformBlockName"); - glad_glUniformBlockBinding = (PFNGLUNIFORMBLOCKBINDINGPROC)load("glUniformBlockBinding"); - glad_glBindBufferRange = (PFNGLBINDBUFFERRANGEPROC)load("glBindBufferRange"); - glad_glBindBufferBase = (PFNGLBINDBUFFERBASEPROC)load("glBindBufferBase"); - glad_glGetIntegeri_v = (PFNGLGETINTEGERI_VPROC)load("glGetIntegeri_v"); -} -static void load_GL_VERSION_3_2(GLADloadproc load) { - if(!GLAD_GL_VERSION_3_2) return; - glad_glDrawElementsBaseVertex = (PFNGLDRAWELEMENTSBASEVERTEXPROC)load("glDrawElementsBaseVertex"); - glad_glDrawRangeElementsBaseVertex = (PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC)load("glDrawRangeElementsBaseVertex"); - glad_glDrawElementsInstancedBaseVertex = (PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC)load("glDrawElementsInstancedBaseVertex"); - glad_glMultiDrawElementsBaseVertex = (PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC)load("glMultiDrawElementsBaseVertex"); - glad_glProvokingVertex = (PFNGLPROVOKINGVERTEXPROC)load("glProvokingVertex"); - glad_glFenceSync = (PFNGLFENCESYNCPROC)load("glFenceSync"); - glad_glIsSync = (PFNGLISSYNCPROC)load("glIsSync"); - glad_glDeleteSync = (PFNGLDELETESYNCPROC)load("glDeleteSync"); - glad_glClientWaitSync = (PFNGLCLIENTWAITSYNCPROC)load("glClientWaitSync"); - glad_glWaitSync = (PFNGLWAITSYNCPROC)load("glWaitSync"); - glad_glGetInteger64v = (PFNGLGETINTEGER64VPROC)load("glGetInteger64v"); - glad_glGetSynciv = (PFNGLGETSYNCIVPROC)load("glGetSynciv"); - glad_glGetInteger64i_v = (PFNGLGETINTEGER64I_VPROC)load("glGetInteger64i_v"); - glad_glGetBufferParameteri64v = (PFNGLGETBUFFERPARAMETERI64VPROC)load("glGetBufferParameteri64v"); - glad_glFramebufferTexture = (PFNGLFRAMEBUFFERTEXTUREPROC)load("glFramebufferTexture"); - glad_glTexImage2DMultisample = (PFNGLTEXIMAGE2DMULTISAMPLEPROC)load("glTexImage2DMultisample"); - glad_glTexImage3DMultisample = (PFNGLTEXIMAGE3DMULTISAMPLEPROC)load("glTexImage3DMultisample"); - glad_glGetMultisamplefv = (PFNGLGETMULTISAMPLEFVPROC)load("glGetMultisamplefv"); - glad_glSampleMaski = (PFNGLSAMPLEMASKIPROC)load("glSampleMaski"); -} -static void load_GL_ARB_multisample(GLADloadproc load) { - if(!GLAD_GL_ARB_multisample) return; - glad_glSampleCoverageARB = (PFNGLSAMPLECOVERAGEARBPROC)load("glSampleCoverageARB"); -} -static void load_GL_ARB_robustness(GLADloadproc load) { - if(!GLAD_GL_ARB_robustness) return; - glad_glGetGraphicsResetStatusARB = (PFNGLGETGRAPHICSRESETSTATUSARBPROC)load("glGetGraphicsResetStatusARB"); - glad_glGetnTexImageARB = (PFNGLGETNTEXIMAGEARBPROC)load("glGetnTexImageARB"); - glad_glReadnPixelsARB = (PFNGLREADNPIXELSARBPROC)load("glReadnPixelsARB"); - glad_glGetnCompressedTexImageARB = (PFNGLGETNCOMPRESSEDTEXIMAGEARBPROC)load("glGetnCompressedTexImageARB"); - glad_glGetnUniformfvARB = (PFNGLGETNUNIFORMFVARBPROC)load("glGetnUniformfvARB"); - glad_glGetnUniformivARB = (PFNGLGETNUNIFORMIVARBPROC)load("glGetnUniformivARB"); - glad_glGetnUniformuivARB = (PFNGLGETNUNIFORMUIVARBPROC)load("glGetnUniformuivARB"); - glad_glGetnUniformdvARB = (PFNGLGETNUNIFORMDVARBPROC)load("glGetnUniformdvARB"); - glad_glGetnMapdvARB = (PFNGLGETNMAPDVARBPROC)load("glGetnMapdvARB"); - glad_glGetnMapfvARB = (PFNGLGETNMAPFVARBPROC)load("glGetnMapfvARB"); - glad_glGetnMapivARB = (PFNGLGETNMAPIVARBPROC)load("glGetnMapivARB"); - glad_glGetnPixelMapfvARB = (PFNGLGETNPIXELMAPFVARBPROC)load("glGetnPixelMapfvARB"); - glad_glGetnPixelMapuivARB = (PFNGLGETNPIXELMAPUIVARBPROC)load("glGetnPixelMapuivARB"); - glad_glGetnPixelMapusvARB = (PFNGLGETNPIXELMAPUSVARBPROC)load("glGetnPixelMapusvARB"); - glad_glGetnPolygonStippleARB = (PFNGLGETNPOLYGONSTIPPLEARBPROC)load("glGetnPolygonStippleARB"); - glad_glGetnColorTableARB = (PFNGLGETNCOLORTABLEARBPROC)load("glGetnColorTableARB"); - glad_glGetnConvolutionFilterARB = (PFNGLGETNCONVOLUTIONFILTERARBPROC)load("glGetnConvolutionFilterARB"); - glad_glGetnSeparableFilterARB = (PFNGLGETNSEPARABLEFILTERARBPROC)load("glGetnSeparableFilterARB"); - glad_glGetnHistogramARB = (PFNGLGETNHISTOGRAMARBPROC)load("glGetnHistogramARB"); - glad_glGetnMinmaxARB = (PFNGLGETNMINMAXARBPROC)load("glGetnMinmaxARB"); -} -static void load_GL_KHR_debug(GLADloadproc load) { - if(!GLAD_GL_KHR_debug) return; - glad_glDebugMessageControl = (PFNGLDEBUGMESSAGECONTROLPROC)load("glDebugMessageControl"); - glad_glDebugMessageInsert = (PFNGLDEBUGMESSAGEINSERTPROC)load("glDebugMessageInsert"); - glad_glDebugMessageCallback = (PFNGLDEBUGMESSAGECALLBACKPROC)load("glDebugMessageCallback"); - glad_glGetDebugMessageLog = (PFNGLGETDEBUGMESSAGELOGPROC)load("glGetDebugMessageLog"); - glad_glPushDebugGroup = (PFNGLPUSHDEBUGGROUPPROC)load("glPushDebugGroup"); - glad_glPopDebugGroup = (PFNGLPOPDEBUGGROUPPROC)load("glPopDebugGroup"); - glad_glObjectLabel = (PFNGLOBJECTLABELPROC)load("glObjectLabel"); - glad_glGetObjectLabel = (PFNGLGETOBJECTLABELPROC)load("glGetObjectLabel"); - glad_glObjectPtrLabel = (PFNGLOBJECTPTRLABELPROC)load("glObjectPtrLabel"); - glad_glGetObjectPtrLabel = (PFNGLGETOBJECTPTRLABELPROC)load("glGetObjectPtrLabel"); - glad_glGetPointerv = (PFNGLGETPOINTERVPROC)load("glGetPointerv"); - glad_glDebugMessageControlKHR = (PFNGLDEBUGMESSAGECONTROLKHRPROC)load("glDebugMessageControlKHR"); - glad_glDebugMessageInsertKHR = (PFNGLDEBUGMESSAGEINSERTKHRPROC)load("glDebugMessageInsertKHR"); - glad_glDebugMessageCallbackKHR = (PFNGLDEBUGMESSAGECALLBACKKHRPROC)load("glDebugMessageCallbackKHR"); - glad_glGetDebugMessageLogKHR = (PFNGLGETDEBUGMESSAGELOGKHRPROC)load("glGetDebugMessageLogKHR"); - glad_glPushDebugGroupKHR = (PFNGLPUSHDEBUGGROUPKHRPROC)load("glPushDebugGroupKHR"); - glad_glPopDebugGroupKHR = (PFNGLPOPDEBUGGROUPKHRPROC)load("glPopDebugGroupKHR"); - glad_glObjectLabelKHR = (PFNGLOBJECTLABELKHRPROC)load("glObjectLabelKHR"); - glad_glGetObjectLabelKHR = (PFNGLGETOBJECTLABELKHRPROC)load("glGetObjectLabelKHR"); - glad_glObjectPtrLabelKHR = (PFNGLOBJECTPTRLABELKHRPROC)load("glObjectPtrLabelKHR"); - glad_glGetObjectPtrLabelKHR = (PFNGLGETOBJECTPTRLABELKHRPROC)load("glGetObjectPtrLabelKHR"); - glad_glGetPointervKHR = (PFNGLGETPOINTERVKHRPROC)load("glGetPointervKHR"); -} -static int find_extensionsGL(void) { - if (!get_exts()) return 0; - GLAD_GL_ARB_multisample = has_ext("GL_ARB_multisample"); - GLAD_GL_ARB_robustness = has_ext("GL_ARB_robustness"); - GLAD_GL_KHR_debug = has_ext("GL_KHR_debug"); - free_exts(); - return 1; -} - -static void find_coreGL(void) { - - /* Thank you @elmindreda - * https://github.com/elmindreda/greg/blob/master/templates/greg.c.in#L176 - * https://github.com/glfw/glfw/blob/master/src/context.c#L36 - */ - int i, major, minor; - - const char* version; - const char* prefixes[] = { - "OpenGL ES-CM ", - "OpenGL ES-CL ", - "OpenGL ES ", - NULL - }; - - version = (const char*) glGetString(GL_VERSION); - if (!version) return; - - for (i = 0; prefixes[i]; i++) { - const size_t length = strlen(prefixes[i]); - if (strncmp(version, prefixes[i], length) == 0) { - version += length; - break; - } - } - -/* PR #18 */ -#ifdef _MSC_VER - sscanf_s(version, "%d.%d", &major, &minor); -#else - sscanf(version, "%d.%d", &major, &minor); -#endif - - GLVersion.major = major; GLVersion.minor = minor; - max_loaded_major = major; max_loaded_minor = minor; - GLAD_GL_VERSION_1_0 = (major == 1 && minor >= 0) || major > 1; - GLAD_GL_VERSION_1_1 = (major == 1 && minor >= 1) || major > 1; - GLAD_GL_VERSION_1_2 = (major == 1 && minor >= 2) || major > 1; - GLAD_GL_VERSION_1_3 = (major == 1 && minor >= 3) || major > 1; - GLAD_GL_VERSION_1_4 = (major == 1 && minor >= 4) || major > 1; - GLAD_GL_VERSION_1_5 = (major == 1 && minor >= 5) || major > 1; - GLAD_GL_VERSION_2_0 = (major == 2 && minor >= 0) || major > 2; - GLAD_GL_VERSION_2_1 = (major == 2 && minor >= 1) || major > 2; - GLAD_GL_VERSION_3_0 = (major == 3 && minor >= 0) || major > 3; - GLAD_GL_VERSION_3_1 = (major == 3 && minor >= 1) || major > 3; - GLAD_GL_VERSION_3_2 = (major == 3 && minor >= 2) || major > 3; - if (GLVersion.major > 3 || (GLVersion.major >= 3 && GLVersion.minor >= 2)) { - max_loaded_major = 3; - max_loaded_minor = 2; - } -} - -int gladLoadGLLoader(GLADloadproc load) { - GLVersion.major = 0; GLVersion.minor = 0; - glGetString = (PFNGLGETSTRINGPROC)load("glGetString"); - if(glGetString == NULL) return 0; - if(glGetString(GL_VERSION) == NULL) return 0; - find_coreGL(); - load_GL_VERSION_1_0(load); - load_GL_VERSION_1_1(load); - load_GL_VERSION_1_2(load); - load_GL_VERSION_1_3(load); - load_GL_VERSION_1_4(load); - load_GL_VERSION_1_5(load); - load_GL_VERSION_2_0(load); - load_GL_VERSION_2_1(load); - load_GL_VERSION_3_0(load); - load_GL_VERSION_3_1(load); - load_GL_VERSION_3_2(load); - - if (!find_extensionsGL()) return 0; - load_GL_ARB_multisample(load); - load_GL_ARB_robustness(load); - load_GL_KHR_debug(load); - return GLVersion.major != 0 || GLVersion.minor != 0; -} - diff --git a/src/external/glfw/deps/glad/gl.h b/src/external/glfw/deps/glad/gl.h new file mode 100644 index 00000000..5c7879f8 --- /dev/null +++ b/src/external/glfw/deps/glad/gl.h @@ -0,0 +1,3840 @@ +/** + * Loader generated by glad 2.0.0-beta on Sun Apr 14 17:03:32 2019 + * + * Generator: C/C++ + * Specification: gl + * Extensions: 3 + * + * APIs: + * - gl:compatibility=3.3 + * + * Options: + * - MX_GLOBAL = False + * - LOADER = False + * - ALIAS = False + * - HEADER_ONLY = False + * - DEBUG = False + * - MX = False + * + * Commandline: + * --api='gl:compatibility=3.3' --extensions='GL_ARB_multisample,GL_ARB_robustness,GL_KHR_debug' c + * + * Online: + * http://glad.sh/#api=gl%3Acompatibility%3D3.3&extensions=GL_ARB_multisample%2CGL_ARB_robustness%2CGL_KHR_debug&generator=c&options= + * + */ + +#ifndef GLAD_GL_H_ +#define GLAD_GL_H_ + +#ifdef __gl_h_ + #error OpenGL header already included (API: gl), remove previous include! +#endif +#define __gl_h_ 1 + + +#define GLAD_GL + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef GLAD_PLATFORM_H_ +#define GLAD_PLATFORM_H_ + +#ifndef GLAD_PLATFORM_WIN32 + #if defined(_WIN32) || defined(__WIN32__) || defined(WIN32) || defined(__MINGW32__) + #define GLAD_PLATFORM_WIN32 1 + #else + #define GLAD_PLATFORM_WIN32 0 + #endif +#endif + +#ifndef GLAD_PLATFORM_APPLE + #ifdef __APPLE__ + #define GLAD_PLATFORM_APPLE 1 + #else + #define GLAD_PLATFORM_APPLE 0 + #endif +#endif + +#ifndef GLAD_PLATFORM_EMSCRIPTEN + #ifdef __EMSCRIPTEN__ + #define GLAD_PLATFORM_EMSCRIPTEN 1 + #else + #define GLAD_PLATFORM_EMSCRIPTEN 0 + #endif +#endif + +#ifndef GLAD_PLATFORM_UWP + #if defined(_MSC_VER) && !defined(GLAD_INTERNAL_HAVE_WINAPIFAMILY) + #ifdef __has_include + #if __has_include() + #define GLAD_INTERNAL_HAVE_WINAPIFAMILY 1 + #endif + #elif _MSC_VER >= 1700 && !_USING_V110_SDK71_ + #define GLAD_INTERNAL_HAVE_WINAPIFAMILY 1 + #endif + #endif + + #ifdef GLAD_INTERNAL_HAVE_WINAPIFAMILY + #include + #if !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) && WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) + #define GLAD_PLATFORM_UWP 1 + #endif + #endif + + #ifndef GLAD_PLATFORM_UWP + #define GLAD_PLATFORM_UWP 0 + #endif +#endif + +#ifdef __GNUC__ + #define GLAD_GNUC_EXTENSION __extension__ +#else + #define GLAD_GNUC_EXTENSION +#endif + +#ifndef GLAD_API_CALL + #if defined(GLAD_API_CALL_EXPORT) + #if GLAD_PLATFORM_WIN32 || defined(__CYGWIN__) + #if defined(GLAD_API_CALL_EXPORT_BUILD) + #if defined(__GNUC__) + #define GLAD_API_CALL __attribute__ ((dllexport)) extern + #else + #define GLAD_API_CALL __declspec(dllexport) extern + #endif + #else + #if defined(__GNUC__) + #define GLAD_API_CALL __attribute__ ((dllimport)) extern + #else + #define GLAD_API_CALL __declspec(dllimport) extern + #endif + #endif + #elif defined(__GNUC__) && defined(GLAD_API_CALL_EXPORT_BUILD) + #define GLAD_API_CALL __attribute__ ((visibility ("default"))) extern + #else + #define GLAD_API_CALL extern + #endif + #else + #define GLAD_API_CALL extern + #endif +#endif + +#ifdef APIENTRY + #define GLAD_API_PTR APIENTRY +#elif GLAD_PLATFORM_WIN32 + #define GLAD_API_PTR __stdcall +#else + #define GLAD_API_PTR +#endif + +#ifndef GLAPI +#define GLAPI GLAD_API_CALL +#endif + +#ifndef GLAPIENTRY +#define GLAPIENTRY GLAD_API_PTR +#endif + + +#define GLAD_MAKE_VERSION(major, minor) (major * 10000 + minor) +#define GLAD_VERSION_MAJOR(version) (version / 10000) +#define GLAD_VERSION_MINOR(version) (version % 10000) + +typedef void (*GLADapiproc)(void); + +typedef GLADapiproc (*GLADloadfunc)(const char *name); +typedef GLADapiproc (*GLADuserptrloadfunc)(const char *name, void *userptr); + +typedef void (*GLADprecallback)(const char *name, GLADapiproc apiproc, int len_args, ...); +typedef void (*GLADpostcallback)(void *ret, const char *name, GLADapiproc apiproc, int len_args, ...); + +#endif /* GLAD_PLATFORM_H_ */ + +#define GL_2D 0x0600 +#define GL_2_BYTES 0x1407 +#define GL_3D 0x0601 +#define GL_3D_COLOR 0x0602 +#define GL_3D_COLOR_TEXTURE 0x0603 +#define GL_3_BYTES 0x1408 +#define GL_4D_COLOR_TEXTURE 0x0604 +#define GL_4_BYTES 0x1409 +#define GL_ACCUM 0x0100 +#define GL_ACCUM_ALPHA_BITS 0x0D5B +#define GL_ACCUM_BLUE_BITS 0x0D5A +#define GL_ACCUM_BUFFER_BIT 0x00000200 +#define GL_ACCUM_CLEAR_VALUE 0x0B80 +#define GL_ACCUM_GREEN_BITS 0x0D59 +#define GL_ACCUM_RED_BITS 0x0D58 +#define GL_ACTIVE_ATTRIBUTES 0x8B89 +#define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH 0x8B8A +#define GL_ACTIVE_TEXTURE 0x84E0 +#define GL_ACTIVE_UNIFORMS 0x8B86 +#define GL_ACTIVE_UNIFORM_BLOCKS 0x8A36 +#define GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH 0x8A35 +#define GL_ACTIVE_UNIFORM_MAX_LENGTH 0x8B87 +#define GL_ADD 0x0104 +#define GL_ADD_SIGNED 0x8574 +#define GL_ALIASED_LINE_WIDTH_RANGE 0x846E +#define GL_ALIASED_POINT_SIZE_RANGE 0x846D +#define GL_ALL_ATTRIB_BITS 0xFFFFFFFF +#define GL_ALPHA 0x1906 +#define GL_ALPHA12 0x803D +#define GL_ALPHA16 0x803E +#define GL_ALPHA4 0x803B +#define GL_ALPHA8 0x803C +#define GL_ALPHA_BIAS 0x0D1D +#define GL_ALPHA_BITS 0x0D55 +#define GL_ALPHA_INTEGER 0x8D97 +#define GL_ALPHA_SCALE 0x0D1C +#define GL_ALPHA_TEST 0x0BC0 +#define GL_ALPHA_TEST_FUNC 0x0BC1 +#define GL_ALPHA_TEST_REF 0x0BC2 +#define GL_ALREADY_SIGNALED 0x911A +#define GL_ALWAYS 0x0207 +#define GL_AMBIENT 0x1200 +#define GL_AMBIENT_AND_DIFFUSE 0x1602 +#define GL_AND 0x1501 +#define GL_AND_INVERTED 0x1504 +#define GL_AND_REVERSE 0x1502 +#define GL_ANY_SAMPLES_PASSED 0x8C2F +#define GL_ARRAY_BUFFER 0x8892 +#define GL_ARRAY_BUFFER_BINDING 0x8894 +#define GL_ATTACHED_SHADERS 0x8B85 +#define GL_ATTRIB_STACK_DEPTH 0x0BB0 +#define GL_AUTO_NORMAL 0x0D80 +#define GL_AUX0 0x0409 +#define GL_AUX1 0x040A +#define GL_AUX2 0x040B +#define GL_AUX3 0x040C +#define GL_AUX_BUFFERS 0x0C00 +#define GL_BACK 0x0405 +#define GL_BACK_LEFT 0x0402 +#define GL_BACK_RIGHT 0x0403 +#define GL_BGR 0x80E0 +#define GL_BGRA 0x80E1 +#define GL_BGRA_INTEGER 0x8D9B +#define GL_BGR_INTEGER 0x8D9A +#define GL_BITMAP 0x1A00 +#define GL_BITMAP_TOKEN 0x0704 +#define GL_BLEND 0x0BE2 +#define GL_BLEND_COLOR 0x8005 +#define GL_BLEND_DST 0x0BE0 +#define GL_BLEND_DST_ALPHA 0x80CA +#define GL_BLEND_DST_RGB 0x80C8 +#define GL_BLEND_EQUATION 0x8009 +#define GL_BLEND_EQUATION_ALPHA 0x883D +#define GL_BLEND_EQUATION_RGB 0x8009 +#define GL_BLEND_SRC 0x0BE1 +#define GL_BLEND_SRC_ALPHA 0x80CB +#define GL_BLEND_SRC_RGB 0x80C9 +#define GL_BLUE 0x1905 +#define GL_BLUE_BIAS 0x0D1B +#define GL_BLUE_BITS 0x0D54 +#define GL_BLUE_INTEGER 0x8D96 +#define GL_BLUE_SCALE 0x0D1A +#define GL_BOOL 0x8B56 +#define GL_BOOL_VEC2 0x8B57 +#define GL_BOOL_VEC3 0x8B58 +#define GL_BOOL_VEC4 0x8B59 +#define GL_BUFFER 0x82E0 +#define GL_BUFFER_ACCESS 0x88BB +#define GL_BUFFER_ACCESS_FLAGS 0x911F +#define GL_BUFFER_MAPPED 0x88BC +#define GL_BUFFER_MAP_LENGTH 0x9120 +#define GL_BUFFER_MAP_OFFSET 0x9121 +#define GL_BUFFER_MAP_POINTER 0x88BD +#define GL_BUFFER_SIZE 0x8764 +#define GL_BUFFER_USAGE 0x8765 +#define GL_BYTE 0x1400 +#define GL_C3F_V3F 0x2A24 +#define GL_C4F_N3F_V3F 0x2A26 +#define GL_C4UB_V2F 0x2A22 +#define GL_C4UB_V3F 0x2A23 +#define GL_CCW 0x0901 +#define GL_CLAMP 0x2900 +#define GL_CLAMP_FRAGMENT_COLOR 0x891B +#define GL_CLAMP_READ_COLOR 0x891C +#define GL_CLAMP_TO_BORDER 0x812D +#define GL_CLAMP_TO_EDGE 0x812F +#define GL_CLAMP_VERTEX_COLOR 0x891A +#define GL_CLEAR 0x1500 +#define GL_CLIENT_ACTIVE_TEXTURE 0x84E1 +#define GL_CLIENT_ALL_ATTRIB_BITS 0xFFFFFFFF +#define GL_CLIENT_ATTRIB_STACK_DEPTH 0x0BB1 +#define GL_CLIENT_PIXEL_STORE_BIT 0x00000001 +#define GL_CLIENT_VERTEX_ARRAY_BIT 0x00000002 +#define GL_CLIP_DISTANCE0 0x3000 +#define GL_CLIP_DISTANCE1 0x3001 +#define GL_CLIP_DISTANCE2 0x3002 +#define GL_CLIP_DISTANCE3 0x3003 +#define GL_CLIP_DISTANCE4 0x3004 +#define GL_CLIP_DISTANCE5 0x3005 +#define GL_CLIP_DISTANCE6 0x3006 +#define GL_CLIP_DISTANCE7 0x3007 +#define GL_CLIP_PLANE0 0x3000 +#define GL_CLIP_PLANE1 0x3001 +#define GL_CLIP_PLANE2 0x3002 +#define GL_CLIP_PLANE3 0x3003 +#define GL_CLIP_PLANE4 0x3004 +#define GL_CLIP_PLANE5 0x3005 +#define GL_COEFF 0x0A00 +#define GL_COLOR 0x1800 +#define GL_COLOR_ARRAY 0x8076 +#define GL_COLOR_ARRAY_BUFFER_BINDING 0x8898 +#define GL_COLOR_ARRAY_POINTER 0x8090 +#define GL_COLOR_ARRAY_SIZE 0x8081 +#define GL_COLOR_ARRAY_STRIDE 0x8083 +#define GL_COLOR_ARRAY_TYPE 0x8082 +#define GL_COLOR_ATTACHMENT0 0x8CE0 +#define GL_COLOR_ATTACHMENT1 0x8CE1 +#define GL_COLOR_ATTACHMENT10 0x8CEA +#define GL_COLOR_ATTACHMENT11 0x8CEB +#define GL_COLOR_ATTACHMENT12 0x8CEC +#define GL_COLOR_ATTACHMENT13 0x8CED +#define GL_COLOR_ATTACHMENT14 0x8CEE +#define GL_COLOR_ATTACHMENT15 0x8CEF +#define GL_COLOR_ATTACHMENT16 0x8CF0 +#define GL_COLOR_ATTACHMENT17 0x8CF1 +#define GL_COLOR_ATTACHMENT18 0x8CF2 +#define GL_COLOR_ATTACHMENT19 0x8CF3 +#define GL_COLOR_ATTACHMENT2 0x8CE2 +#define GL_COLOR_ATTACHMENT20 0x8CF4 +#define GL_COLOR_ATTACHMENT21 0x8CF5 +#define GL_COLOR_ATTACHMENT22 0x8CF6 +#define GL_COLOR_ATTACHMENT23 0x8CF7 +#define GL_COLOR_ATTACHMENT24 0x8CF8 +#define GL_COLOR_ATTACHMENT25 0x8CF9 +#define GL_COLOR_ATTACHMENT26 0x8CFA +#define GL_COLOR_ATTACHMENT27 0x8CFB +#define GL_COLOR_ATTACHMENT28 0x8CFC +#define GL_COLOR_ATTACHMENT29 0x8CFD +#define GL_COLOR_ATTACHMENT3 0x8CE3 +#define GL_COLOR_ATTACHMENT30 0x8CFE +#define GL_COLOR_ATTACHMENT31 0x8CFF +#define GL_COLOR_ATTACHMENT4 0x8CE4 +#define GL_COLOR_ATTACHMENT5 0x8CE5 +#define GL_COLOR_ATTACHMENT6 0x8CE6 +#define GL_COLOR_ATTACHMENT7 0x8CE7 +#define GL_COLOR_ATTACHMENT8 0x8CE8 +#define GL_COLOR_ATTACHMENT9 0x8CE9 +#define GL_COLOR_BUFFER_BIT 0x00004000 +#define GL_COLOR_CLEAR_VALUE 0x0C22 +#define GL_COLOR_INDEX 0x1900 +#define GL_COLOR_INDEXES 0x1603 +#define GL_COLOR_LOGIC_OP 0x0BF2 +#define GL_COLOR_MATERIAL 0x0B57 +#define GL_COLOR_MATERIAL_FACE 0x0B55 +#define GL_COLOR_MATERIAL_PARAMETER 0x0B56 +#define GL_COLOR_SUM 0x8458 +#define GL_COLOR_WRITEMASK 0x0C23 +#define GL_COMBINE 0x8570 +#define GL_COMBINE_ALPHA 0x8572 +#define GL_COMBINE_RGB 0x8571 +#define GL_COMPARE_REF_TO_TEXTURE 0x884E +#define GL_COMPARE_R_TO_TEXTURE 0x884E +#define GL_COMPILE 0x1300 +#define GL_COMPILE_AND_EXECUTE 0x1301 +#define GL_COMPILE_STATUS 0x8B81 +#define GL_COMPRESSED_ALPHA 0x84E9 +#define GL_COMPRESSED_INTENSITY 0x84EC +#define GL_COMPRESSED_LUMINANCE 0x84EA +#define GL_COMPRESSED_LUMINANCE_ALPHA 0x84EB +#define GL_COMPRESSED_RED 0x8225 +#define GL_COMPRESSED_RED_RGTC1 0x8DBB +#define GL_COMPRESSED_RG 0x8226 +#define GL_COMPRESSED_RGB 0x84ED +#define GL_COMPRESSED_RGBA 0x84EE +#define GL_COMPRESSED_RG_RGTC2 0x8DBD +#define GL_COMPRESSED_SIGNED_RED_RGTC1 0x8DBC +#define GL_COMPRESSED_SIGNED_RG_RGTC2 0x8DBE +#define GL_COMPRESSED_SLUMINANCE 0x8C4A +#define GL_COMPRESSED_SLUMINANCE_ALPHA 0x8C4B +#define GL_COMPRESSED_SRGB 0x8C48 +#define GL_COMPRESSED_SRGB_ALPHA 0x8C49 +#define GL_COMPRESSED_TEXTURE_FORMATS 0x86A3 +#define GL_CONDITION_SATISFIED 0x911C +#define GL_CONSTANT 0x8576 +#define GL_CONSTANT_ALPHA 0x8003 +#define GL_CONSTANT_ATTENUATION 0x1207 +#define GL_CONSTANT_COLOR 0x8001 +#define GL_CONTEXT_COMPATIBILITY_PROFILE_BIT 0x00000002 +#define GL_CONTEXT_CORE_PROFILE_BIT 0x00000001 +#define GL_CONTEXT_FLAGS 0x821E +#define GL_CONTEXT_FLAG_DEBUG_BIT 0x00000002 +#define GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT 0x00000001 +#define GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT_ARB 0x00000004 +#define GL_CONTEXT_PROFILE_MASK 0x9126 +#define GL_COORD_REPLACE 0x8862 +#define GL_COPY 0x1503 +#define GL_COPY_INVERTED 0x150C +#define GL_COPY_PIXEL_TOKEN 0x0706 +#define GL_COPY_READ_BUFFER 0x8F36 +#define GL_COPY_WRITE_BUFFER 0x8F37 +#define GL_CULL_FACE 0x0B44 +#define GL_CULL_FACE_MODE 0x0B45 +#define GL_CURRENT_BIT 0x00000001 +#define GL_CURRENT_COLOR 0x0B00 +#define GL_CURRENT_FOG_COORD 0x8453 +#define GL_CURRENT_FOG_COORDINATE 0x8453 +#define GL_CURRENT_INDEX 0x0B01 +#define GL_CURRENT_NORMAL 0x0B02 +#define GL_CURRENT_PROGRAM 0x8B8D +#define GL_CURRENT_QUERY 0x8865 +#define GL_CURRENT_RASTER_COLOR 0x0B04 +#define GL_CURRENT_RASTER_DISTANCE 0x0B09 +#define GL_CURRENT_RASTER_INDEX 0x0B05 +#define GL_CURRENT_RASTER_POSITION 0x0B07 +#define GL_CURRENT_RASTER_POSITION_VALID 0x0B08 +#define GL_CURRENT_RASTER_SECONDARY_COLOR 0x845F +#define GL_CURRENT_RASTER_TEXTURE_COORDS 0x0B06 +#define GL_CURRENT_SECONDARY_COLOR 0x8459 +#define GL_CURRENT_TEXTURE_COORDS 0x0B03 +#define GL_CURRENT_VERTEX_ATTRIB 0x8626 +#define GL_CW 0x0900 +#define GL_DEBUG_CALLBACK_FUNCTION 0x8244 +#define GL_DEBUG_CALLBACK_USER_PARAM 0x8245 +#define GL_DEBUG_GROUP_STACK_DEPTH 0x826D +#define GL_DEBUG_LOGGED_MESSAGES 0x9145 +#define GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH 0x8243 +#define GL_DEBUG_OUTPUT 0x92E0 +#define GL_DEBUG_OUTPUT_SYNCHRONOUS 0x8242 +#define GL_DEBUG_SEVERITY_HIGH 0x9146 +#define GL_DEBUG_SEVERITY_LOW 0x9148 +#define GL_DEBUG_SEVERITY_MEDIUM 0x9147 +#define GL_DEBUG_SEVERITY_NOTIFICATION 0x826B +#define GL_DEBUG_SOURCE_API 0x8246 +#define GL_DEBUG_SOURCE_APPLICATION 0x824A +#define GL_DEBUG_SOURCE_OTHER 0x824B +#define GL_DEBUG_SOURCE_SHADER_COMPILER 0x8248 +#define GL_DEBUG_SOURCE_THIRD_PARTY 0x8249 +#define GL_DEBUG_SOURCE_WINDOW_SYSTEM 0x8247 +#define GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR 0x824D +#define GL_DEBUG_TYPE_ERROR 0x824C +#define GL_DEBUG_TYPE_MARKER 0x8268 +#define GL_DEBUG_TYPE_OTHER 0x8251 +#define GL_DEBUG_TYPE_PERFORMANCE 0x8250 +#define GL_DEBUG_TYPE_POP_GROUP 0x826A +#define GL_DEBUG_TYPE_PORTABILITY 0x824F +#define GL_DEBUG_TYPE_PUSH_GROUP 0x8269 +#define GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR 0x824E +#define GL_DECAL 0x2101 +#define GL_DECR 0x1E03 +#define GL_DECR_WRAP 0x8508 +#define GL_DELETE_STATUS 0x8B80 +#define GL_DEPTH 0x1801 +#define GL_DEPTH24_STENCIL8 0x88F0 +#define GL_DEPTH32F_STENCIL8 0x8CAD +#define GL_DEPTH_ATTACHMENT 0x8D00 +#define GL_DEPTH_BIAS 0x0D1F +#define GL_DEPTH_BITS 0x0D56 +#define GL_DEPTH_BUFFER_BIT 0x00000100 +#define GL_DEPTH_CLAMP 0x864F +#define GL_DEPTH_CLEAR_VALUE 0x0B73 +#define GL_DEPTH_COMPONENT 0x1902 +#define GL_DEPTH_COMPONENT16 0x81A5 +#define GL_DEPTH_COMPONENT24 0x81A6 +#define GL_DEPTH_COMPONENT32 0x81A7 +#define GL_DEPTH_COMPONENT32F 0x8CAC +#define GL_DEPTH_FUNC 0x0B74 +#define GL_DEPTH_RANGE 0x0B70 +#define GL_DEPTH_SCALE 0x0D1E +#define GL_DEPTH_STENCIL 0x84F9 +#define GL_DEPTH_STENCIL_ATTACHMENT 0x821A +#define GL_DEPTH_TEST 0x0B71 +#define GL_DEPTH_TEXTURE_MODE 0x884B +#define GL_DEPTH_WRITEMASK 0x0B72 +#define GL_DIFFUSE 0x1201 +#define GL_DISPLAY_LIST 0x82E7 +#define GL_DITHER 0x0BD0 +#define GL_DOMAIN 0x0A02 +#define GL_DONT_CARE 0x1100 +#define GL_DOT3_RGB 0x86AE +#define GL_DOT3_RGBA 0x86AF +#define GL_DOUBLE 0x140A +#define GL_DOUBLEBUFFER 0x0C32 +#define GL_DRAW_BUFFER 0x0C01 +#define GL_DRAW_BUFFER0 0x8825 +#define GL_DRAW_BUFFER1 0x8826 +#define GL_DRAW_BUFFER10 0x882F +#define GL_DRAW_BUFFER11 0x8830 +#define GL_DRAW_BUFFER12 0x8831 +#define GL_DRAW_BUFFER13 0x8832 +#define GL_DRAW_BUFFER14 0x8833 +#define GL_DRAW_BUFFER15 0x8834 +#define GL_DRAW_BUFFER2 0x8827 +#define GL_DRAW_BUFFER3 0x8828 +#define GL_DRAW_BUFFER4 0x8829 +#define GL_DRAW_BUFFER5 0x882A +#define GL_DRAW_BUFFER6 0x882B +#define GL_DRAW_BUFFER7 0x882C +#define GL_DRAW_BUFFER8 0x882D +#define GL_DRAW_BUFFER9 0x882E +#define GL_DRAW_FRAMEBUFFER 0x8CA9 +#define GL_DRAW_FRAMEBUFFER_BINDING 0x8CA6 +#define GL_DRAW_PIXEL_TOKEN 0x0705 +#define GL_DST_ALPHA 0x0304 +#define GL_DST_COLOR 0x0306 +#define GL_DYNAMIC_COPY 0x88EA +#define GL_DYNAMIC_DRAW 0x88E8 +#define GL_DYNAMIC_READ 0x88E9 +#define GL_EDGE_FLAG 0x0B43 +#define GL_EDGE_FLAG_ARRAY 0x8079 +#define GL_EDGE_FLAG_ARRAY_BUFFER_BINDING 0x889B +#define GL_EDGE_FLAG_ARRAY_POINTER 0x8093 +#define GL_EDGE_FLAG_ARRAY_STRIDE 0x808C +#define GL_ELEMENT_ARRAY_BUFFER 0x8893 +#define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895 +#define GL_EMISSION 0x1600 +#define GL_ENABLE_BIT 0x00002000 +#define GL_EQUAL 0x0202 +#define GL_EQUIV 0x1509 +#define GL_EVAL_BIT 0x00010000 +#define GL_EXP 0x0800 +#define GL_EXP2 0x0801 +#define GL_EXTENSIONS 0x1F03 +#define GL_EYE_LINEAR 0x2400 +#define GL_EYE_PLANE 0x2502 +#define GL_FALSE 0 +#define GL_FASTEST 0x1101 +#define GL_FEEDBACK 0x1C01 +#define GL_FEEDBACK_BUFFER_POINTER 0x0DF0 +#define GL_FEEDBACK_BUFFER_SIZE 0x0DF1 +#define GL_FEEDBACK_BUFFER_TYPE 0x0DF2 +#define GL_FILL 0x1B02 +#define GL_FIRST_VERTEX_CONVENTION 0x8E4D +#define GL_FIXED_ONLY 0x891D +#define GL_FLAT 0x1D00 +#define GL_FLOAT 0x1406 +#define GL_FLOAT_32_UNSIGNED_INT_24_8_REV 0x8DAD +#define GL_FLOAT_MAT2 0x8B5A +#define GL_FLOAT_MAT2x3 0x8B65 +#define GL_FLOAT_MAT2x4 0x8B66 +#define GL_FLOAT_MAT3 0x8B5B +#define GL_FLOAT_MAT3x2 0x8B67 +#define GL_FLOAT_MAT3x4 0x8B68 +#define GL_FLOAT_MAT4 0x8B5C +#define GL_FLOAT_MAT4x2 0x8B69 +#define GL_FLOAT_MAT4x3 0x8B6A +#define GL_FLOAT_VEC2 0x8B50 +#define GL_FLOAT_VEC3 0x8B51 +#define GL_FLOAT_VEC4 0x8B52 +#define GL_FOG 0x0B60 +#define GL_FOG_BIT 0x00000080 +#define GL_FOG_COLOR 0x0B66 +#define GL_FOG_COORD 0x8451 +#define GL_FOG_COORDINATE 0x8451 +#define GL_FOG_COORDINATE_ARRAY 0x8457 +#define GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING 0x889D +#define GL_FOG_COORDINATE_ARRAY_POINTER 0x8456 +#define GL_FOG_COORDINATE_ARRAY_STRIDE 0x8455 +#define GL_FOG_COORDINATE_ARRAY_TYPE 0x8454 +#define GL_FOG_COORDINATE_SOURCE 0x8450 +#define GL_FOG_COORD_ARRAY 0x8457 +#define GL_FOG_COORD_ARRAY_BUFFER_BINDING 0x889D +#define GL_FOG_COORD_ARRAY_POINTER 0x8456 +#define GL_FOG_COORD_ARRAY_STRIDE 0x8455 +#define GL_FOG_COORD_ARRAY_TYPE 0x8454 +#define GL_FOG_COORD_SRC 0x8450 +#define GL_FOG_DENSITY 0x0B62 +#define GL_FOG_END 0x0B64 +#define GL_FOG_HINT 0x0C54 +#define GL_FOG_INDEX 0x0B61 +#define GL_FOG_MODE 0x0B65 +#define GL_FOG_START 0x0B63 +#define GL_FRAGMENT_DEPTH 0x8452 +#define GL_FRAGMENT_SHADER 0x8B30 +#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT 0x8B8B +#define GL_FRAMEBUFFER 0x8D40 +#define GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE 0x8215 +#define GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE 0x8214 +#define GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING 0x8210 +#define GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE 0x8211 +#define GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE 0x8216 +#define GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE 0x8213 +#define GL_FRAMEBUFFER_ATTACHMENT_LAYERED 0x8DA7 +#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME 0x8CD1 +#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE 0x8CD0 +#define GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE 0x8212 +#define GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE 0x8217 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE 0x8CD3 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER 0x8CD4 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL 0x8CD2 +#define GL_FRAMEBUFFER_BINDING 0x8CA6 +#define GL_FRAMEBUFFER_COMPLETE 0x8CD5 +#define GL_FRAMEBUFFER_DEFAULT 0x8218 +#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT 0x8CD6 +#define GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER 0x8CDB +#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS 0x8DA8 +#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT 0x8CD7 +#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE 0x8D56 +#define GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER 0x8CDC +#define GL_FRAMEBUFFER_SRGB 0x8DB9 +#define GL_FRAMEBUFFER_UNDEFINED 0x8219 +#define GL_FRAMEBUFFER_UNSUPPORTED 0x8CDD +#define GL_FRONT 0x0404 +#define GL_FRONT_AND_BACK 0x0408 +#define GL_FRONT_FACE 0x0B46 +#define GL_FRONT_LEFT 0x0400 +#define GL_FRONT_RIGHT 0x0401 +#define GL_FUNC_ADD 0x8006 +#define GL_FUNC_REVERSE_SUBTRACT 0x800B +#define GL_FUNC_SUBTRACT 0x800A +#define GL_GENERATE_MIPMAP 0x8191 +#define GL_GENERATE_MIPMAP_HINT 0x8192 +#define GL_GEOMETRY_INPUT_TYPE 0x8917 +#define GL_GEOMETRY_OUTPUT_TYPE 0x8918 +#define GL_GEOMETRY_SHADER 0x8DD9 +#define GL_GEOMETRY_VERTICES_OUT 0x8916 +#define GL_GEQUAL 0x0206 +#define GL_GREATER 0x0204 +#define GL_GREEN 0x1904 +#define GL_GREEN_BIAS 0x0D19 +#define GL_GREEN_BITS 0x0D53 +#define GL_GREEN_INTEGER 0x8D95 +#define GL_GREEN_SCALE 0x0D18 +#define GL_GUILTY_CONTEXT_RESET_ARB 0x8253 +#define GL_HALF_FLOAT 0x140B +#define GL_HINT_BIT 0x00008000 +#define GL_INCR 0x1E02 +#define GL_INCR_WRAP 0x8507 +#define GL_INDEX 0x8222 +#define GL_INDEX_ARRAY 0x8077 +#define GL_INDEX_ARRAY_BUFFER_BINDING 0x8899 +#define GL_INDEX_ARRAY_POINTER 0x8091 +#define GL_INDEX_ARRAY_STRIDE 0x8086 +#define GL_INDEX_ARRAY_TYPE 0x8085 +#define GL_INDEX_BITS 0x0D51 +#define GL_INDEX_CLEAR_VALUE 0x0C20 +#define GL_INDEX_LOGIC_OP 0x0BF1 +#define GL_INDEX_MODE 0x0C30 +#define GL_INDEX_OFFSET 0x0D13 +#define GL_INDEX_SHIFT 0x0D12 +#define GL_INDEX_WRITEMASK 0x0C21 +#define GL_INFO_LOG_LENGTH 0x8B84 +#define GL_INNOCENT_CONTEXT_RESET_ARB 0x8254 +#define GL_INT 0x1404 +#define GL_INTENSITY 0x8049 +#define GL_INTENSITY12 0x804C +#define GL_INTENSITY16 0x804D +#define GL_INTENSITY4 0x804A +#define GL_INTENSITY8 0x804B +#define GL_INTERLEAVED_ATTRIBS 0x8C8C +#define GL_INTERPOLATE 0x8575 +#define GL_INT_2_10_10_10_REV 0x8D9F +#define GL_INT_SAMPLER_1D 0x8DC9 +#define GL_INT_SAMPLER_1D_ARRAY 0x8DCE +#define GL_INT_SAMPLER_2D 0x8DCA +#define GL_INT_SAMPLER_2D_ARRAY 0x8DCF +#define GL_INT_SAMPLER_2D_MULTISAMPLE 0x9109 +#define GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910C +#define GL_INT_SAMPLER_2D_RECT 0x8DCD +#define GL_INT_SAMPLER_3D 0x8DCB +#define GL_INT_SAMPLER_BUFFER 0x8DD0 +#define GL_INT_SAMPLER_CUBE 0x8DCC +#define GL_INT_VEC2 0x8B53 +#define GL_INT_VEC3 0x8B54 +#define GL_INT_VEC4 0x8B55 +#define GL_INVALID_ENUM 0x0500 +#define GL_INVALID_FRAMEBUFFER_OPERATION 0x0506 +#define GL_INVALID_INDEX 0xFFFFFFFF +#define GL_INVALID_OPERATION 0x0502 +#define GL_INVALID_VALUE 0x0501 +#define GL_INVERT 0x150A +#define GL_KEEP 0x1E00 +#define GL_LAST_VERTEX_CONVENTION 0x8E4E +#define GL_LEFT 0x0406 +#define GL_LEQUAL 0x0203 +#define GL_LESS 0x0201 +#define GL_LIGHT0 0x4000 +#define GL_LIGHT1 0x4001 +#define GL_LIGHT2 0x4002 +#define GL_LIGHT3 0x4003 +#define GL_LIGHT4 0x4004 +#define GL_LIGHT5 0x4005 +#define GL_LIGHT6 0x4006 +#define GL_LIGHT7 0x4007 +#define GL_LIGHTING 0x0B50 +#define GL_LIGHTING_BIT 0x00000040 +#define GL_LIGHT_MODEL_AMBIENT 0x0B53 +#define GL_LIGHT_MODEL_COLOR_CONTROL 0x81F8 +#define GL_LIGHT_MODEL_LOCAL_VIEWER 0x0B51 +#define GL_LIGHT_MODEL_TWO_SIDE 0x0B52 +#define GL_LINE 0x1B01 +#define GL_LINEAR 0x2601 +#define GL_LINEAR_ATTENUATION 0x1208 +#define GL_LINEAR_MIPMAP_LINEAR 0x2703 +#define GL_LINEAR_MIPMAP_NEAREST 0x2701 +#define GL_LINES 0x0001 +#define GL_LINES_ADJACENCY 0x000A +#define GL_LINE_BIT 0x00000004 +#define GL_LINE_LOOP 0x0002 +#define GL_LINE_RESET_TOKEN 0x0707 +#define GL_LINE_SMOOTH 0x0B20 +#define GL_LINE_SMOOTH_HINT 0x0C52 +#define GL_LINE_STIPPLE 0x0B24 +#define GL_LINE_STIPPLE_PATTERN 0x0B25 +#define GL_LINE_STIPPLE_REPEAT 0x0B26 +#define GL_LINE_STRIP 0x0003 +#define GL_LINE_STRIP_ADJACENCY 0x000B +#define GL_LINE_TOKEN 0x0702 +#define GL_LINE_WIDTH 0x0B21 +#define GL_LINE_WIDTH_GRANULARITY 0x0B23 +#define GL_LINE_WIDTH_RANGE 0x0B22 +#define GL_LINK_STATUS 0x8B82 +#define GL_LIST_BASE 0x0B32 +#define GL_LIST_BIT 0x00020000 +#define GL_LIST_INDEX 0x0B33 +#define GL_LIST_MODE 0x0B30 +#define GL_LOAD 0x0101 +#define GL_LOGIC_OP 0x0BF1 +#define GL_LOGIC_OP_MODE 0x0BF0 +#define GL_LOSE_CONTEXT_ON_RESET_ARB 0x8252 +#define GL_LOWER_LEFT 0x8CA1 +#define GL_LUMINANCE 0x1909 +#define GL_LUMINANCE12 0x8041 +#define GL_LUMINANCE12_ALPHA12 0x8047 +#define GL_LUMINANCE12_ALPHA4 0x8046 +#define GL_LUMINANCE16 0x8042 +#define GL_LUMINANCE16_ALPHA16 0x8048 +#define GL_LUMINANCE4 0x803F +#define GL_LUMINANCE4_ALPHA4 0x8043 +#define GL_LUMINANCE6_ALPHA2 0x8044 +#define GL_LUMINANCE8 0x8040 +#define GL_LUMINANCE8_ALPHA8 0x8045 +#define GL_LUMINANCE_ALPHA 0x190A +#define GL_MAJOR_VERSION 0x821B +#define GL_MAP1_COLOR_4 0x0D90 +#define GL_MAP1_GRID_DOMAIN 0x0DD0 +#define GL_MAP1_GRID_SEGMENTS 0x0DD1 +#define GL_MAP1_INDEX 0x0D91 +#define GL_MAP1_NORMAL 0x0D92 +#define GL_MAP1_TEXTURE_COORD_1 0x0D93 +#define GL_MAP1_TEXTURE_COORD_2 0x0D94 +#define GL_MAP1_TEXTURE_COORD_3 0x0D95 +#define GL_MAP1_TEXTURE_COORD_4 0x0D96 +#define GL_MAP1_VERTEX_3 0x0D97 +#define GL_MAP1_VERTEX_4 0x0D98 +#define GL_MAP2_COLOR_4 0x0DB0 +#define GL_MAP2_GRID_DOMAIN 0x0DD2 +#define GL_MAP2_GRID_SEGMENTS 0x0DD3 +#define GL_MAP2_INDEX 0x0DB1 +#define GL_MAP2_NORMAL 0x0DB2 +#define GL_MAP2_TEXTURE_COORD_1 0x0DB3 +#define GL_MAP2_TEXTURE_COORD_2 0x0DB4 +#define GL_MAP2_TEXTURE_COORD_3 0x0DB5 +#define GL_MAP2_TEXTURE_COORD_4 0x0DB6 +#define GL_MAP2_VERTEX_3 0x0DB7 +#define GL_MAP2_VERTEX_4 0x0DB8 +#define GL_MAP_COLOR 0x0D10 +#define GL_MAP_FLUSH_EXPLICIT_BIT 0x0010 +#define GL_MAP_INVALIDATE_BUFFER_BIT 0x0008 +#define GL_MAP_INVALIDATE_RANGE_BIT 0x0004 +#define GL_MAP_READ_BIT 0x0001 +#define GL_MAP_STENCIL 0x0D11 +#define GL_MAP_UNSYNCHRONIZED_BIT 0x0020 +#define GL_MAP_WRITE_BIT 0x0002 +#define GL_MATRIX_MODE 0x0BA0 +#define GL_MAX 0x8008 +#define GL_MAX_3D_TEXTURE_SIZE 0x8073 +#define GL_MAX_ARRAY_TEXTURE_LAYERS 0x88FF +#define GL_MAX_ATTRIB_STACK_DEPTH 0x0D35 +#define GL_MAX_CLIENT_ATTRIB_STACK_DEPTH 0x0D3B +#define GL_MAX_CLIP_DISTANCES 0x0D32 +#define GL_MAX_CLIP_PLANES 0x0D32 +#define GL_MAX_COLOR_ATTACHMENTS 0x8CDF +#define GL_MAX_COLOR_TEXTURE_SAMPLES 0x910E +#define GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS 0x8A33 +#define GL_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS 0x8A32 +#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D +#define GL_MAX_COMBINED_UNIFORM_BLOCKS 0x8A2E +#define GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS 0x8A31 +#define GL_MAX_CUBE_MAP_TEXTURE_SIZE 0x851C +#define GL_MAX_DEBUG_GROUP_STACK_DEPTH 0x826C +#define GL_MAX_DEBUG_LOGGED_MESSAGES 0x9144 +#define GL_MAX_DEBUG_MESSAGE_LENGTH 0x9143 +#define GL_MAX_DEPTH_TEXTURE_SAMPLES 0x910F +#define GL_MAX_DRAW_BUFFERS 0x8824 +#define GL_MAX_DUAL_SOURCE_DRAW_BUFFERS 0x88FC +#define GL_MAX_ELEMENTS_INDICES 0x80E9 +#define GL_MAX_ELEMENTS_VERTICES 0x80E8 +#define GL_MAX_EVAL_ORDER 0x0D30 +#define GL_MAX_FRAGMENT_INPUT_COMPONENTS 0x9125 +#define GL_MAX_FRAGMENT_UNIFORM_BLOCKS 0x8A2D +#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS 0x8B49 +#define GL_MAX_GEOMETRY_INPUT_COMPONENTS 0x9123 +#define GL_MAX_GEOMETRY_OUTPUT_COMPONENTS 0x9124 +#define GL_MAX_GEOMETRY_OUTPUT_VERTICES 0x8DE0 +#define GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS 0x8C29 +#define GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS 0x8DE1 +#define GL_MAX_GEOMETRY_UNIFORM_BLOCKS 0x8A2C +#define GL_MAX_GEOMETRY_UNIFORM_COMPONENTS 0x8DDF +#define GL_MAX_INTEGER_SAMPLES 0x9110 +#define GL_MAX_LABEL_LENGTH 0x82E8 +#define GL_MAX_LIGHTS 0x0D31 +#define GL_MAX_LIST_NESTING 0x0B31 +#define GL_MAX_MODELVIEW_STACK_DEPTH 0x0D36 +#define GL_MAX_NAME_STACK_DEPTH 0x0D37 +#define GL_MAX_PIXEL_MAP_TABLE 0x0D34 +#define GL_MAX_PROGRAM_TEXEL_OFFSET 0x8905 +#define GL_MAX_PROJECTION_STACK_DEPTH 0x0D38 +#define GL_MAX_RECTANGLE_TEXTURE_SIZE 0x84F8 +#define GL_MAX_RENDERBUFFER_SIZE 0x84E8 +#define GL_MAX_SAMPLES 0x8D57 +#define GL_MAX_SAMPLE_MASK_WORDS 0x8E59 +#define GL_MAX_SERVER_WAIT_TIMEOUT 0x9111 +#define GL_MAX_TEXTURE_BUFFER_SIZE 0x8C2B +#define GL_MAX_TEXTURE_COORDS 0x8871 +#define GL_MAX_TEXTURE_IMAGE_UNITS 0x8872 +#define GL_MAX_TEXTURE_LOD_BIAS 0x84FD +#define GL_MAX_TEXTURE_SIZE 0x0D33 +#define GL_MAX_TEXTURE_STACK_DEPTH 0x0D39 +#define GL_MAX_TEXTURE_UNITS 0x84E2 +#define GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS 0x8C8A +#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS 0x8C8B +#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS 0x8C80 +#define GL_MAX_UNIFORM_BLOCK_SIZE 0x8A30 +#define GL_MAX_UNIFORM_BUFFER_BINDINGS 0x8A2F +#define GL_MAX_VARYING_COMPONENTS 0x8B4B +#define GL_MAX_VARYING_FLOATS 0x8B4B +#define GL_MAX_VERTEX_ATTRIBS 0x8869 +#define GL_MAX_VERTEX_OUTPUT_COMPONENTS 0x9122 +#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS 0x8B4C +#define GL_MAX_VERTEX_UNIFORM_BLOCKS 0x8A2B +#define GL_MAX_VERTEX_UNIFORM_COMPONENTS 0x8B4A +#define GL_MAX_VIEWPORT_DIMS 0x0D3A +#define GL_MIN 0x8007 +#define GL_MINOR_VERSION 0x821C +#define GL_MIN_PROGRAM_TEXEL_OFFSET 0x8904 +#define GL_MIRRORED_REPEAT 0x8370 +#define GL_MODELVIEW 0x1700 +#define GL_MODELVIEW_MATRIX 0x0BA6 +#define GL_MODELVIEW_STACK_DEPTH 0x0BA3 +#define GL_MODULATE 0x2100 +#define GL_MULT 0x0103 +#define GL_MULTISAMPLE 0x809D +#define GL_MULTISAMPLE_ARB 0x809D +#define GL_MULTISAMPLE_BIT 0x20000000 +#define GL_MULTISAMPLE_BIT_ARB 0x20000000 +#define GL_N3F_V3F 0x2A25 +#define GL_NAME_STACK_DEPTH 0x0D70 +#define GL_NAND 0x150E +#define GL_NEAREST 0x2600 +#define GL_NEAREST_MIPMAP_LINEAR 0x2702 +#define GL_NEAREST_MIPMAP_NEAREST 0x2700 +#define GL_NEVER 0x0200 +#define GL_NICEST 0x1102 +#define GL_NONE 0 +#define GL_NOOP 0x1505 +#define GL_NOR 0x1508 +#define GL_NORMALIZE 0x0BA1 +#define GL_NORMAL_ARRAY 0x8075 +#define GL_NORMAL_ARRAY_BUFFER_BINDING 0x8897 +#define GL_NORMAL_ARRAY_POINTER 0x808F +#define GL_NORMAL_ARRAY_STRIDE 0x807F +#define GL_NORMAL_ARRAY_TYPE 0x807E +#define GL_NORMAL_MAP 0x8511 +#define GL_NOTEQUAL 0x0205 +#define GL_NO_ERROR 0 +#define GL_NO_RESET_NOTIFICATION_ARB 0x8261 +#define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2 +#define GL_NUM_EXTENSIONS 0x821D +#define GL_OBJECT_LINEAR 0x2401 +#define GL_OBJECT_PLANE 0x2501 +#define GL_OBJECT_TYPE 0x9112 +#define GL_ONE 1 +#define GL_ONE_MINUS_CONSTANT_ALPHA 0x8004 +#define GL_ONE_MINUS_CONSTANT_COLOR 0x8002 +#define GL_ONE_MINUS_DST_ALPHA 0x0305 +#define GL_ONE_MINUS_DST_COLOR 0x0307 +#define GL_ONE_MINUS_SRC1_ALPHA 0x88FB +#define GL_ONE_MINUS_SRC1_COLOR 0x88FA +#define GL_ONE_MINUS_SRC_ALPHA 0x0303 +#define GL_ONE_MINUS_SRC_COLOR 0x0301 +#define GL_OPERAND0_ALPHA 0x8598 +#define GL_OPERAND0_RGB 0x8590 +#define GL_OPERAND1_ALPHA 0x8599 +#define GL_OPERAND1_RGB 0x8591 +#define GL_OPERAND2_ALPHA 0x859A +#define GL_OPERAND2_RGB 0x8592 +#define GL_OR 0x1507 +#define GL_ORDER 0x0A01 +#define GL_OR_INVERTED 0x150D +#define GL_OR_REVERSE 0x150B +#define GL_OUT_OF_MEMORY 0x0505 +#define GL_PACK_ALIGNMENT 0x0D05 +#define GL_PACK_IMAGE_HEIGHT 0x806C +#define GL_PACK_LSB_FIRST 0x0D01 +#define GL_PACK_ROW_LENGTH 0x0D02 +#define GL_PACK_SKIP_IMAGES 0x806B +#define GL_PACK_SKIP_PIXELS 0x0D04 +#define GL_PACK_SKIP_ROWS 0x0D03 +#define GL_PACK_SWAP_BYTES 0x0D00 +#define GL_PASS_THROUGH_TOKEN 0x0700 +#define GL_PERSPECTIVE_CORRECTION_HINT 0x0C50 +#define GL_PIXEL_MAP_A_TO_A 0x0C79 +#define GL_PIXEL_MAP_A_TO_A_SIZE 0x0CB9 +#define GL_PIXEL_MAP_B_TO_B 0x0C78 +#define GL_PIXEL_MAP_B_TO_B_SIZE 0x0CB8 +#define GL_PIXEL_MAP_G_TO_G 0x0C77 +#define GL_PIXEL_MAP_G_TO_G_SIZE 0x0CB7 +#define GL_PIXEL_MAP_I_TO_A 0x0C75 +#define GL_PIXEL_MAP_I_TO_A_SIZE 0x0CB5 +#define GL_PIXEL_MAP_I_TO_B 0x0C74 +#define GL_PIXEL_MAP_I_TO_B_SIZE 0x0CB4 +#define GL_PIXEL_MAP_I_TO_G 0x0C73 +#define GL_PIXEL_MAP_I_TO_G_SIZE 0x0CB3 +#define GL_PIXEL_MAP_I_TO_I 0x0C70 +#define GL_PIXEL_MAP_I_TO_I_SIZE 0x0CB0 +#define GL_PIXEL_MAP_I_TO_R 0x0C72 +#define GL_PIXEL_MAP_I_TO_R_SIZE 0x0CB2 +#define GL_PIXEL_MAP_R_TO_R 0x0C76 +#define GL_PIXEL_MAP_R_TO_R_SIZE 0x0CB6 +#define GL_PIXEL_MAP_S_TO_S 0x0C71 +#define GL_PIXEL_MAP_S_TO_S_SIZE 0x0CB1 +#define GL_PIXEL_MODE_BIT 0x00000020 +#define GL_PIXEL_PACK_BUFFER 0x88EB +#define GL_PIXEL_PACK_BUFFER_BINDING 0x88ED +#define GL_PIXEL_UNPACK_BUFFER 0x88EC +#define GL_PIXEL_UNPACK_BUFFER_BINDING 0x88EF +#define GL_POINT 0x1B00 +#define GL_POINTS 0x0000 +#define GL_POINT_BIT 0x00000002 +#define GL_POINT_DISTANCE_ATTENUATION 0x8129 +#define GL_POINT_FADE_THRESHOLD_SIZE 0x8128 +#define GL_POINT_SIZE 0x0B11 +#define GL_POINT_SIZE_GRANULARITY 0x0B13 +#define GL_POINT_SIZE_MAX 0x8127 +#define GL_POINT_SIZE_MIN 0x8126 +#define GL_POINT_SIZE_RANGE 0x0B12 +#define GL_POINT_SMOOTH 0x0B10 +#define GL_POINT_SMOOTH_HINT 0x0C51 +#define GL_POINT_SPRITE 0x8861 +#define GL_POINT_SPRITE_COORD_ORIGIN 0x8CA0 +#define GL_POINT_TOKEN 0x0701 +#define GL_POLYGON 0x0009 +#define GL_POLYGON_BIT 0x00000008 +#define GL_POLYGON_MODE 0x0B40 +#define GL_POLYGON_OFFSET_FACTOR 0x8038 +#define GL_POLYGON_OFFSET_FILL 0x8037 +#define GL_POLYGON_OFFSET_LINE 0x2A02 +#define GL_POLYGON_OFFSET_POINT 0x2A01 +#define GL_POLYGON_OFFSET_UNITS 0x2A00 +#define GL_POLYGON_SMOOTH 0x0B41 +#define GL_POLYGON_SMOOTH_HINT 0x0C53 +#define GL_POLYGON_STIPPLE 0x0B42 +#define GL_POLYGON_STIPPLE_BIT 0x00000010 +#define GL_POLYGON_TOKEN 0x0703 +#define GL_POSITION 0x1203 +#define GL_PREVIOUS 0x8578 +#define GL_PRIMARY_COLOR 0x8577 +#define GL_PRIMITIVES_GENERATED 0x8C87 +#define GL_PRIMITIVE_RESTART 0x8F9D +#define GL_PRIMITIVE_RESTART_INDEX 0x8F9E +#define GL_PROGRAM 0x82E2 +#define GL_PROGRAM_PIPELINE 0x82E4 +#define GL_PROGRAM_POINT_SIZE 0x8642 +#define GL_PROJECTION 0x1701 +#define GL_PROJECTION_MATRIX 0x0BA7 +#define GL_PROJECTION_STACK_DEPTH 0x0BA4 +#define GL_PROVOKING_VERTEX 0x8E4F +#define GL_PROXY_TEXTURE_1D 0x8063 +#define GL_PROXY_TEXTURE_1D_ARRAY 0x8C19 +#define GL_PROXY_TEXTURE_2D 0x8064 +#define GL_PROXY_TEXTURE_2D_ARRAY 0x8C1B +#define GL_PROXY_TEXTURE_2D_MULTISAMPLE 0x9101 +#define GL_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY 0x9103 +#define GL_PROXY_TEXTURE_3D 0x8070 +#define GL_PROXY_TEXTURE_CUBE_MAP 0x851B +#define GL_PROXY_TEXTURE_RECTANGLE 0x84F7 +#define GL_Q 0x2003 +#define GL_QUADRATIC_ATTENUATION 0x1209 +#define GL_QUADS 0x0007 +#define GL_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION 0x8E4C +#define GL_QUAD_STRIP 0x0008 +#define GL_QUERY 0x82E3 +#define GL_QUERY_BY_REGION_NO_WAIT 0x8E16 +#define GL_QUERY_BY_REGION_WAIT 0x8E15 +#define GL_QUERY_COUNTER_BITS 0x8864 +#define GL_QUERY_NO_WAIT 0x8E14 +#define GL_QUERY_RESULT 0x8866 +#define GL_QUERY_RESULT_AVAILABLE 0x8867 +#define GL_QUERY_WAIT 0x8E13 +#define GL_R 0x2002 +#define GL_R11F_G11F_B10F 0x8C3A +#define GL_R16 0x822A +#define GL_R16F 0x822D +#define GL_R16I 0x8233 +#define GL_R16UI 0x8234 +#define GL_R16_SNORM 0x8F98 +#define GL_R32F 0x822E +#define GL_R32I 0x8235 +#define GL_R32UI 0x8236 +#define GL_R3_G3_B2 0x2A10 +#define GL_R8 0x8229 +#define GL_R8I 0x8231 +#define GL_R8UI 0x8232 +#define GL_R8_SNORM 0x8F94 +#define GL_RASTERIZER_DISCARD 0x8C89 +#define GL_READ_BUFFER 0x0C02 +#define GL_READ_FRAMEBUFFER 0x8CA8 +#define GL_READ_FRAMEBUFFER_BINDING 0x8CAA +#define GL_READ_ONLY 0x88B8 +#define GL_READ_WRITE 0x88BA +#define GL_RED 0x1903 +#define GL_RED_BIAS 0x0D15 +#define GL_RED_BITS 0x0D52 +#define GL_RED_INTEGER 0x8D94 +#define GL_RED_SCALE 0x0D14 +#define GL_REFLECTION_MAP 0x8512 +#define GL_RENDER 0x1C00 +#define GL_RENDERBUFFER 0x8D41 +#define GL_RENDERBUFFER_ALPHA_SIZE 0x8D53 +#define GL_RENDERBUFFER_BINDING 0x8CA7 +#define GL_RENDERBUFFER_BLUE_SIZE 0x8D52 +#define GL_RENDERBUFFER_DEPTH_SIZE 0x8D54 +#define GL_RENDERBUFFER_GREEN_SIZE 0x8D51 +#define GL_RENDERBUFFER_HEIGHT 0x8D43 +#define GL_RENDERBUFFER_INTERNAL_FORMAT 0x8D44 +#define GL_RENDERBUFFER_RED_SIZE 0x8D50 +#define GL_RENDERBUFFER_SAMPLES 0x8CAB +#define GL_RENDERBUFFER_STENCIL_SIZE 0x8D55 +#define GL_RENDERBUFFER_WIDTH 0x8D42 +#define GL_RENDERER 0x1F01 +#define GL_RENDER_MODE 0x0C40 +#define GL_REPEAT 0x2901 +#define GL_REPLACE 0x1E01 +#define GL_RESCALE_NORMAL 0x803A +#define GL_RESET_NOTIFICATION_STRATEGY_ARB 0x8256 +#define GL_RETURN 0x0102 +#define GL_RG 0x8227 +#define GL_RG16 0x822C +#define GL_RG16F 0x822F +#define GL_RG16I 0x8239 +#define GL_RG16UI 0x823A +#define GL_RG16_SNORM 0x8F99 +#define GL_RG32F 0x8230 +#define GL_RG32I 0x823B +#define GL_RG32UI 0x823C +#define GL_RG8 0x822B +#define GL_RG8I 0x8237 +#define GL_RG8UI 0x8238 +#define GL_RG8_SNORM 0x8F95 +#define GL_RGB 0x1907 +#define GL_RGB10 0x8052 +#define GL_RGB10_A2 0x8059 +#define GL_RGB10_A2UI 0x906F +#define GL_RGB12 0x8053 +#define GL_RGB16 0x8054 +#define GL_RGB16F 0x881B +#define GL_RGB16I 0x8D89 +#define GL_RGB16UI 0x8D77 +#define GL_RGB16_SNORM 0x8F9A +#define GL_RGB32F 0x8815 +#define GL_RGB32I 0x8D83 +#define GL_RGB32UI 0x8D71 +#define GL_RGB4 0x804F +#define GL_RGB5 0x8050 +#define GL_RGB5_A1 0x8057 +#define GL_RGB8 0x8051 +#define GL_RGB8I 0x8D8F +#define GL_RGB8UI 0x8D7D +#define GL_RGB8_SNORM 0x8F96 +#define GL_RGB9_E5 0x8C3D +#define GL_RGBA 0x1908 +#define GL_RGBA12 0x805A +#define GL_RGBA16 0x805B +#define GL_RGBA16F 0x881A +#define GL_RGBA16I 0x8D88 +#define GL_RGBA16UI 0x8D76 +#define GL_RGBA16_SNORM 0x8F9B +#define GL_RGBA2 0x8055 +#define GL_RGBA32F 0x8814 +#define GL_RGBA32I 0x8D82 +#define GL_RGBA32UI 0x8D70 +#define GL_RGBA4 0x8056 +#define GL_RGBA8 0x8058 +#define GL_RGBA8I 0x8D8E +#define GL_RGBA8UI 0x8D7C +#define GL_RGBA8_SNORM 0x8F97 +#define GL_RGBA_INTEGER 0x8D99 +#define GL_RGBA_MODE 0x0C31 +#define GL_RGB_INTEGER 0x8D98 +#define GL_RGB_SCALE 0x8573 +#define GL_RG_INTEGER 0x8228 +#define GL_RIGHT 0x0407 +#define GL_S 0x2000 +#define GL_SAMPLER 0x82E6 +#define GL_SAMPLER_1D 0x8B5D +#define GL_SAMPLER_1D_ARRAY 0x8DC0 +#define GL_SAMPLER_1D_ARRAY_SHADOW 0x8DC3 +#define GL_SAMPLER_1D_SHADOW 0x8B61 +#define GL_SAMPLER_2D 0x8B5E +#define GL_SAMPLER_2D_ARRAY 0x8DC1 +#define GL_SAMPLER_2D_ARRAY_SHADOW 0x8DC4 +#define GL_SAMPLER_2D_MULTISAMPLE 0x9108 +#define GL_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910B +#define GL_SAMPLER_2D_RECT 0x8B63 +#define GL_SAMPLER_2D_RECT_SHADOW 0x8B64 +#define GL_SAMPLER_2D_SHADOW 0x8B62 +#define GL_SAMPLER_3D 0x8B5F +#define GL_SAMPLER_BINDING 0x8919 +#define GL_SAMPLER_BUFFER 0x8DC2 +#define GL_SAMPLER_CUBE 0x8B60 +#define GL_SAMPLER_CUBE_SHADOW 0x8DC5 +#define GL_SAMPLES 0x80A9 +#define GL_SAMPLES_ARB 0x80A9 +#define GL_SAMPLES_PASSED 0x8914 +#define GL_SAMPLE_ALPHA_TO_COVERAGE 0x809E +#define GL_SAMPLE_ALPHA_TO_COVERAGE_ARB 0x809E +#define GL_SAMPLE_ALPHA_TO_ONE 0x809F +#define GL_SAMPLE_ALPHA_TO_ONE_ARB 0x809F +#define GL_SAMPLE_BUFFERS 0x80A8 +#define GL_SAMPLE_BUFFERS_ARB 0x80A8 +#define GL_SAMPLE_COVERAGE 0x80A0 +#define GL_SAMPLE_COVERAGE_ARB 0x80A0 +#define GL_SAMPLE_COVERAGE_INVERT 0x80AB +#define GL_SAMPLE_COVERAGE_INVERT_ARB 0x80AB +#define GL_SAMPLE_COVERAGE_VALUE 0x80AA +#define GL_SAMPLE_COVERAGE_VALUE_ARB 0x80AA +#define GL_SAMPLE_MASK 0x8E51 +#define GL_SAMPLE_MASK_VALUE 0x8E52 +#define GL_SAMPLE_POSITION 0x8E50 +#define GL_SCISSOR_BIT 0x00080000 +#define GL_SCISSOR_BOX 0x0C10 +#define GL_SCISSOR_TEST 0x0C11 +#define GL_SECONDARY_COLOR_ARRAY 0x845E +#define GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING 0x889C +#define GL_SECONDARY_COLOR_ARRAY_POINTER 0x845D +#define GL_SECONDARY_COLOR_ARRAY_SIZE 0x845A +#define GL_SECONDARY_COLOR_ARRAY_STRIDE 0x845C +#define GL_SECONDARY_COLOR_ARRAY_TYPE 0x845B +#define GL_SELECT 0x1C02 +#define GL_SELECTION_BUFFER_POINTER 0x0DF3 +#define GL_SELECTION_BUFFER_SIZE 0x0DF4 +#define GL_SEPARATE_ATTRIBS 0x8C8D +#define GL_SEPARATE_SPECULAR_COLOR 0x81FA +#define GL_SET 0x150F +#define GL_SHADER 0x82E1 +#define GL_SHADER_SOURCE_LENGTH 0x8B88 +#define GL_SHADER_TYPE 0x8B4F +#define GL_SHADE_MODEL 0x0B54 +#define GL_SHADING_LANGUAGE_VERSION 0x8B8C +#define GL_SHININESS 0x1601 +#define GL_SHORT 0x1402 +#define GL_SIGNALED 0x9119 +#define GL_SIGNED_NORMALIZED 0x8F9C +#define GL_SINGLE_COLOR 0x81F9 +#define GL_SLUMINANCE 0x8C46 +#define GL_SLUMINANCE8 0x8C47 +#define GL_SLUMINANCE8_ALPHA8 0x8C45 +#define GL_SLUMINANCE_ALPHA 0x8C44 +#define GL_SMOOTH 0x1D01 +#define GL_SMOOTH_LINE_WIDTH_GRANULARITY 0x0B23 +#define GL_SMOOTH_LINE_WIDTH_RANGE 0x0B22 +#define GL_SMOOTH_POINT_SIZE_GRANULARITY 0x0B13 +#define GL_SMOOTH_POINT_SIZE_RANGE 0x0B12 +#define GL_SOURCE0_ALPHA 0x8588 +#define GL_SOURCE0_RGB 0x8580 +#define GL_SOURCE1_ALPHA 0x8589 +#define GL_SOURCE1_RGB 0x8581 +#define GL_SOURCE2_ALPHA 0x858A +#define GL_SOURCE2_RGB 0x8582 +#define GL_SPECULAR 0x1202 +#define GL_SPHERE_MAP 0x2402 +#define GL_SPOT_CUTOFF 0x1206 +#define GL_SPOT_DIRECTION 0x1204 +#define GL_SPOT_EXPONENT 0x1205 +#define GL_SRC0_ALPHA 0x8588 +#define GL_SRC0_RGB 0x8580 +#define GL_SRC1_ALPHA 0x8589 +#define GL_SRC1_COLOR 0x88F9 +#define GL_SRC1_RGB 0x8581 +#define GL_SRC2_ALPHA 0x858A +#define GL_SRC2_RGB 0x8582 +#define GL_SRC_ALPHA 0x0302 +#define GL_SRC_ALPHA_SATURATE 0x0308 +#define GL_SRC_COLOR 0x0300 +#define GL_SRGB 0x8C40 +#define GL_SRGB8 0x8C41 +#define GL_SRGB8_ALPHA8 0x8C43 +#define GL_SRGB_ALPHA 0x8C42 +#define GL_STACK_OVERFLOW 0x0503 +#define GL_STACK_UNDERFLOW 0x0504 +#define GL_STATIC_COPY 0x88E6 +#define GL_STATIC_DRAW 0x88E4 +#define GL_STATIC_READ 0x88E5 +#define GL_STENCIL 0x1802 +#define GL_STENCIL_ATTACHMENT 0x8D20 +#define GL_STENCIL_BACK_FAIL 0x8801 +#define GL_STENCIL_BACK_FUNC 0x8800 +#define GL_STENCIL_BACK_PASS_DEPTH_FAIL 0x8802 +#define GL_STENCIL_BACK_PASS_DEPTH_PASS 0x8803 +#define GL_STENCIL_BACK_REF 0x8CA3 +#define GL_STENCIL_BACK_VALUE_MASK 0x8CA4 +#define GL_STENCIL_BACK_WRITEMASK 0x8CA5 +#define GL_STENCIL_BITS 0x0D57 +#define GL_STENCIL_BUFFER_BIT 0x00000400 +#define GL_STENCIL_CLEAR_VALUE 0x0B91 +#define GL_STENCIL_FAIL 0x0B94 +#define GL_STENCIL_FUNC 0x0B92 +#define GL_STENCIL_INDEX 0x1901 +#define GL_STENCIL_INDEX1 0x8D46 +#define GL_STENCIL_INDEX16 0x8D49 +#define GL_STENCIL_INDEX4 0x8D47 +#define GL_STENCIL_INDEX8 0x8D48 +#define GL_STENCIL_PASS_DEPTH_FAIL 0x0B95 +#define GL_STENCIL_PASS_DEPTH_PASS 0x0B96 +#define GL_STENCIL_REF 0x0B97 +#define GL_STENCIL_TEST 0x0B90 +#define GL_STENCIL_VALUE_MASK 0x0B93 +#define GL_STENCIL_WRITEMASK 0x0B98 +#define GL_STEREO 0x0C33 +#define GL_STREAM_COPY 0x88E2 +#define GL_STREAM_DRAW 0x88E0 +#define GL_STREAM_READ 0x88E1 +#define GL_SUBPIXEL_BITS 0x0D50 +#define GL_SUBTRACT 0x84E7 +#define GL_SYNC_CONDITION 0x9113 +#define GL_SYNC_FENCE 0x9116 +#define GL_SYNC_FLAGS 0x9115 +#define GL_SYNC_FLUSH_COMMANDS_BIT 0x00000001 +#define GL_SYNC_GPU_COMMANDS_COMPLETE 0x9117 +#define GL_SYNC_STATUS 0x9114 +#define GL_T 0x2001 +#define GL_T2F_C3F_V3F 0x2A2A +#define GL_T2F_C4F_N3F_V3F 0x2A2C +#define GL_T2F_C4UB_V3F 0x2A29 +#define GL_T2F_N3F_V3F 0x2A2B +#define GL_T2F_V3F 0x2A27 +#define GL_T4F_C4F_N3F_V4F 0x2A2D +#define GL_T4F_V4F 0x2A28 +#define GL_TEXTURE 0x1702 +#define GL_TEXTURE0 0x84C0 +#define GL_TEXTURE1 0x84C1 +#define GL_TEXTURE10 0x84CA +#define GL_TEXTURE11 0x84CB +#define GL_TEXTURE12 0x84CC +#define GL_TEXTURE13 0x84CD +#define GL_TEXTURE14 0x84CE +#define GL_TEXTURE15 0x84CF +#define GL_TEXTURE16 0x84D0 +#define GL_TEXTURE17 0x84D1 +#define GL_TEXTURE18 0x84D2 +#define GL_TEXTURE19 0x84D3 +#define GL_TEXTURE2 0x84C2 +#define GL_TEXTURE20 0x84D4 +#define GL_TEXTURE21 0x84D5 +#define GL_TEXTURE22 0x84D6 +#define GL_TEXTURE23 0x84D7 +#define GL_TEXTURE24 0x84D8 +#define GL_TEXTURE25 0x84D9 +#define GL_TEXTURE26 0x84DA +#define GL_TEXTURE27 0x84DB +#define GL_TEXTURE28 0x84DC +#define GL_TEXTURE29 0x84DD +#define GL_TEXTURE3 0x84C3 +#define GL_TEXTURE30 0x84DE +#define GL_TEXTURE31 0x84DF +#define GL_TEXTURE4 0x84C4 +#define GL_TEXTURE5 0x84C5 +#define GL_TEXTURE6 0x84C6 +#define GL_TEXTURE7 0x84C7 +#define GL_TEXTURE8 0x84C8 +#define GL_TEXTURE9 0x84C9 +#define GL_TEXTURE_1D 0x0DE0 +#define GL_TEXTURE_1D_ARRAY 0x8C18 +#define GL_TEXTURE_2D 0x0DE1 +#define GL_TEXTURE_2D_ARRAY 0x8C1A +#define GL_TEXTURE_2D_MULTISAMPLE 0x9100 +#define GL_TEXTURE_2D_MULTISAMPLE_ARRAY 0x9102 +#define GL_TEXTURE_3D 0x806F +#define GL_TEXTURE_ALPHA_SIZE 0x805F +#define GL_TEXTURE_ALPHA_TYPE 0x8C13 +#define GL_TEXTURE_BASE_LEVEL 0x813C +#define GL_TEXTURE_BINDING_1D 0x8068 +#define GL_TEXTURE_BINDING_1D_ARRAY 0x8C1C +#define GL_TEXTURE_BINDING_2D 0x8069 +#define GL_TEXTURE_BINDING_2D_ARRAY 0x8C1D +#define GL_TEXTURE_BINDING_2D_MULTISAMPLE 0x9104 +#define GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY 0x9105 +#define GL_TEXTURE_BINDING_3D 0x806A +#define GL_TEXTURE_BINDING_BUFFER 0x8C2C +#define GL_TEXTURE_BINDING_CUBE_MAP 0x8514 +#define GL_TEXTURE_BINDING_RECTANGLE 0x84F6 +#define GL_TEXTURE_BIT 0x00040000 +#define GL_TEXTURE_BLUE_SIZE 0x805E +#define GL_TEXTURE_BLUE_TYPE 0x8C12 +#define GL_TEXTURE_BORDER 0x1005 +#define GL_TEXTURE_BORDER_COLOR 0x1004 +#define GL_TEXTURE_BUFFER 0x8C2A +#define GL_TEXTURE_BUFFER_DATA_STORE_BINDING 0x8C2D +#define GL_TEXTURE_COMPARE_FUNC 0x884D +#define GL_TEXTURE_COMPARE_MODE 0x884C +#define GL_TEXTURE_COMPONENTS 0x1003 +#define GL_TEXTURE_COMPRESSED 0x86A1 +#define GL_TEXTURE_COMPRESSED_IMAGE_SIZE 0x86A0 +#define GL_TEXTURE_COMPRESSION_HINT 0x84EF +#define GL_TEXTURE_COORD_ARRAY 0x8078 +#define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING 0x889A +#define GL_TEXTURE_COORD_ARRAY_POINTER 0x8092 +#define GL_TEXTURE_COORD_ARRAY_SIZE 0x8088 +#define GL_TEXTURE_COORD_ARRAY_STRIDE 0x808A +#define GL_TEXTURE_COORD_ARRAY_TYPE 0x8089 +#define GL_TEXTURE_CUBE_MAP 0x8513 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A +#define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519 +#define GL_TEXTURE_CUBE_MAP_SEAMLESS 0x884F +#define GL_TEXTURE_DEPTH 0x8071 +#define GL_TEXTURE_DEPTH_SIZE 0x884A +#define GL_TEXTURE_DEPTH_TYPE 0x8C16 +#define GL_TEXTURE_ENV 0x2300 +#define GL_TEXTURE_ENV_COLOR 0x2201 +#define GL_TEXTURE_ENV_MODE 0x2200 +#define GL_TEXTURE_FILTER_CONTROL 0x8500 +#define GL_TEXTURE_FIXED_SAMPLE_LOCATIONS 0x9107 +#define GL_TEXTURE_GEN_MODE 0x2500 +#define GL_TEXTURE_GEN_Q 0x0C63 +#define GL_TEXTURE_GEN_R 0x0C62 +#define GL_TEXTURE_GEN_S 0x0C60 +#define GL_TEXTURE_GEN_T 0x0C61 +#define GL_TEXTURE_GREEN_SIZE 0x805D +#define GL_TEXTURE_GREEN_TYPE 0x8C11 +#define GL_TEXTURE_HEIGHT 0x1001 +#define GL_TEXTURE_INTENSITY_SIZE 0x8061 +#define GL_TEXTURE_INTENSITY_TYPE 0x8C15 +#define GL_TEXTURE_INTERNAL_FORMAT 0x1003 +#define GL_TEXTURE_LOD_BIAS 0x8501 +#define GL_TEXTURE_LUMINANCE_SIZE 0x8060 +#define GL_TEXTURE_LUMINANCE_TYPE 0x8C14 +#define GL_TEXTURE_MAG_FILTER 0x2800 +#define GL_TEXTURE_MATRIX 0x0BA8 +#define GL_TEXTURE_MAX_LEVEL 0x813D +#define GL_TEXTURE_MAX_LOD 0x813B +#define GL_TEXTURE_MIN_FILTER 0x2801 +#define GL_TEXTURE_MIN_LOD 0x813A +#define GL_TEXTURE_PRIORITY 0x8066 +#define GL_TEXTURE_RECTANGLE 0x84F5 +#define GL_TEXTURE_RED_SIZE 0x805C +#define GL_TEXTURE_RED_TYPE 0x8C10 +#define GL_TEXTURE_RESIDENT 0x8067 +#define GL_TEXTURE_SAMPLES 0x9106 +#define GL_TEXTURE_SHARED_SIZE 0x8C3F +#define GL_TEXTURE_STACK_DEPTH 0x0BA5 +#define GL_TEXTURE_STENCIL_SIZE 0x88F1 +#define GL_TEXTURE_SWIZZLE_A 0x8E45 +#define GL_TEXTURE_SWIZZLE_B 0x8E44 +#define GL_TEXTURE_SWIZZLE_G 0x8E43 +#define GL_TEXTURE_SWIZZLE_R 0x8E42 +#define GL_TEXTURE_SWIZZLE_RGBA 0x8E46 +#define GL_TEXTURE_WIDTH 0x1000 +#define GL_TEXTURE_WRAP_R 0x8072 +#define GL_TEXTURE_WRAP_S 0x2802 +#define GL_TEXTURE_WRAP_T 0x2803 +#define GL_TIMEOUT_EXPIRED 0x911B +#define GL_TIMEOUT_IGNORED 0xFFFFFFFFFFFFFFFF +#define GL_TIMESTAMP 0x8E28 +#define GL_TIME_ELAPSED 0x88BF +#define GL_TRANSFORM_BIT 0x00001000 +#define GL_TRANSFORM_FEEDBACK_BUFFER 0x8C8E +#define GL_TRANSFORM_FEEDBACK_BUFFER_BINDING 0x8C8F +#define GL_TRANSFORM_FEEDBACK_BUFFER_MODE 0x8C7F +#define GL_TRANSFORM_FEEDBACK_BUFFER_SIZE 0x8C85 +#define GL_TRANSFORM_FEEDBACK_BUFFER_START 0x8C84 +#define GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN 0x8C88 +#define GL_TRANSFORM_FEEDBACK_VARYINGS 0x8C83 +#define GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH 0x8C76 +#define GL_TRANSPOSE_COLOR_MATRIX 0x84E6 +#define GL_TRANSPOSE_MODELVIEW_MATRIX 0x84E3 +#define GL_TRANSPOSE_PROJECTION_MATRIX 0x84E4 +#define GL_TRANSPOSE_TEXTURE_MATRIX 0x84E5 +#define GL_TRIANGLES 0x0004 +#define GL_TRIANGLES_ADJACENCY 0x000C +#define GL_TRIANGLE_FAN 0x0006 +#define GL_TRIANGLE_STRIP 0x0005 +#define GL_TRIANGLE_STRIP_ADJACENCY 0x000D +#define GL_TRUE 1 +#define GL_UNIFORM_ARRAY_STRIDE 0x8A3C +#define GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS 0x8A42 +#define GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES 0x8A43 +#define GL_UNIFORM_BLOCK_BINDING 0x8A3F +#define GL_UNIFORM_BLOCK_DATA_SIZE 0x8A40 +#define GL_UNIFORM_BLOCK_INDEX 0x8A3A +#define GL_UNIFORM_BLOCK_NAME_LENGTH 0x8A41 +#define GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER 0x8A46 +#define GL_UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER 0x8A45 +#define GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER 0x8A44 +#define GL_UNIFORM_BUFFER 0x8A11 +#define GL_UNIFORM_BUFFER_BINDING 0x8A28 +#define GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT 0x8A34 +#define GL_UNIFORM_BUFFER_SIZE 0x8A2A +#define GL_UNIFORM_BUFFER_START 0x8A29 +#define GL_UNIFORM_IS_ROW_MAJOR 0x8A3E +#define GL_UNIFORM_MATRIX_STRIDE 0x8A3D +#define GL_UNIFORM_NAME_LENGTH 0x8A39 +#define GL_UNIFORM_OFFSET 0x8A3B +#define GL_UNIFORM_SIZE 0x8A38 +#define GL_UNIFORM_TYPE 0x8A37 +#define GL_UNKNOWN_CONTEXT_RESET_ARB 0x8255 +#define GL_UNPACK_ALIGNMENT 0x0CF5 +#define GL_UNPACK_IMAGE_HEIGHT 0x806E +#define GL_UNPACK_LSB_FIRST 0x0CF1 +#define GL_UNPACK_ROW_LENGTH 0x0CF2 +#define GL_UNPACK_SKIP_IMAGES 0x806D +#define GL_UNPACK_SKIP_PIXELS 0x0CF4 +#define GL_UNPACK_SKIP_ROWS 0x0CF3 +#define GL_UNPACK_SWAP_BYTES 0x0CF0 +#define GL_UNSIGNALED 0x9118 +#define GL_UNSIGNED_BYTE 0x1401 +#define GL_UNSIGNED_BYTE_2_3_3_REV 0x8362 +#define GL_UNSIGNED_BYTE_3_3_2 0x8032 +#define GL_UNSIGNED_INT 0x1405 +#define GL_UNSIGNED_INT_10F_11F_11F_REV 0x8C3B +#define GL_UNSIGNED_INT_10_10_10_2 0x8036 +#define GL_UNSIGNED_INT_24_8 0x84FA +#define GL_UNSIGNED_INT_2_10_10_10_REV 0x8368 +#define GL_UNSIGNED_INT_5_9_9_9_REV 0x8C3E +#define GL_UNSIGNED_INT_8_8_8_8 0x8035 +#define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367 +#define GL_UNSIGNED_INT_SAMPLER_1D 0x8DD1 +#define GL_UNSIGNED_INT_SAMPLER_1D_ARRAY 0x8DD6 +#define GL_UNSIGNED_INT_SAMPLER_2D 0x8DD2 +#define GL_UNSIGNED_INT_SAMPLER_2D_ARRAY 0x8DD7 +#define GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE 0x910A +#define GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910D +#define GL_UNSIGNED_INT_SAMPLER_2D_RECT 0x8DD5 +#define GL_UNSIGNED_INT_SAMPLER_3D 0x8DD3 +#define GL_UNSIGNED_INT_SAMPLER_BUFFER 0x8DD8 +#define GL_UNSIGNED_INT_SAMPLER_CUBE 0x8DD4 +#define GL_UNSIGNED_INT_VEC2 0x8DC6 +#define GL_UNSIGNED_INT_VEC3 0x8DC7 +#define GL_UNSIGNED_INT_VEC4 0x8DC8 +#define GL_UNSIGNED_NORMALIZED 0x8C17 +#define GL_UNSIGNED_SHORT 0x1403 +#define GL_UNSIGNED_SHORT_1_5_5_5_REV 0x8366 +#define GL_UNSIGNED_SHORT_4_4_4_4 0x8033 +#define GL_UNSIGNED_SHORT_4_4_4_4_REV 0x8365 +#define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 +#define GL_UNSIGNED_SHORT_5_6_5 0x8363 +#define GL_UNSIGNED_SHORT_5_6_5_REV 0x8364 +#define GL_UPPER_LEFT 0x8CA2 +#define GL_V2F 0x2A20 +#define GL_V3F 0x2A21 +#define GL_VALIDATE_STATUS 0x8B83 +#define GL_VENDOR 0x1F00 +#define GL_VERSION 0x1F02 +#define GL_VERTEX_ARRAY 0x8074 +#define GL_VERTEX_ARRAY_BINDING 0x85B5 +#define GL_VERTEX_ARRAY_BUFFER_BINDING 0x8896 +#define GL_VERTEX_ARRAY_POINTER 0x808E +#define GL_VERTEX_ARRAY_SIZE 0x807A +#define GL_VERTEX_ARRAY_STRIDE 0x807C +#define GL_VERTEX_ARRAY_TYPE 0x807B +#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F +#define GL_VERTEX_ATTRIB_ARRAY_DIVISOR 0x88FE +#define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622 +#define GL_VERTEX_ATTRIB_ARRAY_INTEGER 0x88FD +#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A +#define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645 +#define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623 +#define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624 +#define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625 +#define GL_VERTEX_PROGRAM_POINT_SIZE 0x8642 +#define GL_VERTEX_PROGRAM_TWO_SIDE 0x8643 +#define GL_VERTEX_SHADER 0x8B31 +#define GL_VIEWPORT 0x0BA2 +#define GL_VIEWPORT_BIT 0x00000800 +#define GL_WAIT_FAILED 0x911D +#define GL_WEIGHT_ARRAY_BUFFER_BINDING 0x889E +#define GL_WRITE_ONLY 0x88B9 +#define GL_XOR 0x1506 +#define GL_ZERO 0 +#define GL_ZOOM_X 0x0D16 +#define GL_ZOOM_Y 0x0D17 + + +#include +typedef unsigned int GLenum; +typedef unsigned char GLboolean; +typedef unsigned int GLbitfield; +typedef void GLvoid; +typedef khronos_int8_t GLbyte; +typedef khronos_uint8_t GLubyte; +typedef khronos_int16_t GLshort; +typedef khronos_uint16_t GLushort; +typedef int GLint; +typedef unsigned int GLuint; +typedef khronos_int32_t GLclampx; +typedef int GLsizei; +typedef khronos_float_t GLfloat; +typedef khronos_float_t GLclampf; +typedef double GLdouble; +typedef double GLclampd; +typedef void *GLeglClientBufferEXT; +typedef void *GLeglImageOES; +typedef char GLchar; +typedef char GLcharARB; +#ifdef __APPLE__ +typedef void *GLhandleARB; +#else +typedef unsigned int GLhandleARB; +#endif +typedef khronos_uint16_t GLhalf; +typedef khronos_uint16_t GLhalfARB; +typedef khronos_int32_t GLfixed; +#if defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) && (__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ > 1060) +typedef khronos_intptr_t GLintptr; +#else +typedef khronos_intptr_t GLintptr; +#endif +#if defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) && (__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ > 1060) +typedef khronos_intptr_t GLintptrARB; +#else +typedef khronos_intptr_t GLintptrARB; +#endif +#if defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) && (__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ > 1060) +typedef khronos_ssize_t GLsizeiptr; +#else +typedef khronos_ssize_t GLsizeiptr; +#endif +#if defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) && (__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ > 1060) +typedef khronos_ssize_t GLsizeiptrARB; +#else +typedef khronos_ssize_t GLsizeiptrARB; +#endif +typedef khronos_int64_t GLint64; +typedef khronos_int64_t GLint64EXT; +typedef khronos_uint64_t GLuint64; +typedef khronos_uint64_t GLuint64EXT; +typedef struct __GLsync *GLsync; +struct _cl_context; +struct _cl_event; +typedef void ( *GLDEBUGPROC)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); +typedef void ( *GLDEBUGPROCARB)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); +typedef void ( *GLDEBUGPROCKHR)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); +typedef void ( *GLDEBUGPROCAMD)(GLuint id,GLenum category,GLenum severity,GLsizei length,const GLchar *message,void *userParam); +typedef unsigned short GLhalfNV; +typedef GLintptr GLvdpauSurfaceNV; +typedef void ( *GLVULKANPROCNV)(void); + + +#define GL_VERSION_1_0 1 +GLAD_API_CALL int GLAD_GL_VERSION_1_0; +#define GL_VERSION_1_1 1 +GLAD_API_CALL int GLAD_GL_VERSION_1_1; +#define GL_VERSION_1_2 1 +GLAD_API_CALL int GLAD_GL_VERSION_1_2; +#define GL_VERSION_1_3 1 +GLAD_API_CALL int GLAD_GL_VERSION_1_3; +#define GL_VERSION_1_4 1 +GLAD_API_CALL int GLAD_GL_VERSION_1_4; +#define GL_VERSION_1_5 1 +GLAD_API_CALL int GLAD_GL_VERSION_1_5; +#define GL_VERSION_2_0 1 +GLAD_API_CALL int GLAD_GL_VERSION_2_0; +#define GL_VERSION_2_1 1 +GLAD_API_CALL int GLAD_GL_VERSION_2_1; +#define GL_VERSION_3_0 1 +GLAD_API_CALL int GLAD_GL_VERSION_3_0; +#define GL_VERSION_3_1 1 +GLAD_API_CALL int GLAD_GL_VERSION_3_1; +#define GL_VERSION_3_2 1 +GLAD_API_CALL int GLAD_GL_VERSION_3_2; +#define GL_VERSION_3_3 1 +GLAD_API_CALL int GLAD_GL_VERSION_3_3; +#define GL_ARB_multisample 1 +GLAD_API_CALL int GLAD_GL_ARB_multisample; +#define GL_ARB_robustness 1 +GLAD_API_CALL int GLAD_GL_ARB_robustness; +#define GL_KHR_debug 1 +GLAD_API_CALL int GLAD_GL_KHR_debug; + + +typedef void (GLAD_API_PTR *PFNGLACCUMPROC)(GLenum op, GLfloat value); +typedef void (GLAD_API_PTR *PFNGLACTIVETEXTUREPROC)(GLenum texture); +typedef void (GLAD_API_PTR *PFNGLALPHAFUNCPROC)(GLenum func, GLfloat ref); +typedef GLboolean (GLAD_API_PTR *PFNGLARETEXTURESRESIDENTPROC)(GLsizei n, const GLuint * textures, GLboolean * residences); +typedef void (GLAD_API_PTR *PFNGLARRAYELEMENTPROC)(GLint i); +typedef void (GLAD_API_PTR *PFNGLATTACHSHADERPROC)(GLuint program, GLuint shader); +typedef void (GLAD_API_PTR *PFNGLBEGINPROC)(GLenum mode); +typedef void (GLAD_API_PTR *PFNGLBEGINCONDITIONALRENDERPROC)(GLuint id, GLenum mode); +typedef void (GLAD_API_PTR *PFNGLBEGINQUERYPROC)(GLenum target, GLuint id); +typedef void (GLAD_API_PTR *PFNGLBEGINTRANSFORMFEEDBACKPROC)(GLenum primitiveMode); +typedef void (GLAD_API_PTR *PFNGLBINDATTRIBLOCATIONPROC)(GLuint program, GLuint index, const GLchar * name); +typedef void (GLAD_API_PTR *PFNGLBINDBUFFERPROC)(GLenum target, GLuint buffer); +typedef void (GLAD_API_PTR *PFNGLBINDBUFFERBASEPROC)(GLenum target, GLuint index, GLuint buffer); +typedef void (GLAD_API_PTR *PFNGLBINDBUFFERRANGEPROC)(GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); +typedef void (GLAD_API_PTR *PFNGLBINDFRAGDATALOCATIONPROC)(GLuint program, GLuint color, const GLchar * name); +typedef void (GLAD_API_PTR *PFNGLBINDFRAGDATALOCATIONINDEXEDPROC)(GLuint program, GLuint colorNumber, GLuint index, const GLchar * name); +typedef void (GLAD_API_PTR *PFNGLBINDFRAMEBUFFERPROC)(GLenum target, GLuint framebuffer); +typedef void (GLAD_API_PTR *PFNGLBINDRENDERBUFFERPROC)(GLenum target, GLuint renderbuffer); +typedef void (GLAD_API_PTR *PFNGLBINDSAMPLERPROC)(GLuint unit, GLuint sampler); +typedef void (GLAD_API_PTR *PFNGLBINDTEXTUREPROC)(GLenum target, GLuint texture); +typedef void (GLAD_API_PTR *PFNGLBINDVERTEXARRAYPROC)(GLuint array); +typedef void (GLAD_API_PTR *PFNGLBITMAPPROC)(GLsizei width, GLsizei height, GLfloat xorig, GLfloat yorig, GLfloat xmove, GLfloat ymove, const GLubyte * bitmap); +typedef void (GLAD_API_PTR *PFNGLBLENDCOLORPROC)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); +typedef void (GLAD_API_PTR *PFNGLBLENDEQUATIONPROC)(GLenum mode); +typedef void (GLAD_API_PTR *PFNGLBLENDEQUATIONSEPARATEPROC)(GLenum modeRGB, GLenum modeAlpha); +typedef void (GLAD_API_PTR *PFNGLBLENDFUNCPROC)(GLenum sfactor, GLenum dfactor); +typedef void (GLAD_API_PTR *PFNGLBLENDFUNCSEPARATEPROC)(GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); +typedef void (GLAD_API_PTR *PFNGLBLITFRAMEBUFFERPROC)(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); +typedef void (GLAD_API_PTR *PFNGLBUFFERDATAPROC)(GLenum target, GLsizeiptr size, const void * data, GLenum usage); +typedef void (GLAD_API_PTR *PFNGLBUFFERSUBDATAPROC)(GLenum target, GLintptr offset, GLsizeiptr size, const void * data); +typedef void (GLAD_API_PTR *PFNGLCALLLISTPROC)(GLuint list); +typedef void (GLAD_API_PTR *PFNGLCALLLISTSPROC)(GLsizei n, GLenum type, const void * lists); +typedef GLenum (GLAD_API_PTR *PFNGLCHECKFRAMEBUFFERSTATUSPROC)(GLenum target); +typedef void (GLAD_API_PTR *PFNGLCLAMPCOLORPROC)(GLenum target, GLenum clamp); +typedef void (GLAD_API_PTR *PFNGLCLEARPROC)(GLbitfield mask); +typedef void (GLAD_API_PTR *PFNGLCLEARACCUMPROC)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); +typedef void (GLAD_API_PTR *PFNGLCLEARBUFFERFIPROC)(GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil); +typedef void (GLAD_API_PTR *PFNGLCLEARBUFFERFVPROC)(GLenum buffer, GLint drawbuffer, const GLfloat * value); +typedef void (GLAD_API_PTR *PFNGLCLEARBUFFERIVPROC)(GLenum buffer, GLint drawbuffer, const GLint * value); +typedef void (GLAD_API_PTR *PFNGLCLEARBUFFERUIVPROC)(GLenum buffer, GLint drawbuffer, const GLuint * value); +typedef void (GLAD_API_PTR *PFNGLCLEARCOLORPROC)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); +typedef void (GLAD_API_PTR *PFNGLCLEARDEPTHPROC)(GLdouble depth); +typedef void (GLAD_API_PTR *PFNGLCLEARINDEXPROC)(GLfloat c); +typedef void (GLAD_API_PTR *PFNGLCLEARSTENCILPROC)(GLint s); +typedef void (GLAD_API_PTR *PFNGLCLIENTACTIVETEXTUREPROC)(GLenum texture); +typedef GLenum (GLAD_API_PTR *PFNGLCLIENTWAITSYNCPROC)(GLsync sync, GLbitfield flags, GLuint64 timeout); +typedef void (GLAD_API_PTR *PFNGLCLIPPLANEPROC)(GLenum plane, const GLdouble * equation); +typedef void (GLAD_API_PTR *PFNGLCOLOR3BPROC)(GLbyte red, GLbyte green, GLbyte blue); +typedef void (GLAD_API_PTR *PFNGLCOLOR3BVPROC)(const GLbyte * v); +typedef void (GLAD_API_PTR *PFNGLCOLOR3DPROC)(GLdouble red, GLdouble green, GLdouble blue); +typedef void (GLAD_API_PTR *PFNGLCOLOR3DVPROC)(const GLdouble * v); +typedef void (GLAD_API_PTR *PFNGLCOLOR3FPROC)(GLfloat red, GLfloat green, GLfloat blue); +typedef void (GLAD_API_PTR *PFNGLCOLOR3FVPROC)(const GLfloat * v); +typedef void (GLAD_API_PTR *PFNGLCOLOR3IPROC)(GLint red, GLint green, GLint blue); +typedef void (GLAD_API_PTR *PFNGLCOLOR3IVPROC)(const GLint * v); +typedef void (GLAD_API_PTR *PFNGLCOLOR3SPROC)(GLshort red, GLshort green, GLshort blue); +typedef void (GLAD_API_PTR *PFNGLCOLOR3SVPROC)(const GLshort * v); +typedef void (GLAD_API_PTR *PFNGLCOLOR3UBPROC)(GLubyte red, GLubyte green, GLubyte blue); +typedef void (GLAD_API_PTR *PFNGLCOLOR3UBVPROC)(const GLubyte * v); +typedef void (GLAD_API_PTR *PFNGLCOLOR3UIPROC)(GLuint red, GLuint green, GLuint blue); +typedef void (GLAD_API_PTR *PFNGLCOLOR3UIVPROC)(const GLuint * v); +typedef void (GLAD_API_PTR *PFNGLCOLOR3USPROC)(GLushort red, GLushort green, GLushort blue); +typedef void (GLAD_API_PTR *PFNGLCOLOR3USVPROC)(const GLushort * v); +typedef void (GLAD_API_PTR *PFNGLCOLOR4BPROC)(GLbyte red, GLbyte green, GLbyte blue, GLbyte alpha); +typedef void (GLAD_API_PTR *PFNGLCOLOR4BVPROC)(const GLbyte * v); +typedef void (GLAD_API_PTR *PFNGLCOLOR4DPROC)(GLdouble red, GLdouble green, GLdouble blue, GLdouble alpha); +typedef void (GLAD_API_PTR *PFNGLCOLOR4DVPROC)(const GLdouble * v); +typedef void (GLAD_API_PTR *PFNGLCOLOR4FPROC)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); +typedef void (GLAD_API_PTR *PFNGLCOLOR4FVPROC)(const GLfloat * v); +typedef void (GLAD_API_PTR *PFNGLCOLOR4IPROC)(GLint red, GLint green, GLint blue, GLint alpha); +typedef void (GLAD_API_PTR *PFNGLCOLOR4IVPROC)(const GLint * v); +typedef void (GLAD_API_PTR *PFNGLCOLOR4SPROC)(GLshort red, GLshort green, GLshort blue, GLshort alpha); +typedef void (GLAD_API_PTR *PFNGLCOLOR4SVPROC)(const GLshort * v); +typedef void (GLAD_API_PTR *PFNGLCOLOR4UBPROC)(GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha); +typedef void (GLAD_API_PTR *PFNGLCOLOR4UBVPROC)(const GLubyte * v); +typedef void (GLAD_API_PTR *PFNGLCOLOR4UIPROC)(GLuint red, GLuint green, GLuint blue, GLuint alpha); +typedef void (GLAD_API_PTR *PFNGLCOLOR4UIVPROC)(const GLuint * v); +typedef void (GLAD_API_PTR *PFNGLCOLOR4USPROC)(GLushort red, GLushort green, GLushort blue, GLushort alpha); +typedef void (GLAD_API_PTR *PFNGLCOLOR4USVPROC)(const GLushort * v); +typedef void (GLAD_API_PTR *PFNGLCOLORMASKPROC)(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha); +typedef void (GLAD_API_PTR *PFNGLCOLORMASKIPROC)(GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a); +typedef void (GLAD_API_PTR *PFNGLCOLORMATERIALPROC)(GLenum face, GLenum mode); +typedef void (GLAD_API_PTR *PFNGLCOLORP3UIPROC)(GLenum type, GLuint color); +typedef void (GLAD_API_PTR *PFNGLCOLORP3UIVPROC)(GLenum type, const GLuint * color); +typedef void (GLAD_API_PTR *PFNGLCOLORP4UIPROC)(GLenum type, GLuint color); +typedef void (GLAD_API_PTR *PFNGLCOLORP4UIVPROC)(GLenum type, const GLuint * color); +typedef void (GLAD_API_PTR *PFNGLCOLORPOINTERPROC)(GLint size, GLenum type, GLsizei stride, const void * pointer); +typedef void (GLAD_API_PTR *PFNGLCOMPILESHADERPROC)(GLuint shader); +typedef void (GLAD_API_PTR *PFNGLCOMPRESSEDTEXIMAGE1DPROC)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void * data); +typedef void (GLAD_API_PTR *PFNGLCOMPRESSEDTEXIMAGE2DPROC)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void * data); +typedef void (GLAD_API_PTR *PFNGLCOMPRESSEDTEXIMAGE3DPROC)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void * data); +typedef void (GLAD_API_PTR *PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC)(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void * data); +typedef void (GLAD_API_PTR *PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void * data); +typedef void (GLAD_API_PTR *PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void * data); +typedef void (GLAD_API_PTR *PFNGLCOPYBUFFERSUBDATAPROC)(GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); +typedef void (GLAD_API_PTR *PFNGLCOPYPIXELSPROC)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum type); +typedef void (GLAD_API_PTR *PFNGLCOPYTEXIMAGE1DPROC)(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border); +typedef void (GLAD_API_PTR *PFNGLCOPYTEXIMAGE2DPROC)(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); +typedef void (GLAD_API_PTR *PFNGLCOPYTEXSUBIMAGE1DPROC)(GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); +typedef void (GLAD_API_PTR *PFNGLCOPYTEXSUBIMAGE2DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (GLAD_API_PTR *PFNGLCOPYTEXSUBIMAGE3DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +typedef GLuint (GLAD_API_PTR *PFNGLCREATEPROGRAMPROC)(void); +typedef GLuint (GLAD_API_PTR *PFNGLCREATESHADERPROC)(GLenum type); +typedef void (GLAD_API_PTR *PFNGLCULLFACEPROC)(GLenum mode); +typedef void (GLAD_API_PTR *PFNGLDEBUGMESSAGECALLBACKPROC)(GLDEBUGPROC callback, const void * userParam); +typedef void (GLAD_API_PTR *PFNGLDEBUGMESSAGECONTROLPROC)(GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint * ids, GLboolean enabled); +typedef void (GLAD_API_PTR *PFNGLDEBUGMESSAGEINSERTPROC)(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar * buf); +typedef void (GLAD_API_PTR *PFNGLDELETEBUFFERSPROC)(GLsizei n, const GLuint * buffers); +typedef void (GLAD_API_PTR *PFNGLDELETEFRAMEBUFFERSPROC)(GLsizei n, const GLuint * framebuffers); +typedef void (GLAD_API_PTR *PFNGLDELETELISTSPROC)(GLuint list, GLsizei range); +typedef void (GLAD_API_PTR *PFNGLDELETEPROGRAMPROC)(GLuint program); +typedef void (GLAD_API_PTR *PFNGLDELETEQUERIESPROC)(GLsizei n, const GLuint * ids); +typedef void (GLAD_API_PTR *PFNGLDELETERENDERBUFFERSPROC)(GLsizei n, const GLuint * renderbuffers); +typedef void (GLAD_API_PTR *PFNGLDELETESAMPLERSPROC)(GLsizei count, const GLuint * samplers); +typedef void (GLAD_API_PTR *PFNGLDELETESHADERPROC)(GLuint shader); +typedef void (GLAD_API_PTR *PFNGLDELETESYNCPROC)(GLsync sync); +typedef void (GLAD_API_PTR *PFNGLDELETETEXTURESPROC)(GLsizei n, const GLuint * textures); +typedef void (GLAD_API_PTR *PFNGLDELETEVERTEXARRAYSPROC)(GLsizei n, const GLuint * arrays); +typedef void (GLAD_API_PTR *PFNGLDEPTHFUNCPROC)(GLenum func); +typedef void (GLAD_API_PTR *PFNGLDEPTHMASKPROC)(GLboolean flag); +typedef void (GLAD_API_PTR *PFNGLDEPTHRANGEPROC)(GLdouble n, GLdouble f); +typedef void (GLAD_API_PTR *PFNGLDETACHSHADERPROC)(GLuint program, GLuint shader); +typedef void (GLAD_API_PTR *PFNGLDISABLEPROC)(GLenum cap); +typedef void (GLAD_API_PTR *PFNGLDISABLECLIENTSTATEPROC)(GLenum array); +typedef void (GLAD_API_PTR *PFNGLDISABLEVERTEXATTRIBARRAYPROC)(GLuint index); +typedef void (GLAD_API_PTR *PFNGLDISABLEIPROC)(GLenum target, GLuint index); +typedef void (GLAD_API_PTR *PFNGLDRAWARRAYSPROC)(GLenum mode, GLint first, GLsizei count); +typedef void (GLAD_API_PTR *PFNGLDRAWARRAYSINSTANCEDPROC)(GLenum mode, GLint first, GLsizei count, GLsizei instancecount); +typedef void (GLAD_API_PTR *PFNGLDRAWBUFFERPROC)(GLenum buf); +typedef void (GLAD_API_PTR *PFNGLDRAWBUFFERSPROC)(GLsizei n, const GLenum * bufs); +typedef void (GLAD_API_PTR *PFNGLDRAWELEMENTSPROC)(GLenum mode, GLsizei count, GLenum type, const void * indices); +typedef void (GLAD_API_PTR *PFNGLDRAWELEMENTSBASEVERTEXPROC)(GLenum mode, GLsizei count, GLenum type, const void * indices, GLint basevertex); +typedef void (GLAD_API_PTR *PFNGLDRAWELEMENTSINSTANCEDPROC)(GLenum mode, GLsizei count, GLenum type, const void * indices, GLsizei instancecount); +typedef void (GLAD_API_PTR *PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC)(GLenum mode, GLsizei count, GLenum type, const void * indices, GLsizei instancecount, GLint basevertex); +typedef void (GLAD_API_PTR *PFNGLDRAWPIXELSPROC)(GLsizei width, GLsizei height, GLenum format, GLenum type, const void * pixels); +typedef void (GLAD_API_PTR *PFNGLDRAWRANGEELEMENTSPROC)(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void * indices); +typedef void (GLAD_API_PTR *PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC)(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void * indices, GLint basevertex); +typedef void (GLAD_API_PTR *PFNGLEDGEFLAGPROC)(GLboolean flag); +typedef void (GLAD_API_PTR *PFNGLEDGEFLAGPOINTERPROC)(GLsizei stride, const void * pointer); +typedef void (GLAD_API_PTR *PFNGLEDGEFLAGVPROC)(const GLboolean * flag); +typedef void (GLAD_API_PTR *PFNGLENABLEPROC)(GLenum cap); +typedef void (GLAD_API_PTR *PFNGLENABLECLIENTSTATEPROC)(GLenum array); +typedef void (GLAD_API_PTR *PFNGLENABLEVERTEXATTRIBARRAYPROC)(GLuint index); +typedef void (GLAD_API_PTR *PFNGLENABLEIPROC)(GLenum target, GLuint index); +typedef void (GLAD_API_PTR *PFNGLENDPROC)(void); +typedef void (GLAD_API_PTR *PFNGLENDCONDITIONALRENDERPROC)(void); +typedef void (GLAD_API_PTR *PFNGLENDLISTPROC)(void); +typedef void (GLAD_API_PTR *PFNGLENDQUERYPROC)(GLenum target); +typedef void (GLAD_API_PTR *PFNGLENDTRANSFORMFEEDBACKPROC)(void); +typedef void (GLAD_API_PTR *PFNGLEVALCOORD1DPROC)(GLdouble u); +typedef void (GLAD_API_PTR *PFNGLEVALCOORD1DVPROC)(const GLdouble * u); +typedef void (GLAD_API_PTR *PFNGLEVALCOORD1FPROC)(GLfloat u); +typedef void (GLAD_API_PTR *PFNGLEVALCOORD1FVPROC)(const GLfloat * u); +typedef void (GLAD_API_PTR *PFNGLEVALCOORD2DPROC)(GLdouble u, GLdouble v); +typedef void (GLAD_API_PTR *PFNGLEVALCOORD2DVPROC)(const GLdouble * u); +typedef void (GLAD_API_PTR *PFNGLEVALCOORD2FPROC)(GLfloat u, GLfloat v); +typedef void (GLAD_API_PTR *PFNGLEVALCOORD2FVPROC)(const GLfloat * u); +typedef void (GLAD_API_PTR *PFNGLEVALMESH1PROC)(GLenum mode, GLint i1, GLint i2); +typedef void (GLAD_API_PTR *PFNGLEVALMESH2PROC)(GLenum mode, GLint i1, GLint i2, GLint j1, GLint j2); +typedef void (GLAD_API_PTR *PFNGLEVALPOINT1PROC)(GLint i); +typedef void (GLAD_API_PTR *PFNGLEVALPOINT2PROC)(GLint i, GLint j); +typedef void (GLAD_API_PTR *PFNGLFEEDBACKBUFFERPROC)(GLsizei size, GLenum type, GLfloat * buffer); +typedef GLsync (GLAD_API_PTR *PFNGLFENCESYNCPROC)(GLenum condition, GLbitfield flags); +typedef void (GLAD_API_PTR *PFNGLFINISHPROC)(void); +typedef void (GLAD_API_PTR *PFNGLFLUSHPROC)(void); +typedef void (GLAD_API_PTR *PFNGLFLUSHMAPPEDBUFFERRANGEPROC)(GLenum target, GLintptr offset, GLsizeiptr length); +typedef void (GLAD_API_PTR *PFNGLFOGCOORDPOINTERPROC)(GLenum type, GLsizei stride, const void * pointer); +typedef void (GLAD_API_PTR *PFNGLFOGCOORDDPROC)(GLdouble coord); +typedef void (GLAD_API_PTR *PFNGLFOGCOORDDVPROC)(const GLdouble * coord); +typedef void (GLAD_API_PTR *PFNGLFOGCOORDFPROC)(GLfloat coord); +typedef void (GLAD_API_PTR *PFNGLFOGCOORDFVPROC)(const GLfloat * coord); +typedef void (GLAD_API_PTR *PFNGLFOGFPROC)(GLenum pname, GLfloat param); +typedef void (GLAD_API_PTR *PFNGLFOGFVPROC)(GLenum pname, const GLfloat * params); +typedef void (GLAD_API_PTR *PFNGLFOGIPROC)(GLenum pname, GLint param); +typedef void (GLAD_API_PTR *PFNGLFOGIVPROC)(GLenum pname, const GLint * params); +typedef void (GLAD_API_PTR *PFNGLFRAMEBUFFERRENDERBUFFERPROC)(GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); +typedef void (GLAD_API_PTR *PFNGLFRAMEBUFFERTEXTUREPROC)(GLenum target, GLenum attachment, GLuint texture, GLint level); +typedef void (GLAD_API_PTR *PFNGLFRAMEBUFFERTEXTURE1DPROC)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +typedef void (GLAD_API_PTR *PFNGLFRAMEBUFFERTEXTURE2DPROC)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +typedef void (GLAD_API_PTR *PFNGLFRAMEBUFFERTEXTURE3DPROC)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); +typedef void (GLAD_API_PTR *PFNGLFRAMEBUFFERTEXTURELAYERPROC)(GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); +typedef void (GLAD_API_PTR *PFNGLFRONTFACEPROC)(GLenum mode); +typedef void (GLAD_API_PTR *PFNGLFRUSTUMPROC)(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); +typedef void (GLAD_API_PTR *PFNGLGENBUFFERSPROC)(GLsizei n, GLuint * buffers); +typedef void (GLAD_API_PTR *PFNGLGENFRAMEBUFFERSPROC)(GLsizei n, GLuint * framebuffers); +typedef GLuint (GLAD_API_PTR *PFNGLGENLISTSPROC)(GLsizei range); +typedef void (GLAD_API_PTR *PFNGLGENQUERIESPROC)(GLsizei n, GLuint * ids); +typedef void (GLAD_API_PTR *PFNGLGENRENDERBUFFERSPROC)(GLsizei n, GLuint * renderbuffers); +typedef void (GLAD_API_PTR *PFNGLGENSAMPLERSPROC)(GLsizei count, GLuint * samplers); +typedef void (GLAD_API_PTR *PFNGLGENTEXTURESPROC)(GLsizei n, GLuint * textures); +typedef void (GLAD_API_PTR *PFNGLGENVERTEXARRAYSPROC)(GLsizei n, GLuint * arrays); +typedef void (GLAD_API_PTR *PFNGLGENERATEMIPMAPPROC)(GLenum target); +typedef void (GLAD_API_PTR *PFNGLGETACTIVEATTRIBPROC)(GLuint program, GLuint index, GLsizei bufSize, GLsizei * length, GLint * size, GLenum * type, GLchar * name); +typedef void (GLAD_API_PTR *PFNGLGETACTIVEUNIFORMPROC)(GLuint program, GLuint index, GLsizei bufSize, GLsizei * length, GLint * size, GLenum * type, GLchar * name); +typedef void (GLAD_API_PTR *PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC)(GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei * length, GLchar * uniformBlockName); +typedef void (GLAD_API_PTR *PFNGLGETACTIVEUNIFORMBLOCKIVPROC)(GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint * params); +typedef void (GLAD_API_PTR *PFNGLGETACTIVEUNIFORMNAMEPROC)(GLuint program, GLuint uniformIndex, GLsizei bufSize, GLsizei * length, GLchar * uniformName); +typedef void (GLAD_API_PTR *PFNGLGETACTIVEUNIFORMSIVPROC)(GLuint program, GLsizei uniformCount, const GLuint * uniformIndices, GLenum pname, GLint * params); +typedef void (GLAD_API_PTR *PFNGLGETATTACHEDSHADERSPROC)(GLuint program, GLsizei maxCount, GLsizei * count, GLuint * shaders); +typedef GLint (GLAD_API_PTR *PFNGLGETATTRIBLOCATIONPROC)(GLuint program, const GLchar * name); +typedef void (GLAD_API_PTR *PFNGLGETBOOLEANI_VPROC)(GLenum target, GLuint index, GLboolean * data); +typedef void (GLAD_API_PTR *PFNGLGETBOOLEANVPROC)(GLenum pname, GLboolean * data); +typedef void (GLAD_API_PTR *PFNGLGETBUFFERPARAMETERI64VPROC)(GLenum target, GLenum pname, GLint64 * params); +typedef void (GLAD_API_PTR *PFNGLGETBUFFERPARAMETERIVPROC)(GLenum target, GLenum pname, GLint * params); +typedef void (GLAD_API_PTR *PFNGLGETBUFFERPOINTERVPROC)(GLenum target, GLenum pname, void ** params); +typedef void (GLAD_API_PTR *PFNGLGETBUFFERSUBDATAPROC)(GLenum target, GLintptr offset, GLsizeiptr size, void * data); +typedef void (GLAD_API_PTR *PFNGLGETCLIPPLANEPROC)(GLenum plane, GLdouble * equation); +typedef void (GLAD_API_PTR *PFNGLGETCOMPRESSEDTEXIMAGEPROC)(GLenum target, GLint level, void * img); +typedef GLuint (GLAD_API_PTR *PFNGLGETDEBUGMESSAGELOGPROC)(GLuint count, GLsizei bufSize, GLenum * sources, GLenum * types, GLuint * ids, GLenum * severities, GLsizei * lengths, GLchar * messageLog); +typedef void (GLAD_API_PTR *PFNGLGETDOUBLEVPROC)(GLenum pname, GLdouble * data); +typedef GLenum (GLAD_API_PTR *PFNGLGETERRORPROC)(void); +typedef void (GLAD_API_PTR *PFNGLGETFLOATVPROC)(GLenum pname, GLfloat * data); +typedef GLint (GLAD_API_PTR *PFNGLGETFRAGDATAINDEXPROC)(GLuint program, const GLchar * name); +typedef GLint (GLAD_API_PTR *PFNGLGETFRAGDATALOCATIONPROC)(GLuint program, const GLchar * name); +typedef void (GLAD_API_PTR *PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC)(GLenum target, GLenum attachment, GLenum pname, GLint * params); +typedef GLenum (GLAD_API_PTR *PFNGLGETGRAPHICSRESETSTATUSARBPROC)(void); +typedef void (GLAD_API_PTR *PFNGLGETINTEGER64I_VPROC)(GLenum target, GLuint index, GLint64 * data); +typedef void (GLAD_API_PTR *PFNGLGETINTEGER64VPROC)(GLenum pname, GLint64 * data); +typedef void (GLAD_API_PTR *PFNGLGETINTEGERI_VPROC)(GLenum target, GLuint index, GLint * data); +typedef void (GLAD_API_PTR *PFNGLGETINTEGERVPROC)(GLenum pname, GLint * data); +typedef void (GLAD_API_PTR *PFNGLGETLIGHTFVPROC)(GLenum light, GLenum pname, GLfloat * params); +typedef void (GLAD_API_PTR *PFNGLGETLIGHTIVPROC)(GLenum light, GLenum pname, GLint * params); +typedef void (GLAD_API_PTR *PFNGLGETMAPDVPROC)(GLenum target, GLenum query, GLdouble * v); +typedef void (GLAD_API_PTR *PFNGLGETMAPFVPROC)(GLenum target, GLenum query, GLfloat * v); +typedef void (GLAD_API_PTR *PFNGLGETMAPIVPROC)(GLenum target, GLenum query, GLint * v); +typedef void (GLAD_API_PTR *PFNGLGETMATERIALFVPROC)(GLenum face, GLenum pname, GLfloat * params); +typedef void (GLAD_API_PTR *PFNGLGETMATERIALIVPROC)(GLenum face, GLenum pname, GLint * params); +typedef void (GLAD_API_PTR *PFNGLGETMULTISAMPLEFVPROC)(GLenum pname, GLuint index, GLfloat * val); +typedef void (GLAD_API_PTR *PFNGLGETOBJECTLABELPROC)(GLenum identifier, GLuint name, GLsizei bufSize, GLsizei * length, GLchar * label); +typedef void (GLAD_API_PTR *PFNGLGETOBJECTPTRLABELPROC)(const void * ptr, GLsizei bufSize, GLsizei * length, GLchar * label); +typedef void (GLAD_API_PTR *PFNGLGETPIXELMAPFVPROC)(GLenum map, GLfloat * values); +typedef void (GLAD_API_PTR *PFNGLGETPIXELMAPUIVPROC)(GLenum map, GLuint * values); +typedef void (GLAD_API_PTR *PFNGLGETPIXELMAPUSVPROC)(GLenum map, GLushort * values); +typedef void (GLAD_API_PTR *PFNGLGETPOINTERVPROC)(GLenum pname, void ** params); +typedef void (GLAD_API_PTR *PFNGLGETPOLYGONSTIPPLEPROC)(GLubyte * mask); +typedef void (GLAD_API_PTR *PFNGLGETPROGRAMINFOLOGPROC)(GLuint program, GLsizei bufSize, GLsizei * length, GLchar * infoLog); +typedef void (GLAD_API_PTR *PFNGLGETPROGRAMIVPROC)(GLuint program, GLenum pname, GLint * params); +typedef void (GLAD_API_PTR *PFNGLGETQUERYOBJECTI64VPROC)(GLuint id, GLenum pname, GLint64 * params); +typedef void (GLAD_API_PTR *PFNGLGETQUERYOBJECTIVPROC)(GLuint id, GLenum pname, GLint * params); +typedef void (GLAD_API_PTR *PFNGLGETQUERYOBJECTUI64VPROC)(GLuint id, GLenum pname, GLuint64 * params); +typedef void (GLAD_API_PTR *PFNGLGETQUERYOBJECTUIVPROC)(GLuint id, GLenum pname, GLuint * params); +typedef void (GLAD_API_PTR *PFNGLGETQUERYIVPROC)(GLenum target, GLenum pname, GLint * params); +typedef void (GLAD_API_PTR *PFNGLGETRENDERBUFFERPARAMETERIVPROC)(GLenum target, GLenum pname, GLint * params); +typedef void (GLAD_API_PTR *PFNGLGETSAMPLERPARAMETERIIVPROC)(GLuint sampler, GLenum pname, GLint * params); +typedef void (GLAD_API_PTR *PFNGLGETSAMPLERPARAMETERIUIVPROC)(GLuint sampler, GLenum pname, GLuint * params); +typedef void (GLAD_API_PTR *PFNGLGETSAMPLERPARAMETERFVPROC)(GLuint sampler, GLenum pname, GLfloat * params); +typedef void (GLAD_API_PTR *PFNGLGETSAMPLERPARAMETERIVPROC)(GLuint sampler, GLenum pname, GLint * params); +typedef void (GLAD_API_PTR *PFNGLGETSHADERINFOLOGPROC)(GLuint shader, GLsizei bufSize, GLsizei * length, GLchar * infoLog); +typedef void (GLAD_API_PTR *PFNGLGETSHADERSOURCEPROC)(GLuint shader, GLsizei bufSize, GLsizei * length, GLchar * source); +typedef void (GLAD_API_PTR *PFNGLGETSHADERIVPROC)(GLuint shader, GLenum pname, GLint * params); +typedef const GLubyte * (GLAD_API_PTR *PFNGLGETSTRINGPROC)(GLenum name); +typedef const GLubyte * (GLAD_API_PTR *PFNGLGETSTRINGIPROC)(GLenum name, GLuint index); +typedef void (GLAD_API_PTR *PFNGLGETSYNCIVPROC)(GLsync sync, GLenum pname, GLsizei bufSize, GLsizei * length, GLint * values); +typedef void (GLAD_API_PTR *PFNGLGETTEXENVFVPROC)(GLenum target, GLenum pname, GLfloat * params); +typedef void (GLAD_API_PTR *PFNGLGETTEXENVIVPROC)(GLenum target, GLenum pname, GLint * params); +typedef void (GLAD_API_PTR *PFNGLGETTEXGENDVPROC)(GLenum coord, GLenum pname, GLdouble * params); +typedef void (GLAD_API_PTR *PFNGLGETTEXGENFVPROC)(GLenum coord, GLenum pname, GLfloat * params); +typedef void (GLAD_API_PTR *PFNGLGETTEXGENIVPROC)(GLenum coord, GLenum pname, GLint * params); +typedef void (GLAD_API_PTR *PFNGLGETTEXIMAGEPROC)(GLenum target, GLint level, GLenum format, GLenum type, void * pixels); +typedef void (GLAD_API_PTR *PFNGLGETTEXLEVELPARAMETERFVPROC)(GLenum target, GLint level, GLenum pname, GLfloat * params); +typedef void (GLAD_API_PTR *PFNGLGETTEXLEVELPARAMETERIVPROC)(GLenum target, GLint level, GLenum pname, GLint * params); +typedef void (GLAD_API_PTR *PFNGLGETTEXPARAMETERIIVPROC)(GLenum target, GLenum pname, GLint * params); +typedef void (GLAD_API_PTR *PFNGLGETTEXPARAMETERIUIVPROC)(GLenum target, GLenum pname, GLuint * params); +typedef void (GLAD_API_PTR *PFNGLGETTEXPARAMETERFVPROC)(GLenum target, GLenum pname, GLfloat * params); +typedef void (GLAD_API_PTR *PFNGLGETTEXPARAMETERIVPROC)(GLenum target, GLenum pname, GLint * params); +typedef void (GLAD_API_PTR *PFNGLGETTRANSFORMFEEDBACKVARYINGPROC)(GLuint program, GLuint index, GLsizei bufSize, GLsizei * length, GLsizei * size, GLenum * type, GLchar * name); +typedef GLuint (GLAD_API_PTR *PFNGLGETUNIFORMBLOCKINDEXPROC)(GLuint program, const GLchar * uniformBlockName); +typedef void (GLAD_API_PTR *PFNGLGETUNIFORMINDICESPROC)(GLuint program, GLsizei uniformCount, const GLchar *const* uniformNames, GLuint * uniformIndices); +typedef GLint (GLAD_API_PTR *PFNGLGETUNIFORMLOCATIONPROC)(GLuint program, const GLchar * name); +typedef void (GLAD_API_PTR *PFNGLGETUNIFORMFVPROC)(GLuint program, GLint location, GLfloat * params); +typedef void (GLAD_API_PTR *PFNGLGETUNIFORMIVPROC)(GLuint program, GLint location, GLint * params); +typedef void (GLAD_API_PTR *PFNGLGETUNIFORMUIVPROC)(GLuint program, GLint location, GLuint * params); +typedef void (GLAD_API_PTR *PFNGLGETVERTEXATTRIBIIVPROC)(GLuint index, GLenum pname, GLint * params); +typedef void (GLAD_API_PTR *PFNGLGETVERTEXATTRIBIUIVPROC)(GLuint index, GLenum pname, GLuint * params); +typedef void (GLAD_API_PTR *PFNGLGETVERTEXATTRIBPOINTERVPROC)(GLuint index, GLenum pname, void ** pointer); +typedef void (GLAD_API_PTR *PFNGLGETVERTEXATTRIBDVPROC)(GLuint index, GLenum pname, GLdouble * params); +typedef void (GLAD_API_PTR *PFNGLGETVERTEXATTRIBFVPROC)(GLuint index, GLenum pname, GLfloat * params); +typedef void (GLAD_API_PTR *PFNGLGETVERTEXATTRIBIVPROC)(GLuint index, GLenum pname, GLint * params); +typedef void (GLAD_API_PTR *PFNGLGETNCOLORTABLEARBPROC)(GLenum target, GLenum format, GLenum type, GLsizei bufSize, void * table); +typedef void (GLAD_API_PTR *PFNGLGETNCOMPRESSEDTEXIMAGEARBPROC)(GLenum target, GLint lod, GLsizei bufSize, void * img); +typedef void (GLAD_API_PTR *PFNGLGETNCONVOLUTIONFILTERARBPROC)(GLenum target, GLenum format, GLenum type, GLsizei bufSize, void * image); +typedef void (GLAD_API_PTR *PFNGLGETNHISTOGRAMARBPROC)(GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, void * values); +typedef void (GLAD_API_PTR *PFNGLGETNMAPDVARBPROC)(GLenum target, GLenum query, GLsizei bufSize, GLdouble * v); +typedef void (GLAD_API_PTR *PFNGLGETNMAPFVARBPROC)(GLenum target, GLenum query, GLsizei bufSize, GLfloat * v); +typedef void (GLAD_API_PTR *PFNGLGETNMAPIVARBPROC)(GLenum target, GLenum query, GLsizei bufSize, GLint * v); +typedef void (GLAD_API_PTR *PFNGLGETNMINMAXARBPROC)(GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, void * values); +typedef void (GLAD_API_PTR *PFNGLGETNPIXELMAPFVARBPROC)(GLenum map, GLsizei bufSize, GLfloat * values); +typedef void (GLAD_API_PTR *PFNGLGETNPIXELMAPUIVARBPROC)(GLenum map, GLsizei bufSize, GLuint * values); +typedef void (GLAD_API_PTR *PFNGLGETNPIXELMAPUSVARBPROC)(GLenum map, GLsizei bufSize, GLushort * values); +typedef void (GLAD_API_PTR *PFNGLGETNPOLYGONSTIPPLEARBPROC)(GLsizei bufSize, GLubyte * pattern); +typedef void (GLAD_API_PTR *PFNGLGETNSEPARABLEFILTERARBPROC)(GLenum target, GLenum format, GLenum type, GLsizei rowBufSize, void * row, GLsizei columnBufSize, void * column, void * span); +typedef void (GLAD_API_PTR *PFNGLGETNTEXIMAGEARBPROC)(GLenum target, GLint level, GLenum format, GLenum type, GLsizei bufSize, void * img); +typedef void (GLAD_API_PTR *PFNGLGETNUNIFORMDVARBPROC)(GLuint program, GLint location, GLsizei bufSize, GLdouble * params); +typedef void (GLAD_API_PTR *PFNGLGETNUNIFORMFVARBPROC)(GLuint program, GLint location, GLsizei bufSize, GLfloat * params); +typedef void (GLAD_API_PTR *PFNGLGETNUNIFORMIVARBPROC)(GLuint program, GLint location, GLsizei bufSize, GLint * params); +typedef void (GLAD_API_PTR *PFNGLGETNUNIFORMUIVARBPROC)(GLuint program, GLint location, GLsizei bufSize, GLuint * params); +typedef void (GLAD_API_PTR *PFNGLHINTPROC)(GLenum target, GLenum mode); +typedef void (GLAD_API_PTR *PFNGLINDEXMASKPROC)(GLuint mask); +typedef void (GLAD_API_PTR *PFNGLINDEXPOINTERPROC)(GLenum type, GLsizei stride, const void * pointer); +typedef void (GLAD_API_PTR *PFNGLINDEXDPROC)(GLdouble c); +typedef void (GLAD_API_PTR *PFNGLINDEXDVPROC)(const GLdouble * c); +typedef void (GLAD_API_PTR *PFNGLINDEXFPROC)(GLfloat c); +typedef void (GLAD_API_PTR *PFNGLINDEXFVPROC)(const GLfloat * c); +typedef void (GLAD_API_PTR *PFNGLINDEXIPROC)(GLint c); +typedef void (GLAD_API_PTR *PFNGLINDEXIVPROC)(const GLint * c); +typedef void (GLAD_API_PTR *PFNGLINDEXSPROC)(GLshort c); +typedef void (GLAD_API_PTR *PFNGLINDEXSVPROC)(const GLshort * c); +typedef void (GLAD_API_PTR *PFNGLINDEXUBPROC)(GLubyte c); +typedef void (GLAD_API_PTR *PFNGLINDEXUBVPROC)(const GLubyte * c); +typedef void (GLAD_API_PTR *PFNGLINITNAMESPROC)(void); +typedef void (GLAD_API_PTR *PFNGLINTERLEAVEDARRAYSPROC)(GLenum format, GLsizei stride, const void * pointer); +typedef GLboolean (GLAD_API_PTR *PFNGLISBUFFERPROC)(GLuint buffer); +typedef GLboolean (GLAD_API_PTR *PFNGLISENABLEDPROC)(GLenum cap); +typedef GLboolean (GLAD_API_PTR *PFNGLISENABLEDIPROC)(GLenum target, GLuint index); +typedef GLboolean (GLAD_API_PTR *PFNGLISFRAMEBUFFERPROC)(GLuint framebuffer); +typedef GLboolean (GLAD_API_PTR *PFNGLISLISTPROC)(GLuint list); +typedef GLboolean (GLAD_API_PTR *PFNGLISPROGRAMPROC)(GLuint program); +typedef GLboolean (GLAD_API_PTR *PFNGLISQUERYPROC)(GLuint id); +typedef GLboolean (GLAD_API_PTR *PFNGLISRENDERBUFFERPROC)(GLuint renderbuffer); +typedef GLboolean (GLAD_API_PTR *PFNGLISSAMPLERPROC)(GLuint sampler); +typedef GLboolean (GLAD_API_PTR *PFNGLISSHADERPROC)(GLuint shader); +typedef GLboolean (GLAD_API_PTR *PFNGLISSYNCPROC)(GLsync sync); +typedef GLboolean (GLAD_API_PTR *PFNGLISTEXTUREPROC)(GLuint texture); +typedef GLboolean (GLAD_API_PTR *PFNGLISVERTEXARRAYPROC)(GLuint array); +typedef void (GLAD_API_PTR *PFNGLLIGHTMODELFPROC)(GLenum pname, GLfloat param); +typedef void (GLAD_API_PTR *PFNGLLIGHTMODELFVPROC)(GLenum pname, const GLfloat * params); +typedef void (GLAD_API_PTR *PFNGLLIGHTMODELIPROC)(GLenum pname, GLint param); +typedef void (GLAD_API_PTR *PFNGLLIGHTMODELIVPROC)(GLenum pname, const GLint * params); +typedef void (GLAD_API_PTR *PFNGLLIGHTFPROC)(GLenum light, GLenum pname, GLfloat param); +typedef void (GLAD_API_PTR *PFNGLLIGHTFVPROC)(GLenum light, GLenum pname, const GLfloat * params); +typedef void (GLAD_API_PTR *PFNGLLIGHTIPROC)(GLenum light, GLenum pname, GLint param); +typedef void (GLAD_API_PTR *PFNGLLIGHTIVPROC)(GLenum light, GLenum pname, const GLint * params); +typedef void (GLAD_API_PTR *PFNGLLINESTIPPLEPROC)(GLint factor, GLushort pattern); +typedef void (GLAD_API_PTR *PFNGLLINEWIDTHPROC)(GLfloat width); +typedef void (GLAD_API_PTR *PFNGLLINKPROGRAMPROC)(GLuint program); +typedef void (GLAD_API_PTR *PFNGLLISTBASEPROC)(GLuint base); +typedef void (GLAD_API_PTR *PFNGLLOADIDENTITYPROC)(void); +typedef void (GLAD_API_PTR *PFNGLLOADMATRIXDPROC)(const GLdouble * m); +typedef void (GLAD_API_PTR *PFNGLLOADMATRIXFPROC)(const GLfloat * m); +typedef void (GLAD_API_PTR *PFNGLLOADNAMEPROC)(GLuint name); +typedef void (GLAD_API_PTR *PFNGLLOADTRANSPOSEMATRIXDPROC)(const GLdouble * m); +typedef void (GLAD_API_PTR *PFNGLLOADTRANSPOSEMATRIXFPROC)(const GLfloat * m); +typedef void (GLAD_API_PTR *PFNGLLOGICOPPROC)(GLenum opcode); +typedef void (GLAD_API_PTR *PFNGLMAP1DPROC)(GLenum target, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble * points); +typedef void (GLAD_API_PTR *PFNGLMAP1FPROC)(GLenum target, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat * points); +typedef void (GLAD_API_PTR *PFNGLMAP2DPROC)(GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble * points); +typedef void (GLAD_API_PTR *PFNGLMAP2FPROC)(GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat * points); +typedef void * (GLAD_API_PTR *PFNGLMAPBUFFERPROC)(GLenum target, GLenum access); +typedef void * (GLAD_API_PTR *PFNGLMAPBUFFERRANGEPROC)(GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access); +typedef void (GLAD_API_PTR *PFNGLMAPGRID1DPROC)(GLint un, GLdouble u1, GLdouble u2); +typedef void (GLAD_API_PTR *PFNGLMAPGRID1FPROC)(GLint un, GLfloat u1, GLfloat u2); +typedef void (GLAD_API_PTR *PFNGLMAPGRID2DPROC)(GLint un, GLdouble u1, GLdouble u2, GLint vn, GLdouble v1, GLdouble v2); +typedef void (GLAD_API_PTR *PFNGLMAPGRID2FPROC)(GLint un, GLfloat u1, GLfloat u2, GLint vn, GLfloat v1, GLfloat v2); +typedef void (GLAD_API_PTR *PFNGLMATERIALFPROC)(GLenum face, GLenum pname, GLfloat param); +typedef void (GLAD_API_PTR *PFNGLMATERIALFVPROC)(GLenum face, GLenum pname, const GLfloat * params); +typedef void (GLAD_API_PTR *PFNGLMATERIALIPROC)(GLenum face, GLenum pname, GLint param); +typedef void (GLAD_API_PTR *PFNGLMATERIALIVPROC)(GLenum face, GLenum pname, const GLint * params); +typedef void (GLAD_API_PTR *PFNGLMATRIXMODEPROC)(GLenum mode); +typedef void (GLAD_API_PTR *PFNGLMULTMATRIXDPROC)(const GLdouble * m); +typedef void (GLAD_API_PTR *PFNGLMULTMATRIXFPROC)(const GLfloat * m); +typedef void (GLAD_API_PTR *PFNGLMULTTRANSPOSEMATRIXDPROC)(const GLdouble * m); +typedef void (GLAD_API_PTR *PFNGLMULTTRANSPOSEMATRIXFPROC)(const GLfloat * m); +typedef void (GLAD_API_PTR *PFNGLMULTIDRAWARRAYSPROC)(GLenum mode, const GLint * first, const GLsizei * count, GLsizei drawcount); +typedef void (GLAD_API_PTR *PFNGLMULTIDRAWELEMENTSPROC)(GLenum mode, const GLsizei * count, GLenum type, const void *const* indices, GLsizei drawcount); +typedef void (GLAD_API_PTR *PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC)(GLenum mode, const GLsizei * count, GLenum type, const void *const* indices, GLsizei drawcount, const GLint * basevertex); +typedef void (GLAD_API_PTR *PFNGLMULTITEXCOORD1DPROC)(GLenum target, GLdouble s); +typedef void (GLAD_API_PTR *PFNGLMULTITEXCOORD1DVPROC)(GLenum target, const GLdouble * v); +typedef void (GLAD_API_PTR *PFNGLMULTITEXCOORD1FPROC)(GLenum target, GLfloat s); +typedef void (GLAD_API_PTR *PFNGLMULTITEXCOORD1FVPROC)(GLenum target, const GLfloat * v); +typedef void (GLAD_API_PTR *PFNGLMULTITEXCOORD1IPROC)(GLenum target, GLint s); +typedef void (GLAD_API_PTR *PFNGLMULTITEXCOORD1IVPROC)(GLenum target, const GLint * v); +typedef void (GLAD_API_PTR *PFNGLMULTITEXCOORD1SPROC)(GLenum target, GLshort s); +typedef void (GLAD_API_PTR *PFNGLMULTITEXCOORD1SVPROC)(GLenum target, const GLshort * v); +typedef void (GLAD_API_PTR *PFNGLMULTITEXCOORD2DPROC)(GLenum target, GLdouble s, GLdouble t); +typedef void (GLAD_API_PTR *PFNGLMULTITEXCOORD2DVPROC)(GLenum target, const GLdouble * v); +typedef void (GLAD_API_PTR *PFNGLMULTITEXCOORD2FPROC)(GLenum target, GLfloat s, GLfloat t); +typedef void (GLAD_API_PTR *PFNGLMULTITEXCOORD2FVPROC)(GLenum target, const GLfloat * v); +typedef void (GLAD_API_PTR *PFNGLMULTITEXCOORD2IPROC)(GLenum target, GLint s, GLint t); +typedef void (GLAD_API_PTR *PFNGLMULTITEXCOORD2IVPROC)(GLenum target, const GLint * v); +typedef void (GLAD_API_PTR *PFNGLMULTITEXCOORD2SPROC)(GLenum target, GLshort s, GLshort t); +typedef void (GLAD_API_PTR *PFNGLMULTITEXCOORD2SVPROC)(GLenum target, const GLshort * v); +typedef void (GLAD_API_PTR *PFNGLMULTITEXCOORD3DPROC)(GLenum target, GLdouble s, GLdouble t, GLdouble r); +typedef void (GLAD_API_PTR *PFNGLMULTITEXCOORD3DVPROC)(GLenum target, const GLdouble * v); +typedef void (GLAD_API_PTR *PFNGLMULTITEXCOORD3FPROC)(GLenum target, GLfloat s, GLfloat t, GLfloat r); +typedef void (GLAD_API_PTR *PFNGLMULTITEXCOORD3FVPROC)(GLenum target, const GLfloat * v); +typedef void (GLAD_API_PTR *PFNGLMULTITEXCOORD3IPROC)(GLenum target, GLint s, GLint t, GLint r); +typedef void (GLAD_API_PTR *PFNGLMULTITEXCOORD3IVPROC)(GLenum target, const GLint * v); +typedef void (GLAD_API_PTR *PFNGLMULTITEXCOORD3SPROC)(GLenum target, GLshort s, GLshort t, GLshort r); +typedef void (GLAD_API_PTR *PFNGLMULTITEXCOORD3SVPROC)(GLenum target, const GLshort * v); +typedef void (GLAD_API_PTR *PFNGLMULTITEXCOORD4DPROC)(GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q); +typedef void (GLAD_API_PTR *PFNGLMULTITEXCOORD4DVPROC)(GLenum target, const GLdouble * v); +typedef void (GLAD_API_PTR *PFNGLMULTITEXCOORD4FPROC)(GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q); +typedef void (GLAD_API_PTR *PFNGLMULTITEXCOORD4FVPROC)(GLenum target, const GLfloat * v); +typedef void (GLAD_API_PTR *PFNGLMULTITEXCOORD4IPROC)(GLenum target, GLint s, GLint t, GLint r, GLint q); +typedef void (GLAD_API_PTR *PFNGLMULTITEXCOORD4IVPROC)(GLenum target, const GLint * v); +typedef void (GLAD_API_PTR *PFNGLMULTITEXCOORD4SPROC)(GLenum target, GLshort s, GLshort t, GLshort r, GLshort q); +typedef void (GLAD_API_PTR *PFNGLMULTITEXCOORD4SVPROC)(GLenum target, const GLshort * v); +typedef void (GLAD_API_PTR *PFNGLMULTITEXCOORDP1UIPROC)(GLenum texture, GLenum type, GLuint coords); +typedef void (GLAD_API_PTR *PFNGLMULTITEXCOORDP1UIVPROC)(GLenum texture, GLenum type, const GLuint * coords); +typedef void (GLAD_API_PTR *PFNGLMULTITEXCOORDP2UIPROC)(GLenum texture, GLenum type, GLuint coords); +typedef void (GLAD_API_PTR *PFNGLMULTITEXCOORDP2UIVPROC)(GLenum texture, GLenum type, const GLuint * coords); +typedef void (GLAD_API_PTR *PFNGLMULTITEXCOORDP3UIPROC)(GLenum texture, GLenum type, GLuint coords); +typedef void (GLAD_API_PTR *PFNGLMULTITEXCOORDP3UIVPROC)(GLenum texture, GLenum type, const GLuint * coords); +typedef void (GLAD_API_PTR *PFNGLMULTITEXCOORDP4UIPROC)(GLenum texture, GLenum type, GLuint coords); +typedef void (GLAD_API_PTR *PFNGLMULTITEXCOORDP4UIVPROC)(GLenum texture, GLenum type, const GLuint * coords); +typedef void (GLAD_API_PTR *PFNGLNEWLISTPROC)(GLuint list, GLenum mode); +typedef void (GLAD_API_PTR *PFNGLNORMAL3BPROC)(GLbyte nx, GLbyte ny, GLbyte nz); +typedef void (GLAD_API_PTR *PFNGLNORMAL3BVPROC)(const GLbyte * v); +typedef void (GLAD_API_PTR *PFNGLNORMAL3DPROC)(GLdouble nx, GLdouble ny, GLdouble nz); +typedef void (GLAD_API_PTR *PFNGLNORMAL3DVPROC)(const GLdouble * v); +typedef void (GLAD_API_PTR *PFNGLNORMAL3FPROC)(GLfloat nx, GLfloat ny, GLfloat nz); +typedef void (GLAD_API_PTR *PFNGLNORMAL3FVPROC)(const GLfloat * v); +typedef void (GLAD_API_PTR *PFNGLNORMAL3IPROC)(GLint nx, GLint ny, GLint nz); +typedef void (GLAD_API_PTR *PFNGLNORMAL3IVPROC)(const GLint * v); +typedef void (GLAD_API_PTR *PFNGLNORMAL3SPROC)(GLshort nx, GLshort ny, GLshort nz); +typedef void (GLAD_API_PTR *PFNGLNORMAL3SVPROC)(const GLshort * v); +typedef void (GLAD_API_PTR *PFNGLNORMALP3UIPROC)(GLenum type, GLuint coords); +typedef void (GLAD_API_PTR *PFNGLNORMALP3UIVPROC)(GLenum type, const GLuint * coords); +typedef void (GLAD_API_PTR *PFNGLNORMALPOINTERPROC)(GLenum type, GLsizei stride, const void * pointer); +typedef void (GLAD_API_PTR *PFNGLOBJECTLABELPROC)(GLenum identifier, GLuint name, GLsizei length, const GLchar * label); +typedef void (GLAD_API_PTR *PFNGLOBJECTPTRLABELPROC)(const void * ptr, GLsizei length, const GLchar * label); +typedef void (GLAD_API_PTR *PFNGLORTHOPROC)(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); +typedef void (GLAD_API_PTR *PFNGLPASSTHROUGHPROC)(GLfloat token); +typedef void (GLAD_API_PTR *PFNGLPIXELMAPFVPROC)(GLenum map, GLsizei mapsize, const GLfloat * values); +typedef void (GLAD_API_PTR *PFNGLPIXELMAPUIVPROC)(GLenum map, GLsizei mapsize, const GLuint * values); +typedef void (GLAD_API_PTR *PFNGLPIXELMAPUSVPROC)(GLenum map, GLsizei mapsize, const GLushort * values); +typedef void (GLAD_API_PTR *PFNGLPIXELSTOREFPROC)(GLenum pname, GLfloat param); +typedef void (GLAD_API_PTR *PFNGLPIXELSTOREIPROC)(GLenum pname, GLint param); +typedef void (GLAD_API_PTR *PFNGLPIXELTRANSFERFPROC)(GLenum pname, GLfloat param); +typedef void (GLAD_API_PTR *PFNGLPIXELTRANSFERIPROC)(GLenum pname, GLint param); +typedef void (GLAD_API_PTR *PFNGLPIXELZOOMPROC)(GLfloat xfactor, GLfloat yfactor); +typedef void (GLAD_API_PTR *PFNGLPOINTPARAMETERFPROC)(GLenum pname, GLfloat param); +typedef void (GLAD_API_PTR *PFNGLPOINTPARAMETERFVPROC)(GLenum pname, const GLfloat * params); +typedef void (GLAD_API_PTR *PFNGLPOINTPARAMETERIPROC)(GLenum pname, GLint param); +typedef void (GLAD_API_PTR *PFNGLPOINTPARAMETERIVPROC)(GLenum pname, const GLint * params); +typedef void (GLAD_API_PTR *PFNGLPOINTSIZEPROC)(GLfloat size); +typedef void (GLAD_API_PTR *PFNGLPOLYGONMODEPROC)(GLenum face, GLenum mode); +typedef void (GLAD_API_PTR *PFNGLPOLYGONOFFSETPROC)(GLfloat factor, GLfloat units); +typedef void (GLAD_API_PTR *PFNGLPOLYGONSTIPPLEPROC)(const GLubyte * mask); +typedef void (GLAD_API_PTR *PFNGLPOPATTRIBPROC)(void); +typedef void (GLAD_API_PTR *PFNGLPOPCLIENTATTRIBPROC)(void); +typedef void (GLAD_API_PTR *PFNGLPOPDEBUGGROUPPROC)(void); +typedef void (GLAD_API_PTR *PFNGLPOPMATRIXPROC)(void); +typedef void (GLAD_API_PTR *PFNGLPOPNAMEPROC)(void); +typedef void (GLAD_API_PTR *PFNGLPRIMITIVERESTARTINDEXPROC)(GLuint index); +typedef void (GLAD_API_PTR *PFNGLPRIORITIZETEXTURESPROC)(GLsizei n, const GLuint * textures, const GLfloat * priorities); +typedef void (GLAD_API_PTR *PFNGLPROVOKINGVERTEXPROC)(GLenum mode); +typedef void (GLAD_API_PTR *PFNGLPUSHATTRIBPROC)(GLbitfield mask); +typedef void (GLAD_API_PTR *PFNGLPUSHCLIENTATTRIBPROC)(GLbitfield mask); +typedef void (GLAD_API_PTR *PFNGLPUSHDEBUGGROUPPROC)(GLenum source, GLuint id, GLsizei length, const GLchar * message); +typedef void (GLAD_API_PTR *PFNGLPUSHMATRIXPROC)(void); +typedef void (GLAD_API_PTR *PFNGLPUSHNAMEPROC)(GLuint name); +typedef void (GLAD_API_PTR *PFNGLQUERYCOUNTERPROC)(GLuint id, GLenum target); +typedef void (GLAD_API_PTR *PFNGLRASTERPOS2DPROC)(GLdouble x, GLdouble y); +typedef void (GLAD_API_PTR *PFNGLRASTERPOS2DVPROC)(const GLdouble * v); +typedef void (GLAD_API_PTR *PFNGLRASTERPOS2FPROC)(GLfloat x, GLfloat y); +typedef void (GLAD_API_PTR *PFNGLRASTERPOS2FVPROC)(const GLfloat * v); +typedef void (GLAD_API_PTR *PFNGLRASTERPOS2IPROC)(GLint x, GLint y); +typedef void (GLAD_API_PTR *PFNGLRASTERPOS2IVPROC)(const GLint * v); +typedef void (GLAD_API_PTR *PFNGLRASTERPOS2SPROC)(GLshort x, GLshort y); +typedef void (GLAD_API_PTR *PFNGLRASTERPOS2SVPROC)(const GLshort * v); +typedef void (GLAD_API_PTR *PFNGLRASTERPOS3DPROC)(GLdouble x, GLdouble y, GLdouble z); +typedef void (GLAD_API_PTR *PFNGLRASTERPOS3DVPROC)(const GLdouble * v); +typedef void (GLAD_API_PTR *PFNGLRASTERPOS3FPROC)(GLfloat x, GLfloat y, GLfloat z); +typedef void (GLAD_API_PTR *PFNGLRASTERPOS3FVPROC)(const GLfloat * v); +typedef void (GLAD_API_PTR *PFNGLRASTERPOS3IPROC)(GLint x, GLint y, GLint z); +typedef void (GLAD_API_PTR *PFNGLRASTERPOS3IVPROC)(const GLint * v); +typedef void (GLAD_API_PTR *PFNGLRASTERPOS3SPROC)(GLshort x, GLshort y, GLshort z); +typedef void (GLAD_API_PTR *PFNGLRASTERPOS3SVPROC)(const GLshort * v); +typedef void (GLAD_API_PTR *PFNGLRASTERPOS4DPROC)(GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (GLAD_API_PTR *PFNGLRASTERPOS4DVPROC)(const GLdouble * v); +typedef void (GLAD_API_PTR *PFNGLRASTERPOS4FPROC)(GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (GLAD_API_PTR *PFNGLRASTERPOS4FVPROC)(const GLfloat * v); +typedef void (GLAD_API_PTR *PFNGLRASTERPOS4IPROC)(GLint x, GLint y, GLint z, GLint w); +typedef void (GLAD_API_PTR *PFNGLRASTERPOS4IVPROC)(const GLint * v); +typedef void (GLAD_API_PTR *PFNGLRASTERPOS4SPROC)(GLshort x, GLshort y, GLshort z, GLshort w); +typedef void (GLAD_API_PTR *PFNGLRASTERPOS4SVPROC)(const GLshort * v); +typedef void (GLAD_API_PTR *PFNGLREADBUFFERPROC)(GLenum src); +typedef void (GLAD_API_PTR *PFNGLREADPIXELSPROC)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void * pixels); +typedef void (GLAD_API_PTR *PFNGLREADNPIXELSPROC)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void * data); +typedef void (GLAD_API_PTR *PFNGLREADNPIXELSARBPROC)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void * data); +typedef void (GLAD_API_PTR *PFNGLRECTDPROC)(GLdouble x1, GLdouble y1, GLdouble x2, GLdouble y2); +typedef void (GLAD_API_PTR *PFNGLRECTDVPROC)(const GLdouble * v1, const GLdouble * v2); +typedef void (GLAD_API_PTR *PFNGLRECTFPROC)(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2); +typedef void (GLAD_API_PTR *PFNGLRECTFVPROC)(const GLfloat * v1, const GLfloat * v2); +typedef void (GLAD_API_PTR *PFNGLRECTIPROC)(GLint x1, GLint y1, GLint x2, GLint y2); +typedef void (GLAD_API_PTR *PFNGLRECTIVPROC)(const GLint * v1, const GLint * v2); +typedef void (GLAD_API_PTR *PFNGLRECTSPROC)(GLshort x1, GLshort y1, GLshort x2, GLshort y2); +typedef void (GLAD_API_PTR *PFNGLRECTSVPROC)(const GLshort * v1, const GLshort * v2); +typedef GLint (GLAD_API_PTR *PFNGLRENDERMODEPROC)(GLenum mode); +typedef void (GLAD_API_PTR *PFNGLRENDERBUFFERSTORAGEPROC)(GLenum target, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (GLAD_API_PTR *PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (GLAD_API_PTR *PFNGLROTATEDPROC)(GLdouble angle, GLdouble x, GLdouble y, GLdouble z); +typedef void (GLAD_API_PTR *PFNGLROTATEFPROC)(GLfloat angle, GLfloat x, GLfloat y, GLfloat z); +typedef void (GLAD_API_PTR *PFNGLSAMPLECOVERAGEPROC)(GLfloat value, GLboolean invert); +typedef void (GLAD_API_PTR *PFNGLSAMPLECOVERAGEARBPROC)(GLfloat value, GLboolean invert); +typedef void (GLAD_API_PTR *PFNGLSAMPLEMASKIPROC)(GLuint maskNumber, GLbitfield mask); +typedef void (GLAD_API_PTR *PFNGLSAMPLERPARAMETERIIVPROC)(GLuint sampler, GLenum pname, const GLint * param); +typedef void (GLAD_API_PTR *PFNGLSAMPLERPARAMETERIUIVPROC)(GLuint sampler, GLenum pname, const GLuint * param); +typedef void (GLAD_API_PTR *PFNGLSAMPLERPARAMETERFPROC)(GLuint sampler, GLenum pname, GLfloat param); +typedef void (GLAD_API_PTR *PFNGLSAMPLERPARAMETERFVPROC)(GLuint sampler, GLenum pname, const GLfloat * param); +typedef void (GLAD_API_PTR *PFNGLSAMPLERPARAMETERIPROC)(GLuint sampler, GLenum pname, GLint param); +typedef void (GLAD_API_PTR *PFNGLSAMPLERPARAMETERIVPROC)(GLuint sampler, GLenum pname, const GLint * param); +typedef void (GLAD_API_PTR *PFNGLSCALEDPROC)(GLdouble x, GLdouble y, GLdouble z); +typedef void (GLAD_API_PTR *PFNGLSCALEFPROC)(GLfloat x, GLfloat y, GLfloat z); +typedef void (GLAD_API_PTR *PFNGLSCISSORPROC)(GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (GLAD_API_PTR *PFNGLSECONDARYCOLOR3BPROC)(GLbyte red, GLbyte green, GLbyte blue); +typedef void (GLAD_API_PTR *PFNGLSECONDARYCOLOR3BVPROC)(const GLbyte * v); +typedef void (GLAD_API_PTR *PFNGLSECONDARYCOLOR3DPROC)(GLdouble red, GLdouble green, GLdouble blue); +typedef void (GLAD_API_PTR *PFNGLSECONDARYCOLOR3DVPROC)(const GLdouble * v); +typedef void (GLAD_API_PTR *PFNGLSECONDARYCOLOR3FPROC)(GLfloat red, GLfloat green, GLfloat blue); +typedef void (GLAD_API_PTR *PFNGLSECONDARYCOLOR3FVPROC)(const GLfloat * v); +typedef void (GLAD_API_PTR *PFNGLSECONDARYCOLOR3IPROC)(GLint red, GLint green, GLint blue); +typedef void (GLAD_API_PTR *PFNGLSECONDARYCOLOR3IVPROC)(const GLint * v); +typedef void (GLAD_API_PTR *PFNGLSECONDARYCOLOR3SPROC)(GLshort red, GLshort green, GLshort blue); +typedef void (GLAD_API_PTR *PFNGLSECONDARYCOLOR3SVPROC)(const GLshort * v); +typedef void (GLAD_API_PTR *PFNGLSECONDARYCOLOR3UBPROC)(GLubyte red, GLubyte green, GLubyte blue); +typedef void (GLAD_API_PTR *PFNGLSECONDARYCOLOR3UBVPROC)(const GLubyte * v); +typedef void (GLAD_API_PTR *PFNGLSECONDARYCOLOR3UIPROC)(GLuint red, GLuint green, GLuint blue); +typedef void (GLAD_API_PTR *PFNGLSECONDARYCOLOR3UIVPROC)(const GLuint * v); +typedef void (GLAD_API_PTR *PFNGLSECONDARYCOLOR3USPROC)(GLushort red, GLushort green, GLushort blue); +typedef void (GLAD_API_PTR *PFNGLSECONDARYCOLOR3USVPROC)(const GLushort * v); +typedef void (GLAD_API_PTR *PFNGLSECONDARYCOLORP3UIPROC)(GLenum type, GLuint color); +typedef void (GLAD_API_PTR *PFNGLSECONDARYCOLORP3UIVPROC)(GLenum type, const GLuint * color); +typedef void (GLAD_API_PTR *PFNGLSECONDARYCOLORPOINTERPROC)(GLint size, GLenum type, GLsizei stride, const void * pointer); +typedef void (GLAD_API_PTR *PFNGLSELECTBUFFERPROC)(GLsizei size, GLuint * buffer); +typedef void (GLAD_API_PTR *PFNGLSHADEMODELPROC)(GLenum mode); +typedef void (GLAD_API_PTR *PFNGLSHADERSOURCEPROC)(GLuint shader, GLsizei count, const GLchar *const* string, const GLint * length); +typedef void (GLAD_API_PTR *PFNGLSTENCILFUNCPROC)(GLenum func, GLint ref, GLuint mask); +typedef void (GLAD_API_PTR *PFNGLSTENCILFUNCSEPARATEPROC)(GLenum face, GLenum func, GLint ref, GLuint mask); +typedef void (GLAD_API_PTR *PFNGLSTENCILMASKPROC)(GLuint mask); +typedef void (GLAD_API_PTR *PFNGLSTENCILMASKSEPARATEPROC)(GLenum face, GLuint mask); +typedef void (GLAD_API_PTR *PFNGLSTENCILOPPROC)(GLenum fail, GLenum zfail, GLenum zpass); +typedef void (GLAD_API_PTR *PFNGLSTENCILOPSEPARATEPROC)(GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); +typedef void (GLAD_API_PTR *PFNGLTEXBUFFERPROC)(GLenum target, GLenum internalformat, GLuint buffer); +typedef void (GLAD_API_PTR *PFNGLTEXCOORD1DPROC)(GLdouble s); +typedef void (GLAD_API_PTR *PFNGLTEXCOORD1DVPROC)(const GLdouble * v); +typedef void (GLAD_API_PTR *PFNGLTEXCOORD1FPROC)(GLfloat s); +typedef void (GLAD_API_PTR *PFNGLTEXCOORD1FVPROC)(const GLfloat * v); +typedef void (GLAD_API_PTR *PFNGLTEXCOORD1IPROC)(GLint s); +typedef void (GLAD_API_PTR *PFNGLTEXCOORD1IVPROC)(const GLint * v); +typedef void (GLAD_API_PTR *PFNGLTEXCOORD1SPROC)(GLshort s); +typedef void (GLAD_API_PTR *PFNGLTEXCOORD1SVPROC)(const GLshort * v); +typedef void (GLAD_API_PTR *PFNGLTEXCOORD2DPROC)(GLdouble s, GLdouble t); +typedef void (GLAD_API_PTR *PFNGLTEXCOORD2DVPROC)(const GLdouble * v); +typedef void (GLAD_API_PTR *PFNGLTEXCOORD2FPROC)(GLfloat s, GLfloat t); +typedef void (GLAD_API_PTR *PFNGLTEXCOORD2FVPROC)(const GLfloat * v); +typedef void (GLAD_API_PTR *PFNGLTEXCOORD2IPROC)(GLint s, GLint t); +typedef void (GLAD_API_PTR *PFNGLTEXCOORD2IVPROC)(const GLint * v); +typedef void (GLAD_API_PTR *PFNGLTEXCOORD2SPROC)(GLshort s, GLshort t); +typedef void (GLAD_API_PTR *PFNGLTEXCOORD2SVPROC)(const GLshort * v); +typedef void (GLAD_API_PTR *PFNGLTEXCOORD3DPROC)(GLdouble s, GLdouble t, GLdouble r); +typedef void (GLAD_API_PTR *PFNGLTEXCOORD3DVPROC)(const GLdouble * v); +typedef void (GLAD_API_PTR *PFNGLTEXCOORD3FPROC)(GLfloat s, GLfloat t, GLfloat r); +typedef void (GLAD_API_PTR *PFNGLTEXCOORD3FVPROC)(const GLfloat * v); +typedef void (GLAD_API_PTR *PFNGLTEXCOORD3IPROC)(GLint s, GLint t, GLint r); +typedef void (GLAD_API_PTR *PFNGLTEXCOORD3IVPROC)(const GLint * v); +typedef void (GLAD_API_PTR *PFNGLTEXCOORD3SPROC)(GLshort s, GLshort t, GLshort r); +typedef void (GLAD_API_PTR *PFNGLTEXCOORD3SVPROC)(const GLshort * v); +typedef void (GLAD_API_PTR *PFNGLTEXCOORD4DPROC)(GLdouble s, GLdouble t, GLdouble r, GLdouble q); +typedef void (GLAD_API_PTR *PFNGLTEXCOORD4DVPROC)(const GLdouble * v); +typedef void (GLAD_API_PTR *PFNGLTEXCOORD4FPROC)(GLfloat s, GLfloat t, GLfloat r, GLfloat q); +typedef void (GLAD_API_PTR *PFNGLTEXCOORD4FVPROC)(const GLfloat * v); +typedef void (GLAD_API_PTR *PFNGLTEXCOORD4IPROC)(GLint s, GLint t, GLint r, GLint q); +typedef void (GLAD_API_PTR *PFNGLTEXCOORD4IVPROC)(const GLint * v); +typedef void (GLAD_API_PTR *PFNGLTEXCOORD4SPROC)(GLshort s, GLshort t, GLshort r, GLshort q); +typedef void (GLAD_API_PTR *PFNGLTEXCOORD4SVPROC)(const GLshort * v); +typedef void (GLAD_API_PTR *PFNGLTEXCOORDP1UIPROC)(GLenum type, GLuint coords); +typedef void (GLAD_API_PTR *PFNGLTEXCOORDP1UIVPROC)(GLenum type, const GLuint * coords); +typedef void (GLAD_API_PTR *PFNGLTEXCOORDP2UIPROC)(GLenum type, GLuint coords); +typedef void (GLAD_API_PTR *PFNGLTEXCOORDP2UIVPROC)(GLenum type, const GLuint * coords); +typedef void (GLAD_API_PTR *PFNGLTEXCOORDP3UIPROC)(GLenum type, GLuint coords); +typedef void (GLAD_API_PTR *PFNGLTEXCOORDP3UIVPROC)(GLenum type, const GLuint * coords); +typedef void (GLAD_API_PTR *PFNGLTEXCOORDP4UIPROC)(GLenum type, GLuint coords); +typedef void (GLAD_API_PTR *PFNGLTEXCOORDP4UIVPROC)(GLenum type, const GLuint * coords); +typedef void (GLAD_API_PTR *PFNGLTEXCOORDPOINTERPROC)(GLint size, GLenum type, GLsizei stride, const void * pointer); +typedef void (GLAD_API_PTR *PFNGLTEXENVFPROC)(GLenum target, GLenum pname, GLfloat param); +typedef void (GLAD_API_PTR *PFNGLTEXENVFVPROC)(GLenum target, GLenum pname, const GLfloat * params); +typedef void (GLAD_API_PTR *PFNGLTEXENVIPROC)(GLenum target, GLenum pname, GLint param); +typedef void (GLAD_API_PTR *PFNGLTEXENVIVPROC)(GLenum target, GLenum pname, const GLint * params); +typedef void (GLAD_API_PTR *PFNGLTEXGENDPROC)(GLenum coord, GLenum pname, GLdouble param); +typedef void (GLAD_API_PTR *PFNGLTEXGENDVPROC)(GLenum coord, GLenum pname, const GLdouble * params); +typedef void (GLAD_API_PTR *PFNGLTEXGENFPROC)(GLenum coord, GLenum pname, GLfloat param); +typedef void (GLAD_API_PTR *PFNGLTEXGENFVPROC)(GLenum coord, GLenum pname, const GLfloat * params); +typedef void (GLAD_API_PTR *PFNGLTEXGENIPROC)(GLenum coord, GLenum pname, GLint param); +typedef void (GLAD_API_PTR *PFNGLTEXGENIVPROC)(GLenum coord, GLenum pname, const GLint * params); +typedef void (GLAD_API_PTR *PFNGLTEXIMAGE1DPROC)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void * pixels); +typedef void (GLAD_API_PTR *PFNGLTEXIMAGE2DPROC)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void * pixels); +typedef void (GLAD_API_PTR *PFNGLTEXIMAGE2DMULTISAMPLEPROC)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); +typedef void (GLAD_API_PTR *PFNGLTEXIMAGE3DPROC)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void * pixels); +typedef void (GLAD_API_PTR *PFNGLTEXIMAGE3DMULTISAMPLEPROC)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); +typedef void (GLAD_API_PTR *PFNGLTEXPARAMETERIIVPROC)(GLenum target, GLenum pname, const GLint * params); +typedef void (GLAD_API_PTR *PFNGLTEXPARAMETERIUIVPROC)(GLenum target, GLenum pname, const GLuint * params); +typedef void (GLAD_API_PTR *PFNGLTEXPARAMETERFPROC)(GLenum target, GLenum pname, GLfloat param); +typedef void (GLAD_API_PTR *PFNGLTEXPARAMETERFVPROC)(GLenum target, GLenum pname, const GLfloat * params); +typedef void (GLAD_API_PTR *PFNGLTEXPARAMETERIPROC)(GLenum target, GLenum pname, GLint param); +typedef void (GLAD_API_PTR *PFNGLTEXPARAMETERIVPROC)(GLenum target, GLenum pname, const GLint * params); +typedef void (GLAD_API_PTR *PFNGLTEXSUBIMAGE1DPROC)(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void * pixels); +typedef void (GLAD_API_PTR *PFNGLTEXSUBIMAGE2DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void * pixels); +typedef void (GLAD_API_PTR *PFNGLTEXSUBIMAGE3DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void * pixels); +typedef void (GLAD_API_PTR *PFNGLTRANSFORMFEEDBACKVARYINGSPROC)(GLuint program, GLsizei count, const GLchar *const* varyings, GLenum bufferMode); +typedef void (GLAD_API_PTR *PFNGLTRANSLATEDPROC)(GLdouble x, GLdouble y, GLdouble z); +typedef void (GLAD_API_PTR *PFNGLTRANSLATEFPROC)(GLfloat x, GLfloat y, GLfloat z); +typedef void (GLAD_API_PTR *PFNGLUNIFORM1FPROC)(GLint location, GLfloat v0); +typedef void (GLAD_API_PTR *PFNGLUNIFORM1FVPROC)(GLint location, GLsizei count, const GLfloat * value); +typedef void (GLAD_API_PTR *PFNGLUNIFORM1IPROC)(GLint location, GLint v0); +typedef void (GLAD_API_PTR *PFNGLUNIFORM1IVPROC)(GLint location, GLsizei count, const GLint * value); +typedef void (GLAD_API_PTR *PFNGLUNIFORM1UIPROC)(GLint location, GLuint v0); +typedef void (GLAD_API_PTR *PFNGLUNIFORM1UIVPROC)(GLint location, GLsizei count, const GLuint * value); +typedef void (GLAD_API_PTR *PFNGLUNIFORM2FPROC)(GLint location, GLfloat v0, GLfloat v1); +typedef void (GLAD_API_PTR *PFNGLUNIFORM2FVPROC)(GLint location, GLsizei count, const GLfloat * value); +typedef void (GLAD_API_PTR *PFNGLUNIFORM2IPROC)(GLint location, GLint v0, GLint v1); +typedef void (GLAD_API_PTR *PFNGLUNIFORM2IVPROC)(GLint location, GLsizei count, const GLint * value); +typedef void (GLAD_API_PTR *PFNGLUNIFORM2UIPROC)(GLint location, GLuint v0, GLuint v1); +typedef void (GLAD_API_PTR *PFNGLUNIFORM2UIVPROC)(GLint location, GLsizei count, const GLuint * value); +typedef void (GLAD_API_PTR *PFNGLUNIFORM3FPROC)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2); +typedef void (GLAD_API_PTR *PFNGLUNIFORM3FVPROC)(GLint location, GLsizei count, const GLfloat * value); +typedef void (GLAD_API_PTR *PFNGLUNIFORM3IPROC)(GLint location, GLint v0, GLint v1, GLint v2); +typedef void (GLAD_API_PTR *PFNGLUNIFORM3IVPROC)(GLint location, GLsizei count, const GLint * value); +typedef void (GLAD_API_PTR *PFNGLUNIFORM3UIPROC)(GLint location, GLuint v0, GLuint v1, GLuint v2); +typedef void (GLAD_API_PTR *PFNGLUNIFORM3UIVPROC)(GLint location, GLsizei count, const GLuint * value); +typedef void (GLAD_API_PTR *PFNGLUNIFORM4FPROC)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); +typedef void (GLAD_API_PTR *PFNGLUNIFORM4FVPROC)(GLint location, GLsizei count, const GLfloat * value); +typedef void (GLAD_API_PTR *PFNGLUNIFORM4IPROC)(GLint location, GLint v0, GLint v1, GLint v2, GLint v3); +typedef void (GLAD_API_PTR *PFNGLUNIFORM4IVPROC)(GLint location, GLsizei count, const GLint * value); +typedef void (GLAD_API_PTR *PFNGLUNIFORM4UIPROC)(GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); +typedef void (GLAD_API_PTR *PFNGLUNIFORM4UIVPROC)(GLint location, GLsizei count, const GLuint * value); +typedef void (GLAD_API_PTR *PFNGLUNIFORMBLOCKBINDINGPROC)(GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding); +typedef void (GLAD_API_PTR *PFNGLUNIFORMMATRIX2FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value); +typedef void (GLAD_API_PTR *PFNGLUNIFORMMATRIX2X3FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value); +typedef void (GLAD_API_PTR *PFNGLUNIFORMMATRIX2X4FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value); +typedef void (GLAD_API_PTR *PFNGLUNIFORMMATRIX3FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value); +typedef void (GLAD_API_PTR *PFNGLUNIFORMMATRIX3X2FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value); +typedef void (GLAD_API_PTR *PFNGLUNIFORMMATRIX3X4FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value); +typedef void (GLAD_API_PTR *PFNGLUNIFORMMATRIX4FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value); +typedef void (GLAD_API_PTR *PFNGLUNIFORMMATRIX4X2FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value); +typedef void (GLAD_API_PTR *PFNGLUNIFORMMATRIX4X3FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat * value); +typedef GLboolean (GLAD_API_PTR *PFNGLUNMAPBUFFERPROC)(GLenum target); +typedef void (GLAD_API_PTR *PFNGLUSEPROGRAMPROC)(GLuint program); +typedef void (GLAD_API_PTR *PFNGLVALIDATEPROGRAMPROC)(GLuint program); +typedef void (GLAD_API_PTR *PFNGLVERTEX2DPROC)(GLdouble x, GLdouble y); +typedef void (GLAD_API_PTR *PFNGLVERTEX2DVPROC)(const GLdouble * v); +typedef void (GLAD_API_PTR *PFNGLVERTEX2FPROC)(GLfloat x, GLfloat y); +typedef void (GLAD_API_PTR *PFNGLVERTEX2FVPROC)(const GLfloat * v); +typedef void (GLAD_API_PTR *PFNGLVERTEX2IPROC)(GLint x, GLint y); +typedef void (GLAD_API_PTR *PFNGLVERTEX2IVPROC)(const GLint * v); +typedef void (GLAD_API_PTR *PFNGLVERTEX2SPROC)(GLshort x, GLshort y); +typedef void (GLAD_API_PTR *PFNGLVERTEX2SVPROC)(const GLshort * v); +typedef void (GLAD_API_PTR *PFNGLVERTEX3DPROC)(GLdouble x, GLdouble y, GLdouble z); +typedef void (GLAD_API_PTR *PFNGLVERTEX3DVPROC)(const GLdouble * v); +typedef void (GLAD_API_PTR *PFNGLVERTEX3FPROC)(GLfloat x, GLfloat y, GLfloat z); +typedef void (GLAD_API_PTR *PFNGLVERTEX3FVPROC)(const GLfloat * v); +typedef void (GLAD_API_PTR *PFNGLVERTEX3IPROC)(GLint x, GLint y, GLint z); +typedef void (GLAD_API_PTR *PFNGLVERTEX3IVPROC)(const GLint * v); +typedef void (GLAD_API_PTR *PFNGLVERTEX3SPROC)(GLshort x, GLshort y, GLshort z); +typedef void (GLAD_API_PTR *PFNGLVERTEX3SVPROC)(const GLshort * v); +typedef void (GLAD_API_PTR *PFNGLVERTEX4DPROC)(GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (GLAD_API_PTR *PFNGLVERTEX4DVPROC)(const GLdouble * v); +typedef void (GLAD_API_PTR *PFNGLVERTEX4FPROC)(GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (GLAD_API_PTR *PFNGLVERTEX4FVPROC)(const GLfloat * v); +typedef void (GLAD_API_PTR *PFNGLVERTEX4IPROC)(GLint x, GLint y, GLint z, GLint w); +typedef void (GLAD_API_PTR *PFNGLVERTEX4IVPROC)(const GLint * v); +typedef void (GLAD_API_PTR *PFNGLVERTEX4SPROC)(GLshort x, GLshort y, GLshort z, GLshort w); +typedef void (GLAD_API_PTR *PFNGLVERTEX4SVPROC)(const GLshort * v); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIB1DPROC)(GLuint index, GLdouble x); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIB1DVPROC)(GLuint index, const GLdouble * v); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIB1FPROC)(GLuint index, GLfloat x); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIB1FVPROC)(GLuint index, const GLfloat * v); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIB1SPROC)(GLuint index, GLshort x); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIB1SVPROC)(GLuint index, const GLshort * v); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIB2DPROC)(GLuint index, GLdouble x, GLdouble y); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIB2DVPROC)(GLuint index, const GLdouble * v); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIB2FPROC)(GLuint index, GLfloat x, GLfloat y); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIB2FVPROC)(GLuint index, const GLfloat * v); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIB2SPROC)(GLuint index, GLshort x, GLshort y); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIB2SVPROC)(GLuint index, const GLshort * v); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIB3DPROC)(GLuint index, GLdouble x, GLdouble y, GLdouble z); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIB3DVPROC)(GLuint index, const GLdouble * v); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIB3FPROC)(GLuint index, GLfloat x, GLfloat y, GLfloat z); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIB3FVPROC)(GLuint index, const GLfloat * v); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIB3SPROC)(GLuint index, GLshort x, GLshort y, GLshort z); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIB3SVPROC)(GLuint index, const GLshort * v); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIB4NBVPROC)(GLuint index, const GLbyte * v); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIB4NIVPROC)(GLuint index, const GLint * v); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIB4NSVPROC)(GLuint index, const GLshort * v); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIB4NUBPROC)(GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIB4NUBVPROC)(GLuint index, const GLubyte * v); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIB4NUIVPROC)(GLuint index, const GLuint * v); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIB4NUSVPROC)(GLuint index, const GLushort * v); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIB4BVPROC)(GLuint index, const GLbyte * v); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIB4DPROC)(GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIB4DVPROC)(GLuint index, const GLdouble * v); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIB4FPROC)(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIB4FVPROC)(GLuint index, const GLfloat * v); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIB4IVPROC)(GLuint index, const GLint * v); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIB4SPROC)(GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIB4SVPROC)(GLuint index, const GLshort * v); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIB4UBVPROC)(GLuint index, const GLubyte * v); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIB4UIVPROC)(GLuint index, const GLuint * v); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIB4USVPROC)(GLuint index, const GLushort * v); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIBDIVISORPROC)(GLuint index, GLuint divisor); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIBI1IPROC)(GLuint index, GLint x); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIBI1IVPROC)(GLuint index, const GLint * v); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIBI1UIPROC)(GLuint index, GLuint x); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIBI1UIVPROC)(GLuint index, const GLuint * v); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIBI2IPROC)(GLuint index, GLint x, GLint y); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIBI2IVPROC)(GLuint index, const GLint * v); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIBI2UIPROC)(GLuint index, GLuint x, GLuint y); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIBI2UIVPROC)(GLuint index, const GLuint * v); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIBI3IPROC)(GLuint index, GLint x, GLint y, GLint z); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIBI3IVPROC)(GLuint index, const GLint * v); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIBI3UIPROC)(GLuint index, GLuint x, GLuint y, GLuint z); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIBI3UIVPROC)(GLuint index, const GLuint * v); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIBI4BVPROC)(GLuint index, const GLbyte * v); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIBI4IPROC)(GLuint index, GLint x, GLint y, GLint z, GLint w); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIBI4IVPROC)(GLuint index, const GLint * v); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIBI4SVPROC)(GLuint index, const GLshort * v); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIBI4UBVPROC)(GLuint index, const GLubyte * v); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIBI4UIPROC)(GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIBI4UIVPROC)(GLuint index, const GLuint * v); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIBI4USVPROC)(GLuint index, const GLushort * v); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIBIPOINTERPROC)(GLuint index, GLint size, GLenum type, GLsizei stride, const void * pointer); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIBP1UIPROC)(GLuint index, GLenum type, GLboolean normalized, GLuint value); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIBP1UIVPROC)(GLuint index, GLenum type, GLboolean normalized, const GLuint * value); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIBP2UIPROC)(GLuint index, GLenum type, GLboolean normalized, GLuint value); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIBP2UIVPROC)(GLuint index, GLenum type, GLboolean normalized, const GLuint * value); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIBP3UIPROC)(GLuint index, GLenum type, GLboolean normalized, GLuint value); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIBP3UIVPROC)(GLuint index, GLenum type, GLboolean normalized, const GLuint * value); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIBP4UIPROC)(GLuint index, GLenum type, GLboolean normalized, GLuint value); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIBP4UIVPROC)(GLuint index, GLenum type, GLboolean normalized, const GLuint * value); +typedef void (GLAD_API_PTR *PFNGLVERTEXATTRIBPOINTERPROC)(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void * pointer); +typedef void (GLAD_API_PTR *PFNGLVERTEXP2UIPROC)(GLenum type, GLuint value); +typedef void (GLAD_API_PTR *PFNGLVERTEXP2UIVPROC)(GLenum type, const GLuint * value); +typedef void (GLAD_API_PTR *PFNGLVERTEXP3UIPROC)(GLenum type, GLuint value); +typedef void (GLAD_API_PTR *PFNGLVERTEXP3UIVPROC)(GLenum type, const GLuint * value); +typedef void (GLAD_API_PTR *PFNGLVERTEXP4UIPROC)(GLenum type, GLuint value); +typedef void (GLAD_API_PTR *PFNGLVERTEXP4UIVPROC)(GLenum type, const GLuint * value); +typedef void (GLAD_API_PTR *PFNGLVERTEXPOINTERPROC)(GLint size, GLenum type, GLsizei stride, const void * pointer); +typedef void (GLAD_API_PTR *PFNGLVIEWPORTPROC)(GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (GLAD_API_PTR *PFNGLWAITSYNCPROC)(GLsync sync, GLbitfield flags, GLuint64 timeout); +typedef void (GLAD_API_PTR *PFNGLWINDOWPOS2DPROC)(GLdouble x, GLdouble y); +typedef void (GLAD_API_PTR *PFNGLWINDOWPOS2DVPROC)(const GLdouble * v); +typedef void (GLAD_API_PTR *PFNGLWINDOWPOS2FPROC)(GLfloat x, GLfloat y); +typedef void (GLAD_API_PTR *PFNGLWINDOWPOS2FVPROC)(const GLfloat * v); +typedef void (GLAD_API_PTR *PFNGLWINDOWPOS2IPROC)(GLint x, GLint y); +typedef void (GLAD_API_PTR *PFNGLWINDOWPOS2IVPROC)(const GLint * v); +typedef void (GLAD_API_PTR *PFNGLWINDOWPOS2SPROC)(GLshort x, GLshort y); +typedef void (GLAD_API_PTR *PFNGLWINDOWPOS2SVPROC)(const GLshort * v); +typedef void (GLAD_API_PTR *PFNGLWINDOWPOS3DPROC)(GLdouble x, GLdouble y, GLdouble z); +typedef void (GLAD_API_PTR *PFNGLWINDOWPOS3DVPROC)(const GLdouble * v); +typedef void (GLAD_API_PTR *PFNGLWINDOWPOS3FPROC)(GLfloat x, GLfloat y, GLfloat z); +typedef void (GLAD_API_PTR *PFNGLWINDOWPOS3FVPROC)(const GLfloat * v); +typedef void (GLAD_API_PTR *PFNGLWINDOWPOS3IPROC)(GLint x, GLint y, GLint z); +typedef void (GLAD_API_PTR *PFNGLWINDOWPOS3IVPROC)(const GLint * v); +typedef void (GLAD_API_PTR *PFNGLWINDOWPOS3SPROC)(GLshort x, GLshort y, GLshort z); +typedef void (GLAD_API_PTR *PFNGLWINDOWPOS3SVPROC)(const GLshort * v); + +GLAD_API_CALL PFNGLACCUMPROC glad_glAccum; +#define glAccum glad_glAccum +GLAD_API_CALL PFNGLACTIVETEXTUREPROC glad_glActiveTexture; +#define glActiveTexture glad_glActiveTexture +GLAD_API_CALL PFNGLALPHAFUNCPROC glad_glAlphaFunc; +#define glAlphaFunc glad_glAlphaFunc +GLAD_API_CALL PFNGLARETEXTURESRESIDENTPROC glad_glAreTexturesResident; +#define glAreTexturesResident glad_glAreTexturesResident +GLAD_API_CALL PFNGLARRAYELEMENTPROC glad_glArrayElement; +#define glArrayElement glad_glArrayElement +GLAD_API_CALL PFNGLATTACHSHADERPROC glad_glAttachShader; +#define glAttachShader glad_glAttachShader +GLAD_API_CALL PFNGLBEGINPROC glad_glBegin; +#define glBegin glad_glBegin +GLAD_API_CALL PFNGLBEGINCONDITIONALRENDERPROC glad_glBeginConditionalRender; +#define glBeginConditionalRender glad_glBeginConditionalRender +GLAD_API_CALL PFNGLBEGINQUERYPROC glad_glBeginQuery; +#define glBeginQuery glad_glBeginQuery +GLAD_API_CALL PFNGLBEGINTRANSFORMFEEDBACKPROC glad_glBeginTransformFeedback; +#define glBeginTransformFeedback glad_glBeginTransformFeedback +GLAD_API_CALL PFNGLBINDATTRIBLOCATIONPROC glad_glBindAttribLocation; +#define glBindAttribLocation glad_glBindAttribLocation +GLAD_API_CALL PFNGLBINDBUFFERPROC glad_glBindBuffer; +#define glBindBuffer glad_glBindBuffer +GLAD_API_CALL PFNGLBINDBUFFERBASEPROC glad_glBindBufferBase; +#define glBindBufferBase glad_glBindBufferBase +GLAD_API_CALL PFNGLBINDBUFFERRANGEPROC glad_glBindBufferRange; +#define glBindBufferRange glad_glBindBufferRange +GLAD_API_CALL PFNGLBINDFRAGDATALOCATIONPROC glad_glBindFragDataLocation; +#define glBindFragDataLocation glad_glBindFragDataLocation +GLAD_API_CALL PFNGLBINDFRAGDATALOCATIONINDEXEDPROC glad_glBindFragDataLocationIndexed; +#define glBindFragDataLocationIndexed glad_glBindFragDataLocationIndexed +GLAD_API_CALL PFNGLBINDFRAMEBUFFERPROC glad_glBindFramebuffer; +#define glBindFramebuffer glad_glBindFramebuffer +GLAD_API_CALL PFNGLBINDRENDERBUFFERPROC glad_glBindRenderbuffer; +#define glBindRenderbuffer glad_glBindRenderbuffer +GLAD_API_CALL PFNGLBINDSAMPLERPROC glad_glBindSampler; +#define glBindSampler glad_glBindSampler +GLAD_API_CALL PFNGLBINDTEXTUREPROC glad_glBindTexture; +#define glBindTexture glad_glBindTexture +GLAD_API_CALL PFNGLBINDVERTEXARRAYPROC glad_glBindVertexArray; +#define glBindVertexArray glad_glBindVertexArray +GLAD_API_CALL PFNGLBITMAPPROC glad_glBitmap; +#define glBitmap glad_glBitmap +GLAD_API_CALL PFNGLBLENDCOLORPROC glad_glBlendColor; +#define glBlendColor glad_glBlendColor +GLAD_API_CALL PFNGLBLENDEQUATIONPROC glad_glBlendEquation; +#define glBlendEquation glad_glBlendEquation +GLAD_API_CALL PFNGLBLENDEQUATIONSEPARATEPROC glad_glBlendEquationSeparate; +#define glBlendEquationSeparate glad_glBlendEquationSeparate +GLAD_API_CALL PFNGLBLENDFUNCPROC glad_glBlendFunc; +#define glBlendFunc glad_glBlendFunc +GLAD_API_CALL PFNGLBLENDFUNCSEPARATEPROC glad_glBlendFuncSeparate; +#define glBlendFuncSeparate glad_glBlendFuncSeparate +GLAD_API_CALL PFNGLBLITFRAMEBUFFERPROC glad_glBlitFramebuffer; +#define glBlitFramebuffer glad_glBlitFramebuffer +GLAD_API_CALL PFNGLBUFFERDATAPROC glad_glBufferData; +#define glBufferData glad_glBufferData +GLAD_API_CALL PFNGLBUFFERSUBDATAPROC glad_glBufferSubData; +#define glBufferSubData glad_glBufferSubData +GLAD_API_CALL PFNGLCALLLISTPROC glad_glCallList; +#define glCallList glad_glCallList +GLAD_API_CALL PFNGLCALLLISTSPROC glad_glCallLists; +#define glCallLists glad_glCallLists +GLAD_API_CALL PFNGLCHECKFRAMEBUFFERSTATUSPROC glad_glCheckFramebufferStatus; +#define glCheckFramebufferStatus glad_glCheckFramebufferStatus +GLAD_API_CALL PFNGLCLAMPCOLORPROC glad_glClampColor; +#define glClampColor glad_glClampColor +GLAD_API_CALL PFNGLCLEARPROC glad_glClear; +#define glClear glad_glClear +GLAD_API_CALL PFNGLCLEARACCUMPROC glad_glClearAccum; +#define glClearAccum glad_glClearAccum +GLAD_API_CALL PFNGLCLEARBUFFERFIPROC glad_glClearBufferfi; +#define glClearBufferfi glad_glClearBufferfi +GLAD_API_CALL PFNGLCLEARBUFFERFVPROC glad_glClearBufferfv; +#define glClearBufferfv glad_glClearBufferfv +GLAD_API_CALL PFNGLCLEARBUFFERIVPROC glad_glClearBufferiv; +#define glClearBufferiv glad_glClearBufferiv +GLAD_API_CALL PFNGLCLEARBUFFERUIVPROC glad_glClearBufferuiv; +#define glClearBufferuiv glad_glClearBufferuiv +GLAD_API_CALL PFNGLCLEARCOLORPROC glad_glClearColor; +#define glClearColor glad_glClearColor +GLAD_API_CALL PFNGLCLEARDEPTHPROC glad_glClearDepth; +#define glClearDepth glad_glClearDepth +GLAD_API_CALL PFNGLCLEARINDEXPROC glad_glClearIndex; +#define glClearIndex glad_glClearIndex +GLAD_API_CALL PFNGLCLEARSTENCILPROC glad_glClearStencil; +#define glClearStencil glad_glClearStencil +GLAD_API_CALL PFNGLCLIENTACTIVETEXTUREPROC glad_glClientActiveTexture; +#define glClientActiveTexture glad_glClientActiveTexture +GLAD_API_CALL PFNGLCLIENTWAITSYNCPROC glad_glClientWaitSync; +#define glClientWaitSync glad_glClientWaitSync +GLAD_API_CALL PFNGLCLIPPLANEPROC glad_glClipPlane; +#define glClipPlane glad_glClipPlane +GLAD_API_CALL PFNGLCOLOR3BPROC glad_glColor3b; +#define glColor3b glad_glColor3b +GLAD_API_CALL PFNGLCOLOR3BVPROC glad_glColor3bv; +#define glColor3bv glad_glColor3bv +GLAD_API_CALL PFNGLCOLOR3DPROC glad_glColor3d; +#define glColor3d glad_glColor3d +GLAD_API_CALL PFNGLCOLOR3DVPROC glad_glColor3dv; +#define glColor3dv glad_glColor3dv +GLAD_API_CALL PFNGLCOLOR3FPROC glad_glColor3f; +#define glColor3f glad_glColor3f +GLAD_API_CALL PFNGLCOLOR3FVPROC glad_glColor3fv; +#define glColor3fv glad_glColor3fv +GLAD_API_CALL PFNGLCOLOR3IPROC glad_glColor3i; +#define glColor3i glad_glColor3i +GLAD_API_CALL PFNGLCOLOR3IVPROC glad_glColor3iv; +#define glColor3iv glad_glColor3iv +GLAD_API_CALL PFNGLCOLOR3SPROC glad_glColor3s; +#define glColor3s glad_glColor3s +GLAD_API_CALL PFNGLCOLOR3SVPROC glad_glColor3sv; +#define glColor3sv glad_glColor3sv +GLAD_API_CALL PFNGLCOLOR3UBPROC glad_glColor3ub; +#define glColor3ub glad_glColor3ub +GLAD_API_CALL PFNGLCOLOR3UBVPROC glad_glColor3ubv; +#define glColor3ubv glad_glColor3ubv +GLAD_API_CALL PFNGLCOLOR3UIPROC glad_glColor3ui; +#define glColor3ui glad_glColor3ui +GLAD_API_CALL PFNGLCOLOR3UIVPROC glad_glColor3uiv; +#define glColor3uiv glad_glColor3uiv +GLAD_API_CALL PFNGLCOLOR3USPROC glad_glColor3us; +#define glColor3us glad_glColor3us +GLAD_API_CALL PFNGLCOLOR3USVPROC glad_glColor3usv; +#define glColor3usv glad_glColor3usv +GLAD_API_CALL PFNGLCOLOR4BPROC glad_glColor4b; +#define glColor4b glad_glColor4b +GLAD_API_CALL PFNGLCOLOR4BVPROC glad_glColor4bv; +#define glColor4bv glad_glColor4bv +GLAD_API_CALL PFNGLCOLOR4DPROC glad_glColor4d; +#define glColor4d glad_glColor4d +GLAD_API_CALL PFNGLCOLOR4DVPROC glad_glColor4dv; +#define glColor4dv glad_glColor4dv +GLAD_API_CALL PFNGLCOLOR4FPROC glad_glColor4f; +#define glColor4f glad_glColor4f +GLAD_API_CALL PFNGLCOLOR4FVPROC glad_glColor4fv; +#define glColor4fv glad_glColor4fv +GLAD_API_CALL PFNGLCOLOR4IPROC glad_glColor4i; +#define glColor4i glad_glColor4i +GLAD_API_CALL PFNGLCOLOR4IVPROC glad_glColor4iv; +#define glColor4iv glad_glColor4iv +GLAD_API_CALL PFNGLCOLOR4SPROC glad_glColor4s; +#define glColor4s glad_glColor4s +GLAD_API_CALL PFNGLCOLOR4SVPROC glad_glColor4sv; +#define glColor4sv glad_glColor4sv +GLAD_API_CALL PFNGLCOLOR4UBPROC glad_glColor4ub; +#define glColor4ub glad_glColor4ub +GLAD_API_CALL PFNGLCOLOR4UBVPROC glad_glColor4ubv; +#define glColor4ubv glad_glColor4ubv +GLAD_API_CALL PFNGLCOLOR4UIPROC glad_glColor4ui; +#define glColor4ui glad_glColor4ui +GLAD_API_CALL PFNGLCOLOR4UIVPROC glad_glColor4uiv; +#define glColor4uiv glad_glColor4uiv +GLAD_API_CALL PFNGLCOLOR4USPROC glad_glColor4us; +#define glColor4us glad_glColor4us +GLAD_API_CALL PFNGLCOLOR4USVPROC glad_glColor4usv; +#define glColor4usv glad_glColor4usv +GLAD_API_CALL PFNGLCOLORMASKPROC glad_glColorMask; +#define glColorMask glad_glColorMask +GLAD_API_CALL PFNGLCOLORMASKIPROC glad_glColorMaski; +#define glColorMaski glad_glColorMaski +GLAD_API_CALL PFNGLCOLORMATERIALPROC glad_glColorMaterial; +#define glColorMaterial glad_glColorMaterial +GLAD_API_CALL PFNGLCOLORP3UIPROC glad_glColorP3ui; +#define glColorP3ui glad_glColorP3ui +GLAD_API_CALL PFNGLCOLORP3UIVPROC glad_glColorP3uiv; +#define glColorP3uiv glad_glColorP3uiv +GLAD_API_CALL PFNGLCOLORP4UIPROC glad_glColorP4ui; +#define glColorP4ui glad_glColorP4ui +GLAD_API_CALL PFNGLCOLORP4UIVPROC glad_glColorP4uiv; +#define glColorP4uiv glad_glColorP4uiv +GLAD_API_CALL PFNGLCOLORPOINTERPROC glad_glColorPointer; +#define glColorPointer glad_glColorPointer +GLAD_API_CALL PFNGLCOMPILESHADERPROC glad_glCompileShader; +#define glCompileShader glad_glCompileShader +GLAD_API_CALL PFNGLCOMPRESSEDTEXIMAGE1DPROC glad_glCompressedTexImage1D; +#define glCompressedTexImage1D glad_glCompressedTexImage1D +GLAD_API_CALL PFNGLCOMPRESSEDTEXIMAGE2DPROC glad_glCompressedTexImage2D; +#define glCompressedTexImage2D glad_glCompressedTexImage2D +GLAD_API_CALL PFNGLCOMPRESSEDTEXIMAGE3DPROC glad_glCompressedTexImage3D; +#define glCompressedTexImage3D glad_glCompressedTexImage3D +GLAD_API_CALL PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC glad_glCompressedTexSubImage1D; +#define glCompressedTexSubImage1D glad_glCompressedTexSubImage1D +GLAD_API_CALL PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC glad_glCompressedTexSubImage2D; +#define glCompressedTexSubImage2D glad_glCompressedTexSubImage2D +GLAD_API_CALL PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC glad_glCompressedTexSubImage3D; +#define glCompressedTexSubImage3D glad_glCompressedTexSubImage3D +GLAD_API_CALL PFNGLCOPYBUFFERSUBDATAPROC glad_glCopyBufferSubData; +#define glCopyBufferSubData glad_glCopyBufferSubData +GLAD_API_CALL PFNGLCOPYPIXELSPROC glad_glCopyPixels; +#define glCopyPixels glad_glCopyPixels +GLAD_API_CALL PFNGLCOPYTEXIMAGE1DPROC glad_glCopyTexImage1D; +#define glCopyTexImage1D glad_glCopyTexImage1D +GLAD_API_CALL PFNGLCOPYTEXIMAGE2DPROC glad_glCopyTexImage2D; +#define glCopyTexImage2D glad_glCopyTexImage2D +GLAD_API_CALL PFNGLCOPYTEXSUBIMAGE1DPROC glad_glCopyTexSubImage1D; +#define glCopyTexSubImage1D glad_glCopyTexSubImage1D +GLAD_API_CALL PFNGLCOPYTEXSUBIMAGE2DPROC glad_glCopyTexSubImage2D; +#define glCopyTexSubImage2D glad_glCopyTexSubImage2D +GLAD_API_CALL PFNGLCOPYTEXSUBIMAGE3DPROC glad_glCopyTexSubImage3D; +#define glCopyTexSubImage3D glad_glCopyTexSubImage3D +GLAD_API_CALL PFNGLCREATEPROGRAMPROC glad_glCreateProgram; +#define glCreateProgram glad_glCreateProgram +GLAD_API_CALL PFNGLCREATESHADERPROC glad_glCreateShader; +#define glCreateShader glad_glCreateShader +GLAD_API_CALL PFNGLCULLFACEPROC glad_glCullFace; +#define glCullFace glad_glCullFace +GLAD_API_CALL PFNGLDEBUGMESSAGECALLBACKPROC glad_glDebugMessageCallback; +#define glDebugMessageCallback glad_glDebugMessageCallback +GLAD_API_CALL PFNGLDEBUGMESSAGECONTROLPROC glad_glDebugMessageControl; +#define glDebugMessageControl glad_glDebugMessageControl +GLAD_API_CALL PFNGLDEBUGMESSAGEINSERTPROC glad_glDebugMessageInsert; +#define glDebugMessageInsert glad_glDebugMessageInsert +GLAD_API_CALL PFNGLDELETEBUFFERSPROC glad_glDeleteBuffers; +#define glDeleteBuffers glad_glDeleteBuffers +GLAD_API_CALL PFNGLDELETEFRAMEBUFFERSPROC glad_glDeleteFramebuffers; +#define glDeleteFramebuffers glad_glDeleteFramebuffers +GLAD_API_CALL PFNGLDELETELISTSPROC glad_glDeleteLists; +#define glDeleteLists glad_glDeleteLists +GLAD_API_CALL PFNGLDELETEPROGRAMPROC glad_glDeleteProgram; +#define glDeleteProgram glad_glDeleteProgram +GLAD_API_CALL PFNGLDELETEQUERIESPROC glad_glDeleteQueries; +#define glDeleteQueries glad_glDeleteQueries +GLAD_API_CALL PFNGLDELETERENDERBUFFERSPROC glad_glDeleteRenderbuffers; +#define glDeleteRenderbuffers glad_glDeleteRenderbuffers +GLAD_API_CALL PFNGLDELETESAMPLERSPROC glad_glDeleteSamplers; +#define glDeleteSamplers glad_glDeleteSamplers +GLAD_API_CALL PFNGLDELETESHADERPROC glad_glDeleteShader; +#define glDeleteShader glad_glDeleteShader +GLAD_API_CALL PFNGLDELETESYNCPROC glad_glDeleteSync; +#define glDeleteSync glad_glDeleteSync +GLAD_API_CALL PFNGLDELETETEXTURESPROC glad_glDeleteTextures; +#define glDeleteTextures glad_glDeleteTextures +GLAD_API_CALL PFNGLDELETEVERTEXARRAYSPROC glad_glDeleteVertexArrays; +#define glDeleteVertexArrays glad_glDeleteVertexArrays +GLAD_API_CALL PFNGLDEPTHFUNCPROC glad_glDepthFunc; +#define glDepthFunc glad_glDepthFunc +GLAD_API_CALL PFNGLDEPTHMASKPROC glad_glDepthMask; +#define glDepthMask glad_glDepthMask +GLAD_API_CALL PFNGLDEPTHRANGEPROC glad_glDepthRange; +#define glDepthRange glad_glDepthRange +GLAD_API_CALL PFNGLDETACHSHADERPROC glad_glDetachShader; +#define glDetachShader glad_glDetachShader +GLAD_API_CALL PFNGLDISABLEPROC glad_glDisable; +#define glDisable glad_glDisable +GLAD_API_CALL PFNGLDISABLECLIENTSTATEPROC glad_glDisableClientState; +#define glDisableClientState glad_glDisableClientState +GLAD_API_CALL PFNGLDISABLEVERTEXATTRIBARRAYPROC glad_glDisableVertexAttribArray; +#define glDisableVertexAttribArray glad_glDisableVertexAttribArray +GLAD_API_CALL PFNGLDISABLEIPROC glad_glDisablei; +#define glDisablei glad_glDisablei +GLAD_API_CALL PFNGLDRAWARRAYSPROC glad_glDrawArrays; +#define glDrawArrays glad_glDrawArrays +GLAD_API_CALL PFNGLDRAWARRAYSINSTANCEDPROC glad_glDrawArraysInstanced; +#define glDrawArraysInstanced glad_glDrawArraysInstanced +GLAD_API_CALL PFNGLDRAWBUFFERPROC glad_glDrawBuffer; +#define glDrawBuffer glad_glDrawBuffer +GLAD_API_CALL PFNGLDRAWBUFFERSPROC glad_glDrawBuffers; +#define glDrawBuffers glad_glDrawBuffers +GLAD_API_CALL PFNGLDRAWELEMENTSPROC glad_glDrawElements; +#define glDrawElements glad_glDrawElements +GLAD_API_CALL PFNGLDRAWELEMENTSBASEVERTEXPROC glad_glDrawElementsBaseVertex; +#define glDrawElementsBaseVertex glad_glDrawElementsBaseVertex +GLAD_API_CALL PFNGLDRAWELEMENTSINSTANCEDPROC glad_glDrawElementsInstanced; +#define glDrawElementsInstanced glad_glDrawElementsInstanced +GLAD_API_CALL PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC glad_glDrawElementsInstancedBaseVertex; +#define glDrawElementsInstancedBaseVertex glad_glDrawElementsInstancedBaseVertex +GLAD_API_CALL PFNGLDRAWPIXELSPROC glad_glDrawPixels; +#define glDrawPixels glad_glDrawPixels +GLAD_API_CALL PFNGLDRAWRANGEELEMENTSPROC glad_glDrawRangeElements; +#define glDrawRangeElements glad_glDrawRangeElements +GLAD_API_CALL PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC glad_glDrawRangeElementsBaseVertex; +#define glDrawRangeElementsBaseVertex glad_glDrawRangeElementsBaseVertex +GLAD_API_CALL PFNGLEDGEFLAGPROC glad_glEdgeFlag; +#define glEdgeFlag glad_glEdgeFlag +GLAD_API_CALL PFNGLEDGEFLAGPOINTERPROC glad_glEdgeFlagPointer; +#define glEdgeFlagPointer glad_glEdgeFlagPointer +GLAD_API_CALL PFNGLEDGEFLAGVPROC glad_glEdgeFlagv; +#define glEdgeFlagv glad_glEdgeFlagv +GLAD_API_CALL PFNGLENABLEPROC glad_glEnable; +#define glEnable glad_glEnable +GLAD_API_CALL PFNGLENABLECLIENTSTATEPROC glad_glEnableClientState; +#define glEnableClientState glad_glEnableClientState +GLAD_API_CALL PFNGLENABLEVERTEXATTRIBARRAYPROC glad_glEnableVertexAttribArray; +#define glEnableVertexAttribArray glad_glEnableVertexAttribArray +GLAD_API_CALL PFNGLENABLEIPROC glad_glEnablei; +#define glEnablei glad_glEnablei +GLAD_API_CALL PFNGLENDPROC glad_glEnd; +#define glEnd glad_glEnd +GLAD_API_CALL PFNGLENDCONDITIONALRENDERPROC glad_glEndConditionalRender; +#define glEndConditionalRender glad_glEndConditionalRender +GLAD_API_CALL PFNGLENDLISTPROC glad_glEndList; +#define glEndList glad_glEndList +GLAD_API_CALL PFNGLENDQUERYPROC glad_glEndQuery; +#define glEndQuery glad_glEndQuery +GLAD_API_CALL PFNGLENDTRANSFORMFEEDBACKPROC glad_glEndTransformFeedback; +#define glEndTransformFeedback glad_glEndTransformFeedback +GLAD_API_CALL PFNGLEVALCOORD1DPROC glad_glEvalCoord1d; +#define glEvalCoord1d glad_glEvalCoord1d +GLAD_API_CALL PFNGLEVALCOORD1DVPROC glad_glEvalCoord1dv; +#define glEvalCoord1dv glad_glEvalCoord1dv +GLAD_API_CALL PFNGLEVALCOORD1FPROC glad_glEvalCoord1f; +#define glEvalCoord1f glad_glEvalCoord1f +GLAD_API_CALL PFNGLEVALCOORD1FVPROC glad_glEvalCoord1fv; +#define glEvalCoord1fv glad_glEvalCoord1fv +GLAD_API_CALL PFNGLEVALCOORD2DPROC glad_glEvalCoord2d; +#define glEvalCoord2d glad_glEvalCoord2d +GLAD_API_CALL PFNGLEVALCOORD2DVPROC glad_glEvalCoord2dv; +#define glEvalCoord2dv glad_glEvalCoord2dv +GLAD_API_CALL PFNGLEVALCOORD2FPROC glad_glEvalCoord2f; +#define glEvalCoord2f glad_glEvalCoord2f +GLAD_API_CALL PFNGLEVALCOORD2FVPROC glad_glEvalCoord2fv; +#define glEvalCoord2fv glad_glEvalCoord2fv +GLAD_API_CALL PFNGLEVALMESH1PROC glad_glEvalMesh1; +#define glEvalMesh1 glad_glEvalMesh1 +GLAD_API_CALL PFNGLEVALMESH2PROC glad_glEvalMesh2; +#define glEvalMesh2 glad_glEvalMesh2 +GLAD_API_CALL PFNGLEVALPOINT1PROC glad_glEvalPoint1; +#define glEvalPoint1 glad_glEvalPoint1 +GLAD_API_CALL PFNGLEVALPOINT2PROC glad_glEvalPoint2; +#define glEvalPoint2 glad_glEvalPoint2 +GLAD_API_CALL PFNGLFEEDBACKBUFFERPROC glad_glFeedbackBuffer; +#define glFeedbackBuffer glad_glFeedbackBuffer +GLAD_API_CALL PFNGLFENCESYNCPROC glad_glFenceSync; +#define glFenceSync glad_glFenceSync +GLAD_API_CALL PFNGLFINISHPROC glad_glFinish; +#define glFinish glad_glFinish +GLAD_API_CALL PFNGLFLUSHPROC glad_glFlush; +#define glFlush glad_glFlush +GLAD_API_CALL PFNGLFLUSHMAPPEDBUFFERRANGEPROC glad_glFlushMappedBufferRange; +#define glFlushMappedBufferRange glad_glFlushMappedBufferRange +GLAD_API_CALL PFNGLFOGCOORDPOINTERPROC glad_glFogCoordPointer; +#define glFogCoordPointer glad_glFogCoordPointer +GLAD_API_CALL PFNGLFOGCOORDDPROC glad_glFogCoordd; +#define glFogCoordd glad_glFogCoordd +GLAD_API_CALL PFNGLFOGCOORDDVPROC glad_glFogCoorddv; +#define glFogCoorddv glad_glFogCoorddv +GLAD_API_CALL PFNGLFOGCOORDFPROC glad_glFogCoordf; +#define glFogCoordf glad_glFogCoordf +GLAD_API_CALL PFNGLFOGCOORDFVPROC glad_glFogCoordfv; +#define glFogCoordfv glad_glFogCoordfv +GLAD_API_CALL PFNGLFOGFPROC glad_glFogf; +#define glFogf glad_glFogf +GLAD_API_CALL PFNGLFOGFVPROC glad_glFogfv; +#define glFogfv glad_glFogfv +GLAD_API_CALL PFNGLFOGIPROC glad_glFogi; +#define glFogi glad_glFogi +GLAD_API_CALL PFNGLFOGIVPROC glad_glFogiv; +#define glFogiv glad_glFogiv +GLAD_API_CALL PFNGLFRAMEBUFFERRENDERBUFFERPROC glad_glFramebufferRenderbuffer; +#define glFramebufferRenderbuffer glad_glFramebufferRenderbuffer +GLAD_API_CALL PFNGLFRAMEBUFFERTEXTUREPROC glad_glFramebufferTexture; +#define glFramebufferTexture glad_glFramebufferTexture +GLAD_API_CALL PFNGLFRAMEBUFFERTEXTURE1DPROC glad_glFramebufferTexture1D; +#define glFramebufferTexture1D glad_glFramebufferTexture1D +GLAD_API_CALL PFNGLFRAMEBUFFERTEXTURE2DPROC glad_glFramebufferTexture2D; +#define glFramebufferTexture2D glad_glFramebufferTexture2D +GLAD_API_CALL PFNGLFRAMEBUFFERTEXTURE3DPROC glad_glFramebufferTexture3D; +#define glFramebufferTexture3D glad_glFramebufferTexture3D +GLAD_API_CALL PFNGLFRAMEBUFFERTEXTURELAYERPROC glad_glFramebufferTextureLayer; +#define glFramebufferTextureLayer glad_glFramebufferTextureLayer +GLAD_API_CALL PFNGLFRONTFACEPROC glad_glFrontFace; +#define glFrontFace glad_glFrontFace +GLAD_API_CALL PFNGLFRUSTUMPROC glad_glFrustum; +#define glFrustum glad_glFrustum +GLAD_API_CALL PFNGLGENBUFFERSPROC glad_glGenBuffers; +#define glGenBuffers glad_glGenBuffers +GLAD_API_CALL PFNGLGENFRAMEBUFFERSPROC glad_glGenFramebuffers; +#define glGenFramebuffers glad_glGenFramebuffers +GLAD_API_CALL PFNGLGENLISTSPROC glad_glGenLists; +#define glGenLists glad_glGenLists +GLAD_API_CALL PFNGLGENQUERIESPROC glad_glGenQueries; +#define glGenQueries glad_glGenQueries +GLAD_API_CALL PFNGLGENRENDERBUFFERSPROC glad_glGenRenderbuffers; +#define glGenRenderbuffers glad_glGenRenderbuffers +GLAD_API_CALL PFNGLGENSAMPLERSPROC glad_glGenSamplers; +#define glGenSamplers glad_glGenSamplers +GLAD_API_CALL PFNGLGENTEXTURESPROC glad_glGenTextures; +#define glGenTextures glad_glGenTextures +GLAD_API_CALL PFNGLGENVERTEXARRAYSPROC glad_glGenVertexArrays; +#define glGenVertexArrays glad_glGenVertexArrays +GLAD_API_CALL PFNGLGENERATEMIPMAPPROC glad_glGenerateMipmap; +#define glGenerateMipmap glad_glGenerateMipmap +GLAD_API_CALL PFNGLGETACTIVEATTRIBPROC glad_glGetActiveAttrib; +#define glGetActiveAttrib glad_glGetActiveAttrib +GLAD_API_CALL PFNGLGETACTIVEUNIFORMPROC glad_glGetActiveUniform; +#define glGetActiveUniform glad_glGetActiveUniform +GLAD_API_CALL PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC glad_glGetActiveUniformBlockName; +#define glGetActiveUniformBlockName glad_glGetActiveUniformBlockName +GLAD_API_CALL PFNGLGETACTIVEUNIFORMBLOCKIVPROC glad_glGetActiveUniformBlockiv; +#define glGetActiveUniformBlockiv glad_glGetActiveUniformBlockiv +GLAD_API_CALL PFNGLGETACTIVEUNIFORMNAMEPROC glad_glGetActiveUniformName; +#define glGetActiveUniformName glad_glGetActiveUniformName +GLAD_API_CALL PFNGLGETACTIVEUNIFORMSIVPROC glad_glGetActiveUniformsiv; +#define glGetActiveUniformsiv glad_glGetActiveUniformsiv +GLAD_API_CALL PFNGLGETATTACHEDSHADERSPROC glad_glGetAttachedShaders; +#define glGetAttachedShaders glad_glGetAttachedShaders +GLAD_API_CALL PFNGLGETATTRIBLOCATIONPROC glad_glGetAttribLocation; +#define glGetAttribLocation glad_glGetAttribLocation +GLAD_API_CALL PFNGLGETBOOLEANI_VPROC glad_glGetBooleani_v; +#define glGetBooleani_v glad_glGetBooleani_v +GLAD_API_CALL PFNGLGETBOOLEANVPROC glad_glGetBooleanv; +#define glGetBooleanv glad_glGetBooleanv +GLAD_API_CALL PFNGLGETBUFFERPARAMETERI64VPROC glad_glGetBufferParameteri64v; +#define glGetBufferParameteri64v glad_glGetBufferParameteri64v +GLAD_API_CALL PFNGLGETBUFFERPARAMETERIVPROC glad_glGetBufferParameteriv; +#define glGetBufferParameteriv glad_glGetBufferParameteriv +GLAD_API_CALL PFNGLGETBUFFERPOINTERVPROC glad_glGetBufferPointerv; +#define glGetBufferPointerv glad_glGetBufferPointerv +GLAD_API_CALL PFNGLGETBUFFERSUBDATAPROC glad_glGetBufferSubData; +#define glGetBufferSubData glad_glGetBufferSubData +GLAD_API_CALL PFNGLGETCLIPPLANEPROC glad_glGetClipPlane; +#define glGetClipPlane glad_glGetClipPlane +GLAD_API_CALL PFNGLGETCOMPRESSEDTEXIMAGEPROC glad_glGetCompressedTexImage; +#define glGetCompressedTexImage glad_glGetCompressedTexImage +GLAD_API_CALL PFNGLGETDEBUGMESSAGELOGPROC glad_glGetDebugMessageLog; +#define glGetDebugMessageLog glad_glGetDebugMessageLog +GLAD_API_CALL PFNGLGETDOUBLEVPROC glad_glGetDoublev; +#define glGetDoublev glad_glGetDoublev +GLAD_API_CALL PFNGLGETERRORPROC glad_glGetError; +#define glGetError glad_glGetError +GLAD_API_CALL PFNGLGETFLOATVPROC glad_glGetFloatv; +#define glGetFloatv glad_glGetFloatv +GLAD_API_CALL PFNGLGETFRAGDATAINDEXPROC glad_glGetFragDataIndex; +#define glGetFragDataIndex glad_glGetFragDataIndex +GLAD_API_CALL PFNGLGETFRAGDATALOCATIONPROC glad_glGetFragDataLocation; +#define glGetFragDataLocation glad_glGetFragDataLocation +GLAD_API_CALL PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC glad_glGetFramebufferAttachmentParameteriv; +#define glGetFramebufferAttachmentParameteriv glad_glGetFramebufferAttachmentParameteriv +GLAD_API_CALL PFNGLGETGRAPHICSRESETSTATUSARBPROC glad_glGetGraphicsResetStatusARB; +#define glGetGraphicsResetStatusARB glad_glGetGraphicsResetStatusARB +GLAD_API_CALL PFNGLGETINTEGER64I_VPROC glad_glGetInteger64i_v; +#define glGetInteger64i_v glad_glGetInteger64i_v +GLAD_API_CALL PFNGLGETINTEGER64VPROC glad_glGetInteger64v; +#define glGetInteger64v glad_glGetInteger64v +GLAD_API_CALL PFNGLGETINTEGERI_VPROC glad_glGetIntegeri_v; +#define glGetIntegeri_v glad_glGetIntegeri_v +GLAD_API_CALL PFNGLGETINTEGERVPROC glad_glGetIntegerv; +#define glGetIntegerv glad_glGetIntegerv +GLAD_API_CALL PFNGLGETLIGHTFVPROC glad_glGetLightfv; +#define glGetLightfv glad_glGetLightfv +GLAD_API_CALL PFNGLGETLIGHTIVPROC glad_glGetLightiv; +#define glGetLightiv glad_glGetLightiv +GLAD_API_CALL PFNGLGETMAPDVPROC glad_glGetMapdv; +#define glGetMapdv glad_glGetMapdv +GLAD_API_CALL PFNGLGETMAPFVPROC glad_glGetMapfv; +#define glGetMapfv glad_glGetMapfv +GLAD_API_CALL PFNGLGETMAPIVPROC glad_glGetMapiv; +#define glGetMapiv glad_glGetMapiv +GLAD_API_CALL PFNGLGETMATERIALFVPROC glad_glGetMaterialfv; +#define glGetMaterialfv glad_glGetMaterialfv +GLAD_API_CALL PFNGLGETMATERIALIVPROC glad_glGetMaterialiv; +#define glGetMaterialiv glad_glGetMaterialiv +GLAD_API_CALL PFNGLGETMULTISAMPLEFVPROC glad_glGetMultisamplefv; +#define glGetMultisamplefv glad_glGetMultisamplefv +GLAD_API_CALL PFNGLGETOBJECTLABELPROC glad_glGetObjectLabel; +#define glGetObjectLabel glad_glGetObjectLabel +GLAD_API_CALL PFNGLGETOBJECTPTRLABELPROC glad_glGetObjectPtrLabel; +#define glGetObjectPtrLabel glad_glGetObjectPtrLabel +GLAD_API_CALL PFNGLGETPIXELMAPFVPROC glad_glGetPixelMapfv; +#define glGetPixelMapfv glad_glGetPixelMapfv +GLAD_API_CALL PFNGLGETPIXELMAPUIVPROC glad_glGetPixelMapuiv; +#define glGetPixelMapuiv glad_glGetPixelMapuiv +GLAD_API_CALL PFNGLGETPIXELMAPUSVPROC glad_glGetPixelMapusv; +#define glGetPixelMapusv glad_glGetPixelMapusv +GLAD_API_CALL PFNGLGETPOINTERVPROC glad_glGetPointerv; +#define glGetPointerv glad_glGetPointerv +GLAD_API_CALL PFNGLGETPOLYGONSTIPPLEPROC glad_glGetPolygonStipple; +#define glGetPolygonStipple glad_glGetPolygonStipple +GLAD_API_CALL PFNGLGETPROGRAMINFOLOGPROC glad_glGetProgramInfoLog; +#define glGetProgramInfoLog glad_glGetProgramInfoLog +GLAD_API_CALL PFNGLGETPROGRAMIVPROC glad_glGetProgramiv; +#define glGetProgramiv glad_glGetProgramiv +GLAD_API_CALL PFNGLGETQUERYOBJECTI64VPROC glad_glGetQueryObjecti64v; +#define glGetQueryObjecti64v glad_glGetQueryObjecti64v +GLAD_API_CALL PFNGLGETQUERYOBJECTIVPROC glad_glGetQueryObjectiv; +#define glGetQueryObjectiv glad_glGetQueryObjectiv +GLAD_API_CALL PFNGLGETQUERYOBJECTUI64VPROC glad_glGetQueryObjectui64v; +#define glGetQueryObjectui64v glad_glGetQueryObjectui64v +GLAD_API_CALL PFNGLGETQUERYOBJECTUIVPROC glad_glGetQueryObjectuiv; +#define glGetQueryObjectuiv glad_glGetQueryObjectuiv +GLAD_API_CALL PFNGLGETQUERYIVPROC glad_glGetQueryiv; +#define glGetQueryiv glad_glGetQueryiv +GLAD_API_CALL PFNGLGETRENDERBUFFERPARAMETERIVPROC glad_glGetRenderbufferParameteriv; +#define glGetRenderbufferParameteriv glad_glGetRenderbufferParameteriv +GLAD_API_CALL PFNGLGETSAMPLERPARAMETERIIVPROC glad_glGetSamplerParameterIiv; +#define glGetSamplerParameterIiv glad_glGetSamplerParameterIiv +GLAD_API_CALL PFNGLGETSAMPLERPARAMETERIUIVPROC glad_glGetSamplerParameterIuiv; +#define glGetSamplerParameterIuiv glad_glGetSamplerParameterIuiv +GLAD_API_CALL PFNGLGETSAMPLERPARAMETERFVPROC glad_glGetSamplerParameterfv; +#define glGetSamplerParameterfv glad_glGetSamplerParameterfv +GLAD_API_CALL PFNGLGETSAMPLERPARAMETERIVPROC glad_glGetSamplerParameteriv; +#define glGetSamplerParameteriv glad_glGetSamplerParameteriv +GLAD_API_CALL PFNGLGETSHADERINFOLOGPROC glad_glGetShaderInfoLog; +#define glGetShaderInfoLog glad_glGetShaderInfoLog +GLAD_API_CALL PFNGLGETSHADERSOURCEPROC glad_glGetShaderSource; +#define glGetShaderSource glad_glGetShaderSource +GLAD_API_CALL PFNGLGETSHADERIVPROC glad_glGetShaderiv; +#define glGetShaderiv glad_glGetShaderiv +GLAD_API_CALL PFNGLGETSTRINGPROC glad_glGetString; +#define glGetString glad_glGetString +GLAD_API_CALL PFNGLGETSTRINGIPROC glad_glGetStringi; +#define glGetStringi glad_glGetStringi +GLAD_API_CALL PFNGLGETSYNCIVPROC glad_glGetSynciv; +#define glGetSynciv glad_glGetSynciv +GLAD_API_CALL PFNGLGETTEXENVFVPROC glad_glGetTexEnvfv; +#define glGetTexEnvfv glad_glGetTexEnvfv +GLAD_API_CALL PFNGLGETTEXENVIVPROC glad_glGetTexEnviv; +#define glGetTexEnviv glad_glGetTexEnviv +GLAD_API_CALL PFNGLGETTEXGENDVPROC glad_glGetTexGendv; +#define glGetTexGendv glad_glGetTexGendv +GLAD_API_CALL PFNGLGETTEXGENFVPROC glad_glGetTexGenfv; +#define glGetTexGenfv glad_glGetTexGenfv +GLAD_API_CALL PFNGLGETTEXGENIVPROC glad_glGetTexGeniv; +#define glGetTexGeniv glad_glGetTexGeniv +GLAD_API_CALL PFNGLGETTEXIMAGEPROC glad_glGetTexImage; +#define glGetTexImage glad_glGetTexImage +GLAD_API_CALL PFNGLGETTEXLEVELPARAMETERFVPROC glad_glGetTexLevelParameterfv; +#define glGetTexLevelParameterfv glad_glGetTexLevelParameterfv +GLAD_API_CALL PFNGLGETTEXLEVELPARAMETERIVPROC glad_glGetTexLevelParameteriv; +#define glGetTexLevelParameteriv glad_glGetTexLevelParameteriv +GLAD_API_CALL PFNGLGETTEXPARAMETERIIVPROC glad_glGetTexParameterIiv; +#define glGetTexParameterIiv glad_glGetTexParameterIiv +GLAD_API_CALL PFNGLGETTEXPARAMETERIUIVPROC glad_glGetTexParameterIuiv; +#define glGetTexParameterIuiv glad_glGetTexParameterIuiv +GLAD_API_CALL PFNGLGETTEXPARAMETERFVPROC glad_glGetTexParameterfv; +#define glGetTexParameterfv glad_glGetTexParameterfv +GLAD_API_CALL PFNGLGETTEXPARAMETERIVPROC glad_glGetTexParameteriv; +#define glGetTexParameteriv glad_glGetTexParameteriv +GLAD_API_CALL PFNGLGETTRANSFORMFEEDBACKVARYINGPROC glad_glGetTransformFeedbackVarying; +#define glGetTransformFeedbackVarying glad_glGetTransformFeedbackVarying +GLAD_API_CALL PFNGLGETUNIFORMBLOCKINDEXPROC glad_glGetUniformBlockIndex; +#define glGetUniformBlockIndex glad_glGetUniformBlockIndex +GLAD_API_CALL PFNGLGETUNIFORMINDICESPROC glad_glGetUniformIndices; +#define glGetUniformIndices glad_glGetUniformIndices +GLAD_API_CALL PFNGLGETUNIFORMLOCATIONPROC glad_glGetUniformLocation; +#define glGetUniformLocation glad_glGetUniformLocation +GLAD_API_CALL PFNGLGETUNIFORMFVPROC glad_glGetUniformfv; +#define glGetUniformfv glad_glGetUniformfv +GLAD_API_CALL PFNGLGETUNIFORMIVPROC glad_glGetUniformiv; +#define glGetUniformiv glad_glGetUniformiv +GLAD_API_CALL PFNGLGETUNIFORMUIVPROC glad_glGetUniformuiv; +#define glGetUniformuiv glad_glGetUniformuiv +GLAD_API_CALL PFNGLGETVERTEXATTRIBIIVPROC glad_glGetVertexAttribIiv; +#define glGetVertexAttribIiv glad_glGetVertexAttribIiv +GLAD_API_CALL PFNGLGETVERTEXATTRIBIUIVPROC glad_glGetVertexAttribIuiv; +#define glGetVertexAttribIuiv glad_glGetVertexAttribIuiv +GLAD_API_CALL PFNGLGETVERTEXATTRIBPOINTERVPROC glad_glGetVertexAttribPointerv; +#define glGetVertexAttribPointerv glad_glGetVertexAttribPointerv +GLAD_API_CALL PFNGLGETVERTEXATTRIBDVPROC glad_glGetVertexAttribdv; +#define glGetVertexAttribdv glad_glGetVertexAttribdv +GLAD_API_CALL PFNGLGETVERTEXATTRIBFVPROC glad_glGetVertexAttribfv; +#define glGetVertexAttribfv glad_glGetVertexAttribfv +GLAD_API_CALL PFNGLGETVERTEXATTRIBIVPROC glad_glGetVertexAttribiv; +#define glGetVertexAttribiv glad_glGetVertexAttribiv +GLAD_API_CALL PFNGLGETNCOLORTABLEARBPROC glad_glGetnColorTableARB; +#define glGetnColorTableARB glad_glGetnColorTableARB +GLAD_API_CALL PFNGLGETNCOMPRESSEDTEXIMAGEARBPROC glad_glGetnCompressedTexImageARB; +#define glGetnCompressedTexImageARB glad_glGetnCompressedTexImageARB +GLAD_API_CALL PFNGLGETNCONVOLUTIONFILTERARBPROC glad_glGetnConvolutionFilterARB; +#define glGetnConvolutionFilterARB glad_glGetnConvolutionFilterARB +GLAD_API_CALL PFNGLGETNHISTOGRAMARBPROC glad_glGetnHistogramARB; +#define glGetnHistogramARB glad_glGetnHistogramARB +GLAD_API_CALL PFNGLGETNMAPDVARBPROC glad_glGetnMapdvARB; +#define glGetnMapdvARB glad_glGetnMapdvARB +GLAD_API_CALL PFNGLGETNMAPFVARBPROC glad_glGetnMapfvARB; +#define glGetnMapfvARB glad_glGetnMapfvARB +GLAD_API_CALL PFNGLGETNMAPIVARBPROC glad_glGetnMapivARB; +#define glGetnMapivARB glad_glGetnMapivARB +GLAD_API_CALL PFNGLGETNMINMAXARBPROC glad_glGetnMinmaxARB; +#define glGetnMinmaxARB glad_glGetnMinmaxARB +GLAD_API_CALL PFNGLGETNPIXELMAPFVARBPROC glad_glGetnPixelMapfvARB; +#define glGetnPixelMapfvARB glad_glGetnPixelMapfvARB +GLAD_API_CALL PFNGLGETNPIXELMAPUIVARBPROC glad_glGetnPixelMapuivARB; +#define glGetnPixelMapuivARB glad_glGetnPixelMapuivARB +GLAD_API_CALL PFNGLGETNPIXELMAPUSVARBPROC glad_glGetnPixelMapusvARB; +#define glGetnPixelMapusvARB glad_glGetnPixelMapusvARB +GLAD_API_CALL PFNGLGETNPOLYGONSTIPPLEARBPROC glad_glGetnPolygonStippleARB; +#define glGetnPolygonStippleARB glad_glGetnPolygonStippleARB +GLAD_API_CALL PFNGLGETNSEPARABLEFILTERARBPROC glad_glGetnSeparableFilterARB; +#define glGetnSeparableFilterARB glad_glGetnSeparableFilterARB +GLAD_API_CALL PFNGLGETNTEXIMAGEARBPROC glad_glGetnTexImageARB; +#define glGetnTexImageARB glad_glGetnTexImageARB +GLAD_API_CALL PFNGLGETNUNIFORMDVARBPROC glad_glGetnUniformdvARB; +#define glGetnUniformdvARB glad_glGetnUniformdvARB +GLAD_API_CALL PFNGLGETNUNIFORMFVARBPROC glad_glGetnUniformfvARB; +#define glGetnUniformfvARB glad_glGetnUniformfvARB +GLAD_API_CALL PFNGLGETNUNIFORMIVARBPROC glad_glGetnUniformivARB; +#define glGetnUniformivARB glad_glGetnUniformivARB +GLAD_API_CALL PFNGLGETNUNIFORMUIVARBPROC glad_glGetnUniformuivARB; +#define glGetnUniformuivARB glad_glGetnUniformuivARB +GLAD_API_CALL PFNGLHINTPROC glad_glHint; +#define glHint glad_glHint +GLAD_API_CALL PFNGLINDEXMASKPROC glad_glIndexMask; +#define glIndexMask glad_glIndexMask +GLAD_API_CALL PFNGLINDEXPOINTERPROC glad_glIndexPointer; +#define glIndexPointer glad_glIndexPointer +GLAD_API_CALL PFNGLINDEXDPROC glad_glIndexd; +#define glIndexd glad_glIndexd +GLAD_API_CALL PFNGLINDEXDVPROC glad_glIndexdv; +#define glIndexdv glad_glIndexdv +GLAD_API_CALL PFNGLINDEXFPROC glad_glIndexf; +#define glIndexf glad_glIndexf +GLAD_API_CALL PFNGLINDEXFVPROC glad_glIndexfv; +#define glIndexfv glad_glIndexfv +GLAD_API_CALL PFNGLINDEXIPROC glad_glIndexi; +#define glIndexi glad_glIndexi +GLAD_API_CALL PFNGLINDEXIVPROC glad_glIndexiv; +#define glIndexiv glad_glIndexiv +GLAD_API_CALL PFNGLINDEXSPROC glad_glIndexs; +#define glIndexs glad_glIndexs +GLAD_API_CALL PFNGLINDEXSVPROC glad_glIndexsv; +#define glIndexsv glad_glIndexsv +GLAD_API_CALL PFNGLINDEXUBPROC glad_glIndexub; +#define glIndexub glad_glIndexub +GLAD_API_CALL PFNGLINDEXUBVPROC glad_glIndexubv; +#define glIndexubv glad_glIndexubv +GLAD_API_CALL PFNGLINITNAMESPROC glad_glInitNames; +#define glInitNames glad_glInitNames +GLAD_API_CALL PFNGLINTERLEAVEDARRAYSPROC glad_glInterleavedArrays; +#define glInterleavedArrays glad_glInterleavedArrays +GLAD_API_CALL PFNGLISBUFFERPROC glad_glIsBuffer; +#define glIsBuffer glad_glIsBuffer +GLAD_API_CALL PFNGLISENABLEDPROC glad_glIsEnabled; +#define glIsEnabled glad_glIsEnabled +GLAD_API_CALL PFNGLISENABLEDIPROC glad_glIsEnabledi; +#define glIsEnabledi glad_glIsEnabledi +GLAD_API_CALL PFNGLISFRAMEBUFFERPROC glad_glIsFramebuffer; +#define glIsFramebuffer glad_glIsFramebuffer +GLAD_API_CALL PFNGLISLISTPROC glad_glIsList; +#define glIsList glad_glIsList +GLAD_API_CALL PFNGLISPROGRAMPROC glad_glIsProgram; +#define glIsProgram glad_glIsProgram +GLAD_API_CALL PFNGLISQUERYPROC glad_glIsQuery; +#define glIsQuery glad_glIsQuery +GLAD_API_CALL PFNGLISRENDERBUFFERPROC glad_glIsRenderbuffer; +#define glIsRenderbuffer glad_glIsRenderbuffer +GLAD_API_CALL PFNGLISSAMPLERPROC glad_glIsSampler; +#define glIsSampler glad_glIsSampler +GLAD_API_CALL PFNGLISSHADERPROC glad_glIsShader; +#define glIsShader glad_glIsShader +GLAD_API_CALL PFNGLISSYNCPROC glad_glIsSync; +#define glIsSync glad_glIsSync +GLAD_API_CALL PFNGLISTEXTUREPROC glad_glIsTexture; +#define glIsTexture glad_glIsTexture +GLAD_API_CALL PFNGLISVERTEXARRAYPROC glad_glIsVertexArray; +#define glIsVertexArray glad_glIsVertexArray +GLAD_API_CALL PFNGLLIGHTMODELFPROC glad_glLightModelf; +#define glLightModelf glad_glLightModelf +GLAD_API_CALL PFNGLLIGHTMODELFVPROC glad_glLightModelfv; +#define glLightModelfv glad_glLightModelfv +GLAD_API_CALL PFNGLLIGHTMODELIPROC glad_glLightModeli; +#define glLightModeli glad_glLightModeli +GLAD_API_CALL PFNGLLIGHTMODELIVPROC glad_glLightModeliv; +#define glLightModeliv glad_glLightModeliv +GLAD_API_CALL PFNGLLIGHTFPROC glad_glLightf; +#define glLightf glad_glLightf +GLAD_API_CALL PFNGLLIGHTFVPROC glad_glLightfv; +#define glLightfv glad_glLightfv +GLAD_API_CALL PFNGLLIGHTIPROC glad_glLighti; +#define glLighti glad_glLighti +GLAD_API_CALL PFNGLLIGHTIVPROC glad_glLightiv; +#define glLightiv glad_glLightiv +GLAD_API_CALL PFNGLLINESTIPPLEPROC glad_glLineStipple; +#define glLineStipple glad_glLineStipple +GLAD_API_CALL PFNGLLINEWIDTHPROC glad_glLineWidth; +#define glLineWidth glad_glLineWidth +GLAD_API_CALL PFNGLLINKPROGRAMPROC glad_glLinkProgram; +#define glLinkProgram glad_glLinkProgram +GLAD_API_CALL PFNGLLISTBASEPROC glad_glListBase; +#define glListBase glad_glListBase +GLAD_API_CALL PFNGLLOADIDENTITYPROC glad_glLoadIdentity; +#define glLoadIdentity glad_glLoadIdentity +GLAD_API_CALL PFNGLLOADMATRIXDPROC glad_glLoadMatrixd; +#define glLoadMatrixd glad_glLoadMatrixd +GLAD_API_CALL PFNGLLOADMATRIXFPROC glad_glLoadMatrixf; +#define glLoadMatrixf glad_glLoadMatrixf +GLAD_API_CALL PFNGLLOADNAMEPROC glad_glLoadName; +#define glLoadName glad_glLoadName +GLAD_API_CALL PFNGLLOADTRANSPOSEMATRIXDPROC glad_glLoadTransposeMatrixd; +#define glLoadTransposeMatrixd glad_glLoadTransposeMatrixd +GLAD_API_CALL PFNGLLOADTRANSPOSEMATRIXFPROC glad_glLoadTransposeMatrixf; +#define glLoadTransposeMatrixf glad_glLoadTransposeMatrixf +GLAD_API_CALL PFNGLLOGICOPPROC glad_glLogicOp; +#define glLogicOp glad_glLogicOp +GLAD_API_CALL PFNGLMAP1DPROC glad_glMap1d; +#define glMap1d glad_glMap1d +GLAD_API_CALL PFNGLMAP1FPROC glad_glMap1f; +#define glMap1f glad_glMap1f +GLAD_API_CALL PFNGLMAP2DPROC glad_glMap2d; +#define glMap2d glad_glMap2d +GLAD_API_CALL PFNGLMAP2FPROC glad_glMap2f; +#define glMap2f glad_glMap2f +GLAD_API_CALL PFNGLMAPBUFFERPROC glad_glMapBuffer; +#define glMapBuffer glad_glMapBuffer +GLAD_API_CALL PFNGLMAPBUFFERRANGEPROC glad_glMapBufferRange; +#define glMapBufferRange glad_glMapBufferRange +GLAD_API_CALL PFNGLMAPGRID1DPROC glad_glMapGrid1d; +#define glMapGrid1d glad_glMapGrid1d +GLAD_API_CALL PFNGLMAPGRID1FPROC glad_glMapGrid1f; +#define glMapGrid1f glad_glMapGrid1f +GLAD_API_CALL PFNGLMAPGRID2DPROC glad_glMapGrid2d; +#define glMapGrid2d glad_glMapGrid2d +GLAD_API_CALL PFNGLMAPGRID2FPROC glad_glMapGrid2f; +#define glMapGrid2f glad_glMapGrid2f +GLAD_API_CALL PFNGLMATERIALFPROC glad_glMaterialf; +#define glMaterialf glad_glMaterialf +GLAD_API_CALL PFNGLMATERIALFVPROC glad_glMaterialfv; +#define glMaterialfv glad_glMaterialfv +GLAD_API_CALL PFNGLMATERIALIPROC glad_glMateriali; +#define glMateriali glad_glMateriali +GLAD_API_CALL PFNGLMATERIALIVPROC glad_glMaterialiv; +#define glMaterialiv glad_glMaterialiv +GLAD_API_CALL PFNGLMATRIXMODEPROC glad_glMatrixMode; +#define glMatrixMode glad_glMatrixMode +GLAD_API_CALL PFNGLMULTMATRIXDPROC glad_glMultMatrixd; +#define glMultMatrixd glad_glMultMatrixd +GLAD_API_CALL PFNGLMULTMATRIXFPROC glad_glMultMatrixf; +#define glMultMatrixf glad_glMultMatrixf +GLAD_API_CALL PFNGLMULTTRANSPOSEMATRIXDPROC glad_glMultTransposeMatrixd; +#define glMultTransposeMatrixd glad_glMultTransposeMatrixd +GLAD_API_CALL PFNGLMULTTRANSPOSEMATRIXFPROC glad_glMultTransposeMatrixf; +#define glMultTransposeMatrixf glad_glMultTransposeMatrixf +GLAD_API_CALL PFNGLMULTIDRAWARRAYSPROC glad_glMultiDrawArrays; +#define glMultiDrawArrays glad_glMultiDrawArrays +GLAD_API_CALL PFNGLMULTIDRAWELEMENTSPROC glad_glMultiDrawElements; +#define glMultiDrawElements glad_glMultiDrawElements +GLAD_API_CALL PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC glad_glMultiDrawElementsBaseVertex; +#define glMultiDrawElementsBaseVertex glad_glMultiDrawElementsBaseVertex +GLAD_API_CALL PFNGLMULTITEXCOORD1DPROC glad_glMultiTexCoord1d; +#define glMultiTexCoord1d glad_glMultiTexCoord1d +GLAD_API_CALL PFNGLMULTITEXCOORD1DVPROC glad_glMultiTexCoord1dv; +#define glMultiTexCoord1dv glad_glMultiTexCoord1dv +GLAD_API_CALL PFNGLMULTITEXCOORD1FPROC glad_glMultiTexCoord1f; +#define glMultiTexCoord1f glad_glMultiTexCoord1f +GLAD_API_CALL PFNGLMULTITEXCOORD1FVPROC glad_glMultiTexCoord1fv; +#define glMultiTexCoord1fv glad_glMultiTexCoord1fv +GLAD_API_CALL PFNGLMULTITEXCOORD1IPROC glad_glMultiTexCoord1i; +#define glMultiTexCoord1i glad_glMultiTexCoord1i +GLAD_API_CALL PFNGLMULTITEXCOORD1IVPROC glad_glMultiTexCoord1iv; +#define glMultiTexCoord1iv glad_glMultiTexCoord1iv +GLAD_API_CALL PFNGLMULTITEXCOORD1SPROC glad_glMultiTexCoord1s; +#define glMultiTexCoord1s glad_glMultiTexCoord1s +GLAD_API_CALL PFNGLMULTITEXCOORD1SVPROC glad_glMultiTexCoord1sv; +#define glMultiTexCoord1sv glad_glMultiTexCoord1sv +GLAD_API_CALL PFNGLMULTITEXCOORD2DPROC glad_glMultiTexCoord2d; +#define glMultiTexCoord2d glad_glMultiTexCoord2d +GLAD_API_CALL PFNGLMULTITEXCOORD2DVPROC glad_glMultiTexCoord2dv; +#define glMultiTexCoord2dv glad_glMultiTexCoord2dv +GLAD_API_CALL PFNGLMULTITEXCOORD2FPROC glad_glMultiTexCoord2f; +#define glMultiTexCoord2f glad_glMultiTexCoord2f +GLAD_API_CALL PFNGLMULTITEXCOORD2FVPROC glad_glMultiTexCoord2fv; +#define glMultiTexCoord2fv glad_glMultiTexCoord2fv +GLAD_API_CALL PFNGLMULTITEXCOORD2IPROC glad_glMultiTexCoord2i; +#define glMultiTexCoord2i glad_glMultiTexCoord2i +GLAD_API_CALL PFNGLMULTITEXCOORD2IVPROC glad_glMultiTexCoord2iv; +#define glMultiTexCoord2iv glad_glMultiTexCoord2iv +GLAD_API_CALL PFNGLMULTITEXCOORD2SPROC glad_glMultiTexCoord2s; +#define glMultiTexCoord2s glad_glMultiTexCoord2s +GLAD_API_CALL PFNGLMULTITEXCOORD2SVPROC glad_glMultiTexCoord2sv; +#define glMultiTexCoord2sv glad_glMultiTexCoord2sv +GLAD_API_CALL PFNGLMULTITEXCOORD3DPROC glad_glMultiTexCoord3d; +#define glMultiTexCoord3d glad_glMultiTexCoord3d +GLAD_API_CALL PFNGLMULTITEXCOORD3DVPROC glad_glMultiTexCoord3dv; +#define glMultiTexCoord3dv glad_glMultiTexCoord3dv +GLAD_API_CALL PFNGLMULTITEXCOORD3FPROC glad_glMultiTexCoord3f; +#define glMultiTexCoord3f glad_glMultiTexCoord3f +GLAD_API_CALL PFNGLMULTITEXCOORD3FVPROC glad_glMultiTexCoord3fv; +#define glMultiTexCoord3fv glad_glMultiTexCoord3fv +GLAD_API_CALL PFNGLMULTITEXCOORD3IPROC glad_glMultiTexCoord3i; +#define glMultiTexCoord3i glad_glMultiTexCoord3i +GLAD_API_CALL PFNGLMULTITEXCOORD3IVPROC glad_glMultiTexCoord3iv; +#define glMultiTexCoord3iv glad_glMultiTexCoord3iv +GLAD_API_CALL PFNGLMULTITEXCOORD3SPROC glad_glMultiTexCoord3s; +#define glMultiTexCoord3s glad_glMultiTexCoord3s +GLAD_API_CALL PFNGLMULTITEXCOORD3SVPROC glad_glMultiTexCoord3sv; +#define glMultiTexCoord3sv glad_glMultiTexCoord3sv +GLAD_API_CALL PFNGLMULTITEXCOORD4DPROC glad_glMultiTexCoord4d; +#define glMultiTexCoord4d glad_glMultiTexCoord4d +GLAD_API_CALL PFNGLMULTITEXCOORD4DVPROC glad_glMultiTexCoord4dv; +#define glMultiTexCoord4dv glad_glMultiTexCoord4dv +GLAD_API_CALL PFNGLMULTITEXCOORD4FPROC glad_glMultiTexCoord4f; +#define glMultiTexCoord4f glad_glMultiTexCoord4f +GLAD_API_CALL PFNGLMULTITEXCOORD4FVPROC glad_glMultiTexCoord4fv; +#define glMultiTexCoord4fv glad_glMultiTexCoord4fv +GLAD_API_CALL PFNGLMULTITEXCOORD4IPROC glad_glMultiTexCoord4i; +#define glMultiTexCoord4i glad_glMultiTexCoord4i +GLAD_API_CALL PFNGLMULTITEXCOORD4IVPROC glad_glMultiTexCoord4iv; +#define glMultiTexCoord4iv glad_glMultiTexCoord4iv +GLAD_API_CALL PFNGLMULTITEXCOORD4SPROC glad_glMultiTexCoord4s; +#define glMultiTexCoord4s glad_glMultiTexCoord4s +GLAD_API_CALL PFNGLMULTITEXCOORD4SVPROC glad_glMultiTexCoord4sv; +#define glMultiTexCoord4sv glad_glMultiTexCoord4sv +GLAD_API_CALL PFNGLMULTITEXCOORDP1UIPROC glad_glMultiTexCoordP1ui; +#define glMultiTexCoordP1ui glad_glMultiTexCoordP1ui +GLAD_API_CALL PFNGLMULTITEXCOORDP1UIVPROC glad_glMultiTexCoordP1uiv; +#define glMultiTexCoordP1uiv glad_glMultiTexCoordP1uiv +GLAD_API_CALL PFNGLMULTITEXCOORDP2UIPROC glad_glMultiTexCoordP2ui; +#define glMultiTexCoordP2ui glad_glMultiTexCoordP2ui +GLAD_API_CALL PFNGLMULTITEXCOORDP2UIVPROC glad_glMultiTexCoordP2uiv; +#define glMultiTexCoordP2uiv glad_glMultiTexCoordP2uiv +GLAD_API_CALL PFNGLMULTITEXCOORDP3UIPROC glad_glMultiTexCoordP3ui; +#define glMultiTexCoordP3ui glad_glMultiTexCoordP3ui +GLAD_API_CALL PFNGLMULTITEXCOORDP3UIVPROC glad_glMultiTexCoordP3uiv; +#define glMultiTexCoordP3uiv glad_glMultiTexCoordP3uiv +GLAD_API_CALL PFNGLMULTITEXCOORDP4UIPROC glad_glMultiTexCoordP4ui; +#define glMultiTexCoordP4ui glad_glMultiTexCoordP4ui +GLAD_API_CALL PFNGLMULTITEXCOORDP4UIVPROC glad_glMultiTexCoordP4uiv; +#define glMultiTexCoordP4uiv glad_glMultiTexCoordP4uiv +GLAD_API_CALL PFNGLNEWLISTPROC glad_glNewList; +#define glNewList glad_glNewList +GLAD_API_CALL PFNGLNORMAL3BPROC glad_glNormal3b; +#define glNormal3b glad_glNormal3b +GLAD_API_CALL PFNGLNORMAL3BVPROC glad_glNormal3bv; +#define glNormal3bv glad_glNormal3bv +GLAD_API_CALL PFNGLNORMAL3DPROC glad_glNormal3d; +#define glNormal3d glad_glNormal3d +GLAD_API_CALL PFNGLNORMAL3DVPROC glad_glNormal3dv; +#define glNormal3dv glad_glNormal3dv +GLAD_API_CALL PFNGLNORMAL3FPROC glad_glNormal3f; +#define glNormal3f glad_glNormal3f +GLAD_API_CALL PFNGLNORMAL3FVPROC glad_glNormal3fv; +#define glNormal3fv glad_glNormal3fv +GLAD_API_CALL PFNGLNORMAL3IPROC glad_glNormal3i; +#define glNormal3i glad_glNormal3i +GLAD_API_CALL PFNGLNORMAL3IVPROC glad_glNormal3iv; +#define glNormal3iv glad_glNormal3iv +GLAD_API_CALL PFNGLNORMAL3SPROC glad_glNormal3s; +#define glNormal3s glad_glNormal3s +GLAD_API_CALL PFNGLNORMAL3SVPROC glad_glNormal3sv; +#define glNormal3sv glad_glNormal3sv +GLAD_API_CALL PFNGLNORMALP3UIPROC glad_glNormalP3ui; +#define glNormalP3ui glad_glNormalP3ui +GLAD_API_CALL PFNGLNORMALP3UIVPROC glad_glNormalP3uiv; +#define glNormalP3uiv glad_glNormalP3uiv +GLAD_API_CALL PFNGLNORMALPOINTERPROC glad_glNormalPointer; +#define glNormalPointer glad_glNormalPointer +GLAD_API_CALL PFNGLOBJECTLABELPROC glad_glObjectLabel; +#define glObjectLabel glad_glObjectLabel +GLAD_API_CALL PFNGLOBJECTPTRLABELPROC glad_glObjectPtrLabel; +#define glObjectPtrLabel glad_glObjectPtrLabel +GLAD_API_CALL PFNGLORTHOPROC glad_glOrtho; +#define glOrtho glad_glOrtho +GLAD_API_CALL PFNGLPASSTHROUGHPROC glad_glPassThrough; +#define glPassThrough glad_glPassThrough +GLAD_API_CALL PFNGLPIXELMAPFVPROC glad_glPixelMapfv; +#define glPixelMapfv glad_glPixelMapfv +GLAD_API_CALL PFNGLPIXELMAPUIVPROC glad_glPixelMapuiv; +#define glPixelMapuiv glad_glPixelMapuiv +GLAD_API_CALL PFNGLPIXELMAPUSVPROC glad_glPixelMapusv; +#define glPixelMapusv glad_glPixelMapusv +GLAD_API_CALL PFNGLPIXELSTOREFPROC glad_glPixelStoref; +#define glPixelStoref glad_glPixelStoref +GLAD_API_CALL PFNGLPIXELSTOREIPROC glad_glPixelStorei; +#define glPixelStorei glad_glPixelStorei +GLAD_API_CALL PFNGLPIXELTRANSFERFPROC glad_glPixelTransferf; +#define glPixelTransferf glad_glPixelTransferf +GLAD_API_CALL PFNGLPIXELTRANSFERIPROC glad_glPixelTransferi; +#define glPixelTransferi glad_glPixelTransferi +GLAD_API_CALL PFNGLPIXELZOOMPROC glad_glPixelZoom; +#define glPixelZoom glad_glPixelZoom +GLAD_API_CALL PFNGLPOINTPARAMETERFPROC glad_glPointParameterf; +#define glPointParameterf glad_glPointParameterf +GLAD_API_CALL PFNGLPOINTPARAMETERFVPROC glad_glPointParameterfv; +#define glPointParameterfv glad_glPointParameterfv +GLAD_API_CALL PFNGLPOINTPARAMETERIPROC glad_glPointParameteri; +#define glPointParameteri glad_glPointParameteri +GLAD_API_CALL PFNGLPOINTPARAMETERIVPROC glad_glPointParameteriv; +#define glPointParameteriv glad_glPointParameteriv +GLAD_API_CALL PFNGLPOINTSIZEPROC glad_glPointSize; +#define glPointSize glad_glPointSize +GLAD_API_CALL PFNGLPOLYGONMODEPROC glad_glPolygonMode; +#define glPolygonMode glad_glPolygonMode +GLAD_API_CALL PFNGLPOLYGONOFFSETPROC glad_glPolygonOffset; +#define glPolygonOffset glad_glPolygonOffset +GLAD_API_CALL PFNGLPOLYGONSTIPPLEPROC glad_glPolygonStipple; +#define glPolygonStipple glad_glPolygonStipple +GLAD_API_CALL PFNGLPOPATTRIBPROC glad_glPopAttrib; +#define glPopAttrib glad_glPopAttrib +GLAD_API_CALL PFNGLPOPCLIENTATTRIBPROC glad_glPopClientAttrib; +#define glPopClientAttrib glad_glPopClientAttrib +GLAD_API_CALL PFNGLPOPDEBUGGROUPPROC glad_glPopDebugGroup; +#define glPopDebugGroup glad_glPopDebugGroup +GLAD_API_CALL PFNGLPOPMATRIXPROC glad_glPopMatrix; +#define glPopMatrix glad_glPopMatrix +GLAD_API_CALL PFNGLPOPNAMEPROC glad_glPopName; +#define glPopName glad_glPopName +GLAD_API_CALL PFNGLPRIMITIVERESTARTINDEXPROC glad_glPrimitiveRestartIndex; +#define glPrimitiveRestartIndex glad_glPrimitiveRestartIndex +GLAD_API_CALL PFNGLPRIORITIZETEXTURESPROC glad_glPrioritizeTextures; +#define glPrioritizeTextures glad_glPrioritizeTextures +GLAD_API_CALL PFNGLPROVOKINGVERTEXPROC glad_glProvokingVertex; +#define glProvokingVertex glad_glProvokingVertex +GLAD_API_CALL PFNGLPUSHATTRIBPROC glad_glPushAttrib; +#define glPushAttrib glad_glPushAttrib +GLAD_API_CALL PFNGLPUSHCLIENTATTRIBPROC glad_glPushClientAttrib; +#define glPushClientAttrib glad_glPushClientAttrib +GLAD_API_CALL PFNGLPUSHDEBUGGROUPPROC glad_glPushDebugGroup; +#define glPushDebugGroup glad_glPushDebugGroup +GLAD_API_CALL PFNGLPUSHMATRIXPROC glad_glPushMatrix; +#define glPushMatrix glad_glPushMatrix +GLAD_API_CALL PFNGLPUSHNAMEPROC glad_glPushName; +#define glPushName glad_glPushName +GLAD_API_CALL PFNGLQUERYCOUNTERPROC glad_glQueryCounter; +#define glQueryCounter glad_glQueryCounter +GLAD_API_CALL PFNGLRASTERPOS2DPROC glad_glRasterPos2d; +#define glRasterPos2d glad_glRasterPos2d +GLAD_API_CALL PFNGLRASTERPOS2DVPROC glad_glRasterPos2dv; +#define glRasterPos2dv glad_glRasterPos2dv +GLAD_API_CALL PFNGLRASTERPOS2FPROC glad_glRasterPos2f; +#define glRasterPos2f glad_glRasterPos2f +GLAD_API_CALL PFNGLRASTERPOS2FVPROC glad_glRasterPos2fv; +#define glRasterPos2fv glad_glRasterPos2fv +GLAD_API_CALL PFNGLRASTERPOS2IPROC glad_glRasterPos2i; +#define glRasterPos2i glad_glRasterPos2i +GLAD_API_CALL PFNGLRASTERPOS2IVPROC glad_glRasterPos2iv; +#define glRasterPos2iv glad_glRasterPos2iv +GLAD_API_CALL PFNGLRASTERPOS2SPROC glad_glRasterPos2s; +#define glRasterPos2s glad_glRasterPos2s +GLAD_API_CALL PFNGLRASTERPOS2SVPROC glad_glRasterPos2sv; +#define glRasterPos2sv glad_glRasterPos2sv +GLAD_API_CALL PFNGLRASTERPOS3DPROC glad_glRasterPos3d; +#define glRasterPos3d glad_glRasterPos3d +GLAD_API_CALL PFNGLRASTERPOS3DVPROC glad_glRasterPos3dv; +#define glRasterPos3dv glad_glRasterPos3dv +GLAD_API_CALL PFNGLRASTERPOS3FPROC glad_glRasterPos3f; +#define glRasterPos3f glad_glRasterPos3f +GLAD_API_CALL PFNGLRASTERPOS3FVPROC glad_glRasterPos3fv; +#define glRasterPos3fv glad_glRasterPos3fv +GLAD_API_CALL PFNGLRASTERPOS3IPROC glad_glRasterPos3i; +#define glRasterPos3i glad_glRasterPos3i +GLAD_API_CALL PFNGLRASTERPOS3IVPROC glad_glRasterPos3iv; +#define glRasterPos3iv glad_glRasterPos3iv +GLAD_API_CALL PFNGLRASTERPOS3SPROC glad_glRasterPos3s; +#define glRasterPos3s glad_glRasterPos3s +GLAD_API_CALL PFNGLRASTERPOS3SVPROC glad_glRasterPos3sv; +#define glRasterPos3sv glad_glRasterPos3sv +GLAD_API_CALL PFNGLRASTERPOS4DPROC glad_glRasterPos4d; +#define glRasterPos4d glad_glRasterPos4d +GLAD_API_CALL PFNGLRASTERPOS4DVPROC glad_glRasterPos4dv; +#define glRasterPos4dv glad_glRasterPos4dv +GLAD_API_CALL PFNGLRASTERPOS4FPROC glad_glRasterPos4f; +#define glRasterPos4f glad_glRasterPos4f +GLAD_API_CALL PFNGLRASTERPOS4FVPROC glad_glRasterPos4fv; +#define glRasterPos4fv glad_glRasterPos4fv +GLAD_API_CALL PFNGLRASTERPOS4IPROC glad_glRasterPos4i; +#define glRasterPos4i glad_glRasterPos4i +GLAD_API_CALL PFNGLRASTERPOS4IVPROC glad_glRasterPos4iv; +#define glRasterPos4iv glad_glRasterPos4iv +GLAD_API_CALL PFNGLRASTERPOS4SPROC glad_glRasterPos4s; +#define glRasterPos4s glad_glRasterPos4s +GLAD_API_CALL PFNGLRASTERPOS4SVPROC glad_glRasterPos4sv; +#define glRasterPos4sv glad_glRasterPos4sv +GLAD_API_CALL PFNGLREADBUFFERPROC glad_glReadBuffer; +#define glReadBuffer glad_glReadBuffer +GLAD_API_CALL PFNGLREADPIXELSPROC glad_glReadPixels; +#define glReadPixels glad_glReadPixels +GLAD_API_CALL PFNGLREADNPIXELSPROC glad_glReadnPixels; +#define glReadnPixels glad_glReadnPixels +GLAD_API_CALL PFNGLREADNPIXELSARBPROC glad_glReadnPixelsARB; +#define glReadnPixelsARB glad_glReadnPixelsARB +GLAD_API_CALL PFNGLRECTDPROC glad_glRectd; +#define glRectd glad_glRectd +GLAD_API_CALL PFNGLRECTDVPROC glad_glRectdv; +#define glRectdv glad_glRectdv +GLAD_API_CALL PFNGLRECTFPROC glad_glRectf; +#define glRectf glad_glRectf +GLAD_API_CALL PFNGLRECTFVPROC glad_glRectfv; +#define glRectfv glad_glRectfv +GLAD_API_CALL PFNGLRECTIPROC glad_glRecti; +#define glRecti glad_glRecti +GLAD_API_CALL PFNGLRECTIVPROC glad_glRectiv; +#define glRectiv glad_glRectiv +GLAD_API_CALL PFNGLRECTSPROC glad_glRects; +#define glRects glad_glRects +GLAD_API_CALL PFNGLRECTSVPROC glad_glRectsv; +#define glRectsv glad_glRectsv +GLAD_API_CALL PFNGLRENDERMODEPROC glad_glRenderMode; +#define glRenderMode glad_glRenderMode +GLAD_API_CALL PFNGLRENDERBUFFERSTORAGEPROC glad_glRenderbufferStorage; +#define glRenderbufferStorage glad_glRenderbufferStorage +GLAD_API_CALL PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC glad_glRenderbufferStorageMultisample; +#define glRenderbufferStorageMultisample glad_glRenderbufferStorageMultisample +GLAD_API_CALL PFNGLROTATEDPROC glad_glRotated; +#define glRotated glad_glRotated +GLAD_API_CALL PFNGLROTATEFPROC glad_glRotatef; +#define glRotatef glad_glRotatef +GLAD_API_CALL PFNGLSAMPLECOVERAGEPROC glad_glSampleCoverage; +#define glSampleCoverage glad_glSampleCoverage +GLAD_API_CALL PFNGLSAMPLECOVERAGEARBPROC glad_glSampleCoverageARB; +#define glSampleCoverageARB glad_glSampleCoverageARB +GLAD_API_CALL PFNGLSAMPLEMASKIPROC glad_glSampleMaski; +#define glSampleMaski glad_glSampleMaski +GLAD_API_CALL PFNGLSAMPLERPARAMETERIIVPROC glad_glSamplerParameterIiv; +#define glSamplerParameterIiv glad_glSamplerParameterIiv +GLAD_API_CALL PFNGLSAMPLERPARAMETERIUIVPROC glad_glSamplerParameterIuiv; +#define glSamplerParameterIuiv glad_glSamplerParameterIuiv +GLAD_API_CALL PFNGLSAMPLERPARAMETERFPROC glad_glSamplerParameterf; +#define glSamplerParameterf glad_glSamplerParameterf +GLAD_API_CALL PFNGLSAMPLERPARAMETERFVPROC glad_glSamplerParameterfv; +#define glSamplerParameterfv glad_glSamplerParameterfv +GLAD_API_CALL PFNGLSAMPLERPARAMETERIPROC glad_glSamplerParameteri; +#define glSamplerParameteri glad_glSamplerParameteri +GLAD_API_CALL PFNGLSAMPLERPARAMETERIVPROC glad_glSamplerParameteriv; +#define glSamplerParameteriv glad_glSamplerParameteriv +GLAD_API_CALL PFNGLSCALEDPROC glad_glScaled; +#define glScaled glad_glScaled +GLAD_API_CALL PFNGLSCALEFPROC glad_glScalef; +#define glScalef glad_glScalef +GLAD_API_CALL PFNGLSCISSORPROC glad_glScissor; +#define glScissor glad_glScissor +GLAD_API_CALL PFNGLSECONDARYCOLOR3BPROC glad_glSecondaryColor3b; +#define glSecondaryColor3b glad_glSecondaryColor3b +GLAD_API_CALL PFNGLSECONDARYCOLOR3BVPROC glad_glSecondaryColor3bv; +#define glSecondaryColor3bv glad_glSecondaryColor3bv +GLAD_API_CALL PFNGLSECONDARYCOLOR3DPROC glad_glSecondaryColor3d; +#define glSecondaryColor3d glad_glSecondaryColor3d +GLAD_API_CALL PFNGLSECONDARYCOLOR3DVPROC glad_glSecondaryColor3dv; +#define glSecondaryColor3dv glad_glSecondaryColor3dv +GLAD_API_CALL PFNGLSECONDARYCOLOR3FPROC glad_glSecondaryColor3f; +#define glSecondaryColor3f glad_glSecondaryColor3f +GLAD_API_CALL PFNGLSECONDARYCOLOR3FVPROC glad_glSecondaryColor3fv; +#define glSecondaryColor3fv glad_glSecondaryColor3fv +GLAD_API_CALL PFNGLSECONDARYCOLOR3IPROC glad_glSecondaryColor3i; +#define glSecondaryColor3i glad_glSecondaryColor3i +GLAD_API_CALL PFNGLSECONDARYCOLOR3IVPROC glad_glSecondaryColor3iv; +#define glSecondaryColor3iv glad_glSecondaryColor3iv +GLAD_API_CALL PFNGLSECONDARYCOLOR3SPROC glad_glSecondaryColor3s; +#define glSecondaryColor3s glad_glSecondaryColor3s +GLAD_API_CALL PFNGLSECONDARYCOLOR3SVPROC glad_glSecondaryColor3sv; +#define glSecondaryColor3sv glad_glSecondaryColor3sv +GLAD_API_CALL PFNGLSECONDARYCOLOR3UBPROC glad_glSecondaryColor3ub; +#define glSecondaryColor3ub glad_glSecondaryColor3ub +GLAD_API_CALL PFNGLSECONDARYCOLOR3UBVPROC glad_glSecondaryColor3ubv; +#define glSecondaryColor3ubv glad_glSecondaryColor3ubv +GLAD_API_CALL PFNGLSECONDARYCOLOR3UIPROC glad_glSecondaryColor3ui; +#define glSecondaryColor3ui glad_glSecondaryColor3ui +GLAD_API_CALL PFNGLSECONDARYCOLOR3UIVPROC glad_glSecondaryColor3uiv; +#define glSecondaryColor3uiv glad_glSecondaryColor3uiv +GLAD_API_CALL PFNGLSECONDARYCOLOR3USPROC glad_glSecondaryColor3us; +#define glSecondaryColor3us glad_glSecondaryColor3us +GLAD_API_CALL PFNGLSECONDARYCOLOR3USVPROC glad_glSecondaryColor3usv; +#define glSecondaryColor3usv glad_glSecondaryColor3usv +GLAD_API_CALL PFNGLSECONDARYCOLORP3UIPROC glad_glSecondaryColorP3ui; +#define glSecondaryColorP3ui glad_glSecondaryColorP3ui +GLAD_API_CALL PFNGLSECONDARYCOLORP3UIVPROC glad_glSecondaryColorP3uiv; +#define glSecondaryColorP3uiv glad_glSecondaryColorP3uiv +GLAD_API_CALL PFNGLSECONDARYCOLORPOINTERPROC glad_glSecondaryColorPointer; +#define glSecondaryColorPointer glad_glSecondaryColorPointer +GLAD_API_CALL PFNGLSELECTBUFFERPROC glad_glSelectBuffer; +#define glSelectBuffer glad_glSelectBuffer +GLAD_API_CALL PFNGLSHADEMODELPROC glad_glShadeModel; +#define glShadeModel glad_glShadeModel +GLAD_API_CALL PFNGLSHADERSOURCEPROC glad_glShaderSource; +#define glShaderSource glad_glShaderSource +GLAD_API_CALL PFNGLSTENCILFUNCPROC glad_glStencilFunc; +#define glStencilFunc glad_glStencilFunc +GLAD_API_CALL PFNGLSTENCILFUNCSEPARATEPROC glad_glStencilFuncSeparate; +#define glStencilFuncSeparate glad_glStencilFuncSeparate +GLAD_API_CALL PFNGLSTENCILMASKPROC glad_glStencilMask; +#define glStencilMask glad_glStencilMask +GLAD_API_CALL PFNGLSTENCILMASKSEPARATEPROC glad_glStencilMaskSeparate; +#define glStencilMaskSeparate glad_glStencilMaskSeparate +GLAD_API_CALL PFNGLSTENCILOPPROC glad_glStencilOp; +#define glStencilOp glad_glStencilOp +GLAD_API_CALL PFNGLSTENCILOPSEPARATEPROC glad_glStencilOpSeparate; +#define glStencilOpSeparate glad_glStencilOpSeparate +GLAD_API_CALL PFNGLTEXBUFFERPROC glad_glTexBuffer; +#define glTexBuffer glad_glTexBuffer +GLAD_API_CALL PFNGLTEXCOORD1DPROC glad_glTexCoord1d; +#define glTexCoord1d glad_glTexCoord1d +GLAD_API_CALL PFNGLTEXCOORD1DVPROC glad_glTexCoord1dv; +#define glTexCoord1dv glad_glTexCoord1dv +GLAD_API_CALL PFNGLTEXCOORD1FPROC glad_glTexCoord1f; +#define glTexCoord1f glad_glTexCoord1f +GLAD_API_CALL PFNGLTEXCOORD1FVPROC glad_glTexCoord1fv; +#define glTexCoord1fv glad_glTexCoord1fv +GLAD_API_CALL PFNGLTEXCOORD1IPROC glad_glTexCoord1i; +#define glTexCoord1i glad_glTexCoord1i +GLAD_API_CALL PFNGLTEXCOORD1IVPROC glad_glTexCoord1iv; +#define glTexCoord1iv glad_glTexCoord1iv +GLAD_API_CALL PFNGLTEXCOORD1SPROC glad_glTexCoord1s; +#define glTexCoord1s glad_glTexCoord1s +GLAD_API_CALL PFNGLTEXCOORD1SVPROC glad_glTexCoord1sv; +#define glTexCoord1sv glad_glTexCoord1sv +GLAD_API_CALL PFNGLTEXCOORD2DPROC glad_glTexCoord2d; +#define glTexCoord2d glad_glTexCoord2d +GLAD_API_CALL PFNGLTEXCOORD2DVPROC glad_glTexCoord2dv; +#define glTexCoord2dv glad_glTexCoord2dv +GLAD_API_CALL PFNGLTEXCOORD2FPROC glad_glTexCoord2f; +#define glTexCoord2f glad_glTexCoord2f +GLAD_API_CALL PFNGLTEXCOORD2FVPROC glad_glTexCoord2fv; +#define glTexCoord2fv glad_glTexCoord2fv +GLAD_API_CALL PFNGLTEXCOORD2IPROC glad_glTexCoord2i; +#define glTexCoord2i glad_glTexCoord2i +GLAD_API_CALL PFNGLTEXCOORD2IVPROC glad_glTexCoord2iv; +#define glTexCoord2iv glad_glTexCoord2iv +GLAD_API_CALL PFNGLTEXCOORD2SPROC glad_glTexCoord2s; +#define glTexCoord2s glad_glTexCoord2s +GLAD_API_CALL PFNGLTEXCOORD2SVPROC glad_glTexCoord2sv; +#define glTexCoord2sv glad_glTexCoord2sv +GLAD_API_CALL PFNGLTEXCOORD3DPROC glad_glTexCoord3d; +#define glTexCoord3d glad_glTexCoord3d +GLAD_API_CALL PFNGLTEXCOORD3DVPROC glad_glTexCoord3dv; +#define glTexCoord3dv glad_glTexCoord3dv +GLAD_API_CALL PFNGLTEXCOORD3FPROC glad_glTexCoord3f; +#define glTexCoord3f glad_glTexCoord3f +GLAD_API_CALL PFNGLTEXCOORD3FVPROC glad_glTexCoord3fv; +#define glTexCoord3fv glad_glTexCoord3fv +GLAD_API_CALL PFNGLTEXCOORD3IPROC glad_glTexCoord3i; +#define glTexCoord3i glad_glTexCoord3i +GLAD_API_CALL PFNGLTEXCOORD3IVPROC glad_glTexCoord3iv; +#define glTexCoord3iv glad_glTexCoord3iv +GLAD_API_CALL PFNGLTEXCOORD3SPROC glad_glTexCoord3s; +#define glTexCoord3s glad_glTexCoord3s +GLAD_API_CALL PFNGLTEXCOORD3SVPROC glad_glTexCoord3sv; +#define glTexCoord3sv glad_glTexCoord3sv +GLAD_API_CALL PFNGLTEXCOORD4DPROC glad_glTexCoord4d; +#define glTexCoord4d glad_glTexCoord4d +GLAD_API_CALL PFNGLTEXCOORD4DVPROC glad_glTexCoord4dv; +#define glTexCoord4dv glad_glTexCoord4dv +GLAD_API_CALL PFNGLTEXCOORD4FPROC glad_glTexCoord4f; +#define glTexCoord4f glad_glTexCoord4f +GLAD_API_CALL PFNGLTEXCOORD4FVPROC glad_glTexCoord4fv; +#define glTexCoord4fv glad_glTexCoord4fv +GLAD_API_CALL PFNGLTEXCOORD4IPROC glad_glTexCoord4i; +#define glTexCoord4i glad_glTexCoord4i +GLAD_API_CALL PFNGLTEXCOORD4IVPROC glad_glTexCoord4iv; +#define glTexCoord4iv glad_glTexCoord4iv +GLAD_API_CALL PFNGLTEXCOORD4SPROC glad_glTexCoord4s; +#define glTexCoord4s glad_glTexCoord4s +GLAD_API_CALL PFNGLTEXCOORD4SVPROC glad_glTexCoord4sv; +#define glTexCoord4sv glad_glTexCoord4sv +GLAD_API_CALL PFNGLTEXCOORDP1UIPROC glad_glTexCoordP1ui; +#define glTexCoordP1ui glad_glTexCoordP1ui +GLAD_API_CALL PFNGLTEXCOORDP1UIVPROC glad_glTexCoordP1uiv; +#define glTexCoordP1uiv glad_glTexCoordP1uiv +GLAD_API_CALL PFNGLTEXCOORDP2UIPROC glad_glTexCoordP2ui; +#define glTexCoordP2ui glad_glTexCoordP2ui +GLAD_API_CALL PFNGLTEXCOORDP2UIVPROC glad_glTexCoordP2uiv; +#define glTexCoordP2uiv glad_glTexCoordP2uiv +GLAD_API_CALL PFNGLTEXCOORDP3UIPROC glad_glTexCoordP3ui; +#define glTexCoordP3ui glad_glTexCoordP3ui +GLAD_API_CALL PFNGLTEXCOORDP3UIVPROC glad_glTexCoordP3uiv; +#define glTexCoordP3uiv glad_glTexCoordP3uiv +GLAD_API_CALL PFNGLTEXCOORDP4UIPROC glad_glTexCoordP4ui; +#define glTexCoordP4ui glad_glTexCoordP4ui +GLAD_API_CALL PFNGLTEXCOORDP4UIVPROC glad_glTexCoordP4uiv; +#define glTexCoordP4uiv glad_glTexCoordP4uiv +GLAD_API_CALL PFNGLTEXCOORDPOINTERPROC glad_glTexCoordPointer; +#define glTexCoordPointer glad_glTexCoordPointer +GLAD_API_CALL PFNGLTEXENVFPROC glad_glTexEnvf; +#define glTexEnvf glad_glTexEnvf +GLAD_API_CALL PFNGLTEXENVFVPROC glad_glTexEnvfv; +#define glTexEnvfv glad_glTexEnvfv +GLAD_API_CALL PFNGLTEXENVIPROC glad_glTexEnvi; +#define glTexEnvi glad_glTexEnvi +GLAD_API_CALL PFNGLTEXENVIVPROC glad_glTexEnviv; +#define glTexEnviv glad_glTexEnviv +GLAD_API_CALL PFNGLTEXGENDPROC glad_glTexGend; +#define glTexGend glad_glTexGend +GLAD_API_CALL PFNGLTEXGENDVPROC glad_glTexGendv; +#define glTexGendv glad_glTexGendv +GLAD_API_CALL PFNGLTEXGENFPROC glad_glTexGenf; +#define glTexGenf glad_glTexGenf +GLAD_API_CALL PFNGLTEXGENFVPROC glad_glTexGenfv; +#define glTexGenfv glad_glTexGenfv +GLAD_API_CALL PFNGLTEXGENIPROC glad_glTexGeni; +#define glTexGeni glad_glTexGeni +GLAD_API_CALL PFNGLTEXGENIVPROC glad_glTexGeniv; +#define glTexGeniv glad_glTexGeniv +GLAD_API_CALL PFNGLTEXIMAGE1DPROC glad_glTexImage1D; +#define glTexImage1D glad_glTexImage1D +GLAD_API_CALL PFNGLTEXIMAGE2DPROC glad_glTexImage2D; +#define glTexImage2D glad_glTexImage2D +GLAD_API_CALL PFNGLTEXIMAGE2DMULTISAMPLEPROC glad_glTexImage2DMultisample; +#define glTexImage2DMultisample glad_glTexImage2DMultisample +GLAD_API_CALL PFNGLTEXIMAGE3DPROC glad_glTexImage3D; +#define glTexImage3D glad_glTexImage3D +GLAD_API_CALL PFNGLTEXIMAGE3DMULTISAMPLEPROC glad_glTexImage3DMultisample; +#define glTexImage3DMultisample glad_glTexImage3DMultisample +GLAD_API_CALL PFNGLTEXPARAMETERIIVPROC glad_glTexParameterIiv; +#define glTexParameterIiv glad_glTexParameterIiv +GLAD_API_CALL PFNGLTEXPARAMETERIUIVPROC glad_glTexParameterIuiv; +#define glTexParameterIuiv glad_glTexParameterIuiv +GLAD_API_CALL PFNGLTEXPARAMETERFPROC glad_glTexParameterf; +#define glTexParameterf glad_glTexParameterf +GLAD_API_CALL PFNGLTEXPARAMETERFVPROC glad_glTexParameterfv; +#define glTexParameterfv glad_glTexParameterfv +GLAD_API_CALL PFNGLTEXPARAMETERIPROC glad_glTexParameteri; +#define glTexParameteri glad_glTexParameteri +GLAD_API_CALL PFNGLTEXPARAMETERIVPROC glad_glTexParameteriv; +#define glTexParameteriv glad_glTexParameteriv +GLAD_API_CALL PFNGLTEXSUBIMAGE1DPROC glad_glTexSubImage1D; +#define glTexSubImage1D glad_glTexSubImage1D +GLAD_API_CALL PFNGLTEXSUBIMAGE2DPROC glad_glTexSubImage2D; +#define glTexSubImage2D glad_glTexSubImage2D +GLAD_API_CALL PFNGLTEXSUBIMAGE3DPROC glad_glTexSubImage3D; +#define glTexSubImage3D glad_glTexSubImage3D +GLAD_API_CALL PFNGLTRANSFORMFEEDBACKVARYINGSPROC glad_glTransformFeedbackVaryings; +#define glTransformFeedbackVaryings glad_glTransformFeedbackVaryings +GLAD_API_CALL PFNGLTRANSLATEDPROC glad_glTranslated; +#define glTranslated glad_glTranslated +GLAD_API_CALL PFNGLTRANSLATEFPROC glad_glTranslatef; +#define glTranslatef glad_glTranslatef +GLAD_API_CALL PFNGLUNIFORM1FPROC glad_glUniform1f; +#define glUniform1f glad_glUniform1f +GLAD_API_CALL PFNGLUNIFORM1FVPROC glad_glUniform1fv; +#define glUniform1fv glad_glUniform1fv +GLAD_API_CALL PFNGLUNIFORM1IPROC glad_glUniform1i; +#define glUniform1i glad_glUniform1i +GLAD_API_CALL PFNGLUNIFORM1IVPROC glad_glUniform1iv; +#define glUniform1iv glad_glUniform1iv +GLAD_API_CALL PFNGLUNIFORM1UIPROC glad_glUniform1ui; +#define glUniform1ui glad_glUniform1ui +GLAD_API_CALL PFNGLUNIFORM1UIVPROC glad_glUniform1uiv; +#define glUniform1uiv glad_glUniform1uiv +GLAD_API_CALL PFNGLUNIFORM2FPROC glad_glUniform2f; +#define glUniform2f glad_glUniform2f +GLAD_API_CALL PFNGLUNIFORM2FVPROC glad_glUniform2fv; +#define glUniform2fv glad_glUniform2fv +GLAD_API_CALL PFNGLUNIFORM2IPROC glad_glUniform2i; +#define glUniform2i glad_glUniform2i +GLAD_API_CALL PFNGLUNIFORM2IVPROC glad_glUniform2iv; +#define glUniform2iv glad_glUniform2iv +GLAD_API_CALL PFNGLUNIFORM2UIPROC glad_glUniform2ui; +#define glUniform2ui glad_glUniform2ui +GLAD_API_CALL PFNGLUNIFORM2UIVPROC glad_glUniform2uiv; +#define glUniform2uiv glad_glUniform2uiv +GLAD_API_CALL PFNGLUNIFORM3FPROC glad_glUniform3f; +#define glUniform3f glad_glUniform3f +GLAD_API_CALL PFNGLUNIFORM3FVPROC glad_glUniform3fv; +#define glUniform3fv glad_glUniform3fv +GLAD_API_CALL PFNGLUNIFORM3IPROC glad_glUniform3i; +#define glUniform3i glad_glUniform3i +GLAD_API_CALL PFNGLUNIFORM3IVPROC glad_glUniform3iv; +#define glUniform3iv glad_glUniform3iv +GLAD_API_CALL PFNGLUNIFORM3UIPROC glad_glUniform3ui; +#define glUniform3ui glad_glUniform3ui +GLAD_API_CALL PFNGLUNIFORM3UIVPROC glad_glUniform3uiv; +#define glUniform3uiv glad_glUniform3uiv +GLAD_API_CALL PFNGLUNIFORM4FPROC glad_glUniform4f; +#define glUniform4f glad_glUniform4f +GLAD_API_CALL PFNGLUNIFORM4FVPROC glad_glUniform4fv; +#define glUniform4fv glad_glUniform4fv +GLAD_API_CALL PFNGLUNIFORM4IPROC glad_glUniform4i; +#define glUniform4i glad_glUniform4i +GLAD_API_CALL PFNGLUNIFORM4IVPROC glad_glUniform4iv; +#define glUniform4iv glad_glUniform4iv +GLAD_API_CALL PFNGLUNIFORM4UIPROC glad_glUniform4ui; +#define glUniform4ui glad_glUniform4ui +GLAD_API_CALL PFNGLUNIFORM4UIVPROC glad_glUniform4uiv; +#define glUniform4uiv glad_glUniform4uiv +GLAD_API_CALL PFNGLUNIFORMBLOCKBINDINGPROC glad_glUniformBlockBinding; +#define glUniformBlockBinding glad_glUniformBlockBinding +GLAD_API_CALL PFNGLUNIFORMMATRIX2FVPROC glad_glUniformMatrix2fv; +#define glUniformMatrix2fv glad_glUniformMatrix2fv +GLAD_API_CALL PFNGLUNIFORMMATRIX2X3FVPROC glad_glUniformMatrix2x3fv; +#define glUniformMatrix2x3fv glad_glUniformMatrix2x3fv +GLAD_API_CALL PFNGLUNIFORMMATRIX2X4FVPROC glad_glUniformMatrix2x4fv; +#define glUniformMatrix2x4fv glad_glUniformMatrix2x4fv +GLAD_API_CALL PFNGLUNIFORMMATRIX3FVPROC glad_glUniformMatrix3fv; +#define glUniformMatrix3fv glad_glUniformMatrix3fv +GLAD_API_CALL PFNGLUNIFORMMATRIX3X2FVPROC glad_glUniformMatrix3x2fv; +#define glUniformMatrix3x2fv glad_glUniformMatrix3x2fv +GLAD_API_CALL PFNGLUNIFORMMATRIX3X4FVPROC glad_glUniformMatrix3x4fv; +#define glUniformMatrix3x4fv glad_glUniformMatrix3x4fv +GLAD_API_CALL PFNGLUNIFORMMATRIX4FVPROC glad_glUniformMatrix4fv; +#define glUniformMatrix4fv glad_glUniformMatrix4fv +GLAD_API_CALL PFNGLUNIFORMMATRIX4X2FVPROC glad_glUniformMatrix4x2fv; +#define glUniformMatrix4x2fv glad_glUniformMatrix4x2fv +GLAD_API_CALL PFNGLUNIFORMMATRIX4X3FVPROC glad_glUniformMatrix4x3fv; +#define glUniformMatrix4x3fv glad_glUniformMatrix4x3fv +GLAD_API_CALL PFNGLUNMAPBUFFERPROC glad_glUnmapBuffer; +#define glUnmapBuffer glad_glUnmapBuffer +GLAD_API_CALL PFNGLUSEPROGRAMPROC glad_glUseProgram; +#define glUseProgram glad_glUseProgram +GLAD_API_CALL PFNGLVALIDATEPROGRAMPROC glad_glValidateProgram; +#define glValidateProgram glad_glValidateProgram +GLAD_API_CALL PFNGLVERTEX2DPROC glad_glVertex2d; +#define glVertex2d glad_glVertex2d +GLAD_API_CALL PFNGLVERTEX2DVPROC glad_glVertex2dv; +#define glVertex2dv glad_glVertex2dv +GLAD_API_CALL PFNGLVERTEX2FPROC glad_glVertex2f; +#define glVertex2f glad_glVertex2f +GLAD_API_CALL PFNGLVERTEX2FVPROC glad_glVertex2fv; +#define glVertex2fv glad_glVertex2fv +GLAD_API_CALL PFNGLVERTEX2IPROC glad_glVertex2i; +#define glVertex2i glad_glVertex2i +GLAD_API_CALL PFNGLVERTEX2IVPROC glad_glVertex2iv; +#define glVertex2iv glad_glVertex2iv +GLAD_API_CALL PFNGLVERTEX2SPROC glad_glVertex2s; +#define glVertex2s glad_glVertex2s +GLAD_API_CALL PFNGLVERTEX2SVPROC glad_glVertex2sv; +#define glVertex2sv glad_glVertex2sv +GLAD_API_CALL PFNGLVERTEX3DPROC glad_glVertex3d; +#define glVertex3d glad_glVertex3d +GLAD_API_CALL PFNGLVERTEX3DVPROC glad_glVertex3dv; +#define glVertex3dv glad_glVertex3dv +GLAD_API_CALL PFNGLVERTEX3FPROC glad_glVertex3f; +#define glVertex3f glad_glVertex3f +GLAD_API_CALL PFNGLVERTEX3FVPROC glad_glVertex3fv; +#define glVertex3fv glad_glVertex3fv +GLAD_API_CALL PFNGLVERTEX3IPROC glad_glVertex3i; +#define glVertex3i glad_glVertex3i +GLAD_API_CALL PFNGLVERTEX3IVPROC glad_glVertex3iv; +#define glVertex3iv glad_glVertex3iv +GLAD_API_CALL PFNGLVERTEX3SPROC glad_glVertex3s; +#define glVertex3s glad_glVertex3s +GLAD_API_CALL PFNGLVERTEX3SVPROC glad_glVertex3sv; +#define glVertex3sv glad_glVertex3sv +GLAD_API_CALL PFNGLVERTEX4DPROC glad_glVertex4d; +#define glVertex4d glad_glVertex4d +GLAD_API_CALL PFNGLVERTEX4DVPROC glad_glVertex4dv; +#define glVertex4dv glad_glVertex4dv +GLAD_API_CALL PFNGLVERTEX4FPROC glad_glVertex4f; +#define glVertex4f glad_glVertex4f +GLAD_API_CALL PFNGLVERTEX4FVPROC glad_glVertex4fv; +#define glVertex4fv glad_glVertex4fv +GLAD_API_CALL PFNGLVERTEX4IPROC glad_glVertex4i; +#define glVertex4i glad_glVertex4i +GLAD_API_CALL PFNGLVERTEX4IVPROC glad_glVertex4iv; +#define glVertex4iv glad_glVertex4iv +GLAD_API_CALL PFNGLVERTEX4SPROC glad_glVertex4s; +#define glVertex4s glad_glVertex4s +GLAD_API_CALL PFNGLVERTEX4SVPROC glad_glVertex4sv; +#define glVertex4sv glad_glVertex4sv +GLAD_API_CALL PFNGLVERTEXATTRIB1DPROC glad_glVertexAttrib1d; +#define glVertexAttrib1d glad_glVertexAttrib1d +GLAD_API_CALL PFNGLVERTEXATTRIB1DVPROC glad_glVertexAttrib1dv; +#define glVertexAttrib1dv glad_glVertexAttrib1dv +GLAD_API_CALL PFNGLVERTEXATTRIB1FPROC glad_glVertexAttrib1f; +#define glVertexAttrib1f glad_glVertexAttrib1f +GLAD_API_CALL PFNGLVERTEXATTRIB1FVPROC glad_glVertexAttrib1fv; +#define glVertexAttrib1fv glad_glVertexAttrib1fv +GLAD_API_CALL PFNGLVERTEXATTRIB1SPROC glad_glVertexAttrib1s; +#define glVertexAttrib1s glad_glVertexAttrib1s +GLAD_API_CALL PFNGLVERTEXATTRIB1SVPROC glad_glVertexAttrib1sv; +#define glVertexAttrib1sv glad_glVertexAttrib1sv +GLAD_API_CALL PFNGLVERTEXATTRIB2DPROC glad_glVertexAttrib2d; +#define glVertexAttrib2d glad_glVertexAttrib2d +GLAD_API_CALL PFNGLVERTEXATTRIB2DVPROC glad_glVertexAttrib2dv; +#define glVertexAttrib2dv glad_glVertexAttrib2dv +GLAD_API_CALL PFNGLVERTEXATTRIB2FPROC glad_glVertexAttrib2f; +#define glVertexAttrib2f glad_glVertexAttrib2f +GLAD_API_CALL PFNGLVERTEXATTRIB2FVPROC glad_glVertexAttrib2fv; +#define glVertexAttrib2fv glad_glVertexAttrib2fv +GLAD_API_CALL PFNGLVERTEXATTRIB2SPROC glad_glVertexAttrib2s; +#define glVertexAttrib2s glad_glVertexAttrib2s +GLAD_API_CALL PFNGLVERTEXATTRIB2SVPROC glad_glVertexAttrib2sv; +#define glVertexAttrib2sv glad_glVertexAttrib2sv +GLAD_API_CALL PFNGLVERTEXATTRIB3DPROC glad_glVertexAttrib3d; +#define glVertexAttrib3d glad_glVertexAttrib3d +GLAD_API_CALL PFNGLVERTEXATTRIB3DVPROC glad_glVertexAttrib3dv; +#define glVertexAttrib3dv glad_glVertexAttrib3dv +GLAD_API_CALL PFNGLVERTEXATTRIB3FPROC glad_glVertexAttrib3f; +#define glVertexAttrib3f glad_glVertexAttrib3f +GLAD_API_CALL PFNGLVERTEXATTRIB3FVPROC glad_glVertexAttrib3fv; +#define glVertexAttrib3fv glad_glVertexAttrib3fv +GLAD_API_CALL PFNGLVERTEXATTRIB3SPROC glad_glVertexAttrib3s; +#define glVertexAttrib3s glad_glVertexAttrib3s +GLAD_API_CALL PFNGLVERTEXATTRIB3SVPROC glad_glVertexAttrib3sv; +#define glVertexAttrib3sv glad_glVertexAttrib3sv +GLAD_API_CALL PFNGLVERTEXATTRIB4NBVPROC glad_glVertexAttrib4Nbv; +#define glVertexAttrib4Nbv glad_glVertexAttrib4Nbv +GLAD_API_CALL PFNGLVERTEXATTRIB4NIVPROC glad_glVertexAttrib4Niv; +#define glVertexAttrib4Niv glad_glVertexAttrib4Niv +GLAD_API_CALL PFNGLVERTEXATTRIB4NSVPROC glad_glVertexAttrib4Nsv; +#define glVertexAttrib4Nsv glad_glVertexAttrib4Nsv +GLAD_API_CALL PFNGLVERTEXATTRIB4NUBPROC glad_glVertexAttrib4Nub; +#define glVertexAttrib4Nub glad_glVertexAttrib4Nub +GLAD_API_CALL PFNGLVERTEXATTRIB4NUBVPROC glad_glVertexAttrib4Nubv; +#define glVertexAttrib4Nubv glad_glVertexAttrib4Nubv +GLAD_API_CALL PFNGLVERTEXATTRIB4NUIVPROC glad_glVertexAttrib4Nuiv; +#define glVertexAttrib4Nuiv glad_glVertexAttrib4Nuiv +GLAD_API_CALL PFNGLVERTEXATTRIB4NUSVPROC glad_glVertexAttrib4Nusv; +#define glVertexAttrib4Nusv glad_glVertexAttrib4Nusv +GLAD_API_CALL PFNGLVERTEXATTRIB4BVPROC glad_glVertexAttrib4bv; +#define glVertexAttrib4bv glad_glVertexAttrib4bv +GLAD_API_CALL PFNGLVERTEXATTRIB4DPROC glad_glVertexAttrib4d; +#define glVertexAttrib4d glad_glVertexAttrib4d +GLAD_API_CALL PFNGLVERTEXATTRIB4DVPROC glad_glVertexAttrib4dv; +#define glVertexAttrib4dv glad_glVertexAttrib4dv +GLAD_API_CALL PFNGLVERTEXATTRIB4FPROC glad_glVertexAttrib4f; +#define glVertexAttrib4f glad_glVertexAttrib4f +GLAD_API_CALL PFNGLVERTEXATTRIB4FVPROC glad_glVertexAttrib4fv; +#define glVertexAttrib4fv glad_glVertexAttrib4fv +GLAD_API_CALL PFNGLVERTEXATTRIB4IVPROC glad_glVertexAttrib4iv; +#define glVertexAttrib4iv glad_glVertexAttrib4iv +GLAD_API_CALL PFNGLVERTEXATTRIB4SPROC glad_glVertexAttrib4s; +#define glVertexAttrib4s glad_glVertexAttrib4s +GLAD_API_CALL PFNGLVERTEXATTRIB4SVPROC glad_glVertexAttrib4sv; +#define glVertexAttrib4sv glad_glVertexAttrib4sv +GLAD_API_CALL PFNGLVERTEXATTRIB4UBVPROC glad_glVertexAttrib4ubv; +#define glVertexAttrib4ubv glad_glVertexAttrib4ubv +GLAD_API_CALL PFNGLVERTEXATTRIB4UIVPROC glad_glVertexAttrib4uiv; +#define glVertexAttrib4uiv glad_glVertexAttrib4uiv +GLAD_API_CALL PFNGLVERTEXATTRIB4USVPROC glad_glVertexAttrib4usv; +#define glVertexAttrib4usv glad_glVertexAttrib4usv +GLAD_API_CALL PFNGLVERTEXATTRIBDIVISORPROC glad_glVertexAttribDivisor; +#define glVertexAttribDivisor glad_glVertexAttribDivisor +GLAD_API_CALL PFNGLVERTEXATTRIBI1IPROC glad_glVertexAttribI1i; +#define glVertexAttribI1i glad_glVertexAttribI1i +GLAD_API_CALL PFNGLVERTEXATTRIBI1IVPROC glad_glVertexAttribI1iv; +#define glVertexAttribI1iv glad_glVertexAttribI1iv +GLAD_API_CALL PFNGLVERTEXATTRIBI1UIPROC glad_glVertexAttribI1ui; +#define glVertexAttribI1ui glad_glVertexAttribI1ui +GLAD_API_CALL PFNGLVERTEXATTRIBI1UIVPROC glad_glVertexAttribI1uiv; +#define glVertexAttribI1uiv glad_glVertexAttribI1uiv +GLAD_API_CALL PFNGLVERTEXATTRIBI2IPROC glad_glVertexAttribI2i; +#define glVertexAttribI2i glad_glVertexAttribI2i +GLAD_API_CALL PFNGLVERTEXATTRIBI2IVPROC glad_glVertexAttribI2iv; +#define glVertexAttribI2iv glad_glVertexAttribI2iv +GLAD_API_CALL PFNGLVERTEXATTRIBI2UIPROC glad_glVertexAttribI2ui; +#define glVertexAttribI2ui glad_glVertexAttribI2ui +GLAD_API_CALL PFNGLVERTEXATTRIBI2UIVPROC glad_glVertexAttribI2uiv; +#define glVertexAttribI2uiv glad_glVertexAttribI2uiv +GLAD_API_CALL PFNGLVERTEXATTRIBI3IPROC glad_glVertexAttribI3i; +#define glVertexAttribI3i glad_glVertexAttribI3i +GLAD_API_CALL PFNGLVERTEXATTRIBI3IVPROC glad_glVertexAttribI3iv; +#define glVertexAttribI3iv glad_glVertexAttribI3iv +GLAD_API_CALL PFNGLVERTEXATTRIBI3UIPROC glad_glVertexAttribI3ui; +#define glVertexAttribI3ui glad_glVertexAttribI3ui +GLAD_API_CALL PFNGLVERTEXATTRIBI3UIVPROC glad_glVertexAttribI3uiv; +#define glVertexAttribI3uiv glad_glVertexAttribI3uiv +GLAD_API_CALL PFNGLVERTEXATTRIBI4BVPROC glad_glVertexAttribI4bv; +#define glVertexAttribI4bv glad_glVertexAttribI4bv +GLAD_API_CALL PFNGLVERTEXATTRIBI4IPROC glad_glVertexAttribI4i; +#define glVertexAttribI4i glad_glVertexAttribI4i +GLAD_API_CALL PFNGLVERTEXATTRIBI4IVPROC glad_glVertexAttribI4iv; +#define glVertexAttribI4iv glad_glVertexAttribI4iv +GLAD_API_CALL PFNGLVERTEXATTRIBI4SVPROC glad_glVertexAttribI4sv; +#define glVertexAttribI4sv glad_glVertexAttribI4sv +GLAD_API_CALL PFNGLVERTEXATTRIBI4UBVPROC glad_glVertexAttribI4ubv; +#define glVertexAttribI4ubv glad_glVertexAttribI4ubv +GLAD_API_CALL PFNGLVERTEXATTRIBI4UIPROC glad_glVertexAttribI4ui; +#define glVertexAttribI4ui glad_glVertexAttribI4ui +GLAD_API_CALL PFNGLVERTEXATTRIBI4UIVPROC glad_glVertexAttribI4uiv; +#define glVertexAttribI4uiv glad_glVertexAttribI4uiv +GLAD_API_CALL PFNGLVERTEXATTRIBI4USVPROC glad_glVertexAttribI4usv; +#define glVertexAttribI4usv glad_glVertexAttribI4usv +GLAD_API_CALL PFNGLVERTEXATTRIBIPOINTERPROC glad_glVertexAttribIPointer; +#define glVertexAttribIPointer glad_glVertexAttribIPointer +GLAD_API_CALL PFNGLVERTEXATTRIBP1UIPROC glad_glVertexAttribP1ui; +#define glVertexAttribP1ui glad_glVertexAttribP1ui +GLAD_API_CALL PFNGLVERTEXATTRIBP1UIVPROC glad_glVertexAttribP1uiv; +#define glVertexAttribP1uiv glad_glVertexAttribP1uiv +GLAD_API_CALL PFNGLVERTEXATTRIBP2UIPROC glad_glVertexAttribP2ui; +#define glVertexAttribP2ui glad_glVertexAttribP2ui +GLAD_API_CALL PFNGLVERTEXATTRIBP2UIVPROC glad_glVertexAttribP2uiv; +#define glVertexAttribP2uiv glad_glVertexAttribP2uiv +GLAD_API_CALL PFNGLVERTEXATTRIBP3UIPROC glad_glVertexAttribP3ui; +#define glVertexAttribP3ui glad_glVertexAttribP3ui +GLAD_API_CALL PFNGLVERTEXATTRIBP3UIVPROC glad_glVertexAttribP3uiv; +#define glVertexAttribP3uiv glad_glVertexAttribP3uiv +GLAD_API_CALL PFNGLVERTEXATTRIBP4UIPROC glad_glVertexAttribP4ui; +#define glVertexAttribP4ui glad_glVertexAttribP4ui +GLAD_API_CALL PFNGLVERTEXATTRIBP4UIVPROC glad_glVertexAttribP4uiv; +#define glVertexAttribP4uiv glad_glVertexAttribP4uiv +GLAD_API_CALL PFNGLVERTEXATTRIBPOINTERPROC glad_glVertexAttribPointer; +#define glVertexAttribPointer glad_glVertexAttribPointer +GLAD_API_CALL PFNGLVERTEXP2UIPROC glad_glVertexP2ui; +#define glVertexP2ui glad_glVertexP2ui +GLAD_API_CALL PFNGLVERTEXP2UIVPROC glad_glVertexP2uiv; +#define glVertexP2uiv glad_glVertexP2uiv +GLAD_API_CALL PFNGLVERTEXP3UIPROC glad_glVertexP3ui; +#define glVertexP3ui glad_glVertexP3ui +GLAD_API_CALL PFNGLVERTEXP3UIVPROC glad_glVertexP3uiv; +#define glVertexP3uiv glad_glVertexP3uiv +GLAD_API_CALL PFNGLVERTEXP4UIPROC glad_glVertexP4ui; +#define glVertexP4ui glad_glVertexP4ui +GLAD_API_CALL PFNGLVERTEXP4UIVPROC glad_glVertexP4uiv; +#define glVertexP4uiv glad_glVertexP4uiv +GLAD_API_CALL PFNGLVERTEXPOINTERPROC glad_glVertexPointer; +#define glVertexPointer glad_glVertexPointer +GLAD_API_CALL PFNGLVIEWPORTPROC glad_glViewport; +#define glViewport glad_glViewport +GLAD_API_CALL PFNGLWAITSYNCPROC glad_glWaitSync; +#define glWaitSync glad_glWaitSync +GLAD_API_CALL PFNGLWINDOWPOS2DPROC glad_glWindowPos2d; +#define glWindowPos2d glad_glWindowPos2d +GLAD_API_CALL PFNGLWINDOWPOS2DVPROC glad_glWindowPos2dv; +#define glWindowPos2dv glad_glWindowPos2dv +GLAD_API_CALL PFNGLWINDOWPOS2FPROC glad_glWindowPos2f; +#define glWindowPos2f glad_glWindowPos2f +GLAD_API_CALL PFNGLWINDOWPOS2FVPROC glad_glWindowPos2fv; +#define glWindowPos2fv glad_glWindowPos2fv +GLAD_API_CALL PFNGLWINDOWPOS2IPROC glad_glWindowPos2i; +#define glWindowPos2i glad_glWindowPos2i +GLAD_API_CALL PFNGLWINDOWPOS2IVPROC glad_glWindowPos2iv; +#define glWindowPos2iv glad_glWindowPos2iv +GLAD_API_CALL PFNGLWINDOWPOS2SPROC glad_glWindowPos2s; +#define glWindowPos2s glad_glWindowPos2s +GLAD_API_CALL PFNGLWINDOWPOS2SVPROC glad_glWindowPos2sv; +#define glWindowPos2sv glad_glWindowPos2sv +GLAD_API_CALL PFNGLWINDOWPOS3DPROC glad_glWindowPos3d; +#define glWindowPos3d glad_glWindowPos3d +GLAD_API_CALL PFNGLWINDOWPOS3DVPROC glad_glWindowPos3dv; +#define glWindowPos3dv glad_glWindowPos3dv +GLAD_API_CALL PFNGLWINDOWPOS3FPROC glad_glWindowPos3f; +#define glWindowPos3f glad_glWindowPos3f +GLAD_API_CALL PFNGLWINDOWPOS3FVPROC glad_glWindowPos3fv; +#define glWindowPos3fv glad_glWindowPos3fv +GLAD_API_CALL PFNGLWINDOWPOS3IPROC glad_glWindowPos3i; +#define glWindowPos3i glad_glWindowPos3i +GLAD_API_CALL PFNGLWINDOWPOS3IVPROC glad_glWindowPos3iv; +#define glWindowPos3iv glad_glWindowPos3iv +GLAD_API_CALL PFNGLWINDOWPOS3SPROC glad_glWindowPos3s; +#define glWindowPos3s glad_glWindowPos3s +GLAD_API_CALL PFNGLWINDOWPOS3SVPROC glad_glWindowPos3sv; +#define glWindowPos3sv glad_glWindowPos3sv + + +GLAD_API_CALL int gladLoadGLUserPtr( GLADuserptrloadfunc load, void *userptr); +GLAD_API_CALL int gladLoadGL( GLADloadfunc load); + + + + + + +#ifdef __cplusplus +} +#endif +#endif diff --git a/src/external/glfw/deps/glad/glad.h b/src/external/glfw/deps/glad/glad.h deleted file mode 100644 index 7d81e98e..00000000 --- a/src/external/glfw/deps/glad/glad.h +++ /dev/null @@ -1,3680 +0,0 @@ -/* - - OpenGL loader generated by glad 0.1.12a0 on Fri Sep 23 13:36:15 2016. - - Language/Generator: C/C++ - Specification: gl - APIs: gl=3.2 - Profile: compatibility - Extensions: - GL_ARB_multisample, - GL_ARB_robustness, - GL_KHR_debug - Loader: False - Local files: False - Omit khrplatform: False - - Commandline: - --profile="compatibility" --api="gl=3.2" --generator="c" --spec="gl" --no-loader --extensions="GL_ARB_multisample,GL_ARB_robustness,GL_KHR_debug" - Online: - http://glad.dav1d.de/#profile=compatibility&language=c&specification=gl&api=gl%3D3.2&extensions=GL_ARB_multisample&extensions=GL_ARB_robustness&extensions=GL_KHR_debug -*/ - - -#ifndef __glad_h_ -#define __glad_h_ - -#ifdef __gl_h_ -#error OpenGL header already included, remove this include, glad already provides it -#endif -#define __gl_h_ - -#if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__) -#ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN 1 -#endif -#include -#endif - -#ifndef APIENTRY -#define APIENTRY -#endif -#ifndef APIENTRYP -#define APIENTRYP APIENTRY * -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -struct gladGLversionStruct { - int major; - int minor; -}; - -typedef void* (* GLADloadproc)(const char *name); - -#ifndef GLAPI -# if defined(GLAD_GLAPI_EXPORT) -# if defined(WIN32) || defined(__CYGWIN__) -# if defined(GLAD_GLAPI_EXPORT_BUILD) -# if defined(__GNUC__) -# define GLAPI __attribute__ ((dllexport)) extern -# else -# define GLAPI __declspec(dllexport) extern -# endif -# else -# if defined(__GNUC__) -# define GLAPI __attribute__ ((dllimport)) extern -# else -# define GLAPI __declspec(dllimport) extern -# endif -# endif -# elif defined(__GNUC__) && defined(GLAD_GLAPI_EXPORT_BUILD) -# define GLAPI __attribute__ ((visibility ("default"))) extern -# else -# define GLAPI extern -# endif -# else -# define GLAPI extern -# endif -#endif - -GLAPI struct gladGLversionStruct GLVersion; -GLAPI int gladLoadGLLoader(GLADloadproc); - -#include -#include -#ifndef GLEXT_64_TYPES_DEFINED -/* This code block is duplicated in glxext.h, so must be protected */ -#define GLEXT_64_TYPES_DEFINED -/* Define int32_t, int64_t, and uint64_t types for UST/MSC */ -/* (as used in the GL_EXT_timer_query extension). */ -#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L -#include -#elif defined(__sun__) || defined(__digital__) -#include -#if defined(__STDC__) -#if defined(__arch64__) || defined(_LP64) -typedef long int int64_t; -typedef unsigned long int uint64_t; -#else -typedef long long int int64_t; -typedef unsigned long long int uint64_t; -#endif /* __arch64__ */ -#endif /* __STDC__ */ -#elif defined( __VMS ) || defined(__sgi) -#include -#elif defined(__SCO__) || defined(__USLC__) -#include -#elif defined(__UNIXOS2__) || defined(__SOL64__) -typedef long int int32_t; -typedef long long int int64_t; -typedef unsigned long long int uint64_t; -#elif defined(_WIN32) && defined(__GNUC__) -#include -#elif defined(_WIN32) -typedef __int32 int32_t; -typedef __int64 int64_t; -typedef unsigned __int64 uint64_t; -#else -/* Fallback if nothing above works */ -#include -#endif -#endif -typedef unsigned int GLenum; -typedef unsigned char GLboolean; -typedef unsigned int GLbitfield; -typedef void GLvoid; -typedef signed char GLbyte; -typedef short GLshort; -typedef int GLint; -typedef int GLclampx; -typedef unsigned char GLubyte; -typedef unsigned short GLushort; -typedef unsigned int GLuint; -typedef int GLsizei; -typedef float GLfloat; -typedef float GLclampf; -typedef double GLdouble; -typedef double GLclampd; -typedef void *GLeglImageOES; -typedef char GLchar; -typedef char GLcharARB; -#ifdef __APPLE__ -typedef void *GLhandleARB; -#else -typedef unsigned int GLhandleARB; -#endif -typedef unsigned short GLhalfARB; -typedef unsigned short GLhalf; -typedef GLint GLfixed; -typedef ptrdiff_t GLintptr; -typedef ptrdiff_t GLsizeiptr; -typedef int64_t GLint64; -typedef uint64_t GLuint64; -typedef ptrdiff_t GLintptrARB; -typedef ptrdiff_t GLsizeiptrARB; -typedef int64_t GLint64EXT; -typedef uint64_t GLuint64EXT; -typedef struct __GLsync *GLsync; -struct _cl_context; -struct _cl_event; -typedef void (APIENTRY *GLDEBUGPROC)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); -typedef void (APIENTRY *GLDEBUGPROCARB)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); -typedef void (APIENTRY *GLDEBUGPROCKHR)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); -typedef void (APIENTRY *GLDEBUGPROCAMD)(GLuint id,GLenum category,GLenum severity,GLsizei length,const GLchar *message,void *userParam); -typedef unsigned short GLhalfNV; -typedef GLintptr GLvdpauSurfaceNV; -#define GL_DEPTH_BUFFER_BIT 0x00000100 -#define GL_STENCIL_BUFFER_BIT 0x00000400 -#define GL_COLOR_BUFFER_BIT 0x00004000 -#define GL_FALSE 0 -#define GL_TRUE 1 -#define GL_POINTS 0x0000 -#define GL_LINES 0x0001 -#define GL_LINE_LOOP 0x0002 -#define GL_LINE_STRIP 0x0003 -#define GL_TRIANGLES 0x0004 -#define GL_TRIANGLE_STRIP 0x0005 -#define GL_TRIANGLE_FAN 0x0006 -#define GL_QUADS 0x0007 -#define GL_NEVER 0x0200 -#define GL_LESS 0x0201 -#define GL_EQUAL 0x0202 -#define GL_LEQUAL 0x0203 -#define GL_GREATER 0x0204 -#define GL_NOTEQUAL 0x0205 -#define GL_GEQUAL 0x0206 -#define GL_ALWAYS 0x0207 -#define GL_ZERO 0 -#define GL_ONE 1 -#define GL_SRC_COLOR 0x0300 -#define GL_ONE_MINUS_SRC_COLOR 0x0301 -#define GL_SRC_ALPHA 0x0302 -#define GL_ONE_MINUS_SRC_ALPHA 0x0303 -#define GL_DST_ALPHA 0x0304 -#define GL_ONE_MINUS_DST_ALPHA 0x0305 -#define GL_DST_COLOR 0x0306 -#define GL_ONE_MINUS_DST_COLOR 0x0307 -#define GL_SRC_ALPHA_SATURATE 0x0308 -#define GL_NONE 0 -#define GL_FRONT_LEFT 0x0400 -#define GL_FRONT_RIGHT 0x0401 -#define GL_BACK_LEFT 0x0402 -#define GL_BACK_RIGHT 0x0403 -#define GL_FRONT 0x0404 -#define GL_BACK 0x0405 -#define GL_LEFT 0x0406 -#define GL_RIGHT 0x0407 -#define GL_FRONT_AND_BACK 0x0408 -#define GL_NO_ERROR 0 -#define GL_INVALID_ENUM 0x0500 -#define GL_INVALID_VALUE 0x0501 -#define GL_INVALID_OPERATION 0x0502 -#define GL_OUT_OF_MEMORY 0x0505 -#define GL_CW 0x0900 -#define GL_CCW 0x0901 -#define GL_POINT_SIZE 0x0B11 -#define GL_POINT_SIZE_RANGE 0x0B12 -#define GL_POINT_SIZE_GRANULARITY 0x0B13 -#define GL_LINE_SMOOTH 0x0B20 -#define GL_LINE_WIDTH 0x0B21 -#define GL_LINE_WIDTH_RANGE 0x0B22 -#define GL_LINE_WIDTH_GRANULARITY 0x0B23 -#define GL_POLYGON_MODE 0x0B40 -#define GL_POLYGON_SMOOTH 0x0B41 -#define GL_CULL_FACE 0x0B44 -#define GL_CULL_FACE_MODE 0x0B45 -#define GL_FRONT_FACE 0x0B46 -#define GL_DEPTH_RANGE 0x0B70 -#define GL_DEPTH_TEST 0x0B71 -#define GL_DEPTH_WRITEMASK 0x0B72 -#define GL_DEPTH_CLEAR_VALUE 0x0B73 -#define GL_DEPTH_FUNC 0x0B74 -#define GL_STENCIL_TEST 0x0B90 -#define GL_STENCIL_CLEAR_VALUE 0x0B91 -#define GL_STENCIL_FUNC 0x0B92 -#define GL_STENCIL_VALUE_MASK 0x0B93 -#define GL_STENCIL_FAIL 0x0B94 -#define GL_STENCIL_PASS_DEPTH_FAIL 0x0B95 -#define GL_STENCIL_PASS_DEPTH_PASS 0x0B96 -#define GL_STENCIL_REF 0x0B97 -#define GL_STENCIL_WRITEMASK 0x0B98 -#define GL_VIEWPORT 0x0BA2 -#define GL_DITHER 0x0BD0 -#define GL_BLEND_DST 0x0BE0 -#define GL_BLEND_SRC 0x0BE1 -#define GL_BLEND 0x0BE2 -#define GL_LOGIC_OP_MODE 0x0BF0 -#define GL_COLOR_LOGIC_OP 0x0BF2 -#define GL_DRAW_BUFFER 0x0C01 -#define GL_READ_BUFFER 0x0C02 -#define GL_SCISSOR_BOX 0x0C10 -#define GL_SCISSOR_TEST 0x0C11 -#define GL_COLOR_CLEAR_VALUE 0x0C22 -#define GL_COLOR_WRITEMASK 0x0C23 -#define GL_DOUBLEBUFFER 0x0C32 -#define GL_STEREO 0x0C33 -#define GL_LINE_SMOOTH_HINT 0x0C52 -#define GL_POLYGON_SMOOTH_HINT 0x0C53 -#define GL_UNPACK_SWAP_BYTES 0x0CF0 -#define GL_UNPACK_LSB_FIRST 0x0CF1 -#define GL_UNPACK_ROW_LENGTH 0x0CF2 -#define GL_UNPACK_SKIP_ROWS 0x0CF3 -#define GL_UNPACK_SKIP_PIXELS 0x0CF4 -#define GL_UNPACK_ALIGNMENT 0x0CF5 -#define GL_PACK_SWAP_BYTES 0x0D00 -#define GL_PACK_LSB_FIRST 0x0D01 -#define GL_PACK_ROW_LENGTH 0x0D02 -#define GL_PACK_SKIP_ROWS 0x0D03 -#define GL_PACK_SKIP_PIXELS 0x0D04 -#define GL_PACK_ALIGNMENT 0x0D05 -#define GL_MAX_TEXTURE_SIZE 0x0D33 -#define GL_MAX_VIEWPORT_DIMS 0x0D3A -#define GL_SUBPIXEL_BITS 0x0D50 -#define GL_TEXTURE_1D 0x0DE0 -#define GL_TEXTURE_2D 0x0DE1 -#define GL_POLYGON_OFFSET_UNITS 0x2A00 -#define GL_POLYGON_OFFSET_POINT 0x2A01 -#define GL_POLYGON_OFFSET_LINE 0x2A02 -#define GL_POLYGON_OFFSET_FILL 0x8037 -#define GL_POLYGON_OFFSET_FACTOR 0x8038 -#define GL_TEXTURE_BINDING_1D 0x8068 -#define GL_TEXTURE_BINDING_2D 0x8069 -#define GL_TEXTURE_WIDTH 0x1000 -#define GL_TEXTURE_HEIGHT 0x1001 -#define GL_TEXTURE_INTERNAL_FORMAT 0x1003 -#define GL_TEXTURE_BORDER_COLOR 0x1004 -#define GL_TEXTURE_RED_SIZE 0x805C -#define GL_TEXTURE_GREEN_SIZE 0x805D -#define GL_TEXTURE_BLUE_SIZE 0x805E -#define GL_TEXTURE_ALPHA_SIZE 0x805F -#define GL_DONT_CARE 0x1100 -#define GL_FASTEST 0x1101 -#define GL_NICEST 0x1102 -#define GL_BYTE 0x1400 -#define GL_UNSIGNED_BYTE 0x1401 -#define GL_SHORT 0x1402 -#define GL_UNSIGNED_SHORT 0x1403 -#define GL_INT 0x1404 -#define GL_UNSIGNED_INT 0x1405 -#define GL_FLOAT 0x1406 -#define GL_DOUBLE 0x140A -#define GL_STACK_OVERFLOW 0x0503 -#define GL_STACK_UNDERFLOW 0x0504 -#define GL_CLEAR 0x1500 -#define GL_AND 0x1501 -#define GL_AND_REVERSE 0x1502 -#define GL_COPY 0x1503 -#define GL_AND_INVERTED 0x1504 -#define GL_NOOP 0x1505 -#define GL_XOR 0x1506 -#define GL_OR 0x1507 -#define GL_NOR 0x1508 -#define GL_EQUIV 0x1509 -#define GL_INVERT 0x150A -#define GL_OR_REVERSE 0x150B -#define GL_COPY_INVERTED 0x150C -#define GL_OR_INVERTED 0x150D -#define GL_NAND 0x150E -#define GL_SET 0x150F -#define GL_TEXTURE 0x1702 -#define GL_COLOR 0x1800 -#define GL_DEPTH 0x1801 -#define GL_STENCIL 0x1802 -#define GL_STENCIL_INDEX 0x1901 -#define GL_DEPTH_COMPONENT 0x1902 -#define GL_RED 0x1903 -#define GL_GREEN 0x1904 -#define GL_BLUE 0x1905 -#define GL_ALPHA 0x1906 -#define GL_RGB 0x1907 -#define GL_RGBA 0x1908 -#define GL_POINT 0x1B00 -#define GL_LINE 0x1B01 -#define GL_FILL 0x1B02 -#define GL_KEEP 0x1E00 -#define GL_REPLACE 0x1E01 -#define GL_INCR 0x1E02 -#define GL_DECR 0x1E03 -#define GL_VENDOR 0x1F00 -#define GL_RENDERER 0x1F01 -#define GL_VERSION 0x1F02 -#define GL_EXTENSIONS 0x1F03 -#define GL_NEAREST 0x2600 -#define GL_LINEAR 0x2601 -#define GL_NEAREST_MIPMAP_NEAREST 0x2700 -#define GL_LINEAR_MIPMAP_NEAREST 0x2701 -#define GL_NEAREST_MIPMAP_LINEAR 0x2702 -#define GL_LINEAR_MIPMAP_LINEAR 0x2703 -#define GL_TEXTURE_MAG_FILTER 0x2800 -#define GL_TEXTURE_MIN_FILTER 0x2801 -#define GL_TEXTURE_WRAP_S 0x2802 -#define GL_TEXTURE_WRAP_T 0x2803 -#define GL_PROXY_TEXTURE_1D 0x8063 -#define GL_PROXY_TEXTURE_2D 0x8064 -#define GL_REPEAT 0x2901 -#define GL_R3_G3_B2 0x2A10 -#define GL_RGB4 0x804F -#define GL_RGB5 0x8050 -#define GL_RGB8 0x8051 -#define GL_RGB10 0x8052 -#define GL_RGB12 0x8053 -#define GL_RGB16 0x8054 -#define GL_RGBA2 0x8055 -#define GL_RGBA4 0x8056 -#define GL_RGB5_A1 0x8057 -#define GL_RGBA8 0x8058 -#define GL_RGB10_A2 0x8059 -#define GL_RGBA12 0x805A -#define GL_RGBA16 0x805B -#define GL_CURRENT_BIT 0x00000001 -#define GL_POINT_BIT 0x00000002 -#define GL_LINE_BIT 0x00000004 -#define GL_POLYGON_BIT 0x00000008 -#define GL_POLYGON_STIPPLE_BIT 0x00000010 -#define GL_PIXEL_MODE_BIT 0x00000020 -#define GL_LIGHTING_BIT 0x00000040 -#define GL_FOG_BIT 0x00000080 -#define GL_ACCUM_BUFFER_BIT 0x00000200 -#define GL_VIEWPORT_BIT 0x00000800 -#define GL_TRANSFORM_BIT 0x00001000 -#define GL_ENABLE_BIT 0x00002000 -#define GL_HINT_BIT 0x00008000 -#define GL_EVAL_BIT 0x00010000 -#define GL_LIST_BIT 0x00020000 -#define GL_TEXTURE_BIT 0x00040000 -#define GL_SCISSOR_BIT 0x00080000 -#define GL_ALL_ATTRIB_BITS 0xFFFFFFFF -#define GL_CLIENT_PIXEL_STORE_BIT 0x00000001 -#define GL_CLIENT_VERTEX_ARRAY_BIT 0x00000002 -#define GL_CLIENT_ALL_ATTRIB_BITS 0xFFFFFFFF -#define GL_QUAD_STRIP 0x0008 -#define GL_POLYGON 0x0009 -#define GL_ACCUM 0x0100 -#define GL_LOAD 0x0101 -#define GL_RETURN 0x0102 -#define GL_MULT 0x0103 -#define GL_ADD 0x0104 -#define GL_AUX0 0x0409 -#define GL_AUX1 0x040A -#define GL_AUX2 0x040B -#define GL_AUX3 0x040C -#define GL_2D 0x0600 -#define GL_3D 0x0601 -#define GL_3D_COLOR 0x0602 -#define GL_3D_COLOR_TEXTURE 0x0603 -#define GL_4D_COLOR_TEXTURE 0x0604 -#define GL_PASS_THROUGH_TOKEN 0x0700 -#define GL_POINT_TOKEN 0x0701 -#define GL_LINE_TOKEN 0x0702 -#define GL_POLYGON_TOKEN 0x0703 -#define GL_BITMAP_TOKEN 0x0704 -#define GL_DRAW_PIXEL_TOKEN 0x0705 -#define GL_COPY_PIXEL_TOKEN 0x0706 -#define GL_LINE_RESET_TOKEN 0x0707 -#define GL_EXP 0x0800 -#define GL_EXP2 0x0801 -#define GL_COEFF 0x0A00 -#define GL_ORDER 0x0A01 -#define GL_DOMAIN 0x0A02 -#define GL_PIXEL_MAP_I_TO_I 0x0C70 -#define GL_PIXEL_MAP_S_TO_S 0x0C71 -#define GL_PIXEL_MAP_I_TO_R 0x0C72 -#define GL_PIXEL_MAP_I_TO_G 0x0C73 -#define GL_PIXEL_MAP_I_TO_B 0x0C74 -#define GL_PIXEL_MAP_I_TO_A 0x0C75 -#define GL_PIXEL_MAP_R_TO_R 0x0C76 -#define GL_PIXEL_MAP_G_TO_G 0x0C77 -#define GL_PIXEL_MAP_B_TO_B 0x0C78 -#define GL_PIXEL_MAP_A_TO_A 0x0C79 -#define GL_VERTEX_ARRAY_POINTER 0x808E -#define GL_NORMAL_ARRAY_POINTER 0x808F -#define GL_COLOR_ARRAY_POINTER 0x8090 -#define GL_INDEX_ARRAY_POINTER 0x8091 -#define GL_TEXTURE_COORD_ARRAY_POINTER 0x8092 -#define GL_EDGE_FLAG_ARRAY_POINTER 0x8093 -#define GL_FEEDBACK_BUFFER_POINTER 0x0DF0 -#define GL_SELECTION_BUFFER_POINTER 0x0DF3 -#define GL_CURRENT_COLOR 0x0B00 -#define GL_CURRENT_INDEX 0x0B01 -#define GL_CURRENT_NORMAL 0x0B02 -#define GL_CURRENT_TEXTURE_COORDS 0x0B03 -#define GL_CURRENT_RASTER_COLOR 0x0B04 -#define GL_CURRENT_RASTER_INDEX 0x0B05 -#define GL_CURRENT_RASTER_TEXTURE_COORDS 0x0B06 -#define GL_CURRENT_RASTER_POSITION 0x0B07 -#define GL_CURRENT_RASTER_POSITION_VALID 0x0B08 -#define GL_CURRENT_RASTER_DISTANCE 0x0B09 -#define GL_POINT_SMOOTH 0x0B10 -#define GL_LINE_STIPPLE 0x0B24 -#define GL_LINE_STIPPLE_PATTERN 0x0B25 -#define GL_LINE_STIPPLE_REPEAT 0x0B26 -#define GL_LIST_MODE 0x0B30 -#define GL_MAX_LIST_NESTING 0x0B31 -#define GL_LIST_BASE 0x0B32 -#define GL_LIST_INDEX 0x0B33 -#define GL_POLYGON_STIPPLE 0x0B42 -#define GL_EDGE_FLAG 0x0B43 -#define GL_LIGHTING 0x0B50 -#define GL_LIGHT_MODEL_LOCAL_VIEWER 0x0B51 -#define GL_LIGHT_MODEL_TWO_SIDE 0x0B52 -#define GL_LIGHT_MODEL_AMBIENT 0x0B53 -#define GL_SHADE_MODEL 0x0B54 -#define GL_COLOR_MATERIAL_FACE 0x0B55 -#define GL_COLOR_MATERIAL_PARAMETER 0x0B56 -#define GL_COLOR_MATERIAL 0x0B57 -#define GL_FOG 0x0B60 -#define GL_FOG_INDEX 0x0B61 -#define GL_FOG_DENSITY 0x0B62 -#define GL_FOG_START 0x0B63 -#define GL_FOG_END 0x0B64 -#define GL_FOG_MODE 0x0B65 -#define GL_FOG_COLOR 0x0B66 -#define GL_ACCUM_CLEAR_VALUE 0x0B80 -#define GL_MATRIX_MODE 0x0BA0 -#define GL_NORMALIZE 0x0BA1 -#define GL_MODELVIEW_STACK_DEPTH 0x0BA3 -#define GL_PROJECTION_STACK_DEPTH 0x0BA4 -#define GL_TEXTURE_STACK_DEPTH 0x0BA5 -#define GL_MODELVIEW_MATRIX 0x0BA6 -#define GL_PROJECTION_MATRIX 0x0BA7 -#define GL_TEXTURE_MATRIX 0x0BA8 -#define GL_ATTRIB_STACK_DEPTH 0x0BB0 -#define GL_CLIENT_ATTRIB_STACK_DEPTH 0x0BB1 -#define GL_ALPHA_TEST 0x0BC0 -#define GL_ALPHA_TEST_FUNC 0x0BC1 -#define GL_ALPHA_TEST_REF 0x0BC2 -#define GL_INDEX_LOGIC_OP 0x0BF1 -#define GL_LOGIC_OP 0x0BF1 -#define GL_AUX_BUFFERS 0x0C00 -#define GL_INDEX_CLEAR_VALUE 0x0C20 -#define GL_INDEX_WRITEMASK 0x0C21 -#define GL_INDEX_MODE 0x0C30 -#define GL_RGBA_MODE 0x0C31 -#define GL_RENDER_MODE 0x0C40 -#define GL_PERSPECTIVE_CORRECTION_HINT 0x0C50 -#define GL_POINT_SMOOTH_HINT 0x0C51 -#define GL_FOG_HINT 0x0C54 -#define GL_TEXTURE_GEN_S 0x0C60 -#define GL_TEXTURE_GEN_T 0x0C61 -#define GL_TEXTURE_GEN_R 0x0C62 -#define GL_TEXTURE_GEN_Q 0x0C63 -#define GL_PIXEL_MAP_I_TO_I_SIZE 0x0CB0 -#define GL_PIXEL_MAP_S_TO_S_SIZE 0x0CB1 -#define GL_PIXEL_MAP_I_TO_R_SIZE 0x0CB2 -#define GL_PIXEL_MAP_I_TO_G_SIZE 0x0CB3 -#define GL_PIXEL_MAP_I_TO_B_SIZE 0x0CB4 -#define GL_PIXEL_MAP_I_TO_A_SIZE 0x0CB5 -#define GL_PIXEL_MAP_R_TO_R_SIZE 0x0CB6 -#define GL_PIXEL_MAP_G_TO_G_SIZE 0x0CB7 -#define GL_PIXEL_MAP_B_TO_B_SIZE 0x0CB8 -#define GL_PIXEL_MAP_A_TO_A_SIZE 0x0CB9 -#define GL_MAP_COLOR 0x0D10 -#define GL_MAP_STENCIL 0x0D11 -#define GL_INDEX_SHIFT 0x0D12 -#define GL_INDEX_OFFSET 0x0D13 -#define GL_RED_SCALE 0x0D14 -#define GL_RED_BIAS 0x0D15 -#define GL_ZOOM_X 0x0D16 -#define GL_ZOOM_Y 0x0D17 -#define GL_GREEN_SCALE 0x0D18 -#define GL_GREEN_BIAS 0x0D19 -#define GL_BLUE_SCALE 0x0D1A -#define GL_BLUE_BIAS 0x0D1B -#define GL_ALPHA_SCALE 0x0D1C -#define GL_ALPHA_BIAS 0x0D1D -#define GL_DEPTH_SCALE 0x0D1E -#define GL_DEPTH_BIAS 0x0D1F -#define GL_MAX_EVAL_ORDER 0x0D30 -#define GL_MAX_LIGHTS 0x0D31 -#define GL_MAX_CLIP_PLANES 0x0D32 -#define GL_MAX_PIXEL_MAP_TABLE 0x0D34 -#define GL_MAX_ATTRIB_STACK_DEPTH 0x0D35 -#define GL_MAX_MODELVIEW_STACK_DEPTH 0x0D36 -#define GL_MAX_NAME_STACK_DEPTH 0x0D37 -#define GL_MAX_PROJECTION_STACK_DEPTH 0x0D38 -#define GL_MAX_TEXTURE_STACK_DEPTH 0x0D39 -#define GL_MAX_CLIENT_ATTRIB_STACK_DEPTH 0x0D3B -#define GL_INDEX_BITS 0x0D51 -#define GL_RED_BITS 0x0D52 -#define GL_GREEN_BITS 0x0D53 -#define GL_BLUE_BITS 0x0D54 -#define GL_ALPHA_BITS 0x0D55 -#define GL_DEPTH_BITS 0x0D56 -#define GL_STENCIL_BITS 0x0D57 -#define GL_ACCUM_RED_BITS 0x0D58 -#define GL_ACCUM_GREEN_BITS 0x0D59 -#define GL_ACCUM_BLUE_BITS 0x0D5A -#define GL_ACCUM_ALPHA_BITS 0x0D5B -#define GL_NAME_STACK_DEPTH 0x0D70 -#define GL_AUTO_NORMAL 0x0D80 -#define GL_MAP1_COLOR_4 0x0D90 -#define GL_MAP1_INDEX 0x0D91 -#define GL_MAP1_NORMAL 0x0D92 -#define GL_MAP1_TEXTURE_COORD_1 0x0D93 -#define GL_MAP1_TEXTURE_COORD_2 0x0D94 -#define GL_MAP1_TEXTURE_COORD_3 0x0D95 -#define GL_MAP1_TEXTURE_COORD_4 0x0D96 -#define GL_MAP1_VERTEX_3 0x0D97 -#define GL_MAP1_VERTEX_4 0x0D98 -#define GL_MAP2_COLOR_4 0x0DB0 -#define GL_MAP2_INDEX 0x0DB1 -#define GL_MAP2_NORMAL 0x0DB2 -#define GL_MAP2_TEXTURE_COORD_1 0x0DB3 -#define GL_MAP2_TEXTURE_COORD_2 0x0DB4 -#define GL_MAP2_TEXTURE_COORD_3 0x0DB5 -#define GL_MAP2_TEXTURE_COORD_4 0x0DB6 -#define GL_MAP2_VERTEX_3 0x0DB7 -#define GL_MAP2_VERTEX_4 0x0DB8 -#define GL_MAP1_GRID_DOMAIN 0x0DD0 -#define GL_MAP1_GRID_SEGMENTS 0x0DD1 -#define GL_MAP2_GRID_DOMAIN 0x0DD2 -#define GL_MAP2_GRID_SEGMENTS 0x0DD3 -#define GL_FEEDBACK_BUFFER_SIZE 0x0DF1 -#define GL_FEEDBACK_BUFFER_TYPE 0x0DF2 -#define GL_SELECTION_BUFFER_SIZE 0x0DF4 -#define GL_VERTEX_ARRAY 0x8074 -#define GL_NORMAL_ARRAY 0x8075 -#define GL_COLOR_ARRAY 0x8076 -#define GL_INDEX_ARRAY 0x8077 -#define GL_TEXTURE_COORD_ARRAY 0x8078 -#define GL_EDGE_FLAG_ARRAY 0x8079 -#define GL_VERTEX_ARRAY_SIZE 0x807A -#define GL_VERTEX_ARRAY_TYPE 0x807B -#define GL_VERTEX_ARRAY_STRIDE 0x807C -#define GL_NORMAL_ARRAY_TYPE 0x807E -#define GL_NORMAL_ARRAY_STRIDE 0x807F -#define GL_COLOR_ARRAY_SIZE 0x8081 -#define GL_COLOR_ARRAY_TYPE 0x8082 -#define GL_COLOR_ARRAY_STRIDE 0x8083 -#define GL_INDEX_ARRAY_TYPE 0x8085 -#define GL_INDEX_ARRAY_STRIDE 0x8086 -#define GL_TEXTURE_COORD_ARRAY_SIZE 0x8088 -#define GL_TEXTURE_COORD_ARRAY_TYPE 0x8089 -#define GL_TEXTURE_COORD_ARRAY_STRIDE 0x808A -#define GL_EDGE_FLAG_ARRAY_STRIDE 0x808C -#define GL_TEXTURE_COMPONENTS 0x1003 -#define GL_TEXTURE_BORDER 0x1005 -#define GL_TEXTURE_LUMINANCE_SIZE 0x8060 -#define GL_TEXTURE_INTENSITY_SIZE 0x8061 -#define GL_TEXTURE_PRIORITY 0x8066 -#define GL_TEXTURE_RESIDENT 0x8067 -#define GL_AMBIENT 0x1200 -#define GL_DIFFUSE 0x1201 -#define GL_SPECULAR 0x1202 -#define GL_POSITION 0x1203 -#define GL_SPOT_DIRECTION 0x1204 -#define GL_SPOT_EXPONENT 0x1205 -#define GL_SPOT_CUTOFF 0x1206 -#define GL_CONSTANT_ATTENUATION 0x1207 -#define GL_LINEAR_ATTENUATION 0x1208 -#define GL_QUADRATIC_ATTENUATION 0x1209 -#define GL_COMPILE 0x1300 -#define GL_COMPILE_AND_EXECUTE 0x1301 -#define GL_2_BYTES 0x1407 -#define GL_3_BYTES 0x1408 -#define GL_4_BYTES 0x1409 -#define GL_EMISSION 0x1600 -#define GL_SHININESS 0x1601 -#define GL_AMBIENT_AND_DIFFUSE 0x1602 -#define GL_COLOR_INDEXES 0x1603 -#define GL_MODELVIEW 0x1700 -#define GL_PROJECTION 0x1701 -#define GL_COLOR_INDEX 0x1900 -#define GL_LUMINANCE 0x1909 -#define GL_LUMINANCE_ALPHA 0x190A -#define GL_BITMAP 0x1A00 -#define GL_RENDER 0x1C00 -#define GL_FEEDBACK 0x1C01 -#define GL_SELECT 0x1C02 -#define GL_FLAT 0x1D00 -#define GL_SMOOTH 0x1D01 -#define GL_S 0x2000 -#define GL_T 0x2001 -#define GL_R 0x2002 -#define GL_Q 0x2003 -#define GL_MODULATE 0x2100 -#define GL_DECAL 0x2101 -#define GL_TEXTURE_ENV_MODE 0x2200 -#define GL_TEXTURE_ENV_COLOR 0x2201 -#define GL_TEXTURE_ENV 0x2300 -#define GL_EYE_LINEAR 0x2400 -#define GL_OBJECT_LINEAR 0x2401 -#define GL_SPHERE_MAP 0x2402 -#define GL_TEXTURE_GEN_MODE 0x2500 -#define GL_OBJECT_PLANE 0x2501 -#define GL_EYE_PLANE 0x2502 -#define GL_CLAMP 0x2900 -#define GL_ALPHA4 0x803B -#define GL_ALPHA8 0x803C -#define GL_ALPHA12 0x803D -#define GL_ALPHA16 0x803E -#define GL_LUMINANCE4 0x803F -#define GL_LUMINANCE8 0x8040 -#define GL_LUMINANCE12 0x8041 -#define GL_LUMINANCE16 0x8042 -#define GL_LUMINANCE4_ALPHA4 0x8043 -#define GL_LUMINANCE6_ALPHA2 0x8044 -#define GL_LUMINANCE8_ALPHA8 0x8045 -#define GL_LUMINANCE12_ALPHA4 0x8046 -#define GL_LUMINANCE12_ALPHA12 0x8047 -#define GL_LUMINANCE16_ALPHA16 0x8048 -#define GL_INTENSITY 0x8049 -#define GL_INTENSITY4 0x804A -#define GL_INTENSITY8 0x804B -#define GL_INTENSITY12 0x804C -#define GL_INTENSITY16 0x804D -#define GL_V2F 0x2A20 -#define GL_V3F 0x2A21 -#define GL_C4UB_V2F 0x2A22 -#define GL_C4UB_V3F 0x2A23 -#define GL_C3F_V3F 0x2A24 -#define GL_N3F_V3F 0x2A25 -#define GL_C4F_N3F_V3F 0x2A26 -#define GL_T2F_V3F 0x2A27 -#define GL_T4F_V4F 0x2A28 -#define GL_T2F_C4UB_V3F 0x2A29 -#define GL_T2F_C3F_V3F 0x2A2A -#define GL_T2F_N3F_V3F 0x2A2B -#define GL_T2F_C4F_N3F_V3F 0x2A2C -#define GL_T4F_C4F_N3F_V4F 0x2A2D -#define GL_CLIP_PLANE0 0x3000 -#define GL_CLIP_PLANE1 0x3001 -#define GL_CLIP_PLANE2 0x3002 -#define GL_CLIP_PLANE3 0x3003 -#define GL_CLIP_PLANE4 0x3004 -#define GL_CLIP_PLANE5 0x3005 -#define GL_LIGHT0 0x4000 -#define GL_LIGHT1 0x4001 -#define GL_LIGHT2 0x4002 -#define GL_LIGHT3 0x4003 -#define GL_LIGHT4 0x4004 -#define GL_LIGHT5 0x4005 -#define GL_LIGHT6 0x4006 -#define GL_LIGHT7 0x4007 -#define GL_UNSIGNED_BYTE_3_3_2 0x8032 -#define GL_UNSIGNED_SHORT_4_4_4_4 0x8033 -#define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 -#define GL_UNSIGNED_INT_8_8_8_8 0x8035 -#define GL_UNSIGNED_INT_10_10_10_2 0x8036 -#define GL_TEXTURE_BINDING_3D 0x806A -#define GL_PACK_SKIP_IMAGES 0x806B -#define GL_PACK_IMAGE_HEIGHT 0x806C -#define GL_UNPACK_SKIP_IMAGES 0x806D -#define GL_UNPACK_IMAGE_HEIGHT 0x806E -#define GL_TEXTURE_3D 0x806F -#define GL_PROXY_TEXTURE_3D 0x8070 -#define GL_TEXTURE_DEPTH 0x8071 -#define GL_TEXTURE_WRAP_R 0x8072 -#define GL_MAX_3D_TEXTURE_SIZE 0x8073 -#define GL_UNSIGNED_BYTE_2_3_3_REV 0x8362 -#define GL_UNSIGNED_SHORT_5_6_5 0x8363 -#define GL_UNSIGNED_SHORT_5_6_5_REV 0x8364 -#define GL_UNSIGNED_SHORT_4_4_4_4_REV 0x8365 -#define GL_UNSIGNED_SHORT_1_5_5_5_REV 0x8366 -#define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367 -#define GL_UNSIGNED_INT_2_10_10_10_REV 0x8368 -#define GL_BGR 0x80E0 -#define GL_BGRA 0x80E1 -#define GL_MAX_ELEMENTS_VERTICES 0x80E8 -#define GL_MAX_ELEMENTS_INDICES 0x80E9 -#define GL_CLAMP_TO_EDGE 0x812F -#define GL_TEXTURE_MIN_LOD 0x813A -#define GL_TEXTURE_MAX_LOD 0x813B -#define GL_TEXTURE_BASE_LEVEL 0x813C -#define GL_TEXTURE_MAX_LEVEL 0x813D -#define GL_SMOOTH_POINT_SIZE_RANGE 0x0B12 -#define GL_SMOOTH_POINT_SIZE_GRANULARITY 0x0B13 -#define GL_SMOOTH_LINE_WIDTH_RANGE 0x0B22 -#define GL_SMOOTH_LINE_WIDTH_GRANULARITY 0x0B23 -#define GL_ALIASED_LINE_WIDTH_RANGE 0x846E -#define GL_RESCALE_NORMAL 0x803A -#define GL_LIGHT_MODEL_COLOR_CONTROL 0x81F8 -#define GL_SINGLE_COLOR 0x81F9 -#define GL_SEPARATE_SPECULAR_COLOR 0x81FA -#define GL_ALIASED_POINT_SIZE_RANGE 0x846D -#define GL_TEXTURE0 0x84C0 -#define GL_TEXTURE1 0x84C1 -#define GL_TEXTURE2 0x84C2 -#define GL_TEXTURE3 0x84C3 -#define GL_TEXTURE4 0x84C4 -#define GL_TEXTURE5 0x84C5 -#define GL_TEXTURE6 0x84C6 -#define GL_TEXTURE7 0x84C7 -#define GL_TEXTURE8 0x84C8 -#define GL_TEXTURE9 0x84C9 -#define GL_TEXTURE10 0x84CA -#define GL_TEXTURE11 0x84CB -#define GL_TEXTURE12 0x84CC -#define GL_TEXTURE13 0x84CD -#define GL_TEXTURE14 0x84CE -#define GL_TEXTURE15 0x84CF -#define GL_TEXTURE16 0x84D0 -#define GL_TEXTURE17 0x84D1 -#define GL_TEXTURE18 0x84D2 -#define GL_TEXTURE19 0x84D3 -#define GL_TEXTURE20 0x84D4 -#define GL_TEXTURE21 0x84D5 -#define GL_TEXTURE22 0x84D6 -#define GL_TEXTURE23 0x84D7 -#define GL_TEXTURE24 0x84D8 -#define GL_TEXTURE25 0x84D9 -#define GL_TEXTURE26 0x84DA -#define GL_TEXTURE27 0x84DB -#define GL_TEXTURE28 0x84DC -#define GL_TEXTURE29 0x84DD -#define GL_TEXTURE30 0x84DE -#define GL_TEXTURE31 0x84DF -#define GL_ACTIVE_TEXTURE 0x84E0 -#define GL_MULTISAMPLE 0x809D -#define GL_SAMPLE_ALPHA_TO_COVERAGE 0x809E -#define GL_SAMPLE_ALPHA_TO_ONE 0x809F -#define GL_SAMPLE_COVERAGE 0x80A0 -#define GL_SAMPLE_BUFFERS 0x80A8 -#define GL_SAMPLES 0x80A9 -#define GL_SAMPLE_COVERAGE_VALUE 0x80AA -#define GL_SAMPLE_COVERAGE_INVERT 0x80AB -#define GL_TEXTURE_CUBE_MAP 0x8513 -#define GL_TEXTURE_BINDING_CUBE_MAP 0x8514 -#define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515 -#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516 -#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517 -#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518 -#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519 -#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A -#define GL_PROXY_TEXTURE_CUBE_MAP 0x851B -#define GL_MAX_CUBE_MAP_TEXTURE_SIZE 0x851C -#define GL_COMPRESSED_RGB 0x84ED -#define GL_COMPRESSED_RGBA 0x84EE -#define GL_TEXTURE_COMPRESSION_HINT 0x84EF -#define GL_TEXTURE_COMPRESSED_IMAGE_SIZE 0x86A0 -#define GL_TEXTURE_COMPRESSED 0x86A1 -#define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2 -#define GL_COMPRESSED_TEXTURE_FORMATS 0x86A3 -#define GL_CLAMP_TO_BORDER 0x812D -#define GL_CLIENT_ACTIVE_TEXTURE 0x84E1 -#define GL_MAX_TEXTURE_UNITS 0x84E2 -#define GL_TRANSPOSE_MODELVIEW_MATRIX 0x84E3 -#define GL_TRANSPOSE_PROJECTION_MATRIX 0x84E4 -#define GL_TRANSPOSE_TEXTURE_MATRIX 0x84E5 -#define GL_TRANSPOSE_COLOR_MATRIX 0x84E6 -#define GL_MULTISAMPLE_BIT 0x20000000 -#define GL_NORMAL_MAP 0x8511 -#define GL_REFLECTION_MAP 0x8512 -#define GL_COMPRESSED_ALPHA 0x84E9 -#define GL_COMPRESSED_LUMINANCE 0x84EA -#define GL_COMPRESSED_LUMINANCE_ALPHA 0x84EB -#define GL_COMPRESSED_INTENSITY 0x84EC -#define GL_COMBINE 0x8570 -#define GL_COMBINE_RGB 0x8571 -#define GL_COMBINE_ALPHA 0x8572 -#define GL_SOURCE0_RGB 0x8580 -#define GL_SOURCE1_RGB 0x8581 -#define GL_SOURCE2_RGB 0x8582 -#define GL_SOURCE0_ALPHA 0x8588 -#define GL_SOURCE1_ALPHA 0x8589 -#define GL_SOURCE2_ALPHA 0x858A -#define GL_OPERAND0_RGB 0x8590 -#define GL_OPERAND1_RGB 0x8591 -#define GL_OPERAND2_RGB 0x8592 -#define GL_OPERAND0_ALPHA 0x8598 -#define GL_OPERAND1_ALPHA 0x8599 -#define GL_OPERAND2_ALPHA 0x859A -#define GL_RGB_SCALE 0x8573 -#define GL_ADD_SIGNED 0x8574 -#define GL_INTERPOLATE 0x8575 -#define GL_SUBTRACT 0x84E7 -#define GL_CONSTANT 0x8576 -#define GL_PRIMARY_COLOR 0x8577 -#define GL_PREVIOUS 0x8578 -#define GL_DOT3_RGB 0x86AE -#define GL_DOT3_RGBA 0x86AF -#define GL_BLEND_DST_RGB 0x80C8 -#define GL_BLEND_SRC_RGB 0x80C9 -#define GL_BLEND_DST_ALPHA 0x80CA -#define GL_BLEND_SRC_ALPHA 0x80CB -#define GL_POINT_FADE_THRESHOLD_SIZE 0x8128 -#define GL_DEPTH_COMPONENT16 0x81A5 -#define GL_DEPTH_COMPONENT24 0x81A6 -#define GL_DEPTH_COMPONENT32 0x81A7 -#define GL_MIRRORED_REPEAT 0x8370 -#define GL_MAX_TEXTURE_LOD_BIAS 0x84FD -#define GL_TEXTURE_LOD_BIAS 0x8501 -#define GL_INCR_WRAP 0x8507 -#define GL_DECR_WRAP 0x8508 -#define GL_TEXTURE_DEPTH_SIZE 0x884A -#define GL_TEXTURE_COMPARE_MODE 0x884C -#define GL_TEXTURE_COMPARE_FUNC 0x884D -#define GL_POINT_SIZE_MIN 0x8126 -#define GL_POINT_SIZE_MAX 0x8127 -#define GL_POINT_DISTANCE_ATTENUATION 0x8129 -#define GL_GENERATE_MIPMAP 0x8191 -#define GL_GENERATE_MIPMAP_HINT 0x8192 -#define GL_FOG_COORDINATE_SOURCE 0x8450 -#define GL_FOG_COORDINATE 0x8451 -#define GL_FRAGMENT_DEPTH 0x8452 -#define GL_CURRENT_FOG_COORDINATE 0x8453 -#define GL_FOG_COORDINATE_ARRAY_TYPE 0x8454 -#define GL_FOG_COORDINATE_ARRAY_STRIDE 0x8455 -#define GL_FOG_COORDINATE_ARRAY_POINTER 0x8456 -#define GL_FOG_COORDINATE_ARRAY 0x8457 -#define GL_COLOR_SUM 0x8458 -#define GL_CURRENT_SECONDARY_COLOR 0x8459 -#define GL_SECONDARY_COLOR_ARRAY_SIZE 0x845A -#define GL_SECONDARY_COLOR_ARRAY_TYPE 0x845B -#define GL_SECONDARY_COLOR_ARRAY_STRIDE 0x845C -#define GL_SECONDARY_COLOR_ARRAY_POINTER 0x845D -#define GL_SECONDARY_COLOR_ARRAY 0x845E -#define GL_TEXTURE_FILTER_CONTROL 0x8500 -#define GL_DEPTH_TEXTURE_MODE 0x884B -#define GL_COMPARE_R_TO_TEXTURE 0x884E -#define GL_FUNC_ADD 0x8006 -#define GL_FUNC_SUBTRACT 0x800A -#define GL_FUNC_REVERSE_SUBTRACT 0x800B -#define GL_MIN 0x8007 -#define GL_MAX 0x8008 -#define GL_CONSTANT_COLOR 0x8001 -#define GL_ONE_MINUS_CONSTANT_COLOR 0x8002 -#define GL_CONSTANT_ALPHA 0x8003 -#define GL_ONE_MINUS_CONSTANT_ALPHA 0x8004 -#define GL_BUFFER_SIZE 0x8764 -#define GL_BUFFER_USAGE 0x8765 -#define GL_QUERY_COUNTER_BITS 0x8864 -#define GL_CURRENT_QUERY 0x8865 -#define GL_QUERY_RESULT 0x8866 -#define GL_QUERY_RESULT_AVAILABLE 0x8867 -#define GL_ARRAY_BUFFER 0x8892 -#define GL_ELEMENT_ARRAY_BUFFER 0x8893 -#define GL_ARRAY_BUFFER_BINDING 0x8894 -#define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895 -#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F -#define GL_READ_ONLY 0x88B8 -#define GL_WRITE_ONLY 0x88B9 -#define GL_READ_WRITE 0x88BA -#define GL_BUFFER_ACCESS 0x88BB -#define GL_BUFFER_MAPPED 0x88BC -#define GL_BUFFER_MAP_POINTER 0x88BD -#define GL_STREAM_DRAW 0x88E0 -#define GL_STREAM_READ 0x88E1 -#define GL_STREAM_COPY 0x88E2 -#define GL_STATIC_DRAW 0x88E4 -#define GL_STATIC_READ 0x88E5 -#define GL_STATIC_COPY 0x88E6 -#define GL_DYNAMIC_DRAW 0x88E8 -#define GL_DYNAMIC_READ 0x88E9 -#define GL_DYNAMIC_COPY 0x88EA -#define GL_SAMPLES_PASSED 0x8914 -#define GL_SRC1_ALPHA 0x8589 -#define GL_VERTEX_ARRAY_BUFFER_BINDING 0x8896 -#define GL_NORMAL_ARRAY_BUFFER_BINDING 0x8897 -#define GL_COLOR_ARRAY_BUFFER_BINDING 0x8898 -#define GL_INDEX_ARRAY_BUFFER_BINDING 0x8899 -#define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING 0x889A -#define GL_EDGE_FLAG_ARRAY_BUFFER_BINDING 0x889B -#define GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING 0x889C -#define GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING 0x889D -#define GL_WEIGHT_ARRAY_BUFFER_BINDING 0x889E -#define GL_FOG_COORD_SRC 0x8450 -#define GL_FOG_COORD 0x8451 -#define GL_CURRENT_FOG_COORD 0x8453 -#define GL_FOG_COORD_ARRAY_TYPE 0x8454 -#define GL_FOG_COORD_ARRAY_STRIDE 0x8455 -#define GL_FOG_COORD_ARRAY_POINTER 0x8456 -#define GL_FOG_COORD_ARRAY 0x8457 -#define GL_FOG_COORD_ARRAY_BUFFER_BINDING 0x889D -#define GL_SRC0_RGB 0x8580 -#define GL_SRC1_RGB 0x8581 -#define GL_SRC2_RGB 0x8582 -#define GL_SRC0_ALPHA 0x8588 -#define GL_SRC2_ALPHA 0x858A -#define GL_BLEND_EQUATION_RGB 0x8009 -#define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622 -#define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623 -#define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624 -#define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625 -#define GL_CURRENT_VERTEX_ATTRIB 0x8626 -#define GL_VERTEX_PROGRAM_POINT_SIZE 0x8642 -#define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645 -#define GL_STENCIL_BACK_FUNC 0x8800 -#define GL_STENCIL_BACK_FAIL 0x8801 -#define GL_STENCIL_BACK_PASS_DEPTH_FAIL 0x8802 -#define GL_STENCIL_BACK_PASS_DEPTH_PASS 0x8803 -#define GL_MAX_DRAW_BUFFERS 0x8824 -#define GL_DRAW_BUFFER0 0x8825 -#define GL_DRAW_BUFFER1 0x8826 -#define GL_DRAW_BUFFER2 0x8827 -#define GL_DRAW_BUFFER3 0x8828 -#define GL_DRAW_BUFFER4 0x8829 -#define GL_DRAW_BUFFER5 0x882A -#define GL_DRAW_BUFFER6 0x882B -#define GL_DRAW_BUFFER7 0x882C -#define GL_DRAW_BUFFER8 0x882D -#define GL_DRAW_BUFFER9 0x882E -#define GL_DRAW_BUFFER10 0x882F -#define GL_DRAW_BUFFER11 0x8830 -#define GL_DRAW_BUFFER12 0x8831 -#define GL_DRAW_BUFFER13 0x8832 -#define GL_DRAW_BUFFER14 0x8833 -#define GL_DRAW_BUFFER15 0x8834 -#define GL_BLEND_EQUATION_ALPHA 0x883D -#define GL_MAX_VERTEX_ATTRIBS 0x8869 -#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A -#define GL_MAX_TEXTURE_IMAGE_UNITS 0x8872 -#define GL_FRAGMENT_SHADER 0x8B30 -#define GL_VERTEX_SHADER 0x8B31 -#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS 0x8B49 -#define GL_MAX_VERTEX_UNIFORM_COMPONENTS 0x8B4A -#define GL_MAX_VARYING_FLOATS 0x8B4B -#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS 0x8B4C -#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D -#define GL_SHADER_TYPE 0x8B4F -#define GL_FLOAT_VEC2 0x8B50 -#define GL_FLOAT_VEC3 0x8B51 -#define GL_FLOAT_VEC4 0x8B52 -#define GL_INT_VEC2 0x8B53 -#define GL_INT_VEC3 0x8B54 -#define GL_INT_VEC4 0x8B55 -#define GL_BOOL 0x8B56 -#define GL_BOOL_VEC2 0x8B57 -#define GL_BOOL_VEC3 0x8B58 -#define GL_BOOL_VEC4 0x8B59 -#define GL_FLOAT_MAT2 0x8B5A -#define GL_FLOAT_MAT3 0x8B5B -#define GL_FLOAT_MAT4 0x8B5C -#define GL_SAMPLER_1D 0x8B5D -#define GL_SAMPLER_2D 0x8B5E -#define GL_SAMPLER_3D 0x8B5F -#define GL_SAMPLER_CUBE 0x8B60 -#define GL_SAMPLER_1D_SHADOW 0x8B61 -#define GL_SAMPLER_2D_SHADOW 0x8B62 -#define GL_DELETE_STATUS 0x8B80 -#define GL_COMPILE_STATUS 0x8B81 -#define GL_LINK_STATUS 0x8B82 -#define GL_VALIDATE_STATUS 0x8B83 -#define GL_INFO_LOG_LENGTH 0x8B84 -#define GL_ATTACHED_SHADERS 0x8B85 -#define GL_ACTIVE_UNIFORMS 0x8B86 -#define GL_ACTIVE_UNIFORM_MAX_LENGTH 0x8B87 -#define GL_SHADER_SOURCE_LENGTH 0x8B88 -#define GL_ACTIVE_ATTRIBUTES 0x8B89 -#define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH 0x8B8A -#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT 0x8B8B -#define GL_SHADING_LANGUAGE_VERSION 0x8B8C -#define GL_CURRENT_PROGRAM 0x8B8D -#define GL_POINT_SPRITE_COORD_ORIGIN 0x8CA0 -#define GL_LOWER_LEFT 0x8CA1 -#define GL_UPPER_LEFT 0x8CA2 -#define GL_STENCIL_BACK_REF 0x8CA3 -#define GL_STENCIL_BACK_VALUE_MASK 0x8CA4 -#define GL_STENCIL_BACK_WRITEMASK 0x8CA5 -#define GL_VERTEX_PROGRAM_TWO_SIDE 0x8643 -#define GL_POINT_SPRITE 0x8861 -#define GL_COORD_REPLACE 0x8862 -#define GL_MAX_TEXTURE_COORDS 0x8871 -#define GL_PIXEL_PACK_BUFFER 0x88EB -#define GL_PIXEL_UNPACK_BUFFER 0x88EC -#define GL_PIXEL_PACK_BUFFER_BINDING 0x88ED -#define GL_PIXEL_UNPACK_BUFFER_BINDING 0x88EF -#define GL_FLOAT_MAT2x3 0x8B65 -#define GL_FLOAT_MAT2x4 0x8B66 -#define GL_FLOAT_MAT3x2 0x8B67 -#define GL_FLOAT_MAT3x4 0x8B68 -#define GL_FLOAT_MAT4x2 0x8B69 -#define GL_FLOAT_MAT4x3 0x8B6A -#define GL_SRGB 0x8C40 -#define GL_SRGB8 0x8C41 -#define GL_SRGB_ALPHA 0x8C42 -#define GL_SRGB8_ALPHA8 0x8C43 -#define GL_COMPRESSED_SRGB 0x8C48 -#define GL_COMPRESSED_SRGB_ALPHA 0x8C49 -#define GL_CURRENT_RASTER_SECONDARY_COLOR 0x845F -#define GL_SLUMINANCE_ALPHA 0x8C44 -#define GL_SLUMINANCE8_ALPHA8 0x8C45 -#define GL_SLUMINANCE 0x8C46 -#define GL_SLUMINANCE8 0x8C47 -#define GL_COMPRESSED_SLUMINANCE 0x8C4A -#define GL_COMPRESSED_SLUMINANCE_ALPHA 0x8C4B -#define GL_COMPARE_REF_TO_TEXTURE 0x884E -#define GL_CLIP_DISTANCE0 0x3000 -#define GL_CLIP_DISTANCE1 0x3001 -#define GL_CLIP_DISTANCE2 0x3002 -#define GL_CLIP_DISTANCE3 0x3003 -#define GL_CLIP_DISTANCE4 0x3004 -#define GL_CLIP_DISTANCE5 0x3005 -#define GL_CLIP_DISTANCE6 0x3006 -#define GL_CLIP_DISTANCE7 0x3007 -#define GL_MAX_CLIP_DISTANCES 0x0D32 -#define GL_MAJOR_VERSION 0x821B -#define GL_MINOR_VERSION 0x821C -#define GL_NUM_EXTENSIONS 0x821D -#define GL_CONTEXT_FLAGS 0x821E -#define GL_COMPRESSED_RED 0x8225 -#define GL_COMPRESSED_RG 0x8226 -#define GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT 0x00000001 -#define GL_RGBA32F 0x8814 -#define GL_RGB32F 0x8815 -#define GL_RGBA16F 0x881A -#define GL_RGB16F 0x881B -#define GL_VERTEX_ATTRIB_ARRAY_INTEGER 0x88FD -#define GL_MAX_ARRAY_TEXTURE_LAYERS 0x88FF -#define GL_MIN_PROGRAM_TEXEL_OFFSET 0x8904 -#define GL_MAX_PROGRAM_TEXEL_OFFSET 0x8905 -#define GL_CLAMP_READ_COLOR 0x891C -#define GL_FIXED_ONLY 0x891D -#define GL_MAX_VARYING_COMPONENTS 0x8B4B -#define GL_TEXTURE_1D_ARRAY 0x8C18 -#define GL_PROXY_TEXTURE_1D_ARRAY 0x8C19 -#define GL_TEXTURE_2D_ARRAY 0x8C1A -#define GL_PROXY_TEXTURE_2D_ARRAY 0x8C1B -#define GL_TEXTURE_BINDING_1D_ARRAY 0x8C1C -#define GL_TEXTURE_BINDING_2D_ARRAY 0x8C1D -#define GL_R11F_G11F_B10F 0x8C3A -#define GL_UNSIGNED_INT_10F_11F_11F_REV 0x8C3B -#define GL_RGB9_E5 0x8C3D -#define GL_UNSIGNED_INT_5_9_9_9_REV 0x8C3E -#define GL_TEXTURE_SHARED_SIZE 0x8C3F -#define GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH 0x8C76 -#define GL_TRANSFORM_FEEDBACK_BUFFER_MODE 0x8C7F -#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS 0x8C80 -#define GL_TRANSFORM_FEEDBACK_VARYINGS 0x8C83 -#define GL_TRANSFORM_FEEDBACK_BUFFER_START 0x8C84 -#define GL_TRANSFORM_FEEDBACK_BUFFER_SIZE 0x8C85 -#define GL_PRIMITIVES_GENERATED 0x8C87 -#define GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN 0x8C88 -#define GL_RASTERIZER_DISCARD 0x8C89 -#define GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS 0x8C8A -#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS 0x8C8B -#define GL_INTERLEAVED_ATTRIBS 0x8C8C -#define GL_SEPARATE_ATTRIBS 0x8C8D -#define GL_TRANSFORM_FEEDBACK_BUFFER 0x8C8E -#define GL_TRANSFORM_FEEDBACK_BUFFER_BINDING 0x8C8F -#define GL_RGBA32UI 0x8D70 -#define GL_RGB32UI 0x8D71 -#define GL_RGBA16UI 0x8D76 -#define GL_RGB16UI 0x8D77 -#define GL_RGBA8UI 0x8D7C -#define GL_RGB8UI 0x8D7D -#define GL_RGBA32I 0x8D82 -#define GL_RGB32I 0x8D83 -#define GL_RGBA16I 0x8D88 -#define GL_RGB16I 0x8D89 -#define GL_RGBA8I 0x8D8E -#define GL_RGB8I 0x8D8F -#define GL_RED_INTEGER 0x8D94 -#define GL_GREEN_INTEGER 0x8D95 -#define GL_BLUE_INTEGER 0x8D96 -#define GL_RGB_INTEGER 0x8D98 -#define GL_RGBA_INTEGER 0x8D99 -#define GL_BGR_INTEGER 0x8D9A -#define GL_BGRA_INTEGER 0x8D9B -#define GL_SAMPLER_1D_ARRAY 0x8DC0 -#define GL_SAMPLER_2D_ARRAY 0x8DC1 -#define GL_SAMPLER_1D_ARRAY_SHADOW 0x8DC3 -#define GL_SAMPLER_2D_ARRAY_SHADOW 0x8DC4 -#define GL_SAMPLER_CUBE_SHADOW 0x8DC5 -#define GL_UNSIGNED_INT_VEC2 0x8DC6 -#define GL_UNSIGNED_INT_VEC3 0x8DC7 -#define GL_UNSIGNED_INT_VEC4 0x8DC8 -#define GL_INT_SAMPLER_1D 0x8DC9 -#define GL_INT_SAMPLER_2D 0x8DCA -#define GL_INT_SAMPLER_3D 0x8DCB -#define GL_INT_SAMPLER_CUBE 0x8DCC -#define GL_INT_SAMPLER_1D_ARRAY 0x8DCE -#define GL_INT_SAMPLER_2D_ARRAY 0x8DCF -#define GL_UNSIGNED_INT_SAMPLER_1D 0x8DD1 -#define GL_UNSIGNED_INT_SAMPLER_2D 0x8DD2 -#define GL_UNSIGNED_INT_SAMPLER_3D 0x8DD3 -#define GL_UNSIGNED_INT_SAMPLER_CUBE 0x8DD4 -#define GL_UNSIGNED_INT_SAMPLER_1D_ARRAY 0x8DD6 -#define GL_UNSIGNED_INT_SAMPLER_2D_ARRAY 0x8DD7 -#define GL_QUERY_WAIT 0x8E13 -#define GL_QUERY_NO_WAIT 0x8E14 -#define GL_QUERY_BY_REGION_WAIT 0x8E15 -#define GL_QUERY_BY_REGION_NO_WAIT 0x8E16 -#define GL_BUFFER_ACCESS_FLAGS 0x911F -#define GL_BUFFER_MAP_LENGTH 0x9120 -#define GL_BUFFER_MAP_OFFSET 0x9121 -#define GL_DEPTH_COMPONENT32F 0x8CAC -#define GL_DEPTH32F_STENCIL8 0x8CAD -#define GL_FLOAT_32_UNSIGNED_INT_24_8_REV 0x8DAD -#define GL_INVALID_FRAMEBUFFER_OPERATION 0x0506 -#define GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING 0x8210 -#define GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE 0x8211 -#define GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE 0x8212 -#define GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE 0x8213 -#define GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE 0x8214 -#define GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE 0x8215 -#define GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE 0x8216 -#define GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE 0x8217 -#define GL_FRAMEBUFFER_DEFAULT 0x8218 -#define GL_FRAMEBUFFER_UNDEFINED 0x8219 -#define GL_DEPTH_STENCIL_ATTACHMENT 0x821A -#define GL_MAX_RENDERBUFFER_SIZE 0x84E8 -#define GL_DEPTH_STENCIL 0x84F9 -#define GL_UNSIGNED_INT_24_8 0x84FA -#define GL_DEPTH24_STENCIL8 0x88F0 -#define GL_TEXTURE_STENCIL_SIZE 0x88F1 -#define GL_TEXTURE_RED_TYPE 0x8C10 -#define GL_TEXTURE_GREEN_TYPE 0x8C11 -#define GL_TEXTURE_BLUE_TYPE 0x8C12 -#define GL_TEXTURE_ALPHA_TYPE 0x8C13 -#define GL_TEXTURE_DEPTH_TYPE 0x8C16 -#define GL_UNSIGNED_NORMALIZED 0x8C17 -#define GL_FRAMEBUFFER_BINDING 0x8CA6 -#define GL_DRAW_FRAMEBUFFER_BINDING 0x8CA6 -#define GL_RENDERBUFFER_BINDING 0x8CA7 -#define GL_READ_FRAMEBUFFER 0x8CA8 -#define GL_DRAW_FRAMEBUFFER 0x8CA9 -#define GL_READ_FRAMEBUFFER_BINDING 0x8CAA -#define GL_RENDERBUFFER_SAMPLES 0x8CAB -#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE 0x8CD0 -#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME 0x8CD1 -#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL 0x8CD2 -#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE 0x8CD3 -#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER 0x8CD4 -#define GL_FRAMEBUFFER_COMPLETE 0x8CD5 -#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT 0x8CD6 -#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT 0x8CD7 -#define GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER 0x8CDB -#define GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER 0x8CDC -#define GL_FRAMEBUFFER_UNSUPPORTED 0x8CDD -#define GL_MAX_COLOR_ATTACHMENTS 0x8CDF -#define GL_COLOR_ATTACHMENT0 0x8CE0 -#define GL_COLOR_ATTACHMENT1 0x8CE1 -#define GL_COLOR_ATTACHMENT2 0x8CE2 -#define GL_COLOR_ATTACHMENT3 0x8CE3 -#define GL_COLOR_ATTACHMENT4 0x8CE4 -#define GL_COLOR_ATTACHMENT5 0x8CE5 -#define GL_COLOR_ATTACHMENT6 0x8CE6 -#define GL_COLOR_ATTACHMENT7 0x8CE7 -#define GL_COLOR_ATTACHMENT8 0x8CE8 -#define GL_COLOR_ATTACHMENT9 0x8CE9 -#define GL_COLOR_ATTACHMENT10 0x8CEA -#define GL_COLOR_ATTACHMENT11 0x8CEB -#define GL_COLOR_ATTACHMENT12 0x8CEC -#define GL_COLOR_ATTACHMENT13 0x8CED -#define GL_COLOR_ATTACHMENT14 0x8CEE -#define GL_COLOR_ATTACHMENT15 0x8CEF -#define GL_COLOR_ATTACHMENT16 0x8CF0 -#define GL_COLOR_ATTACHMENT17 0x8CF1 -#define GL_COLOR_ATTACHMENT18 0x8CF2 -#define GL_COLOR_ATTACHMENT19 0x8CF3 -#define GL_COLOR_ATTACHMENT20 0x8CF4 -#define GL_COLOR_ATTACHMENT21 0x8CF5 -#define GL_COLOR_ATTACHMENT22 0x8CF6 -#define GL_COLOR_ATTACHMENT23 0x8CF7 -#define GL_COLOR_ATTACHMENT24 0x8CF8 -#define GL_COLOR_ATTACHMENT25 0x8CF9 -#define GL_COLOR_ATTACHMENT26 0x8CFA -#define GL_COLOR_ATTACHMENT27 0x8CFB -#define GL_COLOR_ATTACHMENT28 0x8CFC -#define GL_COLOR_ATTACHMENT29 0x8CFD -#define GL_COLOR_ATTACHMENT30 0x8CFE -#define GL_COLOR_ATTACHMENT31 0x8CFF -#define GL_DEPTH_ATTACHMENT 0x8D00 -#define GL_STENCIL_ATTACHMENT 0x8D20 -#define GL_FRAMEBUFFER 0x8D40 -#define GL_RENDERBUFFER 0x8D41 -#define GL_RENDERBUFFER_WIDTH 0x8D42 -#define GL_RENDERBUFFER_HEIGHT 0x8D43 -#define GL_RENDERBUFFER_INTERNAL_FORMAT 0x8D44 -#define GL_STENCIL_INDEX1 0x8D46 -#define GL_STENCIL_INDEX4 0x8D47 -#define GL_STENCIL_INDEX8 0x8D48 -#define GL_STENCIL_INDEX16 0x8D49 -#define GL_RENDERBUFFER_RED_SIZE 0x8D50 -#define GL_RENDERBUFFER_GREEN_SIZE 0x8D51 -#define GL_RENDERBUFFER_BLUE_SIZE 0x8D52 -#define GL_RENDERBUFFER_ALPHA_SIZE 0x8D53 -#define GL_RENDERBUFFER_DEPTH_SIZE 0x8D54 -#define GL_RENDERBUFFER_STENCIL_SIZE 0x8D55 -#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE 0x8D56 -#define GL_MAX_SAMPLES 0x8D57 -#define GL_INDEX 0x8222 -#define GL_TEXTURE_LUMINANCE_TYPE 0x8C14 -#define GL_TEXTURE_INTENSITY_TYPE 0x8C15 -#define GL_FRAMEBUFFER_SRGB 0x8DB9 -#define GL_HALF_FLOAT 0x140B -#define GL_MAP_READ_BIT 0x0001 -#define GL_MAP_WRITE_BIT 0x0002 -#define GL_MAP_INVALIDATE_RANGE_BIT 0x0004 -#define GL_MAP_INVALIDATE_BUFFER_BIT 0x0008 -#define GL_MAP_FLUSH_EXPLICIT_BIT 0x0010 -#define GL_MAP_UNSYNCHRONIZED_BIT 0x0020 -#define GL_COMPRESSED_RED_RGTC1 0x8DBB -#define GL_COMPRESSED_SIGNED_RED_RGTC1 0x8DBC -#define GL_COMPRESSED_RG_RGTC2 0x8DBD -#define GL_COMPRESSED_SIGNED_RG_RGTC2 0x8DBE -#define GL_RG 0x8227 -#define GL_RG_INTEGER 0x8228 -#define GL_R8 0x8229 -#define GL_R16 0x822A -#define GL_RG8 0x822B -#define GL_RG16 0x822C -#define GL_R16F 0x822D -#define GL_R32F 0x822E -#define GL_RG16F 0x822F -#define GL_RG32F 0x8230 -#define GL_R8I 0x8231 -#define GL_R8UI 0x8232 -#define GL_R16I 0x8233 -#define GL_R16UI 0x8234 -#define GL_R32I 0x8235 -#define GL_R32UI 0x8236 -#define GL_RG8I 0x8237 -#define GL_RG8UI 0x8238 -#define GL_RG16I 0x8239 -#define GL_RG16UI 0x823A -#define GL_RG32I 0x823B -#define GL_RG32UI 0x823C -#define GL_VERTEX_ARRAY_BINDING 0x85B5 -#define GL_CLAMP_VERTEX_COLOR 0x891A -#define GL_CLAMP_FRAGMENT_COLOR 0x891B -#define GL_ALPHA_INTEGER 0x8D97 -#define GL_SAMPLER_2D_RECT 0x8B63 -#define GL_SAMPLER_2D_RECT_SHADOW 0x8B64 -#define GL_SAMPLER_BUFFER 0x8DC2 -#define GL_INT_SAMPLER_2D_RECT 0x8DCD -#define GL_INT_SAMPLER_BUFFER 0x8DD0 -#define GL_UNSIGNED_INT_SAMPLER_2D_RECT 0x8DD5 -#define GL_UNSIGNED_INT_SAMPLER_BUFFER 0x8DD8 -#define GL_TEXTURE_BUFFER 0x8C2A -#define GL_MAX_TEXTURE_BUFFER_SIZE 0x8C2B -#define GL_TEXTURE_BINDING_BUFFER 0x8C2C -#define GL_TEXTURE_BUFFER_DATA_STORE_BINDING 0x8C2D -#define GL_TEXTURE_RECTANGLE 0x84F5 -#define GL_TEXTURE_BINDING_RECTANGLE 0x84F6 -#define GL_PROXY_TEXTURE_RECTANGLE 0x84F7 -#define GL_MAX_RECTANGLE_TEXTURE_SIZE 0x84F8 -#define GL_R8_SNORM 0x8F94 -#define GL_RG8_SNORM 0x8F95 -#define GL_RGB8_SNORM 0x8F96 -#define GL_RGBA8_SNORM 0x8F97 -#define GL_R16_SNORM 0x8F98 -#define GL_RG16_SNORM 0x8F99 -#define GL_RGB16_SNORM 0x8F9A -#define GL_RGBA16_SNORM 0x8F9B -#define GL_SIGNED_NORMALIZED 0x8F9C -#define GL_PRIMITIVE_RESTART 0x8F9D -#define GL_PRIMITIVE_RESTART_INDEX 0x8F9E -#define GL_COPY_READ_BUFFER 0x8F36 -#define GL_COPY_WRITE_BUFFER 0x8F37 -#define GL_UNIFORM_BUFFER 0x8A11 -#define GL_UNIFORM_BUFFER_BINDING 0x8A28 -#define GL_UNIFORM_BUFFER_START 0x8A29 -#define GL_UNIFORM_BUFFER_SIZE 0x8A2A -#define GL_MAX_VERTEX_UNIFORM_BLOCKS 0x8A2B -#define GL_MAX_GEOMETRY_UNIFORM_BLOCKS 0x8A2C -#define GL_MAX_FRAGMENT_UNIFORM_BLOCKS 0x8A2D -#define GL_MAX_COMBINED_UNIFORM_BLOCKS 0x8A2E -#define GL_MAX_UNIFORM_BUFFER_BINDINGS 0x8A2F -#define GL_MAX_UNIFORM_BLOCK_SIZE 0x8A30 -#define GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS 0x8A31 -#define GL_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS 0x8A32 -#define GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS 0x8A33 -#define GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT 0x8A34 -#define GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH 0x8A35 -#define GL_ACTIVE_UNIFORM_BLOCKS 0x8A36 -#define GL_UNIFORM_TYPE 0x8A37 -#define GL_UNIFORM_SIZE 0x8A38 -#define GL_UNIFORM_NAME_LENGTH 0x8A39 -#define GL_UNIFORM_BLOCK_INDEX 0x8A3A -#define GL_UNIFORM_OFFSET 0x8A3B -#define GL_UNIFORM_ARRAY_STRIDE 0x8A3C -#define GL_UNIFORM_MATRIX_STRIDE 0x8A3D -#define GL_UNIFORM_IS_ROW_MAJOR 0x8A3E -#define GL_UNIFORM_BLOCK_BINDING 0x8A3F -#define GL_UNIFORM_BLOCK_DATA_SIZE 0x8A40 -#define GL_UNIFORM_BLOCK_NAME_LENGTH 0x8A41 -#define GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS 0x8A42 -#define GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES 0x8A43 -#define GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER 0x8A44 -#define GL_UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER 0x8A45 -#define GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER 0x8A46 -#define GL_INVALID_INDEX 0xFFFFFFFF -#define GL_CONTEXT_CORE_PROFILE_BIT 0x00000001 -#define GL_CONTEXT_COMPATIBILITY_PROFILE_BIT 0x00000002 -#define GL_LINES_ADJACENCY 0x000A -#define GL_LINE_STRIP_ADJACENCY 0x000B -#define GL_TRIANGLES_ADJACENCY 0x000C -#define GL_TRIANGLE_STRIP_ADJACENCY 0x000D -#define GL_PROGRAM_POINT_SIZE 0x8642 -#define GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS 0x8C29 -#define GL_FRAMEBUFFER_ATTACHMENT_LAYERED 0x8DA7 -#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS 0x8DA8 -#define GL_GEOMETRY_SHADER 0x8DD9 -#define GL_GEOMETRY_VERTICES_OUT 0x8916 -#define GL_GEOMETRY_INPUT_TYPE 0x8917 -#define GL_GEOMETRY_OUTPUT_TYPE 0x8918 -#define GL_MAX_GEOMETRY_UNIFORM_COMPONENTS 0x8DDF -#define GL_MAX_GEOMETRY_OUTPUT_VERTICES 0x8DE0 -#define GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS 0x8DE1 -#define GL_MAX_VERTEX_OUTPUT_COMPONENTS 0x9122 -#define GL_MAX_GEOMETRY_INPUT_COMPONENTS 0x9123 -#define GL_MAX_GEOMETRY_OUTPUT_COMPONENTS 0x9124 -#define GL_MAX_FRAGMENT_INPUT_COMPONENTS 0x9125 -#define GL_CONTEXT_PROFILE_MASK 0x9126 -#define GL_DEPTH_CLAMP 0x864F -#define GL_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION 0x8E4C -#define GL_FIRST_VERTEX_CONVENTION 0x8E4D -#define GL_LAST_VERTEX_CONVENTION 0x8E4E -#define GL_PROVOKING_VERTEX 0x8E4F -#define GL_TEXTURE_CUBE_MAP_SEAMLESS 0x884F -#define GL_MAX_SERVER_WAIT_TIMEOUT 0x9111 -#define GL_OBJECT_TYPE 0x9112 -#define GL_SYNC_CONDITION 0x9113 -#define GL_SYNC_STATUS 0x9114 -#define GL_SYNC_FLAGS 0x9115 -#define GL_SYNC_FENCE 0x9116 -#define GL_SYNC_GPU_COMMANDS_COMPLETE 0x9117 -#define GL_UNSIGNALED 0x9118 -#define GL_SIGNALED 0x9119 -#define GL_ALREADY_SIGNALED 0x911A -#define GL_TIMEOUT_EXPIRED 0x911B -#define GL_CONDITION_SATISFIED 0x911C -#define GL_WAIT_FAILED 0x911D -#define GL_TIMEOUT_IGNORED 0xFFFFFFFFFFFFFFFF -#define GL_SYNC_FLUSH_COMMANDS_BIT 0x00000001 -#define GL_SAMPLE_POSITION 0x8E50 -#define GL_SAMPLE_MASK 0x8E51 -#define GL_SAMPLE_MASK_VALUE 0x8E52 -#define GL_MAX_SAMPLE_MASK_WORDS 0x8E59 -#define GL_TEXTURE_2D_MULTISAMPLE 0x9100 -#define GL_PROXY_TEXTURE_2D_MULTISAMPLE 0x9101 -#define GL_TEXTURE_2D_MULTISAMPLE_ARRAY 0x9102 -#define GL_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY 0x9103 -#define GL_TEXTURE_BINDING_2D_MULTISAMPLE 0x9104 -#define GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY 0x9105 -#define GL_TEXTURE_SAMPLES 0x9106 -#define GL_TEXTURE_FIXED_SAMPLE_LOCATIONS 0x9107 -#define GL_SAMPLER_2D_MULTISAMPLE 0x9108 -#define GL_INT_SAMPLER_2D_MULTISAMPLE 0x9109 -#define GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE 0x910A -#define GL_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910B -#define GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910C -#define GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910D -#define GL_MAX_COLOR_TEXTURE_SAMPLES 0x910E -#define GL_MAX_DEPTH_TEXTURE_SAMPLES 0x910F -#define GL_MAX_INTEGER_SAMPLES 0x9110 -#ifndef GL_VERSION_1_0 -#define GL_VERSION_1_0 1 -GLAPI int GLAD_GL_VERSION_1_0; -typedef void (APIENTRYP PFNGLCULLFACEPROC)(GLenum mode); -GLAPI PFNGLCULLFACEPROC glad_glCullFace; -#define glCullFace glad_glCullFace -typedef void (APIENTRYP PFNGLFRONTFACEPROC)(GLenum mode); -GLAPI PFNGLFRONTFACEPROC glad_glFrontFace; -#define glFrontFace glad_glFrontFace -typedef void (APIENTRYP PFNGLHINTPROC)(GLenum target, GLenum mode); -GLAPI PFNGLHINTPROC glad_glHint; -#define glHint glad_glHint -typedef void (APIENTRYP PFNGLLINEWIDTHPROC)(GLfloat width); -GLAPI PFNGLLINEWIDTHPROC glad_glLineWidth; -#define glLineWidth glad_glLineWidth -typedef void (APIENTRYP PFNGLPOINTSIZEPROC)(GLfloat size); -GLAPI PFNGLPOINTSIZEPROC glad_glPointSize; -#define glPointSize glad_glPointSize -typedef void (APIENTRYP PFNGLPOLYGONMODEPROC)(GLenum face, GLenum mode); -GLAPI PFNGLPOLYGONMODEPROC glad_glPolygonMode; -#define glPolygonMode glad_glPolygonMode -typedef void (APIENTRYP PFNGLSCISSORPROC)(GLint x, GLint y, GLsizei width, GLsizei height); -GLAPI PFNGLSCISSORPROC glad_glScissor; -#define glScissor glad_glScissor -typedef void (APIENTRYP PFNGLTEXPARAMETERFPROC)(GLenum target, GLenum pname, GLfloat param); -GLAPI PFNGLTEXPARAMETERFPROC glad_glTexParameterf; -#define glTexParameterf glad_glTexParameterf -typedef void (APIENTRYP PFNGLTEXPARAMETERFVPROC)(GLenum target, GLenum pname, const GLfloat *params); -GLAPI PFNGLTEXPARAMETERFVPROC glad_glTexParameterfv; -#define glTexParameterfv glad_glTexParameterfv -typedef void (APIENTRYP PFNGLTEXPARAMETERIPROC)(GLenum target, GLenum pname, GLint param); -GLAPI PFNGLTEXPARAMETERIPROC glad_glTexParameteri; -#define glTexParameteri glad_glTexParameteri -typedef void (APIENTRYP PFNGLTEXPARAMETERIVPROC)(GLenum target, GLenum pname, const GLint *params); -GLAPI PFNGLTEXPARAMETERIVPROC glad_glTexParameteriv; -#define glTexParameteriv glad_glTexParameteriv -typedef void (APIENTRYP PFNGLTEXIMAGE1DPROC)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void *pixels); -GLAPI PFNGLTEXIMAGE1DPROC glad_glTexImage1D; -#define glTexImage1D glad_glTexImage1D -typedef void (APIENTRYP PFNGLTEXIMAGE2DPROC)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels); -GLAPI PFNGLTEXIMAGE2DPROC glad_glTexImage2D; -#define glTexImage2D glad_glTexImage2D -typedef void (APIENTRYP PFNGLDRAWBUFFERPROC)(GLenum buf); -GLAPI PFNGLDRAWBUFFERPROC glad_glDrawBuffer; -#define glDrawBuffer glad_glDrawBuffer -typedef void (APIENTRYP PFNGLCLEARPROC)(GLbitfield mask); -GLAPI PFNGLCLEARPROC glad_glClear; -#define glClear glad_glClear -typedef void (APIENTRYP PFNGLCLEARCOLORPROC)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); -GLAPI PFNGLCLEARCOLORPROC glad_glClearColor; -#define glClearColor glad_glClearColor -typedef void (APIENTRYP PFNGLCLEARSTENCILPROC)(GLint s); -GLAPI PFNGLCLEARSTENCILPROC glad_glClearStencil; -#define glClearStencil glad_glClearStencil -typedef void (APIENTRYP PFNGLCLEARDEPTHPROC)(GLdouble depth); -GLAPI PFNGLCLEARDEPTHPROC glad_glClearDepth; -#define glClearDepth glad_glClearDepth -typedef void (APIENTRYP PFNGLSTENCILMASKPROC)(GLuint mask); -GLAPI PFNGLSTENCILMASKPROC glad_glStencilMask; -#define glStencilMask glad_glStencilMask -typedef void (APIENTRYP PFNGLCOLORMASKPROC)(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha); -GLAPI PFNGLCOLORMASKPROC glad_glColorMask; -#define glColorMask glad_glColorMask -typedef void (APIENTRYP PFNGLDEPTHMASKPROC)(GLboolean flag); -GLAPI PFNGLDEPTHMASKPROC glad_glDepthMask; -#define glDepthMask glad_glDepthMask -typedef void (APIENTRYP PFNGLDISABLEPROC)(GLenum cap); -GLAPI PFNGLDISABLEPROC glad_glDisable; -#define glDisable glad_glDisable -typedef void (APIENTRYP PFNGLENABLEPROC)(GLenum cap); -GLAPI PFNGLENABLEPROC glad_glEnable; -#define glEnable glad_glEnable -typedef void (APIENTRYP PFNGLFINISHPROC)(); -GLAPI PFNGLFINISHPROC glad_glFinish; -#define glFinish glad_glFinish -typedef void (APIENTRYP PFNGLFLUSHPROC)(); -GLAPI PFNGLFLUSHPROC glad_glFlush; -#define glFlush glad_glFlush -typedef void (APIENTRYP PFNGLBLENDFUNCPROC)(GLenum sfactor, GLenum dfactor); -GLAPI PFNGLBLENDFUNCPROC glad_glBlendFunc; -#define glBlendFunc glad_glBlendFunc -typedef void (APIENTRYP PFNGLLOGICOPPROC)(GLenum opcode); -GLAPI PFNGLLOGICOPPROC glad_glLogicOp; -#define glLogicOp glad_glLogicOp -typedef void (APIENTRYP PFNGLSTENCILFUNCPROC)(GLenum func, GLint ref, GLuint mask); -GLAPI PFNGLSTENCILFUNCPROC glad_glStencilFunc; -#define glStencilFunc glad_glStencilFunc -typedef void (APIENTRYP PFNGLSTENCILOPPROC)(GLenum fail, GLenum zfail, GLenum zpass); -GLAPI PFNGLSTENCILOPPROC glad_glStencilOp; -#define glStencilOp glad_glStencilOp -typedef void (APIENTRYP PFNGLDEPTHFUNCPROC)(GLenum func); -GLAPI PFNGLDEPTHFUNCPROC glad_glDepthFunc; -#define glDepthFunc glad_glDepthFunc -typedef void (APIENTRYP PFNGLPIXELSTOREFPROC)(GLenum pname, GLfloat param); -GLAPI PFNGLPIXELSTOREFPROC glad_glPixelStoref; -#define glPixelStoref glad_glPixelStoref -typedef void (APIENTRYP PFNGLPIXELSTOREIPROC)(GLenum pname, GLint param); -GLAPI PFNGLPIXELSTOREIPROC glad_glPixelStorei; -#define glPixelStorei glad_glPixelStorei -typedef void (APIENTRYP PFNGLREADBUFFERPROC)(GLenum src); -GLAPI PFNGLREADBUFFERPROC glad_glReadBuffer; -#define glReadBuffer glad_glReadBuffer -typedef void (APIENTRYP PFNGLREADPIXELSPROC)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels); -GLAPI PFNGLREADPIXELSPROC glad_glReadPixels; -#define glReadPixels glad_glReadPixels -typedef void (APIENTRYP PFNGLGETBOOLEANVPROC)(GLenum pname, GLboolean *data); -GLAPI PFNGLGETBOOLEANVPROC glad_glGetBooleanv; -#define glGetBooleanv glad_glGetBooleanv -typedef void (APIENTRYP PFNGLGETDOUBLEVPROC)(GLenum pname, GLdouble *data); -GLAPI PFNGLGETDOUBLEVPROC glad_glGetDoublev; -#define glGetDoublev glad_glGetDoublev -typedef GLenum (APIENTRYP PFNGLGETERRORPROC)(); -GLAPI PFNGLGETERRORPROC glad_glGetError; -#define glGetError glad_glGetError -typedef void (APIENTRYP PFNGLGETFLOATVPROC)(GLenum pname, GLfloat *data); -GLAPI PFNGLGETFLOATVPROC glad_glGetFloatv; -#define glGetFloatv glad_glGetFloatv -typedef void (APIENTRYP PFNGLGETINTEGERVPROC)(GLenum pname, GLint *data); -GLAPI PFNGLGETINTEGERVPROC glad_glGetIntegerv; -#define glGetIntegerv glad_glGetIntegerv -typedef const GLubyte * (APIENTRYP PFNGLGETSTRINGPROC)(GLenum name); -GLAPI PFNGLGETSTRINGPROC glad_glGetString; -#define glGetString glad_glGetString -typedef void (APIENTRYP PFNGLGETTEXIMAGEPROC)(GLenum target, GLint level, GLenum format, GLenum type, void *pixels); -GLAPI PFNGLGETTEXIMAGEPROC glad_glGetTexImage; -#define glGetTexImage glad_glGetTexImage -typedef void (APIENTRYP PFNGLGETTEXPARAMETERFVPROC)(GLenum target, GLenum pname, GLfloat *params); -GLAPI PFNGLGETTEXPARAMETERFVPROC glad_glGetTexParameterfv; -#define glGetTexParameterfv glad_glGetTexParameterfv -typedef void (APIENTRYP PFNGLGETTEXPARAMETERIVPROC)(GLenum target, GLenum pname, GLint *params); -GLAPI PFNGLGETTEXPARAMETERIVPROC glad_glGetTexParameteriv; -#define glGetTexParameteriv glad_glGetTexParameteriv -typedef void (APIENTRYP PFNGLGETTEXLEVELPARAMETERFVPROC)(GLenum target, GLint level, GLenum pname, GLfloat *params); -GLAPI PFNGLGETTEXLEVELPARAMETERFVPROC glad_glGetTexLevelParameterfv; -#define glGetTexLevelParameterfv glad_glGetTexLevelParameterfv -typedef void (APIENTRYP PFNGLGETTEXLEVELPARAMETERIVPROC)(GLenum target, GLint level, GLenum pname, GLint *params); -GLAPI PFNGLGETTEXLEVELPARAMETERIVPROC glad_glGetTexLevelParameteriv; -#define glGetTexLevelParameteriv glad_glGetTexLevelParameteriv -typedef GLboolean (APIENTRYP PFNGLISENABLEDPROC)(GLenum cap); -GLAPI PFNGLISENABLEDPROC glad_glIsEnabled; -#define glIsEnabled glad_glIsEnabled -typedef void (APIENTRYP PFNGLDEPTHRANGEPROC)(GLdouble near, GLdouble far); -GLAPI PFNGLDEPTHRANGEPROC glad_glDepthRange; -#define glDepthRange glad_glDepthRange -typedef void (APIENTRYP PFNGLVIEWPORTPROC)(GLint x, GLint y, GLsizei width, GLsizei height); -GLAPI PFNGLVIEWPORTPROC glad_glViewport; -#define glViewport glad_glViewport -typedef void (APIENTRYP PFNGLNEWLISTPROC)(GLuint list, GLenum mode); -GLAPI PFNGLNEWLISTPROC glad_glNewList; -#define glNewList glad_glNewList -typedef void (APIENTRYP PFNGLENDLISTPROC)(); -GLAPI PFNGLENDLISTPROC glad_glEndList; -#define glEndList glad_glEndList -typedef void (APIENTRYP PFNGLCALLLISTPROC)(GLuint list); -GLAPI PFNGLCALLLISTPROC glad_glCallList; -#define glCallList glad_glCallList -typedef void (APIENTRYP PFNGLCALLLISTSPROC)(GLsizei n, GLenum type, const void *lists); -GLAPI PFNGLCALLLISTSPROC glad_glCallLists; -#define glCallLists glad_glCallLists -typedef void (APIENTRYP PFNGLDELETELISTSPROC)(GLuint list, GLsizei range); -GLAPI PFNGLDELETELISTSPROC glad_glDeleteLists; -#define glDeleteLists glad_glDeleteLists -typedef GLuint (APIENTRYP PFNGLGENLISTSPROC)(GLsizei range); -GLAPI PFNGLGENLISTSPROC glad_glGenLists; -#define glGenLists glad_glGenLists -typedef void (APIENTRYP PFNGLLISTBASEPROC)(GLuint base); -GLAPI PFNGLLISTBASEPROC glad_glListBase; -#define glListBase glad_glListBase -typedef void (APIENTRYP PFNGLBEGINPROC)(GLenum mode); -GLAPI PFNGLBEGINPROC glad_glBegin; -#define glBegin glad_glBegin -typedef void (APIENTRYP PFNGLBITMAPPROC)(GLsizei width, GLsizei height, GLfloat xorig, GLfloat yorig, GLfloat xmove, GLfloat ymove, const GLubyte *bitmap); -GLAPI PFNGLBITMAPPROC glad_glBitmap; -#define glBitmap glad_glBitmap -typedef void (APIENTRYP PFNGLCOLOR3BPROC)(GLbyte red, GLbyte green, GLbyte blue); -GLAPI PFNGLCOLOR3BPROC glad_glColor3b; -#define glColor3b glad_glColor3b -typedef void (APIENTRYP PFNGLCOLOR3BVPROC)(const GLbyte *v); -GLAPI PFNGLCOLOR3BVPROC glad_glColor3bv; -#define glColor3bv glad_glColor3bv -typedef void (APIENTRYP PFNGLCOLOR3DPROC)(GLdouble red, GLdouble green, GLdouble blue); -GLAPI PFNGLCOLOR3DPROC glad_glColor3d; -#define glColor3d glad_glColor3d -typedef void (APIENTRYP PFNGLCOLOR3DVPROC)(const GLdouble *v); -GLAPI PFNGLCOLOR3DVPROC glad_glColor3dv; -#define glColor3dv glad_glColor3dv -typedef void (APIENTRYP PFNGLCOLOR3FPROC)(GLfloat red, GLfloat green, GLfloat blue); -GLAPI PFNGLCOLOR3FPROC glad_glColor3f; -#define glColor3f glad_glColor3f -typedef void (APIENTRYP PFNGLCOLOR3FVPROC)(const GLfloat *v); -GLAPI PFNGLCOLOR3FVPROC glad_glColor3fv; -#define glColor3fv glad_glColor3fv -typedef void (APIENTRYP PFNGLCOLOR3IPROC)(GLint red, GLint green, GLint blue); -GLAPI PFNGLCOLOR3IPROC glad_glColor3i; -#define glColor3i glad_glColor3i -typedef void (APIENTRYP PFNGLCOLOR3IVPROC)(const GLint *v); -GLAPI PFNGLCOLOR3IVPROC glad_glColor3iv; -#define glColor3iv glad_glColor3iv -typedef void (APIENTRYP PFNGLCOLOR3SPROC)(GLshort red, GLshort green, GLshort blue); -GLAPI PFNGLCOLOR3SPROC glad_glColor3s; -#define glColor3s glad_glColor3s -typedef void (APIENTRYP PFNGLCOLOR3SVPROC)(const GLshort *v); -GLAPI PFNGLCOLOR3SVPROC glad_glColor3sv; -#define glColor3sv glad_glColor3sv -typedef void (APIENTRYP PFNGLCOLOR3UBPROC)(GLubyte red, GLubyte green, GLubyte blue); -GLAPI PFNGLCOLOR3UBPROC glad_glColor3ub; -#define glColor3ub glad_glColor3ub -typedef void (APIENTRYP PFNGLCOLOR3UBVPROC)(const GLubyte *v); -GLAPI PFNGLCOLOR3UBVPROC glad_glColor3ubv; -#define glColor3ubv glad_glColor3ubv -typedef void (APIENTRYP PFNGLCOLOR3UIPROC)(GLuint red, GLuint green, GLuint blue); -GLAPI PFNGLCOLOR3UIPROC glad_glColor3ui; -#define glColor3ui glad_glColor3ui -typedef void (APIENTRYP PFNGLCOLOR3UIVPROC)(const GLuint *v); -GLAPI PFNGLCOLOR3UIVPROC glad_glColor3uiv; -#define glColor3uiv glad_glColor3uiv -typedef void (APIENTRYP PFNGLCOLOR3USPROC)(GLushort red, GLushort green, GLushort blue); -GLAPI PFNGLCOLOR3USPROC glad_glColor3us; -#define glColor3us glad_glColor3us -typedef void (APIENTRYP PFNGLCOLOR3USVPROC)(const GLushort *v); -GLAPI PFNGLCOLOR3USVPROC glad_glColor3usv; -#define glColor3usv glad_glColor3usv -typedef void (APIENTRYP PFNGLCOLOR4BPROC)(GLbyte red, GLbyte green, GLbyte blue, GLbyte alpha); -GLAPI PFNGLCOLOR4BPROC glad_glColor4b; -#define glColor4b glad_glColor4b -typedef void (APIENTRYP PFNGLCOLOR4BVPROC)(const GLbyte *v); -GLAPI PFNGLCOLOR4BVPROC glad_glColor4bv; -#define glColor4bv glad_glColor4bv -typedef void (APIENTRYP PFNGLCOLOR4DPROC)(GLdouble red, GLdouble green, GLdouble blue, GLdouble alpha); -GLAPI PFNGLCOLOR4DPROC glad_glColor4d; -#define glColor4d glad_glColor4d -typedef void (APIENTRYP PFNGLCOLOR4DVPROC)(const GLdouble *v); -GLAPI PFNGLCOLOR4DVPROC glad_glColor4dv; -#define glColor4dv glad_glColor4dv -typedef void (APIENTRYP PFNGLCOLOR4FPROC)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); -GLAPI PFNGLCOLOR4FPROC glad_glColor4f; -#define glColor4f glad_glColor4f -typedef void (APIENTRYP PFNGLCOLOR4FVPROC)(const GLfloat *v); -GLAPI PFNGLCOLOR4FVPROC glad_glColor4fv; -#define glColor4fv glad_glColor4fv -typedef void (APIENTRYP PFNGLCOLOR4IPROC)(GLint red, GLint green, GLint blue, GLint alpha); -GLAPI PFNGLCOLOR4IPROC glad_glColor4i; -#define glColor4i glad_glColor4i -typedef void (APIENTRYP PFNGLCOLOR4IVPROC)(const GLint *v); -GLAPI PFNGLCOLOR4IVPROC glad_glColor4iv; -#define glColor4iv glad_glColor4iv -typedef void (APIENTRYP PFNGLCOLOR4SPROC)(GLshort red, GLshort green, GLshort blue, GLshort alpha); -GLAPI PFNGLCOLOR4SPROC glad_glColor4s; -#define glColor4s glad_glColor4s -typedef void (APIENTRYP PFNGLCOLOR4SVPROC)(const GLshort *v); -GLAPI PFNGLCOLOR4SVPROC glad_glColor4sv; -#define glColor4sv glad_glColor4sv -typedef void (APIENTRYP PFNGLCOLOR4UBPROC)(GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha); -GLAPI PFNGLCOLOR4UBPROC glad_glColor4ub; -#define glColor4ub glad_glColor4ub -typedef void (APIENTRYP PFNGLCOLOR4UBVPROC)(const GLubyte *v); -GLAPI PFNGLCOLOR4UBVPROC glad_glColor4ubv; -#define glColor4ubv glad_glColor4ubv -typedef void (APIENTRYP PFNGLCOLOR4UIPROC)(GLuint red, GLuint green, GLuint blue, GLuint alpha); -GLAPI PFNGLCOLOR4UIPROC glad_glColor4ui; -#define glColor4ui glad_glColor4ui -typedef void (APIENTRYP PFNGLCOLOR4UIVPROC)(const GLuint *v); -GLAPI PFNGLCOLOR4UIVPROC glad_glColor4uiv; -#define glColor4uiv glad_glColor4uiv -typedef void (APIENTRYP PFNGLCOLOR4USPROC)(GLushort red, GLushort green, GLushort blue, GLushort alpha); -GLAPI PFNGLCOLOR4USPROC glad_glColor4us; -#define glColor4us glad_glColor4us -typedef void (APIENTRYP PFNGLCOLOR4USVPROC)(const GLushort *v); -GLAPI PFNGLCOLOR4USVPROC glad_glColor4usv; -#define glColor4usv glad_glColor4usv -typedef void (APIENTRYP PFNGLEDGEFLAGPROC)(GLboolean flag); -GLAPI PFNGLEDGEFLAGPROC glad_glEdgeFlag; -#define glEdgeFlag glad_glEdgeFlag -typedef void (APIENTRYP PFNGLEDGEFLAGVPROC)(const GLboolean *flag); -GLAPI PFNGLEDGEFLAGVPROC glad_glEdgeFlagv; -#define glEdgeFlagv glad_glEdgeFlagv -typedef void (APIENTRYP PFNGLENDPROC)(); -GLAPI PFNGLENDPROC glad_glEnd; -#define glEnd glad_glEnd -typedef void (APIENTRYP PFNGLINDEXDPROC)(GLdouble c); -GLAPI PFNGLINDEXDPROC glad_glIndexd; -#define glIndexd glad_glIndexd -typedef void (APIENTRYP PFNGLINDEXDVPROC)(const GLdouble *c); -GLAPI PFNGLINDEXDVPROC glad_glIndexdv; -#define glIndexdv glad_glIndexdv -typedef void (APIENTRYP PFNGLINDEXFPROC)(GLfloat c); -GLAPI PFNGLINDEXFPROC glad_glIndexf; -#define glIndexf glad_glIndexf -typedef void (APIENTRYP PFNGLINDEXFVPROC)(const GLfloat *c); -GLAPI PFNGLINDEXFVPROC glad_glIndexfv; -#define glIndexfv glad_glIndexfv -typedef void (APIENTRYP PFNGLINDEXIPROC)(GLint c); -GLAPI PFNGLINDEXIPROC glad_glIndexi; -#define glIndexi glad_glIndexi -typedef void (APIENTRYP PFNGLINDEXIVPROC)(const GLint *c); -GLAPI PFNGLINDEXIVPROC glad_glIndexiv; -#define glIndexiv glad_glIndexiv -typedef void (APIENTRYP PFNGLINDEXSPROC)(GLshort c); -GLAPI PFNGLINDEXSPROC glad_glIndexs; -#define glIndexs glad_glIndexs -typedef void (APIENTRYP PFNGLINDEXSVPROC)(const GLshort *c); -GLAPI PFNGLINDEXSVPROC glad_glIndexsv; -#define glIndexsv glad_glIndexsv -typedef void (APIENTRYP PFNGLNORMAL3BPROC)(GLbyte nx, GLbyte ny, GLbyte nz); -GLAPI PFNGLNORMAL3BPROC glad_glNormal3b; -#define glNormal3b glad_glNormal3b -typedef void (APIENTRYP PFNGLNORMAL3BVPROC)(const GLbyte *v); -GLAPI PFNGLNORMAL3BVPROC glad_glNormal3bv; -#define glNormal3bv glad_glNormal3bv -typedef void (APIENTRYP PFNGLNORMAL3DPROC)(GLdouble nx, GLdouble ny, GLdouble nz); -GLAPI PFNGLNORMAL3DPROC glad_glNormal3d; -#define glNormal3d glad_glNormal3d -typedef void (APIENTRYP PFNGLNORMAL3DVPROC)(const GLdouble *v); -GLAPI PFNGLNORMAL3DVPROC glad_glNormal3dv; -#define glNormal3dv glad_glNormal3dv -typedef void (APIENTRYP PFNGLNORMAL3FPROC)(GLfloat nx, GLfloat ny, GLfloat nz); -GLAPI PFNGLNORMAL3FPROC glad_glNormal3f; -#define glNormal3f glad_glNormal3f -typedef void (APIENTRYP PFNGLNORMAL3FVPROC)(const GLfloat *v); -GLAPI PFNGLNORMAL3FVPROC glad_glNormal3fv; -#define glNormal3fv glad_glNormal3fv -typedef void (APIENTRYP PFNGLNORMAL3IPROC)(GLint nx, GLint ny, GLint nz); -GLAPI PFNGLNORMAL3IPROC glad_glNormal3i; -#define glNormal3i glad_glNormal3i -typedef void (APIENTRYP PFNGLNORMAL3IVPROC)(const GLint *v); -GLAPI PFNGLNORMAL3IVPROC glad_glNormal3iv; -#define glNormal3iv glad_glNormal3iv -typedef void (APIENTRYP PFNGLNORMAL3SPROC)(GLshort nx, GLshort ny, GLshort nz); -GLAPI PFNGLNORMAL3SPROC glad_glNormal3s; -#define glNormal3s glad_glNormal3s -typedef void (APIENTRYP PFNGLNORMAL3SVPROC)(const GLshort *v); -GLAPI PFNGLNORMAL3SVPROC glad_glNormal3sv; -#define glNormal3sv glad_glNormal3sv -typedef void (APIENTRYP PFNGLRASTERPOS2DPROC)(GLdouble x, GLdouble y); -GLAPI PFNGLRASTERPOS2DPROC glad_glRasterPos2d; -#define glRasterPos2d glad_glRasterPos2d -typedef void (APIENTRYP PFNGLRASTERPOS2DVPROC)(const GLdouble *v); -GLAPI PFNGLRASTERPOS2DVPROC glad_glRasterPos2dv; -#define glRasterPos2dv glad_glRasterPos2dv -typedef void (APIENTRYP PFNGLRASTERPOS2FPROC)(GLfloat x, GLfloat y); -GLAPI PFNGLRASTERPOS2FPROC glad_glRasterPos2f; -#define glRasterPos2f glad_glRasterPos2f -typedef void (APIENTRYP PFNGLRASTERPOS2FVPROC)(const GLfloat *v); -GLAPI PFNGLRASTERPOS2FVPROC glad_glRasterPos2fv; -#define glRasterPos2fv glad_glRasterPos2fv -typedef void (APIENTRYP PFNGLRASTERPOS2IPROC)(GLint x, GLint y); -GLAPI PFNGLRASTERPOS2IPROC glad_glRasterPos2i; -#define glRasterPos2i glad_glRasterPos2i -typedef void (APIENTRYP PFNGLRASTERPOS2IVPROC)(const GLint *v); -GLAPI PFNGLRASTERPOS2IVPROC glad_glRasterPos2iv; -#define glRasterPos2iv glad_glRasterPos2iv -typedef void (APIENTRYP PFNGLRASTERPOS2SPROC)(GLshort x, GLshort y); -GLAPI PFNGLRASTERPOS2SPROC glad_glRasterPos2s; -#define glRasterPos2s glad_glRasterPos2s -typedef void (APIENTRYP PFNGLRASTERPOS2SVPROC)(const GLshort *v); -GLAPI PFNGLRASTERPOS2SVPROC glad_glRasterPos2sv; -#define glRasterPos2sv glad_glRasterPos2sv -typedef void (APIENTRYP PFNGLRASTERPOS3DPROC)(GLdouble x, GLdouble y, GLdouble z); -GLAPI PFNGLRASTERPOS3DPROC glad_glRasterPos3d; -#define glRasterPos3d glad_glRasterPos3d -typedef void (APIENTRYP PFNGLRASTERPOS3DVPROC)(const GLdouble *v); -GLAPI PFNGLRASTERPOS3DVPROC glad_glRasterPos3dv; -#define glRasterPos3dv glad_glRasterPos3dv -typedef void (APIENTRYP PFNGLRASTERPOS3FPROC)(GLfloat x, GLfloat y, GLfloat z); -GLAPI PFNGLRASTERPOS3FPROC glad_glRasterPos3f; -#define glRasterPos3f glad_glRasterPos3f -typedef void (APIENTRYP PFNGLRASTERPOS3FVPROC)(const GLfloat *v); -GLAPI PFNGLRASTERPOS3FVPROC glad_glRasterPos3fv; -#define glRasterPos3fv glad_glRasterPos3fv -typedef void (APIENTRYP PFNGLRASTERPOS3IPROC)(GLint x, GLint y, GLint z); -GLAPI PFNGLRASTERPOS3IPROC glad_glRasterPos3i; -#define glRasterPos3i glad_glRasterPos3i -typedef void (APIENTRYP PFNGLRASTERPOS3IVPROC)(const GLint *v); -GLAPI PFNGLRASTERPOS3IVPROC glad_glRasterPos3iv; -#define glRasterPos3iv glad_glRasterPos3iv -typedef void (APIENTRYP PFNGLRASTERPOS3SPROC)(GLshort x, GLshort y, GLshort z); -GLAPI PFNGLRASTERPOS3SPROC glad_glRasterPos3s; -#define glRasterPos3s glad_glRasterPos3s -typedef void (APIENTRYP PFNGLRASTERPOS3SVPROC)(const GLshort *v); -GLAPI PFNGLRASTERPOS3SVPROC glad_glRasterPos3sv; -#define glRasterPos3sv glad_glRasterPos3sv -typedef void (APIENTRYP PFNGLRASTERPOS4DPROC)(GLdouble x, GLdouble y, GLdouble z, GLdouble w); -GLAPI PFNGLRASTERPOS4DPROC glad_glRasterPos4d; -#define glRasterPos4d glad_glRasterPos4d -typedef void (APIENTRYP PFNGLRASTERPOS4DVPROC)(const GLdouble *v); -GLAPI PFNGLRASTERPOS4DVPROC glad_glRasterPos4dv; -#define glRasterPos4dv glad_glRasterPos4dv -typedef void (APIENTRYP PFNGLRASTERPOS4FPROC)(GLfloat x, GLfloat y, GLfloat z, GLfloat w); -GLAPI PFNGLRASTERPOS4FPROC glad_glRasterPos4f; -#define glRasterPos4f glad_glRasterPos4f -typedef void (APIENTRYP PFNGLRASTERPOS4FVPROC)(const GLfloat *v); -GLAPI PFNGLRASTERPOS4FVPROC glad_glRasterPos4fv; -#define glRasterPos4fv glad_glRasterPos4fv -typedef void (APIENTRYP PFNGLRASTERPOS4IPROC)(GLint x, GLint y, GLint z, GLint w); -GLAPI PFNGLRASTERPOS4IPROC glad_glRasterPos4i; -#define glRasterPos4i glad_glRasterPos4i -typedef void (APIENTRYP PFNGLRASTERPOS4IVPROC)(const GLint *v); -GLAPI PFNGLRASTERPOS4IVPROC glad_glRasterPos4iv; -#define glRasterPos4iv glad_glRasterPos4iv -typedef void (APIENTRYP PFNGLRASTERPOS4SPROC)(GLshort x, GLshort y, GLshort z, GLshort w); -GLAPI PFNGLRASTERPOS4SPROC glad_glRasterPos4s; -#define glRasterPos4s glad_glRasterPos4s -typedef void (APIENTRYP PFNGLRASTERPOS4SVPROC)(const GLshort *v); -GLAPI PFNGLRASTERPOS4SVPROC glad_glRasterPos4sv; -#define glRasterPos4sv glad_glRasterPos4sv -typedef void (APIENTRYP PFNGLRECTDPROC)(GLdouble x1, GLdouble y1, GLdouble x2, GLdouble y2); -GLAPI PFNGLRECTDPROC glad_glRectd; -#define glRectd glad_glRectd -typedef void (APIENTRYP PFNGLRECTDVPROC)(const GLdouble *v1, const GLdouble *v2); -GLAPI PFNGLRECTDVPROC glad_glRectdv; -#define glRectdv glad_glRectdv -typedef void (APIENTRYP PFNGLRECTFPROC)(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2); -GLAPI PFNGLRECTFPROC glad_glRectf; -#define glRectf glad_glRectf -typedef void (APIENTRYP PFNGLRECTFVPROC)(const GLfloat *v1, const GLfloat *v2); -GLAPI PFNGLRECTFVPROC glad_glRectfv; -#define glRectfv glad_glRectfv -typedef void (APIENTRYP PFNGLRECTIPROC)(GLint x1, GLint y1, GLint x2, GLint y2); -GLAPI PFNGLRECTIPROC glad_glRecti; -#define glRecti glad_glRecti -typedef void (APIENTRYP PFNGLRECTIVPROC)(const GLint *v1, const GLint *v2); -GLAPI PFNGLRECTIVPROC glad_glRectiv; -#define glRectiv glad_glRectiv -typedef void (APIENTRYP PFNGLRECTSPROC)(GLshort x1, GLshort y1, GLshort x2, GLshort y2); -GLAPI PFNGLRECTSPROC glad_glRects; -#define glRects glad_glRects -typedef void (APIENTRYP PFNGLRECTSVPROC)(const GLshort *v1, const GLshort *v2); -GLAPI PFNGLRECTSVPROC glad_glRectsv; -#define glRectsv glad_glRectsv -typedef void (APIENTRYP PFNGLTEXCOORD1DPROC)(GLdouble s); -GLAPI PFNGLTEXCOORD1DPROC glad_glTexCoord1d; -#define glTexCoord1d glad_glTexCoord1d -typedef void (APIENTRYP PFNGLTEXCOORD1DVPROC)(const GLdouble *v); -GLAPI PFNGLTEXCOORD1DVPROC glad_glTexCoord1dv; -#define glTexCoord1dv glad_glTexCoord1dv -typedef void (APIENTRYP PFNGLTEXCOORD1FPROC)(GLfloat s); -GLAPI PFNGLTEXCOORD1FPROC glad_glTexCoord1f; -#define glTexCoord1f glad_glTexCoord1f -typedef void (APIENTRYP PFNGLTEXCOORD1FVPROC)(const GLfloat *v); -GLAPI PFNGLTEXCOORD1FVPROC glad_glTexCoord1fv; -#define glTexCoord1fv glad_glTexCoord1fv -typedef void (APIENTRYP PFNGLTEXCOORD1IPROC)(GLint s); -GLAPI PFNGLTEXCOORD1IPROC glad_glTexCoord1i; -#define glTexCoord1i glad_glTexCoord1i -typedef void (APIENTRYP PFNGLTEXCOORD1IVPROC)(const GLint *v); -GLAPI PFNGLTEXCOORD1IVPROC glad_glTexCoord1iv; -#define glTexCoord1iv glad_glTexCoord1iv -typedef void (APIENTRYP PFNGLTEXCOORD1SPROC)(GLshort s); -GLAPI PFNGLTEXCOORD1SPROC glad_glTexCoord1s; -#define glTexCoord1s glad_glTexCoord1s -typedef void (APIENTRYP PFNGLTEXCOORD1SVPROC)(const GLshort *v); -GLAPI PFNGLTEXCOORD1SVPROC glad_glTexCoord1sv; -#define glTexCoord1sv glad_glTexCoord1sv -typedef void (APIENTRYP PFNGLTEXCOORD2DPROC)(GLdouble s, GLdouble t); -GLAPI PFNGLTEXCOORD2DPROC glad_glTexCoord2d; -#define glTexCoord2d glad_glTexCoord2d -typedef void (APIENTRYP PFNGLTEXCOORD2DVPROC)(const GLdouble *v); -GLAPI PFNGLTEXCOORD2DVPROC glad_glTexCoord2dv; -#define glTexCoord2dv glad_glTexCoord2dv -typedef void (APIENTRYP PFNGLTEXCOORD2FPROC)(GLfloat s, GLfloat t); -GLAPI PFNGLTEXCOORD2FPROC glad_glTexCoord2f; -#define glTexCoord2f glad_glTexCoord2f -typedef void (APIENTRYP PFNGLTEXCOORD2FVPROC)(const GLfloat *v); -GLAPI PFNGLTEXCOORD2FVPROC glad_glTexCoord2fv; -#define glTexCoord2fv glad_glTexCoord2fv -typedef void (APIENTRYP PFNGLTEXCOORD2IPROC)(GLint s, GLint t); -GLAPI PFNGLTEXCOORD2IPROC glad_glTexCoord2i; -#define glTexCoord2i glad_glTexCoord2i -typedef void (APIENTRYP PFNGLTEXCOORD2IVPROC)(const GLint *v); -GLAPI PFNGLTEXCOORD2IVPROC glad_glTexCoord2iv; -#define glTexCoord2iv glad_glTexCoord2iv -typedef void (APIENTRYP PFNGLTEXCOORD2SPROC)(GLshort s, GLshort t); -GLAPI PFNGLTEXCOORD2SPROC glad_glTexCoord2s; -#define glTexCoord2s glad_glTexCoord2s -typedef void (APIENTRYP PFNGLTEXCOORD2SVPROC)(const GLshort *v); -GLAPI PFNGLTEXCOORD2SVPROC glad_glTexCoord2sv; -#define glTexCoord2sv glad_glTexCoord2sv -typedef void (APIENTRYP PFNGLTEXCOORD3DPROC)(GLdouble s, GLdouble t, GLdouble r); -GLAPI PFNGLTEXCOORD3DPROC glad_glTexCoord3d; -#define glTexCoord3d glad_glTexCoord3d -typedef void (APIENTRYP PFNGLTEXCOORD3DVPROC)(const GLdouble *v); -GLAPI PFNGLTEXCOORD3DVPROC glad_glTexCoord3dv; -#define glTexCoord3dv glad_glTexCoord3dv -typedef void (APIENTRYP PFNGLTEXCOORD3FPROC)(GLfloat s, GLfloat t, GLfloat r); -GLAPI PFNGLTEXCOORD3FPROC glad_glTexCoord3f; -#define glTexCoord3f glad_glTexCoord3f -typedef void (APIENTRYP PFNGLTEXCOORD3FVPROC)(const GLfloat *v); -GLAPI PFNGLTEXCOORD3FVPROC glad_glTexCoord3fv; -#define glTexCoord3fv glad_glTexCoord3fv -typedef void (APIENTRYP PFNGLTEXCOORD3IPROC)(GLint s, GLint t, GLint r); -GLAPI PFNGLTEXCOORD3IPROC glad_glTexCoord3i; -#define glTexCoord3i glad_glTexCoord3i -typedef void (APIENTRYP PFNGLTEXCOORD3IVPROC)(const GLint *v); -GLAPI PFNGLTEXCOORD3IVPROC glad_glTexCoord3iv; -#define glTexCoord3iv glad_glTexCoord3iv -typedef void (APIENTRYP PFNGLTEXCOORD3SPROC)(GLshort s, GLshort t, GLshort r); -GLAPI PFNGLTEXCOORD3SPROC glad_glTexCoord3s; -#define glTexCoord3s glad_glTexCoord3s -typedef void (APIENTRYP PFNGLTEXCOORD3SVPROC)(const GLshort *v); -GLAPI PFNGLTEXCOORD3SVPROC glad_glTexCoord3sv; -#define glTexCoord3sv glad_glTexCoord3sv -typedef void (APIENTRYP PFNGLTEXCOORD4DPROC)(GLdouble s, GLdouble t, GLdouble r, GLdouble q); -GLAPI PFNGLTEXCOORD4DPROC glad_glTexCoord4d; -#define glTexCoord4d glad_glTexCoord4d -typedef void (APIENTRYP PFNGLTEXCOORD4DVPROC)(const GLdouble *v); -GLAPI PFNGLTEXCOORD4DVPROC glad_glTexCoord4dv; -#define glTexCoord4dv glad_glTexCoord4dv -typedef void (APIENTRYP PFNGLTEXCOORD4FPROC)(GLfloat s, GLfloat t, GLfloat r, GLfloat q); -GLAPI PFNGLTEXCOORD4FPROC glad_glTexCoord4f; -#define glTexCoord4f glad_glTexCoord4f -typedef void (APIENTRYP PFNGLTEXCOORD4FVPROC)(const GLfloat *v); -GLAPI PFNGLTEXCOORD4FVPROC glad_glTexCoord4fv; -#define glTexCoord4fv glad_glTexCoord4fv -typedef void (APIENTRYP PFNGLTEXCOORD4IPROC)(GLint s, GLint t, GLint r, GLint q); -GLAPI PFNGLTEXCOORD4IPROC glad_glTexCoord4i; -#define glTexCoord4i glad_glTexCoord4i -typedef void (APIENTRYP PFNGLTEXCOORD4IVPROC)(const GLint *v); -GLAPI PFNGLTEXCOORD4IVPROC glad_glTexCoord4iv; -#define glTexCoord4iv glad_glTexCoord4iv -typedef void (APIENTRYP PFNGLTEXCOORD4SPROC)(GLshort s, GLshort t, GLshort r, GLshort q); -GLAPI PFNGLTEXCOORD4SPROC glad_glTexCoord4s; -#define glTexCoord4s glad_glTexCoord4s -typedef void (APIENTRYP PFNGLTEXCOORD4SVPROC)(const GLshort *v); -GLAPI PFNGLTEXCOORD4SVPROC glad_glTexCoord4sv; -#define glTexCoord4sv glad_glTexCoord4sv -typedef void (APIENTRYP PFNGLVERTEX2DPROC)(GLdouble x, GLdouble y); -GLAPI PFNGLVERTEX2DPROC glad_glVertex2d; -#define glVertex2d glad_glVertex2d -typedef void (APIENTRYP PFNGLVERTEX2DVPROC)(const GLdouble *v); -GLAPI PFNGLVERTEX2DVPROC glad_glVertex2dv; -#define glVertex2dv glad_glVertex2dv -typedef void (APIENTRYP PFNGLVERTEX2FPROC)(GLfloat x, GLfloat y); -GLAPI PFNGLVERTEX2FPROC glad_glVertex2f; -#define glVertex2f glad_glVertex2f -typedef void (APIENTRYP PFNGLVERTEX2FVPROC)(const GLfloat *v); -GLAPI PFNGLVERTEX2FVPROC glad_glVertex2fv; -#define glVertex2fv glad_glVertex2fv -typedef void (APIENTRYP PFNGLVERTEX2IPROC)(GLint x, GLint y); -GLAPI PFNGLVERTEX2IPROC glad_glVertex2i; -#define glVertex2i glad_glVertex2i -typedef void (APIENTRYP PFNGLVERTEX2IVPROC)(const GLint *v); -GLAPI PFNGLVERTEX2IVPROC glad_glVertex2iv; -#define glVertex2iv glad_glVertex2iv -typedef void (APIENTRYP PFNGLVERTEX2SPROC)(GLshort x, GLshort y); -GLAPI PFNGLVERTEX2SPROC glad_glVertex2s; -#define glVertex2s glad_glVertex2s -typedef void (APIENTRYP PFNGLVERTEX2SVPROC)(const GLshort *v); -GLAPI PFNGLVERTEX2SVPROC glad_glVertex2sv; -#define glVertex2sv glad_glVertex2sv -typedef void (APIENTRYP PFNGLVERTEX3DPROC)(GLdouble x, GLdouble y, GLdouble z); -GLAPI PFNGLVERTEX3DPROC glad_glVertex3d; -#define glVertex3d glad_glVertex3d -typedef void (APIENTRYP PFNGLVERTEX3DVPROC)(const GLdouble *v); -GLAPI PFNGLVERTEX3DVPROC glad_glVertex3dv; -#define glVertex3dv glad_glVertex3dv -typedef void (APIENTRYP PFNGLVERTEX3FPROC)(GLfloat x, GLfloat y, GLfloat z); -GLAPI PFNGLVERTEX3FPROC glad_glVertex3f; -#define glVertex3f glad_glVertex3f -typedef void (APIENTRYP PFNGLVERTEX3FVPROC)(const GLfloat *v); -GLAPI PFNGLVERTEX3FVPROC glad_glVertex3fv; -#define glVertex3fv glad_glVertex3fv -typedef void (APIENTRYP PFNGLVERTEX3IPROC)(GLint x, GLint y, GLint z); -GLAPI PFNGLVERTEX3IPROC glad_glVertex3i; -#define glVertex3i glad_glVertex3i -typedef void (APIENTRYP PFNGLVERTEX3IVPROC)(const GLint *v); -GLAPI PFNGLVERTEX3IVPROC glad_glVertex3iv; -#define glVertex3iv glad_glVertex3iv -typedef void (APIENTRYP PFNGLVERTEX3SPROC)(GLshort x, GLshort y, GLshort z); -GLAPI PFNGLVERTEX3SPROC glad_glVertex3s; -#define glVertex3s glad_glVertex3s -typedef void (APIENTRYP PFNGLVERTEX3SVPROC)(const GLshort *v); -GLAPI PFNGLVERTEX3SVPROC glad_glVertex3sv; -#define glVertex3sv glad_glVertex3sv -typedef void (APIENTRYP PFNGLVERTEX4DPROC)(GLdouble x, GLdouble y, GLdouble z, GLdouble w); -GLAPI PFNGLVERTEX4DPROC glad_glVertex4d; -#define glVertex4d glad_glVertex4d -typedef void (APIENTRYP PFNGLVERTEX4DVPROC)(const GLdouble *v); -GLAPI PFNGLVERTEX4DVPROC glad_glVertex4dv; -#define glVertex4dv glad_glVertex4dv -typedef void (APIENTRYP PFNGLVERTEX4FPROC)(GLfloat x, GLfloat y, GLfloat z, GLfloat w); -GLAPI PFNGLVERTEX4FPROC glad_glVertex4f; -#define glVertex4f glad_glVertex4f -typedef void (APIENTRYP PFNGLVERTEX4FVPROC)(const GLfloat *v); -GLAPI PFNGLVERTEX4FVPROC glad_glVertex4fv; -#define glVertex4fv glad_glVertex4fv -typedef void (APIENTRYP PFNGLVERTEX4IPROC)(GLint x, GLint y, GLint z, GLint w); -GLAPI PFNGLVERTEX4IPROC glad_glVertex4i; -#define glVertex4i glad_glVertex4i -typedef void (APIENTRYP PFNGLVERTEX4IVPROC)(const GLint *v); -GLAPI PFNGLVERTEX4IVPROC glad_glVertex4iv; -#define glVertex4iv glad_glVertex4iv -typedef void (APIENTRYP PFNGLVERTEX4SPROC)(GLshort x, GLshort y, GLshort z, GLshort w); -GLAPI PFNGLVERTEX4SPROC glad_glVertex4s; -#define glVertex4s glad_glVertex4s -typedef void (APIENTRYP PFNGLVERTEX4SVPROC)(const GLshort *v); -GLAPI PFNGLVERTEX4SVPROC glad_glVertex4sv; -#define glVertex4sv glad_glVertex4sv -typedef void (APIENTRYP PFNGLCLIPPLANEPROC)(GLenum plane, const GLdouble *equation); -GLAPI PFNGLCLIPPLANEPROC glad_glClipPlane; -#define glClipPlane glad_glClipPlane -typedef void (APIENTRYP PFNGLCOLORMATERIALPROC)(GLenum face, GLenum mode); -GLAPI PFNGLCOLORMATERIALPROC glad_glColorMaterial; -#define glColorMaterial glad_glColorMaterial -typedef void (APIENTRYP PFNGLFOGFPROC)(GLenum pname, GLfloat param); -GLAPI PFNGLFOGFPROC glad_glFogf; -#define glFogf glad_glFogf -typedef void (APIENTRYP PFNGLFOGFVPROC)(GLenum pname, const GLfloat *params); -GLAPI PFNGLFOGFVPROC glad_glFogfv; -#define glFogfv glad_glFogfv -typedef void (APIENTRYP PFNGLFOGIPROC)(GLenum pname, GLint param); -GLAPI PFNGLFOGIPROC glad_glFogi; -#define glFogi glad_glFogi -typedef void (APIENTRYP PFNGLFOGIVPROC)(GLenum pname, const GLint *params); -GLAPI PFNGLFOGIVPROC glad_glFogiv; -#define glFogiv glad_glFogiv -typedef void (APIENTRYP PFNGLLIGHTFPROC)(GLenum light, GLenum pname, GLfloat param); -GLAPI PFNGLLIGHTFPROC glad_glLightf; -#define glLightf glad_glLightf -typedef void (APIENTRYP PFNGLLIGHTFVPROC)(GLenum light, GLenum pname, const GLfloat *params); -GLAPI PFNGLLIGHTFVPROC glad_glLightfv; -#define glLightfv glad_glLightfv -typedef void (APIENTRYP PFNGLLIGHTIPROC)(GLenum light, GLenum pname, GLint param); -GLAPI PFNGLLIGHTIPROC glad_glLighti; -#define glLighti glad_glLighti -typedef void (APIENTRYP PFNGLLIGHTIVPROC)(GLenum light, GLenum pname, const GLint *params); -GLAPI PFNGLLIGHTIVPROC glad_glLightiv; -#define glLightiv glad_glLightiv -typedef void (APIENTRYP PFNGLLIGHTMODELFPROC)(GLenum pname, GLfloat param); -GLAPI PFNGLLIGHTMODELFPROC glad_glLightModelf; -#define glLightModelf glad_glLightModelf -typedef void (APIENTRYP PFNGLLIGHTMODELFVPROC)(GLenum pname, const GLfloat *params); -GLAPI PFNGLLIGHTMODELFVPROC glad_glLightModelfv; -#define glLightModelfv glad_glLightModelfv -typedef void (APIENTRYP PFNGLLIGHTMODELIPROC)(GLenum pname, GLint param); -GLAPI PFNGLLIGHTMODELIPROC glad_glLightModeli; -#define glLightModeli glad_glLightModeli -typedef void (APIENTRYP PFNGLLIGHTMODELIVPROC)(GLenum pname, const GLint *params); -GLAPI PFNGLLIGHTMODELIVPROC glad_glLightModeliv; -#define glLightModeliv glad_glLightModeliv -typedef void (APIENTRYP PFNGLLINESTIPPLEPROC)(GLint factor, GLushort pattern); -GLAPI PFNGLLINESTIPPLEPROC glad_glLineStipple; -#define glLineStipple glad_glLineStipple -typedef void (APIENTRYP PFNGLMATERIALFPROC)(GLenum face, GLenum pname, GLfloat param); -GLAPI PFNGLMATERIALFPROC glad_glMaterialf; -#define glMaterialf glad_glMaterialf -typedef void (APIENTRYP PFNGLMATERIALFVPROC)(GLenum face, GLenum pname, const GLfloat *params); -GLAPI PFNGLMATERIALFVPROC glad_glMaterialfv; -#define glMaterialfv glad_glMaterialfv -typedef void (APIENTRYP PFNGLMATERIALIPROC)(GLenum face, GLenum pname, GLint param); -GLAPI PFNGLMATERIALIPROC glad_glMateriali; -#define glMateriali glad_glMateriali -typedef void (APIENTRYP PFNGLMATERIALIVPROC)(GLenum face, GLenum pname, const GLint *params); -GLAPI PFNGLMATERIALIVPROC glad_glMaterialiv; -#define glMaterialiv glad_glMaterialiv -typedef void (APIENTRYP PFNGLPOLYGONSTIPPLEPROC)(const GLubyte *mask); -GLAPI PFNGLPOLYGONSTIPPLEPROC glad_glPolygonStipple; -#define glPolygonStipple glad_glPolygonStipple -typedef void (APIENTRYP PFNGLSHADEMODELPROC)(GLenum mode); -GLAPI PFNGLSHADEMODELPROC glad_glShadeModel; -#define glShadeModel glad_glShadeModel -typedef void (APIENTRYP PFNGLTEXENVFPROC)(GLenum target, GLenum pname, GLfloat param); -GLAPI PFNGLTEXENVFPROC glad_glTexEnvf; -#define glTexEnvf glad_glTexEnvf -typedef void (APIENTRYP PFNGLTEXENVFVPROC)(GLenum target, GLenum pname, const GLfloat *params); -GLAPI PFNGLTEXENVFVPROC glad_glTexEnvfv; -#define glTexEnvfv glad_glTexEnvfv -typedef void (APIENTRYP PFNGLTEXENVIPROC)(GLenum target, GLenum pname, GLint param); -GLAPI PFNGLTEXENVIPROC glad_glTexEnvi; -#define glTexEnvi glad_glTexEnvi -typedef void (APIENTRYP PFNGLTEXENVIVPROC)(GLenum target, GLenum pname, const GLint *params); -GLAPI PFNGLTEXENVIVPROC glad_glTexEnviv; -#define glTexEnviv glad_glTexEnviv -typedef void (APIENTRYP PFNGLTEXGENDPROC)(GLenum coord, GLenum pname, GLdouble param); -GLAPI PFNGLTEXGENDPROC glad_glTexGend; -#define glTexGend glad_glTexGend -typedef void (APIENTRYP PFNGLTEXGENDVPROC)(GLenum coord, GLenum pname, const GLdouble *params); -GLAPI PFNGLTEXGENDVPROC glad_glTexGendv; -#define glTexGendv glad_glTexGendv -typedef void (APIENTRYP PFNGLTEXGENFPROC)(GLenum coord, GLenum pname, GLfloat param); -GLAPI PFNGLTEXGENFPROC glad_glTexGenf; -#define glTexGenf glad_glTexGenf -typedef void (APIENTRYP PFNGLTEXGENFVPROC)(GLenum coord, GLenum pname, const GLfloat *params); -GLAPI PFNGLTEXGENFVPROC glad_glTexGenfv; -#define glTexGenfv glad_glTexGenfv -typedef void (APIENTRYP PFNGLTEXGENIPROC)(GLenum coord, GLenum pname, GLint param); -GLAPI PFNGLTEXGENIPROC glad_glTexGeni; -#define glTexGeni glad_glTexGeni -typedef void (APIENTRYP PFNGLTEXGENIVPROC)(GLenum coord, GLenum pname, const GLint *params); -GLAPI PFNGLTEXGENIVPROC glad_glTexGeniv; -#define glTexGeniv glad_glTexGeniv -typedef void (APIENTRYP PFNGLFEEDBACKBUFFERPROC)(GLsizei size, GLenum type, GLfloat *buffer); -GLAPI PFNGLFEEDBACKBUFFERPROC glad_glFeedbackBuffer; -#define glFeedbackBuffer glad_glFeedbackBuffer -typedef void (APIENTRYP PFNGLSELECTBUFFERPROC)(GLsizei size, GLuint *buffer); -GLAPI PFNGLSELECTBUFFERPROC glad_glSelectBuffer; -#define glSelectBuffer glad_glSelectBuffer -typedef GLint (APIENTRYP PFNGLRENDERMODEPROC)(GLenum mode); -GLAPI PFNGLRENDERMODEPROC glad_glRenderMode; -#define glRenderMode glad_glRenderMode -typedef void (APIENTRYP PFNGLINITNAMESPROC)(); -GLAPI PFNGLINITNAMESPROC glad_glInitNames; -#define glInitNames glad_glInitNames -typedef void (APIENTRYP PFNGLLOADNAMEPROC)(GLuint name); -GLAPI PFNGLLOADNAMEPROC glad_glLoadName; -#define glLoadName glad_glLoadName -typedef void (APIENTRYP PFNGLPASSTHROUGHPROC)(GLfloat token); -GLAPI PFNGLPASSTHROUGHPROC glad_glPassThrough; -#define glPassThrough glad_glPassThrough -typedef void (APIENTRYP PFNGLPOPNAMEPROC)(); -GLAPI PFNGLPOPNAMEPROC glad_glPopName; -#define glPopName glad_glPopName -typedef void (APIENTRYP PFNGLPUSHNAMEPROC)(GLuint name); -GLAPI PFNGLPUSHNAMEPROC glad_glPushName; -#define glPushName glad_glPushName -typedef void (APIENTRYP PFNGLCLEARACCUMPROC)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); -GLAPI PFNGLCLEARACCUMPROC glad_glClearAccum; -#define glClearAccum glad_glClearAccum -typedef void (APIENTRYP PFNGLCLEARINDEXPROC)(GLfloat c); -GLAPI PFNGLCLEARINDEXPROC glad_glClearIndex; -#define glClearIndex glad_glClearIndex -typedef void (APIENTRYP PFNGLINDEXMASKPROC)(GLuint mask); -GLAPI PFNGLINDEXMASKPROC glad_glIndexMask; -#define glIndexMask glad_glIndexMask -typedef void (APIENTRYP PFNGLACCUMPROC)(GLenum op, GLfloat value); -GLAPI PFNGLACCUMPROC glad_glAccum; -#define glAccum glad_glAccum -typedef void (APIENTRYP PFNGLPOPATTRIBPROC)(); -GLAPI PFNGLPOPATTRIBPROC glad_glPopAttrib; -#define glPopAttrib glad_glPopAttrib -typedef void (APIENTRYP PFNGLPUSHATTRIBPROC)(GLbitfield mask); -GLAPI PFNGLPUSHATTRIBPROC glad_glPushAttrib; -#define glPushAttrib glad_glPushAttrib -typedef void (APIENTRYP PFNGLMAP1DPROC)(GLenum target, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble *points); -GLAPI PFNGLMAP1DPROC glad_glMap1d; -#define glMap1d glad_glMap1d -typedef void (APIENTRYP PFNGLMAP1FPROC)(GLenum target, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat *points); -GLAPI PFNGLMAP1FPROC glad_glMap1f; -#define glMap1f glad_glMap1f -typedef void (APIENTRYP PFNGLMAP2DPROC)(GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble *points); -GLAPI PFNGLMAP2DPROC glad_glMap2d; -#define glMap2d glad_glMap2d -typedef void (APIENTRYP PFNGLMAP2FPROC)(GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat *points); -GLAPI PFNGLMAP2FPROC glad_glMap2f; -#define glMap2f glad_glMap2f -typedef void (APIENTRYP PFNGLMAPGRID1DPROC)(GLint un, GLdouble u1, GLdouble u2); -GLAPI PFNGLMAPGRID1DPROC glad_glMapGrid1d; -#define glMapGrid1d glad_glMapGrid1d -typedef void (APIENTRYP PFNGLMAPGRID1FPROC)(GLint un, GLfloat u1, GLfloat u2); -GLAPI PFNGLMAPGRID1FPROC glad_glMapGrid1f; -#define glMapGrid1f glad_glMapGrid1f -typedef void (APIENTRYP PFNGLMAPGRID2DPROC)(GLint un, GLdouble u1, GLdouble u2, GLint vn, GLdouble v1, GLdouble v2); -GLAPI PFNGLMAPGRID2DPROC glad_glMapGrid2d; -#define glMapGrid2d glad_glMapGrid2d -typedef void (APIENTRYP PFNGLMAPGRID2FPROC)(GLint un, GLfloat u1, GLfloat u2, GLint vn, GLfloat v1, GLfloat v2); -GLAPI PFNGLMAPGRID2FPROC glad_glMapGrid2f; -#define glMapGrid2f glad_glMapGrid2f -typedef void (APIENTRYP PFNGLEVALCOORD1DPROC)(GLdouble u); -GLAPI PFNGLEVALCOORD1DPROC glad_glEvalCoord1d; -#define glEvalCoord1d glad_glEvalCoord1d -typedef void (APIENTRYP PFNGLEVALCOORD1DVPROC)(const GLdouble *u); -GLAPI PFNGLEVALCOORD1DVPROC glad_glEvalCoord1dv; -#define glEvalCoord1dv glad_glEvalCoord1dv -typedef void (APIENTRYP PFNGLEVALCOORD1FPROC)(GLfloat u); -GLAPI PFNGLEVALCOORD1FPROC glad_glEvalCoord1f; -#define glEvalCoord1f glad_glEvalCoord1f -typedef void (APIENTRYP PFNGLEVALCOORD1FVPROC)(const GLfloat *u); -GLAPI PFNGLEVALCOORD1FVPROC glad_glEvalCoord1fv; -#define glEvalCoord1fv glad_glEvalCoord1fv -typedef void (APIENTRYP PFNGLEVALCOORD2DPROC)(GLdouble u, GLdouble v); -GLAPI PFNGLEVALCOORD2DPROC glad_glEvalCoord2d; -#define glEvalCoord2d glad_glEvalCoord2d -typedef void (APIENTRYP PFNGLEVALCOORD2DVPROC)(const GLdouble *u); -GLAPI PFNGLEVALCOORD2DVPROC glad_glEvalCoord2dv; -#define glEvalCoord2dv glad_glEvalCoord2dv -typedef void (APIENTRYP PFNGLEVALCOORD2FPROC)(GLfloat u, GLfloat v); -GLAPI PFNGLEVALCOORD2FPROC glad_glEvalCoord2f; -#define glEvalCoord2f glad_glEvalCoord2f -typedef void (APIENTRYP PFNGLEVALCOORD2FVPROC)(const GLfloat *u); -GLAPI PFNGLEVALCOORD2FVPROC glad_glEvalCoord2fv; -#define glEvalCoord2fv glad_glEvalCoord2fv -typedef void (APIENTRYP PFNGLEVALMESH1PROC)(GLenum mode, GLint i1, GLint i2); -GLAPI PFNGLEVALMESH1PROC glad_glEvalMesh1; -#define glEvalMesh1 glad_glEvalMesh1 -typedef void (APIENTRYP PFNGLEVALPOINT1PROC)(GLint i); -GLAPI PFNGLEVALPOINT1PROC glad_glEvalPoint1; -#define glEvalPoint1 glad_glEvalPoint1 -typedef void (APIENTRYP PFNGLEVALMESH2PROC)(GLenum mode, GLint i1, GLint i2, GLint j1, GLint j2); -GLAPI PFNGLEVALMESH2PROC glad_glEvalMesh2; -#define glEvalMesh2 glad_glEvalMesh2 -typedef void (APIENTRYP PFNGLEVALPOINT2PROC)(GLint i, GLint j); -GLAPI PFNGLEVALPOINT2PROC glad_glEvalPoint2; -#define glEvalPoint2 glad_glEvalPoint2 -typedef void (APIENTRYP PFNGLALPHAFUNCPROC)(GLenum func, GLfloat ref); -GLAPI PFNGLALPHAFUNCPROC glad_glAlphaFunc; -#define glAlphaFunc glad_glAlphaFunc -typedef void (APIENTRYP PFNGLPIXELZOOMPROC)(GLfloat xfactor, GLfloat yfactor); -GLAPI PFNGLPIXELZOOMPROC glad_glPixelZoom; -#define glPixelZoom glad_glPixelZoom -typedef void (APIENTRYP PFNGLPIXELTRANSFERFPROC)(GLenum pname, GLfloat param); -GLAPI PFNGLPIXELTRANSFERFPROC glad_glPixelTransferf; -#define glPixelTransferf glad_glPixelTransferf -typedef void (APIENTRYP PFNGLPIXELTRANSFERIPROC)(GLenum pname, GLint param); -GLAPI PFNGLPIXELTRANSFERIPROC glad_glPixelTransferi; -#define glPixelTransferi glad_glPixelTransferi -typedef void (APIENTRYP PFNGLPIXELMAPFVPROC)(GLenum map, GLsizei mapsize, const GLfloat *values); -GLAPI PFNGLPIXELMAPFVPROC glad_glPixelMapfv; -#define glPixelMapfv glad_glPixelMapfv -typedef void (APIENTRYP PFNGLPIXELMAPUIVPROC)(GLenum map, GLsizei mapsize, const GLuint *values); -GLAPI PFNGLPIXELMAPUIVPROC glad_glPixelMapuiv; -#define glPixelMapuiv glad_glPixelMapuiv -typedef void (APIENTRYP PFNGLPIXELMAPUSVPROC)(GLenum map, GLsizei mapsize, const GLushort *values); -GLAPI PFNGLPIXELMAPUSVPROC glad_glPixelMapusv; -#define glPixelMapusv glad_glPixelMapusv -typedef void (APIENTRYP PFNGLCOPYPIXELSPROC)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum type); -GLAPI PFNGLCOPYPIXELSPROC glad_glCopyPixels; -#define glCopyPixels glad_glCopyPixels -typedef void (APIENTRYP PFNGLDRAWPIXELSPROC)(GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); -GLAPI PFNGLDRAWPIXELSPROC glad_glDrawPixels; -#define glDrawPixels glad_glDrawPixels -typedef void (APIENTRYP PFNGLGETCLIPPLANEPROC)(GLenum plane, GLdouble *equation); -GLAPI PFNGLGETCLIPPLANEPROC glad_glGetClipPlane; -#define glGetClipPlane glad_glGetClipPlane -typedef void (APIENTRYP PFNGLGETLIGHTFVPROC)(GLenum light, GLenum pname, GLfloat *params); -GLAPI PFNGLGETLIGHTFVPROC glad_glGetLightfv; -#define glGetLightfv glad_glGetLightfv -typedef void (APIENTRYP PFNGLGETLIGHTIVPROC)(GLenum light, GLenum pname, GLint *params); -GLAPI PFNGLGETLIGHTIVPROC glad_glGetLightiv; -#define glGetLightiv glad_glGetLightiv -typedef void (APIENTRYP PFNGLGETMAPDVPROC)(GLenum target, GLenum query, GLdouble *v); -GLAPI PFNGLGETMAPDVPROC glad_glGetMapdv; -#define glGetMapdv glad_glGetMapdv -typedef void (APIENTRYP PFNGLGETMAPFVPROC)(GLenum target, GLenum query, GLfloat *v); -GLAPI PFNGLGETMAPFVPROC glad_glGetMapfv; -#define glGetMapfv glad_glGetMapfv -typedef void (APIENTRYP PFNGLGETMAPIVPROC)(GLenum target, GLenum query, GLint *v); -GLAPI PFNGLGETMAPIVPROC glad_glGetMapiv; -#define glGetMapiv glad_glGetMapiv -typedef void (APIENTRYP PFNGLGETMATERIALFVPROC)(GLenum face, GLenum pname, GLfloat *params); -GLAPI PFNGLGETMATERIALFVPROC glad_glGetMaterialfv; -#define glGetMaterialfv glad_glGetMaterialfv -typedef void (APIENTRYP PFNGLGETMATERIALIVPROC)(GLenum face, GLenum pname, GLint *params); -GLAPI PFNGLGETMATERIALIVPROC glad_glGetMaterialiv; -#define glGetMaterialiv glad_glGetMaterialiv -typedef void (APIENTRYP PFNGLGETPIXELMAPFVPROC)(GLenum map, GLfloat *values); -GLAPI PFNGLGETPIXELMAPFVPROC glad_glGetPixelMapfv; -#define glGetPixelMapfv glad_glGetPixelMapfv -typedef void (APIENTRYP PFNGLGETPIXELMAPUIVPROC)(GLenum map, GLuint *values); -GLAPI PFNGLGETPIXELMAPUIVPROC glad_glGetPixelMapuiv; -#define glGetPixelMapuiv glad_glGetPixelMapuiv -typedef void (APIENTRYP PFNGLGETPIXELMAPUSVPROC)(GLenum map, GLushort *values); -GLAPI PFNGLGETPIXELMAPUSVPROC glad_glGetPixelMapusv; -#define glGetPixelMapusv glad_glGetPixelMapusv -typedef void (APIENTRYP PFNGLGETPOLYGONSTIPPLEPROC)(GLubyte *mask); -GLAPI PFNGLGETPOLYGONSTIPPLEPROC glad_glGetPolygonStipple; -#define glGetPolygonStipple glad_glGetPolygonStipple -typedef void (APIENTRYP PFNGLGETTEXENVFVPROC)(GLenum target, GLenum pname, GLfloat *params); -GLAPI PFNGLGETTEXENVFVPROC glad_glGetTexEnvfv; -#define glGetTexEnvfv glad_glGetTexEnvfv -typedef void (APIENTRYP PFNGLGETTEXENVIVPROC)(GLenum target, GLenum pname, GLint *params); -GLAPI PFNGLGETTEXENVIVPROC glad_glGetTexEnviv; -#define glGetTexEnviv glad_glGetTexEnviv -typedef void (APIENTRYP PFNGLGETTEXGENDVPROC)(GLenum coord, GLenum pname, GLdouble *params); -GLAPI PFNGLGETTEXGENDVPROC glad_glGetTexGendv; -#define glGetTexGendv glad_glGetTexGendv -typedef void (APIENTRYP PFNGLGETTEXGENFVPROC)(GLenum coord, GLenum pname, GLfloat *params); -GLAPI PFNGLGETTEXGENFVPROC glad_glGetTexGenfv; -#define glGetTexGenfv glad_glGetTexGenfv -typedef void (APIENTRYP PFNGLGETTEXGENIVPROC)(GLenum coord, GLenum pname, GLint *params); -GLAPI PFNGLGETTEXGENIVPROC glad_glGetTexGeniv; -#define glGetTexGeniv glad_glGetTexGeniv -typedef GLboolean (APIENTRYP PFNGLISLISTPROC)(GLuint list); -GLAPI PFNGLISLISTPROC glad_glIsList; -#define glIsList glad_glIsList -typedef void (APIENTRYP PFNGLFRUSTUMPROC)(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); -GLAPI PFNGLFRUSTUMPROC glad_glFrustum; -#define glFrustum glad_glFrustum -typedef void (APIENTRYP PFNGLLOADIDENTITYPROC)(); -GLAPI PFNGLLOADIDENTITYPROC glad_glLoadIdentity; -#define glLoadIdentity glad_glLoadIdentity -typedef void (APIENTRYP PFNGLLOADMATRIXFPROC)(const GLfloat *m); -GLAPI PFNGLLOADMATRIXFPROC glad_glLoadMatrixf; -#define glLoadMatrixf glad_glLoadMatrixf -typedef void (APIENTRYP PFNGLLOADMATRIXDPROC)(const GLdouble *m); -GLAPI PFNGLLOADMATRIXDPROC glad_glLoadMatrixd; -#define glLoadMatrixd glad_glLoadMatrixd -typedef void (APIENTRYP PFNGLMATRIXMODEPROC)(GLenum mode); -GLAPI PFNGLMATRIXMODEPROC glad_glMatrixMode; -#define glMatrixMode glad_glMatrixMode -typedef void (APIENTRYP PFNGLMULTMATRIXFPROC)(const GLfloat *m); -GLAPI PFNGLMULTMATRIXFPROC glad_glMultMatrixf; -#define glMultMatrixf glad_glMultMatrixf -typedef void (APIENTRYP PFNGLMULTMATRIXDPROC)(const GLdouble *m); -GLAPI PFNGLMULTMATRIXDPROC glad_glMultMatrixd; -#define glMultMatrixd glad_glMultMatrixd -typedef void (APIENTRYP PFNGLORTHOPROC)(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); -GLAPI PFNGLORTHOPROC glad_glOrtho; -#define glOrtho glad_glOrtho -typedef void (APIENTRYP PFNGLPOPMATRIXPROC)(); -GLAPI PFNGLPOPMATRIXPROC glad_glPopMatrix; -#define glPopMatrix glad_glPopMatrix -typedef void (APIENTRYP PFNGLPUSHMATRIXPROC)(); -GLAPI PFNGLPUSHMATRIXPROC glad_glPushMatrix; -#define glPushMatrix glad_glPushMatrix -typedef void (APIENTRYP PFNGLROTATEDPROC)(GLdouble angle, GLdouble x, GLdouble y, GLdouble z); -GLAPI PFNGLROTATEDPROC glad_glRotated; -#define glRotated glad_glRotated -typedef void (APIENTRYP PFNGLROTATEFPROC)(GLfloat angle, GLfloat x, GLfloat y, GLfloat z); -GLAPI PFNGLROTATEFPROC glad_glRotatef; -#define glRotatef glad_glRotatef -typedef void (APIENTRYP PFNGLSCALEDPROC)(GLdouble x, GLdouble y, GLdouble z); -GLAPI PFNGLSCALEDPROC glad_glScaled; -#define glScaled glad_glScaled -typedef void (APIENTRYP PFNGLSCALEFPROC)(GLfloat x, GLfloat y, GLfloat z); -GLAPI PFNGLSCALEFPROC glad_glScalef; -#define glScalef glad_glScalef -typedef void (APIENTRYP PFNGLTRANSLATEDPROC)(GLdouble x, GLdouble y, GLdouble z); -GLAPI PFNGLTRANSLATEDPROC glad_glTranslated; -#define glTranslated glad_glTranslated -typedef void (APIENTRYP PFNGLTRANSLATEFPROC)(GLfloat x, GLfloat y, GLfloat z); -GLAPI PFNGLTRANSLATEFPROC glad_glTranslatef; -#define glTranslatef glad_glTranslatef -#endif -#ifndef GL_VERSION_1_1 -#define GL_VERSION_1_1 1 -GLAPI int GLAD_GL_VERSION_1_1; -typedef void (APIENTRYP PFNGLDRAWARRAYSPROC)(GLenum mode, GLint first, GLsizei count); -GLAPI PFNGLDRAWARRAYSPROC glad_glDrawArrays; -#define glDrawArrays glad_glDrawArrays -typedef void (APIENTRYP PFNGLDRAWELEMENTSPROC)(GLenum mode, GLsizei count, GLenum type, const void *indices); -GLAPI PFNGLDRAWELEMENTSPROC glad_glDrawElements; -#define glDrawElements glad_glDrawElements -typedef void (APIENTRYP PFNGLGETPOINTERVPROC)(GLenum pname, void **params); -GLAPI PFNGLGETPOINTERVPROC glad_glGetPointerv; -#define glGetPointerv glad_glGetPointerv -typedef void (APIENTRYP PFNGLPOLYGONOFFSETPROC)(GLfloat factor, GLfloat units); -GLAPI PFNGLPOLYGONOFFSETPROC glad_glPolygonOffset; -#define glPolygonOffset glad_glPolygonOffset -typedef void (APIENTRYP PFNGLCOPYTEXIMAGE1DPROC)(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border); -GLAPI PFNGLCOPYTEXIMAGE1DPROC glad_glCopyTexImage1D; -#define glCopyTexImage1D glad_glCopyTexImage1D -typedef void (APIENTRYP PFNGLCOPYTEXIMAGE2DPROC)(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); -GLAPI PFNGLCOPYTEXIMAGE2DPROC glad_glCopyTexImage2D; -#define glCopyTexImage2D glad_glCopyTexImage2D -typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE1DPROC)(GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); -GLAPI PFNGLCOPYTEXSUBIMAGE1DPROC glad_glCopyTexSubImage1D; -#define glCopyTexSubImage1D glad_glCopyTexSubImage1D -typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE2DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); -GLAPI PFNGLCOPYTEXSUBIMAGE2DPROC glad_glCopyTexSubImage2D; -#define glCopyTexSubImage2D glad_glCopyTexSubImage2D -typedef void (APIENTRYP PFNGLTEXSUBIMAGE1DPROC)(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); -GLAPI PFNGLTEXSUBIMAGE1DPROC glad_glTexSubImage1D; -#define glTexSubImage1D glad_glTexSubImage1D -typedef void (APIENTRYP PFNGLTEXSUBIMAGE2DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); -GLAPI PFNGLTEXSUBIMAGE2DPROC glad_glTexSubImage2D; -#define glTexSubImage2D glad_glTexSubImage2D -typedef void (APIENTRYP PFNGLBINDTEXTUREPROC)(GLenum target, GLuint texture); -GLAPI PFNGLBINDTEXTUREPROC glad_glBindTexture; -#define glBindTexture glad_glBindTexture -typedef void (APIENTRYP PFNGLDELETETEXTURESPROC)(GLsizei n, const GLuint *textures); -GLAPI PFNGLDELETETEXTURESPROC glad_glDeleteTextures; -#define glDeleteTextures glad_glDeleteTextures -typedef void (APIENTRYP PFNGLGENTEXTURESPROC)(GLsizei n, GLuint *textures); -GLAPI PFNGLGENTEXTURESPROC glad_glGenTextures; -#define glGenTextures glad_glGenTextures -typedef GLboolean (APIENTRYP PFNGLISTEXTUREPROC)(GLuint texture); -GLAPI PFNGLISTEXTUREPROC glad_glIsTexture; -#define glIsTexture glad_glIsTexture -typedef void (APIENTRYP PFNGLARRAYELEMENTPROC)(GLint i); -GLAPI PFNGLARRAYELEMENTPROC glad_glArrayElement; -#define glArrayElement glad_glArrayElement -typedef void (APIENTRYP PFNGLCOLORPOINTERPROC)(GLint size, GLenum type, GLsizei stride, const void *pointer); -GLAPI PFNGLCOLORPOINTERPROC glad_glColorPointer; -#define glColorPointer glad_glColorPointer -typedef void (APIENTRYP PFNGLDISABLECLIENTSTATEPROC)(GLenum array); -GLAPI PFNGLDISABLECLIENTSTATEPROC glad_glDisableClientState; -#define glDisableClientState glad_glDisableClientState -typedef void (APIENTRYP PFNGLEDGEFLAGPOINTERPROC)(GLsizei stride, const void *pointer); -GLAPI PFNGLEDGEFLAGPOINTERPROC glad_glEdgeFlagPointer; -#define glEdgeFlagPointer glad_glEdgeFlagPointer -typedef void (APIENTRYP PFNGLENABLECLIENTSTATEPROC)(GLenum array); -GLAPI PFNGLENABLECLIENTSTATEPROC glad_glEnableClientState; -#define glEnableClientState glad_glEnableClientState -typedef void (APIENTRYP PFNGLINDEXPOINTERPROC)(GLenum type, GLsizei stride, const void *pointer); -GLAPI PFNGLINDEXPOINTERPROC glad_glIndexPointer; -#define glIndexPointer glad_glIndexPointer -typedef void (APIENTRYP PFNGLINTERLEAVEDARRAYSPROC)(GLenum format, GLsizei stride, const void *pointer); -GLAPI PFNGLINTERLEAVEDARRAYSPROC glad_glInterleavedArrays; -#define glInterleavedArrays glad_glInterleavedArrays -typedef void (APIENTRYP PFNGLNORMALPOINTERPROC)(GLenum type, GLsizei stride, const void *pointer); -GLAPI PFNGLNORMALPOINTERPROC glad_glNormalPointer; -#define glNormalPointer glad_glNormalPointer -typedef void (APIENTRYP PFNGLTEXCOORDPOINTERPROC)(GLint size, GLenum type, GLsizei stride, const void *pointer); -GLAPI PFNGLTEXCOORDPOINTERPROC glad_glTexCoordPointer; -#define glTexCoordPointer glad_glTexCoordPointer -typedef void (APIENTRYP PFNGLVERTEXPOINTERPROC)(GLint size, GLenum type, GLsizei stride, const void *pointer); -GLAPI PFNGLVERTEXPOINTERPROC glad_glVertexPointer; -#define glVertexPointer glad_glVertexPointer -typedef GLboolean (APIENTRYP PFNGLARETEXTURESRESIDENTPROC)(GLsizei n, const GLuint *textures, GLboolean *residences); -GLAPI PFNGLARETEXTURESRESIDENTPROC glad_glAreTexturesResident; -#define glAreTexturesResident glad_glAreTexturesResident -typedef void (APIENTRYP PFNGLPRIORITIZETEXTURESPROC)(GLsizei n, const GLuint *textures, const GLfloat *priorities); -GLAPI PFNGLPRIORITIZETEXTURESPROC glad_glPrioritizeTextures; -#define glPrioritizeTextures glad_glPrioritizeTextures -typedef void (APIENTRYP PFNGLINDEXUBPROC)(GLubyte c); -GLAPI PFNGLINDEXUBPROC glad_glIndexub; -#define glIndexub glad_glIndexub -typedef void (APIENTRYP PFNGLINDEXUBVPROC)(const GLubyte *c); -GLAPI PFNGLINDEXUBVPROC glad_glIndexubv; -#define glIndexubv glad_glIndexubv -typedef void (APIENTRYP PFNGLPOPCLIENTATTRIBPROC)(); -GLAPI PFNGLPOPCLIENTATTRIBPROC glad_glPopClientAttrib; -#define glPopClientAttrib glad_glPopClientAttrib -typedef void (APIENTRYP PFNGLPUSHCLIENTATTRIBPROC)(GLbitfield mask); -GLAPI PFNGLPUSHCLIENTATTRIBPROC glad_glPushClientAttrib; -#define glPushClientAttrib glad_glPushClientAttrib -#endif -#ifndef GL_VERSION_1_2 -#define GL_VERSION_1_2 1 -GLAPI int GLAD_GL_VERSION_1_2; -typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSPROC)(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices); -GLAPI PFNGLDRAWRANGEELEMENTSPROC glad_glDrawRangeElements; -#define glDrawRangeElements glad_glDrawRangeElements -typedef void (APIENTRYP PFNGLTEXIMAGE3DPROC)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); -GLAPI PFNGLTEXIMAGE3DPROC glad_glTexImage3D; -#define glTexImage3D glad_glTexImage3D -typedef void (APIENTRYP PFNGLTEXSUBIMAGE3DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); -GLAPI PFNGLTEXSUBIMAGE3DPROC glad_glTexSubImage3D; -#define glTexSubImage3D glad_glTexSubImage3D -typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE3DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); -GLAPI PFNGLCOPYTEXSUBIMAGE3DPROC glad_glCopyTexSubImage3D; -#define glCopyTexSubImage3D glad_glCopyTexSubImage3D -#endif -#ifndef GL_VERSION_1_3 -#define GL_VERSION_1_3 1 -GLAPI int GLAD_GL_VERSION_1_3; -typedef void (APIENTRYP PFNGLACTIVETEXTUREPROC)(GLenum texture); -GLAPI PFNGLACTIVETEXTUREPROC glad_glActiveTexture; -#define glActiveTexture glad_glActiveTexture -typedef void (APIENTRYP PFNGLSAMPLECOVERAGEPROC)(GLfloat value, GLboolean invert); -GLAPI PFNGLSAMPLECOVERAGEPROC glad_glSampleCoverage; -#define glSampleCoverage glad_glSampleCoverage -typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DPROC)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data); -GLAPI PFNGLCOMPRESSEDTEXIMAGE3DPROC glad_glCompressedTexImage3D; -#define glCompressedTexImage3D glad_glCompressedTexImage3D -typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DPROC)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *data); -GLAPI PFNGLCOMPRESSEDTEXIMAGE2DPROC glad_glCompressedTexImage2D; -#define glCompressedTexImage2D glad_glCompressedTexImage2D -typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE1DPROC)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *data); -GLAPI PFNGLCOMPRESSEDTEXIMAGE1DPROC glad_glCompressedTexImage1D; -#define glCompressedTexImage1D glad_glCompressedTexImage1D -typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); -GLAPI PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC glad_glCompressedTexSubImage3D; -#define glCompressedTexSubImage3D glad_glCompressedTexSubImage3D -typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); -GLAPI PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC glad_glCompressedTexSubImage2D; -#define glCompressedTexSubImage2D glad_glCompressedTexSubImage2D -typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC)(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data); -GLAPI PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC glad_glCompressedTexSubImage1D; -#define glCompressedTexSubImage1D glad_glCompressedTexSubImage1D -typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXIMAGEPROC)(GLenum target, GLint level, void *img); -GLAPI PFNGLGETCOMPRESSEDTEXIMAGEPROC glad_glGetCompressedTexImage; -#define glGetCompressedTexImage glad_glGetCompressedTexImage -typedef void (APIENTRYP PFNGLCLIENTACTIVETEXTUREPROC)(GLenum texture); -GLAPI PFNGLCLIENTACTIVETEXTUREPROC glad_glClientActiveTexture; -#define glClientActiveTexture glad_glClientActiveTexture -typedef void (APIENTRYP PFNGLMULTITEXCOORD1DPROC)(GLenum target, GLdouble s); -GLAPI PFNGLMULTITEXCOORD1DPROC glad_glMultiTexCoord1d; -#define glMultiTexCoord1d glad_glMultiTexCoord1d -typedef void (APIENTRYP PFNGLMULTITEXCOORD1DVPROC)(GLenum target, const GLdouble *v); -GLAPI PFNGLMULTITEXCOORD1DVPROC glad_glMultiTexCoord1dv; -#define glMultiTexCoord1dv glad_glMultiTexCoord1dv -typedef void (APIENTRYP PFNGLMULTITEXCOORD1FPROC)(GLenum target, GLfloat s); -GLAPI PFNGLMULTITEXCOORD1FPROC glad_glMultiTexCoord1f; -#define glMultiTexCoord1f glad_glMultiTexCoord1f -typedef void (APIENTRYP PFNGLMULTITEXCOORD1FVPROC)(GLenum target, const GLfloat *v); -GLAPI PFNGLMULTITEXCOORD1FVPROC glad_glMultiTexCoord1fv; -#define glMultiTexCoord1fv glad_glMultiTexCoord1fv -typedef void (APIENTRYP PFNGLMULTITEXCOORD1IPROC)(GLenum target, GLint s); -GLAPI PFNGLMULTITEXCOORD1IPROC glad_glMultiTexCoord1i; -#define glMultiTexCoord1i glad_glMultiTexCoord1i -typedef void (APIENTRYP PFNGLMULTITEXCOORD1IVPROC)(GLenum target, const GLint *v); -GLAPI PFNGLMULTITEXCOORD1IVPROC glad_glMultiTexCoord1iv; -#define glMultiTexCoord1iv glad_glMultiTexCoord1iv -typedef void (APIENTRYP PFNGLMULTITEXCOORD1SPROC)(GLenum target, GLshort s); -GLAPI PFNGLMULTITEXCOORD1SPROC glad_glMultiTexCoord1s; -#define glMultiTexCoord1s glad_glMultiTexCoord1s -typedef void (APIENTRYP PFNGLMULTITEXCOORD1SVPROC)(GLenum target, const GLshort *v); -GLAPI PFNGLMULTITEXCOORD1SVPROC glad_glMultiTexCoord1sv; -#define glMultiTexCoord1sv glad_glMultiTexCoord1sv -typedef void (APIENTRYP PFNGLMULTITEXCOORD2DPROC)(GLenum target, GLdouble s, GLdouble t); -GLAPI PFNGLMULTITEXCOORD2DPROC glad_glMultiTexCoord2d; -#define glMultiTexCoord2d glad_glMultiTexCoord2d -typedef void (APIENTRYP PFNGLMULTITEXCOORD2DVPROC)(GLenum target, const GLdouble *v); -GLAPI PFNGLMULTITEXCOORD2DVPROC glad_glMultiTexCoord2dv; -#define glMultiTexCoord2dv glad_glMultiTexCoord2dv -typedef void (APIENTRYP PFNGLMULTITEXCOORD2FPROC)(GLenum target, GLfloat s, GLfloat t); -GLAPI PFNGLMULTITEXCOORD2FPROC glad_glMultiTexCoord2f; -#define glMultiTexCoord2f glad_glMultiTexCoord2f -typedef void (APIENTRYP PFNGLMULTITEXCOORD2FVPROC)(GLenum target, const GLfloat *v); -GLAPI PFNGLMULTITEXCOORD2FVPROC glad_glMultiTexCoord2fv; -#define glMultiTexCoord2fv glad_glMultiTexCoord2fv -typedef void (APIENTRYP PFNGLMULTITEXCOORD2IPROC)(GLenum target, GLint s, GLint t); -GLAPI PFNGLMULTITEXCOORD2IPROC glad_glMultiTexCoord2i; -#define glMultiTexCoord2i glad_glMultiTexCoord2i -typedef void (APIENTRYP PFNGLMULTITEXCOORD2IVPROC)(GLenum target, const GLint *v); -GLAPI PFNGLMULTITEXCOORD2IVPROC glad_glMultiTexCoord2iv; -#define glMultiTexCoord2iv glad_glMultiTexCoord2iv -typedef void (APIENTRYP PFNGLMULTITEXCOORD2SPROC)(GLenum target, GLshort s, GLshort t); -GLAPI PFNGLMULTITEXCOORD2SPROC glad_glMultiTexCoord2s; -#define glMultiTexCoord2s glad_glMultiTexCoord2s -typedef void (APIENTRYP PFNGLMULTITEXCOORD2SVPROC)(GLenum target, const GLshort *v); -GLAPI PFNGLMULTITEXCOORD2SVPROC glad_glMultiTexCoord2sv; -#define glMultiTexCoord2sv glad_glMultiTexCoord2sv -typedef void (APIENTRYP PFNGLMULTITEXCOORD3DPROC)(GLenum target, GLdouble s, GLdouble t, GLdouble r); -GLAPI PFNGLMULTITEXCOORD3DPROC glad_glMultiTexCoord3d; -#define glMultiTexCoord3d glad_glMultiTexCoord3d -typedef void (APIENTRYP PFNGLMULTITEXCOORD3DVPROC)(GLenum target, const GLdouble *v); -GLAPI PFNGLMULTITEXCOORD3DVPROC glad_glMultiTexCoord3dv; -#define glMultiTexCoord3dv glad_glMultiTexCoord3dv -typedef void (APIENTRYP PFNGLMULTITEXCOORD3FPROC)(GLenum target, GLfloat s, GLfloat t, GLfloat r); -GLAPI PFNGLMULTITEXCOORD3FPROC glad_glMultiTexCoord3f; -#define glMultiTexCoord3f glad_glMultiTexCoord3f -typedef void (APIENTRYP PFNGLMULTITEXCOORD3FVPROC)(GLenum target, const GLfloat *v); -GLAPI PFNGLMULTITEXCOORD3FVPROC glad_glMultiTexCoord3fv; -#define glMultiTexCoord3fv glad_glMultiTexCoord3fv -typedef void (APIENTRYP PFNGLMULTITEXCOORD3IPROC)(GLenum target, GLint s, GLint t, GLint r); -GLAPI PFNGLMULTITEXCOORD3IPROC glad_glMultiTexCoord3i; -#define glMultiTexCoord3i glad_glMultiTexCoord3i -typedef void (APIENTRYP PFNGLMULTITEXCOORD3IVPROC)(GLenum target, const GLint *v); -GLAPI PFNGLMULTITEXCOORD3IVPROC glad_glMultiTexCoord3iv; -#define glMultiTexCoord3iv glad_glMultiTexCoord3iv -typedef void (APIENTRYP PFNGLMULTITEXCOORD3SPROC)(GLenum target, GLshort s, GLshort t, GLshort r); -GLAPI PFNGLMULTITEXCOORD3SPROC glad_glMultiTexCoord3s; -#define glMultiTexCoord3s glad_glMultiTexCoord3s -typedef void (APIENTRYP PFNGLMULTITEXCOORD3SVPROC)(GLenum target, const GLshort *v); -GLAPI PFNGLMULTITEXCOORD3SVPROC glad_glMultiTexCoord3sv; -#define glMultiTexCoord3sv glad_glMultiTexCoord3sv -typedef void (APIENTRYP PFNGLMULTITEXCOORD4DPROC)(GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q); -GLAPI PFNGLMULTITEXCOORD4DPROC glad_glMultiTexCoord4d; -#define glMultiTexCoord4d glad_glMultiTexCoord4d -typedef void (APIENTRYP PFNGLMULTITEXCOORD4DVPROC)(GLenum target, const GLdouble *v); -GLAPI PFNGLMULTITEXCOORD4DVPROC glad_glMultiTexCoord4dv; -#define glMultiTexCoord4dv glad_glMultiTexCoord4dv -typedef void (APIENTRYP PFNGLMULTITEXCOORD4FPROC)(GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q); -GLAPI PFNGLMULTITEXCOORD4FPROC glad_glMultiTexCoord4f; -#define glMultiTexCoord4f glad_glMultiTexCoord4f -typedef void (APIENTRYP PFNGLMULTITEXCOORD4FVPROC)(GLenum target, const GLfloat *v); -GLAPI PFNGLMULTITEXCOORD4FVPROC glad_glMultiTexCoord4fv; -#define glMultiTexCoord4fv glad_glMultiTexCoord4fv -typedef void (APIENTRYP PFNGLMULTITEXCOORD4IPROC)(GLenum target, GLint s, GLint t, GLint r, GLint q); -GLAPI PFNGLMULTITEXCOORD4IPROC glad_glMultiTexCoord4i; -#define glMultiTexCoord4i glad_glMultiTexCoord4i -typedef void (APIENTRYP PFNGLMULTITEXCOORD4IVPROC)(GLenum target, const GLint *v); -GLAPI PFNGLMULTITEXCOORD4IVPROC glad_glMultiTexCoord4iv; -#define glMultiTexCoord4iv glad_glMultiTexCoord4iv -typedef void (APIENTRYP PFNGLMULTITEXCOORD4SPROC)(GLenum target, GLshort s, GLshort t, GLshort r, GLshort q); -GLAPI PFNGLMULTITEXCOORD4SPROC glad_glMultiTexCoord4s; -#define glMultiTexCoord4s glad_glMultiTexCoord4s -typedef void (APIENTRYP PFNGLMULTITEXCOORD4SVPROC)(GLenum target, const GLshort *v); -GLAPI PFNGLMULTITEXCOORD4SVPROC glad_glMultiTexCoord4sv; -#define glMultiTexCoord4sv glad_glMultiTexCoord4sv -typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXFPROC)(const GLfloat *m); -GLAPI PFNGLLOADTRANSPOSEMATRIXFPROC glad_glLoadTransposeMatrixf; -#define glLoadTransposeMatrixf glad_glLoadTransposeMatrixf -typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXDPROC)(const GLdouble *m); -GLAPI PFNGLLOADTRANSPOSEMATRIXDPROC glad_glLoadTransposeMatrixd; -#define glLoadTransposeMatrixd glad_glLoadTransposeMatrixd -typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXFPROC)(const GLfloat *m); -GLAPI PFNGLMULTTRANSPOSEMATRIXFPROC glad_glMultTransposeMatrixf; -#define glMultTransposeMatrixf glad_glMultTransposeMatrixf -typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXDPROC)(const GLdouble *m); -GLAPI PFNGLMULTTRANSPOSEMATRIXDPROC glad_glMultTransposeMatrixd; -#define glMultTransposeMatrixd glad_glMultTransposeMatrixd -#endif -#ifndef GL_VERSION_1_4 -#define GL_VERSION_1_4 1 -GLAPI int GLAD_GL_VERSION_1_4; -typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEPROC)(GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); -GLAPI PFNGLBLENDFUNCSEPARATEPROC glad_glBlendFuncSeparate; -#define glBlendFuncSeparate glad_glBlendFuncSeparate -typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSPROC)(GLenum mode, const GLint *first, const GLsizei *count, GLsizei drawcount); -GLAPI PFNGLMULTIDRAWARRAYSPROC glad_glMultiDrawArrays; -#define glMultiDrawArrays glad_glMultiDrawArrays -typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSPROC)(GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei drawcount); -GLAPI PFNGLMULTIDRAWELEMENTSPROC glad_glMultiDrawElements; -#define glMultiDrawElements glad_glMultiDrawElements -typedef void (APIENTRYP PFNGLPOINTPARAMETERFPROC)(GLenum pname, GLfloat param); -GLAPI PFNGLPOINTPARAMETERFPROC glad_glPointParameterf; -#define glPointParameterf glad_glPointParameterf -typedef void (APIENTRYP PFNGLPOINTPARAMETERFVPROC)(GLenum pname, const GLfloat *params); -GLAPI PFNGLPOINTPARAMETERFVPROC glad_glPointParameterfv; -#define glPointParameterfv glad_glPointParameterfv -typedef void (APIENTRYP PFNGLPOINTPARAMETERIPROC)(GLenum pname, GLint param); -GLAPI PFNGLPOINTPARAMETERIPROC glad_glPointParameteri; -#define glPointParameteri glad_glPointParameteri -typedef void (APIENTRYP PFNGLPOINTPARAMETERIVPROC)(GLenum pname, const GLint *params); -GLAPI PFNGLPOINTPARAMETERIVPROC glad_glPointParameteriv; -#define glPointParameteriv glad_glPointParameteriv -typedef void (APIENTRYP PFNGLFOGCOORDFPROC)(GLfloat coord); -GLAPI PFNGLFOGCOORDFPROC glad_glFogCoordf; -#define glFogCoordf glad_glFogCoordf -typedef void (APIENTRYP PFNGLFOGCOORDFVPROC)(const GLfloat *coord); -GLAPI PFNGLFOGCOORDFVPROC glad_glFogCoordfv; -#define glFogCoordfv glad_glFogCoordfv -typedef void (APIENTRYP PFNGLFOGCOORDDPROC)(GLdouble coord); -GLAPI PFNGLFOGCOORDDPROC glad_glFogCoordd; -#define glFogCoordd glad_glFogCoordd -typedef void (APIENTRYP PFNGLFOGCOORDDVPROC)(const GLdouble *coord); -GLAPI PFNGLFOGCOORDDVPROC glad_glFogCoorddv; -#define glFogCoorddv glad_glFogCoorddv -typedef void (APIENTRYP PFNGLFOGCOORDPOINTERPROC)(GLenum type, GLsizei stride, const void *pointer); -GLAPI PFNGLFOGCOORDPOINTERPROC glad_glFogCoordPointer; -#define glFogCoordPointer glad_glFogCoordPointer -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BPROC)(GLbyte red, GLbyte green, GLbyte blue); -GLAPI PFNGLSECONDARYCOLOR3BPROC glad_glSecondaryColor3b; -#define glSecondaryColor3b glad_glSecondaryColor3b -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BVPROC)(const GLbyte *v); -GLAPI PFNGLSECONDARYCOLOR3BVPROC glad_glSecondaryColor3bv; -#define glSecondaryColor3bv glad_glSecondaryColor3bv -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DPROC)(GLdouble red, GLdouble green, GLdouble blue); -GLAPI PFNGLSECONDARYCOLOR3DPROC glad_glSecondaryColor3d; -#define glSecondaryColor3d glad_glSecondaryColor3d -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DVPROC)(const GLdouble *v); -GLAPI PFNGLSECONDARYCOLOR3DVPROC glad_glSecondaryColor3dv; -#define glSecondaryColor3dv glad_glSecondaryColor3dv -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FPROC)(GLfloat red, GLfloat green, GLfloat blue); -GLAPI PFNGLSECONDARYCOLOR3FPROC glad_glSecondaryColor3f; -#define glSecondaryColor3f glad_glSecondaryColor3f -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FVPROC)(const GLfloat *v); -GLAPI PFNGLSECONDARYCOLOR3FVPROC glad_glSecondaryColor3fv; -#define glSecondaryColor3fv glad_glSecondaryColor3fv -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IPROC)(GLint red, GLint green, GLint blue); -GLAPI PFNGLSECONDARYCOLOR3IPROC glad_glSecondaryColor3i; -#define glSecondaryColor3i glad_glSecondaryColor3i -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IVPROC)(const GLint *v); -GLAPI PFNGLSECONDARYCOLOR3IVPROC glad_glSecondaryColor3iv; -#define glSecondaryColor3iv glad_glSecondaryColor3iv -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SPROC)(GLshort red, GLshort green, GLshort blue); -GLAPI PFNGLSECONDARYCOLOR3SPROC glad_glSecondaryColor3s; -#define glSecondaryColor3s glad_glSecondaryColor3s -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SVPROC)(const GLshort *v); -GLAPI PFNGLSECONDARYCOLOR3SVPROC glad_glSecondaryColor3sv; -#define glSecondaryColor3sv glad_glSecondaryColor3sv -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBPROC)(GLubyte red, GLubyte green, GLubyte blue); -GLAPI PFNGLSECONDARYCOLOR3UBPROC glad_glSecondaryColor3ub; -#define glSecondaryColor3ub glad_glSecondaryColor3ub -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBVPROC)(const GLubyte *v); -GLAPI PFNGLSECONDARYCOLOR3UBVPROC glad_glSecondaryColor3ubv; -#define glSecondaryColor3ubv glad_glSecondaryColor3ubv -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIPROC)(GLuint red, GLuint green, GLuint blue); -GLAPI PFNGLSECONDARYCOLOR3UIPROC glad_glSecondaryColor3ui; -#define glSecondaryColor3ui glad_glSecondaryColor3ui -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIVPROC)(const GLuint *v); -GLAPI PFNGLSECONDARYCOLOR3UIVPROC glad_glSecondaryColor3uiv; -#define glSecondaryColor3uiv glad_glSecondaryColor3uiv -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USPROC)(GLushort red, GLushort green, GLushort blue); -GLAPI PFNGLSECONDARYCOLOR3USPROC glad_glSecondaryColor3us; -#define glSecondaryColor3us glad_glSecondaryColor3us -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USVPROC)(const GLushort *v); -GLAPI PFNGLSECONDARYCOLOR3USVPROC glad_glSecondaryColor3usv; -#define glSecondaryColor3usv glad_glSecondaryColor3usv -typedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTERPROC)(GLint size, GLenum type, GLsizei stride, const void *pointer); -GLAPI PFNGLSECONDARYCOLORPOINTERPROC glad_glSecondaryColorPointer; -#define glSecondaryColorPointer glad_glSecondaryColorPointer -typedef void (APIENTRYP PFNGLWINDOWPOS2DPROC)(GLdouble x, GLdouble y); -GLAPI PFNGLWINDOWPOS2DPROC glad_glWindowPos2d; -#define glWindowPos2d glad_glWindowPos2d -typedef void (APIENTRYP PFNGLWINDOWPOS2DVPROC)(const GLdouble *v); -GLAPI PFNGLWINDOWPOS2DVPROC glad_glWindowPos2dv; -#define glWindowPos2dv glad_glWindowPos2dv -typedef void (APIENTRYP PFNGLWINDOWPOS2FPROC)(GLfloat x, GLfloat y); -GLAPI PFNGLWINDOWPOS2FPROC glad_glWindowPos2f; -#define glWindowPos2f glad_glWindowPos2f -typedef void (APIENTRYP PFNGLWINDOWPOS2FVPROC)(const GLfloat *v); -GLAPI PFNGLWINDOWPOS2FVPROC glad_glWindowPos2fv; -#define glWindowPos2fv glad_glWindowPos2fv -typedef void (APIENTRYP PFNGLWINDOWPOS2IPROC)(GLint x, GLint y); -GLAPI PFNGLWINDOWPOS2IPROC glad_glWindowPos2i; -#define glWindowPos2i glad_glWindowPos2i -typedef void (APIENTRYP PFNGLWINDOWPOS2IVPROC)(const GLint *v); -GLAPI PFNGLWINDOWPOS2IVPROC glad_glWindowPos2iv; -#define glWindowPos2iv glad_glWindowPos2iv -typedef void (APIENTRYP PFNGLWINDOWPOS2SPROC)(GLshort x, GLshort y); -GLAPI PFNGLWINDOWPOS2SPROC glad_glWindowPos2s; -#define glWindowPos2s glad_glWindowPos2s -typedef void (APIENTRYP PFNGLWINDOWPOS2SVPROC)(const GLshort *v); -GLAPI PFNGLWINDOWPOS2SVPROC glad_glWindowPos2sv; -#define glWindowPos2sv glad_glWindowPos2sv -typedef void (APIENTRYP PFNGLWINDOWPOS3DPROC)(GLdouble x, GLdouble y, GLdouble z); -GLAPI PFNGLWINDOWPOS3DPROC glad_glWindowPos3d; -#define glWindowPos3d glad_glWindowPos3d -typedef void (APIENTRYP PFNGLWINDOWPOS3DVPROC)(const GLdouble *v); -GLAPI PFNGLWINDOWPOS3DVPROC glad_glWindowPos3dv; -#define glWindowPos3dv glad_glWindowPos3dv -typedef void (APIENTRYP PFNGLWINDOWPOS3FPROC)(GLfloat x, GLfloat y, GLfloat z); -GLAPI PFNGLWINDOWPOS3FPROC glad_glWindowPos3f; -#define glWindowPos3f glad_glWindowPos3f -typedef void (APIENTRYP PFNGLWINDOWPOS3FVPROC)(const GLfloat *v); -GLAPI PFNGLWINDOWPOS3FVPROC glad_glWindowPos3fv; -#define glWindowPos3fv glad_glWindowPos3fv -typedef void (APIENTRYP PFNGLWINDOWPOS3IPROC)(GLint x, GLint y, GLint z); -GLAPI PFNGLWINDOWPOS3IPROC glad_glWindowPos3i; -#define glWindowPos3i glad_glWindowPos3i -typedef void (APIENTRYP PFNGLWINDOWPOS3IVPROC)(const GLint *v); -GLAPI PFNGLWINDOWPOS3IVPROC glad_glWindowPos3iv; -#define glWindowPos3iv glad_glWindowPos3iv -typedef void (APIENTRYP PFNGLWINDOWPOS3SPROC)(GLshort x, GLshort y, GLshort z); -GLAPI PFNGLWINDOWPOS3SPROC glad_glWindowPos3s; -#define glWindowPos3s glad_glWindowPos3s -typedef void (APIENTRYP PFNGLWINDOWPOS3SVPROC)(const GLshort *v); -GLAPI PFNGLWINDOWPOS3SVPROC glad_glWindowPos3sv; -#define glWindowPos3sv glad_glWindowPos3sv -typedef void (APIENTRYP PFNGLBLENDCOLORPROC)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); -GLAPI PFNGLBLENDCOLORPROC glad_glBlendColor; -#define glBlendColor glad_glBlendColor -typedef void (APIENTRYP PFNGLBLENDEQUATIONPROC)(GLenum mode); -GLAPI PFNGLBLENDEQUATIONPROC glad_glBlendEquation; -#define glBlendEquation glad_glBlendEquation -#endif -#ifndef GL_VERSION_1_5 -#define GL_VERSION_1_5 1 -GLAPI int GLAD_GL_VERSION_1_5; -typedef void (APIENTRYP PFNGLGENQUERIESPROC)(GLsizei n, GLuint *ids); -GLAPI PFNGLGENQUERIESPROC glad_glGenQueries; -#define glGenQueries glad_glGenQueries -typedef void (APIENTRYP PFNGLDELETEQUERIESPROC)(GLsizei n, const GLuint *ids); -GLAPI PFNGLDELETEQUERIESPROC glad_glDeleteQueries; -#define glDeleteQueries glad_glDeleteQueries -typedef GLboolean (APIENTRYP PFNGLISQUERYPROC)(GLuint id); -GLAPI PFNGLISQUERYPROC glad_glIsQuery; -#define glIsQuery glad_glIsQuery -typedef void (APIENTRYP PFNGLBEGINQUERYPROC)(GLenum target, GLuint id); -GLAPI PFNGLBEGINQUERYPROC glad_glBeginQuery; -#define glBeginQuery glad_glBeginQuery -typedef void (APIENTRYP PFNGLENDQUERYPROC)(GLenum target); -GLAPI PFNGLENDQUERYPROC glad_glEndQuery; -#define glEndQuery glad_glEndQuery -typedef void (APIENTRYP PFNGLGETQUERYIVPROC)(GLenum target, GLenum pname, GLint *params); -GLAPI PFNGLGETQUERYIVPROC glad_glGetQueryiv; -#define glGetQueryiv glad_glGetQueryiv -typedef void (APIENTRYP PFNGLGETQUERYOBJECTIVPROC)(GLuint id, GLenum pname, GLint *params); -GLAPI PFNGLGETQUERYOBJECTIVPROC glad_glGetQueryObjectiv; -#define glGetQueryObjectiv glad_glGetQueryObjectiv -typedef void (APIENTRYP PFNGLGETQUERYOBJECTUIVPROC)(GLuint id, GLenum pname, GLuint *params); -GLAPI PFNGLGETQUERYOBJECTUIVPROC glad_glGetQueryObjectuiv; -#define glGetQueryObjectuiv glad_glGetQueryObjectuiv -typedef void (APIENTRYP PFNGLBINDBUFFERPROC)(GLenum target, GLuint buffer); -GLAPI PFNGLBINDBUFFERPROC glad_glBindBuffer; -#define glBindBuffer glad_glBindBuffer -typedef void (APIENTRYP PFNGLDELETEBUFFERSPROC)(GLsizei n, const GLuint *buffers); -GLAPI PFNGLDELETEBUFFERSPROC glad_glDeleteBuffers; -#define glDeleteBuffers glad_glDeleteBuffers -typedef void (APIENTRYP PFNGLGENBUFFERSPROC)(GLsizei n, GLuint *buffers); -GLAPI PFNGLGENBUFFERSPROC glad_glGenBuffers; -#define glGenBuffers glad_glGenBuffers -typedef GLboolean (APIENTRYP PFNGLISBUFFERPROC)(GLuint buffer); -GLAPI PFNGLISBUFFERPROC glad_glIsBuffer; -#define glIsBuffer glad_glIsBuffer -typedef void (APIENTRYP PFNGLBUFFERDATAPROC)(GLenum target, GLsizeiptr size, const void *data, GLenum usage); -GLAPI PFNGLBUFFERDATAPROC glad_glBufferData; -#define glBufferData glad_glBufferData -typedef void (APIENTRYP PFNGLBUFFERSUBDATAPROC)(GLenum target, GLintptr offset, GLsizeiptr size, const void *data); -GLAPI PFNGLBUFFERSUBDATAPROC glad_glBufferSubData; -#define glBufferSubData glad_glBufferSubData -typedef void (APIENTRYP PFNGLGETBUFFERSUBDATAPROC)(GLenum target, GLintptr offset, GLsizeiptr size, void *data); -GLAPI PFNGLGETBUFFERSUBDATAPROC glad_glGetBufferSubData; -#define glGetBufferSubData glad_glGetBufferSubData -typedef void * (APIENTRYP PFNGLMAPBUFFERPROC)(GLenum target, GLenum access); -GLAPI PFNGLMAPBUFFERPROC glad_glMapBuffer; -#define glMapBuffer glad_glMapBuffer -typedef GLboolean (APIENTRYP PFNGLUNMAPBUFFERPROC)(GLenum target); -GLAPI PFNGLUNMAPBUFFERPROC glad_glUnmapBuffer; -#define glUnmapBuffer glad_glUnmapBuffer -typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERIVPROC)(GLenum target, GLenum pname, GLint *params); -GLAPI PFNGLGETBUFFERPARAMETERIVPROC glad_glGetBufferParameteriv; -#define glGetBufferParameteriv glad_glGetBufferParameteriv -typedef void (APIENTRYP PFNGLGETBUFFERPOINTERVPROC)(GLenum target, GLenum pname, void **params); -GLAPI PFNGLGETBUFFERPOINTERVPROC glad_glGetBufferPointerv; -#define glGetBufferPointerv glad_glGetBufferPointerv -#endif -#ifndef GL_VERSION_2_0 -#define GL_VERSION_2_0 1 -GLAPI int GLAD_GL_VERSION_2_0; -typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEPROC)(GLenum modeRGB, GLenum modeAlpha); -GLAPI PFNGLBLENDEQUATIONSEPARATEPROC glad_glBlendEquationSeparate; -#define glBlendEquationSeparate glad_glBlendEquationSeparate -typedef void (APIENTRYP PFNGLDRAWBUFFERSPROC)(GLsizei n, const GLenum *bufs); -GLAPI PFNGLDRAWBUFFERSPROC glad_glDrawBuffers; -#define glDrawBuffers glad_glDrawBuffers -typedef void (APIENTRYP PFNGLSTENCILOPSEPARATEPROC)(GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); -GLAPI PFNGLSTENCILOPSEPARATEPROC glad_glStencilOpSeparate; -#define glStencilOpSeparate glad_glStencilOpSeparate -typedef void (APIENTRYP PFNGLSTENCILFUNCSEPARATEPROC)(GLenum face, GLenum func, GLint ref, GLuint mask); -GLAPI PFNGLSTENCILFUNCSEPARATEPROC glad_glStencilFuncSeparate; -#define glStencilFuncSeparate glad_glStencilFuncSeparate -typedef void (APIENTRYP PFNGLSTENCILMASKSEPARATEPROC)(GLenum face, GLuint mask); -GLAPI PFNGLSTENCILMASKSEPARATEPROC glad_glStencilMaskSeparate; -#define glStencilMaskSeparate glad_glStencilMaskSeparate -typedef void (APIENTRYP PFNGLATTACHSHADERPROC)(GLuint program, GLuint shader); -GLAPI PFNGLATTACHSHADERPROC glad_glAttachShader; -#define glAttachShader glad_glAttachShader -typedef void (APIENTRYP PFNGLBINDATTRIBLOCATIONPROC)(GLuint program, GLuint index, const GLchar *name); -GLAPI PFNGLBINDATTRIBLOCATIONPROC glad_glBindAttribLocation; -#define glBindAttribLocation glad_glBindAttribLocation -typedef void (APIENTRYP PFNGLCOMPILESHADERPROC)(GLuint shader); -GLAPI PFNGLCOMPILESHADERPROC glad_glCompileShader; -#define glCompileShader glad_glCompileShader -typedef GLuint (APIENTRYP PFNGLCREATEPROGRAMPROC)(); -GLAPI PFNGLCREATEPROGRAMPROC glad_glCreateProgram; -#define glCreateProgram glad_glCreateProgram -typedef GLuint (APIENTRYP PFNGLCREATESHADERPROC)(GLenum type); -GLAPI PFNGLCREATESHADERPROC glad_glCreateShader; -#define glCreateShader glad_glCreateShader -typedef void (APIENTRYP PFNGLDELETEPROGRAMPROC)(GLuint program); -GLAPI PFNGLDELETEPROGRAMPROC glad_glDeleteProgram; -#define glDeleteProgram glad_glDeleteProgram -typedef void (APIENTRYP PFNGLDELETESHADERPROC)(GLuint shader); -GLAPI PFNGLDELETESHADERPROC glad_glDeleteShader; -#define glDeleteShader glad_glDeleteShader -typedef void (APIENTRYP PFNGLDETACHSHADERPROC)(GLuint program, GLuint shader); -GLAPI PFNGLDETACHSHADERPROC glad_glDetachShader; -#define glDetachShader glad_glDetachShader -typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYPROC)(GLuint index); -GLAPI PFNGLDISABLEVERTEXATTRIBARRAYPROC glad_glDisableVertexAttribArray; -#define glDisableVertexAttribArray glad_glDisableVertexAttribArray -typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYPROC)(GLuint index); -GLAPI PFNGLENABLEVERTEXATTRIBARRAYPROC glad_glEnableVertexAttribArray; -#define glEnableVertexAttribArray glad_glEnableVertexAttribArray -typedef void (APIENTRYP PFNGLGETACTIVEATTRIBPROC)(GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); -GLAPI PFNGLGETACTIVEATTRIBPROC glad_glGetActiveAttrib; -#define glGetActiveAttrib glad_glGetActiveAttrib -typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMPROC)(GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); -GLAPI PFNGLGETACTIVEUNIFORMPROC glad_glGetActiveUniform; -#define glGetActiveUniform glad_glGetActiveUniform -typedef void (APIENTRYP PFNGLGETATTACHEDSHADERSPROC)(GLuint program, GLsizei maxCount, GLsizei *count, GLuint *shaders); -GLAPI PFNGLGETATTACHEDSHADERSPROC glad_glGetAttachedShaders; -#define glGetAttachedShaders glad_glGetAttachedShaders -typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONPROC)(GLuint program, const GLchar *name); -GLAPI PFNGLGETATTRIBLOCATIONPROC glad_glGetAttribLocation; -#define glGetAttribLocation glad_glGetAttribLocation -typedef void (APIENTRYP PFNGLGETPROGRAMIVPROC)(GLuint program, GLenum pname, GLint *params); -GLAPI PFNGLGETPROGRAMIVPROC glad_glGetProgramiv; -#define glGetProgramiv glad_glGetProgramiv -typedef void (APIENTRYP PFNGLGETPROGRAMINFOLOGPROC)(GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog); -GLAPI PFNGLGETPROGRAMINFOLOGPROC glad_glGetProgramInfoLog; -#define glGetProgramInfoLog glad_glGetProgramInfoLog -typedef void (APIENTRYP PFNGLGETSHADERIVPROC)(GLuint shader, GLenum pname, GLint *params); -GLAPI PFNGLGETSHADERIVPROC glad_glGetShaderiv; -#define glGetShaderiv glad_glGetShaderiv -typedef void (APIENTRYP PFNGLGETSHADERINFOLOGPROC)(GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog); -GLAPI PFNGLGETSHADERINFOLOGPROC glad_glGetShaderInfoLog; -#define glGetShaderInfoLog glad_glGetShaderInfoLog -typedef void (APIENTRYP PFNGLGETSHADERSOURCEPROC)(GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *source); -GLAPI PFNGLGETSHADERSOURCEPROC glad_glGetShaderSource; -#define glGetShaderSource glad_glGetShaderSource -typedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONPROC)(GLuint program, const GLchar *name); -GLAPI PFNGLGETUNIFORMLOCATIONPROC glad_glGetUniformLocation; -#define glGetUniformLocation glad_glGetUniformLocation -typedef void (APIENTRYP PFNGLGETUNIFORMFVPROC)(GLuint program, GLint location, GLfloat *params); -GLAPI PFNGLGETUNIFORMFVPROC glad_glGetUniformfv; -#define glGetUniformfv glad_glGetUniformfv -typedef void (APIENTRYP PFNGLGETUNIFORMIVPROC)(GLuint program, GLint location, GLint *params); -GLAPI PFNGLGETUNIFORMIVPROC glad_glGetUniformiv; -#define glGetUniformiv glad_glGetUniformiv -typedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVPROC)(GLuint index, GLenum pname, GLdouble *params); -GLAPI PFNGLGETVERTEXATTRIBDVPROC glad_glGetVertexAttribdv; -#define glGetVertexAttribdv glad_glGetVertexAttribdv -typedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVPROC)(GLuint index, GLenum pname, GLfloat *params); -GLAPI PFNGLGETVERTEXATTRIBFVPROC glad_glGetVertexAttribfv; -#define glGetVertexAttribfv glad_glGetVertexAttribfv -typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVPROC)(GLuint index, GLenum pname, GLint *params); -GLAPI PFNGLGETVERTEXATTRIBIVPROC glad_glGetVertexAttribiv; -#define glGetVertexAttribiv glad_glGetVertexAttribiv -typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVPROC)(GLuint index, GLenum pname, void **pointer); -GLAPI PFNGLGETVERTEXATTRIBPOINTERVPROC glad_glGetVertexAttribPointerv; -#define glGetVertexAttribPointerv glad_glGetVertexAttribPointerv -typedef GLboolean (APIENTRYP PFNGLISPROGRAMPROC)(GLuint program); -GLAPI PFNGLISPROGRAMPROC glad_glIsProgram; -#define glIsProgram glad_glIsProgram -typedef GLboolean (APIENTRYP PFNGLISSHADERPROC)(GLuint shader); -GLAPI PFNGLISSHADERPROC glad_glIsShader; -#define glIsShader glad_glIsShader -typedef void (APIENTRYP PFNGLLINKPROGRAMPROC)(GLuint program); -GLAPI PFNGLLINKPROGRAMPROC glad_glLinkProgram; -#define glLinkProgram glad_glLinkProgram -typedef void (APIENTRYP PFNGLSHADERSOURCEPROC)(GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length); -GLAPI PFNGLSHADERSOURCEPROC glad_glShaderSource; -#define glShaderSource glad_glShaderSource -typedef void (APIENTRYP PFNGLUSEPROGRAMPROC)(GLuint program); -GLAPI PFNGLUSEPROGRAMPROC glad_glUseProgram; -#define glUseProgram glad_glUseProgram -typedef void (APIENTRYP PFNGLUNIFORM1FPROC)(GLint location, GLfloat v0); -GLAPI PFNGLUNIFORM1FPROC glad_glUniform1f; -#define glUniform1f glad_glUniform1f -typedef void (APIENTRYP PFNGLUNIFORM2FPROC)(GLint location, GLfloat v0, GLfloat v1); -GLAPI PFNGLUNIFORM2FPROC glad_glUniform2f; -#define glUniform2f glad_glUniform2f -typedef void (APIENTRYP PFNGLUNIFORM3FPROC)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2); -GLAPI PFNGLUNIFORM3FPROC glad_glUniform3f; -#define glUniform3f glad_glUniform3f -typedef void (APIENTRYP PFNGLUNIFORM4FPROC)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); -GLAPI PFNGLUNIFORM4FPROC glad_glUniform4f; -#define glUniform4f glad_glUniform4f -typedef void (APIENTRYP PFNGLUNIFORM1IPROC)(GLint location, GLint v0); -GLAPI PFNGLUNIFORM1IPROC glad_glUniform1i; -#define glUniform1i glad_glUniform1i -typedef void (APIENTRYP PFNGLUNIFORM2IPROC)(GLint location, GLint v0, GLint v1); -GLAPI PFNGLUNIFORM2IPROC glad_glUniform2i; -#define glUniform2i glad_glUniform2i -typedef void (APIENTRYP PFNGLUNIFORM3IPROC)(GLint location, GLint v0, GLint v1, GLint v2); -GLAPI PFNGLUNIFORM3IPROC glad_glUniform3i; -#define glUniform3i glad_glUniform3i -typedef void (APIENTRYP PFNGLUNIFORM4IPROC)(GLint location, GLint v0, GLint v1, GLint v2, GLint v3); -GLAPI PFNGLUNIFORM4IPROC glad_glUniform4i; -#define glUniform4i glad_glUniform4i -typedef void (APIENTRYP PFNGLUNIFORM1FVPROC)(GLint location, GLsizei count, const GLfloat *value); -GLAPI PFNGLUNIFORM1FVPROC glad_glUniform1fv; -#define glUniform1fv glad_glUniform1fv -typedef void (APIENTRYP PFNGLUNIFORM2FVPROC)(GLint location, GLsizei count, const GLfloat *value); -GLAPI PFNGLUNIFORM2FVPROC glad_glUniform2fv; -#define glUniform2fv glad_glUniform2fv -typedef void (APIENTRYP PFNGLUNIFORM3FVPROC)(GLint location, GLsizei count, const GLfloat *value); -GLAPI PFNGLUNIFORM3FVPROC glad_glUniform3fv; -#define glUniform3fv glad_glUniform3fv -typedef void (APIENTRYP PFNGLUNIFORM4FVPROC)(GLint location, GLsizei count, const GLfloat *value); -GLAPI PFNGLUNIFORM4FVPROC glad_glUniform4fv; -#define glUniform4fv glad_glUniform4fv -typedef void (APIENTRYP PFNGLUNIFORM1IVPROC)(GLint location, GLsizei count, const GLint *value); -GLAPI PFNGLUNIFORM1IVPROC glad_glUniform1iv; -#define glUniform1iv glad_glUniform1iv -typedef void (APIENTRYP PFNGLUNIFORM2IVPROC)(GLint location, GLsizei count, const GLint *value); -GLAPI PFNGLUNIFORM2IVPROC glad_glUniform2iv; -#define glUniform2iv glad_glUniform2iv -typedef void (APIENTRYP PFNGLUNIFORM3IVPROC)(GLint location, GLsizei count, const GLint *value); -GLAPI PFNGLUNIFORM3IVPROC glad_glUniform3iv; -#define glUniform3iv glad_glUniform3iv -typedef void (APIENTRYP PFNGLUNIFORM4IVPROC)(GLint location, GLsizei count, const GLint *value); -GLAPI PFNGLUNIFORM4IVPROC glad_glUniform4iv; -#define glUniform4iv glad_glUniform4iv -typedef void (APIENTRYP PFNGLUNIFORMMATRIX2FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI PFNGLUNIFORMMATRIX2FVPROC glad_glUniformMatrix2fv; -#define glUniformMatrix2fv glad_glUniformMatrix2fv -typedef void (APIENTRYP PFNGLUNIFORMMATRIX3FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI PFNGLUNIFORMMATRIX3FVPROC glad_glUniformMatrix3fv; -#define glUniformMatrix3fv glad_glUniformMatrix3fv -typedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI PFNGLUNIFORMMATRIX4FVPROC glad_glUniformMatrix4fv; -#define glUniformMatrix4fv glad_glUniformMatrix4fv -typedef void (APIENTRYP PFNGLVALIDATEPROGRAMPROC)(GLuint program); -GLAPI PFNGLVALIDATEPROGRAMPROC glad_glValidateProgram; -#define glValidateProgram glad_glValidateProgram -typedef void (APIENTRYP PFNGLVERTEXATTRIB1DPROC)(GLuint index, GLdouble x); -GLAPI PFNGLVERTEXATTRIB1DPROC glad_glVertexAttrib1d; -#define glVertexAttrib1d glad_glVertexAttrib1d -typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVPROC)(GLuint index, const GLdouble *v); -GLAPI PFNGLVERTEXATTRIB1DVPROC glad_glVertexAttrib1dv; -#define glVertexAttrib1dv glad_glVertexAttrib1dv -typedef void (APIENTRYP PFNGLVERTEXATTRIB1FPROC)(GLuint index, GLfloat x); -GLAPI PFNGLVERTEXATTRIB1FPROC glad_glVertexAttrib1f; -#define glVertexAttrib1f glad_glVertexAttrib1f -typedef void (APIENTRYP PFNGLVERTEXATTRIB1FVPROC)(GLuint index, const GLfloat *v); -GLAPI PFNGLVERTEXATTRIB1FVPROC glad_glVertexAttrib1fv; -#define glVertexAttrib1fv glad_glVertexAttrib1fv -typedef void (APIENTRYP PFNGLVERTEXATTRIB1SPROC)(GLuint index, GLshort x); -GLAPI PFNGLVERTEXATTRIB1SPROC glad_glVertexAttrib1s; -#define glVertexAttrib1s glad_glVertexAttrib1s -typedef void (APIENTRYP PFNGLVERTEXATTRIB1SVPROC)(GLuint index, const GLshort *v); -GLAPI PFNGLVERTEXATTRIB1SVPROC glad_glVertexAttrib1sv; -#define glVertexAttrib1sv glad_glVertexAttrib1sv -typedef void (APIENTRYP PFNGLVERTEXATTRIB2DPROC)(GLuint index, GLdouble x, GLdouble y); -GLAPI PFNGLVERTEXATTRIB2DPROC glad_glVertexAttrib2d; -#define glVertexAttrib2d glad_glVertexAttrib2d -typedef void (APIENTRYP PFNGLVERTEXATTRIB2DVPROC)(GLuint index, const GLdouble *v); -GLAPI PFNGLVERTEXATTRIB2DVPROC glad_glVertexAttrib2dv; -#define glVertexAttrib2dv glad_glVertexAttrib2dv -typedef void (APIENTRYP PFNGLVERTEXATTRIB2FPROC)(GLuint index, GLfloat x, GLfloat y); -GLAPI PFNGLVERTEXATTRIB2FPROC glad_glVertexAttrib2f; -#define glVertexAttrib2f glad_glVertexAttrib2f -typedef void (APIENTRYP PFNGLVERTEXATTRIB2FVPROC)(GLuint index, const GLfloat *v); -GLAPI PFNGLVERTEXATTRIB2FVPROC glad_glVertexAttrib2fv; -#define glVertexAttrib2fv glad_glVertexAttrib2fv -typedef void (APIENTRYP PFNGLVERTEXATTRIB2SPROC)(GLuint index, GLshort x, GLshort y); -GLAPI PFNGLVERTEXATTRIB2SPROC glad_glVertexAttrib2s; -#define glVertexAttrib2s glad_glVertexAttrib2s -typedef void (APIENTRYP PFNGLVERTEXATTRIB2SVPROC)(GLuint index, const GLshort *v); -GLAPI PFNGLVERTEXATTRIB2SVPROC glad_glVertexAttrib2sv; -#define glVertexAttrib2sv glad_glVertexAttrib2sv -typedef void (APIENTRYP PFNGLVERTEXATTRIB3DPROC)(GLuint index, GLdouble x, GLdouble y, GLdouble z); -GLAPI PFNGLVERTEXATTRIB3DPROC glad_glVertexAttrib3d; -#define glVertexAttrib3d glad_glVertexAttrib3d -typedef void (APIENTRYP PFNGLVERTEXATTRIB3DVPROC)(GLuint index, const GLdouble *v); -GLAPI PFNGLVERTEXATTRIB3DVPROC glad_glVertexAttrib3dv; -#define glVertexAttrib3dv glad_glVertexAttrib3dv -typedef void (APIENTRYP PFNGLVERTEXATTRIB3FPROC)(GLuint index, GLfloat x, GLfloat y, GLfloat z); -GLAPI PFNGLVERTEXATTRIB3FPROC glad_glVertexAttrib3f; -#define glVertexAttrib3f glad_glVertexAttrib3f -typedef void (APIENTRYP PFNGLVERTEXATTRIB3FVPROC)(GLuint index, const GLfloat *v); -GLAPI PFNGLVERTEXATTRIB3FVPROC glad_glVertexAttrib3fv; -#define glVertexAttrib3fv glad_glVertexAttrib3fv -typedef void (APIENTRYP PFNGLVERTEXATTRIB3SPROC)(GLuint index, GLshort x, GLshort y, GLshort z); -GLAPI PFNGLVERTEXATTRIB3SPROC glad_glVertexAttrib3s; -#define glVertexAttrib3s glad_glVertexAttrib3s -typedef void (APIENTRYP PFNGLVERTEXATTRIB3SVPROC)(GLuint index, const GLshort *v); -GLAPI PFNGLVERTEXATTRIB3SVPROC glad_glVertexAttrib3sv; -#define glVertexAttrib3sv glad_glVertexAttrib3sv -typedef void (APIENTRYP PFNGLVERTEXATTRIB4NBVPROC)(GLuint index, const GLbyte *v); -GLAPI PFNGLVERTEXATTRIB4NBVPROC glad_glVertexAttrib4Nbv; -#define glVertexAttrib4Nbv glad_glVertexAttrib4Nbv -typedef void (APIENTRYP PFNGLVERTEXATTRIB4NIVPROC)(GLuint index, const GLint *v); -GLAPI PFNGLVERTEXATTRIB4NIVPROC glad_glVertexAttrib4Niv; -#define glVertexAttrib4Niv glad_glVertexAttrib4Niv -typedef void (APIENTRYP PFNGLVERTEXATTRIB4NSVPROC)(GLuint index, const GLshort *v); -GLAPI PFNGLVERTEXATTRIB4NSVPROC glad_glVertexAttrib4Nsv; -#define glVertexAttrib4Nsv glad_glVertexAttrib4Nsv -typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBPROC)(GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); -GLAPI PFNGLVERTEXATTRIB4NUBPROC glad_glVertexAttrib4Nub; -#define glVertexAttrib4Nub glad_glVertexAttrib4Nub -typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBVPROC)(GLuint index, const GLubyte *v); -GLAPI PFNGLVERTEXATTRIB4NUBVPROC glad_glVertexAttrib4Nubv; -#define glVertexAttrib4Nubv glad_glVertexAttrib4Nubv -typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUIVPROC)(GLuint index, const GLuint *v); -GLAPI PFNGLVERTEXATTRIB4NUIVPROC glad_glVertexAttrib4Nuiv; -#define glVertexAttrib4Nuiv glad_glVertexAttrib4Nuiv -typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUSVPROC)(GLuint index, const GLushort *v); -GLAPI PFNGLVERTEXATTRIB4NUSVPROC glad_glVertexAttrib4Nusv; -#define glVertexAttrib4Nusv glad_glVertexAttrib4Nusv -typedef void (APIENTRYP PFNGLVERTEXATTRIB4BVPROC)(GLuint index, const GLbyte *v); -GLAPI PFNGLVERTEXATTRIB4BVPROC glad_glVertexAttrib4bv; -#define glVertexAttrib4bv glad_glVertexAttrib4bv -typedef void (APIENTRYP PFNGLVERTEXATTRIB4DPROC)(GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); -GLAPI PFNGLVERTEXATTRIB4DPROC glad_glVertexAttrib4d; -#define glVertexAttrib4d glad_glVertexAttrib4d -typedef void (APIENTRYP PFNGLVERTEXATTRIB4DVPROC)(GLuint index, const GLdouble *v); -GLAPI PFNGLVERTEXATTRIB4DVPROC glad_glVertexAttrib4dv; -#define glVertexAttrib4dv glad_glVertexAttrib4dv -typedef void (APIENTRYP PFNGLVERTEXATTRIB4FPROC)(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); -GLAPI PFNGLVERTEXATTRIB4FPROC glad_glVertexAttrib4f; -#define glVertexAttrib4f glad_glVertexAttrib4f -typedef void (APIENTRYP PFNGLVERTEXATTRIB4FVPROC)(GLuint index, const GLfloat *v); -GLAPI PFNGLVERTEXATTRIB4FVPROC glad_glVertexAttrib4fv; -#define glVertexAttrib4fv glad_glVertexAttrib4fv -typedef void (APIENTRYP PFNGLVERTEXATTRIB4IVPROC)(GLuint index, const GLint *v); -GLAPI PFNGLVERTEXATTRIB4IVPROC glad_glVertexAttrib4iv; -#define glVertexAttrib4iv glad_glVertexAttrib4iv -typedef void (APIENTRYP PFNGLVERTEXATTRIB4SPROC)(GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); -GLAPI PFNGLVERTEXATTRIB4SPROC glad_glVertexAttrib4s; -#define glVertexAttrib4s glad_glVertexAttrib4s -typedef void (APIENTRYP PFNGLVERTEXATTRIB4SVPROC)(GLuint index, const GLshort *v); -GLAPI PFNGLVERTEXATTRIB4SVPROC glad_glVertexAttrib4sv; -#define glVertexAttrib4sv glad_glVertexAttrib4sv -typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVPROC)(GLuint index, const GLubyte *v); -GLAPI PFNGLVERTEXATTRIB4UBVPROC glad_glVertexAttrib4ubv; -#define glVertexAttrib4ubv glad_glVertexAttrib4ubv -typedef void (APIENTRYP PFNGLVERTEXATTRIB4UIVPROC)(GLuint index, const GLuint *v); -GLAPI PFNGLVERTEXATTRIB4UIVPROC glad_glVertexAttrib4uiv; -#define glVertexAttrib4uiv glad_glVertexAttrib4uiv -typedef void (APIENTRYP PFNGLVERTEXATTRIB4USVPROC)(GLuint index, const GLushort *v); -GLAPI PFNGLVERTEXATTRIB4USVPROC glad_glVertexAttrib4usv; -#define glVertexAttrib4usv glad_glVertexAttrib4usv -typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERPROC)(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer); -GLAPI PFNGLVERTEXATTRIBPOINTERPROC glad_glVertexAttribPointer; -#define glVertexAttribPointer glad_glVertexAttribPointer -#endif -#ifndef GL_VERSION_2_1 -#define GL_VERSION_2_1 1 -GLAPI int GLAD_GL_VERSION_2_1; -typedef void (APIENTRYP PFNGLUNIFORMMATRIX2X3FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI PFNGLUNIFORMMATRIX2X3FVPROC glad_glUniformMatrix2x3fv; -#define glUniformMatrix2x3fv glad_glUniformMatrix2x3fv -typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X2FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI PFNGLUNIFORMMATRIX3X2FVPROC glad_glUniformMatrix3x2fv; -#define glUniformMatrix3x2fv glad_glUniformMatrix3x2fv -typedef void (APIENTRYP PFNGLUNIFORMMATRIX2X4FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI PFNGLUNIFORMMATRIX2X4FVPROC glad_glUniformMatrix2x4fv; -#define glUniformMatrix2x4fv glad_glUniformMatrix2x4fv -typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X2FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI PFNGLUNIFORMMATRIX4X2FVPROC glad_glUniformMatrix4x2fv; -#define glUniformMatrix4x2fv glad_glUniformMatrix4x2fv -typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X4FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI PFNGLUNIFORMMATRIX3X4FVPROC glad_glUniformMatrix3x4fv; -#define glUniformMatrix3x4fv glad_glUniformMatrix3x4fv -typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X3FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI PFNGLUNIFORMMATRIX4X3FVPROC glad_glUniformMatrix4x3fv; -#define glUniformMatrix4x3fv glad_glUniformMatrix4x3fv -#endif -#ifndef GL_VERSION_3_0 -#define GL_VERSION_3_0 1 -GLAPI int GLAD_GL_VERSION_3_0; -typedef void (APIENTRYP PFNGLCOLORMASKIPROC)(GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a); -GLAPI PFNGLCOLORMASKIPROC glad_glColorMaski; -#define glColorMaski glad_glColorMaski -typedef void (APIENTRYP PFNGLGETBOOLEANI_VPROC)(GLenum target, GLuint index, GLboolean *data); -GLAPI PFNGLGETBOOLEANI_VPROC glad_glGetBooleani_v; -#define glGetBooleani_v glad_glGetBooleani_v -typedef void (APIENTRYP PFNGLGETINTEGERI_VPROC)(GLenum target, GLuint index, GLint *data); -GLAPI PFNGLGETINTEGERI_VPROC glad_glGetIntegeri_v; -#define glGetIntegeri_v glad_glGetIntegeri_v -typedef void (APIENTRYP PFNGLENABLEIPROC)(GLenum target, GLuint index); -GLAPI PFNGLENABLEIPROC glad_glEnablei; -#define glEnablei glad_glEnablei -typedef void (APIENTRYP PFNGLDISABLEIPROC)(GLenum target, GLuint index); -GLAPI PFNGLDISABLEIPROC glad_glDisablei; -#define glDisablei glad_glDisablei -typedef GLboolean (APIENTRYP PFNGLISENABLEDIPROC)(GLenum target, GLuint index); -GLAPI PFNGLISENABLEDIPROC glad_glIsEnabledi; -#define glIsEnabledi glad_glIsEnabledi -typedef void (APIENTRYP PFNGLBEGINTRANSFORMFEEDBACKPROC)(GLenum primitiveMode); -GLAPI PFNGLBEGINTRANSFORMFEEDBACKPROC glad_glBeginTransformFeedback; -#define glBeginTransformFeedback glad_glBeginTransformFeedback -typedef void (APIENTRYP PFNGLENDTRANSFORMFEEDBACKPROC)(); -GLAPI PFNGLENDTRANSFORMFEEDBACKPROC glad_glEndTransformFeedback; -#define glEndTransformFeedback glad_glEndTransformFeedback -typedef void (APIENTRYP PFNGLBINDBUFFERRANGEPROC)(GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); -GLAPI PFNGLBINDBUFFERRANGEPROC glad_glBindBufferRange; -#define glBindBufferRange glad_glBindBufferRange -typedef void (APIENTRYP PFNGLBINDBUFFERBASEPROC)(GLenum target, GLuint index, GLuint buffer); -GLAPI PFNGLBINDBUFFERBASEPROC glad_glBindBufferBase; -#define glBindBufferBase glad_glBindBufferBase -typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKVARYINGSPROC)(GLuint program, GLsizei count, const GLchar *const*varyings, GLenum bufferMode); -GLAPI PFNGLTRANSFORMFEEDBACKVARYINGSPROC glad_glTransformFeedbackVaryings; -#define glTransformFeedbackVaryings glad_glTransformFeedbackVaryings -typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKVARYINGPROC)(GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name); -GLAPI PFNGLGETTRANSFORMFEEDBACKVARYINGPROC glad_glGetTransformFeedbackVarying; -#define glGetTransformFeedbackVarying glad_glGetTransformFeedbackVarying -typedef void (APIENTRYP PFNGLCLAMPCOLORPROC)(GLenum target, GLenum clamp); -GLAPI PFNGLCLAMPCOLORPROC glad_glClampColor; -#define glClampColor glad_glClampColor -typedef void (APIENTRYP PFNGLBEGINCONDITIONALRENDERPROC)(GLuint id, GLenum mode); -GLAPI PFNGLBEGINCONDITIONALRENDERPROC glad_glBeginConditionalRender; -#define glBeginConditionalRender glad_glBeginConditionalRender -typedef void (APIENTRYP PFNGLENDCONDITIONALRENDERPROC)(); -GLAPI PFNGLENDCONDITIONALRENDERPROC glad_glEndConditionalRender; -#define glEndConditionalRender glad_glEndConditionalRender -typedef void (APIENTRYP PFNGLVERTEXATTRIBIPOINTERPROC)(GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer); -GLAPI PFNGLVERTEXATTRIBIPOINTERPROC glad_glVertexAttribIPointer; -#define glVertexAttribIPointer glad_glVertexAttribIPointer -typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIIVPROC)(GLuint index, GLenum pname, GLint *params); -GLAPI PFNGLGETVERTEXATTRIBIIVPROC glad_glGetVertexAttribIiv; -#define glGetVertexAttribIiv glad_glGetVertexAttribIiv -typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIUIVPROC)(GLuint index, GLenum pname, GLuint *params); -GLAPI PFNGLGETVERTEXATTRIBIUIVPROC glad_glGetVertexAttribIuiv; -#define glGetVertexAttribIuiv glad_glGetVertexAttribIuiv -typedef void (APIENTRYP PFNGLVERTEXATTRIBI1IPROC)(GLuint index, GLint x); -GLAPI PFNGLVERTEXATTRIBI1IPROC glad_glVertexAttribI1i; -#define glVertexAttribI1i glad_glVertexAttribI1i -typedef void (APIENTRYP PFNGLVERTEXATTRIBI2IPROC)(GLuint index, GLint x, GLint y); -GLAPI PFNGLVERTEXATTRIBI2IPROC glad_glVertexAttribI2i; -#define glVertexAttribI2i glad_glVertexAttribI2i -typedef void (APIENTRYP PFNGLVERTEXATTRIBI3IPROC)(GLuint index, GLint x, GLint y, GLint z); -GLAPI PFNGLVERTEXATTRIBI3IPROC glad_glVertexAttribI3i; -#define glVertexAttribI3i glad_glVertexAttribI3i -typedef void (APIENTRYP PFNGLVERTEXATTRIBI4IPROC)(GLuint index, GLint x, GLint y, GLint z, GLint w); -GLAPI PFNGLVERTEXATTRIBI4IPROC glad_glVertexAttribI4i; -#define glVertexAttribI4i glad_glVertexAttribI4i -typedef void (APIENTRYP PFNGLVERTEXATTRIBI1UIPROC)(GLuint index, GLuint x); -GLAPI PFNGLVERTEXATTRIBI1UIPROC glad_glVertexAttribI1ui; -#define glVertexAttribI1ui glad_glVertexAttribI1ui -typedef void (APIENTRYP PFNGLVERTEXATTRIBI2UIPROC)(GLuint index, GLuint x, GLuint y); -GLAPI PFNGLVERTEXATTRIBI2UIPROC glad_glVertexAttribI2ui; -#define glVertexAttribI2ui glad_glVertexAttribI2ui -typedef void (APIENTRYP PFNGLVERTEXATTRIBI3UIPROC)(GLuint index, GLuint x, GLuint y, GLuint z); -GLAPI PFNGLVERTEXATTRIBI3UIPROC glad_glVertexAttribI3ui; -#define glVertexAttribI3ui glad_glVertexAttribI3ui -typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UIPROC)(GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); -GLAPI PFNGLVERTEXATTRIBI4UIPROC glad_glVertexAttribI4ui; -#define glVertexAttribI4ui glad_glVertexAttribI4ui -typedef void (APIENTRYP PFNGLVERTEXATTRIBI1IVPROC)(GLuint index, const GLint *v); -GLAPI PFNGLVERTEXATTRIBI1IVPROC glad_glVertexAttribI1iv; -#define glVertexAttribI1iv glad_glVertexAttribI1iv -typedef void (APIENTRYP PFNGLVERTEXATTRIBI2IVPROC)(GLuint index, const GLint *v); -GLAPI PFNGLVERTEXATTRIBI2IVPROC glad_glVertexAttribI2iv; -#define glVertexAttribI2iv glad_glVertexAttribI2iv -typedef void (APIENTRYP PFNGLVERTEXATTRIBI3IVPROC)(GLuint index, const GLint *v); -GLAPI PFNGLVERTEXATTRIBI3IVPROC glad_glVertexAttribI3iv; -#define glVertexAttribI3iv glad_glVertexAttribI3iv -typedef void (APIENTRYP PFNGLVERTEXATTRIBI4IVPROC)(GLuint index, const GLint *v); -GLAPI PFNGLVERTEXATTRIBI4IVPROC glad_glVertexAttribI4iv; -#define glVertexAttribI4iv glad_glVertexAttribI4iv -typedef void (APIENTRYP PFNGLVERTEXATTRIBI1UIVPROC)(GLuint index, const GLuint *v); -GLAPI PFNGLVERTEXATTRIBI1UIVPROC glad_glVertexAttribI1uiv; -#define glVertexAttribI1uiv glad_glVertexAttribI1uiv -typedef void (APIENTRYP PFNGLVERTEXATTRIBI2UIVPROC)(GLuint index, const GLuint *v); -GLAPI PFNGLVERTEXATTRIBI2UIVPROC glad_glVertexAttribI2uiv; -#define glVertexAttribI2uiv glad_glVertexAttribI2uiv -typedef void (APIENTRYP PFNGLVERTEXATTRIBI3UIVPROC)(GLuint index, const GLuint *v); -GLAPI PFNGLVERTEXATTRIBI3UIVPROC glad_glVertexAttribI3uiv; -#define glVertexAttribI3uiv glad_glVertexAttribI3uiv -typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UIVPROC)(GLuint index, const GLuint *v); -GLAPI PFNGLVERTEXATTRIBI4UIVPROC glad_glVertexAttribI4uiv; -#define glVertexAttribI4uiv glad_glVertexAttribI4uiv -typedef void (APIENTRYP PFNGLVERTEXATTRIBI4BVPROC)(GLuint index, const GLbyte *v); -GLAPI PFNGLVERTEXATTRIBI4BVPROC glad_glVertexAttribI4bv; -#define glVertexAttribI4bv glad_glVertexAttribI4bv -typedef void (APIENTRYP PFNGLVERTEXATTRIBI4SVPROC)(GLuint index, const GLshort *v); -GLAPI PFNGLVERTEXATTRIBI4SVPROC glad_glVertexAttribI4sv; -#define glVertexAttribI4sv glad_glVertexAttribI4sv -typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UBVPROC)(GLuint index, const GLubyte *v); -GLAPI PFNGLVERTEXATTRIBI4UBVPROC glad_glVertexAttribI4ubv; -#define glVertexAttribI4ubv glad_glVertexAttribI4ubv -typedef void (APIENTRYP PFNGLVERTEXATTRIBI4USVPROC)(GLuint index, const GLushort *v); -GLAPI PFNGLVERTEXATTRIBI4USVPROC glad_glVertexAttribI4usv; -#define glVertexAttribI4usv glad_glVertexAttribI4usv -typedef void (APIENTRYP PFNGLGETUNIFORMUIVPROC)(GLuint program, GLint location, GLuint *params); -GLAPI PFNGLGETUNIFORMUIVPROC glad_glGetUniformuiv; -#define glGetUniformuiv glad_glGetUniformuiv -typedef void (APIENTRYP PFNGLBINDFRAGDATALOCATIONPROC)(GLuint program, GLuint color, const GLchar *name); -GLAPI PFNGLBINDFRAGDATALOCATIONPROC glad_glBindFragDataLocation; -#define glBindFragDataLocation glad_glBindFragDataLocation -typedef GLint (APIENTRYP PFNGLGETFRAGDATALOCATIONPROC)(GLuint program, const GLchar *name); -GLAPI PFNGLGETFRAGDATALOCATIONPROC glad_glGetFragDataLocation; -#define glGetFragDataLocation glad_glGetFragDataLocation -typedef void (APIENTRYP PFNGLUNIFORM1UIPROC)(GLint location, GLuint v0); -GLAPI PFNGLUNIFORM1UIPROC glad_glUniform1ui; -#define glUniform1ui glad_glUniform1ui -typedef void (APIENTRYP PFNGLUNIFORM2UIPROC)(GLint location, GLuint v0, GLuint v1); -GLAPI PFNGLUNIFORM2UIPROC glad_glUniform2ui; -#define glUniform2ui glad_glUniform2ui -typedef void (APIENTRYP PFNGLUNIFORM3UIPROC)(GLint location, GLuint v0, GLuint v1, GLuint v2); -GLAPI PFNGLUNIFORM3UIPROC glad_glUniform3ui; -#define glUniform3ui glad_glUniform3ui -typedef void (APIENTRYP PFNGLUNIFORM4UIPROC)(GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); -GLAPI PFNGLUNIFORM4UIPROC glad_glUniform4ui; -#define glUniform4ui glad_glUniform4ui -typedef void (APIENTRYP PFNGLUNIFORM1UIVPROC)(GLint location, GLsizei count, const GLuint *value); -GLAPI PFNGLUNIFORM1UIVPROC glad_glUniform1uiv; -#define glUniform1uiv glad_glUniform1uiv -typedef void (APIENTRYP PFNGLUNIFORM2UIVPROC)(GLint location, GLsizei count, const GLuint *value); -GLAPI PFNGLUNIFORM2UIVPROC glad_glUniform2uiv; -#define glUniform2uiv glad_glUniform2uiv -typedef void (APIENTRYP PFNGLUNIFORM3UIVPROC)(GLint location, GLsizei count, const GLuint *value); -GLAPI PFNGLUNIFORM3UIVPROC glad_glUniform3uiv; -#define glUniform3uiv glad_glUniform3uiv -typedef void (APIENTRYP PFNGLUNIFORM4UIVPROC)(GLint location, GLsizei count, const GLuint *value); -GLAPI PFNGLUNIFORM4UIVPROC glad_glUniform4uiv; -#define glUniform4uiv glad_glUniform4uiv -typedef void (APIENTRYP PFNGLTEXPARAMETERIIVPROC)(GLenum target, GLenum pname, const GLint *params); -GLAPI PFNGLTEXPARAMETERIIVPROC glad_glTexParameterIiv; -#define glTexParameterIiv glad_glTexParameterIiv -typedef void (APIENTRYP PFNGLTEXPARAMETERIUIVPROC)(GLenum target, GLenum pname, const GLuint *params); -GLAPI PFNGLTEXPARAMETERIUIVPROC glad_glTexParameterIuiv; -#define glTexParameterIuiv glad_glTexParameterIuiv -typedef void (APIENTRYP PFNGLGETTEXPARAMETERIIVPROC)(GLenum target, GLenum pname, GLint *params); -GLAPI PFNGLGETTEXPARAMETERIIVPROC glad_glGetTexParameterIiv; -#define glGetTexParameterIiv glad_glGetTexParameterIiv -typedef void (APIENTRYP PFNGLGETTEXPARAMETERIUIVPROC)(GLenum target, GLenum pname, GLuint *params); -GLAPI PFNGLGETTEXPARAMETERIUIVPROC glad_glGetTexParameterIuiv; -#define glGetTexParameterIuiv glad_glGetTexParameterIuiv -typedef void (APIENTRYP PFNGLCLEARBUFFERIVPROC)(GLenum buffer, GLint drawbuffer, const GLint *value); -GLAPI PFNGLCLEARBUFFERIVPROC glad_glClearBufferiv; -#define glClearBufferiv glad_glClearBufferiv -typedef void (APIENTRYP PFNGLCLEARBUFFERUIVPROC)(GLenum buffer, GLint drawbuffer, const GLuint *value); -GLAPI PFNGLCLEARBUFFERUIVPROC glad_glClearBufferuiv; -#define glClearBufferuiv glad_glClearBufferuiv -typedef void (APIENTRYP PFNGLCLEARBUFFERFVPROC)(GLenum buffer, GLint drawbuffer, const GLfloat *value); -GLAPI PFNGLCLEARBUFFERFVPROC glad_glClearBufferfv; -#define glClearBufferfv glad_glClearBufferfv -typedef void (APIENTRYP PFNGLCLEARBUFFERFIPROC)(GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil); -GLAPI PFNGLCLEARBUFFERFIPROC glad_glClearBufferfi; -#define glClearBufferfi glad_glClearBufferfi -typedef const GLubyte * (APIENTRYP PFNGLGETSTRINGIPROC)(GLenum name, GLuint index); -GLAPI PFNGLGETSTRINGIPROC glad_glGetStringi; -#define glGetStringi glad_glGetStringi -typedef GLboolean (APIENTRYP PFNGLISRENDERBUFFERPROC)(GLuint renderbuffer); -GLAPI PFNGLISRENDERBUFFERPROC glad_glIsRenderbuffer; -#define glIsRenderbuffer glad_glIsRenderbuffer -typedef void (APIENTRYP PFNGLBINDRENDERBUFFERPROC)(GLenum target, GLuint renderbuffer); -GLAPI PFNGLBINDRENDERBUFFERPROC glad_glBindRenderbuffer; -#define glBindRenderbuffer glad_glBindRenderbuffer -typedef void (APIENTRYP PFNGLDELETERENDERBUFFERSPROC)(GLsizei n, const GLuint *renderbuffers); -GLAPI PFNGLDELETERENDERBUFFERSPROC glad_glDeleteRenderbuffers; -#define glDeleteRenderbuffers glad_glDeleteRenderbuffers -typedef void (APIENTRYP PFNGLGENRENDERBUFFERSPROC)(GLsizei n, GLuint *renderbuffers); -GLAPI PFNGLGENRENDERBUFFERSPROC glad_glGenRenderbuffers; -#define glGenRenderbuffers glad_glGenRenderbuffers -typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEPROC)(GLenum target, GLenum internalformat, GLsizei width, GLsizei height); -GLAPI PFNGLRENDERBUFFERSTORAGEPROC glad_glRenderbufferStorage; -#define glRenderbufferStorage glad_glRenderbufferStorage -typedef void (APIENTRYP PFNGLGETRENDERBUFFERPARAMETERIVPROC)(GLenum target, GLenum pname, GLint *params); -GLAPI PFNGLGETRENDERBUFFERPARAMETERIVPROC glad_glGetRenderbufferParameteriv; -#define glGetRenderbufferParameteriv glad_glGetRenderbufferParameteriv -typedef GLboolean (APIENTRYP PFNGLISFRAMEBUFFERPROC)(GLuint framebuffer); -GLAPI PFNGLISFRAMEBUFFERPROC glad_glIsFramebuffer; -#define glIsFramebuffer glad_glIsFramebuffer -typedef void (APIENTRYP PFNGLBINDFRAMEBUFFERPROC)(GLenum target, GLuint framebuffer); -GLAPI PFNGLBINDFRAMEBUFFERPROC glad_glBindFramebuffer; -#define glBindFramebuffer glad_glBindFramebuffer -typedef void (APIENTRYP PFNGLDELETEFRAMEBUFFERSPROC)(GLsizei n, const GLuint *framebuffers); -GLAPI PFNGLDELETEFRAMEBUFFERSPROC glad_glDeleteFramebuffers; -#define glDeleteFramebuffers glad_glDeleteFramebuffers -typedef void (APIENTRYP PFNGLGENFRAMEBUFFERSPROC)(GLsizei n, GLuint *framebuffers); -GLAPI PFNGLGENFRAMEBUFFERSPROC glad_glGenFramebuffers; -#define glGenFramebuffers glad_glGenFramebuffers -typedef GLenum (APIENTRYP PFNGLCHECKFRAMEBUFFERSTATUSPROC)(GLenum target); -GLAPI PFNGLCHECKFRAMEBUFFERSTATUSPROC glad_glCheckFramebufferStatus; -#define glCheckFramebufferStatus glad_glCheckFramebufferStatus -typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE1DPROC)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); -GLAPI PFNGLFRAMEBUFFERTEXTURE1DPROC glad_glFramebufferTexture1D; -#define glFramebufferTexture1D glad_glFramebufferTexture1D -typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DPROC)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); -GLAPI PFNGLFRAMEBUFFERTEXTURE2DPROC glad_glFramebufferTexture2D; -#define glFramebufferTexture2D glad_glFramebufferTexture2D -typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE3DPROC)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); -GLAPI PFNGLFRAMEBUFFERTEXTURE3DPROC glad_glFramebufferTexture3D; -#define glFramebufferTexture3D glad_glFramebufferTexture3D -typedef void (APIENTRYP PFNGLFRAMEBUFFERRENDERBUFFERPROC)(GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); -GLAPI PFNGLFRAMEBUFFERRENDERBUFFERPROC glad_glFramebufferRenderbuffer; -#define glFramebufferRenderbuffer glad_glFramebufferRenderbuffer -typedef void (APIENTRYP PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC)(GLenum target, GLenum attachment, GLenum pname, GLint *params); -GLAPI PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC glad_glGetFramebufferAttachmentParameteriv; -#define glGetFramebufferAttachmentParameteriv glad_glGetFramebufferAttachmentParameteriv -typedef void (APIENTRYP PFNGLGENERATEMIPMAPPROC)(GLenum target); -GLAPI PFNGLGENERATEMIPMAPPROC glad_glGenerateMipmap; -#define glGenerateMipmap glad_glGenerateMipmap -typedef void (APIENTRYP PFNGLBLITFRAMEBUFFERPROC)(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); -GLAPI PFNGLBLITFRAMEBUFFERPROC glad_glBlitFramebuffer; -#define glBlitFramebuffer glad_glBlitFramebuffer -typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); -GLAPI PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC glad_glRenderbufferStorageMultisample; -#define glRenderbufferStorageMultisample glad_glRenderbufferStorageMultisample -typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURELAYERPROC)(GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); -GLAPI PFNGLFRAMEBUFFERTEXTURELAYERPROC glad_glFramebufferTextureLayer; -#define glFramebufferTextureLayer glad_glFramebufferTextureLayer -typedef void * (APIENTRYP PFNGLMAPBUFFERRANGEPROC)(GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access); -GLAPI PFNGLMAPBUFFERRANGEPROC glad_glMapBufferRange; -#define glMapBufferRange glad_glMapBufferRange -typedef void (APIENTRYP PFNGLFLUSHMAPPEDBUFFERRANGEPROC)(GLenum target, GLintptr offset, GLsizeiptr length); -GLAPI PFNGLFLUSHMAPPEDBUFFERRANGEPROC glad_glFlushMappedBufferRange; -#define glFlushMappedBufferRange glad_glFlushMappedBufferRange -typedef void (APIENTRYP PFNGLBINDVERTEXARRAYPROC)(GLuint array); -GLAPI PFNGLBINDVERTEXARRAYPROC glad_glBindVertexArray; -#define glBindVertexArray glad_glBindVertexArray -typedef void (APIENTRYP PFNGLDELETEVERTEXARRAYSPROC)(GLsizei n, const GLuint *arrays); -GLAPI PFNGLDELETEVERTEXARRAYSPROC glad_glDeleteVertexArrays; -#define glDeleteVertexArrays glad_glDeleteVertexArrays -typedef void (APIENTRYP PFNGLGENVERTEXARRAYSPROC)(GLsizei n, GLuint *arrays); -GLAPI PFNGLGENVERTEXARRAYSPROC glad_glGenVertexArrays; -#define glGenVertexArrays glad_glGenVertexArrays -typedef GLboolean (APIENTRYP PFNGLISVERTEXARRAYPROC)(GLuint array); -GLAPI PFNGLISVERTEXARRAYPROC glad_glIsVertexArray; -#define glIsVertexArray glad_glIsVertexArray -#endif -#ifndef GL_VERSION_3_1 -#define GL_VERSION_3_1 1 -GLAPI int GLAD_GL_VERSION_3_1; -typedef void (APIENTRYP PFNGLDRAWARRAYSINSTANCEDPROC)(GLenum mode, GLint first, GLsizei count, GLsizei instancecount); -GLAPI PFNGLDRAWARRAYSINSTANCEDPROC glad_glDrawArraysInstanced; -#define glDrawArraysInstanced glad_glDrawArraysInstanced -typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDPROC)(GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount); -GLAPI PFNGLDRAWELEMENTSINSTANCEDPROC glad_glDrawElementsInstanced; -#define glDrawElementsInstanced glad_glDrawElementsInstanced -typedef void (APIENTRYP PFNGLTEXBUFFERPROC)(GLenum target, GLenum internalformat, GLuint buffer); -GLAPI PFNGLTEXBUFFERPROC glad_glTexBuffer; -#define glTexBuffer glad_glTexBuffer -typedef void (APIENTRYP PFNGLPRIMITIVERESTARTINDEXPROC)(GLuint index); -GLAPI PFNGLPRIMITIVERESTARTINDEXPROC glad_glPrimitiveRestartIndex; -#define glPrimitiveRestartIndex glad_glPrimitiveRestartIndex -typedef void (APIENTRYP PFNGLCOPYBUFFERSUBDATAPROC)(GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); -GLAPI PFNGLCOPYBUFFERSUBDATAPROC glad_glCopyBufferSubData; -#define glCopyBufferSubData glad_glCopyBufferSubData -typedef void (APIENTRYP PFNGLGETUNIFORMINDICESPROC)(GLuint program, GLsizei uniformCount, const GLchar *const*uniformNames, GLuint *uniformIndices); -GLAPI PFNGLGETUNIFORMINDICESPROC glad_glGetUniformIndices; -#define glGetUniformIndices glad_glGetUniformIndices -typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMSIVPROC)(GLuint program, GLsizei uniformCount, const GLuint *uniformIndices, GLenum pname, GLint *params); -GLAPI PFNGLGETACTIVEUNIFORMSIVPROC glad_glGetActiveUniformsiv; -#define glGetActiveUniformsiv glad_glGetActiveUniformsiv -typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMNAMEPROC)(GLuint program, GLuint uniformIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformName); -GLAPI PFNGLGETACTIVEUNIFORMNAMEPROC glad_glGetActiveUniformName; -#define glGetActiveUniformName glad_glGetActiveUniformName -typedef GLuint (APIENTRYP PFNGLGETUNIFORMBLOCKINDEXPROC)(GLuint program, const GLchar *uniformBlockName); -GLAPI PFNGLGETUNIFORMBLOCKINDEXPROC glad_glGetUniformBlockIndex; -#define glGetUniformBlockIndex glad_glGetUniformBlockIndex -typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMBLOCKIVPROC)(GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint *params); -GLAPI PFNGLGETACTIVEUNIFORMBLOCKIVPROC glad_glGetActiveUniformBlockiv; -#define glGetActiveUniformBlockiv glad_glGetActiveUniformBlockiv -typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC)(GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformBlockName); -GLAPI PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC glad_glGetActiveUniformBlockName; -#define glGetActiveUniformBlockName glad_glGetActiveUniformBlockName -typedef void (APIENTRYP PFNGLUNIFORMBLOCKBINDINGPROC)(GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding); -GLAPI PFNGLUNIFORMBLOCKBINDINGPROC glad_glUniformBlockBinding; -#define glUniformBlockBinding glad_glUniformBlockBinding -#endif -#ifndef GL_VERSION_3_2 -#define GL_VERSION_3_2 1 -GLAPI int GLAD_GL_VERSION_3_2; -typedef void (APIENTRYP PFNGLDRAWELEMENTSBASEVERTEXPROC)(GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex); -GLAPI PFNGLDRAWELEMENTSBASEVERTEXPROC glad_glDrawElementsBaseVertex; -#define glDrawElementsBaseVertex glad_glDrawElementsBaseVertex -typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC)(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices, GLint basevertex); -GLAPI PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC glad_glDrawRangeElementsBaseVertex; -#define glDrawRangeElementsBaseVertex glad_glDrawRangeElementsBaseVertex -typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC)(GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex); -GLAPI PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC glad_glDrawElementsInstancedBaseVertex; -#define glDrawElementsInstancedBaseVertex glad_glDrawElementsInstancedBaseVertex -typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC)(GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei drawcount, const GLint *basevertex); -GLAPI PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC glad_glMultiDrawElementsBaseVertex; -#define glMultiDrawElementsBaseVertex glad_glMultiDrawElementsBaseVertex -typedef void (APIENTRYP PFNGLPROVOKINGVERTEXPROC)(GLenum mode); -GLAPI PFNGLPROVOKINGVERTEXPROC glad_glProvokingVertex; -#define glProvokingVertex glad_glProvokingVertex -typedef GLsync (APIENTRYP PFNGLFENCESYNCPROC)(GLenum condition, GLbitfield flags); -GLAPI PFNGLFENCESYNCPROC glad_glFenceSync; -#define glFenceSync glad_glFenceSync -typedef GLboolean (APIENTRYP PFNGLISSYNCPROC)(GLsync sync); -GLAPI PFNGLISSYNCPROC glad_glIsSync; -#define glIsSync glad_glIsSync -typedef void (APIENTRYP PFNGLDELETESYNCPROC)(GLsync sync); -GLAPI PFNGLDELETESYNCPROC glad_glDeleteSync; -#define glDeleteSync glad_glDeleteSync -typedef GLenum (APIENTRYP PFNGLCLIENTWAITSYNCPROC)(GLsync sync, GLbitfield flags, GLuint64 timeout); -GLAPI PFNGLCLIENTWAITSYNCPROC glad_glClientWaitSync; -#define glClientWaitSync glad_glClientWaitSync -typedef void (APIENTRYP PFNGLWAITSYNCPROC)(GLsync sync, GLbitfield flags, GLuint64 timeout); -GLAPI PFNGLWAITSYNCPROC glad_glWaitSync; -#define glWaitSync glad_glWaitSync -typedef void (APIENTRYP PFNGLGETINTEGER64VPROC)(GLenum pname, GLint64 *data); -GLAPI PFNGLGETINTEGER64VPROC glad_glGetInteger64v; -#define glGetInteger64v glad_glGetInteger64v -typedef void (APIENTRYP PFNGLGETSYNCIVPROC)(GLsync sync, GLenum pname, GLsizei bufSize, GLsizei *length, GLint *values); -GLAPI PFNGLGETSYNCIVPROC glad_glGetSynciv; -#define glGetSynciv glad_glGetSynciv -typedef void (APIENTRYP PFNGLGETINTEGER64I_VPROC)(GLenum target, GLuint index, GLint64 *data); -GLAPI PFNGLGETINTEGER64I_VPROC glad_glGetInteger64i_v; -#define glGetInteger64i_v glad_glGetInteger64i_v -typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERI64VPROC)(GLenum target, GLenum pname, GLint64 *params); -GLAPI PFNGLGETBUFFERPARAMETERI64VPROC glad_glGetBufferParameteri64v; -#define glGetBufferParameteri64v glad_glGetBufferParameteri64v -typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREPROC)(GLenum target, GLenum attachment, GLuint texture, GLint level); -GLAPI PFNGLFRAMEBUFFERTEXTUREPROC glad_glFramebufferTexture; -#define glFramebufferTexture glad_glFramebufferTexture -typedef void (APIENTRYP PFNGLTEXIMAGE2DMULTISAMPLEPROC)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); -GLAPI PFNGLTEXIMAGE2DMULTISAMPLEPROC glad_glTexImage2DMultisample; -#define glTexImage2DMultisample glad_glTexImage2DMultisample -typedef void (APIENTRYP PFNGLTEXIMAGE3DMULTISAMPLEPROC)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); -GLAPI PFNGLTEXIMAGE3DMULTISAMPLEPROC glad_glTexImage3DMultisample; -#define glTexImage3DMultisample glad_glTexImage3DMultisample -typedef void (APIENTRYP PFNGLGETMULTISAMPLEFVPROC)(GLenum pname, GLuint index, GLfloat *val); -GLAPI PFNGLGETMULTISAMPLEFVPROC glad_glGetMultisamplefv; -#define glGetMultisamplefv glad_glGetMultisamplefv -typedef void (APIENTRYP PFNGLSAMPLEMASKIPROC)(GLuint maskNumber, GLbitfield mask); -GLAPI PFNGLSAMPLEMASKIPROC glad_glSampleMaski; -#define glSampleMaski glad_glSampleMaski -#endif -#define GL_MULTISAMPLE_ARB 0x809D -#define GL_SAMPLE_ALPHA_TO_COVERAGE_ARB 0x809E -#define GL_SAMPLE_ALPHA_TO_ONE_ARB 0x809F -#define GL_SAMPLE_COVERAGE_ARB 0x80A0 -#define GL_SAMPLE_BUFFERS_ARB 0x80A8 -#define GL_SAMPLES_ARB 0x80A9 -#define GL_SAMPLE_COVERAGE_VALUE_ARB 0x80AA -#define GL_SAMPLE_COVERAGE_INVERT_ARB 0x80AB -#define GL_MULTISAMPLE_BIT_ARB 0x20000000 -#define GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT_ARB 0x00000004 -#define GL_LOSE_CONTEXT_ON_RESET_ARB 0x8252 -#define GL_GUILTY_CONTEXT_RESET_ARB 0x8253 -#define GL_INNOCENT_CONTEXT_RESET_ARB 0x8254 -#define GL_UNKNOWN_CONTEXT_RESET_ARB 0x8255 -#define GL_RESET_NOTIFICATION_STRATEGY_ARB 0x8256 -#define GL_NO_RESET_NOTIFICATION_ARB 0x8261 -#define GL_DEBUG_OUTPUT_SYNCHRONOUS 0x8242 -#define GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH 0x8243 -#define GL_DEBUG_CALLBACK_FUNCTION 0x8244 -#define GL_DEBUG_CALLBACK_USER_PARAM 0x8245 -#define GL_DEBUG_SOURCE_API 0x8246 -#define GL_DEBUG_SOURCE_WINDOW_SYSTEM 0x8247 -#define GL_DEBUG_SOURCE_SHADER_COMPILER 0x8248 -#define GL_DEBUG_SOURCE_THIRD_PARTY 0x8249 -#define GL_DEBUG_SOURCE_APPLICATION 0x824A -#define GL_DEBUG_SOURCE_OTHER 0x824B -#define GL_DEBUG_TYPE_ERROR 0x824C -#define GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR 0x824D -#define GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR 0x824E -#define GL_DEBUG_TYPE_PORTABILITY 0x824F -#define GL_DEBUG_TYPE_PERFORMANCE 0x8250 -#define GL_DEBUG_TYPE_OTHER 0x8251 -#define GL_DEBUG_TYPE_MARKER 0x8268 -#define GL_DEBUG_TYPE_PUSH_GROUP 0x8269 -#define GL_DEBUG_TYPE_POP_GROUP 0x826A -#define GL_DEBUG_SEVERITY_NOTIFICATION 0x826B -#define GL_MAX_DEBUG_GROUP_STACK_DEPTH 0x826C -#define GL_DEBUG_GROUP_STACK_DEPTH 0x826D -#define GL_BUFFER 0x82E0 -#define GL_SHADER 0x82E1 -#define GL_PROGRAM 0x82E2 -#define GL_QUERY 0x82E3 -#define GL_PROGRAM_PIPELINE 0x82E4 -#define GL_SAMPLER 0x82E6 -#define GL_MAX_LABEL_LENGTH 0x82E8 -#define GL_MAX_DEBUG_MESSAGE_LENGTH 0x9143 -#define GL_MAX_DEBUG_LOGGED_MESSAGES 0x9144 -#define GL_DEBUG_LOGGED_MESSAGES 0x9145 -#define GL_DEBUG_SEVERITY_HIGH 0x9146 -#define GL_DEBUG_SEVERITY_MEDIUM 0x9147 -#define GL_DEBUG_SEVERITY_LOW 0x9148 -#define GL_DEBUG_OUTPUT 0x92E0 -#define GL_CONTEXT_FLAG_DEBUG_BIT 0x00000002 -#define GL_DEBUG_OUTPUT_SYNCHRONOUS_KHR 0x8242 -#define GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH_KHR 0x8243 -#define GL_DEBUG_CALLBACK_FUNCTION_KHR 0x8244 -#define GL_DEBUG_CALLBACK_USER_PARAM_KHR 0x8245 -#define GL_DEBUG_SOURCE_API_KHR 0x8246 -#define GL_DEBUG_SOURCE_WINDOW_SYSTEM_KHR 0x8247 -#define GL_DEBUG_SOURCE_SHADER_COMPILER_KHR 0x8248 -#define GL_DEBUG_SOURCE_THIRD_PARTY_KHR 0x8249 -#define GL_DEBUG_SOURCE_APPLICATION_KHR 0x824A -#define GL_DEBUG_SOURCE_OTHER_KHR 0x824B -#define GL_DEBUG_TYPE_ERROR_KHR 0x824C -#define GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_KHR 0x824D -#define GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_KHR 0x824E -#define GL_DEBUG_TYPE_PORTABILITY_KHR 0x824F -#define GL_DEBUG_TYPE_PERFORMANCE_KHR 0x8250 -#define GL_DEBUG_TYPE_OTHER_KHR 0x8251 -#define GL_DEBUG_TYPE_MARKER_KHR 0x8268 -#define GL_DEBUG_TYPE_PUSH_GROUP_KHR 0x8269 -#define GL_DEBUG_TYPE_POP_GROUP_KHR 0x826A -#define GL_DEBUG_SEVERITY_NOTIFICATION_KHR 0x826B -#define GL_MAX_DEBUG_GROUP_STACK_DEPTH_KHR 0x826C -#define GL_DEBUG_GROUP_STACK_DEPTH_KHR 0x826D -#define GL_BUFFER_KHR 0x82E0 -#define GL_SHADER_KHR 0x82E1 -#define GL_PROGRAM_KHR 0x82E2 -#define GL_VERTEX_ARRAY_KHR 0x8074 -#define GL_QUERY_KHR 0x82E3 -#define GL_PROGRAM_PIPELINE_KHR 0x82E4 -#define GL_SAMPLER_KHR 0x82E6 -#define GL_MAX_LABEL_LENGTH_KHR 0x82E8 -#define GL_MAX_DEBUG_MESSAGE_LENGTH_KHR 0x9143 -#define GL_MAX_DEBUG_LOGGED_MESSAGES_KHR 0x9144 -#define GL_DEBUG_LOGGED_MESSAGES_KHR 0x9145 -#define GL_DEBUG_SEVERITY_HIGH_KHR 0x9146 -#define GL_DEBUG_SEVERITY_MEDIUM_KHR 0x9147 -#define GL_DEBUG_SEVERITY_LOW_KHR 0x9148 -#define GL_DEBUG_OUTPUT_KHR 0x92E0 -#define GL_CONTEXT_FLAG_DEBUG_BIT_KHR 0x00000002 -#define GL_STACK_OVERFLOW_KHR 0x0503 -#define GL_STACK_UNDERFLOW_KHR 0x0504 -#define GL_DISPLAY_LIST 0x82E7 -#ifndef GL_ARB_multisample -#define GL_ARB_multisample 1 -GLAPI int GLAD_GL_ARB_multisample; -typedef void (APIENTRYP PFNGLSAMPLECOVERAGEARBPROC)(GLfloat value, GLboolean invert); -GLAPI PFNGLSAMPLECOVERAGEARBPROC glad_glSampleCoverageARB; -#define glSampleCoverageARB glad_glSampleCoverageARB -#endif -#ifndef GL_ARB_robustness -#define GL_ARB_robustness 1 -GLAPI int GLAD_GL_ARB_robustness; -typedef GLenum (APIENTRYP PFNGLGETGRAPHICSRESETSTATUSARBPROC)(); -GLAPI PFNGLGETGRAPHICSRESETSTATUSARBPROC glad_glGetGraphicsResetStatusARB; -#define glGetGraphicsResetStatusARB glad_glGetGraphicsResetStatusARB -typedef void (APIENTRYP PFNGLGETNTEXIMAGEARBPROC)(GLenum target, GLint level, GLenum format, GLenum type, GLsizei bufSize, void *img); -GLAPI PFNGLGETNTEXIMAGEARBPROC glad_glGetnTexImageARB; -#define glGetnTexImageARB glad_glGetnTexImageARB -typedef void (APIENTRYP PFNGLREADNPIXELSARBPROC)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void *data); -GLAPI PFNGLREADNPIXELSARBPROC glad_glReadnPixelsARB; -#define glReadnPixelsARB glad_glReadnPixelsARB -typedef void (APIENTRYP PFNGLGETNCOMPRESSEDTEXIMAGEARBPROC)(GLenum target, GLint lod, GLsizei bufSize, void *img); -GLAPI PFNGLGETNCOMPRESSEDTEXIMAGEARBPROC glad_glGetnCompressedTexImageARB; -#define glGetnCompressedTexImageARB glad_glGetnCompressedTexImageARB -typedef void (APIENTRYP PFNGLGETNUNIFORMFVARBPROC)(GLuint program, GLint location, GLsizei bufSize, GLfloat *params); -GLAPI PFNGLGETNUNIFORMFVARBPROC glad_glGetnUniformfvARB; -#define glGetnUniformfvARB glad_glGetnUniformfvARB -typedef void (APIENTRYP PFNGLGETNUNIFORMIVARBPROC)(GLuint program, GLint location, GLsizei bufSize, GLint *params); -GLAPI PFNGLGETNUNIFORMIVARBPROC glad_glGetnUniformivARB; -#define glGetnUniformivARB glad_glGetnUniformivARB -typedef void (APIENTRYP PFNGLGETNUNIFORMUIVARBPROC)(GLuint program, GLint location, GLsizei bufSize, GLuint *params); -GLAPI PFNGLGETNUNIFORMUIVARBPROC glad_glGetnUniformuivARB; -#define glGetnUniformuivARB glad_glGetnUniformuivARB -typedef void (APIENTRYP PFNGLGETNUNIFORMDVARBPROC)(GLuint program, GLint location, GLsizei bufSize, GLdouble *params); -GLAPI PFNGLGETNUNIFORMDVARBPROC glad_glGetnUniformdvARB; -#define glGetnUniformdvARB glad_glGetnUniformdvARB -typedef void (APIENTRYP PFNGLGETNMAPDVARBPROC)(GLenum target, GLenum query, GLsizei bufSize, GLdouble *v); -GLAPI PFNGLGETNMAPDVARBPROC glad_glGetnMapdvARB; -#define glGetnMapdvARB glad_glGetnMapdvARB -typedef void (APIENTRYP PFNGLGETNMAPFVARBPROC)(GLenum target, GLenum query, GLsizei bufSize, GLfloat *v); -GLAPI PFNGLGETNMAPFVARBPROC glad_glGetnMapfvARB; -#define glGetnMapfvARB glad_glGetnMapfvARB -typedef void (APIENTRYP PFNGLGETNMAPIVARBPROC)(GLenum target, GLenum query, GLsizei bufSize, GLint *v); -GLAPI PFNGLGETNMAPIVARBPROC glad_glGetnMapivARB; -#define glGetnMapivARB glad_glGetnMapivARB -typedef void (APIENTRYP PFNGLGETNPIXELMAPFVARBPROC)(GLenum map, GLsizei bufSize, GLfloat *values); -GLAPI PFNGLGETNPIXELMAPFVARBPROC glad_glGetnPixelMapfvARB; -#define glGetnPixelMapfvARB glad_glGetnPixelMapfvARB -typedef void (APIENTRYP PFNGLGETNPIXELMAPUIVARBPROC)(GLenum map, GLsizei bufSize, GLuint *values); -GLAPI PFNGLGETNPIXELMAPUIVARBPROC glad_glGetnPixelMapuivARB; -#define glGetnPixelMapuivARB glad_glGetnPixelMapuivARB -typedef void (APIENTRYP PFNGLGETNPIXELMAPUSVARBPROC)(GLenum map, GLsizei bufSize, GLushort *values); -GLAPI PFNGLGETNPIXELMAPUSVARBPROC glad_glGetnPixelMapusvARB; -#define glGetnPixelMapusvARB glad_glGetnPixelMapusvARB -typedef void (APIENTRYP PFNGLGETNPOLYGONSTIPPLEARBPROC)(GLsizei bufSize, GLubyte *pattern); -GLAPI PFNGLGETNPOLYGONSTIPPLEARBPROC glad_glGetnPolygonStippleARB; -#define glGetnPolygonStippleARB glad_glGetnPolygonStippleARB -typedef void (APIENTRYP PFNGLGETNCOLORTABLEARBPROC)(GLenum target, GLenum format, GLenum type, GLsizei bufSize, void *table); -GLAPI PFNGLGETNCOLORTABLEARBPROC glad_glGetnColorTableARB; -#define glGetnColorTableARB glad_glGetnColorTableARB -typedef void (APIENTRYP PFNGLGETNCONVOLUTIONFILTERARBPROC)(GLenum target, GLenum format, GLenum type, GLsizei bufSize, void *image); -GLAPI PFNGLGETNCONVOLUTIONFILTERARBPROC glad_glGetnConvolutionFilterARB; -#define glGetnConvolutionFilterARB glad_glGetnConvolutionFilterARB -typedef void (APIENTRYP PFNGLGETNSEPARABLEFILTERARBPROC)(GLenum target, GLenum format, GLenum type, GLsizei rowBufSize, void *row, GLsizei columnBufSize, void *column, void *span); -GLAPI PFNGLGETNSEPARABLEFILTERARBPROC glad_glGetnSeparableFilterARB; -#define glGetnSeparableFilterARB glad_glGetnSeparableFilterARB -typedef void (APIENTRYP PFNGLGETNHISTOGRAMARBPROC)(GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, void *values); -GLAPI PFNGLGETNHISTOGRAMARBPROC glad_glGetnHistogramARB; -#define glGetnHistogramARB glad_glGetnHistogramARB -typedef void (APIENTRYP PFNGLGETNMINMAXARBPROC)(GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, void *values); -GLAPI PFNGLGETNMINMAXARBPROC glad_glGetnMinmaxARB; -#define glGetnMinmaxARB glad_glGetnMinmaxARB -#endif -#ifndef GL_KHR_debug -#define GL_KHR_debug 1 -GLAPI int GLAD_GL_KHR_debug; -typedef void (APIENTRYP PFNGLDEBUGMESSAGECONTROLPROC)(GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled); -GLAPI PFNGLDEBUGMESSAGECONTROLPROC glad_glDebugMessageControl; -#define glDebugMessageControl glad_glDebugMessageControl -typedef void (APIENTRYP PFNGLDEBUGMESSAGEINSERTPROC)(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *buf); -GLAPI PFNGLDEBUGMESSAGEINSERTPROC glad_glDebugMessageInsert; -#define glDebugMessageInsert glad_glDebugMessageInsert -typedef void (APIENTRYP PFNGLDEBUGMESSAGECALLBACKPROC)(GLDEBUGPROC callback, const void *userParam); -GLAPI PFNGLDEBUGMESSAGECALLBACKPROC glad_glDebugMessageCallback; -#define glDebugMessageCallback glad_glDebugMessageCallback -typedef GLuint (APIENTRYP PFNGLGETDEBUGMESSAGELOGPROC)(GLuint count, GLsizei bufSize, GLenum *sources, GLenum *types, GLuint *ids, GLenum *severities, GLsizei *lengths, GLchar *messageLog); -GLAPI PFNGLGETDEBUGMESSAGELOGPROC glad_glGetDebugMessageLog; -#define glGetDebugMessageLog glad_glGetDebugMessageLog -typedef void (APIENTRYP PFNGLPUSHDEBUGGROUPPROC)(GLenum source, GLuint id, GLsizei length, const GLchar *message); -GLAPI PFNGLPUSHDEBUGGROUPPROC glad_glPushDebugGroup; -#define glPushDebugGroup glad_glPushDebugGroup -typedef void (APIENTRYP PFNGLPOPDEBUGGROUPPROC)(); -GLAPI PFNGLPOPDEBUGGROUPPROC glad_glPopDebugGroup; -#define glPopDebugGroup glad_glPopDebugGroup -typedef void (APIENTRYP PFNGLOBJECTLABELPROC)(GLenum identifier, GLuint name, GLsizei length, const GLchar *label); -GLAPI PFNGLOBJECTLABELPROC glad_glObjectLabel; -#define glObjectLabel glad_glObjectLabel -typedef void (APIENTRYP PFNGLGETOBJECTLABELPROC)(GLenum identifier, GLuint name, GLsizei bufSize, GLsizei *length, GLchar *label); -GLAPI PFNGLGETOBJECTLABELPROC glad_glGetObjectLabel; -#define glGetObjectLabel glad_glGetObjectLabel -typedef void (APIENTRYP PFNGLOBJECTPTRLABELPROC)(const void *ptr, GLsizei length, const GLchar *label); -GLAPI PFNGLOBJECTPTRLABELPROC glad_glObjectPtrLabel; -#define glObjectPtrLabel glad_glObjectPtrLabel -typedef void (APIENTRYP PFNGLGETOBJECTPTRLABELPROC)(const void *ptr, GLsizei bufSize, GLsizei *length, GLchar *label); -GLAPI PFNGLGETOBJECTPTRLABELPROC glad_glGetObjectPtrLabel; -#define glGetObjectPtrLabel glad_glGetObjectPtrLabel -typedef void (APIENTRYP PFNGLDEBUGMESSAGECONTROLKHRPROC)(GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled); -GLAPI PFNGLDEBUGMESSAGECONTROLKHRPROC glad_glDebugMessageControlKHR; -#define glDebugMessageControlKHR glad_glDebugMessageControlKHR -typedef void (APIENTRYP PFNGLDEBUGMESSAGEINSERTKHRPROC)(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *buf); -GLAPI PFNGLDEBUGMESSAGEINSERTKHRPROC glad_glDebugMessageInsertKHR; -#define glDebugMessageInsertKHR glad_glDebugMessageInsertKHR -typedef void (APIENTRYP PFNGLDEBUGMESSAGECALLBACKKHRPROC)(GLDEBUGPROCKHR callback, const void *userParam); -GLAPI PFNGLDEBUGMESSAGECALLBACKKHRPROC glad_glDebugMessageCallbackKHR; -#define glDebugMessageCallbackKHR glad_glDebugMessageCallbackKHR -typedef GLuint (APIENTRYP PFNGLGETDEBUGMESSAGELOGKHRPROC)(GLuint count, GLsizei bufSize, GLenum *sources, GLenum *types, GLuint *ids, GLenum *severities, GLsizei *lengths, GLchar *messageLog); -GLAPI PFNGLGETDEBUGMESSAGELOGKHRPROC glad_glGetDebugMessageLogKHR; -#define glGetDebugMessageLogKHR glad_glGetDebugMessageLogKHR -typedef void (APIENTRYP PFNGLPUSHDEBUGGROUPKHRPROC)(GLenum source, GLuint id, GLsizei length, const GLchar *message); -GLAPI PFNGLPUSHDEBUGGROUPKHRPROC glad_glPushDebugGroupKHR; -#define glPushDebugGroupKHR glad_glPushDebugGroupKHR -typedef void (APIENTRYP PFNGLPOPDEBUGGROUPKHRPROC)(); -GLAPI PFNGLPOPDEBUGGROUPKHRPROC glad_glPopDebugGroupKHR; -#define glPopDebugGroupKHR glad_glPopDebugGroupKHR -typedef void (APIENTRYP PFNGLOBJECTLABELKHRPROC)(GLenum identifier, GLuint name, GLsizei length, const GLchar *label); -GLAPI PFNGLOBJECTLABELKHRPROC glad_glObjectLabelKHR; -#define glObjectLabelKHR glad_glObjectLabelKHR -typedef void (APIENTRYP PFNGLGETOBJECTLABELKHRPROC)(GLenum identifier, GLuint name, GLsizei bufSize, GLsizei *length, GLchar *label); -GLAPI PFNGLGETOBJECTLABELKHRPROC glad_glGetObjectLabelKHR; -#define glGetObjectLabelKHR glad_glGetObjectLabelKHR -typedef void (APIENTRYP PFNGLOBJECTPTRLABELKHRPROC)(const void *ptr, GLsizei length, const GLchar *label); -GLAPI PFNGLOBJECTPTRLABELKHRPROC glad_glObjectPtrLabelKHR; -#define glObjectPtrLabelKHR glad_glObjectPtrLabelKHR -typedef void (APIENTRYP PFNGLGETOBJECTPTRLABELKHRPROC)(const void *ptr, GLsizei bufSize, GLsizei *length, GLchar *label); -GLAPI PFNGLGETOBJECTPTRLABELKHRPROC glad_glGetObjectPtrLabelKHR; -#define glGetObjectPtrLabelKHR glad_glGetObjectPtrLabelKHR -typedef void (APIENTRYP PFNGLGETPOINTERVKHRPROC)(GLenum pname, void **params); -GLAPI PFNGLGETPOINTERVKHRPROC glad_glGetPointervKHR; -#define glGetPointervKHR glad_glGetPointervKHR -#endif - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/src/external/glfw/deps/glad/khrplatform.h b/src/external/glfw/deps/glad/khrplatform.h new file mode 100644 index 00000000..975bbffe --- /dev/null +++ b/src/external/glfw/deps/glad/khrplatform.h @@ -0,0 +1,282 @@ +#ifndef __khrplatform_h_ +#define __khrplatform_h_ + +/* +** Copyright (c) 2008-2018 The Khronos Group Inc. +** +** Permission is hereby granted, free of charge, to any person obtaining a +** copy of this software and/or associated documentation files (the +** "Materials"), to deal in the Materials without restriction, including +** without limitation the rights to use, copy, modify, merge, publish, +** distribute, sublicense, and/or sell copies of the Materials, and to +** permit persons to whom the Materials are furnished to do so, subject to +** the following conditions: +** +** The above copyright notice and this permission notice shall be included +** in all copies or substantial portions of the Materials. +** +** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. +*/ + +/* Khronos platform-specific types and definitions. + * + * The master copy of khrplatform.h is maintained in the Khronos EGL + * Registry repository at https://github.com/KhronosGroup/EGL-Registry + * The last semantic modification to khrplatform.h was at commit ID: + * 67a3e0864c2d75ea5287b9f3d2eb74a745936692 + * + * Adopters may modify this file to suit their platform. Adopters are + * encouraged to submit platform specific modifications to the Khronos + * group so that they can be included in future versions of this file. + * Please submit changes by filing pull requests or issues on + * the EGL Registry repository linked above. + * + * + * See the Implementer's Guidelines for information about where this file + * should be located on your system and for more details of its use: + * http://www.khronos.org/registry/implementers_guide.pdf + * + * This file should be included as + * #include + * by Khronos client API header files that use its types and defines. + * + * The types in khrplatform.h should only be used to define API-specific types. + * + * Types defined in khrplatform.h: + * khronos_int8_t signed 8 bit + * khronos_uint8_t unsigned 8 bit + * khronos_int16_t signed 16 bit + * khronos_uint16_t unsigned 16 bit + * khronos_int32_t signed 32 bit + * khronos_uint32_t unsigned 32 bit + * khronos_int64_t signed 64 bit + * khronos_uint64_t unsigned 64 bit + * khronos_intptr_t signed same number of bits as a pointer + * khronos_uintptr_t unsigned same number of bits as a pointer + * khronos_ssize_t signed size + * khronos_usize_t unsigned size + * khronos_float_t signed 32 bit floating point + * khronos_time_ns_t unsigned 64 bit time in nanoseconds + * khronos_utime_nanoseconds_t unsigned time interval or absolute time in + * nanoseconds + * khronos_stime_nanoseconds_t signed time interval in nanoseconds + * khronos_boolean_enum_t enumerated boolean type. This should + * only be used as a base type when a client API's boolean type is + * an enum. Client APIs which use an integer or other type for + * booleans cannot use this as the base type for their boolean. + * + * Tokens defined in khrplatform.h: + * + * KHRONOS_FALSE, KHRONOS_TRUE Enumerated boolean false/true values. + * + * KHRONOS_SUPPORT_INT64 is 1 if 64 bit integers are supported; otherwise 0. + * KHRONOS_SUPPORT_FLOAT is 1 if floats are supported; otherwise 0. + * + * Calling convention macros defined in this file: + * KHRONOS_APICALL + * KHRONOS_APIENTRY + * KHRONOS_APIATTRIBUTES + * + * These may be used in function prototypes as: + * + * KHRONOS_APICALL void KHRONOS_APIENTRY funcname( + * int arg1, + * int arg2) KHRONOS_APIATTRIBUTES; + */ + +/*------------------------------------------------------------------------- + * Definition of KHRONOS_APICALL + *------------------------------------------------------------------------- + * This precedes the return type of the function in the function prototype. + */ +#if defined(_WIN32) && !defined(__SCITECH_SNAP__) +# define KHRONOS_APICALL __declspec(dllimport) +#elif defined (__SYMBIAN32__) +# define KHRONOS_APICALL IMPORT_C +#elif defined(__ANDROID__) +# define KHRONOS_APICALL __attribute__((visibility("default"))) +#else +# define KHRONOS_APICALL +#endif + +/*------------------------------------------------------------------------- + * Definition of KHRONOS_APIENTRY + *------------------------------------------------------------------------- + * This follows the return type of the function and precedes the function + * name in the function prototype. + */ +#if defined(_WIN32) && !defined(_WIN32_WCE) && !defined(__SCITECH_SNAP__) + /* Win32 but not WinCE */ +# define KHRONOS_APIENTRY __stdcall +#else +# define KHRONOS_APIENTRY +#endif + +/*------------------------------------------------------------------------- + * Definition of KHRONOS_APIATTRIBUTES + *------------------------------------------------------------------------- + * This follows the closing parenthesis of the function prototype arguments. + */ +#if defined (__ARMCC_2__) +#define KHRONOS_APIATTRIBUTES __softfp +#else +#define KHRONOS_APIATTRIBUTES +#endif + +/*------------------------------------------------------------------------- + * basic type definitions + *-----------------------------------------------------------------------*/ +#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(__GNUC__) || defined(__SCO__) || defined(__USLC__) + + +/* + * Using + */ +#include +typedef int32_t khronos_int32_t; +typedef uint32_t khronos_uint32_t; +typedef int64_t khronos_int64_t; +typedef uint64_t khronos_uint64_t; +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#elif defined(__VMS ) || defined(__sgi) + +/* + * Using + */ +#include +typedef int32_t khronos_int32_t; +typedef uint32_t khronos_uint32_t; +typedef int64_t khronos_int64_t; +typedef uint64_t khronos_uint64_t; +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#elif defined(_WIN32) && !defined(__SCITECH_SNAP__) + +/* + * Win32 + */ +typedef __int32 khronos_int32_t; +typedef unsigned __int32 khronos_uint32_t; +typedef __int64 khronos_int64_t; +typedef unsigned __int64 khronos_uint64_t; +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#elif defined(__sun__) || defined(__digital__) + +/* + * Sun or Digital + */ +typedef int khronos_int32_t; +typedef unsigned int khronos_uint32_t; +#if defined(__arch64__) || defined(_LP64) +typedef long int khronos_int64_t; +typedef unsigned long int khronos_uint64_t; +#else +typedef long long int khronos_int64_t; +typedef unsigned long long int khronos_uint64_t; +#endif /* __arch64__ */ +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#elif 0 + +/* + * Hypothetical platform with no float or int64 support + */ +typedef int khronos_int32_t; +typedef unsigned int khronos_uint32_t; +#define KHRONOS_SUPPORT_INT64 0 +#define KHRONOS_SUPPORT_FLOAT 0 + +#else + +/* + * Generic fallback + */ +#include +typedef int32_t khronos_int32_t; +typedef uint32_t khronos_uint32_t; +typedef int64_t khronos_int64_t; +typedef uint64_t khronos_uint64_t; +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#endif + + +/* + * Types that are (so far) the same on all platforms + */ +typedef signed char khronos_int8_t; +typedef unsigned char khronos_uint8_t; +typedef signed short int khronos_int16_t; +typedef unsigned short int khronos_uint16_t; + +/* + * Types that differ between LLP64 and LP64 architectures - in LLP64, + * pointers are 64 bits, but 'long' is still 32 bits. Win64 appears + * to be the only LLP64 architecture in current use. + */ +#ifdef _WIN64 +typedef signed long long int khronos_intptr_t; +typedef unsigned long long int khronos_uintptr_t; +typedef signed long long int khronos_ssize_t; +typedef unsigned long long int khronos_usize_t; +#else +typedef signed long int khronos_intptr_t; +typedef unsigned long int khronos_uintptr_t; +typedef signed long int khronos_ssize_t; +typedef unsigned long int khronos_usize_t; +#endif + +#if KHRONOS_SUPPORT_FLOAT +/* + * Float type + */ +typedef float khronos_float_t; +#endif + +#if KHRONOS_SUPPORT_INT64 +/* Time types + * + * These types can be used to represent a time interval in nanoseconds or + * an absolute Unadjusted System Time. Unadjusted System Time is the number + * of nanoseconds since some arbitrary system event (e.g. since the last + * time the system booted). The Unadjusted System Time is an unsigned + * 64 bit value that wraps back to 0 every 584 years. Time intervals + * may be either signed or unsigned. + */ +typedef khronos_uint64_t khronos_utime_nanoseconds_t; +typedef khronos_int64_t khronos_stime_nanoseconds_t; +#endif + +/* + * Dummy value used to pad enum types to 32 bits. + */ +#ifndef KHRONOS_MAX_ENUM +#define KHRONOS_MAX_ENUM 0x7FFFFFFF +#endif + +/* + * Enumerated boolean type + * + * Values other than zero should be considered to be true. Therefore + * comparisons should not be made against KHRONOS_TRUE. + */ +typedef enum { + KHRONOS_FALSE = 0, + KHRONOS_TRUE = 1, + KHRONOS_BOOLEAN_ENUM_FORCE_SIZE = KHRONOS_MAX_ENUM +} khronos_boolean_enum_t; + +#endif /* __khrplatform_h_ */ diff --git a/src/external/glfw/deps/glad/vk_platform.h b/src/external/glfw/deps/glad/vk_platform.h new file mode 100644 index 00000000..d7d22e1e --- /dev/null +++ b/src/external/glfw/deps/glad/vk_platform.h @@ -0,0 +1,92 @@ +/* */ +/* File: vk_platform.h */ +/* */ +/* +** Copyright (c) 2014-2017 The Khronos Group Inc. +** +** 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 VK_PLATFORM_H_ +#define VK_PLATFORM_H_ + +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +/* +*************************************************************************************************** +* Platform-specific directives and type declarations +*************************************************************************************************** +*/ + +/* Platform-specific calling convention macros. + * + * Platforms should define these so that Vulkan clients call Vulkan commands + * with the same calling conventions that the Vulkan implementation expects. + * + * VKAPI_ATTR - Placed before the return type in function declarations. + * Useful for C++11 and GCC/Clang-style function attribute syntax. + * VKAPI_CALL - Placed after the return type in function declarations. + * Useful for MSVC-style calling convention syntax. + * VKAPI_PTR - Placed between the '(' and '*' in function pointer types. + * + * Function declaration: VKAPI_ATTR void VKAPI_CALL vkCommand(void); + * Function pointer type: typedef void (VKAPI_PTR *PFN_vkCommand)(void); + */ +#if defined(_WIN32) + /* On Windows, Vulkan commands use the stdcall convention */ + #define VKAPI_ATTR + #define VKAPI_CALL __stdcall + #define VKAPI_PTR VKAPI_CALL +#elif defined(__ANDROID__) && defined(__ARM_ARCH) && __ARM_ARCH < 7 + #error "Vulkan isn't supported for the 'armeabi' NDK ABI" +#elif defined(__ANDROID__) && defined(__ARM_ARCH) && __ARM_ARCH >= 7 && defined(__ARM_32BIT_STATE) + /* On Android 32-bit ARM targets, Vulkan functions use the "hardfloat" */ + /* calling convention, i.e. float parameters are passed in registers. This */ + /* is true even if the rest of the application passes floats on the stack, */ + /* as it does by default when compiling for the armeabi-v7a NDK ABI. */ + #define VKAPI_ATTR __attribute__((pcs("aapcs-vfp"))) + #define VKAPI_CALL + #define VKAPI_PTR VKAPI_ATTR +#else + /* On other platforms, use the default calling convention */ + #define VKAPI_ATTR + #define VKAPI_CALL + #define VKAPI_PTR +#endif + +#include + +#if !defined(VK_NO_STDINT_H) + #if defined(_MSC_VER) && (_MSC_VER < 1600) + typedef signed __int8 int8_t; + typedef unsigned __int8 uint8_t; + typedef signed __int16 int16_t; + typedef unsigned __int16 uint16_t; + typedef signed __int32 int32_t; + typedef unsigned __int32 uint32_t; + typedef signed __int64 int64_t; + typedef unsigned __int64 uint64_t; + #else + #include + #endif +#endif /* !defined(VK_NO_STDINT_H) */ + +#ifdef __cplusplus +} /* extern "C" */ +#endif /* __cplusplus */ + +#endif diff --git a/src/external/glfw/deps/glad/vulkan.h b/src/external/glfw/deps/glad/vulkan.h new file mode 100644 index 00000000..6bace71d --- /dev/null +++ b/src/external/glfw/deps/glad/vulkan.h @@ -0,0 +1,3480 @@ +/** + * Loader generated by glad 2.0.0-beta on Sun Apr 14 17:03:38 2019 + * + * Generator: C/C++ + * Specification: vk + * Extensions: 3 + * + * APIs: + * - vulkan=1.1 + * + * Options: + * - MX_GLOBAL = False + * - LOADER = False + * - ALIAS = False + * - HEADER_ONLY = False + * - DEBUG = False + * - MX = False + * + * Commandline: + * --api='vulkan=1.1' --extensions='VK_EXT_debug_report,VK_KHR_surface,VK_KHR_swapchain' c + * + * Online: + * http://glad.sh/#api=vulkan%3D1.1&extensions=VK_EXT_debug_report%2CVK_KHR_surface%2CVK_KHR_swapchain&generator=c&options= + * + */ + +#ifndef GLAD_VULKAN_H_ +#define GLAD_VULKAN_H_ + +#ifdef VULKAN_H_ + #error header already included (API: vulkan), remove previous include! +#endif +#define VULKAN_H_ 1 + +#ifdef VULKAN_CORE_H_ + #error header already included (API: vulkan), remove previous include! +#endif +#define VULKAN_CORE_H_ 1 + + +#define GLAD_VULKAN + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef GLAD_PLATFORM_H_ +#define GLAD_PLATFORM_H_ + +#ifndef GLAD_PLATFORM_WIN32 + #if defined(_WIN32) || defined(__WIN32__) || defined(WIN32) || defined(__MINGW32__) + #define GLAD_PLATFORM_WIN32 1 + #else + #define GLAD_PLATFORM_WIN32 0 + #endif +#endif + +#ifndef GLAD_PLATFORM_APPLE + #ifdef __APPLE__ + #define GLAD_PLATFORM_APPLE 1 + #else + #define GLAD_PLATFORM_APPLE 0 + #endif +#endif + +#ifndef GLAD_PLATFORM_EMSCRIPTEN + #ifdef __EMSCRIPTEN__ + #define GLAD_PLATFORM_EMSCRIPTEN 1 + #else + #define GLAD_PLATFORM_EMSCRIPTEN 0 + #endif +#endif + +#ifndef GLAD_PLATFORM_UWP + #if defined(_MSC_VER) && !defined(GLAD_INTERNAL_HAVE_WINAPIFAMILY) + #ifdef __has_include + #if __has_include() + #define GLAD_INTERNAL_HAVE_WINAPIFAMILY 1 + #endif + #elif _MSC_VER >= 1700 && !_USING_V110_SDK71_ + #define GLAD_INTERNAL_HAVE_WINAPIFAMILY 1 + #endif + #endif + + #ifdef GLAD_INTERNAL_HAVE_WINAPIFAMILY + #include + #if !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) && WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) + #define GLAD_PLATFORM_UWP 1 + #endif + #endif + + #ifndef GLAD_PLATFORM_UWP + #define GLAD_PLATFORM_UWP 0 + #endif +#endif + +#ifdef __GNUC__ + #define GLAD_GNUC_EXTENSION __extension__ +#else + #define GLAD_GNUC_EXTENSION +#endif + +#ifndef GLAD_API_CALL + #if defined(GLAD_API_CALL_EXPORT) + #if GLAD_PLATFORM_WIN32 || defined(__CYGWIN__) + #if defined(GLAD_API_CALL_EXPORT_BUILD) + #if defined(__GNUC__) + #define GLAD_API_CALL __attribute__ ((dllexport)) extern + #else + #define GLAD_API_CALL __declspec(dllexport) extern + #endif + #else + #if defined(__GNUC__) + #define GLAD_API_CALL __attribute__ ((dllimport)) extern + #else + #define GLAD_API_CALL __declspec(dllimport) extern + #endif + #endif + #elif defined(__GNUC__) && defined(GLAD_API_CALL_EXPORT_BUILD) + #define GLAD_API_CALL __attribute__ ((visibility ("default"))) extern + #else + #define GLAD_API_CALL extern + #endif + #else + #define GLAD_API_CALL extern + #endif +#endif + +#ifdef APIENTRY + #define GLAD_API_PTR APIENTRY +#elif GLAD_PLATFORM_WIN32 + #define GLAD_API_PTR __stdcall +#else + #define GLAD_API_PTR +#endif + +#ifndef GLAPI +#define GLAPI GLAD_API_CALL +#endif + +#ifndef GLAPIENTRY +#define GLAPIENTRY GLAD_API_PTR +#endif + + +#define GLAD_MAKE_VERSION(major, minor) (major * 10000 + minor) +#define GLAD_VERSION_MAJOR(version) (version / 10000) +#define GLAD_VERSION_MINOR(version) (version % 10000) + +typedef void (*GLADapiproc)(void); + +typedef GLADapiproc (*GLADloadfunc)(const char *name); +typedef GLADapiproc (*GLADuserptrloadfunc)(const char *name, void *userptr); + +typedef void (*GLADprecallback)(const char *name, GLADapiproc apiproc, int len_args, ...); +typedef void (*GLADpostcallback)(void *ret, const char *name, GLADapiproc apiproc, int len_args, ...); + +#endif /* GLAD_PLATFORM_H_ */ + +#define VK_ATTACHMENT_UNUSED (~0U) +#define VK_EXT_DEBUG_REPORT_EXTENSION_NAME "VK_EXT_debug_report" +#define VK_EXT_DEBUG_REPORT_SPEC_VERSION 9 +#define VK_FALSE 0 +#define VK_KHR_SURFACE_EXTENSION_NAME "VK_KHR_surface" +#define VK_KHR_SURFACE_SPEC_VERSION 25 +#define VK_KHR_SWAPCHAIN_EXTENSION_NAME "VK_KHR_swapchain" +#define VK_KHR_SWAPCHAIN_SPEC_VERSION 70 +#define VK_LOD_CLAMP_NONE 1000.0f +#define VK_LUID_SIZE 8 +#define VK_MAX_DESCRIPTION_SIZE 256 +#define VK_MAX_DEVICE_GROUP_SIZE 32 +#define VK_MAX_EXTENSION_NAME_SIZE 256 +#define VK_MAX_MEMORY_HEAPS 16 +#define VK_MAX_MEMORY_TYPES 32 +#define VK_MAX_PHYSICAL_DEVICE_NAME_SIZE 256 +#define VK_QUEUE_FAMILY_EXTERNAL (~0U-1) +#define VK_QUEUE_FAMILY_IGNORED (~0U) +#define VK_REMAINING_ARRAY_LAYERS (~0U) +#define VK_REMAINING_MIP_LEVELS (~0U) +#define VK_SUBPASS_EXTERNAL (~0U) +#define VK_TRUE 1 +#define VK_UUID_SIZE 16 +#define VK_WHOLE_SIZE (~0ULL) + + +#include +#define VK_MAKE_VERSION(major, minor, patch) \ + (((major) << 22) | ((minor) << 12) | (patch)) +#define VK_VERSION_MAJOR(version) ((uint32_t)(version) >> 22) +#define VK_VERSION_MINOR(version) (((uint32_t)(version) >> 12) & 0x3ff) +#define VK_VERSION_PATCH(version) ((uint32_t)(version) & 0xfff) +/* DEPRECATED: This define has been removed. Specific version defines (e.g. VK_API_VERSION_1_0), or the VK_MAKE_VERSION macro, should be used instead. */ +/*#define VK_API_VERSION VK_MAKE_VERSION(1, 0, 0) // Patch version should always be set to 0 */ +/* Vulkan 1.0 version number */ +#define VK_API_VERSION_1_0 VK_MAKE_VERSION(1, 0, 0)/* Patch version should always be set to 0 */ +/* Vulkan 1.1 version number */ +#define VK_API_VERSION_1_1 VK_MAKE_VERSION(1, 1, 0)/* Patch version should always be set to 0 */ +/* Version of this file */ +#define VK_HEADER_VERSION 106 +#define VK_DEFINE_HANDLE(object) typedef struct object##_T* object; +#if !defined(VK_DEFINE_NON_DISPATCHABLE_HANDLE) +#if defined(__LP64__) || defined(_WIN64) || (defined(__x86_64__) && !defined(__ILP32__) ) || defined(_M_X64) || defined(__ia64) || defined (_M_IA64) || defined(__aarch64__) || defined(__powerpc64__) + #define VK_DEFINE_NON_DISPATCHABLE_HANDLE(object) typedef struct object##_T *object; +#else + #define VK_DEFINE_NON_DISPATCHABLE_HANDLE(object) typedef uint64_t object; +#endif +#endif +#define VK_NULL_HANDLE 0 + + + + + + + + +VK_DEFINE_HANDLE(VkInstance) +VK_DEFINE_HANDLE(VkPhysicalDevice) +VK_DEFINE_HANDLE(VkDevice) +VK_DEFINE_HANDLE(VkQueue) +VK_DEFINE_HANDLE(VkCommandBuffer) +VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkDeviceMemory) +VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkCommandPool) +VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkBuffer) +VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkBufferView) +VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkImage) +VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkImageView) +VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkShaderModule) +VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkPipeline) +VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkPipelineLayout) +VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkSampler) +VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkDescriptorSet) +VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkDescriptorSetLayout) +VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkDescriptorPool) +VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkFence) +VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkSemaphore) +VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkEvent) +VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkQueryPool) +VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkFramebuffer) +VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkRenderPass) +VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkPipelineCache) +VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkDescriptorUpdateTemplate) +VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkSamplerYcbcrConversion) +VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkSurfaceKHR) +VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkSwapchainKHR) +VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkDebugReportCallbackEXT) +typedef enum VkAttachmentLoadOp { + VK_ATTACHMENT_LOAD_OP_LOAD = 0, + VK_ATTACHMENT_LOAD_OP_CLEAR = 1, + VK_ATTACHMENT_LOAD_OP_DONT_CARE = 2 +} VkAttachmentLoadOp; +typedef enum VkAttachmentStoreOp { + VK_ATTACHMENT_STORE_OP_STORE = 0, + VK_ATTACHMENT_STORE_OP_DONT_CARE = 1 +} VkAttachmentStoreOp; +typedef enum VkBlendFactor { + VK_BLEND_FACTOR_ZERO = 0, + VK_BLEND_FACTOR_ONE = 1, + VK_BLEND_FACTOR_SRC_COLOR = 2, + VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR = 3, + VK_BLEND_FACTOR_DST_COLOR = 4, + VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR = 5, + VK_BLEND_FACTOR_SRC_ALPHA = 6, + VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA = 7, + VK_BLEND_FACTOR_DST_ALPHA = 8, + VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA = 9, + VK_BLEND_FACTOR_CONSTANT_COLOR = 10, + VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR = 11, + VK_BLEND_FACTOR_CONSTANT_ALPHA = 12, + VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA = 13, + VK_BLEND_FACTOR_SRC_ALPHA_SATURATE = 14, + VK_BLEND_FACTOR_SRC1_COLOR = 15, + VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR = 16, + VK_BLEND_FACTOR_SRC1_ALPHA = 17, + VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA = 18 +} VkBlendFactor; +typedef enum VkBlendOp { + VK_BLEND_OP_ADD = 0, + VK_BLEND_OP_SUBTRACT = 1, + VK_BLEND_OP_REVERSE_SUBTRACT = 2, + VK_BLEND_OP_MIN = 3, + VK_BLEND_OP_MAX = 4 +} VkBlendOp; +typedef enum VkBorderColor { + VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK = 0, + VK_BORDER_COLOR_INT_TRANSPARENT_BLACK = 1, + VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK = 2, + VK_BORDER_COLOR_INT_OPAQUE_BLACK = 3, + VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE = 4, + VK_BORDER_COLOR_INT_OPAQUE_WHITE = 5 +} VkBorderColor; + +typedef enum VkPipelineCacheHeaderVersion { + VK_PIPELINE_CACHE_HEADER_VERSION_ONE = 1 +} VkPipelineCacheHeaderVersion; + +typedef enum VkDeviceQueueCreateFlagBits { + VK_DEVICE_QUEUE_CREATE_PROTECTED_BIT = 1 +} VkDeviceQueueCreateFlagBits; +typedef enum VkBufferCreateFlagBits { + VK_BUFFER_CREATE_SPARSE_BINDING_BIT = 1, + VK_BUFFER_CREATE_SPARSE_RESIDENCY_BIT = 2, + VK_BUFFER_CREATE_SPARSE_ALIASED_BIT = 4, + VK_BUFFER_CREATE_PROTECTED_BIT = 8 +} VkBufferCreateFlagBits; +typedef enum VkBufferUsageFlagBits { + VK_BUFFER_USAGE_TRANSFER_SRC_BIT = 1, + VK_BUFFER_USAGE_TRANSFER_DST_BIT = 2, + VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT = 4, + VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT = 8, + VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT = 16, + VK_BUFFER_USAGE_STORAGE_BUFFER_BIT = 32, + VK_BUFFER_USAGE_INDEX_BUFFER_BIT = 64, + VK_BUFFER_USAGE_VERTEX_BUFFER_BIT = 128, + VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT = 256 +} VkBufferUsageFlagBits; +typedef enum VkColorComponentFlagBits { + VK_COLOR_COMPONENT_R_BIT = 1, + VK_COLOR_COMPONENT_G_BIT = 2, + VK_COLOR_COMPONENT_B_BIT = 4, + VK_COLOR_COMPONENT_A_BIT = 8 +} VkColorComponentFlagBits; +typedef enum VkComponentSwizzle { + VK_COMPONENT_SWIZZLE_IDENTITY = 0, + VK_COMPONENT_SWIZZLE_ZERO = 1, + VK_COMPONENT_SWIZZLE_ONE = 2, + VK_COMPONENT_SWIZZLE_R = 3, + VK_COMPONENT_SWIZZLE_G = 4, + VK_COMPONENT_SWIZZLE_B = 5, + VK_COMPONENT_SWIZZLE_A = 6 +} VkComponentSwizzle; +typedef enum VkCommandPoolCreateFlagBits { + VK_COMMAND_POOL_CREATE_TRANSIENT_BIT = 1, + VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT = 2, + VK_COMMAND_POOL_CREATE_PROTECTED_BIT = 4 +} VkCommandPoolCreateFlagBits; +typedef enum VkCommandPoolResetFlagBits { + VK_COMMAND_POOL_RESET_RELEASE_RESOURCES_BIT = 1 +} VkCommandPoolResetFlagBits; +typedef enum VkCommandBufferResetFlagBits { + VK_COMMAND_BUFFER_RESET_RELEASE_RESOURCES_BIT = 1 +} VkCommandBufferResetFlagBits; +typedef enum VkCommandBufferLevel { + VK_COMMAND_BUFFER_LEVEL_PRIMARY = 0, + VK_COMMAND_BUFFER_LEVEL_SECONDARY = 1 +} VkCommandBufferLevel; +typedef enum VkCommandBufferUsageFlagBits { + VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT = 1, + VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT = 2, + VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT = 4 +} VkCommandBufferUsageFlagBits; +typedef enum VkCompareOp { + VK_COMPARE_OP_NEVER = 0, + VK_COMPARE_OP_LESS = 1, + VK_COMPARE_OP_EQUAL = 2, + VK_COMPARE_OP_LESS_OR_EQUAL = 3, + VK_COMPARE_OP_GREATER = 4, + VK_COMPARE_OP_NOT_EQUAL = 5, + VK_COMPARE_OP_GREATER_OR_EQUAL = 6, + VK_COMPARE_OP_ALWAYS = 7 +} VkCompareOp; +typedef enum VkCullModeFlagBits { + VK_CULL_MODE_NONE = 0, + VK_CULL_MODE_FRONT_BIT = 1, + VK_CULL_MODE_BACK_BIT = 2, + VK_CULL_MODE_FRONT_AND_BACK = 0x00000003 +} VkCullModeFlagBits; +typedef enum VkDescriptorType { + VK_DESCRIPTOR_TYPE_SAMPLER = 0, + VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER = 1, + VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE = 2, + VK_DESCRIPTOR_TYPE_STORAGE_IMAGE = 3, + VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER = 4, + VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER = 5, + VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER = 6, + VK_DESCRIPTOR_TYPE_STORAGE_BUFFER = 7, + VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC = 8, + VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC = 9, + VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT = 10 +} VkDescriptorType; +typedef enum VkDynamicState { + VK_DYNAMIC_STATE_VIEWPORT = 0, + VK_DYNAMIC_STATE_SCISSOR = 1, + VK_DYNAMIC_STATE_LINE_WIDTH = 2, + VK_DYNAMIC_STATE_DEPTH_BIAS = 3, + VK_DYNAMIC_STATE_BLEND_CONSTANTS = 4, + VK_DYNAMIC_STATE_DEPTH_BOUNDS = 5, + VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK = 6, + VK_DYNAMIC_STATE_STENCIL_WRITE_MASK = 7, + VK_DYNAMIC_STATE_STENCIL_REFERENCE = 8, + VK_DYNAMIC_STATE_RANGE_SIZE = (VK_DYNAMIC_STATE_STENCIL_REFERENCE - VK_DYNAMIC_STATE_VIEWPORT + 1) +} VkDynamicState; +typedef enum VkFenceCreateFlagBits { + VK_FENCE_CREATE_SIGNALED_BIT = 1 +} VkFenceCreateFlagBits; +typedef enum VkPolygonMode { + VK_POLYGON_MODE_FILL = 0, + VK_POLYGON_MODE_LINE = 1, + VK_POLYGON_MODE_POINT = 2 +} VkPolygonMode; +typedef enum VkFormat { + VK_FORMAT_UNDEFINED = 0, + VK_FORMAT_R4G4_UNORM_PACK8 = 1, + VK_FORMAT_R4G4B4A4_UNORM_PACK16 = 2, + VK_FORMAT_B4G4R4A4_UNORM_PACK16 = 3, + VK_FORMAT_R5G6B5_UNORM_PACK16 = 4, + VK_FORMAT_B5G6R5_UNORM_PACK16 = 5, + VK_FORMAT_R5G5B5A1_UNORM_PACK16 = 6, + VK_FORMAT_B5G5R5A1_UNORM_PACK16 = 7, + VK_FORMAT_A1R5G5B5_UNORM_PACK16 = 8, + VK_FORMAT_R8_UNORM = 9, + VK_FORMAT_R8_SNORM = 10, + VK_FORMAT_R8_USCALED = 11, + VK_FORMAT_R8_SSCALED = 12, + VK_FORMAT_R8_UINT = 13, + VK_FORMAT_R8_SINT = 14, + VK_FORMAT_R8_SRGB = 15, + VK_FORMAT_R8G8_UNORM = 16, + VK_FORMAT_R8G8_SNORM = 17, + VK_FORMAT_R8G8_USCALED = 18, + VK_FORMAT_R8G8_SSCALED = 19, + VK_FORMAT_R8G8_UINT = 20, + VK_FORMAT_R8G8_SINT = 21, + VK_FORMAT_R8G8_SRGB = 22, + VK_FORMAT_R8G8B8_UNORM = 23, + VK_FORMAT_R8G8B8_SNORM = 24, + VK_FORMAT_R8G8B8_USCALED = 25, + VK_FORMAT_R8G8B8_SSCALED = 26, + VK_FORMAT_R8G8B8_UINT = 27, + VK_FORMAT_R8G8B8_SINT = 28, + VK_FORMAT_R8G8B8_SRGB = 29, + VK_FORMAT_B8G8R8_UNORM = 30, + VK_FORMAT_B8G8R8_SNORM = 31, + VK_FORMAT_B8G8R8_USCALED = 32, + VK_FORMAT_B8G8R8_SSCALED = 33, + VK_FORMAT_B8G8R8_UINT = 34, + VK_FORMAT_B8G8R8_SINT = 35, + VK_FORMAT_B8G8R8_SRGB = 36, + VK_FORMAT_R8G8B8A8_UNORM = 37, + VK_FORMAT_R8G8B8A8_SNORM = 38, + VK_FORMAT_R8G8B8A8_USCALED = 39, + VK_FORMAT_R8G8B8A8_SSCALED = 40, + VK_FORMAT_R8G8B8A8_UINT = 41, + VK_FORMAT_R8G8B8A8_SINT = 42, + VK_FORMAT_R8G8B8A8_SRGB = 43, + VK_FORMAT_B8G8R8A8_UNORM = 44, + VK_FORMAT_B8G8R8A8_SNORM = 45, + VK_FORMAT_B8G8R8A8_USCALED = 46, + VK_FORMAT_B8G8R8A8_SSCALED = 47, + VK_FORMAT_B8G8R8A8_UINT = 48, + VK_FORMAT_B8G8R8A8_SINT = 49, + VK_FORMAT_B8G8R8A8_SRGB = 50, + VK_FORMAT_A8B8G8R8_UNORM_PACK32 = 51, + VK_FORMAT_A8B8G8R8_SNORM_PACK32 = 52, + VK_FORMAT_A8B8G8R8_USCALED_PACK32 = 53, + VK_FORMAT_A8B8G8R8_SSCALED_PACK32 = 54, + VK_FORMAT_A8B8G8R8_UINT_PACK32 = 55, + VK_FORMAT_A8B8G8R8_SINT_PACK32 = 56, + VK_FORMAT_A8B8G8R8_SRGB_PACK32 = 57, + VK_FORMAT_A2R10G10B10_UNORM_PACK32 = 58, + VK_FORMAT_A2R10G10B10_SNORM_PACK32 = 59, + VK_FORMAT_A2R10G10B10_USCALED_PACK32 = 60, + VK_FORMAT_A2R10G10B10_SSCALED_PACK32 = 61, + VK_FORMAT_A2R10G10B10_UINT_PACK32 = 62, + VK_FORMAT_A2R10G10B10_SINT_PACK32 = 63, + VK_FORMAT_A2B10G10R10_UNORM_PACK32 = 64, + VK_FORMAT_A2B10G10R10_SNORM_PACK32 = 65, + VK_FORMAT_A2B10G10R10_USCALED_PACK32 = 66, + VK_FORMAT_A2B10G10R10_SSCALED_PACK32 = 67, + VK_FORMAT_A2B10G10R10_UINT_PACK32 = 68, + VK_FORMAT_A2B10G10R10_SINT_PACK32 = 69, + VK_FORMAT_R16_UNORM = 70, + VK_FORMAT_R16_SNORM = 71, + VK_FORMAT_R16_USCALED = 72, + VK_FORMAT_R16_SSCALED = 73, + VK_FORMAT_R16_UINT = 74, + VK_FORMAT_R16_SINT = 75, + VK_FORMAT_R16_SFLOAT = 76, + VK_FORMAT_R16G16_UNORM = 77, + VK_FORMAT_R16G16_SNORM = 78, + VK_FORMAT_R16G16_USCALED = 79, + VK_FORMAT_R16G16_SSCALED = 80, + VK_FORMAT_R16G16_UINT = 81, + VK_FORMAT_R16G16_SINT = 82, + VK_FORMAT_R16G16_SFLOAT = 83, + VK_FORMAT_R16G16B16_UNORM = 84, + VK_FORMAT_R16G16B16_SNORM = 85, + VK_FORMAT_R16G16B16_USCALED = 86, + VK_FORMAT_R16G16B16_SSCALED = 87, + VK_FORMAT_R16G16B16_UINT = 88, + VK_FORMAT_R16G16B16_SINT = 89, + VK_FORMAT_R16G16B16_SFLOAT = 90, + VK_FORMAT_R16G16B16A16_UNORM = 91, + VK_FORMAT_R16G16B16A16_SNORM = 92, + VK_FORMAT_R16G16B16A16_USCALED = 93, + VK_FORMAT_R16G16B16A16_SSCALED = 94, + VK_FORMAT_R16G16B16A16_UINT = 95, + VK_FORMAT_R16G16B16A16_SINT = 96, + VK_FORMAT_R16G16B16A16_SFLOAT = 97, + VK_FORMAT_R32_UINT = 98, + VK_FORMAT_R32_SINT = 99, + VK_FORMAT_R32_SFLOAT = 100, + VK_FORMAT_R32G32_UINT = 101, + VK_FORMAT_R32G32_SINT = 102, + VK_FORMAT_R32G32_SFLOAT = 103, + VK_FORMAT_R32G32B32_UINT = 104, + VK_FORMAT_R32G32B32_SINT = 105, + VK_FORMAT_R32G32B32_SFLOAT = 106, + VK_FORMAT_R32G32B32A32_UINT = 107, + VK_FORMAT_R32G32B32A32_SINT = 108, + VK_FORMAT_R32G32B32A32_SFLOAT = 109, + VK_FORMAT_R64_UINT = 110, + VK_FORMAT_R64_SINT = 111, + VK_FORMAT_R64_SFLOAT = 112, + VK_FORMAT_R64G64_UINT = 113, + VK_FORMAT_R64G64_SINT = 114, + VK_FORMAT_R64G64_SFLOAT = 115, + VK_FORMAT_R64G64B64_UINT = 116, + VK_FORMAT_R64G64B64_SINT = 117, + VK_FORMAT_R64G64B64_SFLOAT = 118, + VK_FORMAT_R64G64B64A64_UINT = 119, + VK_FORMAT_R64G64B64A64_SINT = 120, + VK_FORMAT_R64G64B64A64_SFLOAT = 121, + VK_FORMAT_B10G11R11_UFLOAT_PACK32 = 122, + VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 = 123, + VK_FORMAT_D16_UNORM = 124, + VK_FORMAT_X8_D24_UNORM_PACK32 = 125, + VK_FORMAT_D32_SFLOAT = 126, + VK_FORMAT_S8_UINT = 127, + VK_FORMAT_D16_UNORM_S8_UINT = 128, + VK_FORMAT_D24_UNORM_S8_UINT = 129, + VK_FORMAT_D32_SFLOAT_S8_UINT = 130, + VK_FORMAT_BC1_RGB_UNORM_BLOCK = 131, + VK_FORMAT_BC1_RGB_SRGB_BLOCK = 132, + VK_FORMAT_BC1_RGBA_UNORM_BLOCK = 133, + VK_FORMAT_BC1_RGBA_SRGB_BLOCK = 134, + VK_FORMAT_BC2_UNORM_BLOCK = 135, + VK_FORMAT_BC2_SRGB_BLOCK = 136, + VK_FORMAT_BC3_UNORM_BLOCK = 137, + VK_FORMAT_BC3_SRGB_BLOCK = 138, + VK_FORMAT_BC4_UNORM_BLOCK = 139, + VK_FORMAT_BC4_SNORM_BLOCK = 140, + VK_FORMAT_BC5_UNORM_BLOCK = 141, + VK_FORMAT_BC5_SNORM_BLOCK = 142, + VK_FORMAT_BC6H_UFLOAT_BLOCK = 143, + VK_FORMAT_BC6H_SFLOAT_BLOCK = 144, + VK_FORMAT_BC7_UNORM_BLOCK = 145, + VK_FORMAT_BC7_SRGB_BLOCK = 146, + VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK = 147, + VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK = 148, + VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK = 149, + VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK = 150, + VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK = 151, + VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK = 152, + VK_FORMAT_EAC_R11_UNORM_BLOCK = 153, + VK_FORMAT_EAC_R11_SNORM_BLOCK = 154, + VK_FORMAT_EAC_R11G11_UNORM_BLOCK = 155, + VK_FORMAT_EAC_R11G11_SNORM_BLOCK = 156, + VK_FORMAT_ASTC_4x4_UNORM_BLOCK = 157, + VK_FORMAT_ASTC_4x4_SRGB_BLOCK = 158, + VK_FORMAT_ASTC_5x4_UNORM_BLOCK = 159, + VK_FORMAT_ASTC_5x4_SRGB_BLOCK = 160, + VK_FORMAT_ASTC_5x5_UNORM_BLOCK = 161, + VK_FORMAT_ASTC_5x5_SRGB_BLOCK = 162, + VK_FORMAT_ASTC_6x5_UNORM_BLOCK = 163, + VK_FORMAT_ASTC_6x5_SRGB_BLOCK = 164, + VK_FORMAT_ASTC_6x6_UNORM_BLOCK = 165, + VK_FORMAT_ASTC_6x6_SRGB_BLOCK = 166, + VK_FORMAT_ASTC_8x5_UNORM_BLOCK = 167, + VK_FORMAT_ASTC_8x5_SRGB_BLOCK = 168, + VK_FORMAT_ASTC_8x6_UNORM_BLOCK = 169, + VK_FORMAT_ASTC_8x6_SRGB_BLOCK = 170, + VK_FORMAT_ASTC_8x8_UNORM_BLOCK = 171, + VK_FORMAT_ASTC_8x8_SRGB_BLOCK = 172, + VK_FORMAT_ASTC_10x5_UNORM_BLOCK = 173, + VK_FORMAT_ASTC_10x5_SRGB_BLOCK = 174, + VK_FORMAT_ASTC_10x6_UNORM_BLOCK = 175, + VK_FORMAT_ASTC_10x6_SRGB_BLOCK = 176, + VK_FORMAT_ASTC_10x8_UNORM_BLOCK = 177, + VK_FORMAT_ASTC_10x8_SRGB_BLOCK = 178, + VK_FORMAT_ASTC_10x10_UNORM_BLOCK = 179, + VK_FORMAT_ASTC_10x10_SRGB_BLOCK = 180, + VK_FORMAT_ASTC_12x10_UNORM_BLOCK = 181, + VK_FORMAT_ASTC_12x10_SRGB_BLOCK = 182, + VK_FORMAT_ASTC_12x12_UNORM_BLOCK = 183, + VK_FORMAT_ASTC_12x12_SRGB_BLOCK = 184, + VK_FORMAT_G8B8G8R8_422_UNORM = 1000156000, + VK_FORMAT_B8G8R8G8_422_UNORM = 1000156001, + VK_FORMAT_G8_B8_R8_3PLANE_420_UNORM = 1000156002, + VK_FORMAT_G8_B8R8_2PLANE_420_UNORM = 1000156003, + VK_FORMAT_G8_B8_R8_3PLANE_422_UNORM = 1000156004, + VK_FORMAT_G8_B8R8_2PLANE_422_UNORM = 1000156005, + VK_FORMAT_G8_B8_R8_3PLANE_444_UNORM = 1000156006, + VK_FORMAT_R10X6_UNORM_PACK16 = 1000156007, + VK_FORMAT_R10X6G10X6_UNORM_2PACK16 = 1000156008, + VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16 = 1000156009, + VK_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16 = 1000156010, + VK_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16 = 1000156011, + VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_420_UNORM_3PACK16 = 1000156012, + VK_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16 = 1000156013, + VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_422_UNORM_3PACK16 = 1000156014, + VK_FORMAT_G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16 = 1000156015, + VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16 = 1000156016, + VK_FORMAT_R12X4_UNORM_PACK16 = 1000156017, + VK_FORMAT_R12X4G12X4_UNORM_2PACK16 = 1000156018, + VK_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16 = 1000156019, + VK_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16 = 1000156020, + VK_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16 = 1000156021, + VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_420_UNORM_3PACK16 = 1000156022, + VK_FORMAT_G12X4_B12X4R12X4_2PLANE_420_UNORM_3PACK16 = 1000156023, + VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_422_UNORM_3PACK16 = 1000156024, + VK_FORMAT_G12X4_B12X4R12X4_2PLANE_422_UNORM_3PACK16 = 1000156025, + VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_444_UNORM_3PACK16 = 1000156026, + VK_FORMAT_G16B16G16R16_422_UNORM = 1000156027, + VK_FORMAT_B16G16R16G16_422_UNORM = 1000156028, + VK_FORMAT_G16_B16_R16_3PLANE_420_UNORM = 1000156029, + VK_FORMAT_G16_B16R16_2PLANE_420_UNORM = 1000156030, + VK_FORMAT_G16_B16_R16_3PLANE_422_UNORM = 1000156031, + VK_FORMAT_G16_B16R16_2PLANE_422_UNORM = 1000156032, + VK_FORMAT_G16_B16_R16_3PLANE_444_UNORM = 1000156033 +} VkFormat; +typedef enum VkFormatFeatureFlagBits { + VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT = 1, + VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT = 2, + VK_FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT = 4, + VK_FORMAT_FEATURE_UNIFORM_TEXEL_BUFFER_BIT = 8, + VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_BIT = 16, + VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_ATOMIC_BIT = 32, + VK_FORMAT_FEATURE_VERTEX_BUFFER_BIT = 64, + VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT = 128, + VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT = 256, + VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT = 512, + VK_FORMAT_FEATURE_BLIT_SRC_BIT = 1024, + VK_FORMAT_FEATURE_BLIT_DST_BIT = 2048, + VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT = 4096, + VK_FORMAT_FEATURE_TRANSFER_SRC_BIT = 16384, + VK_FORMAT_FEATURE_TRANSFER_DST_BIT = 32768, + VK_FORMAT_FEATURE_MIDPOINT_CHROMA_SAMPLES_BIT = 131072, + VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_LINEAR_FILTER_BIT = 262144, + VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_SEPARATE_RECONSTRUCTION_FILTER_BIT = 524288, + VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_CHROMA_RECONSTRUCTION_EXPLICIT_BIT = 1048576, + VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_CHROMA_RECONSTRUCTION_EXPLICIT_FORCEABLE_BIT = 2097152, + VK_FORMAT_FEATURE_DISJOINT_BIT = 4194304, + VK_FORMAT_FEATURE_COSITED_CHROMA_SAMPLES_BIT = 8388608 +} VkFormatFeatureFlagBits; +typedef enum VkFrontFace { + VK_FRONT_FACE_COUNTER_CLOCKWISE = 0, + VK_FRONT_FACE_CLOCKWISE = 1 +} VkFrontFace; +typedef enum VkImageAspectFlagBits { + VK_IMAGE_ASPECT_COLOR_BIT = 1, + VK_IMAGE_ASPECT_DEPTH_BIT = 2, + VK_IMAGE_ASPECT_STENCIL_BIT = 4, + VK_IMAGE_ASPECT_METADATA_BIT = 8, + VK_IMAGE_ASPECT_PLANE_0_BIT = 16, + VK_IMAGE_ASPECT_PLANE_1_BIT = 32, + VK_IMAGE_ASPECT_PLANE_2_BIT = 64 +} VkImageAspectFlagBits; +typedef enum VkImageCreateFlagBits { + VK_IMAGE_CREATE_SPARSE_BINDING_BIT = 1, + VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT = 2, + VK_IMAGE_CREATE_SPARSE_ALIASED_BIT = 4, + VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT = 8, + VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT = 16, + VK_IMAGE_CREATE_ALIAS_BIT = 1024, + VK_IMAGE_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT = 64, + VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT = 32, + VK_IMAGE_CREATE_BLOCK_TEXEL_VIEW_COMPATIBLE_BIT = 128, + VK_IMAGE_CREATE_EXTENDED_USAGE_BIT = 256, + VK_IMAGE_CREATE_PROTECTED_BIT = 2048, + VK_IMAGE_CREATE_DISJOINT_BIT = 512 +} VkImageCreateFlagBits; +typedef enum VkImageLayout { + VK_IMAGE_LAYOUT_UNDEFINED = 0, + VK_IMAGE_LAYOUT_GENERAL = 1, + VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL = 2, + VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL = 3, + VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL = 4, + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL = 5, + VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL = 6, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL = 7, + VK_IMAGE_LAYOUT_PREINITIALIZED = 8, + VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL = 1000117000, + VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL = 1000117001, + VK_IMAGE_LAYOUT_PRESENT_SRC_KHR = 1000001002 +} VkImageLayout; +typedef enum VkImageTiling { + VK_IMAGE_TILING_OPTIMAL = 0, + VK_IMAGE_TILING_LINEAR = 1 +} VkImageTiling; +typedef enum VkImageType { + VK_IMAGE_TYPE_1D = 0, + VK_IMAGE_TYPE_2D = 1, + VK_IMAGE_TYPE_3D = 2 +} VkImageType; +typedef enum VkImageUsageFlagBits { + VK_IMAGE_USAGE_TRANSFER_SRC_BIT = 1, + VK_IMAGE_USAGE_TRANSFER_DST_BIT = 2, + VK_IMAGE_USAGE_SAMPLED_BIT = 4, + VK_IMAGE_USAGE_STORAGE_BIT = 8, + VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT = 16, + VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT = 32, + VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT = 64, + VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT = 128 +} VkImageUsageFlagBits; + +typedef enum VkImageViewType { + VK_IMAGE_VIEW_TYPE_1D = 0, + VK_IMAGE_VIEW_TYPE_2D = 1, + VK_IMAGE_VIEW_TYPE_3D = 2, + VK_IMAGE_VIEW_TYPE_CUBE = 3, + VK_IMAGE_VIEW_TYPE_1D_ARRAY = 4, + VK_IMAGE_VIEW_TYPE_2D_ARRAY = 5, + VK_IMAGE_VIEW_TYPE_CUBE_ARRAY = 6 +} VkImageViewType; +typedef enum VkSharingMode { + VK_SHARING_MODE_EXCLUSIVE = 0, + VK_SHARING_MODE_CONCURRENT = 1 +} VkSharingMode; +typedef enum VkIndexType { + VK_INDEX_TYPE_UINT16 = 0, + VK_INDEX_TYPE_UINT32 = 1 +} VkIndexType; +typedef enum VkLogicOp { + VK_LOGIC_OP_CLEAR = 0, + VK_LOGIC_OP_AND = 1, + VK_LOGIC_OP_AND_REVERSE = 2, + VK_LOGIC_OP_COPY = 3, + VK_LOGIC_OP_AND_INVERTED = 4, + VK_LOGIC_OP_NO_OP = 5, + VK_LOGIC_OP_XOR = 6, + VK_LOGIC_OP_OR = 7, + VK_LOGIC_OP_NOR = 8, + VK_LOGIC_OP_EQUIVALENT = 9, + VK_LOGIC_OP_INVERT = 10, + VK_LOGIC_OP_OR_REVERSE = 11, + VK_LOGIC_OP_COPY_INVERTED = 12, + VK_LOGIC_OP_OR_INVERTED = 13, + VK_LOGIC_OP_NAND = 14, + VK_LOGIC_OP_SET = 15 +} VkLogicOp; +typedef enum VkMemoryHeapFlagBits { + VK_MEMORY_HEAP_DEVICE_LOCAL_BIT = 1, + VK_MEMORY_HEAP_MULTI_INSTANCE_BIT = 2 +} VkMemoryHeapFlagBits; +typedef enum VkAccessFlagBits { + VK_ACCESS_INDIRECT_COMMAND_READ_BIT = 1, + VK_ACCESS_INDEX_READ_BIT = 2, + VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT = 4, + VK_ACCESS_UNIFORM_READ_BIT = 8, + VK_ACCESS_INPUT_ATTACHMENT_READ_BIT = 16, + VK_ACCESS_SHADER_READ_BIT = 32, + VK_ACCESS_SHADER_WRITE_BIT = 64, + VK_ACCESS_COLOR_ATTACHMENT_READ_BIT = 128, + VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT = 256, + VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT = 512, + VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT = 1024, + VK_ACCESS_TRANSFER_READ_BIT = 2048, + VK_ACCESS_TRANSFER_WRITE_BIT = 4096, + VK_ACCESS_HOST_READ_BIT = 8192, + VK_ACCESS_HOST_WRITE_BIT = 16384, + VK_ACCESS_MEMORY_READ_BIT = 32768, + VK_ACCESS_MEMORY_WRITE_BIT = 65536 +} VkAccessFlagBits; +typedef enum VkMemoryPropertyFlagBits { + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT = 1, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT = 2, + VK_MEMORY_PROPERTY_HOST_COHERENT_BIT = 4, + VK_MEMORY_PROPERTY_HOST_CACHED_BIT = 8, + VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT = 16, + VK_MEMORY_PROPERTY_PROTECTED_BIT = 32 +} VkMemoryPropertyFlagBits; +typedef enum VkPhysicalDeviceType { + VK_PHYSICAL_DEVICE_TYPE_OTHER = 0, + VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU = 1, + VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU = 2, + VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU = 3, + VK_PHYSICAL_DEVICE_TYPE_CPU = 4 +} VkPhysicalDeviceType; +typedef enum VkPipelineBindPoint { + VK_PIPELINE_BIND_POINT_GRAPHICS = 0, + VK_PIPELINE_BIND_POINT_COMPUTE = 1 +} VkPipelineBindPoint; +typedef enum VkPipelineCreateFlagBits { + VK_PIPELINE_CREATE_DISABLE_OPTIMIZATION_BIT = 1, + VK_PIPELINE_CREATE_ALLOW_DERIVATIVES_BIT = 2, + VK_PIPELINE_CREATE_DERIVATIVE_BIT = 4, + VK_PIPELINE_CREATE_VIEW_INDEX_FROM_DEVICE_INDEX_BIT = 8, + VK_PIPELINE_CREATE_DISPATCH_BASE = 16 +} VkPipelineCreateFlagBits; +typedef enum VkPrimitiveTopology { + VK_PRIMITIVE_TOPOLOGY_POINT_LIST = 0, + VK_PRIMITIVE_TOPOLOGY_LINE_LIST = 1, + VK_PRIMITIVE_TOPOLOGY_LINE_STRIP = 2, + VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST = 3, + VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP = 4, + VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN = 5, + VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY = 6, + VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY = 7, + VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY = 8, + VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY = 9, + VK_PRIMITIVE_TOPOLOGY_PATCH_LIST = 10 +} VkPrimitiveTopology; +typedef enum VkQueryControlFlagBits { + VK_QUERY_CONTROL_PRECISE_BIT = 1 +} VkQueryControlFlagBits; +typedef enum VkQueryPipelineStatisticFlagBits { + VK_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_VERTICES_BIT = 1, + VK_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_PRIMITIVES_BIT = 2, + VK_QUERY_PIPELINE_STATISTIC_VERTEX_SHADER_INVOCATIONS_BIT = 4, + VK_QUERY_PIPELINE_STATISTIC_GEOMETRY_SHADER_INVOCATIONS_BIT = 8, + VK_QUERY_PIPELINE_STATISTIC_GEOMETRY_SHADER_PRIMITIVES_BIT = 16, + VK_QUERY_PIPELINE_STATISTIC_CLIPPING_INVOCATIONS_BIT = 32, + VK_QUERY_PIPELINE_STATISTIC_CLIPPING_PRIMITIVES_BIT = 64, + VK_QUERY_PIPELINE_STATISTIC_FRAGMENT_SHADER_INVOCATIONS_BIT = 128, + VK_QUERY_PIPELINE_STATISTIC_TESSELLATION_CONTROL_SHADER_PATCHES_BIT = 256, + VK_QUERY_PIPELINE_STATISTIC_TESSELLATION_EVALUATION_SHADER_INVOCATIONS_BIT = 512, + VK_QUERY_PIPELINE_STATISTIC_COMPUTE_SHADER_INVOCATIONS_BIT = 1024 +} VkQueryPipelineStatisticFlagBits; +typedef enum VkQueryResultFlagBits { + VK_QUERY_RESULT_64_BIT = 1, + VK_QUERY_RESULT_WAIT_BIT = 2, + VK_QUERY_RESULT_WITH_AVAILABILITY_BIT = 4, + VK_QUERY_RESULT_PARTIAL_BIT = 8 +} VkQueryResultFlagBits; +typedef enum VkQueryType { + VK_QUERY_TYPE_OCCLUSION = 0, + VK_QUERY_TYPE_PIPELINE_STATISTICS = 1, + VK_QUERY_TYPE_TIMESTAMP = 2 +} VkQueryType; +typedef enum VkQueueFlagBits { + VK_QUEUE_GRAPHICS_BIT = 1, + VK_QUEUE_COMPUTE_BIT = 2, + VK_QUEUE_TRANSFER_BIT = 4, + VK_QUEUE_SPARSE_BINDING_BIT = 8, + VK_QUEUE_PROTECTED_BIT = 16 +} VkQueueFlagBits; +typedef enum VkSubpassContents { + VK_SUBPASS_CONTENTS_INLINE = 0, + VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS = 1 +} VkSubpassContents; +typedef enum VkResult { + VK_SUCCESS = 0, + VK_NOT_READY = 1, + VK_TIMEOUT = 2, + VK_EVENT_SET = 3, + VK_EVENT_RESET = 4, + VK_INCOMPLETE = 5, + VK_ERROR_OUT_OF_HOST_MEMORY = -1, + VK_ERROR_OUT_OF_DEVICE_MEMORY = -2, + VK_ERROR_INITIALIZATION_FAILED = -3, + VK_ERROR_DEVICE_LOST = -4, + VK_ERROR_MEMORY_MAP_FAILED = -5, + VK_ERROR_LAYER_NOT_PRESENT = -6, + VK_ERROR_EXTENSION_NOT_PRESENT = -7, + VK_ERROR_FEATURE_NOT_PRESENT = -8, + VK_ERROR_INCOMPATIBLE_DRIVER = -9, + VK_ERROR_TOO_MANY_OBJECTS = -10, + VK_ERROR_FORMAT_NOT_SUPPORTED = -11, + VK_ERROR_FRAGMENTED_POOL = -12, + VK_ERROR_OUT_OF_POOL_MEMORY = -1000069000, + VK_ERROR_INVALID_EXTERNAL_HANDLE = -1000072003, + VK_ERROR_SURFACE_LOST_KHR = -1000000000, + VK_ERROR_NATIVE_WINDOW_IN_USE_KHR = -1000000001, + VK_SUBOPTIMAL_KHR = 1000001003, + VK_ERROR_OUT_OF_DATE_KHR = -1000001004, + VK_ERROR_VALIDATION_FAILED_EXT = -1000011001 +} VkResult; +typedef enum VkShaderStageFlagBits { + VK_SHADER_STAGE_VERTEX_BIT = 1, + VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT = 2, + VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT = 4, + VK_SHADER_STAGE_GEOMETRY_BIT = 8, + VK_SHADER_STAGE_FRAGMENT_BIT = 16, + VK_SHADER_STAGE_COMPUTE_BIT = 32, + VK_SHADER_STAGE_ALL_GRAPHICS = 0x0000001F, + VK_SHADER_STAGE_ALL = 0x7FFFFFFF +} VkShaderStageFlagBits; +typedef enum VkSparseMemoryBindFlagBits { + VK_SPARSE_MEMORY_BIND_METADATA_BIT = 1 +} VkSparseMemoryBindFlagBits; +typedef enum VkStencilFaceFlagBits { + VK_STENCIL_FACE_FRONT_BIT = 1, + VK_STENCIL_FACE_BACK_BIT = 2, + VK_STENCIL_FRONT_AND_BACK = 0x00000003 +} VkStencilFaceFlagBits; +typedef enum VkStencilOp { + VK_STENCIL_OP_KEEP = 0, + VK_STENCIL_OP_ZERO = 1, + VK_STENCIL_OP_REPLACE = 2, + VK_STENCIL_OP_INCREMENT_AND_CLAMP = 3, + VK_STENCIL_OP_DECREMENT_AND_CLAMP = 4, + VK_STENCIL_OP_INVERT = 5, + VK_STENCIL_OP_INCREMENT_AND_WRAP = 6, + VK_STENCIL_OP_DECREMENT_AND_WRAP = 7 +} VkStencilOp; +typedef enum VkStructureType { + VK_STRUCTURE_TYPE_APPLICATION_INFO = 0, + VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO = 1, + VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO = 2, + VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO = 3, + VK_STRUCTURE_TYPE_SUBMIT_INFO = 4, + VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO = 5, + VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE = 6, + VK_STRUCTURE_TYPE_BIND_SPARSE_INFO = 7, + VK_STRUCTURE_TYPE_FENCE_CREATE_INFO = 8, + VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO = 9, + VK_STRUCTURE_TYPE_EVENT_CREATE_INFO = 10, + VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO = 11, + VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO = 12, + VK_STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO = 13, + VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO = 14, + VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO = 15, + VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO = 16, + VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO = 17, + VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO = 18, + VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO = 19, + VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO = 20, + VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_STATE_CREATE_INFO = 21, + VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO = 22, + VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO = 23, + VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO = 24, + VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO = 25, + VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO = 26, + VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO = 27, + VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO = 28, + VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO = 29, + VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO = 30, + VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO = 31, + VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO = 32, + VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO = 33, + VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO = 34, + VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET = 35, + VK_STRUCTURE_TYPE_COPY_DESCRIPTOR_SET = 36, + VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO = 37, + VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO = 38, + VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO = 39, + VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO = 40, + VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO = 41, + VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO = 42, + VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO = 43, + VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER = 44, + VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER = 45, + VK_STRUCTURE_TYPE_MEMORY_BARRIER = 46, + VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO = 47, + VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO = 48, + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES = 1000094000, + VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO = 1000157000, + VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO = 1000157001, + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES = 1000083000, + VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS = 1000127000, + VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO = 1000127001, + VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO = 1000060000, + VK_STRUCTURE_TYPE_DEVICE_GROUP_RENDER_PASS_BEGIN_INFO = 1000060003, + VK_STRUCTURE_TYPE_DEVICE_GROUP_COMMAND_BUFFER_BEGIN_INFO = 1000060004, + VK_STRUCTURE_TYPE_DEVICE_GROUP_SUBMIT_INFO = 1000060005, + VK_STRUCTURE_TYPE_DEVICE_GROUP_BIND_SPARSE_INFO = 1000060006, + VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_DEVICE_GROUP_INFO = 1000060013, + VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_DEVICE_GROUP_INFO = 1000060014, + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_GROUP_PROPERTIES = 1000070000, + VK_STRUCTURE_TYPE_DEVICE_GROUP_DEVICE_CREATE_INFO = 1000070001, + VK_STRUCTURE_TYPE_BUFFER_MEMORY_REQUIREMENTS_INFO_2 = 1000146000, + VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2 = 1000146001, + VK_STRUCTURE_TYPE_IMAGE_SPARSE_MEMORY_REQUIREMENTS_INFO_2 = 1000146002, + VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2 = 1000146003, + VK_STRUCTURE_TYPE_SPARSE_IMAGE_MEMORY_REQUIREMENTS_2 = 1000146004, + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2 = 1000059000, + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2 = 1000059001, + VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2 = 1000059002, + VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2 = 1000059003, + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2 = 1000059004, + VK_STRUCTURE_TYPE_QUEUE_FAMILY_PROPERTIES_2 = 1000059005, + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PROPERTIES_2 = 1000059006, + VK_STRUCTURE_TYPE_SPARSE_IMAGE_FORMAT_PROPERTIES_2 = 1000059007, + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SPARSE_IMAGE_FORMAT_INFO_2 = 1000059008, + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_POINT_CLIPPING_PROPERTIES = 1000117000, + VK_STRUCTURE_TYPE_RENDER_PASS_INPUT_ATTACHMENT_ASPECT_CREATE_INFO = 1000117001, + VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO = 1000117002, + VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_DOMAIN_ORIGIN_STATE_CREATE_INFO = 1000117003, + VK_STRUCTURE_TYPE_RENDER_PASS_MULTIVIEW_CREATE_INFO = 1000053000, + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES = 1000053001, + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES = 1000053002, + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTERS_FEATURES = 1000120000, + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTER_FEATURES = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTERS_FEATURES, + VK_STRUCTURE_TYPE_PROTECTED_SUBMIT_INFO = 1000145000, + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROTECTED_MEMORY_FEATURES = 1000145001, + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROTECTED_MEMORY_PROPERTIES = 1000145002, + VK_STRUCTURE_TYPE_DEVICE_QUEUE_INFO_2 = 1000145003, + VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_CREATE_INFO = 1000156000, + VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_INFO = 1000156001, + VK_STRUCTURE_TYPE_BIND_IMAGE_PLANE_MEMORY_INFO = 1000156002, + VK_STRUCTURE_TYPE_IMAGE_PLANE_MEMORY_REQUIREMENTS_INFO = 1000156003, + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES = 1000156004, + VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_IMAGE_FORMAT_PROPERTIES = 1000156005, + VK_STRUCTURE_TYPE_DESCRIPTOR_UPDATE_TEMPLATE_CREATE_INFO = 1000085000, + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO = 1000071000, + VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES = 1000071001, + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_BUFFER_INFO = 1000071002, + VK_STRUCTURE_TYPE_EXTERNAL_BUFFER_PROPERTIES = 1000071003, + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES = 1000071004, + VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO = 1000072000, + VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO = 1000072001, + VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO = 1000072002, + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_FENCE_INFO = 1000112000, + VK_STRUCTURE_TYPE_EXTERNAL_FENCE_PROPERTIES = 1000112001, + VK_STRUCTURE_TYPE_EXPORT_FENCE_CREATE_INFO = 1000113000, + VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO = 1000077000, + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_SEMAPHORE_INFO = 1000076000, + VK_STRUCTURE_TYPE_EXTERNAL_SEMAPHORE_PROPERTIES = 1000076001, + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_3_PROPERTIES = 1000168000, + VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_SUPPORT = 1000168001, + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DRAW_PARAMETERS_FEATURES = 1000063000, + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DRAW_PARAMETER_FEATURES = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DRAW_PARAMETERS_FEATURES, + VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR = 1000001000, + VK_STRUCTURE_TYPE_PRESENT_INFO_KHR = 1000001001, + VK_STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_CAPABILITIES_KHR = 1000060007, + VK_STRUCTURE_TYPE_IMAGE_SWAPCHAIN_CREATE_INFO_KHR = 1000060008, + VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR = 1000060009, + VK_STRUCTURE_TYPE_ACQUIRE_NEXT_IMAGE_INFO_KHR = 1000060010, + VK_STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_INFO_KHR = 1000060011, + VK_STRUCTURE_TYPE_DEVICE_GROUP_SWAPCHAIN_CREATE_INFO_KHR = 1000060012, + VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT = 1000011000, + VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT +} VkStructureType; +typedef enum VkSystemAllocationScope { + VK_SYSTEM_ALLOCATION_SCOPE_COMMAND = 0, + VK_SYSTEM_ALLOCATION_SCOPE_OBJECT = 1, + VK_SYSTEM_ALLOCATION_SCOPE_CACHE = 2, + VK_SYSTEM_ALLOCATION_SCOPE_DEVICE = 3, + VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE = 4 +} VkSystemAllocationScope; +typedef enum VkInternalAllocationType { + VK_INTERNAL_ALLOCATION_TYPE_EXECUTABLE = 0 +} VkInternalAllocationType; +typedef enum VkSamplerAddressMode { + VK_SAMPLER_ADDRESS_MODE_REPEAT = 0, + VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT = 1, + VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE = 2, + VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER = 3 +} VkSamplerAddressMode; +typedef enum VkFilter { + VK_FILTER_NEAREST = 0, + VK_FILTER_LINEAR = 1 +} VkFilter; +typedef enum VkSamplerMipmapMode { + VK_SAMPLER_MIPMAP_MODE_NEAREST = 0, + VK_SAMPLER_MIPMAP_MODE_LINEAR = 1 +} VkSamplerMipmapMode; +typedef enum VkVertexInputRate { + VK_VERTEX_INPUT_RATE_VERTEX = 0, + VK_VERTEX_INPUT_RATE_INSTANCE = 1 +} VkVertexInputRate; +typedef enum VkPipelineStageFlagBits { + VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT = 1, + VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT = 2, + VK_PIPELINE_STAGE_VERTEX_INPUT_BIT = 4, + VK_PIPELINE_STAGE_VERTEX_SHADER_BIT = 8, + VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT = 16, + VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT = 32, + VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT = 64, + VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT = 128, + VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT = 256, + VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT = 512, + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT = 1024, + VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT = 2048, + VK_PIPELINE_STAGE_TRANSFER_BIT = 4096, + VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT = 8192, + VK_PIPELINE_STAGE_HOST_BIT = 16384, + VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT = 32768, + VK_PIPELINE_STAGE_ALL_COMMANDS_BIT = 65536 +} VkPipelineStageFlagBits; +typedef enum VkSparseImageFormatFlagBits { + VK_SPARSE_IMAGE_FORMAT_SINGLE_MIPTAIL_BIT = 1, + VK_SPARSE_IMAGE_FORMAT_ALIGNED_MIP_SIZE_BIT = 2, + VK_SPARSE_IMAGE_FORMAT_NONSTANDARD_BLOCK_SIZE_BIT = 4 +} VkSparseImageFormatFlagBits; +typedef enum VkSampleCountFlagBits { + VK_SAMPLE_COUNT_1_BIT = 1, + VK_SAMPLE_COUNT_2_BIT = 2, + VK_SAMPLE_COUNT_4_BIT = 4, + VK_SAMPLE_COUNT_8_BIT = 8, + VK_SAMPLE_COUNT_16_BIT = 16, + VK_SAMPLE_COUNT_32_BIT = 32, + VK_SAMPLE_COUNT_64_BIT = 64 +} VkSampleCountFlagBits; +typedef enum VkAttachmentDescriptionFlagBits { + VK_ATTACHMENT_DESCRIPTION_MAY_ALIAS_BIT = 1 +} VkAttachmentDescriptionFlagBits; +typedef enum VkDescriptorPoolCreateFlagBits { + VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT = 1 +} VkDescriptorPoolCreateFlagBits; +typedef enum VkDependencyFlagBits { + VK_DEPENDENCY_BY_REGION_BIT = 1, + VK_DEPENDENCY_DEVICE_GROUP_BIT = 4, + VK_DEPENDENCY_VIEW_LOCAL_BIT = 2 +} VkDependencyFlagBits; +typedef enum VkObjectType { + VK_OBJECT_TYPE_UNKNOWN = 0, + VK_OBJECT_TYPE_INSTANCE = 1, + VK_OBJECT_TYPE_PHYSICAL_DEVICE = 2, + VK_OBJECT_TYPE_DEVICE = 3, + VK_OBJECT_TYPE_QUEUE = 4, + VK_OBJECT_TYPE_SEMAPHORE = 5, + VK_OBJECT_TYPE_COMMAND_BUFFER = 6, + VK_OBJECT_TYPE_FENCE = 7, + VK_OBJECT_TYPE_DEVICE_MEMORY = 8, + VK_OBJECT_TYPE_BUFFER = 9, + VK_OBJECT_TYPE_IMAGE = 10, + VK_OBJECT_TYPE_EVENT = 11, + VK_OBJECT_TYPE_QUERY_POOL = 12, + VK_OBJECT_TYPE_BUFFER_VIEW = 13, + VK_OBJECT_TYPE_IMAGE_VIEW = 14, + VK_OBJECT_TYPE_SHADER_MODULE = 15, + VK_OBJECT_TYPE_PIPELINE_CACHE = 16, + VK_OBJECT_TYPE_PIPELINE_LAYOUT = 17, + VK_OBJECT_TYPE_RENDER_PASS = 18, + VK_OBJECT_TYPE_PIPELINE = 19, + VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT = 20, + VK_OBJECT_TYPE_SAMPLER = 21, + VK_OBJECT_TYPE_DESCRIPTOR_POOL = 22, + VK_OBJECT_TYPE_DESCRIPTOR_SET = 23, + VK_OBJECT_TYPE_FRAMEBUFFER = 24, + VK_OBJECT_TYPE_COMMAND_POOL = 25, + VK_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION = 1000156000, + VK_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE = 1000085000, + VK_OBJECT_TYPE_SURFACE_KHR = 1000000000, + VK_OBJECT_TYPE_SWAPCHAIN_KHR = 1000001000, + VK_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT = 1000011000 +} VkObjectType; +typedef enum VkDescriptorUpdateTemplateType { + VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_DESCRIPTOR_SET = 0 +} VkDescriptorUpdateTemplateType; + +typedef enum VkPointClippingBehavior { + VK_POINT_CLIPPING_BEHAVIOR_ALL_CLIP_PLANES = 0, + VK_POINT_CLIPPING_BEHAVIOR_USER_CLIP_PLANES_ONLY = 1 +} VkPointClippingBehavior; +typedef enum VkColorSpaceKHR { + VK_COLOR_SPACE_SRGB_NONLINEAR_KHR = 0, + VK_COLORSPACE_SRGB_NONLINEAR_KHR = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR +} VkColorSpaceKHR; +typedef enum VkCompositeAlphaFlagBitsKHR { + VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR = 1, + VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR = 2, + VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR = 4, + VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR = 8 +} VkCompositeAlphaFlagBitsKHR; +typedef enum VkPresentModeKHR { + VK_PRESENT_MODE_IMMEDIATE_KHR = 0, + VK_PRESENT_MODE_MAILBOX_KHR = 1, + VK_PRESENT_MODE_FIFO_KHR = 2, + VK_PRESENT_MODE_FIFO_RELAXED_KHR = 3 +} VkPresentModeKHR; +typedef enum VkSurfaceTransformFlagBitsKHR { + VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR = 1, + VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR = 2, + VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR = 4, + VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR = 8, + VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR = 16, + VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR = 32, + VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR = 64, + VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR = 128, + VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR = 256 +} VkSurfaceTransformFlagBitsKHR; +typedef enum VkDebugReportFlagBitsEXT { + VK_DEBUG_REPORT_INFORMATION_BIT_EXT = 1, + VK_DEBUG_REPORT_WARNING_BIT_EXT = 2, + VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT = 4, + VK_DEBUG_REPORT_ERROR_BIT_EXT = 8, + VK_DEBUG_REPORT_DEBUG_BIT_EXT = 16 +} VkDebugReportFlagBitsEXT; +typedef enum VkDebugReportObjectTypeEXT { + VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT = 0, + VK_DEBUG_REPORT_OBJECT_TYPE_INSTANCE_EXT = 1, + VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT = 2, + VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT = 3, + VK_DEBUG_REPORT_OBJECT_TYPE_QUEUE_EXT = 4, + VK_DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT = 5, + VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT = 6, + VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT = 7, + VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT = 8, + VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT = 9, + VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT = 10, + VK_DEBUG_REPORT_OBJECT_TYPE_EVENT_EXT = 11, + VK_DEBUG_REPORT_OBJECT_TYPE_QUERY_POOL_EXT = 12, + VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_VIEW_EXT = 13, + VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_VIEW_EXT = 14, + VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT = 15, + VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_CACHE_EXT = 16, + VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_LAYOUT_EXT = 17, + VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT = 18, + VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT = 19, + VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT_EXT = 20, + VK_DEBUG_REPORT_OBJECT_TYPE_SAMPLER_EXT = 21, + VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_POOL_EXT = 22, + VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT = 23, + VK_DEBUG_REPORT_OBJECT_TYPE_FRAMEBUFFER_EXT = 24, + VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_POOL_EXT = 25, + VK_DEBUG_REPORT_OBJECT_TYPE_SURFACE_KHR_EXT = 26, + VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT = 27, + VK_DEBUG_REPORT_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT_EXT = 28, + VK_DEBUG_REPORT_OBJECT_TYPE_DEBUG_REPORT_EXT = VK_DEBUG_REPORT_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT_EXT, + VK_DEBUG_REPORT_OBJECT_TYPE_DISPLAY_KHR_EXT = 29, + VK_DEBUG_REPORT_OBJECT_TYPE_DISPLAY_MODE_KHR_EXT = 30, + VK_DEBUG_REPORT_OBJECT_TYPE_OBJECT_TABLE_NVX_EXT = 31, + VK_DEBUG_REPORT_OBJECT_TYPE_INDIRECT_COMMANDS_LAYOUT_NVX_EXT = 32, + VK_DEBUG_REPORT_OBJECT_TYPE_VALIDATION_CACHE_EXT_EXT = 33, + VK_DEBUG_REPORT_OBJECT_TYPE_VALIDATION_CACHE_EXT = VK_DEBUG_REPORT_OBJECT_TYPE_VALIDATION_CACHE_EXT_EXT, + VK_DEBUG_REPORT_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION_EXT = 1000156000, + VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE_EXT = 1000085000 +} VkDebugReportObjectTypeEXT; +typedef enum VkExternalMemoryHandleTypeFlagBits { + VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT = 1, + VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_BIT = 2, + VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT = 4, + VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_BIT = 8, + VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_KMT_BIT = 16, + VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_HEAP_BIT = 32, + VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_RESOURCE_BIT = 64 +} VkExternalMemoryHandleTypeFlagBits; +typedef enum VkExternalMemoryFeatureFlagBits { + VK_EXTERNAL_MEMORY_FEATURE_DEDICATED_ONLY_BIT = 1, + VK_EXTERNAL_MEMORY_FEATURE_EXPORTABLE_BIT = 2, + VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT = 4 +} VkExternalMemoryFeatureFlagBits; +typedef enum VkExternalSemaphoreHandleTypeFlagBits { + VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT = 1, + VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_BIT = 2, + VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT = 4, + VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE_BIT = 8, + VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT = 16 +} VkExternalSemaphoreHandleTypeFlagBits; +typedef enum VkExternalSemaphoreFeatureFlagBits { + VK_EXTERNAL_SEMAPHORE_FEATURE_EXPORTABLE_BIT = 1, + VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT = 2 +} VkExternalSemaphoreFeatureFlagBits; +typedef enum VkSemaphoreImportFlagBits { + VK_SEMAPHORE_IMPORT_TEMPORARY_BIT = 1 +} VkSemaphoreImportFlagBits; +typedef enum VkExternalFenceHandleTypeFlagBits { + VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT = 1, + VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_WIN32_BIT = 2, + VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT = 4, + VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT = 8 +} VkExternalFenceHandleTypeFlagBits; +typedef enum VkExternalFenceFeatureFlagBits { + VK_EXTERNAL_FENCE_FEATURE_EXPORTABLE_BIT = 1, + VK_EXTERNAL_FENCE_FEATURE_IMPORTABLE_BIT = 2 +} VkExternalFenceFeatureFlagBits; +typedef enum VkFenceImportFlagBits { + VK_FENCE_IMPORT_TEMPORARY_BIT = 1 +} VkFenceImportFlagBits; +typedef enum VkPeerMemoryFeatureFlagBits { + VK_PEER_MEMORY_FEATURE_COPY_SRC_BIT = 1, + VK_PEER_MEMORY_FEATURE_COPY_DST_BIT = 2, + VK_PEER_MEMORY_FEATURE_GENERIC_SRC_BIT = 4, + VK_PEER_MEMORY_FEATURE_GENERIC_DST_BIT = 8 +} VkPeerMemoryFeatureFlagBits; +typedef enum VkMemoryAllocateFlagBits { + VK_MEMORY_ALLOCATE_DEVICE_MASK_BIT = 1 +} VkMemoryAllocateFlagBits; +typedef enum VkDeviceGroupPresentModeFlagBitsKHR { + VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR = 1, + VK_DEVICE_GROUP_PRESENT_MODE_REMOTE_BIT_KHR = 2, + VK_DEVICE_GROUP_PRESENT_MODE_SUM_BIT_KHR = 4, + VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_MULTI_DEVICE_BIT_KHR = 8 +} VkDeviceGroupPresentModeFlagBitsKHR; +typedef enum VkSwapchainCreateFlagBitsKHR { + VK_SWAPCHAIN_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT_KHR = 1, + VK_SWAPCHAIN_CREATE_PROTECTED_BIT_KHR = 2 +} VkSwapchainCreateFlagBitsKHR; +typedef enum VkSubgroupFeatureFlagBits { + VK_SUBGROUP_FEATURE_BASIC_BIT = 1, + VK_SUBGROUP_FEATURE_VOTE_BIT = 2, + VK_SUBGROUP_FEATURE_ARITHMETIC_BIT = 4, + VK_SUBGROUP_FEATURE_BALLOT_BIT = 8, + VK_SUBGROUP_FEATURE_SHUFFLE_BIT = 16, + VK_SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT = 32, + VK_SUBGROUP_FEATURE_CLUSTERED_BIT = 64, + VK_SUBGROUP_FEATURE_QUAD_BIT = 128 +} VkSubgroupFeatureFlagBits; +typedef enum VkTessellationDomainOrigin { + VK_TESSELLATION_DOMAIN_ORIGIN_UPPER_LEFT = 0, + VK_TESSELLATION_DOMAIN_ORIGIN_LOWER_LEFT = 1 +} VkTessellationDomainOrigin; +typedef enum VkSamplerYcbcrModelConversion { + VK_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY = 0, + VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_IDENTITY = 1, + VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_709 = 2, + VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_601 = 3, + VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_2020 = 4 +} VkSamplerYcbcrModelConversion; +typedef enum VkSamplerYcbcrRange { + VK_SAMPLER_YCBCR_RANGE_ITU_FULL = 0, + VK_SAMPLER_YCBCR_RANGE_ITU_NARROW = 1 +} VkSamplerYcbcrRange; +typedef enum VkChromaLocation { + VK_CHROMA_LOCATION_COSITED_EVEN = 0, + VK_CHROMA_LOCATION_MIDPOINT = 1 +} VkChromaLocation; +typedef enum VkVendorId { + VK_VENDOR_ID_VIV = 0x10001, + VK_VENDOR_ID_VSI = 0x10002, + VK_VENDOR_ID_KAZAN = 0x10003 +} VkVendorId; +typedef void (VKAPI_PTR *PFN_vkInternalAllocationNotification)( + void* pUserData, + size_t size, + VkInternalAllocationType allocationType, + VkSystemAllocationScope allocationScope); +typedef void (VKAPI_PTR *PFN_vkInternalFreeNotification)( + void* pUserData, + size_t size, + VkInternalAllocationType allocationType, + VkSystemAllocationScope allocationScope); +typedef void* (VKAPI_PTR *PFN_vkReallocationFunction)( + void* pUserData, + void* pOriginal, + size_t size, + size_t alignment, + VkSystemAllocationScope allocationScope); +typedef void* (VKAPI_PTR *PFN_vkAllocationFunction)( + void* pUserData, + size_t size, + size_t alignment, + VkSystemAllocationScope allocationScope); +typedef void (VKAPI_PTR *PFN_vkFreeFunction)( + void* pUserData, + void* pMemory); +typedef void (VKAPI_PTR *PFN_vkVoidFunction)(void); +typedef struct VkBaseOutStructure { + VkStructureType sType; + struct VkBaseOutStructure * pNext; +} VkBaseOutStructure; +typedef struct VkBaseInStructure { + VkStructureType sType; + const struct VkBaseInStructure * pNext; +} VkBaseInStructure; +typedef struct VkOffset2D { + int32_t x; + int32_t y; +} VkOffset2D; +typedef struct VkOffset3D { + int32_t x; + int32_t y; + int32_t z; +} VkOffset3D; +typedef struct VkExtent2D { + uint32_t width; + uint32_t height; +} VkExtent2D; +typedef struct VkExtent3D { + uint32_t width; + uint32_t height; + uint32_t depth; +} VkExtent3D; +typedef struct VkViewport { + float x; + float y; + float width; + float height; + float minDepth; + float maxDepth; +} VkViewport; +typedef struct VkRect2D { + VkOffset2D offset; + VkExtent2D extent; +} VkRect2D; +typedef struct VkClearRect { + VkRect2D rect; + uint32_t baseArrayLayer; + uint32_t layerCount; +} VkClearRect; +typedef struct VkComponentMapping { + VkComponentSwizzle r; + VkComponentSwizzle g; + VkComponentSwizzle b; + VkComponentSwizzle a; +} VkComponentMapping; +typedef struct VkExtensionProperties { + char extensionName [ VK_MAX_EXTENSION_NAME_SIZE ]; + uint32_t specVersion; +} VkExtensionProperties; +typedef struct VkLayerProperties { + char layerName [ VK_MAX_EXTENSION_NAME_SIZE ]; + uint32_t specVersion; + uint32_t implementationVersion; + char description [ VK_MAX_DESCRIPTION_SIZE ]; +} VkLayerProperties; +typedef struct VkApplicationInfo { + VkStructureType sType; + const void * pNext; + const char * pApplicationName; + uint32_t applicationVersion; + const char * pEngineName; + uint32_t engineVersion; + uint32_t apiVersion; +} VkApplicationInfo; +typedef struct VkAllocationCallbacks { + void * pUserData; + PFN_vkAllocationFunction pfnAllocation; + PFN_vkReallocationFunction pfnReallocation; + PFN_vkFreeFunction pfnFree; + PFN_vkInternalAllocationNotification pfnInternalAllocation; + PFN_vkInternalFreeNotification pfnInternalFree; +} VkAllocationCallbacks; +typedef struct VkDescriptorImageInfo { + VkSampler sampler; + VkImageView imageView; + VkImageLayout imageLayout; +} VkDescriptorImageInfo; +typedef struct VkCopyDescriptorSet { + VkStructureType sType; + const void * pNext; + VkDescriptorSet srcSet; + uint32_t srcBinding; + uint32_t srcArrayElement; + VkDescriptorSet dstSet; + uint32_t dstBinding; + uint32_t dstArrayElement; + uint32_t descriptorCount; +} VkCopyDescriptorSet; +typedef struct VkDescriptorPoolSize { + VkDescriptorType type; + uint32_t descriptorCount; +} VkDescriptorPoolSize; +typedef struct VkDescriptorSetAllocateInfo { + VkStructureType sType; + const void * pNext; + VkDescriptorPool descriptorPool; + uint32_t descriptorSetCount; + const VkDescriptorSetLayout * pSetLayouts; +} VkDescriptorSetAllocateInfo; +typedef struct VkSpecializationMapEntry { + uint32_t constantID; + uint32_t offset; + size_t size; +} VkSpecializationMapEntry; +typedef struct VkSpecializationInfo { + uint32_t mapEntryCount; + const VkSpecializationMapEntry * pMapEntries; + size_t dataSize; + const void * pData; +} VkSpecializationInfo; +typedef struct VkVertexInputBindingDescription { + uint32_t binding; + uint32_t stride; + VkVertexInputRate inputRate; +} VkVertexInputBindingDescription; +typedef struct VkVertexInputAttributeDescription { + uint32_t location; + uint32_t binding; + VkFormat format; + uint32_t offset; +} VkVertexInputAttributeDescription; +typedef struct VkStencilOpState { + VkStencilOp failOp; + VkStencilOp passOp; + VkStencilOp depthFailOp; + VkCompareOp compareOp; + uint32_t compareMask; + uint32_t writeMask; + uint32_t reference; +} VkStencilOpState; +typedef struct VkCommandBufferAllocateInfo { + VkStructureType sType; + const void * pNext; + VkCommandPool commandPool; + VkCommandBufferLevel level; + uint32_t commandBufferCount; +} VkCommandBufferAllocateInfo; +typedef union VkClearColorValue { + float float32 [4]; + int32_t int32 [4]; + uint32_t uint32 [4]; +} VkClearColorValue; +typedef struct VkClearDepthStencilValue { + float depth; + uint32_t stencil; +} VkClearDepthStencilValue; +typedef union VkClearValue { + VkClearColorValue color; + VkClearDepthStencilValue depthStencil; +} VkClearValue; +typedef struct VkAttachmentReference { + uint32_t attachment; + VkImageLayout layout; +} VkAttachmentReference; +typedef struct VkDrawIndirectCommand { + uint32_t vertexCount; + uint32_t instanceCount; + uint32_t firstVertex; + uint32_t firstInstance; +} VkDrawIndirectCommand; +typedef struct VkDrawIndexedIndirectCommand { + uint32_t indexCount; + uint32_t instanceCount; + uint32_t firstIndex; + int32_t vertexOffset; + uint32_t firstInstance; +} VkDrawIndexedIndirectCommand; +typedef struct VkDispatchIndirectCommand { + uint32_t x; + uint32_t y; + uint32_t z; +} VkDispatchIndirectCommand; +typedef struct VkSurfaceFormatKHR { + VkFormat format; + VkColorSpaceKHR colorSpace; +} VkSurfaceFormatKHR; +typedef struct VkPresentInfoKHR { + VkStructureType sType; + const void * pNext; + uint32_t waitSemaphoreCount; + const VkSemaphore * pWaitSemaphores; + uint32_t swapchainCount; + const VkSwapchainKHR * pSwapchains; + const uint32_t * pImageIndices; + VkResult * pResults; +} VkPresentInfoKHR; +typedef struct VkPhysicalDeviceExternalImageFormatInfo { + VkStructureType sType; + const void * pNext; + VkExternalMemoryHandleTypeFlagBits handleType; +} VkPhysicalDeviceExternalImageFormatInfo; +typedef struct VkPhysicalDeviceExternalSemaphoreInfo { + VkStructureType sType; + const void * pNext; + VkExternalSemaphoreHandleTypeFlagBits handleType; +} VkPhysicalDeviceExternalSemaphoreInfo; +typedef struct VkPhysicalDeviceExternalFenceInfo { + VkStructureType sType; + const void * pNext; + VkExternalFenceHandleTypeFlagBits handleType; +} VkPhysicalDeviceExternalFenceInfo; +typedef struct VkPhysicalDeviceMultiviewProperties { + VkStructureType sType; + void * pNext; + uint32_t maxMultiviewViewCount; + uint32_t maxMultiviewInstanceIndex; +} VkPhysicalDeviceMultiviewProperties; +typedef struct VkRenderPassMultiviewCreateInfo { + VkStructureType sType; + const void * pNext; + uint32_t subpassCount; + const uint32_t * pViewMasks; + uint32_t dependencyCount; + const int32_t * pViewOffsets; + uint32_t correlationMaskCount; + const uint32_t * pCorrelationMasks; +} VkRenderPassMultiviewCreateInfo; +typedef struct VkBindBufferMemoryDeviceGroupInfo { + VkStructureType sType; + const void * pNext; + uint32_t deviceIndexCount; + const uint32_t * pDeviceIndices; +} VkBindBufferMemoryDeviceGroupInfo; +typedef struct VkBindImageMemoryDeviceGroupInfo { + VkStructureType sType; + const void * pNext; + uint32_t deviceIndexCount; + const uint32_t * pDeviceIndices; + uint32_t splitInstanceBindRegionCount; + const VkRect2D * pSplitInstanceBindRegions; +} VkBindImageMemoryDeviceGroupInfo; +typedef struct VkDeviceGroupRenderPassBeginInfo { + VkStructureType sType; + const void * pNext; + uint32_t deviceMask; + uint32_t deviceRenderAreaCount; + const VkRect2D * pDeviceRenderAreas; +} VkDeviceGroupRenderPassBeginInfo; +typedef struct VkDeviceGroupCommandBufferBeginInfo { + VkStructureType sType; + const void * pNext; + uint32_t deviceMask; +} VkDeviceGroupCommandBufferBeginInfo; +typedef struct VkDeviceGroupSubmitInfo { + VkStructureType sType; + const void * pNext; + uint32_t waitSemaphoreCount; + const uint32_t * pWaitSemaphoreDeviceIndices; + uint32_t commandBufferCount; + const uint32_t * pCommandBufferDeviceMasks; + uint32_t signalSemaphoreCount; + const uint32_t * pSignalSemaphoreDeviceIndices; +} VkDeviceGroupSubmitInfo; +typedef struct VkDeviceGroupBindSparseInfo { + VkStructureType sType; + const void * pNext; + uint32_t resourceDeviceIndex; + uint32_t memoryDeviceIndex; +} VkDeviceGroupBindSparseInfo; +typedef struct VkImageSwapchainCreateInfoKHR { + VkStructureType sType; + const void * pNext; + VkSwapchainKHR swapchain; +} VkImageSwapchainCreateInfoKHR; +typedef struct VkBindImageMemorySwapchainInfoKHR { + VkStructureType sType; + const void * pNext; + VkSwapchainKHR swapchain; + uint32_t imageIndex; +} VkBindImageMemorySwapchainInfoKHR; +typedef struct VkAcquireNextImageInfoKHR { + VkStructureType sType; + const void * pNext; + VkSwapchainKHR swapchain; + uint64_t timeout; + VkSemaphore semaphore; + VkFence fence; + uint32_t deviceMask; +} VkAcquireNextImageInfoKHR; +typedef struct VkDeviceGroupPresentInfoKHR { + VkStructureType sType; + const void * pNext; + uint32_t swapchainCount; + const uint32_t * pDeviceMasks; + VkDeviceGroupPresentModeFlagBitsKHR mode; +} VkDeviceGroupPresentInfoKHR; +typedef struct VkDeviceGroupDeviceCreateInfo { + VkStructureType sType; + const void * pNext; + uint32_t physicalDeviceCount; + const VkPhysicalDevice * pPhysicalDevices; +} VkDeviceGroupDeviceCreateInfo; +typedef struct VkDescriptorUpdateTemplateEntry { + uint32_t dstBinding; + uint32_t dstArrayElement; + uint32_t descriptorCount; + VkDescriptorType descriptorType; + size_t offset; + size_t stride; +} VkDescriptorUpdateTemplateEntry; +typedef struct VkBufferMemoryRequirementsInfo2 { + VkStructureType sType; + const void * pNext; + VkBuffer buffer; +} VkBufferMemoryRequirementsInfo2; +typedef struct VkImageMemoryRequirementsInfo2 { + VkStructureType sType; + const void * pNext; + VkImage image; +} VkImageMemoryRequirementsInfo2; +typedef struct VkImageSparseMemoryRequirementsInfo2 { + VkStructureType sType; + const void * pNext; + VkImage image; +} VkImageSparseMemoryRequirementsInfo2; +typedef struct VkPhysicalDevicePointClippingProperties { + VkStructureType sType; + void * pNext; + VkPointClippingBehavior pointClippingBehavior; +} VkPhysicalDevicePointClippingProperties; +typedef struct VkMemoryDedicatedAllocateInfo { + VkStructureType sType; + const void * pNext; + VkImage image; + VkBuffer buffer; +} VkMemoryDedicatedAllocateInfo; +typedef struct VkPipelineTessellationDomainOriginStateCreateInfo { + VkStructureType sType; + const void * pNext; + VkTessellationDomainOrigin domainOrigin; +} VkPipelineTessellationDomainOriginStateCreateInfo; +typedef struct VkSamplerYcbcrConversionInfo { + VkStructureType sType; + const void * pNext; + VkSamplerYcbcrConversion conversion; +} VkSamplerYcbcrConversionInfo; +typedef struct VkBindImagePlaneMemoryInfo { + VkStructureType sType; + const void * pNext; + VkImageAspectFlagBits planeAspect; +} VkBindImagePlaneMemoryInfo; +typedef struct VkImagePlaneMemoryRequirementsInfo { + VkStructureType sType; + const void * pNext; + VkImageAspectFlagBits planeAspect; +} VkImagePlaneMemoryRequirementsInfo; +typedef struct VkSamplerYcbcrConversionImageFormatProperties { + VkStructureType sType; + void * pNext; + uint32_t combinedImageSamplerDescriptorCount; +} VkSamplerYcbcrConversionImageFormatProperties; +typedef uint32_t VkSampleMask; +typedef uint32_t VkBool32; +typedef uint32_t VkFlags; +typedef uint64_t VkDeviceSize; +typedef VkFlags VkFramebufferCreateFlags; +typedef VkFlags VkQueryPoolCreateFlags; +typedef VkFlags VkRenderPassCreateFlags; +typedef VkFlags VkSamplerCreateFlags; +typedef VkFlags VkPipelineLayoutCreateFlags; +typedef VkFlags VkPipelineCacheCreateFlags; +typedef VkFlags VkPipelineDepthStencilStateCreateFlags; +typedef VkFlags VkPipelineDynamicStateCreateFlags; +typedef VkFlags VkPipelineColorBlendStateCreateFlags; +typedef VkFlags VkPipelineMultisampleStateCreateFlags; +typedef VkFlags VkPipelineRasterizationStateCreateFlags; +typedef VkFlags VkPipelineViewportStateCreateFlags; +typedef VkFlags VkPipelineTessellationStateCreateFlags; +typedef VkFlags VkPipelineInputAssemblyStateCreateFlags; +typedef VkFlags VkPipelineVertexInputStateCreateFlags; +typedef VkFlags VkPipelineShaderStageCreateFlags; +typedef VkFlags VkDescriptorSetLayoutCreateFlags; +typedef VkFlags VkBufferViewCreateFlags; +typedef VkFlags VkInstanceCreateFlags; +typedef VkFlags VkDeviceCreateFlags; +typedef VkFlags VkDeviceQueueCreateFlags; +typedef VkFlags VkQueueFlags; +typedef VkFlags VkMemoryPropertyFlags; +typedef VkFlags VkMemoryHeapFlags; +typedef VkFlags VkAccessFlags; +typedef VkFlags VkBufferUsageFlags; +typedef VkFlags VkBufferCreateFlags; +typedef VkFlags VkShaderStageFlags; +typedef VkFlags VkImageUsageFlags; +typedef VkFlags VkImageCreateFlags; +typedef VkFlags VkImageViewCreateFlags; +typedef VkFlags VkPipelineCreateFlags; +typedef VkFlags VkColorComponentFlags; +typedef VkFlags VkFenceCreateFlags; +typedef VkFlags VkSemaphoreCreateFlags; +typedef VkFlags VkFormatFeatureFlags; +typedef VkFlags VkQueryControlFlags; +typedef VkFlags VkQueryResultFlags; +typedef VkFlags VkShaderModuleCreateFlags; +typedef VkFlags VkEventCreateFlags; +typedef VkFlags VkCommandPoolCreateFlags; +typedef VkFlags VkCommandPoolResetFlags; +typedef VkFlags VkCommandBufferResetFlags; +typedef VkFlags VkCommandBufferUsageFlags; +typedef VkFlags VkQueryPipelineStatisticFlags; +typedef VkFlags VkMemoryMapFlags; +typedef VkFlags VkImageAspectFlags; +typedef VkFlags VkSparseMemoryBindFlags; +typedef VkFlags VkSparseImageFormatFlags; +typedef VkFlags VkSubpassDescriptionFlags; +typedef VkFlags VkPipelineStageFlags; +typedef VkFlags VkSampleCountFlags; +typedef VkFlags VkAttachmentDescriptionFlags; +typedef VkFlags VkStencilFaceFlags; +typedef VkFlags VkCullModeFlags; +typedef VkFlags VkDescriptorPoolCreateFlags; +typedef VkFlags VkDescriptorPoolResetFlags; +typedef VkFlags VkDependencyFlags; +typedef VkFlags VkSubgroupFeatureFlags; +typedef VkFlags VkDescriptorUpdateTemplateCreateFlags; +typedef VkFlags VkCompositeAlphaFlagsKHR; +typedef VkFlags VkSurfaceTransformFlagsKHR; +typedef VkFlags VkSwapchainCreateFlagsKHR; +typedef VkFlags VkPeerMemoryFeatureFlags; +typedef VkFlags VkMemoryAllocateFlags; +typedef VkFlags VkDeviceGroupPresentModeFlagsKHR; +typedef VkFlags VkDebugReportFlagsEXT; +typedef VkFlags VkCommandPoolTrimFlags; +typedef VkFlags VkExternalMemoryHandleTypeFlags; +typedef VkFlags VkExternalMemoryFeatureFlags; +typedef VkFlags VkExternalSemaphoreHandleTypeFlags; +typedef VkFlags VkExternalSemaphoreFeatureFlags; +typedef VkFlags VkSemaphoreImportFlags; +typedef VkFlags VkExternalFenceHandleTypeFlags; +typedef VkFlags VkExternalFenceFeatureFlags; +typedef VkFlags VkFenceImportFlags; +typedef VkBool32 (VKAPI_PTR *PFN_vkDebugReportCallbackEXT)( + VkDebugReportFlagsEXT flags, + VkDebugReportObjectTypeEXT objectType, + uint64_t object, + size_t location, + int32_t messageCode, + const char* pLayerPrefix, + const char* pMessage, + void* pUserData); +typedef struct VkDeviceQueueCreateInfo { + VkStructureType sType; + const void * pNext; + VkDeviceQueueCreateFlags flags; + uint32_t queueFamilyIndex; + uint32_t queueCount; + const float * pQueuePriorities; +} VkDeviceQueueCreateInfo; +typedef struct VkInstanceCreateInfo { + VkStructureType sType; + const void * pNext; + VkInstanceCreateFlags flags; + const VkApplicationInfo * pApplicationInfo; + uint32_t enabledLayerCount; + const char * const* ppEnabledLayerNames; + uint32_t enabledExtensionCount; + const char * const* ppEnabledExtensionNames; +} VkInstanceCreateInfo; +typedef struct VkQueueFamilyProperties { + VkQueueFlags queueFlags; + uint32_t queueCount; + uint32_t timestampValidBits; + VkExtent3D minImageTransferGranularity; +} VkQueueFamilyProperties; +typedef struct VkMemoryAllocateInfo { + VkStructureType sType; + const void * pNext; + VkDeviceSize allocationSize; + uint32_t memoryTypeIndex; +} VkMemoryAllocateInfo; +typedef struct VkMemoryRequirements { + VkDeviceSize size; + VkDeviceSize alignment; + uint32_t memoryTypeBits; +} VkMemoryRequirements; +typedef struct VkSparseImageFormatProperties { + VkImageAspectFlags aspectMask; + VkExtent3D imageGranularity; + VkSparseImageFormatFlags flags; +} VkSparseImageFormatProperties; +typedef struct VkSparseImageMemoryRequirements { + VkSparseImageFormatProperties formatProperties; + uint32_t imageMipTailFirstLod; + VkDeviceSize imageMipTailSize; + VkDeviceSize imageMipTailOffset; + VkDeviceSize imageMipTailStride; +} VkSparseImageMemoryRequirements; +typedef struct VkMemoryType { + VkMemoryPropertyFlags propertyFlags; + uint32_t heapIndex; +} VkMemoryType; +typedef struct VkMemoryHeap { + VkDeviceSize size; + VkMemoryHeapFlags flags; +} VkMemoryHeap; +typedef struct VkMappedMemoryRange { + VkStructureType sType; + const void * pNext; + VkDeviceMemory memory; + VkDeviceSize offset; + VkDeviceSize size; +} VkMappedMemoryRange; +typedef struct VkFormatProperties { + VkFormatFeatureFlags linearTilingFeatures; + VkFormatFeatureFlags optimalTilingFeatures; + VkFormatFeatureFlags bufferFeatures; +} VkFormatProperties; +typedef struct VkImageFormatProperties { + VkExtent3D maxExtent; + uint32_t maxMipLevels; + uint32_t maxArrayLayers; + VkSampleCountFlags sampleCounts; + VkDeviceSize maxResourceSize; +} VkImageFormatProperties; +typedef struct VkDescriptorBufferInfo { + VkBuffer buffer; + VkDeviceSize offset; + VkDeviceSize range; +} VkDescriptorBufferInfo; +typedef struct VkWriteDescriptorSet { + VkStructureType sType; + const void * pNext; + VkDescriptorSet dstSet; + uint32_t dstBinding; + uint32_t dstArrayElement; + uint32_t descriptorCount; + VkDescriptorType descriptorType; + const VkDescriptorImageInfo * pImageInfo; + const VkDescriptorBufferInfo * pBufferInfo; + const VkBufferView * pTexelBufferView; +} VkWriteDescriptorSet; +typedef struct VkBufferCreateInfo { + VkStructureType sType; + const void * pNext; + VkBufferCreateFlags flags; + VkDeviceSize size; + VkBufferUsageFlags usage; + VkSharingMode sharingMode; + uint32_t queueFamilyIndexCount; + const uint32_t * pQueueFamilyIndices; +} VkBufferCreateInfo; +typedef struct VkBufferViewCreateInfo { + VkStructureType sType; + const void * pNext; + VkBufferViewCreateFlags flags; + VkBuffer buffer; + VkFormat format; + VkDeviceSize offset; + VkDeviceSize range; +} VkBufferViewCreateInfo; +typedef struct VkImageSubresource { + VkImageAspectFlags aspectMask; + uint32_t mipLevel; + uint32_t arrayLayer; +} VkImageSubresource; +typedef struct VkImageSubresourceLayers { + VkImageAspectFlags aspectMask; + uint32_t mipLevel; + uint32_t baseArrayLayer; + uint32_t layerCount; +} VkImageSubresourceLayers; +typedef struct VkImageSubresourceRange { + VkImageAspectFlags aspectMask; + uint32_t baseMipLevel; + uint32_t levelCount; + uint32_t baseArrayLayer; + uint32_t layerCount; +} VkImageSubresourceRange; +typedef struct VkMemoryBarrier { + VkStructureType sType; + const void * pNext; + VkAccessFlags srcAccessMask; + VkAccessFlags dstAccessMask; +} VkMemoryBarrier; +typedef struct VkBufferMemoryBarrier { + VkStructureType sType; + const void * pNext; + VkAccessFlags srcAccessMask; + VkAccessFlags dstAccessMask; + uint32_t srcQueueFamilyIndex; + uint32_t dstQueueFamilyIndex; + VkBuffer buffer; + VkDeviceSize offset; + VkDeviceSize size; +} VkBufferMemoryBarrier; +typedef struct VkImageMemoryBarrier { + VkStructureType sType; + const void * pNext; + VkAccessFlags srcAccessMask; + VkAccessFlags dstAccessMask; + VkImageLayout oldLayout; + VkImageLayout newLayout; + uint32_t srcQueueFamilyIndex; + uint32_t dstQueueFamilyIndex; + VkImage image; + VkImageSubresourceRange subresourceRange; +} VkImageMemoryBarrier; +typedef struct VkImageCreateInfo { + VkStructureType sType; + const void * pNext; + VkImageCreateFlags flags; + VkImageType imageType; + VkFormat format; + VkExtent3D extent; + uint32_t mipLevels; + uint32_t arrayLayers; + VkSampleCountFlagBits samples; + VkImageTiling tiling; + VkImageUsageFlags usage; + VkSharingMode sharingMode; + uint32_t queueFamilyIndexCount; + const uint32_t * pQueueFamilyIndices; + VkImageLayout initialLayout; +} VkImageCreateInfo; +typedef struct VkSubresourceLayout { + VkDeviceSize offset; + VkDeviceSize size; + VkDeviceSize rowPitch; + VkDeviceSize arrayPitch; + VkDeviceSize depthPitch; +} VkSubresourceLayout; +typedef struct VkImageViewCreateInfo { + VkStructureType sType; + const void * pNext; + VkImageViewCreateFlags flags; + VkImage image; + VkImageViewType viewType; + VkFormat format; + VkComponentMapping components; + VkImageSubresourceRange subresourceRange; +} VkImageViewCreateInfo; +typedef struct VkBufferCopy { + VkDeviceSize srcOffset; + VkDeviceSize dstOffset; + VkDeviceSize size; +} VkBufferCopy; +typedef struct VkSparseMemoryBind { + VkDeviceSize resourceOffset; + VkDeviceSize size; + VkDeviceMemory memory; + VkDeviceSize memoryOffset; + VkSparseMemoryBindFlags flags; +} VkSparseMemoryBind; +typedef struct VkSparseImageMemoryBind { + VkImageSubresource subresource; + VkOffset3D offset; + VkExtent3D extent; + VkDeviceMemory memory; + VkDeviceSize memoryOffset; + VkSparseMemoryBindFlags flags; +} VkSparseImageMemoryBind; +typedef struct VkSparseBufferMemoryBindInfo { + VkBuffer buffer; + uint32_t bindCount; + const VkSparseMemoryBind * pBinds; +} VkSparseBufferMemoryBindInfo; +typedef struct VkSparseImageOpaqueMemoryBindInfo { + VkImage image; + uint32_t bindCount; + const VkSparseMemoryBind * pBinds; +} VkSparseImageOpaqueMemoryBindInfo; +typedef struct VkSparseImageMemoryBindInfo { + VkImage image; + uint32_t bindCount; + const VkSparseImageMemoryBind * pBinds; +} VkSparseImageMemoryBindInfo; +typedef struct VkBindSparseInfo { + VkStructureType sType; + const void * pNext; + uint32_t waitSemaphoreCount; + const VkSemaphore * pWaitSemaphores; + uint32_t bufferBindCount; + const VkSparseBufferMemoryBindInfo * pBufferBinds; + uint32_t imageOpaqueBindCount; + const VkSparseImageOpaqueMemoryBindInfo * pImageOpaqueBinds; + uint32_t imageBindCount; + const VkSparseImageMemoryBindInfo * pImageBinds; + uint32_t signalSemaphoreCount; + const VkSemaphore * pSignalSemaphores; +} VkBindSparseInfo; +typedef struct VkImageCopy { + VkImageSubresourceLayers srcSubresource; + VkOffset3D srcOffset; + VkImageSubresourceLayers dstSubresource; + VkOffset3D dstOffset; + VkExtent3D extent; +} VkImageCopy; +typedef struct VkImageBlit { + VkImageSubresourceLayers srcSubresource; + VkOffset3D srcOffsets [2]; + VkImageSubresourceLayers dstSubresource; + VkOffset3D dstOffsets [2]; +} VkImageBlit; +typedef struct VkBufferImageCopy { + VkDeviceSize bufferOffset; + uint32_t bufferRowLength; + uint32_t bufferImageHeight; + VkImageSubresourceLayers imageSubresource; + VkOffset3D imageOffset; + VkExtent3D imageExtent; +} VkBufferImageCopy; +typedef struct VkImageResolve { + VkImageSubresourceLayers srcSubresource; + VkOffset3D srcOffset; + VkImageSubresourceLayers dstSubresource; + VkOffset3D dstOffset; + VkExtent3D extent; +} VkImageResolve; +typedef struct VkShaderModuleCreateInfo { + VkStructureType sType; + const void * pNext; + VkShaderModuleCreateFlags flags; + size_t codeSize; + const uint32_t * pCode; +} VkShaderModuleCreateInfo; +typedef struct VkDescriptorSetLayoutBinding { + uint32_t binding; + VkDescriptorType descriptorType; + uint32_t descriptorCount; + VkShaderStageFlags stageFlags; + const VkSampler * pImmutableSamplers; +} VkDescriptorSetLayoutBinding; +typedef struct VkDescriptorSetLayoutCreateInfo { + VkStructureType sType; + const void * pNext; + VkDescriptorSetLayoutCreateFlags flags; + uint32_t bindingCount; + const VkDescriptorSetLayoutBinding * pBindings; +} VkDescriptorSetLayoutCreateInfo; +typedef struct VkDescriptorPoolCreateInfo { + VkStructureType sType; + const void * pNext; + VkDescriptorPoolCreateFlags flags; + uint32_t maxSets; + uint32_t poolSizeCount; + const VkDescriptorPoolSize * pPoolSizes; +} VkDescriptorPoolCreateInfo; +typedef struct VkPipelineShaderStageCreateInfo { + VkStructureType sType; + const void * pNext; + VkPipelineShaderStageCreateFlags flags; + VkShaderStageFlagBits stage; + VkShaderModule module; + const char * pName; + const VkSpecializationInfo * pSpecializationInfo; +} VkPipelineShaderStageCreateInfo; +typedef struct VkComputePipelineCreateInfo { + VkStructureType sType; + const void * pNext; + VkPipelineCreateFlags flags; + VkPipelineShaderStageCreateInfo stage; + VkPipelineLayout layout; + VkPipeline basePipelineHandle; + int32_t basePipelineIndex; +} VkComputePipelineCreateInfo; +typedef struct VkPipelineVertexInputStateCreateInfo { + VkStructureType sType; + const void * pNext; + VkPipelineVertexInputStateCreateFlags flags; + uint32_t vertexBindingDescriptionCount; + const VkVertexInputBindingDescription * pVertexBindingDescriptions; + uint32_t vertexAttributeDescriptionCount; + const VkVertexInputAttributeDescription * pVertexAttributeDescriptions; +} VkPipelineVertexInputStateCreateInfo; +typedef struct VkPipelineInputAssemblyStateCreateInfo { + VkStructureType sType; + const void * pNext; + VkPipelineInputAssemblyStateCreateFlags flags; + VkPrimitiveTopology topology; + VkBool32 primitiveRestartEnable; +} VkPipelineInputAssemblyStateCreateInfo; +typedef struct VkPipelineTessellationStateCreateInfo { + VkStructureType sType; + const void * pNext; + VkPipelineTessellationStateCreateFlags flags; + uint32_t patchControlPoints; +} VkPipelineTessellationStateCreateInfo; +typedef struct VkPipelineViewportStateCreateInfo { + VkStructureType sType; + const void * pNext; + VkPipelineViewportStateCreateFlags flags; + uint32_t viewportCount; + const VkViewport * pViewports; + uint32_t scissorCount; + const VkRect2D * pScissors; +} VkPipelineViewportStateCreateInfo; +typedef struct VkPipelineRasterizationStateCreateInfo { + VkStructureType sType; + const void * pNext; + VkPipelineRasterizationStateCreateFlags flags; + VkBool32 depthClampEnable; + VkBool32 rasterizerDiscardEnable; + VkPolygonMode polygonMode; + VkCullModeFlags cullMode; + VkFrontFace frontFace; + VkBool32 depthBiasEnable; + float depthBiasConstantFactor; + float depthBiasClamp; + float depthBiasSlopeFactor; + float lineWidth; +} VkPipelineRasterizationStateCreateInfo; +typedef struct VkPipelineMultisampleStateCreateInfo { + VkStructureType sType; + const void * pNext; + VkPipelineMultisampleStateCreateFlags flags; + VkSampleCountFlagBits rasterizationSamples; + VkBool32 sampleShadingEnable; + float minSampleShading; + const VkSampleMask * pSampleMask; + VkBool32 alphaToCoverageEnable; + VkBool32 alphaToOneEnable; +} VkPipelineMultisampleStateCreateInfo; +typedef struct VkPipelineColorBlendAttachmentState { + VkBool32 blendEnable; + VkBlendFactor srcColorBlendFactor; + VkBlendFactor dstColorBlendFactor; + VkBlendOp colorBlendOp; + VkBlendFactor srcAlphaBlendFactor; + VkBlendFactor dstAlphaBlendFactor; + VkBlendOp alphaBlendOp; + VkColorComponentFlags colorWriteMask; +} VkPipelineColorBlendAttachmentState; +typedef struct VkPipelineColorBlendStateCreateInfo { + VkStructureType sType; + const void * pNext; + VkPipelineColorBlendStateCreateFlags flags; + VkBool32 logicOpEnable; + VkLogicOp logicOp; + uint32_t attachmentCount; + const VkPipelineColorBlendAttachmentState * pAttachments; + float blendConstants [4]; +} VkPipelineColorBlendStateCreateInfo; +typedef struct VkPipelineDynamicStateCreateInfo { + VkStructureType sType; + const void * pNext; + VkPipelineDynamicStateCreateFlags flags; + uint32_t dynamicStateCount; + const VkDynamicState * pDynamicStates; +} VkPipelineDynamicStateCreateInfo; +typedef struct VkPipelineDepthStencilStateCreateInfo { + VkStructureType sType; + const void * pNext; + VkPipelineDepthStencilStateCreateFlags flags; + VkBool32 depthTestEnable; + VkBool32 depthWriteEnable; + VkCompareOp depthCompareOp; + VkBool32 depthBoundsTestEnable; + VkBool32 stencilTestEnable; + VkStencilOpState front; + VkStencilOpState back; + float minDepthBounds; + float maxDepthBounds; +} VkPipelineDepthStencilStateCreateInfo; +typedef struct VkGraphicsPipelineCreateInfo { + VkStructureType sType; + const void * pNext; + VkPipelineCreateFlags flags; + uint32_t stageCount; + const VkPipelineShaderStageCreateInfo * pStages; + const VkPipelineVertexInputStateCreateInfo * pVertexInputState; + const VkPipelineInputAssemblyStateCreateInfo * pInputAssemblyState; + const VkPipelineTessellationStateCreateInfo * pTessellationState; + const VkPipelineViewportStateCreateInfo * pViewportState; + const VkPipelineRasterizationStateCreateInfo * pRasterizationState; + const VkPipelineMultisampleStateCreateInfo * pMultisampleState; + const VkPipelineDepthStencilStateCreateInfo * pDepthStencilState; + const VkPipelineColorBlendStateCreateInfo * pColorBlendState; + const VkPipelineDynamicStateCreateInfo * pDynamicState; + VkPipelineLayout layout; + VkRenderPass renderPass; + uint32_t subpass; + VkPipeline basePipelineHandle; + int32_t basePipelineIndex; +} VkGraphicsPipelineCreateInfo; +typedef struct VkPipelineCacheCreateInfo { + VkStructureType sType; + const void * pNext; + VkPipelineCacheCreateFlags flags; + size_t initialDataSize; + const void * pInitialData; +} VkPipelineCacheCreateInfo; +typedef struct VkPushConstantRange { + VkShaderStageFlags stageFlags; + uint32_t offset; + uint32_t size; +} VkPushConstantRange; +typedef struct VkPipelineLayoutCreateInfo { + VkStructureType sType; + const void * pNext; + VkPipelineLayoutCreateFlags flags; + uint32_t setLayoutCount; + const VkDescriptorSetLayout * pSetLayouts; + uint32_t pushConstantRangeCount; + const VkPushConstantRange * pPushConstantRanges; +} VkPipelineLayoutCreateInfo; +typedef struct VkSamplerCreateInfo { + VkStructureType sType; + const void * pNext; + VkSamplerCreateFlags flags; + VkFilter magFilter; + VkFilter minFilter; + VkSamplerMipmapMode mipmapMode; + VkSamplerAddressMode addressModeU; + VkSamplerAddressMode addressModeV; + VkSamplerAddressMode addressModeW; + float mipLodBias; + VkBool32 anisotropyEnable; + float maxAnisotropy; + VkBool32 compareEnable; + VkCompareOp compareOp; + float minLod; + float maxLod; + VkBorderColor borderColor; + VkBool32 unnormalizedCoordinates; +} VkSamplerCreateInfo; +typedef struct VkCommandPoolCreateInfo { + VkStructureType sType; + const void * pNext; + VkCommandPoolCreateFlags flags; + uint32_t queueFamilyIndex; +} VkCommandPoolCreateInfo; +typedef struct VkCommandBufferInheritanceInfo { + VkStructureType sType; + const void * pNext; + VkRenderPass renderPass; + uint32_t subpass; + VkFramebuffer framebuffer; + VkBool32 occlusionQueryEnable; + VkQueryControlFlags queryFlags; + VkQueryPipelineStatisticFlags pipelineStatistics; +} VkCommandBufferInheritanceInfo; +typedef struct VkCommandBufferBeginInfo { + VkStructureType sType; + const void * pNext; + VkCommandBufferUsageFlags flags; + const VkCommandBufferInheritanceInfo * pInheritanceInfo; +} VkCommandBufferBeginInfo; +typedef struct VkRenderPassBeginInfo { + VkStructureType sType; + const void * pNext; + VkRenderPass renderPass; + VkFramebuffer framebuffer; + VkRect2D renderArea; + uint32_t clearValueCount; + const VkClearValue * pClearValues; +} VkRenderPassBeginInfo; +typedef struct VkClearAttachment { + VkImageAspectFlags aspectMask; + uint32_t colorAttachment; + VkClearValue clearValue; +} VkClearAttachment; +typedef struct VkAttachmentDescription { + VkAttachmentDescriptionFlags flags; + VkFormat format; + VkSampleCountFlagBits samples; + VkAttachmentLoadOp loadOp; + VkAttachmentStoreOp storeOp; + VkAttachmentLoadOp stencilLoadOp; + VkAttachmentStoreOp stencilStoreOp; + VkImageLayout initialLayout; + VkImageLayout finalLayout; +} VkAttachmentDescription; +typedef struct VkSubpassDescription { + VkSubpassDescriptionFlags flags; + VkPipelineBindPoint pipelineBindPoint; + uint32_t inputAttachmentCount; + const VkAttachmentReference * pInputAttachments; + uint32_t colorAttachmentCount; + const VkAttachmentReference * pColorAttachments; + const VkAttachmentReference * pResolveAttachments; + const VkAttachmentReference * pDepthStencilAttachment; + uint32_t preserveAttachmentCount; + const uint32_t * pPreserveAttachments; +} VkSubpassDescription; +typedef struct VkSubpassDependency { + uint32_t srcSubpass; + uint32_t dstSubpass; + VkPipelineStageFlags srcStageMask; + VkPipelineStageFlags dstStageMask; + VkAccessFlags srcAccessMask; + VkAccessFlags dstAccessMask; + VkDependencyFlags dependencyFlags; +} VkSubpassDependency; +typedef struct VkRenderPassCreateInfo { + VkStructureType sType; + const void * pNext; + VkRenderPassCreateFlags flags; + uint32_t attachmentCount; + const VkAttachmentDescription * pAttachments; + uint32_t subpassCount; + const VkSubpassDescription * pSubpasses; + uint32_t dependencyCount; + const VkSubpassDependency * pDependencies; +} VkRenderPassCreateInfo; +typedef struct VkEventCreateInfo { + VkStructureType sType; + const void * pNext; + VkEventCreateFlags flags; +} VkEventCreateInfo; +typedef struct VkFenceCreateInfo { + VkStructureType sType; + const void * pNext; + VkFenceCreateFlags flags; +} VkFenceCreateInfo; +typedef struct VkPhysicalDeviceFeatures { + VkBool32 robustBufferAccess; + VkBool32 fullDrawIndexUint32; + VkBool32 imageCubeArray; + VkBool32 independentBlend; + VkBool32 geometryShader; + VkBool32 tessellationShader; + VkBool32 sampleRateShading; + VkBool32 dualSrcBlend; + VkBool32 logicOp; + VkBool32 multiDrawIndirect; + VkBool32 drawIndirectFirstInstance; + VkBool32 depthClamp; + VkBool32 depthBiasClamp; + VkBool32 fillModeNonSolid; + VkBool32 depthBounds; + VkBool32 wideLines; + VkBool32 largePoints; + VkBool32 alphaToOne; + VkBool32 multiViewport; + VkBool32 samplerAnisotropy; + VkBool32 textureCompressionETC2; + VkBool32 textureCompressionASTC_LDR; + VkBool32 textureCompressionBC; + VkBool32 occlusionQueryPrecise; + VkBool32 pipelineStatisticsQuery; + VkBool32 vertexPipelineStoresAndAtomics; + VkBool32 fragmentStoresAndAtomics; + VkBool32 shaderTessellationAndGeometryPointSize; + VkBool32 shaderImageGatherExtended; + VkBool32 shaderStorageImageExtendedFormats; + VkBool32 shaderStorageImageMultisample; + VkBool32 shaderStorageImageReadWithoutFormat; + VkBool32 shaderStorageImageWriteWithoutFormat; + VkBool32 shaderUniformBufferArrayDynamicIndexing; + VkBool32 shaderSampledImageArrayDynamicIndexing; + VkBool32 shaderStorageBufferArrayDynamicIndexing; + VkBool32 shaderStorageImageArrayDynamicIndexing; + VkBool32 shaderClipDistance; + VkBool32 shaderCullDistance; + VkBool32 shaderFloat64; + VkBool32 shaderInt64; + VkBool32 shaderInt16; + VkBool32 shaderResourceResidency; + VkBool32 shaderResourceMinLod; + VkBool32 sparseBinding; + VkBool32 sparseResidencyBuffer; + VkBool32 sparseResidencyImage2D; + VkBool32 sparseResidencyImage3D; + VkBool32 sparseResidency2Samples; + VkBool32 sparseResidency4Samples; + VkBool32 sparseResidency8Samples; + VkBool32 sparseResidency16Samples; + VkBool32 sparseResidencyAliased; + VkBool32 variableMultisampleRate; + VkBool32 inheritedQueries; +} VkPhysicalDeviceFeatures; +typedef struct VkPhysicalDeviceSparseProperties { + VkBool32 residencyStandard2DBlockShape; + VkBool32 residencyStandard2DMultisampleBlockShape; + VkBool32 residencyStandard3DBlockShape; + VkBool32 residencyAlignedMipSize; + VkBool32 residencyNonResidentStrict; +} VkPhysicalDeviceSparseProperties; +typedef struct VkPhysicalDeviceLimits { + uint32_t maxImageDimension1D; + uint32_t maxImageDimension2D; + uint32_t maxImageDimension3D; + uint32_t maxImageDimensionCube; + uint32_t maxImageArrayLayers; + uint32_t maxTexelBufferElements; + uint32_t maxUniformBufferRange; + uint32_t maxStorageBufferRange; + uint32_t maxPushConstantsSize; + uint32_t maxMemoryAllocationCount; + uint32_t maxSamplerAllocationCount; + VkDeviceSize bufferImageGranularity; + VkDeviceSize sparseAddressSpaceSize; + uint32_t maxBoundDescriptorSets; + uint32_t maxPerStageDescriptorSamplers; + uint32_t maxPerStageDescriptorUniformBuffers; + uint32_t maxPerStageDescriptorStorageBuffers; + uint32_t maxPerStageDescriptorSampledImages; + uint32_t maxPerStageDescriptorStorageImages; + uint32_t maxPerStageDescriptorInputAttachments; + uint32_t maxPerStageResources; + uint32_t maxDescriptorSetSamplers; + uint32_t maxDescriptorSetUniformBuffers; + uint32_t maxDescriptorSetUniformBuffersDynamic; + uint32_t maxDescriptorSetStorageBuffers; + uint32_t maxDescriptorSetStorageBuffersDynamic; + uint32_t maxDescriptorSetSampledImages; + uint32_t maxDescriptorSetStorageImages; + uint32_t maxDescriptorSetInputAttachments; + uint32_t maxVertexInputAttributes; + uint32_t maxVertexInputBindings; + uint32_t maxVertexInputAttributeOffset; + uint32_t maxVertexInputBindingStride; + uint32_t maxVertexOutputComponents; + uint32_t maxTessellationGenerationLevel; + uint32_t maxTessellationPatchSize; + uint32_t maxTessellationControlPerVertexInputComponents; + uint32_t maxTessellationControlPerVertexOutputComponents; + uint32_t maxTessellationControlPerPatchOutputComponents; + uint32_t maxTessellationControlTotalOutputComponents; + uint32_t maxTessellationEvaluationInputComponents; + uint32_t maxTessellationEvaluationOutputComponents; + uint32_t maxGeometryShaderInvocations; + uint32_t maxGeometryInputComponents; + uint32_t maxGeometryOutputComponents; + uint32_t maxGeometryOutputVertices; + uint32_t maxGeometryTotalOutputComponents; + uint32_t maxFragmentInputComponents; + uint32_t maxFragmentOutputAttachments; + uint32_t maxFragmentDualSrcAttachments; + uint32_t maxFragmentCombinedOutputResources; + uint32_t maxComputeSharedMemorySize; + uint32_t maxComputeWorkGroupCount [3]; + uint32_t maxComputeWorkGroupInvocations; + uint32_t maxComputeWorkGroupSize [3]; + uint32_t subPixelPrecisionBits; + uint32_t subTexelPrecisionBits; + uint32_t mipmapPrecisionBits; + uint32_t maxDrawIndexedIndexValue; + uint32_t maxDrawIndirectCount; + float maxSamplerLodBias; + float maxSamplerAnisotropy; + uint32_t maxViewports; + uint32_t maxViewportDimensions [2]; + float viewportBoundsRange [2]; + uint32_t viewportSubPixelBits; + size_t minMemoryMapAlignment; + VkDeviceSize minTexelBufferOffsetAlignment; + VkDeviceSize minUniformBufferOffsetAlignment; + VkDeviceSize minStorageBufferOffsetAlignment; + int32_t minTexelOffset; + uint32_t maxTexelOffset; + int32_t minTexelGatherOffset; + uint32_t maxTexelGatherOffset; + float minInterpolationOffset; + float maxInterpolationOffset; + uint32_t subPixelInterpolationOffsetBits; + uint32_t maxFramebufferWidth; + uint32_t maxFramebufferHeight; + uint32_t maxFramebufferLayers; + VkSampleCountFlags framebufferColorSampleCounts; + VkSampleCountFlags framebufferDepthSampleCounts; + VkSampleCountFlags framebufferStencilSampleCounts; + VkSampleCountFlags framebufferNoAttachmentsSampleCounts; + uint32_t maxColorAttachments; + VkSampleCountFlags sampledImageColorSampleCounts; + VkSampleCountFlags sampledImageIntegerSampleCounts; + VkSampleCountFlags sampledImageDepthSampleCounts; + VkSampleCountFlags sampledImageStencilSampleCounts; + VkSampleCountFlags storageImageSampleCounts; + uint32_t maxSampleMaskWords; + VkBool32 timestampComputeAndGraphics; + float timestampPeriod; + uint32_t maxClipDistances; + uint32_t maxCullDistances; + uint32_t maxCombinedClipAndCullDistances; + uint32_t discreteQueuePriorities; + float pointSizeRange [2]; + float lineWidthRange [2]; + float pointSizeGranularity; + float lineWidthGranularity; + VkBool32 strictLines; + VkBool32 standardSampleLocations; + VkDeviceSize optimalBufferCopyOffsetAlignment; + VkDeviceSize optimalBufferCopyRowPitchAlignment; + VkDeviceSize nonCoherentAtomSize; +} VkPhysicalDeviceLimits; +typedef struct VkSemaphoreCreateInfo { + VkStructureType sType; + const void * pNext; + VkSemaphoreCreateFlags flags; +} VkSemaphoreCreateInfo; +typedef struct VkQueryPoolCreateInfo { + VkStructureType sType; + const void * pNext; + VkQueryPoolCreateFlags flags; + VkQueryType queryType; + uint32_t queryCount; + VkQueryPipelineStatisticFlags pipelineStatistics; +} VkQueryPoolCreateInfo; +typedef struct VkFramebufferCreateInfo { + VkStructureType sType; + const void * pNext; + VkFramebufferCreateFlags flags; + VkRenderPass renderPass; + uint32_t attachmentCount; + const VkImageView * pAttachments; + uint32_t width; + uint32_t height; + uint32_t layers; +} VkFramebufferCreateInfo; +typedef struct VkSubmitInfo { + VkStructureType sType; + const void * pNext; + uint32_t waitSemaphoreCount; + const VkSemaphore * pWaitSemaphores; + const VkPipelineStageFlags * pWaitDstStageMask; + uint32_t commandBufferCount; + const VkCommandBuffer * pCommandBuffers; + uint32_t signalSemaphoreCount; + const VkSemaphore * pSignalSemaphores; +} VkSubmitInfo; +typedef struct VkSurfaceCapabilitiesKHR { + uint32_t minImageCount; + uint32_t maxImageCount; + VkExtent2D currentExtent; + VkExtent2D minImageExtent; + VkExtent2D maxImageExtent; + uint32_t maxImageArrayLayers; + VkSurfaceTransformFlagsKHR supportedTransforms; + VkSurfaceTransformFlagBitsKHR currentTransform; + VkCompositeAlphaFlagsKHR supportedCompositeAlpha; + VkImageUsageFlags supportedUsageFlags; +} VkSurfaceCapabilitiesKHR; +typedef struct VkSwapchainCreateInfoKHR { + VkStructureType sType; + const void * pNext; + VkSwapchainCreateFlagsKHR flags; + VkSurfaceKHR surface; + uint32_t minImageCount; + VkFormat imageFormat; + VkColorSpaceKHR imageColorSpace; + VkExtent2D imageExtent; + uint32_t imageArrayLayers; + VkImageUsageFlags imageUsage; + VkSharingMode imageSharingMode; + uint32_t queueFamilyIndexCount; + const uint32_t * pQueueFamilyIndices; + VkSurfaceTransformFlagBitsKHR preTransform; + VkCompositeAlphaFlagBitsKHR compositeAlpha; + VkPresentModeKHR presentMode; + VkBool32 clipped; + VkSwapchainKHR oldSwapchain; +} VkSwapchainCreateInfoKHR; +typedef struct VkDebugReportCallbackCreateInfoEXT { + VkStructureType sType; + const void * pNext; + VkDebugReportFlagsEXT flags; + PFN_vkDebugReportCallbackEXT pfnCallback; + void * pUserData; +} VkDebugReportCallbackCreateInfoEXT; +typedef struct VkPhysicalDeviceFeatures2 { + VkStructureType sType; + void * pNext; + VkPhysicalDeviceFeatures features; +} VkPhysicalDeviceFeatures2; +typedef struct VkFormatProperties2 { + VkStructureType sType; + void * pNext; + VkFormatProperties formatProperties; +} VkFormatProperties2; +typedef struct VkImageFormatProperties2 { + VkStructureType sType; + void * pNext; + VkImageFormatProperties imageFormatProperties; +} VkImageFormatProperties2; +typedef struct VkPhysicalDeviceImageFormatInfo2 { + VkStructureType sType; + const void * pNext; + VkFormat format; + VkImageType type; + VkImageTiling tiling; + VkImageUsageFlags usage; + VkImageCreateFlags flags; +} VkPhysicalDeviceImageFormatInfo2; +typedef struct VkQueueFamilyProperties2 { + VkStructureType sType; + void * pNext; + VkQueueFamilyProperties queueFamilyProperties; +} VkQueueFamilyProperties2; +typedef struct VkSparseImageFormatProperties2 { + VkStructureType sType; + void * pNext; + VkSparseImageFormatProperties properties; +} VkSparseImageFormatProperties2; +typedef struct VkPhysicalDeviceSparseImageFormatInfo2 { + VkStructureType sType; + const void * pNext; + VkFormat format; + VkImageType type; + VkSampleCountFlagBits samples; + VkImageUsageFlags usage; + VkImageTiling tiling; +} VkPhysicalDeviceSparseImageFormatInfo2; +typedef struct VkPhysicalDeviceVariablePointersFeatures { + VkStructureType sType; + void * pNext; + VkBool32 variablePointersStorageBuffer; + VkBool32 variablePointers; +} VkPhysicalDeviceVariablePointersFeatures; +typedef struct VkPhysicalDeviceVariablePointerFeatures VkPhysicalDeviceVariablePointerFeatures; +typedef struct VkExternalMemoryProperties { + VkExternalMemoryFeatureFlags externalMemoryFeatures; + VkExternalMemoryHandleTypeFlags exportFromImportedHandleTypes; + VkExternalMemoryHandleTypeFlags compatibleHandleTypes; +} VkExternalMemoryProperties; +typedef struct VkExternalImageFormatProperties { + VkStructureType sType; + void * pNext; + VkExternalMemoryProperties externalMemoryProperties; +} VkExternalImageFormatProperties; +typedef struct VkPhysicalDeviceExternalBufferInfo { + VkStructureType sType; + const void * pNext; + VkBufferCreateFlags flags; + VkBufferUsageFlags usage; + VkExternalMemoryHandleTypeFlagBits handleType; +} VkPhysicalDeviceExternalBufferInfo; +typedef struct VkExternalBufferProperties { + VkStructureType sType; + void * pNext; + VkExternalMemoryProperties externalMemoryProperties; +} VkExternalBufferProperties; +typedef struct VkPhysicalDeviceIDProperties { + VkStructureType sType; + void * pNext; + uint8_t deviceUUID [ VK_UUID_SIZE ]; + uint8_t driverUUID [ VK_UUID_SIZE ]; + uint8_t deviceLUID [ VK_LUID_SIZE ]; + uint32_t deviceNodeMask; + VkBool32 deviceLUIDValid; +} VkPhysicalDeviceIDProperties; +typedef struct VkExternalMemoryImageCreateInfo { + VkStructureType sType; + const void * pNext; + VkExternalMemoryHandleTypeFlags handleTypes; +} VkExternalMemoryImageCreateInfo; +typedef struct VkExternalMemoryBufferCreateInfo { + VkStructureType sType; + const void * pNext; + VkExternalMemoryHandleTypeFlags handleTypes; +} VkExternalMemoryBufferCreateInfo; +typedef struct VkExportMemoryAllocateInfo { + VkStructureType sType; + const void * pNext; + VkExternalMemoryHandleTypeFlags handleTypes; +} VkExportMemoryAllocateInfo; +typedef struct VkExternalSemaphoreProperties { + VkStructureType sType; + void * pNext; + VkExternalSemaphoreHandleTypeFlags exportFromImportedHandleTypes; + VkExternalSemaphoreHandleTypeFlags compatibleHandleTypes; + VkExternalSemaphoreFeatureFlags externalSemaphoreFeatures; +} VkExternalSemaphoreProperties; +typedef struct VkExportSemaphoreCreateInfo { + VkStructureType sType; + const void * pNext; + VkExternalSemaphoreHandleTypeFlags handleTypes; +} VkExportSemaphoreCreateInfo; +typedef struct VkExternalFenceProperties { + VkStructureType sType; + void * pNext; + VkExternalFenceHandleTypeFlags exportFromImportedHandleTypes; + VkExternalFenceHandleTypeFlags compatibleHandleTypes; + VkExternalFenceFeatureFlags externalFenceFeatures; +} VkExternalFenceProperties; +typedef struct VkExportFenceCreateInfo { + VkStructureType sType; + const void * pNext; + VkExternalFenceHandleTypeFlags handleTypes; +} VkExportFenceCreateInfo; +typedef struct VkPhysicalDeviceMultiviewFeatures { + VkStructureType sType; + void * pNext; + VkBool32 multiview; + VkBool32 multiviewGeometryShader; + VkBool32 multiviewTessellationShader; +} VkPhysicalDeviceMultiviewFeatures; +typedef struct VkPhysicalDeviceGroupProperties { + VkStructureType sType; + void * pNext; + uint32_t physicalDeviceCount; + VkPhysicalDevice physicalDevices [ VK_MAX_DEVICE_GROUP_SIZE ]; + VkBool32 subsetAllocation; +} VkPhysicalDeviceGroupProperties; +typedef struct VkMemoryAllocateFlagsInfo { + VkStructureType sType; + const void * pNext; + VkMemoryAllocateFlags flags; + uint32_t deviceMask; +} VkMemoryAllocateFlagsInfo; +typedef struct VkBindBufferMemoryInfo { + VkStructureType sType; + const void * pNext; + VkBuffer buffer; + VkDeviceMemory memory; + VkDeviceSize memoryOffset; +} VkBindBufferMemoryInfo; +typedef struct VkBindImageMemoryInfo { + VkStructureType sType; + const void * pNext; + VkImage image; + VkDeviceMemory memory; + VkDeviceSize memoryOffset; +} VkBindImageMemoryInfo; +typedef struct VkDeviceGroupPresentCapabilitiesKHR { + VkStructureType sType; + const void * pNext; + uint32_t presentMask [ VK_MAX_DEVICE_GROUP_SIZE ]; + VkDeviceGroupPresentModeFlagsKHR modes; +} VkDeviceGroupPresentCapabilitiesKHR; +typedef struct VkDeviceGroupSwapchainCreateInfoKHR { + VkStructureType sType; + const void * pNext; + VkDeviceGroupPresentModeFlagsKHR modes; +} VkDeviceGroupSwapchainCreateInfoKHR; +typedef struct VkDescriptorUpdateTemplateCreateInfo { + VkStructureType sType; + const void * pNext; + VkDescriptorUpdateTemplateCreateFlags flags; + uint32_t descriptorUpdateEntryCount; + const VkDescriptorUpdateTemplateEntry * pDescriptorUpdateEntries; + VkDescriptorUpdateTemplateType templateType; + VkDescriptorSetLayout descriptorSetLayout; + VkPipelineBindPoint pipelineBindPoint; + VkPipelineLayout pipelineLayout; + uint32_t set; +} VkDescriptorUpdateTemplateCreateInfo; +typedef struct VkInputAttachmentAspectReference { + uint32_t subpass; + uint32_t inputAttachmentIndex; + VkImageAspectFlags aspectMask; +} VkInputAttachmentAspectReference; +typedef struct VkRenderPassInputAttachmentAspectCreateInfo { + VkStructureType sType; + const void * pNext; + uint32_t aspectReferenceCount; + const VkInputAttachmentAspectReference * pAspectReferences; +} VkRenderPassInputAttachmentAspectCreateInfo; +typedef struct VkPhysicalDevice16BitStorageFeatures { + VkStructureType sType; + void * pNext; + VkBool32 storageBuffer16BitAccess; + VkBool32 uniformAndStorageBuffer16BitAccess; + VkBool32 storagePushConstant16; + VkBool32 storageInputOutput16; +} VkPhysicalDevice16BitStorageFeatures; +typedef struct VkPhysicalDeviceSubgroupProperties { + VkStructureType sType; + void * pNext; + uint32_t subgroupSize; + VkShaderStageFlags supportedStages; + VkSubgroupFeatureFlags supportedOperations; + VkBool32 quadOperationsInAllStages; +} VkPhysicalDeviceSubgroupProperties; +typedef struct VkMemoryRequirements2 { + VkStructureType sType; + void * pNext; + VkMemoryRequirements memoryRequirements; +} VkMemoryRequirements2; +typedef struct VkMemoryRequirements2KHR VkMemoryRequirements2KHR; +typedef struct VkSparseImageMemoryRequirements2 { + VkStructureType sType; + void * pNext; + VkSparseImageMemoryRequirements memoryRequirements; +} VkSparseImageMemoryRequirements2; +typedef struct VkMemoryDedicatedRequirements { + VkStructureType sType; + void * pNext; + VkBool32 prefersDedicatedAllocation; + VkBool32 requiresDedicatedAllocation; +} VkMemoryDedicatedRequirements; +typedef struct VkImageViewUsageCreateInfo { + VkStructureType sType; + const void * pNext; + VkImageUsageFlags usage; +} VkImageViewUsageCreateInfo; +typedef struct VkSamplerYcbcrConversionCreateInfo { + VkStructureType sType; + const void * pNext; + VkFormat format; + VkSamplerYcbcrModelConversion ycbcrModel; + VkSamplerYcbcrRange ycbcrRange; + VkComponentMapping components; + VkChromaLocation xChromaOffset; + VkChromaLocation yChromaOffset; + VkFilter chromaFilter; + VkBool32 forceExplicitReconstruction; +} VkSamplerYcbcrConversionCreateInfo; +typedef struct VkPhysicalDeviceSamplerYcbcrConversionFeatures { + VkStructureType sType; + void * pNext; + VkBool32 samplerYcbcrConversion; +} VkPhysicalDeviceSamplerYcbcrConversionFeatures; +typedef struct VkProtectedSubmitInfo { + VkStructureType sType; + const void * pNext; + VkBool32 protectedSubmit; +} VkProtectedSubmitInfo; +typedef struct VkPhysicalDeviceProtectedMemoryFeatures { + VkStructureType sType; + void * pNext; + VkBool32 protectedMemory; +} VkPhysicalDeviceProtectedMemoryFeatures; +typedef struct VkPhysicalDeviceProtectedMemoryProperties { + VkStructureType sType; + void * pNext; + VkBool32 protectedNoFault; +} VkPhysicalDeviceProtectedMemoryProperties; +typedef struct VkDeviceQueueInfo2 { + VkStructureType sType; + const void * pNext; + VkDeviceQueueCreateFlags flags; + uint32_t queueFamilyIndex; + uint32_t queueIndex; +} VkDeviceQueueInfo2; +typedef struct VkPhysicalDeviceMaintenance3Properties { + VkStructureType sType; + void * pNext; + uint32_t maxPerSetDescriptors; + VkDeviceSize maxMemoryAllocationSize; +} VkPhysicalDeviceMaintenance3Properties; +typedef struct VkDescriptorSetLayoutSupport { + VkStructureType sType; + void * pNext; + VkBool32 supported; +} VkDescriptorSetLayoutSupport; +typedef struct VkPhysicalDeviceShaderDrawParametersFeatures { + VkStructureType sType; + void * pNext; + VkBool32 shaderDrawParameters; +} VkPhysicalDeviceShaderDrawParametersFeatures; +typedef struct VkPhysicalDeviceShaderDrawParameterFeatures VkPhysicalDeviceShaderDrawParameterFeatures; +typedef struct VkPhysicalDeviceProperties { + uint32_t apiVersion; + uint32_t driverVersion; + uint32_t vendorID; + uint32_t deviceID; + VkPhysicalDeviceType deviceType; + char deviceName [ VK_MAX_PHYSICAL_DEVICE_NAME_SIZE ]; + uint8_t pipelineCacheUUID [ VK_UUID_SIZE ]; + VkPhysicalDeviceLimits limits; + VkPhysicalDeviceSparseProperties sparseProperties; +} VkPhysicalDeviceProperties; +typedef struct VkDeviceCreateInfo { + VkStructureType sType; + const void * pNext; + VkDeviceCreateFlags flags; + uint32_t queueCreateInfoCount; + const VkDeviceQueueCreateInfo * pQueueCreateInfos; + uint32_t enabledLayerCount; + const char * const* ppEnabledLayerNames; + uint32_t enabledExtensionCount; + const char * const* ppEnabledExtensionNames; + const VkPhysicalDeviceFeatures * pEnabledFeatures; +} VkDeviceCreateInfo; +typedef struct VkPhysicalDeviceMemoryProperties { + uint32_t memoryTypeCount; + VkMemoryType memoryTypes [ VK_MAX_MEMORY_TYPES ]; + uint32_t memoryHeapCount; + VkMemoryHeap memoryHeaps [ VK_MAX_MEMORY_HEAPS ]; +} VkPhysicalDeviceMemoryProperties; +typedef struct VkPhysicalDeviceProperties2 { + VkStructureType sType; + void * pNext; + VkPhysicalDeviceProperties properties; +} VkPhysicalDeviceProperties2; +typedef struct VkPhysicalDeviceMemoryProperties2 { + VkStructureType sType; + void * pNext; + VkPhysicalDeviceMemoryProperties memoryProperties; +} VkPhysicalDeviceMemoryProperties2; + + +#define VK_VERSION_1_0 1 +GLAD_API_CALL int GLAD_VK_VERSION_1_0; +#define VK_VERSION_1_1 1 +GLAD_API_CALL int GLAD_VK_VERSION_1_1; +#define VK_EXT_debug_report 1 +GLAD_API_CALL int GLAD_VK_EXT_debug_report; +#define VK_KHR_surface 1 +GLAD_API_CALL int GLAD_VK_KHR_surface; +#define VK_KHR_swapchain 1 +GLAD_API_CALL int GLAD_VK_KHR_swapchain; + + +typedef VkResult (GLAD_API_PTR *PFN_vkAcquireNextImage2KHR)(VkDevice device, const VkAcquireNextImageInfoKHR * pAcquireInfo, uint32_t * pImageIndex); +typedef VkResult (GLAD_API_PTR *PFN_vkAcquireNextImageKHR)(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout, VkSemaphore semaphore, VkFence fence, uint32_t * pImageIndex); +typedef VkResult (GLAD_API_PTR *PFN_vkAllocateCommandBuffers)(VkDevice device, const VkCommandBufferAllocateInfo * pAllocateInfo, VkCommandBuffer * pCommandBuffers); +typedef VkResult (GLAD_API_PTR *PFN_vkAllocateDescriptorSets)(VkDevice device, const VkDescriptorSetAllocateInfo * pAllocateInfo, VkDescriptorSet * pDescriptorSets); +typedef VkResult (GLAD_API_PTR *PFN_vkAllocateMemory)(VkDevice device, const VkMemoryAllocateInfo * pAllocateInfo, const VkAllocationCallbacks * pAllocator, VkDeviceMemory * pMemory); +typedef VkResult (GLAD_API_PTR *PFN_vkBeginCommandBuffer)(VkCommandBuffer commandBuffer, const VkCommandBufferBeginInfo * pBeginInfo); +typedef VkResult (GLAD_API_PTR *PFN_vkBindBufferMemory)(VkDevice device, VkBuffer buffer, VkDeviceMemory memory, VkDeviceSize memoryOffset); +typedef VkResult (GLAD_API_PTR *PFN_vkBindBufferMemory2)(VkDevice device, uint32_t bindInfoCount, const VkBindBufferMemoryInfo * pBindInfos); +typedef VkResult (GLAD_API_PTR *PFN_vkBindImageMemory)(VkDevice device, VkImage image, VkDeviceMemory memory, VkDeviceSize memoryOffset); +typedef VkResult (GLAD_API_PTR *PFN_vkBindImageMemory2)(VkDevice device, uint32_t bindInfoCount, const VkBindImageMemoryInfo * pBindInfos); +typedef void (GLAD_API_PTR *PFN_vkCmdBeginQuery)(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t query, VkQueryControlFlags flags); +typedef void (GLAD_API_PTR *PFN_vkCmdBeginRenderPass)(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo * pRenderPassBegin, VkSubpassContents contents); +typedef void (GLAD_API_PTR *PFN_vkCmdBindDescriptorSets)(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint, VkPipelineLayout layout, uint32_t firstSet, uint32_t descriptorSetCount, const VkDescriptorSet * pDescriptorSets, uint32_t dynamicOffsetCount, const uint32_t * pDynamicOffsets); +typedef void (GLAD_API_PTR *PFN_vkCmdBindIndexBuffer)(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkIndexType indexType); +typedef void (GLAD_API_PTR *PFN_vkCmdBindPipeline)(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint, VkPipeline pipeline); +typedef void (GLAD_API_PTR *PFN_vkCmdBindVertexBuffers)(VkCommandBuffer commandBuffer, uint32_t firstBinding, uint32_t bindingCount, const VkBuffer * pBuffers, const VkDeviceSize * pOffsets); +typedef void (GLAD_API_PTR *PFN_vkCmdBlitImage)(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout, VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount, const VkImageBlit * pRegions, VkFilter filter); +typedef void (GLAD_API_PTR *PFN_vkCmdClearAttachments)(VkCommandBuffer commandBuffer, uint32_t attachmentCount, const VkClearAttachment * pAttachments, uint32_t rectCount, const VkClearRect * pRects); +typedef void (GLAD_API_PTR *PFN_vkCmdClearColorImage)(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout, const VkClearColorValue * pColor, uint32_t rangeCount, const VkImageSubresourceRange * pRanges); +typedef void (GLAD_API_PTR *PFN_vkCmdClearDepthStencilImage)(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout, const VkClearDepthStencilValue * pDepthStencil, uint32_t rangeCount, const VkImageSubresourceRange * pRanges); +typedef void (GLAD_API_PTR *PFN_vkCmdCopyBuffer)(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer, uint32_t regionCount, const VkBufferCopy * pRegions); +typedef void (GLAD_API_PTR *PFN_vkCmdCopyBufferToImage)(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount, const VkBufferImageCopy * pRegions); +typedef void (GLAD_API_PTR *PFN_vkCmdCopyImage)(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout, VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount, const VkImageCopy * pRegions); +typedef void (GLAD_API_PTR *PFN_vkCmdCopyImageToBuffer)(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout, VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy * pRegions); +typedef void (GLAD_API_PTR *PFN_vkCmdCopyQueryPoolResults)(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t firstQuery, uint32_t queryCount, VkBuffer dstBuffer, VkDeviceSize dstOffset, VkDeviceSize stride, VkQueryResultFlags flags); +typedef void (GLAD_API_PTR *PFN_vkCmdDispatch)(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY, uint32_t groupCountZ); +typedef void (GLAD_API_PTR *PFN_vkCmdDispatchBase)(VkCommandBuffer commandBuffer, uint32_t baseGroupX, uint32_t baseGroupY, uint32_t baseGroupZ, uint32_t groupCountX, uint32_t groupCountY, uint32_t groupCountZ); +typedef void (GLAD_API_PTR *PFN_vkCmdDispatchIndirect)(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset); +typedef void (GLAD_API_PTR *PFN_vkCmdDraw)(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount, uint32_t firstVertex, uint32_t firstInstance); +typedef void (GLAD_API_PTR *PFN_vkCmdDrawIndexed)(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount, uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance); +typedef void (GLAD_API_PTR *PFN_vkCmdDrawIndexedIndirect)(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, uint32_t drawCount, uint32_t stride); +typedef void (GLAD_API_PTR *PFN_vkCmdDrawIndirect)(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, uint32_t drawCount, uint32_t stride); +typedef void (GLAD_API_PTR *PFN_vkCmdEndQuery)(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t query); +typedef void (GLAD_API_PTR *PFN_vkCmdEndRenderPass)(VkCommandBuffer commandBuffer); +typedef void (GLAD_API_PTR *PFN_vkCmdExecuteCommands)(VkCommandBuffer commandBuffer, uint32_t commandBufferCount, const VkCommandBuffer * pCommandBuffers); +typedef void (GLAD_API_PTR *PFN_vkCmdFillBuffer)(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset, VkDeviceSize size, uint32_t data); +typedef void (GLAD_API_PTR *PFN_vkCmdNextSubpass)(VkCommandBuffer commandBuffer, VkSubpassContents contents); +typedef void (GLAD_API_PTR *PFN_vkCmdPipelineBarrier)(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount, const VkMemoryBarrier * pMemoryBarriers, uint32_t bufferMemoryBarrierCount, const VkBufferMemoryBarrier * pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount, const VkImageMemoryBarrier * pImageMemoryBarriers); +typedef void (GLAD_API_PTR *PFN_vkCmdPushConstants)(VkCommandBuffer commandBuffer, VkPipelineLayout layout, VkShaderStageFlags stageFlags, uint32_t offset, uint32_t size, const void * pValues); +typedef void (GLAD_API_PTR *PFN_vkCmdResetEvent)(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask); +typedef void (GLAD_API_PTR *PFN_vkCmdResetQueryPool)(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t firstQuery, uint32_t queryCount); +typedef void (GLAD_API_PTR *PFN_vkCmdResolveImage)(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout, VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount, const VkImageResolve * pRegions); +typedef void (GLAD_API_PTR *PFN_vkCmdSetBlendConstants)(VkCommandBuffer commandBuffer, const float blendConstants [4]); +typedef void (GLAD_API_PTR *PFN_vkCmdSetDepthBias)(VkCommandBuffer commandBuffer, float depthBiasConstantFactor, float depthBiasClamp, float depthBiasSlopeFactor); +typedef void (GLAD_API_PTR *PFN_vkCmdSetDepthBounds)(VkCommandBuffer commandBuffer, float minDepthBounds, float maxDepthBounds); +typedef void (GLAD_API_PTR *PFN_vkCmdSetDeviceMask)(VkCommandBuffer commandBuffer, uint32_t deviceMask); +typedef void (GLAD_API_PTR *PFN_vkCmdSetEvent)(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask); +typedef void (GLAD_API_PTR *PFN_vkCmdSetLineWidth)(VkCommandBuffer commandBuffer, float lineWidth); +typedef void (GLAD_API_PTR *PFN_vkCmdSetScissor)(VkCommandBuffer commandBuffer, uint32_t firstScissor, uint32_t scissorCount, const VkRect2D * pScissors); +typedef void (GLAD_API_PTR *PFN_vkCmdSetStencilCompareMask)(VkCommandBuffer commandBuffer, VkStencilFaceFlags faceMask, uint32_t compareMask); +typedef void (GLAD_API_PTR *PFN_vkCmdSetStencilReference)(VkCommandBuffer commandBuffer, VkStencilFaceFlags faceMask, uint32_t reference); +typedef void (GLAD_API_PTR *PFN_vkCmdSetStencilWriteMask)(VkCommandBuffer commandBuffer, VkStencilFaceFlags faceMask, uint32_t writeMask); +typedef void (GLAD_API_PTR *PFN_vkCmdSetViewport)(VkCommandBuffer commandBuffer, uint32_t firstViewport, uint32_t viewportCount, const VkViewport * pViewports); +typedef void (GLAD_API_PTR *PFN_vkCmdUpdateBuffer)(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset, VkDeviceSize dataSize, const void * pData); +typedef void (GLAD_API_PTR *PFN_vkCmdWaitEvents)(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent * pEvents, VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask, uint32_t memoryBarrierCount, const VkMemoryBarrier * pMemoryBarriers, uint32_t bufferMemoryBarrierCount, const VkBufferMemoryBarrier * pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount, const VkImageMemoryBarrier * pImageMemoryBarriers); +typedef void (GLAD_API_PTR *PFN_vkCmdWriteTimestamp)(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage, VkQueryPool queryPool, uint32_t query); +typedef VkResult (GLAD_API_PTR *PFN_vkCreateBuffer)(VkDevice device, const VkBufferCreateInfo * pCreateInfo, const VkAllocationCallbacks * pAllocator, VkBuffer * pBuffer); +typedef VkResult (GLAD_API_PTR *PFN_vkCreateBufferView)(VkDevice device, const VkBufferViewCreateInfo * pCreateInfo, const VkAllocationCallbacks * pAllocator, VkBufferView * pView); +typedef VkResult (GLAD_API_PTR *PFN_vkCreateCommandPool)(VkDevice device, const VkCommandPoolCreateInfo * pCreateInfo, const VkAllocationCallbacks * pAllocator, VkCommandPool * pCommandPool); +typedef VkResult (GLAD_API_PTR *PFN_vkCreateComputePipelines)(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount, const VkComputePipelineCreateInfo * pCreateInfos, const VkAllocationCallbacks * pAllocator, VkPipeline * pPipelines); +typedef VkResult (GLAD_API_PTR *PFN_vkCreateDebugReportCallbackEXT)(VkInstance instance, const VkDebugReportCallbackCreateInfoEXT * pCreateInfo, const VkAllocationCallbacks * pAllocator, VkDebugReportCallbackEXT * pCallback); +typedef VkResult (GLAD_API_PTR *PFN_vkCreateDescriptorPool)(VkDevice device, const VkDescriptorPoolCreateInfo * pCreateInfo, const VkAllocationCallbacks * pAllocator, VkDescriptorPool * pDescriptorPool); +typedef VkResult (GLAD_API_PTR *PFN_vkCreateDescriptorSetLayout)(VkDevice device, const VkDescriptorSetLayoutCreateInfo * pCreateInfo, const VkAllocationCallbacks * pAllocator, VkDescriptorSetLayout * pSetLayout); +typedef VkResult (GLAD_API_PTR *PFN_vkCreateDescriptorUpdateTemplate)(VkDevice device, const VkDescriptorUpdateTemplateCreateInfo * pCreateInfo, const VkAllocationCallbacks * pAllocator, VkDescriptorUpdateTemplate * pDescriptorUpdateTemplate); +typedef VkResult (GLAD_API_PTR *PFN_vkCreateDevice)(VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo * pCreateInfo, const VkAllocationCallbacks * pAllocator, VkDevice * pDevice); +typedef VkResult (GLAD_API_PTR *PFN_vkCreateEvent)(VkDevice device, const VkEventCreateInfo * pCreateInfo, const VkAllocationCallbacks * pAllocator, VkEvent * pEvent); +typedef VkResult (GLAD_API_PTR *PFN_vkCreateFence)(VkDevice device, const VkFenceCreateInfo * pCreateInfo, const VkAllocationCallbacks * pAllocator, VkFence * pFence); +typedef VkResult (GLAD_API_PTR *PFN_vkCreateFramebuffer)(VkDevice device, const VkFramebufferCreateInfo * pCreateInfo, const VkAllocationCallbacks * pAllocator, VkFramebuffer * pFramebuffer); +typedef VkResult (GLAD_API_PTR *PFN_vkCreateGraphicsPipelines)(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount, const VkGraphicsPipelineCreateInfo * pCreateInfos, const VkAllocationCallbacks * pAllocator, VkPipeline * pPipelines); +typedef VkResult (GLAD_API_PTR *PFN_vkCreateImage)(VkDevice device, const VkImageCreateInfo * pCreateInfo, const VkAllocationCallbacks * pAllocator, VkImage * pImage); +typedef VkResult (GLAD_API_PTR *PFN_vkCreateImageView)(VkDevice device, const VkImageViewCreateInfo * pCreateInfo, const VkAllocationCallbacks * pAllocator, VkImageView * pView); +typedef VkResult (GLAD_API_PTR *PFN_vkCreateInstance)(const VkInstanceCreateInfo * pCreateInfo, const VkAllocationCallbacks * pAllocator, VkInstance * pInstance); +typedef VkResult (GLAD_API_PTR *PFN_vkCreatePipelineCache)(VkDevice device, const VkPipelineCacheCreateInfo * pCreateInfo, const VkAllocationCallbacks * pAllocator, VkPipelineCache * pPipelineCache); +typedef VkResult (GLAD_API_PTR *PFN_vkCreatePipelineLayout)(VkDevice device, const VkPipelineLayoutCreateInfo * pCreateInfo, const VkAllocationCallbacks * pAllocator, VkPipelineLayout * pPipelineLayout); +typedef VkResult (GLAD_API_PTR *PFN_vkCreateQueryPool)(VkDevice device, const VkQueryPoolCreateInfo * pCreateInfo, const VkAllocationCallbacks * pAllocator, VkQueryPool * pQueryPool); +typedef VkResult (GLAD_API_PTR *PFN_vkCreateRenderPass)(VkDevice device, const VkRenderPassCreateInfo * pCreateInfo, const VkAllocationCallbacks * pAllocator, VkRenderPass * pRenderPass); +typedef VkResult (GLAD_API_PTR *PFN_vkCreateSampler)(VkDevice device, const VkSamplerCreateInfo * pCreateInfo, const VkAllocationCallbacks * pAllocator, VkSampler * pSampler); +typedef VkResult (GLAD_API_PTR *PFN_vkCreateSamplerYcbcrConversion)(VkDevice device, const VkSamplerYcbcrConversionCreateInfo * pCreateInfo, const VkAllocationCallbacks * pAllocator, VkSamplerYcbcrConversion * pYcbcrConversion); +typedef VkResult (GLAD_API_PTR *PFN_vkCreateSemaphore)(VkDevice device, const VkSemaphoreCreateInfo * pCreateInfo, const VkAllocationCallbacks * pAllocator, VkSemaphore * pSemaphore); +typedef VkResult (GLAD_API_PTR *PFN_vkCreateShaderModule)(VkDevice device, const VkShaderModuleCreateInfo * pCreateInfo, const VkAllocationCallbacks * pAllocator, VkShaderModule * pShaderModule); +typedef VkResult (GLAD_API_PTR *PFN_vkCreateSwapchainKHR)(VkDevice device, const VkSwapchainCreateInfoKHR * pCreateInfo, const VkAllocationCallbacks * pAllocator, VkSwapchainKHR * pSwapchain); +typedef void (GLAD_API_PTR *PFN_vkDebugReportMessageEXT)(VkInstance instance, VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objectType, uint64_t object, size_t location, int32_t messageCode, const char * pLayerPrefix, const char * pMessage); +typedef void (GLAD_API_PTR *PFN_vkDestroyBuffer)(VkDevice device, VkBuffer buffer, const VkAllocationCallbacks * pAllocator); +typedef void (GLAD_API_PTR *PFN_vkDestroyBufferView)(VkDevice device, VkBufferView bufferView, const VkAllocationCallbacks * pAllocator); +typedef void (GLAD_API_PTR *PFN_vkDestroyCommandPool)(VkDevice device, VkCommandPool commandPool, const VkAllocationCallbacks * pAllocator); +typedef void (GLAD_API_PTR *PFN_vkDestroyDebugReportCallbackEXT)(VkInstance instance, VkDebugReportCallbackEXT callback, const VkAllocationCallbacks * pAllocator); +typedef void (GLAD_API_PTR *PFN_vkDestroyDescriptorPool)(VkDevice device, VkDescriptorPool descriptorPool, const VkAllocationCallbacks * pAllocator); +typedef void (GLAD_API_PTR *PFN_vkDestroyDescriptorSetLayout)(VkDevice device, VkDescriptorSetLayout descriptorSetLayout, const VkAllocationCallbacks * pAllocator); +typedef void (GLAD_API_PTR *PFN_vkDestroyDescriptorUpdateTemplate)(VkDevice device, VkDescriptorUpdateTemplate descriptorUpdateTemplate, const VkAllocationCallbacks * pAllocator); +typedef void (GLAD_API_PTR *PFN_vkDestroyDevice)(VkDevice device, const VkAllocationCallbacks * pAllocator); +typedef void (GLAD_API_PTR *PFN_vkDestroyEvent)(VkDevice device, VkEvent event, const VkAllocationCallbacks * pAllocator); +typedef void (GLAD_API_PTR *PFN_vkDestroyFence)(VkDevice device, VkFence fence, const VkAllocationCallbacks * pAllocator); +typedef void (GLAD_API_PTR *PFN_vkDestroyFramebuffer)(VkDevice device, VkFramebuffer framebuffer, const VkAllocationCallbacks * pAllocator); +typedef void (GLAD_API_PTR *PFN_vkDestroyImage)(VkDevice device, VkImage image, const VkAllocationCallbacks * pAllocator); +typedef void (GLAD_API_PTR *PFN_vkDestroyImageView)(VkDevice device, VkImageView imageView, const VkAllocationCallbacks * pAllocator); +typedef void (GLAD_API_PTR *PFN_vkDestroyInstance)(VkInstance instance, const VkAllocationCallbacks * pAllocator); +typedef void (GLAD_API_PTR *PFN_vkDestroyPipeline)(VkDevice device, VkPipeline pipeline, const VkAllocationCallbacks * pAllocator); +typedef void (GLAD_API_PTR *PFN_vkDestroyPipelineCache)(VkDevice device, VkPipelineCache pipelineCache, const VkAllocationCallbacks * pAllocator); +typedef void (GLAD_API_PTR *PFN_vkDestroyPipelineLayout)(VkDevice device, VkPipelineLayout pipelineLayout, const VkAllocationCallbacks * pAllocator); +typedef void (GLAD_API_PTR *PFN_vkDestroyQueryPool)(VkDevice device, VkQueryPool queryPool, const VkAllocationCallbacks * pAllocator); +typedef void (GLAD_API_PTR *PFN_vkDestroyRenderPass)(VkDevice device, VkRenderPass renderPass, const VkAllocationCallbacks * pAllocator); +typedef void (GLAD_API_PTR *PFN_vkDestroySampler)(VkDevice device, VkSampler sampler, const VkAllocationCallbacks * pAllocator); +typedef void (GLAD_API_PTR *PFN_vkDestroySamplerYcbcrConversion)(VkDevice device, VkSamplerYcbcrConversion ycbcrConversion, const VkAllocationCallbacks * pAllocator); +typedef void (GLAD_API_PTR *PFN_vkDestroySemaphore)(VkDevice device, VkSemaphore semaphore, const VkAllocationCallbacks * pAllocator); +typedef void (GLAD_API_PTR *PFN_vkDestroyShaderModule)(VkDevice device, VkShaderModule shaderModule, const VkAllocationCallbacks * pAllocator); +typedef void (GLAD_API_PTR *PFN_vkDestroySurfaceKHR)(VkInstance instance, VkSurfaceKHR surface, const VkAllocationCallbacks * pAllocator); +typedef void (GLAD_API_PTR *PFN_vkDestroySwapchainKHR)(VkDevice device, VkSwapchainKHR swapchain, const VkAllocationCallbacks * pAllocator); +typedef VkResult (GLAD_API_PTR *PFN_vkDeviceWaitIdle)(VkDevice device); +typedef VkResult (GLAD_API_PTR *PFN_vkEndCommandBuffer)(VkCommandBuffer commandBuffer); +typedef VkResult (GLAD_API_PTR *PFN_vkEnumerateDeviceExtensionProperties)(VkPhysicalDevice physicalDevice, const char * pLayerName, uint32_t * pPropertyCount, VkExtensionProperties * pProperties); +typedef VkResult (GLAD_API_PTR *PFN_vkEnumerateDeviceLayerProperties)(VkPhysicalDevice physicalDevice, uint32_t * pPropertyCount, VkLayerProperties * pProperties); +typedef VkResult (GLAD_API_PTR *PFN_vkEnumerateInstanceExtensionProperties)(const char * pLayerName, uint32_t * pPropertyCount, VkExtensionProperties * pProperties); +typedef VkResult (GLAD_API_PTR *PFN_vkEnumerateInstanceLayerProperties)(uint32_t * pPropertyCount, VkLayerProperties * pProperties); +typedef VkResult (GLAD_API_PTR *PFN_vkEnumerateInstanceVersion)(uint32_t * pApiVersion); +typedef VkResult (GLAD_API_PTR *PFN_vkEnumeratePhysicalDeviceGroups)(VkInstance instance, uint32_t * pPhysicalDeviceGroupCount, VkPhysicalDeviceGroupProperties * pPhysicalDeviceGroupProperties); +typedef VkResult (GLAD_API_PTR *PFN_vkEnumeratePhysicalDevices)(VkInstance instance, uint32_t * pPhysicalDeviceCount, VkPhysicalDevice * pPhysicalDevices); +typedef VkResult (GLAD_API_PTR *PFN_vkFlushMappedMemoryRanges)(VkDevice device, uint32_t memoryRangeCount, const VkMappedMemoryRange * pMemoryRanges); +typedef void (GLAD_API_PTR *PFN_vkFreeCommandBuffers)(VkDevice device, VkCommandPool commandPool, uint32_t commandBufferCount, const VkCommandBuffer * pCommandBuffers); +typedef VkResult (GLAD_API_PTR *PFN_vkFreeDescriptorSets)(VkDevice device, VkDescriptorPool descriptorPool, uint32_t descriptorSetCount, const VkDescriptorSet * pDescriptorSets); +typedef void (GLAD_API_PTR *PFN_vkFreeMemory)(VkDevice device, VkDeviceMemory memory, const VkAllocationCallbacks * pAllocator); +typedef void (GLAD_API_PTR *PFN_vkGetBufferMemoryRequirements)(VkDevice device, VkBuffer buffer, VkMemoryRequirements * pMemoryRequirements); +typedef void (GLAD_API_PTR *PFN_vkGetBufferMemoryRequirements2)(VkDevice device, const VkBufferMemoryRequirementsInfo2 * pInfo, VkMemoryRequirements2 * pMemoryRequirements); +typedef void (GLAD_API_PTR *PFN_vkGetDescriptorSetLayoutSupport)(VkDevice device, const VkDescriptorSetLayoutCreateInfo * pCreateInfo, VkDescriptorSetLayoutSupport * pSupport); +typedef void (GLAD_API_PTR *PFN_vkGetDeviceGroupPeerMemoryFeatures)(VkDevice device, uint32_t heapIndex, uint32_t localDeviceIndex, uint32_t remoteDeviceIndex, VkPeerMemoryFeatureFlags * pPeerMemoryFeatures); +typedef VkResult (GLAD_API_PTR *PFN_vkGetDeviceGroupPresentCapabilitiesKHR)(VkDevice device, VkDeviceGroupPresentCapabilitiesKHR * pDeviceGroupPresentCapabilities); +typedef VkResult (GLAD_API_PTR *PFN_vkGetDeviceGroupSurfacePresentModesKHR)(VkDevice device, VkSurfaceKHR surface, VkDeviceGroupPresentModeFlagsKHR * pModes); +typedef void (GLAD_API_PTR *PFN_vkGetDeviceMemoryCommitment)(VkDevice device, VkDeviceMemory memory, VkDeviceSize * pCommittedMemoryInBytes); +typedef PFN_vkVoidFunction (GLAD_API_PTR *PFN_vkGetDeviceProcAddr)(VkDevice device, const char * pName); +typedef void (GLAD_API_PTR *PFN_vkGetDeviceQueue)(VkDevice device, uint32_t queueFamilyIndex, uint32_t queueIndex, VkQueue * pQueue); +typedef void (GLAD_API_PTR *PFN_vkGetDeviceQueue2)(VkDevice device, const VkDeviceQueueInfo2 * pQueueInfo, VkQueue * pQueue); +typedef VkResult (GLAD_API_PTR *PFN_vkGetEventStatus)(VkDevice device, VkEvent event); +typedef VkResult (GLAD_API_PTR *PFN_vkGetFenceStatus)(VkDevice device, VkFence fence); +typedef void (GLAD_API_PTR *PFN_vkGetImageMemoryRequirements)(VkDevice device, VkImage image, VkMemoryRequirements * pMemoryRequirements); +typedef void (GLAD_API_PTR *PFN_vkGetImageMemoryRequirements2)(VkDevice device, const VkImageMemoryRequirementsInfo2 * pInfo, VkMemoryRequirements2 * pMemoryRequirements); +typedef void (GLAD_API_PTR *PFN_vkGetImageSparseMemoryRequirements)(VkDevice device, VkImage image, uint32_t * pSparseMemoryRequirementCount, VkSparseImageMemoryRequirements * pSparseMemoryRequirements); +typedef void (GLAD_API_PTR *PFN_vkGetImageSparseMemoryRequirements2)(VkDevice device, const VkImageSparseMemoryRequirementsInfo2 * pInfo, uint32_t * pSparseMemoryRequirementCount, VkSparseImageMemoryRequirements2 * pSparseMemoryRequirements); +typedef void (GLAD_API_PTR *PFN_vkGetImageSubresourceLayout)(VkDevice device, VkImage image, const VkImageSubresource * pSubresource, VkSubresourceLayout * pLayout); +typedef PFN_vkVoidFunction (GLAD_API_PTR *PFN_vkGetInstanceProcAddr)(VkInstance instance, const char * pName); +typedef void (GLAD_API_PTR *PFN_vkGetPhysicalDeviceExternalBufferProperties)(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceExternalBufferInfo * pExternalBufferInfo, VkExternalBufferProperties * pExternalBufferProperties); +typedef void (GLAD_API_PTR *PFN_vkGetPhysicalDeviceExternalFenceProperties)(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceExternalFenceInfo * pExternalFenceInfo, VkExternalFenceProperties * pExternalFenceProperties); +typedef void (GLAD_API_PTR *PFN_vkGetPhysicalDeviceExternalSemaphoreProperties)(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceExternalSemaphoreInfo * pExternalSemaphoreInfo, VkExternalSemaphoreProperties * pExternalSemaphoreProperties); +typedef void (GLAD_API_PTR *PFN_vkGetPhysicalDeviceFeatures)(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures * pFeatures); +typedef void (GLAD_API_PTR *PFN_vkGetPhysicalDeviceFeatures2)(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures2 * pFeatures); +typedef void (GLAD_API_PTR *PFN_vkGetPhysicalDeviceFormatProperties)(VkPhysicalDevice physicalDevice, VkFormat format, VkFormatProperties * pFormatProperties); +typedef void (GLAD_API_PTR *PFN_vkGetPhysicalDeviceFormatProperties2)(VkPhysicalDevice physicalDevice, VkFormat format, VkFormatProperties2 * pFormatProperties); +typedef VkResult (GLAD_API_PTR *PFN_vkGetPhysicalDeviceImageFormatProperties)(VkPhysicalDevice physicalDevice, VkFormat format, VkImageType type, VkImageTiling tiling, VkImageUsageFlags usage, VkImageCreateFlags flags, VkImageFormatProperties * pImageFormatProperties); +typedef VkResult (GLAD_API_PTR *PFN_vkGetPhysicalDeviceImageFormatProperties2)(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceImageFormatInfo2 * pImageFormatInfo, VkImageFormatProperties2 * pImageFormatProperties); +typedef void (GLAD_API_PTR *PFN_vkGetPhysicalDeviceMemoryProperties)(VkPhysicalDevice physicalDevice, VkPhysicalDeviceMemoryProperties * pMemoryProperties); +typedef void (GLAD_API_PTR *PFN_vkGetPhysicalDeviceMemoryProperties2)(VkPhysicalDevice physicalDevice, VkPhysicalDeviceMemoryProperties2 * pMemoryProperties); +typedef VkResult (GLAD_API_PTR *PFN_vkGetPhysicalDevicePresentRectanglesKHR)(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface, uint32_t * pRectCount, VkRect2D * pRects); +typedef void (GLAD_API_PTR *PFN_vkGetPhysicalDeviceProperties)(VkPhysicalDevice physicalDevice, VkPhysicalDeviceProperties * pProperties); +typedef void (GLAD_API_PTR *PFN_vkGetPhysicalDeviceProperties2)(VkPhysicalDevice physicalDevice, VkPhysicalDeviceProperties2 * pProperties); +typedef void (GLAD_API_PTR *PFN_vkGetPhysicalDeviceQueueFamilyProperties)(VkPhysicalDevice physicalDevice, uint32_t * pQueueFamilyPropertyCount, VkQueueFamilyProperties * pQueueFamilyProperties); +typedef void (GLAD_API_PTR *PFN_vkGetPhysicalDeviceQueueFamilyProperties2)(VkPhysicalDevice physicalDevice, uint32_t * pQueueFamilyPropertyCount, VkQueueFamilyProperties2 * pQueueFamilyProperties); +typedef void (GLAD_API_PTR *PFN_vkGetPhysicalDeviceSparseImageFormatProperties)(VkPhysicalDevice physicalDevice, VkFormat format, VkImageType type, VkSampleCountFlagBits samples, VkImageUsageFlags usage, VkImageTiling tiling, uint32_t * pPropertyCount, VkSparseImageFormatProperties * pProperties); +typedef void (GLAD_API_PTR *PFN_vkGetPhysicalDeviceSparseImageFormatProperties2)(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSparseImageFormatInfo2 * pFormatInfo, uint32_t * pPropertyCount, VkSparseImageFormatProperties2 * pProperties); +typedef VkResult (GLAD_API_PTR *PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR)(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface, VkSurfaceCapabilitiesKHR * pSurfaceCapabilities); +typedef VkResult (GLAD_API_PTR *PFN_vkGetPhysicalDeviceSurfaceFormatsKHR)(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface, uint32_t * pSurfaceFormatCount, VkSurfaceFormatKHR * pSurfaceFormats); +typedef VkResult (GLAD_API_PTR *PFN_vkGetPhysicalDeviceSurfacePresentModesKHR)(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface, uint32_t * pPresentModeCount, VkPresentModeKHR * pPresentModes); +typedef VkResult (GLAD_API_PTR *PFN_vkGetPhysicalDeviceSurfaceSupportKHR)(VkPhysicalDevice physicalDevice, uint32_t queueFamilyIndex, VkSurfaceKHR surface, VkBool32 * pSupported); +typedef VkResult (GLAD_API_PTR *PFN_vkGetPipelineCacheData)(VkDevice device, VkPipelineCache pipelineCache, size_t * pDataSize, void * pData); +typedef VkResult (GLAD_API_PTR *PFN_vkGetQueryPoolResults)(VkDevice device, VkQueryPool queryPool, uint32_t firstQuery, uint32_t queryCount, size_t dataSize, void * pData, VkDeviceSize stride, VkQueryResultFlags flags); +typedef void (GLAD_API_PTR *PFN_vkGetRenderAreaGranularity)(VkDevice device, VkRenderPass renderPass, VkExtent2D * pGranularity); +typedef VkResult (GLAD_API_PTR *PFN_vkGetSwapchainImagesKHR)(VkDevice device, VkSwapchainKHR swapchain, uint32_t * pSwapchainImageCount, VkImage * pSwapchainImages); +typedef VkResult (GLAD_API_PTR *PFN_vkInvalidateMappedMemoryRanges)(VkDevice device, uint32_t memoryRangeCount, const VkMappedMemoryRange * pMemoryRanges); +typedef VkResult (GLAD_API_PTR *PFN_vkMapMemory)(VkDevice device, VkDeviceMemory memory, VkDeviceSize offset, VkDeviceSize size, VkMemoryMapFlags flags, void ** ppData); +typedef VkResult (GLAD_API_PTR *PFN_vkMergePipelineCaches)(VkDevice device, VkPipelineCache dstCache, uint32_t srcCacheCount, const VkPipelineCache * pSrcCaches); +typedef VkResult (GLAD_API_PTR *PFN_vkQueueBindSparse)(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo * pBindInfo, VkFence fence); +typedef VkResult (GLAD_API_PTR *PFN_vkQueuePresentKHR)(VkQueue queue, const VkPresentInfoKHR * pPresentInfo); +typedef VkResult (GLAD_API_PTR *PFN_vkQueueSubmit)(VkQueue queue, uint32_t submitCount, const VkSubmitInfo * pSubmits, VkFence fence); +typedef VkResult (GLAD_API_PTR *PFN_vkQueueWaitIdle)(VkQueue queue); +typedef VkResult (GLAD_API_PTR *PFN_vkResetCommandBuffer)(VkCommandBuffer commandBuffer, VkCommandBufferResetFlags flags); +typedef VkResult (GLAD_API_PTR *PFN_vkResetCommandPool)(VkDevice device, VkCommandPool commandPool, VkCommandPoolResetFlags flags); +typedef VkResult (GLAD_API_PTR *PFN_vkResetDescriptorPool)(VkDevice device, VkDescriptorPool descriptorPool, VkDescriptorPoolResetFlags flags); +typedef VkResult (GLAD_API_PTR *PFN_vkResetEvent)(VkDevice device, VkEvent event); +typedef VkResult (GLAD_API_PTR *PFN_vkResetFences)(VkDevice device, uint32_t fenceCount, const VkFence * pFences); +typedef VkResult (GLAD_API_PTR *PFN_vkSetEvent)(VkDevice device, VkEvent event); +typedef void (GLAD_API_PTR *PFN_vkTrimCommandPool)(VkDevice device, VkCommandPool commandPool, VkCommandPoolTrimFlags flags); +typedef void (GLAD_API_PTR *PFN_vkUnmapMemory)(VkDevice device, VkDeviceMemory memory); +typedef void (GLAD_API_PTR *PFN_vkUpdateDescriptorSetWithTemplate)(VkDevice device, VkDescriptorSet descriptorSet, VkDescriptorUpdateTemplate descriptorUpdateTemplate, const void * pData); +typedef void (GLAD_API_PTR *PFN_vkUpdateDescriptorSets)(VkDevice device, uint32_t descriptorWriteCount, const VkWriteDescriptorSet * pDescriptorWrites, uint32_t descriptorCopyCount, const VkCopyDescriptorSet * pDescriptorCopies); +typedef VkResult (GLAD_API_PTR *PFN_vkWaitForFences)(VkDevice device, uint32_t fenceCount, const VkFence * pFences, VkBool32 waitAll, uint64_t timeout); + +GLAD_API_CALL PFN_vkAcquireNextImage2KHR glad_vkAcquireNextImage2KHR; +#define vkAcquireNextImage2KHR glad_vkAcquireNextImage2KHR +GLAD_API_CALL PFN_vkAcquireNextImageKHR glad_vkAcquireNextImageKHR; +#define vkAcquireNextImageKHR glad_vkAcquireNextImageKHR +GLAD_API_CALL PFN_vkAllocateCommandBuffers glad_vkAllocateCommandBuffers; +#define vkAllocateCommandBuffers glad_vkAllocateCommandBuffers +GLAD_API_CALL PFN_vkAllocateDescriptorSets glad_vkAllocateDescriptorSets; +#define vkAllocateDescriptorSets glad_vkAllocateDescriptorSets +GLAD_API_CALL PFN_vkAllocateMemory glad_vkAllocateMemory; +#define vkAllocateMemory glad_vkAllocateMemory +GLAD_API_CALL PFN_vkBeginCommandBuffer glad_vkBeginCommandBuffer; +#define vkBeginCommandBuffer glad_vkBeginCommandBuffer +GLAD_API_CALL PFN_vkBindBufferMemory glad_vkBindBufferMemory; +#define vkBindBufferMemory glad_vkBindBufferMemory +GLAD_API_CALL PFN_vkBindBufferMemory2 glad_vkBindBufferMemory2; +#define vkBindBufferMemory2 glad_vkBindBufferMemory2 +GLAD_API_CALL PFN_vkBindImageMemory glad_vkBindImageMemory; +#define vkBindImageMemory glad_vkBindImageMemory +GLAD_API_CALL PFN_vkBindImageMemory2 glad_vkBindImageMemory2; +#define vkBindImageMemory2 glad_vkBindImageMemory2 +GLAD_API_CALL PFN_vkCmdBeginQuery glad_vkCmdBeginQuery; +#define vkCmdBeginQuery glad_vkCmdBeginQuery +GLAD_API_CALL PFN_vkCmdBeginRenderPass glad_vkCmdBeginRenderPass; +#define vkCmdBeginRenderPass glad_vkCmdBeginRenderPass +GLAD_API_CALL PFN_vkCmdBindDescriptorSets glad_vkCmdBindDescriptorSets; +#define vkCmdBindDescriptorSets glad_vkCmdBindDescriptorSets +GLAD_API_CALL PFN_vkCmdBindIndexBuffer glad_vkCmdBindIndexBuffer; +#define vkCmdBindIndexBuffer glad_vkCmdBindIndexBuffer +GLAD_API_CALL PFN_vkCmdBindPipeline glad_vkCmdBindPipeline; +#define vkCmdBindPipeline glad_vkCmdBindPipeline +GLAD_API_CALL PFN_vkCmdBindVertexBuffers glad_vkCmdBindVertexBuffers; +#define vkCmdBindVertexBuffers glad_vkCmdBindVertexBuffers +GLAD_API_CALL PFN_vkCmdBlitImage glad_vkCmdBlitImage; +#define vkCmdBlitImage glad_vkCmdBlitImage +GLAD_API_CALL PFN_vkCmdClearAttachments glad_vkCmdClearAttachments; +#define vkCmdClearAttachments glad_vkCmdClearAttachments +GLAD_API_CALL PFN_vkCmdClearColorImage glad_vkCmdClearColorImage; +#define vkCmdClearColorImage glad_vkCmdClearColorImage +GLAD_API_CALL PFN_vkCmdClearDepthStencilImage glad_vkCmdClearDepthStencilImage; +#define vkCmdClearDepthStencilImage glad_vkCmdClearDepthStencilImage +GLAD_API_CALL PFN_vkCmdCopyBuffer glad_vkCmdCopyBuffer; +#define vkCmdCopyBuffer glad_vkCmdCopyBuffer +GLAD_API_CALL PFN_vkCmdCopyBufferToImage glad_vkCmdCopyBufferToImage; +#define vkCmdCopyBufferToImage glad_vkCmdCopyBufferToImage +GLAD_API_CALL PFN_vkCmdCopyImage glad_vkCmdCopyImage; +#define vkCmdCopyImage glad_vkCmdCopyImage +GLAD_API_CALL PFN_vkCmdCopyImageToBuffer glad_vkCmdCopyImageToBuffer; +#define vkCmdCopyImageToBuffer glad_vkCmdCopyImageToBuffer +GLAD_API_CALL PFN_vkCmdCopyQueryPoolResults glad_vkCmdCopyQueryPoolResults; +#define vkCmdCopyQueryPoolResults glad_vkCmdCopyQueryPoolResults +GLAD_API_CALL PFN_vkCmdDispatch glad_vkCmdDispatch; +#define vkCmdDispatch glad_vkCmdDispatch +GLAD_API_CALL PFN_vkCmdDispatchBase glad_vkCmdDispatchBase; +#define vkCmdDispatchBase glad_vkCmdDispatchBase +GLAD_API_CALL PFN_vkCmdDispatchIndirect glad_vkCmdDispatchIndirect; +#define vkCmdDispatchIndirect glad_vkCmdDispatchIndirect +GLAD_API_CALL PFN_vkCmdDraw glad_vkCmdDraw; +#define vkCmdDraw glad_vkCmdDraw +GLAD_API_CALL PFN_vkCmdDrawIndexed glad_vkCmdDrawIndexed; +#define vkCmdDrawIndexed glad_vkCmdDrawIndexed +GLAD_API_CALL PFN_vkCmdDrawIndexedIndirect glad_vkCmdDrawIndexedIndirect; +#define vkCmdDrawIndexedIndirect glad_vkCmdDrawIndexedIndirect +GLAD_API_CALL PFN_vkCmdDrawIndirect glad_vkCmdDrawIndirect; +#define vkCmdDrawIndirect glad_vkCmdDrawIndirect +GLAD_API_CALL PFN_vkCmdEndQuery glad_vkCmdEndQuery; +#define vkCmdEndQuery glad_vkCmdEndQuery +GLAD_API_CALL PFN_vkCmdEndRenderPass glad_vkCmdEndRenderPass; +#define vkCmdEndRenderPass glad_vkCmdEndRenderPass +GLAD_API_CALL PFN_vkCmdExecuteCommands glad_vkCmdExecuteCommands; +#define vkCmdExecuteCommands glad_vkCmdExecuteCommands +GLAD_API_CALL PFN_vkCmdFillBuffer glad_vkCmdFillBuffer; +#define vkCmdFillBuffer glad_vkCmdFillBuffer +GLAD_API_CALL PFN_vkCmdNextSubpass glad_vkCmdNextSubpass; +#define vkCmdNextSubpass glad_vkCmdNextSubpass +GLAD_API_CALL PFN_vkCmdPipelineBarrier glad_vkCmdPipelineBarrier; +#define vkCmdPipelineBarrier glad_vkCmdPipelineBarrier +GLAD_API_CALL PFN_vkCmdPushConstants glad_vkCmdPushConstants; +#define vkCmdPushConstants glad_vkCmdPushConstants +GLAD_API_CALL PFN_vkCmdResetEvent glad_vkCmdResetEvent; +#define vkCmdResetEvent glad_vkCmdResetEvent +GLAD_API_CALL PFN_vkCmdResetQueryPool glad_vkCmdResetQueryPool; +#define vkCmdResetQueryPool glad_vkCmdResetQueryPool +GLAD_API_CALL PFN_vkCmdResolveImage glad_vkCmdResolveImage; +#define vkCmdResolveImage glad_vkCmdResolveImage +GLAD_API_CALL PFN_vkCmdSetBlendConstants glad_vkCmdSetBlendConstants; +#define vkCmdSetBlendConstants glad_vkCmdSetBlendConstants +GLAD_API_CALL PFN_vkCmdSetDepthBias glad_vkCmdSetDepthBias; +#define vkCmdSetDepthBias glad_vkCmdSetDepthBias +GLAD_API_CALL PFN_vkCmdSetDepthBounds glad_vkCmdSetDepthBounds; +#define vkCmdSetDepthBounds glad_vkCmdSetDepthBounds +GLAD_API_CALL PFN_vkCmdSetDeviceMask glad_vkCmdSetDeviceMask; +#define vkCmdSetDeviceMask glad_vkCmdSetDeviceMask +GLAD_API_CALL PFN_vkCmdSetEvent glad_vkCmdSetEvent; +#define vkCmdSetEvent glad_vkCmdSetEvent +GLAD_API_CALL PFN_vkCmdSetLineWidth glad_vkCmdSetLineWidth; +#define vkCmdSetLineWidth glad_vkCmdSetLineWidth +GLAD_API_CALL PFN_vkCmdSetScissor glad_vkCmdSetScissor; +#define vkCmdSetScissor glad_vkCmdSetScissor +GLAD_API_CALL PFN_vkCmdSetStencilCompareMask glad_vkCmdSetStencilCompareMask; +#define vkCmdSetStencilCompareMask glad_vkCmdSetStencilCompareMask +GLAD_API_CALL PFN_vkCmdSetStencilReference glad_vkCmdSetStencilReference; +#define vkCmdSetStencilReference glad_vkCmdSetStencilReference +GLAD_API_CALL PFN_vkCmdSetStencilWriteMask glad_vkCmdSetStencilWriteMask; +#define vkCmdSetStencilWriteMask glad_vkCmdSetStencilWriteMask +GLAD_API_CALL PFN_vkCmdSetViewport glad_vkCmdSetViewport; +#define vkCmdSetViewport glad_vkCmdSetViewport +GLAD_API_CALL PFN_vkCmdUpdateBuffer glad_vkCmdUpdateBuffer; +#define vkCmdUpdateBuffer glad_vkCmdUpdateBuffer +GLAD_API_CALL PFN_vkCmdWaitEvents glad_vkCmdWaitEvents; +#define vkCmdWaitEvents glad_vkCmdWaitEvents +GLAD_API_CALL PFN_vkCmdWriteTimestamp glad_vkCmdWriteTimestamp; +#define vkCmdWriteTimestamp glad_vkCmdWriteTimestamp +GLAD_API_CALL PFN_vkCreateBuffer glad_vkCreateBuffer; +#define vkCreateBuffer glad_vkCreateBuffer +GLAD_API_CALL PFN_vkCreateBufferView glad_vkCreateBufferView; +#define vkCreateBufferView glad_vkCreateBufferView +GLAD_API_CALL PFN_vkCreateCommandPool glad_vkCreateCommandPool; +#define vkCreateCommandPool glad_vkCreateCommandPool +GLAD_API_CALL PFN_vkCreateComputePipelines glad_vkCreateComputePipelines; +#define vkCreateComputePipelines glad_vkCreateComputePipelines +GLAD_API_CALL PFN_vkCreateDebugReportCallbackEXT glad_vkCreateDebugReportCallbackEXT; +#define vkCreateDebugReportCallbackEXT glad_vkCreateDebugReportCallbackEXT +GLAD_API_CALL PFN_vkCreateDescriptorPool glad_vkCreateDescriptorPool; +#define vkCreateDescriptorPool glad_vkCreateDescriptorPool +GLAD_API_CALL PFN_vkCreateDescriptorSetLayout glad_vkCreateDescriptorSetLayout; +#define vkCreateDescriptorSetLayout glad_vkCreateDescriptorSetLayout +GLAD_API_CALL PFN_vkCreateDescriptorUpdateTemplate glad_vkCreateDescriptorUpdateTemplate; +#define vkCreateDescriptorUpdateTemplate glad_vkCreateDescriptorUpdateTemplate +GLAD_API_CALL PFN_vkCreateDevice glad_vkCreateDevice; +#define vkCreateDevice glad_vkCreateDevice +GLAD_API_CALL PFN_vkCreateEvent glad_vkCreateEvent; +#define vkCreateEvent glad_vkCreateEvent +GLAD_API_CALL PFN_vkCreateFence glad_vkCreateFence; +#define vkCreateFence glad_vkCreateFence +GLAD_API_CALL PFN_vkCreateFramebuffer glad_vkCreateFramebuffer; +#define vkCreateFramebuffer glad_vkCreateFramebuffer +GLAD_API_CALL PFN_vkCreateGraphicsPipelines glad_vkCreateGraphicsPipelines; +#define vkCreateGraphicsPipelines glad_vkCreateGraphicsPipelines +GLAD_API_CALL PFN_vkCreateImage glad_vkCreateImage; +#define vkCreateImage glad_vkCreateImage +GLAD_API_CALL PFN_vkCreateImageView glad_vkCreateImageView; +#define vkCreateImageView glad_vkCreateImageView +GLAD_API_CALL PFN_vkCreateInstance glad_vkCreateInstance; +#define vkCreateInstance glad_vkCreateInstance +GLAD_API_CALL PFN_vkCreatePipelineCache glad_vkCreatePipelineCache; +#define vkCreatePipelineCache glad_vkCreatePipelineCache +GLAD_API_CALL PFN_vkCreatePipelineLayout glad_vkCreatePipelineLayout; +#define vkCreatePipelineLayout glad_vkCreatePipelineLayout +GLAD_API_CALL PFN_vkCreateQueryPool glad_vkCreateQueryPool; +#define vkCreateQueryPool glad_vkCreateQueryPool +GLAD_API_CALL PFN_vkCreateRenderPass glad_vkCreateRenderPass; +#define vkCreateRenderPass glad_vkCreateRenderPass +GLAD_API_CALL PFN_vkCreateSampler glad_vkCreateSampler; +#define vkCreateSampler glad_vkCreateSampler +GLAD_API_CALL PFN_vkCreateSamplerYcbcrConversion glad_vkCreateSamplerYcbcrConversion; +#define vkCreateSamplerYcbcrConversion glad_vkCreateSamplerYcbcrConversion +GLAD_API_CALL PFN_vkCreateSemaphore glad_vkCreateSemaphore; +#define vkCreateSemaphore glad_vkCreateSemaphore +GLAD_API_CALL PFN_vkCreateShaderModule glad_vkCreateShaderModule; +#define vkCreateShaderModule glad_vkCreateShaderModule +GLAD_API_CALL PFN_vkCreateSwapchainKHR glad_vkCreateSwapchainKHR; +#define vkCreateSwapchainKHR glad_vkCreateSwapchainKHR +GLAD_API_CALL PFN_vkDebugReportMessageEXT glad_vkDebugReportMessageEXT; +#define vkDebugReportMessageEXT glad_vkDebugReportMessageEXT +GLAD_API_CALL PFN_vkDestroyBuffer glad_vkDestroyBuffer; +#define vkDestroyBuffer glad_vkDestroyBuffer +GLAD_API_CALL PFN_vkDestroyBufferView glad_vkDestroyBufferView; +#define vkDestroyBufferView glad_vkDestroyBufferView +GLAD_API_CALL PFN_vkDestroyCommandPool glad_vkDestroyCommandPool; +#define vkDestroyCommandPool glad_vkDestroyCommandPool +GLAD_API_CALL PFN_vkDestroyDebugReportCallbackEXT glad_vkDestroyDebugReportCallbackEXT; +#define vkDestroyDebugReportCallbackEXT glad_vkDestroyDebugReportCallbackEXT +GLAD_API_CALL PFN_vkDestroyDescriptorPool glad_vkDestroyDescriptorPool; +#define vkDestroyDescriptorPool glad_vkDestroyDescriptorPool +GLAD_API_CALL PFN_vkDestroyDescriptorSetLayout glad_vkDestroyDescriptorSetLayout; +#define vkDestroyDescriptorSetLayout glad_vkDestroyDescriptorSetLayout +GLAD_API_CALL PFN_vkDestroyDescriptorUpdateTemplate glad_vkDestroyDescriptorUpdateTemplate; +#define vkDestroyDescriptorUpdateTemplate glad_vkDestroyDescriptorUpdateTemplate +GLAD_API_CALL PFN_vkDestroyDevice glad_vkDestroyDevice; +#define vkDestroyDevice glad_vkDestroyDevice +GLAD_API_CALL PFN_vkDestroyEvent glad_vkDestroyEvent; +#define vkDestroyEvent glad_vkDestroyEvent +GLAD_API_CALL PFN_vkDestroyFence glad_vkDestroyFence; +#define vkDestroyFence glad_vkDestroyFence +GLAD_API_CALL PFN_vkDestroyFramebuffer glad_vkDestroyFramebuffer; +#define vkDestroyFramebuffer glad_vkDestroyFramebuffer +GLAD_API_CALL PFN_vkDestroyImage glad_vkDestroyImage; +#define vkDestroyImage glad_vkDestroyImage +GLAD_API_CALL PFN_vkDestroyImageView glad_vkDestroyImageView; +#define vkDestroyImageView glad_vkDestroyImageView +GLAD_API_CALL PFN_vkDestroyInstance glad_vkDestroyInstance; +#define vkDestroyInstance glad_vkDestroyInstance +GLAD_API_CALL PFN_vkDestroyPipeline glad_vkDestroyPipeline; +#define vkDestroyPipeline glad_vkDestroyPipeline +GLAD_API_CALL PFN_vkDestroyPipelineCache glad_vkDestroyPipelineCache; +#define vkDestroyPipelineCache glad_vkDestroyPipelineCache +GLAD_API_CALL PFN_vkDestroyPipelineLayout glad_vkDestroyPipelineLayout; +#define vkDestroyPipelineLayout glad_vkDestroyPipelineLayout +GLAD_API_CALL PFN_vkDestroyQueryPool glad_vkDestroyQueryPool; +#define vkDestroyQueryPool glad_vkDestroyQueryPool +GLAD_API_CALL PFN_vkDestroyRenderPass glad_vkDestroyRenderPass; +#define vkDestroyRenderPass glad_vkDestroyRenderPass +GLAD_API_CALL PFN_vkDestroySampler glad_vkDestroySampler; +#define vkDestroySampler glad_vkDestroySampler +GLAD_API_CALL PFN_vkDestroySamplerYcbcrConversion glad_vkDestroySamplerYcbcrConversion; +#define vkDestroySamplerYcbcrConversion glad_vkDestroySamplerYcbcrConversion +GLAD_API_CALL PFN_vkDestroySemaphore glad_vkDestroySemaphore; +#define vkDestroySemaphore glad_vkDestroySemaphore +GLAD_API_CALL PFN_vkDestroyShaderModule glad_vkDestroyShaderModule; +#define vkDestroyShaderModule glad_vkDestroyShaderModule +GLAD_API_CALL PFN_vkDestroySurfaceKHR glad_vkDestroySurfaceKHR; +#define vkDestroySurfaceKHR glad_vkDestroySurfaceKHR +GLAD_API_CALL PFN_vkDestroySwapchainKHR glad_vkDestroySwapchainKHR; +#define vkDestroySwapchainKHR glad_vkDestroySwapchainKHR +GLAD_API_CALL PFN_vkDeviceWaitIdle glad_vkDeviceWaitIdle; +#define vkDeviceWaitIdle glad_vkDeviceWaitIdle +GLAD_API_CALL PFN_vkEndCommandBuffer glad_vkEndCommandBuffer; +#define vkEndCommandBuffer glad_vkEndCommandBuffer +GLAD_API_CALL PFN_vkEnumerateDeviceExtensionProperties glad_vkEnumerateDeviceExtensionProperties; +#define vkEnumerateDeviceExtensionProperties glad_vkEnumerateDeviceExtensionProperties +GLAD_API_CALL PFN_vkEnumerateDeviceLayerProperties glad_vkEnumerateDeviceLayerProperties; +#define vkEnumerateDeviceLayerProperties glad_vkEnumerateDeviceLayerProperties +GLAD_API_CALL PFN_vkEnumerateInstanceExtensionProperties glad_vkEnumerateInstanceExtensionProperties; +#define vkEnumerateInstanceExtensionProperties glad_vkEnumerateInstanceExtensionProperties +GLAD_API_CALL PFN_vkEnumerateInstanceLayerProperties glad_vkEnumerateInstanceLayerProperties; +#define vkEnumerateInstanceLayerProperties glad_vkEnumerateInstanceLayerProperties +GLAD_API_CALL PFN_vkEnumerateInstanceVersion glad_vkEnumerateInstanceVersion; +#define vkEnumerateInstanceVersion glad_vkEnumerateInstanceVersion +GLAD_API_CALL PFN_vkEnumeratePhysicalDeviceGroups glad_vkEnumeratePhysicalDeviceGroups; +#define vkEnumeratePhysicalDeviceGroups glad_vkEnumeratePhysicalDeviceGroups +GLAD_API_CALL PFN_vkEnumeratePhysicalDevices glad_vkEnumeratePhysicalDevices; +#define vkEnumeratePhysicalDevices glad_vkEnumeratePhysicalDevices +GLAD_API_CALL PFN_vkFlushMappedMemoryRanges glad_vkFlushMappedMemoryRanges; +#define vkFlushMappedMemoryRanges glad_vkFlushMappedMemoryRanges +GLAD_API_CALL PFN_vkFreeCommandBuffers glad_vkFreeCommandBuffers; +#define vkFreeCommandBuffers glad_vkFreeCommandBuffers +GLAD_API_CALL PFN_vkFreeDescriptorSets glad_vkFreeDescriptorSets; +#define vkFreeDescriptorSets glad_vkFreeDescriptorSets +GLAD_API_CALL PFN_vkFreeMemory glad_vkFreeMemory; +#define vkFreeMemory glad_vkFreeMemory +GLAD_API_CALL PFN_vkGetBufferMemoryRequirements glad_vkGetBufferMemoryRequirements; +#define vkGetBufferMemoryRequirements glad_vkGetBufferMemoryRequirements +GLAD_API_CALL PFN_vkGetBufferMemoryRequirements2 glad_vkGetBufferMemoryRequirements2; +#define vkGetBufferMemoryRequirements2 glad_vkGetBufferMemoryRequirements2 +GLAD_API_CALL PFN_vkGetDescriptorSetLayoutSupport glad_vkGetDescriptorSetLayoutSupport; +#define vkGetDescriptorSetLayoutSupport glad_vkGetDescriptorSetLayoutSupport +GLAD_API_CALL PFN_vkGetDeviceGroupPeerMemoryFeatures glad_vkGetDeviceGroupPeerMemoryFeatures; +#define vkGetDeviceGroupPeerMemoryFeatures glad_vkGetDeviceGroupPeerMemoryFeatures +GLAD_API_CALL PFN_vkGetDeviceGroupPresentCapabilitiesKHR glad_vkGetDeviceGroupPresentCapabilitiesKHR; +#define vkGetDeviceGroupPresentCapabilitiesKHR glad_vkGetDeviceGroupPresentCapabilitiesKHR +GLAD_API_CALL PFN_vkGetDeviceGroupSurfacePresentModesKHR glad_vkGetDeviceGroupSurfacePresentModesKHR; +#define vkGetDeviceGroupSurfacePresentModesKHR glad_vkGetDeviceGroupSurfacePresentModesKHR +GLAD_API_CALL PFN_vkGetDeviceMemoryCommitment glad_vkGetDeviceMemoryCommitment; +#define vkGetDeviceMemoryCommitment glad_vkGetDeviceMemoryCommitment +GLAD_API_CALL PFN_vkGetDeviceProcAddr glad_vkGetDeviceProcAddr; +#define vkGetDeviceProcAddr glad_vkGetDeviceProcAddr +GLAD_API_CALL PFN_vkGetDeviceQueue glad_vkGetDeviceQueue; +#define vkGetDeviceQueue glad_vkGetDeviceQueue +GLAD_API_CALL PFN_vkGetDeviceQueue2 glad_vkGetDeviceQueue2; +#define vkGetDeviceQueue2 glad_vkGetDeviceQueue2 +GLAD_API_CALL PFN_vkGetEventStatus glad_vkGetEventStatus; +#define vkGetEventStatus glad_vkGetEventStatus +GLAD_API_CALL PFN_vkGetFenceStatus glad_vkGetFenceStatus; +#define vkGetFenceStatus glad_vkGetFenceStatus +GLAD_API_CALL PFN_vkGetImageMemoryRequirements glad_vkGetImageMemoryRequirements; +#define vkGetImageMemoryRequirements glad_vkGetImageMemoryRequirements +GLAD_API_CALL PFN_vkGetImageMemoryRequirements2 glad_vkGetImageMemoryRequirements2; +#define vkGetImageMemoryRequirements2 glad_vkGetImageMemoryRequirements2 +GLAD_API_CALL PFN_vkGetImageSparseMemoryRequirements glad_vkGetImageSparseMemoryRequirements; +#define vkGetImageSparseMemoryRequirements glad_vkGetImageSparseMemoryRequirements +GLAD_API_CALL PFN_vkGetImageSparseMemoryRequirements2 glad_vkGetImageSparseMemoryRequirements2; +#define vkGetImageSparseMemoryRequirements2 glad_vkGetImageSparseMemoryRequirements2 +GLAD_API_CALL PFN_vkGetImageSubresourceLayout glad_vkGetImageSubresourceLayout; +#define vkGetImageSubresourceLayout glad_vkGetImageSubresourceLayout +GLAD_API_CALL PFN_vkGetInstanceProcAddr glad_vkGetInstanceProcAddr; +#define vkGetInstanceProcAddr glad_vkGetInstanceProcAddr +GLAD_API_CALL PFN_vkGetPhysicalDeviceExternalBufferProperties glad_vkGetPhysicalDeviceExternalBufferProperties; +#define vkGetPhysicalDeviceExternalBufferProperties glad_vkGetPhysicalDeviceExternalBufferProperties +GLAD_API_CALL PFN_vkGetPhysicalDeviceExternalFenceProperties glad_vkGetPhysicalDeviceExternalFenceProperties; +#define vkGetPhysicalDeviceExternalFenceProperties glad_vkGetPhysicalDeviceExternalFenceProperties +GLAD_API_CALL PFN_vkGetPhysicalDeviceExternalSemaphoreProperties glad_vkGetPhysicalDeviceExternalSemaphoreProperties; +#define vkGetPhysicalDeviceExternalSemaphoreProperties glad_vkGetPhysicalDeviceExternalSemaphoreProperties +GLAD_API_CALL PFN_vkGetPhysicalDeviceFeatures glad_vkGetPhysicalDeviceFeatures; +#define vkGetPhysicalDeviceFeatures glad_vkGetPhysicalDeviceFeatures +GLAD_API_CALL PFN_vkGetPhysicalDeviceFeatures2 glad_vkGetPhysicalDeviceFeatures2; +#define vkGetPhysicalDeviceFeatures2 glad_vkGetPhysicalDeviceFeatures2 +GLAD_API_CALL PFN_vkGetPhysicalDeviceFormatProperties glad_vkGetPhysicalDeviceFormatProperties; +#define vkGetPhysicalDeviceFormatProperties glad_vkGetPhysicalDeviceFormatProperties +GLAD_API_CALL PFN_vkGetPhysicalDeviceFormatProperties2 glad_vkGetPhysicalDeviceFormatProperties2; +#define vkGetPhysicalDeviceFormatProperties2 glad_vkGetPhysicalDeviceFormatProperties2 +GLAD_API_CALL PFN_vkGetPhysicalDeviceImageFormatProperties glad_vkGetPhysicalDeviceImageFormatProperties; +#define vkGetPhysicalDeviceImageFormatProperties glad_vkGetPhysicalDeviceImageFormatProperties +GLAD_API_CALL PFN_vkGetPhysicalDeviceImageFormatProperties2 glad_vkGetPhysicalDeviceImageFormatProperties2; +#define vkGetPhysicalDeviceImageFormatProperties2 glad_vkGetPhysicalDeviceImageFormatProperties2 +GLAD_API_CALL PFN_vkGetPhysicalDeviceMemoryProperties glad_vkGetPhysicalDeviceMemoryProperties; +#define vkGetPhysicalDeviceMemoryProperties glad_vkGetPhysicalDeviceMemoryProperties +GLAD_API_CALL PFN_vkGetPhysicalDeviceMemoryProperties2 glad_vkGetPhysicalDeviceMemoryProperties2; +#define vkGetPhysicalDeviceMemoryProperties2 glad_vkGetPhysicalDeviceMemoryProperties2 +GLAD_API_CALL PFN_vkGetPhysicalDevicePresentRectanglesKHR glad_vkGetPhysicalDevicePresentRectanglesKHR; +#define vkGetPhysicalDevicePresentRectanglesKHR glad_vkGetPhysicalDevicePresentRectanglesKHR +GLAD_API_CALL PFN_vkGetPhysicalDeviceProperties glad_vkGetPhysicalDeviceProperties; +#define vkGetPhysicalDeviceProperties glad_vkGetPhysicalDeviceProperties +GLAD_API_CALL PFN_vkGetPhysicalDeviceProperties2 glad_vkGetPhysicalDeviceProperties2; +#define vkGetPhysicalDeviceProperties2 glad_vkGetPhysicalDeviceProperties2 +GLAD_API_CALL PFN_vkGetPhysicalDeviceQueueFamilyProperties glad_vkGetPhysicalDeviceQueueFamilyProperties; +#define vkGetPhysicalDeviceQueueFamilyProperties glad_vkGetPhysicalDeviceQueueFamilyProperties +GLAD_API_CALL PFN_vkGetPhysicalDeviceQueueFamilyProperties2 glad_vkGetPhysicalDeviceQueueFamilyProperties2; +#define vkGetPhysicalDeviceQueueFamilyProperties2 glad_vkGetPhysicalDeviceQueueFamilyProperties2 +GLAD_API_CALL PFN_vkGetPhysicalDeviceSparseImageFormatProperties glad_vkGetPhysicalDeviceSparseImageFormatProperties; +#define vkGetPhysicalDeviceSparseImageFormatProperties glad_vkGetPhysicalDeviceSparseImageFormatProperties +GLAD_API_CALL PFN_vkGetPhysicalDeviceSparseImageFormatProperties2 glad_vkGetPhysicalDeviceSparseImageFormatProperties2; +#define vkGetPhysicalDeviceSparseImageFormatProperties2 glad_vkGetPhysicalDeviceSparseImageFormatProperties2 +GLAD_API_CALL PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR glad_vkGetPhysicalDeviceSurfaceCapabilitiesKHR; +#define vkGetPhysicalDeviceSurfaceCapabilitiesKHR glad_vkGetPhysicalDeviceSurfaceCapabilitiesKHR +GLAD_API_CALL PFN_vkGetPhysicalDeviceSurfaceFormatsKHR glad_vkGetPhysicalDeviceSurfaceFormatsKHR; +#define vkGetPhysicalDeviceSurfaceFormatsKHR glad_vkGetPhysicalDeviceSurfaceFormatsKHR +GLAD_API_CALL PFN_vkGetPhysicalDeviceSurfacePresentModesKHR glad_vkGetPhysicalDeviceSurfacePresentModesKHR; +#define vkGetPhysicalDeviceSurfacePresentModesKHR glad_vkGetPhysicalDeviceSurfacePresentModesKHR +GLAD_API_CALL PFN_vkGetPhysicalDeviceSurfaceSupportKHR glad_vkGetPhysicalDeviceSurfaceSupportKHR; +#define vkGetPhysicalDeviceSurfaceSupportKHR glad_vkGetPhysicalDeviceSurfaceSupportKHR +GLAD_API_CALL PFN_vkGetPipelineCacheData glad_vkGetPipelineCacheData; +#define vkGetPipelineCacheData glad_vkGetPipelineCacheData +GLAD_API_CALL PFN_vkGetQueryPoolResults glad_vkGetQueryPoolResults; +#define vkGetQueryPoolResults glad_vkGetQueryPoolResults +GLAD_API_CALL PFN_vkGetRenderAreaGranularity glad_vkGetRenderAreaGranularity; +#define vkGetRenderAreaGranularity glad_vkGetRenderAreaGranularity +GLAD_API_CALL PFN_vkGetSwapchainImagesKHR glad_vkGetSwapchainImagesKHR; +#define vkGetSwapchainImagesKHR glad_vkGetSwapchainImagesKHR +GLAD_API_CALL PFN_vkInvalidateMappedMemoryRanges glad_vkInvalidateMappedMemoryRanges; +#define vkInvalidateMappedMemoryRanges glad_vkInvalidateMappedMemoryRanges +GLAD_API_CALL PFN_vkMapMemory glad_vkMapMemory; +#define vkMapMemory glad_vkMapMemory +GLAD_API_CALL PFN_vkMergePipelineCaches glad_vkMergePipelineCaches; +#define vkMergePipelineCaches glad_vkMergePipelineCaches +GLAD_API_CALL PFN_vkQueueBindSparse glad_vkQueueBindSparse; +#define vkQueueBindSparse glad_vkQueueBindSparse +GLAD_API_CALL PFN_vkQueuePresentKHR glad_vkQueuePresentKHR; +#define vkQueuePresentKHR glad_vkQueuePresentKHR +GLAD_API_CALL PFN_vkQueueSubmit glad_vkQueueSubmit; +#define vkQueueSubmit glad_vkQueueSubmit +GLAD_API_CALL PFN_vkQueueWaitIdle glad_vkQueueWaitIdle; +#define vkQueueWaitIdle glad_vkQueueWaitIdle +GLAD_API_CALL PFN_vkResetCommandBuffer glad_vkResetCommandBuffer; +#define vkResetCommandBuffer glad_vkResetCommandBuffer +GLAD_API_CALL PFN_vkResetCommandPool glad_vkResetCommandPool; +#define vkResetCommandPool glad_vkResetCommandPool +GLAD_API_CALL PFN_vkResetDescriptorPool glad_vkResetDescriptorPool; +#define vkResetDescriptorPool glad_vkResetDescriptorPool +GLAD_API_CALL PFN_vkResetEvent glad_vkResetEvent; +#define vkResetEvent glad_vkResetEvent +GLAD_API_CALL PFN_vkResetFences glad_vkResetFences; +#define vkResetFences glad_vkResetFences +GLAD_API_CALL PFN_vkSetEvent glad_vkSetEvent; +#define vkSetEvent glad_vkSetEvent +GLAD_API_CALL PFN_vkTrimCommandPool glad_vkTrimCommandPool; +#define vkTrimCommandPool glad_vkTrimCommandPool +GLAD_API_CALL PFN_vkUnmapMemory glad_vkUnmapMemory; +#define vkUnmapMemory glad_vkUnmapMemory +GLAD_API_CALL PFN_vkUpdateDescriptorSetWithTemplate glad_vkUpdateDescriptorSetWithTemplate; +#define vkUpdateDescriptorSetWithTemplate glad_vkUpdateDescriptorSetWithTemplate +GLAD_API_CALL PFN_vkUpdateDescriptorSets glad_vkUpdateDescriptorSets; +#define vkUpdateDescriptorSets glad_vkUpdateDescriptorSets +GLAD_API_CALL PFN_vkWaitForFences glad_vkWaitForFences; +#define vkWaitForFences glad_vkWaitForFences + + +GLAD_API_CALL int gladLoadVulkanUserPtr( VkPhysicalDevice physical_device, GLADuserptrloadfunc load, void *userptr); +GLAD_API_CALL int gladLoadVulkan( VkPhysicalDevice physical_device, GLADloadfunc load); + + + + + + +#ifdef __cplusplus +} +#endif +#endif diff --git a/src/external/glfw/deps/glad_gl.c b/src/external/glfw/deps/glad_gl.c new file mode 100644 index 00000000..2d4c87fe --- /dev/null +++ b/src/external/glfw/deps/glad_gl.c @@ -0,0 +1,1791 @@ +#include +#include +#include +#include + +#ifndef GLAD_IMPL_UTIL_C_ +#define GLAD_IMPL_UTIL_C_ + +#ifdef _MSC_VER +#define GLAD_IMPL_UTIL_SSCANF sscanf_s +#else +#define GLAD_IMPL_UTIL_SSCANF sscanf +#endif + +#endif /* GLAD_IMPL_UTIL_C_ */ + + +int GLAD_GL_VERSION_1_0 = 0; +int GLAD_GL_VERSION_1_1 = 0; +int GLAD_GL_VERSION_1_2 = 0; +int GLAD_GL_VERSION_1_3 = 0; +int GLAD_GL_VERSION_1_4 = 0; +int GLAD_GL_VERSION_1_5 = 0; +int GLAD_GL_VERSION_2_0 = 0; +int GLAD_GL_VERSION_2_1 = 0; +int GLAD_GL_VERSION_3_0 = 0; +int GLAD_GL_VERSION_3_1 = 0; +int GLAD_GL_VERSION_3_2 = 0; +int GLAD_GL_VERSION_3_3 = 0; +int GLAD_GL_ARB_multisample = 0; +int GLAD_GL_ARB_robustness = 0; +int GLAD_GL_KHR_debug = 0; + + + +PFNGLACCUMPROC glad_glAccum = NULL; +PFNGLACTIVETEXTUREPROC glad_glActiveTexture = NULL; +PFNGLALPHAFUNCPROC glad_glAlphaFunc = NULL; +PFNGLARETEXTURESRESIDENTPROC glad_glAreTexturesResident = NULL; +PFNGLARRAYELEMENTPROC glad_glArrayElement = NULL; +PFNGLATTACHSHADERPROC glad_glAttachShader = NULL; +PFNGLBEGINPROC glad_glBegin = NULL; +PFNGLBEGINCONDITIONALRENDERPROC glad_glBeginConditionalRender = NULL; +PFNGLBEGINQUERYPROC glad_glBeginQuery = NULL; +PFNGLBEGINTRANSFORMFEEDBACKPROC glad_glBeginTransformFeedback = NULL; +PFNGLBINDATTRIBLOCATIONPROC glad_glBindAttribLocation = NULL; +PFNGLBINDBUFFERPROC glad_glBindBuffer = NULL; +PFNGLBINDBUFFERBASEPROC glad_glBindBufferBase = NULL; +PFNGLBINDBUFFERRANGEPROC glad_glBindBufferRange = NULL; +PFNGLBINDFRAGDATALOCATIONPROC glad_glBindFragDataLocation = NULL; +PFNGLBINDFRAGDATALOCATIONINDEXEDPROC glad_glBindFragDataLocationIndexed = NULL; +PFNGLBINDFRAMEBUFFERPROC glad_glBindFramebuffer = NULL; +PFNGLBINDRENDERBUFFERPROC glad_glBindRenderbuffer = NULL; +PFNGLBINDSAMPLERPROC glad_glBindSampler = NULL; +PFNGLBINDTEXTUREPROC glad_glBindTexture = NULL; +PFNGLBINDVERTEXARRAYPROC glad_glBindVertexArray = NULL; +PFNGLBITMAPPROC glad_glBitmap = NULL; +PFNGLBLENDCOLORPROC glad_glBlendColor = NULL; +PFNGLBLENDEQUATIONPROC glad_glBlendEquation = NULL; +PFNGLBLENDEQUATIONSEPARATEPROC glad_glBlendEquationSeparate = NULL; +PFNGLBLENDFUNCPROC glad_glBlendFunc = NULL; +PFNGLBLENDFUNCSEPARATEPROC glad_glBlendFuncSeparate = NULL; +PFNGLBLITFRAMEBUFFERPROC glad_glBlitFramebuffer = NULL; +PFNGLBUFFERDATAPROC glad_glBufferData = NULL; +PFNGLBUFFERSUBDATAPROC glad_glBufferSubData = NULL; +PFNGLCALLLISTPROC glad_glCallList = NULL; +PFNGLCALLLISTSPROC glad_glCallLists = NULL; +PFNGLCHECKFRAMEBUFFERSTATUSPROC glad_glCheckFramebufferStatus = NULL; +PFNGLCLAMPCOLORPROC glad_glClampColor = NULL; +PFNGLCLEARPROC glad_glClear = NULL; +PFNGLCLEARACCUMPROC glad_glClearAccum = NULL; +PFNGLCLEARBUFFERFIPROC glad_glClearBufferfi = NULL; +PFNGLCLEARBUFFERFVPROC glad_glClearBufferfv = NULL; +PFNGLCLEARBUFFERIVPROC glad_glClearBufferiv = NULL; +PFNGLCLEARBUFFERUIVPROC glad_glClearBufferuiv = NULL; +PFNGLCLEARCOLORPROC glad_glClearColor = NULL; +PFNGLCLEARDEPTHPROC glad_glClearDepth = NULL; +PFNGLCLEARINDEXPROC glad_glClearIndex = NULL; +PFNGLCLEARSTENCILPROC glad_glClearStencil = NULL; +PFNGLCLIENTACTIVETEXTUREPROC glad_glClientActiveTexture = NULL; +PFNGLCLIENTWAITSYNCPROC glad_glClientWaitSync = NULL; +PFNGLCLIPPLANEPROC glad_glClipPlane = NULL; +PFNGLCOLOR3BPROC glad_glColor3b = NULL; +PFNGLCOLOR3BVPROC glad_glColor3bv = NULL; +PFNGLCOLOR3DPROC glad_glColor3d = NULL; +PFNGLCOLOR3DVPROC glad_glColor3dv = NULL; +PFNGLCOLOR3FPROC glad_glColor3f = NULL; +PFNGLCOLOR3FVPROC glad_glColor3fv = NULL; +PFNGLCOLOR3IPROC glad_glColor3i = NULL; +PFNGLCOLOR3IVPROC glad_glColor3iv = NULL; +PFNGLCOLOR3SPROC glad_glColor3s = NULL; +PFNGLCOLOR3SVPROC glad_glColor3sv = NULL; +PFNGLCOLOR3UBPROC glad_glColor3ub = NULL; +PFNGLCOLOR3UBVPROC glad_glColor3ubv = NULL; +PFNGLCOLOR3UIPROC glad_glColor3ui = NULL; +PFNGLCOLOR3UIVPROC glad_glColor3uiv = NULL; +PFNGLCOLOR3USPROC glad_glColor3us = NULL; +PFNGLCOLOR3USVPROC glad_glColor3usv = NULL; +PFNGLCOLOR4BPROC glad_glColor4b = NULL; +PFNGLCOLOR4BVPROC glad_glColor4bv = NULL; +PFNGLCOLOR4DPROC glad_glColor4d = NULL; +PFNGLCOLOR4DVPROC glad_glColor4dv = NULL; +PFNGLCOLOR4FPROC glad_glColor4f = NULL; +PFNGLCOLOR4FVPROC glad_glColor4fv = NULL; +PFNGLCOLOR4IPROC glad_glColor4i = NULL; +PFNGLCOLOR4IVPROC glad_glColor4iv = NULL; +PFNGLCOLOR4SPROC glad_glColor4s = NULL; +PFNGLCOLOR4SVPROC glad_glColor4sv = NULL; +PFNGLCOLOR4UBPROC glad_glColor4ub = NULL; +PFNGLCOLOR4UBVPROC glad_glColor4ubv = NULL; +PFNGLCOLOR4UIPROC glad_glColor4ui = NULL; +PFNGLCOLOR4UIVPROC glad_glColor4uiv = NULL; +PFNGLCOLOR4USPROC glad_glColor4us = NULL; +PFNGLCOLOR4USVPROC glad_glColor4usv = NULL; +PFNGLCOLORMASKPROC glad_glColorMask = NULL; +PFNGLCOLORMASKIPROC glad_glColorMaski = NULL; +PFNGLCOLORMATERIALPROC glad_glColorMaterial = NULL; +PFNGLCOLORP3UIPROC glad_glColorP3ui = NULL; +PFNGLCOLORP3UIVPROC glad_glColorP3uiv = NULL; +PFNGLCOLORP4UIPROC glad_glColorP4ui = NULL; +PFNGLCOLORP4UIVPROC glad_glColorP4uiv = NULL; +PFNGLCOLORPOINTERPROC glad_glColorPointer = NULL; +PFNGLCOMPILESHADERPROC glad_glCompileShader = NULL; +PFNGLCOMPRESSEDTEXIMAGE1DPROC glad_glCompressedTexImage1D = NULL; +PFNGLCOMPRESSEDTEXIMAGE2DPROC glad_glCompressedTexImage2D = NULL; +PFNGLCOMPRESSEDTEXIMAGE3DPROC glad_glCompressedTexImage3D = NULL; +PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC glad_glCompressedTexSubImage1D = NULL; +PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC glad_glCompressedTexSubImage2D = NULL; +PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC glad_glCompressedTexSubImage3D = NULL; +PFNGLCOPYBUFFERSUBDATAPROC glad_glCopyBufferSubData = NULL; +PFNGLCOPYPIXELSPROC glad_glCopyPixels = NULL; +PFNGLCOPYTEXIMAGE1DPROC glad_glCopyTexImage1D = NULL; +PFNGLCOPYTEXIMAGE2DPROC glad_glCopyTexImage2D = NULL; +PFNGLCOPYTEXSUBIMAGE1DPROC glad_glCopyTexSubImage1D = NULL; +PFNGLCOPYTEXSUBIMAGE2DPROC glad_glCopyTexSubImage2D = NULL; +PFNGLCOPYTEXSUBIMAGE3DPROC glad_glCopyTexSubImage3D = NULL; +PFNGLCREATEPROGRAMPROC glad_glCreateProgram = NULL; +PFNGLCREATESHADERPROC glad_glCreateShader = NULL; +PFNGLCULLFACEPROC glad_glCullFace = NULL; +PFNGLDEBUGMESSAGECALLBACKPROC glad_glDebugMessageCallback = NULL; +PFNGLDEBUGMESSAGECONTROLPROC glad_glDebugMessageControl = NULL; +PFNGLDEBUGMESSAGEINSERTPROC glad_glDebugMessageInsert = NULL; +PFNGLDELETEBUFFERSPROC glad_glDeleteBuffers = NULL; +PFNGLDELETEFRAMEBUFFERSPROC glad_glDeleteFramebuffers = NULL; +PFNGLDELETELISTSPROC glad_glDeleteLists = NULL; +PFNGLDELETEPROGRAMPROC glad_glDeleteProgram = NULL; +PFNGLDELETEQUERIESPROC glad_glDeleteQueries = NULL; +PFNGLDELETERENDERBUFFERSPROC glad_glDeleteRenderbuffers = NULL; +PFNGLDELETESAMPLERSPROC glad_glDeleteSamplers = NULL; +PFNGLDELETESHADERPROC glad_glDeleteShader = NULL; +PFNGLDELETESYNCPROC glad_glDeleteSync = NULL; +PFNGLDELETETEXTURESPROC glad_glDeleteTextures = NULL; +PFNGLDELETEVERTEXARRAYSPROC glad_glDeleteVertexArrays = NULL; +PFNGLDEPTHFUNCPROC glad_glDepthFunc = NULL; +PFNGLDEPTHMASKPROC glad_glDepthMask = NULL; +PFNGLDEPTHRANGEPROC glad_glDepthRange = NULL; +PFNGLDETACHSHADERPROC glad_glDetachShader = NULL; +PFNGLDISABLEPROC glad_glDisable = NULL; +PFNGLDISABLECLIENTSTATEPROC glad_glDisableClientState = NULL; +PFNGLDISABLEVERTEXATTRIBARRAYPROC glad_glDisableVertexAttribArray = NULL; +PFNGLDISABLEIPROC glad_glDisablei = NULL; +PFNGLDRAWARRAYSPROC glad_glDrawArrays = NULL; +PFNGLDRAWARRAYSINSTANCEDPROC glad_glDrawArraysInstanced = NULL; +PFNGLDRAWBUFFERPROC glad_glDrawBuffer = NULL; +PFNGLDRAWBUFFERSPROC glad_glDrawBuffers = NULL; +PFNGLDRAWELEMENTSPROC glad_glDrawElements = NULL; +PFNGLDRAWELEMENTSBASEVERTEXPROC glad_glDrawElementsBaseVertex = NULL; +PFNGLDRAWELEMENTSINSTANCEDPROC glad_glDrawElementsInstanced = NULL; +PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC glad_glDrawElementsInstancedBaseVertex = NULL; +PFNGLDRAWPIXELSPROC glad_glDrawPixels = NULL; +PFNGLDRAWRANGEELEMENTSPROC glad_glDrawRangeElements = NULL; +PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC glad_glDrawRangeElementsBaseVertex = NULL; +PFNGLEDGEFLAGPROC glad_glEdgeFlag = NULL; +PFNGLEDGEFLAGPOINTERPROC glad_glEdgeFlagPointer = NULL; +PFNGLEDGEFLAGVPROC glad_glEdgeFlagv = NULL; +PFNGLENABLEPROC glad_glEnable = NULL; +PFNGLENABLECLIENTSTATEPROC glad_glEnableClientState = NULL; +PFNGLENABLEVERTEXATTRIBARRAYPROC glad_glEnableVertexAttribArray = NULL; +PFNGLENABLEIPROC glad_glEnablei = NULL; +PFNGLENDPROC glad_glEnd = NULL; +PFNGLENDCONDITIONALRENDERPROC glad_glEndConditionalRender = NULL; +PFNGLENDLISTPROC glad_glEndList = NULL; +PFNGLENDQUERYPROC glad_glEndQuery = NULL; +PFNGLENDTRANSFORMFEEDBACKPROC glad_glEndTransformFeedback = NULL; +PFNGLEVALCOORD1DPROC glad_glEvalCoord1d = NULL; +PFNGLEVALCOORD1DVPROC glad_glEvalCoord1dv = NULL; +PFNGLEVALCOORD1FPROC glad_glEvalCoord1f = NULL; +PFNGLEVALCOORD1FVPROC glad_glEvalCoord1fv = NULL; +PFNGLEVALCOORD2DPROC glad_glEvalCoord2d = NULL; +PFNGLEVALCOORD2DVPROC glad_glEvalCoord2dv = NULL; +PFNGLEVALCOORD2FPROC glad_glEvalCoord2f = NULL; +PFNGLEVALCOORD2FVPROC glad_glEvalCoord2fv = NULL; +PFNGLEVALMESH1PROC glad_glEvalMesh1 = NULL; +PFNGLEVALMESH2PROC glad_glEvalMesh2 = NULL; +PFNGLEVALPOINT1PROC glad_glEvalPoint1 = NULL; +PFNGLEVALPOINT2PROC glad_glEvalPoint2 = NULL; +PFNGLFEEDBACKBUFFERPROC glad_glFeedbackBuffer = NULL; +PFNGLFENCESYNCPROC glad_glFenceSync = NULL; +PFNGLFINISHPROC glad_glFinish = NULL; +PFNGLFLUSHPROC glad_glFlush = NULL; +PFNGLFLUSHMAPPEDBUFFERRANGEPROC glad_glFlushMappedBufferRange = NULL; +PFNGLFOGCOORDPOINTERPROC glad_glFogCoordPointer = NULL; +PFNGLFOGCOORDDPROC glad_glFogCoordd = NULL; +PFNGLFOGCOORDDVPROC glad_glFogCoorddv = NULL; +PFNGLFOGCOORDFPROC glad_glFogCoordf = NULL; +PFNGLFOGCOORDFVPROC glad_glFogCoordfv = NULL; +PFNGLFOGFPROC glad_glFogf = NULL; +PFNGLFOGFVPROC glad_glFogfv = NULL; +PFNGLFOGIPROC glad_glFogi = NULL; +PFNGLFOGIVPROC glad_glFogiv = NULL; +PFNGLFRAMEBUFFERRENDERBUFFERPROC glad_glFramebufferRenderbuffer = NULL; +PFNGLFRAMEBUFFERTEXTUREPROC glad_glFramebufferTexture = NULL; +PFNGLFRAMEBUFFERTEXTURE1DPROC glad_glFramebufferTexture1D = NULL; +PFNGLFRAMEBUFFERTEXTURE2DPROC glad_glFramebufferTexture2D = NULL; +PFNGLFRAMEBUFFERTEXTURE3DPROC glad_glFramebufferTexture3D = NULL; +PFNGLFRAMEBUFFERTEXTURELAYERPROC glad_glFramebufferTextureLayer = NULL; +PFNGLFRONTFACEPROC glad_glFrontFace = NULL; +PFNGLFRUSTUMPROC glad_glFrustum = NULL; +PFNGLGENBUFFERSPROC glad_glGenBuffers = NULL; +PFNGLGENFRAMEBUFFERSPROC glad_glGenFramebuffers = NULL; +PFNGLGENLISTSPROC glad_glGenLists = NULL; +PFNGLGENQUERIESPROC glad_glGenQueries = NULL; +PFNGLGENRENDERBUFFERSPROC glad_glGenRenderbuffers = NULL; +PFNGLGENSAMPLERSPROC glad_glGenSamplers = NULL; +PFNGLGENTEXTURESPROC glad_glGenTextures = NULL; +PFNGLGENVERTEXARRAYSPROC glad_glGenVertexArrays = NULL; +PFNGLGENERATEMIPMAPPROC glad_glGenerateMipmap = NULL; +PFNGLGETACTIVEATTRIBPROC glad_glGetActiveAttrib = NULL; +PFNGLGETACTIVEUNIFORMPROC glad_glGetActiveUniform = NULL; +PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC glad_glGetActiveUniformBlockName = NULL; +PFNGLGETACTIVEUNIFORMBLOCKIVPROC glad_glGetActiveUniformBlockiv = NULL; +PFNGLGETACTIVEUNIFORMNAMEPROC glad_glGetActiveUniformName = NULL; +PFNGLGETACTIVEUNIFORMSIVPROC glad_glGetActiveUniformsiv = NULL; +PFNGLGETATTACHEDSHADERSPROC glad_glGetAttachedShaders = NULL; +PFNGLGETATTRIBLOCATIONPROC glad_glGetAttribLocation = NULL; +PFNGLGETBOOLEANI_VPROC glad_glGetBooleani_v = NULL; +PFNGLGETBOOLEANVPROC glad_glGetBooleanv = NULL; +PFNGLGETBUFFERPARAMETERI64VPROC glad_glGetBufferParameteri64v = NULL; +PFNGLGETBUFFERPARAMETERIVPROC glad_glGetBufferParameteriv = NULL; +PFNGLGETBUFFERPOINTERVPROC glad_glGetBufferPointerv = NULL; +PFNGLGETBUFFERSUBDATAPROC glad_glGetBufferSubData = NULL; +PFNGLGETCLIPPLANEPROC glad_glGetClipPlane = NULL; +PFNGLGETCOMPRESSEDTEXIMAGEPROC glad_glGetCompressedTexImage = NULL; +PFNGLGETDEBUGMESSAGELOGPROC glad_glGetDebugMessageLog = NULL; +PFNGLGETDOUBLEVPROC glad_glGetDoublev = NULL; +PFNGLGETERRORPROC glad_glGetError = NULL; +PFNGLGETFLOATVPROC glad_glGetFloatv = NULL; +PFNGLGETFRAGDATAINDEXPROC glad_glGetFragDataIndex = NULL; +PFNGLGETFRAGDATALOCATIONPROC glad_glGetFragDataLocation = NULL; +PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC glad_glGetFramebufferAttachmentParameteriv = NULL; +PFNGLGETGRAPHICSRESETSTATUSARBPROC glad_glGetGraphicsResetStatusARB = NULL; +PFNGLGETINTEGER64I_VPROC glad_glGetInteger64i_v = NULL; +PFNGLGETINTEGER64VPROC glad_glGetInteger64v = NULL; +PFNGLGETINTEGERI_VPROC glad_glGetIntegeri_v = NULL; +PFNGLGETINTEGERVPROC glad_glGetIntegerv = NULL; +PFNGLGETLIGHTFVPROC glad_glGetLightfv = NULL; +PFNGLGETLIGHTIVPROC glad_glGetLightiv = NULL; +PFNGLGETMAPDVPROC glad_glGetMapdv = NULL; +PFNGLGETMAPFVPROC glad_glGetMapfv = NULL; +PFNGLGETMAPIVPROC glad_glGetMapiv = NULL; +PFNGLGETMATERIALFVPROC glad_glGetMaterialfv = NULL; +PFNGLGETMATERIALIVPROC glad_glGetMaterialiv = NULL; +PFNGLGETMULTISAMPLEFVPROC glad_glGetMultisamplefv = NULL; +PFNGLGETOBJECTLABELPROC glad_glGetObjectLabel = NULL; +PFNGLGETOBJECTPTRLABELPROC glad_glGetObjectPtrLabel = NULL; +PFNGLGETPIXELMAPFVPROC glad_glGetPixelMapfv = NULL; +PFNGLGETPIXELMAPUIVPROC glad_glGetPixelMapuiv = NULL; +PFNGLGETPIXELMAPUSVPROC glad_glGetPixelMapusv = NULL; +PFNGLGETPOINTERVPROC glad_glGetPointerv = NULL; +PFNGLGETPOLYGONSTIPPLEPROC glad_glGetPolygonStipple = NULL; +PFNGLGETPROGRAMINFOLOGPROC glad_glGetProgramInfoLog = NULL; +PFNGLGETPROGRAMIVPROC glad_glGetProgramiv = NULL; +PFNGLGETQUERYOBJECTI64VPROC glad_glGetQueryObjecti64v = NULL; +PFNGLGETQUERYOBJECTIVPROC glad_glGetQueryObjectiv = NULL; +PFNGLGETQUERYOBJECTUI64VPROC glad_glGetQueryObjectui64v = NULL; +PFNGLGETQUERYOBJECTUIVPROC glad_glGetQueryObjectuiv = NULL; +PFNGLGETQUERYIVPROC glad_glGetQueryiv = NULL; +PFNGLGETRENDERBUFFERPARAMETERIVPROC glad_glGetRenderbufferParameteriv = NULL; +PFNGLGETSAMPLERPARAMETERIIVPROC glad_glGetSamplerParameterIiv = NULL; +PFNGLGETSAMPLERPARAMETERIUIVPROC glad_glGetSamplerParameterIuiv = NULL; +PFNGLGETSAMPLERPARAMETERFVPROC glad_glGetSamplerParameterfv = NULL; +PFNGLGETSAMPLERPARAMETERIVPROC glad_glGetSamplerParameteriv = NULL; +PFNGLGETSHADERINFOLOGPROC glad_glGetShaderInfoLog = NULL; +PFNGLGETSHADERSOURCEPROC glad_glGetShaderSource = NULL; +PFNGLGETSHADERIVPROC glad_glGetShaderiv = NULL; +PFNGLGETSTRINGPROC glad_glGetString = NULL; +PFNGLGETSTRINGIPROC glad_glGetStringi = NULL; +PFNGLGETSYNCIVPROC glad_glGetSynciv = NULL; +PFNGLGETTEXENVFVPROC glad_glGetTexEnvfv = NULL; +PFNGLGETTEXENVIVPROC glad_glGetTexEnviv = NULL; +PFNGLGETTEXGENDVPROC glad_glGetTexGendv = NULL; +PFNGLGETTEXGENFVPROC glad_glGetTexGenfv = NULL; +PFNGLGETTEXGENIVPROC glad_glGetTexGeniv = NULL; +PFNGLGETTEXIMAGEPROC glad_glGetTexImage = NULL; +PFNGLGETTEXLEVELPARAMETERFVPROC glad_glGetTexLevelParameterfv = NULL; +PFNGLGETTEXLEVELPARAMETERIVPROC glad_glGetTexLevelParameteriv = NULL; +PFNGLGETTEXPARAMETERIIVPROC glad_glGetTexParameterIiv = NULL; +PFNGLGETTEXPARAMETERIUIVPROC glad_glGetTexParameterIuiv = NULL; +PFNGLGETTEXPARAMETERFVPROC glad_glGetTexParameterfv = NULL; +PFNGLGETTEXPARAMETERIVPROC glad_glGetTexParameteriv = NULL; +PFNGLGETTRANSFORMFEEDBACKVARYINGPROC glad_glGetTransformFeedbackVarying = NULL; +PFNGLGETUNIFORMBLOCKINDEXPROC glad_glGetUniformBlockIndex = NULL; +PFNGLGETUNIFORMINDICESPROC glad_glGetUniformIndices = NULL; +PFNGLGETUNIFORMLOCATIONPROC glad_glGetUniformLocation = NULL; +PFNGLGETUNIFORMFVPROC glad_glGetUniformfv = NULL; +PFNGLGETUNIFORMIVPROC glad_glGetUniformiv = NULL; +PFNGLGETUNIFORMUIVPROC glad_glGetUniformuiv = NULL; +PFNGLGETVERTEXATTRIBIIVPROC glad_glGetVertexAttribIiv = NULL; +PFNGLGETVERTEXATTRIBIUIVPROC glad_glGetVertexAttribIuiv = NULL; +PFNGLGETVERTEXATTRIBPOINTERVPROC glad_glGetVertexAttribPointerv = NULL; +PFNGLGETVERTEXATTRIBDVPROC glad_glGetVertexAttribdv = NULL; +PFNGLGETVERTEXATTRIBFVPROC glad_glGetVertexAttribfv = NULL; +PFNGLGETVERTEXATTRIBIVPROC glad_glGetVertexAttribiv = NULL; +PFNGLGETNCOLORTABLEARBPROC glad_glGetnColorTableARB = NULL; +PFNGLGETNCOMPRESSEDTEXIMAGEARBPROC glad_glGetnCompressedTexImageARB = NULL; +PFNGLGETNCONVOLUTIONFILTERARBPROC glad_glGetnConvolutionFilterARB = NULL; +PFNGLGETNHISTOGRAMARBPROC glad_glGetnHistogramARB = NULL; +PFNGLGETNMAPDVARBPROC glad_glGetnMapdvARB = NULL; +PFNGLGETNMAPFVARBPROC glad_glGetnMapfvARB = NULL; +PFNGLGETNMAPIVARBPROC glad_glGetnMapivARB = NULL; +PFNGLGETNMINMAXARBPROC glad_glGetnMinmaxARB = NULL; +PFNGLGETNPIXELMAPFVARBPROC glad_glGetnPixelMapfvARB = NULL; +PFNGLGETNPIXELMAPUIVARBPROC glad_glGetnPixelMapuivARB = NULL; +PFNGLGETNPIXELMAPUSVARBPROC glad_glGetnPixelMapusvARB = NULL; +PFNGLGETNPOLYGONSTIPPLEARBPROC glad_glGetnPolygonStippleARB = NULL; +PFNGLGETNSEPARABLEFILTERARBPROC glad_glGetnSeparableFilterARB = NULL; +PFNGLGETNTEXIMAGEARBPROC glad_glGetnTexImageARB = NULL; +PFNGLGETNUNIFORMDVARBPROC glad_glGetnUniformdvARB = NULL; +PFNGLGETNUNIFORMFVARBPROC glad_glGetnUniformfvARB = NULL; +PFNGLGETNUNIFORMIVARBPROC glad_glGetnUniformivARB = NULL; +PFNGLGETNUNIFORMUIVARBPROC glad_glGetnUniformuivARB = NULL; +PFNGLHINTPROC glad_glHint = NULL; +PFNGLINDEXMASKPROC glad_glIndexMask = NULL; +PFNGLINDEXPOINTERPROC glad_glIndexPointer = NULL; +PFNGLINDEXDPROC glad_glIndexd = NULL; +PFNGLINDEXDVPROC glad_glIndexdv = NULL; +PFNGLINDEXFPROC glad_glIndexf = NULL; +PFNGLINDEXFVPROC glad_glIndexfv = NULL; +PFNGLINDEXIPROC glad_glIndexi = NULL; +PFNGLINDEXIVPROC glad_glIndexiv = NULL; +PFNGLINDEXSPROC glad_glIndexs = NULL; +PFNGLINDEXSVPROC glad_glIndexsv = NULL; +PFNGLINDEXUBPROC glad_glIndexub = NULL; +PFNGLINDEXUBVPROC glad_glIndexubv = NULL; +PFNGLINITNAMESPROC glad_glInitNames = NULL; +PFNGLINTERLEAVEDARRAYSPROC glad_glInterleavedArrays = NULL; +PFNGLISBUFFERPROC glad_glIsBuffer = NULL; +PFNGLISENABLEDPROC glad_glIsEnabled = NULL; +PFNGLISENABLEDIPROC glad_glIsEnabledi = NULL; +PFNGLISFRAMEBUFFERPROC glad_glIsFramebuffer = NULL; +PFNGLISLISTPROC glad_glIsList = NULL; +PFNGLISPROGRAMPROC glad_glIsProgram = NULL; +PFNGLISQUERYPROC glad_glIsQuery = NULL; +PFNGLISRENDERBUFFERPROC glad_glIsRenderbuffer = NULL; +PFNGLISSAMPLERPROC glad_glIsSampler = NULL; +PFNGLISSHADERPROC glad_glIsShader = NULL; +PFNGLISSYNCPROC glad_glIsSync = NULL; +PFNGLISTEXTUREPROC glad_glIsTexture = NULL; +PFNGLISVERTEXARRAYPROC glad_glIsVertexArray = NULL; +PFNGLLIGHTMODELFPROC glad_glLightModelf = NULL; +PFNGLLIGHTMODELFVPROC glad_glLightModelfv = NULL; +PFNGLLIGHTMODELIPROC glad_glLightModeli = NULL; +PFNGLLIGHTMODELIVPROC glad_glLightModeliv = NULL; +PFNGLLIGHTFPROC glad_glLightf = NULL; +PFNGLLIGHTFVPROC glad_glLightfv = NULL; +PFNGLLIGHTIPROC glad_glLighti = NULL; +PFNGLLIGHTIVPROC glad_glLightiv = NULL; +PFNGLLINESTIPPLEPROC glad_glLineStipple = NULL; +PFNGLLINEWIDTHPROC glad_glLineWidth = NULL; +PFNGLLINKPROGRAMPROC glad_glLinkProgram = NULL; +PFNGLLISTBASEPROC glad_glListBase = NULL; +PFNGLLOADIDENTITYPROC glad_glLoadIdentity = NULL; +PFNGLLOADMATRIXDPROC glad_glLoadMatrixd = NULL; +PFNGLLOADMATRIXFPROC glad_glLoadMatrixf = NULL; +PFNGLLOADNAMEPROC glad_glLoadName = NULL; +PFNGLLOADTRANSPOSEMATRIXDPROC glad_glLoadTransposeMatrixd = NULL; +PFNGLLOADTRANSPOSEMATRIXFPROC glad_glLoadTransposeMatrixf = NULL; +PFNGLLOGICOPPROC glad_glLogicOp = NULL; +PFNGLMAP1DPROC glad_glMap1d = NULL; +PFNGLMAP1FPROC glad_glMap1f = NULL; +PFNGLMAP2DPROC glad_glMap2d = NULL; +PFNGLMAP2FPROC glad_glMap2f = NULL; +PFNGLMAPBUFFERPROC glad_glMapBuffer = NULL; +PFNGLMAPBUFFERRANGEPROC glad_glMapBufferRange = NULL; +PFNGLMAPGRID1DPROC glad_glMapGrid1d = NULL; +PFNGLMAPGRID1FPROC glad_glMapGrid1f = NULL; +PFNGLMAPGRID2DPROC glad_glMapGrid2d = NULL; +PFNGLMAPGRID2FPROC glad_glMapGrid2f = NULL; +PFNGLMATERIALFPROC glad_glMaterialf = NULL; +PFNGLMATERIALFVPROC glad_glMaterialfv = NULL; +PFNGLMATERIALIPROC glad_glMateriali = NULL; +PFNGLMATERIALIVPROC glad_glMaterialiv = NULL; +PFNGLMATRIXMODEPROC glad_glMatrixMode = NULL; +PFNGLMULTMATRIXDPROC glad_glMultMatrixd = NULL; +PFNGLMULTMATRIXFPROC glad_glMultMatrixf = NULL; +PFNGLMULTTRANSPOSEMATRIXDPROC glad_glMultTransposeMatrixd = NULL; +PFNGLMULTTRANSPOSEMATRIXFPROC glad_glMultTransposeMatrixf = NULL; +PFNGLMULTIDRAWARRAYSPROC glad_glMultiDrawArrays = NULL; +PFNGLMULTIDRAWELEMENTSPROC glad_glMultiDrawElements = NULL; +PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC glad_glMultiDrawElementsBaseVertex = NULL; +PFNGLMULTITEXCOORD1DPROC glad_glMultiTexCoord1d = NULL; +PFNGLMULTITEXCOORD1DVPROC glad_glMultiTexCoord1dv = NULL; +PFNGLMULTITEXCOORD1FPROC glad_glMultiTexCoord1f = NULL; +PFNGLMULTITEXCOORD1FVPROC glad_glMultiTexCoord1fv = NULL; +PFNGLMULTITEXCOORD1IPROC glad_glMultiTexCoord1i = NULL; +PFNGLMULTITEXCOORD1IVPROC glad_glMultiTexCoord1iv = NULL; +PFNGLMULTITEXCOORD1SPROC glad_glMultiTexCoord1s = NULL; +PFNGLMULTITEXCOORD1SVPROC glad_glMultiTexCoord1sv = NULL; +PFNGLMULTITEXCOORD2DPROC glad_glMultiTexCoord2d = NULL; +PFNGLMULTITEXCOORD2DVPROC glad_glMultiTexCoord2dv = NULL; +PFNGLMULTITEXCOORD2FPROC glad_glMultiTexCoord2f = NULL; +PFNGLMULTITEXCOORD2FVPROC glad_glMultiTexCoord2fv = NULL; +PFNGLMULTITEXCOORD2IPROC glad_glMultiTexCoord2i = NULL; +PFNGLMULTITEXCOORD2IVPROC glad_glMultiTexCoord2iv = NULL; +PFNGLMULTITEXCOORD2SPROC glad_glMultiTexCoord2s = NULL; +PFNGLMULTITEXCOORD2SVPROC glad_glMultiTexCoord2sv = NULL; +PFNGLMULTITEXCOORD3DPROC glad_glMultiTexCoord3d = NULL; +PFNGLMULTITEXCOORD3DVPROC glad_glMultiTexCoord3dv = NULL; +PFNGLMULTITEXCOORD3FPROC glad_glMultiTexCoord3f = NULL; +PFNGLMULTITEXCOORD3FVPROC glad_glMultiTexCoord3fv = NULL; +PFNGLMULTITEXCOORD3IPROC glad_glMultiTexCoord3i = NULL; +PFNGLMULTITEXCOORD3IVPROC glad_glMultiTexCoord3iv = NULL; +PFNGLMULTITEXCOORD3SPROC glad_glMultiTexCoord3s = NULL; +PFNGLMULTITEXCOORD3SVPROC glad_glMultiTexCoord3sv = NULL; +PFNGLMULTITEXCOORD4DPROC glad_glMultiTexCoord4d = NULL; +PFNGLMULTITEXCOORD4DVPROC glad_glMultiTexCoord4dv = NULL; +PFNGLMULTITEXCOORD4FPROC glad_glMultiTexCoord4f = NULL; +PFNGLMULTITEXCOORD4FVPROC glad_glMultiTexCoord4fv = NULL; +PFNGLMULTITEXCOORD4IPROC glad_glMultiTexCoord4i = NULL; +PFNGLMULTITEXCOORD4IVPROC glad_glMultiTexCoord4iv = NULL; +PFNGLMULTITEXCOORD4SPROC glad_glMultiTexCoord4s = NULL; +PFNGLMULTITEXCOORD4SVPROC glad_glMultiTexCoord4sv = NULL; +PFNGLMULTITEXCOORDP1UIPROC glad_glMultiTexCoordP1ui = NULL; +PFNGLMULTITEXCOORDP1UIVPROC glad_glMultiTexCoordP1uiv = NULL; +PFNGLMULTITEXCOORDP2UIPROC glad_glMultiTexCoordP2ui = NULL; +PFNGLMULTITEXCOORDP2UIVPROC glad_glMultiTexCoordP2uiv = NULL; +PFNGLMULTITEXCOORDP3UIPROC glad_glMultiTexCoordP3ui = NULL; +PFNGLMULTITEXCOORDP3UIVPROC glad_glMultiTexCoordP3uiv = NULL; +PFNGLMULTITEXCOORDP4UIPROC glad_glMultiTexCoordP4ui = NULL; +PFNGLMULTITEXCOORDP4UIVPROC glad_glMultiTexCoordP4uiv = NULL; +PFNGLNEWLISTPROC glad_glNewList = NULL; +PFNGLNORMAL3BPROC glad_glNormal3b = NULL; +PFNGLNORMAL3BVPROC glad_glNormal3bv = NULL; +PFNGLNORMAL3DPROC glad_glNormal3d = NULL; +PFNGLNORMAL3DVPROC glad_glNormal3dv = NULL; +PFNGLNORMAL3FPROC glad_glNormal3f = NULL; +PFNGLNORMAL3FVPROC glad_glNormal3fv = NULL; +PFNGLNORMAL3IPROC glad_glNormal3i = NULL; +PFNGLNORMAL3IVPROC glad_glNormal3iv = NULL; +PFNGLNORMAL3SPROC glad_glNormal3s = NULL; +PFNGLNORMAL3SVPROC glad_glNormal3sv = NULL; +PFNGLNORMALP3UIPROC glad_glNormalP3ui = NULL; +PFNGLNORMALP3UIVPROC glad_glNormalP3uiv = NULL; +PFNGLNORMALPOINTERPROC glad_glNormalPointer = NULL; +PFNGLOBJECTLABELPROC glad_glObjectLabel = NULL; +PFNGLOBJECTPTRLABELPROC glad_glObjectPtrLabel = NULL; +PFNGLORTHOPROC glad_glOrtho = NULL; +PFNGLPASSTHROUGHPROC glad_glPassThrough = NULL; +PFNGLPIXELMAPFVPROC glad_glPixelMapfv = NULL; +PFNGLPIXELMAPUIVPROC glad_glPixelMapuiv = NULL; +PFNGLPIXELMAPUSVPROC glad_glPixelMapusv = NULL; +PFNGLPIXELSTOREFPROC glad_glPixelStoref = NULL; +PFNGLPIXELSTOREIPROC glad_glPixelStorei = NULL; +PFNGLPIXELTRANSFERFPROC glad_glPixelTransferf = NULL; +PFNGLPIXELTRANSFERIPROC glad_glPixelTransferi = NULL; +PFNGLPIXELZOOMPROC glad_glPixelZoom = NULL; +PFNGLPOINTPARAMETERFPROC glad_glPointParameterf = NULL; +PFNGLPOINTPARAMETERFVPROC glad_glPointParameterfv = NULL; +PFNGLPOINTPARAMETERIPROC glad_glPointParameteri = NULL; +PFNGLPOINTPARAMETERIVPROC glad_glPointParameteriv = NULL; +PFNGLPOINTSIZEPROC glad_glPointSize = NULL; +PFNGLPOLYGONMODEPROC glad_glPolygonMode = NULL; +PFNGLPOLYGONOFFSETPROC glad_glPolygonOffset = NULL; +PFNGLPOLYGONSTIPPLEPROC glad_glPolygonStipple = NULL; +PFNGLPOPATTRIBPROC glad_glPopAttrib = NULL; +PFNGLPOPCLIENTATTRIBPROC glad_glPopClientAttrib = NULL; +PFNGLPOPDEBUGGROUPPROC glad_glPopDebugGroup = NULL; +PFNGLPOPMATRIXPROC glad_glPopMatrix = NULL; +PFNGLPOPNAMEPROC glad_glPopName = NULL; +PFNGLPRIMITIVERESTARTINDEXPROC glad_glPrimitiveRestartIndex = NULL; +PFNGLPRIORITIZETEXTURESPROC glad_glPrioritizeTextures = NULL; +PFNGLPROVOKINGVERTEXPROC glad_glProvokingVertex = NULL; +PFNGLPUSHATTRIBPROC glad_glPushAttrib = NULL; +PFNGLPUSHCLIENTATTRIBPROC glad_glPushClientAttrib = NULL; +PFNGLPUSHDEBUGGROUPPROC glad_glPushDebugGroup = NULL; +PFNGLPUSHMATRIXPROC glad_glPushMatrix = NULL; +PFNGLPUSHNAMEPROC glad_glPushName = NULL; +PFNGLQUERYCOUNTERPROC glad_glQueryCounter = NULL; +PFNGLRASTERPOS2DPROC glad_glRasterPos2d = NULL; +PFNGLRASTERPOS2DVPROC glad_glRasterPos2dv = NULL; +PFNGLRASTERPOS2FPROC glad_glRasterPos2f = NULL; +PFNGLRASTERPOS2FVPROC glad_glRasterPos2fv = NULL; +PFNGLRASTERPOS2IPROC glad_glRasterPos2i = NULL; +PFNGLRASTERPOS2IVPROC glad_glRasterPos2iv = NULL; +PFNGLRASTERPOS2SPROC glad_glRasterPos2s = NULL; +PFNGLRASTERPOS2SVPROC glad_glRasterPos2sv = NULL; +PFNGLRASTERPOS3DPROC glad_glRasterPos3d = NULL; +PFNGLRASTERPOS3DVPROC glad_glRasterPos3dv = NULL; +PFNGLRASTERPOS3FPROC glad_glRasterPos3f = NULL; +PFNGLRASTERPOS3FVPROC glad_glRasterPos3fv = NULL; +PFNGLRASTERPOS3IPROC glad_glRasterPos3i = NULL; +PFNGLRASTERPOS3IVPROC glad_glRasterPos3iv = NULL; +PFNGLRASTERPOS3SPROC glad_glRasterPos3s = NULL; +PFNGLRASTERPOS3SVPROC glad_glRasterPos3sv = NULL; +PFNGLRASTERPOS4DPROC glad_glRasterPos4d = NULL; +PFNGLRASTERPOS4DVPROC glad_glRasterPos4dv = NULL; +PFNGLRASTERPOS4FPROC glad_glRasterPos4f = NULL; +PFNGLRASTERPOS4FVPROC glad_glRasterPos4fv = NULL; +PFNGLRASTERPOS4IPROC glad_glRasterPos4i = NULL; +PFNGLRASTERPOS4IVPROC glad_glRasterPos4iv = NULL; +PFNGLRASTERPOS4SPROC glad_glRasterPos4s = NULL; +PFNGLRASTERPOS4SVPROC glad_glRasterPos4sv = NULL; +PFNGLREADBUFFERPROC glad_glReadBuffer = NULL; +PFNGLREADPIXELSPROC glad_glReadPixels = NULL; +PFNGLREADNPIXELSPROC glad_glReadnPixels = NULL; +PFNGLREADNPIXELSARBPROC glad_glReadnPixelsARB = NULL; +PFNGLRECTDPROC glad_glRectd = NULL; +PFNGLRECTDVPROC glad_glRectdv = NULL; +PFNGLRECTFPROC glad_glRectf = NULL; +PFNGLRECTFVPROC glad_glRectfv = NULL; +PFNGLRECTIPROC glad_glRecti = NULL; +PFNGLRECTIVPROC glad_glRectiv = NULL; +PFNGLRECTSPROC glad_glRects = NULL; +PFNGLRECTSVPROC glad_glRectsv = NULL; +PFNGLRENDERMODEPROC glad_glRenderMode = NULL; +PFNGLRENDERBUFFERSTORAGEPROC glad_glRenderbufferStorage = NULL; +PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC glad_glRenderbufferStorageMultisample = NULL; +PFNGLROTATEDPROC glad_glRotated = NULL; +PFNGLROTATEFPROC glad_glRotatef = NULL; +PFNGLSAMPLECOVERAGEPROC glad_glSampleCoverage = NULL; +PFNGLSAMPLECOVERAGEARBPROC glad_glSampleCoverageARB = NULL; +PFNGLSAMPLEMASKIPROC glad_glSampleMaski = NULL; +PFNGLSAMPLERPARAMETERIIVPROC glad_glSamplerParameterIiv = NULL; +PFNGLSAMPLERPARAMETERIUIVPROC glad_glSamplerParameterIuiv = NULL; +PFNGLSAMPLERPARAMETERFPROC glad_glSamplerParameterf = NULL; +PFNGLSAMPLERPARAMETERFVPROC glad_glSamplerParameterfv = NULL; +PFNGLSAMPLERPARAMETERIPROC glad_glSamplerParameteri = NULL; +PFNGLSAMPLERPARAMETERIVPROC glad_glSamplerParameteriv = NULL; +PFNGLSCALEDPROC glad_glScaled = NULL; +PFNGLSCALEFPROC glad_glScalef = NULL; +PFNGLSCISSORPROC glad_glScissor = NULL; +PFNGLSECONDARYCOLOR3BPROC glad_glSecondaryColor3b = NULL; +PFNGLSECONDARYCOLOR3BVPROC glad_glSecondaryColor3bv = NULL; +PFNGLSECONDARYCOLOR3DPROC glad_glSecondaryColor3d = NULL; +PFNGLSECONDARYCOLOR3DVPROC glad_glSecondaryColor3dv = NULL; +PFNGLSECONDARYCOLOR3FPROC glad_glSecondaryColor3f = NULL; +PFNGLSECONDARYCOLOR3FVPROC glad_glSecondaryColor3fv = NULL; +PFNGLSECONDARYCOLOR3IPROC glad_glSecondaryColor3i = NULL; +PFNGLSECONDARYCOLOR3IVPROC glad_glSecondaryColor3iv = NULL; +PFNGLSECONDARYCOLOR3SPROC glad_glSecondaryColor3s = NULL; +PFNGLSECONDARYCOLOR3SVPROC glad_glSecondaryColor3sv = NULL; +PFNGLSECONDARYCOLOR3UBPROC glad_glSecondaryColor3ub = NULL; +PFNGLSECONDARYCOLOR3UBVPROC glad_glSecondaryColor3ubv = NULL; +PFNGLSECONDARYCOLOR3UIPROC glad_glSecondaryColor3ui = NULL; +PFNGLSECONDARYCOLOR3UIVPROC glad_glSecondaryColor3uiv = NULL; +PFNGLSECONDARYCOLOR3USPROC glad_glSecondaryColor3us = NULL; +PFNGLSECONDARYCOLOR3USVPROC glad_glSecondaryColor3usv = NULL; +PFNGLSECONDARYCOLORP3UIPROC glad_glSecondaryColorP3ui = NULL; +PFNGLSECONDARYCOLORP3UIVPROC glad_glSecondaryColorP3uiv = NULL; +PFNGLSECONDARYCOLORPOINTERPROC glad_glSecondaryColorPointer = NULL; +PFNGLSELECTBUFFERPROC glad_glSelectBuffer = NULL; +PFNGLSHADEMODELPROC glad_glShadeModel = NULL; +PFNGLSHADERSOURCEPROC glad_glShaderSource = NULL; +PFNGLSTENCILFUNCPROC glad_glStencilFunc = NULL; +PFNGLSTENCILFUNCSEPARATEPROC glad_glStencilFuncSeparate = NULL; +PFNGLSTENCILMASKPROC glad_glStencilMask = NULL; +PFNGLSTENCILMASKSEPARATEPROC glad_glStencilMaskSeparate = NULL; +PFNGLSTENCILOPPROC glad_glStencilOp = NULL; +PFNGLSTENCILOPSEPARATEPROC glad_glStencilOpSeparate = NULL; +PFNGLTEXBUFFERPROC glad_glTexBuffer = NULL; +PFNGLTEXCOORD1DPROC glad_glTexCoord1d = NULL; +PFNGLTEXCOORD1DVPROC glad_glTexCoord1dv = NULL; +PFNGLTEXCOORD1FPROC glad_glTexCoord1f = NULL; +PFNGLTEXCOORD1FVPROC glad_glTexCoord1fv = NULL; +PFNGLTEXCOORD1IPROC glad_glTexCoord1i = NULL; +PFNGLTEXCOORD1IVPROC glad_glTexCoord1iv = NULL; +PFNGLTEXCOORD1SPROC glad_glTexCoord1s = NULL; +PFNGLTEXCOORD1SVPROC glad_glTexCoord1sv = NULL; +PFNGLTEXCOORD2DPROC glad_glTexCoord2d = NULL; +PFNGLTEXCOORD2DVPROC glad_glTexCoord2dv = NULL; +PFNGLTEXCOORD2FPROC glad_glTexCoord2f = NULL; +PFNGLTEXCOORD2FVPROC glad_glTexCoord2fv = NULL; +PFNGLTEXCOORD2IPROC glad_glTexCoord2i = NULL; +PFNGLTEXCOORD2IVPROC glad_glTexCoord2iv = NULL; +PFNGLTEXCOORD2SPROC glad_glTexCoord2s = NULL; +PFNGLTEXCOORD2SVPROC glad_glTexCoord2sv = NULL; +PFNGLTEXCOORD3DPROC glad_glTexCoord3d = NULL; +PFNGLTEXCOORD3DVPROC glad_glTexCoord3dv = NULL; +PFNGLTEXCOORD3FPROC glad_glTexCoord3f = NULL; +PFNGLTEXCOORD3FVPROC glad_glTexCoord3fv = NULL; +PFNGLTEXCOORD3IPROC glad_glTexCoord3i = NULL; +PFNGLTEXCOORD3IVPROC glad_glTexCoord3iv = NULL; +PFNGLTEXCOORD3SPROC glad_glTexCoord3s = NULL; +PFNGLTEXCOORD3SVPROC glad_glTexCoord3sv = NULL; +PFNGLTEXCOORD4DPROC glad_glTexCoord4d = NULL; +PFNGLTEXCOORD4DVPROC glad_glTexCoord4dv = NULL; +PFNGLTEXCOORD4FPROC glad_glTexCoord4f = NULL; +PFNGLTEXCOORD4FVPROC glad_glTexCoord4fv = NULL; +PFNGLTEXCOORD4IPROC glad_glTexCoord4i = NULL; +PFNGLTEXCOORD4IVPROC glad_glTexCoord4iv = NULL; +PFNGLTEXCOORD4SPROC glad_glTexCoord4s = NULL; +PFNGLTEXCOORD4SVPROC glad_glTexCoord4sv = NULL; +PFNGLTEXCOORDP1UIPROC glad_glTexCoordP1ui = NULL; +PFNGLTEXCOORDP1UIVPROC glad_glTexCoordP1uiv = NULL; +PFNGLTEXCOORDP2UIPROC glad_glTexCoordP2ui = NULL; +PFNGLTEXCOORDP2UIVPROC glad_glTexCoordP2uiv = NULL; +PFNGLTEXCOORDP3UIPROC glad_glTexCoordP3ui = NULL; +PFNGLTEXCOORDP3UIVPROC glad_glTexCoordP3uiv = NULL; +PFNGLTEXCOORDP4UIPROC glad_glTexCoordP4ui = NULL; +PFNGLTEXCOORDP4UIVPROC glad_glTexCoordP4uiv = NULL; +PFNGLTEXCOORDPOINTERPROC glad_glTexCoordPointer = NULL; +PFNGLTEXENVFPROC glad_glTexEnvf = NULL; +PFNGLTEXENVFVPROC glad_glTexEnvfv = NULL; +PFNGLTEXENVIPROC glad_glTexEnvi = NULL; +PFNGLTEXENVIVPROC glad_glTexEnviv = NULL; +PFNGLTEXGENDPROC glad_glTexGend = NULL; +PFNGLTEXGENDVPROC glad_glTexGendv = NULL; +PFNGLTEXGENFPROC glad_glTexGenf = NULL; +PFNGLTEXGENFVPROC glad_glTexGenfv = NULL; +PFNGLTEXGENIPROC glad_glTexGeni = NULL; +PFNGLTEXGENIVPROC glad_glTexGeniv = NULL; +PFNGLTEXIMAGE1DPROC glad_glTexImage1D = NULL; +PFNGLTEXIMAGE2DPROC glad_glTexImage2D = NULL; +PFNGLTEXIMAGE2DMULTISAMPLEPROC glad_glTexImage2DMultisample = NULL; +PFNGLTEXIMAGE3DPROC glad_glTexImage3D = NULL; +PFNGLTEXIMAGE3DMULTISAMPLEPROC glad_glTexImage3DMultisample = NULL; +PFNGLTEXPARAMETERIIVPROC glad_glTexParameterIiv = NULL; +PFNGLTEXPARAMETERIUIVPROC glad_glTexParameterIuiv = NULL; +PFNGLTEXPARAMETERFPROC glad_glTexParameterf = NULL; +PFNGLTEXPARAMETERFVPROC glad_glTexParameterfv = NULL; +PFNGLTEXPARAMETERIPROC glad_glTexParameteri = NULL; +PFNGLTEXPARAMETERIVPROC glad_glTexParameteriv = NULL; +PFNGLTEXSUBIMAGE1DPROC glad_glTexSubImage1D = NULL; +PFNGLTEXSUBIMAGE2DPROC glad_glTexSubImage2D = NULL; +PFNGLTEXSUBIMAGE3DPROC glad_glTexSubImage3D = NULL; +PFNGLTRANSFORMFEEDBACKVARYINGSPROC glad_glTransformFeedbackVaryings = NULL; +PFNGLTRANSLATEDPROC glad_glTranslated = NULL; +PFNGLTRANSLATEFPROC glad_glTranslatef = NULL; +PFNGLUNIFORM1FPROC glad_glUniform1f = NULL; +PFNGLUNIFORM1FVPROC glad_glUniform1fv = NULL; +PFNGLUNIFORM1IPROC glad_glUniform1i = NULL; +PFNGLUNIFORM1IVPROC glad_glUniform1iv = NULL; +PFNGLUNIFORM1UIPROC glad_glUniform1ui = NULL; +PFNGLUNIFORM1UIVPROC glad_glUniform1uiv = NULL; +PFNGLUNIFORM2FPROC glad_glUniform2f = NULL; +PFNGLUNIFORM2FVPROC glad_glUniform2fv = NULL; +PFNGLUNIFORM2IPROC glad_glUniform2i = NULL; +PFNGLUNIFORM2IVPROC glad_glUniform2iv = NULL; +PFNGLUNIFORM2UIPROC glad_glUniform2ui = NULL; +PFNGLUNIFORM2UIVPROC glad_glUniform2uiv = NULL; +PFNGLUNIFORM3FPROC glad_glUniform3f = NULL; +PFNGLUNIFORM3FVPROC glad_glUniform3fv = NULL; +PFNGLUNIFORM3IPROC glad_glUniform3i = NULL; +PFNGLUNIFORM3IVPROC glad_glUniform3iv = NULL; +PFNGLUNIFORM3UIPROC glad_glUniform3ui = NULL; +PFNGLUNIFORM3UIVPROC glad_glUniform3uiv = NULL; +PFNGLUNIFORM4FPROC glad_glUniform4f = NULL; +PFNGLUNIFORM4FVPROC glad_glUniform4fv = NULL; +PFNGLUNIFORM4IPROC glad_glUniform4i = NULL; +PFNGLUNIFORM4IVPROC glad_glUniform4iv = NULL; +PFNGLUNIFORM4UIPROC glad_glUniform4ui = NULL; +PFNGLUNIFORM4UIVPROC glad_glUniform4uiv = NULL; +PFNGLUNIFORMBLOCKBINDINGPROC glad_glUniformBlockBinding = NULL; +PFNGLUNIFORMMATRIX2FVPROC glad_glUniformMatrix2fv = NULL; +PFNGLUNIFORMMATRIX2X3FVPROC glad_glUniformMatrix2x3fv = NULL; +PFNGLUNIFORMMATRIX2X4FVPROC glad_glUniformMatrix2x4fv = NULL; +PFNGLUNIFORMMATRIX3FVPROC glad_glUniformMatrix3fv = NULL; +PFNGLUNIFORMMATRIX3X2FVPROC glad_glUniformMatrix3x2fv = NULL; +PFNGLUNIFORMMATRIX3X4FVPROC glad_glUniformMatrix3x4fv = NULL; +PFNGLUNIFORMMATRIX4FVPROC glad_glUniformMatrix4fv = NULL; +PFNGLUNIFORMMATRIX4X2FVPROC glad_glUniformMatrix4x2fv = NULL; +PFNGLUNIFORMMATRIX4X3FVPROC glad_glUniformMatrix4x3fv = NULL; +PFNGLUNMAPBUFFERPROC glad_glUnmapBuffer = NULL; +PFNGLUSEPROGRAMPROC glad_glUseProgram = NULL; +PFNGLVALIDATEPROGRAMPROC glad_glValidateProgram = NULL; +PFNGLVERTEX2DPROC glad_glVertex2d = NULL; +PFNGLVERTEX2DVPROC glad_glVertex2dv = NULL; +PFNGLVERTEX2FPROC glad_glVertex2f = NULL; +PFNGLVERTEX2FVPROC glad_glVertex2fv = NULL; +PFNGLVERTEX2IPROC glad_glVertex2i = NULL; +PFNGLVERTEX2IVPROC glad_glVertex2iv = NULL; +PFNGLVERTEX2SPROC glad_glVertex2s = NULL; +PFNGLVERTEX2SVPROC glad_glVertex2sv = NULL; +PFNGLVERTEX3DPROC glad_glVertex3d = NULL; +PFNGLVERTEX3DVPROC glad_glVertex3dv = NULL; +PFNGLVERTEX3FPROC glad_glVertex3f = NULL; +PFNGLVERTEX3FVPROC glad_glVertex3fv = NULL; +PFNGLVERTEX3IPROC glad_glVertex3i = NULL; +PFNGLVERTEX3IVPROC glad_glVertex3iv = NULL; +PFNGLVERTEX3SPROC glad_glVertex3s = NULL; +PFNGLVERTEX3SVPROC glad_glVertex3sv = NULL; +PFNGLVERTEX4DPROC glad_glVertex4d = NULL; +PFNGLVERTEX4DVPROC glad_glVertex4dv = NULL; +PFNGLVERTEX4FPROC glad_glVertex4f = NULL; +PFNGLVERTEX4FVPROC glad_glVertex4fv = NULL; +PFNGLVERTEX4IPROC glad_glVertex4i = NULL; +PFNGLVERTEX4IVPROC glad_glVertex4iv = NULL; +PFNGLVERTEX4SPROC glad_glVertex4s = NULL; +PFNGLVERTEX4SVPROC glad_glVertex4sv = NULL; +PFNGLVERTEXATTRIB1DPROC glad_glVertexAttrib1d = NULL; +PFNGLVERTEXATTRIB1DVPROC glad_glVertexAttrib1dv = NULL; +PFNGLVERTEXATTRIB1FPROC glad_glVertexAttrib1f = NULL; +PFNGLVERTEXATTRIB1FVPROC glad_glVertexAttrib1fv = NULL; +PFNGLVERTEXATTRIB1SPROC glad_glVertexAttrib1s = NULL; +PFNGLVERTEXATTRIB1SVPROC glad_glVertexAttrib1sv = NULL; +PFNGLVERTEXATTRIB2DPROC glad_glVertexAttrib2d = NULL; +PFNGLVERTEXATTRIB2DVPROC glad_glVertexAttrib2dv = NULL; +PFNGLVERTEXATTRIB2FPROC glad_glVertexAttrib2f = NULL; +PFNGLVERTEXATTRIB2FVPROC glad_glVertexAttrib2fv = NULL; +PFNGLVERTEXATTRIB2SPROC glad_glVertexAttrib2s = NULL; +PFNGLVERTEXATTRIB2SVPROC glad_glVertexAttrib2sv = NULL; +PFNGLVERTEXATTRIB3DPROC glad_glVertexAttrib3d = NULL; +PFNGLVERTEXATTRIB3DVPROC glad_glVertexAttrib3dv = NULL; +PFNGLVERTEXATTRIB3FPROC glad_glVertexAttrib3f = NULL; +PFNGLVERTEXATTRIB3FVPROC glad_glVertexAttrib3fv = NULL; +PFNGLVERTEXATTRIB3SPROC glad_glVertexAttrib3s = NULL; +PFNGLVERTEXATTRIB3SVPROC glad_glVertexAttrib3sv = NULL; +PFNGLVERTEXATTRIB4NBVPROC glad_glVertexAttrib4Nbv = NULL; +PFNGLVERTEXATTRIB4NIVPROC glad_glVertexAttrib4Niv = NULL; +PFNGLVERTEXATTRIB4NSVPROC glad_glVertexAttrib4Nsv = NULL; +PFNGLVERTEXATTRIB4NUBPROC glad_glVertexAttrib4Nub = NULL; +PFNGLVERTEXATTRIB4NUBVPROC glad_glVertexAttrib4Nubv = NULL; +PFNGLVERTEXATTRIB4NUIVPROC glad_glVertexAttrib4Nuiv = NULL; +PFNGLVERTEXATTRIB4NUSVPROC glad_glVertexAttrib4Nusv = NULL; +PFNGLVERTEXATTRIB4BVPROC glad_glVertexAttrib4bv = NULL; +PFNGLVERTEXATTRIB4DPROC glad_glVertexAttrib4d = NULL; +PFNGLVERTEXATTRIB4DVPROC glad_glVertexAttrib4dv = NULL; +PFNGLVERTEXATTRIB4FPROC glad_glVertexAttrib4f = NULL; +PFNGLVERTEXATTRIB4FVPROC glad_glVertexAttrib4fv = NULL; +PFNGLVERTEXATTRIB4IVPROC glad_glVertexAttrib4iv = NULL; +PFNGLVERTEXATTRIB4SPROC glad_glVertexAttrib4s = NULL; +PFNGLVERTEXATTRIB4SVPROC glad_glVertexAttrib4sv = NULL; +PFNGLVERTEXATTRIB4UBVPROC glad_glVertexAttrib4ubv = NULL; +PFNGLVERTEXATTRIB4UIVPROC glad_glVertexAttrib4uiv = NULL; +PFNGLVERTEXATTRIB4USVPROC glad_glVertexAttrib4usv = NULL; +PFNGLVERTEXATTRIBDIVISORPROC glad_glVertexAttribDivisor = NULL; +PFNGLVERTEXATTRIBI1IPROC glad_glVertexAttribI1i = NULL; +PFNGLVERTEXATTRIBI1IVPROC glad_glVertexAttribI1iv = NULL; +PFNGLVERTEXATTRIBI1UIPROC glad_glVertexAttribI1ui = NULL; +PFNGLVERTEXATTRIBI1UIVPROC glad_glVertexAttribI1uiv = NULL; +PFNGLVERTEXATTRIBI2IPROC glad_glVertexAttribI2i = NULL; +PFNGLVERTEXATTRIBI2IVPROC glad_glVertexAttribI2iv = NULL; +PFNGLVERTEXATTRIBI2UIPROC glad_glVertexAttribI2ui = NULL; +PFNGLVERTEXATTRIBI2UIVPROC glad_glVertexAttribI2uiv = NULL; +PFNGLVERTEXATTRIBI3IPROC glad_glVertexAttribI3i = NULL; +PFNGLVERTEXATTRIBI3IVPROC glad_glVertexAttribI3iv = NULL; +PFNGLVERTEXATTRIBI3UIPROC glad_glVertexAttribI3ui = NULL; +PFNGLVERTEXATTRIBI3UIVPROC glad_glVertexAttribI3uiv = NULL; +PFNGLVERTEXATTRIBI4BVPROC glad_glVertexAttribI4bv = NULL; +PFNGLVERTEXATTRIBI4IPROC glad_glVertexAttribI4i = NULL; +PFNGLVERTEXATTRIBI4IVPROC glad_glVertexAttribI4iv = NULL; +PFNGLVERTEXATTRIBI4SVPROC glad_glVertexAttribI4sv = NULL; +PFNGLVERTEXATTRIBI4UBVPROC glad_glVertexAttribI4ubv = NULL; +PFNGLVERTEXATTRIBI4UIPROC glad_glVertexAttribI4ui = NULL; +PFNGLVERTEXATTRIBI4UIVPROC glad_glVertexAttribI4uiv = NULL; +PFNGLVERTEXATTRIBI4USVPROC glad_glVertexAttribI4usv = NULL; +PFNGLVERTEXATTRIBIPOINTERPROC glad_glVertexAttribIPointer = NULL; +PFNGLVERTEXATTRIBP1UIPROC glad_glVertexAttribP1ui = NULL; +PFNGLVERTEXATTRIBP1UIVPROC glad_glVertexAttribP1uiv = NULL; +PFNGLVERTEXATTRIBP2UIPROC glad_glVertexAttribP2ui = NULL; +PFNGLVERTEXATTRIBP2UIVPROC glad_glVertexAttribP2uiv = NULL; +PFNGLVERTEXATTRIBP3UIPROC glad_glVertexAttribP3ui = NULL; +PFNGLVERTEXATTRIBP3UIVPROC glad_glVertexAttribP3uiv = NULL; +PFNGLVERTEXATTRIBP4UIPROC glad_glVertexAttribP4ui = NULL; +PFNGLVERTEXATTRIBP4UIVPROC glad_glVertexAttribP4uiv = NULL; +PFNGLVERTEXATTRIBPOINTERPROC glad_glVertexAttribPointer = NULL; +PFNGLVERTEXP2UIPROC glad_glVertexP2ui = NULL; +PFNGLVERTEXP2UIVPROC glad_glVertexP2uiv = NULL; +PFNGLVERTEXP3UIPROC glad_glVertexP3ui = NULL; +PFNGLVERTEXP3UIVPROC glad_glVertexP3uiv = NULL; +PFNGLVERTEXP4UIPROC glad_glVertexP4ui = NULL; +PFNGLVERTEXP4UIVPROC glad_glVertexP4uiv = NULL; +PFNGLVERTEXPOINTERPROC glad_glVertexPointer = NULL; +PFNGLVIEWPORTPROC glad_glViewport = NULL; +PFNGLWAITSYNCPROC glad_glWaitSync = NULL; +PFNGLWINDOWPOS2DPROC glad_glWindowPos2d = NULL; +PFNGLWINDOWPOS2DVPROC glad_glWindowPos2dv = NULL; +PFNGLWINDOWPOS2FPROC glad_glWindowPos2f = NULL; +PFNGLWINDOWPOS2FVPROC glad_glWindowPos2fv = NULL; +PFNGLWINDOWPOS2IPROC glad_glWindowPos2i = NULL; +PFNGLWINDOWPOS2IVPROC glad_glWindowPos2iv = NULL; +PFNGLWINDOWPOS2SPROC glad_glWindowPos2s = NULL; +PFNGLWINDOWPOS2SVPROC glad_glWindowPos2sv = NULL; +PFNGLWINDOWPOS3DPROC glad_glWindowPos3d = NULL; +PFNGLWINDOWPOS3DVPROC glad_glWindowPos3dv = NULL; +PFNGLWINDOWPOS3FPROC glad_glWindowPos3f = NULL; +PFNGLWINDOWPOS3FVPROC glad_glWindowPos3fv = NULL; +PFNGLWINDOWPOS3IPROC glad_glWindowPos3i = NULL; +PFNGLWINDOWPOS3IVPROC glad_glWindowPos3iv = NULL; +PFNGLWINDOWPOS3SPROC glad_glWindowPos3s = NULL; +PFNGLWINDOWPOS3SVPROC glad_glWindowPos3sv = NULL; + + +static void glad_gl_load_GL_VERSION_1_0( GLADuserptrloadfunc load, void* userptr) { + if(!GLAD_GL_VERSION_1_0) return; + glAccum = (PFNGLACCUMPROC) load("glAccum", userptr); + glAlphaFunc = (PFNGLALPHAFUNCPROC) load("glAlphaFunc", userptr); + glBegin = (PFNGLBEGINPROC) load("glBegin", userptr); + glBitmap = (PFNGLBITMAPPROC) load("glBitmap", userptr); + glBlendFunc = (PFNGLBLENDFUNCPROC) load("glBlendFunc", userptr); + glCallList = (PFNGLCALLLISTPROC) load("glCallList", userptr); + glCallLists = (PFNGLCALLLISTSPROC) load("glCallLists", userptr); + glClear = (PFNGLCLEARPROC) load("glClear", userptr); + glClearAccum = (PFNGLCLEARACCUMPROC) load("glClearAccum", userptr); + glClearColor = (PFNGLCLEARCOLORPROC) load("glClearColor", userptr); + glClearDepth = (PFNGLCLEARDEPTHPROC) load("glClearDepth", userptr); + glClearIndex = (PFNGLCLEARINDEXPROC) load("glClearIndex", userptr); + glClearStencil = (PFNGLCLEARSTENCILPROC) load("glClearStencil", userptr); + glClipPlane = (PFNGLCLIPPLANEPROC) load("glClipPlane", userptr); + glColor3b = (PFNGLCOLOR3BPROC) load("glColor3b", userptr); + glColor3bv = (PFNGLCOLOR3BVPROC) load("glColor3bv", userptr); + glColor3d = (PFNGLCOLOR3DPROC) load("glColor3d", userptr); + glColor3dv = (PFNGLCOLOR3DVPROC) load("glColor3dv", userptr); + glColor3f = (PFNGLCOLOR3FPROC) load("glColor3f", userptr); + glColor3fv = (PFNGLCOLOR3FVPROC) load("glColor3fv", userptr); + glColor3i = (PFNGLCOLOR3IPROC) load("glColor3i", userptr); + glColor3iv = (PFNGLCOLOR3IVPROC) load("glColor3iv", userptr); + glColor3s = (PFNGLCOLOR3SPROC) load("glColor3s", userptr); + glColor3sv = (PFNGLCOLOR3SVPROC) load("glColor3sv", userptr); + glColor3ub = (PFNGLCOLOR3UBPROC) load("glColor3ub", userptr); + glColor3ubv = (PFNGLCOLOR3UBVPROC) load("glColor3ubv", userptr); + glColor3ui = (PFNGLCOLOR3UIPROC) load("glColor3ui", userptr); + glColor3uiv = (PFNGLCOLOR3UIVPROC) load("glColor3uiv", userptr); + glColor3us = (PFNGLCOLOR3USPROC) load("glColor3us", userptr); + glColor3usv = (PFNGLCOLOR3USVPROC) load("glColor3usv", userptr); + glColor4b = (PFNGLCOLOR4BPROC) load("glColor4b", userptr); + glColor4bv = (PFNGLCOLOR4BVPROC) load("glColor4bv", userptr); + glColor4d = (PFNGLCOLOR4DPROC) load("glColor4d", userptr); + glColor4dv = (PFNGLCOLOR4DVPROC) load("glColor4dv", userptr); + glColor4f = (PFNGLCOLOR4FPROC) load("glColor4f", userptr); + glColor4fv = (PFNGLCOLOR4FVPROC) load("glColor4fv", userptr); + glColor4i = (PFNGLCOLOR4IPROC) load("glColor4i", userptr); + glColor4iv = (PFNGLCOLOR4IVPROC) load("glColor4iv", userptr); + glColor4s = (PFNGLCOLOR4SPROC) load("glColor4s", userptr); + glColor4sv = (PFNGLCOLOR4SVPROC) load("glColor4sv", userptr); + glColor4ub = (PFNGLCOLOR4UBPROC) load("glColor4ub", userptr); + glColor4ubv = (PFNGLCOLOR4UBVPROC) load("glColor4ubv", userptr); + glColor4ui = (PFNGLCOLOR4UIPROC) load("glColor4ui", userptr); + glColor4uiv = (PFNGLCOLOR4UIVPROC) load("glColor4uiv", userptr); + glColor4us = (PFNGLCOLOR4USPROC) load("glColor4us", userptr); + glColor4usv = (PFNGLCOLOR4USVPROC) load("glColor4usv", userptr); + glColorMask = (PFNGLCOLORMASKPROC) load("glColorMask", userptr); + glColorMaterial = (PFNGLCOLORMATERIALPROC) load("glColorMaterial", userptr); + glCopyPixels = (PFNGLCOPYPIXELSPROC) load("glCopyPixels", userptr); + glCullFace = (PFNGLCULLFACEPROC) load("glCullFace", userptr); + glDeleteLists = (PFNGLDELETELISTSPROC) load("glDeleteLists", userptr); + glDepthFunc = (PFNGLDEPTHFUNCPROC) load("glDepthFunc", userptr); + glDepthMask = (PFNGLDEPTHMASKPROC) load("glDepthMask", userptr); + glDepthRange = (PFNGLDEPTHRANGEPROC) load("glDepthRange", userptr); + glDisable = (PFNGLDISABLEPROC) load("glDisable", userptr); + glDrawBuffer = (PFNGLDRAWBUFFERPROC) load("glDrawBuffer", userptr); + glDrawPixels = (PFNGLDRAWPIXELSPROC) load("glDrawPixels", userptr); + glEdgeFlag = (PFNGLEDGEFLAGPROC) load("glEdgeFlag", userptr); + glEdgeFlagv = (PFNGLEDGEFLAGVPROC) load("glEdgeFlagv", userptr); + glEnable = (PFNGLENABLEPROC) load("glEnable", userptr); + glEnd = (PFNGLENDPROC) load("glEnd", userptr); + glEndList = (PFNGLENDLISTPROC) load("glEndList", userptr); + glEvalCoord1d = (PFNGLEVALCOORD1DPROC) load("glEvalCoord1d", userptr); + glEvalCoord1dv = (PFNGLEVALCOORD1DVPROC) load("glEvalCoord1dv", userptr); + glEvalCoord1f = (PFNGLEVALCOORD1FPROC) load("glEvalCoord1f", userptr); + glEvalCoord1fv = (PFNGLEVALCOORD1FVPROC) load("glEvalCoord1fv", userptr); + glEvalCoord2d = (PFNGLEVALCOORD2DPROC) load("glEvalCoord2d", userptr); + glEvalCoord2dv = (PFNGLEVALCOORD2DVPROC) load("glEvalCoord2dv", userptr); + glEvalCoord2f = (PFNGLEVALCOORD2FPROC) load("glEvalCoord2f", userptr); + glEvalCoord2fv = (PFNGLEVALCOORD2FVPROC) load("glEvalCoord2fv", userptr); + glEvalMesh1 = (PFNGLEVALMESH1PROC) load("glEvalMesh1", userptr); + glEvalMesh2 = (PFNGLEVALMESH2PROC) load("glEvalMesh2", userptr); + glEvalPoint1 = (PFNGLEVALPOINT1PROC) load("glEvalPoint1", userptr); + glEvalPoint2 = (PFNGLEVALPOINT2PROC) load("glEvalPoint2", userptr); + glFeedbackBuffer = (PFNGLFEEDBACKBUFFERPROC) load("glFeedbackBuffer", userptr); + glFinish = (PFNGLFINISHPROC) load("glFinish", userptr); + glFlush = (PFNGLFLUSHPROC) load("glFlush", userptr); + glFogf = (PFNGLFOGFPROC) load("glFogf", userptr); + glFogfv = (PFNGLFOGFVPROC) load("glFogfv", userptr); + glFogi = (PFNGLFOGIPROC) load("glFogi", userptr); + glFogiv = (PFNGLFOGIVPROC) load("glFogiv", userptr); + glFrontFace = (PFNGLFRONTFACEPROC) load("glFrontFace", userptr); + glFrustum = (PFNGLFRUSTUMPROC) load("glFrustum", userptr); + glGenLists = (PFNGLGENLISTSPROC) load("glGenLists", userptr); + glGetBooleanv = (PFNGLGETBOOLEANVPROC) load("glGetBooleanv", userptr); + glGetClipPlane = (PFNGLGETCLIPPLANEPROC) load("glGetClipPlane", userptr); + glGetDoublev = (PFNGLGETDOUBLEVPROC) load("glGetDoublev", userptr); + glGetError = (PFNGLGETERRORPROC) load("glGetError", userptr); + glGetFloatv = (PFNGLGETFLOATVPROC) load("glGetFloatv", userptr); + glGetIntegerv = (PFNGLGETINTEGERVPROC) load("glGetIntegerv", userptr); + glGetLightfv = (PFNGLGETLIGHTFVPROC) load("glGetLightfv", userptr); + glGetLightiv = (PFNGLGETLIGHTIVPROC) load("glGetLightiv", userptr); + glGetMapdv = (PFNGLGETMAPDVPROC) load("glGetMapdv", userptr); + glGetMapfv = (PFNGLGETMAPFVPROC) load("glGetMapfv", userptr); + glGetMapiv = (PFNGLGETMAPIVPROC) load("glGetMapiv", userptr); + glGetMaterialfv = (PFNGLGETMATERIALFVPROC) load("glGetMaterialfv", userptr); + glGetMaterialiv = (PFNGLGETMATERIALIVPROC) load("glGetMaterialiv", userptr); + glGetPixelMapfv = (PFNGLGETPIXELMAPFVPROC) load("glGetPixelMapfv", userptr); + glGetPixelMapuiv = (PFNGLGETPIXELMAPUIVPROC) load("glGetPixelMapuiv", userptr); + glGetPixelMapusv = (PFNGLGETPIXELMAPUSVPROC) load("glGetPixelMapusv", userptr); + glGetPolygonStipple = (PFNGLGETPOLYGONSTIPPLEPROC) load("glGetPolygonStipple", userptr); + glGetString = (PFNGLGETSTRINGPROC) load("glGetString", userptr); + glGetTexEnvfv = (PFNGLGETTEXENVFVPROC) load("glGetTexEnvfv", userptr); + glGetTexEnviv = (PFNGLGETTEXENVIVPROC) load("glGetTexEnviv", userptr); + glGetTexGendv = (PFNGLGETTEXGENDVPROC) load("glGetTexGendv", userptr); + glGetTexGenfv = (PFNGLGETTEXGENFVPROC) load("glGetTexGenfv", userptr); + glGetTexGeniv = (PFNGLGETTEXGENIVPROC) load("glGetTexGeniv", userptr); + glGetTexImage = (PFNGLGETTEXIMAGEPROC) load("glGetTexImage", userptr); + glGetTexLevelParameterfv = (PFNGLGETTEXLEVELPARAMETERFVPROC) load("glGetTexLevelParameterfv", userptr); + glGetTexLevelParameteriv = (PFNGLGETTEXLEVELPARAMETERIVPROC) load("glGetTexLevelParameteriv", userptr); + glGetTexParameterfv = (PFNGLGETTEXPARAMETERFVPROC) load("glGetTexParameterfv", userptr); + glGetTexParameteriv = (PFNGLGETTEXPARAMETERIVPROC) load("glGetTexParameteriv", userptr); + glHint = (PFNGLHINTPROC) load("glHint", userptr); + glIndexMask = (PFNGLINDEXMASKPROC) load("glIndexMask", userptr); + glIndexd = (PFNGLINDEXDPROC) load("glIndexd", userptr); + glIndexdv = (PFNGLINDEXDVPROC) load("glIndexdv", userptr); + glIndexf = (PFNGLINDEXFPROC) load("glIndexf", userptr); + glIndexfv = (PFNGLINDEXFVPROC) load("glIndexfv", userptr); + glIndexi = (PFNGLINDEXIPROC) load("glIndexi", userptr); + glIndexiv = (PFNGLINDEXIVPROC) load("glIndexiv", userptr); + glIndexs = (PFNGLINDEXSPROC) load("glIndexs", userptr); + glIndexsv = (PFNGLINDEXSVPROC) load("glIndexsv", userptr); + glInitNames = (PFNGLINITNAMESPROC) load("glInitNames", userptr); + glIsEnabled = (PFNGLISENABLEDPROC) load("glIsEnabled", userptr); + glIsList = (PFNGLISLISTPROC) load("glIsList", userptr); + glLightModelf = (PFNGLLIGHTMODELFPROC) load("glLightModelf", userptr); + glLightModelfv = (PFNGLLIGHTMODELFVPROC) load("glLightModelfv", userptr); + glLightModeli = (PFNGLLIGHTMODELIPROC) load("glLightModeli", userptr); + glLightModeliv = (PFNGLLIGHTMODELIVPROC) load("glLightModeliv", userptr); + glLightf = (PFNGLLIGHTFPROC) load("glLightf", userptr); + glLightfv = (PFNGLLIGHTFVPROC) load("glLightfv", userptr); + glLighti = (PFNGLLIGHTIPROC) load("glLighti", userptr); + glLightiv = (PFNGLLIGHTIVPROC) load("glLightiv", userptr); + glLineStipple = (PFNGLLINESTIPPLEPROC) load("glLineStipple", userptr); + glLineWidth = (PFNGLLINEWIDTHPROC) load("glLineWidth", userptr); + glListBase = (PFNGLLISTBASEPROC) load("glListBase", userptr); + glLoadIdentity = (PFNGLLOADIDENTITYPROC) load("glLoadIdentity", userptr); + glLoadMatrixd = (PFNGLLOADMATRIXDPROC) load("glLoadMatrixd", userptr); + glLoadMatrixf = (PFNGLLOADMATRIXFPROC) load("glLoadMatrixf", userptr); + glLoadName = (PFNGLLOADNAMEPROC) load("glLoadName", userptr); + glLogicOp = (PFNGLLOGICOPPROC) load("glLogicOp", userptr); + glMap1d = (PFNGLMAP1DPROC) load("glMap1d", userptr); + glMap1f = (PFNGLMAP1FPROC) load("glMap1f", userptr); + glMap2d = (PFNGLMAP2DPROC) load("glMap2d", userptr); + glMap2f = (PFNGLMAP2FPROC) load("glMap2f", userptr); + glMapGrid1d = (PFNGLMAPGRID1DPROC) load("glMapGrid1d", userptr); + glMapGrid1f = (PFNGLMAPGRID1FPROC) load("glMapGrid1f", userptr); + glMapGrid2d = (PFNGLMAPGRID2DPROC) load("glMapGrid2d", userptr); + glMapGrid2f = (PFNGLMAPGRID2FPROC) load("glMapGrid2f", userptr); + glMaterialf = (PFNGLMATERIALFPROC) load("glMaterialf", userptr); + glMaterialfv = (PFNGLMATERIALFVPROC) load("glMaterialfv", userptr); + glMateriali = (PFNGLMATERIALIPROC) load("glMateriali", userptr); + glMaterialiv = (PFNGLMATERIALIVPROC) load("glMaterialiv", userptr); + glMatrixMode = (PFNGLMATRIXMODEPROC) load("glMatrixMode", userptr); + glMultMatrixd = (PFNGLMULTMATRIXDPROC) load("glMultMatrixd", userptr); + glMultMatrixf = (PFNGLMULTMATRIXFPROC) load("glMultMatrixf", userptr); + glNewList = (PFNGLNEWLISTPROC) load("glNewList", userptr); + glNormal3b = (PFNGLNORMAL3BPROC) load("glNormal3b", userptr); + glNormal3bv = (PFNGLNORMAL3BVPROC) load("glNormal3bv", userptr); + glNormal3d = (PFNGLNORMAL3DPROC) load("glNormal3d", userptr); + glNormal3dv = (PFNGLNORMAL3DVPROC) load("glNormal3dv", userptr); + glNormal3f = (PFNGLNORMAL3FPROC) load("glNormal3f", userptr); + glNormal3fv = (PFNGLNORMAL3FVPROC) load("glNormal3fv", userptr); + glNormal3i = (PFNGLNORMAL3IPROC) load("glNormal3i", userptr); + glNormal3iv = (PFNGLNORMAL3IVPROC) load("glNormal3iv", userptr); + glNormal3s = (PFNGLNORMAL3SPROC) load("glNormal3s", userptr); + glNormal3sv = (PFNGLNORMAL3SVPROC) load("glNormal3sv", userptr); + glOrtho = (PFNGLORTHOPROC) load("glOrtho", userptr); + glPassThrough = (PFNGLPASSTHROUGHPROC) load("glPassThrough", userptr); + glPixelMapfv = (PFNGLPIXELMAPFVPROC) load("glPixelMapfv", userptr); + glPixelMapuiv = (PFNGLPIXELMAPUIVPROC) load("glPixelMapuiv", userptr); + glPixelMapusv = (PFNGLPIXELMAPUSVPROC) load("glPixelMapusv", userptr); + glPixelStoref = (PFNGLPIXELSTOREFPROC) load("glPixelStoref", userptr); + glPixelStorei = (PFNGLPIXELSTOREIPROC) load("glPixelStorei", userptr); + glPixelTransferf = (PFNGLPIXELTRANSFERFPROC) load("glPixelTransferf", userptr); + glPixelTransferi = (PFNGLPIXELTRANSFERIPROC) load("glPixelTransferi", userptr); + glPixelZoom = (PFNGLPIXELZOOMPROC) load("glPixelZoom", userptr); + glPointSize = (PFNGLPOINTSIZEPROC) load("glPointSize", userptr); + glPolygonMode = (PFNGLPOLYGONMODEPROC) load("glPolygonMode", userptr); + glPolygonStipple = (PFNGLPOLYGONSTIPPLEPROC) load("glPolygonStipple", userptr); + glPopAttrib = (PFNGLPOPATTRIBPROC) load("glPopAttrib", userptr); + glPopMatrix = (PFNGLPOPMATRIXPROC) load("glPopMatrix", userptr); + glPopName = (PFNGLPOPNAMEPROC) load("glPopName", userptr); + glPushAttrib = (PFNGLPUSHATTRIBPROC) load("glPushAttrib", userptr); + glPushMatrix = (PFNGLPUSHMATRIXPROC) load("glPushMatrix", userptr); + glPushName = (PFNGLPUSHNAMEPROC) load("glPushName", userptr); + glRasterPos2d = (PFNGLRASTERPOS2DPROC) load("glRasterPos2d", userptr); + glRasterPos2dv = (PFNGLRASTERPOS2DVPROC) load("glRasterPos2dv", userptr); + glRasterPos2f = (PFNGLRASTERPOS2FPROC) load("glRasterPos2f", userptr); + glRasterPos2fv = (PFNGLRASTERPOS2FVPROC) load("glRasterPos2fv", userptr); + glRasterPos2i = (PFNGLRASTERPOS2IPROC) load("glRasterPos2i", userptr); + glRasterPos2iv = (PFNGLRASTERPOS2IVPROC) load("glRasterPos2iv", userptr); + glRasterPos2s = (PFNGLRASTERPOS2SPROC) load("glRasterPos2s", userptr); + glRasterPos2sv = (PFNGLRASTERPOS2SVPROC) load("glRasterPos2sv", userptr); + glRasterPos3d = (PFNGLRASTERPOS3DPROC) load("glRasterPos3d", userptr); + glRasterPos3dv = (PFNGLRASTERPOS3DVPROC) load("glRasterPos3dv", userptr); + glRasterPos3f = (PFNGLRASTERPOS3FPROC) load("glRasterPos3f", userptr); + glRasterPos3fv = (PFNGLRASTERPOS3FVPROC) load("glRasterPos3fv", userptr); + glRasterPos3i = (PFNGLRASTERPOS3IPROC) load("glRasterPos3i", userptr); + glRasterPos3iv = (PFNGLRASTERPOS3IVPROC) load("glRasterPos3iv", userptr); + glRasterPos3s = (PFNGLRASTERPOS3SPROC) load("glRasterPos3s", userptr); + glRasterPos3sv = (PFNGLRASTERPOS3SVPROC) load("glRasterPos3sv", userptr); + glRasterPos4d = (PFNGLRASTERPOS4DPROC) load("glRasterPos4d", userptr); + glRasterPos4dv = (PFNGLRASTERPOS4DVPROC) load("glRasterPos4dv", userptr); + glRasterPos4f = (PFNGLRASTERPOS4FPROC) load("glRasterPos4f", userptr); + glRasterPos4fv = (PFNGLRASTERPOS4FVPROC) load("glRasterPos4fv", userptr); + glRasterPos4i = (PFNGLRASTERPOS4IPROC) load("glRasterPos4i", userptr); + glRasterPos4iv = (PFNGLRASTERPOS4IVPROC) load("glRasterPos4iv", userptr); + glRasterPos4s = (PFNGLRASTERPOS4SPROC) load("glRasterPos4s", userptr); + glRasterPos4sv = (PFNGLRASTERPOS4SVPROC) load("glRasterPos4sv", userptr); + glReadBuffer = (PFNGLREADBUFFERPROC) load("glReadBuffer", userptr); + glReadPixels = (PFNGLREADPIXELSPROC) load("glReadPixels", userptr); + glRectd = (PFNGLRECTDPROC) load("glRectd", userptr); + glRectdv = (PFNGLRECTDVPROC) load("glRectdv", userptr); + glRectf = (PFNGLRECTFPROC) load("glRectf", userptr); + glRectfv = (PFNGLRECTFVPROC) load("glRectfv", userptr); + glRecti = (PFNGLRECTIPROC) load("glRecti", userptr); + glRectiv = (PFNGLRECTIVPROC) load("glRectiv", userptr); + glRects = (PFNGLRECTSPROC) load("glRects", userptr); + glRectsv = (PFNGLRECTSVPROC) load("glRectsv", userptr); + glRenderMode = (PFNGLRENDERMODEPROC) load("glRenderMode", userptr); + glRotated = (PFNGLROTATEDPROC) load("glRotated", userptr); + glRotatef = (PFNGLROTATEFPROC) load("glRotatef", userptr); + glScaled = (PFNGLSCALEDPROC) load("glScaled", userptr); + glScalef = (PFNGLSCALEFPROC) load("glScalef", userptr); + glScissor = (PFNGLSCISSORPROC) load("glScissor", userptr); + glSelectBuffer = (PFNGLSELECTBUFFERPROC) load("glSelectBuffer", userptr); + glShadeModel = (PFNGLSHADEMODELPROC) load("glShadeModel", userptr); + glStencilFunc = (PFNGLSTENCILFUNCPROC) load("glStencilFunc", userptr); + glStencilMask = (PFNGLSTENCILMASKPROC) load("glStencilMask", userptr); + glStencilOp = (PFNGLSTENCILOPPROC) load("glStencilOp", userptr); + glTexCoord1d = (PFNGLTEXCOORD1DPROC) load("glTexCoord1d", userptr); + glTexCoord1dv = (PFNGLTEXCOORD1DVPROC) load("glTexCoord1dv", userptr); + glTexCoord1f = (PFNGLTEXCOORD1FPROC) load("glTexCoord1f", userptr); + glTexCoord1fv = (PFNGLTEXCOORD1FVPROC) load("glTexCoord1fv", userptr); + glTexCoord1i = (PFNGLTEXCOORD1IPROC) load("glTexCoord1i", userptr); + glTexCoord1iv = (PFNGLTEXCOORD1IVPROC) load("glTexCoord1iv", userptr); + glTexCoord1s = (PFNGLTEXCOORD1SPROC) load("glTexCoord1s", userptr); + glTexCoord1sv = (PFNGLTEXCOORD1SVPROC) load("glTexCoord1sv", userptr); + glTexCoord2d = (PFNGLTEXCOORD2DPROC) load("glTexCoord2d", userptr); + glTexCoord2dv = (PFNGLTEXCOORD2DVPROC) load("glTexCoord2dv", userptr); + glTexCoord2f = (PFNGLTEXCOORD2FPROC) load("glTexCoord2f", userptr); + glTexCoord2fv = (PFNGLTEXCOORD2FVPROC) load("glTexCoord2fv", userptr); + glTexCoord2i = (PFNGLTEXCOORD2IPROC) load("glTexCoord2i", userptr); + glTexCoord2iv = (PFNGLTEXCOORD2IVPROC) load("glTexCoord2iv", userptr); + glTexCoord2s = (PFNGLTEXCOORD2SPROC) load("glTexCoord2s", userptr); + glTexCoord2sv = (PFNGLTEXCOORD2SVPROC) load("glTexCoord2sv", userptr); + glTexCoord3d = (PFNGLTEXCOORD3DPROC) load("glTexCoord3d", userptr); + glTexCoord3dv = (PFNGLTEXCOORD3DVPROC) load("glTexCoord3dv", userptr); + glTexCoord3f = (PFNGLTEXCOORD3FPROC) load("glTexCoord3f", userptr); + glTexCoord3fv = (PFNGLTEXCOORD3FVPROC) load("glTexCoord3fv", userptr); + glTexCoord3i = (PFNGLTEXCOORD3IPROC) load("glTexCoord3i", userptr); + glTexCoord3iv = (PFNGLTEXCOORD3IVPROC) load("glTexCoord3iv", userptr); + glTexCoord3s = (PFNGLTEXCOORD3SPROC) load("glTexCoord3s", userptr); + glTexCoord3sv = (PFNGLTEXCOORD3SVPROC) load("glTexCoord3sv", userptr); + glTexCoord4d = (PFNGLTEXCOORD4DPROC) load("glTexCoord4d", userptr); + glTexCoord4dv = (PFNGLTEXCOORD4DVPROC) load("glTexCoord4dv", userptr); + glTexCoord4f = (PFNGLTEXCOORD4FPROC) load("glTexCoord4f", userptr); + glTexCoord4fv = (PFNGLTEXCOORD4FVPROC) load("glTexCoord4fv", userptr); + glTexCoord4i = (PFNGLTEXCOORD4IPROC) load("glTexCoord4i", userptr); + glTexCoord4iv = (PFNGLTEXCOORD4IVPROC) load("glTexCoord4iv", userptr); + glTexCoord4s = (PFNGLTEXCOORD4SPROC) load("glTexCoord4s", userptr); + glTexCoord4sv = (PFNGLTEXCOORD4SVPROC) load("glTexCoord4sv", userptr); + glTexEnvf = (PFNGLTEXENVFPROC) load("glTexEnvf", userptr); + glTexEnvfv = (PFNGLTEXENVFVPROC) load("glTexEnvfv", userptr); + glTexEnvi = (PFNGLTEXENVIPROC) load("glTexEnvi", userptr); + glTexEnviv = (PFNGLTEXENVIVPROC) load("glTexEnviv", userptr); + glTexGend = (PFNGLTEXGENDPROC) load("glTexGend", userptr); + glTexGendv = (PFNGLTEXGENDVPROC) load("glTexGendv", userptr); + glTexGenf = (PFNGLTEXGENFPROC) load("glTexGenf", userptr); + glTexGenfv = (PFNGLTEXGENFVPROC) load("glTexGenfv", userptr); + glTexGeni = (PFNGLTEXGENIPROC) load("glTexGeni", userptr); + glTexGeniv = (PFNGLTEXGENIVPROC) load("glTexGeniv", userptr); + glTexImage1D = (PFNGLTEXIMAGE1DPROC) load("glTexImage1D", userptr); + glTexImage2D = (PFNGLTEXIMAGE2DPROC) load("glTexImage2D", userptr); + glTexParameterf = (PFNGLTEXPARAMETERFPROC) load("glTexParameterf", userptr); + glTexParameterfv = (PFNGLTEXPARAMETERFVPROC) load("glTexParameterfv", userptr); + glTexParameteri = (PFNGLTEXPARAMETERIPROC) load("glTexParameteri", userptr); + glTexParameteriv = (PFNGLTEXPARAMETERIVPROC) load("glTexParameteriv", userptr); + glTranslated = (PFNGLTRANSLATEDPROC) load("glTranslated", userptr); + glTranslatef = (PFNGLTRANSLATEFPROC) load("glTranslatef", userptr); + glVertex2d = (PFNGLVERTEX2DPROC) load("glVertex2d", userptr); + glVertex2dv = (PFNGLVERTEX2DVPROC) load("glVertex2dv", userptr); + glVertex2f = (PFNGLVERTEX2FPROC) load("glVertex2f", userptr); + glVertex2fv = (PFNGLVERTEX2FVPROC) load("glVertex2fv", userptr); + glVertex2i = (PFNGLVERTEX2IPROC) load("glVertex2i", userptr); + glVertex2iv = (PFNGLVERTEX2IVPROC) load("glVertex2iv", userptr); + glVertex2s = (PFNGLVERTEX2SPROC) load("glVertex2s", userptr); + glVertex2sv = (PFNGLVERTEX2SVPROC) load("glVertex2sv", userptr); + glVertex3d = (PFNGLVERTEX3DPROC) load("glVertex3d", userptr); + glVertex3dv = (PFNGLVERTEX3DVPROC) load("glVertex3dv", userptr); + glVertex3f = (PFNGLVERTEX3FPROC) load("glVertex3f", userptr); + glVertex3fv = (PFNGLVERTEX3FVPROC) load("glVertex3fv", userptr); + glVertex3i = (PFNGLVERTEX3IPROC) load("glVertex3i", userptr); + glVertex3iv = (PFNGLVERTEX3IVPROC) load("glVertex3iv", userptr); + glVertex3s = (PFNGLVERTEX3SPROC) load("glVertex3s", userptr); + glVertex3sv = (PFNGLVERTEX3SVPROC) load("glVertex3sv", userptr); + glVertex4d = (PFNGLVERTEX4DPROC) load("glVertex4d", userptr); + glVertex4dv = (PFNGLVERTEX4DVPROC) load("glVertex4dv", userptr); + glVertex4f = (PFNGLVERTEX4FPROC) load("glVertex4f", userptr); + glVertex4fv = (PFNGLVERTEX4FVPROC) load("glVertex4fv", userptr); + glVertex4i = (PFNGLVERTEX4IPROC) load("glVertex4i", userptr); + glVertex4iv = (PFNGLVERTEX4IVPROC) load("glVertex4iv", userptr); + glVertex4s = (PFNGLVERTEX4SPROC) load("glVertex4s", userptr); + glVertex4sv = (PFNGLVERTEX4SVPROC) load("glVertex4sv", userptr); + glViewport = (PFNGLVIEWPORTPROC) load("glViewport", userptr); +} +static void glad_gl_load_GL_VERSION_1_1( GLADuserptrloadfunc load, void* userptr) { + if(!GLAD_GL_VERSION_1_1) return; + glAreTexturesResident = (PFNGLARETEXTURESRESIDENTPROC) load("glAreTexturesResident", userptr); + glArrayElement = (PFNGLARRAYELEMENTPROC) load("glArrayElement", userptr); + glBindTexture = (PFNGLBINDTEXTUREPROC) load("glBindTexture", userptr); + glColorPointer = (PFNGLCOLORPOINTERPROC) load("glColorPointer", userptr); + glCopyTexImage1D = (PFNGLCOPYTEXIMAGE1DPROC) load("glCopyTexImage1D", userptr); + glCopyTexImage2D = (PFNGLCOPYTEXIMAGE2DPROC) load("glCopyTexImage2D", userptr); + glCopyTexSubImage1D = (PFNGLCOPYTEXSUBIMAGE1DPROC) load("glCopyTexSubImage1D", userptr); + glCopyTexSubImage2D = (PFNGLCOPYTEXSUBIMAGE2DPROC) load("glCopyTexSubImage2D", userptr); + glDeleteTextures = (PFNGLDELETETEXTURESPROC) load("glDeleteTextures", userptr); + glDisableClientState = (PFNGLDISABLECLIENTSTATEPROC) load("glDisableClientState", userptr); + glDrawArrays = (PFNGLDRAWARRAYSPROC) load("glDrawArrays", userptr); + glDrawElements = (PFNGLDRAWELEMENTSPROC) load("glDrawElements", userptr); + glEdgeFlagPointer = (PFNGLEDGEFLAGPOINTERPROC) load("glEdgeFlagPointer", userptr); + glEnableClientState = (PFNGLENABLECLIENTSTATEPROC) load("glEnableClientState", userptr); + glGenTextures = (PFNGLGENTEXTURESPROC) load("glGenTextures", userptr); + glGetPointerv = (PFNGLGETPOINTERVPROC) load("glGetPointerv", userptr); + glIndexPointer = (PFNGLINDEXPOINTERPROC) load("glIndexPointer", userptr); + glIndexub = (PFNGLINDEXUBPROC) load("glIndexub", userptr); + glIndexubv = (PFNGLINDEXUBVPROC) load("glIndexubv", userptr); + glInterleavedArrays = (PFNGLINTERLEAVEDARRAYSPROC) load("glInterleavedArrays", userptr); + glIsTexture = (PFNGLISTEXTUREPROC) load("glIsTexture", userptr); + glNormalPointer = (PFNGLNORMALPOINTERPROC) load("glNormalPointer", userptr); + glPolygonOffset = (PFNGLPOLYGONOFFSETPROC) load("glPolygonOffset", userptr); + glPopClientAttrib = (PFNGLPOPCLIENTATTRIBPROC) load("glPopClientAttrib", userptr); + glPrioritizeTextures = (PFNGLPRIORITIZETEXTURESPROC) load("glPrioritizeTextures", userptr); + glPushClientAttrib = (PFNGLPUSHCLIENTATTRIBPROC) load("glPushClientAttrib", userptr); + glTexCoordPointer = (PFNGLTEXCOORDPOINTERPROC) load("glTexCoordPointer", userptr); + glTexSubImage1D = (PFNGLTEXSUBIMAGE1DPROC) load("glTexSubImage1D", userptr); + glTexSubImage2D = (PFNGLTEXSUBIMAGE2DPROC) load("glTexSubImage2D", userptr); + glVertexPointer = (PFNGLVERTEXPOINTERPROC) load("glVertexPointer", userptr); +} +static void glad_gl_load_GL_VERSION_1_2( GLADuserptrloadfunc load, void* userptr) { + if(!GLAD_GL_VERSION_1_2) return; + glCopyTexSubImage3D = (PFNGLCOPYTEXSUBIMAGE3DPROC) load("glCopyTexSubImage3D", userptr); + glDrawRangeElements = (PFNGLDRAWRANGEELEMENTSPROC) load("glDrawRangeElements", userptr); + glTexImage3D = (PFNGLTEXIMAGE3DPROC) load("glTexImage3D", userptr); + glTexSubImage3D = (PFNGLTEXSUBIMAGE3DPROC) load("glTexSubImage3D", userptr); +} +static void glad_gl_load_GL_VERSION_1_3( GLADuserptrloadfunc load, void* userptr) { + if(!GLAD_GL_VERSION_1_3) return; + glActiveTexture = (PFNGLACTIVETEXTUREPROC) load("glActiveTexture", userptr); + glClientActiveTexture = (PFNGLCLIENTACTIVETEXTUREPROC) load("glClientActiveTexture", userptr); + glCompressedTexImage1D = (PFNGLCOMPRESSEDTEXIMAGE1DPROC) load("glCompressedTexImage1D", userptr); + glCompressedTexImage2D = (PFNGLCOMPRESSEDTEXIMAGE2DPROC) load("glCompressedTexImage2D", userptr); + glCompressedTexImage3D = (PFNGLCOMPRESSEDTEXIMAGE3DPROC) load("glCompressedTexImage3D", userptr); + glCompressedTexSubImage1D = (PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC) load("glCompressedTexSubImage1D", userptr); + glCompressedTexSubImage2D = (PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC) load("glCompressedTexSubImage2D", userptr); + glCompressedTexSubImage3D = (PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC) load("glCompressedTexSubImage3D", userptr); + glGetCompressedTexImage = (PFNGLGETCOMPRESSEDTEXIMAGEPROC) load("glGetCompressedTexImage", userptr); + glLoadTransposeMatrixd = (PFNGLLOADTRANSPOSEMATRIXDPROC) load("glLoadTransposeMatrixd", userptr); + glLoadTransposeMatrixf = (PFNGLLOADTRANSPOSEMATRIXFPROC) load("glLoadTransposeMatrixf", userptr); + glMultTransposeMatrixd = (PFNGLMULTTRANSPOSEMATRIXDPROC) load("glMultTransposeMatrixd", userptr); + glMultTransposeMatrixf = (PFNGLMULTTRANSPOSEMATRIXFPROC) load("glMultTransposeMatrixf", userptr); + glMultiTexCoord1d = (PFNGLMULTITEXCOORD1DPROC) load("glMultiTexCoord1d", userptr); + glMultiTexCoord1dv = (PFNGLMULTITEXCOORD1DVPROC) load("glMultiTexCoord1dv", userptr); + glMultiTexCoord1f = (PFNGLMULTITEXCOORD1FPROC) load("glMultiTexCoord1f", userptr); + glMultiTexCoord1fv = (PFNGLMULTITEXCOORD1FVPROC) load("glMultiTexCoord1fv", userptr); + glMultiTexCoord1i = (PFNGLMULTITEXCOORD1IPROC) load("glMultiTexCoord1i", userptr); + glMultiTexCoord1iv = (PFNGLMULTITEXCOORD1IVPROC) load("glMultiTexCoord1iv", userptr); + glMultiTexCoord1s = (PFNGLMULTITEXCOORD1SPROC) load("glMultiTexCoord1s", userptr); + glMultiTexCoord1sv = (PFNGLMULTITEXCOORD1SVPROC) load("glMultiTexCoord1sv", userptr); + glMultiTexCoord2d = (PFNGLMULTITEXCOORD2DPROC) load("glMultiTexCoord2d", userptr); + glMultiTexCoord2dv = (PFNGLMULTITEXCOORD2DVPROC) load("glMultiTexCoord2dv", userptr); + glMultiTexCoord2f = (PFNGLMULTITEXCOORD2FPROC) load("glMultiTexCoord2f", userptr); + glMultiTexCoord2fv = (PFNGLMULTITEXCOORD2FVPROC) load("glMultiTexCoord2fv", userptr); + glMultiTexCoord2i = (PFNGLMULTITEXCOORD2IPROC) load("glMultiTexCoord2i", userptr); + glMultiTexCoord2iv = (PFNGLMULTITEXCOORD2IVPROC) load("glMultiTexCoord2iv", userptr); + glMultiTexCoord2s = (PFNGLMULTITEXCOORD2SPROC) load("glMultiTexCoord2s", userptr); + glMultiTexCoord2sv = (PFNGLMULTITEXCOORD2SVPROC) load("glMultiTexCoord2sv", userptr); + glMultiTexCoord3d = (PFNGLMULTITEXCOORD3DPROC) load("glMultiTexCoord3d", userptr); + glMultiTexCoord3dv = (PFNGLMULTITEXCOORD3DVPROC) load("glMultiTexCoord3dv", userptr); + glMultiTexCoord3f = (PFNGLMULTITEXCOORD3FPROC) load("glMultiTexCoord3f", userptr); + glMultiTexCoord3fv = (PFNGLMULTITEXCOORD3FVPROC) load("glMultiTexCoord3fv", userptr); + glMultiTexCoord3i = (PFNGLMULTITEXCOORD3IPROC) load("glMultiTexCoord3i", userptr); + glMultiTexCoord3iv = (PFNGLMULTITEXCOORD3IVPROC) load("glMultiTexCoord3iv", userptr); + glMultiTexCoord3s = (PFNGLMULTITEXCOORD3SPROC) load("glMultiTexCoord3s", userptr); + glMultiTexCoord3sv = (PFNGLMULTITEXCOORD3SVPROC) load("glMultiTexCoord3sv", userptr); + glMultiTexCoord4d = (PFNGLMULTITEXCOORD4DPROC) load("glMultiTexCoord4d", userptr); + glMultiTexCoord4dv = (PFNGLMULTITEXCOORD4DVPROC) load("glMultiTexCoord4dv", userptr); + glMultiTexCoord4f = (PFNGLMULTITEXCOORD4FPROC) load("glMultiTexCoord4f", userptr); + glMultiTexCoord4fv = (PFNGLMULTITEXCOORD4FVPROC) load("glMultiTexCoord4fv", userptr); + glMultiTexCoord4i = (PFNGLMULTITEXCOORD4IPROC) load("glMultiTexCoord4i", userptr); + glMultiTexCoord4iv = (PFNGLMULTITEXCOORD4IVPROC) load("glMultiTexCoord4iv", userptr); + glMultiTexCoord4s = (PFNGLMULTITEXCOORD4SPROC) load("glMultiTexCoord4s", userptr); + glMultiTexCoord4sv = (PFNGLMULTITEXCOORD4SVPROC) load("glMultiTexCoord4sv", userptr); + glSampleCoverage = (PFNGLSAMPLECOVERAGEPROC) load("glSampleCoverage", userptr); +} +static void glad_gl_load_GL_VERSION_1_4( GLADuserptrloadfunc load, void* userptr) { + if(!GLAD_GL_VERSION_1_4) return; + glBlendColor = (PFNGLBLENDCOLORPROC) load("glBlendColor", userptr); + glBlendEquation = (PFNGLBLENDEQUATIONPROC) load("glBlendEquation", userptr); + glBlendFuncSeparate = (PFNGLBLENDFUNCSEPARATEPROC) load("glBlendFuncSeparate", userptr); + glFogCoordPointer = (PFNGLFOGCOORDPOINTERPROC) load("glFogCoordPointer", userptr); + glFogCoordd = (PFNGLFOGCOORDDPROC) load("glFogCoordd", userptr); + glFogCoorddv = (PFNGLFOGCOORDDVPROC) load("glFogCoorddv", userptr); + glFogCoordf = (PFNGLFOGCOORDFPROC) load("glFogCoordf", userptr); + glFogCoordfv = (PFNGLFOGCOORDFVPROC) load("glFogCoordfv", userptr); + glMultiDrawArrays = (PFNGLMULTIDRAWARRAYSPROC) load("glMultiDrawArrays", userptr); + glMultiDrawElements = (PFNGLMULTIDRAWELEMENTSPROC) load("glMultiDrawElements", userptr); + glPointParameterf = (PFNGLPOINTPARAMETERFPROC) load("glPointParameterf", userptr); + glPointParameterfv = (PFNGLPOINTPARAMETERFVPROC) load("glPointParameterfv", userptr); + glPointParameteri = (PFNGLPOINTPARAMETERIPROC) load("glPointParameteri", userptr); + glPointParameteriv = (PFNGLPOINTPARAMETERIVPROC) load("glPointParameteriv", userptr); + glSecondaryColor3b = (PFNGLSECONDARYCOLOR3BPROC) load("glSecondaryColor3b", userptr); + glSecondaryColor3bv = (PFNGLSECONDARYCOLOR3BVPROC) load("glSecondaryColor3bv", userptr); + glSecondaryColor3d = (PFNGLSECONDARYCOLOR3DPROC) load("glSecondaryColor3d", userptr); + glSecondaryColor3dv = (PFNGLSECONDARYCOLOR3DVPROC) load("glSecondaryColor3dv", userptr); + glSecondaryColor3f = (PFNGLSECONDARYCOLOR3FPROC) load("glSecondaryColor3f", userptr); + glSecondaryColor3fv = (PFNGLSECONDARYCOLOR3FVPROC) load("glSecondaryColor3fv", userptr); + glSecondaryColor3i = (PFNGLSECONDARYCOLOR3IPROC) load("glSecondaryColor3i", userptr); + glSecondaryColor3iv = (PFNGLSECONDARYCOLOR3IVPROC) load("glSecondaryColor3iv", userptr); + glSecondaryColor3s = (PFNGLSECONDARYCOLOR3SPROC) load("glSecondaryColor3s", userptr); + glSecondaryColor3sv = (PFNGLSECONDARYCOLOR3SVPROC) load("glSecondaryColor3sv", userptr); + glSecondaryColor3ub = (PFNGLSECONDARYCOLOR3UBPROC) load("glSecondaryColor3ub", userptr); + glSecondaryColor3ubv = (PFNGLSECONDARYCOLOR3UBVPROC) load("glSecondaryColor3ubv", userptr); + glSecondaryColor3ui = (PFNGLSECONDARYCOLOR3UIPROC) load("glSecondaryColor3ui", userptr); + glSecondaryColor3uiv = (PFNGLSECONDARYCOLOR3UIVPROC) load("glSecondaryColor3uiv", userptr); + glSecondaryColor3us = (PFNGLSECONDARYCOLOR3USPROC) load("glSecondaryColor3us", userptr); + glSecondaryColor3usv = (PFNGLSECONDARYCOLOR3USVPROC) load("glSecondaryColor3usv", userptr); + glSecondaryColorPointer = (PFNGLSECONDARYCOLORPOINTERPROC) load("glSecondaryColorPointer", userptr); + glWindowPos2d = (PFNGLWINDOWPOS2DPROC) load("glWindowPos2d", userptr); + glWindowPos2dv = (PFNGLWINDOWPOS2DVPROC) load("glWindowPos2dv", userptr); + glWindowPos2f = (PFNGLWINDOWPOS2FPROC) load("glWindowPos2f", userptr); + glWindowPos2fv = (PFNGLWINDOWPOS2FVPROC) load("glWindowPos2fv", userptr); + glWindowPos2i = (PFNGLWINDOWPOS2IPROC) load("glWindowPos2i", userptr); + glWindowPos2iv = (PFNGLWINDOWPOS2IVPROC) load("glWindowPos2iv", userptr); + glWindowPos2s = (PFNGLWINDOWPOS2SPROC) load("glWindowPos2s", userptr); + glWindowPos2sv = (PFNGLWINDOWPOS2SVPROC) load("glWindowPos2sv", userptr); + glWindowPos3d = (PFNGLWINDOWPOS3DPROC) load("glWindowPos3d", userptr); + glWindowPos3dv = (PFNGLWINDOWPOS3DVPROC) load("glWindowPos3dv", userptr); + glWindowPos3f = (PFNGLWINDOWPOS3FPROC) load("glWindowPos3f", userptr); + glWindowPos3fv = (PFNGLWINDOWPOS3FVPROC) load("glWindowPos3fv", userptr); + glWindowPos3i = (PFNGLWINDOWPOS3IPROC) load("glWindowPos3i", userptr); + glWindowPos3iv = (PFNGLWINDOWPOS3IVPROC) load("glWindowPos3iv", userptr); + glWindowPos3s = (PFNGLWINDOWPOS3SPROC) load("glWindowPos3s", userptr); + glWindowPos3sv = (PFNGLWINDOWPOS3SVPROC) load("glWindowPos3sv", userptr); +} +static void glad_gl_load_GL_VERSION_1_5( GLADuserptrloadfunc load, void* userptr) { + if(!GLAD_GL_VERSION_1_5) return; + glBeginQuery = (PFNGLBEGINQUERYPROC) load("glBeginQuery", userptr); + glBindBuffer = (PFNGLBINDBUFFERPROC) load("glBindBuffer", userptr); + glBufferData = (PFNGLBUFFERDATAPROC) load("glBufferData", userptr); + glBufferSubData = (PFNGLBUFFERSUBDATAPROC) load("glBufferSubData", userptr); + glDeleteBuffers = (PFNGLDELETEBUFFERSPROC) load("glDeleteBuffers", userptr); + glDeleteQueries = (PFNGLDELETEQUERIESPROC) load("glDeleteQueries", userptr); + glEndQuery = (PFNGLENDQUERYPROC) load("glEndQuery", userptr); + glGenBuffers = (PFNGLGENBUFFERSPROC) load("glGenBuffers", userptr); + glGenQueries = (PFNGLGENQUERIESPROC) load("glGenQueries", userptr); + glGetBufferParameteriv = (PFNGLGETBUFFERPARAMETERIVPROC) load("glGetBufferParameteriv", userptr); + glGetBufferPointerv = (PFNGLGETBUFFERPOINTERVPROC) load("glGetBufferPointerv", userptr); + glGetBufferSubData = (PFNGLGETBUFFERSUBDATAPROC) load("glGetBufferSubData", userptr); + glGetQueryObjectiv = (PFNGLGETQUERYOBJECTIVPROC) load("glGetQueryObjectiv", userptr); + glGetQueryObjectuiv = (PFNGLGETQUERYOBJECTUIVPROC) load("glGetQueryObjectuiv", userptr); + glGetQueryiv = (PFNGLGETQUERYIVPROC) load("glGetQueryiv", userptr); + glIsBuffer = (PFNGLISBUFFERPROC) load("glIsBuffer", userptr); + glIsQuery = (PFNGLISQUERYPROC) load("glIsQuery", userptr); + glMapBuffer = (PFNGLMAPBUFFERPROC) load("glMapBuffer", userptr); + glUnmapBuffer = (PFNGLUNMAPBUFFERPROC) load("glUnmapBuffer", userptr); +} +static void glad_gl_load_GL_VERSION_2_0( GLADuserptrloadfunc load, void* userptr) { + if(!GLAD_GL_VERSION_2_0) return; + glAttachShader = (PFNGLATTACHSHADERPROC) load("glAttachShader", userptr); + glBindAttribLocation = (PFNGLBINDATTRIBLOCATIONPROC) load("glBindAttribLocation", userptr); + glBlendEquationSeparate = (PFNGLBLENDEQUATIONSEPARATEPROC) load("glBlendEquationSeparate", userptr); + glCompileShader = (PFNGLCOMPILESHADERPROC) load("glCompileShader", userptr); + glCreateProgram = (PFNGLCREATEPROGRAMPROC) load("glCreateProgram", userptr); + glCreateShader = (PFNGLCREATESHADERPROC) load("glCreateShader", userptr); + glDeleteProgram = (PFNGLDELETEPROGRAMPROC) load("glDeleteProgram", userptr); + glDeleteShader = (PFNGLDELETESHADERPROC) load("glDeleteShader", userptr); + glDetachShader = (PFNGLDETACHSHADERPROC) load("glDetachShader", userptr); + glDisableVertexAttribArray = (PFNGLDISABLEVERTEXATTRIBARRAYPROC) load("glDisableVertexAttribArray", userptr); + glDrawBuffers = (PFNGLDRAWBUFFERSPROC) load("glDrawBuffers", userptr); + glEnableVertexAttribArray = (PFNGLENABLEVERTEXATTRIBARRAYPROC) load("glEnableVertexAttribArray", userptr); + glGetActiveAttrib = (PFNGLGETACTIVEATTRIBPROC) load("glGetActiveAttrib", userptr); + glGetActiveUniform = (PFNGLGETACTIVEUNIFORMPROC) load("glGetActiveUniform", userptr); + glGetAttachedShaders = (PFNGLGETATTACHEDSHADERSPROC) load("glGetAttachedShaders", userptr); + glGetAttribLocation = (PFNGLGETATTRIBLOCATIONPROC) load("glGetAttribLocation", userptr); + glGetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC) load("glGetProgramInfoLog", userptr); + glGetProgramiv = (PFNGLGETPROGRAMIVPROC) load("glGetProgramiv", userptr); + glGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC) load("glGetShaderInfoLog", userptr); + glGetShaderSource = (PFNGLGETSHADERSOURCEPROC) load("glGetShaderSource", userptr); + glGetShaderiv = (PFNGLGETSHADERIVPROC) load("glGetShaderiv", userptr); + glGetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC) load("glGetUniformLocation", userptr); + glGetUniformfv = (PFNGLGETUNIFORMFVPROC) load("glGetUniformfv", userptr); + glGetUniformiv = (PFNGLGETUNIFORMIVPROC) load("glGetUniformiv", userptr); + glGetVertexAttribPointerv = (PFNGLGETVERTEXATTRIBPOINTERVPROC) load("glGetVertexAttribPointerv", userptr); + glGetVertexAttribdv = (PFNGLGETVERTEXATTRIBDVPROC) load("glGetVertexAttribdv", userptr); + glGetVertexAttribfv = (PFNGLGETVERTEXATTRIBFVPROC) load("glGetVertexAttribfv", userptr); + glGetVertexAttribiv = (PFNGLGETVERTEXATTRIBIVPROC) load("glGetVertexAttribiv", userptr); + glIsProgram = (PFNGLISPROGRAMPROC) load("glIsProgram", userptr); + glIsShader = (PFNGLISSHADERPROC) load("glIsShader", userptr); + glLinkProgram = (PFNGLLINKPROGRAMPROC) load("glLinkProgram", userptr); + glShaderSource = (PFNGLSHADERSOURCEPROC) load("glShaderSource", userptr); + glStencilFuncSeparate = (PFNGLSTENCILFUNCSEPARATEPROC) load("glStencilFuncSeparate", userptr); + glStencilMaskSeparate = (PFNGLSTENCILMASKSEPARATEPROC) load("glStencilMaskSeparate", userptr); + glStencilOpSeparate = (PFNGLSTENCILOPSEPARATEPROC) load("glStencilOpSeparate", userptr); + glUniform1f = (PFNGLUNIFORM1FPROC) load("glUniform1f", userptr); + glUniform1fv = (PFNGLUNIFORM1FVPROC) load("glUniform1fv", userptr); + glUniform1i = (PFNGLUNIFORM1IPROC) load("glUniform1i", userptr); + glUniform1iv = (PFNGLUNIFORM1IVPROC) load("glUniform1iv", userptr); + glUniform2f = (PFNGLUNIFORM2FPROC) load("glUniform2f", userptr); + glUniform2fv = (PFNGLUNIFORM2FVPROC) load("glUniform2fv", userptr); + glUniform2i = (PFNGLUNIFORM2IPROC) load("glUniform2i", userptr); + glUniform2iv = (PFNGLUNIFORM2IVPROC) load("glUniform2iv", userptr); + glUniform3f = (PFNGLUNIFORM3FPROC) load("glUniform3f", userptr); + glUniform3fv = (PFNGLUNIFORM3FVPROC) load("glUniform3fv", userptr); + glUniform3i = (PFNGLUNIFORM3IPROC) load("glUniform3i", userptr); + glUniform3iv = (PFNGLUNIFORM3IVPROC) load("glUniform3iv", userptr); + glUniform4f = (PFNGLUNIFORM4FPROC) load("glUniform4f", userptr); + glUniform4fv = (PFNGLUNIFORM4FVPROC) load("glUniform4fv", userptr); + glUniform4i = (PFNGLUNIFORM4IPROC) load("glUniform4i", userptr); + glUniform4iv = (PFNGLUNIFORM4IVPROC) load("glUniform4iv", userptr); + glUniformMatrix2fv = (PFNGLUNIFORMMATRIX2FVPROC) load("glUniformMatrix2fv", userptr); + glUniformMatrix3fv = (PFNGLUNIFORMMATRIX3FVPROC) load("glUniformMatrix3fv", userptr); + glUniformMatrix4fv = (PFNGLUNIFORMMATRIX4FVPROC) load("glUniformMatrix4fv", userptr); + glUseProgram = (PFNGLUSEPROGRAMPROC) load("glUseProgram", userptr); + glValidateProgram = (PFNGLVALIDATEPROGRAMPROC) load("glValidateProgram", userptr); + glVertexAttrib1d = (PFNGLVERTEXATTRIB1DPROC) load("glVertexAttrib1d", userptr); + glVertexAttrib1dv = (PFNGLVERTEXATTRIB1DVPROC) load("glVertexAttrib1dv", userptr); + glVertexAttrib1f = (PFNGLVERTEXATTRIB1FPROC) load("glVertexAttrib1f", userptr); + glVertexAttrib1fv = (PFNGLVERTEXATTRIB1FVPROC) load("glVertexAttrib1fv", userptr); + glVertexAttrib1s = (PFNGLVERTEXATTRIB1SPROC) load("glVertexAttrib1s", userptr); + glVertexAttrib1sv = (PFNGLVERTEXATTRIB1SVPROC) load("glVertexAttrib1sv", userptr); + glVertexAttrib2d = (PFNGLVERTEXATTRIB2DPROC) load("glVertexAttrib2d", userptr); + glVertexAttrib2dv = (PFNGLVERTEXATTRIB2DVPROC) load("glVertexAttrib2dv", userptr); + glVertexAttrib2f = (PFNGLVERTEXATTRIB2FPROC) load("glVertexAttrib2f", userptr); + glVertexAttrib2fv = (PFNGLVERTEXATTRIB2FVPROC) load("glVertexAttrib2fv", userptr); + glVertexAttrib2s = (PFNGLVERTEXATTRIB2SPROC) load("glVertexAttrib2s", userptr); + glVertexAttrib2sv = (PFNGLVERTEXATTRIB2SVPROC) load("glVertexAttrib2sv", userptr); + glVertexAttrib3d = (PFNGLVERTEXATTRIB3DPROC) load("glVertexAttrib3d", userptr); + glVertexAttrib3dv = (PFNGLVERTEXATTRIB3DVPROC) load("glVertexAttrib3dv", userptr); + glVertexAttrib3f = (PFNGLVERTEXATTRIB3FPROC) load("glVertexAttrib3f", userptr); + glVertexAttrib3fv = (PFNGLVERTEXATTRIB3FVPROC) load("glVertexAttrib3fv", userptr); + glVertexAttrib3s = (PFNGLVERTEXATTRIB3SPROC) load("glVertexAttrib3s", userptr); + glVertexAttrib3sv = (PFNGLVERTEXATTRIB3SVPROC) load("glVertexAttrib3sv", userptr); + glVertexAttrib4Nbv = (PFNGLVERTEXATTRIB4NBVPROC) load("glVertexAttrib4Nbv", userptr); + glVertexAttrib4Niv = (PFNGLVERTEXATTRIB4NIVPROC) load("glVertexAttrib4Niv", userptr); + glVertexAttrib4Nsv = (PFNGLVERTEXATTRIB4NSVPROC) load("glVertexAttrib4Nsv", userptr); + glVertexAttrib4Nub = (PFNGLVERTEXATTRIB4NUBPROC) load("glVertexAttrib4Nub", userptr); + glVertexAttrib4Nubv = (PFNGLVERTEXATTRIB4NUBVPROC) load("glVertexAttrib4Nubv", userptr); + glVertexAttrib4Nuiv = (PFNGLVERTEXATTRIB4NUIVPROC) load("glVertexAttrib4Nuiv", userptr); + glVertexAttrib4Nusv = (PFNGLVERTEXATTRIB4NUSVPROC) load("glVertexAttrib4Nusv", userptr); + glVertexAttrib4bv = (PFNGLVERTEXATTRIB4BVPROC) load("glVertexAttrib4bv", userptr); + glVertexAttrib4d = (PFNGLVERTEXATTRIB4DPROC) load("glVertexAttrib4d", userptr); + glVertexAttrib4dv = (PFNGLVERTEXATTRIB4DVPROC) load("glVertexAttrib4dv", userptr); + glVertexAttrib4f = (PFNGLVERTEXATTRIB4FPROC) load("glVertexAttrib4f", userptr); + glVertexAttrib4fv = (PFNGLVERTEXATTRIB4FVPROC) load("glVertexAttrib4fv", userptr); + glVertexAttrib4iv = (PFNGLVERTEXATTRIB4IVPROC) load("glVertexAttrib4iv", userptr); + glVertexAttrib4s = (PFNGLVERTEXATTRIB4SPROC) load("glVertexAttrib4s", userptr); + glVertexAttrib4sv = (PFNGLVERTEXATTRIB4SVPROC) load("glVertexAttrib4sv", userptr); + glVertexAttrib4ubv = (PFNGLVERTEXATTRIB4UBVPROC) load("glVertexAttrib4ubv", userptr); + glVertexAttrib4uiv = (PFNGLVERTEXATTRIB4UIVPROC) load("glVertexAttrib4uiv", userptr); + glVertexAttrib4usv = (PFNGLVERTEXATTRIB4USVPROC) load("glVertexAttrib4usv", userptr); + glVertexAttribPointer = (PFNGLVERTEXATTRIBPOINTERPROC) load("glVertexAttribPointer", userptr); +} +static void glad_gl_load_GL_VERSION_2_1( GLADuserptrloadfunc load, void* userptr) { + if(!GLAD_GL_VERSION_2_1) return; + glUniformMatrix2x3fv = (PFNGLUNIFORMMATRIX2X3FVPROC) load("glUniformMatrix2x3fv", userptr); + glUniformMatrix2x4fv = (PFNGLUNIFORMMATRIX2X4FVPROC) load("glUniformMatrix2x4fv", userptr); + glUniformMatrix3x2fv = (PFNGLUNIFORMMATRIX3X2FVPROC) load("glUniformMatrix3x2fv", userptr); + glUniformMatrix3x4fv = (PFNGLUNIFORMMATRIX3X4FVPROC) load("glUniformMatrix3x4fv", userptr); + glUniformMatrix4x2fv = (PFNGLUNIFORMMATRIX4X2FVPROC) load("glUniformMatrix4x2fv", userptr); + glUniformMatrix4x3fv = (PFNGLUNIFORMMATRIX4X3FVPROC) load("glUniformMatrix4x3fv", userptr); +} +static void glad_gl_load_GL_VERSION_3_0( GLADuserptrloadfunc load, void* userptr) { + if(!GLAD_GL_VERSION_3_0) return; + glBeginConditionalRender = (PFNGLBEGINCONDITIONALRENDERPROC) load("glBeginConditionalRender", userptr); + glBeginTransformFeedback = (PFNGLBEGINTRANSFORMFEEDBACKPROC) load("glBeginTransformFeedback", userptr); + glBindBufferBase = (PFNGLBINDBUFFERBASEPROC) load("glBindBufferBase", userptr); + glBindBufferRange = (PFNGLBINDBUFFERRANGEPROC) load("glBindBufferRange", userptr); + glBindFragDataLocation = (PFNGLBINDFRAGDATALOCATIONPROC) load("glBindFragDataLocation", userptr); + glBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC) load("glBindFramebuffer", userptr); + glBindRenderbuffer = (PFNGLBINDRENDERBUFFERPROC) load("glBindRenderbuffer", userptr); + glBindVertexArray = (PFNGLBINDVERTEXARRAYPROC) load("glBindVertexArray", userptr); + glBlitFramebuffer = (PFNGLBLITFRAMEBUFFERPROC) load("glBlitFramebuffer", userptr); + glCheckFramebufferStatus = (PFNGLCHECKFRAMEBUFFERSTATUSPROC) load("glCheckFramebufferStatus", userptr); + glClampColor = (PFNGLCLAMPCOLORPROC) load("glClampColor", userptr); + glClearBufferfi = (PFNGLCLEARBUFFERFIPROC) load("glClearBufferfi", userptr); + glClearBufferfv = (PFNGLCLEARBUFFERFVPROC) load("glClearBufferfv", userptr); + glClearBufferiv = (PFNGLCLEARBUFFERIVPROC) load("glClearBufferiv", userptr); + glClearBufferuiv = (PFNGLCLEARBUFFERUIVPROC) load("glClearBufferuiv", userptr); + glColorMaski = (PFNGLCOLORMASKIPROC) load("glColorMaski", userptr); + glDeleteFramebuffers = (PFNGLDELETEFRAMEBUFFERSPROC) load("glDeleteFramebuffers", userptr); + glDeleteRenderbuffers = (PFNGLDELETERENDERBUFFERSPROC) load("glDeleteRenderbuffers", userptr); + glDeleteVertexArrays = (PFNGLDELETEVERTEXARRAYSPROC) load("glDeleteVertexArrays", userptr); + glDisablei = (PFNGLDISABLEIPROC) load("glDisablei", userptr); + glEnablei = (PFNGLENABLEIPROC) load("glEnablei", userptr); + glEndConditionalRender = (PFNGLENDCONDITIONALRENDERPROC) load("glEndConditionalRender", userptr); + glEndTransformFeedback = (PFNGLENDTRANSFORMFEEDBACKPROC) load("glEndTransformFeedback", userptr); + glFlushMappedBufferRange = (PFNGLFLUSHMAPPEDBUFFERRANGEPROC) load("glFlushMappedBufferRange", userptr); + glFramebufferRenderbuffer = (PFNGLFRAMEBUFFERRENDERBUFFERPROC) load("glFramebufferRenderbuffer", userptr); + glFramebufferTexture1D = (PFNGLFRAMEBUFFERTEXTURE1DPROC) load("glFramebufferTexture1D", userptr); + glFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC) load("glFramebufferTexture2D", userptr); + glFramebufferTexture3D = (PFNGLFRAMEBUFFERTEXTURE3DPROC) load("glFramebufferTexture3D", userptr); + glFramebufferTextureLayer = (PFNGLFRAMEBUFFERTEXTURELAYERPROC) load("glFramebufferTextureLayer", userptr); + glGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC) load("glGenFramebuffers", userptr); + glGenRenderbuffers = (PFNGLGENRENDERBUFFERSPROC) load("glGenRenderbuffers", userptr); + glGenVertexArrays = (PFNGLGENVERTEXARRAYSPROC) load("glGenVertexArrays", userptr); + glGenerateMipmap = (PFNGLGENERATEMIPMAPPROC) load("glGenerateMipmap", userptr); + glGetBooleani_v = (PFNGLGETBOOLEANI_VPROC) load("glGetBooleani_v", userptr); + glGetFragDataLocation = (PFNGLGETFRAGDATALOCATIONPROC) load("glGetFragDataLocation", userptr); + glGetFramebufferAttachmentParameteriv = (PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC) load("glGetFramebufferAttachmentParameteriv", userptr); + glGetIntegeri_v = (PFNGLGETINTEGERI_VPROC) load("glGetIntegeri_v", userptr); + glGetRenderbufferParameteriv = (PFNGLGETRENDERBUFFERPARAMETERIVPROC) load("glGetRenderbufferParameteriv", userptr); + glGetStringi = (PFNGLGETSTRINGIPROC) load("glGetStringi", userptr); + glGetTexParameterIiv = (PFNGLGETTEXPARAMETERIIVPROC) load("glGetTexParameterIiv", userptr); + glGetTexParameterIuiv = (PFNGLGETTEXPARAMETERIUIVPROC) load("glGetTexParameterIuiv", userptr); + glGetTransformFeedbackVarying = (PFNGLGETTRANSFORMFEEDBACKVARYINGPROC) load("glGetTransformFeedbackVarying", userptr); + glGetUniformuiv = (PFNGLGETUNIFORMUIVPROC) load("glGetUniformuiv", userptr); + glGetVertexAttribIiv = (PFNGLGETVERTEXATTRIBIIVPROC) load("glGetVertexAttribIiv", userptr); + glGetVertexAttribIuiv = (PFNGLGETVERTEXATTRIBIUIVPROC) load("glGetVertexAttribIuiv", userptr); + glIsEnabledi = (PFNGLISENABLEDIPROC) load("glIsEnabledi", userptr); + glIsFramebuffer = (PFNGLISFRAMEBUFFERPROC) load("glIsFramebuffer", userptr); + glIsRenderbuffer = (PFNGLISRENDERBUFFERPROC) load("glIsRenderbuffer", userptr); + glIsVertexArray = (PFNGLISVERTEXARRAYPROC) load("glIsVertexArray", userptr); + glMapBufferRange = (PFNGLMAPBUFFERRANGEPROC) load("glMapBufferRange", userptr); + glRenderbufferStorage = (PFNGLRENDERBUFFERSTORAGEPROC) load("glRenderbufferStorage", userptr); + glRenderbufferStorageMultisample = (PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC) load("glRenderbufferStorageMultisample", userptr); + glTexParameterIiv = (PFNGLTEXPARAMETERIIVPROC) load("glTexParameterIiv", userptr); + glTexParameterIuiv = (PFNGLTEXPARAMETERIUIVPROC) load("glTexParameterIuiv", userptr); + glTransformFeedbackVaryings = (PFNGLTRANSFORMFEEDBACKVARYINGSPROC) load("glTransformFeedbackVaryings", userptr); + glUniform1ui = (PFNGLUNIFORM1UIPROC) load("glUniform1ui", userptr); + glUniform1uiv = (PFNGLUNIFORM1UIVPROC) load("glUniform1uiv", userptr); + glUniform2ui = (PFNGLUNIFORM2UIPROC) load("glUniform2ui", userptr); + glUniform2uiv = (PFNGLUNIFORM2UIVPROC) load("glUniform2uiv", userptr); + glUniform3ui = (PFNGLUNIFORM3UIPROC) load("glUniform3ui", userptr); + glUniform3uiv = (PFNGLUNIFORM3UIVPROC) load("glUniform3uiv", userptr); + glUniform4ui = (PFNGLUNIFORM4UIPROC) load("glUniform4ui", userptr); + glUniform4uiv = (PFNGLUNIFORM4UIVPROC) load("glUniform4uiv", userptr); + glVertexAttribI1i = (PFNGLVERTEXATTRIBI1IPROC) load("glVertexAttribI1i", userptr); + glVertexAttribI1iv = (PFNGLVERTEXATTRIBI1IVPROC) load("glVertexAttribI1iv", userptr); + glVertexAttribI1ui = (PFNGLVERTEXATTRIBI1UIPROC) load("glVertexAttribI1ui", userptr); + glVertexAttribI1uiv = (PFNGLVERTEXATTRIBI1UIVPROC) load("glVertexAttribI1uiv", userptr); + glVertexAttribI2i = (PFNGLVERTEXATTRIBI2IPROC) load("glVertexAttribI2i", userptr); + glVertexAttribI2iv = (PFNGLVERTEXATTRIBI2IVPROC) load("glVertexAttribI2iv", userptr); + glVertexAttribI2ui = (PFNGLVERTEXATTRIBI2UIPROC) load("glVertexAttribI2ui", userptr); + glVertexAttribI2uiv = (PFNGLVERTEXATTRIBI2UIVPROC) load("glVertexAttribI2uiv", userptr); + glVertexAttribI3i = (PFNGLVERTEXATTRIBI3IPROC) load("glVertexAttribI3i", userptr); + glVertexAttribI3iv = (PFNGLVERTEXATTRIBI3IVPROC) load("glVertexAttribI3iv", userptr); + glVertexAttribI3ui = (PFNGLVERTEXATTRIBI3UIPROC) load("glVertexAttribI3ui", userptr); + glVertexAttribI3uiv = (PFNGLVERTEXATTRIBI3UIVPROC) load("glVertexAttribI3uiv", userptr); + glVertexAttribI4bv = (PFNGLVERTEXATTRIBI4BVPROC) load("glVertexAttribI4bv", userptr); + glVertexAttribI4i = (PFNGLVERTEXATTRIBI4IPROC) load("glVertexAttribI4i", userptr); + glVertexAttribI4iv = (PFNGLVERTEXATTRIBI4IVPROC) load("glVertexAttribI4iv", userptr); + glVertexAttribI4sv = (PFNGLVERTEXATTRIBI4SVPROC) load("glVertexAttribI4sv", userptr); + glVertexAttribI4ubv = (PFNGLVERTEXATTRIBI4UBVPROC) load("glVertexAttribI4ubv", userptr); + glVertexAttribI4ui = (PFNGLVERTEXATTRIBI4UIPROC) load("glVertexAttribI4ui", userptr); + glVertexAttribI4uiv = (PFNGLVERTEXATTRIBI4UIVPROC) load("glVertexAttribI4uiv", userptr); + glVertexAttribI4usv = (PFNGLVERTEXATTRIBI4USVPROC) load("glVertexAttribI4usv", userptr); + glVertexAttribIPointer = (PFNGLVERTEXATTRIBIPOINTERPROC) load("glVertexAttribIPointer", userptr); +} +static void glad_gl_load_GL_VERSION_3_1( GLADuserptrloadfunc load, void* userptr) { + if(!GLAD_GL_VERSION_3_1) return; + glBindBufferBase = (PFNGLBINDBUFFERBASEPROC) load("glBindBufferBase", userptr); + glBindBufferRange = (PFNGLBINDBUFFERRANGEPROC) load("glBindBufferRange", userptr); + glCopyBufferSubData = (PFNGLCOPYBUFFERSUBDATAPROC) load("glCopyBufferSubData", userptr); + glDrawArraysInstanced = (PFNGLDRAWARRAYSINSTANCEDPROC) load("glDrawArraysInstanced", userptr); + glDrawElementsInstanced = (PFNGLDRAWELEMENTSINSTANCEDPROC) load("glDrawElementsInstanced", userptr); + glGetActiveUniformBlockName = (PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC) load("glGetActiveUniformBlockName", userptr); + glGetActiveUniformBlockiv = (PFNGLGETACTIVEUNIFORMBLOCKIVPROC) load("glGetActiveUniformBlockiv", userptr); + glGetActiveUniformName = (PFNGLGETACTIVEUNIFORMNAMEPROC) load("glGetActiveUniformName", userptr); + glGetActiveUniformsiv = (PFNGLGETACTIVEUNIFORMSIVPROC) load("glGetActiveUniformsiv", userptr); + glGetIntegeri_v = (PFNGLGETINTEGERI_VPROC) load("glGetIntegeri_v", userptr); + glGetUniformBlockIndex = (PFNGLGETUNIFORMBLOCKINDEXPROC) load("glGetUniformBlockIndex", userptr); + glGetUniformIndices = (PFNGLGETUNIFORMINDICESPROC) load("glGetUniformIndices", userptr); + glPrimitiveRestartIndex = (PFNGLPRIMITIVERESTARTINDEXPROC) load("glPrimitiveRestartIndex", userptr); + glTexBuffer = (PFNGLTEXBUFFERPROC) load("glTexBuffer", userptr); + glUniformBlockBinding = (PFNGLUNIFORMBLOCKBINDINGPROC) load("glUniformBlockBinding", userptr); +} +static void glad_gl_load_GL_VERSION_3_2( GLADuserptrloadfunc load, void* userptr) { + if(!GLAD_GL_VERSION_3_2) return; + glClientWaitSync = (PFNGLCLIENTWAITSYNCPROC) load("glClientWaitSync", userptr); + glDeleteSync = (PFNGLDELETESYNCPROC) load("glDeleteSync", userptr); + glDrawElementsBaseVertex = (PFNGLDRAWELEMENTSBASEVERTEXPROC) load("glDrawElementsBaseVertex", userptr); + glDrawElementsInstancedBaseVertex = (PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC) load("glDrawElementsInstancedBaseVertex", userptr); + glDrawRangeElementsBaseVertex = (PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC) load("glDrawRangeElementsBaseVertex", userptr); + glFenceSync = (PFNGLFENCESYNCPROC) load("glFenceSync", userptr); + glFramebufferTexture = (PFNGLFRAMEBUFFERTEXTUREPROC) load("glFramebufferTexture", userptr); + glGetBufferParameteri64v = (PFNGLGETBUFFERPARAMETERI64VPROC) load("glGetBufferParameteri64v", userptr); + glGetInteger64i_v = (PFNGLGETINTEGER64I_VPROC) load("glGetInteger64i_v", userptr); + glGetInteger64v = (PFNGLGETINTEGER64VPROC) load("glGetInteger64v", userptr); + glGetMultisamplefv = (PFNGLGETMULTISAMPLEFVPROC) load("glGetMultisamplefv", userptr); + glGetSynciv = (PFNGLGETSYNCIVPROC) load("glGetSynciv", userptr); + glIsSync = (PFNGLISSYNCPROC) load("glIsSync", userptr); + glMultiDrawElementsBaseVertex = (PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC) load("glMultiDrawElementsBaseVertex", userptr); + glProvokingVertex = (PFNGLPROVOKINGVERTEXPROC) load("glProvokingVertex", userptr); + glSampleMaski = (PFNGLSAMPLEMASKIPROC) load("glSampleMaski", userptr); + glTexImage2DMultisample = (PFNGLTEXIMAGE2DMULTISAMPLEPROC) load("glTexImage2DMultisample", userptr); + glTexImage3DMultisample = (PFNGLTEXIMAGE3DMULTISAMPLEPROC) load("glTexImage3DMultisample", userptr); + glWaitSync = (PFNGLWAITSYNCPROC) load("glWaitSync", userptr); +} +static void glad_gl_load_GL_VERSION_3_3( GLADuserptrloadfunc load, void* userptr) { + if(!GLAD_GL_VERSION_3_3) return; + glBindFragDataLocationIndexed = (PFNGLBINDFRAGDATALOCATIONINDEXEDPROC) load("glBindFragDataLocationIndexed", userptr); + glBindSampler = (PFNGLBINDSAMPLERPROC) load("glBindSampler", userptr); + glColorP3ui = (PFNGLCOLORP3UIPROC) load("glColorP3ui", userptr); + glColorP3uiv = (PFNGLCOLORP3UIVPROC) load("glColorP3uiv", userptr); + glColorP4ui = (PFNGLCOLORP4UIPROC) load("glColorP4ui", userptr); + glColorP4uiv = (PFNGLCOLORP4UIVPROC) load("glColorP4uiv", userptr); + glDeleteSamplers = (PFNGLDELETESAMPLERSPROC) load("glDeleteSamplers", userptr); + glGenSamplers = (PFNGLGENSAMPLERSPROC) load("glGenSamplers", userptr); + glGetFragDataIndex = (PFNGLGETFRAGDATAINDEXPROC) load("glGetFragDataIndex", userptr); + glGetQueryObjecti64v = (PFNGLGETQUERYOBJECTI64VPROC) load("glGetQueryObjecti64v", userptr); + glGetQueryObjectui64v = (PFNGLGETQUERYOBJECTUI64VPROC) load("glGetQueryObjectui64v", userptr); + glGetSamplerParameterIiv = (PFNGLGETSAMPLERPARAMETERIIVPROC) load("glGetSamplerParameterIiv", userptr); + glGetSamplerParameterIuiv = (PFNGLGETSAMPLERPARAMETERIUIVPROC) load("glGetSamplerParameterIuiv", userptr); + glGetSamplerParameterfv = (PFNGLGETSAMPLERPARAMETERFVPROC) load("glGetSamplerParameterfv", userptr); + glGetSamplerParameteriv = (PFNGLGETSAMPLERPARAMETERIVPROC) load("glGetSamplerParameteriv", userptr); + glIsSampler = (PFNGLISSAMPLERPROC) load("glIsSampler", userptr); + glMultiTexCoordP1ui = (PFNGLMULTITEXCOORDP1UIPROC) load("glMultiTexCoordP1ui", userptr); + glMultiTexCoordP1uiv = (PFNGLMULTITEXCOORDP1UIVPROC) load("glMultiTexCoordP1uiv", userptr); + glMultiTexCoordP2ui = (PFNGLMULTITEXCOORDP2UIPROC) load("glMultiTexCoordP2ui", userptr); + glMultiTexCoordP2uiv = (PFNGLMULTITEXCOORDP2UIVPROC) load("glMultiTexCoordP2uiv", userptr); + glMultiTexCoordP3ui = (PFNGLMULTITEXCOORDP3UIPROC) load("glMultiTexCoordP3ui", userptr); + glMultiTexCoordP3uiv = (PFNGLMULTITEXCOORDP3UIVPROC) load("glMultiTexCoordP3uiv", userptr); + glMultiTexCoordP4ui = (PFNGLMULTITEXCOORDP4UIPROC) load("glMultiTexCoordP4ui", userptr); + glMultiTexCoordP4uiv = (PFNGLMULTITEXCOORDP4UIVPROC) load("glMultiTexCoordP4uiv", userptr); + glNormalP3ui = (PFNGLNORMALP3UIPROC) load("glNormalP3ui", userptr); + glNormalP3uiv = (PFNGLNORMALP3UIVPROC) load("glNormalP3uiv", userptr); + glQueryCounter = (PFNGLQUERYCOUNTERPROC) load("glQueryCounter", userptr); + glSamplerParameterIiv = (PFNGLSAMPLERPARAMETERIIVPROC) load("glSamplerParameterIiv", userptr); + glSamplerParameterIuiv = (PFNGLSAMPLERPARAMETERIUIVPROC) load("glSamplerParameterIuiv", userptr); + glSamplerParameterf = (PFNGLSAMPLERPARAMETERFPROC) load("glSamplerParameterf", userptr); + glSamplerParameterfv = (PFNGLSAMPLERPARAMETERFVPROC) load("glSamplerParameterfv", userptr); + glSamplerParameteri = (PFNGLSAMPLERPARAMETERIPROC) load("glSamplerParameteri", userptr); + glSamplerParameteriv = (PFNGLSAMPLERPARAMETERIVPROC) load("glSamplerParameteriv", userptr); + glSecondaryColorP3ui = (PFNGLSECONDARYCOLORP3UIPROC) load("glSecondaryColorP3ui", userptr); + glSecondaryColorP3uiv = (PFNGLSECONDARYCOLORP3UIVPROC) load("glSecondaryColorP3uiv", userptr); + glTexCoordP1ui = (PFNGLTEXCOORDP1UIPROC) load("glTexCoordP1ui", userptr); + glTexCoordP1uiv = (PFNGLTEXCOORDP1UIVPROC) load("glTexCoordP1uiv", userptr); + glTexCoordP2ui = (PFNGLTEXCOORDP2UIPROC) load("glTexCoordP2ui", userptr); + glTexCoordP2uiv = (PFNGLTEXCOORDP2UIVPROC) load("glTexCoordP2uiv", userptr); + glTexCoordP3ui = (PFNGLTEXCOORDP3UIPROC) load("glTexCoordP3ui", userptr); + glTexCoordP3uiv = (PFNGLTEXCOORDP3UIVPROC) load("glTexCoordP3uiv", userptr); + glTexCoordP4ui = (PFNGLTEXCOORDP4UIPROC) load("glTexCoordP4ui", userptr); + glTexCoordP4uiv = (PFNGLTEXCOORDP4UIVPROC) load("glTexCoordP4uiv", userptr); + glVertexAttribDivisor = (PFNGLVERTEXATTRIBDIVISORPROC) load("glVertexAttribDivisor", userptr); + glVertexAttribP1ui = (PFNGLVERTEXATTRIBP1UIPROC) load("glVertexAttribP1ui", userptr); + glVertexAttribP1uiv = (PFNGLVERTEXATTRIBP1UIVPROC) load("glVertexAttribP1uiv", userptr); + glVertexAttribP2ui = (PFNGLVERTEXATTRIBP2UIPROC) load("glVertexAttribP2ui", userptr); + glVertexAttribP2uiv = (PFNGLVERTEXATTRIBP2UIVPROC) load("glVertexAttribP2uiv", userptr); + glVertexAttribP3ui = (PFNGLVERTEXATTRIBP3UIPROC) load("glVertexAttribP3ui", userptr); + glVertexAttribP3uiv = (PFNGLVERTEXATTRIBP3UIVPROC) load("glVertexAttribP3uiv", userptr); + glVertexAttribP4ui = (PFNGLVERTEXATTRIBP4UIPROC) load("glVertexAttribP4ui", userptr); + glVertexAttribP4uiv = (PFNGLVERTEXATTRIBP4UIVPROC) load("glVertexAttribP4uiv", userptr); + glVertexP2ui = (PFNGLVERTEXP2UIPROC) load("glVertexP2ui", userptr); + glVertexP2uiv = (PFNGLVERTEXP2UIVPROC) load("glVertexP2uiv", userptr); + glVertexP3ui = (PFNGLVERTEXP3UIPROC) load("glVertexP3ui", userptr); + glVertexP3uiv = (PFNGLVERTEXP3UIVPROC) load("glVertexP3uiv", userptr); + glVertexP4ui = (PFNGLVERTEXP4UIPROC) load("glVertexP4ui", userptr); + glVertexP4uiv = (PFNGLVERTEXP4UIVPROC) load("glVertexP4uiv", userptr); +} +static void glad_gl_load_GL_ARB_multisample( GLADuserptrloadfunc load, void* userptr) { + if(!GLAD_GL_ARB_multisample) return; + glSampleCoverage = (PFNGLSAMPLECOVERAGEPROC) load("glSampleCoverage", userptr); + glSampleCoverageARB = (PFNGLSAMPLECOVERAGEARBPROC) load("glSampleCoverageARB", userptr); +} +static void glad_gl_load_GL_ARB_robustness( GLADuserptrloadfunc load, void* userptr) { + if(!GLAD_GL_ARB_robustness) return; + glGetGraphicsResetStatusARB = (PFNGLGETGRAPHICSRESETSTATUSARBPROC) load("glGetGraphicsResetStatusARB", userptr); + glGetnColorTableARB = (PFNGLGETNCOLORTABLEARBPROC) load("glGetnColorTableARB", userptr); + glGetnCompressedTexImageARB = (PFNGLGETNCOMPRESSEDTEXIMAGEARBPROC) load("glGetnCompressedTexImageARB", userptr); + glGetnConvolutionFilterARB = (PFNGLGETNCONVOLUTIONFILTERARBPROC) load("glGetnConvolutionFilterARB", userptr); + glGetnHistogramARB = (PFNGLGETNHISTOGRAMARBPROC) load("glGetnHistogramARB", userptr); + glGetnMapdvARB = (PFNGLGETNMAPDVARBPROC) load("glGetnMapdvARB", userptr); + glGetnMapfvARB = (PFNGLGETNMAPFVARBPROC) load("glGetnMapfvARB", userptr); + glGetnMapivARB = (PFNGLGETNMAPIVARBPROC) load("glGetnMapivARB", userptr); + glGetnMinmaxARB = (PFNGLGETNMINMAXARBPROC) load("glGetnMinmaxARB", userptr); + glGetnPixelMapfvARB = (PFNGLGETNPIXELMAPFVARBPROC) load("glGetnPixelMapfvARB", userptr); + glGetnPixelMapuivARB = (PFNGLGETNPIXELMAPUIVARBPROC) load("glGetnPixelMapuivARB", userptr); + glGetnPixelMapusvARB = (PFNGLGETNPIXELMAPUSVARBPROC) load("glGetnPixelMapusvARB", userptr); + glGetnPolygonStippleARB = (PFNGLGETNPOLYGONSTIPPLEARBPROC) load("glGetnPolygonStippleARB", userptr); + glGetnSeparableFilterARB = (PFNGLGETNSEPARABLEFILTERARBPROC) load("glGetnSeparableFilterARB", userptr); + glGetnTexImageARB = (PFNGLGETNTEXIMAGEARBPROC) load("glGetnTexImageARB", userptr); + glGetnUniformdvARB = (PFNGLGETNUNIFORMDVARBPROC) load("glGetnUniformdvARB", userptr); + glGetnUniformfvARB = (PFNGLGETNUNIFORMFVARBPROC) load("glGetnUniformfvARB", userptr); + glGetnUniformivARB = (PFNGLGETNUNIFORMIVARBPROC) load("glGetnUniformivARB", userptr); + glGetnUniformuivARB = (PFNGLGETNUNIFORMUIVARBPROC) load("glGetnUniformuivARB", userptr); + glReadnPixels = (PFNGLREADNPIXELSPROC) load("glReadnPixels", userptr); + glReadnPixelsARB = (PFNGLREADNPIXELSARBPROC) load("glReadnPixelsARB", userptr); +} +static void glad_gl_load_GL_KHR_debug( GLADuserptrloadfunc load, void* userptr) { + if(!GLAD_GL_KHR_debug) return; + glDebugMessageCallback = (PFNGLDEBUGMESSAGECALLBACKPROC) load("glDebugMessageCallback", userptr); + glDebugMessageControl = (PFNGLDEBUGMESSAGECONTROLPROC) load("glDebugMessageControl", userptr); + glDebugMessageInsert = (PFNGLDEBUGMESSAGEINSERTPROC) load("glDebugMessageInsert", userptr); + glGetDebugMessageLog = (PFNGLGETDEBUGMESSAGELOGPROC) load("glGetDebugMessageLog", userptr); + glGetObjectLabel = (PFNGLGETOBJECTLABELPROC) load("glGetObjectLabel", userptr); + glGetObjectPtrLabel = (PFNGLGETOBJECTPTRLABELPROC) load("glGetObjectPtrLabel", userptr); + glGetPointerv = (PFNGLGETPOINTERVPROC) load("glGetPointerv", userptr); + glObjectLabel = (PFNGLOBJECTLABELPROC) load("glObjectLabel", userptr); + glObjectPtrLabel = (PFNGLOBJECTPTRLABELPROC) load("glObjectPtrLabel", userptr); + glPopDebugGroup = (PFNGLPOPDEBUGGROUPPROC) load("glPopDebugGroup", userptr); + glPushDebugGroup = (PFNGLPUSHDEBUGGROUPPROC) load("glPushDebugGroup", userptr); +} + + + +#if defined(GL_ES_VERSION_3_0) || defined(GL_VERSION_3_0) +#define GLAD_GL_IS_SOME_NEW_VERSION 1 +#else +#define GLAD_GL_IS_SOME_NEW_VERSION 0 +#endif + +static int glad_gl_get_extensions( int version, const char **out_exts, unsigned int *out_num_exts_i, char ***out_exts_i) { +#if GLAD_GL_IS_SOME_NEW_VERSION + if(GLAD_VERSION_MAJOR(version) < 3) { +#else + (void) version; + (void) out_num_exts_i; + (void) out_exts_i; +#endif + if (glGetString == NULL) { + return 0; + } + *out_exts = (const char *)glGetString(GL_EXTENSIONS); +#if GLAD_GL_IS_SOME_NEW_VERSION + } else { + unsigned int index = 0; + unsigned int num_exts_i = 0; + char **exts_i = NULL; + if (glGetStringi == NULL || glGetIntegerv == NULL) { + return 0; + } + glGetIntegerv(GL_NUM_EXTENSIONS, (int*) &num_exts_i); + if (num_exts_i > 0) { + exts_i = (char **) malloc(num_exts_i * (sizeof *exts_i)); + } + if (exts_i == NULL) { + return 0; + } + for(index = 0; index < num_exts_i; index++) { + const char *gl_str_tmp = (const char*) glGetStringi(GL_EXTENSIONS, index); + size_t len = strlen(gl_str_tmp) + 1; + + char *local_str = (char*) malloc(len * sizeof(char)); + if(local_str != NULL) { + memcpy(local_str, gl_str_tmp, len * sizeof(char)); + } + + exts_i[index] = local_str; + } + + *out_num_exts_i = num_exts_i; + *out_exts_i = exts_i; + } +#endif + return 1; +} +static void glad_gl_free_extensions(char **exts_i, unsigned int num_exts_i) { + if (exts_i != NULL) { + unsigned int index; + for(index = 0; index < num_exts_i; index++) { + free((void *) (exts_i[index])); + } + free((void *)exts_i); + exts_i = NULL; + } +} +static int glad_gl_has_extension(int version, const char *exts, unsigned int num_exts_i, char **exts_i, const char *ext) { + if(GLAD_VERSION_MAJOR(version) < 3 || !GLAD_GL_IS_SOME_NEW_VERSION) { + const char *extensions; + const char *loc; + const char *terminator; + extensions = exts; + if(extensions == NULL || ext == NULL) { + return 0; + } + while(1) { + loc = strstr(extensions, ext); + if(loc == NULL) { + return 0; + } + terminator = loc + strlen(ext); + if((loc == extensions || *(loc - 1) == ' ') && + (*terminator == ' ' || *terminator == '\0')) { + return 1; + } + extensions = terminator; + } + } else { + unsigned int index; + for(index = 0; index < num_exts_i; index++) { + const char *e = exts_i[index]; + if(strcmp(e, ext) == 0) { + return 1; + } + } + } + return 0; +} + +static GLADapiproc glad_gl_get_proc_from_userptr(const char* name, void *userptr) { + return (GLAD_GNUC_EXTENSION (GLADapiproc (*)(const char *name)) userptr)(name); +} + +static int glad_gl_find_extensions_gl( int version) { + const char *exts = NULL; + unsigned int num_exts_i = 0; + char **exts_i = NULL; + if (!glad_gl_get_extensions(version, &exts, &num_exts_i, &exts_i)) return 0; + + GLAD_GL_ARB_multisample = glad_gl_has_extension(version, exts, num_exts_i, exts_i, "GL_ARB_multisample"); + GLAD_GL_ARB_robustness = glad_gl_has_extension(version, exts, num_exts_i, exts_i, "GL_ARB_robustness"); + GLAD_GL_KHR_debug = glad_gl_has_extension(version, exts, num_exts_i, exts_i, "GL_KHR_debug"); + + glad_gl_free_extensions(exts_i, num_exts_i); + + return 1; +} + +static int glad_gl_find_core_gl(void) { + int i, major, minor; + const char* version; + const char* prefixes[] = { + "OpenGL ES-CM ", + "OpenGL ES-CL ", + "OpenGL ES ", + NULL + }; + version = (const char*) glGetString(GL_VERSION); + if (!version) return 0; + for (i = 0; prefixes[i]; i++) { + const size_t length = strlen(prefixes[i]); + if (strncmp(version, prefixes[i], length) == 0) { + version += length; + break; + } + } + + GLAD_IMPL_UTIL_SSCANF(version, "%d.%d", &major, &minor); + + GLAD_GL_VERSION_1_0 = (major == 1 && minor >= 0) || major > 1; + GLAD_GL_VERSION_1_1 = (major == 1 && minor >= 1) || major > 1; + GLAD_GL_VERSION_1_2 = (major == 1 && minor >= 2) || major > 1; + GLAD_GL_VERSION_1_3 = (major == 1 && minor >= 3) || major > 1; + GLAD_GL_VERSION_1_4 = (major == 1 && minor >= 4) || major > 1; + GLAD_GL_VERSION_1_5 = (major == 1 && minor >= 5) || major > 1; + GLAD_GL_VERSION_2_0 = (major == 2 && minor >= 0) || major > 2; + GLAD_GL_VERSION_2_1 = (major == 2 && minor >= 1) || major > 2; + GLAD_GL_VERSION_3_0 = (major == 3 && minor >= 0) || major > 3; + GLAD_GL_VERSION_3_1 = (major == 3 && minor >= 1) || major > 3; + GLAD_GL_VERSION_3_2 = (major == 3 && minor >= 2) || major > 3; + GLAD_GL_VERSION_3_3 = (major == 3 && minor >= 3) || major > 3; + + return GLAD_MAKE_VERSION(major, minor); +} + +int gladLoadGLUserPtr( GLADuserptrloadfunc load, void *userptr) { + int version; + + glGetString = (PFNGLGETSTRINGPROC) load("glGetString", userptr); + if(glGetString == NULL) return 0; + if(glGetString(GL_VERSION) == NULL) return 0; + version = glad_gl_find_core_gl(); + + glad_gl_load_GL_VERSION_1_0(load, userptr); + glad_gl_load_GL_VERSION_1_1(load, userptr); + glad_gl_load_GL_VERSION_1_2(load, userptr); + glad_gl_load_GL_VERSION_1_3(load, userptr); + glad_gl_load_GL_VERSION_1_4(load, userptr); + glad_gl_load_GL_VERSION_1_5(load, userptr); + glad_gl_load_GL_VERSION_2_0(load, userptr); + glad_gl_load_GL_VERSION_2_1(load, userptr); + glad_gl_load_GL_VERSION_3_0(load, userptr); + glad_gl_load_GL_VERSION_3_1(load, userptr); + glad_gl_load_GL_VERSION_3_2(load, userptr); + glad_gl_load_GL_VERSION_3_3(load, userptr); + + if (!glad_gl_find_extensions_gl(version)) return 0; + glad_gl_load_GL_ARB_multisample(load, userptr); + glad_gl_load_GL_ARB_robustness(load, userptr); + glad_gl_load_GL_KHR_debug(load, userptr); + + + + return version; +} + + +int gladLoadGL( GLADloadfunc load) { + return gladLoadGLUserPtr( glad_gl_get_proc_from_userptr, GLAD_GNUC_EXTENSION (void*) load); +} + + + + diff --git a/src/external/glfw/deps/glad_vulkan.c b/src/external/glfw/deps/glad_vulkan.c new file mode 100644 index 00000000..5adfbbbe --- /dev/null +++ b/src/external/glfw/deps/glad_vulkan.c @@ -0,0 +1,593 @@ +#include +#include +#include +#include + +#ifndef GLAD_IMPL_UTIL_C_ +#define GLAD_IMPL_UTIL_C_ + +#ifdef _MSC_VER +#define GLAD_IMPL_UTIL_SSCANF sscanf_s +#else +#define GLAD_IMPL_UTIL_SSCANF sscanf +#endif + +#endif /* GLAD_IMPL_UTIL_C_ */ + + +int GLAD_VK_VERSION_1_0 = 0; +int GLAD_VK_VERSION_1_1 = 0; +int GLAD_VK_EXT_debug_report = 0; +int GLAD_VK_KHR_surface = 0; +int GLAD_VK_KHR_swapchain = 0; + + + +PFN_vkAcquireNextImage2KHR glad_vkAcquireNextImage2KHR = NULL; +PFN_vkAcquireNextImageKHR glad_vkAcquireNextImageKHR = NULL; +PFN_vkAllocateCommandBuffers glad_vkAllocateCommandBuffers = NULL; +PFN_vkAllocateDescriptorSets glad_vkAllocateDescriptorSets = NULL; +PFN_vkAllocateMemory glad_vkAllocateMemory = NULL; +PFN_vkBeginCommandBuffer glad_vkBeginCommandBuffer = NULL; +PFN_vkBindBufferMemory glad_vkBindBufferMemory = NULL; +PFN_vkBindBufferMemory2 glad_vkBindBufferMemory2 = NULL; +PFN_vkBindImageMemory glad_vkBindImageMemory = NULL; +PFN_vkBindImageMemory2 glad_vkBindImageMemory2 = NULL; +PFN_vkCmdBeginQuery glad_vkCmdBeginQuery = NULL; +PFN_vkCmdBeginRenderPass glad_vkCmdBeginRenderPass = NULL; +PFN_vkCmdBindDescriptorSets glad_vkCmdBindDescriptorSets = NULL; +PFN_vkCmdBindIndexBuffer glad_vkCmdBindIndexBuffer = NULL; +PFN_vkCmdBindPipeline glad_vkCmdBindPipeline = NULL; +PFN_vkCmdBindVertexBuffers glad_vkCmdBindVertexBuffers = NULL; +PFN_vkCmdBlitImage glad_vkCmdBlitImage = NULL; +PFN_vkCmdClearAttachments glad_vkCmdClearAttachments = NULL; +PFN_vkCmdClearColorImage glad_vkCmdClearColorImage = NULL; +PFN_vkCmdClearDepthStencilImage glad_vkCmdClearDepthStencilImage = NULL; +PFN_vkCmdCopyBuffer glad_vkCmdCopyBuffer = NULL; +PFN_vkCmdCopyBufferToImage glad_vkCmdCopyBufferToImage = NULL; +PFN_vkCmdCopyImage glad_vkCmdCopyImage = NULL; +PFN_vkCmdCopyImageToBuffer glad_vkCmdCopyImageToBuffer = NULL; +PFN_vkCmdCopyQueryPoolResults glad_vkCmdCopyQueryPoolResults = NULL; +PFN_vkCmdDispatch glad_vkCmdDispatch = NULL; +PFN_vkCmdDispatchBase glad_vkCmdDispatchBase = NULL; +PFN_vkCmdDispatchIndirect glad_vkCmdDispatchIndirect = NULL; +PFN_vkCmdDraw glad_vkCmdDraw = NULL; +PFN_vkCmdDrawIndexed glad_vkCmdDrawIndexed = NULL; +PFN_vkCmdDrawIndexedIndirect glad_vkCmdDrawIndexedIndirect = NULL; +PFN_vkCmdDrawIndirect glad_vkCmdDrawIndirect = NULL; +PFN_vkCmdEndQuery glad_vkCmdEndQuery = NULL; +PFN_vkCmdEndRenderPass glad_vkCmdEndRenderPass = NULL; +PFN_vkCmdExecuteCommands glad_vkCmdExecuteCommands = NULL; +PFN_vkCmdFillBuffer glad_vkCmdFillBuffer = NULL; +PFN_vkCmdNextSubpass glad_vkCmdNextSubpass = NULL; +PFN_vkCmdPipelineBarrier glad_vkCmdPipelineBarrier = NULL; +PFN_vkCmdPushConstants glad_vkCmdPushConstants = NULL; +PFN_vkCmdResetEvent glad_vkCmdResetEvent = NULL; +PFN_vkCmdResetQueryPool glad_vkCmdResetQueryPool = NULL; +PFN_vkCmdResolveImage glad_vkCmdResolveImage = NULL; +PFN_vkCmdSetBlendConstants glad_vkCmdSetBlendConstants = NULL; +PFN_vkCmdSetDepthBias glad_vkCmdSetDepthBias = NULL; +PFN_vkCmdSetDepthBounds glad_vkCmdSetDepthBounds = NULL; +PFN_vkCmdSetDeviceMask glad_vkCmdSetDeviceMask = NULL; +PFN_vkCmdSetEvent glad_vkCmdSetEvent = NULL; +PFN_vkCmdSetLineWidth glad_vkCmdSetLineWidth = NULL; +PFN_vkCmdSetScissor glad_vkCmdSetScissor = NULL; +PFN_vkCmdSetStencilCompareMask glad_vkCmdSetStencilCompareMask = NULL; +PFN_vkCmdSetStencilReference glad_vkCmdSetStencilReference = NULL; +PFN_vkCmdSetStencilWriteMask glad_vkCmdSetStencilWriteMask = NULL; +PFN_vkCmdSetViewport glad_vkCmdSetViewport = NULL; +PFN_vkCmdUpdateBuffer glad_vkCmdUpdateBuffer = NULL; +PFN_vkCmdWaitEvents glad_vkCmdWaitEvents = NULL; +PFN_vkCmdWriteTimestamp glad_vkCmdWriteTimestamp = NULL; +PFN_vkCreateBuffer glad_vkCreateBuffer = NULL; +PFN_vkCreateBufferView glad_vkCreateBufferView = NULL; +PFN_vkCreateCommandPool glad_vkCreateCommandPool = NULL; +PFN_vkCreateComputePipelines glad_vkCreateComputePipelines = NULL; +PFN_vkCreateDebugReportCallbackEXT glad_vkCreateDebugReportCallbackEXT = NULL; +PFN_vkCreateDescriptorPool glad_vkCreateDescriptorPool = NULL; +PFN_vkCreateDescriptorSetLayout glad_vkCreateDescriptorSetLayout = NULL; +PFN_vkCreateDescriptorUpdateTemplate glad_vkCreateDescriptorUpdateTemplate = NULL; +PFN_vkCreateDevice glad_vkCreateDevice = NULL; +PFN_vkCreateEvent glad_vkCreateEvent = NULL; +PFN_vkCreateFence glad_vkCreateFence = NULL; +PFN_vkCreateFramebuffer glad_vkCreateFramebuffer = NULL; +PFN_vkCreateGraphicsPipelines glad_vkCreateGraphicsPipelines = NULL; +PFN_vkCreateImage glad_vkCreateImage = NULL; +PFN_vkCreateImageView glad_vkCreateImageView = NULL; +PFN_vkCreateInstance glad_vkCreateInstance = NULL; +PFN_vkCreatePipelineCache glad_vkCreatePipelineCache = NULL; +PFN_vkCreatePipelineLayout glad_vkCreatePipelineLayout = NULL; +PFN_vkCreateQueryPool glad_vkCreateQueryPool = NULL; +PFN_vkCreateRenderPass glad_vkCreateRenderPass = NULL; +PFN_vkCreateSampler glad_vkCreateSampler = NULL; +PFN_vkCreateSamplerYcbcrConversion glad_vkCreateSamplerYcbcrConversion = NULL; +PFN_vkCreateSemaphore glad_vkCreateSemaphore = NULL; +PFN_vkCreateShaderModule glad_vkCreateShaderModule = NULL; +PFN_vkCreateSwapchainKHR glad_vkCreateSwapchainKHR = NULL; +PFN_vkDebugReportMessageEXT glad_vkDebugReportMessageEXT = NULL; +PFN_vkDestroyBuffer glad_vkDestroyBuffer = NULL; +PFN_vkDestroyBufferView glad_vkDestroyBufferView = NULL; +PFN_vkDestroyCommandPool glad_vkDestroyCommandPool = NULL; +PFN_vkDestroyDebugReportCallbackEXT glad_vkDestroyDebugReportCallbackEXT = NULL; +PFN_vkDestroyDescriptorPool glad_vkDestroyDescriptorPool = NULL; +PFN_vkDestroyDescriptorSetLayout glad_vkDestroyDescriptorSetLayout = NULL; +PFN_vkDestroyDescriptorUpdateTemplate glad_vkDestroyDescriptorUpdateTemplate = NULL; +PFN_vkDestroyDevice glad_vkDestroyDevice = NULL; +PFN_vkDestroyEvent glad_vkDestroyEvent = NULL; +PFN_vkDestroyFence glad_vkDestroyFence = NULL; +PFN_vkDestroyFramebuffer glad_vkDestroyFramebuffer = NULL; +PFN_vkDestroyImage glad_vkDestroyImage = NULL; +PFN_vkDestroyImageView glad_vkDestroyImageView = NULL; +PFN_vkDestroyInstance glad_vkDestroyInstance = NULL; +PFN_vkDestroyPipeline glad_vkDestroyPipeline = NULL; +PFN_vkDestroyPipelineCache glad_vkDestroyPipelineCache = NULL; +PFN_vkDestroyPipelineLayout glad_vkDestroyPipelineLayout = NULL; +PFN_vkDestroyQueryPool glad_vkDestroyQueryPool = NULL; +PFN_vkDestroyRenderPass glad_vkDestroyRenderPass = NULL; +PFN_vkDestroySampler glad_vkDestroySampler = NULL; +PFN_vkDestroySamplerYcbcrConversion glad_vkDestroySamplerYcbcrConversion = NULL; +PFN_vkDestroySemaphore glad_vkDestroySemaphore = NULL; +PFN_vkDestroyShaderModule glad_vkDestroyShaderModule = NULL; +PFN_vkDestroySurfaceKHR glad_vkDestroySurfaceKHR = NULL; +PFN_vkDestroySwapchainKHR glad_vkDestroySwapchainKHR = NULL; +PFN_vkDeviceWaitIdle glad_vkDeviceWaitIdle = NULL; +PFN_vkEndCommandBuffer glad_vkEndCommandBuffer = NULL; +PFN_vkEnumerateDeviceExtensionProperties glad_vkEnumerateDeviceExtensionProperties = NULL; +PFN_vkEnumerateDeviceLayerProperties glad_vkEnumerateDeviceLayerProperties = NULL; +PFN_vkEnumerateInstanceExtensionProperties glad_vkEnumerateInstanceExtensionProperties = NULL; +PFN_vkEnumerateInstanceLayerProperties glad_vkEnumerateInstanceLayerProperties = NULL; +PFN_vkEnumerateInstanceVersion glad_vkEnumerateInstanceVersion = NULL; +PFN_vkEnumeratePhysicalDeviceGroups glad_vkEnumeratePhysicalDeviceGroups = NULL; +PFN_vkEnumeratePhysicalDevices glad_vkEnumeratePhysicalDevices = NULL; +PFN_vkFlushMappedMemoryRanges glad_vkFlushMappedMemoryRanges = NULL; +PFN_vkFreeCommandBuffers glad_vkFreeCommandBuffers = NULL; +PFN_vkFreeDescriptorSets glad_vkFreeDescriptorSets = NULL; +PFN_vkFreeMemory glad_vkFreeMemory = NULL; +PFN_vkGetBufferMemoryRequirements glad_vkGetBufferMemoryRequirements = NULL; +PFN_vkGetBufferMemoryRequirements2 glad_vkGetBufferMemoryRequirements2 = NULL; +PFN_vkGetDescriptorSetLayoutSupport glad_vkGetDescriptorSetLayoutSupport = NULL; +PFN_vkGetDeviceGroupPeerMemoryFeatures glad_vkGetDeviceGroupPeerMemoryFeatures = NULL; +PFN_vkGetDeviceGroupPresentCapabilitiesKHR glad_vkGetDeviceGroupPresentCapabilitiesKHR = NULL; +PFN_vkGetDeviceGroupSurfacePresentModesKHR glad_vkGetDeviceGroupSurfacePresentModesKHR = NULL; +PFN_vkGetDeviceMemoryCommitment glad_vkGetDeviceMemoryCommitment = NULL; +PFN_vkGetDeviceProcAddr glad_vkGetDeviceProcAddr = NULL; +PFN_vkGetDeviceQueue glad_vkGetDeviceQueue = NULL; +PFN_vkGetDeviceQueue2 glad_vkGetDeviceQueue2 = NULL; +PFN_vkGetEventStatus glad_vkGetEventStatus = NULL; +PFN_vkGetFenceStatus glad_vkGetFenceStatus = NULL; +PFN_vkGetImageMemoryRequirements glad_vkGetImageMemoryRequirements = NULL; +PFN_vkGetImageMemoryRequirements2 glad_vkGetImageMemoryRequirements2 = NULL; +PFN_vkGetImageSparseMemoryRequirements glad_vkGetImageSparseMemoryRequirements = NULL; +PFN_vkGetImageSparseMemoryRequirements2 glad_vkGetImageSparseMemoryRequirements2 = NULL; +PFN_vkGetImageSubresourceLayout glad_vkGetImageSubresourceLayout = NULL; +PFN_vkGetInstanceProcAddr glad_vkGetInstanceProcAddr = NULL; +PFN_vkGetPhysicalDeviceExternalBufferProperties glad_vkGetPhysicalDeviceExternalBufferProperties = NULL; +PFN_vkGetPhysicalDeviceExternalFenceProperties glad_vkGetPhysicalDeviceExternalFenceProperties = NULL; +PFN_vkGetPhysicalDeviceExternalSemaphoreProperties glad_vkGetPhysicalDeviceExternalSemaphoreProperties = NULL; +PFN_vkGetPhysicalDeviceFeatures glad_vkGetPhysicalDeviceFeatures = NULL; +PFN_vkGetPhysicalDeviceFeatures2 glad_vkGetPhysicalDeviceFeatures2 = NULL; +PFN_vkGetPhysicalDeviceFormatProperties glad_vkGetPhysicalDeviceFormatProperties = NULL; +PFN_vkGetPhysicalDeviceFormatProperties2 glad_vkGetPhysicalDeviceFormatProperties2 = NULL; +PFN_vkGetPhysicalDeviceImageFormatProperties glad_vkGetPhysicalDeviceImageFormatProperties = NULL; +PFN_vkGetPhysicalDeviceImageFormatProperties2 glad_vkGetPhysicalDeviceImageFormatProperties2 = NULL; +PFN_vkGetPhysicalDeviceMemoryProperties glad_vkGetPhysicalDeviceMemoryProperties = NULL; +PFN_vkGetPhysicalDeviceMemoryProperties2 glad_vkGetPhysicalDeviceMemoryProperties2 = NULL; +PFN_vkGetPhysicalDevicePresentRectanglesKHR glad_vkGetPhysicalDevicePresentRectanglesKHR = NULL; +PFN_vkGetPhysicalDeviceProperties glad_vkGetPhysicalDeviceProperties = NULL; +PFN_vkGetPhysicalDeviceProperties2 glad_vkGetPhysicalDeviceProperties2 = NULL; +PFN_vkGetPhysicalDeviceQueueFamilyProperties glad_vkGetPhysicalDeviceQueueFamilyProperties = NULL; +PFN_vkGetPhysicalDeviceQueueFamilyProperties2 glad_vkGetPhysicalDeviceQueueFamilyProperties2 = NULL; +PFN_vkGetPhysicalDeviceSparseImageFormatProperties glad_vkGetPhysicalDeviceSparseImageFormatProperties = NULL; +PFN_vkGetPhysicalDeviceSparseImageFormatProperties2 glad_vkGetPhysicalDeviceSparseImageFormatProperties2 = NULL; +PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR glad_vkGetPhysicalDeviceSurfaceCapabilitiesKHR = NULL; +PFN_vkGetPhysicalDeviceSurfaceFormatsKHR glad_vkGetPhysicalDeviceSurfaceFormatsKHR = NULL; +PFN_vkGetPhysicalDeviceSurfacePresentModesKHR glad_vkGetPhysicalDeviceSurfacePresentModesKHR = NULL; +PFN_vkGetPhysicalDeviceSurfaceSupportKHR glad_vkGetPhysicalDeviceSurfaceSupportKHR = NULL; +PFN_vkGetPipelineCacheData glad_vkGetPipelineCacheData = NULL; +PFN_vkGetQueryPoolResults glad_vkGetQueryPoolResults = NULL; +PFN_vkGetRenderAreaGranularity glad_vkGetRenderAreaGranularity = NULL; +PFN_vkGetSwapchainImagesKHR glad_vkGetSwapchainImagesKHR = NULL; +PFN_vkInvalidateMappedMemoryRanges glad_vkInvalidateMappedMemoryRanges = NULL; +PFN_vkMapMemory glad_vkMapMemory = NULL; +PFN_vkMergePipelineCaches glad_vkMergePipelineCaches = NULL; +PFN_vkQueueBindSparse glad_vkQueueBindSparse = NULL; +PFN_vkQueuePresentKHR glad_vkQueuePresentKHR = NULL; +PFN_vkQueueSubmit glad_vkQueueSubmit = NULL; +PFN_vkQueueWaitIdle glad_vkQueueWaitIdle = NULL; +PFN_vkResetCommandBuffer glad_vkResetCommandBuffer = NULL; +PFN_vkResetCommandPool glad_vkResetCommandPool = NULL; +PFN_vkResetDescriptorPool glad_vkResetDescriptorPool = NULL; +PFN_vkResetEvent glad_vkResetEvent = NULL; +PFN_vkResetFences glad_vkResetFences = NULL; +PFN_vkSetEvent glad_vkSetEvent = NULL; +PFN_vkTrimCommandPool glad_vkTrimCommandPool = NULL; +PFN_vkUnmapMemory glad_vkUnmapMemory = NULL; +PFN_vkUpdateDescriptorSetWithTemplate glad_vkUpdateDescriptorSetWithTemplate = NULL; +PFN_vkUpdateDescriptorSets glad_vkUpdateDescriptorSets = NULL; +PFN_vkWaitForFences glad_vkWaitForFences = NULL; + + +static void glad_vk_load_VK_VERSION_1_0( GLADuserptrloadfunc load, void* userptr) { + if(!GLAD_VK_VERSION_1_0) return; + vkAllocateCommandBuffers = (PFN_vkAllocateCommandBuffers) load("vkAllocateCommandBuffers", userptr); + vkAllocateDescriptorSets = (PFN_vkAllocateDescriptorSets) load("vkAllocateDescriptorSets", userptr); + vkAllocateMemory = (PFN_vkAllocateMemory) load("vkAllocateMemory", userptr); + vkBeginCommandBuffer = (PFN_vkBeginCommandBuffer) load("vkBeginCommandBuffer", userptr); + vkBindBufferMemory = (PFN_vkBindBufferMemory) load("vkBindBufferMemory", userptr); + vkBindImageMemory = (PFN_vkBindImageMemory) load("vkBindImageMemory", userptr); + vkCmdBeginQuery = (PFN_vkCmdBeginQuery) load("vkCmdBeginQuery", userptr); + vkCmdBeginRenderPass = (PFN_vkCmdBeginRenderPass) load("vkCmdBeginRenderPass", userptr); + vkCmdBindDescriptorSets = (PFN_vkCmdBindDescriptorSets) load("vkCmdBindDescriptorSets", userptr); + vkCmdBindIndexBuffer = (PFN_vkCmdBindIndexBuffer) load("vkCmdBindIndexBuffer", userptr); + vkCmdBindPipeline = (PFN_vkCmdBindPipeline) load("vkCmdBindPipeline", userptr); + vkCmdBindVertexBuffers = (PFN_vkCmdBindVertexBuffers) load("vkCmdBindVertexBuffers", userptr); + vkCmdBlitImage = (PFN_vkCmdBlitImage) load("vkCmdBlitImage", userptr); + vkCmdClearAttachments = (PFN_vkCmdClearAttachments) load("vkCmdClearAttachments", userptr); + vkCmdClearColorImage = (PFN_vkCmdClearColorImage) load("vkCmdClearColorImage", userptr); + vkCmdClearDepthStencilImage = (PFN_vkCmdClearDepthStencilImage) load("vkCmdClearDepthStencilImage", userptr); + vkCmdCopyBuffer = (PFN_vkCmdCopyBuffer) load("vkCmdCopyBuffer", userptr); + vkCmdCopyBufferToImage = (PFN_vkCmdCopyBufferToImage) load("vkCmdCopyBufferToImage", userptr); + vkCmdCopyImage = (PFN_vkCmdCopyImage) load("vkCmdCopyImage", userptr); + vkCmdCopyImageToBuffer = (PFN_vkCmdCopyImageToBuffer) load("vkCmdCopyImageToBuffer", userptr); + vkCmdCopyQueryPoolResults = (PFN_vkCmdCopyQueryPoolResults) load("vkCmdCopyQueryPoolResults", userptr); + vkCmdDispatch = (PFN_vkCmdDispatch) load("vkCmdDispatch", userptr); + vkCmdDispatchIndirect = (PFN_vkCmdDispatchIndirect) load("vkCmdDispatchIndirect", userptr); + vkCmdDraw = (PFN_vkCmdDraw) load("vkCmdDraw", userptr); + vkCmdDrawIndexed = (PFN_vkCmdDrawIndexed) load("vkCmdDrawIndexed", userptr); + vkCmdDrawIndexedIndirect = (PFN_vkCmdDrawIndexedIndirect) load("vkCmdDrawIndexedIndirect", userptr); + vkCmdDrawIndirect = (PFN_vkCmdDrawIndirect) load("vkCmdDrawIndirect", userptr); + vkCmdEndQuery = (PFN_vkCmdEndQuery) load("vkCmdEndQuery", userptr); + vkCmdEndRenderPass = (PFN_vkCmdEndRenderPass) load("vkCmdEndRenderPass", userptr); + vkCmdExecuteCommands = (PFN_vkCmdExecuteCommands) load("vkCmdExecuteCommands", userptr); + vkCmdFillBuffer = (PFN_vkCmdFillBuffer) load("vkCmdFillBuffer", userptr); + vkCmdNextSubpass = (PFN_vkCmdNextSubpass) load("vkCmdNextSubpass", userptr); + vkCmdPipelineBarrier = (PFN_vkCmdPipelineBarrier) load("vkCmdPipelineBarrier", userptr); + vkCmdPushConstants = (PFN_vkCmdPushConstants) load("vkCmdPushConstants", userptr); + vkCmdResetEvent = (PFN_vkCmdResetEvent) load("vkCmdResetEvent", userptr); + vkCmdResetQueryPool = (PFN_vkCmdResetQueryPool) load("vkCmdResetQueryPool", userptr); + vkCmdResolveImage = (PFN_vkCmdResolveImage) load("vkCmdResolveImage", userptr); + vkCmdSetBlendConstants = (PFN_vkCmdSetBlendConstants) load("vkCmdSetBlendConstants", userptr); + vkCmdSetDepthBias = (PFN_vkCmdSetDepthBias) load("vkCmdSetDepthBias", userptr); + vkCmdSetDepthBounds = (PFN_vkCmdSetDepthBounds) load("vkCmdSetDepthBounds", userptr); + vkCmdSetEvent = (PFN_vkCmdSetEvent) load("vkCmdSetEvent", userptr); + vkCmdSetLineWidth = (PFN_vkCmdSetLineWidth) load("vkCmdSetLineWidth", userptr); + vkCmdSetScissor = (PFN_vkCmdSetScissor) load("vkCmdSetScissor", userptr); + vkCmdSetStencilCompareMask = (PFN_vkCmdSetStencilCompareMask) load("vkCmdSetStencilCompareMask", userptr); + vkCmdSetStencilReference = (PFN_vkCmdSetStencilReference) load("vkCmdSetStencilReference", userptr); + vkCmdSetStencilWriteMask = (PFN_vkCmdSetStencilWriteMask) load("vkCmdSetStencilWriteMask", userptr); + vkCmdSetViewport = (PFN_vkCmdSetViewport) load("vkCmdSetViewport", userptr); + vkCmdUpdateBuffer = (PFN_vkCmdUpdateBuffer) load("vkCmdUpdateBuffer", userptr); + vkCmdWaitEvents = (PFN_vkCmdWaitEvents) load("vkCmdWaitEvents", userptr); + vkCmdWriteTimestamp = (PFN_vkCmdWriteTimestamp) load("vkCmdWriteTimestamp", userptr); + vkCreateBuffer = (PFN_vkCreateBuffer) load("vkCreateBuffer", userptr); + vkCreateBufferView = (PFN_vkCreateBufferView) load("vkCreateBufferView", userptr); + vkCreateCommandPool = (PFN_vkCreateCommandPool) load("vkCreateCommandPool", userptr); + vkCreateComputePipelines = (PFN_vkCreateComputePipelines) load("vkCreateComputePipelines", userptr); + vkCreateDescriptorPool = (PFN_vkCreateDescriptorPool) load("vkCreateDescriptorPool", userptr); + vkCreateDescriptorSetLayout = (PFN_vkCreateDescriptorSetLayout) load("vkCreateDescriptorSetLayout", userptr); + vkCreateDevice = (PFN_vkCreateDevice) load("vkCreateDevice", userptr); + vkCreateEvent = (PFN_vkCreateEvent) load("vkCreateEvent", userptr); + vkCreateFence = (PFN_vkCreateFence) load("vkCreateFence", userptr); + vkCreateFramebuffer = (PFN_vkCreateFramebuffer) load("vkCreateFramebuffer", userptr); + vkCreateGraphicsPipelines = (PFN_vkCreateGraphicsPipelines) load("vkCreateGraphicsPipelines", userptr); + vkCreateImage = (PFN_vkCreateImage) load("vkCreateImage", userptr); + vkCreateImageView = (PFN_vkCreateImageView) load("vkCreateImageView", userptr); + vkCreateInstance = (PFN_vkCreateInstance) load("vkCreateInstance", userptr); + vkCreatePipelineCache = (PFN_vkCreatePipelineCache) load("vkCreatePipelineCache", userptr); + vkCreatePipelineLayout = (PFN_vkCreatePipelineLayout) load("vkCreatePipelineLayout", userptr); + vkCreateQueryPool = (PFN_vkCreateQueryPool) load("vkCreateQueryPool", userptr); + vkCreateRenderPass = (PFN_vkCreateRenderPass) load("vkCreateRenderPass", userptr); + vkCreateSampler = (PFN_vkCreateSampler) load("vkCreateSampler", userptr); + vkCreateSemaphore = (PFN_vkCreateSemaphore) load("vkCreateSemaphore", userptr); + vkCreateShaderModule = (PFN_vkCreateShaderModule) load("vkCreateShaderModule", userptr); + vkDestroyBuffer = (PFN_vkDestroyBuffer) load("vkDestroyBuffer", userptr); + vkDestroyBufferView = (PFN_vkDestroyBufferView) load("vkDestroyBufferView", userptr); + vkDestroyCommandPool = (PFN_vkDestroyCommandPool) load("vkDestroyCommandPool", userptr); + vkDestroyDescriptorPool = (PFN_vkDestroyDescriptorPool) load("vkDestroyDescriptorPool", userptr); + vkDestroyDescriptorSetLayout = (PFN_vkDestroyDescriptorSetLayout) load("vkDestroyDescriptorSetLayout", userptr); + vkDestroyDevice = (PFN_vkDestroyDevice) load("vkDestroyDevice", userptr); + vkDestroyEvent = (PFN_vkDestroyEvent) load("vkDestroyEvent", userptr); + vkDestroyFence = (PFN_vkDestroyFence) load("vkDestroyFence", userptr); + vkDestroyFramebuffer = (PFN_vkDestroyFramebuffer) load("vkDestroyFramebuffer", userptr); + vkDestroyImage = (PFN_vkDestroyImage) load("vkDestroyImage", userptr); + vkDestroyImageView = (PFN_vkDestroyImageView) load("vkDestroyImageView", userptr); + vkDestroyInstance = (PFN_vkDestroyInstance) load("vkDestroyInstance", userptr); + vkDestroyPipeline = (PFN_vkDestroyPipeline) load("vkDestroyPipeline", userptr); + vkDestroyPipelineCache = (PFN_vkDestroyPipelineCache) load("vkDestroyPipelineCache", userptr); + vkDestroyPipelineLayout = (PFN_vkDestroyPipelineLayout) load("vkDestroyPipelineLayout", userptr); + vkDestroyQueryPool = (PFN_vkDestroyQueryPool) load("vkDestroyQueryPool", userptr); + vkDestroyRenderPass = (PFN_vkDestroyRenderPass) load("vkDestroyRenderPass", userptr); + vkDestroySampler = (PFN_vkDestroySampler) load("vkDestroySampler", userptr); + vkDestroySemaphore = (PFN_vkDestroySemaphore) load("vkDestroySemaphore", userptr); + vkDestroyShaderModule = (PFN_vkDestroyShaderModule) load("vkDestroyShaderModule", userptr); + vkDeviceWaitIdle = (PFN_vkDeviceWaitIdle) load("vkDeviceWaitIdle", userptr); + vkEndCommandBuffer = (PFN_vkEndCommandBuffer) load("vkEndCommandBuffer", userptr); + vkEnumerateDeviceExtensionProperties = (PFN_vkEnumerateDeviceExtensionProperties) load("vkEnumerateDeviceExtensionProperties", userptr); + vkEnumerateDeviceLayerProperties = (PFN_vkEnumerateDeviceLayerProperties) load("vkEnumerateDeviceLayerProperties", userptr); + vkEnumerateInstanceExtensionProperties = (PFN_vkEnumerateInstanceExtensionProperties) load("vkEnumerateInstanceExtensionProperties", userptr); + vkEnumerateInstanceLayerProperties = (PFN_vkEnumerateInstanceLayerProperties) load("vkEnumerateInstanceLayerProperties", userptr); + vkEnumeratePhysicalDevices = (PFN_vkEnumeratePhysicalDevices) load("vkEnumeratePhysicalDevices", userptr); + vkFlushMappedMemoryRanges = (PFN_vkFlushMappedMemoryRanges) load("vkFlushMappedMemoryRanges", userptr); + vkFreeCommandBuffers = (PFN_vkFreeCommandBuffers) load("vkFreeCommandBuffers", userptr); + vkFreeDescriptorSets = (PFN_vkFreeDescriptorSets) load("vkFreeDescriptorSets", userptr); + vkFreeMemory = (PFN_vkFreeMemory) load("vkFreeMemory", userptr); + vkGetBufferMemoryRequirements = (PFN_vkGetBufferMemoryRequirements) load("vkGetBufferMemoryRequirements", userptr); + vkGetDeviceMemoryCommitment = (PFN_vkGetDeviceMemoryCommitment) load("vkGetDeviceMemoryCommitment", userptr); + vkGetDeviceProcAddr = (PFN_vkGetDeviceProcAddr) load("vkGetDeviceProcAddr", userptr); + vkGetDeviceQueue = (PFN_vkGetDeviceQueue) load("vkGetDeviceQueue", userptr); + vkGetEventStatus = (PFN_vkGetEventStatus) load("vkGetEventStatus", userptr); + vkGetFenceStatus = (PFN_vkGetFenceStatus) load("vkGetFenceStatus", userptr); + vkGetImageMemoryRequirements = (PFN_vkGetImageMemoryRequirements) load("vkGetImageMemoryRequirements", userptr); + vkGetImageSparseMemoryRequirements = (PFN_vkGetImageSparseMemoryRequirements) load("vkGetImageSparseMemoryRequirements", userptr); + vkGetImageSubresourceLayout = (PFN_vkGetImageSubresourceLayout) load("vkGetImageSubresourceLayout", userptr); + vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr) load("vkGetInstanceProcAddr", userptr); + vkGetPhysicalDeviceFeatures = (PFN_vkGetPhysicalDeviceFeatures) load("vkGetPhysicalDeviceFeatures", userptr); + vkGetPhysicalDeviceFormatProperties = (PFN_vkGetPhysicalDeviceFormatProperties) load("vkGetPhysicalDeviceFormatProperties", userptr); + vkGetPhysicalDeviceImageFormatProperties = (PFN_vkGetPhysicalDeviceImageFormatProperties) load("vkGetPhysicalDeviceImageFormatProperties", userptr); + vkGetPhysicalDeviceMemoryProperties = (PFN_vkGetPhysicalDeviceMemoryProperties) load("vkGetPhysicalDeviceMemoryProperties", userptr); + vkGetPhysicalDeviceProperties = (PFN_vkGetPhysicalDeviceProperties) load("vkGetPhysicalDeviceProperties", userptr); + vkGetPhysicalDeviceQueueFamilyProperties = (PFN_vkGetPhysicalDeviceQueueFamilyProperties) load("vkGetPhysicalDeviceQueueFamilyProperties", userptr); + vkGetPhysicalDeviceSparseImageFormatProperties = (PFN_vkGetPhysicalDeviceSparseImageFormatProperties) load("vkGetPhysicalDeviceSparseImageFormatProperties", userptr); + vkGetPipelineCacheData = (PFN_vkGetPipelineCacheData) load("vkGetPipelineCacheData", userptr); + vkGetQueryPoolResults = (PFN_vkGetQueryPoolResults) load("vkGetQueryPoolResults", userptr); + vkGetRenderAreaGranularity = (PFN_vkGetRenderAreaGranularity) load("vkGetRenderAreaGranularity", userptr); + vkInvalidateMappedMemoryRanges = (PFN_vkInvalidateMappedMemoryRanges) load("vkInvalidateMappedMemoryRanges", userptr); + vkMapMemory = (PFN_vkMapMemory) load("vkMapMemory", userptr); + vkMergePipelineCaches = (PFN_vkMergePipelineCaches) load("vkMergePipelineCaches", userptr); + vkQueueBindSparse = (PFN_vkQueueBindSparse) load("vkQueueBindSparse", userptr); + vkQueueSubmit = (PFN_vkQueueSubmit) load("vkQueueSubmit", userptr); + vkQueueWaitIdle = (PFN_vkQueueWaitIdle) load("vkQueueWaitIdle", userptr); + vkResetCommandBuffer = (PFN_vkResetCommandBuffer) load("vkResetCommandBuffer", userptr); + vkResetCommandPool = (PFN_vkResetCommandPool) load("vkResetCommandPool", userptr); + vkResetDescriptorPool = (PFN_vkResetDescriptorPool) load("vkResetDescriptorPool", userptr); + vkResetEvent = (PFN_vkResetEvent) load("vkResetEvent", userptr); + vkResetFences = (PFN_vkResetFences) load("vkResetFences", userptr); + vkSetEvent = (PFN_vkSetEvent) load("vkSetEvent", userptr); + vkUnmapMemory = (PFN_vkUnmapMemory) load("vkUnmapMemory", userptr); + vkUpdateDescriptorSets = (PFN_vkUpdateDescriptorSets) load("vkUpdateDescriptorSets", userptr); + vkWaitForFences = (PFN_vkWaitForFences) load("vkWaitForFences", userptr); +} +static void glad_vk_load_VK_VERSION_1_1( GLADuserptrloadfunc load, void* userptr) { + if(!GLAD_VK_VERSION_1_1) return; + vkBindBufferMemory2 = (PFN_vkBindBufferMemory2) load("vkBindBufferMemory2", userptr); + vkBindImageMemory2 = (PFN_vkBindImageMemory2) load("vkBindImageMemory2", userptr); + vkCmdDispatchBase = (PFN_vkCmdDispatchBase) load("vkCmdDispatchBase", userptr); + vkCmdSetDeviceMask = (PFN_vkCmdSetDeviceMask) load("vkCmdSetDeviceMask", userptr); + vkCreateDescriptorUpdateTemplate = (PFN_vkCreateDescriptorUpdateTemplate) load("vkCreateDescriptorUpdateTemplate", userptr); + vkCreateSamplerYcbcrConversion = (PFN_vkCreateSamplerYcbcrConversion) load("vkCreateSamplerYcbcrConversion", userptr); + vkDestroyDescriptorUpdateTemplate = (PFN_vkDestroyDescriptorUpdateTemplate) load("vkDestroyDescriptorUpdateTemplate", userptr); + vkDestroySamplerYcbcrConversion = (PFN_vkDestroySamplerYcbcrConversion) load("vkDestroySamplerYcbcrConversion", userptr); + vkEnumerateInstanceVersion = (PFN_vkEnumerateInstanceVersion) load("vkEnumerateInstanceVersion", userptr); + vkEnumeratePhysicalDeviceGroups = (PFN_vkEnumeratePhysicalDeviceGroups) load("vkEnumeratePhysicalDeviceGroups", userptr); + vkGetBufferMemoryRequirements2 = (PFN_vkGetBufferMemoryRequirements2) load("vkGetBufferMemoryRequirements2", userptr); + vkGetDescriptorSetLayoutSupport = (PFN_vkGetDescriptorSetLayoutSupport) load("vkGetDescriptorSetLayoutSupport", userptr); + vkGetDeviceGroupPeerMemoryFeatures = (PFN_vkGetDeviceGroupPeerMemoryFeatures) load("vkGetDeviceGroupPeerMemoryFeatures", userptr); + vkGetDeviceQueue2 = (PFN_vkGetDeviceQueue2) load("vkGetDeviceQueue2", userptr); + vkGetImageMemoryRequirements2 = (PFN_vkGetImageMemoryRequirements2) load("vkGetImageMemoryRequirements2", userptr); + vkGetImageSparseMemoryRequirements2 = (PFN_vkGetImageSparseMemoryRequirements2) load("vkGetImageSparseMemoryRequirements2", userptr); + vkGetPhysicalDeviceExternalBufferProperties = (PFN_vkGetPhysicalDeviceExternalBufferProperties) load("vkGetPhysicalDeviceExternalBufferProperties", userptr); + vkGetPhysicalDeviceExternalFenceProperties = (PFN_vkGetPhysicalDeviceExternalFenceProperties) load("vkGetPhysicalDeviceExternalFenceProperties", userptr); + vkGetPhysicalDeviceExternalSemaphoreProperties = (PFN_vkGetPhysicalDeviceExternalSemaphoreProperties) load("vkGetPhysicalDeviceExternalSemaphoreProperties", userptr); + vkGetPhysicalDeviceFeatures2 = (PFN_vkGetPhysicalDeviceFeatures2) load("vkGetPhysicalDeviceFeatures2", userptr); + vkGetPhysicalDeviceFormatProperties2 = (PFN_vkGetPhysicalDeviceFormatProperties2) load("vkGetPhysicalDeviceFormatProperties2", userptr); + vkGetPhysicalDeviceImageFormatProperties2 = (PFN_vkGetPhysicalDeviceImageFormatProperties2) load("vkGetPhysicalDeviceImageFormatProperties2", userptr); + vkGetPhysicalDeviceMemoryProperties2 = (PFN_vkGetPhysicalDeviceMemoryProperties2) load("vkGetPhysicalDeviceMemoryProperties2", userptr); + vkGetPhysicalDeviceProperties2 = (PFN_vkGetPhysicalDeviceProperties2) load("vkGetPhysicalDeviceProperties2", userptr); + vkGetPhysicalDeviceQueueFamilyProperties2 = (PFN_vkGetPhysicalDeviceQueueFamilyProperties2) load("vkGetPhysicalDeviceQueueFamilyProperties2", userptr); + vkGetPhysicalDeviceSparseImageFormatProperties2 = (PFN_vkGetPhysicalDeviceSparseImageFormatProperties2) load("vkGetPhysicalDeviceSparseImageFormatProperties2", userptr); + vkTrimCommandPool = (PFN_vkTrimCommandPool) load("vkTrimCommandPool", userptr); + vkUpdateDescriptorSetWithTemplate = (PFN_vkUpdateDescriptorSetWithTemplate) load("vkUpdateDescriptorSetWithTemplate", userptr); +} +static void glad_vk_load_VK_EXT_debug_report( GLADuserptrloadfunc load, void* userptr) { + if(!GLAD_VK_EXT_debug_report) return; + vkCreateDebugReportCallbackEXT = (PFN_vkCreateDebugReportCallbackEXT) load("vkCreateDebugReportCallbackEXT", userptr); + vkDebugReportMessageEXT = (PFN_vkDebugReportMessageEXT) load("vkDebugReportMessageEXT", userptr); + vkDestroyDebugReportCallbackEXT = (PFN_vkDestroyDebugReportCallbackEXT) load("vkDestroyDebugReportCallbackEXT", userptr); +} +static void glad_vk_load_VK_KHR_surface( GLADuserptrloadfunc load, void* userptr) { + if(!GLAD_VK_KHR_surface) return; + vkDestroySurfaceKHR = (PFN_vkDestroySurfaceKHR) load("vkDestroySurfaceKHR", userptr); + vkGetPhysicalDeviceSurfaceCapabilitiesKHR = (PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR) load("vkGetPhysicalDeviceSurfaceCapabilitiesKHR", userptr); + vkGetPhysicalDeviceSurfaceFormatsKHR = (PFN_vkGetPhysicalDeviceSurfaceFormatsKHR) load("vkGetPhysicalDeviceSurfaceFormatsKHR", userptr); + vkGetPhysicalDeviceSurfacePresentModesKHR = (PFN_vkGetPhysicalDeviceSurfacePresentModesKHR) load("vkGetPhysicalDeviceSurfacePresentModesKHR", userptr); + vkGetPhysicalDeviceSurfaceSupportKHR = (PFN_vkGetPhysicalDeviceSurfaceSupportKHR) load("vkGetPhysicalDeviceSurfaceSupportKHR", userptr); +} +static void glad_vk_load_VK_KHR_swapchain( GLADuserptrloadfunc load, void* userptr) { + if(!GLAD_VK_KHR_swapchain) return; + vkAcquireNextImage2KHR = (PFN_vkAcquireNextImage2KHR) load("vkAcquireNextImage2KHR", userptr); + vkAcquireNextImageKHR = (PFN_vkAcquireNextImageKHR) load("vkAcquireNextImageKHR", userptr); + vkCreateSwapchainKHR = (PFN_vkCreateSwapchainKHR) load("vkCreateSwapchainKHR", userptr); + vkDestroySwapchainKHR = (PFN_vkDestroySwapchainKHR) load("vkDestroySwapchainKHR", userptr); + vkGetDeviceGroupPresentCapabilitiesKHR = (PFN_vkGetDeviceGroupPresentCapabilitiesKHR) load("vkGetDeviceGroupPresentCapabilitiesKHR", userptr); + vkGetDeviceGroupSurfacePresentModesKHR = (PFN_vkGetDeviceGroupSurfacePresentModesKHR) load("vkGetDeviceGroupSurfacePresentModesKHR", userptr); + vkGetPhysicalDevicePresentRectanglesKHR = (PFN_vkGetPhysicalDevicePresentRectanglesKHR) load("vkGetPhysicalDevicePresentRectanglesKHR", userptr); + vkGetSwapchainImagesKHR = (PFN_vkGetSwapchainImagesKHR) load("vkGetSwapchainImagesKHR", userptr); + vkQueuePresentKHR = (PFN_vkQueuePresentKHR) load("vkQueuePresentKHR", userptr); +} + + + +static int glad_vk_get_extensions( VkPhysicalDevice physical_device, uint32_t *out_extension_count, char ***out_extensions) { + uint32_t i; + uint32_t instance_extension_count = 0; + uint32_t device_extension_count = 0; + uint32_t max_extension_count; + uint32_t total_extension_count; + char **extensions; + VkExtensionProperties *ext_properties; + VkResult result; + + if (vkEnumerateInstanceExtensionProperties == NULL || (physical_device != NULL && vkEnumerateDeviceExtensionProperties == NULL)) { + return 0; + } + + result = vkEnumerateInstanceExtensionProperties(NULL, &instance_extension_count, NULL); + if (result != VK_SUCCESS) { + return 0; + } + + if (physical_device != NULL) { + result = vkEnumerateDeviceExtensionProperties(physical_device, NULL, &device_extension_count, NULL); + if (result != VK_SUCCESS) { + return 0; + } + } + + total_extension_count = instance_extension_count + device_extension_count; + max_extension_count = instance_extension_count > device_extension_count + ? instance_extension_count : device_extension_count; + + ext_properties = (VkExtensionProperties*) malloc(max_extension_count * sizeof(VkExtensionProperties)); + if (ext_properties == NULL) { + return 0; + } + + result = vkEnumerateInstanceExtensionProperties(NULL, &instance_extension_count, ext_properties); + if (result != VK_SUCCESS) { + free((void*) ext_properties); + return 0; + } + + extensions = (char**) calloc(total_extension_count, sizeof(char*)); + if (extensions == NULL) { + free((void*) ext_properties); + return 0; + } + + for (i = 0; i < instance_extension_count; ++i) { + VkExtensionProperties ext = ext_properties[i]; + + size_t extension_name_length = strlen(ext.extensionName) + 1; + extensions[i] = (char*) malloc(extension_name_length * sizeof(char)); + memcpy(extensions[i], ext.extensionName, extension_name_length * sizeof(char)); + } + + if (physical_device != NULL) { + result = vkEnumerateDeviceExtensionProperties(physical_device, NULL, &device_extension_count, ext_properties); + if (result != VK_SUCCESS) { + for (i = 0; i < instance_extension_count; ++i) { + free((void*) extensions[i]); + } + free(extensions); + return 0; + } + + for (i = 0; i < device_extension_count; ++i) { + VkExtensionProperties ext = ext_properties[i]; + + size_t extension_name_length = strlen(ext.extensionName) + 1; + extensions[instance_extension_count + i] = (char*) malloc(extension_name_length * sizeof(char)); + memcpy(extensions[instance_extension_count + i], ext.extensionName, extension_name_length * sizeof(char)); + } + } + + free((void*) ext_properties); + + *out_extension_count = total_extension_count; + *out_extensions = extensions; + + return 1; +} + +static void glad_vk_free_extensions(uint32_t extension_count, char **extensions) { + uint32_t i; + + for(i = 0; i < extension_count ; ++i) { + free((void*) (extensions[i])); + } + + free((void*) extensions); +} + +static int glad_vk_has_extension(const char *name, uint32_t extension_count, char **extensions) { + uint32_t i; + + for (i = 0; i < extension_count; ++i) { + if(strcmp(name, extensions[i]) == 0) { + return 1; + } + } + + return 0; +} + +static GLADapiproc glad_vk_get_proc_from_userptr(const char* name, void *userptr) { + return (GLAD_GNUC_EXTENSION (GLADapiproc (*)(const char *name)) userptr)(name); +} + +static int glad_vk_find_extensions_vulkan( VkPhysicalDevice physical_device) { + uint32_t extension_count = 0; + char **extensions = NULL; + if (!glad_vk_get_extensions(physical_device, &extension_count, &extensions)) return 0; + + GLAD_VK_EXT_debug_report = glad_vk_has_extension("VK_EXT_debug_report", extension_count, extensions); + GLAD_VK_KHR_surface = glad_vk_has_extension("VK_KHR_surface", extension_count, extensions); + GLAD_VK_KHR_swapchain = glad_vk_has_extension("VK_KHR_swapchain", extension_count, extensions); + + glad_vk_free_extensions(extension_count, extensions); + + return 1; +} + +static int glad_vk_find_core_vulkan( VkPhysicalDevice physical_device) { + int major = 1; + int minor = 0; + +#ifdef VK_VERSION_1_1 + if (vkEnumerateInstanceVersion != NULL) { + uint32_t version; + VkResult result; + + result = vkEnumerateInstanceVersion(&version); + if (result == VK_SUCCESS) { + major = (int) VK_VERSION_MAJOR(version); + minor = (int) VK_VERSION_MINOR(version); + } + } +#endif + + if (physical_device != NULL && vkGetPhysicalDeviceProperties != NULL) { + VkPhysicalDeviceProperties properties; + vkGetPhysicalDeviceProperties(physical_device, &properties); + + major = (int) VK_VERSION_MAJOR(properties.apiVersion); + minor = (int) VK_VERSION_MINOR(properties.apiVersion); + } + + GLAD_VK_VERSION_1_0 = (major == 1 && minor >= 0) || major > 1; + GLAD_VK_VERSION_1_1 = (major == 1 && minor >= 1) || major > 1; + + return GLAD_MAKE_VERSION(major, minor); +} + +int gladLoadVulkanUserPtr( VkPhysicalDevice physical_device, GLADuserptrloadfunc load, void *userptr) { + int version; + +#ifdef VK_VERSION_1_1 + vkEnumerateInstanceVersion = (PFN_vkEnumerateInstanceVersion) load("vkEnumerateInstanceVersion", userptr); +#endif + version = glad_vk_find_core_vulkan( physical_device); + if (!version) { + return 0; + } + + glad_vk_load_VK_VERSION_1_0(load, userptr); + glad_vk_load_VK_VERSION_1_1(load, userptr); + + if (!glad_vk_find_extensions_vulkan( physical_device)) return 0; + glad_vk_load_VK_EXT_debug_report(load, userptr); + glad_vk_load_VK_KHR_surface(load, userptr); + glad_vk_load_VK_KHR_swapchain(load, userptr); + + + return version; +} + + +int gladLoadVulkan( VkPhysicalDevice physical_device, GLADloadfunc load) { + return gladLoadVulkanUserPtr( physical_device, glad_vk_get_proc_from_userptr, GLAD_GNUC_EXTENSION (void*) load); +} + + + + diff --git a/src/external/glfw/deps/vulkan/vk_platform.h b/src/external/glfw/deps/vulkan/vk_platform.h deleted file mode 100644 index 8e21a17d..00000000 --- a/src/external/glfw/deps/vulkan/vk_platform.h +++ /dev/null @@ -1,92 +0,0 @@ -// -// File: vk_platform.h -// -/* -** Copyright (c) 2014-2017 The Khronos Group Inc. -** -** 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 VK_PLATFORM_H_ -#define VK_PLATFORM_H_ - -#ifdef __cplusplus -extern "C" -{ -#endif // __cplusplus - -/* -*************************************************************************************************** -* Platform-specific directives and type declarations -*************************************************************************************************** -*/ - -/* Platform-specific calling convention macros. - * - * Platforms should define these so that Vulkan clients call Vulkan commands - * with the same calling conventions that the Vulkan implementation expects. - * - * VKAPI_ATTR - Placed before the return type in function declarations. - * Useful for C++11 and GCC/Clang-style function attribute syntax. - * VKAPI_CALL - Placed after the return type in function declarations. - * Useful for MSVC-style calling convention syntax. - * VKAPI_PTR - Placed between the '(' and '*' in function pointer types. - * - * Function declaration: VKAPI_ATTR void VKAPI_CALL vkCommand(void); - * Function pointer type: typedef void (VKAPI_PTR *PFN_vkCommand)(void); - */ -#if defined(_WIN32) - // On Windows, Vulkan commands use the stdcall convention - #define VKAPI_ATTR - #define VKAPI_CALL __stdcall - #define VKAPI_PTR VKAPI_CALL -#elif defined(__ANDROID__) && defined(__ARM_ARCH) && __ARM_ARCH < 7 - #error "Vulkan isn't supported for the 'armeabi' NDK ABI" -#elif defined(__ANDROID__) && defined(__ARM_ARCH) && __ARM_ARCH >= 7 && defined(__ARM_32BIT_STATE) - // On Android 32-bit ARM targets, Vulkan functions use the "hardfloat" - // calling convention, i.e. float parameters are passed in registers. This - // is true even if the rest of the application passes floats on the stack, - // as it does by default when compiling for the armeabi-v7a NDK ABI. - #define VKAPI_ATTR __attribute__((pcs("aapcs-vfp"))) - #define VKAPI_CALL - #define VKAPI_PTR VKAPI_ATTR -#else - // On other platforms, use the default calling convention - #define VKAPI_ATTR - #define VKAPI_CALL - #define VKAPI_PTR -#endif - -#include - -#if !defined(VK_NO_STDINT_H) - #if defined(_MSC_VER) && (_MSC_VER < 1600) - typedef signed __int8 int8_t; - typedef unsigned __int8 uint8_t; - typedef signed __int16 int16_t; - typedef unsigned __int16 uint16_t; - typedef signed __int32 int32_t; - typedef unsigned __int32 uint32_t; - typedef signed __int64 int64_t; - typedef unsigned __int64 uint64_t; - #else - #include - #endif -#endif // !defined(VK_NO_STDINT_H) - -#ifdef __cplusplus -} // extern "C" -#endif // __cplusplus - -#endif diff --git a/src/external/glfw/deps/vulkan/vulkan.h b/src/external/glfw/deps/vulkan/vulkan.h deleted file mode 100644 index 4ffdeb9d..00000000 --- a/src/external/glfw/deps/vulkan/vulkan.h +++ /dev/null @@ -1,73 +0,0 @@ -#ifndef VULKAN_H_ -#define VULKAN_H_ 1 - -/* -** Copyright (c) 2015-2018 The Khronos Group Inc. -** -** 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. -*/ - -#include "vk_platform.h" -#include "vulkan_core.h" - -#ifdef VK_USE_PLATFORM_ANDROID_KHR -#include "vulkan_android.h" -#endif - - -#ifdef VK_USE_PLATFORM_IOS_MVK -#include "vulkan_ios.h" -#endif - - -#ifdef VK_USE_PLATFORM_MACOS_MVK -#include "vulkan_macos.h" -#endif - - -#ifdef VK_USE_PLATFORM_VI_NN -#include "vulkan_vi.h" -#endif - - -#ifdef VK_USE_PLATFORM_WAYLAND_KHR -#include -#include "vulkan_wayland.h" -#endif - - -#ifdef VK_USE_PLATFORM_WIN32_KHR -#include -#include "vulkan_win32.h" -#endif - - -#ifdef VK_USE_PLATFORM_XCB_KHR -#include -#include "vulkan_xcb.h" -#endif - - -#ifdef VK_USE_PLATFORM_XLIB_KHR -#include -#include "vulkan_xlib.h" -#endif - - -#ifdef VK_USE_PLATFORM_XLIB_XRANDR_EXT -#include -#include -#include "vulkan_xlib_xrandr.h" -#endif - -#endif // VULKAN_H_ diff --git a/src/external/glfw/deps/vulkan/vulkan_core.h b/src/external/glfw/deps/vulkan/vulkan_core.h deleted file mode 100644 index 20dccc11..00000000 --- a/src/external/glfw/deps/vulkan/vulkan_core.h +++ /dev/null @@ -1,7334 +0,0 @@ -#ifndef VULKAN_CORE_H_ -#define VULKAN_CORE_H_ 1 - -#ifdef __cplusplus -extern "C" { -#endif - -/* -** Copyright (c) 2015-2018 The Khronos Group Inc. -** -** 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 header is generated from the Khronos Vulkan XML API Registry. -** -*/ - - -#define VK_VERSION_1_0 1 -#include "vk_platform.h" - -#define VK_MAKE_VERSION(major, minor, patch) \ - (((major) << 22) | ((minor) << 12) | (patch)) - -// DEPRECATED: This define has been removed. Specific version defines (e.g. VK_API_VERSION_1_0), or the VK_MAKE_VERSION macro, should be used instead. -//#define VK_API_VERSION VK_MAKE_VERSION(1, 0, 0) // Patch version should always be set to 0 - -// Vulkan 1.0 version number -#define VK_API_VERSION_1_0 VK_MAKE_VERSION(1, 0, 0)// Patch version should always be set to 0 - -#define VK_VERSION_MAJOR(version) ((uint32_t)(version) >> 22) -#define VK_VERSION_MINOR(version) (((uint32_t)(version) >> 12) & 0x3ff) -#define VK_VERSION_PATCH(version) ((uint32_t)(version) & 0xfff) -// Version of this file -#define VK_HEADER_VERSION 70 - - -#define VK_NULL_HANDLE 0 - - - -#define VK_DEFINE_HANDLE(object) typedef struct object##_T* object; - - -#if !defined(VK_DEFINE_NON_DISPATCHABLE_HANDLE) -#if defined(__LP64__) || defined(_WIN64) || (defined(__x86_64__) && !defined(__ILP32__) ) || defined(_M_X64) || defined(__ia64) || defined (_M_IA64) || defined(__aarch64__) || defined(__powerpc64__) - #define VK_DEFINE_NON_DISPATCHABLE_HANDLE(object) typedef struct object##_T *object; -#else - #define VK_DEFINE_NON_DISPATCHABLE_HANDLE(object) typedef uint64_t object; -#endif -#endif - - - -typedef uint32_t VkFlags; -typedef uint32_t VkBool32; -typedef uint64_t VkDeviceSize; -typedef uint32_t VkSampleMask; - -VK_DEFINE_HANDLE(VkInstance) -VK_DEFINE_HANDLE(VkPhysicalDevice) -VK_DEFINE_HANDLE(VkDevice) -VK_DEFINE_HANDLE(VkQueue) -VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkSemaphore) -VK_DEFINE_HANDLE(VkCommandBuffer) -VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkFence) -VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkDeviceMemory) -VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkBuffer) -VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkImage) -VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkEvent) -VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkQueryPool) -VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkBufferView) -VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkImageView) -VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkShaderModule) -VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkPipelineCache) -VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkPipelineLayout) -VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkRenderPass) -VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkPipeline) -VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkDescriptorSetLayout) -VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkSampler) -VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkDescriptorPool) -VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkDescriptorSet) -VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkFramebuffer) -VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkCommandPool) - -#define VK_LOD_CLAMP_NONE 1000.0f -#define VK_REMAINING_MIP_LEVELS (~0U) -#define VK_REMAINING_ARRAY_LAYERS (~0U) -#define VK_WHOLE_SIZE (~0ULL) -#define VK_ATTACHMENT_UNUSED (~0U) -#define VK_TRUE 1 -#define VK_FALSE 0 -#define VK_QUEUE_FAMILY_IGNORED (~0U) -#define VK_SUBPASS_EXTERNAL (~0U) -#define VK_MAX_PHYSICAL_DEVICE_NAME_SIZE 256 -#define VK_UUID_SIZE 16 -#define VK_MAX_MEMORY_TYPES 32 -#define VK_MAX_MEMORY_HEAPS 16 -#define VK_MAX_EXTENSION_NAME_SIZE 256 -#define VK_MAX_DESCRIPTION_SIZE 256 - - -typedef enum VkPipelineCacheHeaderVersion { - VK_PIPELINE_CACHE_HEADER_VERSION_ONE = 1, - VK_PIPELINE_CACHE_HEADER_VERSION_BEGIN_RANGE = VK_PIPELINE_CACHE_HEADER_VERSION_ONE, - VK_PIPELINE_CACHE_HEADER_VERSION_END_RANGE = VK_PIPELINE_CACHE_HEADER_VERSION_ONE, - VK_PIPELINE_CACHE_HEADER_VERSION_RANGE_SIZE = (VK_PIPELINE_CACHE_HEADER_VERSION_ONE - VK_PIPELINE_CACHE_HEADER_VERSION_ONE + 1), - VK_PIPELINE_CACHE_HEADER_VERSION_MAX_ENUM = 0x7FFFFFFF -} VkPipelineCacheHeaderVersion; - -typedef enum VkResult { - VK_SUCCESS = 0, - VK_NOT_READY = 1, - VK_TIMEOUT = 2, - VK_EVENT_SET = 3, - VK_EVENT_RESET = 4, - VK_INCOMPLETE = 5, - VK_ERROR_OUT_OF_HOST_MEMORY = -1, - VK_ERROR_OUT_OF_DEVICE_MEMORY = -2, - VK_ERROR_INITIALIZATION_FAILED = -3, - VK_ERROR_DEVICE_LOST = -4, - VK_ERROR_MEMORY_MAP_FAILED = -5, - VK_ERROR_LAYER_NOT_PRESENT = -6, - VK_ERROR_EXTENSION_NOT_PRESENT = -7, - VK_ERROR_FEATURE_NOT_PRESENT = -8, - VK_ERROR_INCOMPATIBLE_DRIVER = -9, - VK_ERROR_TOO_MANY_OBJECTS = -10, - VK_ERROR_FORMAT_NOT_SUPPORTED = -11, - VK_ERROR_FRAGMENTED_POOL = -12, - VK_ERROR_OUT_OF_POOL_MEMORY = -1000069000, - VK_ERROR_INVALID_EXTERNAL_HANDLE = -1000072003, - VK_ERROR_SURFACE_LOST_KHR = -1000000000, - VK_ERROR_NATIVE_WINDOW_IN_USE_KHR = -1000000001, - VK_SUBOPTIMAL_KHR = 1000001003, - VK_ERROR_OUT_OF_DATE_KHR = -1000001004, - VK_ERROR_INCOMPATIBLE_DISPLAY_KHR = -1000003001, - VK_ERROR_VALIDATION_FAILED_EXT = -1000011001, - VK_ERROR_INVALID_SHADER_NV = -1000012000, - VK_ERROR_NOT_PERMITTED_EXT = -1000174001, - VK_ERROR_OUT_OF_POOL_MEMORY_KHR = VK_ERROR_OUT_OF_POOL_MEMORY, - VK_ERROR_INVALID_EXTERNAL_HANDLE_KHR = VK_ERROR_INVALID_EXTERNAL_HANDLE, - VK_RESULT_BEGIN_RANGE = VK_ERROR_FRAGMENTED_POOL, - VK_RESULT_END_RANGE = VK_INCOMPLETE, - VK_RESULT_RANGE_SIZE = (VK_INCOMPLETE - VK_ERROR_FRAGMENTED_POOL + 1), - VK_RESULT_MAX_ENUM = 0x7FFFFFFF -} VkResult; - -typedef enum VkStructureType { - VK_STRUCTURE_TYPE_APPLICATION_INFO = 0, - VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO = 1, - VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO = 2, - VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO = 3, - VK_STRUCTURE_TYPE_SUBMIT_INFO = 4, - VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO = 5, - VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE = 6, - VK_STRUCTURE_TYPE_BIND_SPARSE_INFO = 7, - VK_STRUCTURE_TYPE_FENCE_CREATE_INFO = 8, - VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO = 9, - VK_STRUCTURE_TYPE_EVENT_CREATE_INFO = 10, - VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO = 11, - VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO = 12, - VK_STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO = 13, - VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO = 14, - VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO = 15, - VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO = 16, - VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO = 17, - VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO = 18, - VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO = 19, - VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO = 20, - VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_STATE_CREATE_INFO = 21, - VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO = 22, - VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO = 23, - VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO = 24, - VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO = 25, - VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO = 26, - VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO = 27, - VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO = 28, - VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO = 29, - VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO = 30, - VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO = 31, - VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO = 32, - VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO = 33, - VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO = 34, - VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET = 35, - VK_STRUCTURE_TYPE_COPY_DESCRIPTOR_SET = 36, - VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO = 37, - VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO = 38, - VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO = 39, - VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO = 40, - VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO = 41, - VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO = 42, - VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO = 43, - VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER = 44, - VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER = 45, - VK_STRUCTURE_TYPE_MEMORY_BARRIER = 46, - VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO = 47, - VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO = 48, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES = 1000094000, - VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO = 1000157000, - VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO = 1000157001, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES = 1000083000, - VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS = 1000127000, - VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO = 1000127001, - VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO = 1000060000, - VK_STRUCTURE_TYPE_DEVICE_GROUP_RENDER_PASS_BEGIN_INFO = 1000060003, - VK_STRUCTURE_TYPE_DEVICE_GROUP_COMMAND_BUFFER_BEGIN_INFO = 1000060004, - VK_STRUCTURE_TYPE_DEVICE_GROUP_SUBMIT_INFO = 1000060005, - VK_STRUCTURE_TYPE_DEVICE_GROUP_BIND_SPARSE_INFO = 1000060006, - VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_DEVICE_GROUP_INFO = 1000060013, - VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_DEVICE_GROUP_INFO = 1000060014, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_GROUP_PROPERTIES = 1000070000, - VK_STRUCTURE_TYPE_DEVICE_GROUP_DEVICE_CREATE_INFO = 1000070001, - VK_STRUCTURE_TYPE_BUFFER_MEMORY_REQUIREMENTS_INFO_2 = 1000146000, - VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2 = 1000146001, - VK_STRUCTURE_TYPE_IMAGE_SPARSE_MEMORY_REQUIREMENTS_INFO_2 = 1000146002, - VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2 = 1000146003, - VK_STRUCTURE_TYPE_SPARSE_IMAGE_MEMORY_REQUIREMENTS_2 = 1000146004, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2 = 1000059000, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2 = 1000059001, - VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2 = 1000059002, - VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2 = 1000059003, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2 = 1000059004, - VK_STRUCTURE_TYPE_QUEUE_FAMILY_PROPERTIES_2 = 1000059005, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PROPERTIES_2 = 1000059006, - VK_STRUCTURE_TYPE_SPARSE_IMAGE_FORMAT_PROPERTIES_2 = 1000059007, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SPARSE_IMAGE_FORMAT_INFO_2 = 1000059008, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_POINT_CLIPPING_PROPERTIES = 1000117000, - VK_STRUCTURE_TYPE_RENDER_PASS_INPUT_ATTACHMENT_ASPECT_CREATE_INFO = 1000117001, - VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO = 1000117002, - VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_DOMAIN_ORIGIN_STATE_CREATE_INFO = 1000117003, - VK_STRUCTURE_TYPE_RENDER_PASS_MULTIVIEW_CREATE_INFO = 1000053000, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES = 1000053001, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES = 1000053002, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTER_FEATURES = 1000120000, - VK_STRUCTURE_TYPE_PROTECTED_SUBMIT_INFO = 1000145000, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROTECTED_MEMORY_FEATURES = 1000145001, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROTECTED_MEMORY_PROPERTIES = 1000145002, - VK_STRUCTURE_TYPE_DEVICE_QUEUE_INFO_2 = 1000145003, - VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_CREATE_INFO = 1000156000, - VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_INFO = 1000156001, - VK_STRUCTURE_TYPE_BIND_IMAGE_PLANE_MEMORY_INFO = 1000156002, - VK_STRUCTURE_TYPE_IMAGE_PLANE_MEMORY_REQUIREMENTS_INFO = 1000156003, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES = 1000156004, - VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_IMAGE_FORMAT_PROPERTIES = 1000156005, - VK_STRUCTURE_TYPE_DESCRIPTOR_UPDATE_TEMPLATE_CREATE_INFO = 1000085000, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO = 1000071000, - VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES = 1000071001, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_BUFFER_INFO = 1000071002, - VK_STRUCTURE_TYPE_EXTERNAL_BUFFER_PROPERTIES = 1000071003, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES = 1000071004, - VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO = 1000072000, - VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO = 1000072001, - VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO = 1000072002, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_FENCE_INFO = 1000112000, - VK_STRUCTURE_TYPE_EXTERNAL_FENCE_PROPERTIES = 1000112001, - VK_STRUCTURE_TYPE_EXPORT_FENCE_CREATE_INFO = 1000113000, - VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO = 1000077000, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_SEMAPHORE_INFO = 1000076000, - VK_STRUCTURE_TYPE_EXTERNAL_SEMAPHORE_PROPERTIES = 1000076001, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_3_PROPERTIES = 1000168000, - VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_SUPPORT = 1000168001, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DRAW_PARAMETER_FEATURES = 1000063000, - VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR = 1000001000, - VK_STRUCTURE_TYPE_PRESENT_INFO_KHR = 1000001001, - VK_STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_CAPABILITIES_KHR = 1000060007, - VK_STRUCTURE_TYPE_IMAGE_SWAPCHAIN_CREATE_INFO_KHR = 1000060008, - VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR = 1000060009, - VK_STRUCTURE_TYPE_ACQUIRE_NEXT_IMAGE_INFO_KHR = 1000060010, - VK_STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_INFO_KHR = 1000060011, - VK_STRUCTURE_TYPE_DEVICE_GROUP_SWAPCHAIN_CREATE_INFO_KHR = 1000060012, - VK_STRUCTURE_TYPE_DISPLAY_MODE_CREATE_INFO_KHR = 1000002000, - VK_STRUCTURE_TYPE_DISPLAY_SURFACE_CREATE_INFO_KHR = 1000002001, - VK_STRUCTURE_TYPE_DISPLAY_PRESENT_INFO_KHR = 1000003000, - VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR = 1000004000, - VK_STRUCTURE_TYPE_XCB_SURFACE_CREATE_INFO_KHR = 1000005000, - VK_STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR = 1000006000, - VK_STRUCTURE_TYPE_MIR_SURFACE_CREATE_INFO_KHR = 1000007000, - VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR = 1000008000, - VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR = 1000009000, - VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT = 1000011000, - VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_RASTERIZATION_ORDER_AMD = 1000018000, - VK_STRUCTURE_TYPE_DEBUG_MARKER_OBJECT_NAME_INFO_EXT = 1000022000, - VK_STRUCTURE_TYPE_DEBUG_MARKER_OBJECT_TAG_INFO_EXT = 1000022001, - VK_STRUCTURE_TYPE_DEBUG_MARKER_MARKER_INFO_EXT = 1000022002, - VK_STRUCTURE_TYPE_DEDICATED_ALLOCATION_IMAGE_CREATE_INFO_NV = 1000026000, - VK_STRUCTURE_TYPE_DEDICATED_ALLOCATION_BUFFER_CREATE_INFO_NV = 1000026001, - VK_STRUCTURE_TYPE_DEDICATED_ALLOCATION_MEMORY_ALLOCATE_INFO_NV = 1000026002, - VK_STRUCTURE_TYPE_TEXTURE_LOD_GATHER_FORMAT_PROPERTIES_AMD = 1000041000, - VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO_NV = 1000056000, - VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO_NV = 1000056001, - VK_STRUCTURE_TYPE_IMPORT_MEMORY_WIN32_HANDLE_INFO_NV = 1000057000, - VK_STRUCTURE_TYPE_EXPORT_MEMORY_WIN32_HANDLE_INFO_NV = 1000057001, - VK_STRUCTURE_TYPE_WIN32_KEYED_MUTEX_ACQUIRE_RELEASE_INFO_NV = 1000058000, - VK_STRUCTURE_TYPE_VALIDATION_FLAGS_EXT = 1000061000, - VK_STRUCTURE_TYPE_VI_SURFACE_CREATE_INFO_NN = 1000062000, - VK_STRUCTURE_TYPE_IMPORT_MEMORY_WIN32_HANDLE_INFO_KHR = 1000073000, - VK_STRUCTURE_TYPE_EXPORT_MEMORY_WIN32_HANDLE_INFO_KHR = 1000073001, - VK_STRUCTURE_TYPE_MEMORY_WIN32_HANDLE_PROPERTIES_KHR = 1000073002, - VK_STRUCTURE_TYPE_MEMORY_GET_WIN32_HANDLE_INFO_KHR = 1000073003, - VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR = 1000074000, - VK_STRUCTURE_TYPE_MEMORY_FD_PROPERTIES_KHR = 1000074001, - VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR = 1000074002, - VK_STRUCTURE_TYPE_WIN32_KEYED_MUTEX_ACQUIRE_RELEASE_INFO_KHR = 1000075000, - VK_STRUCTURE_TYPE_IMPORT_SEMAPHORE_WIN32_HANDLE_INFO_KHR = 1000078000, - VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_WIN32_HANDLE_INFO_KHR = 1000078001, - VK_STRUCTURE_TYPE_D3D12_FENCE_SUBMIT_INFO_KHR = 1000078002, - VK_STRUCTURE_TYPE_SEMAPHORE_GET_WIN32_HANDLE_INFO_KHR = 1000078003, - VK_STRUCTURE_TYPE_IMPORT_SEMAPHORE_FD_INFO_KHR = 1000079000, - VK_STRUCTURE_TYPE_SEMAPHORE_GET_FD_INFO_KHR = 1000079001, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PUSH_DESCRIPTOR_PROPERTIES_KHR = 1000080000, - VK_STRUCTURE_TYPE_PRESENT_REGIONS_KHR = 1000084000, - VK_STRUCTURE_TYPE_OBJECT_TABLE_CREATE_INFO_NVX = 1000086000, - VK_STRUCTURE_TYPE_INDIRECT_COMMANDS_LAYOUT_CREATE_INFO_NVX = 1000086001, - VK_STRUCTURE_TYPE_CMD_PROCESS_COMMANDS_INFO_NVX = 1000086002, - VK_STRUCTURE_TYPE_CMD_RESERVE_SPACE_FOR_COMMANDS_INFO_NVX = 1000086003, - VK_STRUCTURE_TYPE_DEVICE_GENERATED_COMMANDS_LIMITS_NVX = 1000086004, - VK_STRUCTURE_TYPE_DEVICE_GENERATED_COMMANDS_FEATURES_NVX = 1000086005, - VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_W_SCALING_STATE_CREATE_INFO_NV = 1000087000, - VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_EXT = 1000090000, - VK_STRUCTURE_TYPE_DISPLAY_POWER_INFO_EXT = 1000091000, - VK_STRUCTURE_TYPE_DEVICE_EVENT_INFO_EXT = 1000091001, - VK_STRUCTURE_TYPE_DISPLAY_EVENT_INFO_EXT = 1000091002, - VK_STRUCTURE_TYPE_SWAPCHAIN_COUNTER_CREATE_INFO_EXT = 1000091003, - VK_STRUCTURE_TYPE_PRESENT_TIMES_INFO_GOOGLE = 1000092000, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PER_VIEW_ATTRIBUTES_PROPERTIES_NVX = 1000097000, - VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_SWIZZLE_STATE_CREATE_INFO_NV = 1000098000, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DISCARD_RECTANGLE_PROPERTIES_EXT = 1000099000, - VK_STRUCTURE_TYPE_PIPELINE_DISCARD_RECTANGLE_STATE_CREATE_INFO_EXT = 1000099001, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONSERVATIVE_RASTERIZATION_PROPERTIES_EXT = 1000101000, - VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_CONSERVATIVE_STATE_CREATE_INFO_EXT = 1000101001, - VK_STRUCTURE_TYPE_HDR_METADATA_EXT = 1000105000, - VK_STRUCTURE_TYPE_SHARED_PRESENT_SURFACE_CAPABILITIES_KHR = 1000111000, - VK_STRUCTURE_TYPE_IMPORT_FENCE_WIN32_HANDLE_INFO_KHR = 1000114000, - VK_STRUCTURE_TYPE_EXPORT_FENCE_WIN32_HANDLE_INFO_KHR = 1000114001, - VK_STRUCTURE_TYPE_FENCE_GET_WIN32_HANDLE_INFO_KHR = 1000114002, - VK_STRUCTURE_TYPE_IMPORT_FENCE_FD_INFO_KHR = 1000115000, - VK_STRUCTURE_TYPE_FENCE_GET_FD_INFO_KHR = 1000115001, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SURFACE_INFO_2_KHR = 1000119000, - VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_KHR = 1000119001, - VK_STRUCTURE_TYPE_SURFACE_FORMAT_2_KHR = 1000119002, - VK_STRUCTURE_TYPE_IOS_SURFACE_CREATE_INFO_MVK = 1000122000, - VK_STRUCTURE_TYPE_MACOS_SURFACE_CREATE_INFO_MVK = 1000123000, - VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT = 1000128000, - VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_TAG_INFO_EXT = 1000128001, - VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT = 1000128002, - VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CALLBACK_DATA_EXT = 1000128003, - VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT = 1000128004, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_FILTER_MINMAX_PROPERTIES_EXT = 1000130000, - VK_STRUCTURE_TYPE_SAMPLER_REDUCTION_MODE_CREATE_INFO_EXT = 1000130001, - VK_STRUCTURE_TYPE_SAMPLE_LOCATIONS_INFO_EXT = 1000143000, - VK_STRUCTURE_TYPE_RENDER_PASS_SAMPLE_LOCATIONS_BEGIN_INFO_EXT = 1000143001, - VK_STRUCTURE_TYPE_PIPELINE_SAMPLE_LOCATIONS_STATE_CREATE_INFO_EXT = 1000143002, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLE_LOCATIONS_PROPERTIES_EXT = 1000143003, - VK_STRUCTURE_TYPE_MULTISAMPLE_PROPERTIES_EXT = 1000143004, - VK_STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO_KHR = 1000147000, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BLEND_OPERATION_ADVANCED_FEATURES_EXT = 1000148000, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BLEND_OPERATION_ADVANCED_PROPERTIES_EXT = 1000148001, - VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_ADVANCED_STATE_CREATE_INFO_EXT = 1000148002, - VK_STRUCTURE_TYPE_PIPELINE_COVERAGE_TO_COLOR_STATE_CREATE_INFO_NV = 1000149000, - VK_STRUCTURE_TYPE_PIPELINE_COVERAGE_MODULATION_STATE_CREATE_INFO_NV = 1000152000, - VK_STRUCTURE_TYPE_VALIDATION_CACHE_CREATE_INFO_EXT = 1000160000, - VK_STRUCTURE_TYPE_SHADER_MODULE_VALIDATION_CACHE_CREATE_INFO_EXT = 1000160001, - VK_STRUCTURE_TYPE_DEVICE_QUEUE_GLOBAL_PRIORITY_CREATE_INFO_EXT = 1000174000, - VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT = 1000178000, - VK_STRUCTURE_TYPE_MEMORY_HOST_POINTER_PROPERTIES_EXT = 1000178001, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_MEMORY_HOST_PROPERTIES_EXT = 1000178002, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_PROPERTIES_EXT = 1000190000, - VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_DIVISOR_STATE_CREATE_INFO_EXT = 1000190001, - VK_STRUCTURE_TYPE_RENDER_PASS_MULTIVIEW_CREATE_INFO_KHR = VK_STRUCTURE_TYPE_RENDER_PASS_MULTIVIEW_CREATE_INFO, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES_KHR = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES_KHR = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2_KHR = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2_KHR = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, - VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2_KHR = VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2, - VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2_KHR = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2_KHR = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2, - VK_STRUCTURE_TYPE_QUEUE_FAMILY_PROPERTIES_2_KHR = VK_STRUCTURE_TYPE_QUEUE_FAMILY_PROPERTIES_2, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PROPERTIES_2_KHR = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PROPERTIES_2, - VK_STRUCTURE_TYPE_SPARSE_IMAGE_FORMAT_PROPERTIES_2_KHR = VK_STRUCTURE_TYPE_SPARSE_IMAGE_FORMAT_PROPERTIES_2, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SPARSE_IMAGE_FORMAT_INFO_2_KHR = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SPARSE_IMAGE_FORMAT_INFO_2, - VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO_KHR = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO, - VK_STRUCTURE_TYPE_DEVICE_GROUP_RENDER_PASS_BEGIN_INFO_KHR = VK_STRUCTURE_TYPE_DEVICE_GROUP_RENDER_PASS_BEGIN_INFO, - VK_STRUCTURE_TYPE_DEVICE_GROUP_COMMAND_BUFFER_BEGIN_INFO_KHR = VK_STRUCTURE_TYPE_DEVICE_GROUP_COMMAND_BUFFER_BEGIN_INFO, - VK_STRUCTURE_TYPE_DEVICE_GROUP_SUBMIT_INFO_KHR = VK_STRUCTURE_TYPE_DEVICE_GROUP_SUBMIT_INFO, - VK_STRUCTURE_TYPE_DEVICE_GROUP_BIND_SPARSE_INFO_KHR = VK_STRUCTURE_TYPE_DEVICE_GROUP_BIND_SPARSE_INFO, - VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_DEVICE_GROUP_INFO_KHR = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_DEVICE_GROUP_INFO, - VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_DEVICE_GROUP_INFO_KHR = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_DEVICE_GROUP_INFO, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_GROUP_PROPERTIES_KHR = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_GROUP_PROPERTIES, - VK_STRUCTURE_TYPE_DEVICE_GROUP_DEVICE_CREATE_INFO_KHR = VK_STRUCTURE_TYPE_DEVICE_GROUP_DEVICE_CREATE_INFO, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO_KHR = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO, - VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES_KHR = VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_BUFFER_INFO_KHR = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_BUFFER_INFO, - VK_STRUCTURE_TYPE_EXTERNAL_BUFFER_PROPERTIES_KHR = VK_STRUCTURE_TYPE_EXTERNAL_BUFFER_PROPERTIES, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES_KHR = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES, - VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO_KHR = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO, - VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO_KHR = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO, - VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO_KHR = VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_SEMAPHORE_INFO_KHR = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_SEMAPHORE_INFO, - VK_STRUCTURE_TYPE_EXTERNAL_SEMAPHORE_PROPERTIES_KHR = VK_STRUCTURE_TYPE_EXTERNAL_SEMAPHORE_PROPERTIES, - VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO_KHR = VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES_KHR = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES, - VK_STRUCTURE_TYPE_DESCRIPTOR_UPDATE_TEMPLATE_CREATE_INFO_KHR = VK_STRUCTURE_TYPE_DESCRIPTOR_UPDATE_TEMPLATE_CREATE_INFO, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_FENCE_INFO_KHR = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_FENCE_INFO, - VK_STRUCTURE_TYPE_EXTERNAL_FENCE_PROPERTIES_KHR = VK_STRUCTURE_TYPE_EXTERNAL_FENCE_PROPERTIES, - VK_STRUCTURE_TYPE_EXPORT_FENCE_CREATE_INFO_KHR = VK_STRUCTURE_TYPE_EXPORT_FENCE_CREATE_INFO, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_POINT_CLIPPING_PROPERTIES_KHR = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_POINT_CLIPPING_PROPERTIES, - VK_STRUCTURE_TYPE_RENDER_PASS_INPUT_ATTACHMENT_ASPECT_CREATE_INFO_KHR = VK_STRUCTURE_TYPE_RENDER_PASS_INPUT_ATTACHMENT_ASPECT_CREATE_INFO, - VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO_KHR = VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO, - VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_DOMAIN_ORIGIN_STATE_CREATE_INFO_KHR = VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_DOMAIN_ORIGIN_STATE_CREATE_INFO, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTER_FEATURES_KHR = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTER_FEATURES, - VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS, - VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO_KHR = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO, - VK_STRUCTURE_TYPE_BUFFER_MEMORY_REQUIREMENTS_INFO_2_KHR = VK_STRUCTURE_TYPE_BUFFER_MEMORY_REQUIREMENTS_INFO_2, - VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2_KHR = VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2, - VK_STRUCTURE_TYPE_IMAGE_SPARSE_MEMORY_REQUIREMENTS_INFO_2_KHR = VK_STRUCTURE_TYPE_IMAGE_SPARSE_MEMORY_REQUIREMENTS_INFO_2, - VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2_KHR = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2, - VK_STRUCTURE_TYPE_SPARSE_IMAGE_MEMORY_REQUIREMENTS_2_KHR = VK_STRUCTURE_TYPE_SPARSE_IMAGE_MEMORY_REQUIREMENTS_2, - VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_CREATE_INFO_KHR = VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_CREATE_INFO, - VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_INFO_KHR = VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_INFO, - VK_STRUCTURE_TYPE_BIND_IMAGE_PLANE_MEMORY_INFO_KHR = VK_STRUCTURE_TYPE_BIND_IMAGE_PLANE_MEMORY_INFO, - VK_STRUCTURE_TYPE_IMAGE_PLANE_MEMORY_REQUIREMENTS_INFO_KHR = VK_STRUCTURE_TYPE_IMAGE_PLANE_MEMORY_REQUIREMENTS_INFO, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES_KHR = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES, - VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_IMAGE_FORMAT_PROPERTIES_KHR = VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_IMAGE_FORMAT_PROPERTIES, - VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO_KHR = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO, - VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO_KHR = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO, - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_3_PROPERTIES_KHR = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_3_PROPERTIES, - VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_SUPPORT_KHR = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_SUPPORT, - VK_STRUCTURE_TYPE_BEGIN_RANGE = VK_STRUCTURE_TYPE_APPLICATION_INFO, - VK_STRUCTURE_TYPE_END_RANGE = VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO, - VK_STRUCTURE_TYPE_RANGE_SIZE = (VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO - VK_STRUCTURE_TYPE_APPLICATION_INFO + 1), - VK_STRUCTURE_TYPE_MAX_ENUM = 0x7FFFFFFF -} VkStructureType; - -typedef enum VkSystemAllocationScope { - VK_SYSTEM_ALLOCATION_SCOPE_COMMAND = 0, - VK_SYSTEM_ALLOCATION_SCOPE_OBJECT = 1, - VK_SYSTEM_ALLOCATION_SCOPE_CACHE = 2, - VK_SYSTEM_ALLOCATION_SCOPE_DEVICE = 3, - VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE = 4, - VK_SYSTEM_ALLOCATION_SCOPE_BEGIN_RANGE = VK_SYSTEM_ALLOCATION_SCOPE_COMMAND, - VK_SYSTEM_ALLOCATION_SCOPE_END_RANGE = VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE, - VK_SYSTEM_ALLOCATION_SCOPE_RANGE_SIZE = (VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE - VK_SYSTEM_ALLOCATION_SCOPE_COMMAND + 1), - VK_SYSTEM_ALLOCATION_SCOPE_MAX_ENUM = 0x7FFFFFFF -} VkSystemAllocationScope; - -typedef enum VkInternalAllocationType { - VK_INTERNAL_ALLOCATION_TYPE_EXECUTABLE = 0, - VK_INTERNAL_ALLOCATION_TYPE_BEGIN_RANGE = VK_INTERNAL_ALLOCATION_TYPE_EXECUTABLE, - VK_INTERNAL_ALLOCATION_TYPE_END_RANGE = VK_INTERNAL_ALLOCATION_TYPE_EXECUTABLE, - VK_INTERNAL_ALLOCATION_TYPE_RANGE_SIZE = (VK_INTERNAL_ALLOCATION_TYPE_EXECUTABLE - VK_INTERNAL_ALLOCATION_TYPE_EXECUTABLE + 1), - VK_INTERNAL_ALLOCATION_TYPE_MAX_ENUM = 0x7FFFFFFF -} VkInternalAllocationType; - -typedef enum VkFormat { - VK_FORMAT_UNDEFINED = 0, - VK_FORMAT_R4G4_UNORM_PACK8 = 1, - VK_FORMAT_R4G4B4A4_UNORM_PACK16 = 2, - VK_FORMAT_B4G4R4A4_UNORM_PACK16 = 3, - VK_FORMAT_R5G6B5_UNORM_PACK16 = 4, - VK_FORMAT_B5G6R5_UNORM_PACK16 = 5, - VK_FORMAT_R5G5B5A1_UNORM_PACK16 = 6, - VK_FORMAT_B5G5R5A1_UNORM_PACK16 = 7, - VK_FORMAT_A1R5G5B5_UNORM_PACK16 = 8, - VK_FORMAT_R8_UNORM = 9, - VK_FORMAT_R8_SNORM = 10, - VK_FORMAT_R8_USCALED = 11, - VK_FORMAT_R8_SSCALED = 12, - VK_FORMAT_R8_UINT = 13, - VK_FORMAT_R8_SINT = 14, - VK_FORMAT_R8_SRGB = 15, - VK_FORMAT_R8G8_UNORM = 16, - VK_FORMAT_R8G8_SNORM = 17, - VK_FORMAT_R8G8_USCALED = 18, - VK_FORMAT_R8G8_SSCALED = 19, - VK_FORMAT_R8G8_UINT = 20, - VK_FORMAT_R8G8_SINT = 21, - VK_FORMAT_R8G8_SRGB = 22, - VK_FORMAT_R8G8B8_UNORM = 23, - VK_FORMAT_R8G8B8_SNORM = 24, - VK_FORMAT_R8G8B8_USCALED = 25, - VK_FORMAT_R8G8B8_SSCALED = 26, - VK_FORMAT_R8G8B8_UINT = 27, - VK_FORMAT_R8G8B8_SINT = 28, - VK_FORMAT_R8G8B8_SRGB = 29, - VK_FORMAT_B8G8R8_UNORM = 30, - VK_FORMAT_B8G8R8_SNORM = 31, - VK_FORMAT_B8G8R8_USCALED = 32, - VK_FORMAT_B8G8R8_SSCALED = 33, - VK_FORMAT_B8G8R8_UINT = 34, - VK_FORMAT_B8G8R8_SINT = 35, - VK_FORMAT_B8G8R8_SRGB = 36, - VK_FORMAT_R8G8B8A8_UNORM = 37, - VK_FORMAT_R8G8B8A8_SNORM = 38, - VK_FORMAT_R8G8B8A8_USCALED = 39, - VK_FORMAT_R8G8B8A8_SSCALED = 40, - VK_FORMAT_R8G8B8A8_UINT = 41, - VK_FORMAT_R8G8B8A8_SINT = 42, - VK_FORMAT_R8G8B8A8_SRGB = 43, - VK_FORMAT_B8G8R8A8_UNORM = 44, - VK_FORMAT_B8G8R8A8_SNORM = 45, - VK_FORMAT_B8G8R8A8_USCALED = 46, - VK_FORMAT_B8G8R8A8_SSCALED = 47, - VK_FORMAT_B8G8R8A8_UINT = 48, - VK_FORMAT_B8G8R8A8_SINT = 49, - VK_FORMAT_B8G8R8A8_SRGB = 50, - VK_FORMAT_A8B8G8R8_UNORM_PACK32 = 51, - VK_FORMAT_A8B8G8R8_SNORM_PACK32 = 52, - VK_FORMAT_A8B8G8R8_USCALED_PACK32 = 53, - VK_FORMAT_A8B8G8R8_SSCALED_PACK32 = 54, - VK_FORMAT_A8B8G8R8_UINT_PACK32 = 55, - VK_FORMAT_A8B8G8R8_SINT_PACK32 = 56, - VK_FORMAT_A8B8G8R8_SRGB_PACK32 = 57, - VK_FORMAT_A2R10G10B10_UNORM_PACK32 = 58, - VK_FORMAT_A2R10G10B10_SNORM_PACK32 = 59, - VK_FORMAT_A2R10G10B10_USCALED_PACK32 = 60, - VK_FORMAT_A2R10G10B10_SSCALED_PACK32 = 61, - VK_FORMAT_A2R10G10B10_UINT_PACK32 = 62, - VK_FORMAT_A2R10G10B10_SINT_PACK32 = 63, - VK_FORMAT_A2B10G10R10_UNORM_PACK32 = 64, - VK_FORMAT_A2B10G10R10_SNORM_PACK32 = 65, - VK_FORMAT_A2B10G10R10_USCALED_PACK32 = 66, - VK_FORMAT_A2B10G10R10_SSCALED_PACK32 = 67, - VK_FORMAT_A2B10G10R10_UINT_PACK32 = 68, - VK_FORMAT_A2B10G10R10_SINT_PACK32 = 69, - VK_FORMAT_R16_UNORM = 70, - VK_FORMAT_R16_SNORM = 71, - VK_FORMAT_R16_USCALED = 72, - VK_FORMAT_R16_SSCALED = 73, - VK_FORMAT_R16_UINT = 74, - VK_FORMAT_R16_SINT = 75, - VK_FORMAT_R16_SFLOAT = 76, - VK_FORMAT_R16G16_UNORM = 77, - VK_FORMAT_R16G16_SNORM = 78, - VK_FORMAT_R16G16_USCALED = 79, - VK_FORMAT_R16G16_SSCALED = 80, - VK_FORMAT_R16G16_UINT = 81, - VK_FORMAT_R16G16_SINT = 82, - VK_FORMAT_R16G16_SFLOAT = 83, - VK_FORMAT_R16G16B16_UNORM = 84, - VK_FORMAT_R16G16B16_SNORM = 85, - VK_FORMAT_R16G16B16_USCALED = 86, - VK_FORMAT_R16G16B16_SSCALED = 87, - VK_FORMAT_R16G16B16_UINT = 88, - VK_FORMAT_R16G16B16_SINT = 89, - VK_FORMAT_R16G16B16_SFLOAT = 90, - VK_FORMAT_R16G16B16A16_UNORM = 91, - VK_FORMAT_R16G16B16A16_SNORM = 92, - VK_FORMAT_R16G16B16A16_USCALED = 93, - VK_FORMAT_R16G16B16A16_SSCALED = 94, - VK_FORMAT_R16G16B16A16_UINT = 95, - VK_FORMAT_R16G16B16A16_SINT = 96, - VK_FORMAT_R16G16B16A16_SFLOAT = 97, - VK_FORMAT_R32_UINT = 98, - VK_FORMAT_R32_SINT = 99, - VK_FORMAT_R32_SFLOAT = 100, - VK_FORMAT_R32G32_UINT = 101, - VK_FORMAT_R32G32_SINT = 102, - VK_FORMAT_R32G32_SFLOAT = 103, - VK_FORMAT_R32G32B32_UINT = 104, - VK_FORMAT_R32G32B32_SINT = 105, - VK_FORMAT_R32G32B32_SFLOAT = 106, - VK_FORMAT_R32G32B32A32_UINT = 107, - VK_FORMAT_R32G32B32A32_SINT = 108, - VK_FORMAT_R32G32B32A32_SFLOAT = 109, - VK_FORMAT_R64_UINT = 110, - VK_FORMAT_R64_SINT = 111, - VK_FORMAT_R64_SFLOAT = 112, - VK_FORMAT_R64G64_UINT = 113, - VK_FORMAT_R64G64_SINT = 114, - VK_FORMAT_R64G64_SFLOAT = 115, - VK_FORMAT_R64G64B64_UINT = 116, - VK_FORMAT_R64G64B64_SINT = 117, - VK_FORMAT_R64G64B64_SFLOAT = 118, - VK_FORMAT_R64G64B64A64_UINT = 119, - VK_FORMAT_R64G64B64A64_SINT = 120, - VK_FORMAT_R64G64B64A64_SFLOAT = 121, - VK_FORMAT_B10G11R11_UFLOAT_PACK32 = 122, - VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 = 123, - VK_FORMAT_D16_UNORM = 124, - VK_FORMAT_X8_D24_UNORM_PACK32 = 125, - VK_FORMAT_D32_SFLOAT = 126, - VK_FORMAT_S8_UINT = 127, - VK_FORMAT_D16_UNORM_S8_UINT = 128, - VK_FORMAT_D24_UNORM_S8_UINT = 129, - VK_FORMAT_D32_SFLOAT_S8_UINT = 130, - VK_FORMAT_BC1_RGB_UNORM_BLOCK = 131, - VK_FORMAT_BC1_RGB_SRGB_BLOCK = 132, - VK_FORMAT_BC1_RGBA_UNORM_BLOCK = 133, - VK_FORMAT_BC1_RGBA_SRGB_BLOCK = 134, - VK_FORMAT_BC2_UNORM_BLOCK = 135, - VK_FORMAT_BC2_SRGB_BLOCK = 136, - VK_FORMAT_BC3_UNORM_BLOCK = 137, - VK_FORMAT_BC3_SRGB_BLOCK = 138, - VK_FORMAT_BC4_UNORM_BLOCK = 139, - VK_FORMAT_BC4_SNORM_BLOCK = 140, - VK_FORMAT_BC5_UNORM_BLOCK = 141, - VK_FORMAT_BC5_SNORM_BLOCK = 142, - VK_FORMAT_BC6H_UFLOAT_BLOCK = 143, - VK_FORMAT_BC6H_SFLOAT_BLOCK = 144, - VK_FORMAT_BC7_UNORM_BLOCK = 145, - VK_FORMAT_BC7_SRGB_BLOCK = 146, - VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK = 147, - VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK = 148, - VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK = 149, - VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK = 150, - VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK = 151, - VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK = 152, - VK_FORMAT_EAC_R11_UNORM_BLOCK = 153, - VK_FORMAT_EAC_R11_SNORM_BLOCK = 154, - VK_FORMAT_EAC_R11G11_UNORM_BLOCK = 155, - VK_FORMAT_EAC_R11G11_SNORM_BLOCK = 156, - VK_FORMAT_ASTC_4x4_UNORM_BLOCK = 157, - VK_FORMAT_ASTC_4x4_SRGB_BLOCK = 158, - VK_FORMAT_ASTC_5x4_UNORM_BLOCK = 159, - VK_FORMAT_ASTC_5x4_SRGB_BLOCK = 160, - VK_FORMAT_ASTC_5x5_UNORM_BLOCK = 161, - VK_FORMAT_ASTC_5x5_SRGB_BLOCK = 162, - VK_FORMAT_ASTC_6x5_UNORM_BLOCK = 163, - VK_FORMAT_ASTC_6x5_SRGB_BLOCK = 164, - VK_FORMAT_ASTC_6x6_UNORM_BLOCK = 165, - VK_FORMAT_ASTC_6x6_SRGB_BLOCK = 166, - VK_FORMAT_ASTC_8x5_UNORM_BLOCK = 167, - VK_FORMAT_ASTC_8x5_SRGB_BLOCK = 168, - VK_FORMAT_ASTC_8x6_UNORM_BLOCK = 169, - VK_FORMAT_ASTC_8x6_SRGB_BLOCK = 170, - VK_FORMAT_ASTC_8x8_UNORM_BLOCK = 171, - VK_FORMAT_ASTC_8x8_SRGB_BLOCK = 172, - VK_FORMAT_ASTC_10x5_UNORM_BLOCK = 173, - VK_FORMAT_ASTC_10x5_SRGB_BLOCK = 174, - VK_FORMAT_ASTC_10x6_UNORM_BLOCK = 175, - VK_FORMAT_ASTC_10x6_SRGB_BLOCK = 176, - VK_FORMAT_ASTC_10x8_UNORM_BLOCK = 177, - VK_FORMAT_ASTC_10x8_SRGB_BLOCK = 178, - VK_FORMAT_ASTC_10x10_UNORM_BLOCK = 179, - VK_FORMAT_ASTC_10x10_SRGB_BLOCK = 180, - VK_FORMAT_ASTC_12x10_UNORM_BLOCK = 181, - VK_FORMAT_ASTC_12x10_SRGB_BLOCK = 182, - VK_FORMAT_ASTC_12x12_UNORM_BLOCK = 183, - VK_FORMAT_ASTC_12x12_SRGB_BLOCK = 184, - VK_FORMAT_G8B8G8R8_422_UNORM = 1000156000, - VK_FORMAT_B8G8R8G8_422_UNORM = 1000156001, - VK_FORMAT_G8_B8_R8_3PLANE_420_UNORM = 1000156002, - VK_FORMAT_G8_B8R8_2PLANE_420_UNORM = 1000156003, - VK_FORMAT_G8_B8_R8_3PLANE_422_UNORM = 1000156004, - VK_FORMAT_G8_B8R8_2PLANE_422_UNORM = 1000156005, - VK_FORMAT_G8_B8_R8_3PLANE_444_UNORM = 1000156006, - VK_FORMAT_R10X6_UNORM_PACK16 = 1000156007, - VK_FORMAT_R10X6G10X6_UNORM_2PACK16 = 1000156008, - VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16 = 1000156009, - VK_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16 = 1000156010, - VK_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16 = 1000156011, - VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_420_UNORM_3PACK16 = 1000156012, - VK_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16 = 1000156013, - VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_422_UNORM_3PACK16 = 1000156014, - VK_FORMAT_G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16 = 1000156015, - VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16 = 1000156016, - VK_FORMAT_R12X4_UNORM_PACK16 = 1000156017, - VK_FORMAT_R12X4G12X4_UNORM_2PACK16 = 1000156018, - VK_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16 = 1000156019, - VK_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16 = 1000156020, - VK_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16 = 1000156021, - VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_420_UNORM_3PACK16 = 1000156022, - VK_FORMAT_G12X4_B12X4R12X4_2PLANE_420_UNORM_3PACK16 = 1000156023, - VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_422_UNORM_3PACK16 = 1000156024, - VK_FORMAT_G12X4_B12X4R12X4_2PLANE_422_UNORM_3PACK16 = 1000156025, - VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_444_UNORM_3PACK16 = 1000156026, - VK_FORMAT_G16B16G16R16_422_UNORM = 1000156027, - VK_FORMAT_B16G16R16G16_422_UNORM = 1000156028, - VK_FORMAT_G16_B16_R16_3PLANE_420_UNORM = 1000156029, - VK_FORMAT_G16_B16R16_2PLANE_420_UNORM = 1000156030, - VK_FORMAT_G16_B16_R16_3PLANE_422_UNORM = 1000156031, - VK_FORMAT_G16_B16R16_2PLANE_422_UNORM = 1000156032, - VK_FORMAT_G16_B16_R16_3PLANE_444_UNORM = 1000156033, - VK_FORMAT_PVRTC1_2BPP_UNORM_BLOCK_IMG = 1000054000, - VK_FORMAT_PVRTC1_4BPP_UNORM_BLOCK_IMG = 1000054001, - VK_FORMAT_PVRTC2_2BPP_UNORM_BLOCK_IMG = 1000054002, - VK_FORMAT_PVRTC2_4BPP_UNORM_BLOCK_IMG = 1000054003, - VK_FORMAT_PVRTC1_2BPP_SRGB_BLOCK_IMG = 1000054004, - VK_FORMAT_PVRTC1_4BPP_SRGB_BLOCK_IMG = 1000054005, - VK_FORMAT_PVRTC2_2BPP_SRGB_BLOCK_IMG = 1000054006, - VK_FORMAT_PVRTC2_4BPP_SRGB_BLOCK_IMG = 1000054007, - VK_FORMAT_G8B8G8R8_422_UNORM_KHR = VK_FORMAT_G8B8G8R8_422_UNORM, - VK_FORMAT_B8G8R8G8_422_UNORM_KHR = VK_FORMAT_B8G8R8G8_422_UNORM, - VK_FORMAT_G8_B8_R8_3PLANE_420_UNORM_KHR = VK_FORMAT_G8_B8_R8_3PLANE_420_UNORM, - VK_FORMAT_G8_B8R8_2PLANE_420_UNORM_KHR = VK_FORMAT_G8_B8R8_2PLANE_420_UNORM, - VK_FORMAT_G8_B8_R8_3PLANE_422_UNORM_KHR = VK_FORMAT_G8_B8_R8_3PLANE_422_UNORM, - VK_FORMAT_G8_B8R8_2PLANE_422_UNORM_KHR = VK_FORMAT_G8_B8R8_2PLANE_422_UNORM, - VK_FORMAT_G8_B8_R8_3PLANE_444_UNORM_KHR = VK_FORMAT_G8_B8_R8_3PLANE_444_UNORM, - VK_FORMAT_R10X6_UNORM_PACK16_KHR = VK_FORMAT_R10X6_UNORM_PACK16, - VK_FORMAT_R10X6G10X6_UNORM_2PACK16_KHR = VK_FORMAT_R10X6G10X6_UNORM_2PACK16, - VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16_KHR = VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16, - VK_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16_KHR = VK_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16, - VK_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16_KHR = VK_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16, - VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_420_UNORM_3PACK16_KHR = VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_420_UNORM_3PACK16, - VK_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16_KHR = VK_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16, - VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_422_UNORM_3PACK16_KHR = VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_422_UNORM_3PACK16, - VK_FORMAT_G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16_KHR = VK_FORMAT_G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16, - VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16_KHR = VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16, - VK_FORMAT_R12X4_UNORM_PACK16_KHR = VK_FORMAT_R12X4_UNORM_PACK16, - VK_FORMAT_R12X4G12X4_UNORM_2PACK16_KHR = VK_FORMAT_R12X4G12X4_UNORM_2PACK16, - VK_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16_KHR = VK_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16, - VK_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16_KHR = VK_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16, - VK_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16_KHR = VK_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16, - VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_420_UNORM_3PACK16_KHR = VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_420_UNORM_3PACK16, - VK_FORMAT_G12X4_B12X4R12X4_2PLANE_420_UNORM_3PACK16_KHR = VK_FORMAT_G12X4_B12X4R12X4_2PLANE_420_UNORM_3PACK16, - VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_422_UNORM_3PACK16_KHR = VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_422_UNORM_3PACK16, - VK_FORMAT_G12X4_B12X4R12X4_2PLANE_422_UNORM_3PACK16_KHR = VK_FORMAT_G12X4_B12X4R12X4_2PLANE_422_UNORM_3PACK16, - VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_444_UNORM_3PACK16_KHR = VK_FORMAT_G12X4_B12X4_R12X4_3PLANE_444_UNORM_3PACK16, - VK_FORMAT_G16B16G16R16_422_UNORM_KHR = VK_FORMAT_G16B16G16R16_422_UNORM, - VK_FORMAT_B16G16R16G16_422_UNORM_KHR = VK_FORMAT_B16G16R16G16_422_UNORM, - VK_FORMAT_G16_B16_R16_3PLANE_420_UNORM_KHR = VK_FORMAT_G16_B16_R16_3PLANE_420_UNORM, - VK_FORMAT_G16_B16R16_2PLANE_420_UNORM_KHR = VK_FORMAT_G16_B16R16_2PLANE_420_UNORM, - VK_FORMAT_G16_B16_R16_3PLANE_422_UNORM_KHR = VK_FORMAT_G16_B16_R16_3PLANE_422_UNORM, - VK_FORMAT_G16_B16R16_2PLANE_422_UNORM_KHR = VK_FORMAT_G16_B16R16_2PLANE_422_UNORM, - VK_FORMAT_G16_B16_R16_3PLANE_444_UNORM_KHR = VK_FORMAT_G16_B16_R16_3PLANE_444_UNORM, - VK_FORMAT_BEGIN_RANGE = VK_FORMAT_UNDEFINED, - VK_FORMAT_END_RANGE = VK_FORMAT_ASTC_12x12_SRGB_BLOCK, - VK_FORMAT_RANGE_SIZE = (VK_FORMAT_ASTC_12x12_SRGB_BLOCK - VK_FORMAT_UNDEFINED + 1), - VK_FORMAT_MAX_ENUM = 0x7FFFFFFF -} VkFormat; - -typedef enum VkImageType { - VK_IMAGE_TYPE_1D = 0, - VK_IMAGE_TYPE_2D = 1, - VK_IMAGE_TYPE_3D = 2, - VK_IMAGE_TYPE_BEGIN_RANGE = VK_IMAGE_TYPE_1D, - VK_IMAGE_TYPE_END_RANGE = VK_IMAGE_TYPE_3D, - VK_IMAGE_TYPE_RANGE_SIZE = (VK_IMAGE_TYPE_3D - VK_IMAGE_TYPE_1D + 1), - VK_IMAGE_TYPE_MAX_ENUM = 0x7FFFFFFF -} VkImageType; - -typedef enum VkImageTiling { - VK_IMAGE_TILING_OPTIMAL = 0, - VK_IMAGE_TILING_LINEAR = 1, - VK_IMAGE_TILING_BEGIN_RANGE = VK_IMAGE_TILING_OPTIMAL, - VK_IMAGE_TILING_END_RANGE = VK_IMAGE_TILING_LINEAR, - VK_IMAGE_TILING_RANGE_SIZE = (VK_IMAGE_TILING_LINEAR - VK_IMAGE_TILING_OPTIMAL + 1), - VK_IMAGE_TILING_MAX_ENUM = 0x7FFFFFFF -} VkImageTiling; - -typedef enum VkPhysicalDeviceType { - VK_PHYSICAL_DEVICE_TYPE_OTHER = 0, - VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU = 1, - VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU = 2, - VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU = 3, - VK_PHYSICAL_DEVICE_TYPE_CPU = 4, - VK_PHYSICAL_DEVICE_TYPE_BEGIN_RANGE = VK_PHYSICAL_DEVICE_TYPE_OTHER, - VK_PHYSICAL_DEVICE_TYPE_END_RANGE = VK_PHYSICAL_DEVICE_TYPE_CPU, - VK_PHYSICAL_DEVICE_TYPE_RANGE_SIZE = (VK_PHYSICAL_DEVICE_TYPE_CPU - VK_PHYSICAL_DEVICE_TYPE_OTHER + 1), - VK_PHYSICAL_DEVICE_TYPE_MAX_ENUM = 0x7FFFFFFF -} VkPhysicalDeviceType; - -typedef enum VkQueryType { - VK_QUERY_TYPE_OCCLUSION = 0, - VK_QUERY_TYPE_PIPELINE_STATISTICS = 1, - VK_QUERY_TYPE_TIMESTAMP = 2, - VK_QUERY_TYPE_BEGIN_RANGE = VK_QUERY_TYPE_OCCLUSION, - VK_QUERY_TYPE_END_RANGE = VK_QUERY_TYPE_TIMESTAMP, - VK_QUERY_TYPE_RANGE_SIZE = (VK_QUERY_TYPE_TIMESTAMP - VK_QUERY_TYPE_OCCLUSION + 1), - VK_QUERY_TYPE_MAX_ENUM = 0x7FFFFFFF -} VkQueryType; - -typedef enum VkSharingMode { - VK_SHARING_MODE_EXCLUSIVE = 0, - VK_SHARING_MODE_CONCURRENT = 1, - VK_SHARING_MODE_BEGIN_RANGE = VK_SHARING_MODE_EXCLUSIVE, - VK_SHARING_MODE_END_RANGE = VK_SHARING_MODE_CONCURRENT, - VK_SHARING_MODE_RANGE_SIZE = (VK_SHARING_MODE_CONCURRENT - VK_SHARING_MODE_EXCLUSIVE + 1), - VK_SHARING_MODE_MAX_ENUM = 0x7FFFFFFF -} VkSharingMode; - -typedef enum VkImageLayout { - VK_IMAGE_LAYOUT_UNDEFINED = 0, - VK_IMAGE_LAYOUT_GENERAL = 1, - VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL = 2, - VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL = 3, - VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL = 4, - VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL = 5, - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL = 6, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL = 7, - VK_IMAGE_LAYOUT_PREINITIALIZED = 8, - VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL = 1000117000, - VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL = 1000117001, - VK_IMAGE_LAYOUT_PRESENT_SRC_KHR = 1000001002, - VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR = 1000111000, - VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL_KHR = VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL, - VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL_KHR = VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL, - VK_IMAGE_LAYOUT_BEGIN_RANGE = VK_IMAGE_LAYOUT_UNDEFINED, - VK_IMAGE_LAYOUT_END_RANGE = VK_IMAGE_LAYOUT_PREINITIALIZED, - VK_IMAGE_LAYOUT_RANGE_SIZE = (VK_IMAGE_LAYOUT_PREINITIALIZED - VK_IMAGE_LAYOUT_UNDEFINED + 1), - VK_IMAGE_LAYOUT_MAX_ENUM = 0x7FFFFFFF -} VkImageLayout; - -typedef enum VkImageViewType { - VK_IMAGE_VIEW_TYPE_1D = 0, - VK_IMAGE_VIEW_TYPE_2D = 1, - VK_IMAGE_VIEW_TYPE_3D = 2, - VK_IMAGE_VIEW_TYPE_CUBE = 3, - VK_IMAGE_VIEW_TYPE_1D_ARRAY = 4, - VK_IMAGE_VIEW_TYPE_2D_ARRAY = 5, - VK_IMAGE_VIEW_TYPE_CUBE_ARRAY = 6, - VK_IMAGE_VIEW_TYPE_BEGIN_RANGE = VK_IMAGE_VIEW_TYPE_1D, - VK_IMAGE_VIEW_TYPE_END_RANGE = VK_IMAGE_VIEW_TYPE_CUBE_ARRAY, - VK_IMAGE_VIEW_TYPE_RANGE_SIZE = (VK_IMAGE_VIEW_TYPE_CUBE_ARRAY - VK_IMAGE_VIEW_TYPE_1D + 1), - VK_IMAGE_VIEW_TYPE_MAX_ENUM = 0x7FFFFFFF -} VkImageViewType; - -typedef enum VkComponentSwizzle { - VK_COMPONENT_SWIZZLE_IDENTITY = 0, - VK_COMPONENT_SWIZZLE_ZERO = 1, - VK_COMPONENT_SWIZZLE_ONE = 2, - VK_COMPONENT_SWIZZLE_R = 3, - VK_COMPONENT_SWIZZLE_G = 4, - VK_COMPONENT_SWIZZLE_B = 5, - VK_COMPONENT_SWIZZLE_A = 6, - VK_COMPONENT_SWIZZLE_BEGIN_RANGE = VK_COMPONENT_SWIZZLE_IDENTITY, - VK_COMPONENT_SWIZZLE_END_RANGE = VK_COMPONENT_SWIZZLE_A, - VK_COMPONENT_SWIZZLE_RANGE_SIZE = (VK_COMPONENT_SWIZZLE_A - VK_COMPONENT_SWIZZLE_IDENTITY + 1), - VK_COMPONENT_SWIZZLE_MAX_ENUM = 0x7FFFFFFF -} VkComponentSwizzle; - -typedef enum VkVertexInputRate { - VK_VERTEX_INPUT_RATE_VERTEX = 0, - VK_VERTEX_INPUT_RATE_INSTANCE = 1, - VK_VERTEX_INPUT_RATE_BEGIN_RANGE = VK_VERTEX_INPUT_RATE_VERTEX, - VK_VERTEX_INPUT_RATE_END_RANGE = VK_VERTEX_INPUT_RATE_INSTANCE, - VK_VERTEX_INPUT_RATE_RANGE_SIZE = (VK_VERTEX_INPUT_RATE_INSTANCE - VK_VERTEX_INPUT_RATE_VERTEX + 1), - VK_VERTEX_INPUT_RATE_MAX_ENUM = 0x7FFFFFFF -} VkVertexInputRate; - -typedef enum VkPrimitiveTopology { - VK_PRIMITIVE_TOPOLOGY_POINT_LIST = 0, - VK_PRIMITIVE_TOPOLOGY_LINE_LIST = 1, - VK_PRIMITIVE_TOPOLOGY_LINE_STRIP = 2, - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST = 3, - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP = 4, - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN = 5, - VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY = 6, - VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY = 7, - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY = 8, - VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY = 9, - VK_PRIMITIVE_TOPOLOGY_PATCH_LIST = 10, - VK_PRIMITIVE_TOPOLOGY_BEGIN_RANGE = VK_PRIMITIVE_TOPOLOGY_POINT_LIST, - VK_PRIMITIVE_TOPOLOGY_END_RANGE = VK_PRIMITIVE_TOPOLOGY_PATCH_LIST, - VK_PRIMITIVE_TOPOLOGY_RANGE_SIZE = (VK_PRIMITIVE_TOPOLOGY_PATCH_LIST - VK_PRIMITIVE_TOPOLOGY_POINT_LIST + 1), - VK_PRIMITIVE_TOPOLOGY_MAX_ENUM = 0x7FFFFFFF -} VkPrimitiveTopology; - -typedef enum VkPolygonMode { - VK_POLYGON_MODE_FILL = 0, - VK_POLYGON_MODE_LINE = 1, - VK_POLYGON_MODE_POINT = 2, - VK_POLYGON_MODE_FILL_RECTANGLE_NV = 1000153000, - VK_POLYGON_MODE_BEGIN_RANGE = VK_POLYGON_MODE_FILL, - VK_POLYGON_MODE_END_RANGE = VK_POLYGON_MODE_POINT, - VK_POLYGON_MODE_RANGE_SIZE = (VK_POLYGON_MODE_POINT - VK_POLYGON_MODE_FILL + 1), - VK_POLYGON_MODE_MAX_ENUM = 0x7FFFFFFF -} VkPolygonMode; - -typedef enum VkFrontFace { - VK_FRONT_FACE_COUNTER_CLOCKWISE = 0, - VK_FRONT_FACE_CLOCKWISE = 1, - VK_FRONT_FACE_BEGIN_RANGE = VK_FRONT_FACE_COUNTER_CLOCKWISE, - VK_FRONT_FACE_END_RANGE = VK_FRONT_FACE_CLOCKWISE, - VK_FRONT_FACE_RANGE_SIZE = (VK_FRONT_FACE_CLOCKWISE - VK_FRONT_FACE_COUNTER_CLOCKWISE + 1), - VK_FRONT_FACE_MAX_ENUM = 0x7FFFFFFF -} VkFrontFace; - -typedef enum VkCompareOp { - VK_COMPARE_OP_NEVER = 0, - VK_COMPARE_OP_LESS = 1, - VK_COMPARE_OP_EQUAL = 2, - VK_COMPARE_OP_LESS_OR_EQUAL = 3, - VK_COMPARE_OP_GREATER = 4, - VK_COMPARE_OP_NOT_EQUAL = 5, - VK_COMPARE_OP_GREATER_OR_EQUAL = 6, - VK_COMPARE_OP_ALWAYS = 7, - VK_COMPARE_OP_BEGIN_RANGE = VK_COMPARE_OP_NEVER, - VK_COMPARE_OP_END_RANGE = VK_COMPARE_OP_ALWAYS, - VK_COMPARE_OP_RANGE_SIZE = (VK_COMPARE_OP_ALWAYS - VK_COMPARE_OP_NEVER + 1), - VK_COMPARE_OP_MAX_ENUM = 0x7FFFFFFF -} VkCompareOp; - -typedef enum VkStencilOp { - VK_STENCIL_OP_KEEP = 0, - VK_STENCIL_OP_ZERO = 1, - VK_STENCIL_OP_REPLACE = 2, - VK_STENCIL_OP_INCREMENT_AND_CLAMP = 3, - VK_STENCIL_OP_DECREMENT_AND_CLAMP = 4, - VK_STENCIL_OP_INVERT = 5, - VK_STENCIL_OP_INCREMENT_AND_WRAP = 6, - VK_STENCIL_OP_DECREMENT_AND_WRAP = 7, - VK_STENCIL_OP_BEGIN_RANGE = VK_STENCIL_OP_KEEP, - VK_STENCIL_OP_END_RANGE = VK_STENCIL_OP_DECREMENT_AND_WRAP, - VK_STENCIL_OP_RANGE_SIZE = (VK_STENCIL_OP_DECREMENT_AND_WRAP - VK_STENCIL_OP_KEEP + 1), - VK_STENCIL_OP_MAX_ENUM = 0x7FFFFFFF -} VkStencilOp; - -typedef enum VkLogicOp { - VK_LOGIC_OP_CLEAR = 0, - VK_LOGIC_OP_AND = 1, - VK_LOGIC_OP_AND_REVERSE = 2, - VK_LOGIC_OP_COPY = 3, - VK_LOGIC_OP_AND_INVERTED = 4, - VK_LOGIC_OP_NO_OP = 5, - VK_LOGIC_OP_XOR = 6, - VK_LOGIC_OP_OR = 7, - VK_LOGIC_OP_NOR = 8, - VK_LOGIC_OP_EQUIVALENT = 9, - VK_LOGIC_OP_INVERT = 10, - VK_LOGIC_OP_OR_REVERSE = 11, - VK_LOGIC_OP_COPY_INVERTED = 12, - VK_LOGIC_OP_OR_INVERTED = 13, - VK_LOGIC_OP_NAND = 14, - VK_LOGIC_OP_SET = 15, - VK_LOGIC_OP_BEGIN_RANGE = VK_LOGIC_OP_CLEAR, - VK_LOGIC_OP_END_RANGE = VK_LOGIC_OP_SET, - VK_LOGIC_OP_RANGE_SIZE = (VK_LOGIC_OP_SET - VK_LOGIC_OP_CLEAR + 1), - VK_LOGIC_OP_MAX_ENUM = 0x7FFFFFFF -} VkLogicOp; - -typedef enum VkBlendFactor { - VK_BLEND_FACTOR_ZERO = 0, - VK_BLEND_FACTOR_ONE = 1, - VK_BLEND_FACTOR_SRC_COLOR = 2, - VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR = 3, - VK_BLEND_FACTOR_DST_COLOR = 4, - VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR = 5, - VK_BLEND_FACTOR_SRC_ALPHA = 6, - VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA = 7, - VK_BLEND_FACTOR_DST_ALPHA = 8, - VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA = 9, - VK_BLEND_FACTOR_CONSTANT_COLOR = 10, - VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR = 11, - VK_BLEND_FACTOR_CONSTANT_ALPHA = 12, - VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA = 13, - VK_BLEND_FACTOR_SRC_ALPHA_SATURATE = 14, - VK_BLEND_FACTOR_SRC1_COLOR = 15, - VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR = 16, - VK_BLEND_FACTOR_SRC1_ALPHA = 17, - VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA = 18, - VK_BLEND_FACTOR_BEGIN_RANGE = VK_BLEND_FACTOR_ZERO, - VK_BLEND_FACTOR_END_RANGE = VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA, - VK_BLEND_FACTOR_RANGE_SIZE = (VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA - VK_BLEND_FACTOR_ZERO + 1), - VK_BLEND_FACTOR_MAX_ENUM = 0x7FFFFFFF -} VkBlendFactor; - -typedef enum VkBlendOp { - VK_BLEND_OP_ADD = 0, - VK_BLEND_OP_SUBTRACT = 1, - VK_BLEND_OP_REVERSE_SUBTRACT = 2, - VK_BLEND_OP_MIN = 3, - VK_BLEND_OP_MAX = 4, - VK_BLEND_OP_ZERO_EXT = 1000148000, - VK_BLEND_OP_SRC_EXT = 1000148001, - VK_BLEND_OP_DST_EXT = 1000148002, - VK_BLEND_OP_SRC_OVER_EXT = 1000148003, - VK_BLEND_OP_DST_OVER_EXT = 1000148004, - VK_BLEND_OP_SRC_IN_EXT = 1000148005, - VK_BLEND_OP_DST_IN_EXT = 1000148006, - VK_BLEND_OP_SRC_OUT_EXT = 1000148007, - VK_BLEND_OP_DST_OUT_EXT = 1000148008, - VK_BLEND_OP_SRC_ATOP_EXT = 1000148009, - VK_BLEND_OP_DST_ATOP_EXT = 1000148010, - VK_BLEND_OP_XOR_EXT = 1000148011, - VK_BLEND_OP_MULTIPLY_EXT = 1000148012, - VK_BLEND_OP_SCREEN_EXT = 1000148013, - VK_BLEND_OP_OVERLAY_EXT = 1000148014, - VK_BLEND_OP_DARKEN_EXT = 1000148015, - VK_BLEND_OP_LIGHTEN_EXT = 1000148016, - VK_BLEND_OP_COLORDODGE_EXT = 1000148017, - VK_BLEND_OP_COLORBURN_EXT = 1000148018, - VK_BLEND_OP_HARDLIGHT_EXT = 1000148019, - VK_BLEND_OP_SOFTLIGHT_EXT = 1000148020, - VK_BLEND_OP_DIFFERENCE_EXT = 1000148021, - VK_BLEND_OP_EXCLUSION_EXT = 1000148022, - VK_BLEND_OP_INVERT_EXT = 1000148023, - VK_BLEND_OP_INVERT_RGB_EXT = 1000148024, - VK_BLEND_OP_LINEARDODGE_EXT = 1000148025, - VK_BLEND_OP_LINEARBURN_EXT = 1000148026, - VK_BLEND_OP_VIVIDLIGHT_EXT = 1000148027, - VK_BLEND_OP_LINEARLIGHT_EXT = 1000148028, - VK_BLEND_OP_PINLIGHT_EXT = 1000148029, - VK_BLEND_OP_HARDMIX_EXT = 1000148030, - VK_BLEND_OP_HSL_HUE_EXT = 1000148031, - VK_BLEND_OP_HSL_SATURATION_EXT = 1000148032, - VK_BLEND_OP_HSL_COLOR_EXT = 1000148033, - VK_BLEND_OP_HSL_LUMINOSITY_EXT = 1000148034, - VK_BLEND_OP_PLUS_EXT = 1000148035, - VK_BLEND_OP_PLUS_CLAMPED_EXT = 1000148036, - VK_BLEND_OP_PLUS_CLAMPED_ALPHA_EXT = 1000148037, - VK_BLEND_OP_PLUS_DARKER_EXT = 1000148038, - VK_BLEND_OP_MINUS_EXT = 1000148039, - VK_BLEND_OP_MINUS_CLAMPED_EXT = 1000148040, - VK_BLEND_OP_CONTRAST_EXT = 1000148041, - VK_BLEND_OP_INVERT_OVG_EXT = 1000148042, - VK_BLEND_OP_RED_EXT = 1000148043, - VK_BLEND_OP_GREEN_EXT = 1000148044, - VK_BLEND_OP_BLUE_EXT = 1000148045, - VK_BLEND_OP_BEGIN_RANGE = VK_BLEND_OP_ADD, - VK_BLEND_OP_END_RANGE = VK_BLEND_OP_MAX, - VK_BLEND_OP_RANGE_SIZE = (VK_BLEND_OP_MAX - VK_BLEND_OP_ADD + 1), - VK_BLEND_OP_MAX_ENUM = 0x7FFFFFFF -} VkBlendOp; - -typedef enum VkDynamicState { - VK_DYNAMIC_STATE_VIEWPORT = 0, - VK_DYNAMIC_STATE_SCISSOR = 1, - VK_DYNAMIC_STATE_LINE_WIDTH = 2, - VK_DYNAMIC_STATE_DEPTH_BIAS = 3, - VK_DYNAMIC_STATE_BLEND_CONSTANTS = 4, - VK_DYNAMIC_STATE_DEPTH_BOUNDS = 5, - VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK = 6, - VK_DYNAMIC_STATE_STENCIL_WRITE_MASK = 7, - VK_DYNAMIC_STATE_STENCIL_REFERENCE = 8, - VK_DYNAMIC_STATE_VIEWPORT_W_SCALING_NV = 1000087000, - VK_DYNAMIC_STATE_DISCARD_RECTANGLE_EXT = 1000099000, - VK_DYNAMIC_STATE_SAMPLE_LOCATIONS_EXT = 1000143000, - VK_DYNAMIC_STATE_BEGIN_RANGE = VK_DYNAMIC_STATE_VIEWPORT, - VK_DYNAMIC_STATE_END_RANGE = VK_DYNAMIC_STATE_STENCIL_REFERENCE, - VK_DYNAMIC_STATE_RANGE_SIZE = (VK_DYNAMIC_STATE_STENCIL_REFERENCE - VK_DYNAMIC_STATE_VIEWPORT + 1), - VK_DYNAMIC_STATE_MAX_ENUM = 0x7FFFFFFF -} VkDynamicState; - -typedef enum VkFilter { - VK_FILTER_NEAREST = 0, - VK_FILTER_LINEAR = 1, - VK_FILTER_CUBIC_IMG = 1000015000, - VK_FILTER_BEGIN_RANGE = VK_FILTER_NEAREST, - VK_FILTER_END_RANGE = VK_FILTER_LINEAR, - VK_FILTER_RANGE_SIZE = (VK_FILTER_LINEAR - VK_FILTER_NEAREST + 1), - VK_FILTER_MAX_ENUM = 0x7FFFFFFF -} VkFilter; - -typedef enum VkSamplerMipmapMode { - VK_SAMPLER_MIPMAP_MODE_NEAREST = 0, - VK_SAMPLER_MIPMAP_MODE_LINEAR = 1, - VK_SAMPLER_MIPMAP_MODE_BEGIN_RANGE = VK_SAMPLER_MIPMAP_MODE_NEAREST, - VK_SAMPLER_MIPMAP_MODE_END_RANGE = VK_SAMPLER_MIPMAP_MODE_LINEAR, - VK_SAMPLER_MIPMAP_MODE_RANGE_SIZE = (VK_SAMPLER_MIPMAP_MODE_LINEAR - VK_SAMPLER_MIPMAP_MODE_NEAREST + 1), - VK_SAMPLER_MIPMAP_MODE_MAX_ENUM = 0x7FFFFFFF -} VkSamplerMipmapMode; - -typedef enum VkSamplerAddressMode { - VK_SAMPLER_ADDRESS_MODE_REPEAT = 0, - VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT = 1, - VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE = 2, - VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER = 3, - VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE = 4, - VK_SAMPLER_ADDRESS_MODE_BEGIN_RANGE = VK_SAMPLER_ADDRESS_MODE_REPEAT, - VK_SAMPLER_ADDRESS_MODE_END_RANGE = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER, - VK_SAMPLER_ADDRESS_MODE_RANGE_SIZE = (VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER - VK_SAMPLER_ADDRESS_MODE_REPEAT + 1), - VK_SAMPLER_ADDRESS_MODE_MAX_ENUM = 0x7FFFFFFF -} VkSamplerAddressMode; - -typedef enum VkBorderColor { - VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK = 0, - VK_BORDER_COLOR_INT_TRANSPARENT_BLACK = 1, - VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK = 2, - VK_BORDER_COLOR_INT_OPAQUE_BLACK = 3, - VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE = 4, - VK_BORDER_COLOR_INT_OPAQUE_WHITE = 5, - VK_BORDER_COLOR_BEGIN_RANGE = VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK, - VK_BORDER_COLOR_END_RANGE = VK_BORDER_COLOR_INT_OPAQUE_WHITE, - VK_BORDER_COLOR_RANGE_SIZE = (VK_BORDER_COLOR_INT_OPAQUE_WHITE - VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK + 1), - VK_BORDER_COLOR_MAX_ENUM = 0x7FFFFFFF -} VkBorderColor; - -typedef enum VkDescriptorType { - VK_DESCRIPTOR_TYPE_SAMPLER = 0, - VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER = 1, - VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE = 2, - VK_DESCRIPTOR_TYPE_STORAGE_IMAGE = 3, - VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER = 4, - VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER = 5, - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER = 6, - VK_DESCRIPTOR_TYPE_STORAGE_BUFFER = 7, - VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC = 8, - VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC = 9, - VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT = 10, - VK_DESCRIPTOR_TYPE_BEGIN_RANGE = VK_DESCRIPTOR_TYPE_SAMPLER, - VK_DESCRIPTOR_TYPE_END_RANGE = VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, - VK_DESCRIPTOR_TYPE_RANGE_SIZE = (VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT - VK_DESCRIPTOR_TYPE_SAMPLER + 1), - VK_DESCRIPTOR_TYPE_MAX_ENUM = 0x7FFFFFFF -} VkDescriptorType; - -typedef enum VkAttachmentLoadOp { - VK_ATTACHMENT_LOAD_OP_LOAD = 0, - VK_ATTACHMENT_LOAD_OP_CLEAR = 1, - VK_ATTACHMENT_LOAD_OP_DONT_CARE = 2, - VK_ATTACHMENT_LOAD_OP_BEGIN_RANGE = VK_ATTACHMENT_LOAD_OP_LOAD, - VK_ATTACHMENT_LOAD_OP_END_RANGE = VK_ATTACHMENT_LOAD_OP_DONT_CARE, - VK_ATTACHMENT_LOAD_OP_RANGE_SIZE = (VK_ATTACHMENT_LOAD_OP_DONT_CARE - VK_ATTACHMENT_LOAD_OP_LOAD + 1), - VK_ATTACHMENT_LOAD_OP_MAX_ENUM = 0x7FFFFFFF -} VkAttachmentLoadOp; - -typedef enum VkAttachmentStoreOp { - VK_ATTACHMENT_STORE_OP_STORE = 0, - VK_ATTACHMENT_STORE_OP_DONT_CARE = 1, - VK_ATTACHMENT_STORE_OP_BEGIN_RANGE = VK_ATTACHMENT_STORE_OP_STORE, - VK_ATTACHMENT_STORE_OP_END_RANGE = VK_ATTACHMENT_STORE_OP_DONT_CARE, - VK_ATTACHMENT_STORE_OP_RANGE_SIZE = (VK_ATTACHMENT_STORE_OP_DONT_CARE - VK_ATTACHMENT_STORE_OP_STORE + 1), - VK_ATTACHMENT_STORE_OP_MAX_ENUM = 0x7FFFFFFF -} VkAttachmentStoreOp; - -typedef enum VkPipelineBindPoint { - VK_PIPELINE_BIND_POINT_GRAPHICS = 0, - VK_PIPELINE_BIND_POINT_COMPUTE = 1, - VK_PIPELINE_BIND_POINT_BEGIN_RANGE = VK_PIPELINE_BIND_POINT_GRAPHICS, - VK_PIPELINE_BIND_POINT_END_RANGE = VK_PIPELINE_BIND_POINT_COMPUTE, - VK_PIPELINE_BIND_POINT_RANGE_SIZE = (VK_PIPELINE_BIND_POINT_COMPUTE - VK_PIPELINE_BIND_POINT_GRAPHICS + 1), - VK_PIPELINE_BIND_POINT_MAX_ENUM = 0x7FFFFFFF -} VkPipelineBindPoint; - -typedef enum VkCommandBufferLevel { - VK_COMMAND_BUFFER_LEVEL_PRIMARY = 0, - VK_COMMAND_BUFFER_LEVEL_SECONDARY = 1, - VK_COMMAND_BUFFER_LEVEL_BEGIN_RANGE = VK_COMMAND_BUFFER_LEVEL_PRIMARY, - VK_COMMAND_BUFFER_LEVEL_END_RANGE = VK_COMMAND_BUFFER_LEVEL_SECONDARY, - VK_COMMAND_BUFFER_LEVEL_RANGE_SIZE = (VK_COMMAND_BUFFER_LEVEL_SECONDARY - VK_COMMAND_BUFFER_LEVEL_PRIMARY + 1), - VK_COMMAND_BUFFER_LEVEL_MAX_ENUM = 0x7FFFFFFF -} VkCommandBufferLevel; - -typedef enum VkIndexType { - VK_INDEX_TYPE_UINT16 = 0, - VK_INDEX_TYPE_UINT32 = 1, - VK_INDEX_TYPE_BEGIN_RANGE = VK_INDEX_TYPE_UINT16, - VK_INDEX_TYPE_END_RANGE = VK_INDEX_TYPE_UINT32, - VK_INDEX_TYPE_RANGE_SIZE = (VK_INDEX_TYPE_UINT32 - VK_INDEX_TYPE_UINT16 + 1), - VK_INDEX_TYPE_MAX_ENUM = 0x7FFFFFFF -} VkIndexType; - -typedef enum VkSubpassContents { - VK_SUBPASS_CONTENTS_INLINE = 0, - VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS = 1, - VK_SUBPASS_CONTENTS_BEGIN_RANGE = VK_SUBPASS_CONTENTS_INLINE, - VK_SUBPASS_CONTENTS_END_RANGE = VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS, - VK_SUBPASS_CONTENTS_RANGE_SIZE = (VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS - VK_SUBPASS_CONTENTS_INLINE + 1), - VK_SUBPASS_CONTENTS_MAX_ENUM = 0x7FFFFFFF -} VkSubpassContents; - -typedef enum VkObjectType { - VK_OBJECT_TYPE_UNKNOWN = 0, - VK_OBJECT_TYPE_INSTANCE = 1, - VK_OBJECT_TYPE_PHYSICAL_DEVICE = 2, - VK_OBJECT_TYPE_DEVICE = 3, - VK_OBJECT_TYPE_QUEUE = 4, - VK_OBJECT_TYPE_SEMAPHORE = 5, - VK_OBJECT_TYPE_COMMAND_BUFFER = 6, - VK_OBJECT_TYPE_FENCE = 7, - VK_OBJECT_TYPE_DEVICE_MEMORY = 8, - VK_OBJECT_TYPE_BUFFER = 9, - VK_OBJECT_TYPE_IMAGE = 10, - VK_OBJECT_TYPE_EVENT = 11, - VK_OBJECT_TYPE_QUERY_POOL = 12, - VK_OBJECT_TYPE_BUFFER_VIEW = 13, - VK_OBJECT_TYPE_IMAGE_VIEW = 14, - VK_OBJECT_TYPE_SHADER_MODULE = 15, - VK_OBJECT_TYPE_PIPELINE_CACHE = 16, - VK_OBJECT_TYPE_PIPELINE_LAYOUT = 17, - VK_OBJECT_TYPE_RENDER_PASS = 18, - VK_OBJECT_TYPE_PIPELINE = 19, - VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT = 20, - VK_OBJECT_TYPE_SAMPLER = 21, - VK_OBJECT_TYPE_DESCRIPTOR_POOL = 22, - VK_OBJECT_TYPE_DESCRIPTOR_SET = 23, - VK_OBJECT_TYPE_FRAMEBUFFER = 24, - VK_OBJECT_TYPE_COMMAND_POOL = 25, - VK_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION = 1000156000, - VK_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE = 1000085000, - VK_OBJECT_TYPE_SURFACE_KHR = 1000000000, - VK_OBJECT_TYPE_SWAPCHAIN_KHR = 1000001000, - VK_OBJECT_TYPE_DISPLAY_KHR = 1000002000, - VK_OBJECT_TYPE_DISPLAY_MODE_KHR = 1000002001, - VK_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT = 1000011000, - VK_OBJECT_TYPE_OBJECT_TABLE_NVX = 1000086000, - VK_OBJECT_TYPE_INDIRECT_COMMANDS_LAYOUT_NVX = 1000086001, - VK_OBJECT_TYPE_DEBUG_UTILS_MESSENGER_EXT = 1000128000, - VK_OBJECT_TYPE_VALIDATION_CACHE_EXT = 1000160000, - VK_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE_KHR = VK_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE, - VK_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION_KHR = VK_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION, - VK_OBJECT_TYPE_BEGIN_RANGE = VK_OBJECT_TYPE_UNKNOWN, - VK_OBJECT_TYPE_END_RANGE = VK_OBJECT_TYPE_COMMAND_POOL, - VK_OBJECT_TYPE_RANGE_SIZE = (VK_OBJECT_TYPE_COMMAND_POOL - VK_OBJECT_TYPE_UNKNOWN + 1), - VK_OBJECT_TYPE_MAX_ENUM = 0x7FFFFFFF -} VkObjectType; - -typedef VkFlags VkInstanceCreateFlags; - -typedef enum VkFormatFeatureFlagBits { - VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT = 0x00000001, - VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT = 0x00000002, - VK_FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT = 0x00000004, - VK_FORMAT_FEATURE_UNIFORM_TEXEL_BUFFER_BIT = 0x00000008, - VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_BIT = 0x00000010, - VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_ATOMIC_BIT = 0x00000020, - VK_FORMAT_FEATURE_VERTEX_BUFFER_BIT = 0x00000040, - VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT = 0x00000080, - VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT = 0x00000100, - VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT = 0x00000200, - VK_FORMAT_FEATURE_BLIT_SRC_BIT = 0x00000400, - VK_FORMAT_FEATURE_BLIT_DST_BIT = 0x00000800, - VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT = 0x00001000, - VK_FORMAT_FEATURE_TRANSFER_SRC_BIT = 0x00004000, - VK_FORMAT_FEATURE_TRANSFER_DST_BIT = 0x00008000, - VK_FORMAT_FEATURE_MIDPOINT_CHROMA_SAMPLES_BIT = 0x00020000, - VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_LINEAR_FILTER_BIT = 0x00040000, - VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_SEPARATE_RECONSTRUCTION_FILTER_BIT = 0x00080000, - VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_CHROMA_RECONSTRUCTION_EXPLICIT_BIT = 0x00100000, - VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_CHROMA_RECONSTRUCTION_EXPLICIT_FORCEABLE_BIT = 0x00200000, - VK_FORMAT_FEATURE_DISJOINT_BIT = 0x00400000, - VK_FORMAT_FEATURE_COSITED_CHROMA_SAMPLES_BIT = 0x00800000, - VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_CUBIC_BIT_IMG = 0x00002000, - VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_MINMAX_BIT_EXT = 0x00010000, - VK_FORMAT_FEATURE_TRANSFER_SRC_BIT_KHR = VK_FORMAT_FEATURE_TRANSFER_SRC_BIT, - VK_FORMAT_FEATURE_TRANSFER_DST_BIT_KHR = VK_FORMAT_FEATURE_TRANSFER_DST_BIT, - VK_FORMAT_FEATURE_MIDPOINT_CHROMA_SAMPLES_BIT_KHR = VK_FORMAT_FEATURE_MIDPOINT_CHROMA_SAMPLES_BIT, - VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_LINEAR_FILTER_BIT_KHR = VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_LINEAR_FILTER_BIT, - VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_SEPARATE_RECONSTRUCTION_FILTER_BIT_KHR = VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_SEPARATE_RECONSTRUCTION_FILTER_BIT, - VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_CHROMA_RECONSTRUCTION_EXPLICIT_BIT_KHR = VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_CHROMA_RECONSTRUCTION_EXPLICIT_BIT, - VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_CHROMA_RECONSTRUCTION_EXPLICIT_FORCEABLE_BIT_KHR = VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_CHROMA_RECONSTRUCTION_EXPLICIT_FORCEABLE_BIT, - VK_FORMAT_FEATURE_DISJOINT_BIT_KHR = VK_FORMAT_FEATURE_DISJOINT_BIT, - VK_FORMAT_FEATURE_COSITED_CHROMA_SAMPLES_BIT_KHR = VK_FORMAT_FEATURE_COSITED_CHROMA_SAMPLES_BIT, - VK_FORMAT_FEATURE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkFormatFeatureFlagBits; -typedef VkFlags VkFormatFeatureFlags; - -typedef enum VkImageUsageFlagBits { - VK_IMAGE_USAGE_TRANSFER_SRC_BIT = 0x00000001, - VK_IMAGE_USAGE_TRANSFER_DST_BIT = 0x00000002, - VK_IMAGE_USAGE_SAMPLED_BIT = 0x00000004, - VK_IMAGE_USAGE_STORAGE_BIT = 0x00000008, - VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT = 0x00000010, - VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT = 0x00000020, - VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT = 0x00000040, - VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT = 0x00000080, - VK_IMAGE_USAGE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkImageUsageFlagBits; -typedef VkFlags VkImageUsageFlags; - -typedef enum VkImageCreateFlagBits { - VK_IMAGE_CREATE_SPARSE_BINDING_BIT = 0x00000001, - VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT = 0x00000002, - VK_IMAGE_CREATE_SPARSE_ALIASED_BIT = 0x00000004, - VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT = 0x00000008, - VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT = 0x00000010, - VK_IMAGE_CREATE_ALIAS_BIT = 0x00000400, - VK_IMAGE_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT = 0x00000040, - VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT = 0x00000020, - VK_IMAGE_CREATE_BLOCK_TEXEL_VIEW_COMPATIBLE_BIT = 0x00000080, - VK_IMAGE_CREATE_EXTENDED_USAGE_BIT = 0x00000100, - VK_IMAGE_CREATE_PROTECTED_BIT = 0x00000800, - VK_IMAGE_CREATE_DISJOINT_BIT = 0x00000200, - VK_IMAGE_CREATE_SAMPLE_LOCATIONS_COMPATIBLE_DEPTH_BIT_EXT = 0x00001000, - VK_IMAGE_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT_KHR = VK_IMAGE_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT, - VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT_KHR = VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT, - VK_IMAGE_CREATE_BLOCK_TEXEL_VIEW_COMPATIBLE_BIT_KHR = VK_IMAGE_CREATE_BLOCK_TEXEL_VIEW_COMPATIBLE_BIT, - VK_IMAGE_CREATE_EXTENDED_USAGE_BIT_KHR = VK_IMAGE_CREATE_EXTENDED_USAGE_BIT, - VK_IMAGE_CREATE_DISJOINT_BIT_KHR = VK_IMAGE_CREATE_DISJOINT_BIT, - VK_IMAGE_CREATE_ALIAS_BIT_KHR = VK_IMAGE_CREATE_ALIAS_BIT, - VK_IMAGE_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkImageCreateFlagBits; -typedef VkFlags VkImageCreateFlags; - -typedef enum VkSampleCountFlagBits { - VK_SAMPLE_COUNT_1_BIT = 0x00000001, - VK_SAMPLE_COUNT_2_BIT = 0x00000002, - VK_SAMPLE_COUNT_4_BIT = 0x00000004, - VK_SAMPLE_COUNT_8_BIT = 0x00000008, - VK_SAMPLE_COUNT_16_BIT = 0x00000010, - VK_SAMPLE_COUNT_32_BIT = 0x00000020, - VK_SAMPLE_COUNT_64_BIT = 0x00000040, - VK_SAMPLE_COUNT_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkSampleCountFlagBits; -typedef VkFlags VkSampleCountFlags; - -typedef enum VkQueueFlagBits { - VK_QUEUE_GRAPHICS_BIT = 0x00000001, - VK_QUEUE_COMPUTE_BIT = 0x00000002, - VK_QUEUE_TRANSFER_BIT = 0x00000004, - VK_QUEUE_SPARSE_BINDING_BIT = 0x00000008, - VK_QUEUE_PROTECTED_BIT = 0x00000010, - VK_QUEUE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkQueueFlagBits; -typedef VkFlags VkQueueFlags; - -typedef enum VkMemoryPropertyFlagBits { - VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT = 0x00000001, - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT = 0x00000002, - VK_MEMORY_PROPERTY_HOST_COHERENT_BIT = 0x00000004, - VK_MEMORY_PROPERTY_HOST_CACHED_BIT = 0x00000008, - VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT = 0x00000010, - VK_MEMORY_PROPERTY_PROTECTED_BIT = 0x00000020, - VK_MEMORY_PROPERTY_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkMemoryPropertyFlagBits; -typedef VkFlags VkMemoryPropertyFlags; - -typedef enum VkMemoryHeapFlagBits { - VK_MEMORY_HEAP_DEVICE_LOCAL_BIT = 0x00000001, - VK_MEMORY_HEAP_MULTI_INSTANCE_BIT = 0x00000002, - VK_MEMORY_HEAP_MULTI_INSTANCE_BIT_KHR = VK_MEMORY_HEAP_MULTI_INSTANCE_BIT, - VK_MEMORY_HEAP_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkMemoryHeapFlagBits; -typedef VkFlags VkMemoryHeapFlags; -typedef VkFlags VkDeviceCreateFlags; - -typedef enum VkDeviceQueueCreateFlagBits { - VK_DEVICE_QUEUE_CREATE_PROTECTED_BIT = 0x00000001, - VK_DEVICE_QUEUE_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkDeviceQueueCreateFlagBits; -typedef VkFlags VkDeviceQueueCreateFlags; - -typedef enum VkPipelineStageFlagBits { - VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT = 0x00000001, - VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT = 0x00000002, - VK_PIPELINE_STAGE_VERTEX_INPUT_BIT = 0x00000004, - VK_PIPELINE_STAGE_VERTEX_SHADER_BIT = 0x00000008, - VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT = 0x00000010, - VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT = 0x00000020, - VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT = 0x00000040, - VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT = 0x00000080, - VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT = 0x00000100, - VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT = 0x00000200, - VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT = 0x00000400, - VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT = 0x00000800, - VK_PIPELINE_STAGE_TRANSFER_BIT = 0x00001000, - VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT = 0x00002000, - VK_PIPELINE_STAGE_HOST_BIT = 0x00004000, - VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT = 0x00008000, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT = 0x00010000, - VK_PIPELINE_STAGE_COMMAND_PROCESS_BIT_NVX = 0x00020000, - VK_PIPELINE_STAGE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkPipelineStageFlagBits; -typedef VkFlags VkPipelineStageFlags; -typedef VkFlags VkMemoryMapFlags; - -typedef enum VkImageAspectFlagBits { - VK_IMAGE_ASPECT_COLOR_BIT = 0x00000001, - VK_IMAGE_ASPECT_DEPTH_BIT = 0x00000002, - VK_IMAGE_ASPECT_STENCIL_BIT = 0x00000004, - VK_IMAGE_ASPECT_METADATA_BIT = 0x00000008, - VK_IMAGE_ASPECT_PLANE_0_BIT = 0x00000010, - VK_IMAGE_ASPECT_PLANE_1_BIT = 0x00000020, - VK_IMAGE_ASPECT_PLANE_2_BIT = 0x00000040, - VK_IMAGE_ASPECT_PLANE_0_BIT_KHR = VK_IMAGE_ASPECT_PLANE_0_BIT, - VK_IMAGE_ASPECT_PLANE_1_BIT_KHR = VK_IMAGE_ASPECT_PLANE_1_BIT, - VK_IMAGE_ASPECT_PLANE_2_BIT_KHR = VK_IMAGE_ASPECT_PLANE_2_BIT, - VK_IMAGE_ASPECT_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkImageAspectFlagBits; -typedef VkFlags VkImageAspectFlags; - -typedef enum VkSparseImageFormatFlagBits { - VK_SPARSE_IMAGE_FORMAT_SINGLE_MIPTAIL_BIT = 0x00000001, - VK_SPARSE_IMAGE_FORMAT_ALIGNED_MIP_SIZE_BIT = 0x00000002, - VK_SPARSE_IMAGE_FORMAT_NONSTANDARD_BLOCK_SIZE_BIT = 0x00000004, - VK_SPARSE_IMAGE_FORMAT_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkSparseImageFormatFlagBits; -typedef VkFlags VkSparseImageFormatFlags; - -typedef enum VkSparseMemoryBindFlagBits { - VK_SPARSE_MEMORY_BIND_METADATA_BIT = 0x00000001, - VK_SPARSE_MEMORY_BIND_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkSparseMemoryBindFlagBits; -typedef VkFlags VkSparseMemoryBindFlags; - -typedef enum VkFenceCreateFlagBits { - VK_FENCE_CREATE_SIGNALED_BIT = 0x00000001, - VK_FENCE_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkFenceCreateFlagBits; -typedef VkFlags VkFenceCreateFlags; -typedef VkFlags VkSemaphoreCreateFlags; -typedef VkFlags VkEventCreateFlags; -typedef VkFlags VkQueryPoolCreateFlags; - -typedef enum VkQueryPipelineStatisticFlagBits { - VK_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_VERTICES_BIT = 0x00000001, - VK_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_PRIMITIVES_BIT = 0x00000002, - VK_QUERY_PIPELINE_STATISTIC_VERTEX_SHADER_INVOCATIONS_BIT = 0x00000004, - VK_QUERY_PIPELINE_STATISTIC_GEOMETRY_SHADER_INVOCATIONS_BIT = 0x00000008, - VK_QUERY_PIPELINE_STATISTIC_GEOMETRY_SHADER_PRIMITIVES_BIT = 0x00000010, - VK_QUERY_PIPELINE_STATISTIC_CLIPPING_INVOCATIONS_BIT = 0x00000020, - VK_QUERY_PIPELINE_STATISTIC_CLIPPING_PRIMITIVES_BIT = 0x00000040, - VK_QUERY_PIPELINE_STATISTIC_FRAGMENT_SHADER_INVOCATIONS_BIT = 0x00000080, - VK_QUERY_PIPELINE_STATISTIC_TESSELLATION_CONTROL_SHADER_PATCHES_BIT = 0x00000100, - VK_QUERY_PIPELINE_STATISTIC_TESSELLATION_EVALUATION_SHADER_INVOCATIONS_BIT = 0x00000200, - VK_QUERY_PIPELINE_STATISTIC_COMPUTE_SHADER_INVOCATIONS_BIT = 0x00000400, - VK_QUERY_PIPELINE_STATISTIC_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkQueryPipelineStatisticFlagBits; -typedef VkFlags VkQueryPipelineStatisticFlags; - -typedef enum VkQueryResultFlagBits { - VK_QUERY_RESULT_64_BIT = 0x00000001, - VK_QUERY_RESULT_WAIT_BIT = 0x00000002, - VK_QUERY_RESULT_WITH_AVAILABILITY_BIT = 0x00000004, - VK_QUERY_RESULT_PARTIAL_BIT = 0x00000008, - VK_QUERY_RESULT_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkQueryResultFlagBits; -typedef VkFlags VkQueryResultFlags; - -typedef enum VkBufferCreateFlagBits { - VK_BUFFER_CREATE_SPARSE_BINDING_BIT = 0x00000001, - VK_BUFFER_CREATE_SPARSE_RESIDENCY_BIT = 0x00000002, - VK_BUFFER_CREATE_SPARSE_ALIASED_BIT = 0x00000004, - VK_BUFFER_CREATE_PROTECTED_BIT = 0x00000008, - VK_BUFFER_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkBufferCreateFlagBits; -typedef VkFlags VkBufferCreateFlags; - -typedef enum VkBufferUsageFlagBits { - VK_BUFFER_USAGE_TRANSFER_SRC_BIT = 0x00000001, - VK_BUFFER_USAGE_TRANSFER_DST_BIT = 0x00000002, - VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT = 0x00000004, - VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT = 0x00000008, - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT = 0x00000010, - VK_BUFFER_USAGE_STORAGE_BUFFER_BIT = 0x00000020, - VK_BUFFER_USAGE_INDEX_BUFFER_BIT = 0x00000040, - VK_BUFFER_USAGE_VERTEX_BUFFER_BIT = 0x00000080, - VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT = 0x00000100, - VK_BUFFER_USAGE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkBufferUsageFlagBits; -typedef VkFlags VkBufferUsageFlags; -typedef VkFlags VkBufferViewCreateFlags; -typedef VkFlags VkImageViewCreateFlags; -typedef VkFlags VkShaderModuleCreateFlags; -typedef VkFlags VkPipelineCacheCreateFlags; - -typedef enum VkPipelineCreateFlagBits { - VK_PIPELINE_CREATE_DISABLE_OPTIMIZATION_BIT = 0x00000001, - VK_PIPELINE_CREATE_ALLOW_DERIVATIVES_BIT = 0x00000002, - VK_PIPELINE_CREATE_DERIVATIVE_BIT = 0x00000004, - VK_PIPELINE_CREATE_VIEW_INDEX_FROM_DEVICE_INDEX_BIT = 0x00000008, - VK_PIPELINE_CREATE_DISPATCH_BASE = 0x00000010, - VK_PIPELINE_CREATE_VIEW_INDEX_FROM_DEVICE_INDEX_BIT_KHR = VK_PIPELINE_CREATE_VIEW_INDEX_FROM_DEVICE_INDEX_BIT, - VK_PIPELINE_CREATE_DISPATCH_BASE_KHR = VK_PIPELINE_CREATE_DISPATCH_BASE, - VK_PIPELINE_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkPipelineCreateFlagBits; -typedef VkFlags VkPipelineCreateFlags; -typedef VkFlags VkPipelineShaderStageCreateFlags; - -typedef enum VkShaderStageFlagBits { - VK_SHADER_STAGE_VERTEX_BIT = 0x00000001, - VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT = 0x00000002, - VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT = 0x00000004, - VK_SHADER_STAGE_GEOMETRY_BIT = 0x00000008, - VK_SHADER_STAGE_FRAGMENT_BIT = 0x00000010, - VK_SHADER_STAGE_COMPUTE_BIT = 0x00000020, - VK_SHADER_STAGE_ALL_GRAPHICS = 0x0000001F, - VK_SHADER_STAGE_ALL = 0x7FFFFFFF, - VK_SHADER_STAGE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkShaderStageFlagBits; -typedef VkFlags VkPipelineVertexInputStateCreateFlags; -typedef VkFlags VkPipelineInputAssemblyStateCreateFlags; -typedef VkFlags VkPipelineTessellationStateCreateFlags; -typedef VkFlags VkPipelineViewportStateCreateFlags; -typedef VkFlags VkPipelineRasterizationStateCreateFlags; - -typedef enum VkCullModeFlagBits { - VK_CULL_MODE_NONE = 0, - VK_CULL_MODE_FRONT_BIT = 0x00000001, - VK_CULL_MODE_BACK_BIT = 0x00000002, - VK_CULL_MODE_FRONT_AND_BACK = 0x00000003, - VK_CULL_MODE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkCullModeFlagBits; -typedef VkFlags VkCullModeFlags; -typedef VkFlags VkPipelineMultisampleStateCreateFlags; -typedef VkFlags VkPipelineDepthStencilStateCreateFlags; -typedef VkFlags VkPipelineColorBlendStateCreateFlags; - -typedef enum VkColorComponentFlagBits { - VK_COLOR_COMPONENT_R_BIT = 0x00000001, - VK_COLOR_COMPONENT_G_BIT = 0x00000002, - VK_COLOR_COMPONENT_B_BIT = 0x00000004, - VK_COLOR_COMPONENT_A_BIT = 0x00000008, - VK_COLOR_COMPONENT_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkColorComponentFlagBits; -typedef VkFlags VkColorComponentFlags; -typedef VkFlags VkPipelineDynamicStateCreateFlags; -typedef VkFlags VkPipelineLayoutCreateFlags; -typedef VkFlags VkShaderStageFlags; -typedef VkFlags VkSamplerCreateFlags; - -typedef enum VkDescriptorSetLayoutCreateFlagBits { - VK_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT_KHR = 0x00000001, - VK_DESCRIPTOR_SET_LAYOUT_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkDescriptorSetLayoutCreateFlagBits; -typedef VkFlags VkDescriptorSetLayoutCreateFlags; - -typedef enum VkDescriptorPoolCreateFlagBits { - VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT = 0x00000001, - VK_DESCRIPTOR_POOL_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkDescriptorPoolCreateFlagBits; -typedef VkFlags VkDescriptorPoolCreateFlags; -typedef VkFlags VkDescriptorPoolResetFlags; -typedef VkFlags VkFramebufferCreateFlags; -typedef VkFlags VkRenderPassCreateFlags; - -typedef enum VkAttachmentDescriptionFlagBits { - VK_ATTACHMENT_DESCRIPTION_MAY_ALIAS_BIT = 0x00000001, - VK_ATTACHMENT_DESCRIPTION_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkAttachmentDescriptionFlagBits; -typedef VkFlags VkAttachmentDescriptionFlags; - -typedef enum VkSubpassDescriptionFlagBits { - VK_SUBPASS_DESCRIPTION_PER_VIEW_ATTRIBUTES_BIT_NVX = 0x00000001, - VK_SUBPASS_DESCRIPTION_PER_VIEW_POSITION_X_ONLY_BIT_NVX = 0x00000002, - VK_SUBPASS_DESCRIPTION_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkSubpassDescriptionFlagBits; -typedef VkFlags VkSubpassDescriptionFlags; - -typedef enum VkAccessFlagBits { - VK_ACCESS_INDIRECT_COMMAND_READ_BIT = 0x00000001, - VK_ACCESS_INDEX_READ_BIT = 0x00000002, - VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT = 0x00000004, - VK_ACCESS_UNIFORM_READ_BIT = 0x00000008, - VK_ACCESS_INPUT_ATTACHMENT_READ_BIT = 0x00000010, - VK_ACCESS_SHADER_READ_BIT = 0x00000020, - VK_ACCESS_SHADER_WRITE_BIT = 0x00000040, - VK_ACCESS_COLOR_ATTACHMENT_READ_BIT = 0x00000080, - VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT = 0x00000100, - VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT = 0x00000200, - VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT = 0x00000400, - VK_ACCESS_TRANSFER_READ_BIT = 0x00000800, - VK_ACCESS_TRANSFER_WRITE_BIT = 0x00001000, - VK_ACCESS_HOST_READ_BIT = 0x00002000, - VK_ACCESS_HOST_WRITE_BIT = 0x00004000, - VK_ACCESS_MEMORY_READ_BIT = 0x00008000, - VK_ACCESS_MEMORY_WRITE_BIT = 0x00010000, - VK_ACCESS_COMMAND_PROCESS_READ_BIT_NVX = 0x00020000, - VK_ACCESS_COMMAND_PROCESS_WRITE_BIT_NVX = 0x00040000, - VK_ACCESS_COLOR_ATTACHMENT_READ_NONCOHERENT_BIT_EXT = 0x00080000, - VK_ACCESS_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkAccessFlagBits; -typedef VkFlags VkAccessFlags; - -typedef enum VkDependencyFlagBits { - VK_DEPENDENCY_BY_REGION_BIT = 0x00000001, - VK_DEPENDENCY_DEVICE_GROUP_BIT = 0x00000004, - VK_DEPENDENCY_VIEW_LOCAL_BIT = 0x00000002, - VK_DEPENDENCY_VIEW_LOCAL_BIT_KHR = VK_DEPENDENCY_VIEW_LOCAL_BIT, - VK_DEPENDENCY_DEVICE_GROUP_BIT_KHR = VK_DEPENDENCY_DEVICE_GROUP_BIT, - VK_DEPENDENCY_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkDependencyFlagBits; -typedef VkFlags VkDependencyFlags; - -typedef enum VkCommandPoolCreateFlagBits { - VK_COMMAND_POOL_CREATE_TRANSIENT_BIT = 0x00000001, - VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT = 0x00000002, - VK_COMMAND_POOL_CREATE_PROTECTED_BIT = 0x00000004, - VK_COMMAND_POOL_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkCommandPoolCreateFlagBits; -typedef VkFlags VkCommandPoolCreateFlags; - -typedef enum VkCommandPoolResetFlagBits { - VK_COMMAND_POOL_RESET_RELEASE_RESOURCES_BIT = 0x00000001, - VK_COMMAND_POOL_RESET_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkCommandPoolResetFlagBits; -typedef VkFlags VkCommandPoolResetFlags; - -typedef enum VkCommandBufferUsageFlagBits { - VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT = 0x00000001, - VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT = 0x00000002, - VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT = 0x00000004, - VK_COMMAND_BUFFER_USAGE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkCommandBufferUsageFlagBits; -typedef VkFlags VkCommandBufferUsageFlags; - -typedef enum VkQueryControlFlagBits { - VK_QUERY_CONTROL_PRECISE_BIT = 0x00000001, - VK_QUERY_CONTROL_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkQueryControlFlagBits; -typedef VkFlags VkQueryControlFlags; - -typedef enum VkCommandBufferResetFlagBits { - VK_COMMAND_BUFFER_RESET_RELEASE_RESOURCES_BIT = 0x00000001, - VK_COMMAND_BUFFER_RESET_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkCommandBufferResetFlagBits; -typedef VkFlags VkCommandBufferResetFlags; - -typedef enum VkStencilFaceFlagBits { - VK_STENCIL_FACE_FRONT_BIT = 0x00000001, - VK_STENCIL_FACE_BACK_BIT = 0x00000002, - VK_STENCIL_FRONT_AND_BACK = 0x00000003, - VK_STENCIL_FACE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkStencilFaceFlagBits; -typedef VkFlags VkStencilFaceFlags; - -typedef struct VkApplicationInfo { - VkStructureType sType; - const void* pNext; - const char* pApplicationName; - uint32_t applicationVersion; - const char* pEngineName; - uint32_t engineVersion; - uint32_t apiVersion; -} VkApplicationInfo; - -typedef struct VkInstanceCreateInfo { - VkStructureType sType; - const void* pNext; - VkInstanceCreateFlags flags; - const VkApplicationInfo* pApplicationInfo; - uint32_t enabledLayerCount; - const char* const* ppEnabledLayerNames; - uint32_t enabledExtensionCount; - const char* const* ppEnabledExtensionNames; -} VkInstanceCreateInfo; - -typedef void* (VKAPI_PTR *PFN_vkAllocationFunction)( - void* pUserData, - size_t size, - size_t alignment, - VkSystemAllocationScope allocationScope); - -typedef void* (VKAPI_PTR *PFN_vkReallocationFunction)( - void* pUserData, - void* pOriginal, - size_t size, - size_t alignment, - VkSystemAllocationScope allocationScope); - -typedef void (VKAPI_PTR *PFN_vkFreeFunction)( - void* pUserData, - void* pMemory); - -typedef void (VKAPI_PTR *PFN_vkInternalAllocationNotification)( - void* pUserData, - size_t size, - VkInternalAllocationType allocationType, - VkSystemAllocationScope allocationScope); - -typedef void (VKAPI_PTR *PFN_vkInternalFreeNotification)( - void* pUserData, - size_t size, - VkInternalAllocationType allocationType, - VkSystemAllocationScope allocationScope); - -typedef struct VkAllocationCallbacks { - void* pUserData; - PFN_vkAllocationFunction pfnAllocation; - PFN_vkReallocationFunction pfnReallocation; - PFN_vkFreeFunction pfnFree; - PFN_vkInternalAllocationNotification pfnInternalAllocation; - PFN_vkInternalFreeNotification pfnInternalFree; -} VkAllocationCallbacks; - -typedef struct VkPhysicalDeviceFeatures { - VkBool32 robustBufferAccess; - VkBool32 fullDrawIndexUint32; - VkBool32 imageCubeArray; - VkBool32 independentBlend; - VkBool32 geometryShader; - VkBool32 tessellationShader; - VkBool32 sampleRateShading; - VkBool32 dualSrcBlend; - VkBool32 logicOp; - VkBool32 multiDrawIndirect; - VkBool32 drawIndirectFirstInstance; - VkBool32 depthClamp; - VkBool32 depthBiasClamp; - VkBool32 fillModeNonSolid; - VkBool32 depthBounds; - VkBool32 wideLines; - VkBool32 largePoints; - VkBool32 alphaToOne; - VkBool32 multiViewport; - VkBool32 samplerAnisotropy; - VkBool32 textureCompressionETC2; - VkBool32 textureCompressionASTC_LDR; - VkBool32 textureCompressionBC; - VkBool32 occlusionQueryPrecise; - VkBool32 pipelineStatisticsQuery; - VkBool32 vertexPipelineStoresAndAtomics; - VkBool32 fragmentStoresAndAtomics; - VkBool32 shaderTessellationAndGeometryPointSize; - VkBool32 shaderImageGatherExtended; - VkBool32 shaderStorageImageExtendedFormats; - VkBool32 shaderStorageImageMultisample; - VkBool32 shaderStorageImageReadWithoutFormat; - VkBool32 shaderStorageImageWriteWithoutFormat; - VkBool32 shaderUniformBufferArrayDynamicIndexing; - VkBool32 shaderSampledImageArrayDynamicIndexing; - VkBool32 shaderStorageBufferArrayDynamicIndexing; - VkBool32 shaderStorageImageArrayDynamicIndexing; - VkBool32 shaderClipDistance; - VkBool32 shaderCullDistance; - VkBool32 shaderFloat64; - VkBool32 shaderInt64; - VkBool32 shaderInt16; - VkBool32 shaderResourceResidency; - VkBool32 shaderResourceMinLod; - VkBool32 sparseBinding; - VkBool32 sparseResidencyBuffer; - VkBool32 sparseResidencyImage2D; - VkBool32 sparseResidencyImage3D; - VkBool32 sparseResidency2Samples; - VkBool32 sparseResidency4Samples; - VkBool32 sparseResidency8Samples; - VkBool32 sparseResidency16Samples; - VkBool32 sparseResidencyAliased; - VkBool32 variableMultisampleRate; - VkBool32 inheritedQueries; -} VkPhysicalDeviceFeatures; - -typedef struct VkFormatProperties { - VkFormatFeatureFlags linearTilingFeatures; - VkFormatFeatureFlags optimalTilingFeatures; - VkFormatFeatureFlags bufferFeatures; -} VkFormatProperties; - -typedef struct VkExtent3D { - uint32_t width; - uint32_t height; - uint32_t depth; -} VkExtent3D; - -typedef struct VkImageFormatProperties { - VkExtent3D maxExtent; - uint32_t maxMipLevels; - uint32_t maxArrayLayers; - VkSampleCountFlags sampleCounts; - VkDeviceSize maxResourceSize; -} VkImageFormatProperties; - -typedef struct VkPhysicalDeviceLimits { - uint32_t maxImageDimension1D; - uint32_t maxImageDimension2D; - uint32_t maxImageDimension3D; - uint32_t maxImageDimensionCube; - uint32_t maxImageArrayLayers; - uint32_t maxTexelBufferElements; - uint32_t maxUniformBufferRange; - uint32_t maxStorageBufferRange; - uint32_t maxPushConstantsSize; - uint32_t maxMemoryAllocationCount; - uint32_t maxSamplerAllocationCount; - VkDeviceSize bufferImageGranularity; - VkDeviceSize sparseAddressSpaceSize; - uint32_t maxBoundDescriptorSets; - uint32_t maxPerStageDescriptorSamplers; - uint32_t maxPerStageDescriptorUniformBuffers; - uint32_t maxPerStageDescriptorStorageBuffers; - uint32_t maxPerStageDescriptorSampledImages; - uint32_t maxPerStageDescriptorStorageImages; - uint32_t maxPerStageDescriptorInputAttachments; - uint32_t maxPerStageResources; - uint32_t maxDescriptorSetSamplers; - uint32_t maxDescriptorSetUniformBuffers; - uint32_t maxDescriptorSetUniformBuffersDynamic; - uint32_t maxDescriptorSetStorageBuffers; - uint32_t maxDescriptorSetStorageBuffersDynamic; - uint32_t maxDescriptorSetSampledImages; - uint32_t maxDescriptorSetStorageImages; - uint32_t maxDescriptorSetInputAttachments; - uint32_t maxVertexInputAttributes; - uint32_t maxVertexInputBindings; - uint32_t maxVertexInputAttributeOffset; - uint32_t maxVertexInputBindingStride; - uint32_t maxVertexOutputComponents; - uint32_t maxTessellationGenerationLevel; - uint32_t maxTessellationPatchSize; - uint32_t maxTessellationControlPerVertexInputComponents; - uint32_t maxTessellationControlPerVertexOutputComponents; - uint32_t maxTessellationControlPerPatchOutputComponents; - uint32_t maxTessellationControlTotalOutputComponents; - uint32_t maxTessellationEvaluationInputComponents; - uint32_t maxTessellationEvaluationOutputComponents; - uint32_t maxGeometryShaderInvocations; - uint32_t maxGeometryInputComponents; - uint32_t maxGeometryOutputComponents; - uint32_t maxGeometryOutputVertices; - uint32_t maxGeometryTotalOutputComponents; - uint32_t maxFragmentInputComponents; - uint32_t maxFragmentOutputAttachments; - uint32_t maxFragmentDualSrcAttachments; - uint32_t maxFragmentCombinedOutputResources; - uint32_t maxComputeSharedMemorySize; - uint32_t maxComputeWorkGroupCount[3]; - uint32_t maxComputeWorkGroupInvocations; - uint32_t maxComputeWorkGroupSize[3]; - uint32_t subPixelPrecisionBits; - uint32_t subTexelPrecisionBits; - uint32_t mipmapPrecisionBits; - uint32_t maxDrawIndexedIndexValue; - uint32_t maxDrawIndirectCount; - float maxSamplerLodBias; - float maxSamplerAnisotropy; - uint32_t maxViewports; - uint32_t maxViewportDimensions[2]; - float viewportBoundsRange[2]; - uint32_t viewportSubPixelBits; - size_t minMemoryMapAlignment; - VkDeviceSize minTexelBufferOffsetAlignment; - VkDeviceSize minUniformBufferOffsetAlignment; - VkDeviceSize minStorageBufferOffsetAlignment; - int32_t minTexelOffset; - uint32_t maxTexelOffset; - int32_t minTexelGatherOffset; - uint32_t maxTexelGatherOffset; - float minInterpolationOffset; - float maxInterpolationOffset; - uint32_t subPixelInterpolationOffsetBits; - uint32_t maxFramebufferWidth; - uint32_t maxFramebufferHeight; - uint32_t maxFramebufferLayers; - VkSampleCountFlags framebufferColorSampleCounts; - VkSampleCountFlags framebufferDepthSampleCounts; - VkSampleCountFlags framebufferStencilSampleCounts; - VkSampleCountFlags framebufferNoAttachmentsSampleCounts; - uint32_t maxColorAttachments; - VkSampleCountFlags sampledImageColorSampleCounts; - VkSampleCountFlags sampledImageIntegerSampleCounts; - VkSampleCountFlags sampledImageDepthSampleCounts; - VkSampleCountFlags sampledImageStencilSampleCounts; - VkSampleCountFlags storageImageSampleCounts; - uint32_t maxSampleMaskWords; - VkBool32 timestampComputeAndGraphics; - float timestampPeriod; - uint32_t maxClipDistances; - uint32_t maxCullDistances; - uint32_t maxCombinedClipAndCullDistances; - uint32_t discreteQueuePriorities; - float pointSizeRange[2]; - float lineWidthRange[2]; - float pointSizeGranularity; - float lineWidthGranularity; - VkBool32 strictLines; - VkBool32 standardSampleLocations; - VkDeviceSize optimalBufferCopyOffsetAlignment; - VkDeviceSize optimalBufferCopyRowPitchAlignment; - VkDeviceSize nonCoherentAtomSize; -} VkPhysicalDeviceLimits; - -typedef struct VkPhysicalDeviceSparseProperties { - VkBool32 residencyStandard2DBlockShape; - VkBool32 residencyStandard2DMultisampleBlockShape; - VkBool32 residencyStandard3DBlockShape; - VkBool32 residencyAlignedMipSize; - VkBool32 residencyNonResidentStrict; -} VkPhysicalDeviceSparseProperties; - -typedef struct VkPhysicalDeviceProperties { - uint32_t apiVersion; - uint32_t driverVersion; - uint32_t vendorID; - uint32_t deviceID; - VkPhysicalDeviceType deviceType; - char deviceName[VK_MAX_PHYSICAL_DEVICE_NAME_SIZE]; - uint8_t pipelineCacheUUID[VK_UUID_SIZE]; - VkPhysicalDeviceLimits limits; - VkPhysicalDeviceSparseProperties sparseProperties; -} VkPhysicalDeviceProperties; - -typedef struct VkQueueFamilyProperties { - VkQueueFlags queueFlags; - uint32_t queueCount; - uint32_t timestampValidBits; - VkExtent3D minImageTransferGranularity; -} VkQueueFamilyProperties; - -typedef struct VkMemoryType { - VkMemoryPropertyFlags propertyFlags; - uint32_t heapIndex; -} VkMemoryType; - -typedef struct VkMemoryHeap { - VkDeviceSize size; - VkMemoryHeapFlags flags; -} VkMemoryHeap; - -typedef struct VkPhysicalDeviceMemoryProperties { - uint32_t memoryTypeCount; - VkMemoryType memoryTypes[VK_MAX_MEMORY_TYPES]; - uint32_t memoryHeapCount; - VkMemoryHeap memoryHeaps[VK_MAX_MEMORY_HEAPS]; -} VkPhysicalDeviceMemoryProperties; - -typedef void (VKAPI_PTR *PFN_vkVoidFunction)(void); -typedef struct VkDeviceQueueCreateInfo { - VkStructureType sType; - const void* pNext; - VkDeviceQueueCreateFlags flags; - uint32_t queueFamilyIndex; - uint32_t queueCount; - const float* pQueuePriorities; -} VkDeviceQueueCreateInfo; - -typedef struct VkDeviceCreateInfo { - VkStructureType sType; - const void* pNext; - VkDeviceCreateFlags flags; - uint32_t queueCreateInfoCount; - const VkDeviceQueueCreateInfo* pQueueCreateInfos; - uint32_t enabledLayerCount; - const char* const* ppEnabledLayerNames; - uint32_t enabledExtensionCount; - const char* const* ppEnabledExtensionNames; - const VkPhysicalDeviceFeatures* pEnabledFeatures; -} VkDeviceCreateInfo; - -typedef struct VkExtensionProperties { - char extensionName[VK_MAX_EXTENSION_NAME_SIZE]; - uint32_t specVersion; -} VkExtensionProperties; - -typedef struct VkLayerProperties { - char layerName[VK_MAX_EXTENSION_NAME_SIZE]; - uint32_t specVersion; - uint32_t implementationVersion; - char description[VK_MAX_DESCRIPTION_SIZE]; -} VkLayerProperties; - -typedef struct VkSubmitInfo { - VkStructureType sType; - const void* pNext; - uint32_t waitSemaphoreCount; - const VkSemaphore* pWaitSemaphores; - const VkPipelineStageFlags* pWaitDstStageMask; - uint32_t commandBufferCount; - const VkCommandBuffer* pCommandBuffers; - uint32_t signalSemaphoreCount; - const VkSemaphore* pSignalSemaphores; -} VkSubmitInfo; - -typedef struct VkMemoryAllocateInfo { - VkStructureType sType; - const void* pNext; - VkDeviceSize allocationSize; - uint32_t memoryTypeIndex; -} VkMemoryAllocateInfo; - -typedef struct VkMappedMemoryRange { - VkStructureType sType; - const void* pNext; - VkDeviceMemory memory; - VkDeviceSize offset; - VkDeviceSize size; -} VkMappedMemoryRange; - -typedef struct VkMemoryRequirements { - VkDeviceSize size; - VkDeviceSize alignment; - uint32_t memoryTypeBits; -} VkMemoryRequirements; - -typedef struct VkSparseImageFormatProperties { - VkImageAspectFlags aspectMask; - VkExtent3D imageGranularity; - VkSparseImageFormatFlags flags; -} VkSparseImageFormatProperties; - -typedef struct VkSparseImageMemoryRequirements { - VkSparseImageFormatProperties formatProperties; - uint32_t imageMipTailFirstLod; - VkDeviceSize imageMipTailSize; - VkDeviceSize imageMipTailOffset; - VkDeviceSize imageMipTailStride; -} VkSparseImageMemoryRequirements; - -typedef struct VkSparseMemoryBind { - VkDeviceSize resourceOffset; - VkDeviceSize size; - VkDeviceMemory memory; - VkDeviceSize memoryOffset; - VkSparseMemoryBindFlags flags; -} VkSparseMemoryBind; - -typedef struct VkSparseBufferMemoryBindInfo { - VkBuffer buffer; - uint32_t bindCount; - const VkSparseMemoryBind* pBinds; -} VkSparseBufferMemoryBindInfo; - -typedef struct VkSparseImageOpaqueMemoryBindInfo { - VkImage image; - uint32_t bindCount; - const VkSparseMemoryBind* pBinds; -} VkSparseImageOpaqueMemoryBindInfo; - -typedef struct VkImageSubresource { - VkImageAspectFlags aspectMask; - uint32_t mipLevel; - uint32_t arrayLayer; -} VkImageSubresource; - -typedef struct VkOffset3D { - int32_t x; - int32_t y; - int32_t z; -} VkOffset3D; - -typedef struct VkSparseImageMemoryBind { - VkImageSubresource subresource; - VkOffset3D offset; - VkExtent3D extent; - VkDeviceMemory memory; - VkDeviceSize memoryOffset; - VkSparseMemoryBindFlags flags; -} VkSparseImageMemoryBind; - -typedef struct VkSparseImageMemoryBindInfo { - VkImage image; - uint32_t bindCount; - const VkSparseImageMemoryBind* pBinds; -} VkSparseImageMemoryBindInfo; - -typedef struct VkBindSparseInfo { - VkStructureType sType; - const void* pNext; - uint32_t waitSemaphoreCount; - const VkSemaphore* pWaitSemaphores; - uint32_t bufferBindCount; - const VkSparseBufferMemoryBindInfo* pBufferBinds; - uint32_t imageOpaqueBindCount; - const VkSparseImageOpaqueMemoryBindInfo* pImageOpaqueBinds; - uint32_t imageBindCount; - const VkSparseImageMemoryBindInfo* pImageBinds; - uint32_t signalSemaphoreCount; - const VkSemaphore* pSignalSemaphores; -} VkBindSparseInfo; - -typedef struct VkFenceCreateInfo { - VkStructureType sType; - const void* pNext; - VkFenceCreateFlags flags; -} VkFenceCreateInfo; - -typedef struct VkSemaphoreCreateInfo { - VkStructureType sType; - const void* pNext; - VkSemaphoreCreateFlags flags; -} VkSemaphoreCreateInfo; - -typedef struct VkEventCreateInfo { - VkStructureType sType; - const void* pNext; - VkEventCreateFlags flags; -} VkEventCreateInfo; - -typedef struct VkQueryPoolCreateInfo { - VkStructureType sType; - const void* pNext; - VkQueryPoolCreateFlags flags; - VkQueryType queryType; - uint32_t queryCount; - VkQueryPipelineStatisticFlags pipelineStatistics; -} VkQueryPoolCreateInfo; - -typedef struct VkBufferCreateInfo { - VkStructureType sType; - const void* pNext; - VkBufferCreateFlags flags; - VkDeviceSize size; - VkBufferUsageFlags usage; - VkSharingMode sharingMode; - uint32_t queueFamilyIndexCount; - const uint32_t* pQueueFamilyIndices; -} VkBufferCreateInfo; - -typedef struct VkBufferViewCreateInfo { - VkStructureType sType; - const void* pNext; - VkBufferViewCreateFlags flags; - VkBuffer buffer; - VkFormat format; - VkDeviceSize offset; - VkDeviceSize range; -} VkBufferViewCreateInfo; - -typedef struct VkImageCreateInfo { - VkStructureType sType; - const void* pNext; - VkImageCreateFlags flags; - VkImageType imageType; - VkFormat format; - VkExtent3D extent; - uint32_t mipLevels; - uint32_t arrayLayers; - VkSampleCountFlagBits samples; - VkImageTiling tiling; - VkImageUsageFlags usage; - VkSharingMode sharingMode; - uint32_t queueFamilyIndexCount; - const uint32_t* pQueueFamilyIndices; - VkImageLayout initialLayout; -} VkImageCreateInfo; - -typedef struct VkSubresourceLayout { - VkDeviceSize offset; - VkDeviceSize size; - VkDeviceSize rowPitch; - VkDeviceSize arrayPitch; - VkDeviceSize depthPitch; -} VkSubresourceLayout; - -typedef struct VkComponentMapping { - VkComponentSwizzle r; - VkComponentSwizzle g; - VkComponentSwizzle b; - VkComponentSwizzle a; -} VkComponentMapping; - -typedef struct VkImageSubresourceRange { - VkImageAspectFlags aspectMask; - uint32_t baseMipLevel; - uint32_t levelCount; - uint32_t baseArrayLayer; - uint32_t layerCount; -} VkImageSubresourceRange; - -typedef struct VkImageViewCreateInfo { - VkStructureType sType; - const void* pNext; - VkImageViewCreateFlags flags; - VkImage image; - VkImageViewType viewType; - VkFormat format; - VkComponentMapping components; - VkImageSubresourceRange subresourceRange; -} VkImageViewCreateInfo; - -typedef struct VkShaderModuleCreateInfo { - VkStructureType sType; - const void* pNext; - VkShaderModuleCreateFlags flags; - size_t codeSize; - const uint32_t* pCode; -} VkShaderModuleCreateInfo; - -typedef struct VkPipelineCacheCreateInfo { - VkStructureType sType; - const void* pNext; - VkPipelineCacheCreateFlags flags; - size_t initialDataSize; - const void* pInitialData; -} VkPipelineCacheCreateInfo; - -typedef struct VkSpecializationMapEntry { - uint32_t constantID; - uint32_t offset; - size_t size; -} VkSpecializationMapEntry; - -typedef struct VkSpecializationInfo { - uint32_t mapEntryCount; - const VkSpecializationMapEntry* pMapEntries; - size_t dataSize; - const void* pData; -} VkSpecializationInfo; - -typedef struct VkPipelineShaderStageCreateInfo { - VkStructureType sType; - const void* pNext; - VkPipelineShaderStageCreateFlags flags; - VkShaderStageFlagBits stage; - VkShaderModule module; - const char* pName; - const VkSpecializationInfo* pSpecializationInfo; -} VkPipelineShaderStageCreateInfo; - -typedef struct VkVertexInputBindingDescription { - uint32_t binding; - uint32_t stride; - VkVertexInputRate inputRate; -} VkVertexInputBindingDescription; - -typedef struct VkVertexInputAttributeDescription { - uint32_t location; - uint32_t binding; - VkFormat format; - uint32_t offset; -} VkVertexInputAttributeDescription; - -typedef struct VkPipelineVertexInputStateCreateInfo { - VkStructureType sType; - const void* pNext; - VkPipelineVertexInputStateCreateFlags flags; - uint32_t vertexBindingDescriptionCount; - const VkVertexInputBindingDescription* pVertexBindingDescriptions; - uint32_t vertexAttributeDescriptionCount; - const VkVertexInputAttributeDescription* pVertexAttributeDescriptions; -} VkPipelineVertexInputStateCreateInfo; - -typedef struct VkPipelineInputAssemblyStateCreateInfo { - VkStructureType sType; - const void* pNext; - VkPipelineInputAssemblyStateCreateFlags flags; - VkPrimitiveTopology topology; - VkBool32 primitiveRestartEnable; -} VkPipelineInputAssemblyStateCreateInfo; - -typedef struct VkPipelineTessellationStateCreateInfo { - VkStructureType sType; - const void* pNext; - VkPipelineTessellationStateCreateFlags flags; - uint32_t patchControlPoints; -} VkPipelineTessellationStateCreateInfo; - -typedef struct VkViewport { - float x; - float y; - float width; - float height; - float minDepth; - float maxDepth; -} VkViewport; - -typedef struct VkOffset2D { - int32_t x; - int32_t y; -} VkOffset2D; - -typedef struct VkExtent2D { - uint32_t width; - uint32_t height; -} VkExtent2D; - -typedef struct VkRect2D { - VkOffset2D offset; - VkExtent2D extent; -} VkRect2D; - -typedef struct VkPipelineViewportStateCreateInfo { - VkStructureType sType; - const void* pNext; - VkPipelineViewportStateCreateFlags flags; - uint32_t viewportCount; - const VkViewport* pViewports; - uint32_t scissorCount; - const VkRect2D* pScissors; -} VkPipelineViewportStateCreateInfo; - -typedef struct VkPipelineRasterizationStateCreateInfo { - VkStructureType sType; - const void* pNext; - VkPipelineRasterizationStateCreateFlags flags; - VkBool32 depthClampEnable; - VkBool32 rasterizerDiscardEnable; - VkPolygonMode polygonMode; - VkCullModeFlags cullMode; - VkFrontFace frontFace; - VkBool32 depthBiasEnable; - float depthBiasConstantFactor; - float depthBiasClamp; - float depthBiasSlopeFactor; - float lineWidth; -} VkPipelineRasterizationStateCreateInfo; - -typedef struct VkPipelineMultisampleStateCreateInfo { - VkStructureType sType; - const void* pNext; - VkPipelineMultisampleStateCreateFlags flags; - VkSampleCountFlagBits rasterizationSamples; - VkBool32 sampleShadingEnable; - float minSampleShading; - const VkSampleMask* pSampleMask; - VkBool32 alphaToCoverageEnable; - VkBool32 alphaToOneEnable; -} VkPipelineMultisampleStateCreateInfo; - -typedef struct VkStencilOpState { - VkStencilOp failOp; - VkStencilOp passOp; - VkStencilOp depthFailOp; - VkCompareOp compareOp; - uint32_t compareMask; - uint32_t writeMask; - uint32_t reference; -} VkStencilOpState; - -typedef struct VkPipelineDepthStencilStateCreateInfo { - VkStructureType sType; - const void* pNext; - VkPipelineDepthStencilStateCreateFlags flags; - VkBool32 depthTestEnable; - VkBool32 depthWriteEnable; - VkCompareOp depthCompareOp; - VkBool32 depthBoundsTestEnable; - VkBool32 stencilTestEnable; - VkStencilOpState front; - VkStencilOpState back; - float minDepthBounds; - float maxDepthBounds; -} VkPipelineDepthStencilStateCreateInfo; - -typedef struct VkPipelineColorBlendAttachmentState { - VkBool32 blendEnable; - VkBlendFactor srcColorBlendFactor; - VkBlendFactor dstColorBlendFactor; - VkBlendOp colorBlendOp; - VkBlendFactor srcAlphaBlendFactor; - VkBlendFactor dstAlphaBlendFactor; - VkBlendOp alphaBlendOp; - VkColorComponentFlags colorWriteMask; -} VkPipelineColorBlendAttachmentState; - -typedef struct VkPipelineColorBlendStateCreateInfo { - VkStructureType sType; - const void* pNext; - VkPipelineColorBlendStateCreateFlags flags; - VkBool32 logicOpEnable; - VkLogicOp logicOp; - uint32_t attachmentCount; - const VkPipelineColorBlendAttachmentState* pAttachments; - float blendConstants[4]; -} VkPipelineColorBlendStateCreateInfo; - -typedef struct VkPipelineDynamicStateCreateInfo { - VkStructureType sType; - const void* pNext; - VkPipelineDynamicStateCreateFlags flags; - uint32_t dynamicStateCount; - const VkDynamicState* pDynamicStates; -} VkPipelineDynamicStateCreateInfo; - -typedef struct VkGraphicsPipelineCreateInfo { - VkStructureType sType; - const void* pNext; - VkPipelineCreateFlags flags; - uint32_t stageCount; - const VkPipelineShaderStageCreateInfo* pStages; - const VkPipelineVertexInputStateCreateInfo* pVertexInputState; - const VkPipelineInputAssemblyStateCreateInfo* pInputAssemblyState; - const VkPipelineTessellationStateCreateInfo* pTessellationState; - const VkPipelineViewportStateCreateInfo* pViewportState; - const VkPipelineRasterizationStateCreateInfo* pRasterizationState; - const VkPipelineMultisampleStateCreateInfo* pMultisampleState; - const VkPipelineDepthStencilStateCreateInfo* pDepthStencilState; - const VkPipelineColorBlendStateCreateInfo* pColorBlendState; - const VkPipelineDynamicStateCreateInfo* pDynamicState; - VkPipelineLayout layout; - VkRenderPass renderPass; - uint32_t subpass; - VkPipeline basePipelineHandle; - int32_t basePipelineIndex; -} VkGraphicsPipelineCreateInfo; - -typedef struct VkComputePipelineCreateInfo { - VkStructureType sType; - const void* pNext; - VkPipelineCreateFlags flags; - VkPipelineShaderStageCreateInfo stage; - VkPipelineLayout layout; - VkPipeline basePipelineHandle; - int32_t basePipelineIndex; -} VkComputePipelineCreateInfo; - -typedef struct VkPushConstantRange { - VkShaderStageFlags stageFlags; - uint32_t offset; - uint32_t size; -} VkPushConstantRange; - -typedef struct VkPipelineLayoutCreateInfo { - VkStructureType sType; - const void* pNext; - VkPipelineLayoutCreateFlags flags; - uint32_t setLayoutCount; - const VkDescriptorSetLayout* pSetLayouts; - uint32_t pushConstantRangeCount; - const VkPushConstantRange* pPushConstantRanges; -} VkPipelineLayoutCreateInfo; - -typedef struct VkSamplerCreateInfo { - VkStructureType sType; - const void* pNext; - VkSamplerCreateFlags flags; - VkFilter magFilter; - VkFilter minFilter; - VkSamplerMipmapMode mipmapMode; - VkSamplerAddressMode addressModeU; - VkSamplerAddressMode addressModeV; - VkSamplerAddressMode addressModeW; - float mipLodBias; - VkBool32 anisotropyEnable; - float maxAnisotropy; - VkBool32 compareEnable; - VkCompareOp compareOp; - float minLod; - float maxLod; - VkBorderColor borderColor; - VkBool32 unnormalizedCoordinates; -} VkSamplerCreateInfo; - -typedef struct VkDescriptorSetLayoutBinding { - uint32_t binding; - VkDescriptorType descriptorType; - uint32_t descriptorCount; - VkShaderStageFlags stageFlags; - const VkSampler* pImmutableSamplers; -} VkDescriptorSetLayoutBinding; - -typedef struct VkDescriptorSetLayoutCreateInfo { - VkStructureType sType; - const void* pNext; - VkDescriptorSetLayoutCreateFlags flags; - uint32_t bindingCount; - const VkDescriptorSetLayoutBinding* pBindings; -} VkDescriptorSetLayoutCreateInfo; - -typedef struct VkDescriptorPoolSize { - VkDescriptorType type; - uint32_t descriptorCount; -} VkDescriptorPoolSize; - -typedef struct VkDescriptorPoolCreateInfo { - VkStructureType sType; - const void* pNext; - VkDescriptorPoolCreateFlags flags; - uint32_t maxSets; - uint32_t poolSizeCount; - const VkDescriptorPoolSize* pPoolSizes; -} VkDescriptorPoolCreateInfo; - -typedef struct VkDescriptorSetAllocateInfo { - VkStructureType sType; - const void* pNext; - VkDescriptorPool descriptorPool; - uint32_t descriptorSetCount; - const VkDescriptorSetLayout* pSetLayouts; -} VkDescriptorSetAllocateInfo; - -typedef struct VkDescriptorImageInfo { - VkSampler sampler; - VkImageView imageView; - VkImageLayout imageLayout; -} VkDescriptorImageInfo; - -typedef struct VkDescriptorBufferInfo { - VkBuffer buffer; - VkDeviceSize offset; - VkDeviceSize range; -} VkDescriptorBufferInfo; - -typedef struct VkWriteDescriptorSet { - VkStructureType sType; - const void* pNext; - VkDescriptorSet dstSet; - uint32_t dstBinding; - uint32_t dstArrayElement; - uint32_t descriptorCount; - VkDescriptorType descriptorType; - const VkDescriptorImageInfo* pImageInfo; - const VkDescriptorBufferInfo* pBufferInfo; - const VkBufferView* pTexelBufferView; -} VkWriteDescriptorSet; - -typedef struct VkCopyDescriptorSet { - VkStructureType sType; - const void* pNext; - VkDescriptorSet srcSet; - uint32_t srcBinding; - uint32_t srcArrayElement; - VkDescriptorSet dstSet; - uint32_t dstBinding; - uint32_t dstArrayElement; - uint32_t descriptorCount; -} VkCopyDescriptorSet; - -typedef struct VkFramebufferCreateInfo { - VkStructureType sType; - const void* pNext; - VkFramebufferCreateFlags flags; - VkRenderPass renderPass; - uint32_t attachmentCount; - const VkImageView* pAttachments; - uint32_t width; - uint32_t height; - uint32_t layers; -} VkFramebufferCreateInfo; - -typedef struct VkAttachmentDescription { - VkAttachmentDescriptionFlags flags; - VkFormat format; - VkSampleCountFlagBits samples; - VkAttachmentLoadOp loadOp; - VkAttachmentStoreOp storeOp; - VkAttachmentLoadOp stencilLoadOp; - VkAttachmentStoreOp stencilStoreOp; - VkImageLayout initialLayout; - VkImageLayout finalLayout; -} VkAttachmentDescription; - -typedef struct VkAttachmentReference { - uint32_t attachment; - VkImageLayout layout; -} VkAttachmentReference; - -typedef struct VkSubpassDescription { - VkSubpassDescriptionFlags flags; - VkPipelineBindPoint pipelineBindPoint; - uint32_t inputAttachmentCount; - const VkAttachmentReference* pInputAttachments; - uint32_t colorAttachmentCount; - const VkAttachmentReference* pColorAttachments; - const VkAttachmentReference* pResolveAttachments; - const VkAttachmentReference* pDepthStencilAttachment; - uint32_t preserveAttachmentCount; - const uint32_t* pPreserveAttachments; -} VkSubpassDescription; - -typedef struct VkSubpassDependency { - uint32_t srcSubpass; - uint32_t dstSubpass; - VkPipelineStageFlags srcStageMask; - VkPipelineStageFlags dstStageMask; - VkAccessFlags srcAccessMask; - VkAccessFlags dstAccessMask; - VkDependencyFlags dependencyFlags; -} VkSubpassDependency; - -typedef struct VkRenderPassCreateInfo { - VkStructureType sType; - const void* pNext; - VkRenderPassCreateFlags flags; - uint32_t attachmentCount; - const VkAttachmentDescription* pAttachments; - uint32_t subpassCount; - const VkSubpassDescription* pSubpasses; - uint32_t dependencyCount; - const VkSubpassDependency* pDependencies; -} VkRenderPassCreateInfo; - -typedef struct VkCommandPoolCreateInfo { - VkStructureType sType; - const void* pNext; - VkCommandPoolCreateFlags flags; - uint32_t queueFamilyIndex; -} VkCommandPoolCreateInfo; - -typedef struct VkCommandBufferAllocateInfo { - VkStructureType sType; - const void* pNext; - VkCommandPool commandPool; - VkCommandBufferLevel level; - uint32_t commandBufferCount; -} VkCommandBufferAllocateInfo; - -typedef struct VkCommandBufferInheritanceInfo { - VkStructureType sType; - const void* pNext; - VkRenderPass renderPass; - uint32_t subpass; - VkFramebuffer framebuffer; - VkBool32 occlusionQueryEnable; - VkQueryControlFlags queryFlags; - VkQueryPipelineStatisticFlags pipelineStatistics; -} VkCommandBufferInheritanceInfo; - -typedef struct VkCommandBufferBeginInfo { - VkStructureType sType; - const void* pNext; - VkCommandBufferUsageFlags flags; - const VkCommandBufferInheritanceInfo* pInheritanceInfo; -} VkCommandBufferBeginInfo; - -typedef struct VkBufferCopy { - VkDeviceSize srcOffset; - VkDeviceSize dstOffset; - VkDeviceSize size; -} VkBufferCopy; - -typedef struct VkImageSubresourceLayers { - VkImageAspectFlags aspectMask; - uint32_t mipLevel; - uint32_t baseArrayLayer; - uint32_t layerCount; -} VkImageSubresourceLayers; - -typedef struct VkImageCopy { - VkImageSubresourceLayers srcSubresource; - VkOffset3D srcOffset; - VkImageSubresourceLayers dstSubresource; - VkOffset3D dstOffset; - VkExtent3D extent; -} VkImageCopy; - -typedef struct VkImageBlit { - VkImageSubresourceLayers srcSubresource; - VkOffset3D srcOffsets[2]; - VkImageSubresourceLayers dstSubresource; - VkOffset3D dstOffsets[2]; -} VkImageBlit; - -typedef struct VkBufferImageCopy { - VkDeviceSize bufferOffset; - uint32_t bufferRowLength; - uint32_t bufferImageHeight; - VkImageSubresourceLayers imageSubresource; - VkOffset3D imageOffset; - VkExtent3D imageExtent; -} VkBufferImageCopy; - -typedef union VkClearColorValue { - float float32[4]; - int32_t int32[4]; - uint32_t uint32[4]; -} VkClearColorValue; - -typedef struct VkClearDepthStencilValue { - float depth; - uint32_t stencil; -} VkClearDepthStencilValue; - -typedef union VkClearValue { - VkClearColorValue color; - VkClearDepthStencilValue depthStencil; -} VkClearValue; - -typedef struct VkClearAttachment { - VkImageAspectFlags aspectMask; - uint32_t colorAttachment; - VkClearValue clearValue; -} VkClearAttachment; - -typedef struct VkClearRect { - VkRect2D rect; - uint32_t baseArrayLayer; - uint32_t layerCount; -} VkClearRect; - -typedef struct VkImageResolve { - VkImageSubresourceLayers srcSubresource; - VkOffset3D srcOffset; - VkImageSubresourceLayers dstSubresource; - VkOffset3D dstOffset; - VkExtent3D extent; -} VkImageResolve; - -typedef struct VkMemoryBarrier { - VkStructureType sType; - const void* pNext; - VkAccessFlags srcAccessMask; - VkAccessFlags dstAccessMask; -} VkMemoryBarrier; - -typedef struct VkBufferMemoryBarrier { - VkStructureType sType; - const void* pNext; - VkAccessFlags srcAccessMask; - VkAccessFlags dstAccessMask; - uint32_t srcQueueFamilyIndex; - uint32_t dstQueueFamilyIndex; - VkBuffer buffer; - VkDeviceSize offset; - VkDeviceSize size; -} VkBufferMemoryBarrier; - -typedef struct VkImageMemoryBarrier { - VkStructureType sType; - const void* pNext; - VkAccessFlags srcAccessMask; - VkAccessFlags dstAccessMask; - VkImageLayout oldLayout; - VkImageLayout newLayout; - uint32_t srcQueueFamilyIndex; - uint32_t dstQueueFamilyIndex; - VkImage image; - VkImageSubresourceRange subresourceRange; -} VkImageMemoryBarrier; - -typedef struct VkRenderPassBeginInfo { - VkStructureType sType; - const void* pNext; - VkRenderPass renderPass; - VkFramebuffer framebuffer; - VkRect2D renderArea; - uint32_t clearValueCount; - const VkClearValue* pClearValues; -} VkRenderPassBeginInfo; - -typedef struct VkDispatchIndirectCommand { - uint32_t x; - uint32_t y; - uint32_t z; -} VkDispatchIndirectCommand; - -typedef struct VkDrawIndexedIndirectCommand { - uint32_t indexCount; - uint32_t instanceCount; - uint32_t firstIndex; - int32_t vertexOffset; - uint32_t firstInstance; -} VkDrawIndexedIndirectCommand; - -typedef struct VkDrawIndirectCommand { - uint32_t vertexCount; - uint32_t instanceCount; - uint32_t firstVertex; - uint32_t firstInstance; -} VkDrawIndirectCommand; - - -typedef VkResult (VKAPI_PTR *PFN_vkCreateInstance)(const VkInstanceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkInstance* pInstance); -typedef void (VKAPI_PTR *PFN_vkDestroyInstance)(VkInstance instance, const VkAllocationCallbacks* pAllocator); -typedef VkResult (VKAPI_PTR *PFN_vkEnumeratePhysicalDevices)(VkInstance instance, uint32_t* pPhysicalDeviceCount, VkPhysicalDevice* pPhysicalDevices); -typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceFeatures)(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures* pFeatures); -typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceFormatProperties)(VkPhysicalDevice physicalDevice, VkFormat format, VkFormatProperties* pFormatProperties); -typedef VkResult (VKAPI_PTR *PFN_vkGetPhysicalDeviceImageFormatProperties)(VkPhysicalDevice physicalDevice, VkFormat format, VkImageType type, VkImageTiling tiling, VkImageUsageFlags usage, VkImageCreateFlags flags, VkImageFormatProperties* pImageFormatProperties); -typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceProperties)(VkPhysicalDevice physicalDevice, VkPhysicalDeviceProperties* pProperties); -typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceQueueFamilyProperties)(VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount, VkQueueFamilyProperties* pQueueFamilyProperties); -typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceMemoryProperties)(VkPhysicalDevice physicalDevice, VkPhysicalDeviceMemoryProperties* pMemoryProperties); -typedef PFN_vkVoidFunction (VKAPI_PTR *PFN_vkGetInstanceProcAddr)(VkInstance instance, const char* pName); -typedef PFN_vkVoidFunction (VKAPI_PTR *PFN_vkGetDeviceProcAddr)(VkDevice device, const char* pName); -typedef VkResult (VKAPI_PTR *PFN_vkCreateDevice)(VkPhysicalDevice physicalDevice, const VkDeviceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDevice* pDevice); -typedef void (VKAPI_PTR *PFN_vkDestroyDevice)(VkDevice device, const VkAllocationCallbacks* pAllocator); -typedef VkResult (VKAPI_PTR *PFN_vkEnumerateInstanceExtensionProperties)(const char* pLayerName, uint32_t* pPropertyCount, VkExtensionProperties* pProperties); -typedef VkResult (VKAPI_PTR *PFN_vkEnumerateDeviceExtensionProperties)(VkPhysicalDevice physicalDevice, const char* pLayerName, uint32_t* pPropertyCount, VkExtensionProperties* pProperties); -typedef VkResult (VKAPI_PTR *PFN_vkEnumerateInstanceLayerProperties)(uint32_t* pPropertyCount, VkLayerProperties* pProperties); -typedef VkResult (VKAPI_PTR *PFN_vkEnumerateDeviceLayerProperties)(VkPhysicalDevice physicalDevice, uint32_t* pPropertyCount, VkLayerProperties* pProperties); -typedef void (VKAPI_PTR *PFN_vkGetDeviceQueue)(VkDevice device, uint32_t queueFamilyIndex, uint32_t queueIndex, VkQueue* pQueue); -typedef VkResult (VKAPI_PTR *PFN_vkQueueSubmit)(VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits, VkFence fence); -typedef VkResult (VKAPI_PTR *PFN_vkQueueWaitIdle)(VkQueue queue); -typedef VkResult (VKAPI_PTR *PFN_vkDeviceWaitIdle)(VkDevice device); -typedef VkResult (VKAPI_PTR *PFN_vkAllocateMemory)(VkDevice device, const VkMemoryAllocateInfo* pAllocateInfo, const VkAllocationCallbacks* pAllocator, VkDeviceMemory* pMemory); -typedef void (VKAPI_PTR *PFN_vkFreeMemory)(VkDevice device, VkDeviceMemory memory, const VkAllocationCallbacks* pAllocator); -typedef VkResult (VKAPI_PTR *PFN_vkMapMemory)(VkDevice device, VkDeviceMemory memory, VkDeviceSize offset, VkDeviceSize size, VkMemoryMapFlags flags, void** ppData); -typedef void (VKAPI_PTR *PFN_vkUnmapMemory)(VkDevice device, VkDeviceMemory memory); -typedef VkResult (VKAPI_PTR *PFN_vkFlushMappedMemoryRanges)(VkDevice device, uint32_t memoryRangeCount, const VkMappedMemoryRange* pMemoryRanges); -typedef VkResult (VKAPI_PTR *PFN_vkInvalidateMappedMemoryRanges)(VkDevice device, uint32_t memoryRangeCount, const VkMappedMemoryRange* pMemoryRanges); -typedef void (VKAPI_PTR *PFN_vkGetDeviceMemoryCommitment)(VkDevice device, VkDeviceMemory memory, VkDeviceSize* pCommittedMemoryInBytes); -typedef VkResult (VKAPI_PTR *PFN_vkBindBufferMemory)(VkDevice device, VkBuffer buffer, VkDeviceMemory memory, VkDeviceSize memoryOffset); -typedef VkResult (VKAPI_PTR *PFN_vkBindImageMemory)(VkDevice device, VkImage image, VkDeviceMemory memory, VkDeviceSize memoryOffset); -typedef void (VKAPI_PTR *PFN_vkGetBufferMemoryRequirements)(VkDevice device, VkBuffer buffer, VkMemoryRequirements* pMemoryRequirements); -typedef void (VKAPI_PTR *PFN_vkGetImageMemoryRequirements)(VkDevice device, VkImage image, VkMemoryRequirements* pMemoryRequirements); -typedef void (VKAPI_PTR *PFN_vkGetImageSparseMemoryRequirements)(VkDevice device, VkImage image, uint32_t* pSparseMemoryRequirementCount, VkSparseImageMemoryRequirements* pSparseMemoryRequirements); -typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceSparseImageFormatProperties)(VkPhysicalDevice physicalDevice, VkFormat format, VkImageType type, VkSampleCountFlagBits samples, VkImageUsageFlags usage, VkImageTiling tiling, uint32_t* pPropertyCount, VkSparseImageFormatProperties* pProperties); -typedef VkResult (VKAPI_PTR *PFN_vkQueueBindSparse)(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo* pBindInfo, VkFence fence); -typedef VkResult (VKAPI_PTR *PFN_vkCreateFence)(VkDevice device, const VkFenceCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkFence* pFence); -typedef void (VKAPI_PTR *PFN_vkDestroyFence)(VkDevice device, VkFence fence, const VkAllocationCallbacks* pAllocator); -typedef VkResult (VKAPI_PTR *PFN_vkResetFences)(VkDevice device, uint32_t fenceCount, const VkFence* pFences); -typedef VkResult (VKAPI_PTR *PFN_vkGetFenceStatus)(VkDevice device, VkFence fence); -typedef VkResult (VKAPI_PTR *PFN_vkWaitForFences)(VkDevice device, uint32_t fenceCount, const VkFence* pFences, VkBool32 waitAll, uint64_t timeout); -typedef VkResult (VKAPI_PTR *PFN_vkCreateSemaphore)(VkDevice device, const VkSemaphoreCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSemaphore* pSemaphore); -typedef void (VKAPI_PTR *PFN_vkDestroySemaphore)(VkDevice device, VkSemaphore semaphore, const VkAllocationCallbacks* pAllocator); -typedef VkResult (VKAPI_PTR *PFN_vkCreateEvent)(VkDevice device, const VkEventCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkEvent* pEvent); -typedef void (VKAPI_PTR *PFN_vkDestroyEvent)(VkDevice device, VkEvent event, const VkAllocationCallbacks* pAllocator); -typedef VkResult (VKAPI_PTR *PFN_vkGetEventStatus)(VkDevice device, VkEvent event); -typedef VkResult (VKAPI_PTR *PFN_vkSetEvent)(VkDevice device, VkEvent event); -typedef VkResult (VKAPI_PTR *PFN_vkResetEvent)(VkDevice device, VkEvent event); -typedef VkResult (VKAPI_PTR *PFN_vkCreateQueryPool)(VkDevice device, const VkQueryPoolCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkQueryPool* pQueryPool); -typedef void (VKAPI_PTR *PFN_vkDestroyQueryPool)(VkDevice device, VkQueryPool queryPool, const VkAllocationCallbacks* pAllocator); -typedef VkResult (VKAPI_PTR *PFN_vkGetQueryPoolResults)(VkDevice device, VkQueryPool queryPool, uint32_t firstQuery, uint32_t queryCount, size_t dataSize, void* pData, VkDeviceSize stride, VkQueryResultFlags flags); -typedef VkResult (VKAPI_PTR *PFN_vkCreateBuffer)(VkDevice device, const VkBufferCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkBuffer* pBuffer); -typedef void (VKAPI_PTR *PFN_vkDestroyBuffer)(VkDevice device, VkBuffer buffer, const VkAllocationCallbacks* pAllocator); -typedef VkResult (VKAPI_PTR *PFN_vkCreateBufferView)(VkDevice device, const VkBufferViewCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkBufferView* pView); -typedef void (VKAPI_PTR *PFN_vkDestroyBufferView)(VkDevice device, VkBufferView bufferView, const VkAllocationCallbacks* pAllocator); -typedef VkResult (VKAPI_PTR *PFN_vkCreateImage)(VkDevice device, const VkImageCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkImage* pImage); -typedef void (VKAPI_PTR *PFN_vkDestroyImage)(VkDevice device, VkImage image, const VkAllocationCallbacks* pAllocator); -typedef void (VKAPI_PTR *PFN_vkGetImageSubresourceLayout)(VkDevice device, VkImage image, const VkImageSubresource* pSubresource, VkSubresourceLayout* pLayout); -typedef VkResult (VKAPI_PTR *PFN_vkCreateImageView)(VkDevice device, const VkImageViewCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkImageView* pView); -typedef void (VKAPI_PTR *PFN_vkDestroyImageView)(VkDevice device, VkImageView imageView, const VkAllocationCallbacks* pAllocator); -typedef VkResult (VKAPI_PTR *PFN_vkCreateShaderModule)(VkDevice device, const VkShaderModuleCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkShaderModule* pShaderModule); -typedef void (VKAPI_PTR *PFN_vkDestroyShaderModule)(VkDevice device, VkShaderModule shaderModule, const VkAllocationCallbacks* pAllocator); -typedef VkResult (VKAPI_PTR *PFN_vkCreatePipelineCache)(VkDevice device, const VkPipelineCacheCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkPipelineCache* pPipelineCache); -typedef void (VKAPI_PTR *PFN_vkDestroyPipelineCache)(VkDevice device, VkPipelineCache pipelineCache, const VkAllocationCallbacks* pAllocator); -typedef VkResult (VKAPI_PTR *PFN_vkGetPipelineCacheData)(VkDevice device, VkPipelineCache pipelineCache, size_t* pDataSize, void* pData); -typedef VkResult (VKAPI_PTR *PFN_vkMergePipelineCaches)(VkDevice device, VkPipelineCache dstCache, uint32_t srcCacheCount, const VkPipelineCache* pSrcCaches); -typedef VkResult (VKAPI_PTR *PFN_vkCreateGraphicsPipelines)(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount, const VkGraphicsPipelineCreateInfo* pCreateInfos, const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines); -typedef VkResult (VKAPI_PTR *PFN_vkCreateComputePipelines)(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount, const VkComputePipelineCreateInfo* pCreateInfos, const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines); -typedef void (VKAPI_PTR *PFN_vkDestroyPipeline)(VkDevice device, VkPipeline pipeline, const VkAllocationCallbacks* pAllocator); -typedef VkResult (VKAPI_PTR *PFN_vkCreatePipelineLayout)(VkDevice device, const VkPipelineLayoutCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkPipelineLayout* pPipelineLayout); -typedef void (VKAPI_PTR *PFN_vkDestroyPipelineLayout)(VkDevice device, VkPipelineLayout pipelineLayout, const VkAllocationCallbacks* pAllocator); -typedef VkResult (VKAPI_PTR *PFN_vkCreateSampler)(VkDevice device, const VkSamplerCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSampler* pSampler); -typedef void (VKAPI_PTR *PFN_vkDestroySampler)(VkDevice device, VkSampler sampler, const VkAllocationCallbacks* pAllocator); -typedef VkResult (VKAPI_PTR *PFN_vkCreateDescriptorSetLayout)(VkDevice device, const VkDescriptorSetLayoutCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDescriptorSetLayout* pSetLayout); -typedef void (VKAPI_PTR *PFN_vkDestroyDescriptorSetLayout)(VkDevice device, VkDescriptorSetLayout descriptorSetLayout, const VkAllocationCallbacks* pAllocator); -typedef VkResult (VKAPI_PTR *PFN_vkCreateDescriptorPool)(VkDevice device, const VkDescriptorPoolCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDescriptorPool* pDescriptorPool); -typedef void (VKAPI_PTR *PFN_vkDestroyDescriptorPool)(VkDevice device, VkDescriptorPool descriptorPool, const VkAllocationCallbacks* pAllocator); -typedef VkResult (VKAPI_PTR *PFN_vkResetDescriptorPool)(VkDevice device, VkDescriptorPool descriptorPool, VkDescriptorPoolResetFlags flags); -typedef VkResult (VKAPI_PTR *PFN_vkAllocateDescriptorSets)(VkDevice device, const VkDescriptorSetAllocateInfo* pAllocateInfo, VkDescriptorSet* pDescriptorSets); -typedef VkResult (VKAPI_PTR *PFN_vkFreeDescriptorSets)(VkDevice device, VkDescriptorPool descriptorPool, uint32_t descriptorSetCount, const VkDescriptorSet* pDescriptorSets); -typedef void (VKAPI_PTR *PFN_vkUpdateDescriptorSets)(VkDevice device, uint32_t descriptorWriteCount, const VkWriteDescriptorSet* pDescriptorWrites, uint32_t descriptorCopyCount, const VkCopyDescriptorSet* pDescriptorCopies); -typedef VkResult (VKAPI_PTR *PFN_vkCreateFramebuffer)(VkDevice device, const VkFramebufferCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkFramebuffer* pFramebuffer); -typedef void (VKAPI_PTR *PFN_vkDestroyFramebuffer)(VkDevice device, VkFramebuffer framebuffer, const VkAllocationCallbacks* pAllocator); -typedef VkResult (VKAPI_PTR *PFN_vkCreateRenderPass)(VkDevice device, const VkRenderPassCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkRenderPass* pRenderPass); -typedef void (VKAPI_PTR *PFN_vkDestroyRenderPass)(VkDevice device, VkRenderPass renderPass, const VkAllocationCallbacks* pAllocator); -typedef void (VKAPI_PTR *PFN_vkGetRenderAreaGranularity)(VkDevice device, VkRenderPass renderPass, VkExtent2D* pGranularity); -typedef VkResult (VKAPI_PTR *PFN_vkCreateCommandPool)(VkDevice device, const VkCommandPoolCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkCommandPool* pCommandPool); -typedef void (VKAPI_PTR *PFN_vkDestroyCommandPool)(VkDevice device, VkCommandPool commandPool, const VkAllocationCallbacks* pAllocator); -typedef VkResult (VKAPI_PTR *PFN_vkResetCommandPool)(VkDevice device, VkCommandPool commandPool, VkCommandPoolResetFlags flags); -typedef VkResult (VKAPI_PTR *PFN_vkAllocateCommandBuffers)(VkDevice device, const VkCommandBufferAllocateInfo* pAllocateInfo, VkCommandBuffer* pCommandBuffers); -typedef void (VKAPI_PTR *PFN_vkFreeCommandBuffers)(VkDevice device, VkCommandPool commandPool, uint32_t commandBufferCount, const VkCommandBuffer* pCommandBuffers); -typedef VkResult (VKAPI_PTR *PFN_vkBeginCommandBuffer)(VkCommandBuffer commandBuffer, const VkCommandBufferBeginInfo* pBeginInfo); -typedef VkResult (VKAPI_PTR *PFN_vkEndCommandBuffer)(VkCommandBuffer commandBuffer); -typedef VkResult (VKAPI_PTR *PFN_vkResetCommandBuffer)(VkCommandBuffer commandBuffer, VkCommandBufferResetFlags flags); -typedef void (VKAPI_PTR *PFN_vkCmdBindPipeline)(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint, VkPipeline pipeline); -typedef void (VKAPI_PTR *PFN_vkCmdSetViewport)(VkCommandBuffer commandBuffer, uint32_t firstViewport, uint32_t viewportCount, const VkViewport* pViewports); -typedef void (VKAPI_PTR *PFN_vkCmdSetScissor)(VkCommandBuffer commandBuffer, uint32_t firstScissor, uint32_t scissorCount, const VkRect2D* pScissors); -typedef void (VKAPI_PTR *PFN_vkCmdSetLineWidth)(VkCommandBuffer commandBuffer, float lineWidth); -typedef void (VKAPI_PTR *PFN_vkCmdSetDepthBias)(VkCommandBuffer commandBuffer, float depthBiasConstantFactor, float depthBiasClamp, float depthBiasSlopeFactor); -typedef void (VKAPI_PTR *PFN_vkCmdSetBlendConstants)(VkCommandBuffer commandBuffer, const float blendConstants[4]); -typedef void (VKAPI_PTR *PFN_vkCmdSetDepthBounds)(VkCommandBuffer commandBuffer, float minDepthBounds, float maxDepthBounds); -typedef void (VKAPI_PTR *PFN_vkCmdSetStencilCompareMask)(VkCommandBuffer commandBuffer, VkStencilFaceFlags faceMask, uint32_t compareMask); -typedef void (VKAPI_PTR *PFN_vkCmdSetStencilWriteMask)(VkCommandBuffer commandBuffer, VkStencilFaceFlags faceMask, uint32_t writeMask); -typedef void (VKAPI_PTR *PFN_vkCmdSetStencilReference)(VkCommandBuffer commandBuffer, VkStencilFaceFlags faceMask, uint32_t reference); -typedef void (VKAPI_PTR *PFN_vkCmdBindDescriptorSets)(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint, VkPipelineLayout layout, uint32_t firstSet, uint32_t descriptorSetCount, const VkDescriptorSet* pDescriptorSets, uint32_t dynamicOffsetCount, const uint32_t* pDynamicOffsets); -typedef void (VKAPI_PTR *PFN_vkCmdBindIndexBuffer)(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkIndexType indexType); -typedef void (VKAPI_PTR *PFN_vkCmdBindVertexBuffers)(VkCommandBuffer commandBuffer, uint32_t firstBinding, uint32_t bindingCount, const VkBuffer* pBuffers, const VkDeviceSize* pOffsets); -typedef void (VKAPI_PTR *PFN_vkCmdDraw)(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount, uint32_t firstVertex, uint32_t firstInstance); -typedef void (VKAPI_PTR *PFN_vkCmdDrawIndexed)(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount, uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance); -typedef void (VKAPI_PTR *PFN_vkCmdDrawIndirect)(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, uint32_t drawCount, uint32_t stride); -typedef void (VKAPI_PTR *PFN_vkCmdDrawIndexedIndirect)(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, uint32_t drawCount, uint32_t stride); -typedef void (VKAPI_PTR *PFN_vkCmdDispatch)(VkCommandBuffer commandBuffer, uint32_t groupCountX, uint32_t groupCountY, uint32_t groupCountZ); -typedef void (VKAPI_PTR *PFN_vkCmdDispatchIndirect)(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset); -typedef void (VKAPI_PTR *PFN_vkCmdCopyBuffer)(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer, uint32_t regionCount, const VkBufferCopy* pRegions); -typedef void (VKAPI_PTR *PFN_vkCmdCopyImage)(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout, VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount, const VkImageCopy* pRegions); -typedef void (VKAPI_PTR *PFN_vkCmdBlitImage)(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout, VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount, const VkImageBlit* pRegions, VkFilter filter); -typedef void (VKAPI_PTR *PFN_vkCmdCopyBufferToImage)(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount, const VkBufferImageCopy* pRegions); -typedef void (VKAPI_PTR *PFN_vkCmdCopyImageToBuffer)(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout, VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy* pRegions); -typedef void (VKAPI_PTR *PFN_vkCmdUpdateBuffer)(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset, VkDeviceSize dataSize, const void* pData); -typedef void (VKAPI_PTR *PFN_vkCmdFillBuffer)(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset, VkDeviceSize size, uint32_t data); -typedef void (VKAPI_PTR *PFN_vkCmdClearColorImage)(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout, const VkClearColorValue* pColor, uint32_t rangeCount, const VkImageSubresourceRange* pRanges); -typedef void (VKAPI_PTR *PFN_vkCmdClearDepthStencilImage)(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout, const VkClearDepthStencilValue* pDepthStencil, uint32_t rangeCount, const VkImageSubresourceRange* pRanges); -typedef void (VKAPI_PTR *PFN_vkCmdClearAttachments)(VkCommandBuffer commandBuffer, uint32_t attachmentCount, const VkClearAttachment* pAttachments, uint32_t rectCount, const VkClearRect* pRects); -typedef void (VKAPI_PTR *PFN_vkCmdResolveImage)(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout, VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount, const VkImageResolve* pRegions); -typedef void (VKAPI_PTR *PFN_vkCmdSetEvent)(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask); -typedef void (VKAPI_PTR *PFN_vkCmdResetEvent)(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask); -typedef void (VKAPI_PTR *PFN_vkCmdWaitEvents)(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent* pEvents, VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask, uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers, uint32_t bufferMemoryBarrierCount, const VkBufferMemoryBarrier* pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount, const VkImageMemoryBarrier* pImageMemoryBarriers); -typedef void (VKAPI_PTR *PFN_vkCmdPipelineBarrier)(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount, const VkMemoryBarrier* pMemoryBarriers, uint32_t bufferMemoryBarrierCount, const VkBufferMemoryBarrier* pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount, const VkImageMemoryBarrier* pImageMemoryBarriers); -typedef void (VKAPI_PTR *PFN_vkCmdBeginQuery)(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t query, VkQueryControlFlags flags); -typedef void (VKAPI_PTR *PFN_vkCmdEndQuery)(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t query); -typedef void (VKAPI_PTR *PFN_vkCmdResetQueryPool)(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t firstQuery, uint32_t queryCount); -typedef void (VKAPI_PTR *PFN_vkCmdWriteTimestamp)(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage, VkQueryPool queryPool, uint32_t query); -typedef void (VKAPI_PTR *PFN_vkCmdCopyQueryPoolResults)(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t firstQuery, uint32_t queryCount, VkBuffer dstBuffer, VkDeviceSize dstOffset, VkDeviceSize stride, VkQueryResultFlags flags); -typedef void (VKAPI_PTR *PFN_vkCmdPushConstants)(VkCommandBuffer commandBuffer, VkPipelineLayout layout, VkShaderStageFlags stageFlags, uint32_t offset, uint32_t size, const void* pValues); -typedef void (VKAPI_PTR *PFN_vkCmdBeginRenderPass)(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo* pRenderPassBegin, VkSubpassContents contents); -typedef void (VKAPI_PTR *PFN_vkCmdNextSubpass)(VkCommandBuffer commandBuffer, VkSubpassContents contents); -typedef void (VKAPI_PTR *PFN_vkCmdEndRenderPass)(VkCommandBuffer commandBuffer); -typedef void (VKAPI_PTR *PFN_vkCmdExecuteCommands)(VkCommandBuffer commandBuffer, uint32_t commandBufferCount, const VkCommandBuffer* pCommandBuffers); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR VkResult VKAPI_CALL vkCreateInstance( - const VkInstanceCreateInfo* pCreateInfo, - const VkAllocationCallbacks* pAllocator, - VkInstance* pInstance); - -VKAPI_ATTR void VKAPI_CALL vkDestroyInstance( - VkInstance instance, - const VkAllocationCallbacks* pAllocator); - -VKAPI_ATTR VkResult VKAPI_CALL vkEnumeratePhysicalDevices( - VkInstance instance, - uint32_t* pPhysicalDeviceCount, - VkPhysicalDevice* pPhysicalDevices); - -VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceFeatures( - VkPhysicalDevice physicalDevice, - VkPhysicalDeviceFeatures* pFeatures); - -VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceFormatProperties( - VkPhysicalDevice physicalDevice, - VkFormat format, - VkFormatProperties* pFormatProperties); - -VKAPI_ATTR VkResult VKAPI_CALL vkGetPhysicalDeviceImageFormatProperties( - VkPhysicalDevice physicalDevice, - VkFormat format, - VkImageType type, - VkImageTiling tiling, - VkImageUsageFlags usage, - VkImageCreateFlags flags, - VkImageFormatProperties* pImageFormatProperties); - -VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceProperties( - VkPhysicalDevice physicalDevice, - VkPhysicalDeviceProperties* pProperties); - -VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceQueueFamilyProperties( - VkPhysicalDevice physicalDevice, - uint32_t* pQueueFamilyPropertyCount, - VkQueueFamilyProperties* pQueueFamilyProperties); - -VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceMemoryProperties( - VkPhysicalDevice physicalDevice, - VkPhysicalDeviceMemoryProperties* pMemoryProperties); - -VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vkGetInstanceProcAddr( - VkInstance instance, - const char* pName); - -VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vkGetDeviceProcAddr( - VkDevice device, - const char* pName); - -VKAPI_ATTR VkResult VKAPI_CALL vkCreateDevice( - VkPhysicalDevice physicalDevice, - const VkDeviceCreateInfo* pCreateInfo, - const VkAllocationCallbacks* pAllocator, - VkDevice* pDevice); - -VKAPI_ATTR void VKAPI_CALL vkDestroyDevice( - VkDevice device, - const VkAllocationCallbacks* pAllocator); - -VKAPI_ATTR VkResult VKAPI_CALL vkEnumerateInstanceExtensionProperties( - const char* pLayerName, - uint32_t* pPropertyCount, - VkExtensionProperties* pProperties); - -VKAPI_ATTR VkResult VKAPI_CALL vkEnumerateDeviceExtensionProperties( - VkPhysicalDevice physicalDevice, - const char* pLayerName, - uint32_t* pPropertyCount, - VkExtensionProperties* pProperties); - -VKAPI_ATTR VkResult VKAPI_CALL vkEnumerateInstanceLayerProperties( - uint32_t* pPropertyCount, - VkLayerProperties* pProperties); - -VKAPI_ATTR VkResult VKAPI_CALL vkEnumerateDeviceLayerProperties( - VkPhysicalDevice physicalDevice, - uint32_t* pPropertyCount, - VkLayerProperties* pProperties); - -VKAPI_ATTR void VKAPI_CALL vkGetDeviceQueue( - VkDevice device, - uint32_t queueFamilyIndex, - uint32_t queueIndex, - VkQueue* pQueue); - -VKAPI_ATTR VkResult VKAPI_CALL vkQueueSubmit( - VkQueue queue, - uint32_t submitCount, - const VkSubmitInfo* pSubmits, - VkFence fence); - -VKAPI_ATTR VkResult VKAPI_CALL vkQueueWaitIdle( - VkQueue queue); - -VKAPI_ATTR VkResult VKAPI_CALL vkDeviceWaitIdle( - VkDevice device); - -VKAPI_ATTR VkResult VKAPI_CALL vkAllocateMemory( - VkDevice device, - const VkMemoryAllocateInfo* pAllocateInfo, - const VkAllocationCallbacks* pAllocator, - VkDeviceMemory* pMemory); - -VKAPI_ATTR void VKAPI_CALL vkFreeMemory( - VkDevice device, - VkDeviceMemory memory, - const VkAllocationCallbacks* pAllocator); - -VKAPI_ATTR VkResult VKAPI_CALL vkMapMemory( - VkDevice device, - VkDeviceMemory memory, - VkDeviceSize offset, - VkDeviceSize size, - VkMemoryMapFlags flags, - void** ppData); - -VKAPI_ATTR void VKAPI_CALL vkUnmapMemory( - VkDevice device, - VkDeviceMemory memory); - -VKAPI_ATTR VkResult VKAPI_CALL vkFlushMappedMemoryRanges( - VkDevice device, - uint32_t memoryRangeCount, - const VkMappedMemoryRange* pMemoryRanges); - -VKAPI_ATTR VkResult VKAPI_CALL vkInvalidateMappedMemoryRanges( - VkDevice device, - uint32_t memoryRangeCount, - const VkMappedMemoryRange* pMemoryRanges); - -VKAPI_ATTR void VKAPI_CALL vkGetDeviceMemoryCommitment( - VkDevice device, - VkDeviceMemory memory, - VkDeviceSize* pCommittedMemoryInBytes); - -VKAPI_ATTR VkResult VKAPI_CALL vkBindBufferMemory( - VkDevice device, - VkBuffer buffer, - VkDeviceMemory memory, - VkDeviceSize memoryOffset); - -VKAPI_ATTR VkResult VKAPI_CALL vkBindImageMemory( - VkDevice device, - VkImage image, - VkDeviceMemory memory, - VkDeviceSize memoryOffset); - -VKAPI_ATTR void VKAPI_CALL vkGetBufferMemoryRequirements( - VkDevice device, - VkBuffer buffer, - VkMemoryRequirements* pMemoryRequirements); - -VKAPI_ATTR void VKAPI_CALL vkGetImageMemoryRequirements( - VkDevice device, - VkImage image, - VkMemoryRequirements* pMemoryRequirements); - -VKAPI_ATTR void VKAPI_CALL vkGetImageSparseMemoryRequirements( - VkDevice device, - VkImage image, - uint32_t* pSparseMemoryRequirementCount, - VkSparseImageMemoryRequirements* pSparseMemoryRequirements); - -VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceSparseImageFormatProperties( - VkPhysicalDevice physicalDevice, - VkFormat format, - VkImageType type, - VkSampleCountFlagBits samples, - VkImageUsageFlags usage, - VkImageTiling tiling, - uint32_t* pPropertyCount, - VkSparseImageFormatProperties* pProperties); - -VKAPI_ATTR VkResult VKAPI_CALL vkQueueBindSparse( - VkQueue queue, - uint32_t bindInfoCount, - const VkBindSparseInfo* pBindInfo, - VkFence fence); - -VKAPI_ATTR VkResult VKAPI_CALL vkCreateFence( - VkDevice device, - const VkFenceCreateInfo* pCreateInfo, - const VkAllocationCallbacks* pAllocator, - VkFence* pFence); - -VKAPI_ATTR void VKAPI_CALL vkDestroyFence( - VkDevice device, - VkFence fence, - const VkAllocationCallbacks* pAllocator); - -VKAPI_ATTR VkResult VKAPI_CALL vkResetFences( - VkDevice device, - uint32_t fenceCount, - const VkFence* pFences); - -VKAPI_ATTR VkResult VKAPI_CALL vkGetFenceStatus( - VkDevice device, - VkFence fence); - -VKAPI_ATTR VkResult VKAPI_CALL vkWaitForFences( - VkDevice device, - uint32_t fenceCount, - const VkFence* pFences, - VkBool32 waitAll, - uint64_t timeout); - -VKAPI_ATTR VkResult VKAPI_CALL vkCreateSemaphore( - VkDevice device, - const VkSemaphoreCreateInfo* pCreateInfo, - const VkAllocationCallbacks* pAllocator, - VkSemaphore* pSemaphore); - -VKAPI_ATTR void VKAPI_CALL vkDestroySemaphore( - VkDevice device, - VkSemaphore semaphore, - const VkAllocationCallbacks* pAllocator); - -VKAPI_ATTR VkResult VKAPI_CALL vkCreateEvent( - VkDevice device, - const VkEventCreateInfo* pCreateInfo, - const VkAllocationCallbacks* pAllocator, - VkEvent* pEvent); - -VKAPI_ATTR void VKAPI_CALL vkDestroyEvent( - VkDevice device, - VkEvent event, - const VkAllocationCallbacks* pAllocator); - -VKAPI_ATTR VkResult VKAPI_CALL vkGetEventStatus( - VkDevice device, - VkEvent event); - -VKAPI_ATTR VkResult VKAPI_CALL vkSetEvent( - VkDevice device, - VkEvent event); - -VKAPI_ATTR VkResult VKAPI_CALL vkResetEvent( - VkDevice device, - VkEvent event); - -VKAPI_ATTR VkResult VKAPI_CALL vkCreateQueryPool( - VkDevice device, - const VkQueryPoolCreateInfo* pCreateInfo, - const VkAllocationCallbacks* pAllocator, - VkQueryPool* pQueryPool); - -VKAPI_ATTR void VKAPI_CALL vkDestroyQueryPool( - VkDevice device, - VkQueryPool queryPool, - const VkAllocationCallbacks* pAllocator); - -VKAPI_ATTR VkResult VKAPI_CALL vkGetQueryPoolResults( - VkDevice device, - VkQueryPool queryPool, - uint32_t firstQuery, - uint32_t queryCount, - size_t dataSize, - void* pData, - VkDeviceSize stride, - VkQueryResultFlags flags); - -VKAPI_ATTR VkResult VKAPI_CALL vkCreateBuffer( - VkDevice device, - const VkBufferCreateInfo* pCreateInfo, - const VkAllocationCallbacks* pAllocator, - VkBuffer* pBuffer); - -VKAPI_ATTR void VKAPI_CALL vkDestroyBuffer( - VkDevice device, - VkBuffer buffer, - const VkAllocationCallbacks* pAllocator); - -VKAPI_ATTR VkResult VKAPI_CALL vkCreateBufferView( - VkDevice device, - const VkBufferViewCreateInfo* pCreateInfo, - const VkAllocationCallbacks* pAllocator, - VkBufferView* pView); - -VKAPI_ATTR void VKAPI_CALL vkDestroyBufferView( - VkDevice device, - VkBufferView bufferView, - const VkAllocationCallbacks* pAllocator); - -VKAPI_ATTR VkResult VKAPI_CALL vkCreateImage( - VkDevice device, - const VkImageCreateInfo* pCreateInfo, - const VkAllocationCallbacks* pAllocator, - VkImage* pImage); - -VKAPI_ATTR void VKAPI_CALL vkDestroyImage( - VkDevice device, - VkImage image, - const VkAllocationCallbacks* pAllocator); - -VKAPI_ATTR void VKAPI_CALL vkGetImageSubresourceLayout( - VkDevice device, - VkImage image, - const VkImageSubresource* pSubresource, - VkSubresourceLayout* pLayout); - -VKAPI_ATTR VkResult VKAPI_CALL vkCreateImageView( - VkDevice device, - const VkImageViewCreateInfo* pCreateInfo, - const VkAllocationCallbacks* pAllocator, - VkImageView* pView); - -VKAPI_ATTR void VKAPI_CALL vkDestroyImageView( - VkDevice device, - VkImageView imageView, - const VkAllocationCallbacks* pAllocator); - -VKAPI_ATTR VkResult VKAPI_CALL vkCreateShaderModule( - VkDevice device, - const VkShaderModuleCreateInfo* pCreateInfo, - const VkAllocationCallbacks* pAllocator, - VkShaderModule* pShaderModule); - -VKAPI_ATTR void VKAPI_CALL vkDestroyShaderModule( - VkDevice device, - VkShaderModule shaderModule, - const VkAllocationCallbacks* pAllocator); - -VKAPI_ATTR VkResult VKAPI_CALL vkCreatePipelineCache( - VkDevice device, - const VkPipelineCacheCreateInfo* pCreateInfo, - const VkAllocationCallbacks* pAllocator, - VkPipelineCache* pPipelineCache); - -VKAPI_ATTR void VKAPI_CALL vkDestroyPipelineCache( - VkDevice device, - VkPipelineCache pipelineCache, - const VkAllocationCallbacks* pAllocator); - -VKAPI_ATTR VkResult VKAPI_CALL vkGetPipelineCacheData( - VkDevice device, - VkPipelineCache pipelineCache, - size_t* pDataSize, - void* pData); - -VKAPI_ATTR VkResult VKAPI_CALL vkMergePipelineCaches( - VkDevice device, - VkPipelineCache dstCache, - uint32_t srcCacheCount, - const VkPipelineCache* pSrcCaches); - -VKAPI_ATTR VkResult VKAPI_CALL vkCreateGraphicsPipelines( - VkDevice device, - VkPipelineCache pipelineCache, - uint32_t createInfoCount, - const VkGraphicsPipelineCreateInfo* pCreateInfos, - const VkAllocationCallbacks* pAllocator, - VkPipeline* pPipelines); - -VKAPI_ATTR VkResult VKAPI_CALL vkCreateComputePipelines( - VkDevice device, - VkPipelineCache pipelineCache, - uint32_t createInfoCount, - const VkComputePipelineCreateInfo* pCreateInfos, - const VkAllocationCallbacks* pAllocator, - VkPipeline* pPipelines); - -VKAPI_ATTR void VKAPI_CALL vkDestroyPipeline( - VkDevice device, - VkPipeline pipeline, - const VkAllocationCallbacks* pAllocator); - -VKAPI_ATTR VkResult VKAPI_CALL vkCreatePipelineLayout( - VkDevice device, - const VkPipelineLayoutCreateInfo* pCreateInfo, - const VkAllocationCallbacks* pAllocator, - VkPipelineLayout* pPipelineLayout); - -VKAPI_ATTR void VKAPI_CALL vkDestroyPipelineLayout( - VkDevice device, - VkPipelineLayout pipelineLayout, - const VkAllocationCallbacks* pAllocator); - -VKAPI_ATTR VkResult VKAPI_CALL vkCreateSampler( - VkDevice device, - const VkSamplerCreateInfo* pCreateInfo, - const VkAllocationCallbacks* pAllocator, - VkSampler* pSampler); - -VKAPI_ATTR void VKAPI_CALL vkDestroySampler( - VkDevice device, - VkSampler sampler, - const VkAllocationCallbacks* pAllocator); - -VKAPI_ATTR VkResult VKAPI_CALL vkCreateDescriptorSetLayout( - VkDevice device, - const VkDescriptorSetLayoutCreateInfo* pCreateInfo, - const VkAllocationCallbacks* pAllocator, - VkDescriptorSetLayout* pSetLayout); - -VKAPI_ATTR void VKAPI_CALL vkDestroyDescriptorSetLayout( - VkDevice device, - VkDescriptorSetLayout descriptorSetLayout, - const VkAllocationCallbacks* pAllocator); - -VKAPI_ATTR VkResult VKAPI_CALL vkCreateDescriptorPool( - VkDevice device, - const VkDescriptorPoolCreateInfo* pCreateInfo, - const VkAllocationCallbacks* pAllocator, - VkDescriptorPool* pDescriptorPool); - -VKAPI_ATTR void VKAPI_CALL vkDestroyDescriptorPool( - VkDevice device, - VkDescriptorPool descriptorPool, - const VkAllocationCallbacks* pAllocator); - -VKAPI_ATTR VkResult VKAPI_CALL vkResetDescriptorPool( - VkDevice device, - VkDescriptorPool descriptorPool, - VkDescriptorPoolResetFlags flags); - -VKAPI_ATTR VkResult VKAPI_CALL vkAllocateDescriptorSets( - VkDevice device, - const VkDescriptorSetAllocateInfo* pAllocateInfo, - VkDescriptorSet* pDescriptorSets); - -VKAPI_ATTR VkResult VKAPI_CALL vkFreeDescriptorSets( - VkDevice device, - VkDescriptorPool descriptorPool, - uint32_t descriptorSetCount, - const VkDescriptorSet* pDescriptorSets); - -VKAPI_ATTR void VKAPI_CALL vkUpdateDescriptorSets( - VkDevice device, - uint32_t descriptorWriteCount, - const VkWriteDescriptorSet* pDescriptorWrites, - uint32_t descriptorCopyCount, - const VkCopyDescriptorSet* pDescriptorCopies); - -VKAPI_ATTR VkResult VKAPI_CALL vkCreateFramebuffer( - VkDevice device, - const VkFramebufferCreateInfo* pCreateInfo, - const VkAllocationCallbacks* pAllocator, - VkFramebuffer* pFramebuffer); - -VKAPI_ATTR void VKAPI_CALL vkDestroyFramebuffer( - VkDevice device, - VkFramebuffer framebuffer, - const VkAllocationCallbacks* pAllocator); - -VKAPI_ATTR VkResult VKAPI_CALL vkCreateRenderPass( - VkDevice device, - const VkRenderPassCreateInfo* pCreateInfo, - const VkAllocationCallbacks* pAllocator, - VkRenderPass* pRenderPass); - -VKAPI_ATTR void VKAPI_CALL vkDestroyRenderPass( - VkDevice device, - VkRenderPass renderPass, - const VkAllocationCallbacks* pAllocator); - -VKAPI_ATTR void VKAPI_CALL vkGetRenderAreaGranularity( - VkDevice device, - VkRenderPass renderPass, - VkExtent2D* pGranularity); - -VKAPI_ATTR VkResult VKAPI_CALL vkCreateCommandPool( - VkDevice device, - const VkCommandPoolCreateInfo* pCreateInfo, - const VkAllocationCallbacks* pAllocator, - VkCommandPool* pCommandPool); - -VKAPI_ATTR void VKAPI_CALL vkDestroyCommandPool( - VkDevice device, - VkCommandPool commandPool, - const VkAllocationCallbacks* pAllocator); - -VKAPI_ATTR VkResult VKAPI_CALL vkResetCommandPool( - VkDevice device, - VkCommandPool commandPool, - VkCommandPoolResetFlags flags); - -VKAPI_ATTR VkResult VKAPI_CALL vkAllocateCommandBuffers( - VkDevice device, - const VkCommandBufferAllocateInfo* pAllocateInfo, - VkCommandBuffer* pCommandBuffers); - -VKAPI_ATTR void VKAPI_CALL vkFreeCommandBuffers( - VkDevice device, - VkCommandPool commandPool, - uint32_t commandBufferCount, - const VkCommandBuffer* pCommandBuffers); - -VKAPI_ATTR VkResult VKAPI_CALL vkBeginCommandBuffer( - VkCommandBuffer commandBuffer, - const VkCommandBufferBeginInfo* pBeginInfo); - -VKAPI_ATTR VkResult VKAPI_CALL vkEndCommandBuffer( - VkCommandBuffer commandBuffer); - -VKAPI_ATTR VkResult VKAPI_CALL vkResetCommandBuffer( - VkCommandBuffer commandBuffer, - VkCommandBufferResetFlags flags); - -VKAPI_ATTR void VKAPI_CALL vkCmdBindPipeline( - VkCommandBuffer commandBuffer, - VkPipelineBindPoint pipelineBindPoint, - VkPipeline pipeline); - -VKAPI_ATTR void VKAPI_CALL vkCmdSetViewport( - VkCommandBuffer commandBuffer, - uint32_t firstViewport, - uint32_t viewportCount, - const VkViewport* pViewports); - -VKAPI_ATTR void VKAPI_CALL vkCmdSetScissor( - VkCommandBuffer commandBuffer, - uint32_t firstScissor, - uint32_t scissorCount, - const VkRect2D* pScissors); - -VKAPI_ATTR void VKAPI_CALL vkCmdSetLineWidth( - VkCommandBuffer commandBuffer, - float lineWidth); - -VKAPI_ATTR void VKAPI_CALL vkCmdSetDepthBias( - VkCommandBuffer commandBuffer, - float depthBiasConstantFactor, - float depthBiasClamp, - float depthBiasSlopeFactor); - -VKAPI_ATTR void VKAPI_CALL vkCmdSetBlendConstants( - VkCommandBuffer commandBuffer, - const float blendConstants[4]); - -VKAPI_ATTR void VKAPI_CALL vkCmdSetDepthBounds( - VkCommandBuffer commandBuffer, - float minDepthBounds, - float maxDepthBounds); - -VKAPI_ATTR void VKAPI_CALL vkCmdSetStencilCompareMask( - VkCommandBuffer commandBuffer, - VkStencilFaceFlags faceMask, - uint32_t compareMask); - -VKAPI_ATTR void VKAPI_CALL vkCmdSetStencilWriteMask( - VkCommandBuffer commandBuffer, - VkStencilFaceFlags faceMask, - uint32_t writeMask); - -VKAPI_ATTR void VKAPI_CALL vkCmdSetStencilReference( - VkCommandBuffer commandBuffer, - VkStencilFaceFlags faceMask, - uint32_t reference); - -VKAPI_ATTR void VKAPI_CALL vkCmdBindDescriptorSets( - VkCommandBuffer commandBuffer, - VkPipelineBindPoint pipelineBindPoint, - VkPipelineLayout layout, - uint32_t firstSet, - uint32_t descriptorSetCount, - const VkDescriptorSet* pDescriptorSets, - uint32_t dynamicOffsetCount, - const uint32_t* pDynamicOffsets); - -VKAPI_ATTR void VKAPI_CALL vkCmdBindIndexBuffer( - VkCommandBuffer commandBuffer, - VkBuffer buffer, - VkDeviceSize offset, - VkIndexType indexType); - -VKAPI_ATTR void VKAPI_CALL vkCmdBindVertexBuffers( - VkCommandBuffer commandBuffer, - uint32_t firstBinding, - uint32_t bindingCount, - const VkBuffer* pBuffers, - const VkDeviceSize* pOffsets); - -VKAPI_ATTR void VKAPI_CALL vkCmdDraw( - VkCommandBuffer commandBuffer, - uint32_t vertexCount, - uint32_t instanceCount, - uint32_t firstVertex, - uint32_t firstInstance); - -VKAPI_ATTR void VKAPI_CALL vkCmdDrawIndexed( - VkCommandBuffer commandBuffer, - uint32_t indexCount, - uint32_t instanceCount, - uint32_t firstIndex, - int32_t vertexOffset, - uint32_t firstInstance); - -VKAPI_ATTR void VKAPI_CALL vkCmdDrawIndirect( - VkCommandBuffer commandBuffer, - VkBuffer buffer, - VkDeviceSize offset, - uint32_t drawCount, - uint32_t stride); - -VKAPI_ATTR void VKAPI_CALL vkCmdDrawIndexedIndirect( - VkCommandBuffer commandBuffer, - VkBuffer buffer, - VkDeviceSize offset, - uint32_t drawCount, - uint32_t stride); - -VKAPI_ATTR void VKAPI_CALL vkCmdDispatch( - VkCommandBuffer commandBuffer, - uint32_t groupCountX, - uint32_t groupCountY, - uint32_t groupCountZ); - -VKAPI_ATTR void VKAPI_CALL vkCmdDispatchIndirect( - VkCommandBuffer commandBuffer, - VkBuffer buffer, - VkDeviceSize offset); - -VKAPI_ATTR void VKAPI_CALL vkCmdCopyBuffer( - VkCommandBuffer commandBuffer, - VkBuffer srcBuffer, - VkBuffer dstBuffer, - uint32_t regionCount, - const VkBufferCopy* pRegions); - -VKAPI_ATTR void VKAPI_CALL vkCmdCopyImage( - VkCommandBuffer commandBuffer, - VkImage srcImage, - VkImageLayout srcImageLayout, - VkImage dstImage, - VkImageLayout dstImageLayout, - uint32_t regionCount, - const VkImageCopy* pRegions); - -VKAPI_ATTR void VKAPI_CALL vkCmdBlitImage( - VkCommandBuffer commandBuffer, - VkImage srcImage, - VkImageLayout srcImageLayout, - VkImage dstImage, - VkImageLayout dstImageLayout, - uint32_t regionCount, - const VkImageBlit* pRegions, - VkFilter filter); - -VKAPI_ATTR void VKAPI_CALL vkCmdCopyBufferToImage( - VkCommandBuffer commandBuffer, - VkBuffer srcBuffer, - VkImage dstImage, - VkImageLayout dstImageLayout, - uint32_t regionCount, - const VkBufferImageCopy* pRegions); - -VKAPI_ATTR void VKAPI_CALL vkCmdCopyImageToBuffer( - VkCommandBuffer commandBuffer, - VkImage srcImage, - VkImageLayout srcImageLayout, - VkBuffer dstBuffer, - uint32_t regionCount, - const VkBufferImageCopy* pRegions); - -VKAPI_ATTR void VKAPI_CALL vkCmdUpdateBuffer( - VkCommandBuffer commandBuffer, - VkBuffer dstBuffer, - VkDeviceSize dstOffset, - VkDeviceSize dataSize, - const void* pData); - -VKAPI_ATTR void VKAPI_CALL vkCmdFillBuffer( - VkCommandBuffer commandBuffer, - VkBuffer dstBuffer, - VkDeviceSize dstOffset, - VkDeviceSize size, - uint32_t data); - -VKAPI_ATTR void VKAPI_CALL vkCmdClearColorImage( - VkCommandBuffer commandBuffer, - VkImage image, - VkImageLayout imageLayout, - const VkClearColorValue* pColor, - uint32_t rangeCount, - const VkImageSubresourceRange* pRanges); - -VKAPI_ATTR void VKAPI_CALL vkCmdClearDepthStencilImage( - VkCommandBuffer commandBuffer, - VkImage image, - VkImageLayout imageLayout, - const VkClearDepthStencilValue* pDepthStencil, - uint32_t rangeCount, - const VkImageSubresourceRange* pRanges); - -VKAPI_ATTR void VKAPI_CALL vkCmdClearAttachments( - VkCommandBuffer commandBuffer, - uint32_t attachmentCount, - const VkClearAttachment* pAttachments, - uint32_t rectCount, - const VkClearRect* pRects); - -VKAPI_ATTR void VKAPI_CALL vkCmdResolveImage( - VkCommandBuffer commandBuffer, - VkImage srcImage, - VkImageLayout srcImageLayout, - VkImage dstImage, - VkImageLayout dstImageLayout, - uint32_t regionCount, - const VkImageResolve* pRegions); - -VKAPI_ATTR void VKAPI_CALL vkCmdSetEvent( - VkCommandBuffer commandBuffer, - VkEvent event, - VkPipelineStageFlags stageMask); - -VKAPI_ATTR void VKAPI_CALL vkCmdResetEvent( - VkCommandBuffer commandBuffer, - VkEvent event, - VkPipelineStageFlags stageMask); - -VKAPI_ATTR void VKAPI_CALL vkCmdWaitEvents( - VkCommandBuffer commandBuffer, - uint32_t eventCount, - const VkEvent* pEvents, - VkPipelineStageFlags srcStageMask, - VkPipelineStageFlags dstStageMask, - uint32_t memoryBarrierCount, - const VkMemoryBarrier* pMemoryBarriers, - uint32_t bufferMemoryBarrierCount, - const VkBufferMemoryBarrier* pBufferMemoryBarriers, - uint32_t imageMemoryBarrierCount, - const VkImageMemoryBarrier* pImageMemoryBarriers); - -VKAPI_ATTR void VKAPI_CALL vkCmdPipelineBarrier( - VkCommandBuffer commandBuffer, - VkPipelineStageFlags srcStageMask, - VkPipelineStageFlags dstStageMask, - VkDependencyFlags dependencyFlags, - uint32_t memoryBarrierCount, - const VkMemoryBarrier* pMemoryBarriers, - uint32_t bufferMemoryBarrierCount, - const VkBufferMemoryBarrier* pBufferMemoryBarriers, - uint32_t imageMemoryBarrierCount, - const VkImageMemoryBarrier* pImageMemoryBarriers); - -VKAPI_ATTR void VKAPI_CALL vkCmdBeginQuery( - VkCommandBuffer commandBuffer, - VkQueryPool queryPool, - uint32_t query, - VkQueryControlFlags flags); - -VKAPI_ATTR void VKAPI_CALL vkCmdEndQuery( - VkCommandBuffer commandBuffer, - VkQueryPool queryPool, - uint32_t query); - -VKAPI_ATTR void VKAPI_CALL vkCmdResetQueryPool( - VkCommandBuffer commandBuffer, - VkQueryPool queryPool, - uint32_t firstQuery, - uint32_t queryCount); - -VKAPI_ATTR void VKAPI_CALL vkCmdWriteTimestamp( - VkCommandBuffer commandBuffer, - VkPipelineStageFlagBits pipelineStage, - VkQueryPool queryPool, - uint32_t query); - -VKAPI_ATTR void VKAPI_CALL vkCmdCopyQueryPoolResults( - VkCommandBuffer commandBuffer, - VkQueryPool queryPool, - uint32_t firstQuery, - uint32_t queryCount, - VkBuffer dstBuffer, - VkDeviceSize dstOffset, - VkDeviceSize stride, - VkQueryResultFlags flags); - -VKAPI_ATTR void VKAPI_CALL vkCmdPushConstants( - VkCommandBuffer commandBuffer, - VkPipelineLayout layout, - VkShaderStageFlags stageFlags, - uint32_t offset, - uint32_t size, - const void* pValues); - -VKAPI_ATTR void VKAPI_CALL vkCmdBeginRenderPass( - VkCommandBuffer commandBuffer, - const VkRenderPassBeginInfo* pRenderPassBegin, - VkSubpassContents contents); - -VKAPI_ATTR void VKAPI_CALL vkCmdNextSubpass( - VkCommandBuffer commandBuffer, - VkSubpassContents contents); - -VKAPI_ATTR void VKAPI_CALL vkCmdEndRenderPass( - VkCommandBuffer commandBuffer); - -VKAPI_ATTR void VKAPI_CALL vkCmdExecuteCommands( - VkCommandBuffer commandBuffer, - uint32_t commandBufferCount, - const VkCommandBuffer* pCommandBuffers); -#endif - -#define VK_VERSION_1_1 1 -// Vulkan 1.1 version number -#define VK_API_VERSION_1_1 VK_MAKE_VERSION(1, 1, 0)// Patch version should always be set to 0 - - -VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkSamplerYcbcrConversion) -VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkDescriptorUpdateTemplate) - -#define VK_MAX_DEVICE_GROUP_SIZE 32 -#define VK_LUID_SIZE 8 -#define VK_QUEUE_FAMILY_EXTERNAL (~0U-1) - - -typedef enum VkPointClippingBehavior { - VK_POINT_CLIPPING_BEHAVIOR_ALL_CLIP_PLANES = 0, - VK_POINT_CLIPPING_BEHAVIOR_USER_CLIP_PLANES_ONLY = 1, - VK_POINT_CLIPPING_BEHAVIOR_ALL_CLIP_PLANES_KHR = VK_POINT_CLIPPING_BEHAVIOR_ALL_CLIP_PLANES, - VK_POINT_CLIPPING_BEHAVIOR_USER_CLIP_PLANES_ONLY_KHR = VK_POINT_CLIPPING_BEHAVIOR_USER_CLIP_PLANES_ONLY, - VK_POINT_CLIPPING_BEHAVIOR_BEGIN_RANGE = VK_POINT_CLIPPING_BEHAVIOR_ALL_CLIP_PLANES, - VK_POINT_CLIPPING_BEHAVIOR_END_RANGE = VK_POINT_CLIPPING_BEHAVIOR_USER_CLIP_PLANES_ONLY, - VK_POINT_CLIPPING_BEHAVIOR_RANGE_SIZE = (VK_POINT_CLIPPING_BEHAVIOR_USER_CLIP_PLANES_ONLY - VK_POINT_CLIPPING_BEHAVIOR_ALL_CLIP_PLANES + 1), - VK_POINT_CLIPPING_BEHAVIOR_MAX_ENUM = 0x7FFFFFFF -} VkPointClippingBehavior; - -typedef enum VkTessellationDomainOrigin { - VK_TESSELLATION_DOMAIN_ORIGIN_UPPER_LEFT = 0, - VK_TESSELLATION_DOMAIN_ORIGIN_LOWER_LEFT = 1, - VK_TESSELLATION_DOMAIN_ORIGIN_UPPER_LEFT_KHR = VK_TESSELLATION_DOMAIN_ORIGIN_UPPER_LEFT, - VK_TESSELLATION_DOMAIN_ORIGIN_LOWER_LEFT_KHR = VK_TESSELLATION_DOMAIN_ORIGIN_LOWER_LEFT, - VK_TESSELLATION_DOMAIN_ORIGIN_BEGIN_RANGE = VK_TESSELLATION_DOMAIN_ORIGIN_UPPER_LEFT, - VK_TESSELLATION_DOMAIN_ORIGIN_END_RANGE = VK_TESSELLATION_DOMAIN_ORIGIN_LOWER_LEFT, - VK_TESSELLATION_DOMAIN_ORIGIN_RANGE_SIZE = (VK_TESSELLATION_DOMAIN_ORIGIN_LOWER_LEFT - VK_TESSELLATION_DOMAIN_ORIGIN_UPPER_LEFT + 1), - VK_TESSELLATION_DOMAIN_ORIGIN_MAX_ENUM = 0x7FFFFFFF -} VkTessellationDomainOrigin; - -typedef enum VkSamplerYcbcrModelConversion { - VK_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY = 0, - VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_IDENTITY = 1, - VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_709 = 2, - VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_601 = 3, - VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_2020 = 4, - VK_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY_KHR = VK_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY, - VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_IDENTITY_KHR = VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_IDENTITY, - VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_709_KHR = VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_709, - VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_601_KHR = VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_601, - VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_2020_KHR = VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_2020, - VK_SAMPLER_YCBCR_MODEL_CONVERSION_BEGIN_RANGE = VK_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY, - VK_SAMPLER_YCBCR_MODEL_CONVERSION_END_RANGE = VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_2020, - VK_SAMPLER_YCBCR_MODEL_CONVERSION_RANGE_SIZE = (VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_2020 - VK_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY + 1), - VK_SAMPLER_YCBCR_MODEL_CONVERSION_MAX_ENUM = 0x7FFFFFFF -} VkSamplerYcbcrModelConversion; - -typedef enum VkSamplerYcbcrRange { - VK_SAMPLER_YCBCR_RANGE_ITU_FULL = 0, - VK_SAMPLER_YCBCR_RANGE_ITU_NARROW = 1, - VK_SAMPLER_YCBCR_RANGE_ITU_FULL_KHR = VK_SAMPLER_YCBCR_RANGE_ITU_FULL, - VK_SAMPLER_YCBCR_RANGE_ITU_NARROW_KHR = VK_SAMPLER_YCBCR_RANGE_ITU_NARROW, - VK_SAMPLER_YCBCR_RANGE_BEGIN_RANGE = VK_SAMPLER_YCBCR_RANGE_ITU_FULL, - VK_SAMPLER_YCBCR_RANGE_END_RANGE = VK_SAMPLER_YCBCR_RANGE_ITU_NARROW, - VK_SAMPLER_YCBCR_RANGE_RANGE_SIZE = (VK_SAMPLER_YCBCR_RANGE_ITU_NARROW - VK_SAMPLER_YCBCR_RANGE_ITU_FULL + 1), - VK_SAMPLER_YCBCR_RANGE_MAX_ENUM = 0x7FFFFFFF -} VkSamplerYcbcrRange; - -typedef enum VkChromaLocation { - VK_CHROMA_LOCATION_COSITED_EVEN = 0, - VK_CHROMA_LOCATION_MIDPOINT = 1, - VK_CHROMA_LOCATION_COSITED_EVEN_KHR = VK_CHROMA_LOCATION_COSITED_EVEN, - VK_CHROMA_LOCATION_MIDPOINT_KHR = VK_CHROMA_LOCATION_MIDPOINT, - VK_CHROMA_LOCATION_BEGIN_RANGE = VK_CHROMA_LOCATION_COSITED_EVEN, - VK_CHROMA_LOCATION_END_RANGE = VK_CHROMA_LOCATION_MIDPOINT, - VK_CHROMA_LOCATION_RANGE_SIZE = (VK_CHROMA_LOCATION_MIDPOINT - VK_CHROMA_LOCATION_COSITED_EVEN + 1), - VK_CHROMA_LOCATION_MAX_ENUM = 0x7FFFFFFF -} VkChromaLocation; - -typedef enum VkDescriptorUpdateTemplateType { - VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_DESCRIPTOR_SET = 0, - VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_PUSH_DESCRIPTORS_KHR = 1, - VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_DESCRIPTOR_SET_KHR = VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_DESCRIPTOR_SET, - VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_BEGIN_RANGE = VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_DESCRIPTOR_SET, - VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_END_RANGE = VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_DESCRIPTOR_SET, - VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_RANGE_SIZE = (VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_DESCRIPTOR_SET - VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_DESCRIPTOR_SET + 1), - VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_MAX_ENUM = 0x7FFFFFFF -} VkDescriptorUpdateTemplateType; - - -typedef enum VkSubgroupFeatureFlagBits { - VK_SUBGROUP_FEATURE_BASIC_BIT = 0x00000001, - VK_SUBGROUP_FEATURE_VOTE_BIT = 0x00000002, - VK_SUBGROUP_FEATURE_ARITHMETIC_BIT = 0x00000004, - VK_SUBGROUP_FEATURE_BALLOT_BIT = 0x00000008, - VK_SUBGROUP_FEATURE_SHUFFLE_BIT = 0x00000010, - VK_SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT = 0x00000020, - VK_SUBGROUP_FEATURE_CLUSTERED_BIT = 0x00000040, - VK_SUBGROUP_FEATURE_QUAD_BIT = 0x00000080, - VK_SUBGROUP_FEATURE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkSubgroupFeatureFlagBits; -typedef VkFlags VkSubgroupFeatureFlags; - -typedef enum VkPeerMemoryFeatureFlagBits { - VK_PEER_MEMORY_FEATURE_COPY_SRC_BIT = 0x00000001, - VK_PEER_MEMORY_FEATURE_COPY_DST_BIT = 0x00000002, - VK_PEER_MEMORY_FEATURE_GENERIC_SRC_BIT = 0x00000004, - VK_PEER_MEMORY_FEATURE_GENERIC_DST_BIT = 0x00000008, - VK_PEER_MEMORY_FEATURE_COPY_SRC_BIT_KHR = VK_PEER_MEMORY_FEATURE_COPY_SRC_BIT, - VK_PEER_MEMORY_FEATURE_COPY_DST_BIT_KHR = VK_PEER_MEMORY_FEATURE_COPY_DST_BIT, - VK_PEER_MEMORY_FEATURE_GENERIC_SRC_BIT_KHR = VK_PEER_MEMORY_FEATURE_GENERIC_SRC_BIT, - VK_PEER_MEMORY_FEATURE_GENERIC_DST_BIT_KHR = VK_PEER_MEMORY_FEATURE_GENERIC_DST_BIT, - VK_PEER_MEMORY_FEATURE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkPeerMemoryFeatureFlagBits; -typedef VkFlags VkPeerMemoryFeatureFlags; - -typedef enum VkMemoryAllocateFlagBits { - VK_MEMORY_ALLOCATE_DEVICE_MASK_BIT = 0x00000001, - VK_MEMORY_ALLOCATE_DEVICE_MASK_BIT_KHR = VK_MEMORY_ALLOCATE_DEVICE_MASK_BIT, - VK_MEMORY_ALLOCATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkMemoryAllocateFlagBits; -typedef VkFlags VkMemoryAllocateFlags; -typedef VkFlags VkCommandPoolTrimFlags; -typedef VkFlags VkDescriptorUpdateTemplateCreateFlags; - -typedef enum VkExternalMemoryHandleTypeFlagBits { - VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT = 0x00000001, - VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_BIT = 0x00000002, - VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT = 0x00000004, - VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_BIT = 0x00000008, - VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_KMT_BIT = 0x00000010, - VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_HEAP_BIT = 0x00000020, - VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_RESOURCE_BIT = 0x00000040, - VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT = 0x00000200, - VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT = 0x00000080, - VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_MAPPED_FOREIGN_MEMORY_BIT_EXT = 0x00000100, - VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT, - VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_BIT_KHR = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_BIT, - VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT_KHR = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT, - VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_BIT_KHR = VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_BIT, - VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_KMT_BIT_KHR = VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_KMT_BIT, - VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_HEAP_BIT_KHR = VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_HEAP_BIT, - VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_RESOURCE_BIT_KHR = VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_RESOURCE_BIT, - VK_EXTERNAL_MEMORY_HANDLE_TYPE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkExternalMemoryHandleTypeFlagBits; -typedef VkFlags VkExternalMemoryHandleTypeFlags; - -typedef enum VkExternalMemoryFeatureFlagBits { - VK_EXTERNAL_MEMORY_FEATURE_DEDICATED_ONLY_BIT = 0x00000001, - VK_EXTERNAL_MEMORY_FEATURE_EXPORTABLE_BIT = 0x00000002, - VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT = 0x00000004, - VK_EXTERNAL_MEMORY_FEATURE_DEDICATED_ONLY_BIT_KHR = VK_EXTERNAL_MEMORY_FEATURE_DEDICATED_ONLY_BIT, - VK_EXTERNAL_MEMORY_FEATURE_EXPORTABLE_BIT_KHR = VK_EXTERNAL_MEMORY_FEATURE_EXPORTABLE_BIT, - VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT_KHR = VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT, - VK_EXTERNAL_MEMORY_FEATURE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkExternalMemoryFeatureFlagBits; -typedef VkFlags VkExternalMemoryFeatureFlags; - -typedef enum VkExternalFenceHandleTypeFlagBits { - VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT = 0x00000001, - VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_WIN32_BIT = 0x00000002, - VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT = 0x00000004, - VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT = 0x00000008, - VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT_KHR = VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT, - VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_WIN32_BIT_KHR = VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_WIN32_BIT, - VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT_KHR = VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT, - VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT_KHR = VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT, - VK_EXTERNAL_FENCE_HANDLE_TYPE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkExternalFenceHandleTypeFlagBits; -typedef VkFlags VkExternalFenceHandleTypeFlags; - -typedef enum VkExternalFenceFeatureFlagBits { - VK_EXTERNAL_FENCE_FEATURE_EXPORTABLE_BIT = 0x00000001, - VK_EXTERNAL_FENCE_FEATURE_IMPORTABLE_BIT = 0x00000002, - VK_EXTERNAL_FENCE_FEATURE_EXPORTABLE_BIT_KHR = VK_EXTERNAL_FENCE_FEATURE_EXPORTABLE_BIT, - VK_EXTERNAL_FENCE_FEATURE_IMPORTABLE_BIT_KHR = VK_EXTERNAL_FENCE_FEATURE_IMPORTABLE_BIT, - VK_EXTERNAL_FENCE_FEATURE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkExternalFenceFeatureFlagBits; -typedef VkFlags VkExternalFenceFeatureFlags; - -typedef enum VkFenceImportFlagBits { - VK_FENCE_IMPORT_TEMPORARY_BIT = 0x00000001, - VK_FENCE_IMPORT_TEMPORARY_BIT_KHR = VK_FENCE_IMPORT_TEMPORARY_BIT, - VK_FENCE_IMPORT_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkFenceImportFlagBits; -typedef VkFlags VkFenceImportFlags; - -typedef enum VkSemaphoreImportFlagBits { - VK_SEMAPHORE_IMPORT_TEMPORARY_BIT = 0x00000001, - VK_SEMAPHORE_IMPORT_TEMPORARY_BIT_KHR = VK_SEMAPHORE_IMPORT_TEMPORARY_BIT, - VK_SEMAPHORE_IMPORT_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkSemaphoreImportFlagBits; -typedef VkFlags VkSemaphoreImportFlags; - -typedef enum VkExternalSemaphoreHandleTypeFlagBits { - VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT = 0x00000001, - VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_BIT = 0x00000002, - VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT = 0x00000004, - VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE_BIT = 0x00000008, - VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT = 0x00000010, - VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT_KHR = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT, - VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_BIT_KHR = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_BIT, - VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT_KHR = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT, - VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE_BIT_KHR = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE_BIT, - VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT_KHR = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT, - VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkExternalSemaphoreHandleTypeFlagBits; -typedef VkFlags VkExternalSemaphoreHandleTypeFlags; - -typedef enum VkExternalSemaphoreFeatureFlagBits { - VK_EXTERNAL_SEMAPHORE_FEATURE_EXPORTABLE_BIT = 0x00000001, - VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT = 0x00000002, - VK_EXTERNAL_SEMAPHORE_FEATURE_EXPORTABLE_BIT_KHR = VK_EXTERNAL_SEMAPHORE_FEATURE_EXPORTABLE_BIT, - VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT_KHR = VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT, - VK_EXTERNAL_SEMAPHORE_FEATURE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VkExternalSemaphoreFeatureFlagBits; -typedef VkFlags VkExternalSemaphoreFeatureFlags; - -typedef struct VkPhysicalDeviceSubgroupProperties { - VkStructureType sType; - void* pNext; - uint32_t subgroupSize; - VkShaderStageFlags supportedStages; - VkSubgroupFeatureFlags supportedOperations; - VkBool32 quadOperationsInAllStages; -} VkPhysicalDeviceSubgroupProperties; - -typedef struct VkBindBufferMemoryInfo { - VkStructureType sType; - const void* pNext; - VkBuffer buffer; - VkDeviceMemory memory; - VkDeviceSize memoryOffset; -} VkBindBufferMemoryInfo; - -typedef struct VkBindImageMemoryInfo { - VkStructureType sType; - const void* pNext; - VkImage image; - VkDeviceMemory memory; - VkDeviceSize memoryOffset; -} VkBindImageMemoryInfo; - -typedef struct VkPhysicalDevice16BitStorageFeatures { - VkStructureType sType; - void* pNext; - VkBool32 storageBuffer16BitAccess; - VkBool32 uniformAndStorageBuffer16BitAccess; - VkBool32 storagePushConstant16; - VkBool32 storageInputOutput16; -} VkPhysicalDevice16BitStorageFeatures; - -typedef struct VkMemoryDedicatedRequirements { - VkStructureType sType; - void* pNext; - VkBool32 prefersDedicatedAllocation; - VkBool32 requiresDedicatedAllocation; -} VkMemoryDedicatedRequirements; - -typedef struct VkMemoryDedicatedAllocateInfo { - VkStructureType sType; - const void* pNext; - VkImage image; - VkBuffer buffer; -} VkMemoryDedicatedAllocateInfo; - -typedef struct VkMemoryAllocateFlagsInfo { - VkStructureType sType; - const void* pNext; - VkMemoryAllocateFlags flags; - uint32_t deviceMask; -} VkMemoryAllocateFlagsInfo; - -typedef struct VkDeviceGroupRenderPassBeginInfo { - VkStructureType sType; - const void* pNext; - uint32_t deviceMask; - uint32_t deviceRenderAreaCount; - const VkRect2D* pDeviceRenderAreas; -} VkDeviceGroupRenderPassBeginInfo; - -typedef struct VkDeviceGroupCommandBufferBeginInfo { - VkStructureType sType; - const void* pNext; - uint32_t deviceMask; -} VkDeviceGroupCommandBufferBeginInfo; - -typedef struct VkDeviceGroupSubmitInfo { - VkStructureType sType; - const void* pNext; - uint32_t waitSemaphoreCount; - const uint32_t* pWaitSemaphoreDeviceIndices; - uint32_t commandBufferCount; - const uint32_t* pCommandBufferDeviceMasks; - uint32_t signalSemaphoreCount; - const uint32_t* pSignalSemaphoreDeviceIndices; -} VkDeviceGroupSubmitInfo; - -typedef struct VkDeviceGroupBindSparseInfo { - VkStructureType sType; - const void* pNext; - uint32_t resourceDeviceIndex; - uint32_t memoryDeviceIndex; -} VkDeviceGroupBindSparseInfo; - -typedef struct VkBindBufferMemoryDeviceGroupInfo { - VkStructureType sType; - const void* pNext; - uint32_t deviceIndexCount; - const uint32_t* pDeviceIndices; -} VkBindBufferMemoryDeviceGroupInfo; - -typedef struct VkBindImageMemoryDeviceGroupInfo { - VkStructureType sType; - const void* pNext; - uint32_t deviceIndexCount; - const uint32_t* pDeviceIndices; - uint32_t splitInstanceBindRegionCount; - const VkRect2D* pSplitInstanceBindRegions; -} VkBindImageMemoryDeviceGroupInfo; - -typedef struct VkPhysicalDeviceGroupProperties { - VkStructureType sType; - void* pNext; - uint32_t physicalDeviceCount; - VkPhysicalDevice physicalDevices[VK_MAX_DEVICE_GROUP_SIZE]; - VkBool32 subsetAllocation; -} VkPhysicalDeviceGroupProperties; - -typedef struct VkDeviceGroupDeviceCreateInfo { - VkStructureType sType; - const void* pNext; - uint32_t physicalDeviceCount; - const VkPhysicalDevice* pPhysicalDevices; -} VkDeviceGroupDeviceCreateInfo; - -typedef struct VkBufferMemoryRequirementsInfo2 { - VkStructureType sType; - const void* pNext; - VkBuffer buffer; -} VkBufferMemoryRequirementsInfo2; - -typedef struct VkImageMemoryRequirementsInfo2 { - VkStructureType sType; - const void* pNext; - VkImage image; -} VkImageMemoryRequirementsInfo2; - -typedef struct VkImageSparseMemoryRequirementsInfo2 { - VkStructureType sType; - const void* pNext; - VkImage image; -} VkImageSparseMemoryRequirementsInfo2; - -typedef struct VkMemoryRequirements2 { - VkStructureType sType; - void* pNext; - VkMemoryRequirements memoryRequirements; -} VkMemoryRequirements2; - -typedef struct VkSparseImageMemoryRequirements2 { - VkStructureType sType; - void* pNext; - VkSparseImageMemoryRequirements memoryRequirements; -} VkSparseImageMemoryRequirements2; - -typedef struct VkPhysicalDeviceFeatures2 { - VkStructureType sType; - void* pNext; - VkPhysicalDeviceFeatures features; -} VkPhysicalDeviceFeatures2; - -typedef struct VkPhysicalDeviceProperties2 { - VkStructureType sType; - void* pNext; - VkPhysicalDeviceProperties properties; -} VkPhysicalDeviceProperties2; - -typedef struct VkFormatProperties2 { - VkStructureType sType; - void* pNext; - VkFormatProperties formatProperties; -} VkFormatProperties2; - -typedef struct VkImageFormatProperties2 { - VkStructureType sType; - void* pNext; - VkImageFormatProperties imageFormatProperties; -} VkImageFormatProperties2; - -typedef struct VkPhysicalDeviceImageFormatInfo2 { - VkStructureType sType; - const void* pNext; - VkFormat format; - VkImageType type; - VkImageTiling tiling; - VkImageUsageFlags usage; - VkImageCreateFlags flags; -} VkPhysicalDeviceImageFormatInfo2; - -typedef struct VkQueueFamilyProperties2 { - VkStructureType sType; - void* pNext; - VkQueueFamilyProperties queueFamilyProperties; -} VkQueueFamilyProperties2; - -typedef struct VkPhysicalDeviceMemoryProperties2 { - VkStructureType sType; - void* pNext; - VkPhysicalDeviceMemoryProperties memoryProperties; -} VkPhysicalDeviceMemoryProperties2; - -typedef struct VkSparseImageFormatProperties2 { - VkStructureType sType; - void* pNext; - VkSparseImageFormatProperties properties; -} VkSparseImageFormatProperties2; - -typedef struct VkPhysicalDeviceSparseImageFormatInfo2 { - VkStructureType sType; - const void* pNext; - VkFormat format; - VkImageType type; - VkSampleCountFlagBits samples; - VkImageUsageFlags usage; - VkImageTiling tiling; -} VkPhysicalDeviceSparseImageFormatInfo2; - -typedef struct VkPhysicalDevicePointClippingProperties { - VkStructureType sType; - void* pNext; - VkPointClippingBehavior pointClippingBehavior; -} VkPhysicalDevicePointClippingProperties; - -typedef struct VkInputAttachmentAspectReference { - uint32_t subpass; - uint32_t inputAttachmentIndex; - VkImageAspectFlags aspectMask; -} VkInputAttachmentAspectReference; - -typedef struct VkRenderPassInputAttachmentAspectCreateInfo { - VkStructureType sType; - const void* pNext; - uint32_t aspectReferenceCount; - const VkInputAttachmentAspectReference* pAspectReferences; -} VkRenderPassInputAttachmentAspectCreateInfo; - -typedef struct VkImageViewUsageCreateInfo { - VkStructureType sType; - const void* pNext; - VkImageUsageFlags usage; -} VkImageViewUsageCreateInfo; - -typedef struct VkPipelineTessellationDomainOriginStateCreateInfo { - VkStructureType sType; - const void* pNext; - VkTessellationDomainOrigin domainOrigin; -} VkPipelineTessellationDomainOriginStateCreateInfo; - -typedef struct VkRenderPassMultiviewCreateInfo { - VkStructureType sType; - const void* pNext; - uint32_t subpassCount; - const uint32_t* pViewMasks; - uint32_t dependencyCount; - const int32_t* pViewOffsets; - uint32_t correlationMaskCount; - const uint32_t* pCorrelationMasks; -} VkRenderPassMultiviewCreateInfo; - -typedef struct VkPhysicalDeviceMultiviewFeatures { - VkStructureType sType; - void* pNext; - VkBool32 multiview; - VkBool32 multiviewGeometryShader; - VkBool32 multiviewTessellationShader; -} VkPhysicalDeviceMultiviewFeatures; - -typedef struct VkPhysicalDeviceMultiviewProperties { - VkStructureType sType; - void* pNext; - uint32_t maxMultiviewViewCount; - uint32_t maxMultiviewInstanceIndex; -} VkPhysicalDeviceMultiviewProperties; - -typedef struct VkPhysicalDeviceVariablePointerFeatures { - VkStructureType sType; - void* pNext; - VkBool32 variablePointersStorageBuffer; - VkBool32 variablePointers; -} VkPhysicalDeviceVariablePointerFeatures; - -typedef struct VkPhysicalDeviceProtectedMemoryFeatures { - VkStructureType sType; - void* pNext; - VkBool32 protectedMemory; -} VkPhysicalDeviceProtectedMemoryFeatures; - -typedef struct VkPhysicalDeviceProtectedMemoryProperties { - VkStructureType sType; - void* pNext; - VkBool32 protectedNoFault; -} VkPhysicalDeviceProtectedMemoryProperties; - -typedef struct VkDeviceQueueInfo2 { - VkStructureType sType; - const void* pNext; - VkDeviceQueueCreateFlags flags; - uint32_t queueFamilyIndex; - uint32_t queueIndex; -} VkDeviceQueueInfo2; - -typedef struct VkProtectedSubmitInfo { - VkStructureType sType; - const void* pNext; - VkBool32 protectedSubmit; -} VkProtectedSubmitInfo; - -typedef struct VkSamplerYcbcrConversionCreateInfo { - VkStructureType sType; - const void* pNext; - VkFormat format; - VkSamplerYcbcrModelConversion ycbcrModel; - VkSamplerYcbcrRange ycbcrRange; - VkComponentMapping components; - VkChromaLocation xChromaOffset; - VkChromaLocation yChromaOffset; - VkFilter chromaFilter; - VkBool32 forceExplicitReconstruction; -} VkSamplerYcbcrConversionCreateInfo; - -typedef struct VkSamplerYcbcrConversionInfo { - VkStructureType sType; - const void* pNext; - VkSamplerYcbcrConversion conversion; -} VkSamplerYcbcrConversionInfo; - -typedef struct VkBindImagePlaneMemoryInfo { - VkStructureType sType; - const void* pNext; - VkImageAspectFlagBits planeAspect; -} VkBindImagePlaneMemoryInfo; - -typedef struct VkImagePlaneMemoryRequirementsInfo { - VkStructureType sType; - const void* pNext; - VkImageAspectFlagBits planeAspect; -} VkImagePlaneMemoryRequirementsInfo; - -typedef struct VkPhysicalDeviceSamplerYcbcrConversionFeatures { - VkStructureType sType; - void* pNext; - VkBool32 samplerYcbcrConversion; -} VkPhysicalDeviceSamplerYcbcrConversionFeatures; - -typedef struct VkSamplerYcbcrConversionImageFormatProperties { - VkStructureType sType; - void* pNext; - uint32_t combinedImageSamplerDescriptorCount; -} VkSamplerYcbcrConversionImageFormatProperties; - -typedef struct VkDescriptorUpdateTemplateEntry { - uint32_t dstBinding; - uint32_t dstArrayElement; - uint32_t descriptorCount; - VkDescriptorType descriptorType; - size_t offset; - size_t stride; -} VkDescriptorUpdateTemplateEntry; - -typedef struct VkDescriptorUpdateTemplateCreateInfo { - VkStructureType sType; - void* pNext; - VkDescriptorUpdateTemplateCreateFlags flags; - uint32_t descriptorUpdateEntryCount; - const VkDescriptorUpdateTemplateEntry* pDescriptorUpdateEntries; - VkDescriptorUpdateTemplateType templateType; - VkDescriptorSetLayout descriptorSetLayout; - VkPipelineBindPoint pipelineBindPoint; - VkPipelineLayout pipelineLayout; - uint32_t set; -} VkDescriptorUpdateTemplateCreateInfo; - -typedef struct VkExternalMemoryProperties { - VkExternalMemoryFeatureFlags externalMemoryFeatures; - VkExternalMemoryHandleTypeFlags exportFromImportedHandleTypes; - VkExternalMemoryHandleTypeFlags compatibleHandleTypes; -} VkExternalMemoryProperties; - -typedef struct VkPhysicalDeviceExternalImageFormatInfo { - VkStructureType sType; - const void* pNext; - VkExternalMemoryHandleTypeFlagBits handleType; -} VkPhysicalDeviceExternalImageFormatInfo; - -typedef struct VkExternalImageFormatProperties { - VkStructureType sType; - void* pNext; - VkExternalMemoryProperties externalMemoryProperties; -} VkExternalImageFormatProperties; - -typedef struct VkPhysicalDeviceExternalBufferInfo { - VkStructureType sType; - const void* pNext; - VkBufferCreateFlags flags; - VkBufferUsageFlags usage; - VkExternalMemoryHandleTypeFlagBits handleType; -} VkPhysicalDeviceExternalBufferInfo; - -typedef struct VkExternalBufferProperties { - VkStructureType sType; - void* pNext; - VkExternalMemoryProperties externalMemoryProperties; -} VkExternalBufferProperties; - -typedef struct VkPhysicalDeviceIDProperties { - VkStructureType sType; - void* pNext; - uint8_t deviceUUID[VK_UUID_SIZE]; - uint8_t driverUUID[VK_UUID_SIZE]; - uint8_t deviceLUID[VK_LUID_SIZE]; - uint32_t deviceNodeMask; - VkBool32 deviceLUIDValid; -} VkPhysicalDeviceIDProperties; - -typedef struct VkExternalMemoryImageCreateInfo { - VkStructureType sType; - const void* pNext; - VkExternalMemoryHandleTypeFlags handleTypes; -} VkExternalMemoryImageCreateInfo; - -typedef struct VkExternalMemoryBufferCreateInfo { - VkStructureType sType; - const void* pNext; - VkExternalMemoryHandleTypeFlags handleTypes; -} VkExternalMemoryBufferCreateInfo; - -typedef struct VkExportMemoryAllocateInfo { - VkStructureType sType; - const void* pNext; - VkExternalMemoryHandleTypeFlags handleTypes; -} VkExportMemoryAllocateInfo; - -typedef struct VkPhysicalDeviceExternalFenceInfo { - VkStructureType sType; - const void* pNext; - VkExternalFenceHandleTypeFlagBits handleType; -} VkPhysicalDeviceExternalFenceInfo; - -typedef struct VkExternalFenceProperties { - VkStructureType sType; - void* pNext; - VkExternalFenceHandleTypeFlags exportFromImportedHandleTypes; - VkExternalFenceHandleTypeFlags compatibleHandleTypes; - VkExternalFenceFeatureFlags externalFenceFeatures; -} VkExternalFenceProperties; - -typedef struct VkExportFenceCreateInfo { - VkStructureType sType; - const void* pNext; - VkExternalFenceHandleTypeFlags handleTypes; -} VkExportFenceCreateInfo; - -typedef struct VkExportSemaphoreCreateInfo { - VkStructureType sType; - const void* pNext; - VkExternalSemaphoreHandleTypeFlags handleTypes; -} VkExportSemaphoreCreateInfo; - -typedef struct VkPhysicalDeviceExternalSemaphoreInfo { - VkStructureType sType; - const void* pNext; - VkExternalSemaphoreHandleTypeFlagBits handleType; -} VkPhysicalDeviceExternalSemaphoreInfo; - -typedef struct VkExternalSemaphoreProperties { - VkStructureType sType; - void* pNext; - VkExternalSemaphoreHandleTypeFlags exportFromImportedHandleTypes; - VkExternalSemaphoreHandleTypeFlags compatibleHandleTypes; - VkExternalSemaphoreFeatureFlags externalSemaphoreFeatures; -} VkExternalSemaphoreProperties; - -typedef struct VkPhysicalDeviceMaintenance3Properties { - VkStructureType sType; - void* pNext; - uint32_t maxPerSetDescriptors; - VkDeviceSize maxMemoryAllocationSize; -} VkPhysicalDeviceMaintenance3Properties; - -typedef struct VkDescriptorSetLayoutSupport { - VkStructureType sType; - void* pNext; - VkBool32 supported; -} VkDescriptorSetLayoutSupport; - -typedef struct VkPhysicalDeviceShaderDrawParameterFeatures { - VkStructureType sType; - void* pNext; - VkBool32 shaderDrawParameters; -} VkPhysicalDeviceShaderDrawParameterFeatures; - - -typedef VkResult (VKAPI_PTR *PFN_vkEnumerateInstanceVersion)(uint32_t* pApiVersion); -typedef VkResult (VKAPI_PTR *PFN_vkBindBufferMemory2)(VkDevice device, uint32_t bindInfoCount, const VkBindBufferMemoryInfo* pBindInfos); -typedef VkResult (VKAPI_PTR *PFN_vkBindImageMemory2)(VkDevice device, uint32_t bindInfoCount, const VkBindImageMemoryInfo* pBindInfos); -typedef void (VKAPI_PTR *PFN_vkGetDeviceGroupPeerMemoryFeatures)(VkDevice device, uint32_t heapIndex, uint32_t localDeviceIndex, uint32_t remoteDeviceIndex, VkPeerMemoryFeatureFlags* pPeerMemoryFeatures); -typedef void (VKAPI_PTR *PFN_vkCmdSetDeviceMask)(VkCommandBuffer commandBuffer, uint32_t deviceMask); -typedef void (VKAPI_PTR *PFN_vkCmdDispatchBase)(VkCommandBuffer commandBuffer, uint32_t baseGroupX, uint32_t baseGroupY, uint32_t baseGroupZ, uint32_t groupCountX, uint32_t groupCountY, uint32_t groupCountZ); -typedef VkResult (VKAPI_PTR *PFN_vkEnumeratePhysicalDeviceGroups)(VkInstance instance, uint32_t* pPhysicalDeviceGroupCount, VkPhysicalDeviceGroupProperties* pPhysicalDeviceGroupProperties); -typedef void (VKAPI_PTR *PFN_vkGetImageMemoryRequirements2)(VkDevice device, const VkImageMemoryRequirementsInfo2* pInfo, VkMemoryRequirements2* pMemoryRequirements); -typedef void (VKAPI_PTR *PFN_vkGetBufferMemoryRequirements2)(VkDevice device, const VkBufferMemoryRequirementsInfo2* pInfo, VkMemoryRequirements2* pMemoryRequirements); -typedef void (VKAPI_PTR *PFN_vkGetImageSparseMemoryRequirements2)(VkDevice device, const VkImageSparseMemoryRequirementsInfo2* pInfo, uint32_t* pSparseMemoryRequirementCount, VkSparseImageMemoryRequirements2* pSparseMemoryRequirements); -typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceFeatures2)(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures2* pFeatures); -typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceProperties2)(VkPhysicalDevice physicalDevice, VkPhysicalDeviceProperties2* pProperties); -typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceFormatProperties2)(VkPhysicalDevice physicalDevice, VkFormat format, VkFormatProperties2* pFormatProperties); -typedef VkResult (VKAPI_PTR *PFN_vkGetPhysicalDeviceImageFormatProperties2)(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceImageFormatInfo2* pImageFormatInfo, VkImageFormatProperties2* pImageFormatProperties); -typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceQueueFamilyProperties2)(VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount, VkQueueFamilyProperties2* pQueueFamilyProperties); -typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceMemoryProperties2)(VkPhysicalDevice physicalDevice, VkPhysicalDeviceMemoryProperties2* pMemoryProperties); -typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceSparseImageFormatProperties2)(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSparseImageFormatInfo2* pFormatInfo, uint32_t* pPropertyCount, VkSparseImageFormatProperties2* pProperties); -typedef void (VKAPI_PTR *PFN_vkTrimCommandPool)(VkDevice device, VkCommandPool commandPool, VkCommandPoolTrimFlags flags); -typedef void (VKAPI_PTR *PFN_vkGetDeviceQueue2)(VkDevice device, const VkDeviceQueueInfo2* pQueueInfo, VkQueue* pQueue); -typedef VkResult (VKAPI_PTR *PFN_vkCreateSamplerYcbcrConversion)(VkDevice device, const VkSamplerYcbcrConversionCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSamplerYcbcrConversion* pYcbcrConversion); -typedef void (VKAPI_PTR *PFN_vkDestroySamplerYcbcrConversion)(VkDevice device, VkSamplerYcbcrConversion ycbcrConversion, const VkAllocationCallbacks* pAllocator); -typedef VkResult (VKAPI_PTR *PFN_vkCreateDescriptorUpdateTemplate)(VkDevice device, const VkDescriptorUpdateTemplateCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDescriptorUpdateTemplate* pDescriptorUpdateTemplate); -typedef void (VKAPI_PTR *PFN_vkDestroyDescriptorUpdateTemplate)(VkDevice device, VkDescriptorUpdateTemplate descriptorUpdateTemplate, const VkAllocationCallbacks* pAllocator); -typedef void (VKAPI_PTR *PFN_vkUpdateDescriptorSetWithTemplate)(VkDevice device, VkDescriptorSet descriptorSet, VkDescriptorUpdateTemplate descriptorUpdateTemplate, const void* pData); -typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceExternalBufferProperties)(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceExternalBufferInfo* pExternalBufferInfo, VkExternalBufferProperties* pExternalBufferProperties); -typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceExternalFenceProperties)(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceExternalFenceInfo* pExternalFenceInfo, VkExternalFenceProperties* pExternalFenceProperties); -typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceExternalSemaphoreProperties)(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceExternalSemaphoreInfo* pExternalSemaphoreInfo, VkExternalSemaphoreProperties* pExternalSemaphoreProperties); -typedef void (VKAPI_PTR *PFN_vkGetDescriptorSetLayoutSupport)(VkDevice device, const VkDescriptorSetLayoutCreateInfo* pCreateInfo, VkDescriptorSetLayoutSupport* pSupport); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR VkResult VKAPI_CALL vkEnumerateInstanceVersion( - uint32_t* pApiVersion); - -VKAPI_ATTR VkResult VKAPI_CALL vkBindBufferMemory2( - VkDevice device, - uint32_t bindInfoCount, - const VkBindBufferMemoryInfo* pBindInfos); - -VKAPI_ATTR VkResult VKAPI_CALL vkBindImageMemory2( - VkDevice device, - uint32_t bindInfoCount, - const VkBindImageMemoryInfo* pBindInfos); - -VKAPI_ATTR void VKAPI_CALL vkGetDeviceGroupPeerMemoryFeatures( - VkDevice device, - uint32_t heapIndex, - uint32_t localDeviceIndex, - uint32_t remoteDeviceIndex, - VkPeerMemoryFeatureFlags* pPeerMemoryFeatures); - -VKAPI_ATTR void VKAPI_CALL vkCmdSetDeviceMask( - VkCommandBuffer commandBuffer, - uint32_t deviceMask); - -VKAPI_ATTR void VKAPI_CALL vkCmdDispatchBase( - VkCommandBuffer commandBuffer, - uint32_t baseGroupX, - uint32_t baseGroupY, - uint32_t baseGroupZ, - uint32_t groupCountX, - uint32_t groupCountY, - uint32_t groupCountZ); - -VKAPI_ATTR VkResult VKAPI_CALL vkEnumeratePhysicalDeviceGroups( - VkInstance instance, - uint32_t* pPhysicalDeviceGroupCount, - VkPhysicalDeviceGroupProperties* pPhysicalDeviceGroupProperties); - -VKAPI_ATTR void VKAPI_CALL vkGetImageMemoryRequirements2( - VkDevice device, - const VkImageMemoryRequirementsInfo2* pInfo, - VkMemoryRequirements2* pMemoryRequirements); - -VKAPI_ATTR void VKAPI_CALL vkGetBufferMemoryRequirements2( - VkDevice device, - const VkBufferMemoryRequirementsInfo2* pInfo, - VkMemoryRequirements2* pMemoryRequirements); - -VKAPI_ATTR void VKAPI_CALL vkGetImageSparseMemoryRequirements2( - VkDevice device, - const VkImageSparseMemoryRequirementsInfo2* pInfo, - uint32_t* pSparseMemoryRequirementCount, - VkSparseImageMemoryRequirements2* pSparseMemoryRequirements); - -VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceFeatures2( - VkPhysicalDevice physicalDevice, - VkPhysicalDeviceFeatures2* pFeatures); - -VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceProperties2( - VkPhysicalDevice physicalDevice, - VkPhysicalDeviceProperties2* pProperties); - -VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceFormatProperties2( - VkPhysicalDevice physicalDevice, - VkFormat format, - VkFormatProperties2* pFormatProperties); - -VKAPI_ATTR VkResult VKAPI_CALL vkGetPhysicalDeviceImageFormatProperties2( - VkPhysicalDevice physicalDevice, - const VkPhysicalDeviceImageFormatInfo2* pImageFormatInfo, - VkImageFormatProperties2* pImageFormatProperties); - -VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceQueueFamilyProperties2( - VkPhysicalDevice physicalDevice, - uint32_t* pQueueFamilyPropertyCount, - VkQueueFamilyProperties2* pQueueFamilyProperties); - -VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceMemoryProperties2( - VkPhysicalDevice physicalDevice, - VkPhysicalDeviceMemoryProperties2* pMemoryProperties); - -VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceSparseImageFormatProperties2( - VkPhysicalDevice physicalDevice, - const VkPhysicalDeviceSparseImageFormatInfo2* pFormatInfo, - uint32_t* pPropertyCount, - VkSparseImageFormatProperties2* pProperties); - -VKAPI_ATTR void VKAPI_CALL vkTrimCommandPool( - VkDevice device, - VkCommandPool commandPool, - VkCommandPoolTrimFlags flags); - -VKAPI_ATTR void VKAPI_CALL vkGetDeviceQueue2( - VkDevice device, - const VkDeviceQueueInfo2* pQueueInfo, - VkQueue* pQueue); - -VKAPI_ATTR VkResult VKAPI_CALL vkCreateSamplerYcbcrConversion( - VkDevice device, - const VkSamplerYcbcrConversionCreateInfo* pCreateInfo, - const VkAllocationCallbacks* pAllocator, - VkSamplerYcbcrConversion* pYcbcrConversion); - -VKAPI_ATTR void VKAPI_CALL vkDestroySamplerYcbcrConversion( - VkDevice device, - VkSamplerYcbcrConversion ycbcrConversion, - const VkAllocationCallbacks* pAllocator); - -VKAPI_ATTR VkResult VKAPI_CALL vkCreateDescriptorUpdateTemplate( - VkDevice device, - const VkDescriptorUpdateTemplateCreateInfo* pCreateInfo, - const VkAllocationCallbacks* pAllocator, - VkDescriptorUpdateTemplate* pDescriptorUpdateTemplate); - -VKAPI_ATTR void VKAPI_CALL vkDestroyDescriptorUpdateTemplate( - VkDevice device, - VkDescriptorUpdateTemplate descriptorUpdateTemplate, - const VkAllocationCallbacks* pAllocator); - -VKAPI_ATTR void VKAPI_CALL vkUpdateDescriptorSetWithTemplate( - VkDevice device, - VkDescriptorSet descriptorSet, - VkDescriptorUpdateTemplate descriptorUpdateTemplate, - const void* pData); - -VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceExternalBufferProperties( - VkPhysicalDevice physicalDevice, - const VkPhysicalDeviceExternalBufferInfo* pExternalBufferInfo, - VkExternalBufferProperties* pExternalBufferProperties); - -VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceExternalFenceProperties( - VkPhysicalDevice physicalDevice, - const VkPhysicalDeviceExternalFenceInfo* pExternalFenceInfo, - VkExternalFenceProperties* pExternalFenceProperties); - -VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceExternalSemaphoreProperties( - VkPhysicalDevice physicalDevice, - const VkPhysicalDeviceExternalSemaphoreInfo* pExternalSemaphoreInfo, - VkExternalSemaphoreProperties* pExternalSemaphoreProperties); - -VKAPI_ATTR void VKAPI_CALL vkGetDescriptorSetLayoutSupport( - VkDevice device, - const VkDescriptorSetLayoutCreateInfo* pCreateInfo, - VkDescriptorSetLayoutSupport* pSupport); -#endif - -#define VK_KHR_surface 1 -VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkSurfaceKHR) - -#define VK_KHR_SURFACE_SPEC_VERSION 25 -#define VK_KHR_SURFACE_EXTENSION_NAME "VK_KHR_surface" -#define VK_COLORSPACE_SRGB_NONLINEAR_KHR VK_COLOR_SPACE_SRGB_NONLINEAR_KHR - - -typedef enum VkColorSpaceKHR { - VK_COLOR_SPACE_SRGB_NONLINEAR_KHR = 0, - VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT = 1000104001, - VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT = 1000104002, - VK_COLOR_SPACE_DCI_P3_LINEAR_EXT = 1000104003, - VK_COLOR_SPACE_DCI_P3_NONLINEAR_EXT = 1000104004, - VK_COLOR_SPACE_BT709_LINEAR_EXT = 1000104005, - VK_COLOR_SPACE_BT709_NONLINEAR_EXT = 1000104006, - VK_COLOR_SPACE_BT2020_LINEAR_EXT = 1000104007, - VK_COLOR_SPACE_HDR10_ST2084_EXT = 1000104008, - VK_COLOR_SPACE_DOLBYVISION_EXT = 1000104009, - VK_COLOR_SPACE_HDR10_HLG_EXT = 1000104010, - VK_COLOR_SPACE_ADOBERGB_LINEAR_EXT = 1000104011, - VK_COLOR_SPACE_ADOBERGB_NONLINEAR_EXT = 1000104012, - VK_COLOR_SPACE_PASS_THROUGH_EXT = 1000104013, - VK_COLOR_SPACE_EXTENDED_SRGB_NONLINEAR_EXT = 1000104014, - VK_COLOR_SPACE_BEGIN_RANGE_KHR = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR, - VK_COLOR_SPACE_END_RANGE_KHR = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR, - VK_COLOR_SPACE_RANGE_SIZE_KHR = (VK_COLOR_SPACE_SRGB_NONLINEAR_KHR - VK_COLOR_SPACE_SRGB_NONLINEAR_KHR + 1), - VK_COLOR_SPACE_MAX_ENUM_KHR = 0x7FFFFFFF -} VkColorSpaceKHR; - -typedef enum VkPresentModeKHR { - VK_PRESENT_MODE_IMMEDIATE_KHR = 0, - VK_PRESENT_MODE_MAILBOX_KHR = 1, - VK_PRESENT_MODE_FIFO_KHR = 2, - VK_PRESENT_MODE_FIFO_RELAXED_KHR = 3, - VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR = 1000111000, - VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR = 1000111001, - VK_PRESENT_MODE_BEGIN_RANGE_KHR = VK_PRESENT_MODE_IMMEDIATE_KHR, - VK_PRESENT_MODE_END_RANGE_KHR = VK_PRESENT_MODE_FIFO_RELAXED_KHR, - VK_PRESENT_MODE_RANGE_SIZE_KHR = (VK_PRESENT_MODE_FIFO_RELAXED_KHR - VK_PRESENT_MODE_IMMEDIATE_KHR + 1), - VK_PRESENT_MODE_MAX_ENUM_KHR = 0x7FFFFFFF -} VkPresentModeKHR; - - -typedef enum VkSurfaceTransformFlagBitsKHR { - VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR = 0x00000001, - VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR = 0x00000002, - VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR = 0x00000004, - VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR = 0x00000008, - VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR = 0x00000010, - VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR = 0x00000020, - VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR = 0x00000040, - VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR = 0x00000080, - VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR = 0x00000100, - VK_SURFACE_TRANSFORM_FLAG_BITS_MAX_ENUM_KHR = 0x7FFFFFFF -} VkSurfaceTransformFlagBitsKHR; -typedef VkFlags VkSurfaceTransformFlagsKHR; - -typedef enum VkCompositeAlphaFlagBitsKHR { - VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR = 0x00000001, - VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR = 0x00000002, - VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR = 0x00000004, - VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR = 0x00000008, - VK_COMPOSITE_ALPHA_FLAG_BITS_MAX_ENUM_KHR = 0x7FFFFFFF -} VkCompositeAlphaFlagBitsKHR; -typedef VkFlags VkCompositeAlphaFlagsKHR; - -typedef struct VkSurfaceCapabilitiesKHR { - uint32_t minImageCount; - uint32_t maxImageCount; - VkExtent2D currentExtent; - VkExtent2D minImageExtent; - VkExtent2D maxImageExtent; - uint32_t maxImageArrayLayers; - VkSurfaceTransformFlagsKHR supportedTransforms; - VkSurfaceTransformFlagBitsKHR currentTransform; - VkCompositeAlphaFlagsKHR supportedCompositeAlpha; - VkImageUsageFlags supportedUsageFlags; -} VkSurfaceCapabilitiesKHR; - -typedef struct VkSurfaceFormatKHR { - VkFormat format; - VkColorSpaceKHR colorSpace; -} VkSurfaceFormatKHR; - - -typedef void (VKAPI_PTR *PFN_vkDestroySurfaceKHR)(VkInstance instance, VkSurfaceKHR surface, const VkAllocationCallbacks* pAllocator); -typedef VkResult (VKAPI_PTR *PFN_vkGetPhysicalDeviceSurfaceSupportKHR)(VkPhysicalDevice physicalDevice, uint32_t queueFamilyIndex, VkSurfaceKHR surface, VkBool32* pSupported); -typedef VkResult (VKAPI_PTR *PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR)(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface, VkSurfaceCapabilitiesKHR* pSurfaceCapabilities); -typedef VkResult (VKAPI_PTR *PFN_vkGetPhysicalDeviceSurfaceFormatsKHR)(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface, uint32_t* pSurfaceFormatCount, VkSurfaceFormatKHR* pSurfaceFormats); -typedef VkResult (VKAPI_PTR *PFN_vkGetPhysicalDeviceSurfacePresentModesKHR)(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface, uint32_t* pPresentModeCount, VkPresentModeKHR* pPresentModes); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR void VKAPI_CALL vkDestroySurfaceKHR( - VkInstance instance, - VkSurfaceKHR surface, - const VkAllocationCallbacks* pAllocator); - -VKAPI_ATTR VkResult VKAPI_CALL vkGetPhysicalDeviceSurfaceSupportKHR( - VkPhysicalDevice physicalDevice, - uint32_t queueFamilyIndex, - VkSurfaceKHR surface, - VkBool32* pSupported); - -VKAPI_ATTR VkResult VKAPI_CALL vkGetPhysicalDeviceSurfaceCapabilitiesKHR( - VkPhysicalDevice physicalDevice, - VkSurfaceKHR surface, - VkSurfaceCapabilitiesKHR* pSurfaceCapabilities); - -VKAPI_ATTR VkResult VKAPI_CALL vkGetPhysicalDeviceSurfaceFormatsKHR( - VkPhysicalDevice physicalDevice, - VkSurfaceKHR surface, - uint32_t* pSurfaceFormatCount, - VkSurfaceFormatKHR* pSurfaceFormats); - -VKAPI_ATTR VkResult VKAPI_CALL vkGetPhysicalDeviceSurfacePresentModesKHR( - VkPhysicalDevice physicalDevice, - VkSurfaceKHR surface, - uint32_t* pPresentModeCount, - VkPresentModeKHR* pPresentModes); -#endif - -#define VK_KHR_swapchain 1 -VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkSwapchainKHR) - -#define VK_KHR_SWAPCHAIN_SPEC_VERSION 70 -#define VK_KHR_SWAPCHAIN_EXTENSION_NAME "VK_KHR_swapchain" - - -typedef enum VkSwapchainCreateFlagBitsKHR { - VK_SWAPCHAIN_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT_KHR = 0x00000001, - VK_SWAPCHAIN_CREATE_PROTECTED_BIT_KHR = 0x00000002, - VK_SWAPCHAIN_CREATE_FLAG_BITS_MAX_ENUM_KHR = 0x7FFFFFFF -} VkSwapchainCreateFlagBitsKHR; -typedef VkFlags VkSwapchainCreateFlagsKHR; - -typedef enum VkDeviceGroupPresentModeFlagBitsKHR { - VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR = 0x00000001, - VK_DEVICE_GROUP_PRESENT_MODE_REMOTE_BIT_KHR = 0x00000002, - VK_DEVICE_GROUP_PRESENT_MODE_SUM_BIT_KHR = 0x00000004, - VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_MULTI_DEVICE_BIT_KHR = 0x00000008, - VK_DEVICE_GROUP_PRESENT_MODE_FLAG_BITS_MAX_ENUM_KHR = 0x7FFFFFFF -} VkDeviceGroupPresentModeFlagBitsKHR; -typedef VkFlags VkDeviceGroupPresentModeFlagsKHR; - -typedef struct VkSwapchainCreateInfoKHR { - VkStructureType sType; - const void* pNext; - VkSwapchainCreateFlagsKHR flags; - VkSurfaceKHR surface; - uint32_t minImageCount; - VkFormat imageFormat; - VkColorSpaceKHR imageColorSpace; - VkExtent2D imageExtent; - uint32_t imageArrayLayers; - VkImageUsageFlags imageUsage; - VkSharingMode imageSharingMode; - uint32_t queueFamilyIndexCount; - const uint32_t* pQueueFamilyIndices; - VkSurfaceTransformFlagBitsKHR preTransform; - VkCompositeAlphaFlagBitsKHR compositeAlpha; - VkPresentModeKHR presentMode; - VkBool32 clipped; - VkSwapchainKHR oldSwapchain; -} VkSwapchainCreateInfoKHR; - -typedef struct VkPresentInfoKHR { - VkStructureType sType; - const void* pNext; - uint32_t waitSemaphoreCount; - const VkSemaphore* pWaitSemaphores; - uint32_t swapchainCount; - const VkSwapchainKHR* pSwapchains; - const uint32_t* pImageIndices; - VkResult* pResults; -} VkPresentInfoKHR; - -typedef struct VkImageSwapchainCreateInfoKHR { - VkStructureType sType; - const void* pNext; - VkSwapchainKHR swapchain; -} VkImageSwapchainCreateInfoKHR; - -typedef struct VkBindImageMemorySwapchainInfoKHR { - VkStructureType sType; - const void* pNext; - VkSwapchainKHR swapchain; - uint32_t imageIndex; -} VkBindImageMemorySwapchainInfoKHR; - -typedef struct VkAcquireNextImageInfoKHR { - VkStructureType sType; - const void* pNext; - VkSwapchainKHR swapchain; - uint64_t timeout; - VkSemaphore semaphore; - VkFence fence; - uint32_t deviceMask; -} VkAcquireNextImageInfoKHR; - -typedef struct VkDeviceGroupPresentCapabilitiesKHR { - VkStructureType sType; - const void* pNext; - uint32_t presentMask[VK_MAX_DEVICE_GROUP_SIZE]; - VkDeviceGroupPresentModeFlagsKHR modes; -} VkDeviceGroupPresentCapabilitiesKHR; - -typedef struct VkDeviceGroupPresentInfoKHR { - VkStructureType sType; - const void* pNext; - uint32_t swapchainCount; - const uint32_t* pDeviceMasks; - VkDeviceGroupPresentModeFlagBitsKHR mode; -} VkDeviceGroupPresentInfoKHR; - -typedef struct VkDeviceGroupSwapchainCreateInfoKHR { - VkStructureType sType; - const void* pNext; - VkDeviceGroupPresentModeFlagsKHR modes; -} VkDeviceGroupSwapchainCreateInfoKHR; - - -typedef VkResult (VKAPI_PTR *PFN_vkCreateSwapchainKHR)(VkDevice device, const VkSwapchainCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchain); -typedef void (VKAPI_PTR *PFN_vkDestroySwapchainKHR)(VkDevice device, VkSwapchainKHR swapchain, const VkAllocationCallbacks* pAllocator); -typedef VkResult (VKAPI_PTR *PFN_vkGetSwapchainImagesKHR)(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pSwapchainImageCount, VkImage* pSwapchainImages); -typedef VkResult (VKAPI_PTR *PFN_vkAcquireNextImageKHR)(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout, VkSemaphore semaphore, VkFence fence, uint32_t* pImageIndex); -typedef VkResult (VKAPI_PTR *PFN_vkQueuePresentKHR)(VkQueue queue, const VkPresentInfoKHR* pPresentInfo); -typedef VkResult (VKAPI_PTR *PFN_vkGetDeviceGroupPresentCapabilitiesKHR)(VkDevice device, VkDeviceGroupPresentCapabilitiesKHR* pDeviceGroupPresentCapabilities); -typedef VkResult (VKAPI_PTR *PFN_vkGetDeviceGroupSurfacePresentModesKHR)(VkDevice device, VkSurfaceKHR surface, VkDeviceGroupPresentModeFlagsKHR* pModes); -typedef VkResult (VKAPI_PTR *PFN_vkGetPhysicalDevicePresentRectanglesKHR)(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface, uint32_t* pRectCount, VkRect2D* pRects); -typedef VkResult (VKAPI_PTR *PFN_vkAcquireNextImage2KHR)(VkDevice device, const VkAcquireNextImageInfoKHR* pAcquireInfo, uint32_t* pImageIndex); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR VkResult VKAPI_CALL vkCreateSwapchainKHR( - VkDevice device, - const VkSwapchainCreateInfoKHR* pCreateInfo, - const VkAllocationCallbacks* pAllocator, - VkSwapchainKHR* pSwapchain); - -VKAPI_ATTR void VKAPI_CALL vkDestroySwapchainKHR( - VkDevice device, - VkSwapchainKHR swapchain, - const VkAllocationCallbacks* pAllocator); - -VKAPI_ATTR VkResult VKAPI_CALL vkGetSwapchainImagesKHR( - VkDevice device, - VkSwapchainKHR swapchain, - uint32_t* pSwapchainImageCount, - VkImage* pSwapchainImages); - -VKAPI_ATTR VkResult VKAPI_CALL vkAcquireNextImageKHR( - VkDevice device, - VkSwapchainKHR swapchain, - uint64_t timeout, - VkSemaphore semaphore, - VkFence fence, - uint32_t* pImageIndex); - -VKAPI_ATTR VkResult VKAPI_CALL vkQueuePresentKHR( - VkQueue queue, - const VkPresentInfoKHR* pPresentInfo); - -VKAPI_ATTR VkResult VKAPI_CALL vkGetDeviceGroupPresentCapabilitiesKHR( - VkDevice device, - VkDeviceGroupPresentCapabilitiesKHR* pDeviceGroupPresentCapabilities); - -VKAPI_ATTR VkResult VKAPI_CALL vkGetDeviceGroupSurfacePresentModesKHR( - VkDevice device, - VkSurfaceKHR surface, - VkDeviceGroupPresentModeFlagsKHR* pModes); - -VKAPI_ATTR VkResult VKAPI_CALL vkGetPhysicalDevicePresentRectanglesKHR( - VkPhysicalDevice physicalDevice, - VkSurfaceKHR surface, - uint32_t* pRectCount, - VkRect2D* pRects); - -VKAPI_ATTR VkResult VKAPI_CALL vkAcquireNextImage2KHR( - VkDevice device, - const VkAcquireNextImageInfoKHR* pAcquireInfo, - uint32_t* pImageIndex); -#endif - -#define VK_KHR_display 1 -VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkDisplayKHR) -VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkDisplayModeKHR) - -#define VK_KHR_DISPLAY_SPEC_VERSION 21 -#define VK_KHR_DISPLAY_EXTENSION_NAME "VK_KHR_display" - - -typedef enum VkDisplayPlaneAlphaFlagBitsKHR { - VK_DISPLAY_PLANE_ALPHA_OPAQUE_BIT_KHR = 0x00000001, - VK_DISPLAY_PLANE_ALPHA_GLOBAL_BIT_KHR = 0x00000002, - VK_DISPLAY_PLANE_ALPHA_PER_PIXEL_BIT_KHR = 0x00000004, - VK_DISPLAY_PLANE_ALPHA_PER_PIXEL_PREMULTIPLIED_BIT_KHR = 0x00000008, - VK_DISPLAY_PLANE_ALPHA_FLAG_BITS_MAX_ENUM_KHR = 0x7FFFFFFF -} VkDisplayPlaneAlphaFlagBitsKHR; -typedef VkFlags VkDisplayPlaneAlphaFlagsKHR; -typedef VkFlags VkDisplayModeCreateFlagsKHR; -typedef VkFlags VkDisplaySurfaceCreateFlagsKHR; - -typedef struct VkDisplayPropertiesKHR { - VkDisplayKHR display; - const char* displayName; - VkExtent2D physicalDimensions; - VkExtent2D physicalResolution; - VkSurfaceTransformFlagsKHR supportedTransforms; - VkBool32 planeReorderPossible; - VkBool32 persistentContent; -} VkDisplayPropertiesKHR; - -typedef struct VkDisplayModeParametersKHR { - VkExtent2D visibleRegion; - uint32_t refreshRate; -} VkDisplayModeParametersKHR; - -typedef struct VkDisplayModePropertiesKHR { - VkDisplayModeKHR displayMode; - VkDisplayModeParametersKHR parameters; -} VkDisplayModePropertiesKHR; - -typedef struct VkDisplayModeCreateInfoKHR { - VkStructureType sType; - const void* pNext; - VkDisplayModeCreateFlagsKHR flags; - VkDisplayModeParametersKHR parameters; -} VkDisplayModeCreateInfoKHR; - -typedef struct VkDisplayPlaneCapabilitiesKHR { - VkDisplayPlaneAlphaFlagsKHR supportedAlpha; - VkOffset2D minSrcPosition; - VkOffset2D maxSrcPosition; - VkExtent2D minSrcExtent; - VkExtent2D maxSrcExtent; - VkOffset2D minDstPosition; - VkOffset2D maxDstPosition; - VkExtent2D minDstExtent; - VkExtent2D maxDstExtent; -} VkDisplayPlaneCapabilitiesKHR; - -typedef struct VkDisplayPlanePropertiesKHR { - VkDisplayKHR currentDisplay; - uint32_t currentStackIndex; -} VkDisplayPlanePropertiesKHR; - -typedef struct VkDisplaySurfaceCreateInfoKHR { - VkStructureType sType; - const void* pNext; - VkDisplaySurfaceCreateFlagsKHR flags; - VkDisplayModeKHR displayMode; - uint32_t planeIndex; - uint32_t planeStackIndex; - VkSurfaceTransformFlagBitsKHR transform; - float globalAlpha; - VkDisplayPlaneAlphaFlagBitsKHR alphaMode; - VkExtent2D imageExtent; -} VkDisplaySurfaceCreateInfoKHR; - - -typedef VkResult (VKAPI_PTR *PFN_vkGetPhysicalDeviceDisplayPropertiesKHR)(VkPhysicalDevice physicalDevice, uint32_t* pPropertyCount, VkDisplayPropertiesKHR* pProperties); -typedef VkResult (VKAPI_PTR *PFN_vkGetPhysicalDeviceDisplayPlanePropertiesKHR)(VkPhysicalDevice physicalDevice, uint32_t* pPropertyCount, VkDisplayPlanePropertiesKHR* pProperties); -typedef VkResult (VKAPI_PTR *PFN_vkGetDisplayPlaneSupportedDisplaysKHR)(VkPhysicalDevice physicalDevice, uint32_t planeIndex, uint32_t* pDisplayCount, VkDisplayKHR* pDisplays); -typedef VkResult (VKAPI_PTR *PFN_vkGetDisplayModePropertiesKHR)(VkPhysicalDevice physicalDevice, VkDisplayKHR display, uint32_t* pPropertyCount, VkDisplayModePropertiesKHR* pProperties); -typedef VkResult (VKAPI_PTR *PFN_vkCreateDisplayModeKHR)(VkPhysicalDevice physicalDevice, VkDisplayKHR display, const VkDisplayModeCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDisplayModeKHR* pMode); -typedef VkResult (VKAPI_PTR *PFN_vkGetDisplayPlaneCapabilitiesKHR)(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode, uint32_t planeIndex, VkDisplayPlaneCapabilitiesKHR* pCapabilities); -typedef VkResult (VKAPI_PTR *PFN_vkCreateDisplayPlaneSurfaceKHR)(VkInstance instance, const VkDisplaySurfaceCreateInfoKHR* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSurfaceKHR* pSurface); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR VkResult VKAPI_CALL vkGetPhysicalDeviceDisplayPropertiesKHR( - VkPhysicalDevice physicalDevice, - uint32_t* pPropertyCount, - VkDisplayPropertiesKHR* pProperties); - -VKAPI_ATTR VkResult VKAPI_CALL vkGetPhysicalDeviceDisplayPlanePropertiesKHR( - VkPhysicalDevice physicalDevice, - uint32_t* pPropertyCount, - VkDisplayPlanePropertiesKHR* pProperties); - -VKAPI_ATTR VkResult VKAPI_CALL vkGetDisplayPlaneSupportedDisplaysKHR( - VkPhysicalDevice physicalDevice, - uint32_t planeIndex, - uint32_t* pDisplayCount, - VkDisplayKHR* pDisplays); - -VKAPI_ATTR VkResult VKAPI_CALL vkGetDisplayModePropertiesKHR( - VkPhysicalDevice physicalDevice, - VkDisplayKHR display, - uint32_t* pPropertyCount, - VkDisplayModePropertiesKHR* pProperties); - -VKAPI_ATTR VkResult VKAPI_CALL vkCreateDisplayModeKHR( - VkPhysicalDevice physicalDevice, - VkDisplayKHR display, - const VkDisplayModeCreateInfoKHR* pCreateInfo, - const VkAllocationCallbacks* pAllocator, - VkDisplayModeKHR* pMode); - -VKAPI_ATTR VkResult VKAPI_CALL vkGetDisplayPlaneCapabilitiesKHR( - VkPhysicalDevice physicalDevice, - VkDisplayModeKHR mode, - uint32_t planeIndex, - VkDisplayPlaneCapabilitiesKHR* pCapabilities); - -VKAPI_ATTR VkResult VKAPI_CALL vkCreateDisplayPlaneSurfaceKHR( - VkInstance instance, - const VkDisplaySurfaceCreateInfoKHR* pCreateInfo, - const VkAllocationCallbacks* pAllocator, - VkSurfaceKHR* pSurface); -#endif - -#define VK_KHR_display_swapchain 1 -#define VK_KHR_DISPLAY_SWAPCHAIN_SPEC_VERSION 9 -#define VK_KHR_DISPLAY_SWAPCHAIN_EXTENSION_NAME "VK_KHR_display_swapchain" - -typedef struct VkDisplayPresentInfoKHR { - VkStructureType sType; - const void* pNext; - VkRect2D srcRect; - VkRect2D dstRect; - VkBool32 persistent; -} VkDisplayPresentInfoKHR; - - -typedef VkResult (VKAPI_PTR *PFN_vkCreateSharedSwapchainsKHR)(VkDevice device, uint32_t swapchainCount, const VkSwapchainCreateInfoKHR* pCreateInfos, const VkAllocationCallbacks* pAllocator, VkSwapchainKHR* pSwapchains); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR VkResult VKAPI_CALL vkCreateSharedSwapchainsKHR( - VkDevice device, - uint32_t swapchainCount, - const VkSwapchainCreateInfoKHR* pCreateInfos, - const VkAllocationCallbacks* pAllocator, - VkSwapchainKHR* pSwapchains); -#endif - -#define VK_KHR_sampler_mirror_clamp_to_edge 1 -#define VK_KHR_SAMPLER_MIRROR_CLAMP_TO_EDGE_SPEC_VERSION 1 -#define VK_KHR_SAMPLER_MIRROR_CLAMP_TO_EDGE_EXTENSION_NAME "VK_KHR_sampler_mirror_clamp_to_edge" - - -#define VK_KHR_multiview 1 -#define VK_KHR_MULTIVIEW_SPEC_VERSION 1 -#define VK_KHR_MULTIVIEW_EXTENSION_NAME "VK_KHR_multiview" - -typedef VkRenderPassMultiviewCreateInfo VkRenderPassMultiviewCreateInfoKHR; - -typedef VkPhysicalDeviceMultiviewFeatures VkPhysicalDeviceMultiviewFeaturesKHR; - -typedef VkPhysicalDeviceMultiviewProperties VkPhysicalDeviceMultiviewPropertiesKHR; - - - -#define VK_KHR_get_physical_device_properties2 1 -#define VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_SPEC_VERSION 1 -#define VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME "VK_KHR_get_physical_device_properties2" - -typedef VkPhysicalDeviceFeatures2 VkPhysicalDeviceFeatures2KHR; - -typedef VkPhysicalDeviceProperties2 VkPhysicalDeviceProperties2KHR; - -typedef VkFormatProperties2 VkFormatProperties2KHR; - -typedef VkImageFormatProperties2 VkImageFormatProperties2KHR; - -typedef VkPhysicalDeviceImageFormatInfo2 VkPhysicalDeviceImageFormatInfo2KHR; - -typedef VkQueueFamilyProperties2 VkQueueFamilyProperties2KHR; - -typedef VkPhysicalDeviceMemoryProperties2 VkPhysicalDeviceMemoryProperties2KHR; - -typedef VkSparseImageFormatProperties2 VkSparseImageFormatProperties2KHR; - -typedef VkPhysicalDeviceSparseImageFormatInfo2 VkPhysicalDeviceSparseImageFormatInfo2KHR; - - -typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceFeatures2KHR)(VkPhysicalDevice physicalDevice, VkPhysicalDeviceFeatures2* pFeatures); -typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceProperties2KHR)(VkPhysicalDevice physicalDevice, VkPhysicalDeviceProperties2* pProperties); -typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceFormatProperties2KHR)(VkPhysicalDevice physicalDevice, VkFormat format, VkFormatProperties2* pFormatProperties); -typedef VkResult (VKAPI_PTR *PFN_vkGetPhysicalDeviceImageFormatProperties2KHR)(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceImageFormatInfo2* pImageFormatInfo, VkImageFormatProperties2* pImageFormatProperties); -typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceQueueFamilyProperties2KHR)(VkPhysicalDevice physicalDevice, uint32_t* pQueueFamilyPropertyCount, VkQueueFamilyProperties2* pQueueFamilyProperties); -typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceMemoryProperties2KHR)(VkPhysicalDevice physicalDevice, VkPhysicalDeviceMemoryProperties2* pMemoryProperties); -typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceSparseImageFormatProperties2KHR)(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSparseImageFormatInfo2* pFormatInfo, uint32_t* pPropertyCount, VkSparseImageFormatProperties2* pProperties); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceFeatures2KHR( - VkPhysicalDevice physicalDevice, - VkPhysicalDeviceFeatures2* pFeatures); - -VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceProperties2KHR( - VkPhysicalDevice physicalDevice, - VkPhysicalDeviceProperties2* pProperties); - -VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceFormatProperties2KHR( - VkPhysicalDevice physicalDevice, - VkFormat format, - VkFormatProperties2* pFormatProperties); - -VKAPI_ATTR VkResult VKAPI_CALL vkGetPhysicalDeviceImageFormatProperties2KHR( - VkPhysicalDevice physicalDevice, - const VkPhysicalDeviceImageFormatInfo2* pImageFormatInfo, - VkImageFormatProperties2* pImageFormatProperties); - -VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceQueueFamilyProperties2KHR( - VkPhysicalDevice physicalDevice, - uint32_t* pQueueFamilyPropertyCount, - VkQueueFamilyProperties2* pQueueFamilyProperties); - -VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceMemoryProperties2KHR( - VkPhysicalDevice physicalDevice, - VkPhysicalDeviceMemoryProperties2* pMemoryProperties); - -VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceSparseImageFormatProperties2KHR( - VkPhysicalDevice physicalDevice, - const VkPhysicalDeviceSparseImageFormatInfo2* pFormatInfo, - uint32_t* pPropertyCount, - VkSparseImageFormatProperties2* pProperties); -#endif - -#define VK_KHR_device_group 1 -#define VK_KHR_DEVICE_GROUP_SPEC_VERSION 3 -#define VK_KHR_DEVICE_GROUP_EXTENSION_NAME "VK_KHR_device_group" - -typedef VkPeerMemoryFeatureFlags VkPeerMemoryFeatureFlagsKHR; - -typedef VkPeerMemoryFeatureFlagBits VkPeerMemoryFeatureFlagBitsKHR; - -typedef VkMemoryAllocateFlags VkMemoryAllocateFlagsKHR; - -typedef VkMemoryAllocateFlagBits VkMemoryAllocateFlagBitsKHR; - - -typedef VkMemoryAllocateFlagsInfo VkMemoryAllocateFlagsInfoKHR; - -typedef VkDeviceGroupRenderPassBeginInfo VkDeviceGroupRenderPassBeginInfoKHR; - -typedef VkDeviceGroupCommandBufferBeginInfo VkDeviceGroupCommandBufferBeginInfoKHR; - -typedef VkDeviceGroupSubmitInfo VkDeviceGroupSubmitInfoKHR; - -typedef VkDeviceGroupBindSparseInfo VkDeviceGroupBindSparseInfoKHR; - -typedef VkBindBufferMemoryDeviceGroupInfo VkBindBufferMemoryDeviceGroupInfoKHR; - -typedef VkBindImageMemoryDeviceGroupInfo VkBindImageMemoryDeviceGroupInfoKHR; - - -typedef void (VKAPI_PTR *PFN_vkGetDeviceGroupPeerMemoryFeaturesKHR)(VkDevice device, uint32_t heapIndex, uint32_t localDeviceIndex, uint32_t remoteDeviceIndex, VkPeerMemoryFeatureFlags* pPeerMemoryFeatures); -typedef void (VKAPI_PTR *PFN_vkCmdSetDeviceMaskKHR)(VkCommandBuffer commandBuffer, uint32_t deviceMask); -typedef void (VKAPI_PTR *PFN_vkCmdDispatchBaseKHR)(VkCommandBuffer commandBuffer, uint32_t baseGroupX, uint32_t baseGroupY, uint32_t baseGroupZ, uint32_t groupCountX, uint32_t groupCountY, uint32_t groupCountZ); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR void VKAPI_CALL vkGetDeviceGroupPeerMemoryFeaturesKHR( - VkDevice device, - uint32_t heapIndex, - uint32_t localDeviceIndex, - uint32_t remoteDeviceIndex, - VkPeerMemoryFeatureFlags* pPeerMemoryFeatures); - -VKAPI_ATTR void VKAPI_CALL vkCmdSetDeviceMaskKHR( - VkCommandBuffer commandBuffer, - uint32_t deviceMask); - -VKAPI_ATTR void VKAPI_CALL vkCmdDispatchBaseKHR( - VkCommandBuffer commandBuffer, - uint32_t baseGroupX, - uint32_t baseGroupY, - uint32_t baseGroupZ, - uint32_t groupCountX, - uint32_t groupCountY, - uint32_t groupCountZ); -#endif - -#define VK_KHR_shader_draw_parameters 1 -#define VK_KHR_SHADER_DRAW_PARAMETERS_SPEC_VERSION 1 -#define VK_KHR_SHADER_DRAW_PARAMETERS_EXTENSION_NAME "VK_KHR_shader_draw_parameters" - - -#define VK_KHR_maintenance1 1 -#define VK_KHR_MAINTENANCE1_SPEC_VERSION 1 -#define VK_KHR_MAINTENANCE1_EXTENSION_NAME "VK_KHR_maintenance1" - -typedef VkCommandPoolTrimFlags VkCommandPoolTrimFlagsKHR; - - -typedef void (VKAPI_PTR *PFN_vkTrimCommandPoolKHR)(VkDevice device, VkCommandPool commandPool, VkCommandPoolTrimFlags flags); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR void VKAPI_CALL vkTrimCommandPoolKHR( - VkDevice device, - VkCommandPool commandPool, - VkCommandPoolTrimFlags flags); -#endif - -#define VK_KHR_device_group_creation 1 -#define VK_KHR_DEVICE_GROUP_CREATION_SPEC_VERSION 1 -#define VK_KHR_DEVICE_GROUP_CREATION_EXTENSION_NAME "VK_KHR_device_group_creation" -#define VK_MAX_DEVICE_GROUP_SIZE_KHR VK_MAX_DEVICE_GROUP_SIZE - -typedef VkPhysicalDeviceGroupProperties VkPhysicalDeviceGroupPropertiesKHR; - -typedef VkDeviceGroupDeviceCreateInfo VkDeviceGroupDeviceCreateInfoKHR; - - -typedef VkResult (VKAPI_PTR *PFN_vkEnumeratePhysicalDeviceGroupsKHR)(VkInstance instance, uint32_t* pPhysicalDeviceGroupCount, VkPhysicalDeviceGroupProperties* pPhysicalDeviceGroupProperties); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR VkResult VKAPI_CALL vkEnumeratePhysicalDeviceGroupsKHR( - VkInstance instance, - uint32_t* pPhysicalDeviceGroupCount, - VkPhysicalDeviceGroupProperties* pPhysicalDeviceGroupProperties); -#endif - -#define VK_KHR_external_memory_capabilities 1 -#define VK_KHR_EXTERNAL_MEMORY_CAPABILITIES_SPEC_VERSION 1 -#define VK_KHR_EXTERNAL_MEMORY_CAPABILITIES_EXTENSION_NAME "VK_KHR_external_memory_capabilities" -#define VK_LUID_SIZE_KHR VK_LUID_SIZE - -typedef VkExternalMemoryHandleTypeFlags VkExternalMemoryHandleTypeFlagsKHR; - -typedef VkExternalMemoryHandleTypeFlagBits VkExternalMemoryHandleTypeFlagBitsKHR; - -typedef VkExternalMemoryFeatureFlags VkExternalMemoryFeatureFlagsKHR; - -typedef VkExternalMemoryFeatureFlagBits VkExternalMemoryFeatureFlagBitsKHR; - - -typedef VkExternalMemoryProperties VkExternalMemoryPropertiesKHR; - -typedef VkPhysicalDeviceExternalImageFormatInfo VkPhysicalDeviceExternalImageFormatInfoKHR; - -typedef VkExternalImageFormatProperties VkExternalImageFormatPropertiesKHR; - -typedef VkPhysicalDeviceExternalBufferInfo VkPhysicalDeviceExternalBufferInfoKHR; - -typedef VkExternalBufferProperties VkExternalBufferPropertiesKHR; - -typedef VkPhysicalDeviceIDProperties VkPhysicalDeviceIDPropertiesKHR; - - -typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceExternalBufferPropertiesKHR)(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceExternalBufferInfo* pExternalBufferInfo, VkExternalBufferProperties* pExternalBufferProperties); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceExternalBufferPropertiesKHR( - VkPhysicalDevice physicalDevice, - const VkPhysicalDeviceExternalBufferInfo* pExternalBufferInfo, - VkExternalBufferProperties* pExternalBufferProperties); -#endif - -#define VK_KHR_external_memory 1 -#define VK_KHR_EXTERNAL_MEMORY_SPEC_VERSION 1 -#define VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME "VK_KHR_external_memory" -#define VK_QUEUE_FAMILY_EXTERNAL_KHR VK_QUEUE_FAMILY_EXTERNAL - -typedef VkExternalMemoryImageCreateInfo VkExternalMemoryImageCreateInfoKHR; - -typedef VkExternalMemoryBufferCreateInfo VkExternalMemoryBufferCreateInfoKHR; - -typedef VkExportMemoryAllocateInfo VkExportMemoryAllocateInfoKHR; - - - -#define VK_KHR_external_memory_fd 1 -#define VK_KHR_EXTERNAL_MEMORY_FD_SPEC_VERSION 1 -#define VK_KHR_EXTERNAL_MEMORY_FD_EXTENSION_NAME "VK_KHR_external_memory_fd" - -typedef struct VkImportMemoryFdInfoKHR { - VkStructureType sType; - const void* pNext; - VkExternalMemoryHandleTypeFlagBits handleType; - int fd; -} VkImportMemoryFdInfoKHR; - -typedef struct VkMemoryFdPropertiesKHR { - VkStructureType sType; - void* pNext; - uint32_t memoryTypeBits; -} VkMemoryFdPropertiesKHR; - -typedef struct VkMemoryGetFdInfoKHR { - VkStructureType sType; - const void* pNext; - VkDeviceMemory memory; - VkExternalMemoryHandleTypeFlagBits handleType; -} VkMemoryGetFdInfoKHR; - - -typedef VkResult (VKAPI_PTR *PFN_vkGetMemoryFdKHR)(VkDevice device, const VkMemoryGetFdInfoKHR* pGetFdInfo, int* pFd); -typedef VkResult (VKAPI_PTR *PFN_vkGetMemoryFdPropertiesKHR)(VkDevice device, VkExternalMemoryHandleTypeFlagBits handleType, int fd, VkMemoryFdPropertiesKHR* pMemoryFdProperties); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR VkResult VKAPI_CALL vkGetMemoryFdKHR( - VkDevice device, - const VkMemoryGetFdInfoKHR* pGetFdInfo, - int* pFd); - -VKAPI_ATTR VkResult VKAPI_CALL vkGetMemoryFdPropertiesKHR( - VkDevice device, - VkExternalMemoryHandleTypeFlagBits handleType, - int fd, - VkMemoryFdPropertiesKHR* pMemoryFdProperties); -#endif - -#define VK_KHR_external_semaphore_capabilities 1 -#define VK_KHR_EXTERNAL_SEMAPHORE_CAPABILITIES_SPEC_VERSION 1 -#define VK_KHR_EXTERNAL_SEMAPHORE_CAPABILITIES_EXTENSION_NAME "VK_KHR_external_semaphore_capabilities" - -typedef VkExternalSemaphoreHandleTypeFlags VkExternalSemaphoreHandleTypeFlagsKHR; - -typedef VkExternalSemaphoreHandleTypeFlagBits VkExternalSemaphoreHandleTypeFlagBitsKHR; - -typedef VkExternalSemaphoreFeatureFlags VkExternalSemaphoreFeatureFlagsKHR; - -typedef VkExternalSemaphoreFeatureFlagBits VkExternalSemaphoreFeatureFlagBitsKHR; - - -typedef VkPhysicalDeviceExternalSemaphoreInfo VkPhysicalDeviceExternalSemaphoreInfoKHR; - -typedef VkExternalSemaphoreProperties VkExternalSemaphorePropertiesKHR; - - -typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceExternalSemaphorePropertiesKHR)(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceExternalSemaphoreInfo* pExternalSemaphoreInfo, VkExternalSemaphoreProperties* pExternalSemaphoreProperties); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceExternalSemaphorePropertiesKHR( - VkPhysicalDevice physicalDevice, - const VkPhysicalDeviceExternalSemaphoreInfo* pExternalSemaphoreInfo, - VkExternalSemaphoreProperties* pExternalSemaphoreProperties); -#endif - -#define VK_KHR_external_semaphore 1 -#define VK_KHR_EXTERNAL_SEMAPHORE_SPEC_VERSION 1 -#define VK_KHR_EXTERNAL_SEMAPHORE_EXTENSION_NAME "VK_KHR_external_semaphore" - -typedef VkSemaphoreImportFlags VkSemaphoreImportFlagsKHR; - -typedef VkSemaphoreImportFlagBits VkSemaphoreImportFlagBitsKHR; - - -typedef VkExportSemaphoreCreateInfo VkExportSemaphoreCreateInfoKHR; - - - -#define VK_KHR_external_semaphore_fd 1 -#define VK_KHR_EXTERNAL_SEMAPHORE_FD_SPEC_VERSION 1 -#define VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME "VK_KHR_external_semaphore_fd" - -typedef struct VkImportSemaphoreFdInfoKHR { - VkStructureType sType; - const void* pNext; - VkSemaphore semaphore; - VkSemaphoreImportFlags flags; - VkExternalSemaphoreHandleTypeFlagBits handleType; - int fd; -} VkImportSemaphoreFdInfoKHR; - -typedef struct VkSemaphoreGetFdInfoKHR { - VkStructureType sType; - const void* pNext; - VkSemaphore semaphore; - VkExternalSemaphoreHandleTypeFlagBits handleType; -} VkSemaphoreGetFdInfoKHR; - - -typedef VkResult (VKAPI_PTR *PFN_vkImportSemaphoreFdKHR)(VkDevice device, const VkImportSemaphoreFdInfoKHR* pImportSemaphoreFdInfo); -typedef VkResult (VKAPI_PTR *PFN_vkGetSemaphoreFdKHR)(VkDevice device, const VkSemaphoreGetFdInfoKHR* pGetFdInfo, int* pFd); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR VkResult VKAPI_CALL vkImportSemaphoreFdKHR( - VkDevice device, - const VkImportSemaphoreFdInfoKHR* pImportSemaphoreFdInfo); - -VKAPI_ATTR VkResult VKAPI_CALL vkGetSemaphoreFdKHR( - VkDevice device, - const VkSemaphoreGetFdInfoKHR* pGetFdInfo, - int* pFd); -#endif - -#define VK_KHR_push_descriptor 1 -#define VK_KHR_PUSH_DESCRIPTOR_SPEC_VERSION 2 -#define VK_KHR_PUSH_DESCRIPTOR_EXTENSION_NAME "VK_KHR_push_descriptor" - -typedef struct VkPhysicalDevicePushDescriptorPropertiesKHR { - VkStructureType sType; - void* pNext; - uint32_t maxPushDescriptors; -} VkPhysicalDevicePushDescriptorPropertiesKHR; - - -typedef void (VKAPI_PTR *PFN_vkCmdPushDescriptorSetKHR)(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint, VkPipelineLayout layout, uint32_t set, uint32_t descriptorWriteCount, const VkWriteDescriptorSet* pDescriptorWrites); -typedef void (VKAPI_PTR *PFN_vkCmdPushDescriptorSetWithTemplateKHR)(VkCommandBuffer commandBuffer, VkDescriptorUpdateTemplate descriptorUpdateTemplate, VkPipelineLayout layout, uint32_t set, const void* pData); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR void VKAPI_CALL vkCmdPushDescriptorSetKHR( - VkCommandBuffer commandBuffer, - VkPipelineBindPoint pipelineBindPoint, - VkPipelineLayout layout, - uint32_t set, - uint32_t descriptorWriteCount, - const VkWriteDescriptorSet* pDescriptorWrites); - -VKAPI_ATTR void VKAPI_CALL vkCmdPushDescriptorSetWithTemplateKHR( - VkCommandBuffer commandBuffer, - VkDescriptorUpdateTemplate descriptorUpdateTemplate, - VkPipelineLayout layout, - uint32_t set, - const void* pData); -#endif - -#define VK_KHR_16bit_storage 1 -#define VK_KHR_16BIT_STORAGE_SPEC_VERSION 1 -#define VK_KHR_16BIT_STORAGE_EXTENSION_NAME "VK_KHR_16bit_storage" - -typedef VkPhysicalDevice16BitStorageFeatures VkPhysicalDevice16BitStorageFeaturesKHR; - - - -#define VK_KHR_incremental_present 1 -#define VK_KHR_INCREMENTAL_PRESENT_SPEC_VERSION 1 -#define VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME "VK_KHR_incremental_present" - -typedef struct VkRectLayerKHR { - VkOffset2D offset; - VkExtent2D extent; - uint32_t layer; -} VkRectLayerKHR; - -typedef struct VkPresentRegionKHR { - uint32_t rectangleCount; - const VkRectLayerKHR* pRectangles; -} VkPresentRegionKHR; - -typedef struct VkPresentRegionsKHR { - VkStructureType sType; - const void* pNext; - uint32_t swapchainCount; - const VkPresentRegionKHR* pRegions; -} VkPresentRegionsKHR; - - - -#define VK_KHR_descriptor_update_template 1 -typedef VkDescriptorUpdateTemplate VkDescriptorUpdateTemplateKHR; - - -#define VK_KHR_DESCRIPTOR_UPDATE_TEMPLATE_SPEC_VERSION 1 -#define VK_KHR_DESCRIPTOR_UPDATE_TEMPLATE_EXTENSION_NAME "VK_KHR_descriptor_update_template" - -typedef VkDescriptorUpdateTemplateType VkDescriptorUpdateTemplateTypeKHR; - - -typedef VkDescriptorUpdateTemplateCreateFlags VkDescriptorUpdateTemplateCreateFlagsKHR; - - -typedef VkDescriptorUpdateTemplateEntry VkDescriptorUpdateTemplateEntryKHR; - -typedef VkDescriptorUpdateTemplateCreateInfo VkDescriptorUpdateTemplateCreateInfoKHR; - - -typedef VkResult (VKAPI_PTR *PFN_vkCreateDescriptorUpdateTemplateKHR)(VkDevice device, const VkDescriptorUpdateTemplateCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDescriptorUpdateTemplate* pDescriptorUpdateTemplate); -typedef void (VKAPI_PTR *PFN_vkDestroyDescriptorUpdateTemplateKHR)(VkDevice device, VkDescriptorUpdateTemplate descriptorUpdateTemplate, const VkAllocationCallbacks* pAllocator); -typedef void (VKAPI_PTR *PFN_vkUpdateDescriptorSetWithTemplateKHR)(VkDevice device, VkDescriptorSet descriptorSet, VkDescriptorUpdateTemplate descriptorUpdateTemplate, const void* pData); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR VkResult VKAPI_CALL vkCreateDescriptorUpdateTemplateKHR( - VkDevice device, - const VkDescriptorUpdateTemplateCreateInfo* pCreateInfo, - const VkAllocationCallbacks* pAllocator, - VkDescriptorUpdateTemplate* pDescriptorUpdateTemplate); - -VKAPI_ATTR void VKAPI_CALL vkDestroyDescriptorUpdateTemplateKHR( - VkDevice device, - VkDescriptorUpdateTemplate descriptorUpdateTemplate, - const VkAllocationCallbacks* pAllocator); - -VKAPI_ATTR void VKAPI_CALL vkUpdateDescriptorSetWithTemplateKHR( - VkDevice device, - VkDescriptorSet descriptorSet, - VkDescriptorUpdateTemplate descriptorUpdateTemplate, - const void* pData); -#endif - -#define VK_KHR_shared_presentable_image 1 -#define VK_KHR_SHARED_PRESENTABLE_IMAGE_SPEC_VERSION 1 -#define VK_KHR_SHARED_PRESENTABLE_IMAGE_EXTENSION_NAME "VK_KHR_shared_presentable_image" - -typedef struct VkSharedPresentSurfaceCapabilitiesKHR { - VkStructureType sType; - void* pNext; - VkImageUsageFlags sharedPresentSupportedUsageFlags; -} VkSharedPresentSurfaceCapabilitiesKHR; - - -typedef VkResult (VKAPI_PTR *PFN_vkGetSwapchainStatusKHR)(VkDevice device, VkSwapchainKHR swapchain); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR VkResult VKAPI_CALL vkGetSwapchainStatusKHR( - VkDevice device, - VkSwapchainKHR swapchain); -#endif - -#define VK_KHR_external_fence_capabilities 1 -#define VK_KHR_EXTERNAL_FENCE_CAPABILITIES_SPEC_VERSION 1 -#define VK_KHR_EXTERNAL_FENCE_CAPABILITIES_EXTENSION_NAME "VK_KHR_external_fence_capabilities" - -typedef VkExternalFenceHandleTypeFlags VkExternalFenceHandleTypeFlagsKHR; - -typedef VkExternalFenceHandleTypeFlagBits VkExternalFenceHandleTypeFlagBitsKHR; - -typedef VkExternalFenceFeatureFlags VkExternalFenceFeatureFlagsKHR; - -typedef VkExternalFenceFeatureFlagBits VkExternalFenceFeatureFlagBitsKHR; - - -typedef VkPhysicalDeviceExternalFenceInfo VkPhysicalDeviceExternalFenceInfoKHR; - -typedef VkExternalFenceProperties VkExternalFencePropertiesKHR; - - -typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceExternalFencePropertiesKHR)(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceExternalFenceInfo* pExternalFenceInfo, VkExternalFenceProperties* pExternalFenceProperties); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceExternalFencePropertiesKHR( - VkPhysicalDevice physicalDevice, - const VkPhysicalDeviceExternalFenceInfo* pExternalFenceInfo, - VkExternalFenceProperties* pExternalFenceProperties); -#endif - -#define VK_KHR_external_fence 1 -#define VK_KHR_EXTERNAL_FENCE_SPEC_VERSION 1 -#define VK_KHR_EXTERNAL_FENCE_EXTENSION_NAME "VK_KHR_external_fence" - -typedef VkFenceImportFlags VkFenceImportFlagsKHR; - -typedef VkFenceImportFlagBits VkFenceImportFlagBitsKHR; - - -typedef VkExportFenceCreateInfo VkExportFenceCreateInfoKHR; - - - -#define VK_KHR_external_fence_fd 1 -#define VK_KHR_EXTERNAL_FENCE_FD_SPEC_VERSION 1 -#define VK_KHR_EXTERNAL_FENCE_FD_EXTENSION_NAME "VK_KHR_external_fence_fd" - -typedef struct VkImportFenceFdInfoKHR { - VkStructureType sType; - const void* pNext; - VkFence fence; - VkFenceImportFlags flags; - VkExternalFenceHandleTypeFlagBits handleType; - int fd; -} VkImportFenceFdInfoKHR; - -typedef struct VkFenceGetFdInfoKHR { - VkStructureType sType; - const void* pNext; - VkFence fence; - VkExternalFenceHandleTypeFlagBits handleType; -} VkFenceGetFdInfoKHR; - - -typedef VkResult (VKAPI_PTR *PFN_vkImportFenceFdKHR)(VkDevice device, const VkImportFenceFdInfoKHR* pImportFenceFdInfo); -typedef VkResult (VKAPI_PTR *PFN_vkGetFenceFdKHR)(VkDevice device, const VkFenceGetFdInfoKHR* pGetFdInfo, int* pFd); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR VkResult VKAPI_CALL vkImportFenceFdKHR( - VkDevice device, - const VkImportFenceFdInfoKHR* pImportFenceFdInfo); - -VKAPI_ATTR VkResult VKAPI_CALL vkGetFenceFdKHR( - VkDevice device, - const VkFenceGetFdInfoKHR* pGetFdInfo, - int* pFd); -#endif - -#define VK_KHR_maintenance2 1 -#define VK_KHR_MAINTENANCE2_SPEC_VERSION 1 -#define VK_KHR_MAINTENANCE2_EXTENSION_NAME "VK_KHR_maintenance2" - -typedef VkPointClippingBehavior VkPointClippingBehaviorKHR; - -typedef VkTessellationDomainOrigin VkTessellationDomainOriginKHR; - - -typedef VkPhysicalDevicePointClippingProperties VkPhysicalDevicePointClippingPropertiesKHR; - -typedef VkRenderPassInputAttachmentAspectCreateInfo VkRenderPassInputAttachmentAspectCreateInfoKHR; - -typedef VkInputAttachmentAspectReference VkInputAttachmentAspectReferenceKHR; - -typedef VkImageViewUsageCreateInfo VkImageViewUsageCreateInfoKHR; - -typedef VkPipelineTessellationDomainOriginStateCreateInfo VkPipelineTessellationDomainOriginStateCreateInfoKHR; - - - -#define VK_KHR_get_surface_capabilities2 1 -#define VK_KHR_GET_SURFACE_CAPABILITIES_2_SPEC_VERSION 1 -#define VK_KHR_GET_SURFACE_CAPABILITIES_2_EXTENSION_NAME "VK_KHR_get_surface_capabilities2" - -typedef struct VkPhysicalDeviceSurfaceInfo2KHR { - VkStructureType sType; - const void* pNext; - VkSurfaceKHR surface; -} VkPhysicalDeviceSurfaceInfo2KHR; - -typedef struct VkSurfaceCapabilities2KHR { - VkStructureType sType; - void* pNext; - VkSurfaceCapabilitiesKHR surfaceCapabilities; -} VkSurfaceCapabilities2KHR; - -typedef struct VkSurfaceFormat2KHR { - VkStructureType sType; - void* pNext; - VkSurfaceFormatKHR surfaceFormat; -} VkSurfaceFormat2KHR; - - -typedef VkResult (VKAPI_PTR *PFN_vkGetPhysicalDeviceSurfaceCapabilities2KHR)(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo, VkSurfaceCapabilities2KHR* pSurfaceCapabilities); -typedef VkResult (VKAPI_PTR *PFN_vkGetPhysicalDeviceSurfaceFormats2KHR)(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo, uint32_t* pSurfaceFormatCount, VkSurfaceFormat2KHR* pSurfaceFormats); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR VkResult VKAPI_CALL vkGetPhysicalDeviceSurfaceCapabilities2KHR( - VkPhysicalDevice physicalDevice, - const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo, - VkSurfaceCapabilities2KHR* pSurfaceCapabilities); - -VKAPI_ATTR VkResult VKAPI_CALL vkGetPhysicalDeviceSurfaceFormats2KHR( - VkPhysicalDevice physicalDevice, - const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo, - uint32_t* pSurfaceFormatCount, - VkSurfaceFormat2KHR* pSurfaceFormats); -#endif - -#define VK_KHR_variable_pointers 1 -#define VK_KHR_VARIABLE_POINTERS_SPEC_VERSION 1 -#define VK_KHR_VARIABLE_POINTERS_EXTENSION_NAME "VK_KHR_variable_pointers" - -typedef VkPhysicalDeviceVariablePointerFeatures VkPhysicalDeviceVariablePointerFeaturesKHR; - - - -#define VK_KHR_dedicated_allocation 1 -#define VK_KHR_DEDICATED_ALLOCATION_SPEC_VERSION 3 -#define VK_KHR_DEDICATED_ALLOCATION_EXTENSION_NAME "VK_KHR_dedicated_allocation" - -typedef VkMemoryDedicatedRequirements VkMemoryDedicatedRequirementsKHR; - -typedef VkMemoryDedicatedAllocateInfo VkMemoryDedicatedAllocateInfoKHR; - - - -#define VK_KHR_storage_buffer_storage_class 1 -#define VK_KHR_STORAGE_BUFFER_STORAGE_CLASS_SPEC_VERSION 1 -#define VK_KHR_STORAGE_BUFFER_STORAGE_CLASS_EXTENSION_NAME "VK_KHR_storage_buffer_storage_class" - - -#define VK_KHR_relaxed_block_layout 1 -#define VK_KHR_RELAXED_BLOCK_LAYOUT_SPEC_VERSION 1 -#define VK_KHR_RELAXED_BLOCK_LAYOUT_EXTENSION_NAME "VK_KHR_relaxed_block_layout" - - -#define VK_KHR_get_memory_requirements2 1 -#define VK_KHR_GET_MEMORY_REQUIREMENTS_2_SPEC_VERSION 1 -#define VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME "VK_KHR_get_memory_requirements2" - -typedef VkBufferMemoryRequirementsInfo2 VkBufferMemoryRequirementsInfo2KHR; - -typedef VkImageMemoryRequirementsInfo2 VkImageMemoryRequirementsInfo2KHR; - -typedef VkImageSparseMemoryRequirementsInfo2 VkImageSparseMemoryRequirementsInfo2KHR; - -typedef VkMemoryRequirements2 VkMemoryRequirements2KHR; - -typedef VkSparseImageMemoryRequirements2 VkSparseImageMemoryRequirements2KHR; - - -typedef void (VKAPI_PTR *PFN_vkGetImageMemoryRequirements2KHR)(VkDevice device, const VkImageMemoryRequirementsInfo2* pInfo, VkMemoryRequirements2* pMemoryRequirements); -typedef void (VKAPI_PTR *PFN_vkGetBufferMemoryRequirements2KHR)(VkDevice device, const VkBufferMemoryRequirementsInfo2* pInfo, VkMemoryRequirements2* pMemoryRequirements); -typedef void (VKAPI_PTR *PFN_vkGetImageSparseMemoryRequirements2KHR)(VkDevice device, const VkImageSparseMemoryRequirementsInfo2* pInfo, uint32_t* pSparseMemoryRequirementCount, VkSparseImageMemoryRequirements2* pSparseMemoryRequirements); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR void VKAPI_CALL vkGetImageMemoryRequirements2KHR( - VkDevice device, - const VkImageMemoryRequirementsInfo2* pInfo, - VkMemoryRequirements2* pMemoryRequirements); - -VKAPI_ATTR void VKAPI_CALL vkGetBufferMemoryRequirements2KHR( - VkDevice device, - const VkBufferMemoryRequirementsInfo2* pInfo, - VkMemoryRequirements2* pMemoryRequirements); - -VKAPI_ATTR void VKAPI_CALL vkGetImageSparseMemoryRequirements2KHR( - VkDevice device, - const VkImageSparseMemoryRequirementsInfo2* pInfo, - uint32_t* pSparseMemoryRequirementCount, - VkSparseImageMemoryRequirements2* pSparseMemoryRequirements); -#endif - -#define VK_KHR_image_format_list 1 -#define VK_KHR_IMAGE_FORMAT_LIST_SPEC_VERSION 1 -#define VK_KHR_IMAGE_FORMAT_LIST_EXTENSION_NAME "VK_KHR_image_format_list" - -typedef struct VkImageFormatListCreateInfoKHR { - VkStructureType sType; - const void* pNext; - uint32_t viewFormatCount; - const VkFormat* pViewFormats; -} VkImageFormatListCreateInfoKHR; - - - -#define VK_KHR_sampler_ycbcr_conversion 1 -typedef VkSamplerYcbcrConversion VkSamplerYcbcrConversionKHR; - - -#define VK_KHR_SAMPLER_YCBCR_CONVERSION_SPEC_VERSION 1 -#define VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME "VK_KHR_sampler_ycbcr_conversion" - -typedef VkSamplerYcbcrModelConversion VkSamplerYcbcrModelConversionKHR; - -typedef VkSamplerYcbcrRange VkSamplerYcbcrRangeKHR; - -typedef VkChromaLocation VkChromaLocationKHR; - - -typedef VkSamplerYcbcrConversionCreateInfo VkSamplerYcbcrConversionCreateInfoKHR; - -typedef VkSamplerYcbcrConversionInfo VkSamplerYcbcrConversionInfoKHR; - -typedef VkBindImagePlaneMemoryInfo VkBindImagePlaneMemoryInfoKHR; - -typedef VkImagePlaneMemoryRequirementsInfo VkImagePlaneMemoryRequirementsInfoKHR; - -typedef VkPhysicalDeviceSamplerYcbcrConversionFeatures VkPhysicalDeviceSamplerYcbcrConversionFeaturesKHR; - -typedef VkSamplerYcbcrConversionImageFormatProperties VkSamplerYcbcrConversionImageFormatPropertiesKHR; - - -typedef VkResult (VKAPI_PTR *PFN_vkCreateSamplerYcbcrConversionKHR)(VkDevice device, const VkSamplerYcbcrConversionCreateInfo* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkSamplerYcbcrConversion* pYcbcrConversion); -typedef void (VKAPI_PTR *PFN_vkDestroySamplerYcbcrConversionKHR)(VkDevice device, VkSamplerYcbcrConversion ycbcrConversion, const VkAllocationCallbacks* pAllocator); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR VkResult VKAPI_CALL vkCreateSamplerYcbcrConversionKHR( - VkDevice device, - const VkSamplerYcbcrConversionCreateInfo* pCreateInfo, - const VkAllocationCallbacks* pAllocator, - VkSamplerYcbcrConversion* pYcbcrConversion); - -VKAPI_ATTR void VKAPI_CALL vkDestroySamplerYcbcrConversionKHR( - VkDevice device, - VkSamplerYcbcrConversion ycbcrConversion, - const VkAllocationCallbacks* pAllocator); -#endif - -#define VK_KHR_bind_memory2 1 -#define VK_KHR_BIND_MEMORY_2_SPEC_VERSION 1 -#define VK_KHR_BIND_MEMORY_2_EXTENSION_NAME "VK_KHR_bind_memory2" - -typedef VkBindBufferMemoryInfo VkBindBufferMemoryInfoKHR; - -typedef VkBindImageMemoryInfo VkBindImageMemoryInfoKHR; - - -typedef VkResult (VKAPI_PTR *PFN_vkBindBufferMemory2KHR)(VkDevice device, uint32_t bindInfoCount, const VkBindBufferMemoryInfo* pBindInfos); -typedef VkResult (VKAPI_PTR *PFN_vkBindImageMemory2KHR)(VkDevice device, uint32_t bindInfoCount, const VkBindImageMemoryInfo* pBindInfos); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR VkResult VKAPI_CALL vkBindBufferMemory2KHR( - VkDevice device, - uint32_t bindInfoCount, - const VkBindBufferMemoryInfo* pBindInfos); - -VKAPI_ATTR VkResult VKAPI_CALL vkBindImageMemory2KHR( - VkDevice device, - uint32_t bindInfoCount, - const VkBindImageMemoryInfo* pBindInfos); -#endif - -#define VK_KHR_maintenance3 1 -#define VK_KHR_MAINTENANCE3_SPEC_VERSION 1 -#define VK_KHR_MAINTENANCE3_EXTENSION_NAME "VK_KHR_maintenance3" - -typedef VkPhysicalDeviceMaintenance3Properties VkPhysicalDeviceMaintenance3PropertiesKHR; - -typedef VkDescriptorSetLayoutSupport VkDescriptorSetLayoutSupportKHR; - - -typedef void (VKAPI_PTR *PFN_vkGetDescriptorSetLayoutSupportKHR)(VkDevice device, const VkDescriptorSetLayoutCreateInfo* pCreateInfo, VkDescriptorSetLayoutSupport* pSupport); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR void VKAPI_CALL vkGetDescriptorSetLayoutSupportKHR( - VkDevice device, - const VkDescriptorSetLayoutCreateInfo* pCreateInfo, - VkDescriptorSetLayoutSupport* pSupport); -#endif - -#define VK_EXT_debug_report 1 -VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkDebugReportCallbackEXT) - -#define VK_EXT_DEBUG_REPORT_SPEC_VERSION 9 -#define VK_EXT_DEBUG_REPORT_EXTENSION_NAME "VK_EXT_debug_report" -#define VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT -#define VK_DEBUG_REPORT_OBJECT_TYPE_DEBUG_REPORT_EXT VK_DEBUG_REPORT_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT_EXT - - -typedef enum VkDebugReportObjectTypeEXT { - VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT = 0, - VK_DEBUG_REPORT_OBJECT_TYPE_INSTANCE_EXT = 1, - VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT = 2, - VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT = 3, - VK_DEBUG_REPORT_OBJECT_TYPE_QUEUE_EXT = 4, - VK_DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT = 5, - VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT = 6, - VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT = 7, - VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT = 8, - VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT = 9, - VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT = 10, - VK_DEBUG_REPORT_OBJECT_TYPE_EVENT_EXT = 11, - VK_DEBUG_REPORT_OBJECT_TYPE_QUERY_POOL_EXT = 12, - VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_VIEW_EXT = 13, - VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_VIEW_EXT = 14, - VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT = 15, - VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_CACHE_EXT = 16, - VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_LAYOUT_EXT = 17, - VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT = 18, - VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT = 19, - VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT_EXT = 20, - VK_DEBUG_REPORT_OBJECT_TYPE_SAMPLER_EXT = 21, - VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_POOL_EXT = 22, - VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT = 23, - VK_DEBUG_REPORT_OBJECT_TYPE_FRAMEBUFFER_EXT = 24, - VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_POOL_EXT = 25, - VK_DEBUG_REPORT_OBJECT_TYPE_SURFACE_KHR_EXT = 26, - VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT = 27, - VK_DEBUG_REPORT_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT_EXT = 28, - VK_DEBUG_REPORT_OBJECT_TYPE_DISPLAY_KHR_EXT = 29, - VK_DEBUG_REPORT_OBJECT_TYPE_DISPLAY_MODE_KHR_EXT = 30, - VK_DEBUG_REPORT_OBJECT_TYPE_OBJECT_TABLE_NVX_EXT = 31, - VK_DEBUG_REPORT_OBJECT_TYPE_INDIRECT_COMMANDS_LAYOUT_NVX_EXT = 32, - VK_DEBUG_REPORT_OBJECT_TYPE_VALIDATION_CACHE_EXT_EXT = 33, - VK_DEBUG_REPORT_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION_EXT = 1000156000, - VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE_EXT = 1000085000, - VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE_KHR_EXT = VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE_EXT, - VK_DEBUG_REPORT_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION_KHR_EXT = VK_DEBUG_REPORT_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION_EXT, - VK_DEBUG_REPORT_OBJECT_TYPE_BEGIN_RANGE_EXT = VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, - VK_DEBUG_REPORT_OBJECT_TYPE_END_RANGE_EXT = VK_DEBUG_REPORT_OBJECT_TYPE_VALIDATION_CACHE_EXT_EXT, - VK_DEBUG_REPORT_OBJECT_TYPE_RANGE_SIZE_EXT = (VK_DEBUG_REPORT_OBJECT_TYPE_VALIDATION_CACHE_EXT_EXT - VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT + 1), - VK_DEBUG_REPORT_OBJECT_TYPE_MAX_ENUM_EXT = 0x7FFFFFFF -} VkDebugReportObjectTypeEXT; - - -typedef enum VkDebugReportFlagBitsEXT { - VK_DEBUG_REPORT_INFORMATION_BIT_EXT = 0x00000001, - VK_DEBUG_REPORT_WARNING_BIT_EXT = 0x00000002, - VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT = 0x00000004, - VK_DEBUG_REPORT_ERROR_BIT_EXT = 0x00000008, - VK_DEBUG_REPORT_DEBUG_BIT_EXT = 0x00000010, - VK_DEBUG_REPORT_FLAG_BITS_MAX_ENUM_EXT = 0x7FFFFFFF -} VkDebugReportFlagBitsEXT; -typedef VkFlags VkDebugReportFlagsEXT; - -typedef VkBool32 (VKAPI_PTR *PFN_vkDebugReportCallbackEXT)( - VkDebugReportFlagsEXT flags, - VkDebugReportObjectTypeEXT objectType, - uint64_t object, - size_t location, - int32_t messageCode, - const char* pLayerPrefix, - const char* pMessage, - void* pUserData); - -typedef struct VkDebugReportCallbackCreateInfoEXT { - VkStructureType sType; - const void* pNext; - VkDebugReportFlagsEXT flags; - PFN_vkDebugReportCallbackEXT pfnCallback; - void* pUserData; -} VkDebugReportCallbackCreateInfoEXT; - - -typedef VkResult (VKAPI_PTR *PFN_vkCreateDebugReportCallbackEXT)(VkInstance instance, const VkDebugReportCallbackCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDebugReportCallbackEXT* pCallback); -typedef void (VKAPI_PTR *PFN_vkDestroyDebugReportCallbackEXT)(VkInstance instance, VkDebugReportCallbackEXT callback, const VkAllocationCallbacks* pAllocator); -typedef void (VKAPI_PTR *PFN_vkDebugReportMessageEXT)(VkInstance instance, VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objectType, uint64_t object, size_t location, int32_t messageCode, const char* pLayerPrefix, const char* pMessage); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR VkResult VKAPI_CALL vkCreateDebugReportCallbackEXT( - VkInstance instance, - const VkDebugReportCallbackCreateInfoEXT* pCreateInfo, - const VkAllocationCallbacks* pAllocator, - VkDebugReportCallbackEXT* pCallback); - -VKAPI_ATTR void VKAPI_CALL vkDestroyDebugReportCallbackEXT( - VkInstance instance, - VkDebugReportCallbackEXT callback, - const VkAllocationCallbacks* pAllocator); - -VKAPI_ATTR void VKAPI_CALL vkDebugReportMessageEXT( - VkInstance instance, - VkDebugReportFlagsEXT flags, - VkDebugReportObjectTypeEXT objectType, - uint64_t object, - size_t location, - int32_t messageCode, - const char* pLayerPrefix, - const char* pMessage); -#endif - -#define VK_NV_glsl_shader 1 -#define VK_NV_GLSL_SHADER_SPEC_VERSION 1 -#define VK_NV_GLSL_SHADER_EXTENSION_NAME "VK_NV_glsl_shader" - - -#define VK_EXT_depth_range_unrestricted 1 -#define VK_EXT_DEPTH_RANGE_UNRESTRICTED_SPEC_VERSION 1 -#define VK_EXT_DEPTH_RANGE_UNRESTRICTED_EXTENSION_NAME "VK_EXT_depth_range_unrestricted" - - -#define VK_IMG_filter_cubic 1 -#define VK_IMG_FILTER_CUBIC_SPEC_VERSION 1 -#define VK_IMG_FILTER_CUBIC_EXTENSION_NAME "VK_IMG_filter_cubic" - - -#define VK_AMD_rasterization_order 1 -#define VK_AMD_RASTERIZATION_ORDER_SPEC_VERSION 1 -#define VK_AMD_RASTERIZATION_ORDER_EXTENSION_NAME "VK_AMD_rasterization_order" - - -typedef enum VkRasterizationOrderAMD { - VK_RASTERIZATION_ORDER_STRICT_AMD = 0, - VK_RASTERIZATION_ORDER_RELAXED_AMD = 1, - VK_RASTERIZATION_ORDER_BEGIN_RANGE_AMD = VK_RASTERIZATION_ORDER_STRICT_AMD, - VK_RASTERIZATION_ORDER_END_RANGE_AMD = VK_RASTERIZATION_ORDER_RELAXED_AMD, - VK_RASTERIZATION_ORDER_RANGE_SIZE_AMD = (VK_RASTERIZATION_ORDER_RELAXED_AMD - VK_RASTERIZATION_ORDER_STRICT_AMD + 1), - VK_RASTERIZATION_ORDER_MAX_ENUM_AMD = 0x7FFFFFFF -} VkRasterizationOrderAMD; - -typedef struct VkPipelineRasterizationStateRasterizationOrderAMD { - VkStructureType sType; - const void* pNext; - VkRasterizationOrderAMD rasterizationOrder; -} VkPipelineRasterizationStateRasterizationOrderAMD; - - - -#define VK_AMD_shader_trinary_minmax 1 -#define VK_AMD_SHADER_TRINARY_MINMAX_SPEC_VERSION 1 -#define VK_AMD_SHADER_TRINARY_MINMAX_EXTENSION_NAME "VK_AMD_shader_trinary_minmax" - - -#define VK_AMD_shader_explicit_vertex_parameter 1 -#define VK_AMD_SHADER_EXPLICIT_VERTEX_PARAMETER_SPEC_VERSION 1 -#define VK_AMD_SHADER_EXPLICIT_VERTEX_PARAMETER_EXTENSION_NAME "VK_AMD_shader_explicit_vertex_parameter" - - -#define VK_EXT_debug_marker 1 -#define VK_EXT_DEBUG_MARKER_SPEC_VERSION 4 -#define VK_EXT_DEBUG_MARKER_EXTENSION_NAME "VK_EXT_debug_marker" - -typedef struct VkDebugMarkerObjectNameInfoEXT { - VkStructureType sType; - const void* pNext; - VkDebugReportObjectTypeEXT objectType; - uint64_t object; - const char* pObjectName; -} VkDebugMarkerObjectNameInfoEXT; - -typedef struct VkDebugMarkerObjectTagInfoEXT { - VkStructureType sType; - const void* pNext; - VkDebugReportObjectTypeEXT objectType; - uint64_t object; - uint64_t tagName; - size_t tagSize; - const void* pTag; -} VkDebugMarkerObjectTagInfoEXT; - -typedef struct VkDebugMarkerMarkerInfoEXT { - VkStructureType sType; - const void* pNext; - const char* pMarkerName; - float color[4]; -} VkDebugMarkerMarkerInfoEXT; - - -typedef VkResult (VKAPI_PTR *PFN_vkDebugMarkerSetObjectTagEXT)(VkDevice device, const VkDebugMarkerObjectTagInfoEXT* pTagInfo); -typedef VkResult (VKAPI_PTR *PFN_vkDebugMarkerSetObjectNameEXT)(VkDevice device, const VkDebugMarkerObjectNameInfoEXT* pNameInfo); -typedef void (VKAPI_PTR *PFN_vkCmdDebugMarkerBeginEXT)(VkCommandBuffer commandBuffer, const VkDebugMarkerMarkerInfoEXT* pMarkerInfo); -typedef void (VKAPI_PTR *PFN_vkCmdDebugMarkerEndEXT)(VkCommandBuffer commandBuffer); -typedef void (VKAPI_PTR *PFN_vkCmdDebugMarkerInsertEXT)(VkCommandBuffer commandBuffer, const VkDebugMarkerMarkerInfoEXT* pMarkerInfo); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR VkResult VKAPI_CALL vkDebugMarkerSetObjectTagEXT( - VkDevice device, - const VkDebugMarkerObjectTagInfoEXT* pTagInfo); - -VKAPI_ATTR VkResult VKAPI_CALL vkDebugMarkerSetObjectNameEXT( - VkDevice device, - const VkDebugMarkerObjectNameInfoEXT* pNameInfo); - -VKAPI_ATTR void VKAPI_CALL vkCmdDebugMarkerBeginEXT( - VkCommandBuffer commandBuffer, - const VkDebugMarkerMarkerInfoEXT* pMarkerInfo); - -VKAPI_ATTR void VKAPI_CALL vkCmdDebugMarkerEndEXT( - VkCommandBuffer commandBuffer); - -VKAPI_ATTR void VKAPI_CALL vkCmdDebugMarkerInsertEXT( - VkCommandBuffer commandBuffer, - const VkDebugMarkerMarkerInfoEXT* pMarkerInfo); -#endif - -#define VK_AMD_gcn_shader 1 -#define VK_AMD_GCN_SHADER_SPEC_VERSION 1 -#define VK_AMD_GCN_SHADER_EXTENSION_NAME "VK_AMD_gcn_shader" - - -#define VK_NV_dedicated_allocation 1 -#define VK_NV_DEDICATED_ALLOCATION_SPEC_VERSION 1 -#define VK_NV_DEDICATED_ALLOCATION_EXTENSION_NAME "VK_NV_dedicated_allocation" - -typedef struct VkDedicatedAllocationImageCreateInfoNV { - VkStructureType sType; - const void* pNext; - VkBool32 dedicatedAllocation; -} VkDedicatedAllocationImageCreateInfoNV; - -typedef struct VkDedicatedAllocationBufferCreateInfoNV { - VkStructureType sType; - const void* pNext; - VkBool32 dedicatedAllocation; -} VkDedicatedAllocationBufferCreateInfoNV; - -typedef struct VkDedicatedAllocationMemoryAllocateInfoNV { - VkStructureType sType; - const void* pNext; - VkImage image; - VkBuffer buffer; -} VkDedicatedAllocationMemoryAllocateInfoNV; - - - -#define VK_AMD_draw_indirect_count 1 -#define VK_AMD_DRAW_INDIRECT_COUNT_SPEC_VERSION 1 -#define VK_AMD_DRAW_INDIRECT_COUNT_EXTENSION_NAME "VK_AMD_draw_indirect_count" - -typedef void (VKAPI_PTR *PFN_vkCmdDrawIndirectCountAMD)(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount, uint32_t stride); -typedef void (VKAPI_PTR *PFN_vkCmdDrawIndexedIndirectCountAMD)(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount, uint32_t stride); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR void VKAPI_CALL vkCmdDrawIndirectCountAMD( - VkCommandBuffer commandBuffer, - VkBuffer buffer, - VkDeviceSize offset, - VkBuffer countBuffer, - VkDeviceSize countBufferOffset, - uint32_t maxDrawCount, - uint32_t stride); - -VKAPI_ATTR void VKAPI_CALL vkCmdDrawIndexedIndirectCountAMD( - VkCommandBuffer commandBuffer, - VkBuffer buffer, - VkDeviceSize offset, - VkBuffer countBuffer, - VkDeviceSize countBufferOffset, - uint32_t maxDrawCount, - uint32_t stride); -#endif - -#define VK_AMD_negative_viewport_height 1 -#define VK_AMD_NEGATIVE_VIEWPORT_HEIGHT_SPEC_VERSION 1 -#define VK_AMD_NEGATIVE_VIEWPORT_HEIGHT_EXTENSION_NAME "VK_AMD_negative_viewport_height" - - -#define VK_AMD_gpu_shader_half_float 1 -#define VK_AMD_GPU_SHADER_HALF_FLOAT_SPEC_VERSION 1 -#define VK_AMD_GPU_SHADER_HALF_FLOAT_EXTENSION_NAME "VK_AMD_gpu_shader_half_float" - - -#define VK_AMD_shader_ballot 1 -#define VK_AMD_SHADER_BALLOT_SPEC_VERSION 1 -#define VK_AMD_SHADER_BALLOT_EXTENSION_NAME "VK_AMD_shader_ballot" - - -#define VK_AMD_texture_gather_bias_lod 1 -#define VK_AMD_TEXTURE_GATHER_BIAS_LOD_SPEC_VERSION 1 -#define VK_AMD_TEXTURE_GATHER_BIAS_LOD_EXTENSION_NAME "VK_AMD_texture_gather_bias_lod" - -typedef struct VkTextureLODGatherFormatPropertiesAMD { - VkStructureType sType; - void* pNext; - VkBool32 supportsTextureGatherLODBiasAMD; -} VkTextureLODGatherFormatPropertiesAMD; - - - -#define VK_AMD_shader_info 1 -#define VK_AMD_SHADER_INFO_SPEC_VERSION 1 -#define VK_AMD_SHADER_INFO_EXTENSION_NAME "VK_AMD_shader_info" - - -typedef enum VkShaderInfoTypeAMD { - VK_SHADER_INFO_TYPE_STATISTICS_AMD = 0, - VK_SHADER_INFO_TYPE_BINARY_AMD = 1, - VK_SHADER_INFO_TYPE_DISASSEMBLY_AMD = 2, - VK_SHADER_INFO_TYPE_BEGIN_RANGE_AMD = VK_SHADER_INFO_TYPE_STATISTICS_AMD, - VK_SHADER_INFO_TYPE_END_RANGE_AMD = VK_SHADER_INFO_TYPE_DISASSEMBLY_AMD, - VK_SHADER_INFO_TYPE_RANGE_SIZE_AMD = (VK_SHADER_INFO_TYPE_DISASSEMBLY_AMD - VK_SHADER_INFO_TYPE_STATISTICS_AMD + 1), - VK_SHADER_INFO_TYPE_MAX_ENUM_AMD = 0x7FFFFFFF -} VkShaderInfoTypeAMD; - -typedef struct VkShaderResourceUsageAMD { - uint32_t numUsedVgprs; - uint32_t numUsedSgprs; - uint32_t ldsSizePerLocalWorkGroup; - size_t ldsUsageSizeInBytes; - size_t scratchMemUsageInBytes; -} VkShaderResourceUsageAMD; - -typedef struct VkShaderStatisticsInfoAMD { - VkShaderStageFlags shaderStageMask; - VkShaderResourceUsageAMD resourceUsage; - uint32_t numPhysicalVgprs; - uint32_t numPhysicalSgprs; - uint32_t numAvailableVgprs; - uint32_t numAvailableSgprs; - uint32_t computeWorkGroupSize[3]; -} VkShaderStatisticsInfoAMD; - - -typedef VkResult (VKAPI_PTR *PFN_vkGetShaderInfoAMD)(VkDevice device, VkPipeline pipeline, VkShaderStageFlagBits shaderStage, VkShaderInfoTypeAMD infoType, size_t* pInfoSize, void* pInfo); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR VkResult VKAPI_CALL vkGetShaderInfoAMD( - VkDevice device, - VkPipeline pipeline, - VkShaderStageFlagBits shaderStage, - VkShaderInfoTypeAMD infoType, - size_t* pInfoSize, - void* pInfo); -#endif - -#define VK_AMD_shader_image_load_store_lod 1 -#define VK_AMD_SHADER_IMAGE_LOAD_STORE_LOD_SPEC_VERSION 1 -#define VK_AMD_SHADER_IMAGE_LOAD_STORE_LOD_EXTENSION_NAME "VK_AMD_shader_image_load_store_lod" - - -#define VK_IMG_format_pvrtc 1 -#define VK_IMG_FORMAT_PVRTC_SPEC_VERSION 1 -#define VK_IMG_FORMAT_PVRTC_EXTENSION_NAME "VK_IMG_format_pvrtc" - - -#define VK_NV_external_memory_capabilities 1 -#define VK_NV_EXTERNAL_MEMORY_CAPABILITIES_SPEC_VERSION 1 -#define VK_NV_EXTERNAL_MEMORY_CAPABILITIES_EXTENSION_NAME "VK_NV_external_memory_capabilities" - - -typedef enum VkExternalMemoryHandleTypeFlagBitsNV { - VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_BIT_NV = 0x00000001, - VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT_NV = 0x00000002, - VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_IMAGE_BIT_NV = 0x00000004, - VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_IMAGE_KMT_BIT_NV = 0x00000008, - VK_EXTERNAL_MEMORY_HANDLE_TYPE_FLAG_BITS_MAX_ENUM_NV = 0x7FFFFFFF -} VkExternalMemoryHandleTypeFlagBitsNV; -typedef VkFlags VkExternalMemoryHandleTypeFlagsNV; - -typedef enum VkExternalMemoryFeatureFlagBitsNV { - VK_EXTERNAL_MEMORY_FEATURE_DEDICATED_ONLY_BIT_NV = 0x00000001, - VK_EXTERNAL_MEMORY_FEATURE_EXPORTABLE_BIT_NV = 0x00000002, - VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT_NV = 0x00000004, - VK_EXTERNAL_MEMORY_FEATURE_FLAG_BITS_MAX_ENUM_NV = 0x7FFFFFFF -} VkExternalMemoryFeatureFlagBitsNV; -typedef VkFlags VkExternalMemoryFeatureFlagsNV; - -typedef struct VkExternalImageFormatPropertiesNV { - VkImageFormatProperties imageFormatProperties; - VkExternalMemoryFeatureFlagsNV externalMemoryFeatures; - VkExternalMemoryHandleTypeFlagsNV exportFromImportedHandleTypes; - VkExternalMemoryHandleTypeFlagsNV compatibleHandleTypes; -} VkExternalImageFormatPropertiesNV; - - -typedef VkResult (VKAPI_PTR *PFN_vkGetPhysicalDeviceExternalImageFormatPropertiesNV)(VkPhysicalDevice physicalDevice, VkFormat format, VkImageType type, VkImageTiling tiling, VkImageUsageFlags usage, VkImageCreateFlags flags, VkExternalMemoryHandleTypeFlagsNV externalHandleType, VkExternalImageFormatPropertiesNV* pExternalImageFormatProperties); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR VkResult VKAPI_CALL vkGetPhysicalDeviceExternalImageFormatPropertiesNV( - VkPhysicalDevice physicalDevice, - VkFormat format, - VkImageType type, - VkImageTiling tiling, - VkImageUsageFlags usage, - VkImageCreateFlags flags, - VkExternalMemoryHandleTypeFlagsNV externalHandleType, - VkExternalImageFormatPropertiesNV* pExternalImageFormatProperties); -#endif - -#define VK_NV_external_memory 1 -#define VK_NV_EXTERNAL_MEMORY_SPEC_VERSION 1 -#define VK_NV_EXTERNAL_MEMORY_EXTENSION_NAME "VK_NV_external_memory" - -typedef struct VkExternalMemoryImageCreateInfoNV { - VkStructureType sType; - const void* pNext; - VkExternalMemoryHandleTypeFlagsNV handleTypes; -} VkExternalMemoryImageCreateInfoNV; - -typedef struct VkExportMemoryAllocateInfoNV { - VkStructureType sType; - const void* pNext; - VkExternalMemoryHandleTypeFlagsNV handleTypes; -} VkExportMemoryAllocateInfoNV; - - - -#define VK_EXT_validation_flags 1 -#define VK_EXT_VALIDATION_FLAGS_SPEC_VERSION 1 -#define VK_EXT_VALIDATION_FLAGS_EXTENSION_NAME "VK_EXT_validation_flags" - - -typedef enum VkValidationCheckEXT { - VK_VALIDATION_CHECK_ALL_EXT = 0, - VK_VALIDATION_CHECK_SHADERS_EXT = 1, - VK_VALIDATION_CHECK_BEGIN_RANGE_EXT = VK_VALIDATION_CHECK_ALL_EXT, - VK_VALIDATION_CHECK_END_RANGE_EXT = VK_VALIDATION_CHECK_SHADERS_EXT, - VK_VALIDATION_CHECK_RANGE_SIZE_EXT = (VK_VALIDATION_CHECK_SHADERS_EXT - VK_VALIDATION_CHECK_ALL_EXT + 1), - VK_VALIDATION_CHECK_MAX_ENUM_EXT = 0x7FFFFFFF -} VkValidationCheckEXT; - -typedef struct VkValidationFlagsEXT { - VkStructureType sType; - const void* pNext; - uint32_t disabledValidationCheckCount; - VkValidationCheckEXT* pDisabledValidationChecks; -} VkValidationFlagsEXT; - - - -#define VK_EXT_shader_subgroup_ballot 1 -#define VK_EXT_SHADER_SUBGROUP_BALLOT_SPEC_VERSION 1 -#define VK_EXT_SHADER_SUBGROUP_BALLOT_EXTENSION_NAME "VK_EXT_shader_subgroup_ballot" - - -#define VK_EXT_shader_subgroup_vote 1 -#define VK_EXT_SHADER_SUBGROUP_VOTE_SPEC_VERSION 1 -#define VK_EXT_SHADER_SUBGROUP_VOTE_EXTENSION_NAME "VK_EXT_shader_subgroup_vote" - - -#define VK_NVX_device_generated_commands 1 -VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkObjectTableNVX) -VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkIndirectCommandsLayoutNVX) - -#define VK_NVX_DEVICE_GENERATED_COMMANDS_SPEC_VERSION 3 -#define VK_NVX_DEVICE_GENERATED_COMMANDS_EXTENSION_NAME "VK_NVX_device_generated_commands" - - -typedef enum VkIndirectCommandsTokenTypeNVX { - VK_INDIRECT_COMMANDS_TOKEN_TYPE_PIPELINE_NVX = 0, - VK_INDIRECT_COMMANDS_TOKEN_TYPE_DESCRIPTOR_SET_NVX = 1, - VK_INDIRECT_COMMANDS_TOKEN_TYPE_INDEX_BUFFER_NVX = 2, - VK_INDIRECT_COMMANDS_TOKEN_TYPE_VERTEX_BUFFER_NVX = 3, - VK_INDIRECT_COMMANDS_TOKEN_TYPE_PUSH_CONSTANT_NVX = 4, - VK_INDIRECT_COMMANDS_TOKEN_TYPE_DRAW_INDEXED_NVX = 5, - VK_INDIRECT_COMMANDS_TOKEN_TYPE_DRAW_NVX = 6, - VK_INDIRECT_COMMANDS_TOKEN_TYPE_DISPATCH_NVX = 7, - VK_INDIRECT_COMMANDS_TOKEN_TYPE_BEGIN_RANGE_NVX = VK_INDIRECT_COMMANDS_TOKEN_TYPE_PIPELINE_NVX, - VK_INDIRECT_COMMANDS_TOKEN_TYPE_END_RANGE_NVX = VK_INDIRECT_COMMANDS_TOKEN_TYPE_DISPATCH_NVX, - VK_INDIRECT_COMMANDS_TOKEN_TYPE_RANGE_SIZE_NVX = (VK_INDIRECT_COMMANDS_TOKEN_TYPE_DISPATCH_NVX - VK_INDIRECT_COMMANDS_TOKEN_TYPE_PIPELINE_NVX + 1), - VK_INDIRECT_COMMANDS_TOKEN_TYPE_MAX_ENUM_NVX = 0x7FFFFFFF -} VkIndirectCommandsTokenTypeNVX; - -typedef enum VkObjectEntryTypeNVX { - VK_OBJECT_ENTRY_TYPE_DESCRIPTOR_SET_NVX = 0, - VK_OBJECT_ENTRY_TYPE_PIPELINE_NVX = 1, - VK_OBJECT_ENTRY_TYPE_INDEX_BUFFER_NVX = 2, - VK_OBJECT_ENTRY_TYPE_VERTEX_BUFFER_NVX = 3, - VK_OBJECT_ENTRY_TYPE_PUSH_CONSTANT_NVX = 4, - VK_OBJECT_ENTRY_TYPE_BEGIN_RANGE_NVX = VK_OBJECT_ENTRY_TYPE_DESCRIPTOR_SET_NVX, - VK_OBJECT_ENTRY_TYPE_END_RANGE_NVX = VK_OBJECT_ENTRY_TYPE_PUSH_CONSTANT_NVX, - VK_OBJECT_ENTRY_TYPE_RANGE_SIZE_NVX = (VK_OBJECT_ENTRY_TYPE_PUSH_CONSTANT_NVX - VK_OBJECT_ENTRY_TYPE_DESCRIPTOR_SET_NVX + 1), - VK_OBJECT_ENTRY_TYPE_MAX_ENUM_NVX = 0x7FFFFFFF -} VkObjectEntryTypeNVX; - - -typedef enum VkIndirectCommandsLayoutUsageFlagBitsNVX { - VK_INDIRECT_COMMANDS_LAYOUT_USAGE_UNORDERED_SEQUENCES_BIT_NVX = 0x00000001, - VK_INDIRECT_COMMANDS_LAYOUT_USAGE_SPARSE_SEQUENCES_BIT_NVX = 0x00000002, - VK_INDIRECT_COMMANDS_LAYOUT_USAGE_EMPTY_EXECUTIONS_BIT_NVX = 0x00000004, - VK_INDIRECT_COMMANDS_LAYOUT_USAGE_INDEXED_SEQUENCES_BIT_NVX = 0x00000008, - VK_INDIRECT_COMMANDS_LAYOUT_USAGE_FLAG_BITS_MAX_ENUM_NVX = 0x7FFFFFFF -} VkIndirectCommandsLayoutUsageFlagBitsNVX; -typedef VkFlags VkIndirectCommandsLayoutUsageFlagsNVX; - -typedef enum VkObjectEntryUsageFlagBitsNVX { - VK_OBJECT_ENTRY_USAGE_GRAPHICS_BIT_NVX = 0x00000001, - VK_OBJECT_ENTRY_USAGE_COMPUTE_BIT_NVX = 0x00000002, - VK_OBJECT_ENTRY_USAGE_FLAG_BITS_MAX_ENUM_NVX = 0x7FFFFFFF -} VkObjectEntryUsageFlagBitsNVX; -typedef VkFlags VkObjectEntryUsageFlagsNVX; - -typedef struct VkDeviceGeneratedCommandsFeaturesNVX { - VkStructureType sType; - const void* pNext; - VkBool32 computeBindingPointSupport; -} VkDeviceGeneratedCommandsFeaturesNVX; - -typedef struct VkDeviceGeneratedCommandsLimitsNVX { - VkStructureType sType; - const void* pNext; - uint32_t maxIndirectCommandsLayoutTokenCount; - uint32_t maxObjectEntryCounts; - uint32_t minSequenceCountBufferOffsetAlignment; - uint32_t minSequenceIndexBufferOffsetAlignment; - uint32_t minCommandsTokenBufferOffsetAlignment; -} VkDeviceGeneratedCommandsLimitsNVX; - -typedef struct VkIndirectCommandsTokenNVX { - VkIndirectCommandsTokenTypeNVX tokenType; - VkBuffer buffer; - VkDeviceSize offset; -} VkIndirectCommandsTokenNVX; - -typedef struct VkIndirectCommandsLayoutTokenNVX { - VkIndirectCommandsTokenTypeNVX tokenType; - uint32_t bindingUnit; - uint32_t dynamicCount; - uint32_t divisor; -} VkIndirectCommandsLayoutTokenNVX; - -typedef struct VkIndirectCommandsLayoutCreateInfoNVX { - VkStructureType sType; - const void* pNext; - VkPipelineBindPoint pipelineBindPoint; - VkIndirectCommandsLayoutUsageFlagsNVX flags; - uint32_t tokenCount; - const VkIndirectCommandsLayoutTokenNVX* pTokens; -} VkIndirectCommandsLayoutCreateInfoNVX; - -typedef struct VkCmdProcessCommandsInfoNVX { - VkStructureType sType; - const void* pNext; - VkObjectTableNVX objectTable; - VkIndirectCommandsLayoutNVX indirectCommandsLayout; - uint32_t indirectCommandsTokenCount; - const VkIndirectCommandsTokenNVX* pIndirectCommandsTokens; - uint32_t maxSequencesCount; - VkCommandBuffer targetCommandBuffer; - VkBuffer sequencesCountBuffer; - VkDeviceSize sequencesCountOffset; - VkBuffer sequencesIndexBuffer; - VkDeviceSize sequencesIndexOffset; -} VkCmdProcessCommandsInfoNVX; - -typedef struct VkCmdReserveSpaceForCommandsInfoNVX { - VkStructureType sType; - const void* pNext; - VkObjectTableNVX objectTable; - VkIndirectCommandsLayoutNVX indirectCommandsLayout; - uint32_t maxSequencesCount; -} VkCmdReserveSpaceForCommandsInfoNVX; - -typedef struct VkObjectTableCreateInfoNVX { - VkStructureType sType; - const void* pNext; - uint32_t objectCount; - const VkObjectEntryTypeNVX* pObjectEntryTypes; - const uint32_t* pObjectEntryCounts; - const VkObjectEntryUsageFlagsNVX* pObjectEntryUsageFlags; - uint32_t maxUniformBuffersPerDescriptor; - uint32_t maxStorageBuffersPerDescriptor; - uint32_t maxStorageImagesPerDescriptor; - uint32_t maxSampledImagesPerDescriptor; - uint32_t maxPipelineLayouts; -} VkObjectTableCreateInfoNVX; - -typedef struct VkObjectTableEntryNVX { - VkObjectEntryTypeNVX type; - VkObjectEntryUsageFlagsNVX flags; -} VkObjectTableEntryNVX; - -typedef struct VkObjectTablePipelineEntryNVX { - VkObjectEntryTypeNVX type; - VkObjectEntryUsageFlagsNVX flags; - VkPipeline pipeline; -} VkObjectTablePipelineEntryNVX; - -typedef struct VkObjectTableDescriptorSetEntryNVX { - VkObjectEntryTypeNVX type; - VkObjectEntryUsageFlagsNVX flags; - VkPipelineLayout pipelineLayout; - VkDescriptorSet descriptorSet; -} VkObjectTableDescriptorSetEntryNVX; - -typedef struct VkObjectTableVertexBufferEntryNVX { - VkObjectEntryTypeNVX type; - VkObjectEntryUsageFlagsNVX flags; - VkBuffer buffer; -} VkObjectTableVertexBufferEntryNVX; - -typedef struct VkObjectTableIndexBufferEntryNVX { - VkObjectEntryTypeNVX type; - VkObjectEntryUsageFlagsNVX flags; - VkBuffer buffer; - VkIndexType indexType; -} VkObjectTableIndexBufferEntryNVX; - -typedef struct VkObjectTablePushConstantEntryNVX { - VkObjectEntryTypeNVX type; - VkObjectEntryUsageFlagsNVX flags; - VkPipelineLayout pipelineLayout; - VkShaderStageFlags stageFlags; -} VkObjectTablePushConstantEntryNVX; - - -typedef void (VKAPI_PTR *PFN_vkCmdProcessCommandsNVX)(VkCommandBuffer commandBuffer, const VkCmdProcessCommandsInfoNVX* pProcessCommandsInfo); -typedef void (VKAPI_PTR *PFN_vkCmdReserveSpaceForCommandsNVX)(VkCommandBuffer commandBuffer, const VkCmdReserveSpaceForCommandsInfoNVX* pReserveSpaceInfo); -typedef VkResult (VKAPI_PTR *PFN_vkCreateIndirectCommandsLayoutNVX)(VkDevice device, const VkIndirectCommandsLayoutCreateInfoNVX* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkIndirectCommandsLayoutNVX* pIndirectCommandsLayout); -typedef void (VKAPI_PTR *PFN_vkDestroyIndirectCommandsLayoutNVX)(VkDevice device, VkIndirectCommandsLayoutNVX indirectCommandsLayout, const VkAllocationCallbacks* pAllocator); -typedef VkResult (VKAPI_PTR *PFN_vkCreateObjectTableNVX)(VkDevice device, const VkObjectTableCreateInfoNVX* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkObjectTableNVX* pObjectTable); -typedef void (VKAPI_PTR *PFN_vkDestroyObjectTableNVX)(VkDevice device, VkObjectTableNVX objectTable, const VkAllocationCallbacks* pAllocator); -typedef VkResult (VKAPI_PTR *PFN_vkRegisterObjectsNVX)(VkDevice device, VkObjectTableNVX objectTable, uint32_t objectCount, const VkObjectTableEntryNVX* const* ppObjectTableEntries, const uint32_t* pObjectIndices); -typedef VkResult (VKAPI_PTR *PFN_vkUnregisterObjectsNVX)(VkDevice device, VkObjectTableNVX objectTable, uint32_t objectCount, const VkObjectEntryTypeNVX* pObjectEntryTypes, const uint32_t* pObjectIndices); -typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceGeneratedCommandsPropertiesNVX)(VkPhysicalDevice physicalDevice, VkDeviceGeneratedCommandsFeaturesNVX* pFeatures, VkDeviceGeneratedCommandsLimitsNVX* pLimits); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR void VKAPI_CALL vkCmdProcessCommandsNVX( - VkCommandBuffer commandBuffer, - const VkCmdProcessCommandsInfoNVX* pProcessCommandsInfo); - -VKAPI_ATTR void VKAPI_CALL vkCmdReserveSpaceForCommandsNVX( - VkCommandBuffer commandBuffer, - const VkCmdReserveSpaceForCommandsInfoNVX* pReserveSpaceInfo); - -VKAPI_ATTR VkResult VKAPI_CALL vkCreateIndirectCommandsLayoutNVX( - VkDevice device, - const VkIndirectCommandsLayoutCreateInfoNVX* pCreateInfo, - const VkAllocationCallbacks* pAllocator, - VkIndirectCommandsLayoutNVX* pIndirectCommandsLayout); - -VKAPI_ATTR void VKAPI_CALL vkDestroyIndirectCommandsLayoutNVX( - VkDevice device, - VkIndirectCommandsLayoutNVX indirectCommandsLayout, - const VkAllocationCallbacks* pAllocator); - -VKAPI_ATTR VkResult VKAPI_CALL vkCreateObjectTableNVX( - VkDevice device, - const VkObjectTableCreateInfoNVX* pCreateInfo, - const VkAllocationCallbacks* pAllocator, - VkObjectTableNVX* pObjectTable); - -VKAPI_ATTR void VKAPI_CALL vkDestroyObjectTableNVX( - VkDevice device, - VkObjectTableNVX objectTable, - const VkAllocationCallbacks* pAllocator); - -VKAPI_ATTR VkResult VKAPI_CALL vkRegisterObjectsNVX( - VkDevice device, - VkObjectTableNVX objectTable, - uint32_t objectCount, - const VkObjectTableEntryNVX* const* ppObjectTableEntries, - const uint32_t* pObjectIndices); - -VKAPI_ATTR VkResult VKAPI_CALL vkUnregisterObjectsNVX( - VkDevice device, - VkObjectTableNVX objectTable, - uint32_t objectCount, - const VkObjectEntryTypeNVX* pObjectEntryTypes, - const uint32_t* pObjectIndices); - -VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceGeneratedCommandsPropertiesNVX( - VkPhysicalDevice physicalDevice, - VkDeviceGeneratedCommandsFeaturesNVX* pFeatures, - VkDeviceGeneratedCommandsLimitsNVX* pLimits); -#endif - -#define VK_NV_clip_space_w_scaling 1 -#define VK_NV_CLIP_SPACE_W_SCALING_SPEC_VERSION 1 -#define VK_NV_CLIP_SPACE_W_SCALING_EXTENSION_NAME "VK_NV_clip_space_w_scaling" - -typedef struct VkViewportWScalingNV { - float xcoeff; - float ycoeff; -} VkViewportWScalingNV; - -typedef struct VkPipelineViewportWScalingStateCreateInfoNV { - VkStructureType sType; - const void* pNext; - VkBool32 viewportWScalingEnable; - uint32_t viewportCount; - const VkViewportWScalingNV* pViewportWScalings; -} VkPipelineViewportWScalingStateCreateInfoNV; - - -typedef void (VKAPI_PTR *PFN_vkCmdSetViewportWScalingNV)(VkCommandBuffer commandBuffer, uint32_t firstViewport, uint32_t viewportCount, const VkViewportWScalingNV* pViewportWScalings); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR void VKAPI_CALL vkCmdSetViewportWScalingNV( - VkCommandBuffer commandBuffer, - uint32_t firstViewport, - uint32_t viewportCount, - const VkViewportWScalingNV* pViewportWScalings); -#endif - -#define VK_EXT_direct_mode_display 1 -#define VK_EXT_DIRECT_MODE_DISPLAY_SPEC_VERSION 1 -#define VK_EXT_DIRECT_MODE_DISPLAY_EXTENSION_NAME "VK_EXT_direct_mode_display" - -typedef VkResult (VKAPI_PTR *PFN_vkReleaseDisplayEXT)(VkPhysicalDevice physicalDevice, VkDisplayKHR display); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR VkResult VKAPI_CALL vkReleaseDisplayEXT( - VkPhysicalDevice physicalDevice, - VkDisplayKHR display); -#endif - -#define VK_EXT_display_surface_counter 1 -#define VK_EXT_DISPLAY_SURFACE_COUNTER_SPEC_VERSION 1 -#define VK_EXT_DISPLAY_SURFACE_COUNTER_EXTENSION_NAME "VK_EXT_display_surface_counter" -#define VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES2_EXT VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_EXT - - -typedef enum VkSurfaceCounterFlagBitsEXT { - VK_SURFACE_COUNTER_VBLANK_EXT = 0x00000001, - VK_SURFACE_COUNTER_FLAG_BITS_MAX_ENUM_EXT = 0x7FFFFFFF -} VkSurfaceCounterFlagBitsEXT; -typedef VkFlags VkSurfaceCounterFlagsEXT; - -typedef struct VkSurfaceCapabilities2EXT { - VkStructureType sType; - void* pNext; - uint32_t minImageCount; - uint32_t maxImageCount; - VkExtent2D currentExtent; - VkExtent2D minImageExtent; - VkExtent2D maxImageExtent; - uint32_t maxImageArrayLayers; - VkSurfaceTransformFlagsKHR supportedTransforms; - VkSurfaceTransformFlagBitsKHR currentTransform; - VkCompositeAlphaFlagsKHR supportedCompositeAlpha; - VkImageUsageFlags supportedUsageFlags; - VkSurfaceCounterFlagsEXT supportedSurfaceCounters; -} VkSurfaceCapabilities2EXT; - - -typedef VkResult (VKAPI_PTR *PFN_vkGetPhysicalDeviceSurfaceCapabilities2EXT)(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface, VkSurfaceCapabilities2EXT* pSurfaceCapabilities); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR VkResult VKAPI_CALL vkGetPhysicalDeviceSurfaceCapabilities2EXT( - VkPhysicalDevice physicalDevice, - VkSurfaceKHR surface, - VkSurfaceCapabilities2EXT* pSurfaceCapabilities); -#endif - -#define VK_EXT_display_control 1 -#define VK_EXT_DISPLAY_CONTROL_SPEC_VERSION 1 -#define VK_EXT_DISPLAY_CONTROL_EXTENSION_NAME "VK_EXT_display_control" - - -typedef enum VkDisplayPowerStateEXT { - VK_DISPLAY_POWER_STATE_OFF_EXT = 0, - VK_DISPLAY_POWER_STATE_SUSPEND_EXT = 1, - VK_DISPLAY_POWER_STATE_ON_EXT = 2, - VK_DISPLAY_POWER_STATE_BEGIN_RANGE_EXT = VK_DISPLAY_POWER_STATE_OFF_EXT, - VK_DISPLAY_POWER_STATE_END_RANGE_EXT = VK_DISPLAY_POWER_STATE_ON_EXT, - VK_DISPLAY_POWER_STATE_RANGE_SIZE_EXT = (VK_DISPLAY_POWER_STATE_ON_EXT - VK_DISPLAY_POWER_STATE_OFF_EXT + 1), - VK_DISPLAY_POWER_STATE_MAX_ENUM_EXT = 0x7FFFFFFF -} VkDisplayPowerStateEXT; - -typedef enum VkDeviceEventTypeEXT { - VK_DEVICE_EVENT_TYPE_DISPLAY_HOTPLUG_EXT = 0, - VK_DEVICE_EVENT_TYPE_BEGIN_RANGE_EXT = VK_DEVICE_EVENT_TYPE_DISPLAY_HOTPLUG_EXT, - VK_DEVICE_EVENT_TYPE_END_RANGE_EXT = VK_DEVICE_EVENT_TYPE_DISPLAY_HOTPLUG_EXT, - VK_DEVICE_EVENT_TYPE_RANGE_SIZE_EXT = (VK_DEVICE_EVENT_TYPE_DISPLAY_HOTPLUG_EXT - VK_DEVICE_EVENT_TYPE_DISPLAY_HOTPLUG_EXT + 1), - VK_DEVICE_EVENT_TYPE_MAX_ENUM_EXT = 0x7FFFFFFF -} VkDeviceEventTypeEXT; - -typedef enum VkDisplayEventTypeEXT { - VK_DISPLAY_EVENT_TYPE_FIRST_PIXEL_OUT_EXT = 0, - VK_DISPLAY_EVENT_TYPE_BEGIN_RANGE_EXT = VK_DISPLAY_EVENT_TYPE_FIRST_PIXEL_OUT_EXT, - VK_DISPLAY_EVENT_TYPE_END_RANGE_EXT = VK_DISPLAY_EVENT_TYPE_FIRST_PIXEL_OUT_EXT, - VK_DISPLAY_EVENT_TYPE_RANGE_SIZE_EXT = (VK_DISPLAY_EVENT_TYPE_FIRST_PIXEL_OUT_EXT - VK_DISPLAY_EVENT_TYPE_FIRST_PIXEL_OUT_EXT + 1), - VK_DISPLAY_EVENT_TYPE_MAX_ENUM_EXT = 0x7FFFFFFF -} VkDisplayEventTypeEXT; - -typedef struct VkDisplayPowerInfoEXT { - VkStructureType sType; - const void* pNext; - VkDisplayPowerStateEXT powerState; -} VkDisplayPowerInfoEXT; - -typedef struct VkDeviceEventInfoEXT { - VkStructureType sType; - const void* pNext; - VkDeviceEventTypeEXT deviceEvent; -} VkDeviceEventInfoEXT; - -typedef struct VkDisplayEventInfoEXT { - VkStructureType sType; - const void* pNext; - VkDisplayEventTypeEXT displayEvent; -} VkDisplayEventInfoEXT; - -typedef struct VkSwapchainCounterCreateInfoEXT { - VkStructureType sType; - const void* pNext; - VkSurfaceCounterFlagsEXT surfaceCounters; -} VkSwapchainCounterCreateInfoEXT; - - -typedef VkResult (VKAPI_PTR *PFN_vkDisplayPowerControlEXT)(VkDevice device, VkDisplayKHR display, const VkDisplayPowerInfoEXT* pDisplayPowerInfo); -typedef VkResult (VKAPI_PTR *PFN_vkRegisterDeviceEventEXT)(VkDevice device, const VkDeviceEventInfoEXT* pDeviceEventInfo, const VkAllocationCallbacks* pAllocator, VkFence* pFence); -typedef VkResult (VKAPI_PTR *PFN_vkRegisterDisplayEventEXT)(VkDevice device, VkDisplayKHR display, const VkDisplayEventInfoEXT* pDisplayEventInfo, const VkAllocationCallbacks* pAllocator, VkFence* pFence); -typedef VkResult (VKAPI_PTR *PFN_vkGetSwapchainCounterEXT)(VkDevice device, VkSwapchainKHR swapchain, VkSurfaceCounterFlagBitsEXT counter, uint64_t* pCounterValue); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR VkResult VKAPI_CALL vkDisplayPowerControlEXT( - VkDevice device, - VkDisplayKHR display, - const VkDisplayPowerInfoEXT* pDisplayPowerInfo); - -VKAPI_ATTR VkResult VKAPI_CALL vkRegisterDeviceEventEXT( - VkDevice device, - const VkDeviceEventInfoEXT* pDeviceEventInfo, - const VkAllocationCallbacks* pAllocator, - VkFence* pFence); - -VKAPI_ATTR VkResult VKAPI_CALL vkRegisterDisplayEventEXT( - VkDevice device, - VkDisplayKHR display, - const VkDisplayEventInfoEXT* pDisplayEventInfo, - const VkAllocationCallbacks* pAllocator, - VkFence* pFence); - -VKAPI_ATTR VkResult VKAPI_CALL vkGetSwapchainCounterEXT( - VkDevice device, - VkSwapchainKHR swapchain, - VkSurfaceCounterFlagBitsEXT counter, - uint64_t* pCounterValue); -#endif - -#define VK_GOOGLE_display_timing 1 -#define VK_GOOGLE_DISPLAY_TIMING_SPEC_VERSION 1 -#define VK_GOOGLE_DISPLAY_TIMING_EXTENSION_NAME "VK_GOOGLE_display_timing" - -typedef struct VkRefreshCycleDurationGOOGLE { - uint64_t refreshDuration; -} VkRefreshCycleDurationGOOGLE; - -typedef struct VkPastPresentationTimingGOOGLE { - uint32_t presentID; - uint64_t desiredPresentTime; - uint64_t actualPresentTime; - uint64_t earliestPresentTime; - uint64_t presentMargin; -} VkPastPresentationTimingGOOGLE; - -typedef struct VkPresentTimeGOOGLE { - uint32_t presentID; - uint64_t desiredPresentTime; -} VkPresentTimeGOOGLE; - -typedef struct VkPresentTimesInfoGOOGLE { - VkStructureType sType; - const void* pNext; - uint32_t swapchainCount; - const VkPresentTimeGOOGLE* pTimes; -} VkPresentTimesInfoGOOGLE; - - -typedef VkResult (VKAPI_PTR *PFN_vkGetRefreshCycleDurationGOOGLE)(VkDevice device, VkSwapchainKHR swapchain, VkRefreshCycleDurationGOOGLE* pDisplayTimingProperties); -typedef VkResult (VKAPI_PTR *PFN_vkGetPastPresentationTimingGOOGLE)(VkDevice device, VkSwapchainKHR swapchain, uint32_t* pPresentationTimingCount, VkPastPresentationTimingGOOGLE* pPresentationTimings); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR VkResult VKAPI_CALL vkGetRefreshCycleDurationGOOGLE( - VkDevice device, - VkSwapchainKHR swapchain, - VkRefreshCycleDurationGOOGLE* pDisplayTimingProperties); - -VKAPI_ATTR VkResult VKAPI_CALL vkGetPastPresentationTimingGOOGLE( - VkDevice device, - VkSwapchainKHR swapchain, - uint32_t* pPresentationTimingCount, - VkPastPresentationTimingGOOGLE* pPresentationTimings); -#endif - -#define VK_NV_sample_mask_override_coverage 1 -#define VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_SPEC_VERSION 1 -#define VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME "VK_NV_sample_mask_override_coverage" - - -#define VK_NV_geometry_shader_passthrough 1 -#define VK_NV_GEOMETRY_SHADER_PASSTHROUGH_SPEC_VERSION 1 -#define VK_NV_GEOMETRY_SHADER_PASSTHROUGH_EXTENSION_NAME "VK_NV_geometry_shader_passthrough" - - -#define VK_NV_viewport_array2 1 -#define VK_NV_VIEWPORT_ARRAY2_SPEC_VERSION 1 -#define VK_NV_VIEWPORT_ARRAY2_EXTENSION_NAME "VK_NV_viewport_array2" - - -#define VK_NVX_multiview_per_view_attributes 1 -#define VK_NVX_MULTIVIEW_PER_VIEW_ATTRIBUTES_SPEC_VERSION 1 -#define VK_NVX_MULTIVIEW_PER_VIEW_ATTRIBUTES_EXTENSION_NAME "VK_NVX_multiview_per_view_attributes" - -typedef struct VkPhysicalDeviceMultiviewPerViewAttributesPropertiesNVX { - VkStructureType sType; - void* pNext; - VkBool32 perViewPositionAllComponents; -} VkPhysicalDeviceMultiviewPerViewAttributesPropertiesNVX; - - - -#define VK_NV_viewport_swizzle 1 -#define VK_NV_VIEWPORT_SWIZZLE_SPEC_VERSION 1 -#define VK_NV_VIEWPORT_SWIZZLE_EXTENSION_NAME "VK_NV_viewport_swizzle" - - -typedef enum VkViewportCoordinateSwizzleNV { - VK_VIEWPORT_COORDINATE_SWIZZLE_POSITIVE_X_NV = 0, - VK_VIEWPORT_COORDINATE_SWIZZLE_NEGATIVE_X_NV = 1, - VK_VIEWPORT_COORDINATE_SWIZZLE_POSITIVE_Y_NV = 2, - VK_VIEWPORT_COORDINATE_SWIZZLE_NEGATIVE_Y_NV = 3, - VK_VIEWPORT_COORDINATE_SWIZZLE_POSITIVE_Z_NV = 4, - VK_VIEWPORT_COORDINATE_SWIZZLE_NEGATIVE_Z_NV = 5, - VK_VIEWPORT_COORDINATE_SWIZZLE_POSITIVE_W_NV = 6, - VK_VIEWPORT_COORDINATE_SWIZZLE_NEGATIVE_W_NV = 7, - VK_VIEWPORT_COORDINATE_SWIZZLE_BEGIN_RANGE_NV = VK_VIEWPORT_COORDINATE_SWIZZLE_POSITIVE_X_NV, - VK_VIEWPORT_COORDINATE_SWIZZLE_END_RANGE_NV = VK_VIEWPORT_COORDINATE_SWIZZLE_NEGATIVE_W_NV, - VK_VIEWPORT_COORDINATE_SWIZZLE_RANGE_SIZE_NV = (VK_VIEWPORT_COORDINATE_SWIZZLE_NEGATIVE_W_NV - VK_VIEWPORT_COORDINATE_SWIZZLE_POSITIVE_X_NV + 1), - VK_VIEWPORT_COORDINATE_SWIZZLE_MAX_ENUM_NV = 0x7FFFFFFF -} VkViewportCoordinateSwizzleNV; - -typedef VkFlags VkPipelineViewportSwizzleStateCreateFlagsNV; - -typedef struct VkViewportSwizzleNV { - VkViewportCoordinateSwizzleNV x; - VkViewportCoordinateSwizzleNV y; - VkViewportCoordinateSwizzleNV z; - VkViewportCoordinateSwizzleNV w; -} VkViewportSwizzleNV; - -typedef struct VkPipelineViewportSwizzleStateCreateInfoNV { - VkStructureType sType; - const void* pNext; - VkPipelineViewportSwizzleStateCreateFlagsNV flags; - uint32_t viewportCount; - const VkViewportSwizzleNV* pViewportSwizzles; -} VkPipelineViewportSwizzleStateCreateInfoNV; - - - -#define VK_EXT_discard_rectangles 1 -#define VK_EXT_DISCARD_RECTANGLES_SPEC_VERSION 1 -#define VK_EXT_DISCARD_RECTANGLES_EXTENSION_NAME "VK_EXT_discard_rectangles" - - -typedef enum VkDiscardRectangleModeEXT { - VK_DISCARD_RECTANGLE_MODE_INCLUSIVE_EXT = 0, - VK_DISCARD_RECTANGLE_MODE_EXCLUSIVE_EXT = 1, - VK_DISCARD_RECTANGLE_MODE_BEGIN_RANGE_EXT = VK_DISCARD_RECTANGLE_MODE_INCLUSIVE_EXT, - VK_DISCARD_RECTANGLE_MODE_END_RANGE_EXT = VK_DISCARD_RECTANGLE_MODE_EXCLUSIVE_EXT, - VK_DISCARD_RECTANGLE_MODE_RANGE_SIZE_EXT = (VK_DISCARD_RECTANGLE_MODE_EXCLUSIVE_EXT - VK_DISCARD_RECTANGLE_MODE_INCLUSIVE_EXT + 1), - VK_DISCARD_RECTANGLE_MODE_MAX_ENUM_EXT = 0x7FFFFFFF -} VkDiscardRectangleModeEXT; - -typedef VkFlags VkPipelineDiscardRectangleStateCreateFlagsEXT; - -typedef struct VkPhysicalDeviceDiscardRectanglePropertiesEXT { - VkStructureType sType; - void* pNext; - uint32_t maxDiscardRectangles; -} VkPhysicalDeviceDiscardRectanglePropertiesEXT; - -typedef struct VkPipelineDiscardRectangleStateCreateInfoEXT { - VkStructureType sType; - const void* pNext; - VkPipelineDiscardRectangleStateCreateFlagsEXT flags; - VkDiscardRectangleModeEXT discardRectangleMode; - uint32_t discardRectangleCount; - const VkRect2D* pDiscardRectangles; -} VkPipelineDiscardRectangleStateCreateInfoEXT; - - -typedef void (VKAPI_PTR *PFN_vkCmdSetDiscardRectangleEXT)(VkCommandBuffer commandBuffer, uint32_t firstDiscardRectangle, uint32_t discardRectangleCount, const VkRect2D* pDiscardRectangles); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR void VKAPI_CALL vkCmdSetDiscardRectangleEXT( - VkCommandBuffer commandBuffer, - uint32_t firstDiscardRectangle, - uint32_t discardRectangleCount, - const VkRect2D* pDiscardRectangles); -#endif - -#define VK_EXT_conservative_rasterization 1 -#define VK_EXT_CONSERVATIVE_RASTERIZATION_SPEC_VERSION 1 -#define VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME "VK_EXT_conservative_rasterization" - - -typedef enum VkConservativeRasterizationModeEXT { - VK_CONSERVATIVE_RASTERIZATION_MODE_DISABLED_EXT = 0, - VK_CONSERVATIVE_RASTERIZATION_MODE_OVERESTIMATE_EXT = 1, - VK_CONSERVATIVE_RASTERIZATION_MODE_UNDERESTIMATE_EXT = 2, - VK_CONSERVATIVE_RASTERIZATION_MODE_BEGIN_RANGE_EXT = VK_CONSERVATIVE_RASTERIZATION_MODE_DISABLED_EXT, - VK_CONSERVATIVE_RASTERIZATION_MODE_END_RANGE_EXT = VK_CONSERVATIVE_RASTERIZATION_MODE_UNDERESTIMATE_EXT, - VK_CONSERVATIVE_RASTERIZATION_MODE_RANGE_SIZE_EXT = (VK_CONSERVATIVE_RASTERIZATION_MODE_UNDERESTIMATE_EXT - VK_CONSERVATIVE_RASTERIZATION_MODE_DISABLED_EXT + 1), - VK_CONSERVATIVE_RASTERIZATION_MODE_MAX_ENUM_EXT = 0x7FFFFFFF -} VkConservativeRasterizationModeEXT; - -typedef VkFlags VkPipelineRasterizationConservativeStateCreateFlagsEXT; - -typedef struct VkPhysicalDeviceConservativeRasterizationPropertiesEXT { - VkStructureType sType; - void* pNext; - float primitiveOverestimationSize; - float maxExtraPrimitiveOverestimationSize; - float extraPrimitiveOverestimationSizeGranularity; - VkBool32 primitiveUnderestimation; - VkBool32 conservativePointAndLineRasterization; - VkBool32 degenerateTrianglesRasterized; - VkBool32 degenerateLinesRasterized; - VkBool32 fullyCoveredFragmentShaderInputVariable; - VkBool32 conservativeRasterizationPostDepthCoverage; -} VkPhysicalDeviceConservativeRasterizationPropertiesEXT; - -typedef struct VkPipelineRasterizationConservativeStateCreateInfoEXT { - VkStructureType sType; - const void* pNext; - VkPipelineRasterizationConservativeStateCreateFlagsEXT flags; - VkConservativeRasterizationModeEXT conservativeRasterizationMode; - float extraPrimitiveOverestimationSize; -} VkPipelineRasterizationConservativeStateCreateInfoEXT; - - - -#define VK_EXT_swapchain_colorspace 1 -#define VK_EXT_SWAPCHAIN_COLOR_SPACE_SPEC_VERSION 3 -#define VK_EXT_SWAPCHAIN_COLOR_SPACE_EXTENSION_NAME "VK_EXT_swapchain_colorspace" - - -#define VK_EXT_hdr_metadata 1 -#define VK_EXT_HDR_METADATA_SPEC_VERSION 1 -#define VK_EXT_HDR_METADATA_EXTENSION_NAME "VK_EXT_hdr_metadata" - -typedef struct VkXYColorEXT { - float x; - float y; -} VkXYColorEXT; - -typedef struct VkHdrMetadataEXT { - VkStructureType sType; - const void* pNext; - VkXYColorEXT displayPrimaryRed; - VkXYColorEXT displayPrimaryGreen; - VkXYColorEXT displayPrimaryBlue; - VkXYColorEXT whitePoint; - float maxLuminance; - float minLuminance; - float maxContentLightLevel; - float maxFrameAverageLightLevel; -} VkHdrMetadataEXT; - - -typedef void (VKAPI_PTR *PFN_vkSetHdrMetadataEXT)(VkDevice device, uint32_t swapchainCount, const VkSwapchainKHR* pSwapchains, const VkHdrMetadataEXT* pMetadata); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR void VKAPI_CALL vkSetHdrMetadataEXT( - VkDevice device, - uint32_t swapchainCount, - const VkSwapchainKHR* pSwapchains, - const VkHdrMetadataEXT* pMetadata); -#endif - -#define VK_EXT_external_memory_dma_buf 1 -#define VK_EXT_EXTERNAL_MEMORY_DMA_BUF_SPEC_VERSION 1 -#define VK_EXT_EXTERNAL_MEMORY_DMA_BUF_EXTENSION_NAME "VK_EXT_external_memory_dma_buf" - - -#define VK_EXT_queue_family_foreign 1 -#define VK_EXT_QUEUE_FAMILY_FOREIGN_SPEC_VERSION 1 -#define VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME "VK_EXT_queue_family_foreign" -#define VK_QUEUE_FAMILY_FOREIGN_EXT (~0U-2) - - -#define VK_EXT_debug_utils 1 -VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkDebugUtilsMessengerEXT) - -#define VK_EXT_DEBUG_UTILS_SPEC_VERSION 1 -#define VK_EXT_DEBUG_UTILS_EXTENSION_NAME "VK_EXT_debug_utils" - -typedef VkFlags VkDebugUtilsMessengerCallbackDataFlagsEXT; -typedef VkFlags VkDebugUtilsMessengerCreateFlagsEXT; - -typedef enum VkDebugUtilsMessageSeverityFlagBitsEXT { - VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT = 0x00000001, - VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT = 0x00000010, - VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT = 0x00000100, - VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT = 0x00001000, - VK_DEBUG_UTILS_MESSAGE_SEVERITY_FLAG_BITS_MAX_ENUM_EXT = 0x7FFFFFFF -} VkDebugUtilsMessageSeverityFlagBitsEXT; -typedef VkFlags VkDebugUtilsMessageSeverityFlagsEXT; - -typedef enum VkDebugUtilsMessageTypeFlagBitsEXT { - VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT = 0x00000001, - VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT = 0x00000002, - VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT = 0x00000004, - VK_DEBUG_UTILS_MESSAGE_TYPE_FLAG_BITS_MAX_ENUM_EXT = 0x7FFFFFFF -} VkDebugUtilsMessageTypeFlagBitsEXT; -typedef VkFlags VkDebugUtilsMessageTypeFlagsEXT; - -typedef struct VkDebugUtilsObjectNameInfoEXT { - VkStructureType sType; - const void* pNext; - VkObjectType objectType; - uint64_t objectHandle; - const char* pObjectName; -} VkDebugUtilsObjectNameInfoEXT; - -typedef struct VkDebugUtilsObjectTagInfoEXT { - VkStructureType sType; - const void* pNext; - VkObjectType objectType; - uint64_t objectHandle; - uint64_t tagName; - size_t tagSize; - const void* pTag; -} VkDebugUtilsObjectTagInfoEXT; - -typedef struct VkDebugUtilsLabelEXT { - VkStructureType sType; - const void* pNext; - const char* pLabelName; - float color[4]; -} VkDebugUtilsLabelEXT; - -typedef struct VkDebugUtilsMessengerCallbackDataEXT { - VkStructureType sType; - const void* pNext; - VkDebugUtilsMessengerCallbackDataFlagsEXT flags; - const char* pMessageIdName; - int32_t messageIdNumber; - const char* pMessage; - uint32_t queueLabelCount; - VkDebugUtilsLabelEXT* pQueueLabels; - uint32_t cmdBufLabelCount; - VkDebugUtilsLabelEXT* pCmdBufLabels; - uint32_t objectCount; - VkDebugUtilsObjectNameInfoEXT* pObjects; -} VkDebugUtilsMessengerCallbackDataEXT; - -typedef VkBool32 (VKAPI_PTR *PFN_vkDebugUtilsMessengerCallbackEXT)( - VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, - VkDebugUtilsMessageTypeFlagsEXT messageType, - const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData, - void* pUserData); - -typedef struct VkDebugUtilsMessengerCreateInfoEXT { - VkStructureType sType; - const void* pNext; - VkDebugUtilsMessengerCreateFlagsEXT flags; - VkDebugUtilsMessageSeverityFlagsEXT messageSeverity; - VkDebugUtilsMessageTypeFlagsEXT messageType; - PFN_vkDebugUtilsMessengerCallbackEXT pfnUserCallback; - void* pUserData; -} VkDebugUtilsMessengerCreateInfoEXT; - - -typedef VkResult (VKAPI_PTR *PFN_vkSetDebugUtilsObjectNameEXT)(VkDevice device, const VkDebugUtilsObjectNameInfoEXT* pNameInfo); -typedef VkResult (VKAPI_PTR *PFN_vkSetDebugUtilsObjectTagEXT)(VkDevice device, const VkDebugUtilsObjectTagInfoEXT* pTagInfo); -typedef void (VKAPI_PTR *PFN_vkQueueBeginDebugUtilsLabelEXT)(VkQueue queue, const VkDebugUtilsLabelEXT* pLabelInfo); -typedef void (VKAPI_PTR *PFN_vkQueueEndDebugUtilsLabelEXT)(VkQueue queue); -typedef void (VKAPI_PTR *PFN_vkQueueInsertDebugUtilsLabelEXT)(VkQueue queue, const VkDebugUtilsLabelEXT* pLabelInfo); -typedef void (VKAPI_PTR *PFN_vkCmdBeginDebugUtilsLabelEXT)(VkCommandBuffer commandBuffer, const VkDebugUtilsLabelEXT* pLabelInfo); -typedef void (VKAPI_PTR *PFN_vkCmdEndDebugUtilsLabelEXT)(VkCommandBuffer commandBuffer); -typedef void (VKAPI_PTR *PFN_vkCmdInsertDebugUtilsLabelEXT)(VkCommandBuffer commandBuffer, const VkDebugUtilsLabelEXT* pLabelInfo); -typedef VkResult (VKAPI_PTR *PFN_vkCreateDebugUtilsMessengerEXT)(VkInstance instance, const VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDebugUtilsMessengerEXT* pMessenger); -typedef void (VKAPI_PTR *PFN_vkDestroyDebugUtilsMessengerEXT)(VkInstance instance, VkDebugUtilsMessengerEXT messenger, const VkAllocationCallbacks* pAllocator); -typedef void (VKAPI_PTR *PFN_vkSubmitDebugUtilsMessageEXT)(VkInstance instance, VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, VkDebugUtilsMessageTypeFlagsEXT messageTypes, const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR VkResult VKAPI_CALL vkSetDebugUtilsObjectNameEXT( - VkDevice device, - const VkDebugUtilsObjectNameInfoEXT* pNameInfo); - -VKAPI_ATTR VkResult VKAPI_CALL vkSetDebugUtilsObjectTagEXT( - VkDevice device, - const VkDebugUtilsObjectTagInfoEXT* pTagInfo); - -VKAPI_ATTR void VKAPI_CALL vkQueueBeginDebugUtilsLabelEXT( - VkQueue queue, - const VkDebugUtilsLabelEXT* pLabelInfo); - -VKAPI_ATTR void VKAPI_CALL vkQueueEndDebugUtilsLabelEXT( - VkQueue queue); - -VKAPI_ATTR void VKAPI_CALL vkQueueInsertDebugUtilsLabelEXT( - VkQueue queue, - const VkDebugUtilsLabelEXT* pLabelInfo); - -VKAPI_ATTR void VKAPI_CALL vkCmdBeginDebugUtilsLabelEXT( - VkCommandBuffer commandBuffer, - const VkDebugUtilsLabelEXT* pLabelInfo); - -VKAPI_ATTR void VKAPI_CALL vkCmdEndDebugUtilsLabelEXT( - VkCommandBuffer commandBuffer); - -VKAPI_ATTR void VKAPI_CALL vkCmdInsertDebugUtilsLabelEXT( - VkCommandBuffer commandBuffer, - const VkDebugUtilsLabelEXT* pLabelInfo); - -VKAPI_ATTR VkResult VKAPI_CALL vkCreateDebugUtilsMessengerEXT( - VkInstance instance, - const VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo, - const VkAllocationCallbacks* pAllocator, - VkDebugUtilsMessengerEXT* pMessenger); - -VKAPI_ATTR void VKAPI_CALL vkDestroyDebugUtilsMessengerEXT( - VkInstance instance, - VkDebugUtilsMessengerEXT messenger, - const VkAllocationCallbacks* pAllocator); - -VKAPI_ATTR void VKAPI_CALL vkSubmitDebugUtilsMessageEXT( - VkInstance instance, - VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, - VkDebugUtilsMessageTypeFlagsEXT messageTypes, - const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData); -#endif - -#define VK_EXT_sampler_filter_minmax 1 -#define VK_EXT_SAMPLER_FILTER_MINMAX_SPEC_VERSION 1 -#define VK_EXT_SAMPLER_FILTER_MINMAX_EXTENSION_NAME "VK_EXT_sampler_filter_minmax" - - -typedef enum VkSamplerReductionModeEXT { - VK_SAMPLER_REDUCTION_MODE_WEIGHTED_AVERAGE_EXT = 0, - VK_SAMPLER_REDUCTION_MODE_MIN_EXT = 1, - VK_SAMPLER_REDUCTION_MODE_MAX_EXT = 2, - VK_SAMPLER_REDUCTION_MODE_BEGIN_RANGE_EXT = VK_SAMPLER_REDUCTION_MODE_WEIGHTED_AVERAGE_EXT, - VK_SAMPLER_REDUCTION_MODE_END_RANGE_EXT = VK_SAMPLER_REDUCTION_MODE_MAX_EXT, - VK_SAMPLER_REDUCTION_MODE_RANGE_SIZE_EXT = (VK_SAMPLER_REDUCTION_MODE_MAX_EXT - VK_SAMPLER_REDUCTION_MODE_WEIGHTED_AVERAGE_EXT + 1), - VK_SAMPLER_REDUCTION_MODE_MAX_ENUM_EXT = 0x7FFFFFFF -} VkSamplerReductionModeEXT; - -typedef struct VkSamplerReductionModeCreateInfoEXT { - VkStructureType sType; - const void* pNext; - VkSamplerReductionModeEXT reductionMode; -} VkSamplerReductionModeCreateInfoEXT; - -typedef struct VkPhysicalDeviceSamplerFilterMinmaxPropertiesEXT { - VkStructureType sType; - void* pNext; - VkBool32 filterMinmaxSingleComponentFormats; - VkBool32 filterMinmaxImageComponentMapping; -} VkPhysicalDeviceSamplerFilterMinmaxPropertiesEXT; - - - -#define VK_AMD_gpu_shader_int16 1 -#define VK_AMD_GPU_SHADER_INT16_SPEC_VERSION 1 -#define VK_AMD_GPU_SHADER_INT16_EXTENSION_NAME "VK_AMD_gpu_shader_int16" - - -#define VK_AMD_mixed_attachment_samples 1 -#define VK_AMD_MIXED_ATTACHMENT_SAMPLES_SPEC_VERSION 1 -#define VK_AMD_MIXED_ATTACHMENT_SAMPLES_EXTENSION_NAME "VK_AMD_mixed_attachment_samples" - - -#define VK_AMD_shader_fragment_mask 1 -#define VK_AMD_SHADER_FRAGMENT_MASK_SPEC_VERSION 1 -#define VK_AMD_SHADER_FRAGMENT_MASK_EXTENSION_NAME "VK_AMD_shader_fragment_mask" - - -#define VK_EXT_shader_stencil_export 1 -#define VK_EXT_SHADER_STENCIL_EXPORT_SPEC_VERSION 1 -#define VK_EXT_SHADER_STENCIL_EXPORT_EXTENSION_NAME "VK_EXT_shader_stencil_export" - - -#define VK_EXT_sample_locations 1 -#define VK_EXT_SAMPLE_LOCATIONS_SPEC_VERSION 1 -#define VK_EXT_SAMPLE_LOCATIONS_EXTENSION_NAME "VK_EXT_sample_locations" - -typedef struct VkSampleLocationEXT { - float x; - float y; -} VkSampleLocationEXT; - -typedef struct VkSampleLocationsInfoEXT { - VkStructureType sType; - const void* pNext; - VkSampleCountFlagBits sampleLocationsPerPixel; - VkExtent2D sampleLocationGridSize; - uint32_t sampleLocationsCount; - const VkSampleLocationEXT* pSampleLocations; -} VkSampleLocationsInfoEXT; - -typedef struct VkAttachmentSampleLocationsEXT { - uint32_t attachmentIndex; - VkSampleLocationsInfoEXT sampleLocationsInfo; -} VkAttachmentSampleLocationsEXT; - -typedef struct VkSubpassSampleLocationsEXT { - uint32_t subpassIndex; - VkSampleLocationsInfoEXT sampleLocationsInfo; -} VkSubpassSampleLocationsEXT; - -typedef struct VkRenderPassSampleLocationsBeginInfoEXT { - VkStructureType sType; - const void* pNext; - uint32_t attachmentInitialSampleLocationsCount; - const VkAttachmentSampleLocationsEXT* pAttachmentInitialSampleLocations; - uint32_t postSubpassSampleLocationsCount; - const VkSubpassSampleLocationsEXT* pPostSubpassSampleLocations; -} VkRenderPassSampleLocationsBeginInfoEXT; - -typedef struct VkPipelineSampleLocationsStateCreateInfoEXT { - VkStructureType sType; - const void* pNext; - VkBool32 sampleLocationsEnable; - VkSampleLocationsInfoEXT sampleLocationsInfo; -} VkPipelineSampleLocationsStateCreateInfoEXT; - -typedef struct VkPhysicalDeviceSampleLocationsPropertiesEXT { - VkStructureType sType; - void* pNext; - VkSampleCountFlags sampleLocationSampleCounts; - VkExtent2D maxSampleLocationGridSize; - float sampleLocationCoordinateRange[2]; - uint32_t sampleLocationSubPixelBits; - VkBool32 variableSampleLocations; -} VkPhysicalDeviceSampleLocationsPropertiesEXT; - -typedef struct VkMultisamplePropertiesEXT { - VkStructureType sType; - void* pNext; - VkExtent2D maxSampleLocationGridSize; -} VkMultisamplePropertiesEXT; - - -typedef void (VKAPI_PTR *PFN_vkCmdSetSampleLocationsEXT)(VkCommandBuffer commandBuffer, const VkSampleLocationsInfoEXT* pSampleLocationsInfo); -typedef void (VKAPI_PTR *PFN_vkGetPhysicalDeviceMultisamplePropertiesEXT)(VkPhysicalDevice physicalDevice, VkSampleCountFlagBits samples, VkMultisamplePropertiesEXT* pMultisampleProperties); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR void VKAPI_CALL vkCmdSetSampleLocationsEXT( - VkCommandBuffer commandBuffer, - const VkSampleLocationsInfoEXT* pSampleLocationsInfo); - -VKAPI_ATTR void VKAPI_CALL vkGetPhysicalDeviceMultisamplePropertiesEXT( - VkPhysicalDevice physicalDevice, - VkSampleCountFlagBits samples, - VkMultisamplePropertiesEXT* pMultisampleProperties); -#endif - -#define VK_EXT_blend_operation_advanced 1 -#define VK_EXT_BLEND_OPERATION_ADVANCED_SPEC_VERSION 2 -#define VK_EXT_BLEND_OPERATION_ADVANCED_EXTENSION_NAME "VK_EXT_blend_operation_advanced" - - -typedef enum VkBlendOverlapEXT { - VK_BLEND_OVERLAP_UNCORRELATED_EXT = 0, - VK_BLEND_OVERLAP_DISJOINT_EXT = 1, - VK_BLEND_OVERLAP_CONJOINT_EXT = 2, - VK_BLEND_OVERLAP_BEGIN_RANGE_EXT = VK_BLEND_OVERLAP_UNCORRELATED_EXT, - VK_BLEND_OVERLAP_END_RANGE_EXT = VK_BLEND_OVERLAP_CONJOINT_EXT, - VK_BLEND_OVERLAP_RANGE_SIZE_EXT = (VK_BLEND_OVERLAP_CONJOINT_EXT - VK_BLEND_OVERLAP_UNCORRELATED_EXT + 1), - VK_BLEND_OVERLAP_MAX_ENUM_EXT = 0x7FFFFFFF -} VkBlendOverlapEXT; - -typedef struct VkPhysicalDeviceBlendOperationAdvancedFeaturesEXT { - VkStructureType sType; - void* pNext; - VkBool32 advancedBlendCoherentOperations; -} VkPhysicalDeviceBlendOperationAdvancedFeaturesEXT; - -typedef struct VkPhysicalDeviceBlendOperationAdvancedPropertiesEXT { - VkStructureType sType; - void* pNext; - uint32_t advancedBlendMaxColorAttachments; - VkBool32 advancedBlendIndependentBlend; - VkBool32 advancedBlendNonPremultipliedSrcColor; - VkBool32 advancedBlendNonPremultipliedDstColor; - VkBool32 advancedBlendCorrelatedOverlap; - VkBool32 advancedBlendAllOperations; -} VkPhysicalDeviceBlendOperationAdvancedPropertiesEXT; - -typedef struct VkPipelineColorBlendAdvancedStateCreateInfoEXT { - VkStructureType sType; - const void* pNext; - VkBool32 srcPremultiplied; - VkBool32 dstPremultiplied; - VkBlendOverlapEXT blendOverlap; -} VkPipelineColorBlendAdvancedStateCreateInfoEXT; - - - -#define VK_NV_fragment_coverage_to_color 1 -#define VK_NV_FRAGMENT_COVERAGE_TO_COLOR_SPEC_VERSION 1 -#define VK_NV_FRAGMENT_COVERAGE_TO_COLOR_EXTENSION_NAME "VK_NV_fragment_coverage_to_color" - -typedef VkFlags VkPipelineCoverageToColorStateCreateFlagsNV; - -typedef struct VkPipelineCoverageToColorStateCreateInfoNV { - VkStructureType sType; - const void* pNext; - VkPipelineCoverageToColorStateCreateFlagsNV flags; - VkBool32 coverageToColorEnable; - uint32_t coverageToColorLocation; -} VkPipelineCoverageToColorStateCreateInfoNV; - - - -#define VK_NV_framebuffer_mixed_samples 1 -#define VK_NV_FRAMEBUFFER_MIXED_SAMPLES_SPEC_VERSION 1 -#define VK_NV_FRAMEBUFFER_MIXED_SAMPLES_EXTENSION_NAME "VK_NV_framebuffer_mixed_samples" - - -typedef enum VkCoverageModulationModeNV { - VK_COVERAGE_MODULATION_MODE_NONE_NV = 0, - VK_COVERAGE_MODULATION_MODE_RGB_NV = 1, - VK_COVERAGE_MODULATION_MODE_ALPHA_NV = 2, - VK_COVERAGE_MODULATION_MODE_RGBA_NV = 3, - VK_COVERAGE_MODULATION_MODE_BEGIN_RANGE_NV = VK_COVERAGE_MODULATION_MODE_NONE_NV, - VK_COVERAGE_MODULATION_MODE_END_RANGE_NV = VK_COVERAGE_MODULATION_MODE_RGBA_NV, - VK_COVERAGE_MODULATION_MODE_RANGE_SIZE_NV = (VK_COVERAGE_MODULATION_MODE_RGBA_NV - VK_COVERAGE_MODULATION_MODE_NONE_NV + 1), - VK_COVERAGE_MODULATION_MODE_MAX_ENUM_NV = 0x7FFFFFFF -} VkCoverageModulationModeNV; - -typedef VkFlags VkPipelineCoverageModulationStateCreateFlagsNV; - -typedef struct VkPipelineCoverageModulationStateCreateInfoNV { - VkStructureType sType; - const void* pNext; - VkPipelineCoverageModulationStateCreateFlagsNV flags; - VkCoverageModulationModeNV coverageModulationMode; - VkBool32 coverageModulationTableEnable; - uint32_t coverageModulationTableCount; - const float* pCoverageModulationTable; -} VkPipelineCoverageModulationStateCreateInfoNV; - - - -#define VK_NV_fill_rectangle 1 -#define VK_NV_FILL_RECTANGLE_SPEC_VERSION 1 -#define VK_NV_FILL_RECTANGLE_EXTENSION_NAME "VK_NV_fill_rectangle" - - -#define VK_EXT_post_depth_coverage 1 -#define VK_EXT_POST_DEPTH_COVERAGE_SPEC_VERSION 1 -#define VK_EXT_POST_DEPTH_COVERAGE_EXTENSION_NAME "VK_EXT_post_depth_coverage" - - -#define VK_EXT_validation_cache 1 -VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkValidationCacheEXT) - -#define VK_EXT_VALIDATION_CACHE_SPEC_VERSION 1 -#define VK_EXT_VALIDATION_CACHE_EXTENSION_NAME "VK_EXT_validation_cache" -#define VK_DEBUG_REPORT_OBJECT_TYPE_VALIDATION_CACHE_EXT VK_DEBUG_REPORT_OBJECT_TYPE_VALIDATION_CACHE_EXT_EXT - - -typedef enum VkValidationCacheHeaderVersionEXT { - VK_VALIDATION_CACHE_HEADER_VERSION_ONE_EXT = 1, - VK_VALIDATION_CACHE_HEADER_VERSION_BEGIN_RANGE_EXT = VK_VALIDATION_CACHE_HEADER_VERSION_ONE_EXT, - VK_VALIDATION_CACHE_HEADER_VERSION_END_RANGE_EXT = VK_VALIDATION_CACHE_HEADER_VERSION_ONE_EXT, - VK_VALIDATION_CACHE_HEADER_VERSION_RANGE_SIZE_EXT = (VK_VALIDATION_CACHE_HEADER_VERSION_ONE_EXT - VK_VALIDATION_CACHE_HEADER_VERSION_ONE_EXT + 1), - VK_VALIDATION_CACHE_HEADER_VERSION_MAX_ENUM_EXT = 0x7FFFFFFF -} VkValidationCacheHeaderVersionEXT; - -typedef VkFlags VkValidationCacheCreateFlagsEXT; - -typedef struct VkValidationCacheCreateInfoEXT { - VkStructureType sType; - const void* pNext; - VkValidationCacheCreateFlagsEXT flags; - size_t initialDataSize; - const void* pInitialData; -} VkValidationCacheCreateInfoEXT; - -typedef struct VkShaderModuleValidationCacheCreateInfoEXT { - VkStructureType sType; - const void* pNext; - VkValidationCacheEXT validationCache; -} VkShaderModuleValidationCacheCreateInfoEXT; - - -typedef VkResult (VKAPI_PTR *PFN_vkCreateValidationCacheEXT)(VkDevice device, const VkValidationCacheCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkValidationCacheEXT* pValidationCache); -typedef void (VKAPI_PTR *PFN_vkDestroyValidationCacheEXT)(VkDevice device, VkValidationCacheEXT validationCache, const VkAllocationCallbacks* pAllocator); -typedef VkResult (VKAPI_PTR *PFN_vkMergeValidationCachesEXT)(VkDevice device, VkValidationCacheEXT dstCache, uint32_t srcCacheCount, const VkValidationCacheEXT* pSrcCaches); -typedef VkResult (VKAPI_PTR *PFN_vkGetValidationCacheDataEXT)(VkDevice device, VkValidationCacheEXT validationCache, size_t* pDataSize, void* pData); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR VkResult VKAPI_CALL vkCreateValidationCacheEXT( - VkDevice device, - const VkValidationCacheCreateInfoEXT* pCreateInfo, - const VkAllocationCallbacks* pAllocator, - VkValidationCacheEXT* pValidationCache); - -VKAPI_ATTR void VKAPI_CALL vkDestroyValidationCacheEXT( - VkDevice device, - VkValidationCacheEXT validationCache, - const VkAllocationCallbacks* pAllocator); - -VKAPI_ATTR VkResult VKAPI_CALL vkMergeValidationCachesEXT( - VkDevice device, - VkValidationCacheEXT dstCache, - uint32_t srcCacheCount, - const VkValidationCacheEXT* pSrcCaches); - -VKAPI_ATTR VkResult VKAPI_CALL vkGetValidationCacheDataEXT( - VkDevice device, - VkValidationCacheEXT validationCache, - size_t* pDataSize, - void* pData); -#endif - -#define VK_EXT_shader_viewport_index_layer 1 -#define VK_EXT_SHADER_VIEWPORT_INDEX_LAYER_SPEC_VERSION 1 -#define VK_EXT_SHADER_VIEWPORT_INDEX_LAYER_EXTENSION_NAME "VK_EXT_shader_viewport_index_layer" - - -#define VK_EXT_global_priority 1 -#define VK_EXT_GLOBAL_PRIORITY_SPEC_VERSION 2 -#define VK_EXT_GLOBAL_PRIORITY_EXTENSION_NAME "VK_EXT_global_priority" - - -typedef enum VkQueueGlobalPriorityEXT { - VK_QUEUE_GLOBAL_PRIORITY_LOW_EXT = 128, - VK_QUEUE_GLOBAL_PRIORITY_MEDIUM_EXT = 256, - VK_QUEUE_GLOBAL_PRIORITY_HIGH_EXT = 512, - VK_QUEUE_GLOBAL_PRIORITY_REALTIME_EXT = 1024, - VK_QUEUE_GLOBAL_PRIORITY_BEGIN_RANGE_EXT = VK_QUEUE_GLOBAL_PRIORITY_LOW_EXT, - VK_QUEUE_GLOBAL_PRIORITY_END_RANGE_EXT = VK_QUEUE_GLOBAL_PRIORITY_REALTIME_EXT, - VK_QUEUE_GLOBAL_PRIORITY_RANGE_SIZE_EXT = (VK_QUEUE_GLOBAL_PRIORITY_REALTIME_EXT - VK_QUEUE_GLOBAL_PRIORITY_LOW_EXT + 1), - VK_QUEUE_GLOBAL_PRIORITY_MAX_ENUM_EXT = 0x7FFFFFFF -} VkQueueGlobalPriorityEXT; - -typedef struct VkDeviceQueueGlobalPriorityCreateInfoEXT { - VkStructureType sType; - const void* pNext; - VkQueueGlobalPriorityEXT globalPriority; -} VkDeviceQueueGlobalPriorityCreateInfoEXT; - - - -#define VK_EXT_external_memory_host 1 -#define VK_EXT_EXTERNAL_MEMORY_HOST_SPEC_VERSION 1 -#define VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME "VK_EXT_external_memory_host" - -typedef struct VkImportMemoryHostPointerInfoEXT { - VkStructureType sType; - const void* pNext; - VkExternalMemoryHandleTypeFlagBits handleType; - void* pHostPointer; -} VkImportMemoryHostPointerInfoEXT; - -typedef struct VkMemoryHostPointerPropertiesEXT { - VkStructureType sType; - void* pNext; - uint32_t memoryTypeBits; -} VkMemoryHostPointerPropertiesEXT; - -typedef struct VkPhysicalDeviceExternalMemoryHostPropertiesEXT { - VkStructureType sType; - void* pNext; - VkDeviceSize minImportedHostPointerAlignment; -} VkPhysicalDeviceExternalMemoryHostPropertiesEXT; - - -typedef VkResult (VKAPI_PTR *PFN_vkGetMemoryHostPointerPropertiesEXT)(VkDevice device, VkExternalMemoryHandleTypeFlagBits handleType, const void* pHostPointer, VkMemoryHostPointerPropertiesEXT* pMemoryHostPointerProperties); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR VkResult VKAPI_CALL vkGetMemoryHostPointerPropertiesEXT( - VkDevice device, - VkExternalMemoryHandleTypeFlagBits handleType, - const void* pHostPointer, - VkMemoryHostPointerPropertiesEXT* pMemoryHostPointerProperties); -#endif - -#define VK_AMD_buffer_marker 1 -#define VK_AMD_BUFFER_MARKER_SPEC_VERSION 1 -#define VK_AMD_BUFFER_MARKER_EXTENSION_NAME "VK_AMD_buffer_marker" - -typedef void (VKAPI_PTR *PFN_vkCmdWriteBufferMarkerAMD)(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage, VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker); - -#ifndef VK_NO_PROTOTYPES -VKAPI_ATTR void VKAPI_CALL vkCmdWriteBufferMarkerAMD( - VkCommandBuffer commandBuffer, - VkPipelineStageFlagBits pipelineStage, - VkBuffer dstBuffer, - VkDeviceSize dstOffset, - uint32_t marker); -#endif - -#define VK_EXT_vertex_attribute_divisor 1 -#define VK_EXT_VERTEX_ATTRIBUTE_DIVISOR_SPEC_VERSION 1 -#define VK_EXT_VERTEX_ATTRIBUTE_DIVISOR_EXTENSION_NAME "VK_EXT_vertex_attribute_divisor" - -typedef struct VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT { - VkStructureType sType; - void* pNext; - uint32_t maxVertexAttribDivisor; -} VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT; - -typedef struct VkVertexInputBindingDivisorDescriptionEXT { - uint32_t binding; - uint32_t divisor; -} VkVertexInputBindingDivisorDescriptionEXT; - -typedef struct VkPipelineVertexInputDivisorStateCreateInfoEXT { - VkStructureType sType; - const void* pNext; - uint32_t vertexBindingDivisorCount; - const VkVertexInputBindingDivisorDescriptionEXT* pVertexBindingDivisors; -} VkPipelineVertexInputDivisorStateCreateInfoEXT; - - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/src/external/glfw/include/GLFW/glfw3.h b/src/external/glfw/include/GLFW/glfw3.h index 099cd8e6..e2e3af17 100644 --- a/src/external/glfw/include/GLFW/glfw3.h +++ b/src/external/glfw/include/GLFW/glfw3.h @@ -3,7 +3,7 @@ * A library for OpenGL, window and input *------------------------------------------------------------------------ * Copyright (c) 2002-2006 Marcus Geelnard - * Copyright (c) 2006-2016 Camilla Lรถwy + * Copyright (c) 2006-2019 Camilla Lรถwy * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages @@ -266,13 +266,14 @@ extern "C" { * API changes. * @ingroup init */ -#define GLFW_VERSION_REVISION 0 +#define GLFW_VERSION_REVISION 1 /*! @} */ /*! @brief One. * * This is only semantic sugar for the number 1. You can instead use `1` or - * `true` or `_True` or `GL_TRUE` or anything else that is equal to one. + * `true` or `_True` or `GL_TRUE` or `VK_TRUE` or anything else that is equal + * to one. * * @ingroup init */ @@ -280,7 +281,8 @@ extern "C" { /*! @brief Zero. * * This is only semantic sugar for the number 0. You can instead use `0` or - * `false` or `_False` or `GL_FALSE` or anything else that is equal to zero. + * `false` or `_False` or `GL_FALSE` or `VK_FALSE` or anything else that is + * equal to zero. * * @ingroup init */ @@ -977,12 +979,25 @@ extern "C" { * [window hint](@ref GLFW_SCALE_TO_MONITOR). */ #define GLFW_SCALE_TO_MONITOR 0x0002200C - +/*! @brief macOS specific + * [window hint](@ref GLFW_COCOA_RETINA_FRAMEBUFFER_hint). + */ #define GLFW_COCOA_RETINA_FRAMEBUFFER 0x00023001 +/*! @brief macOS specific + * [window hint](@ref GLFW_COCOA_FRAME_NAME_hint). + */ #define GLFW_COCOA_FRAME_NAME 0x00023002 +/*! @brief macOS specific + * [window hint](@ref GLFW_COCOA_GRAPHICS_SWITCHING_hint). + */ #define GLFW_COCOA_GRAPHICS_SWITCHING 0x00023003 - +/*! @brief X11 specific + * [window hint](@ref GLFW_X11_CLASS_NAME_hint). + */ #define GLFW_X11_CLASS_NAME 0x00024001 +/*! @brief X11 specific + * [window hint](@ref GLFW_X11_CLASS_NAME_hint). + */ #define GLFW_X11_INSTANCE_NAME 0x00024002 /*! @} */ @@ -1002,6 +1017,7 @@ extern "C" { #define GLFW_STICKY_KEYS 0x00033002 #define GLFW_STICKY_MOUSE_BUTTONS 0x00033003 #define GLFW_LOCK_KEY_MODS 0x00033004 +#define GLFW_RAW_MOUSE_MOTION 0x00033005 #define GLFW_CURSOR_NORMAL 0x00034001 #define GLFW_CURSOR_HIDDEN 0x00034002 @@ -1062,17 +1078,17 @@ extern "C" { * @{ */ /*! @brief Joystick hat buttons init hint. * - * Joystick hat buttons [init hint](@ref GLFW_JOYSTICK_HAT_BUTTONS) + * Joystick hat buttons [init hint](@ref GLFW_JOYSTICK_HAT_BUTTONS). */ #define GLFW_JOYSTICK_HAT_BUTTONS 0x00050001 /*! @brief macOS specific init hint. * - * macOS specific [init hint](@ref GLFW_COCOA_CHDIR_RESOURCES) + * macOS specific [init hint](@ref GLFW_COCOA_CHDIR_RESOURCES_hint). */ #define GLFW_COCOA_CHDIR_RESOURCES 0x00051001 /*! @brief macOS specific init hint. * - * macOS specific [init hint](@ref GLFW_COCOA_MENUBAR) + * macOS specific [init hint](@ref GLFW_COCOA_MENUBAR_hint). */ #define GLFW_COCOA_MENUBAR 0x00051002 /*! @} */ @@ -1170,9 +1186,9 @@ typedef void (* GLFWerrorfun)(int,const char*); * * @param[in] window The window that was moved. * @param[in] xpos The new x-coordinate, in screen coordinates, of the - * upper-left corner of the client area of the window. + * upper-left corner of the content area of the window. * @param[in] ypos The new y-coordinate, in screen coordinates, of the - * upper-left corner of the client area of the window. + * upper-left corner of the content area of the window. * * @sa @ref window_pos * @sa @ref glfwSetWindowPosCallback @@ -1349,9 +1365,9 @@ typedef void (* GLFWmousebuttonfun)(GLFWwindow*,int,int,int); * * @param[in] window The window that received the event. * @param[in] xpos The new cursor x-coordinate, relative to the left edge of - * the client area. + * the content area. * @param[in] ypos The new cursor y-coordinate, relative to the top edge of the - * client area. + * content area. * * @sa @ref cursor_pos * @sa @ref glfwSetCursorPosCallback @@ -1367,7 +1383,7 @@ typedef void (* GLFWcursorposfun)(GLFWwindow*,double,double); * This is the function signature for cursor enter/leave callback functions. * * @param[in] window The window that received the event. - * @param[in] entered `GLFW_TRUE` if the cursor entered the window's client + * @param[in] entered `GLFW_TRUE` if the cursor entered the window's content * area, or `GLFW_FALSE` if it left it. * * @sa @ref cursor_enter @@ -1930,6 +1946,37 @@ GLFWAPI GLFWmonitor* glfwGetPrimaryMonitor(void); */ GLFWAPI void glfwGetMonitorPos(GLFWmonitor* monitor, int* xpos, int* ypos); +/*! @brief Retrives the work area of the monitor. + * + * This function returns the position, in screen coordinates, of the upper-left + * corner of the work area of the specified monitor along with the work area + * size in screen coordinates. The work area is defined as the area of the + * monitor not occluded by the operating system task bar where present. If no + * task bar exists then the work area is the monitor resolution in screen + * coordinates. + * + * Any or all of the position and size arguments may be `NULL`. If an error + * occurs, all non-`NULL` position and size arguments will be set to zero. + * + * @param[in] monitor The monitor to query. + * @param[out] xpos Where to store the monitor x-coordinate, or `NULL`. + * @param[out] ypos Where to store the monitor y-coordinate, or `NULL`. + * @param[out] width Where to store the monitor width, or `NULL`. + * @param[out] height Where to store the monitor height, or `NULL`. + * + * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref + * GLFW_PLATFORM_ERROR. + * + * @thread_safety This function must only be called from the main thread. + * + * @sa @ref monitor_workarea + * + * @since Added in version 3.3. + * + * @ingroup monitor + */ +GLFWAPI void glfwGetMonitorWorkarea(GLFWmonitor* monitor, int* xpos, int* ypos, int* width, int* height); + /*! @brief Returns the physical size of the monitor. * * This function returns the size, in millimetres, of the display area of the @@ -1968,9 +2015,11 @@ GLFWAPI void glfwGetMonitorPhysicalSize(GLFWmonitor* monitor, int* widthMM, int* * * This function retrieves the content scale for the specified monitor. The * content scale is the ratio between the current DPI and the platform's - * default DPI. If you scale all pixel dimensions by this scale then your - * content should appear at an appropriate size. This is especially important - * for text and any UI elements. + * default DPI. This is especially important for text and any UI elements. If + * the pixel dimensions of your UI scaled by this look appropriate on your + * machine then it should appear at a reasonable size on other machines + * regardless of their DPI and scaling settings. This relies on the system DPI + * and scaling settings being somewhat correct. * * The content scale may depend on both the monitor resolution and pixel * density and on user settings. It may be very different from the raw DPI @@ -2474,15 +2523,18 @@ GLFWAPI void glfwWindowHintString(int hint, const char* value); * @remark @x11 The class part of the `WM_CLASS` window property will by * default be set to the window title passed to this function. The instance * part will use the contents of the `RESOURCE_NAME` environment variable, if - * present and not empty, or fall back to the window title. Set the @ref - * GLFW_X11_CLASS_NAME and @ref GLFW_X11_INSTANCE_NAME window hints to override - * this. - * - * @remark @wayland The window frame is currently very simple, only allowing - * window resize or move. A compositor can still emit close, maximize or - * fullscreen events, using for example a keybind mechanism. Additionally, - * the wp_viewporter protocol is required for this feature, otherwise the - * window will not be decorated. + * present and not empty, or fall back to the window title. Set the + * [GLFW_X11_CLASS_NAME](@ref GLFW_X11_CLASS_NAME_hint) and + * [GLFW_X11_INSTANCE_NAME](@ref GLFW_X11_INSTANCE_NAME_hint) window hints to + * override this. + * + * @remark @wayland Compositors should implement the xdg-decoration protocol + * for GLFW to decorate the window properly. If this protocol isn't + * supported, or if the compositor prefers client-side decorations, a very + * simple fallback frame will be drawn using the wp_viewporter protocol. A + * compositor can still emit close, maximize or fullscreen events, using for + * instance a keybind mechanism. If neither of these protocols is supported, + * the window won't be decorated. * * @remark @wayland A full screen window will not attempt to change the mode, * no matter what the requested size or refresh rate. @@ -2644,19 +2696,19 @@ GLFWAPI void glfwSetWindowTitle(GLFWwindow* window, const char* title); */ GLFWAPI void glfwSetWindowIcon(GLFWwindow* window, int count, const GLFWimage* images); -/*! @brief Retrieves the position of the client area of the specified window. +/*! @brief Retrieves the position of the content area of the specified window. * * This function retrieves the position, in screen coordinates, of the - * upper-left corner of the client area of the specified window. + * upper-left corner of the content area of the specified window. * * Any or all of the position arguments may be `NULL`. If an error occurs, all * non-`NULL` position arguments will be set to zero. * * @param[in] window The window to query. * @param[out] xpos Where to store the x-coordinate of the upper-left corner of - * the client area, or `NULL`. + * the content area, or `NULL`. * @param[out] ypos Where to store the y-coordinate of the upper-left corner of - * the client area, or `NULL`. + * the content area, or `NULL`. * * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref * GLFW_PLATFORM_ERROR. @@ -2676,10 +2728,10 @@ GLFWAPI void glfwSetWindowIcon(GLFWwindow* window, int count, const GLFWimage* i */ GLFWAPI void glfwGetWindowPos(GLFWwindow* window, int* xpos, int* ypos); -/*! @brief Sets the position of the client area of the specified window. +/*! @brief Sets the position of the content area of the specified window. * * This function sets the position, in screen coordinates, of the upper-left - * corner of the client area of the specified windowed mode window. If the + * corner of the content area of the specified windowed mode window. If the * window is a full screen window, this function does nothing. * * __Do not use this function__ to move an already visible window unless you @@ -2689,8 +2741,8 @@ GLFWAPI void glfwGetWindowPos(GLFWwindow* window, int* xpos, int* ypos); * cannot and should not override these limits. * * @param[in] window The window to query. - * @param[in] xpos The x-coordinate of the upper-left corner of the client area. - * @param[in] ypos The y-coordinate of the upper-left corner of the client area. + * @param[in] xpos The x-coordinate of the upper-left corner of the content area. + * @param[in] ypos The y-coordinate of the upper-left corner of the content area. * * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref * GLFW_PLATFORM_ERROR. @@ -2711,9 +2763,9 @@ GLFWAPI void glfwGetWindowPos(GLFWwindow* window, int* xpos, int* ypos); */ GLFWAPI void glfwSetWindowPos(GLFWwindow* window, int xpos, int ypos); -/*! @brief Retrieves the size of the client area of the specified window. +/*! @brief Retrieves the size of the content area of the specified window. * - * This function retrieves the size, in screen coordinates, of the client area + * This function retrieves the size, in screen coordinates, of the content area * of the specified window. If you wish to retrieve the size of the * framebuffer of the window in pixels, see @ref glfwGetFramebufferSize. * @@ -2722,9 +2774,9 @@ GLFWAPI void glfwSetWindowPos(GLFWwindow* window, int xpos, int ypos); * * @param[in] window The window whose size to retrieve. * @param[out] width Where to store the width, in screen coordinates, of the - * client area, or `NULL`. + * content area, or `NULL`. * @param[out] height Where to store the height, in screen coordinates, of the - * client area, or `NULL`. + * content area, or `NULL`. * * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref * GLFW_PLATFORM_ERROR. @@ -2743,7 +2795,7 @@ GLFWAPI void glfwGetWindowSize(GLFWwindow* window, int* width, int* height); /*! @brief Sets the size limits of the specified window. * - * This function sets the size limits of the client area of the specified + * This function sets the size limits of the content area of the specified * window. If the window is full screen, the size limits only take effect * once it is made windowed. If the window is not resizable, this function * does nothing. @@ -2755,14 +2807,14 @@ GLFWAPI void glfwGetWindowSize(GLFWwindow* window, int* width, int* height); * dimensions and all must be greater than or equal to zero. * * @param[in] window The window to set limits for. - * @param[in] minwidth The minimum width, in screen coordinates, of the client + * @param[in] minwidth The minimum width, in screen coordinates, of the content * area, or `GLFW_DONT_CARE`. * @param[in] minheight The minimum height, in screen coordinates, of the - * client area, or `GLFW_DONT_CARE`. - * @param[in] maxwidth The maximum width, in screen coordinates, of the client + * content area, or `GLFW_DONT_CARE`. + * @param[in] maxwidth The maximum width, in screen coordinates, of the content * area, or `GLFW_DONT_CARE`. * @param[in] maxheight The maximum height, in screen coordinates, of the - * client area, or `GLFW_DONT_CARE`. + * content area, or `GLFW_DONT_CARE`. * * @errors Possible errors include @ref GLFW_NOT_INITIALIZED, @ref * GLFW_INVALID_VALUE and @ref GLFW_PLATFORM_ERROR. @@ -2786,7 +2838,7 @@ GLFWAPI void glfwSetWindowSizeLimits(GLFWwindow* window, int minwidth, int minhe /*! @brief Sets the aspect ratio of the specified window. * - * This function sets the required aspect ratio of the client area of the + * This function sets the required aspect ratio of the content area of the * specified window. If the window is full screen, the aspect ratio only takes * effect once it is made windowed. If the window is not resizable, this * function does nothing. @@ -2827,9 +2879,9 @@ GLFWAPI void glfwSetWindowSizeLimits(GLFWwindow* window, int minwidth, int minhe */ GLFWAPI void glfwSetWindowAspectRatio(GLFWwindow* window, int numer, int denom); -/*! @brief Sets the size of the client area of the specified window. +/*! @brief Sets the size of the content area of the specified window. * - * This function sets the size, in screen coordinates, of the client area of + * This function sets the size, in screen coordinates, of the content area of * the specified window. * * For full screen windows, this function updates the resolution of its desired @@ -2845,9 +2897,9 @@ GLFWAPI void glfwSetWindowAspectRatio(GLFWwindow* window, int numer, int denom); * * @param[in] window The window to resize. * @param[in] width The desired width, in screen coordinates, of the window - * client area. + * content area. * @param[in] height The desired height, in screen coordinates, of the window - * client area. + * content area. * * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref * GLFW_PLATFORM_ERROR. @@ -2938,9 +2990,11 @@ GLFWAPI void glfwGetWindowFrameSize(GLFWwindow* window, int* left, int* top, int * * This function retrieves the content scale for the specified window. The * content scale is the ratio between the current DPI and the platform's - * default DPI. If you scale all pixel dimensions by this scale then your - * content should appear at an appropriate size. This is especially important - * for text and any UI elements. + * default DPI. This is especially important for text and any UI elements. If + * the pixel dimensions of your UI scaled by this look appropriate on your + * machine then it should appear at a reasonable size on other machines + * regardless of their DPI and scaling settings. This relies on the system DPI + * and scaling settings being somewhat correct. * * On systems where each monitors can have its own content scale, the window * content scale will depend on which monitor the system considers the window @@ -3251,7 +3305,7 @@ GLFWAPI GLFWmonitor* glfwGetWindowMonitor(GLFWwindow* window); * The window position is ignored when setting a monitor. * * When the monitor is `NULL`, the position, width and height are used to - * place the window client area. The refresh rate is ignored when no monitor + * place the window content area. The refresh rate is ignored when no monitor * is specified. * * If you only wish to update the resolution of a full screen window or the @@ -3264,12 +3318,12 @@ GLFWAPI GLFWmonitor* glfwGetWindowMonitor(GLFWwindow* window); * @param[in] window The window whose monitor, size or video mode to set. * @param[in] monitor The desired monitor, or `NULL` to set windowed mode. * @param[in] xpos The desired x-coordinate of the upper-left corner of the - * client area. + * content area. * @param[in] ypos The desired y-coordinate of the upper-left corner of the - * client area. - * @param[in] width The desired with, in screen coordinates, of the client area - * or video mode. - * @param[in] height The desired height, in screen coordinates, of the client + * content area. + * @param[in] width The desired with, in screen coordinates, of the content + * area or video mode. + * @param[in] height The desired height, in screen coordinates, of the content * area or video mode. * @param[in] refreshRate The desired refresh rate, in Hz, of the video mode, * or `GLFW_DONT_CARE`. @@ -3419,8 +3473,8 @@ GLFWAPI void* glfwGetWindowUserPointer(GLFWwindow* window); * * This function sets the position callback of the specified window, which is * called when the window is moved. The callback is provided with the - * position, in screen coordinates, of the upper-left corner of the client area - * of the window. + * position, in screen coordinates, of the upper-left corner of the content + * area of the window. * * @param[in] window The window whose callback to set. * @param[in] cbfun The new callback, or `NULL` to remove the currently set @@ -3447,7 +3501,7 @@ GLFWAPI GLFWwindowposfun glfwSetWindowPosCallback(GLFWwindow* window, GLFWwindow * * This function sets the size callback of the specified window, which is * called when the window is resized. The callback is provided with the size, - * in screen coordinates, of the client area of the window. + * in screen coordinates, of the content area of the window. * * @param[in] window The window whose callback to set. * @param[in] cbfun The new callback, or `NULL` to remove the currently set @@ -3504,7 +3558,7 @@ GLFWAPI GLFWwindowclosefun glfwSetWindowCloseCallback(GLFWwindow* window, GLFWwi /*! @brief Sets the refresh callback for the specified window. * * This function sets the refresh callback of the specified window, which is - * called when the client area of the window needs to be redrawn, for example + * called when the content area of the window needs to be redrawn, for example * if the window has been exposed after having been covered by another window. * * On compositing window systems such as Aero, Compiz, Aqua or Wayland, where @@ -3718,10 +3772,6 @@ GLFWAPI void glfwPollEvents(void); * GLFW will pass those events on to the application callbacks before * returning. * - * If no windows exist, this function returns immediately. For synchronization - * of threads in applications that do not create windows, use your threading - * library of choice. - * * Event processing is not required for joystick input to work. * * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref @@ -3769,10 +3819,6 @@ GLFWAPI void glfwWaitEvents(void); * GLFW will pass those events on to the application callbacks before * returning. * - * If no windows exist, this function returns immediately. For synchronization - * of threads in applications that do not create windows, use your threading - * library of choice. - * * Event processing is not required for joystick input to work. * * @param[in] timeout The maximum amount of time, in seconds, to wait. @@ -3799,10 +3845,6 @@ GLFWAPI void glfwWaitEventsTimeout(double timeout); * This function posts an empty event from the current thread to the event * queue, causing @ref glfwWaitEvents or @ref glfwWaitEventsTimeout to return. * - * If no windows exist, this function returns immediately. For synchronization - * of threads in applications that do not create windows, use your threading - * library of choice. - * * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref * GLFW_PLATFORM_ERROR. * @@ -3822,11 +3864,13 @@ GLFWAPI void glfwPostEmptyEvent(void); * * This function returns the value of an input option for the specified window. * The mode must be one of @ref GLFW_CURSOR, @ref GLFW_STICKY_KEYS, - * @ref GLFW_STICKY_MOUSE_BUTTONS or @ref GLFW_LOCK_KEY_MODS. + * @ref GLFW_STICKY_MOUSE_BUTTONS, @ref GLFW_LOCK_KEY_MODS or + * @ref GLFW_RAW_MOUSE_MOTION. * * @param[in] window The window to query. * @param[in] mode One of `GLFW_CURSOR`, `GLFW_STICKY_KEYS`, - * `GLFW_STICKY_MOUSE_BUTTONS` or `GLFW_LOCK_KEY_MODS`. + * `GLFW_STICKY_MOUSE_BUTTONS`, `GLFW_LOCK_KEY_MODS` or + * `GLFW_RAW_MOUSE_MOTION`. * * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref * GLFW_INVALID_ENUM. @@ -3845,13 +3889,14 @@ GLFWAPI int glfwGetInputMode(GLFWwindow* window, int mode); * * This function sets an input mode option for the specified window. The mode * must be one of @ref GLFW_CURSOR, @ref GLFW_STICKY_KEYS, - * @ref GLFW_STICKY_MOUSE_BUTTONS or @ref GLFW_LOCK_KEY_MODS. + * @ref GLFW_STICKY_MOUSE_BUTTONS, @ref GLFW_LOCK_KEY_MODS or + * @ref GLFW_RAW_MOUSE_MOTION. * * If the mode is `GLFW_CURSOR`, the value must be one of the following cursor * modes: * - `GLFW_CURSOR_NORMAL` makes the cursor visible and behaving normally. - * - `GLFW_CURSOR_HIDDEN` makes the cursor invisible when it is over the client - * area of the window but does not restrict the cursor from leaving. + * - `GLFW_CURSOR_HIDDEN` makes the cursor invisible when it is over the + * content area of the window but does not restrict the cursor from leaving. * - `GLFW_CURSOR_DISABLED` hides and grabs the cursor, providing virtual * and unlimited cursor movement. This is useful for implementing for * example 3D camera controls. @@ -3877,9 +3922,16 @@ GLFWAPI int glfwGetInputMode(GLFWwindow* window, int mode); * GLFW_MOD_CAPS_LOCK bit set when the event was generated with Caps Lock on, * and the @ref GLFW_MOD_NUM_LOCK bit when Num Lock was on. * + * If the mode is `GLFW_RAW_MOUSE_MOTION`, the value must be either `GLFW_TRUE` + * to enable raw (unscaled and unaccelerated) mouse motion when the cursor is + * disabled, or `GLFW_FALSE` to disable it. If raw motion is not supported, + * attempting to set this will emit @ref GLFW_PLATFORM_ERROR. Call @ref + * glfwRawMouseMotionSupported to check for support. + * * @param[in] window The window whose input mode to set. * @param[in] mode One of `GLFW_CURSOR`, `GLFW_STICKY_KEYS`, - * `GLFW_STICKY_MOUSE_BUTTONS` or `GLFW_LOCK_KEY_MODS`. + * `GLFW_STICKY_MOUSE_BUTTONS`, `GLFW_LOCK_KEY_MODS` or + * `GLFW_RAW_MOUSE_MOTION`. * @param[in] value The new value of the specified input mode. * * @errors Possible errors include @ref GLFW_NOT_INITIALIZED, @ref @@ -3895,6 +3947,35 @@ GLFWAPI int glfwGetInputMode(GLFWwindow* window, int mode); */ GLFWAPI void glfwSetInputMode(GLFWwindow* window, int mode, int value); +/*! @brief Returns whether raw mouse motion is supported. + * + * This function returns whether raw mouse motion is supported on the current + * system. This status does not change after GLFW has been initialized so you + * only need to check this once. If you attempt to enable raw motion on + * a system that does not support it, @ref GLFW_PLATFORM_ERROR will be emitted. + * + * Raw mouse motion is closer to the actual motion of the mouse across + * a surface. It is not affected by the scaling and acceleration applied to + * the motion of the desktop cursor. That processing is suitable for a cursor + * while raw motion is better for controlling for example a 3D camera. Because + * of this, raw mouse motion is only provided when the cursor is disabled. + * + * @return `GLFW_TRUE` if raw mouse motion is supported on the current machine, + * or `GLFW_FALSE` otherwise. + * + * @errors Possible errors include @ref GLFW_NOT_INITIALIZED. + * + * @thread_safety This function must only be called from the main thread. + * + * @sa @ref raw_mouse_motion + * @sa @ref glfwSetInputMode + * + * @since Added in version 3.3. + * + * @ingroup input + */ +GLFWAPI int glfwRawMouseMotionSupported(void); + /*! @brief Returns the layout-specific name of the specified printable key. * * This function returns the name of the specified printable key, encoded as @@ -4054,11 +4135,11 @@ GLFWAPI int glfwGetKey(GLFWwindow* window, int key); */ GLFWAPI int glfwGetMouseButton(GLFWwindow* window, int button); -/*! @brief Retrieves the position of the cursor relative to the client area of +/*! @brief Retrieves the position of the cursor relative to the content area of * the window. * * This function returns the position of the cursor, in screen coordinates, - * relative to the upper-left corner of the client area of the specified + * relative to the upper-left corner of the content area of the specified * window. * * If the cursor is disabled (with `GLFW_CURSOR_DISABLED`) then the cursor @@ -4074,9 +4155,9 @@ GLFWAPI int glfwGetMouseButton(GLFWwindow* window, int button); * * @param[in] window The desired window. * @param[out] xpos Where to store the cursor x-coordinate, relative to the - * left edge of the client area, or `NULL`. + * left edge of the content area, or `NULL`. * @param[out] ypos Where to store the cursor y-coordinate, relative to the to - * top edge of the client area, or `NULL`. + * top edge of the content area, or `NULL`. * * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref * GLFW_PLATFORM_ERROR. @@ -4092,11 +4173,11 @@ GLFWAPI int glfwGetMouseButton(GLFWwindow* window, int button); */ GLFWAPI void glfwGetCursorPos(GLFWwindow* window, double* xpos, double* ypos); -/*! @brief Sets the position of the cursor, relative to the client area of the +/*! @brief Sets the position of the cursor, relative to the content area of the * window. * * This function sets the position, in screen coordinates, of the cursor - * relative to the upper-left corner of the client area of the specified + * relative to the upper-left corner of the content area of the specified * window. The window must have input focus. If the window does not have * input focus when this function is called, it fails silently. * @@ -4111,9 +4192,9 @@ GLFWAPI void glfwGetCursorPos(GLFWwindow* window, double* xpos, double* ypos); * * @param[in] window The desired window. * @param[in] xpos The desired x-coordinate, relative to the left edge of the - * client area. + * content area. * @param[in] ypos The desired y-coordinate, relative to the top edge of the - * client area. + * content area. * * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref * GLFW_PLATFORM_ERROR. @@ -4223,7 +4304,7 @@ GLFWAPI void glfwDestroyCursor(GLFWcursor* cursor); /*! @brief Sets the cursor for the window. * * This function sets the cursor image to be used when the cursor is over the - * client area of the specified window. The set cursor will only be visible + * content area of the specified window. The set cursor will only be visible * when the [cursor mode](@ref cursor_mode) of the window is * `GLFW_CURSOR_NORMAL`. * @@ -4396,7 +4477,7 @@ GLFWAPI GLFWmousebuttonfun glfwSetMouseButtonCallback(GLFWwindow* window, GLFWmo * This function sets the cursor position callback of the specified window, * which is called when the cursor is moved. The callback is provided with the * position, in screen coordinates, relative to the upper-left corner of the - * client area of the window. + * content area of the window. * * @param[in] window The window whose callback to set. * @param[in] cbfun The new callback, or `NULL` to remove the currently set @@ -4419,7 +4500,7 @@ GLFWAPI GLFWcursorposfun glfwSetCursorPosCallback(GLFWwindow* window, GLFWcursor /*! @brief Sets the cursor enter/exit callback. * * This function sets the cursor boundary crossing callback of the specified - * window, which is called when the cursor enters or leaves the client area of + * window, which is called when the cursor enters or leaves the content area of * the window. * * @param[in] window The window whose callback to set. diff --git a/src/external/glfw/include/GLFW/glfw3native.h b/src/external/glfw/include/GLFW/glfw3native.h index 81f48d0e..73f7ab93 100644 --- a/src/external/glfw/include/GLFW/glfw3native.h +++ b/src/external/glfw/include/GLFW/glfw3native.h @@ -3,7 +3,7 @@ * A library for OpenGL, window and input *------------------------------------------------------------------------ * Copyright (c) 2002-2006 Marcus Geelnard - * Copyright (c) 2006-2016 Camilla Lรถwy + * Copyright (c) 2006-2018 Camilla Lรถwy * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages diff --git a/src/external/glfw/src/CMakeLists.txt b/src/external/glfw/src/CMakeLists.txt index f6b4911f..a1de3ab3 100644 --- a/src/external/glfw/src/CMakeLists.txt +++ b/src/external/glfw/src/CMakeLists.txt @@ -79,7 +79,10 @@ endif() # Make GCC and Clang warn about declarations that VS 2010 and 2012 won't accept # for all source files that VS will build -if (${CMAKE_C_COMPILER_ID} STREQUAL GNU OR ${CMAKE_C_COMPILER_ID} STREQUAL Clang) +if ("${CMAKE_C_COMPILER_ID}" STREQUAL "GNU" OR + "${CMAKE_C_COMPILER_ID}" STREQUAL "Clang" OR + "${CMAKE_C_COMPILER_ID}" STREQUAL "AppleClang") + if (WIN32) set(windows_SOURCES ${glfw_SOURCES}) else() @@ -119,6 +122,7 @@ target_compile_definitions(glfw_objlib PRIVATE # Enable a reasonable set of warnings (no, -Wextra is not reasonable) target_compile_options(glfw_objlib PRIVATE + "$<$:-Wall>" "$<$:-Wall>" "$<$:-Wall>") diff --git a/src/external/glfw/src/cocoa_init.m b/src/external/glfw/src/cocoa_init.m index f3c47957..41329b37 100644 --- a/src/external/glfw/src/cocoa_init.m +++ b/src/external/glfw/src/cocoa_init.m @@ -1,7 +1,7 @@ //======================================================================== // GLFW 3.3 macOS - www.glfw.org //------------------------------------------------------------------------ -// Copyright (c) 2009-2016 Camilla Lรถwy +// Copyright (c) 2009-2019 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages @@ -27,10 +27,8 @@ #include "internal.h" #include // For MAXPATHLEN -#if MAC_OS_X_VERSION_MAX_ALLOWED < 101200 - #define NSEventMaskKeyUp NSKeyUpMask - #define NSEventModifierFlagCommand NSCommandKeyMask -#endif +// Needed for _NSGetProgname +#include // Change to our application bundle's resources directory, if present // @@ -68,6 +66,111 @@ static void changeToResourcesDirectory(void) chdir(resourcesPath); } +// Set up the menu bar (manually) +// This is nasty, nasty stuff -- calls to undocumented semi-private APIs that +// could go away at any moment, lots of stuff that really should be +// localize(d|able), etc. Add a nib to save us this horror. +// +static void createMenuBar(void) +{ + size_t i; + NSString* appName = nil; + NSDictionary* bundleInfo = [[NSBundle mainBundle] infoDictionary]; + NSString* nameKeys[] = + { + @"CFBundleDisplayName", + @"CFBundleName", + @"CFBundleExecutable", + }; + + // Try to figure out what the calling application is called + + for (i = 0; i < sizeof(nameKeys) / sizeof(nameKeys[0]); i++) + { + id name = bundleInfo[nameKeys[i]]; + if (name && + [name isKindOfClass:[NSString class]] && + ![name isEqualToString:@""]) + { + appName = name; + break; + } + } + + if (!appName) + { + char** progname = _NSGetProgname(); + if (progname && *progname) + appName = @(*progname); + else + appName = @"GLFW Application"; + } + + NSMenu* bar = [[NSMenu alloc] init]; + [NSApp setMainMenu:bar]; + + NSMenuItem* appMenuItem = + [bar addItemWithTitle:@"" action:NULL keyEquivalent:@""]; + NSMenu* appMenu = [[NSMenu alloc] init]; + [appMenuItem setSubmenu:appMenu]; + + [appMenu addItemWithTitle:[NSString stringWithFormat:@"About %@", appName] + action:@selector(orderFrontStandardAboutPanel:) + keyEquivalent:@""]; + [appMenu addItem:[NSMenuItem separatorItem]]; + NSMenu* servicesMenu = [[NSMenu alloc] init]; + [NSApp setServicesMenu:servicesMenu]; + [[appMenu addItemWithTitle:@"Services" + action:NULL + keyEquivalent:@""] setSubmenu:servicesMenu]; + [servicesMenu release]; + [appMenu addItem:[NSMenuItem separatorItem]]; + [appMenu addItemWithTitle:[NSString stringWithFormat:@"Hide %@", appName] + action:@selector(hide:) + keyEquivalent:@"h"]; + [[appMenu addItemWithTitle:@"Hide Others" + action:@selector(hideOtherApplications:) + keyEquivalent:@"h"] + setKeyEquivalentModifierMask:NSEventModifierFlagOption | NSEventModifierFlagCommand]; + [appMenu addItemWithTitle:@"Show All" + action:@selector(unhideAllApplications:) + keyEquivalent:@""]; + [appMenu addItem:[NSMenuItem separatorItem]]; + [appMenu addItemWithTitle:[NSString stringWithFormat:@"Quit %@", appName] + action:@selector(terminate:) + keyEquivalent:@"q"]; + + NSMenuItem* windowMenuItem = + [bar addItemWithTitle:@"" action:NULL keyEquivalent:@""]; + [bar release]; + NSMenu* windowMenu = [[NSMenu alloc] initWithTitle:@"Window"]; + [NSApp setWindowsMenu:windowMenu]; + [windowMenuItem setSubmenu:windowMenu]; + + [windowMenu addItemWithTitle:@"Minimize" + action:@selector(performMiniaturize:) + keyEquivalent:@"m"]; + [windowMenu addItemWithTitle:@"Zoom" + action:@selector(performZoom:) + keyEquivalent:@""]; + [windowMenu addItem:[NSMenuItem separatorItem]]; + [windowMenu addItemWithTitle:@"Bring All to Front" + action:@selector(arrangeInFront:) + keyEquivalent:@""]; + + // TODO: Make this appear at the bottom of the menu (for consistency) + [windowMenu addItem:[NSMenuItem separatorItem]]; + [[windowMenu addItemWithTitle:@"Enter Full Screen" + action:@selector(toggleFullScreen:) + keyEquivalent:@"f"] + setKeyEquivalentModifierMask:NSEventModifierFlagControl | NSEventModifierFlagCommand]; + + // Prior to Snow Leopard, we need to use this oddly-named semi-private API + // to get the application menu working properly. + SEL setAppleMenuSelector = NSSelectorFromString(@"setAppleMenu:"); + [NSApp performSelector:setAppleMenuSelector withObject:appMenu]; +} + // Create key code translation tables // static void createKeyTables(void) @@ -291,6 +394,73 @@ static GLFWbool initializeTIS(void) @end // GLFWHelper +@interface GLFWApplicationDelegate : NSObject +@end + +@implementation GLFWApplicationDelegate + +- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender +{ + _GLFWwindow* window; + + for (window = _glfw.windowListHead; window; window = window->next) + _glfwInputWindowCloseRequest(window); + + return NSTerminateCancel; +} + +- (void)applicationDidChangeScreenParameters:(NSNotification *) notification +{ + _GLFWwindow* window; + + for (window = _glfw.windowListHead; window; window = window->next) + { + if (window->context.client != GLFW_NO_API) + [window->context.nsgl.object update]; + } + + _glfwPollMonitorsNS(); +} + +- (void)applicationWillFinishLaunching:(NSNotification *)notification +{ + if (_glfw.hints.init.ns.menubar) + { + // In case we are unbundled, make us a proper UI application + [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular]; + + // Menu bar setup must go between sharedApplication above and + // finishLaunching below, in order to properly emulate the behavior + // of NSApplicationMain + + if ([[NSBundle mainBundle] pathForResource:@"MainMenu" ofType:@"nib"]) + { + [[NSBundle mainBundle] loadNibNamed:@"MainMenu" + owner:NSApp + topLevelObjects:&_glfw.ns.nibObjects]; + } + else + createMenuBar(); + } +} + +- (void)applicationDidFinishLaunching:(NSNotification *)notification +{ + [NSApp stop:nil]; + + _glfwPlatformPostEmptyEvent(); +} + +- (void)applicationDidHide:(NSNotification *)notification +{ + int i; + + for (i = 0; i < _glfw.monitorCount; i++) + _glfwRestoreVideoModeNS(_glfw.monitors[i]); +} + +@end // GLFWApplicationDelegate + ////////////////////////////////////////////////////////////////////////// ////// GLFW platform API ////// @@ -298,15 +468,29 @@ static GLFWbool initializeTIS(void) int _glfwPlatformInit(void) { - _glfw.ns.autoreleasePool = [[NSAutoreleasePool alloc] init]; + @autoreleasepool { + _glfw.ns.helper = [[GLFWHelper alloc] init]; [NSThread detachNewThreadSelector:@selector(doNothing:) toTarget:_glfw.ns.helper withObject:nil]; + if (NSApp) + _glfw.ns.finishedLaunching = GLFW_TRUE; + [NSApplication sharedApplication]; + _glfw.ns.delegate = [[GLFWApplicationDelegate alloc] init]; + if (_glfw.ns.delegate == nil) + { + _glfwInputError(GLFW_PLATFORM_ERROR, + "Cocoa: Failed to create application delegate"); + return GLFW_FALSE; + } + + [NSApp setDelegate:_glfw.ns.delegate]; + NSEvent* (^block)(NSEvent*) = ^ NSEvent* (NSEvent* event) { if ([event modifierFlags] & NSEventModifierFlagCommand) @@ -322,6 +506,10 @@ int _glfwPlatformInit(void) if (_glfw.hints.init.ns.chdir) changeToResourcesDirectory(); + // Press and Hold prevents some keys from emitting repeated characters + NSDictionary* defaults = @{@"ApplePressAndHoldEnabled":@NO}; + [[NSUserDefaults standardUserDefaults] registerDefaults:defaults]; + [[NSNotificationCenter defaultCenter] addObserver:_glfw.ns.helper selector:@selector(selectedKeyboardInputSourceChanged:) @@ -344,10 +532,14 @@ int _glfwPlatformInit(void) _glfwPollMonitorsNS(); return GLFW_TRUE; + + } // autoreleasepool } void _glfwPlatformTerminate(void) { + @autoreleasepool { + if (_glfw.ns.inputSource) { CFRelease(_glfw.ns.inputSource); @@ -388,13 +580,12 @@ void _glfwPlatformTerminate(void) _glfwTerminateNSGL(); _glfwTerminateJoysticksNS(); - [_glfw.ns.autoreleasePool release]; - _glfw.ns.autoreleasePool = nil; + } // autoreleasepool } const char* _glfwPlatformGetVersionString(void) { - return _GLFW_VERSION_NUMBER " Cocoa NSGL" + return _GLFW_VERSION_NUMBER " Cocoa NSGL EGL OSMesa" #if defined(_GLFW_BUILD_DLL) " dynamic" #endif diff --git a/src/external/glfw/src/cocoa_joystick.h b/src/external/glfw/src/cocoa_joystick.h index d18d032a..0ab81377 100644 --- a/src/external/glfw/src/cocoa_joystick.h +++ b/src/external/glfw/src/cocoa_joystick.h @@ -1,7 +1,7 @@ //======================================================================== // GLFW 3.3 Cocoa - www.glfw.org //------------------------------------------------------------------------ -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2006-2017 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages diff --git a/src/external/glfw/src/cocoa_joystick.m b/src/external/glfw/src/cocoa_joystick.m index 0831809f..db4427d6 100644 --- a/src/external/glfw/src/cocoa_joystick.m +++ b/src/external/glfw/src/cocoa_joystick.m @@ -1,7 +1,7 @@ //======================================================================== // GLFW 3.3 Cocoa - www.glfw.org //------------------------------------------------------------------------ -// Copyright (c) 2009-2016 Camilla Lรถwy +// Copyright (c) 2009-2019 Camilla Lรถwy // Copyright (c) 2012 Torsten Walluhn // // This software is provided 'as-is', without any express or implied @@ -220,9 +220,31 @@ static void matchCallback(void* context, case kHIDUsage_GD_Hatswitch: target = hats; break; + case kHIDUsage_GD_DPadUp: + case kHIDUsage_GD_DPadRight: + case kHIDUsage_GD_DPadDown: + case kHIDUsage_GD_DPadLeft: + case kHIDUsage_GD_SystemMainMenu: + case kHIDUsage_GD_Select: + case kHIDUsage_GD_Start: + target = buttons; + break; + } + } + else if (page == kHIDPage_Simulation) + { + switch (usage) + { + case kHIDUsage_Sim_Accelerator: + case kHIDUsage_Sim_Brake: + case kHIDUsage_Sim_Throttle: + case kHIDUsage_Sim_Rudder: + case kHIDUsage_Sim_Steering: + target = axes; + break; } } - else if (page == kHIDPage_Button) + else if (page == kHIDPage_Button || page == kHIDPage_Consumer) target = buttons; if (target) @@ -397,12 +419,12 @@ int _glfwPlatformPollJoystick(_GLFWjoystick* js, int mode) if (raw > axis->maximum) axis->maximum = raw; - const long delta = axis->maximum - axis->minimum; - if (delta == 0) + const long size = axis->maximum - axis->minimum; + if (size == 0) _glfwInputJoystickAxis(js, (int) i, 0.f); else { - const float value = (2.f * (raw - axis->minimum) / delta) - 1.f; + const float value = (2.f * (raw - axis->minimum) / size) - 1.f; _glfwInputJoystickAxis(js, (int) i, value); } } @@ -417,7 +439,8 @@ int _glfwPlatformPollJoystick(_GLFWjoystick* js, int mode) _GLFWjoyelementNS* button = (_GLFWjoyelementNS*) CFArrayGetValueAtIndex(js->ns.buttons, i); const char value = getElementValue(js, button) - button->minimum; - _glfwInputJoystickButton(js, (int) i, value); + const int state = (value > 0) ? GLFW_PRESS : GLFW_RELEASE; + _glfwInputJoystickButton(js, (int) i, state); } for (i = 0; i < CFArrayGetCount(js->ns.hats); i++) @@ -454,7 +477,7 @@ void _glfwPlatformUpdateGamepadGUID(char* guid) (strncmp(guid + 20, "000000000000", 12) == 0)) { char original[33]; - strcpy(original, guid); + strncpy(original, guid, sizeof(original) - 1); sprintf(guid, "03000000%.4s0000%.4s000000000000", original, original + 16); } diff --git a/src/external/glfw/src/cocoa_monitor.m b/src/external/glfw/src/cocoa_monitor.m index 39fff6f7..e327c628 100644 --- a/src/external/glfw/src/cocoa_monitor.m +++ b/src/external/glfw/src/cocoa_monitor.m @@ -2,7 +2,7 @@ // GLFW 3.3 macOS - www.glfw.org //------------------------------------------------------------------------ // Copyright (c) 2002-2006 Marcus Geelnard -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2006-2019 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages @@ -29,10 +29,9 @@ #include #include +#include #include -#include -#include #include @@ -148,7 +147,7 @@ static GLFWvidmode vidmodeFromCGDisplayMode(CGDisplayModeRef mode, GLFWvidmode result; result.width = (int) CGDisplayModeGetWidth(mode); result.height = (int) CGDisplayModeGetHeight(mode); - result.refreshRate = (int) CGDisplayModeGetRefreshRate(mode); + result.refreshRate = (int) round(CGDisplayModeGetRefreshRate(mode)); if (result.refreshRate == 0) { @@ -212,6 +211,31 @@ static void endFadeReservation(CGDisplayFadeReservationToken token) } } +// Finds and caches the NSScreen corresponding to the specified monitor +// +GLFWbool refreshMonitorScreen(_GLFWmonitor* monitor) +{ + if (monitor->ns.screen) + return GLFW_TRUE; + + for (NSScreen* screen in [NSScreen screens]) + { + NSNumber* displayID = [screen deviceDescription][@"NSScreenNumber"]; + + // HACK: Compare unit numbers instead of display IDs to work around + // display replacement on machines with automatic graphics + // switching + if (monitor->ns.unitNumber == CGDisplayUnitNumber([displayID unsignedIntValue])) + { + monitor->ns.screen = screen; + return GLFW_TRUE; + } + } + + _glfwInputError(GLFW_PLATFORM_ERROR, "Cocoa: Failed to find a screen for monitor"); + return GLFW_FALSE; +} + ////////////////////////////////////////////////////////////////////////// ////// GLFW internal API ////// @@ -361,46 +385,25 @@ void _glfwPlatformFreeMonitor(_GLFWmonitor* monitor) void _glfwPlatformGetMonitorPos(_GLFWmonitor* monitor, int* xpos, int* ypos) { + @autoreleasepool { + const CGRect bounds = CGDisplayBounds(monitor->ns.displayID); if (xpos) *xpos = (int) bounds.origin.x; if (ypos) *ypos = (int) bounds.origin.y; + + } // autoreleasepool } void _glfwPlatformGetMonitorContentScale(_GLFWmonitor* monitor, float* xscale, float* yscale) { - if (!monitor->ns.screen) - { - NSUInteger i; - NSArray* screens = [NSScreen screens]; - - for (i = 0; i < [screens count]; i++) - { - NSScreen* screen = [screens objectAtIndex:i]; - NSNumber* displayID = - [[screen deviceDescription] objectForKey:@"NSScreenNumber"]; - - // HACK: Compare unit numbers instead of display IDs to work around - // display replacement on machines with automatic graphics - // switching - if (monitor->ns.unitNumber == - CGDisplayUnitNumber([displayID unsignedIntValue])) - { - monitor->ns.screen = screen; - break; - } - } + @autoreleasepool { - if (i == [screens count]) - { - _glfwInputError(GLFW_PLATFORM_ERROR, - "Cocoa: Failed to find a screen for monitor"); - return; - } - } + if (!refreshMonitorScreen(monitor)) + return; const NSRect points = [monitor->ns.screen frame]; const NSRect pixels = [monitor->ns.screen convertRectToBacking:points]; @@ -409,10 +412,37 @@ void _glfwPlatformGetMonitorContentScale(_GLFWmonitor* monitor, *xscale = (float) (pixels.size.width / points.size.width); if (yscale) *yscale = (float) (pixels.size.height / points.size.height); + + } // autoreleasepool +} + +void _glfwPlatformGetMonitorWorkarea(_GLFWmonitor* monitor, + int* xpos, int* ypos, + int* width, int* height) +{ + @autoreleasepool { + + if (!refreshMonitorScreen(monitor)) + return; + + const NSRect frameRect = [monitor->ns.screen visibleFrame]; + + if (xpos) + *xpos = frameRect.origin.x; + if (ypos) + *ypos = _glfwTransformYNS(frameRect.origin.y + frameRect.size.height - 1); + if (width) + *width = frameRect.size.width; + if (height) + *height = frameRect.size.height; + + } // autoreleasepool } GLFWvidmode* _glfwPlatformGetVideoModes(_GLFWmonitor* monitor, int* count) { + @autoreleasepool { + CFArrayRef modes; CFIndex found, i, j; GLFWvidmode* result; @@ -451,10 +481,14 @@ GLFWvidmode* _glfwPlatformGetVideoModes(_GLFWmonitor* monitor, int* count) CFRelease(modes); CVDisplayLinkRelease(link); return result; + + } // autoreleasepool } void _glfwPlatformGetVideoMode(_GLFWmonitor* monitor, GLFWvidmode *mode) { + @autoreleasepool { + CGDisplayModeRef displayMode; CVDisplayLinkRef link; @@ -465,10 +499,14 @@ void _glfwPlatformGetVideoMode(_GLFWmonitor* monitor, GLFWvidmode *mode) CGDisplayModeRelease(displayMode); CVDisplayLinkRelease(link); + + } // autoreleasepool } GLFWbool _glfwPlatformGetGammaRamp(_GLFWmonitor* monitor, GLFWgammaramp* ramp) { + @autoreleasepool { + uint32_t i, size = CGDisplayGammaTableCapacity(monitor->ns.displayID); CGGammaValue* values = calloc(size * 3, sizeof(CGGammaValue)); @@ -490,10 +528,14 @@ GLFWbool _glfwPlatformGetGammaRamp(_GLFWmonitor* monitor, GLFWgammaramp* ramp) free(values); return GLFW_TRUE; + + } // autoreleasepool } void _glfwPlatformSetGammaRamp(_GLFWmonitor* monitor, const GLFWgammaramp* ramp) { + @autoreleasepool { + int i; CGGammaValue* values = calloc(ramp->size * 3, sizeof(CGGammaValue)); @@ -511,6 +553,8 @@ void _glfwPlatformSetGammaRamp(_GLFWmonitor* monitor, const GLFWgammaramp* ramp) values + ramp->size * 2); free(values); + + } // autoreleasepool } diff --git a/src/external/glfw/src/cocoa_platform.h b/src/external/glfw/src/cocoa_platform.h index 13adaa97..2847f36b 100644 --- a/src/external/glfw/src/cocoa_platform.h +++ b/src/external/glfw/src/cocoa_platform.h @@ -1,7 +1,7 @@ //======================================================================== // GLFW 3.3 macOS - www.glfw.org //------------------------------------------------------------------------ -// Copyright (c) 2009-2016 Camilla Lรถwy +// Copyright (c) 2009-2019 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages @@ -28,12 +28,37 @@ #include #include +#include +#include + +// NOTE: All of NSGL was deprecated in the 10.14 SDK +// This disables the pointless warnings for every symbol we use +#define GL_SILENCE_DEPRECATION + #if defined(__OBJC__) #import #else typedef void* id; #endif +#if MAC_OS_X_VERSION_MAX_ALLOWED < 101200 + #define NSBitmapFormatAlphaNonpremultiplied NSAlphaNonpremultipliedBitmapFormat + #define NSEventMaskAny NSAnyEventMask + #define NSEventMaskKeyUp NSKeyUpMask + #define NSEventModifierFlagCapsLock NSAlphaShiftKeyMask + #define NSEventModifierFlagCommand NSCommandKeyMask + #define NSEventModifierFlagControl NSControlKeyMask + #define NSEventModifierFlagDeviceIndependentFlagsMask NSDeviceIndependentModifierFlagsMask + #define NSEventModifierFlagOption NSAlternateKeyMask + #define NSEventModifierFlagShift NSShiftKeyMask + #define NSEventTypeApplicationDefined NSApplicationDefined + #define NSWindowStyleMaskBorderless NSBorderlessWindowMask + #define NSWindowStyleMaskClosable NSClosableWindowMask + #define NSWindowStyleMaskMiniaturizable NSMiniaturizableWindowMask + #define NSWindowStyleMaskResizable NSResizableWindowMask + #define NSWindowStyleMaskTitled NSTitledWindowMask +#endif + typedef VkFlags VkMacOSSurfaceCreateFlagsMVK; typedef struct VkMacOSSurfaceCreateInfoMVK @@ -85,6 +110,7 @@ typedef struct _GLFWwindowNS id layer; GLFWbool maximized; + GLFWbool retina; // Cached window properties to filter out duplicate events int width, height; @@ -104,7 +130,7 @@ typedef struct _GLFWlibraryNS { CGEventSourceRef eventSource; id delegate; - id autoreleasePool; + GLFWbool finishedLaunching; GLFWbool cursorHidden; TISInputSourceRef inputSource; IOHIDManagerRef hidManager; @@ -167,3 +193,5 @@ void _glfwPollMonitorsNS(void); void _glfwSetVideoModeNS(_GLFWmonitor* monitor, const GLFWvidmode* desired); void _glfwRestoreVideoModeNS(_GLFWmonitor* monitor); +float _glfwTransformYNS(float y); + diff --git a/src/external/glfw/src/cocoa_window.m b/src/external/glfw/src/cocoa_window.m index db9935ce..d6480960 100644 --- a/src/external/glfw/src/cocoa_window.m +++ b/src/external/glfw/src/cocoa_window.m @@ -1,7 +1,7 @@ //======================================================================== // GLFW 3.3 macOS - www.glfw.org //------------------------------------------------------------------------ -// Copyright (c) 2009-2016 Camilla Lรถwy +// Copyright (c) 2009-2019 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages @@ -29,26 +29,6 @@ #include #include -// Needed for _NSGetProgname -#include - -#if MAC_OS_X_VERSION_MAX_ALLOWED < 101200 - #define NSWindowStyleMaskBorderless NSBorderlessWindowMask - #define NSWindowStyleMaskClosable NSClosableWindowMask - #define NSWindowStyleMaskMiniaturizable NSMiniaturizableWindowMask - #define NSWindowStyleMaskResizable NSResizableWindowMask - #define NSWindowStyleMaskTitled NSTitledWindowMask - #define NSEventModifierFlagCommand NSCommandKeyMask - #define NSEventModifierFlagControl NSControlKeyMask - #define NSEventModifierFlagOption NSAlternateKeyMask - #define NSEventModifierFlagShift NSShiftKeyMask - #define NSEventModifierFlagCapsLock NSAlphaShiftKeyMask - #define NSEventModifierFlagDeviceIndependentFlagsMask NSDeviceIndependentModifierFlagsMask - #define NSEventMaskAny NSAnyEventMask - #define NSEventTypeApplicationDefined NSApplicationDefined - #define NSBitmapFormatAlphaNonpremultiplied NSAlphaNonpremultipliedBitmapFormat -#endif - // Returns the style mask corresponding to the window settings // static NSUInteger getStyleMask(_GLFWwindow* window) @@ -70,18 +50,9 @@ static NSUInteger getStyleMask(_GLFWwindow* window) return styleMask; } -// Center the cursor in the view of the window -// -static void centerCursor(_GLFWwindow *window) -{ - int width, height; - _glfwPlatformGetWindowSize(window, &width, &height); - _glfwPlatformSetCursorPos(window, width / 2.0, height / 2.0); -} - -// Returns whether the cursor is in the client area of the specified window +// Returns whether the cursor is in the content area of the specified window // -static GLFWbool cursorInClientArea(_GLFWwindow* window) +static GLFWbool cursorInContentArea(_GLFWwindow* window) { const NSPoint pos = [window->ns.object mouseLocationOutsideOfEventStream]; return [window->ns.view mouse:pos inRect:[window->ns.view frame]]; @@ -136,7 +107,7 @@ static void updateCursorMode(_GLFWwindow* window) _glfwPlatformGetCursorPos(window, &_glfw.ns.restoreCursorPosX, &_glfw.ns.restoreCursorPosY); - centerCursor(window); + _glfwCenterCursorInContentArea(window); CGAssociateMouseAndMouseCursorPosition(false); } else if (_glfw.ns.disabledCursorWindow == window) @@ -148,18 +119,10 @@ static void updateCursorMode(_GLFWwindow* window) _glfw.ns.restoreCursorPosY); } - if (cursorInClientArea(window)) + if (cursorInContentArea(window)) updateCursorImage(window); } -// Transforms the specified y-coordinate between the CG display and NS screen -// coordinate systems -// -static float transformY(float y) -{ - return CGDisplayBounds(CGMainDisplayID()).size.height - y; -} - // Make the specified window and its video mode active on its monitor // static void acquireMonitor(_GLFWwindow* window) @@ -167,7 +130,7 @@ static void acquireMonitor(_GLFWwindow* window) _glfwSetVideoModeNS(window->monitor, &window->videoMode); const CGRect bounds = CGDisplayBounds(window->monitor->ns.displayID); const NSRect frame = NSMakeRect(bounds.origin.x, - transformY(bounds.origin.y + bounds.size.height), + _glfwTransformYNS(bounds.origin.y + bounds.size.height - 1), bounds.size.width, bounds.size.height); @@ -283,7 +246,7 @@ static const NSRange kEmptyRange = { NSNotFound, 0 }; [window->context.nsgl.object update]; if (_glfw.ns.disabledCursorWindow == window) - centerCursor(window); + _glfwCenterCursorInContentArea(window); const int maximized = [window->ns.object isZoomed]; if (window->ns.maximized != maximized) @@ -318,7 +281,7 @@ static const NSRange kEmptyRange = { NSNotFound, 0 }; [window->context.nsgl.object update]; if (_glfw.ns.disabledCursorWindow == window) - centerCursor(window); + _glfwCenterCursorInContentArea(window); int x, y; _glfwPlatformGetWindowPos(window, &x, &y); @@ -344,7 +307,7 @@ static const NSRange kEmptyRange = { NSNotFound, 0 }; - (void)windowDidBecomeKey:(NSNotification *)notification { if (_glfw.ns.disabledCursorWindow == window) - centerCursor(window); + _glfwCenterCursorInContentArea(window); _glfwInputWindowFocus(window, GLFW_TRUE); updateCursorMode(window); @@ -358,54 +321,10 @@ static const NSRange kEmptyRange = { NSNotFound, 0 }; _glfwInputWindowFocus(window, GLFW_FALSE); } -@end - - -//------------------------------------------------------------------------ -// Delegate for application related notifications -//------------------------------------------------------------------------ - -@interface GLFWApplicationDelegate : NSObject -@end - -@implementation GLFWApplicationDelegate - -- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender -{ - _GLFWwindow* window; - - for (window = _glfw.windowListHead; window; window = window->next) - _glfwInputWindowCloseRequest(window); - - return NSTerminateCancel; -} - -- (void)applicationDidChangeScreenParameters:(NSNotification *) notification +- (void)windowDidChangeScreen:(NSNotification *)notification { - _GLFWwindow* window; - - for (window = _glfw.windowListHead; window; window = window->next) - { - if (window->context.client != GLFW_NO_API) - [window->context.nsgl.object update]; - } - - _glfwPollMonitorsNS(); -} - -- (void)applicationDidFinishLaunching:(NSNotification *)notification -{ - [NSApp stop:nil]; - - _glfwPlatformPostEmptyEvent(); -} - -- (void)applicationDidHide:(NSNotification *)notification -{ - int i; - - for (i = 0; i < _glfw.monitorCount; i++) - _glfwRestoreVideoModeNS(_glfw.monitors[i]); + if (window->context.source == GLFW_NATIVE_CONTEXT_API) + _glfwUpdateDisplayLinkDisplayNSGL(window); } @end @@ -481,14 +400,6 @@ static const NSRange kEmptyRange = { NSNotFound, 0 }; _glfwInputWindowDamage(window); } -- (id)makeBackingLayer -{ - if (window->ns.layer) - return window->ns.layer; - - return [super makeBackingLayer]; -} - - (void)cursorUpdate:(NSEvent *)event { updateCursorImage(window); @@ -534,6 +445,7 @@ static const NSRange kEmptyRange = { NSNotFound, 0 }; else { const NSRect contentRect = [window->ns.view frame]; + // NOTE: The returned location uses base 0,1 not 0,0 const NSPoint pos = [event locationInWindow]; _glfwInputCursorPos(window, pos.x, contentRect.size.height - pos.y); @@ -623,7 +535,7 @@ static const NSRange kEmptyRange = { NSNotFound, 0 }; window->ns.yscale = yscale; _glfwInputWindowContentScale(window, xscale, yscale); - if (window->ns.layer) + if (window->ns.retina && window->ns.layer) [window->ns.layer setContentsScale:[window->ns.object backingScaleFactor]]; } } @@ -723,9 +635,9 @@ static const NSRange kEmptyRange = { NSNotFound, 0 }; - (BOOL)performDragOperation:(id )sender { const NSRect contentRect = [window->ns.view frame]; - _glfwInputCursorPos(window, - [sender draggingLocation].x, - contentRect.size.height - [sender draggingLocation].y); + // NOTE: The returned location uses base 0,1 not 0,0 + const NSPoint pos = [sender draggingLocation]; + _glfwInputCursorPos(window, pos.x, contentRect.size.height - pos.y); NSPasteboard* pasteboard = [sender draggingPasteboard]; NSDictionary* options = @{NSPasteboardURLReadingFileURLsOnlyKey:@YES}; @@ -737,7 +649,7 @@ static const NSRange kEmptyRange = { NSNotFound, 0 }; char** paths = calloc(count, sizeof(char*)); for (NSUInteger i = 0; i < count; i++) - paths[i] = _glfw_strdup([[urls objectAtIndex:i] fileSystemRepresentation]); + paths[i] = _glfw_strdup([urls[i] fileSystemRepresentation]); _glfwInputDrop(window, (int) count, (const char**) paths); @@ -802,10 +714,8 @@ static const NSRange kEmptyRange = { NSNotFound, 0 }; - (NSRect)firstRectForCharacterRange:(NSRange)range actualRange:(NSRangePointer)actualRange { - int xpos, ypos; - _glfwPlatformGetWindowPos(window, &xpos, &ypos); - const NSRect contentRect = [window->ns.view frame]; - return NSMakeRect(xpos, transformY(ypos + contentRect.size.height), 0.0, 0.0); + const NSRect frame = [window->ns.view frame]; + return NSMakeRect(frame.origin.x, frame.origin.y, 0.0, 0.0); } - (void)insertText:(id)string replacementRange:(NSRange)replacementRange @@ -862,162 +772,6 @@ static const NSRange kEmptyRange = { NSNotFound, 0 }; @end -// Set up the menu bar (manually) -// This is nasty, nasty stuff -- calls to undocumented semi-private APIs that -// could go away at any moment, lots of stuff that really should be -// localize(d|able), etc. Add a nib to save us this horror. -// -static void createMenuBar(void) -{ - size_t i; - NSString* appName = nil; - NSDictionary* bundleInfo = [[NSBundle mainBundle] infoDictionary]; - NSString* nameKeys[] = - { - @"CFBundleDisplayName", - @"CFBundleName", - @"CFBundleExecutable", - }; - - // Try to figure out what the calling application is called - - for (i = 0; i < sizeof(nameKeys) / sizeof(nameKeys[0]); i++) - { - id name = [bundleInfo objectForKey:nameKeys[i]]; - if (name && - [name isKindOfClass:[NSString class]] && - ![name isEqualToString:@""]) - { - appName = name; - break; - } - } - - if (!appName) - { - char** progname = _NSGetProgname(); - if (progname && *progname) - appName = [NSString stringWithUTF8String:*progname]; - else - appName = @"GLFW Application"; - } - - NSMenu* bar = [[NSMenu alloc] init]; - [NSApp setMainMenu:bar]; - - NSMenuItem* appMenuItem = - [bar addItemWithTitle:@"" action:NULL keyEquivalent:@""]; - NSMenu* appMenu = [[NSMenu alloc] init]; - [appMenuItem setSubmenu:appMenu]; - - [appMenu addItemWithTitle:[NSString stringWithFormat:@"About %@", appName] - action:@selector(orderFrontStandardAboutPanel:) - keyEquivalent:@""]; - [appMenu addItem:[NSMenuItem separatorItem]]; - NSMenu* servicesMenu = [[NSMenu alloc] init]; - [NSApp setServicesMenu:servicesMenu]; - [[appMenu addItemWithTitle:@"Services" - action:NULL - keyEquivalent:@""] setSubmenu:servicesMenu]; - [servicesMenu release]; - [appMenu addItem:[NSMenuItem separatorItem]]; - [appMenu addItemWithTitle:[NSString stringWithFormat:@"Hide %@", appName] - action:@selector(hide:) - keyEquivalent:@"h"]; - [[appMenu addItemWithTitle:@"Hide Others" - action:@selector(hideOtherApplications:) - keyEquivalent:@"h"] - setKeyEquivalentModifierMask:NSEventModifierFlagOption | NSEventModifierFlagCommand]; - [appMenu addItemWithTitle:@"Show All" - action:@selector(unhideAllApplications:) - keyEquivalent:@""]; - [appMenu addItem:[NSMenuItem separatorItem]]; - [appMenu addItemWithTitle:[NSString stringWithFormat:@"Quit %@", appName] - action:@selector(terminate:) - keyEquivalent:@"q"]; - - NSMenuItem* windowMenuItem = - [bar addItemWithTitle:@"" action:NULL keyEquivalent:@""]; - [bar release]; - NSMenu* windowMenu = [[NSMenu alloc] initWithTitle:@"Window"]; - [NSApp setWindowsMenu:windowMenu]; - [windowMenuItem setSubmenu:windowMenu]; - - [windowMenu addItemWithTitle:@"Minimize" - action:@selector(performMiniaturize:) - keyEquivalent:@"m"]; - [windowMenu addItemWithTitle:@"Zoom" - action:@selector(performZoom:) - keyEquivalent:@""]; - [windowMenu addItem:[NSMenuItem separatorItem]]; - [windowMenu addItemWithTitle:@"Bring All to Front" - action:@selector(arrangeInFront:) - keyEquivalent:@""]; - - // TODO: Make this appear at the bottom of the menu (for consistency) - [windowMenu addItem:[NSMenuItem separatorItem]]; - [[windowMenu addItemWithTitle:@"Enter Full Screen" - action:@selector(toggleFullScreen:) - keyEquivalent:@"f"] - setKeyEquivalentModifierMask:NSEventModifierFlagControl | NSEventModifierFlagCommand]; - - // Prior to Snow Leopard, we need to use this oddly-named semi-private API - // to get the application menu working properly. - SEL setAppleMenuSelector = NSSelectorFromString(@"setAppleMenu:"); - [NSApp performSelector:setAppleMenuSelector withObject:appMenu]; -} - -// Initialize the Cocoa Application Kit -// -static GLFWbool initializeAppKit(void) -{ - if (_glfw.ns.delegate) - return GLFW_TRUE; - - // There can only be one application delegate, but we allocate it the - // first time a window is created to keep all window code in this file - _glfw.ns.delegate = [[GLFWApplicationDelegate alloc] init]; - if (_glfw.ns.delegate == nil) - { - _glfwInputError(GLFW_PLATFORM_ERROR, - "Cocoa: Failed to create application delegate"); - return GLFW_FALSE; - } - - [NSApp setDelegate:_glfw.ns.delegate]; - - if (_glfw.hints.init.ns.menubar) - { - // In case we are unbundled, make us a proper UI application - [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular]; - - // Menu bar setup must go between sharedApplication above and - // finishLaunching below, in order to properly emulate the behavior - // of NSApplicationMain - - if ([[NSBundle mainBundle] pathForResource:@"MainMenu" ofType:@"nib"]) - { -#if MAC_OS_X_VERSION_MAX_ALLOWED >= 1080 - [[NSBundle mainBundle] loadNibNamed:@"MainMenu" - owner:NSApp - topLevelObjects:&_glfw.ns.nibObjects]; -#else - [[NSBundle mainBundle] loadNibNamed:@"MainMenu" owner:NSApp]; -#endif - } - else - createMenuBar(); - } - - [NSApp run]; - - // Press and Hold prevents some keys from emitting repeated characters - NSDictionary* defaults = @{@"ApplePressAndHoldEnabled":@NO}; - [[NSUserDefaults standardUserDefaults] registerDefaults:defaults]; - - return GLFW_TRUE; -} - // Create the Cocoa window // static GLFWbool createNativeWindow(_GLFWwindow* window, @@ -1084,26 +838,30 @@ static GLFWbool createNativeWindow(_GLFWwindow* window, } if (strlen(wndconfig->ns.frameName)) - [window->ns.object setFrameAutosaveName:[NSString stringWithUTF8String:wndconfig->ns.frameName]]; + [window->ns.object setFrameAutosaveName:@(wndconfig->ns.frameName)]; window->ns.view = [[GLFWContentView alloc] initWithGlfwWindow:window]; - - if (wndconfig->ns.retina) - [window->ns.view setWantsBestResolutionOpenGLSurface:YES]; + window->ns.retina = wndconfig->ns.retina; if (fbconfig->transparent) { [window->ns.object setOpaque:NO]; + [window->ns.object setHasShadow:NO]; [window->ns.object setBackgroundColor:[NSColor clearColor]]; } [window->ns.object setContentView:window->ns.view]; [window->ns.object makeFirstResponder:window->ns.view]; - [window->ns.object setTitle:[NSString stringWithUTF8String:wndconfig->title]]; + [window->ns.object setTitle:@(wndconfig->title)]; [window->ns.object setDelegate:window->ns.delegate]; [window->ns.object setAcceptsMouseMovedEvents:YES]; [window->ns.object setRestorable:NO]; +#if MAC_OS_X_VERSION_MAX_ALLOWED >= 101200 + if ([window->ns.object respondsToSelector:@selector(setTabbingMode:)]) + [window->ns.object setTabbingMode:NSWindowTabbingModeDisallowed]; +#endif + _glfwPlatformGetWindowSize(window, &window->ns.width, &window->ns.height); _glfwPlatformGetFramebufferSize(window, &window->ns.fbWidth, &window->ns.fbHeight); @@ -1111,6 +869,18 @@ static GLFWbool createNativeWindow(_GLFWwindow* window, } +////////////////////////////////////////////////////////////////////////// +////// GLFW internal API ////// +////////////////////////////////////////////////////////////////////////// + +// Transforms a y-coordinate between the CG display and NS screen spaces +// +float _glfwTransformYNS(float y) +{ + return CGDisplayBounds(CGMainDisplayID()).size.height - y - 1; +} + + ////////////////////////////////////////////////////////////////////////// ////// GLFW platform API ////// ////////////////////////////////////////////////////////////////////////// @@ -1120,8 +890,13 @@ int _glfwPlatformCreateWindow(_GLFWwindow* window, const _GLFWctxconfig* ctxconfig, const _GLFWfbconfig* fbconfig) { - if (!initializeAppKit()) - return GLFW_FALSE; + @autoreleasepool { + + if (!_glfw.ns.finishedLaunching) + { + [NSApp run]; + _glfw.ns.finishedLaunching = GLFW_TRUE; + } if (!createNativeWindow(window, wndconfig, fbconfig)) return GLFW_FALSE; @@ -1159,10 +934,14 @@ int _glfwPlatformCreateWindow(_GLFWwindow* window, } return GLFW_TRUE; + + } // autoreleasepool } void _glfwPlatformDestroyWindow(_GLFWwindow* window) { + @autoreleasepool { + if (_glfw.ns.disabledCursorWindow == window) _glfw.ns.disabledCursorWindow = NULL; @@ -1184,17 +963,17 @@ void _glfwPlatformDestroyWindow(_GLFWwindow* window) [window->ns.object close]; window->ns.object = nil; - [_glfw.ns.autoreleasePool drain]; - _glfw.ns.autoreleasePool = [[NSAutoreleasePool alloc] init]; + } // autoreleasepool } void _glfwPlatformSetWindowTitle(_GLFWwindow* window, const char *title) { - NSString* string = [NSString stringWithUTF8String:title]; - [window->ns.object setTitle:string]; + @autoreleasepool { + [window->ns.object setTitle:@(title)]; // HACK: Set the miniwindow title explicitly as setTitle: doesn't update it // if the window lacks NSWindowStyleMaskTitled - [window->ns.object setMiniwindowTitle:string]; + [window->ns.object setMiniwindowTitle:@(title)]; + } // autoreleasepool } void _glfwPlatformSetWindowIcon(_GLFWwindow* window, @@ -1205,35 +984,49 @@ void _glfwPlatformSetWindowIcon(_GLFWwindow* window, void _glfwPlatformGetWindowPos(_GLFWwindow* window, int* xpos, int* ypos) { + @autoreleasepool { + const NSRect contentRect = [window->ns.object contentRectForFrameRect:[window->ns.object frame]]; if (xpos) *xpos = contentRect.origin.x; if (ypos) - *ypos = transformY(contentRect.origin.y + contentRect.size.height); + *ypos = _glfwTransformYNS(contentRect.origin.y + contentRect.size.height - 1); + + } // autoreleasepool } void _glfwPlatformSetWindowPos(_GLFWwindow* window, int x, int y) { + @autoreleasepool { + const NSRect contentRect = [window->ns.view frame]; - const NSRect dummyRect = NSMakeRect(x, transformY(y + contentRect.size.height), 0, 0); + const NSRect dummyRect = NSMakeRect(x, _glfwTransformYNS(y + contentRect.size.height - 1), 0, 0); const NSRect frameRect = [window->ns.object frameRectForContentRect:dummyRect]; [window->ns.object setFrameOrigin:frameRect.origin]; + + } // autoreleasepool } void _glfwPlatformGetWindowSize(_GLFWwindow* window, int* width, int* height) { + @autoreleasepool { + const NSRect contentRect = [window->ns.view frame]; if (width) *width = contentRect.size.width; if (height) *height = contentRect.size.height; + + } // autoreleasepool } void _glfwPlatformSetWindowSize(_GLFWwindow* window, int width, int height) { + @autoreleasepool { + if (window->monitor) { if (window->monitor->window == window) @@ -1241,12 +1034,16 @@ void _glfwPlatformSetWindowSize(_GLFWwindow* window, int width, int height) } else [window->ns.object setContentSize:NSMakeSize(width, height)]; + + } // autoreleasepool } void _glfwPlatformSetWindowSizeLimits(_GLFWwindow* window, int minwidth, int minheight, int maxwidth, int maxheight) { + @autoreleasepool { + if (minwidth == GLFW_DONT_CARE || minheight == GLFW_DONT_CARE) [window->ns.object setContentMinSize:NSMakeSize(0, 0)]; else @@ -1256,18 +1053,24 @@ void _glfwPlatformSetWindowSizeLimits(_GLFWwindow* window, [window->ns.object setContentMaxSize:NSMakeSize(DBL_MAX, DBL_MAX)]; else [window->ns.object setContentMaxSize:NSMakeSize(maxwidth, maxheight)]; + + } // autoreleasepool } void _glfwPlatformSetWindowAspectRatio(_GLFWwindow* window, int numer, int denom) { + @autoreleasepool { if (numer == GLFW_DONT_CARE || denom == GLFW_DONT_CARE) [window->ns.object setResizeIncrements:NSMakeSize(1.0, 1.0)]; else [window->ns.object setContentAspectRatio:NSMakeSize(numer, denom)]; + } // autoreleasepool } void _glfwPlatformGetFramebufferSize(_GLFWwindow* window, int* width, int* height) { + @autoreleasepool { + const NSRect contentRect = [window->ns.view frame]; const NSRect fbRect = [window->ns.view convertRectToBacking:contentRect]; @@ -1275,12 +1078,16 @@ void _glfwPlatformGetFramebufferSize(_GLFWwindow* window, int* width, int* heigh *width = (int) fbRect.size.width; if (height) *height = (int) fbRect.size.height; + + } // autoreleasepool } void _glfwPlatformGetWindowFrameSize(_GLFWwindow* window, int* left, int* top, int* right, int* bottom) { + @autoreleasepool { + const NSRect contentRect = [window->ns.view frame]; const NSRect frameRect = [window->ns.object frameRectForContentRect:contentRect]; @@ -1294,11 +1101,15 @@ void _glfwPlatformGetWindowFrameSize(_GLFWwindow* window, contentRect.origin.x - contentRect.size.width; if (bottom) *bottom = contentRect.origin.y - frameRect.origin.y; + + } // autoreleasepool } void _glfwPlatformGetWindowContentScale(_GLFWwindow* window, float* xscale, float* yscale) { + @autoreleasepool { + const NSRect points = [window->ns.view frame]; const NSRect pixels = [window->ns.view convertRectToBacking:points]; @@ -1306,51 +1117,66 @@ void _glfwPlatformGetWindowContentScale(_GLFWwindow* window, *xscale = (float) (pixels.size.width / points.size.width); if (yscale) *yscale = (float) (pixels.size.height / points.size.height); + + } // autoreleasepool } void _glfwPlatformIconifyWindow(_GLFWwindow* window) { + @autoreleasepool { [window->ns.object miniaturize:nil]; + } // autoreleasepool } void _glfwPlatformRestoreWindow(_GLFWwindow* window) { + @autoreleasepool { if ([window->ns.object isMiniaturized]) [window->ns.object deminiaturize:nil]; else if ([window->ns.object isZoomed]) [window->ns.object zoom:nil]; + } // autoreleasepool } void _glfwPlatformMaximizeWindow(_GLFWwindow* window) { + @autoreleasepool { if (![window->ns.object isZoomed]) [window->ns.object zoom:nil]; + } // autoreleasepool } void _glfwPlatformShowWindow(_GLFWwindow* window) { + @autoreleasepool { [window->ns.object orderFront:nil]; + } // autoreleasepool } void _glfwPlatformHideWindow(_GLFWwindow* window) { + @autoreleasepool { [window->ns.object orderOut:nil]; + } // autoreleasepool } void _glfwPlatformRequestWindowAttention(_GLFWwindow* window) { + @autoreleasepool { [NSApp requestUserAttention:NSInformationalRequest]; + } // autoreleasepool } void _glfwPlatformFocusWindow(_GLFWwindow* window) { + @autoreleasepool { // Make us the active application - // HACK: This has been moved here from initializeAppKit to prevent - // applications using only hidden windows from being activated, but - // should probably not be done every time any window is shown + // HACK: This is here to prevent applications using only hidden windows from + // being activated, but should probably not be done every time any + // window is shown [NSApp activateIgnoringOtherApps:YES]; - [window->ns.object makeKeyAndOrderFront:nil]; + } // autoreleasepool } void _glfwPlatformSetWindowMonitor(_GLFWwindow* window, @@ -1359,6 +1185,8 @@ void _glfwPlatformSetWindowMonitor(_GLFWwindow* window, int width, int height, int refreshRate) { + @autoreleasepool { + if (window->monitor == monitor) { if (monitor) @@ -1369,7 +1197,7 @@ void _glfwPlatformSetWindowMonitor(_GLFWwindow* window, else { const NSRect contentRect = - NSMakeRect(xpos, transformY(ypos + height), width, height); + NSMakeRect(xpos, _glfwTransformYNS(ypos + height - 1), width, height); const NSRect frameRect = [window->ns.object frameRectForContentRect:contentRect styleMask:getStyleMask(window)]; @@ -1403,7 +1231,7 @@ void _glfwPlatformSetWindowMonitor(_GLFWwindow* window, } else { - NSRect contentRect = NSMakeRect(xpos, transformY(ypos + height), + NSRect contentRect = NSMakeRect(xpos, _glfwTransformYNS(ypos + height - 1), width, height); NSRect frameRect = [window->ns.object frameRectForContentRect:contentRect styleMask:styleMask]; @@ -1440,30 +1268,42 @@ void _glfwPlatformSetWindowMonitor(_GLFWwindow* window, // title property but the miniwindow title property is unaffected [window->ns.object setTitle:[window->ns.object miniwindowTitle]]; } + + } // autoreleasepool } int _glfwPlatformWindowFocused(_GLFWwindow* window) { + @autoreleasepool { return [window->ns.object isKeyWindow]; + } // autoreleasepool } int _glfwPlatformWindowIconified(_GLFWwindow* window) { + @autoreleasepool { return [window->ns.object isMiniaturized]; + } // autoreleasepool } int _glfwPlatformWindowVisible(_GLFWwindow* window) { + @autoreleasepool { return [window->ns.object isVisible]; + } // autoreleasepool } int _glfwPlatformWindowMaximized(_GLFWwindow* window) { + @autoreleasepool { return [window->ns.object isZoomed]; + } // autoreleasepool } int _glfwPlatformWindowHovered(_GLFWwindow* window) { + @autoreleasepool { + const NSPoint point = [NSEvent mouseLocation]; if ([NSWindow windowNumberAtPoint:point belowWindowWithWindowNumber:0] != @@ -1472,46 +1312,71 @@ int _glfwPlatformWindowHovered(_GLFWwindow* window) return GLFW_FALSE; } - return NSPointInRect(point, - [window->ns.object convertRectToScreen:[window->ns.view bounds]]); + return NSMouseInRect(point, + [window->ns.object convertRectToScreen:[window->ns.view frame]], NO); + + } // autoreleasepool } int _glfwPlatformFramebufferTransparent(_GLFWwindow* window) { + @autoreleasepool { return ![window->ns.object isOpaque] && ![window->ns.view isOpaque]; + } // autoreleasepool } void _glfwPlatformSetWindowResizable(_GLFWwindow* window, GLFWbool enabled) { + @autoreleasepool { [window->ns.object setStyleMask:getStyleMask(window)]; + } // autoreleasepool } void _glfwPlatformSetWindowDecorated(_GLFWwindow* window, GLFWbool enabled) { + @autoreleasepool { [window->ns.object setStyleMask:getStyleMask(window)]; [window->ns.object makeFirstResponder:window->ns.view]; + } // autoreleasepool } void _glfwPlatformSetWindowFloating(_GLFWwindow* window, GLFWbool enabled) { + @autoreleasepool { if (enabled) [window->ns.object setLevel:NSFloatingWindowLevel]; else [window->ns.object setLevel:NSNormalWindowLevel]; + } // autoreleasepool } float _glfwPlatformGetWindowOpacity(_GLFWwindow* window) { + @autoreleasepool { return (float) [window->ns.object alphaValue]; + } // autoreleasepool } void _glfwPlatformSetWindowOpacity(_GLFWwindow* window, float opacity) { + @autoreleasepool { [window->ns.object setAlphaValue:opacity]; + } // autoreleasepool +} + +void _glfwPlatformSetRawMouseMotion(_GLFWwindow *window, GLFWbool enabled) +{ +} + +GLFWbool _glfwPlatformRawMouseMotionSupported(void) +{ + return GLFW_FALSE; } void _glfwPlatformPollEvents(void) { + @autoreleasepool { + for (;;) { NSEvent* event = [NSApp nextEventMatchingMask:NSEventMaskAny @@ -1524,12 +1389,13 @@ void _glfwPlatformPollEvents(void) [NSApp sendEvent:event]; } - [_glfw.ns.autoreleasePool drain]; - _glfw.ns.autoreleasePool = [[NSAutoreleasePool alloc] init]; + } // autoreleasepool } void _glfwPlatformWaitEvents(void) { + @autoreleasepool { + // I wanted to pass NO to dequeue:, and rely on PollEvents to // dequeue and send. For reasons not at all clear to me, passing // NO to dequeue: causes this method never to return. @@ -1540,10 +1406,14 @@ void _glfwPlatformWaitEvents(void) [NSApp sendEvent:event]; _glfwPlatformPollEvents(); + + } // autoreleasepool } void _glfwPlatformWaitEventsTimeout(double timeout) { + @autoreleasepool { + NSDate* date = [NSDate dateWithTimeIntervalSinceNow:timeout]; NSEvent* event = [NSApp nextEventMatchingMask:NSEventMaskAny untilDate:date @@ -1553,11 +1423,14 @@ void _glfwPlatformWaitEventsTimeout(double timeout) [NSApp sendEvent:event]; _glfwPlatformPollEvents(); + + } // autoreleasepool } void _glfwPlatformPostEmptyEvent(void) { - NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + @autoreleasepool { + NSEvent* event = [NSEvent otherEventWithType:NSEventTypeApplicationDefined location:NSMakePoint(0, 0) modifierFlags:0 @@ -1568,25 +1441,34 @@ void _glfwPlatformPostEmptyEvent(void) data1:0 data2:0]; [NSApp postEvent:event atStart:YES]; - [pool drain]; + + } // autoreleasepool } void _glfwPlatformGetCursorPos(_GLFWwindow* window, double* xpos, double* ypos) { + @autoreleasepool { + const NSRect contentRect = [window->ns.view frame]; + // NOTE: The returned location uses base 0,1 not 0,0 const NSPoint pos = [window->ns.object mouseLocationOutsideOfEventStream]; if (xpos) *xpos = pos.x; if (ypos) - *ypos = contentRect.size.height - pos.y - 1; + *ypos = contentRect.size.height - pos.y; + + } // autoreleasepool } void _glfwPlatformSetCursorPos(_GLFWwindow* window, double x, double y) { + @autoreleasepool { + updateCursorImage(window); const NSRect contentRect = [window->ns.view frame]; + // NOTE: The returned location uses base 0,1 not 0,0 const NSPoint pos = [window->ns.object mouseLocationOutsideOfEventStream]; window->ns.cursorWarpDeltaX += x - pos.x; @@ -1604,18 +1486,24 @@ void _glfwPlatformSetCursorPos(_GLFWwindow* window, double x, double y) const NSPoint globalPoint = globalRect.origin; CGWarpMouseCursorPosition(CGPointMake(globalPoint.x, - transformY(globalPoint.y))); + _glfwTransformYNS(globalPoint.y))); } + + } // autoreleasepool } void _glfwPlatformSetCursorMode(_GLFWwindow* window, int mode) { + @autoreleasepool { if (_glfwPlatformWindowFocused(window)) updateCursorMode(window); + } // autoreleasepool } const char* _glfwPlatformGetScancodeName(int scancode) { + @autoreleasepool { + UInt32 deadKeyState = 0; UniChar characters[8]; UniCharCount characterCount = 0; @@ -1648,6 +1536,8 @@ const char* _glfwPlatformGetScancodeName(int scancode) CFRelease(string); return _glfw.ns.keyName; + + } // autoreleasepool } int _glfwPlatformGetKeyScancode(int key) @@ -1659,6 +1549,8 @@ int _glfwPlatformCreateCursor(_GLFWcursor* cursor, const GLFWimage* image, int xhot, int yhot) { + @autoreleasepool { + NSImage* native; NSBitmapImageRep* rep; @@ -1693,10 +1585,14 @@ int _glfwPlatformCreateCursor(_GLFWcursor* cursor, return GLFW_FALSE; return GLFW_TRUE; + + } // autoreleasepool } int _glfwPlatformCreateStandardCursor(_GLFWcursor* cursor, int shape) { + @autoreleasepool { + if (shape == GLFW_ARROW_CURSOR) cursor->ns.object = [NSCursor arrowCursor]; else if (shape == GLFW_IBEAM_CURSOR) @@ -1719,30 +1615,39 @@ int _glfwPlatformCreateStandardCursor(_GLFWcursor* cursor, int shape) [cursor->ns.object retain]; return GLFW_TRUE; + + } // autoreleasepool } void _glfwPlatformDestroyCursor(_GLFWcursor* cursor) { + @autoreleasepool { if (cursor->ns.object) [(NSCursor*) cursor->ns.object release]; + } // autoreleasepool } void _glfwPlatformSetCursor(_GLFWwindow* window, _GLFWcursor* cursor) { - if (cursorInClientArea(window)) + @autoreleasepool { + if (cursorInContentArea(window)) updateCursorImage(window); + } // autoreleasepool } void _glfwPlatformSetClipboardString(const char* string) { + @autoreleasepool { NSPasteboard* pasteboard = [NSPasteboard generalPasteboard]; [pasteboard declareTypes:@[NSPasteboardTypeString] owner:nil]; - [pasteboard setString:[NSString stringWithUTF8String:string] - forType:NSPasteboardTypeString]; + [pasteboard setString:@(string) forType:NSPasteboardTypeString]; + } // autoreleasepool } const char* _glfwPlatformGetClipboardString(void) { + @autoreleasepool { + NSPasteboard* pasteboard = [NSPasteboard generalPasteboard]; if (![[pasteboard types] containsObject:NSPasteboardTypeString]) @@ -1764,6 +1669,8 @@ const char* _glfwPlatformGetClipboardString(void) _glfw.ns.clipboardString = _glfw_strdup([object UTF8String]); return _glfw.ns.clipboardString; + + } // autoreleasepool } void _glfwPlatformGetRequiredInstanceExtensions(char** extensions) @@ -1787,6 +1694,8 @@ VkResult _glfwPlatformCreateWindowSurface(VkInstance instance, const VkAllocationCallbacks* allocator, VkSurfaceKHR* surface) { + @autoreleasepool { + #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101100 VkResult err; VkMacOSSurfaceCreateInfoMVK sci; @@ -1820,7 +1729,10 @@ VkResult _glfwPlatformCreateWindowSurface(VkInstance instance, return VK_ERROR_EXTENSION_NOT_PRESENT; } - [window->ns.layer setContentsScale:[window->ns.object backingScaleFactor]]; + if (window->ns.retina) + [window->ns.layer setContentsScale:[window->ns.object backingScaleFactor]]; + + [window->ns.view setLayer:window->ns.layer]; [window->ns.view setWantsLayer:YES]; memset(&sci, 0, sizeof(sci)); @@ -1839,6 +1751,8 @@ VkResult _glfwPlatformCreateWindowSurface(VkInstance instance, #else return VK_ERROR_EXTENSION_NOT_PRESENT; #endif + + } // autoreleasepool } diff --git a/src/external/glfw/src/context.c b/src/external/glfw/src/context.c index fd344cf1..38508522 100644 --- a/src/external/glfw/src/context.c +++ b/src/external/glfw/src/context.c @@ -358,7 +358,7 @@ GLFWbool _glfwRefreshContextAttribs(_GLFWwindow* window, window->context.source = ctxconfig->source; window->context.client = GLFW_OPENGL_API; - previous = _glfwPlatformGetTls(&_glfw.contextSlot);; + previous = _glfwPlatformGetTls(&_glfw.contextSlot); glfwMakeContextCurrent((GLFWwindow*) window); window->context.GetIntegerv = (PFNGLGETINTEGERVPROC) diff --git a/src/external/glfw/src/egl_context.c b/src/external/glfw/src/egl_context.c index b2d11a47..19525276 100644 --- a/src/external/glfw/src/egl_context.c +++ b/src/external/glfw/src/egl_context.c @@ -2,7 +2,7 @@ // GLFW 3.3 EGL - www.glfw.org //------------------------------------------------------------------------ // Copyright (c) 2002-2006 Marcus Geelnard -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2006-2019 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages @@ -446,7 +446,7 @@ void _glfwTerminateEGL(void) #define setAttrib(a, v) \ { \ - assert((size_t) (index + 1) < sizeof(attribs) / sizeof(attribs[0])); \ + assert(((size_t) index + 1) < sizeof(attribs) / sizeof(attribs[0])); \ attribs[index++] = a; \ attribs[index++] = v; \ } diff --git a/src/external/glfw/src/egl_context.h b/src/external/glfw/src/egl_context.h index 8f3d075c..7def043a 100644 --- a/src/external/glfw/src/egl_context.h +++ b/src/external/glfw/src/egl_context.h @@ -2,7 +2,7 @@ // GLFW 3.3 EGL - www.glfw.org //------------------------------------------------------------------------ // Copyright (c) 2002-2006 Marcus Geelnard -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2006-2017 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages diff --git a/src/external/glfw/src/glx_context.c b/src/external/glfw/src/glx_context.c index adace82d..b03a0489 100644 --- a/src/external/glfw/src/glx_context.c +++ b/src/external/glfw/src/glx_context.c @@ -2,7 +2,7 @@ // GLFW 3.3 GLX - www.glfw.org //------------------------------------------------------------------------ // Copyright (c) 2002-2006 Marcus Geelnard -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2006-2019 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages @@ -435,7 +435,7 @@ void _glfwTerminateGLX(void) #define setAttrib(a, v) \ { \ - assert((size_t) (index + 1) < sizeof(attribs) / sizeof(attribs[0])); \ + assert(((size_t) index + 1) < sizeof(attribs) / sizeof(attribs[0])); \ attribs[index++] = a; \ attribs[index++] = v; \ } diff --git a/src/external/glfw/src/glx_context.h b/src/external/glfw/src/glx_context.h index f767cb14..e63684f3 100644 --- a/src/external/glfw/src/glx_context.h +++ b/src/external/glfw/src/glx_context.h @@ -2,7 +2,7 @@ // GLFW 3.3 GLX - www.glfw.org //------------------------------------------------------------------------ // Copyright (c) 2002-2006 Marcus Geelnard -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2006-2017 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages diff --git a/src/external/glfw/src/init.c b/src/external/glfw/src/init.c index 4f424c4a..3d0f9cf7 100644 --- a/src/external/glfw/src/init.c +++ b/src/external/glfw/src/init.c @@ -2,7 +2,7 @@ // GLFW 3.3 - www.glfw.org //------------------------------------------------------------------------ // Copyright (c) 2002-2006 Marcus Geelnard -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2006-2018 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages diff --git a/src/external/glfw/src/input.c b/src/external/glfw/src/input.c index 460e9f31..a2f42efe 100644 --- a/src/external/glfw/src/input.c +++ b/src/external/glfw/src/input.c @@ -2,7 +2,7 @@ // GLFW 3.3 - www.glfw.org //------------------------------------------------------------------------ // Copyright (c) 2002-2006 Marcus Geelnard -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2006-2019 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages @@ -333,7 +333,7 @@ void _glfwInputMouseClick(_GLFWwindow* window, int button, int action, int mods) } // Notifies shared code of a cursor motion event -// The position is specified in client-area relative screen coordinates +// The position is specified in content area relative screen coordinates // void _glfwInputCursorPos(_GLFWwindow* window, double xpos, double ypos) { @@ -430,13 +430,13 @@ _GLFWjoystick* _glfwAllocJoystick(const char* name, js->present = GLFW_TRUE; js->name = _glfw_strdup(name); js->axes = calloc(axisCount, sizeof(float)); - js->buttons = calloc(buttonCount + hatCount * 4, 1); + js->buttons = calloc(buttonCount + (size_t) hatCount * 4, 1); js->hats = calloc(hatCount, 1); js->axisCount = axisCount; js->buttonCount = buttonCount; js->hatCount = hatCount; - strcpy(js->guid, guid); + strncpy(js->guid, guid, sizeof(js->guid) - 1); js->mapping = findValidMapping(js); return js; @@ -453,6 +453,16 @@ void _glfwFreeJoystick(_GLFWjoystick* js) memset(js, 0, sizeof(_GLFWjoystick)); } +// Center the cursor in the content area of the specified window +// +void _glfwCenterCursorInContentArea(_GLFWwindow* window) +{ + int width, height; + + _glfwPlatformGetWindowSize(window, &width, &height); + _glfwPlatformSetCursorPos(window, width / 2.0, height / 2.0); +} + ////////////////////////////////////////////////////////////////////////// ////// GLFW public API ////// @@ -475,6 +485,8 @@ GLFWAPI int glfwGetInputMode(GLFWwindow* handle, int mode) return window->stickyMouseButtons; case GLFW_LOCK_KEY_MODS: return window->lockKeyMods; + case GLFW_RAW_MOUSE_MOTION: + return window->rawMouseMotion; } _glfwInputError(GLFW_INVALID_ENUM, "Invalid input mode 0x%08X", mode); @@ -551,11 +563,35 @@ GLFWAPI void glfwSetInputMode(GLFWwindow* handle, int mode, int value) window->stickyMouseButtons = value; } else if (mode == GLFW_LOCK_KEY_MODS) + { window->lockKeyMods = value ? GLFW_TRUE : GLFW_FALSE; + } + else if (mode == GLFW_RAW_MOUSE_MOTION) + { + if (!_glfwPlatformRawMouseMotionSupported()) + { + _glfwInputError(GLFW_PLATFORM_ERROR, + "Raw mouse motion is not supported on this system"); + return; + } + + value = value ? GLFW_TRUE : GLFW_FALSE; + if (window->rawMouseMotion == value) + return; + + window->rawMouseMotion = value; + _glfwPlatformSetRawMouseMotion(window, value); + } else _glfwInputError(GLFW_INVALID_ENUM, "Invalid input mode 0x%08X", mode); } +GLFWAPI int glfwRawMouseMotionSupported(void) +{ + _GLFW_REQUIRE_INIT_OR_RETURN(GLFW_FALSE); + return _glfwPlatformRawMouseMotionSupported(); +} + GLFWAPI const char* glfwGetKeyName(int key, int scancode) { _GLFW_REQUIRE_INIT_OR_RETURN(NULL); @@ -1222,8 +1258,18 @@ GLFWAPI int glfwGetGamepadState(int jid, GLFWgamepadstate* state) if (e->type == _GLFW_JOYSTICK_AXIS) { const float value = js->axes[e->index] * e->axisScale + e->axisOffset; - if (value > 0.f) - state->buttons[i] = GLFW_PRESS; + // HACK: This should be baked into the value transform + // TODO: Bake into transform when implementing output modifiers + if (e->axisOffset < 0 || (e->axisOffset == 0 && e->axisScale > 0)) + { + if (value >= 0.f) + state->buttons[i] = GLFW_PRESS; + } + else + { + if (value <= 0.f) + state->buttons[i] = GLFW_PRESS; + } } else if (e->type == _GLFW_JOYSTICK_HATBIT) { @@ -1250,9 +1296,11 @@ GLFWAPI int glfwGetGamepadState(int jid, GLFWgamepadstate* state) const unsigned int bit = e->index & 0xf; if (js->hats[hat] & bit) state->axes[i] = 1.f; + else + state->axes[i] = -1.f; } else if (e->type == _GLFW_JOYSTICK_BUTTON) - state->axes[i] = (float) js->buttons[e->index]; + state->axes[i] = js->buttons[e->index] * 2.f - 1.f; } return GLFW_TRUE; @@ -1304,4 +1352,3 @@ GLFWAPI uint64_t glfwGetTimerFrequency(void) _GLFW_REQUIRE_INIT_OR_RETURN(0); return _glfwPlatformGetTimerFrequency(); } - diff --git a/src/external/glfw/src/internal.h b/src/external/glfw/src/internal.h index c7c5bf8f..618507c6 100644 --- a/src/external/glfw/src/internal.h +++ b/src/external/glfw/src/internal.h @@ -2,7 +2,7 @@ // GLFW 3.3 - www.glfw.org //------------------------------------------------------------------------ // Copyright (c) 2002-2006 Marcus Geelnard -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2006-2019 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages @@ -390,6 +390,7 @@ struct _GLFWwindow char keys[GLFW_KEY_LAST + 1]; // Virtual cursor position when cursor is disabled double virtualCursorPosX, virtualCursorPosY; + GLFWbool rawMouseMotion; _GLFWcontext context; @@ -596,6 +597,8 @@ const char* _glfwPlatformGetVersionString(void); void _glfwPlatformGetCursorPos(_GLFWwindow* window, double* xpos, double* ypos); void _glfwPlatformSetCursorPos(_GLFWwindow* window, double xpos, double ypos); void _glfwPlatformSetCursorMode(_GLFWwindow* window, int mode); +void _glfwPlatformSetRawMouseMotion(_GLFWwindow *window, GLFWbool enabled); +GLFWbool _glfwPlatformRawMouseMotionSupported(void); int _glfwPlatformCreateCursor(_GLFWcursor* cursor, const GLFWimage* image, int xhot, int yhot); int _glfwPlatformCreateStandardCursor(_GLFWcursor* cursor, int shape); @@ -609,6 +612,7 @@ void _glfwPlatformFreeMonitor(_GLFWmonitor* monitor); void _glfwPlatformGetMonitorPos(_GLFWmonitor* monitor, int* xpos, int* ypos); void _glfwPlatformGetMonitorContentScale(_GLFWmonitor* monitor, float* xscale, float* yscale); +void _glfwPlatformGetMonitorWorkarea(_GLFWmonitor* monitor, int* xpos, int* ypos, int *width, int *height); GLFWvidmode* _glfwPlatformGetVideoModes(_GLFWmonitor* monitor, int* count); void _glfwPlatformGetVideoMode(_GLFWmonitor* monitor, GLFWvidmode* mode); GLFWbool _glfwPlatformGetGammaRamp(_GLFWmonitor* monitor, GLFWgammaramp* ramp); @@ -760,6 +764,7 @@ _GLFWjoystick* _glfwAllocJoystick(const char* name, int buttonCount, int hatCount); void _glfwFreeJoystick(_GLFWjoystick* js); +void _glfwCenterCursorInContentArea(_GLFWwindow* window); GLFWbool _glfwInitVulkan(int mode); void _glfwTerminateVulkan(void); diff --git a/src/external/glfw/src/linux_joystick.c b/src/external/glfw/src/linux_joystick.c index baa3651b..42e457f2 100644 --- a/src/external/glfw/src/linux_joystick.c +++ b/src/external/glfw/src/linux_joystick.c @@ -2,7 +2,7 @@ // GLFW 3.3 Linux - www.glfw.org //------------------------------------------------------------------------ // Copyright (c) 2002-2006 Marcus Geelnard -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2006-2017 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages diff --git a/src/external/glfw/src/mappings.h b/src/external/glfw/src/mappings.h index 97073db5..94a279af 100644 --- a/src/external/glfw/src/mappings.h +++ b/src/external/glfw/src/mappings.h @@ -1,7 +1,7 @@ //======================================================================== // GLFW 3.3 - www.glfw.org //------------------------------------------------------------------------ -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2006-2018 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages diff --git a/src/external/glfw/src/mappings.h.in b/src/external/glfw/src/mappings.h.in index eb6c32f7..72460b0d 100644 --- a/src/external/glfw/src/mappings.h.in +++ b/src/external/glfw/src/mappings.h.in @@ -1,7 +1,7 @@ //======================================================================== // GLFW 3.3 - www.glfw.org //------------------------------------------------------------------------ -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2006-2018 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages diff --git a/src/external/glfw/src/monitor.c b/src/external/glfw/src/monitor.c index 0ab865e3..d390a1c6 100644 --- a/src/external/glfw/src/monitor.c +++ b/src/external/glfw/src/monitor.c @@ -2,7 +2,7 @@ // GLFW 3.3 - www.glfw.org //------------------------------------------------------------------------ // Copyright (c) 2002-2006 Marcus Geelnard -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2006-2019 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages @@ -100,7 +100,7 @@ void _glfwInputMonitor(_GLFWmonitor* monitor, int action, int placement) { memmove(_glfw.monitors + 1, _glfw.monitors, - (_glfw.monitorCount - 1) * sizeof(_GLFWmonitor*)); + ((size_t) _glfw.monitorCount - 1) * sizeof(_GLFWmonitor*)); _glfw.monitors[0] = monitor; } else @@ -130,7 +130,7 @@ void _glfwInputMonitor(_GLFWmonitor* monitor, int action, int placement) _glfw.monitorCount--; memmove(_glfw.monitors + i, _glfw.monitors + i + 1, - (_glfw.monitorCount - i) * sizeof(_GLFWmonitor*)); + ((size_t) _glfw.monitorCount - i) * sizeof(_GLFWmonitor*)); break; } } @@ -330,6 +330,27 @@ GLFWAPI void glfwGetMonitorPos(GLFWmonitor* handle, int* xpos, int* ypos) _glfwPlatformGetMonitorPos(monitor, xpos, ypos); } +GLFWAPI void glfwGetMonitorWorkarea(GLFWmonitor* handle, + int* xpos, int* ypos, + int* width, int* height) +{ + _GLFWmonitor* monitor = (_GLFWmonitor*) handle; + assert(monitor != NULL); + + if (xpos) + *xpos = 0; + if (ypos) + *ypos = 0; + if (width) + *width = 0; + if (height) + *height = 0; + + _GLFW_REQUIRE_INIT(); + + _glfwPlatformGetMonitorWorkarea(monitor, xpos, ypos, width, height); +} + GLFWAPI void glfwGetMonitorPhysicalSize(GLFWmonitor* handle, int* widthMM, int* heightMM) { _GLFWmonitor* monitor = (_GLFWmonitor*) handle; diff --git a/src/external/glfw/src/nsgl_context.h b/src/external/glfw/src/nsgl_context.h index 18042dee..2485b180 100644 --- a/src/external/glfw/src/nsgl_context.h +++ b/src/external/glfw/src/nsgl_context.h @@ -1,7 +1,7 @@ //======================================================================== // GLFW 3.3 macOS - www.glfw.org //------------------------------------------------------------------------ -// Copyright (c) 2009-2016 Camilla Lรถwy +// Copyright (c) 2009-2019 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages @@ -24,16 +24,27 @@ // //======================================================================== +#if MAC_OS_X_VERSION_MAX_ALLOWED < 101400 + #define NSOpenGLContextParameterSwapInterval NSOpenGLCPSwapInterval + #define NSOpenGLContextParameterSurfaceOpacity NSOpenGLCPSurfaceOpacity +#endif + #define _GLFW_PLATFORM_CONTEXT_STATE _GLFWcontextNSGL nsgl #define _GLFW_PLATFORM_LIBRARY_CONTEXT_STATE _GLFWlibraryNSGL nsgl +#include + // NSGL-specific per-context data // typedef struct _GLFWcontextNSGL { - id pixelFormat; - id object; + id pixelFormat; + id object; + CVDisplayLinkRef displayLink; + atomic_int swapInterval; + int swapIntervalsPassed; + id swapIntervalCond; } _GLFWcontextNSGL; @@ -53,4 +64,5 @@ GLFWbool _glfwCreateContextNSGL(_GLFWwindow* window, const _GLFWctxconfig* ctxconfig, const _GLFWfbconfig* fbconfig); void _glfwDestroyContextNSGL(_GLFWwindow* window); +void _glfwUpdateDisplayLinkDisplayNSGL(_GLFWwindow* window); diff --git a/src/external/glfw/src/nsgl_context.m b/src/external/glfw/src/nsgl_context.m index ec1012e9..bbbbd36d 100644 --- a/src/external/glfw/src/nsgl_context.m +++ b/src/external/glfw/src/nsgl_context.m @@ -1,7 +1,7 @@ //======================================================================== // GLFW 3.3 macOS - www.glfw.org //------------------------------------------------------------------------ -// Copyright (c) 2009-2016 Camilla Lรถwy +// Copyright (c) 2009-2019 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages @@ -26,34 +26,75 @@ #include "internal.h" -#if MAC_OS_X_VERSION_MAX_ALLOWED < 101400 - #define NSOpenGLContextParameterSwapInterval NSOpenGLCPSwapInterval - #define NSOpenGLContextParameterSurfaceOpacity NSOpenGLCPSurfaceOpacity -#endif +// Display link callback for manual swap interval implementation +// This is based on a similar workaround added to SDL2 +// +static CVReturn displayLinkCallback(CVDisplayLinkRef displayLink, + const CVTimeStamp* now, + const CVTimeStamp* outputTime, + CVOptionFlags flagsIn, + CVOptionFlags* flagsOut, + void* userInfo) +{ + _GLFWwindow* window = (_GLFWwindow *) userInfo; + + const int interval = atomic_load(&window->context.nsgl.swapInterval); + if (interval > 0) + { + [window->context.nsgl.swapIntervalCond lock]; + window->context.nsgl.swapIntervalsPassed++; + [window->context.nsgl.swapIntervalCond signal]; + [window->context.nsgl.swapIntervalCond unlock]; + } + + return kCVReturnSuccess; +} static void makeContextCurrentNSGL(_GLFWwindow* window) { + @autoreleasepool { + if (window) [window->context.nsgl.object makeCurrentContext]; else [NSOpenGLContext clearCurrentContext]; _glfwPlatformSetTls(&_glfw.contextSlot, window); + + } // autoreleasepool } static void swapBuffersNSGL(_GLFWwindow* window) { + @autoreleasepool { + + const int interval = atomic_load(&window->context.nsgl.swapInterval); + if (interval > 0) + { + [window->context.nsgl.swapIntervalCond lock]; + do + { + [window->context.nsgl.swapIntervalCond wait]; + } while (window->context.nsgl.swapIntervalsPassed % interval != 0); + window->context.nsgl.swapIntervalsPassed = 0; + [window->context.nsgl.swapIntervalCond unlock]; + } + // ARP appears to be unnecessary, but this is future-proof [window->context.nsgl.object flushBuffer]; + + } // autoreleasepool } static void swapIntervalNSGL(int interval) { + @autoreleasepool { _GLFWwindow* window = _glfwPlatformGetTls(&_glfw.contextSlot); - - GLint sync = interval; - [window->context.nsgl.object setValues:&sync - forParameter:NSOpenGLContextParameterSwapInterval]; + atomic_store(&window->context.nsgl.swapInterval, interval); + [window->context.nsgl.swapIntervalCond lock]; + window->context.nsgl.swapIntervalsPassed = 0; + [window->context.nsgl.swapIntervalCond unlock]; + } // autoreleasepool } static int extensionSupportedNSGL(const char* extension) @@ -80,11 +121,26 @@ static GLFWglproc getProcAddressNSGL(const char* procname) // static void destroyContextNSGL(_GLFWwindow* window) { + @autoreleasepool { + + if (window->context.nsgl.displayLink) + { + if (CVDisplayLinkIsRunning(window->context.nsgl.displayLink)) + CVDisplayLinkStop(window->context.nsgl.displayLink); + + CVDisplayLinkRelease(window->context.nsgl.displayLink); + } + + [window->context.nsgl.swapIntervalCond release]; + window->context.nsgl.swapIntervalCond = nil; + [window->context.nsgl.pixelFormat release]; window->context.nsgl.pixelFormat = nil; [window->context.nsgl.object release]; window->context.nsgl.object = nil; + + } // autoreleasepool } @@ -179,9 +235,7 @@ GLFWbool _glfwCreateContextNSGL(_GLFWwindow* window, // Info.plist for unbundled applications // HACK: This assumes that NSOpenGLPixelFormat will remain // a straightforward wrapper of its CGL counterpart -#if MAC_OS_X_VERSION_MAX_ALLOWED >= 1080 addAttrib(kCGLPFASupportsAutomaticGraphicsSwitching); -#endif /*MAC_OS_X_VERSION_MAX_ALLOWED*/ } #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101000 @@ -307,8 +361,17 @@ GLFWbool _glfwCreateContextNSGL(_GLFWwindow* window, forParameter:NSOpenGLContextParameterSurfaceOpacity]; } + if (window->ns.retina) + [window->ns.view setWantsBestResolutionOpenGLSurface:YES]; + + GLint interval = 0; + [window->context.nsgl.object setValues:&interval + forParameter:NSOpenGLContextParameterSwapInterval]; + [window->context.nsgl.object setView:window->ns.view]; + window->context.nsgl.swapIntervalCond = [NSCondition new]; + window->context.makeCurrent = makeContextCurrentNSGL; window->context.swapBuffers = swapBuffersNSGL; window->context.swapInterval = swapIntervalNSGL; @@ -316,9 +379,26 @@ GLFWbool _glfwCreateContextNSGL(_GLFWwindow* window, window->context.getProcAddress = getProcAddressNSGL; window->context.destroy = destroyContextNSGL; + CVDisplayLinkCreateWithActiveCGDisplays(&window->context.nsgl.displayLink); + CVDisplayLinkSetOutputCallback(window->context.nsgl.displayLink, + &displayLinkCallback, + window); + CVDisplayLinkStart(window->context.nsgl.displayLink); + + _glfwUpdateDisplayLinkDisplayNSGL(window); return GLFW_TRUE; } +void _glfwUpdateDisplayLinkDisplayNSGL(_GLFWwindow* window) +{ + CGDirectDisplayID displayID = + [[[window->ns.object screen] deviceDescription][@"NSScreenNumber"] unsignedIntValue]; + if (!displayID) + return; + + CVDisplayLinkSetCurrentCGDisplay(window->context.nsgl.displayLink, displayID); +} + ////////////////////////////////////////////////////////////////////////// ////// GLFW native API ////// diff --git a/src/external/glfw/src/null_init.c b/src/external/glfw/src/null_init.c index 34147388..b48477b6 100644 --- a/src/external/glfw/src/null_init.c +++ b/src/external/glfw/src/null_init.c @@ -2,7 +2,7 @@ // GLFW 3.3 - www.glfw.org //------------------------------------------------------------------------ // Copyright (c) 2016 Google Inc. -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2016-2017 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages diff --git a/src/external/glfw/src/null_joystick.c b/src/external/glfw/src/null_joystick.c index afd65e15..60180bcb 100644 --- a/src/external/glfw/src/null_joystick.c +++ b/src/external/glfw/src/null_joystick.c @@ -1,7 +1,7 @@ //======================================================================== // GLFW 3.3 - www.glfw.org //------------------------------------------------------------------------ -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2016-2017 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages diff --git a/src/external/glfw/src/null_joystick.h b/src/external/glfw/src/null_joystick.h index 3075815d..5a5c5584 100644 --- a/src/external/glfw/src/null_joystick.h +++ b/src/external/glfw/src/null_joystick.h @@ -1,7 +1,7 @@ //======================================================================== // GLFW 3.3 - www.glfw.org //------------------------------------------------------------------------ -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2006-2017 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages diff --git a/src/external/glfw/src/null_monitor.c b/src/external/glfw/src/null_monitor.c index 45c4a10f..f5cb092f 100644 --- a/src/external/glfw/src/null_monitor.c +++ b/src/external/glfw/src/null_monitor.c @@ -2,7 +2,7 @@ // GLFW 3.3 - www.glfw.org //------------------------------------------------------------------------ // Copyright (c) 2016 Google Inc. -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2016-2019 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages @@ -49,6 +49,12 @@ void _glfwPlatformGetMonitorContentScale(_GLFWmonitor* monitor, *yscale = 1.f; } +void _glfwPlatformGetMonitorWorkarea(_GLFWmonitor* monitor, + int* xpos, int* ypos, + int* width, int* height) +{ +} + GLFWvidmode* _glfwPlatformGetVideoModes(_GLFWmonitor* monitor, int* found) { return NULL; diff --git a/src/external/glfw/src/null_platform.h b/src/external/glfw/src/null_platform.h index 2d67c50c..7871683e 100644 --- a/src/external/glfw/src/null_platform.h +++ b/src/external/glfw/src/null_platform.h @@ -2,7 +2,7 @@ // GLFW 3.3 - www.glfw.org //------------------------------------------------------------------------ // Copyright (c) 2016 Google Inc. -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2016-2017 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages diff --git a/src/external/glfw/src/null_window.c b/src/external/glfw/src/null_window.c index 6a54cfe5..67021ab6 100644 --- a/src/external/glfw/src/null_window.c +++ b/src/external/glfw/src/null_window.c @@ -2,7 +2,7 @@ // GLFW 3.3 - www.glfw.org //------------------------------------------------------------------------ // Copyright (c) 2016 Google Inc. -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2016-2019 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages @@ -196,6 +196,15 @@ void _glfwPlatformSetWindowOpacity(_GLFWwindow* window, float opacity) { } +void _glfwPlatformSetRawMouseMotion(_GLFWwindow *window, GLFWbool enabled) +{ +} + +GLFWbool _glfwPlatformRawMouseMotionSupported(void) +{ + return GLFW_FALSE; +} + void _glfwPlatformShowWindow(_GLFWwindow* window) { } diff --git a/src/external/glfw/src/osmesa_context.c b/src/external/glfw/src/osmesa_context.c index 03651ebf..b45bb2e1 100644 --- a/src/external/glfw/src/osmesa_context.c +++ b/src/external/glfw/src/osmesa_context.c @@ -2,7 +2,7 @@ // GLFW 3.3 OSMesa - www.glfw.org //------------------------------------------------------------------------ // Copyright (c) 2016 Google Inc. -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2016-2017 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages @@ -47,7 +47,7 @@ static void makeContextCurrentOSMesa(_GLFWwindow* window) free(window->context.osmesa.buffer); // Allocate the new buffer (width * height * 8-bit RGBA) - window->context.osmesa.buffer = calloc(4, width * height); + window->context.osmesa.buffer = calloc(4, (size_t) width * height); window->context.osmesa.width = width; window->context.osmesa.height = height; } @@ -188,7 +188,7 @@ void _glfwTerminateOSMesa(void) #define setAttrib(a, v) \ { \ - assert((size_t) (index + 1) < sizeof(attribs) / sizeof(attribs[0])); \ + assert(((size_t) index + 1) < sizeof(attribs) / sizeof(attribs[0])); \ attribs[index++] = a; \ attribs[index++] = v; \ } diff --git a/src/external/glfw/src/osmesa_context.h b/src/external/glfw/src/osmesa_context.h index 07bb469a..2413188d 100644 --- a/src/external/glfw/src/osmesa_context.h +++ b/src/external/glfw/src/osmesa_context.h @@ -2,7 +2,7 @@ // GLFW 3.3 OSMesa - www.glfw.org //------------------------------------------------------------------------ // Copyright (c) 2016 Google Inc. -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2016-2017 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages diff --git a/src/external/glfw/src/posix_thread.c b/src/external/glfw/src/posix_thread.c index ce0bc39b..ff4ea60b 100644 --- a/src/external/glfw/src/posix_thread.c +++ b/src/external/glfw/src/posix_thread.c @@ -2,7 +2,7 @@ // GLFW 3.3 POSIX - www.glfw.org //------------------------------------------------------------------------ // Copyright (c) 2002-2006 Marcus Geelnard -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2006-2017 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages diff --git a/src/external/glfw/src/posix_thread.h b/src/external/glfw/src/posix_thread.h index bdddf41a..24452ba0 100644 --- a/src/external/glfw/src/posix_thread.h +++ b/src/external/glfw/src/posix_thread.h @@ -2,7 +2,7 @@ // GLFW 3.3 POSIX - www.glfw.org //------------------------------------------------------------------------ // Copyright (c) 2002-2006 Marcus Geelnard -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2006-2017 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages diff --git a/src/external/glfw/src/posix_time.c b/src/external/glfw/src/posix_time.c index 00b2831d..53f856cc 100644 --- a/src/external/glfw/src/posix_time.c +++ b/src/external/glfw/src/posix_time.c @@ -2,7 +2,7 @@ // GLFW 3.3 POSIX - www.glfw.org //------------------------------------------------------------------------ // Copyright (c) 2002-2006 Marcus Geelnard -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2006-2017 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages diff --git a/src/external/glfw/src/posix_time.h b/src/external/glfw/src/posix_time.h index f1a69eb2..08cf4fcf 100644 --- a/src/external/glfw/src/posix_time.h +++ b/src/external/glfw/src/posix_time.h @@ -2,7 +2,7 @@ // GLFW 3.3 POSIX - www.glfw.org //------------------------------------------------------------------------ // Copyright (c) 2002-2006 Marcus Geelnard -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2006-2017 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages diff --git a/src/external/glfw/src/vulkan.c b/src/external/glfw/src/vulkan.c index b8f752fb..cb326732 100644 --- a/src/external/glfw/src/vulkan.c +++ b/src/external/glfw/src/vulkan.c @@ -2,7 +2,7 @@ // GLFW 3.3 - www.glfw.org //------------------------------------------------------------------------ // Copyright (c) 2002-2006 Marcus Geelnard -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2006-2018 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages diff --git a/src/external/glfw/src/wgl_context.c b/src/external/glfw/src/wgl_context.c index 06ba8b55..5b0d09b8 100644 --- a/src/external/glfw/src/wgl_context.c +++ b/src/external/glfw/src/wgl_context.c @@ -2,7 +2,7 @@ // GLFW 3.3 WGL - www.glfw.org //------------------------------------------------------------------------ // Copyright (c) 2002-2006 Marcus Geelnard -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2006-2019 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages @@ -31,27 +31,34 @@ #include #include - -// Returns the specified attribute of the specified pixel format +// Return the value corresponding to the specified attribute // -static int getPixelFormatAttrib(_GLFWwindow* window, int pixelFormat, int attrib) +static int findPixelFormatAttribValue(const int* attribs, + int attribCount, + const int* values, + int attrib) { - int value = 0; - - assert(_glfw.wgl.ARB_pixel_format); + int i; - if (!_glfw.wgl.GetPixelFormatAttribivARB(window->context.wgl.dc, - pixelFormat, - 0, 1, &attrib, &value)) + for (i = 0; i < attribCount; i++) { - _glfwInputErrorWin32(GLFW_PLATFORM_ERROR, - "WGL: Failed to retrieve pixel format attribute"); - return 0; + if (attribs[i] == attrib) + return values[i]; } - return value; + _glfwInputErrorWin32(GLFW_PLATFORM_ERROR, + "WGL: Unknown pixel format attribute requested"); + return 0; } +#define addAttrib(a) \ +{ \ + assert((size_t) attribCount < sizeof(attribs) / sizeof(attribs[0])); \ + attribs[attribCount++] = a; \ +} +#define findAttribValue(a) \ + findPixelFormatAttribValue(attribs, attribCount, values, a) + // Return a list of available and usable framebuffer configs // static int choosePixelFormat(_GLFWwindow* window, @@ -60,13 +67,58 @@ static int choosePixelFormat(_GLFWwindow* window, { _GLFWfbconfig* usableConfigs; const _GLFWfbconfig* closest; - int i, pixelFormat, nativeCount, usableCount; + int i, pixelFormat, nativeCount, usableCount = 0, attribCount = 0; + int attribs[40]; + int values[sizeof(attribs) / sizeof(attribs[0])]; if (_glfw.wgl.ARB_pixel_format) { - nativeCount = getPixelFormatAttrib(window, - 1, - WGL_NUMBER_PIXEL_FORMATS_ARB); + const int attrib = WGL_NUMBER_PIXEL_FORMATS_ARB; + + if (!_glfw.wgl.GetPixelFormatAttribivARB(window->context.wgl.dc, + 1, 0, 1, &attrib, &nativeCount)) + { + _glfwInputErrorWin32(GLFW_PLATFORM_ERROR, + "WGL: Failed to retrieve pixel format attribute"); + return 0; + } + + addAttrib(WGL_SUPPORT_OPENGL_ARB); + addAttrib(WGL_DRAW_TO_WINDOW_ARB); + addAttrib(WGL_PIXEL_TYPE_ARB); + addAttrib(WGL_ACCELERATION_ARB); + addAttrib(WGL_RED_BITS_ARB); + addAttrib(WGL_RED_SHIFT_ARB); + addAttrib(WGL_GREEN_BITS_ARB); + addAttrib(WGL_GREEN_SHIFT_ARB); + addAttrib(WGL_BLUE_BITS_ARB); + addAttrib(WGL_BLUE_SHIFT_ARB); + addAttrib(WGL_ALPHA_BITS_ARB); + addAttrib(WGL_ALPHA_SHIFT_ARB); + addAttrib(WGL_DEPTH_BITS_ARB); + addAttrib(WGL_STENCIL_BITS_ARB); + addAttrib(WGL_ACCUM_BITS_ARB); + addAttrib(WGL_ACCUM_RED_BITS_ARB); + addAttrib(WGL_ACCUM_GREEN_BITS_ARB); + addAttrib(WGL_ACCUM_BLUE_BITS_ARB); + addAttrib(WGL_ACCUM_ALPHA_BITS_ARB); + addAttrib(WGL_AUX_BUFFERS_ARB); + addAttrib(WGL_STEREO_ARB); + addAttrib(WGL_DOUBLE_BUFFER_ARB); + + if (_glfw.wgl.ARB_multisample) + addAttrib(WGL_SAMPLES_ARB); + + if (ctxconfig->client == GLFW_OPENGL_API) + { + if (_glfw.wgl.ARB_framebuffer_sRGB || _glfw.wgl.EXT_framebuffer_sRGB) + addAttrib(WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB); + } + else + { + if (_glfw.wgl.EXT_colorspace) + addAttrib(WGL_COLORSPACE_EXT); + } } else { @@ -77,64 +129,69 @@ static int choosePixelFormat(_GLFWwindow* window, } usableConfigs = calloc(nativeCount, sizeof(_GLFWfbconfig)); - usableCount = 0; for (i = 0; i < nativeCount; i++) { - const int n = i + 1; _GLFWfbconfig* u = usableConfigs + usableCount; + pixelFormat = i + 1; if (_glfw.wgl.ARB_pixel_format) { // Get pixel format attributes through "modern" extension - if (!getPixelFormatAttrib(window, n, WGL_SUPPORT_OPENGL_ARB) || - !getPixelFormatAttrib(window, n, WGL_DRAW_TO_WINDOW_ARB)) + if (!_glfw.wgl.GetPixelFormatAttribivARB(window->context.wgl.dc, + pixelFormat, 0, + attribCount, + attribs, values)) { - continue; + _glfwInputErrorWin32(GLFW_PLATFORM_ERROR, + "WGL: Failed to retrieve pixel format attributes"); + + free(usableConfigs); + return 0; } - if (getPixelFormatAttrib(window, n, WGL_PIXEL_TYPE_ARB) != - WGL_TYPE_RGBA_ARB) + if (!findAttribValue(WGL_SUPPORT_OPENGL_ARB) || + !findAttribValue(WGL_DRAW_TO_WINDOW_ARB)) { continue; } - if (getPixelFormatAttrib(window, n, WGL_ACCELERATION_ARB) == - WGL_NO_ACCELERATION_ARB) - { + if (findAttribValue(WGL_PIXEL_TYPE_ARB) != WGL_TYPE_RGBA_ARB) + continue; + + if (findAttribValue(WGL_ACCELERATION_ARB) == WGL_NO_ACCELERATION_ARB) continue; - } - u->redBits = getPixelFormatAttrib(window, n, WGL_RED_BITS_ARB); - u->greenBits = getPixelFormatAttrib(window, n, WGL_GREEN_BITS_ARB); - u->blueBits = getPixelFormatAttrib(window, n, WGL_BLUE_BITS_ARB); - u->alphaBits = getPixelFormatAttrib(window, n, WGL_ALPHA_BITS_ARB); + u->redBits = findAttribValue(WGL_RED_BITS_ARB); + u->greenBits = findAttribValue(WGL_GREEN_BITS_ARB); + u->blueBits = findAttribValue(WGL_BLUE_BITS_ARB); + u->alphaBits = findAttribValue(WGL_ALPHA_BITS_ARB); - u->depthBits = getPixelFormatAttrib(window, n, WGL_DEPTH_BITS_ARB); - u->stencilBits = getPixelFormatAttrib(window, n, WGL_STENCIL_BITS_ARB); + u->depthBits = findAttribValue(WGL_DEPTH_BITS_ARB); + u->stencilBits = findAttribValue(WGL_STENCIL_BITS_ARB); - u->accumRedBits = getPixelFormatAttrib(window, n, WGL_ACCUM_RED_BITS_ARB); - u->accumGreenBits = getPixelFormatAttrib(window, n, WGL_ACCUM_GREEN_BITS_ARB); - u->accumBlueBits = getPixelFormatAttrib(window, n, WGL_ACCUM_BLUE_BITS_ARB); - u->accumAlphaBits = getPixelFormatAttrib(window, n, WGL_ACCUM_ALPHA_BITS_ARB); + u->accumRedBits = findAttribValue(WGL_ACCUM_RED_BITS_ARB); + u->accumGreenBits = findAttribValue(WGL_ACCUM_GREEN_BITS_ARB); + u->accumBlueBits = findAttribValue(WGL_ACCUM_BLUE_BITS_ARB); + u->accumAlphaBits = findAttribValue(WGL_ACCUM_ALPHA_BITS_ARB); - u->auxBuffers = getPixelFormatAttrib(window, n, WGL_AUX_BUFFERS_ARB); + u->auxBuffers = findAttribValue(WGL_AUX_BUFFERS_ARB); - if (getPixelFormatAttrib(window, n, WGL_STEREO_ARB)) + if (findAttribValue(WGL_STEREO_ARB)) u->stereo = GLFW_TRUE; - if (getPixelFormatAttrib(window, n, WGL_DOUBLE_BUFFER_ARB)) + if (findAttribValue(WGL_DOUBLE_BUFFER_ARB)) u->doublebuffer = GLFW_TRUE; if (_glfw.wgl.ARB_multisample) - u->samples = getPixelFormatAttrib(window, n, WGL_SAMPLES_ARB); + u->samples = findAttribValue(WGL_SAMPLES_ARB); if (ctxconfig->client == GLFW_OPENGL_API) { if (_glfw.wgl.ARB_framebuffer_sRGB || _glfw.wgl.EXT_framebuffer_sRGB) { - if (getPixelFormatAttrib(window, n, WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB)) + if (findAttribValue(WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB)) u->sRGB = GLFW_TRUE; } } @@ -142,11 +199,8 @@ static int choosePixelFormat(_GLFWwindow* window, { if (_glfw.wgl.EXT_colorspace) { - if (getPixelFormatAttrib(window, n, WGL_COLORSPACE_EXT) == - WGL_COLORSPACE_SRGB_EXT) - { + if (findAttribValue(WGL_COLORSPACE_EXT) == WGL_COLORSPACE_SRGB_EXT) u->sRGB = GLFW_TRUE; - } } } } @@ -157,11 +211,15 @@ static int choosePixelFormat(_GLFWwindow* window, PIXELFORMATDESCRIPTOR pfd; if (!DescribePixelFormat(window->context.wgl.dc, - n, + pixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &pfd)) { - continue; + _glfwInputErrorWin32(GLFW_PLATFORM_ERROR, + "WGL: Failed to describe pixel format"); + + free(usableConfigs); + return 0; } if (!(pfd.dwFlags & PFD_DRAW_TO_WINDOW) || @@ -200,7 +258,7 @@ static int choosePixelFormat(_GLFWwindow* window, u->doublebuffer = GLFW_TRUE; } - u->handle = n; + u->handle = pixelFormat; usableCount++; } @@ -229,6 +287,9 @@ static int choosePixelFormat(_GLFWwindow* window, return pixelFormat; } +#undef addAttrib +#undef findAttribValue + static void makeContextCurrentWGL(_GLFWwindow* window) { if (window) @@ -260,10 +321,12 @@ static void swapBuffersWGL(_GLFWwindow* window) { if (IsWindowsVistaOrGreater()) { - BOOL enabled; + // DWM Composition is always enabled on Win8+ + BOOL enabled = IsWindows8OrGreater(); // HACK: Use DwmFlush when desktop composition is enabled - if (SUCCEEDED(DwmIsCompositionEnabled(&enabled)) && enabled) + if (enabled || + (SUCCEEDED(DwmIsCompositionEnabled(&enabled)) && enabled)) { int count = abs(window->context.wgl.interval); while (count--) @@ -285,11 +348,13 @@ static void swapIntervalWGL(int interval) { if (IsWindowsVistaOrGreater()) { - BOOL enabled; + // DWM Composition is always enabled on Win8+ + BOOL enabled = IsWindows8OrGreater(); // HACK: Disable WGL swap interval when desktop composition is enabled to // avoid interfering with DWM vsync - if (SUCCEEDED(DwmIsCompositionEnabled(&enabled)) && enabled) + if (enabled || + (SUCCEEDED(DwmIsCompositionEnabled(&enabled)) && enabled)) interval = 0; } } @@ -377,7 +442,7 @@ GLFWbool _glfwInitWGL(void) // NOTE: This code will accept the Microsoft GDI ICD; accelerated context // creation failure occurs during manual pixel format enumeration - dc = GetDC(_glfw.win32.helperWindowHandle);; + dc = GetDC(_glfw.win32.helperWindowHandle); ZeroMemory(&pfd, sizeof(pfd)); pfd.nSize = sizeof(pfd); @@ -468,7 +533,7 @@ void _glfwTerminateWGL(void) #define setAttrib(a, v) \ { \ - assert((size_t) (index + 1) < sizeof(attribs) / sizeof(attribs[0])); \ + assert(((size_t) index + 1) < sizeof(attribs) / sizeof(attribs[0])); \ attribs[index++] = a; \ attribs[index++] = v; \ } diff --git a/src/external/glfw/src/wgl_context.h b/src/external/glfw/src/wgl_context.h index c7540386..fa6605bc 100644 --- a/src/external/glfw/src/wgl_context.h +++ b/src/external/glfw/src/wgl_context.h @@ -2,7 +2,7 @@ // GLFW 3.3 WGL - www.glfw.org //------------------------------------------------------------------------ // Copyright (c) 2002-2006 Marcus Geelnard -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2006-2018 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages diff --git a/src/external/glfw/src/win32_init.c b/src/external/glfw/src/win32_init.c index 3ee5eb85..e28868f4 100644 --- a/src/external/glfw/src/win32_init.c +++ b/src/external/glfw/src/win32_init.c @@ -2,7 +2,7 @@ // GLFW 3.3 Win32 - www.glfw.org //------------------------------------------------------------------------ // Copyright (c) 2002-2006 Marcus Geelnard -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2006-2019 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages @@ -329,27 +329,30 @@ static void createKeyTables(void) // Creates a dummy window for behind-the-scenes work // -static HWND createHelperWindow(void) +static GLFWbool createHelperWindow(void) { MSG msg; - HWND window = CreateWindowExW(WS_EX_OVERLAPPEDWINDOW, - _GLFW_WNDCLASSNAME, - L"GLFW message window", - WS_CLIPSIBLINGS | WS_CLIPCHILDREN, - 0, 0, 1, 1, - NULL, NULL, - GetModuleHandleW(NULL), - NULL); - if (!window) + + _glfw.win32.helperWindowHandle = + CreateWindowExW(WS_EX_OVERLAPPEDWINDOW, + _GLFW_WNDCLASSNAME, + L"GLFW message window", + WS_CLIPSIBLINGS | WS_CLIPCHILDREN, + 0, 0, 1, 1, + NULL, NULL, + GetModuleHandleW(NULL), + NULL); + + if (!_glfw.win32.helperWindowHandle) { _glfwInputErrorWin32(GLFW_PLATFORM_ERROR, "Win32: Failed to create helper window"); - return NULL; + return GLFW_FALSE; } // HACK: The command to the first ShowWindow call is ignored if the parent // process passed along a STARTUPINFO, so clear that with a no-op call - ShowWindow(window, SW_HIDE); + ShowWindow(_glfw.win32.helperWindowHandle, SW_HIDE); // Register for HID device notifications { @@ -360,7 +363,7 @@ static HWND createHelperWindow(void) dbi.dbcc_classguid = GUID_DEVINTERFACE_HID; _glfw.win32.deviceNotificationHandle = - RegisterDeviceNotificationW(window, + RegisterDeviceNotificationW(_glfw.win32.helperWindowHandle, (DEV_BROADCAST_HDR*) &dbi, DEVICE_NOTIFY_WINDOW_HANDLE); } @@ -371,7 +374,7 @@ static HWND createHelperWindow(void) DispatchMessageW(&msg); } - return window; + return GLFW_TRUE; } @@ -449,7 +452,7 @@ void _glfwInputErrorWin32(int error, const char* description) GetLastError() & 0xffff, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buffer, - sizeof(buffer), + sizeof(buffer) / sizeof(WCHAR), NULL); WideCharToMultiByte(CP_UTF8, 0, buffer, -1, message, sizeof(message), NULL, NULL); @@ -571,8 +574,7 @@ int _glfwPlatformInit(void) if (!_glfwRegisterWindowClassWin32()) return GLFW_FALSE; - _glfw.win32.helperWindowHandle = createHelperWindow(); - if (!_glfw.win32.helperWindowHandle) + if (!createHelperWindow()) return GLFW_FALSE; _glfwInitTimerWin32(); @@ -610,7 +612,7 @@ void _glfwPlatformTerminate(void) const char* _glfwPlatformGetVersionString(void) { - return _GLFW_VERSION_NUMBER " Win32 WGL EGL" + return _GLFW_VERSION_NUMBER " Win32 WGL EGL OSMesa" #if defined(__MINGW32__) " MinGW" #elif defined(_MSC_VER) diff --git a/src/external/glfw/src/win32_joystick.c b/src/external/glfw/src/win32_joystick.c index 58123965..5c3e87de 100644 --- a/src/external/glfw/src/win32_joystick.c +++ b/src/external/glfw/src/win32_joystick.c @@ -2,7 +2,7 @@ // GLFW 3.3 Win32 - www.glfw.org //------------------------------------------------------------------------ // Copyright (c) 2002-2006 Marcus Geelnard -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2006-2019 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages @@ -414,7 +414,7 @@ static BOOL CALLBACK deviceCallback(const DIDEVICEINSTANCE* di, void* user) memset(&data, 0, sizeof(data)); data.device = device; - data.objects = calloc(dc.dwAxes + dc.dwButtons + dc.dwPOVs, + data.objects = calloc(dc.dwAxes + (size_t) dc.dwButtons + dc.dwPOVs, sizeof(_GLFWjoyobjectWin32)); if (FAILED(IDirectInputDevice8_EnumObjects(device, @@ -745,7 +745,7 @@ void _glfwPlatformUpdateGamepadGUID(char* guid) if (strcmp(guid + 20, "504944564944") == 0) { char original[33]; - strcpy(original, guid); + strncpy(original, guid, sizeof(original) - 1); sprintf(guid, "03000000%.4s0000%.4s000000000000", original, original + 4); } diff --git a/src/external/glfw/src/win32_joystick.h b/src/external/glfw/src/win32_joystick.h index 9156f6c1..22bcded3 100644 --- a/src/external/glfw/src/win32_joystick.h +++ b/src/external/glfw/src/win32_joystick.h @@ -1,7 +1,7 @@ //======================================================================== // GLFW 3.3 Win32 - www.glfw.org //------------------------------------------------------------------------ -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2006-2017 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages diff --git a/src/external/glfw/src/win32_monitor.c b/src/external/glfw/src/win32_monitor.c index 07b3614b..e6875dbc 100644 --- a/src/external/glfw/src/win32_monitor.c +++ b/src/external/glfw/src/win32_monitor.c @@ -2,7 +2,7 @@ // GLFW 3.3 Win32 - www.glfw.org //------------------------------------------------------------------------ // Copyright (c) 2002-2006 Marcus Geelnard -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2006-2019 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages @@ -361,6 +361,23 @@ void _glfwPlatformGetMonitorContentScale(_GLFWmonitor* monitor, _glfwGetMonitorContentScaleWin32(monitor->win32.handle, xscale, yscale); } +void _glfwPlatformGetMonitorWorkarea(_GLFWmonitor* monitor, + int* xpos, int* ypos, + int* width, int* height) +{ + MONITORINFO mi = { sizeof(mi) }; + GetMonitorInfo(monitor->win32.handle, &mi); + + if (xpos) + *xpos = mi.rcWork.left; + if (ypos) + *ypos = mi.rcWork.top; + if (width) + *width = mi.rcWork.right - mi.rcWork.left; + if (height) + *height = mi.rcWork.bottom - mi.rcWork.top; +} + GLFWvidmode* _glfwPlatformGetVideoModes(_GLFWmonitor* monitor, int* count) { int modeIndex = 0, size = 0; diff --git a/src/external/glfw/src/win32_platform.h b/src/external/glfw/src/win32_platform.h index 712de7f1..07e43776 100644 --- a/src/external/glfw/src/win32_platform.h +++ b/src/external/glfw/src/win32_platform.h @@ -2,7 +2,7 @@ // GLFW 3.3 Win32 - www.glfw.org //------------------------------------------------------------------------ // Copyright (c) 2002-2006 Marcus Geelnard -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2006-2019 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages @@ -61,6 +61,9 @@ // GLFW uses DirectInput8 interfaces #define DIRECTINPUT_VERSION 0x0800 +// GLFW uses OEM cursor resources +#define OEMRESOURCE + #include #include #include @@ -98,12 +101,18 @@ #ifndef _WIN32_WINNT_WINBLUE #define _WIN32_WINNT_WINBLUE 0x0602 #endif +#ifndef _WIN32_WINNT_WIN8 + #define _WIN32_WINNT_WIN8 0x0602 +#endif #ifndef WM_GETDPISCALEDSIZE #define WM_GETDPISCALEDSIZE 0x02e4 #endif #ifndef USER_DEFAULT_SCREEN_DPI #define USER_DEFAULT_SCREEN_DPI 96 #endif +#ifndef OCR_HAND + #define OCR_HAND 32649 +#endif #if WINVER < 0x0601 typedef struct diff --git a/src/external/glfw/src/win32_thread.c b/src/external/glfw/src/win32_thread.c index 98231c1e..9391fc9b 100644 --- a/src/external/glfw/src/win32_thread.c +++ b/src/external/glfw/src/win32_thread.c @@ -2,7 +2,7 @@ // GLFW 3.3 Win32 - www.glfw.org //------------------------------------------------------------------------ // Copyright (c) 2002-2006 Marcus Geelnard -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2006-2017 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages diff --git a/src/external/glfw/src/win32_time.c b/src/external/glfw/src/win32_time.c index f333cd44..29670f97 100644 --- a/src/external/glfw/src/win32_time.c +++ b/src/external/glfw/src/win32_time.c @@ -2,7 +2,7 @@ // GLFW 3.3 Win32 - www.glfw.org //------------------------------------------------------------------------ // Copyright (c) 2002-2006 Marcus Geelnard -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2006-2017 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages diff --git a/src/external/glfw/src/win32_window.c b/src/external/glfw/src/win32_window.c index a0abca06..48b3dd5d 100644 --- a/src/external/glfw/src/win32_window.c +++ b/src/external/glfw/src/win32_window.c @@ -2,7 +2,7 @@ // GLFW 3.3 Win32 - www.glfw.org //------------------------------------------------------------------------ // Copyright (c) 2002-2006 Marcus Geelnard -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2006-2019 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages @@ -186,14 +186,14 @@ static HICON createIcon(const GLFWimage* image, return handle; } -// Translate client window size to full window size according to styles and DPI +// Translate content area size to full window size according to styles and DPI // static void getFullWindowSize(DWORD style, DWORD exStyle, - int clientWidth, int clientHeight, + int contentWidth, int contentHeight, int* fullWidth, int* fullHeight, UINT dpi) { - RECT rect = { 0, 0, clientWidth, clientHeight }; + RECT rect = { 0, 0, contentWidth, contentHeight }; if (_glfwIsWindows10AnniversaryUpdateOrGreaterWin32()) AdjustWindowRectExForDpi(&rect, style, FALSE, exStyle, dpi); @@ -204,7 +204,7 @@ static void getFullWindowSize(DWORD style, DWORD exStyle, *fullHeight = rect.bottom - rect.top; } -// Enforce the client rect aspect ratio based on which edge is being dragged +// Enforce the content area aspect ratio based on which edge is being dragged // static void applyAspectRatio(_GLFWwindow* window, int edge, RECT* area) { @@ -236,15 +236,6 @@ static void applyAspectRatio(_GLFWwindow* window, int edge, RECT* area) } } -// Centers the cursor over the window client area -// -static void centerCursor(_GLFWwindow* window) -{ - int width, height; - _glfwPlatformGetWindowSize(window, &width, &height); - _glfwPlatformSetCursorPos(window, width / 2.0, height / 2.0); -} - // Updates the cursor image according to its cursor mode // static void updateCursorImage(_GLFWwindow* window) @@ -276,32 +267,54 @@ static void updateClipRect(_GLFWwindow* window) ClipCursor(NULL); } -// Apply disabled cursor mode to a focused window +// Enables WM_INPUT messages for the mouse for the specified window // -static void disableCursor(_GLFWwindow* window) +static void enableRawMouseMotion(_GLFWwindow* window) { const RAWINPUTDEVICE rid = { 0x01, 0x02, 0, window->win32.handle }; + if (!RegisterRawInputDevices(&rid, 1, sizeof(rid))) + { + _glfwInputErrorWin32(GLFW_PLATFORM_ERROR, + "Win32: Failed to register raw input device"); + } +} + +// Disables WM_INPUT messages for the mouse +// +static void disableRawMouseMotion(_GLFWwindow* window) +{ + const RAWINPUTDEVICE rid = { 0x01, 0x02, RIDEV_REMOVE, NULL }; + + if (!RegisterRawInputDevices(&rid, 1, sizeof(rid))) + { + _glfwInputErrorWin32(GLFW_PLATFORM_ERROR, + "Win32: Failed to remove raw input device"); + } +} + +// Apply disabled cursor mode to a focused window +// +static void disableCursor(_GLFWwindow* window) +{ _glfw.win32.disabledCursorWindow = window; _glfwPlatformGetCursorPos(window, &_glfw.win32.restoreCursorPosX, &_glfw.win32.restoreCursorPosY); updateCursorImage(window); - centerCursor(window); + _glfwCenterCursorInContentArea(window); updateClipRect(window); - if (!RegisterRawInputDevices(&rid, 1, sizeof(rid))) - { - _glfwInputErrorWin32(GLFW_PLATFORM_ERROR, - "Win32: Failed to register raw input device"); - } + if (window->rawMouseMotion) + enableRawMouseMotion(window); } // Exit disabled cursor mode for the specified window // static void enableCursor(_GLFWwindow* window) { - const RAWINPUTDEVICE rid = { 0x01, 0x02, RIDEV_REMOVE, NULL }; + if (window->rawMouseMotion) + disableRawMouseMotion(window); _glfw.win32.disabledCursorWindow = NULL; updateClipRect(NULL); @@ -309,17 +322,11 @@ static void enableCursor(_GLFWwindow* window) _glfw.win32.restoreCursorPosX, _glfw.win32.restoreCursorPosY); updateCursorImage(window); - - if (!RegisterRawInputDevices(&rid, 1, sizeof(rid))) - { - _glfwInputErrorWin32(GLFW_PLATFORM_ERROR, - "Win32: Failed to remove raw input device"); - } } -// Returns whether the cursor is in the client area of the specified window +// Returns whether the cursor is in the content area of the specified window // -static GLFWbool cursorInClientArea(_GLFWwindow* window) +static GLFWbool cursorInContentArea(_GLFWwindow* window) { RECT area; POINT pos; @@ -825,9 +832,21 @@ static LRESULT CALLBACK windowProc(HWND hWnd, UINT uMsg, // Disabled cursor motion input is provided by WM_INPUT if (window->cursorMode == GLFW_CURSOR_DISABLED) - break; + { + const int dx = x - window->win32.lastCursorPosX; + const int dy = y - window->win32.lastCursorPosY; + + if (_glfw.win32.disabledCursorWindow != window) + break; + if (window->rawMouseMotion) + break; - _glfwInputCursorPos(window, x, y); + _glfwInputCursorPos(window, + window->virtualCursorPosX + dx, + window->virtualCursorPosY + dy); + } + else + _glfwInputCursorPos(window, x, y); window->win32.lastCursorPosX = x; window->win32.lastCursorPosY = y; @@ -850,14 +869,15 @@ static LRESULT CALLBACK windowProc(HWND hWnd, UINT uMsg, case WM_INPUT: { - UINT size; + UINT size = 0; HRAWINPUT ri = (HRAWINPUT) lParam; - RAWINPUT* data; + RAWINPUT* data = NULL; int dx, dy; - // Only process input when disabled cursor mode is applied if (_glfw.win32.disabledCursorWindow != window) break; + if (!window->rawMouseMotion) + break; GetRawInputData(ri, RID_INPUT, NULL, &size, sizeof(RAWINPUTHEADER)); if (size > (UINT) _glfw.win32.rawInputSize) @@ -1083,7 +1103,7 @@ static LRESULT CALLBACK windowProc(HWND hWnd, UINT uMsg, if (window->win32.scaleToMonitor) break; - // Adjust the window size to keep the client area size constant + // Adjust the window size to keep the content area size constant if (_glfwIsWindows10CreatorsUpdateOrGreaterWin32()) { RECT source = {0}, target = {0}; @@ -1155,7 +1175,7 @@ static LRESULT CALLBACK windowProc(HWND hWnd, UINT uMsg, for (i = 0; i < count; i++) { const UINT length = DragQueryFileW(drop, i, NULL, 0); - WCHAR* buffer = calloc(length + 1, sizeof(WCHAR)); + WCHAR* buffer = calloc((size_t) length + 1, sizeof(WCHAR)); DragQueryFileW(drop, i, buffer, length + 1); paths[i] = _glfwCreateUTF8FromWideStringWin32(buffer); @@ -1253,7 +1273,7 @@ static int createNativeWindow(_GLFWwindow* window, window->win32.scaleToMonitor = wndconfig->scaleToMonitor; // Adjust window size to account for DPI scaling of the window frame and - // optionally DPI scaling of the client area + // optionally DPI scaling of the content area // This cannot be done until we know what monitor it was placed on if (!window->monitor) { @@ -1788,7 +1808,7 @@ int _glfwPlatformWindowMaximized(_GLFWwindow* window) int _glfwPlatformWindowHovered(_GLFWwindow* window) { - return cursorInClientArea(window); + return cursorInContentArea(window); } int _glfwPlatformFramebufferTransparent(_GLFWwindow* window) @@ -1854,6 +1874,22 @@ void _glfwPlatformSetWindowOpacity(_GLFWwindow* window, float opacity) } } +void _glfwPlatformSetRawMouseMotion(_GLFWwindow *window, GLFWbool enabled) +{ + if (_glfw.win32.disabledCursorWindow != window) + return; + + if (enabled) + enableRawMouseMotion(window); + else + disableRawMouseMotion(window); +} + +GLFWbool _glfwPlatformRawMouseMotionSupported(void) +{ + return GLFW_TRUE; +} + void _glfwPlatformPollEvents(void) { MSG msg; @@ -1981,7 +2017,7 @@ void _glfwPlatformSetCursorMode(_GLFWwindow* window, int mode) } else if (_glfw.win32.disabledCursorWindow == window) enableCursor(window); - else if (cursorInClientArea(window)) + else if (cursorInContentArea(window)) updateCursorImage(window); } @@ -2008,24 +2044,26 @@ int _glfwPlatformCreateCursor(_GLFWcursor* cursor, int _glfwPlatformCreateStandardCursor(_GLFWcursor* cursor, int shape) { - LPCWSTR name = NULL; + int id = 0; if (shape == GLFW_ARROW_CURSOR) - name = IDC_ARROW; + id = OCR_NORMAL; else if (shape == GLFW_IBEAM_CURSOR) - name = IDC_IBEAM; + id = OCR_IBEAM; else if (shape == GLFW_CROSSHAIR_CURSOR) - name = IDC_CROSS; + id = OCR_CROSS; else if (shape == GLFW_HAND_CURSOR) - name = IDC_HAND; + id = OCR_HAND; else if (shape == GLFW_HRESIZE_CURSOR) - name = IDC_SIZEWE; + id = OCR_SIZEWE; else if (shape == GLFW_VRESIZE_CURSOR) - name = IDC_SIZENS; + id = OCR_SIZENS; else return GLFW_FALSE; - cursor->win32.handle = CopyCursor(LoadCursorW(NULL, name)); + cursor->win32.handle = LoadImageW(NULL, + MAKEINTRESOURCEW(id), IMAGE_CURSOR, 0, 0, + LR_DEFAULTSIZE | LR_SHARED); if (!cursor->win32.handle) { _glfwInputErrorWin32(GLFW_PLATFORM_ERROR, @@ -2044,7 +2082,7 @@ void _glfwPlatformDestroyCursor(_GLFWcursor* cursor) void _glfwPlatformSetCursor(_GLFWwindow* window, _GLFWcursor* cursor) { - if (cursorInClientArea(window)) + if (cursorInContentArea(window)) updateCursorImage(window); } diff --git a/src/external/glfw/src/window.c b/src/external/glfw/src/window.c index 4e365cb4..cf403dd0 100644 --- a/src/external/glfw/src/window.c +++ b/src/external/glfw/src/window.c @@ -2,7 +2,7 @@ // GLFW 3.3 - www.glfw.org //------------------------------------------------------------------------ // Copyright (c) 2002-2006 Marcus Geelnard -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2006-2019 Camilla Lรถwy // Copyright (c) 2012 Torsten Walluhn // // This software is provided 'as-is', without any express or implied @@ -67,7 +67,7 @@ void _glfwInputWindowFocus(_GLFWwindow* window, GLFWbool focused) } // Notifies shared code that a window has moved -// The position is specified in client-area relative screen coordinates +// The position is specified in content area relative screen coordinates // void _glfwInputWindowPos(_GLFWwindow* window, int x, int y) { @@ -143,7 +143,6 @@ void _glfwInputWindowMonitor(_GLFWwindow* window, _GLFWmonitor* monitor) window->monitor = monitor; } - ////////////////////////////////////////////////////////////////////////// ////// GLFW public API ////// ////////////////////////////////////////////////////////////////////////// @@ -230,11 +229,7 @@ GLFWAPI GLFWwindow* glfwCreateWindow(int width, int height, if (window->monitor) { if (wndconfig.centerCursor) - { - int width, height; - _glfwPlatformGetWindowSize(window, &width, &height); - _glfwPlatformSetCursorPos(window, width / 2.0, height / 2.0); - } + _glfwCenterCursorInContentArea(window); } else { @@ -1078,10 +1073,6 @@ GLFWAPI void glfwPollEvents(void) GLFWAPI void glfwWaitEvents(void) { _GLFW_REQUIRE_INIT(); - - if (!_glfw.windowListHead) - return; - _glfwPlatformWaitEvents(); } @@ -1104,10 +1095,5 @@ GLFWAPI void glfwWaitEventsTimeout(double timeout) GLFWAPI void glfwPostEmptyEvent(void) { _GLFW_REQUIRE_INIT(); - - if (!_glfw.windowListHead) - return; - _glfwPlatformPostEmptyEvent(); } - diff --git a/src/external/glfw/src/wl_init.c b/src/external/glfw/src/wl_init.c index c6b209bc..8a6b918c 100644 --- a/src/external/glfw/src/wl_init.c +++ b/src/external/glfw/src/wl_init.c @@ -589,8 +589,10 @@ static void keyboardHandleKey(void* data, { _glfw.wl.keyboardLastKey = keyCode; _glfw.wl.keyboardLastScancode = key; - timer.it_interval.tv_sec = _glfw.wl.keyboardRepeatRate / 1000; - timer.it_interval.tv_nsec = (_glfw.wl.keyboardRepeatRate % 1000) * 1000000; + if (_glfw.wl.keyboardRepeatRate > 1) + timer.it_interval.tv_nsec = 1000000000 / _glfw.wl.keyboardRepeatRate; + else + timer.it_interval.tv_sec = 1; timer.it_value.tv_sec = _glfw.wl.keyboardRepeatDelay / 1000; timer.it_value.tv_nsec = (_glfw.wl.keyboardRepeatDelay % 1000) * 1000000; } @@ -1304,7 +1306,7 @@ void _glfwPlatformTerminate(void) const char* _glfwPlatformGetVersionString(void) { - return _GLFW_VERSION_NUMBER " Wayland EGL" + return _GLFW_VERSION_NUMBER " Wayland EGL OSMesa" #if defined(_POSIX_TIMERS) && defined(_POSIX_MONOTONIC_CLOCK) " clock_gettime" #else diff --git a/src/external/glfw/src/wl_monitor.c b/src/external/glfw/src/wl_monitor.c index 588f8b0d..223c3b8d 100644 --- a/src/external/glfw/src/wl_monitor.c +++ b/src/external/glfw/src/wl_monitor.c @@ -30,6 +30,7 @@ #include #include #include +#include static void outputHandleGeometry(void* data, @@ -70,7 +71,7 @@ static void outputHandleMode(void* data, mode.redBits = 8; mode.greenBits = 8; mode.blueBits = 8; - mode.refreshRate = refresh / 1000; + mode.refreshRate = (int) round(refresh / 1000.0); monitor->modeCount++; monitor->modes = @@ -169,6 +170,20 @@ void _glfwPlatformGetMonitorContentScale(_GLFWmonitor* monitor, *yscale = (float) monitor->wl.scale; } +void _glfwPlatformGetMonitorWorkarea(_GLFWmonitor* monitor, + int* xpos, int* ypos, + int* width, int* height) +{ + if (xpos) + *xpos = monitor->wl.x; + if (ypos) + *ypos = monitor->wl.y; + if (width) + *width = monitor->modes[monitor->wl.currentMode].width; + if (height) + *height = monitor->modes[monitor->wl.currentMode].height; +} + GLFWvidmode* _glfwPlatformGetVideoModes(_GLFWmonitor* monitor, int* found) { *found = monitor->modeCount; diff --git a/src/external/glfw/src/wl_platform.h b/src/external/glfw/src/wl_platform.h index c17ebe88..9fef848d 100644 --- a/src/external/glfw/src/wl_platform.h +++ b/src/external/glfw/src/wl_platform.h @@ -208,8 +208,7 @@ typedef struct _GLFWwindowWayland struct zwp_idle_inhibitor_v1* idleInhibitor; - // This is a hack to prevent auto-iconification on creation. - GLFWbool justCreated; + GLFWbool wasFullscreen; struct { GLFWbool serverSide; diff --git a/src/external/glfw/src/wl_window.c b/src/external/glfw/src/wl_window.c index 98a64659..0ae712dd 100644 --- a/src/external/glfw/src/wl_window.c +++ b/src/external/glfw/src/wl_window.c @@ -156,6 +156,9 @@ static int createAnonymousFile(off_t size) fcntl(fd, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_SEAL); } else +#elif defined(SHM_ANON) + fd = shm_open(SHM_ANON, O_RDWR | O_CLOEXEC, 0600); + if (fd < 0) #endif { path = getenv("XDG_RUNTIME_DIR"); @@ -175,7 +178,12 @@ static int createAnonymousFile(off_t size) return -1; } +#if defined(SHM_ANON) + // posix_fallocate does not work on SHM descriptors + ret = ftruncate(fd, size); +#else ret = posix_fallocate(fd, 0, size); +#endif if (ret != 0) { close(fd); @@ -633,10 +641,17 @@ static void xdgToplevelHandleConfigure(void* data, _glfwInputWindowDamage(window); } - if (!window->wl.justCreated && !activated && window->autoIconify) - _glfwPlatformIconifyWindow(window); + if (window->wl.wasFullscreen && window->autoIconify) + { + if (!activated || !fullscreen) + { + _glfwPlatformIconifyWindow(window); + window->wl.wasFullscreen = GLFW_FALSE; + } + } + if (fullscreen && activated) + window->wl.wasFullscreen = GLFW_TRUE; _glfwInputWindowFocus(window, activated); - window->wl.justCreated = GLFW_FALSE; } static void xdgToplevelHandleClose(void* data, @@ -905,7 +920,6 @@ int _glfwPlatformCreateWindow(_GLFWwindow* window, const _GLFWctxconfig* ctxconfig, const _GLFWfbconfig* fbconfig) { - window->wl.justCreated = GLFW_TRUE; window->wl.transparent = fbconfig->transparent; if (!createSurface(window, wndconfig)) @@ -1304,6 +1318,16 @@ void _glfwPlatformSetWindowOpacity(_GLFWwindow* window, float opacity) { } +void _glfwPlatformSetRawMouseMotion(_GLFWwindow *window, GLFWbool enabled) +{ + // This is handled in relativePointerHandleRelativeMotion +} + +GLFWbool _glfwPlatformRawMouseMotionSupported(void) +{ + return GLFW_TRUE; +} + void _glfwPlatformPollEvents(void) { handleEvents(0); @@ -1423,13 +1447,24 @@ static void relativePointerHandleRelativeMotion(void* data, wl_fixed_t dyUnaccel) { _GLFWwindow* window = data; + double xpos = window->virtualCursorPosX; + double ypos = window->virtualCursorPosY; if (window->cursorMode != GLFW_CURSOR_DISABLED) return; - _glfwInputCursorPos(window, - window->virtualCursorPosX + wl_fixed_to_double(dxUnaccel), - window->virtualCursorPosY + wl_fixed_to_double(dyUnaccel)); + if (window->rawMouseMotion) + { + xpos += wl_fixed_to_double(dxUnaccel); + ypos += wl_fixed_to_double(dyUnaccel); + } + else + { + xpos += wl_fixed_to_double(dx); + ypos += wl_fixed_to_double(dy); + } + + _glfwInputCursorPos(window, xpos, ypos); } static const struct zwp_relative_pointer_v1_listener relativePointerListener = { diff --git a/src/external/glfw/src/x11_init.c b/src/external/glfw/src/x11_init.c index e3e3ad51..dae5b98c 100644 --- a/src/external/glfw/src/x11_init.c +++ b/src/external/glfw/src/x11_init.c @@ -2,7 +2,7 @@ // GLFW 3.3 X11 - www.glfw.org //------------------------------------------------------------------------ // Copyright (c) 2002-2006 Marcus Geelnard -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2006-2019 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages @@ -446,6 +446,10 @@ static void detectEWMH(void) getSupportedAtom(supportedAtoms, atomCount, "_NET_WM_WINDOW_TYPE"); _glfw.x11.NET_WM_WINDOW_TYPE_NORMAL = getSupportedAtom(supportedAtoms, atomCount, "_NET_WM_WINDOW_TYPE_NORMAL"); + _glfw.x11.NET_WORKAREA = + getSupportedAtom(supportedAtoms, atomCount, "_NET_WORKAREA"); + _glfw.x11.NET_CURRENT_DESKTOP = + getSupportedAtom(supportedAtoms, atomCount, "_NET_CURRENT_DESKTOP"); _glfw.x11.NET_ACTIVE_WINDOW = getSupportedAtom(supportedAtoms, atomCount, "_NET_ACTIVE_WINDOW"); _glfw.x11.NET_FRAME_EXTENTS = @@ -1079,7 +1083,7 @@ void _glfwPlatformTerminate(void) const char* _glfwPlatformGetVersionString(void) { - return _GLFW_VERSION_NUMBER " X11 GLX EGL" + return _GLFW_VERSION_NUMBER " X11 GLX EGL OSMesa" #if defined(_POSIX_TIMERS) && defined(_POSIX_MONOTONIC_CLOCK) " clock_gettime" #else diff --git a/src/external/glfw/src/x11_monitor.c b/src/external/glfw/src/x11_monitor.c index df53041d..1cf0c42b 100644 --- a/src/external/glfw/src/x11_monitor.c +++ b/src/external/glfw/src/x11_monitor.c @@ -2,7 +2,7 @@ // GLFW 3.3 X11 - www.glfw.org //------------------------------------------------------------------------ // Copyright (c) 2002-2006 Marcus Geelnard -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2006-2019 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages @@ -30,6 +30,7 @@ #include #include #include +#include // Check whether the display mode should be included in enumeration @@ -44,7 +45,7 @@ static GLFWbool modeIsGood(const XRRModeInfo* mi) static int calculateRefreshRate(const XRRModeInfo* mi) { if (mi->hTotal && mi->vTotal) - return (int) ((double) mi->dotClock / ((double) mi->hTotal * (double) mi->vTotal)); + return (int) round((double) mi->dotClock / ((double) mi->hTotal * (double) mi->vTotal)); else return 0; } @@ -341,6 +342,100 @@ void _glfwPlatformGetMonitorContentScale(_GLFWmonitor* monitor, *yscale = _glfw.x11.contentScaleY; } +void _glfwPlatformGetMonitorWorkarea(_GLFWmonitor* monitor, int* xpos, int* ypos, int* width, int* height) +{ + int areaX = 0, areaY = 0, areaWidth = 0, areaHeight = 0; + + if (_glfw.x11.randr.available && !_glfw.x11.randr.monitorBroken) + { + XRRScreenResources* sr; + XRRCrtcInfo* ci; + + sr = XRRGetScreenResourcesCurrent(_glfw.x11.display, _glfw.x11.root); + ci = XRRGetCrtcInfo(_glfw.x11.display, sr, monitor->x11.crtc); + + areaX = ci->x; + areaY = ci->y; + + const XRRModeInfo* mi = getModeInfo(sr, ci->mode); + + if (ci->rotation == RR_Rotate_90 || ci->rotation == RR_Rotate_270) + { + areaWidth = mi->height; + areaHeight = mi->width; + } + else + { + areaWidth = mi->width; + areaHeight = mi->height; + } + + XRRFreeCrtcInfo(ci); + XRRFreeScreenResources(sr); + } + else + { + areaWidth = DisplayWidth(_glfw.x11.display, _glfw.x11.screen); + areaHeight = DisplayHeight(_glfw.x11.display, _glfw.x11.screen); + } + + if (_glfw.x11.NET_WORKAREA && _glfw.x11.NET_CURRENT_DESKTOP) + { + Atom* extents = NULL; + Atom* desktop = NULL; + const unsigned long extentCount = + _glfwGetWindowPropertyX11(_glfw.x11.root, + _glfw.x11.NET_WORKAREA, + XA_CARDINAL, + (unsigned char**) &extents); + + if (_glfwGetWindowPropertyX11(_glfw.x11.root, + _glfw.x11.NET_CURRENT_DESKTOP, + XA_CARDINAL, + (unsigned char**) &desktop) > 0) + { + if (extentCount >= 4 && *desktop < extentCount / 4) + { + const int globalX = extents[*desktop * 4 + 0]; + const int globalY = extents[*desktop * 4 + 1]; + const int globalWidth = extents[*desktop * 4 + 2]; + const int globalHeight = extents[*desktop * 4 + 3]; + + if (areaX < globalX) + { + areaWidth -= globalX - areaX; + areaX = globalX; + } + + if (areaY < globalY) + { + areaHeight -= globalY - areaY; + areaY = globalY; + } + + if (areaX + areaWidth > globalX + globalWidth) + areaWidth = globalX - areaX + globalWidth; + if (areaY + areaHeight > globalY + globalHeight) + areaHeight = globalY - areaY + globalHeight; + } + } + + if (extents) + XFree(extents); + if (desktop) + XFree(desktop); + } + + if (xpos) + *xpos = areaX; + if (ypos) + *ypos = areaY; + if (width) + *width = areaWidth; + if (height) + *height = areaHeight; +} + GLFWvidmode* _glfwPlatformGetVideoModes(_GLFWmonitor* monitor, int* count) { GLFWvidmode* result; diff --git a/src/external/glfw/src/x11_platform.h b/src/external/glfw/src/x11_platform.h index c37c740e..3b2b2b22 100644 --- a/src/external/glfw/src/x11_platform.h +++ b/src/external/glfw/src/x11_platform.h @@ -2,7 +2,7 @@ // GLFW 3.3 X11 - www.glfw.org //------------------------------------------------------------------------ // Copyright (c) 2002-2006 Marcus Geelnard -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2006-2019 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages @@ -259,6 +259,8 @@ typedef struct _GLFWlibraryX11 Atom NET_WM_FULLSCREEN_MONITORS; Atom NET_WM_WINDOW_OPACITY; Atom NET_WM_CM_Sx; + Atom NET_WORKAREA; + Atom NET_CURRENT_DESKTOP; Atom NET_ACTIVE_WINDOW; Atom NET_FRAME_EXTENTS; Atom NET_REQUEST_FRAME_EXTENTS; diff --git a/src/external/glfw/src/x11_window.c b/src/external/glfw/src/x11_window.c index 5e916107..f66c49b7 100644 --- a/src/external/glfw/src/x11_window.c +++ b/src/external/glfw/src/x11_window.c @@ -2,7 +2,7 @@ // GLFW 3.3 X11 - www.glfw.org //------------------------------------------------------------------------ // Copyright (c) 2002-2006 Marcus Geelnard -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2006-2019 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages @@ -501,15 +501,6 @@ static char* convertLatin1toUTF8(const char* source) return target; } -// Centers the cursor over the window client area -// -static void centerCursor(_GLFWwindow* window) -{ - int width, height; - _glfwPlatformGetWindowSize(window, &width, &height); - _glfwPlatformSetCursorPos(window, width / 2.0, height / 2.0); -} - // Updates the cursor image according to its cursor mode // static void updateCursorImage(_GLFWwindow* window) @@ -531,29 +522,48 @@ static void updateCursorImage(_GLFWwindow* window) } } -// Apply disabled cursor mode to a focused window +// Enable XI2 raw mouse motion events // -static void disableCursor(_GLFWwindow* window) +static void enableRawMouseMotion(_GLFWwindow* window) { - if (_glfw.x11.xi.available) - { - XIEventMask em; - unsigned char mask[XIMaskLen(XI_RawMotion)] = { 0 }; + XIEventMask em; + unsigned char mask[XIMaskLen(XI_RawMotion)] = { 0 }; - em.deviceid = XIAllMasterDevices; - em.mask_len = sizeof(mask); - em.mask = mask; - XISetMask(mask, XI_RawMotion); + em.deviceid = XIAllMasterDevices; + em.mask_len = sizeof(mask); + em.mask = mask; + XISetMask(mask, XI_RawMotion); - XISelectEvents(_glfw.x11.display, _glfw.x11.root, &em, 1); - } + XISelectEvents(_glfw.x11.display, _glfw.x11.root, &em, 1); +} + +// Disable XI2 raw mouse motion events +// +static void disableRawMouseMotion(_GLFWwindow* window) +{ + XIEventMask em; + unsigned char mask[] = { 0 }; + + em.deviceid = XIAllMasterDevices; + em.mask_len = sizeof(mask); + em.mask = mask; + + XISelectEvents(_glfw.x11.display, _glfw.x11.root, &em, 1); +} + +// Apply disabled cursor mode to a focused window +// +static void disableCursor(_GLFWwindow* window) +{ + if (window->rawMouseMotion) + enableRawMouseMotion(window); _glfw.x11.disabledCursorWindow = window; _glfwPlatformGetCursorPos(window, &_glfw.x11.restoreCursorPosX, &_glfw.x11.restoreCursorPosY); updateCursorImage(window); - centerCursor(window); + _glfwCenterCursorInContentArea(window); XGrabPointer(_glfw.x11.display, window->x11.handle, True, ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync, GrabModeAsync, @@ -566,17 +576,8 @@ static void disableCursor(_GLFWwindow* window) // static void enableCursor(_GLFWwindow* window) { - if (_glfw.x11.xi.available) - { - XIEventMask em; - unsigned char mask[] = { 0 }; - - em.deviceid = XIAllMasterDevices; - em.mask_len = sizeof(mask); - em.mask = mask; - - XISelectEvents(_glfw.x11.display, _glfw.x11.root, &em, 1); - } + if (window->rawMouseMotion) + disableRawMouseMotion(window); _glfw.x11.disabledCursorWindow = NULL; XUngrabPointer(_glfw.x11.display, CurrentTime); @@ -1192,6 +1193,7 @@ static void processEvent(XEvent *event) _GLFWwindow* window = _glfw.x11.disabledCursorWindow; if (window && + window->rawMouseMotion && event->xcookie.extension == _glfw.x11.xi.majorOpcode && XGetEventData(_glfw.x11.display, &event->xcookie) && event->xcookie.evtype == XI_RawMotion) @@ -1492,7 +1494,7 @@ static void processEvent(XEvent *event) { if (_glfw.x11.disabledCursorWindow != window) return; - if (_glfw.x11.xi.available) + if (window->rawMouseMotion) return; const int dx = x - window->x11.lastCursorPosX; @@ -2403,10 +2405,14 @@ void _glfwPlatformSetWindowMonitor(_GLFWwindow* window, } else { + if (!window->resizable) + updateNormalHints(window, width, height); + XMoveResizeWindow(_glfw.x11.display, window->x11.handle, xpos, ypos, width, height); } + XFlush(_glfw.x11.display); return; } @@ -2415,16 +2421,21 @@ void _glfwPlatformSetWindowMonitor(_GLFWwindow* window, _glfwInputWindowMonitor(window, monitor); updateNormalHints(window, width, height); - updateWindowMode(window); if (window->monitor) { - XMapRaised(_glfw.x11.display, window->x11.handle); - if (waitForVisibilityNotify(window)) - acquireMonitor(window); + if (!_glfwPlatformWindowVisible(window)) + { + XMapRaised(_glfw.x11.display, window->x11.handle); + waitForVisibilityNotify(window); + } + + updateWindowMode(window); + acquireMonitor(window); } else { + updateWindowMode(window); XMoveResizeWindow(_glfw.x11.display, window->x11.handle, xpos, ypos, width, height); } @@ -2652,6 +2663,25 @@ void _glfwPlatformSetWindowOpacity(_GLFWwindow* window, float opacity) PropModeReplace, (unsigned char*) &value, 1); } +void _glfwPlatformSetRawMouseMotion(_GLFWwindow *window, GLFWbool enabled) +{ + if (!_glfw.x11.xi.available) + return; + + if (_glfw.x11.disabledCursorWindow != window) + return; + + if (enabled) + enableRawMouseMotion(window); + else + disableRawMouseMotion(window); +} + +GLFWbool _glfwPlatformRawMouseMotionSupported(void) +{ + return _glfw.x11.xi.available; +} + void _glfwPlatformPollEvents(void) { _GLFWwindow* window; @@ -2810,7 +2840,7 @@ int _glfwPlatformCreateStandardCursor(_GLFWcursor* cursor, int shape) else if (shape == GLFW_CROSSHAIR_CURSOR) native = XC_crosshair; else if (shape == GLFW_HAND_CURSOR) - native = XC_hand1; + native = XC_hand2; else if (shape == GLFW_HRESIZE_CURSOR) native = XC_sb_h_double_arrow; else if (shape == GLFW_VRESIZE_CURSOR) diff --git a/src/external/glfw/src/xkb_unicode.c b/src/external/glfw/src/xkb_unicode.c index ecfdc2af..ad3cc233 100644 --- a/src/external/glfw/src/xkb_unicode.c +++ b/src/external/glfw/src/xkb_unicode.c @@ -2,7 +2,7 @@ // GLFW 3.3 X11 - www.glfw.org //------------------------------------------------------------------------ // Copyright (c) 2002-2006 Marcus Geelnard -// Copyright (c) 2006-2016 Camilla Lรถwy +// Copyright (c) 2006-2017 Camilla Lรถwy // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages -- cgit v1.2.3 From 4b8d06f50139b33d7670c286e2e3f006843ac8ba Mon Sep 17 00:00:00 2001 From: Jak <5613046+Syphonx@users.noreply.github.com> Date: Mon, 22 Apr 2019 19:03:00 +0100 Subject: [rnet] module WIP (#809) Added experimental network module --- src/raylib.h | 176 +++++ src/rnet.c | 2023 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/rnet.h | 228 +++++++ 3 files changed, 2427 insertions(+) create mode 100644 src/rnet.c create mode 100644 src/rnet.h (limited to 'src') diff --git a/src/raylib.h b/src/raylib.h index 6a5f0ef8..710f69b6 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -75,6 +75,7 @@ #define RAYLIB_H #include // Required for: va_list - Only used by TraceLogCallback +#include // Required for rnet #if defined(_WIN32) && defined(BUILD_LIBTYPE_SHARED) #define RLAPI __declspec(dllexport) // We are building raylib as a Win32 shared library (.dll) @@ -99,6 +100,11 @@ // Shader and material limits #define MAX_SHADER_LOCATIONS 32 // Maximum number of predefined locations stored in shader struct #define MAX_MATERIAL_MAPS 12 // Maximum number of texture maps stored in shader struct + +// Network connection related defines +#define SOCKET_MAX_SOCK_OPTS (4) // Maximum socket options +#define SOCKET_MAX_UDPCHANNELS (32) // Maximum UDP channels +#define SOCKET_MAX_UDPADDRESSES (4) // Maximum bound UDP addresses // NOTE: MSC C++ compiler does not support compound literals (C99 feature) // Plain structures in C++ (without constructors) can be initialized from { } initializers. @@ -442,6 +448,100 @@ typedef struct VrDeviceInfo { float lensDistortionValues[4]; // HMD lens distortion constant parameters float chromaAbCorrection[4]; // HMD chromatic aberration correction parameters } VrDeviceInfo; + +// Network typedefs +typedef uint32_t SocketChannel; +typedef struct _AddressInformation * AddressInformation; +typedef struct _SocketAddress * SocketAddress; +typedef struct _SocketAddressIPv4 * SocketAddressIPv4; +typedef struct _SocketAddressIPv6 * SocketAddressIPv6; +typedef struct _SocketAddressStorage *SocketAddressStorage; + +// IPAddress definition (in network byte order) +typedef struct IPAddress +{ + unsigned long host; /* 32-bit IPv4 host address */ + unsigned short port; /* 16-bit protocol port */ +} IPAddress; + +// An option ID, value, sizeof(value) tuple for setsockopt(2). +typedef struct SocketOpt +{ + int id; + void *value; + int valueLen; +} SocketOpt; + +typedef enum +{ + SOCKET_TCP = 0, // SOCK_STREAM + SOCKET_UDP = 1 // SOCK_DGRAM +} SocketType; + +typedef struct UDPChannel +{ + int numbound; // The total number of addresses this channel is bound to + IPAddress address[SOCKET_MAX_UDPADDRESSES]; // The list of remote addresses this channel is bound to +} UDPChannel; + +typedef struct Socket +{ + int ready; // Is the socket ready? i.e. has information + int status; // The last status code to have occured using this socket + bool isServer; // Is this socket a server socket (i.e. TCP/UDP Listen Server) + SocketChannel channel; // The socket handle id + SocketType type; // Is this socket a TCP or UDP socket? + bool isIPv6; // Is this socket address an ipv6 address? + SocketAddressIPv4 addripv4; // The host/target IPv4 for this socket (in network byte order) + SocketAddressIPv6 addripv6; // The host/target IPv6 for this socket (in network byte order) + + struct UDPChannel binding[SOCKET_MAX_UDPCHANNELS]; // The amount of channels (if UDP) this socket is bound to +} Socket; + +typedef struct SocketSet +{ + int numsockets; + int maxsockets; + struct Socket **sockets; +} SocketSet; + +typedef struct SocketDataPacket +{ + int channel; // The src/dst channel of the packet + unsigned char *data; // The packet data + int len; // The length of the packet data + int maxlen; // The size of the data buffer + int status; // packet status after sending + IPAddress address; // The source/dest address of an incoming/outgoing packet +} SocketDataPacket; + +// Configuration for a socket. +typedef struct SocketConfig +{ + char * host; // The host address in xxx.xxx.xxx.xxx form + char * port; // The target port/service in the form "http" or "25565" + bool server; // Listen for incoming clients? + SocketType type; // The type of socket, TCP/UDP + bool nonblocking; // non-blocking operation? + int backlog_size; // set a custom backlog size + SocketOpt sockopts[SOCKET_MAX_SOCK_OPTS]; +} SocketConfig; + +// Result from calling open with a given config. +typedef struct SocketResult +{ + int status; + Socket *socket; +} SocketResult; + +// +typedef struct Packet +{ + uint32_t size; // The total size of bytes in data + uint32_t offs; // The offset to data access + uint32_t maxs; // The max size of data + uint8_t *data; // Data stored in network byte order +} Packet; //---------------------------------------------------------------------------------- // Enumerators Definition @@ -1407,6 +1507,82 @@ RLAPI bool IsAudioStreamPlaying(AudioStream stream); // Check i RLAPI void StopAudioStream(AudioStream stream); // Stop audio stream RLAPI void SetAudioStreamVolume(AudioStream stream, float volume); // Set volume for audio stream (1.0 is max level) RLAPI void SetAudioStreamPitch(AudioStream stream, float pitch); // Set pitch for audio stream (1.0 is base level) + +//------------------------------------------------------------------------------------ +// Network (Module: network) +//------------------------------------------------------------------------------------ + +// Initialisation and cleanup +RLAPI bool InitNetwork(void); +RLAPI void CloseNetwork(void); + +// Address API +RLAPI void ResolveIP(const char *ip, const char *service, int flags, char *outhost, char *outserv); +RLAPI int ResolveHost(const char *address, const char *service, int addressType, int flags, AddressInformation *outAddr); +RLAPI int GetAddressFamily(AddressInformation address); +RLAPI int GetAddressSocketType(AddressInformation address); +RLAPI int GetAddressProtocol(AddressInformation address); +RLAPI char* GetAddressCanonName(AddressInformation address); +RLAPI char* GetAddressHostAndPort(AddressInformation address, char *outhost, int *outport); +RLAPI void PrintAddressInfo(AddressInformation address); + +// Address Memory API +RLAPI AddressInformation AllocAddress(); +RLAPI void FreeAddress(AddressInformation *addressInfo); +RLAPI AddressInformation *AllocAddressList(int size); + +// Socket API +RLAPI bool SocketCreate(SocketConfig *config, SocketResult *result); +RLAPI bool SocketBind(SocketConfig *config, SocketResult *result); +RLAPI bool SocketListen(SocketConfig *config, SocketResult *result); +RLAPI bool SocketConnect(SocketConfig *config, SocketResult *result); +RLAPI Socket *SocketAccept(Socket *server, SocketConfig *config); + +// UDP Socket API +RLAPI int SocketSetChannel(Socket *socket, int channel, const IPAddress *address); +RLAPI void SocketUnsetChannel(Socket *socket, int channel); + +// UDP DataPacket API +RLAPI SocketDataPacket *AllocPacket(int size); +RLAPI int ResizePacket(SocketDataPacket *packet, int newsize); +RLAPI void FreePacket(SocketDataPacket *packet); +RLAPI SocketDataPacket **AllocPacketList(int count, int size); +RLAPI void FreePacketList(SocketDataPacket **packets); + +// General Socket API +RLAPI int SocketSend(Socket *sock, const void *datap, int len); +RLAPI int SocketReceive(Socket *sock, void *data, int maxlen); +RLAPI void SocketClose(Socket *sock); +RLAPI SocketAddressStorage SocketGetPeerAddress(Socket *sock); +RLAPI char* GetSocketAddressHost(SocketAddressStorage storage); +RLAPI short GetSocketAddressPort(SocketAddressStorage storage); + +// Socket Memory API +RLAPI Socket *AllocSocket(); +RLAPI void FreeSocket(Socket **sock); +RLAPI SocketResult *AllocSocketResult(); +RLAPI void FreeSocketResult(SocketResult **result); +RLAPI SocketSet *AllocSocketSet(int max); +RLAPI void FreeSocketSet(SocketSet *sockset); + +// Socket I/O API +RLAPI bool IsSocketReady(Socket *sock); +RLAPI bool IsSocketConnected(Socket *sock); +RLAPI int AddSocket(SocketSet *set, Socket *sock); +RLAPI int RemoveSocket(SocketSet *set, Socket *sock); +RLAPI int CheckSockets(SocketSet *set, unsigned int timeout); + +// Packet API +void PacketSend(Packet *packet); +void PacketReceive(Packet *packet); +void PacketWrite8(Packet *packet, uint16_t value); +void PacketWrite16(Packet *packet, uint16_t value); +void PacketWrite32(Packet *packet, uint32_t value); +void PacketWrite64(Packet *packet, uint64_t value); +uint16_t PacketRead8(Packet *packet); +uint16_t PacketRead16(Packet *packet); +uint32_t PacketRead32(Packet *packet); +uint64_t PacketRead64(Packet *packet); #if defined(__cplusplus) } diff --git a/src/rnet.c b/src/rnet.c new file mode 100644 index 00000000..0a47b44f --- /dev/null +++ b/src/rnet.c @@ -0,0 +1,2023 @@ +/********************************************************************************************* +* +* rnet - A simple and easy-to-use network module for raylib +* +* FEATURES: +* - Provides a simple and (hopefully) easy to use wrapper around the Berkeley socket API +* +* DEPENDENCIES: +* raylib.h - TraceLog +* rnet.h - platform-specific network includes +* +* CONTRIBUTORS: +* Jak Barnes (github: @syphonx) (Feb. 2019): +* - Initial version +* +* +* LICENSE: zlib/libpng +* +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) +* +* 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, subject to the following restrictions: +* +* 1. The origin of this software must not be misrepresented; you must not claim that you +* wrote the original software. If you use this software in a product, an acknowledgment +* in the product documentation would be appreciated but is not required. +* +* 2. Altered source versions must be plainly marked as such, and must not be misrepresented +* as being the original software. +* +* 3. This notice may not be removed or altered from any source distribution. +* +**********************************************************************************************/ + +//---------------------------------------------------------------------------------- +// Check if config flags have been externally provided on compilation line +//---------------------------------------------------------------------------------- + +#include "rnet.h" + +#include "raylib.h" + +#include // Required for: assert() +#include // Required for: FILE, fopen(), fclose(), fread() +#include // Required for: malloc(), free() +#include // Required for: strcmp(), strncmp() + +//---------------------------------------------------------------------------------- +// Module defines +//---------------------------------------------------------------------------------- + +#define NET_DEBUG_ENABLED (1) + +//---------------------------------------------------------------------------------- +// Types and Structures Definition +//---------------------------------------------------------------------------------- + +typedef struct _SocketAddress +{ + struct sockaddr address; +} _SocketAddress; + +typedef struct _SocketAddressIPv4 +{ + struct sockaddr_in address; +} _SocketAddressIPv4; + +typedef struct _SocketAddressIPv6 +{ + struct sockaddr_in6 address; +} _SocketAddressIPv6; + +typedef struct _SocketAddressStorage +{ + struct sockaddr_storage address; +} _SocketAddressStorage; + +typedef struct _AddressInformation +{ + struct addrinfo addr; +} _AddressInformation; + + + +//---------------------------------------------------------------------------------- +// Global module forward declarations +//---------------------------------------------------------------------------------- + +static void PrintSocket(struct sockaddr_storage *addr, const int family, const int socktype, const int protocol); +static const char *SocketAddressToString(struct sockaddr_storage *sockaddr); +static bool IsIPv4Address(const char *ip); +static bool IsIPv6Address(const char *ip); +static void * GetSocketPortPtr(struct sockaddr_storage *sa); +static void * GetSocketAddressPtr(struct sockaddr_storage *sa); +static bool IsSocketValid(Socket *sock); +static void SocketSetLastError(int err); +static int SocketGetLastError(); +static char * SocketGetLastErrorString(); +static char * SocketErrorCodeToString(int err); +static bool SocketSetDefaults(SocketConfig *config); +static bool InitSocket(Socket *sock, struct addrinfo *addr); +static bool CreateSocket(SocketConfig *config, SocketResult *outresult); +static bool SocketSetBlocking(Socket *sock); +static bool SocketSetNonBlocking(Socket *sock); +static bool SocketSetOptions(SocketConfig *config, Socket *sock); +static void SocketSetHints(SocketConfig *config, struct addrinfo *hints); + +//---------------------------------------------------------------------------------- +// Global module implementation +//---------------------------------------------------------------------------------- + +// Print socket information +static void PrintSocket(struct sockaddr_storage *addr, const int family, const int socktype, const int protocol) +{ + switch (family) + { + case AF_UNSPEC: { TraceLog(LOG_DEBUG, "\tFamily: Unspecified"); + } + break; + case AF_INET: + { + TraceLog(LOG_DEBUG, "\tFamily: AF_INET (IPv4)"); + TraceLog(LOG_INFO, "\t- IPv4 address %s", SocketAddressToString(addr)); + } + break; + case AF_INET6: + { + TraceLog(LOG_DEBUG, "\tFamily: AF_INET6 (IPv6)"); + TraceLog(LOG_INFO, "\t- IPv6 address %s", SocketAddressToString(addr)); + } + break; + case AF_NETBIOS: + { + TraceLog(LOG_DEBUG, "\tFamily: AF_NETBIOS (NetBIOS)"); + } + break; + default: { TraceLog(LOG_DEBUG, "\tFamily: Other %ld", family); + } + break; + } + TraceLog(LOG_DEBUG, "\tSocket type:"); + switch (socktype) + { + case 0: TraceLog(LOG_DEBUG, "\t- Unspecified"); break; + case SOCK_STREAM: + TraceLog(LOG_DEBUG, "\t- SOCK_STREAM (stream)"); + break; + case SOCK_DGRAM: + TraceLog(LOG_DEBUG, "\t- SOCK_DGRAM (datagram)"); + break; + case SOCK_RAW: TraceLog(LOG_DEBUG, "\t- SOCK_RAW (raw)"); break; + case SOCK_RDM: + TraceLog(LOG_DEBUG, "\t- SOCK_RDM (reliable message datagram)"); + break; + case SOCK_SEQPACKET: + TraceLog(LOG_DEBUG, "\t- SOCK_SEQPACKET (pseudo-stream packet)"); + break; + default: TraceLog(LOG_DEBUG, "\t- Other %ld", socktype); break; + } + TraceLog(LOG_DEBUG, "\tProtocol:"); + switch (protocol) + { + case 0: TraceLog(LOG_DEBUG, "\t- Unspecified"); break; + case IPPROTO_TCP: TraceLog(LOG_DEBUG, "\t- IPPROTO_TCP (TCP)"); break; + case IPPROTO_UDP: TraceLog(LOG_DEBUG, "\t- IPPROTO_UDP (UDP)"); break; + default: TraceLog(LOG_DEBUG, "\t- Other %ld", protocol); break; + } +} + +// Convert network ordered socket address to human readable string (127.0.0.1) +static const char *SocketAddressToString(struct sockaddr_storage *sockaddr) +{ + static const char* ipv6[INET6_ADDRSTRLEN]; + assert(sockaddr != NULL); + assert(sockaddr->ss_family == AF_INET || sockaddr->ss_family == AF_INET6); + switch (sockaddr->ss_family) + { + case AF_INET: + { + struct sockaddr_in *s = ((struct sockaddr_in *) sockaddr); + return inet_ntop(AF_INET, &s->sin_addr, ipv6, INET_ADDRSTRLEN); + } + break; + case AF_INET6: + { + struct sockaddr_in6 *s = ((struct sockaddr_in6 *) sockaddr); + return inet_ntop(AF_INET6, &s->sin6_addr, ipv6, INET6_ADDRSTRLEN); + } + break; + } + return NULL; +} + +// Check if the null terminated string ip is a valid IPv4 address +static bool IsIPv4Address(const char *ip) +{ + struct sockaddr_in sa; + int result = inet_pton(AF_INET, ip, &(sa.sin_addr)); + return result != 0; +} + +// Check if the null terminated string ip is a valid IPv6 address +static bool IsIPv6Address(const char *ip) +{ + struct sockaddr_in6 sa; + int result = inet_pton(AF_INET6, ip, &(sa.sin6_addr)); + return result != 0; +} + +// Return a pointer to the port from the correct address family (IPv4, or IPv6) +static void *GetSocketPortPtr(struct sockaddr_storage *sa) +{ + if (sa->ss_family == AF_INET) + { + return &(((struct sockaddr_in *) sa)->sin_port); + } + + return &(((struct sockaddr_in6 *) sa)->sin6_port); +} + +// Return a pointer to the address from the correct address family (IPv4, or IPv6) +static void *GetSocketAddressPtr(struct sockaddr_storage *sa) +{ + if (sa->ss_family == AF_INET) + { + return &(((struct sockaddr_in *) sa)->sin_addr); + } + + return &(((struct sockaddr_in6 *) sa)->sin6_addr); +} + +// Is the socket in a valid state? +static bool IsSocketValid(Socket *sock) +{ + if (sock != NULL) + { + return (sock->channel != INVALID_SOCKET); + } + return false; +} + +// Sets the error code that can be retrieved through the WSAGetLastError function. +static void SocketSetLastError(int err) +{ +#if PLATFORM == PLATFORM_WINDOWS + WSASetLastError(err); +#else + errno = err; +#endif +} + +// Returns the error status for the last Sockets operation that failed +static int SocketGetLastError() +{ +#if PLATFORM == PLATFORM_WINDOWS + return WSAGetLastError(); +#else + return errno; +#endif +} + +// Returns a human-readable string representing the last error message +static char *SocketGetLastErrorString() +{ + return SocketErrorCodeToString(SocketGetLastError()); +} + +// Returns a human-readable string representing the error message (err) +static char *SocketErrorCodeToString(int err) +{ +#if PLATFORM == PLATFORM_WINDOWS + static char gaiStrErrorBuffer[GAI_STRERROR_BUFFER_SIZE]; + sprintf(gaiStrErrorBuffer, "%ws", gai_strerror(err)); + return gaiStrErrorBuffer; +#else + return gai_strerror(err); +#endif +} + +// Set the defaults in the supplied SocketConfig if they're not already set +static bool SocketSetDefaults(SocketConfig *config) +{ + if (config->backlog_size == 0) + { + config->backlog_size = SOCKET_MAX_QUEUE_SIZE; + } + + return true; +} + +// Create the socket channel +static bool InitSocket(Socket *sock, struct addrinfo *addr) +{ + switch (sock->type) + { + case SOCKET_TCP: + if (addr->ai_family == AF_INET) + { + sock->channel = socket(AF_INET, SOCK_STREAM, 0); + } + else + { + sock->channel = socket(AF_INET6, SOCK_STREAM, 0); + } + break; + case SOCKET_UDP: + if (addr->ai_family == AF_INET) + { + sock->channel = socket(AF_INET, SOCK_DGRAM, 0); + } + else + { + sock->channel = socket(AF_INET6, SOCK_DGRAM, 0); + } + break; + default: + TraceLog(LOG_WARNING, "Invalid socket type specified."); + break; + } + return IsSocketValid(sock); +} + +// CreateSocket() - Interally called by CreateSocket() +// +// This here is the bread and butter of the socket API, This function will +// attempt to open a socket, bind and listen to it based on the config passed in +// +// SocketConfig* config - Configuration for which socket to open +// SocketResult* result - The results of this function (if any, including errors) +// +// e.g. +// SocketConfig server_config = { SocketConfig client_config = { +// .host = "127.0.0.1", .host = "127.0.0.1", +// .port = 8080, .port = 8080, +// .server = true, }; +// .nonblocking = true, +// }; +// SocketResult server_res; SocketResult client_res; +static bool CreateSocket(SocketConfig *config, SocketResult *outresult) +{ + bool success = true; + int addrstatus; + struct addrinfo hints; // Address flags (IPV4, IPV6, UDP?) + struct addrinfo *res; // A pointer to the resulting address list + outresult->socket->channel = INVALID_SOCKET; + outresult->status = RESULT_FAILURE; + + // Set the socket type + outresult->socket->type = config->type; + + // Set the hints based on information in the config + // + // AI_CANONNAME Causes the ai_canonname of the result to the filled out with the host's canonical (real) name. + // AI_PASSIVE: Causes the result's IP address to be filled out with INADDR_ANY (IPv4)or in6addr_any (IPv6); + // Note: This causes a subsequent call to bind() to auto-fill the IP address + // of the struct sockaddr with the address of the current host. + // + SocketSetHints(config, &hints); + + // Populate address information + addrstatus = getaddrinfo(config->host, // e.g. "www.example.com" or IP (Can be null if AI_PASSIVE flag is set + config->port, // e.g. "http" or port number + &hints, // e.g. SOCK_STREAM/SOCK_DGRAM + &res // The struct to populate + ); + + // Did we succeed? + if (addrstatus != 0) + { + outresult->socket->status = SocketGetLastError(); + TraceLog(LOG_WARNING, + "Socket Error: %s", + SocketErrorCodeToString(outresult->socket->status)); + SocketSetLastError(0); + TraceLog(LOG_WARNING, + "Failed to get resolve host %s:%s: %s", + config->host, + config->port, + SocketGetLastErrorString()); + return (success = false); + } + else + { + char hoststr[NI_MAXHOST]; + char portstr[NI_MAXSERV]; + socklen_t client_len = sizeof(struct sockaddr_storage); + int rc = getnameinfo((struct sockaddr *) res->ai_addr, client_len, hoststr, sizeof(hoststr), portstr, sizeof(portstr), NI_NUMERICHOST | NI_NUMERICSERV); + TraceLog(LOG_INFO, "Successfully resolved host %s:%s", hoststr, portstr); + } + + // Walk the address information linked-list + struct addrinfo *it; + for (it = res; it != NULL; it = it->ai_next) + { + // Initialise the socket + if (!InitSocket(outresult->socket, it)) + { + outresult->socket->status = SocketGetLastError(); + TraceLog(LOG_WARNING, + "Socket Error: %s", + SocketErrorCodeToString(outresult->socket->status)); + SocketSetLastError(0); + continue; + } + + // Set socket options + if (!SocketSetOptions(config, outresult->socket)) + { + outresult->socket->status = SocketGetLastError(); + TraceLog(LOG_WARNING, + "Socket Error: %s", + SocketErrorCodeToString(outresult->socket->status)); + SocketSetLastError(0); + freeaddrinfo(res); + return (success = false); + } + } + + if (!IsSocketValid(outresult->socket)) + { + outresult->socket->status = SocketGetLastError(); + TraceLog( + LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(outresult->status)); + SocketSetLastError(0); + freeaddrinfo(res); + return (success = false); + } + + if (success) + { + outresult->status = RESULT_SUCCESS; + outresult->socket->ready = 0; + outresult->socket->status = 0; + if (!(config->type == SOCKET_UDP)) + { + outresult->socket->isServer = config->server; + } + switch (res->ai_addr->sa_family) + { + case AF_INET: + { + outresult->socket->addripv4 = (struct _SocketAddressIPv4 *) malloc( + sizeof(*outresult->socket->addripv4)); + if (outresult->socket->addripv4 != NULL) + { + memset(outresult->socket->addripv4, 0, + sizeof(*outresult->socket->addripv4)); + if (outresult->socket->addripv4 != NULL) + { + memcpy(&outresult->socket->addripv4->address, + (struct sockaddr_in *) res->ai_addr, sizeof(struct sockaddr_in)); + outresult->socket->isIPv6 = false; + char hoststr[NI_MAXHOST]; + char portstr[NI_MAXSERV]; + socklen_t client_len = sizeof(struct sockaddr_storage); + getnameinfo( + (struct sockaddr *) &outresult->socket->addripv4->address, client_len, hoststr, sizeof(hoststr), portstr, sizeof(portstr), NI_NUMERICHOST | NI_NUMERICSERV); + TraceLog(LOG_INFO, "Socket address set to %s:%s", hoststr, portstr); + } + } + } + break; + case AF_INET6: + { + outresult->socket->addripv6 = (struct _SocketAddressIPv6 *) malloc( + sizeof(*outresult->socket->addripv6)); + if (outresult->socket->addripv6 != NULL) + { + memset(outresult->socket->addripv6, 0, + sizeof(*outresult->socket->addripv6)); + if (outresult->socket->addripv6 != NULL) + { + memcpy(&outresult->socket->addripv6->address, + (struct sockaddr_in6 *) res->ai_addr, sizeof(struct sockaddr_in6)); + outresult->socket->isIPv6 = true; + char hoststr[NI_MAXHOST]; + char portstr[NI_MAXSERV]; + socklen_t client_len = sizeof(struct sockaddr_storage); + getnameinfo( + (struct sockaddr *) &outresult->socket->addripv6->address, client_len, hoststr, sizeof(hoststr), portstr, sizeof(portstr), NI_NUMERICHOST | NI_NUMERICSERV); + TraceLog(LOG_INFO, "Socket address set to %s:%s", hoststr, portstr); + } + } + } + break; + } + } + freeaddrinfo(res); + return success; +} + +// Set the state of the Socket sock to blocking +static bool SocketSetBlocking(Socket *sock) +{ + bool ret = true; +#if PLATFORM == PLATFORM_WINDOWS + unsigned long mode = 0; + ret = ioctlsocket(sock->channel, FIONBIO, &mode); +#else + const int flags = fcntl(sock->channel, F_GETFL, 0); + if (!(flags & O_NONBLOCK)) + { + TraceLog(LOG_DEBUG, "Socket was already in blocking mode"); + return ret; + } + + ret = (0 == fcntl(sock->channel, F_SETFL, (flags ^ O_NONBLOCK))); +#endif + return ret; +} + +// Set the state of the Socket sock to non-blocking +static bool SocketSetNonBlocking(Socket *sock) +{ + bool ret = true; +#if PLATFORM == PLATFORM_WINDOWS + unsigned long mode = 1; + ret = ioctlsocket(sock->channel, FIONBIO, &mode); +#else + const int flags = fcntl(sock->channel, F_GETFL, 0); + if ((flags & O_NONBLOCK)) + { + TraceLog(LOG_DEBUG, "Socket was already in non-blocking mode"); + return ret; + } + ret = (0 == fcntl(sock->channel, F_SETFL, (flags | O_NONBLOCK))); +#endif + return ret; +} + +// Set options specified in SocketConfig to Socket sock +static bool SocketSetOptions(SocketConfig *config, Socket *sock) +{ + for (int i = 0; i < SOCKET_MAX_SOCK_OPTS; i++) + { + SocketOpt *opt = &config->sockopts[i]; + if (opt->id == 0) + { + break; + } + + if (setsockopt(sock->channel, SOL_SOCKET, opt->id, opt->value, opt->valueLen) < 0) + { + return false; + } + } + + return true; +} + +// Set "hints" in an addrinfo struct, to be passed to getaddrinfo. +static void SocketSetHints(SocketConfig *config, struct addrinfo *hints) +{ + if (config == NULL || hints == NULL) + { + return; + } + memset(hints, 0, sizeof(*hints)); + + // Check if the ip supplied in the config is a valid ipv4 ip ipv6 address + if (IsIPv4Address(config->host)) + { + hints->ai_family = AF_INET; + hints->ai_flags |= AI_NUMERICHOST; + } + else + { + if (IsIPv6Address(config->host)) + { + hints->ai_family = AF_INET6; + hints->ai_flags |= AI_NUMERICHOST; + } + else + { + hints->ai_family = AF_UNSPEC; + } + } + + if (config->type == SOCKET_UDP) + { + hints->ai_socktype = SOCK_DGRAM; + } + else + { + hints->ai_socktype = SOCK_STREAM; + } + + // Set passive unless UDP client + if (!(config->type == SOCKET_UDP) || config->server) + { + hints->ai_flags = AI_PASSIVE; + } +} + +//---------------------------------------------------------------------------------- +// Module implementation +//---------------------------------------------------------------------------------- + +// Initialise the network (requires for windows platforms only) +bool InitNetwork() +{ +#if PLATFORM == PLATFORM_WINDOWS + WORD wVersionRequested; + WSADATA wsaData; + int err; + + wVersionRequested = MAKEWORD(2, 2); + err = WSAStartup(wVersionRequested, &wsaData); + if (err != 0) + { + TraceLog(LOG_WARNING, "WinSock failed to initialise."); + return false; + } + else + { + TraceLog(LOG_INFO, "WinSock initialised."); + } + + if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) + { + TraceLog(LOG_WARNING, "WinSock failed to initialise."); + WSACleanup(); + return false; + } + + return true; +#else + return true; +#endif +} + +// Cleanup, and close the network +void CloseNetwork() +{ +#if PLATFORM == PLATFORM_WINDOWS + WSACleanup(); +#endif +} + +// Protocol-independent name resolution from an address to an ANSI host name +// and from a port number to the ANSI service name. +// +// The flags parameter can be used to customize processing of the getnameinfo function +// +// The following flags are available: +// +// NAME_INFO_DEFAULT 0x00 // No flags set +// NAME_INFO_NOFQDN 0x01 // Only return nodename portion for local hosts +// NAME_INFO_NUMERICHOST 0x02 // Return numeric form of the host's address +// NAME_INFO_NAMEREQD 0x04 // Error if the host's name not in DNS +// NAME_INFO_NUMERICSERV 0x08 // Return numeric form of the service (port #) +// NAME_INFO_DGRAM 0x10 // Service is a datagram service +void ResolveIP(const char *ip, const char *port, int flags, char *host, char *serv) +{ + // Variables + int status; // Status value to return (0) is success + struct addrinfo hints; // Address flags (IPV4, IPV6, UDP?) + struct addrinfo *res; // A pointer to the resulting address list + + // Set the hints + memset(&hints, 0, sizeof hints); + hints.ai_family = AF_UNSPEC; // Either IPv4 or IPv6 (AF_INET, AF_INET6) + hints.ai_protocol = 0; // Automatically select correct protocol (IPPROTO_TCP), (IPPROTO_UDP) + + // Populate address information + status = getaddrinfo(ip, // e.g. "www.example.com" or IP + port, // e.g. "http" or port number + &hints, // e.g. SOCK_STREAM/SOCK_DGRAM + &res // The struct to populate + ); + + // Did we succeed? + if (status != 0) + { + TraceLog(LOG_WARNING, "Failed to get resolve host %s:%s: %s", ip, port, gai_strerror(errno)); + } + else + { + TraceLog(LOG_DEBUG, "Resolving... %s::%s", ip, port); + } + + // Attempt to resolve network byte order ip to hostname + switch (res->ai_family) + { + case AF_INET: + status = getnameinfo(&*((struct sockaddr *) res->ai_addr), + sizeof(*((struct sockaddr_in *) res->ai_addr)), + host, + NI_MAXHOST, + serv, + NI_MAXSERV, + flags); + break; + case AF_INET6: + status = getnameinfo(&*((struct sockaddr_in6 *) res->ai_addr), + sizeof(*((struct sockaddr_in6 *) res->ai_addr)), + host, + NI_MAXHOST, + serv, + NI_MAXSERV, + flags); + break; + default: break; + } + + if (status != 0) + { + TraceLog(LOG_WARNING, "Failed to resolve ip %s: %s", ip, SocketGetLastErrorString()); + } + else + { + TraceLog(LOG_DEBUG, "Successfully resolved %s::%s to %s", ip, port, host); + } + + // Free the pointer to the data returned by addrinfo + freeaddrinfo(res); +} + +// Protocol-independent translation from an ANSI host name to an address +// +// e.g. +// const char* address = "127.0.0.1" (local address) +// const char* port = "80" +// +// Parameters: +// const char* address - A pointer to a NULL-terminated ANSI string that contains a host (node) name or a numeric host address string. +// const char* service - A pointer to a NULL-terminated ANSI string that contains either a service name or port number represented as a string. +// +// Returns: +// The total amount of addresses found, -1 on error +// +int ResolveHost(const char *address, const char *service, int addressType, int flags, AddressInformation *outAddr) +{ + // Variables + int status; // Status value to return (0) is success + struct addrinfo hints; // Address flags (IPV4, IPV6, UDP?) + struct addrinfo *res; // will point to the results + struct addrinfo *iterator; + assert(((address != NULL || address != 0) || (service != NULL || service != 0))); + assert(((addressType == AF_INET) || (addressType == AF_INET6) || (addressType == AF_UNSPEC))); + + // Set the hints + memset(&hints, 0, sizeof hints); + hints.ai_family = addressType; // Either IPv4 or IPv6 (ADDRESS_TYPE_IPV4, ADDRESS_TYPE_IPV6) + hints.ai_protocol = 0; // Automatically select correct protocol (IPPROTO_TCP), (IPPROTO_UDP) + hints.ai_flags = flags; + assert(hints.ai_addrlen == NULL || hints.ai_addrlen == 0); + assert(hints.ai_canonname == NULL || hints.ai_canonname == 0); + assert(hints.ai_addr == NULL || hints.ai_addr == 0); + assert(hints.ai_next == NULL || hints.ai_next == 0); + + // When the address is NULL, populate the IP for me + if (address == NULL) + { + if ((hints.ai_flags & AI_PASSIVE) == 0) + { + hints.ai_flags |= AI_PASSIVE; + } + } + + TraceLog(LOG_INFO, "Resolving host..."); + + // Populate address information + status = getaddrinfo(address, // e.g. "www.example.com" or IP + service, // e.g. "http" or port number + &hints, // e.g. SOCK_STREAM/SOCK_DGRAM + &res // The struct to populate + ); + + // Did we succeed? + if (status != 0) + { + int error = SocketGetLastError(); + SocketSetLastError(0); + TraceLog(LOG_WARNING, "Failed to get resolve host: %s", SocketErrorCodeToString(error)); + return -1; + } + else + { + TraceLog(LOG_INFO, "Successfully resolved host %s:%s", address, service); + } + + // Calculate the size of the address information list + int size = 0; + for (iterator = res; iterator != NULL; iterator = iterator->ai_next) + { + size++; + } + + // Validate the size is > 0, otherwise return + if (size <= 0) + { + TraceLog(LOG_WARNING, "Error, no addresses found."); + return -1; + } + + // If not address list was allocated, allocate it dynamically with the known address size + if (outAddr == NULL) + { + outAddr = (AddressInformation *) malloc(size * sizeof(AddressInformation)); + } + + // Dynamically allocate an array of address information structs + if (outAddr != NULL) + { + int i; + for (i = 0; i < size; ++i) + { + outAddr[i] = AllocAddress(); + if (outAddr[i] == NULL) + { + break; + } + } + outAddr[i] = NULL; + if (i != size) + { + outAddr = NULL; + } + } + else + { + TraceLog(LOG_WARNING, + "Error, failed to dynamically allocate memory for the address list"); + return -1; + } + + // Copy all the address information from res into outAddrList + int i = 0; + for (iterator = res; iterator != NULL; iterator = iterator->ai_next) + { + if (i < size) + { + outAddr[i]->addr.ai_flags = iterator->ai_flags; + outAddr[i]->addr.ai_family = iterator->ai_family; + outAddr[i]->addr.ai_socktype = iterator->ai_socktype; + outAddr[i]->addr.ai_protocol = iterator->ai_protocol; + outAddr[i]->addr.ai_addrlen = iterator->ai_addrlen; + *outAddr[i]->addr.ai_addr = *iterator->ai_addr; +#if NET_DEBUG_ENABLED + TraceLog(LOG_DEBUG, "GetAddressInformation"); + TraceLog(LOG_DEBUG, "\tFlags: 0x%x", iterator->ai_flags); + PrintSocket(outAddr[i]->addr.ai_addr, + outAddr[i]->addr.ai_family, + outAddr[i]->addr.ai_socktype, + outAddr[i]->addr.ai_protocol); + TraceLog(LOG_DEBUG, "Length of this sockaddr: %d", outAddr[i]->addr.ai_addrlen); + TraceLog(LOG_DEBUG, "Canonical name: %s", iterator->ai_canonname); +#endif + i++; + } + } + + // Free the pointer to the data returned by addrinfo + freeaddrinfo(res); + + // Return the total count of addresses found + return size; +} + +// This here is the bread and butter of the socket API, This function will +// attempt to open a socket, bind and listen to it based on the config passed in +// +// SocketConfig* config - Configuration for which socket to open +// SocketResult* result - The results of this function (if any, including errors) +// +// e.g. +// SocketConfig server_config = { SocketConfig client_config = { +// .host = "127.0.0.1", .host = "127.0.0.1", +// .port = 8080, .port = 8080, +// .server = true, }; +// .nonblocking = true, +// }; +// SocketResult server_res; SocketResult client_res; +bool SocketCreate(SocketConfig *config, SocketResult *result) +{ + // Socket creation result + bool success = true; + + // Make sure we've not received a null config or result pointer + if (config == NULL || result == NULL) + { + return (success = false); + } + + // Set the defaults based on the config + if (!SocketSetDefaults(config)) + { + TraceLog(LOG_WARNING, "Configuration Error."); + success = false; + } + else + { + // Create the socket + if (CreateSocket(config, result)) + { + if (config->nonblocking) + { + SocketSetNonBlocking(result->socket); + } + else + { + SocketSetBlocking(result->socket); + } + } + else + { + success = false; + } + } + return success; +} + +// Bind a socket to a local address +// Note: The bind function is required on an unconnected socket before subsequent calls to the listen function. +bool SocketBind(SocketConfig *config, SocketResult *result) +{ + bool success = false; + result->status = RESULT_FAILURE; + struct sockaddr_storage *sock_addr = NULL; + + // Don't bind to a socket that isn't configured as a server + if (!IsSocketValid(result->socket) || !config->server) + { + TraceLog(LOG_WARNING, + "Cannot bind to socket marked as \"Client\" in SocketConfig."); + success = false; + } + else + { + if (result->socket->isIPv6) + { + sock_addr = (struct sockaddr_storage *) &result->socket->addripv6->address; + } + else + { + sock_addr = (struct sockaddr_storage *) &result->socket->addripv4->address; + } + if (sock_addr != NULL) + { + if (bind(result->socket->channel, (struct sockaddr *) sock_addr, sizeof(*sock_addr)) != SOCKET_ERROR) + { + TraceLog(LOG_INFO, "Successfully bound socket."); + success = true; + } + else + { + result->socket->status = SocketGetLastError(); + TraceLog(LOG_WARNING, "Socket Error: %s", + SocketErrorCodeToString(result->socket->status)); + SocketSetLastError(0); + success = false; + } + } + } + // Was the bind a success? + if (success) + { + result->status = RESULT_SUCCESS; + result->socket->ready = 0; + result->socket->status = 0; + socklen_t sock_len = sizeof(*sock_addr); + if (getsockname(result->socket->channel, (struct sockaddr *) sock_addr, &sock_len) < 0) + { + TraceLog(LOG_WARNING, "Couldn't get socket address"); + } + else + { + struct sockaddr_in *s = (struct sockaddr_in *) sock_addr; + // result->socket->address.host = s->sin_addr.s_addr; + // result->socket->address.port = s->sin_port; + + // + result->socket->addripv4 + = (struct _SocketAddressIPv4 *) malloc(sizeof(*result->socket->addripv4)); + if (result->socket->addripv4 != NULL) + { + memset(result->socket->addripv4, 0, sizeof(*result->socket->addripv4)); + } + memcpy(&result->socket->addripv4->address, (struct sockaddr_in *) &s->sin_addr, sizeof(struct sockaddr_in)); + // + } + } + return success; +} + +// Listens (and queues) incoming connections requests for a bound port. +bool SocketListen(SocketConfig *config, SocketResult *result) +{ + bool success = false; + result->status = RESULT_FAILURE; + + // Don't bind to a socket that isn't configured as a server + if (!IsSocketValid(result->socket) || !config->server) + { + TraceLog(LOG_WARNING, + "Cannot listen on socket marked as \"Client\" in SocketConfig."); + success = false; + } + else + { + // Don't listen on UDP sockets + if (!(config->type == SOCKET_UDP)) + { + if (listen(result->socket->channel, config->backlog_size) != SOCKET_ERROR) + { + TraceLog(LOG_INFO, "Started listening on socket..."); + success = true; + } + else + { + success = false; + result->socket->status = SocketGetLastError(); + TraceLog(LOG_WARNING, "Socket Error: %s", + SocketErrorCodeToString(result->socket->status)); + SocketSetLastError(0); + } + } + else + { + TraceLog(LOG_WARNING, + "Cannot listen on socket marked as \"UDP\" (datagram) in SocketConfig."); + success = false; + } + } + + // Was the listen a success? + if (success) + { + result->status = RESULT_SUCCESS; + result->socket->ready = 0; + result->socket->status = 0; + } + return success; +} + +// Connect the socket to the destination specified by "host" and "port" in SocketConfig +bool SocketConnect(SocketConfig *config, SocketResult *result) +{ + bool success = true; + result->status = RESULT_FAILURE; + + // Only bind to sockets marked as server + if (config->server) + { + TraceLog(LOG_WARNING, + "Cannot connect to socket marked as \"Server\" in SocketConfig."); + success = false; + } + else + { + if (IsIPv4Address(config->host)) + { + struct sockaddr_in ip4addr; + ip4addr.sin_family = AF_INET; + unsigned long hport; + hport = strtoul(config->port, NULL, 0); + ip4addr.sin_port = htons(hport); + inet_pton(AF_INET, config->host, &ip4addr.sin_addr); + int connect_result = connect(result->socket->channel, (struct sockaddr *) &ip4addr, sizeof(ip4addr)); + if (connect_result == SOCKET_ERROR) + { + result->socket->status = SocketGetLastError(); + SocketSetLastError(0); + switch (result->socket->status) + { + case WSAEWOULDBLOCK: + { + success = true; + break; + } + default: + { + TraceLog(LOG_WARNING, "Socket Error: %s", + SocketErrorCodeToString(result->socket->status)); + success = false; + break; + } + } + } + else + { + TraceLog(LOG_INFO, "Successfully connected to socket."); + success = true; + } + } + else + { + if (IsIPv6Address(config->host)) + { + struct sockaddr_in6 ip6addr; + ip6addr.sin6_family = AF_INET6; + unsigned long hport; + hport = strtoul(config->port, NULL, 0); + ip6addr.sin6_port = htons(hport); + inet_pton(AF_INET6, config->host, &ip6addr.sin6_addr); + int connect_result = connect(result->socket->channel, (struct sockaddr *) &ip6addr, sizeof(ip6addr)); + if (connect_result == SOCKET_ERROR) + { + result->socket->status = SocketGetLastError(); + SocketSetLastError(0); + switch (result->socket->status) + { + case WSAEWOULDBLOCK: + { + success = true; + break; + } + default: + { + TraceLog(LOG_WARNING, "Socket Error: %s", + SocketErrorCodeToString(result->socket->status)); + success = false; + break; + } + } + } + else + { + TraceLog(LOG_INFO, "Successfully connected to socket."); + success = true; + } + } + } + } + + if (success) + { + result->status = RESULT_SUCCESS; + result->socket->ready = 0; + result->socket->status = 0; + } + + return success; +} + +// Closes an existing socket +// +// SocketChannel socket - The id of the socket to close +void SocketClose(Socket *sock) +{ + if (sock != NULL) + { + if (sock->channel != INVALID_SOCKET) + { + closesocket(sock->channel); + } + } +} + +// Returns the sockaddress for a specific socket in a generic storage struct +SocketAddressStorage SocketGetPeerAddress(Socket *sock) +{ + if (sock->isServer) + { + return NULL; + } + if (sock->isIPv6) + { + return sock->addripv6; + } + else + { + return sock->addripv4; + } +} + +// Return the address-type appropriate host portion of a socket address +char *GetSocketAddressHost(SocketAddressStorage storage) +{ + assert(storage->address.ss_family == AF_INET || storage->address.ss_family == AF_INET6); + return SocketAddressToString((struct sockaddr_storage *) storage); +} + +// Return the address-type appropriate port(service) portion of a socket address +short GetSocketAddressPort(SocketAddressStorage storage) +{ + return ntohs(GetSocketPortPtr(storage)); +} + +// The accept function permits an incoming connection attempt on a socket. +// +// SocketChannel listener - The socket to listen for incoming connections on (i.e. server) +// SocketResult* out - The result of this function (if any, including errors) +// +// e.g. +// +// SocketResult connection; +// bool connected = false; +// if (!connected) +// { +// if (SocketAccept(server_res.socket.channel, &connection)) +// { +// connected = true; +// } +// } +Socket *SocketAccept(Socket *server, SocketConfig *config) +{ + if (!server->isServer || server->type == SOCKET_UDP) + { + return NULL; + } + struct sockaddr_storage sock_addr; + socklen_t sock_alen; + Socket * sock; + sock = AllocSocket(); + server->ready = 0; + sock_alen = sizeof(sock_addr); + sock->channel = accept(server->channel, (struct sockaddr *) &sock_addr, &sock_alen); + if (sock->channel == INVALID_SOCKET) + { + sock->status = SocketGetLastError(); + TraceLog(LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(sock->status)); + SocketSetLastError(0); + SocketClose(sock); + return NULL; + } + (config->nonblocking) ? SocketSetNonBlocking(sock) : SocketSetBlocking(sock); + sock->isServer = false; + sock->ready = 0; + sock->type = server->type; + switch (sock_addr.ss_family) + { + case AF_INET: + { + struct sockaddr_in *s = ((struct sockaddr_in *) &sock_addr); + sock->addripv4 = (struct _SocketAddressIPv4 *) malloc(sizeof(*sock->addripv4)); + if (sock->addripv4 != NULL) + { + memset(sock->addripv4, 0, sizeof(*sock->addripv4)); + memcpy(&sock->addripv4->address, (struct sockaddr_in *) &s->sin_addr, sizeof(struct sockaddr_in)); + TraceLog(LOG_INFO, "Server: Got connection from %s::%hu", SocketAddressToString((struct sockaddr_storage *) s), + ntohs(sock->addripv4->address.sin_port)); + } + } + break; + case AF_INET6: + { + struct sockaddr_in6 *s = ((struct sockaddr_in6 *) &sock_addr); + sock->addripv6 = (struct _SocketAddressIPv6 *) malloc(sizeof(*sock->addripv6)); + if (sock->addripv6 != NULL) + { + memset(sock->addripv6, 0, sizeof(*sock->addripv6)); + memcpy(&sock->addripv6->address, (struct sockaddr_in6 *) &s->sin6_addr, sizeof(struct sockaddr_in6)); + TraceLog(LOG_INFO, "Server: Got connection from %s::%hu", SocketAddressToString((struct sockaddr_storage *) s), + ntohs(sock->addripv6->address.sin6_port)); + } + } + break; + } + return sock; +} + +// Verify that the channel is in the valid range +static int ValidChannel(int channel) +{ + if ((channel < 0) || (channel >= SOCKET_MAX_UDPCHANNELS)) + { + TraceLog(LOG_WARNING, "Invalid channel"); + return 0; + } + return 1; +} + +// Set the socket channel +int SocketSetChannel(Socket *socket, int channel, const IPAddress *address) +{ + struct UDPChannel *binding; + if (socket == NULL) + { + TraceLog(LOG_WARNING, "Passed a NULL socket"); + return (-1); + } + if (channel == -1) + { + for (channel = 0; channel < SOCKET_MAX_UDPCHANNELS; ++channel) + { + binding = &socket->binding[channel]; + if (binding->numbound < SOCKET_MAX_UDPADDRESSES) + { + break; + } + } + } + else + { + if (!ValidChannel(channel)) + { + return (-1); + } + binding = &socket->binding[channel]; + } + if (binding->numbound == SOCKET_MAX_UDPADDRESSES) + { + TraceLog(LOG_WARNING, "No room for new addresses"); + return (-1); + } + binding->address[binding->numbound++] = *address; + return (channel); +} + +// Remove the socket channel +void SocketUnsetChannel(Socket *socket, int channel) +{ + if ((channel >= 0) && (channel < SOCKET_MAX_UDPCHANNELS)) + { + socket->binding[channel].numbound = 0; + } +} + +/* Allocate/free a single UDP packet 'size' bytes long. + The new packet is returned, or NULL if the function ran out of memory. + */ +SocketDataPacket *AllocPacket(int size) +{ + SocketDataPacket *packet; + int error; + + error = 1; + packet = (SocketDataPacket *) malloc(sizeof(*packet)); + if (packet != NULL) + { + packet->maxlen = size; + packet->data = (uint8_t *) malloc(size); + if (packet->data != NULL) + { + error = 0; + } + } + if (error) + { + FreePacket(packet); + packet = NULL; + } + return (packet); +} + +int ResizePacket(SocketDataPacket *packet, int newsize) +{ + uint8_t *newdata; + + newdata = (uint8_t *) malloc(newsize); + if (newdata != NULL) + { + free(packet->data); + packet->data = newdata; + packet->maxlen = newsize; + } + return (packet->maxlen); +} + +void FreePacket(SocketDataPacket *packet) +{ + if (packet) + { + free(packet->data); + free(packet); + } +} + +/* Allocate/Free a UDP packet vector (array of packets) of 'howmany' packets, + each 'size' bytes long. + A pointer to the packet array is returned, or NULL if the function ran out + of memory. + */ +SocketDataPacket **AllocPacketList(int howmany, int size) +{ + SocketDataPacket **packetV; + + packetV = (SocketDataPacket **) malloc((howmany + 1) * sizeof(*packetV)); + if (packetV != NULL) + { + int i; + for (i = 0; i < howmany; ++i) + { + packetV[i] = AllocPacket(size); + if (packetV[i] == NULL) + { + break; + } + } + packetV[i] = NULL; + + if (i != howmany) + { + FreePacketList(packetV); + packetV = NULL; + } + } + return (packetV); +} + +void FreePacketList(SocketDataPacket **packetV) +{ + if (packetV) + { + int i; + for (i = 0; packetV[i]; ++i) + { + FreePacket(packetV[i]); + } + free(packetV); + } +} + +// Send 'len' bytes of 'data' over the non-server socket 'sock' +// +// Example +int SocketSend(Socket *sock, const void *datap, int length) +{ + int sent = 0; + int left = length; + int status = -1; + int numsent = 0; + const unsigned char *data = (const unsigned char *) datap; + + // Server sockets are for accepting connections only + if (sock->isServer) + { + TraceLog(LOG_WARNING, "Cannot send information on a server socket"); + return -1; + } + + // Which socket are we trying to send data on + switch (sock->type) + { + case SOCKET_TCP: + { + SocketSetLastError(0); + do + { + length = send(sock->channel, (const char *) data, left, 0); + if (length > 0) + { + sent += length; + left -= length; + data += length; + } + } while ((left > 0) && // While we still have bytes left to send + ((length > 0) || // The amount of bytes we actually sent is > 0 + (SocketGetLastError() == WSAEINTR)) // The socket was interupted + ); + + if (length == SOCKET_ERROR) + { + sock->status = SocketGetLastError(); + TraceLog(LOG_DEBUG, "Socket Error: %s", SocketErrorCodeToString(sock->status)); + SocketSetLastError(0); + } + else + { + TraceLog(LOG_DEBUG, "Successfully sent \"%s\" (%d bytes)", datap, sent); + } + + return sent; + } + break; + case SOCKET_UDP: + { + SocketSetLastError(0); + if (sock->isIPv6) + { + status = sendto(sock->channel, (const char *) data, left, 0, + (struct sockaddr *) &sock->addripv6->address, + sizeof(sock->addripv6->address)); + } + else + { + status = sendto(sock->channel, (const char *) data, left, 0, + (struct sockaddr *) &sock->addripv4->address, + sizeof(sock->addripv4->address)); + } + if (sent >= 0) + { + sock->status = 0; + ++numsent; + TraceLog(LOG_DEBUG, "Successfully sent \"%s\" (%d bytes)", datap, status); + } + else + { + sock->status = SocketGetLastError(); + TraceLog(LOG_DEBUG, "Socket Error: %s", SocketGetLastErrorString(sock->status)); + SocketSetLastError(0); + return 0; + } + return numsent; + } + break; + default: break; + } + return -1; +} + +// Receive up to 'maxlen' bytes of data over the non-server socket 'sock', +// and store them in the buffer pointed to by 'data'. +// This function returns the actual amount of data received. If the return +// value is less than or equal to zero, then either the remote connection was +// closed, or an unknown socket error occurred. +int SocketReceive(Socket *sock, void *data, int maxlen) +{ + int len = 0; + int numrecv = 0; + int status = 0; + socklen_t sock_len; + struct sockaddr_storage sock_addr; + char ip[INET6_ADDRSTRLEN]; + + // Server sockets are for accepting connections only + if (sock->isServer && sock->type == SOCKET_TCP) + { + sock->status = SocketGetLastError(); + TraceLog(LOG_DEBUG, "Socket Error: %s", + "Server sockets cannot be used to receive data"); + SocketSetLastError(0); + return 0; + } + + // Which socket are we trying to send data on + switch (sock->type) + { + case SOCKET_TCP: + { + SocketSetLastError(0); + do + { + len = recv(sock->channel, (char *) data, maxlen, 0); + } while (SocketGetLastError() == WSAEINTR); + + if (len > 0) + { + // Who sent the packet? + if (sock->type == SOCKET_UDP) + { + TraceLog( + LOG_DEBUG, "Received data from: %s", inet_ntop(sock_addr.ss_family, GetSocketAddressPtr((struct sockaddr *) &sock_addr), ip, sizeof(ip))); + } + ((unsigned char *) data)[len] = '\0'; // Add null terminating character to the end of the stream + TraceLog(LOG_DEBUG, "Received \"%s\" (%d bytes)", data, len); + } + sock->ready = 0; + return len; + } + break; + case SOCKET_UDP: + { + SocketSetLastError(0); + sock_len = sizeof(sock_addr); + status = recvfrom(sock->channel, // The receving channel + data, // A pointer to the data buffer to fill + maxlen, // The max length of the data to fill + 0, // Flags + (struct sockaddr *) &sock_addr, // The address of the recevied data + &sock_len // The length of the received data address + ); + if (status >= 0) + { + ++numrecv; + } + else + { + sock->status = SocketGetLastError(); + switch (sock->status) + { + case WSAEWOULDBLOCK: { break; + } + default: + { + TraceLog(LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(sock->status)); + break; + } + } + SocketSetLastError(0); + return 0; + } + sock->ready = 0; + return numrecv; + } + break; + } + return -1; +} + +// Does the socket have it's 'ready' flag set? +bool IsSocketReady(Socket *sock) +{ + return (sock != NULL) && (sock->ready); +} + +// Check if the socket is considered connected +bool IsSocketConnected(Socket *sock) +{ +#if PLATFORM_WINDOWS + FD_SET writefds; + FD_ZERO(&writefds); + FD_SET(sock->channel, &writefds); + struct timeval timeout; + timeout.tv_sec = 1; + timeout.tv_usec = 1000000000UL; + int total = select(0, NULL, &writefds, NULL, &timeout); + if (total == -1) + { // Error + sock->status = SocketGetLastError(); + TraceLog(LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(sock->status)); + SocketSetLastError(0); + } + else if (total == 0) + { // Timeout + return false; + } + else + { + if (FD_ISSET(sock->channel, &writefds)) + { + return true; + } + } + return false; +#else + return true; +#endif +} + +// Allocate and return a SocketResult struct +SocketResult *AllocSocketResult() +{ + struct SocketResult *res; + res = (struct SocketResult *) malloc(sizeof(*res)); + if (res != NULL) + { + memset(res, 0, sizeof(*res)); + if ((res->socket = AllocSocket()) == NULL) + { + free(res); + res = NULL; + } + } + return res; +} + +// Free an allocated SocketResult +void FreeSocketResult(SocketResult **result) +{ + if (*result != NULL) + { + if ((*result)->socket != NULL) + { + FreeSocket(&((*result)->socket)); + } + free(*result); + *result = NULL; + } +} + +// Allocate a Socket +Socket *AllocSocket() +{ + // Allocate a socket if one already hasn't been + struct Socket *sock; + sock = (Socket *) malloc(sizeof(*sock)); + if (sock != NULL) + { + memset(sock, 0, sizeof(*sock)); + } + else + { + TraceLog( + LOG_WARNING, "Ran out of memory attempting to allocate a socket"); + SocketClose(sock); + free(sock); + sock = NULL; + } + return sock; +} + +// Free an allocated Socket +void FreeSocket(Socket **sock) +{ + if (*sock != NULL) + { + free(*sock); + *sock = NULL; + } +} + +// Allocate a SocketSet +SocketSet *AllocSocketSet(int max) +{ + struct SocketSet *set; + int i; + + set = (struct SocketSet *) malloc(sizeof(*set)); + if (set != NULL) + { + set->numsockets = 0; + set->maxsockets = max; + set->sockets = (struct Socket **) malloc(max * sizeof(*set->sockets)); + if (set->sockets != NULL) + { + for (i = 0; i < max; ++i) + { + set->sockets[i] = NULL; + } + } + else + { + free(set); + set = NULL; + } + } + return (set); +} + +// Free an allocated SocketSet +void FreeSocketSet(SocketSet *set) +{ + if (set) + { + free(set->sockets); + free(set); + } +} + +// Add a Socket "sock" to the SocketSet "set" +int AddSocket(SocketSet *set, Socket *sock) +{ + if (sock != NULL) + { + if (set->numsockets == set->maxsockets) + { + TraceLog(LOG_DEBUG, "Socket Error: %s", "SocketSet is full"); + SocketSetLastError(0); + return (-1); + } + set->sockets[set->numsockets++] = (struct Socket *) sock; + } + else + { + TraceLog(LOG_DEBUG, "Socket Error: %s", "Socket was null"); + SocketSetLastError(0); + return (-1); + } + return (set->numsockets); +} + +// Remove a Socket "sock" to the SocketSet "set" +int RemoveSocket(SocketSet *set, Socket *sock) +{ + int i; + + if (sock != NULL) + { + for (i = 0; i < set->numsockets; ++i) + { + if (set->sockets[i] == (struct Socket *) sock) + { + break; + } + } + if (i == set->numsockets) + { + TraceLog(LOG_DEBUG, "Socket Error: %s", "Socket not found"); + SocketSetLastError(0); + return (-1); + } + --set->numsockets; + for (; i < set->numsockets; ++i) + { + set->sockets[i] = set->sockets[i + 1]; + } + } + return (set->numsockets); +} + +// Check the sockets in the socket set for pending information +int CheckSockets(SocketSet *set, unsigned int timeout) +{ + int i; + SOCKET maxfd; + int retval; + struct timeval tv; + fd_set mask; + + /* Find the largest file descriptor */ + maxfd = 0; + for (i = set->numsockets - 1; i >= 0; --i) + { + if (set->sockets[i]->channel > maxfd) + { + maxfd = set->sockets[i]->channel; + } + } + + // Check the file descriptors for available data + do + { + SocketSetLastError(0); + + // Set up the mask of file descriptors + FD_ZERO(&mask); + for (i = set->numsockets - 1; i >= 0; --i) + { + FD_SET(set->sockets[i]->channel, &mask); + } // Set up the timeout + tv.tv_sec = timeout / 1000; + tv.tv_usec = (timeout % 1000) * 1000; + + /* Look! */ + retval = select(maxfd + 1, &mask, NULL, NULL, &tv); + } while (SocketGetLastError() == WSAEINTR); + + // Mark all file descriptors ready that have data available + if (retval > 0) + { + for (i = set->numsockets - 1; i >= 0; --i) + { + if (FD_ISSET(set->sockets[i]->channel, &mask)) + { + set->sockets[i]->ready = 1; + } + } + } + return (retval); +} + +// Allocate an AddressInformation +AddressInformation AllocAddress() +{ + AddressInformation addressInfo = NULL; + addressInfo = (AddressInformation) calloc(1, sizeof(*addressInfo)); + if (addressInfo != NULL) + { + addressInfo->addr.ai_addr = (struct sockaddr *) calloc(1, sizeof(struct sockaddr)); + if (addressInfo->addr.ai_addr == NULL) + { + TraceLog(LOG_WARNING, + "Failed to allocate memory for \"struct sockaddr\""); + } + } + else + { + TraceLog(LOG_WARNING, + "Failed to allocate memory for \"struct AddressInformation\""); + } + return addressInfo; +} + +// Free an AddressInformation struct +void FreeAddress(AddressInformation *addressInfo) +{ + if (*addressInfo != NULL) + { + if ((*addressInfo)->addr.ai_addr != NULL) + { + free((*addressInfo)->addr.ai_addr); + (*addressInfo)->addr.ai_addr = NULL; + } + free(*addressInfo); + *addressInfo = NULL; + } +} + +// Allocate a list of AddressInformation +AddressInformation *AllocAddressList(int size) +{ + AddressInformation *addr; + addr = (AddressInformation *) malloc(size * sizeof(AddressInformation)); + return addr; +} + +// Opaque datatype accessor addrinfo->ai_family +int GetAddressFamily(AddressInformation address) +{ + return address->addr.ai_family; +} + +// Opaque datatype accessor addrinfo->ai_socktype +int GetAddressSocketType(AddressInformation address) +{ + return address->addr.ai_socktype; +} + +// Opaque datatype accessor addrinfo->ai_protocol +int GetAddressProtocol(AddressInformation address) +{ + return address->addr.ai_protocol; +} + +// Opaque datatype accessor addrinfo->ai_canonname +char *GetAddressCanonName(AddressInformation address) +{ + return address->addr.ai_canonname; +} + +// Opaque datatype accessor addrinfo->ai_addr +char *GetAddressHostAndPort(AddressInformation address, char *outhost, int *outport) +{ + char * ip[INET6_ADDRSTRLEN]; + char * result = NULL; + struct sockaddr_storage *storage = (struct sockaddr_storage *) address->addr.ai_addr; + switch (storage->ss_family) + { + case AF_INET: + { + struct sockaddr_in *s = ((struct sockaddr_in *) address->addr.ai_addr); + result = inet_ntop(AF_INET, &s->sin_addr, ip, INET_ADDRSTRLEN); + *outport = ntohs(s->sin_port); + } + break; + case AF_INET6: + { + struct sockaddr_in6 *s = ((struct sockaddr_in6 *) address->addr.ai_addr); + result = inet_ntop(AF_INET6, &s->sin6_addr, ip, INET6_ADDRSTRLEN); + *outport = ntohs(s->sin6_port); + } + break; + } + if (result == NULL) + { + TraceLog(LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(SocketGetLastError())); + SocketSetLastError(0); + } + else + { + strcpy(outhost, result); + } + return result; +} + +// +void PacketSend(Packet *packet) +{ + printf("Sending packet (%s) with size %d\n", packet->data, packet->size); +} + +// +void PacketReceive(Packet *packet) +{ + printf("Receiving packet (%s) with size %d\n", packet->data, packet->size); +} + +// +void PacketWrite16(Packet *packet, uint16_t value) +{ + printf("Original: 0x%04" PRIX16 " - %" PRIu16 "\n", value, value); + uint8_t *data = packet->data + packet->offs; + *data++ = (uint8_t)(value >> 8); + *data++ = (uint8_t)(value); + packet->size += sizeof(uint16_t); + packet->offs += sizeof(uint16_t); + printf("Network: 0x%04" PRIX16 " - %" PRIu16 "\n", (uint16_t) *data, (uint16_t) *data); +} + +// +void PacketWrite32(Packet *packet, uint32_t value) +{ + printf("Original: 0x%08" PRIX32 " - %" PRIu32 "\n", value, value); + uint8_t *data = packet->data + packet->offs; + *data++ = (uint8_t)(value >> 24); + *data++ = (uint8_t)(value >> 16); + *data++ = (uint8_t)(value >> 8); + *data++ = (uint8_t)(value); + packet->size += sizeof(uint32_t); + packet->offs += sizeof(uint32_t); + printf("Network: 0x%08" PRIX32 " - %" PRIu32 "\n", + (uint32_t)(((intptr_t) packet->data) - packet->offs), + (uint32_t)(((intptr_t) packet->data) - packet->offs)); +} + +// +void PacketWrite64(Packet *packet, uint64_t value) +{ + printf("Original: 0x%016" PRIX64 " - %" PRIu64 "\n", value, value); + uint8_t *data = packet->data + packet->offs; + *data++ = (uint8_t)(value >> 56); + *data++ = (uint8_t)(value >> 48); + *data++ = (uint8_t)(value >> 40); + *data++ = (uint8_t)(value >> 32); + *data++ = (uint8_t)(value >> 24); + *data++ = (uint8_t)(value >> 16); + *data++ = (uint8_t)(value >> 8); + *data++ = (uint8_t)(value); + packet->size += sizeof(uint64_t); + packet->offs += sizeof(uint64_t); + printf("Network: 0x%016" PRIX64 " - %" PRIu64 "\n", + (uint64_t)(packet->data - packet->offs), + (uint64_t)(packet->data - packet->offs)); +} + +// +uint16_t PacketRead16(Packet *packet) +{ + uint8_t *data = packet->data + packet->offs; + packet->size += sizeof(uint16_t); + packet->offs += sizeof(uint16_t); + uint16_t value = ((uint16_t) data[0] << 8) | data[1]; + printf("Original: 0x%04" PRIX16 " - %" PRIu16 "\n", value, value); + return value; +} + +// +uint32_t PacketRead32(Packet *packet) +{ + uint8_t *data = packet->data + packet->offs; + packet->size += sizeof(uint32_t); + packet->offs += sizeof(uint32_t); + uint32_t value = ((uint32_t) data[0] << 24) | ((uint32_t) data[1] << 16) | ((uint32_t) data[2] << 8) | data[3]; + printf("Original: 0x%08" PRIX32 " - %" PRIu32 "\n", value, value); + return value; +} + +// +uint64_t PacketRead64(Packet *packet) +{ + uint8_t *data = packet->data + packet->offs; + packet->size += sizeof(uint64_t); + packet->offs += sizeof(uint64_t); + uint64_t value = ((uint64_t) data[0] << 56) | ((uint64_t) data[1] << 48) | ((uint64_t) data[2] << 40) | ((uint64_t) data[3] << 32) | ((uint64_t) data[4] << 24) | ((uint64_t) data[5] << 16) | ((uint64_t) data[6] << 8) | data[7]; + printf("Original: 0x%016" PRIX64 " - %" PRIu64 "\n", value, value); + return value; +} diff --git a/src/rnet.h b/src/rnet.h new file mode 100644 index 00000000..c2a14015 --- /dev/null +++ b/src/rnet.h @@ -0,0 +1,228 @@ +/********************************************************************************************** +* +* rnet - Provides cross-platform network defines, macros etc +* +* DEPENDENCIES: +* - Used for cross-platform type specifiers +* +* INSPIRED BY: +* SFML Sockets - https://www.sfml-dev.org/documentation/2.5.1/classsf_1_1Socket.php +* SDL_net - https://www.libsdl.org/projects/SDL_net/ +* BSD Sockets - https://www.gnu.org/software/libc/manual/html_node/Sockets.html +* BEEJ - https://beej.us/guide/bgnet/html/single/bgnet.html +* Winsock2 - https://docs.microsoft.com/en-us/windows/desktop/api/winsock2 +* +* +* CONTRIBUTORS: +* Jak Barnes (github: @syphonx) (Feb. 2019): +* - Initial version +* +* LICENSE: zlib/libpng +* +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) +* +* 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, subject to the following restrictions: +* +* 1. The origin of this software must not be misrepresented; you must not claim that you +* wrote the original software. If you use this software in a product, an acknowledgment +* in the product documentation would be appreciated but is not required. +* +* 2. Altered source versions must be plainly marked as such, and must not be misrepresented +* as being the original software. +* +* 3. This notice may not be removed or altered from any source distribution. +* +**********************************************************************************************/ + +//---------------------------------------------------------------------------------- +// Platform type sizes +//---------------------------------------------------------------------------------- + +#include + +//---------------------------------------------------------------------------------- +// Undefine any conflicting windows.h symbols +//---------------------------------------------------------------------------------- + +// If defined, the following flags inhibit definition of the indicated items. +#define NOGDICAPMASKS // CC_*, LC_*, PC_*, CP_*, TC_*, RC_ +#define NOVIRTUALKEYCODES // VK_* +#define NOWINMESSAGES // WM_*, EM_*, LB_*, CB_* +#define NOWINSTYLES // WS_*, CS_*, ES_*, LBS_*, SBS_*, CBS_* +#define NOSYSMETRICS // SM_* +#define NOMENUS // MF_* +#define NOICONS // IDI_* +#define NOKEYSTATES // MK_* +#define NOSYSCOMMANDS // SC_* +#define NORASTEROPS // Binary and Tertiary raster ops +#define NOSHOWWINDOW // SW_* +#define OEMRESOURCE // OEM Resource values +#define NOATOM // Atom Manager routines +#define NOCLIPBOARD // Clipboard routines +#define NOCOLOR // Screen colors +#define NOCTLMGR // Control and Dialog routines +#define NODRAWTEXT // DrawText() and DT_* +#define NOGDI // All GDI defines and routines +#define NOKERNEL // All KERNEL defines and routines +#define NOUSER // All USER defines and routines +#define NONLS // All NLS defines and routines +#define NOMB // MB_* and MessageBox() +#define NOMEMMGR // GMEM_*, LMEM_*, GHND, LHND, associated routines +#define NOMETAFILE // typedef METAFILEPICT +#define NOMINMAX // Macros min(a,b) and max(a,b) +#define NOMSG // typedef MSG and associated routines +#define NOOPENFILE // OpenFile(), OemToAnsi, AnsiToOem, and OF_* +#define NOSCROLL // SB_* and scrolling routines +#define NOSERVICE // All Service Controller routines, SERVICE_ equates, etc. +#define NOSOUND // Sound driver routines +#define NOTEXTMETRIC // typedef TEXTMETRIC and associated routines +#define NOWH // SetWindowsHook and WH_* +#define NOWINOFFSETS // GWL_*, GCL_*, associated routines +#define NOCOMM // COMM driver routines +#define NOKANJI // Kanji support stuff. +#define NOHELP // Help engine interface. +#define NOPROFILER // Profiler interface. +#define NODEFERWINDOWPOS // DeferWindowPos routines +#define NOMCX // Modem Configuration Extensions +#define MMNOSOUND + +//---------------------------------------------------------------------------------- +// Platform defines +//---------------------------------------------------------------------------------- + +#define PLATFORM_WINDOWS 1 +#define PLATFORM_LINUX 2 + +#if defined(__WIN32__) || defined(WIN32) +# define PLATFORM PLATFORM_WINDOWS +#elif defined(_LINUX) +# define PLATFORM PLATFORM_LINUX +#endif + +//---------------------------------------------------------------------------------- +// Platform type definitions +// From: https://github.com/DFHack/clsocket/blob/master/src/Host.h +//---------------------------------------------------------------------------------- + +#ifdef WIN32 +typedef int socklen_t; +#endif + +#ifndef RESULT_SUCCESS +# define RESULT_SUCCESS 0 +#endif // RESULT_SUCCESS + +#ifndef RESULT_FAILURE +# define RESULT_FAILURE 1 +#endif // RESULT_FAILURE + +#ifndef htonll +# ifdef _BIG_ENDIAN +# define htonll(x) (x) +# define ntohll(x) (x) +# else +# define htonll(x) ((((uint64) htonl(x)) << 32) + htonl(x >> 32)) +# define ntohll(x) ((((uint64) ntohl(x)) << 32) + ntohl(x >> 32)) +# endif // _BIG_ENDIAN +#endif // htonll + +//---------------------------------------------------------------------------------- +// Platform specific network includes +// From: https://github.com/SDL-mirror/SDL_net/blob/master/SDLnetsys.h +//---------------------------------------------------------------------------------- + +// Include system network headers + +#ifdef _WIN32 +# pragma comment(lib, "ws2_32.lib") +# define __USE_W32_SOCKETS +# define WIN32_LEAN_AND_MEAN +# include +# include +# include +# define IPTOS_LOWDELAY 0x10 +#else /* UNIX */ +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +#endif /* WIN32 */ + +#ifndef INVALID_SOCKET +# define INVALID_SOCKET ~(0) +#endif + +#ifndef __USE_W32_SOCKETS +# define closesocket close +# define SOCKET int +# define INVALID_SOCKET -1 +# define SOCKET_ERROR -1 +#endif + +#ifdef __USE_W32_SOCKETS +# ifndef EINTR +# define EINTR WSAEINTR +# endif +#endif + +//---------------------------------------------------------------------------------- +// Module defines +//---------------------------------------------------------------------------------- + +// Network connection related defines +#define SOCKET_MAX_SET_SIZE (32) // Maximum sockets in a set +#define SOCKET_MAX_QUEUE_SIZE (16) // Maximum socket queue size + +// Network address related defines +#define ADDRESS_IPV4_ADDRSTRLEN (22) // IPv4 string length +#define ADDRESS_IPV6_ADDRSTRLEN (65) // IPv6 string length +#define ADDRESS_TYPE_ANY (0) // AF_UNSPEC +#define ADDRESS_TYPE_IPV4 (2) // AF_INET +#define ADDRESS_TYPE_IPV6 (23) // AF_INET6 +#define ADDRESS_MAXHOST (1025) // Max size of a fully-qualified domain name +#define ADDRESS_MAXSERV (32) // Max size of a service name + +// Network address related defines +#define ADDRESS_ANY ((unsigned long) 0x00000000) +#define ADDRESS_LOOPBACK (0x7f000001) +#define ADDRESS_BROADCAST ((unsigned long) 0xffffffff) +#define ADDRESS_NONE (0xffffffff) + +// Address resolution related defines +#if defined(_WIN32) + #define ADDRESS_INFO_PASSIVE (0x00000001) // Socket address will be used in bind() call + #define ADDRESS_INFO_CANONNAME (0x00000002) // Return canonical name in first ai_canonname + #define ADDRESS_INFO_NUMERICHOST (0x00000004) // Nodename must be a numeric address string + #define ADDRESS_INFO_NUMERICSERV (0x00000008) // Servicename must be a numeric port number + #define ADDRESS_INFO_DNS_ONLY (0x00000010) // Restrict queries to unicast DNS only (no LLMNR, netbios, etc.) + #define ADDRESS_INFO_ALL (0x00000100) // Query both IP6 and IP4 with AI_V4MAPPED + #define ADDRESS_INFO_ADDRCONFIG (0x00000400) // Resolution only if global address configured + #define ADDRESS_INFO_V4MAPPED (0x00000800) // On v6 failure, query v4 and convert to V4MAPPED format + #define ADDRESS_INFO_NON_AUTHORITATIVE (0x00004000) // LUP_NON_AUTHORITATIVE + #define ADDRESS_INFO_SECURE (0x00008000) // LUP_SECURE + #define ADDRESS_INFO_RETURN_PREFERRED_NAMES (0x00010000) // LUP_RETURN_PREFERRED_NAMES + #define ADDRESS_INFO_FQDN (0x00020000) // Return the FQDN in ai_canonname + #define ADDRESS_INFO_FILESERVER (0x00040000) // Resolving fileserver name resolution + #define ADDRESS_INFO_DISABLE_IDN_ENCODING (0x00080000) // Disable Internationalized Domain Names handling + #define ADDRESS_INFO_EXTENDED (0x80000000) // Indicates this is extended ADDRINFOEX(2/..) struct + #define ADDRESS_INFO_RESOLUTION_HANDLE (0x40000000) // Request resolution handle +#endif + +// Network resolution related defines +#define NAME_INFO_DEFAULT (0x00) // No flags set +#define NAME_INFO_NOFQDN (0x01) // Only return nodename portion for local hosts +#define NAME_INFO_NUMERICHOST (0x02) // Return numeric form of the host's address +#define NAME_INFO_NAMEREQD (0x04) // Error if the host's name not in DNS +#define NAME_INFO_NUMERICSERV (0x08) // Return numeric form of the service (port #) +#define NAME_INFO_DGRAM (0x10) // Service is a datagram service \ No newline at end of file -- cgit v1.2.3 From f7d978e7261d3a8cb715108095f582d8908ac647 Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 22 Apr 2019 20:27:54 +0200 Subject: Reviewed rnet inclusion Move to own header for a more deep review of the module --- src/raylib.h | 167 +------------------------------------------- src/rnet.c | 21 +++--- src/rnet.h | 223 ++++++++++++++++++++++++++++++++++++++++++++++++++++------- 3 files changed, 210 insertions(+), 201 deletions(-) (limited to 'src') diff --git a/src/raylib.h b/src/raylib.h index 710f69b6..29850efd 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -75,7 +75,6 @@ #define RAYLIB_H #include // Required for: va_list - Only used by TraceLogCallback -#include // Required for rnet #if defined(_WIN32) && defined(BUILD_LIBTYPE_SHARED) #define RLAPI __declspec(dllexport) // We are building raylib as a Win32 shared library (.dll) @@ -448,100 +447,6 @@ typedef struct VrDeviceInfo { float lensDistortionValues[4]; // HMD lens distortion constant parameters float chromaAbCorrection[4]; // HMD chromatic aberration correction parameters } VrDeviceInfo; - -// Network typedefs -typedef uint32_t SocketChannel; -typedef struct _AddressInformation * AddressInformation; -typedef struct _SocketAddress * SocketAddress; -typedef struct _SocketAddressIPv4 * SocketAddressIPv4; -typedef struct _SocketAddressIPv6 * SocketAddressIPv6; -typedef struct _SocketAddressStorage *SocketAddressStorage; - -// IPAddress definition (in network byte order) -typedef struct IPAddress -{ - unsigned long host; /* 32-bit IPv4 host address */ - unsigned short port; /* 16-bit protocol port */ -} IPAddress; - -// An option ID, value, sizeof(value) tuple for setsockopt(2). -typedef struct SocketOpt -{ - int id; - void *value; - int valueLen; -} SocketOpt; - -typedef enum -{ - SOCKET_TCP = 0, // SOCK_STREAM - SOCKET_UDP = 1 // SOCK_DGRAM -} SocketType; - -typedef struct UDPChannel -{ - int numbound; // The total number of addresses this channel is bound to - IPAddress address[SOCKET_MAX_UDPADDRESSES]; // The list of remote addresses this channel is bound to -} UDPChannel; - -typedef struct Socket -{ - int ready; // Is the socket ready? i.e. has information - int status; // The last status code to have occured using this socket - bool isServer; // Is this socket a server socket (i.e. TCP/UDP Listen Server) - SocketChannel channel; // The socket handle id - SocketType type; // Is this socket a TCP or UDP socket? - bool isIPv6; // Is this socket address an ipv6 address? - SocketAddressIPv4 addripv4; // The host/target IPv4 for this socket (in network byte order) - SocketAddressIPv6 addripv6; // The host/target IPv6 for this socket (in network byte order) - - struct UDPChannel binding[SOCKET_MAX_UDPCHANNELS]; // The amount of channels (if UDP) this socket is bound to -} Socket; - -typedef struct SocketSet -{ - int numsockets; - int maxsockets; - struct Socket **sockets; -} SocketSet; - -typedef struct SocketDataPacket -{ - int channel; // The src/dst channel of the packet - unsigned char *data; // The packet data - int len; // The length of the packet data - int maxlen; // The size of the data buffer - int status; // packet status after sending - IPAddress address; // The source/dest address of an incoming/outgoing packet -} SocketDataPacket; - -// Configuration for a socket. -typedef struct SocketConfig -{ - char * host; // The host address in xxx.xxx.xxx.xxx form - char * port; // The target port/service in the form "http" or "25565" - bool server; // Listen for incoming clients? - SocketType type; // The type of socket, TCP/UDP - bool nonblocking; // non-blocking operation? - int backlog_size; // set a custom backlog size - SocketOpt sockopts[SOCKET_MAX_SOCK_OPTS]; -} SocketConfig; - -// Result from calling open with a given config. -typedef struct SocketResult -{ - int status; - Socket *socket; -} SocketResult; - -// -typedef struct Packet -{ - uint32_t size; // The total size of bytes in data - uint32_t offs; // The offset to data access - uint32_t maxs; // The max size of data - uint8_t *data; // Data stored in network byte order -} Packet; //---------------------------------------------------------------------------------- // Enumerators Definition @@ -1512,77 +1417,7 @@ RLAPI void SetAudioStreamPitch(AudioStream stream, float pitch); // Set pit // Network (Module: network) //------------------------------------------------------------------------------------ -// Initialisation and cleanup -RLAPI bool InitNetwork(void); -RLAPI void CloseNetwork(void); - -// Address API -RLAPI void ResolveIP(const char *ip, const char *service, int flags, char *outhost, char *outserv); -RLAPI int ResolveHost(const char *address, const char *service, int addressType, int flags, AddressInformation *outAddr); -RLAPI int GetAddressFamily(AddressInformation address); -RLAPI int GetAddressSocketType(AddressInformation address); -RLAPI int GetAddressProtocol(AddressInformation address); -RLAPI char* GetAddressCanonName(AddressInformation address); -RLAPI char* GetAddressHostAndPort(AddressInformation address, char *outhost, int *outport); -RLAPI void PrintAddressInfo(AddressInformation address); - -// Address Memory API -RLAPI AddressInformation AllocAddress(); -RLAPI void FreeAddress(AddressInformation *addressInfo); -RLAPI AddressInformation *AllocAddressList(int size); - -// Socket API -RLAPI bool SocketCreate(SocketConfig *config, SocketResult *result); -RLAPI bool SocketBind(SocketConfig *config, SocketResult *result); -RLAPI bool SocketListen(SocketConfig *config, SocketResult *result); -RLAPI bool SocketConnect(SocketConfig *config, SocketResult *result); -RLAPI Socket *SocketAccept(Socket *server, SocketConfig *config); - -// UDP Socket API -RLAPI int SocketSetChannel(Socket *socket, int channel, const IPAddress *address); -RLAPI void SocketUnsetChannel(Socket *socket, int channel); - -// UDP DataPacket API -RLAPI SocketDataPacket *AllocPacket(int size); -RLAPI int ResizePacket(SocketDataPacket *packet, int newsize); -RLAPI void FreePacket(SocketDataPacket *packet); -RLAPI SocketDataPacket **AllocPacketList(int count, int size); -RLAPI void FreePacketList(SocketDataPacket **packets); - -// General Socket API -RLAPI int SocketSend(Socket *sock, const void *datap, int len); -RLAPI int SocketReceive(Socket *sock, void *data, int maxlen); -RLAPI void SocketClose(Socket *sock); -RLAPI SocketAddressStorage SocketGetPeerAddress(Socket *sock); -RLAPI char* GetSocketAddressHost(SocketAddressStorage storage); -RLAPI short GetSocketAddressPort(SocketAddressStorage storage); - -// Socket Memory API -RLAPI Socket *AllocSocket(); -RLAPI void FreeSocket(Socket **sock); -RLAPI SocketResult *AllocSocketResult(); -RLAPI void FreeSocketResult(SocketResult **result); -RLAPI SocketSet *AllocSocketSet(int max); -RLAPI void FreeSocketSet(SocketSet *sockset); - -// Socket I/O API -RLAPI bool IsSocketReady(Socket *sock); -RLAPI bool IsSocketConnected(Socket *sock); -RLAPI int AddSocket(SocketSet *set, Socket *sock); -RLAPI int RemoveSocket(SocketSet *set, Socket *sock); -RLAPI int CheckSockets(SocketSet *set, unsigned int timeout); - -// Packet API -void PacketSend(Packet *packet); -void PacketReceive(Packet *packet); -void PacketWrite8(Packet *packet, uint16_t value); -void PacketWrite16(Packet *packet, uint16_t value); -void PacketWrite32(Packet *packet, uint32_t value); -void PacketWrite64(Packet *packet, uint64_t value); -uint16_t PacketRead8(Packet *packet); -uint16_t PacketRead16(Packet *packet); -uint32_t PacketRead32(Packet *packet); -uint64_t PacketRead64(Packet *packet); +// IN PROGRESS: Check rnet.h for reference #if defined(__cplusplus) } diff --git a/src/rnet.c b/src/rnet.c index 0a47b44f..07bc5ecc 100644 --- a/src/rnet.c +++ b/src/rnet.c @@ -10,13 +10,12 @@ * rnet.h - platform-specific network includes * * CONTRIBUTORS: -* Jak Barnes (github: @syphonx) (Feb. 2019): -* - Initial version +* Jak Barnes (github: @syphonx) (Feb. 2019) - Initial version * * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) +* Copyright (c) 2019 Jak Barnes (github: @syphonx) and Ramon Santamaria (@raysan5) * * 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. @@ -245,7 +244,7 @@ static bool IsSocketValid(Socket *sock) // Sets the error code that can be retrieved through the WSAGetLastError function. static void SocketSetLastError(int err) { -#if PLATFORM == PLATFORM_WINDOWS +#if defined(_WIN32) WSASetLastError(err); #else errno = err; @@ -255,7 +254,7 @@ static void SocketSetLastError(int err) // Returns the error status for the last Sockets operation that failed static int SocketGetLastError() { -#if PLATFORM == PLATFORM_WINDOWS +#if defined(_WIN32) return WSAGetLastError(); #else return errno; @@ -271,7 +270,7 @@ static char *SocketGetLastErrorString() // Returns a human-readable string representing the error message (err) static char *SocketErrorCodeToString(int err) { -#if PLATFORM == PLATFORM_WINDOWS +#if defined(_WIN32) static char gaiStrErrorBuffer[GAI_STRERROR_BUFFER_SIZE]; sprintf(gaiStrErrorBuffer, "%ws", gai_strerror(err)); return gaiStrErrorBuffer; @@ -496,7 +495,7 @@ static bool CreateSocket(SocketConfig *config, SocketResult *outresult) static bool SocketSetBlocking(Socket *sock) { bool ret = true; -#if PLATFORM == PLATFORM_WINDOWS +#if defined(_WIN32) unsigned long mode = 0; ret = ioctlsocket(sock->channel, FIONBIO, &mode); #else @@ -516,7 +515,7 @@ static bool SocketSetBlocking(Socket *sock) static bool SocketSetNonBlocking(Socket *sock) { bool ret = true; -#if PLATFORM == PLATFORM_WINDOWS +#if defined(_WIN32) unsigned long mode = 1; ret = ioctlsocket(sock->channel, FIONBIO, &mode); #else @@ -602,7 +601,7 @@ static void SocketSetHints(SocketConfig *config, struct addrinfo *hints) // Initialise the network (requires for windows platforms only) bool InitNetwork() { -#if PLATFORM == PLATFORM_WINDOWS +#if defined(_WIN32) WORD wVersionRequested; WSADATA wsaData; int err; @@ -635,7 +634,7 @@ bool InitNetwork() // Cleanup, and close the network void CloseNetwork() { -#if PLATFORM == PLATFORM_WINDOWS +#if defined(_WIN32) WSACleanup(); #endif } @@ -1592,7 +1591,7 @@ bool IsSocketReady(Socket *sock) // Check if the socket is considered connected bool IsSocketConnected(Socket *sock) { -#if PLATFORM_WINDOWS +#if defined(_WIN32) FD_SET writefds; FD_ZERO(&writefds); FD_SET(sock->channel, &writefds); diff --git a/src/rnet.h b/src/rnet.h index c2a14015..a2233a3c 100644 --- a/src/rnet.h +++ b/src/rnet.h @@ -14,12 +14,12 @@ * * * CONTRIBUTORS: -* Jak Barnes (github: @syphonx) (Feb. 2019): -* - Initial version +* Jak Barnes (github: @syphonx) (Feb. 2019) - Initial version +* * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) +* Copyright (c) 2019 Jak Barnes (github: @syphonx) and Ramon Santamaria (@raysan5) * * 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. @@ -38,16 +38,14 @@ * **********************************************************************************************/ -//---------------------------------------------------------------------------------- -// Platform type sizes -//---------------------------------------------------------------------------------- - -#include +#include // Required for limits +#include // Required for platform type sizes //---------------------------------------------------------------------------------- -// Undefine any conflicting windows.h symbols +// Defines and Macros //---------------------------------------------------------------------------------- +// Undefine any conflicting windows.h symbols // If defined, the following flags inhibit definition of the indicated items. #define NOGDICAPMASKS // CC_*, LC_*, PC_*, CP_*, TC_*, RC_ #define NOVIRTUALKEYCODES // VK_* @@ -90,19 +88,6 @@ #define NOMCX // Modem Configuration Extensions #define MMNOSOUND -//---------------------------------------------------------------------------------- -// Platform defines -//---------------------------------------------------------------------------------- - -#define PLATFORM_WINDOWS 1 -#define PLATFORM_LINUX 2 - -#if defined(__WIN32__) || defined(WIN32) -# define PLATFORM PLATFORM_WINDOWS -#elif defined(_LINUX) -# define PLATFORM PLATFORM_LINUX -#endif - //---------------------------------------------------------------------------------- // Platform type definitions // From: https://github.com/DFHack/clsocket/blob/master/src/Host.h @@ -137,7 +122,7 @@ typedef int socklen_t; // Include system network headers -#ifdef _WIN32 +#if defined(_WIN32) # pragma comment(lib, "ws2_32.lib") # define __USE_W32_SOCKETS # define WIN32_LEAN_AND_MEAN @@ -225,4 +210,194 @@ typedef int socklen_t; #define NAME_INFO_NUMERICHOST (0x02) // Return numeric form of the host's address #define NAME_INFO_NAMEREQD (0x04) // Error if the host's name not in DNS #define NAME_INFO_NUMERICSERV (0x08) // Return numeric form of the service (port #) -#define NAME_INFO_DGRAM (0x10) // Service is a datagram service \ No newline at end of file +#define NAME_INFO_DGRAM (0x10) // Service is a datagram service + +//---------------------------------------------------------------------------------- +// Types and Structures Definition +//---------------------------------------------------------------------------------- + +// Network typedefs +typedef uint32_t SocketChannel; +typedef struct _AddressInformation * AddressInformation; +typedef struct _SocketAddress * SocketAddress; +typedef struct _SocketAddressIPv4 * SocketAddressIPv4; +typedef struct _SocketAddressIPv6 * SocketAddressIPv6; +typedef struct _SocketAddressStorage *SocketAddressStorage; + +// IPAddress definition (in network byte order) +typedef struct IPAddress +{ + unsigned long host; /* 32-bit IPv4 host address */ + unsigned short port; /* 16-bit protocol port */ +} IPAddress; + +// An option ID, value, sizeof(value) tuple for setsockopt(2). +typedef struct SocketOpt +{ + int id; + void *value; + int valueLen; +} SocketOpt; + +typedef enum +{ + SOCKET_TCP = 0, // SOCK_STREAM + SOCKET_UDP = 1 // SOCK_DGRAM +} SocketType; + +typedef struct UDPChannel +{ + int numbound; // The total number of addresses this channel is bound to + IPAddress address[SOCKET_MAX_UDPADDRESSES]; // The list of remote addresses this channel is bound to +} UDPChannel; + +typedef struct Socket +{ + int ready; // Is the socket ready? i.e. has information + int status; // The last status code to have occured using this socket + bool isServer; // Is this socket a server socket (i.e. TCP/UDP Listen Server) + SocketChannel channel; // The socket handle id + SocketType type; // Is this socket a TCP or UDP socket? + bool isIPv6; // Is this socket address an ipv6 address? + SocketAddressIPv4 addripv4; // The host/target IPv4 for this socket (in network byte order) + SocketAddressIPv6 addripv6; // The host/target IPv6 for this socket (in network byte order) + + struct UDPChannel binding[SOCKET_MAX_UDPCHANNELS]; // The amount of channels (if UDP) this socket is bound to +} Socket; + +typedef struct SocketSet +{ + int numsockets; + int maxsockets; + struct Socket **sockets; +} SocketSet; + +typedef struct SocketDataPacket +{ + int channel; // The src/dst channel of the packet + unsigned char *data; // The packet data + int len; // The length of the packet data + int maxlen; // The size of the data buffer + int status; // packet status after sending + IPAddress address; // The source/dest address of an incoming/outgoing packet +} SocketDataPacket; + +// Configuration for a socket. +typedef struct SocketConfig +{ + char * host; // The host address in xxx.xxx.xxx.xxx form + char * port; // The target port/service in the form "http" or "25565" + bool server; // Listen for incoming clients? + SocketType type; // The type of socket, TCP/UDP + bool nonblocking; // non-blocking operation? + int backlog_size; // set a custom backlog size + SocketOpt sockopts[SOCKET_MAX_SOCK_OPTS]; +} SocketConfig; + +// Result from calling open with a given config. +typedef struct SocketResult +{ + int status; + Socket *socket; +} SocketResult; + +// +typedef struct Packet +{ + uint32_t size; // The total size of bytes in data + uint32_t offs; // The offset to data access + uint32_t maxs; // The max size of data + uint8_t *data; // Data stored in network byte order +} Packet; + + +#ifdef __cplusplus +extern "C" { // Prevents name mangling of functions +#endif + +//---------------------------------------------------------------------------------- +// Global Variables Definition +//---------------------------------------------------------------------------------- +//... + +//---------------------------------------------------------------------------------- +// Module Functions Declaration +//---------------------------------------------------------------------------------- + +// Initialisation and cleanup +RLAPI bool InitNetwork(void); +RLAPI void CloseNetwork(void); + +// Address API +RLAPI void ResolveIP(const char *ip, const char *service, int flags, char *outhost, char *outserv); +RLAPI int ResolveHost(const char *address, const char *service, int addressType, int flags, AddressInformation *outAddr); +RLAPI int GetAddressFamily(AddressInformation address); +RLAPI int GetAddressSocketType(AddressInformation address); +RLAPI int GetAddressProtocol(AddressInformation address); +RLAPI char* GetAddressCanonName(AddressInformation address); +RLAPI char* GetAddressHostAndPort(AddressInformation address, char *outhost, int *outport); +RLAPI void PrintAddressInfo(AddressInformation address); + +// Address Memory API +RLAPI AddressInformation AllocAddress(); +RLAPI void FreeAddress(AddressInformation *addressInfo); +RLAPI AddressInformation *AllocAddressList(int size); + +// Socket API +RLAPI bool SocketCreate(SocketConfig *config, SocketResult *result); +RLAPI bool SocketBind(SocketConfig *config, SocketResult *result); +RLAPI bool SocketListen(SocketConfig *config, SocketResult *result); +RLAPI bool SocketConnect(SocketConfig *config, SocketResult *result); +RLAPI Socket *SocketAccept(Socket *server, SocketConfig *config); + +// UDP Socket API +RLAPI int SocketSetChannel(Socket *socket, int channel, const IPAddress *address); +RLAPI void SocketUnsetChannel(Socket *socket, int channel); + +// UDP DataPacket API +RLAPI SocketDataPacket *AllocPacket(int size); +RLAPI int ResizePacket(SocketDataPacket *packet, int newsize); +RLAPI void FreePacket(SocketDataPacket *packet); +RLAPI SocketDataPacket **AllocPacketList(int count, int size); +RLAPI void FreePacketList(SocketDataPacket **packets); + +// General Socket API +RLAPI int SocketSend(Socket *sock, const void *datap, int len); +RLAPI int SocketReceive(Socket *sock, void *data, int maxlen); +RLAPI void SocketClose(Socket *sock); +RLAPI SocketAddressStorage SocketGetPeerAddress(Socket *sock); +RLAPI char* GetSocketAddressHost(SocketAddressStorage storage); +RLAPI short GetSocketAddressPort(SocketAddressStorage storage); + +// Socket Memory API +RLAPI Socket *AllocSocket(); +RLAPI void FreeSocket(Socket **sock); +RLAPI SocketResult *AllocSocketResult(); +RLAPI void FreeSocketResult(SocketResult **result); +RLAPI SocketSet *AllocSocketSet(int max); +RLAPI void FreeSocketSet(SocketSet *sockset); + +// Socket I/O API +RLAPI bool IsSocketReady(Socket *sock); +RLAPI bool IsSocketConnected(Socket *sock); +RLAPI int AddSocket(SocketSet *set, Socket *sock); +RLAPI int RemoveSocket(SocketSet *set, Socket *sock); +RLAPI int CheckSockets(SocketSet *set, unsigned int timeout); + +// Packet API +void PacketSend(Packet *packet); +void PacketReceive(Packet *packet); +void PacketWrite8(Packet *packet, uint16_t value); +void PacketWrite16(Packet *packet, uint16_t value); +void PacketWrite32(Packet *packet, uint32_t value); +void PacketWrite64(Packet *packet, uint64_t value); +uint16_t PacketRead8(Packet *packet); +uint16_t PacketRead16(Packet *packet); +uint32_t PacketRead32(Packet *packet); +uint64_t PacketRead64(Packet *packet); + +#ifdef __cplusplus +} +#endif + +#endif // RNET_H \ No newline at end of file -- cgit v1.2.3 From c7907a203b8bdc3027fc9b01c9780acc640794cd Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 22 Apr 2019 20:32:11 +0200 Subject: Update miniaudio to v0.9.3 --- src/external/miniaudio.h | 938 +++++++++++++++++++++++++++++------------------ src/raudio.h | 7 +- 2 files changed, 592 insertions(+), 353 deletions(-) (limited to 'src') diff --git a/src/external/miniaudio.h b/src/external/miniaudio.h index c41f7a49..a5646c71 100644 --- a/src/external/miniaudio.h +++ b/src/external/miniaudio.h @@ -1,6 +1,6 @@ /* Audio playback and capture library. Choice of public domain or MIT-0. See license statements at the end of this file. -miniaudio (formerly mini_al) - v0.9 - 2019-03-06 +miniaudio (formerly mini_al) - v0.9.3 - 2019-04-19 David Reid - davidreidsoftware@gmail.com */ @@ -452,6 +452,9 @@ extern "C" { #pragma warning(push) #pragma warning(disable:4201) // nonstandard extension used: nameless struct/union #pragma warning(disable:4324) // structure was padded due to alignment specifier +#else + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wpedantic" /* For ISO C99 doesn't support unnamed structs/unions [-Wpedantic] */ #endif // Platform/backend detection. @@ -1806,13 +1809,10 @@ typedef struct ma_uint32 maxSampleRate; } ma_device_info; -typedef struct +typedef union { - union - { - ma_int64 counter; - double counterD; - }; + ma_int64 counter; + double counterD; } ma_timer; typedef struct @@ -1858,19 +1858,18 @@ typedef struct { ma_log_proc logCallback; ma_thread_priority threadPriority; + void* pUserData; struct { ma_bool32 useVerboseDeviceEnumeration; } alsa; - struct { const char* pApplicationName; const char* pServerName; ma_bool32 tryAutoSpawn; // Enables autospawning of the PulseAudio daemon if necessary. } pulse; - struct { const char* pClientName; @@ -1883,7 +1882,9 @@ typedef ma_bool32 (* ma_enum_devices_callback_proc)(ma_context* pContext, ma_dev struct ma_context { ma_backend backend; // DirectSound, ALSA, etc. - ma_context_config config; + ma_log_proc logCallback; + ma_thread_priority threadPriority; + void* pUserData; ma_mutex deviceEnumLock; // Used to make ma_context_get_devices() thread safe. ma_mutex deviceInfoLock; // Used to make ma_context_get_device_info() thread safe. ma_uint32 deviceInfoCapacity; // Total capacity of pDeviceInfos. @@ -1897,7 +1898,7 @@ struct ma_context ma_result (* onEnumDevices )(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData); // Return false from the callback to stop enumeration. ma_result (* onGetDeviceInfo )(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_share_mode shareMode, ma_device_info* pDeviceInfo); ma_result (* onDeviceInit )(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice); - void (* onDeviceUninit )(ma_device* pDevice); + void (* onDeviceUninit )(ma_device* pDevice); ma_result (* onDeviceStart )(ma_device* pDevice); ma_result (* onDeviceStop )(ma_device* pDevice); ma_result (* onDeviceWrite )(ma_device* pDevice, const void* pPCMFrames, ma_uint32 frameCount); /* Data is in internal device format. */ @@ -2006,6 +2007,7 @@ struct ma_context ma_proc snd_config_update_free_global; ma_mutex internalDeviceEnumLock; + ma_bool32 useVerboseDeviceEnumeration; } alsa; #endif #ifdef MA_SUPPORT_PULSEAUDIO @@ -2056,6 +2058,10 @@ struct ma_context ma_proc pa_stream_drop; ma_proc pa_stream_writable_size; ma_proc pa_stream_readable_size; + + char* pApplicationName; + char* pServerName; + ma_bool32 tryAutoSpawn; } pulse; #endif #ifdef MA_SUPPORT_JACK @@ -2078,6 +2084,9 @@ struct ma_context ma_proc jack_port_name; ma_proc jack_port_get_buffer; ma_proc jack_free; + + char* pClientName; + ma_bool32 tryStartServer; } jack; #endif #ifdef MA_SUPPORT_COREAUDIO @@ -2494,6 +2503,8 @@ MA_ALIGNED_STRUCT(MA_SIMD_ALIGNMENT) ma_device }; #if defined(_MSC_VER) #pragma warning(pop) +#else + #pragma GCC diagnostic pop /* For ISO C99 doesn't support unnamed structs/unions [-Wpedantic] */ #endif // Initializes a context. @@ -2958,7 +2969,6 @@ ma_result ma_sine_wave_init(double amplitude, double period, ma_uint32 sampleRat ma_uint64 ma_sine_wave_read_f32(ma_sine_wave* pSineWave, ma_uint64 count, float* pSamples); ma_uint64 ma_sine_wave_read_f32_ex(ma_sine_wave* pSineWave, ma_uint64 frameCount, ma_uint32 channels, ma_stream_layout layout, float** ppFrames); - #ifdef __cplusplus } #endif @@ -3068,6 +3078,8 @@ typedef struct tagBITMAPINFOHEADER { #endif #ifdef MA_POSIX +#include +#include #include #include #endif @@ -3774,6 +3786,19 @@ int ma_strcmp(const char* str1, const char* str2) return ((unsigned char*)str1)[0] - ((unsigned char*)str2)[0]; } +char* ma_copy_string(const char* src) +{ + size_t sz = strlen(src)+1; + char* dst = (char*)ma_malloc(sz); + if (dst == NULL) { + return NULL; + } + + ma_strcpy_s(dst, sz, src); + + return dst; +} + // Thanks to good old Bit Twiddling Hacks for this one: http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 static MA_INLINE unsigned int ma_next_power_of_2(unsigned int x) @@ -4268,6 +4293,7 @@ double ma_timer_get_time_in_seconds(ma_timer* pTimer) return (emscripten_get_now() - pTimer->counterD) / 1000; /* Emscripten is in milliseconds. */ } #else +#if _POSIX_C_SOURCE >= 199309L #if defined(CLOCK_MONOTONIC) #define MA_CLOCK_ID CLOCK_MONOTONIC #else @@ -4292,6 +4318,26 @@ double ma_timer_get_time_in_seconds(ma_timer* pTimer) return (newTimeCounter - oldTimeCounter) / 1000000000.0; } +#else +void ma_timer_init(ma_timer* pTimer) +{ + struct timeval newTime; + gettimeofday(&newTime, NULL); + + pTimer->counter = (newTime.tv_sec * 1000000) + newTime.tv_usec; +} + +double ma_timer_get_time_in_seconds(ma_timer* pTimer) +{ + struct timeval newTime; + gettimeofday(&newTime, NULL); + + ma_uint64 newTimeCounter = (newTime.tv_sec * 1000000) + newTime.tv_usec; + ma_uint64 oldTimeCounter = pTimer->counter; + + return (newTimeCounter - oldTimeCounter) / 1000000.0; +} +#endif #endif @@ -4333,7 +4379,14 @@ ma_proc ma_dlsym(ma_handle handle, const char* symbol) #ifdef _WIN32 return (ma_proc)GetProcAddress((HMODULE)handle, symbol); #else +#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wpedantic" +#endif return (ma_proc)dlsym((void*)handle, symbol); +#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) + #pragma GCC diagnostic pop +#endif #endif } @@ -4365,7 +4418,7 @@ ma_result ma_thread_create__win32(ma_context* pContext, ma_thread* pThread, ma_t return MA_FAILED_TO_CREATE_THREAD; } - SetThreadPriority((HANDLE)pThread->win32.hThread, ma_thread_priority_to_win32(pContext->config.threadPriority)); + SetThreadPriority((HANDLE)pThread->win32.hThread, ma_thread_priority_to_win32(pContext->threadPriority)); return MA_SUCCESS; } @@ -4466,13 +4519,13 @@ ma_bool32 ma_thread_create__posix(ma_context* pContext, ma_thread* pThread, ma_t pthread_attr_t attr; if (((ma_pthread_attr_init_proc)pContext->posix.pthread_attr_init)(&attr) == 0) { int scheduler = -1; - if (pContext->config.threadPriority == ma_thread_priority_idle) { + if (pContext->threadPriority == ma_thread_priority_idle) { #ifdef SCHED_IDLE if (((ma_pthread_attr_setschedpolicy_proc)pContext->posix.pthread_attr_setschedpolicy)(&attr, SCHED_IDLE) == 0) { scheduler = SCHED_IDLE; } #endif - } else if (pContext->config.threadPriority == ma_thread_priority_realtime) { + } else if (pContext->threadPriority == ma_thread_priority_realtime) { #ifdef SCHED_FIFO if (((ma_pthread_attr_setschedpolicy_proc)pContext->posix.pthread_attr_setschedpolicy)(&attr, SCHED_FIFO) == 0) { scheduler = SCHED_FIFO; @@ -4491,12 +4544,12 @@ ma_bool32 ma_thread_create__posix(ma_context* pContext, ma_thread* pThread, ma_t struct sched_param sched; if (((ma_pthread_attr_getschedparam_proc)pContext->posix.pthread_attr_getschedparam)(&attr, &sched) == 0) { - if (pContext->config.threadPriority == ma_thread_priority_idle) { + if (pContext->threadPriority == ma_thread_priority_idle) { sched.sched_priority = priorityMin; - } else if (pContext->config.threadPriority == ma_thread_priority_realtime) { + } else if (pContext->threadPriority == ma_thread_priority_realtime) { sched.sched_priority = priorityMax; } else { - sched.sched_priority += ((int)pContext->config.threadPriority + 5) * priorityStep; // +5 because the lowest priority is -5. + sched.sched_priority += ((int)pContext->threadPriority + 5) * priorityStep; // +5 because the lowest priority is -5. if (sched.sched_priority < priorityMin) { sched.sched_priority = priorityMin; } @@ -4534,7 +4587,17 @@ void ma_sleep__posix(ma_uint32 milliseconds) (void)milliseconds; ma_assert(MA_FALSE); /* The Emscripten build should never sleep. */ #else - usleep(milliseconds * 1000); /* <-- usleep is in microseconds. */ + #if _POSIX_C_SOURCE >= 199309L + struct timespec ts; + ts.tv_sec = milliseconds / 1000000; + ts.tv_nsec = milliseconds % 1000000 * 1000000; + nanosleep(&ts, NULL); + #else + struct timeval tv; + tv.tv_sec = milliseconds / 1000; + tv.tv_usec = milliseconds % 1000 * 1000; + select(0, NULL, NULL, NULL, &tv); + #endif #endif } @@ -4887,7 +4950,7 @@ void ma_log(ma_context* pContext, ma_device* pDevice, ma_uint32 logLevel, const } #endif - ma_log_proc onLog = pContext->config.logCallback; + ma_log_proc onLog = pContext->logCallback; if (onLog) { onLog(pContext, pDevice, logLevel, message); } @@ -4989,7 +5052,15 @@ static MA_INLINE void ma_device__read_frames_from_client(ma_device* pDevice, ma_ ma_assert(frameCount > 0); ma_assert(pSamples != NULL); - ma_pcm_converter_read(&pDevice->playback.converter, pSamples, frameCount); + ma_device_callback_proc onData = pDevice->onData; + if (onData) { + if (pDevice->playback.converter.isPassthrough) { + ma_zero_pcm_frames(pSamples, frameCount, pDevice->playback.format, pDevice->playback.channels); + onData(pDevice, pSamples, NULL, frameCount); + } else { + ma_pcm_converter_read(&pDevice->playback.converter, pSamples, frameCount); + } + } } // A helper for sending sample data to the client. @@ -5001,22 +5072,26 @@ static MA_INLINE void ma_device__send_frames_to_client(ma_device* pDevice, ma_ui ma_device_callback_proc onData = pDevice->onData; if (onData) { - pDevice->capture._dspFrameCount = frameCount; - pDevice->capture._dspFrames = (const ma_uint8*)pSamples; + if (pDevice->capture.converter.isPassthrough) { + onData(pDevice, NULL, pSamples, frameCount); + } else { + pDevice->capture._dspFrameCount = frameCount; + pDevice->capture._dspFrames = (const ma_uint8*)pSamples; - ma_uint8 chunkBuffer[4096]; - ma_uint32 chunkFrameCount = sizeof(chunkBuffer) / ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels); + ma_uint8 chunkBuffer[4096]; + ma_uint32 chunkFrameCount = sizeof(chunkBuffer) / ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels); - for (;;) { - ma_uint32 framesJustRead = (ma_uint32)ma_pcm_converter_read(&pDevice->capture.converter, chunkBuffer, chunkFrameCount); - if (framesJustRead == 0) { - break; - } + for (;;) { + ma_uint32 framesJustRead = (ma_uint32)ma_pcm_converter_read(&pDevice->capture.converter, chunkBuffer, chunkFrameCount); + if (framesJustRead == 0) { + break; + } - onData(pDevice, NULL, chunkBuffer, framesJustRead); + onData(pDevice, NULL, chunkBuffer, framesJustRead); - if (framesJustRead < chunkFrameCount) { - break; + if (framesJustRead < chunkFrameCount) { + break; + } } } } @@ -5652,10 +5727,12 @@ ma_result ma_context_uninit__null(ma_context* pContext) return MA_SUCCESS; } -ma_result ma_context_init__null(ma_context* pContext) +ma_result ma_context_init__null(const ma_context_config* pConfig, ma_context* pContext) { ma_assert(pContext != NULL); + (void)pConfig; + pContext->onUninit = ma_context_uninit__null; pContext->onDeviceIDEqual = ma_context_is_device_id_equal__null; pContext->onEnumDevices = ma_context_enumerate_devices__null; @@ -8232,12 +8309,8 @@ ma_result ma_device_main_loop__wasapi(ma_device* pDevice) break; } - /* We should have a buffer at this point. If we are running a passthrough pipeline we can send it straight to the callback. Otherwise we need to convert. */ - if (pDevice->capture.converter.isPassthrough) { - pDevice->onData(pDevice, NULL, pMappedBufferCapture, mappedBufferSizeInFramesCapture); - } else { - ma_device__send_frames_to_client(pDevice, mappedBufferSizeInFramesCapture, pMappedBufferCapture); - } + /* We should have a buffer at this point. */ + ma_device__send_frames_to_client(pDevice, mappedBufferSizeInFramesCapture, pMappedBufferCapture); /* At this point we're done with the buffer. */ hr = ma_IAudioCaptureClient_ReleaseBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, mappedBufferSizeInFramesCapture); @@ -8281,11 +8354,8 @@ ma_result ma_device_main_loop__wasapi(ma_device* pDevice) break; } - if (pDevice->playback.converter.isPassthrough) { - pDevice->onData(pDevice, pMappedBufferPlayback, NULL, framesAvailablePlayback); - } else { - ma_device__read_frames_from_client(pDevice, framesAvailablePlayback, pMappedBufferPlayback); - } + /* We should have a buffer at this point. */ + ma_device__read_frames_from_client(pDevice, framesAvailablePlayback, pMappedBufferPlayback); /* At this point we're done writing to the device and we just need to release the buffer. */ hr = ma_IAudioRenderClient_ReleaseBuffer((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient, framesAvailablePlayback, 0); @@ -8404,10 +8474,12 @@ ma_result ma_context_uninit__wasapi(ma_context* pContext) return MA_SUCCESS; } -ma_result ma_context_init__wasapi(ma_context* pContext) +ma_result ma_context_init__wasapi(const ma_context_config* pConfig, ma_context* pContext) { ma_assert(pContext != NULL); + (void)pContext; + (void)pConfig; ma_result result = MA_SUCCESS; @@ -9848,14 +9920,7 @@ ma_result ma_device_main_loop__dsound(ma_device* pDevice) } #endif - /* Optimization: If we are running as a passthrough we can pass the mapped pointer to the callback directly. */ - if (pDevice->capture.converter.isPassthrough) { - /* Passthrough. */ - pDevice->onData(pDevice, NULL, pMappedBufferCapture, mappedSizeInBytesCapture/bpfCapture); - } else { - /* Not a passthrough. */ - ma_device__send_frames_to_client(pDevice, mappedSizeInBytesCapture/bpfCapture, pMappedBufferCapture); - } + ma_device__send_frames_to_client(pDevice, mappedSizeInBytesCapture/bpfCapture, pMappedBufferCapture); hr = ma_IDirectSoundCaptureBuffer_Unlock((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, pMappedBufferCapture, mappedSizeInBytesCapture, NULL, 0); if (FAILED(hr)) { @@ -9944,17 +10009,8 @@ ma_result ma_device_main_loop__dsound(ma_device* pDevice) break; } - /* - At this point we have a buffer for output. If we don't need to do any data conversion we can pass the mapped pointer to the buffer directly. Otherwise - we need to convert the data. - */ - if (pDevice->playback.converter.isPassthrough) { - /* Passthrough. */ - pDevice->onData(pDevice, pMappedBufferPlayback, NULL, (mappedSizeInBytesPlayback/bpfPlayback)); - } else { - /* Conversion. */ - ma_device__read_frames_from_client(pDevice, (mappedSizeInBytesPlayback/bpfPlayback), pMappedBufferPlayback); - } + /* At this point we have a buffer for output. */ + ma_device__read_frames_from_client(pDevice, (mappedSizeInBytesPlayback/bpfPlayback), pMappedBufferPlayback); hr = ma_IDirectSoundBuffer_Unlock((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, pMappedBufferPlayback, mappedSizeInBytesPlayback, NULL, 0); if (FAILED(hr)) { @@ -10058,10 +10114,12 @@ ma_result ma_context_uninit__dsound(ma_context* pContext) return MA_SUCCESS; } -ma_result ma_context_init__dsound(ma_context* pContext) +ma_result ma_context_init__dsound(const ma_context_config* pConfig, ma_context* pContext) { ma_assert(pContext != NULL); + (void)pConfig; + pContext->dsound.hDSoundDLL = ma_dlopen("dsound.dll"); if (pContext->dsound.hDSoundDLL == NULL) { return MA_API_NOT_FOUND; @@ -11021,10 +11079,12 @@ ma_result ma_context_uninit__winmm(ma_context* pContext) return MA_SUCCESS; } -ma_result ma_context_init__winmm(ma_context* pContext) +ma_result ma_context_init__winmm(const ma_context_config* pConfig, ma_context* pContext) { ma_assert(pContext != NULL); + (void)pConfig; + pContext->winmm.hWinMM = ma_dlopen("winmm.dll"); if (pContext->winmm.hWinMM == NULL) { return MA_NO_BACKEND; @@ -11048,16 +11108,16 @@ ma_result ma_context_init__winmm(ma_context* pContext) pContext->winmm.waveInStart = ma_dlsym(pContext->winmm.hWinMM, "waveInStart"); pContext->winmm.waveInReset = ma_dlsym(pContext->winmm.hWinMM, "waveInReset"); - pContext->onUninit = ma_context_uninit__winmm; - pContext->onDeviceIDEqual = ma_context_is_device_id_equal__winmm; - pContext->onEnumDevices = ma_context_enumerate_devices__winmm; - pContext->onGetDeviceInfo = ma_context_get_device_info__winmm; - pContext->onDeviceInit = ma_device_init__winmm; - pContext->onDeviceUninit = ma_device_uninit__winmm; - pContext->onDeviceStart = NULL; /* Not used. Started in onDeviceWrite/onDeviceRead. */ - pContext->onDeviceStop = ma_device_stop__winmm; - pContext->onDeviceWrite = ma_device_write__winmm; - pContext->onDeviceRead = ma_device_read__winmm; + pContext->onUninit = ma_context_uninit__winmm; + pContext->onDeviceIDEqual = ma_context_is_device_id_equal__winmm; + pContext->onEnumDevices = ma_context_enumerate_devices__winmm; + pContext->onGetDeviceInfo = ma_context_get_device_info__winmm; + pContext->onDeviceInit = ma_device_init__winmm; + pContext->onDeviceUninit = ma_device_uninit__winmm; + pContext->onDeviceStart = NULL; /* Not used. Started in onDeviceWrite/onDeviceRead. */ + pContext->onDeviceStop = ma_device_stop__winmm; + pContext->onDeviceWrite = ma_device_write__winmm; + pContext->onDeviceRead = ma_device_read__winmm; return MA_SUCCESS; } @@ -11089,77 +11149,77 @@ typedef snd_pcm_channel_area_t ma_snd_pcm_channel_area_t; typedef snd_pcm_chmap_t ma_snd_pcm_chmap_t; // snd_pcm_stream_t -#define MA_SND_PCM_STREAM_PLAYBACK SND_PCM_STREAM_PLAYBACK -#define MA_SND_PCM_STREAM_CAPTURE SND_PCM_STREAM_CAPTURE +#define MA_SND_PCM_STREAM_PLAYBACK SND_PCM_STREAM_PLAYBACK +#define MA_SND_PCM_STREAM_CAPTURE SND_PCM_STREAM_CAPTURE // snd_pcm_format_t -#define MA_SND_PCM_FORMAT_UNKNOWN SND_PCM_FORMAT_UNKNOWN -#define MA_SND_PCM_FORMAT_U8 SND_PCM_FORMAT_U8 -#define MA_SND_PCM_FORMAT_S16_LE SND_PCM_FORMAT_S16_LE -#define MA_SND_PCM_FORMAT_S16_BE SND_PCM_FORMAT_S16_BE -#define MA_SND_PCM_FORMAT_S24_LE SND_PCM_FORMAT_S24_LE -#define MA_SND_PCM_FORMAT_S24_BE SND_PCM_FORMAT_S24_BE -#define MA_SND_PCM_FORMAT_S32_LE SND_PCM_FORMAT_S32_LE -#define MA_SND_PCM_FORMAT_S32_BE SND_PCM_FORMAT_S32_BE -#define MA_SND_PCM_FORMAT_FLOAT_LE SND_PCM_FORMAT_FLOAT_LE -#define MA_SND_PCM_FORMAT_FLOAT_BE SND_PCM_FORMAT_FLOAT_BE -#define MA_SND_PCM_FORMAT_FLOAT64_LE SND_PCM_FORMAT_FLOAT64_LE -#define MA_SND_PCM_FORMAT_FLOAT64_BE SND_PCM_FORMAT_FLOAT64_BE -#define MA_SND_PCM_FORMAT_MU_LAW SND_PCM_FORMAT_MU_LAW -#define MA_SND_PCM_FORMAT_A_LAW SND_PCM_FORMAT_A_LAW -#define MA_SND_PCM_FORMAT_S24_3LE SND_PCM_FORMAT_S24_3LE -#define MA_SND_PCM_FORMAT_S24_3BE SND_PCM_FORMAT_S24_3BE +#define MA_SND_PCM_FORMAT_UNKNOWN SND_PCM_FORMAT_UNKNOWN +#define MA_SND_PCM_FORMAT_U8 SND_PCM_FORMAT_U8 +#define MA_SND_PCM_FORMAT_S16_LE SND_PCM_FORMAT_S16_LE +#define MA_SND_PCM_FORMAT_S16_BE SND_PCM_FORMAT_S16_BE +#define MA_SND_PCM_FORMAT_S24_LE SND_PCM_FORMAT_S24_LE +#define MA_SND_PCM_FORMAT_S24_BE SND_PCM_FORMAT_S24_BE +#define MA_SND_PCM_FORMAT_S32_LE SND_PCM_FORMAT_S32_LE +#define MA_SND_PCM_FORMAT_S32_BE SND_PCM_FORMAT_S32_BE +#define MA_SND_PCM_FORMAT_FLOAT_LE SND_PCM_FORMAT_FLOAT_LE +#define MA_SND_PCM_FORMAT_FLOAT_BE SND_PCM_FORMAT_FLOAT_BE +#define MA_SND_PCM_FORMAT_FLOAT64_LE SND_PCM_FORMAT_FLOAT64_LE +#define MA_SND_PCM_FORMAT_FLOAT64_BE SND_PCM_FORMAT_FLOAT64_BE +#define MA_SND_PCM_FORMAT_MU_LAW SND_PCM_FORMAT_MU_LAW +#define MA_SND_PCM_FORMAT_A_LAW SND_PCM_FORMAT_A_LAW +#define MA_SND_PCM_FORMAT_S24_3LE SND_PCM_FORMAT_S24_3LE +#define MA_SND_PCM_FORMAT_S24_3BE SND_PCM_FORMAT_S24_3BE // ma_snd_pcm_access_t -#define MA_SND_PCM_ACCESS_MMAP_INTERLEAVED SND_PCM_ACCESS_MMAP_INTERLEAVED -#define MA_SND_PCM_ACCESS_MMAP_NONINTERLEAVED SND_PCM_ACCESS_MMAP_NONINTERLEAVED -#define MA_SND_PCM_ACCESS_MMAP_COMPLEX SND_PCM_ACCESS_MMAP_COMPLEX -#define MA_SND_PCM_ACCESS_RW_INTERLEAVED SND_PCM_ACCESS_RW_INTERLEAVED -#define MA_SND_PCM_ACCESS_RW_NONINTERLEAVED SND_PCM_ACCESS_RW_NONINTERLEAVED +#define MA_SND_PCM_ACCESS_MMAP_INTERLEAVED SND_PCM_ACCESS_MMAP_INTERLEAVED +#define MA_SND_PCM_ACCESS_MMAP_NONINTERLEAVED SND_PCM_ACCESS_MMAP_NONINTERLEAVED +#define MA_SND_PCM_ACCESS_MMAP_COMPLEX SND_PCM_ACCESS_MMAP_COMPLEX +#define MA_SND_PCM_ACCESS_RW_INTERLEAVED SND_PCM_ACCESS_RW_INTERLEAVED +#define MA_SND_PCM_ACCESS_RW_NONINTERLEAVED SND_PCM_ACCESS_RW_NONINTERLEAVED // Channel positions. -#define MA_SND_CHMAP_UNKNOWN SND_CHMAP_UNKNOWN -#define MA_SND_CHMAP_NA SND_CHMAP_NA -#define MA_SND_CHMAP_MONO SND_CHMAP_MONO -#define MA_SND_CHMAP_FL SND_CHMAP_FL -#define MA_SND_CHMAP_FR SND_CHMAP_FR -#define MA_SND_CHMAP_RL SND_CHMAP_RL -#define MA_SND_CHMAP_RR SND_CHMAP_RR -#define MA_SND_CHMAP_FC SND_CHMAP_FC -#define MA_SND_CHMAP_LFE SND_CHMAP_LFE -#define MA_SND_CHMAP_SL SND_CHMAP_SL -#define MA_SND_CHMAP_SR SND_CHMAP_SR -#define MA_SND_CHMAP_RC SND_CHMAP_RC -#define MA_SND_CHMAP_FLC SND_CHMAP_FLC -#define MA_SND_CHMAP_FRC SND_CHMAP_FRC -#define MA_SND_CHMAP_RLC SND_CHMAP_RLC -#define MA_SND_CHMAP_RRC SND_CHMAP_RRC -#define MA_SND_CHMAP_FLW SND_CHMAP_FLW -#define MA_SND_CHMAP_FRW SND_CHMAP_FRW -#define MA_SND_CHMAP_FLH SND_CHMAP_FLH -#define MA_SND_CHMAP_FCH SND_CHMAP_FCH -#define MA_SND_CHMAP_FRH SND_CHMAP_FRH -#define MA_SND_CHMAP_TC SND_CHMAP_TC -#define MA_SND_CHMAP_TFL SND_CHMAP_TFL -#define MA_SND_CHMAP_TFR SND_CHMAP_TFR -#define MA_SND_CHMAP_TFC SND_CHMAP_TFC -#define MA_SND_CHMAP_TRL SND_CHMAP_TRL -#define MA_SND_CHMAP_TRR SND_CHMAP_TRR -#define MA_SND_CHMAP_TRC SND_CHMAP_TRC -#define MA_SND_CHMAP_TFLC SND_CHMAP_TFLC -#define MA_SND_CHMAP_TFRC SND_CHMAP_TFRC -#define MA_SND_CHMAP_TSL SND_CHMAP_TSL -#define MA_SND_CHMAP_TSR SND_CHMAP_TSR -#define MA_SND_CHMAP_LLFE SND_CHMAP_LLFE -#define MA_SND_CHMAP_RLFE SND_CHMAP_RLFE -#define MA_SND_CHMAP_BC SND_CHMAP_BC -#define MA_SND_CHMAP_BLC SND_CHMAP_BLC -#define MA_SND_CHMAP_BRC SND_CHMAP_BRC +#define MA_SND_CHMAP_UNKNOWN SND_CHMAP_UNKNOWN +#define MA_SND_CHMAP_NA SND_CHMAP_NA +#define MA_SND_CHMAP_MONO SND_CHMAP_MONO +#define MA_SND_CHMAP_FL SND_CHMAP_FL +#define MA_SND_CHMAP_FR SND_CHMAP_FR +#define MA_SND_CHMAP_RL SND_CHMAP_RL +#define MA_SND_CHMAP_RR SND_CHMAP_RR +#define MA_SND_CHMAP_FC SND_CHMAP_FC +#define MA_SND_CHMAP_LFE SND_CHMAP_LFE +#define MA_SND_CHMAP_SL SND_CHMAP_SL +#define MA_SND_CHMAP_SR SND_CHMAP_SR +#define MA_SND_CHMAP_RC SND_CHMAP_RC +#define MA_SND_CHMAP_FLC SND_CHMAP_FLC +#define MA_SND_CHMAP_FRC SND_CHMAP_FRC +#define MA_SND_CHMAP_RLC SND_CHMAP_RLC +#define MA_SND_CHMAP_RRC SND_CHMAP_RRC +#define MA_SND_CHMAP_FLW SND_CHMAP_FLW +#define MA_SND_CHMAP_FRW SND_CHMAP_FRW +#define MA_SND_CHMAP_FLH SND_CHMAP_FLH +#define MA_SND_CHMAP_FCH SND_CHMAP_FCH +#define MA_SND_CHMAP_FRH SND_CHMAP_FRH +#define MA_SND_CHMAP_TC SND_CHMAP_TC +#define MA_SND_CHMAP_TFL SND_CHMAP_TFL +#define MA_SND_CHMAP_TFR SND_CHMAP_TFR +#define MA_SND_CHMAP_TFC SND_CHMAP_TFC +#define MA_SND_CHMAP_TRL SND_CHMAP_TRL +#define MA_SND_CHMAP_TRR SND_CHMAP_TRR +#define MA_SND_CHMAP_TRC SND_CHMAP_TRC +#define MA_SND_CHMAP_TFLC SND_CHMAP_TFLC +#define MA_SND_CHMAP_TFRC SND_CHMAP_TFRC +#define MA_SND_CHMAP_TSL SND_CHMAP_TSL +#define MA_SND_CHMAP_TSR SND_CHMAP_TSR +#define MA_SND_CHMAP_LLFE SND_CHMAP_LLFE +#define MA_SND_CHMAP_RLFE SND_CHMAP_RLFE +#define MA_SND_CHMAP_BC SND_CHMAP_BC +#define MA_SND_CHMAP_BLC SND_CHMAP_BLC +#define MA_SND_CHMAP_BRC SND_CHMAP_BRC // Open mode flags. -#define MA_SND_PCM_NO_AUTO_RESAMPLE SND_PCM_NO_AUTO_RESAMPLE -#define MA_SND_PCM_NO_AUTO_CHANNELS SND_PCM_NO_AUTO_CHANNELS -#define MA_SND_PCM_NO_AUTO_FORMAT SND_PCM_NO_AUTO_FORMAT +#define MA_SND_PCM_NO_AUTO_RESAMPLE SND_PCM_NO_AUTO_RESAMPLE +#define MA_SND_PCM_NO_AUTO_CHANNELS SND_PCM_NO_AUTO_CHANNELS +#define MA_SND_PCM_NO_AUTO_FORMAT SND_PCM_NO_AUTO_FORMAT #else #include // For EPIPE, etc. typedef unsigned long ma_snd_pcm_uframes_t; @@ -11167,11 +11227,11 @@ typedef long ma_snd_pcm_sframes_t; typedef int ma_snd_pcm_stream_t; typedef int ma_snd_pcm_format_t; typedef int ma_snd_pcm_access_t; -typedef struct ma_snd_pcm_t ma_snd_pcm_t; -typedef struct ma_snd_pcm_hw_params_t ma_snd_pcm_hw_params_t; -typedef struct ma_snd_pcm_sw_params_t ma_snd_pcm_sw_params_t; -typedef struct ma_snd_pcm_format_mask_t ma_snd_pcm_format_mask_t; -typedef struct ma_snd_pcm_info_t ma_snd_pcm_info_t; +typedef struct ma_snd_pcm_t ma_snd_pcm_t; +typedef struct ma_snd_pcm_hw_params_t ma_snd_pcm_hw_params_t; +typedef struct ma_snd_pcm_sw_params_t ma_snd_pcm_sw_params_t; +typedef struct ma_snd_pcm_format_mask_t ma_snd_pcm_format_mask_t; +typedef struct ma_snd_pcm_info_t ma_snd_pcm_info_t; typedef struct { void* addr; @@ -11181,7 +11241,7 @@ typedef struct typedef struct { unsigned int channels; - unsigned int pos[0]; + unsigned int pos[1]; } ma_snd_pcm_chmap_t; // snd_pcm_state_t @@ -11269,61 +11329,61 @@ typedef struct #define MA_SND_PCM_NO_AUTO_FORMAT 0x00040000 #endif -typedef int (* ma_snd_pcm_open_proc) (ma_snd_pcm_t **pcm, const char *name, ma_snd_pcm_stream_t stream, int mode); -typedef int (* ma_snd_pcm_close_proc) (ma_snd_pcm_t *pcm); -typedef size_t (* ma_snd_pcm_hw_params_sizeof_proc) (void); -typedef int (* ma_snd_pcm_hw_params_any_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params); -typedef int (* ma_snd_pcm_hw_params_set_format_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, ma_snd_pcm_format_t val); -typedef int (* ma_snd_pcm_hw_params_set_format_first_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, ma_snd_pcm_format_t *format); -typedef void (* ma_snd_pcm_hw_params_get_format_mask_proc) (ma_snd_pcm_hw_params_t *params, ma_snd_pcm_format_mask_t *mask); -typedef int (* ma_snd_pcm_hw_params_set_channels_near_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, unsigned int *val); -typedef int (* ma_snd_pcm_hw_params_set_rate_resample_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, unsigned int val); -typedef int (* ma_snd_pcm_hw_params_set_rate_near_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, unsigned int *val, int *dir); -typedef int (* ma_snd_pcm_hw_params_set_buffer_size_near_proc)(ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, ma_snd_pcm_uframes_t *val); -typedef int (* ma_snd_pcm_hw_params_set_periods_near_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, unsigned int *val, int *dir); -typedef int (* ma_snd_pcm_hw_params_set_access_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, ma_snd_pcm_access_t _access); -typedef int (* ma_snd_pcm_hw_params_get_format_proc) (const ma_snd_pcm_hw_params_t *params, ma_snd_pcm_format_t *format); -typedef int (* ma_snd_pcm_hw_params_get_channels_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *val); -typedef int (* ma_snd_pcm_hw_params_get_channels_min_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *val); -typedef int (* ma_snd_pcm_hw_params_get_channels_max_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *val); -typedef int (* ma_snd_pcm_hw_params_get_rate_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *rate, int *dir); -typedef int (* ma_snd_pcm_hw_params_get_rate_min_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *rate, int *dir); -typedef int (* ma_snd_pcm_hw_params_get_rate_max_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *rate, int *dir); -typedef int (* ma_snd_pcm_hw_params_get_buffer_size_proc) (const ma_snd_pcm_hw_params_t *params, ma_snd_pcm_uframes_t *val); -typedef int (* ma_snd_pcm_hw_params_get_periods_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *val, int *dir); -typedef int (* ma_snd_pcm_hw_params_get_access_proc) (const ma_snd_pcm_hw_params_t *params, ma_snd_pcm_access_t *_access); -typedef int (* ma_snd_pcm_hw_params_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params); -typedef size_t (* ma_snd_pcm_sw_params_sizeof_proc) (void); -typedef int (* ma_snd_pcm_sw_params_current_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_sw_params_t *params); -typedef int (* ma_snd_pcm_sw_params_get_boundary_proc) (ma_snd_pcm_sw_params_t *params, ma_snd_pcm_uframes_t* val); -typedef int (* ma_snd_pcm_sw_params_set_avail_min_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_sw_params_t *params, ma_snd_pcm_uframes_t val); -typedef int (* ma_snd_pcm_sw_params_set_start_threshold_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_sw_params_t *params, ma_snd_pcm_uframes_t val); -typedef int (* ma_snd_pcm_sw_params_set_stop_threshold_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_sw_params_t *params, ma_snd_pcm_uframes_t val); -typedef int (* ma_snd_pcm_sw_params_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_sw_params_t *params); -typedef size_t (* ma_snd_pcm_format_mask_sizeof_proc) (void); -typedef int (* ma_snd_pcm_format_mask_test_proc) (const ma_snd_pcm_format_mask_t *mask, ma_snd_pcm_format_t val); +typedef int (* ma_snd_pcm_open_proc) (ma_snd_pcm_t **pcm, const char *name, ma_snd_pcm_stream_t stream, int mode); +typedef int (* ma_snd_pcm_close_proc) (ma_snd_pcm_t *pcm); +typedef size_t (* ma_snd_pcm_hw_params_sizeof_proc) (void); +typedef int (* ma_snd_pcm_hw_params_any_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params); +typedef int (* ma_snd_pcm_hw_params_set_format_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, ma_snd_pcm_format_t val); +typedef int (* ma_snd_pcm_hw_params_set_format_first_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, ma_snd_pcm_format_t *format); +typedef void (* ma_snd_pcm_hw_params_get_format_mask_proc) (ma_snd_pcm_hw_params_t *params, ma_snd_pcm_format_mask_t *mask); +typedef int (* ma_snd_pcm_hw_params_set_channels_near_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, unsigned int *val); +typedef int (* ma_snd_pcm_hw_params_set_rate_resample_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, unsigned int val); +typedef int (* ma_snd_pcm_hw_params_set_rate_near_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, unsigned int *val, int *dir); +typedef int (* ma_snd_pcm_hw_params_set_buffer_size_near_proc)(ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, ma_snd_pcm_uframes_t *val); +typedef int (* ma_snd_pcm_hw_params_set_periods_near_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, unsigned int *val, int *dir); +typedef int (* ma_snd_pcm_hw_params_set_access_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params, ma_snd_pcm_access_t _access); +typedef int (* ma_snd_pcm_hw_params_get_format_proc) (const ma_snd_pcm_hw_params_t *params, ma_snd_pcm_format_t *format); +typedef int (* ma_snd_pcm_hw_params_get_channels_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *val); +typedef int (* ma_snd_pcm_hw_params_get_channels_min_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *val); +typedef int (* ma_snd_pcm_hw_params_get_channels_max_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *val); +typedef int (* ma_snd_pcm_hw_params_get_rate_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *rate, int *dir); +typedef int (* ma_snd_pcm_hw_params_get_rate_min_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *rate, int *dir); +typedef int (* ma_snd_pcm_hw_params_get_rate_max_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *rate, int *dir); +typedef int (* ma_snd_pcm_hw_params_get_buffer_size_proc) (const ma_snd_pcm_hw_params_t *params, ma_snd_pcm_uframes_t *val); +typedef int (* ma_snd_pcm_hw_params_get_periods_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *val, int *dir); +typedef int (* ma_snd_pcm_hw_params_get_access_proc) (const ma_snd_pcm_hw_params_t *params, ma_snd_pcm_access_t *_access); +typedef int (* ma_snd_pcm_hw_params_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params); +typedef size_t (* ma_snd_pcm_sw_params_sizeof_proc) (void); +typedef int (* ma_snd_pcm_sw_params_current_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_sw_params_t *params); +typedef int (* ma_snd_pcm_sw_params_get_boundary_proc) (ma_snd_pcm_sw_params_t *params, ma_snd_pcm_uframes_t* val); +typedef int (* ma_snd_pcm_sw_params_set_avail_min_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_sw_params_t *params, ma_snd_pcm_uframes_t val); +typedef int (* ma_snd_pcm_sw_params_set_start_threshold_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_sw_params_t *params, ma_snd_pcm_uframes_t val); +typedef int (* ma_snd_pcm_sw_params_set_stop_threshold_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_sw_params_t *params, ma_snd_pcm_uframes_t val); +typedef int (* ma_snd_pcm_sw_params_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_sw_params_t *params); +typedef size_t (* ma_snd_pcm_format_mask_sizeof_proc) (void); +typedef int (* ma_snd_pcm_format_mask_test_proc) (const ma_snd_pcm_format_mask_t *mask, ma_snd_pcm_format_t val); typedef ma_snd_pcm_chmap_t * (* ma_snd_pcm_get_chmap_proc) (ma_snd_pcm_t *pcm); -typedef int (* ma_snd_pcm_state_proc) (ma_snd_pcm_t *pcm); -typedef int (* ma_snd_pcm_prepare_proc) (ma_snd_pcm_t *pcm); -typedef int (* ma_snd_pcm_start_proc) (ma_snd_pcm_t *pcm); -typedef int (* ma_snd_pcm_drop_proc) (ma_snd_pcm_t *pcm); -typedef int (* ma_snd_pcm_drain_proc) (ma_snd_pcm_t *pcm); -typedef int (* ma_snd_device_name_hint_proc) (int card, const char *iface, void ***hints); -typedef char * (* ma_snd_device_name_get_hint_proc) (const void *hint, const char *id); -typedef int (* ma_snd_card_get_index_proc) (const char *name); -typedef int (* ma_snd_device_name_free_hint_proc) (void **hints); -typedef int (* ma_snd_pcm_mmap_begin_proc) (ma_snd_pcm_t *pcm, const ma_snd_pcm_channel_area_t **areas, ma_snd_pcm_uframes_t *offset, ma_snd_pcm_uframes_t *frames); +typedef int (* ma_snd_pcm_state_proc) (ma_snd_pcm_t *pcm); +typedef int (* ma_snd_pcm_prepare_proc) (ma_snd_pcm_t *pcm); +typedef int (* ma_snd_pcm_start_proc) (ma_snd_pcm_t *pcm); +typedef int (* ma_snd_pcm_drop_proc) (ma_snd_pcm_t *pcm); +typedef int (* ma_snd_pcm_drain_proc) (ma_snd_pcm_t *pcm); +typedef int (* ma_snd_device_name_hint_proc) (int card, const char *iface, void ***hints); +typedef char * (* ma_snd_device_name_get_hint_proc) (const void *hint, const char *id); +typedef int (* ma_snd_card_get_index_proc) (const char *name); +typedef int (* ma_snd_device_name_free_hint_proc) (void **hints); +typedef int (* ma_snd_pcm_mmap_begin_proc) (ma_snd_pcm_t *pcm, const ma_snd_pcm_channel_area_t **areas, ma_snd_pcm_uframes_t *offset, ma_snd_pcm_uframes_t *frames); typedef ma_snd_pcm_sframes_t (* ma_snd_pcm_mmap_commit_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_uframes_t offset, ma_snd_pcm_uframes_t frames); -typedef int (* ma_snd_pcm_recover_proc) (ma_snd_pcm_t *pcm, int err, int silent); +typedef int (* ma_snd_pcm_recover_proc) (ma_snd_pcm_t *pcm, int err, int silent); typedef ma_snd_pcm_sframes_t (* ma_snd_pcm_readi_proc) (ma_snd_pcm_t *pcm, void *buffer, ma_snd_pcm_uframes_t size); typedef ma_snd_pcm_sframes_t (* ma_snd_pcm_writei_proc) (ma_snd_pcm_t *pcm, const void *buffer, ma_snd_pcm_uframes_t size); typedef ma_snd_pcm_sframes_t (* ma_snd_pcm_avail_proc) (ma_snd_pcm_t *pcm); typedef ma_snd_pcm_sframes_t (* ma_snd_pcm_avail_update_proc) (ma_snd_pcm_t *pcm); -typedef int (* ma_snd_pcm_wait_proc) (ma_snd_pcm_t *pcm, int timeout); -typedef int (* ma_snd_pcm_info_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_info_t* info); -typedef size_t (* ma_snd_pcm_info_sizeof_proc) (); -typedef const char* (* ma_snd_pcm_info_get_name_proc) (const ma_snd_pcm_info_t* info); -typedef int (* ma_snd_config_update_free_global_proc) (); +typedef int (* ma_snd_pcm_wait_proc) (ma_snd_pcm_t *pcm, int timeout); +typedef int (* ma_snd_pcm_info_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_info_t* info); +typedef size_t (* ma_snd_pcm_info_sizeof_proc) (); +typedef const char* (* ma_snd_pcm_info_get_name_proc) (const ma_snd_pcm_info_t* info); +typedef int (* ma_snd_config_update_free_global_proc) (); // This array specifies each of the common devices that can be used for both playback and capture. const char* g_maCommonDeviceNamesALSA[] = { @@ -11806,7 +11866,7 @@ ma_result ma_context_enumerate_devices__alsa(ma_context* pContext, ma_enum_devic char hwid[sizeof(pUniqueIDs->alsa)]; if (NAME != NULL) { - if (pContext->config.alsa.useVerboseDeviceEnumeration) { + if (pContext->alsa.useVerboseDeviceEnumeration) { // Verbose mode. Use the name exactly as-is. ma_strncpy_s(hwid, sizeof(hwid), NAME, (size_t)-1); } else { @@ -11861,7 +11921,7 @@ ma_result ma_context_enumerate_devices__alsa(ma_context* pContext, ma_enum_devic if (line2 != NULL) { line2 += 1; // Skip past the new-line character. - if (pContext->config.alsa.useVerboseDeviceEnumeration) { + if (pContext->alsa.useVerboseDeviceEnumeration) { // Verbose mode. Put the second line in brackets. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), DESC, lfPos); ma_strcat_s (deviceInfo.name, sizeof(deviceInfo.name), " ("); @@ -11979,8 +12039,10 @@ ma_result ma_context_get_device_info__alsa(ma_context* pContext, ma_device_type } // We need to initialize a HW parameters object in order to know what formats are supported. - ma_snd_pcm_hw_params_t* pHWParams = (ma_snd_pcm_hw_params_t*)alloca(((ma_snd_pcm_hw_params_sizeof_proc)pContext->alsa.snd_pcm_hw_params_sizeof)()); - ma_zero_memory(pHWParams, ((ma_snd_pcm_hw_params_sizeof_proc)pContext->alsa.snd_pcm_hw_params_sizeof)()); + ma_snd_pcm_hw_params_t* pHWParams = (ma_snd_pcm_hw_params_t*)calloc(1, ((ma_snd_pcm_hw_params_sizeof_proc)pContext->alsa.snd_pcm_hw_params_sizeof)()); + if (pHWParams == NULL) { + return MA_OUT_OF_MEMORY; + } if (((ma_snd_pcm_hw_params_any_proc)pContext->alsa.snd_pcm_hw_params_any)(pPCM, pHWParams) < 0) { return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to initialize hardware parameters. snd_pcm_hw_params_any() failed.", MA_FAILED_TO_CONFIGURE_BACKEND_DEVICE); @@ -11994,8 +12056,11 @@ ma_result ma_context_get_device_info__alsa(ma_context* pContext, ma_device_type ((ma_snd_pcm_hw_params_get_rate_max_proc)pContext->alsa.snd_pcm_hw_params_get_rate_max)(pHWParams, &pDeviceInfo->maxSampleRate, &sampleRateDir); // Formats. - ma_snd_pcm_format_mask_t* pFormatMask = (ma_snd_pcm_format_mask_t*)alloca(((ma_snd_pcm_format_mask_sizeof_proc)pContext->alsa.snd_pcm_format_mask_sizeof)()); - ma_zero_memory(pFormatMask, ((ma_snd_pcm_format_mask_sizeof_proc)pContext->alsa.snd_pcm_format_mask_sizeof)()); + ma_snd_pcm_format_mask_t* pFormatMask = (ma_snd_pcm_format_mask_t*)calloc(1, ((ma_snd_pcm_format_mask_sizeof_proc)pContext->alsa.snd_pcm_format_mask_sizeof)()); + if (pFormatMask == NULL) { + return MA_OUT_OF_MEMORY; + } + ((ma_snd_pcm_hw_params_get_format_mask_proc)pContext->alsa.snd_pcm_hw_params_get_format_mask)(pHWParams, pFormatMask); pDeviceInfo->formatCount = 0; @@ -12015,6 +12080,9 @@ ma_result ma_context_get_device_info__alsa(ma_context* pContext, ma_device_type pDeviceInfo->formats[pDeviceInfo->formatCount++] = ma_format_f32; } + ma_free(pFormatMask); + ma_free(pHWParams); + ((ma_snd_pcm_close_proc)pContext->alsa.snd_pcm_close)(pPCM); return MA_SUCCESS; } @@ -12333,8 +12401,10 @@ ma_result ma_device_init_by_type__alsa(ma_context* pContext, const ma_device_con /* If using the default buffer size we may want to apply some device-specific scaling for known devices that have peculiar latency characteristics */ float bufferSizeScaleFactor = 1; if (pDevice->usingDefaultBufferSize) { - ma_snd_pcm_info_t* pInfo = (ma_snd_pcm_info_t*)alloca(((ma_snd_pcm_info_sizeof_proc)pContext->alsa.snd_pcm_info_sizeof)()); - ma_zero_memory(pInfo, ((ma_snd_pcm_info_sizeof_proc)pContext->alsa.snd_pcm_info_sizeof)()); + ma_snd_pcm_info_t* pInfo = (ma_snd_pcm_info_t*)calloc(1, ((ma_snd_pcm_info_sizeof_proc)pContext->alsa.snd_pcm_info_sizeof)()); + if (pInfo == NULL) { + return MA_OUT_OF_MEMORY; + } /* We may need to scale the size of the buffer depending on the device. */ if (((ma_snd_pcm_info_proc)pContext->alsa.snd_pcm_info)(pPCM, pInfo) == 0) { @@ -12346,6 +12416,7 @@ ma_result ma_device_init_by_type__alsa(ma_context* pContext, const ma_device_con /* It's the default device. We need to use DESC from snd_device_name_hint(). */ if (((ma_snd_device_name_hint_proc)pContext->alsa.snd_device_name_hint)(-1, "pcm", (void***)&ppDeviceHints) < 0) { + ma_free(pInfo); return MA_NO_BACKEND; } @@ -12380,14 +12451,19 @@ ma_result ma_device_init_by_type__alsa(ma_context* pContext, const ma_device_con } } } + + ma_free(pInfo); } /* Hardware parameters. */ - pHWParams = (ma_snd_pcm_hw_params_t*)alloca(((ma_snd_pcm_hw_params_sizeof_proc)pContext->alsa.snd_pcm_hw_params_sizeof)()); - ma_zero_memory(pHWParams, ((ma_snd_pcm_hw_params_sizeof_proc)pContext->alsa.snd_pcm_hw_params_sizeof)()); + pHWParams = (ma_snd_pcm_hw_params_t*)calloc(1, ((ma_snd_pcm_hw_params_sizeof_proc)pContext->alsa.snd_pcm_hw_params_sizeof)()); + if (pHWParams == NULL) { + return MA_OUT_OF_MEMORY; + } if (((ma_snd_pcm_hw_params_any_proc)pContext->alsa.snd_pcm_hw_params_any)(pPCM, pHWParams) < 0) { + ma_free(pHWParams); ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to initialize hardware parameters. snd_pcm_hw_params_any() failed.", MA_FAILED_TO_CONFIGURE_BACKEND_DEVICE); } @@ -12405,7 +12481,8 @@ ma_result ma_device_init_by_type__alsa(ma_context* pContext, const ma_device_con #endif if (!isUsingMMap) { - if (((ma_snd_pcm_hw_params_set_access_proc)pContext->alsa.snd_pcm_hw_params_set_access)(pPCM, pHWParams, MA_SND_PCM_ACCESS_RW_INTERLEAVED) < 0) {; + if (((ma_snd_pcm_hw_params_set_access_proc)pContext->alsa.snd_pcm_hw_params_set_access)(pPCM, pHWParams, MA_SND_PCM_ACCESS_RW_INTERLEAVED) < 0) { + ma_free(pHWParams); ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set access mode to neither SND_PCM_ACCESS_MMAP_INTERLEAVED nor SND_PCM_ACCESS_RW_INTERLEAVED. snd_pcm_hw_params_set_access() failed.", MA_FORMAT_NOT_SUPPORTED); } @@ -12421,8 +12498,12 @@ ma_result ma_device_init_by_type__alsa(ma_context* pContext, const ma_device_con ma_snd_pcm_format_mask_t* pFormatMask; /* Try getting every supported format first. */ - pFormatMask = (ma_snd_pcm_format_mask_t*)alloca(((ma_snd_pcm_format_mask_sizeof_proc)pContext->alsa.snd_pcm_format_mask_sizeof)()); - ma_zero_memory(pFormatMask, ((ma_snd_pcm_format_mask_sizeof_proc)pContext->alsa.snd_pcm_format_mask_sizeof)()); + pFormatMask = (ma_snd_pcm_format_mask_t*)calloc(1, ((ma_snd_pcm_format_mask_sizeof_proc)pContext->alsa.snd_pcm_format_mask_sizeof)()); + if (pFormatMask == NULL) { + ma_free(pHWParams); + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + return MA_OUT_OF_MEMORY; + } ((ma_snd_pcm_hw_params_get_format_mask_proc)pContext->alsa.snd_pcm_hw_params_get_format_mask)(pHWParams, pFormatMask); @@ -12457,18 +12538,24 @@ ma_result ma_device_init_by_type__alsa(ma_context* pContext, const ma_device_con } if (formatALSA == MA_SND_PCM_FORMAT_UNKNOWN) { + ma_free(pHWParams); ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Format not supported. The device does not support any miniaudio formats.", MA_FORMAT_NOT_SUPPORTED); } } + ma_free(pFormatMask); + pFormatMask = NULL; + if (((ma_snd_pcm_hw_params_set_format_proc)pContext->alsa.snd_pcm_hw_params_set_format)(pPCM, pHWParams, formatALSA) < 0) { + ma_free(pHWParams); ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Format not supported. snd_pcm_hw_params_set_format() failed.", MA_FORMAT_NOT_SUPPORTED); } internalFormat = ma_convert_alsa_format_to_ma_format(formatALSA); if (internalFormat == ma_format_unknown) { + ma_free(pHWParams); ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] The chosen format is not supported by miniaudio.", MA_FORMAT_NOT_SUPPORTED); } @@ -12478,6 +12565,7 @@ ma_result ma_device_init_by_type__alsa(ma_context* pContext, const ma_device_con { unsigned int channels = (deviceType == ma_device_type_capture) ? pConfig->capture.channels : pConfig->playback.channels; if (((ma_snd_pcm_hw_params_set_channels_near_proc)pContext->alsa.snd_pcm_hw_params_set_channels_near)(pPCM, pHWParams, &channels) < 0) { + ma_free(pHWParams); ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set channel count. snd_pcm_hw_params_set_channels_near() failed.", MA_FORMAT_NOT_SUPPORTED); } @@ -12509,6 +12597,7 @@ ma_result ma_device_init_by_type__alsa(ma_context* pContext, const ma_device_con sampleRate = pConfig->sampleRate; if (((ma_snd_pcm_hw_params_set_rate_near_proc)pContext->alsa.snd_pcm_hw_params_set_rate_near)(pPCM, pHWParams, &sampleRate, 0) < 0) { + ma_free(pHWParams); ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Sample rate not supported. snd_pcm_hw_params_set_rate_near() failed.", MA_FORMAT_NOT_SUPPORTED); } @@ -12523,6 +12612,7 @@ ma_result ma_device_init_by_type__alsa(ma_context* pContext, const ma_device_con } if (((ma_snd_pcm_hw_params_set_buffer_size_near_proc)pContext->alsa.snd_pcm_hw_params_set_buffer_size_near)(pPCM, pHWParams, &actualBufferSizeInFrames) < 0) { + ma_free(pHWParams); ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set buffer size for device. snd_pcm_hw_params_set_buffer_size() failed.", MA_FORMAT_NOT_SUPPORTED); } @@ -12533,6 +12623,7 @@ ma_result ma_device_init_by_type__alsa(ma_context* pContext, const ma_device_con { ma_uint32 periods = pConfig->periods; if (((ma_snd_pcm_hw_params_set_periods_near_proc)pContext->alsa.snd_pcm_hw_params_set_periods_near)(pPCM, pHWParams, &periods, NULL) < 0) { + ma_free(pHWParams); ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set period count. snd_pcm_hw_params_set_periods_near() failed.", MA_FORMAT_NOT_SUPPORTED); } @@ -12541,27 +12632,37 @@ ma_result ma_device_init_by_type__alsa(ma_context* pContext, const ma_device_con /* Apply hardware parameters. */ if (((ma_snd_pcm_hw_params_proc)pContext->alsa.snd_pcm_hw_params)(pPCM, pHWParams) < 0) { + ma_free(pHWParams); ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set hardware parameters. snd_pcm_hw_params() failed.", MA_FAILED_TO_CONFIGURE_BACKEND_DEVICE); } + ma_free(pHWParams); + pHWParams = NULL; + /* Software parameters. */ - pSWParams = (ma_snd_pcm_sw_params_t*)alloca(((ma_snd_pcm_sw_params_sizeof_proc)pContext->alsa.snd_pcm_sw_params_sizeof)()); - ma_zero_memory(pSWParams, ((ma_snd_pcm_sw_params_sizeof_proc)pContext->alsa.snd_pcm_sw_params_sizeof)()); + pSWParams = (ma_snd_pcm_sw_params_t*)calloc(1, ((ma_snd_pcm_sw_params_sizeof_proc)pContext->alsa.snd_pcm_sw_params_sizeof)()); + if (pSWParams == NULL) { + ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); + return MA_OUT_OF_MEMORY; + } if (((ma_snd_pcm_sw_params_current_proc)pContext->alsa.snd_pcm_sw_params_current)(pPCM, pSWParams) != 0) { + ma_free(pSWParams); ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to initialize software parameters. snd_pcm_sw_params_current() failed.", MA_FAILED_TO_CONFIGURE_BACKEND_DEVICE); } if (deviceType == ma_device_type_capture) { if (((ma_snd_pcm_sw_params_set_avail_min_proc)pContext->alsa.snd_pcm_sw_params_set_avail_min)(pPCM, pSWParams, 1) != 0) { + ma_free(pSWParams); ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] snd_pcm_sw_params_set_avail_min() failed.", MA_FORMAT_NOT_SUPPORTED); } } else { if (((ma_snd_pcm_sw_params_set_avail_min_proc)pContext->alsa.snd_pcm_sw_params_set_avail_min)(pPCM, pSWParams, 1) != 0) { + ma_free(pSWParams); ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] snd_pcm_sw_params_set_avail_min() failed.", MA_FORMAT_NOT_SUPPORTED); } @@ -12580,20 +12681,26 @@ ma_result ma_device_init_by_type__alsa(ma_context* pContext, const ma_device_con the size of a period. But for full-duplex we need to set it such that it is at least two periods. */ if (((ma_snd_pcm_sw_params_set_start_threshold_proc)pContext->alsa.snd_pcm_sw_params_set_start_threshold)(pPCM, pSWParams, internalBufferSizeInFrames) != 0) { + ma_free(pSWParams); ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set start threshold for playback device. snd_pcm_sw_params_set_start_threshold() failed.", MA_FAILED_TO_CONFIGURE_BACKEND_DEVICE); } if (((ma_snd_pcm_sw_params_set_stop_threshold_proc)pContext->alsa.snd_pcm_sw_params_set_stop_threshold)(pPCM, pSWParams, bufferBoundary) != 0) { /* Set to boundary to loop instead of stop in the event of an xrun. */ + ma_free(pSWParams); ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set stop threshold for playback device. snd_pcm_sw_params_set_stop_threshold() failed.", MA_FAILED_TO_CONFIGURE_BACKEND_DEVICE); } } if (((ma_snd_pcm_sw_params_proc)pContext->alsa.snd_pcm_sw_params)(pPCM, pSWParams) != 0) { + ma_free(pSWParams); ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set software parameters. snd_pcm_sw_params() failed.", MA_FAILED_TO_CONFIGURE_BACKEND_DEVICE); } + ma_free(pSWParams); + pSWParams = NULL; + /* Grab the internal channel map. For now we're not going to bother trying to change the channel map and instead just do it ourselves. */ { @@ -12899,7 +13006,7 @@ ma_result ma_context_uninit__alsa(ma_context* pContext) return MA_SUCCESS; } -ma_result ma_context_init__alsa(ma_context* pContext) +ma_result ma_context_init__alsa(const ma_context_config* pConfig, ma_context* pContext) { ma_assert(pContext != NULL); @@ -13091,6 +13198,8 @@ ma_result ma_context_init__alsa(ma_context* pContext) pContext->alsa.snd_config_update_free_global = (ma_proc)_snd_config_update_free_global; #endif + pContext->alsa.useVerboseDeviceEnumeration = pConfig->alsa.useVerboseDeviceEnumeration; + if (ma_mutex_init(pContext, &pContext->alsa.internalDeviceEnumLock) != MA_SUCCESS) { ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[ALSA] WARNING: Failed to initialize mutex for internal device enumeration.", MA_ERROR); } @@ -13608,49 +13717,49 @@ typedef void (* ma_pa_free_cb_t) (void* p); typedef ma_pa_mainloop* (* ma_pa_mainloop_new_proc) (); -typedef void (* ma_pa_mainloop_free_proc) (ma_pa_mainloop* m); +typedef void (* ma_pa_mainloop_free_proc) (ma_pa_mainloop* m); typedef ma_pa_mainloop_api* (* ma_pa_mainloop_get_api_proc) (ma_pa_mainloop* m); -typedef int (* ma_pa_mainloop_iterate_proc) (ma_pa_mainloop* m, int block, int* retval); -typedef void (* ma_pa_mainloop_wakeup_proc) (ma_pa_mainloop* m); +typedef int (* ma_pa_mainloop_iterate_proc) (ma_pa_mainloop* m, int block, int* retval); +typedef void (* ma_pa_mainloop_wakeup_proc) (ma_pa_mainloop* m); typedef ma_pa_context* (* ma_pa_context_new_proc) (ma_pa_mainloop_api* mainloop, const char* name); -typedef void (* ma_pa_context_unref_proc) (ma_pa_context* c); -typedef int (* ma_pa_context_connect_proc) (ma_pa_context* c, const char* server, ma_pa_context_flags_t flags, const ma_pa_spawn_api* api); -typedef void (* ma_pa_context_disconnect_proc) (ma_pa_context* c); -typedef void (* ma_pa_context_set_state_callback_proc) (ma_pa_context* c, ma_pa_context_notify_cb_t cb, void* userdata); +typedef void (* ma_pa_context_unref_proc) (ma_pa_context* c); +typedef int (* ma_pa_context_connect_proc) (ma_pa_context* c, const char* server, ma_pa_context_flags_t flags, const ma_pa_spawn_api* api); +typedef void (* ma_pa_context_disconnect_proc) (ma_pa_context* c); +typedef void (* ma_pa_context_set_state_callback_proc) (ma_pa_context* c, ma_pa_context_notify_cb_t cb, void* userdata); typedef ma_pa_context_state_t (* ma_pa_context_get_state_proc) (ma_pa_context* c); typedef ma_pa_operation* (* ma_pa_context_get_sink_info_list_proc) (ma_pa_context* c, ma_pa_sink_info_cb_t cb, void* userdata); typedef ma_pa_operation* (* ma_pa_context_get_source_info_list_proc) (ma_pa_context* c, ma_pa_source_info_cb_t cb, void* userdata); typedef ma_pa_operation* (* ma_pa_context_get_sink_info_by_name_proc) (ma_pa_context* c, const char* name, ma_pa_sink_info_cb_t cb, void* userdata); typedef ma_pa_operation* (* ma_pa_context_get_source_info_by_name_proc)(ma_pa_context* c, const char* name, ma_pa_source_info_cb_t cb, void* userdata); -typedef void (* ma_pa_operation_unref_proc) (ma_pa_operation* o); +typedef void (* ma_pa_operation_unref_proc) (ma_pa_operation* o); typedef ma_pa_operation_state_t (* ma_pa_operation_get_state_proc) (ma_pa_operation* o); typedef ma_pa_channel_map* (* ma_pa_channel_map_init_extend_proc) (ma_pa_channel_map* m, unsigned channels, ma_pa_channel_map_def_t def); -typedef int (* ma_pa_channel_map_valid_proc) (const ma_pa_channel_map* m); -typedef int (* ma_pa_channel_map_compatible_proc) (const ma_pa_channel_map* m, const ma_pa_sample_spec* ss); +typedef int (* ma_pa_channel_map_valid_proc) (const ma_pa_channel_map* m); +typedef int (* ma_pa_channel_map_compatible_proc) (const ma_pa_channel_map* m, const ma_pa_sample_spec* ss); typedef ma_pa_stream* (* ma_pa_stream_new_proc) (ma_pa_context* c, const char* name, const ma_pa_sample_spec* ss, const ma_pa_channel_map* map); -typedef void (* ma_pa_stream_unref_proc) (ma_pa_stream* s); -typedef int (* ma_pa_stream_connect_playback_proc) (ma_pa_stream* s, const char* dev, const ma_pa_buffer_attr* attr, ma_pa_stream_flags_t flags, const ma_pa_cvolume* volume, ma_pa_stream* sync_stream); -typedef int (* ma_pa_stream_connect_record_proc) (ma_pa_stream* s, const char* dev, const ma_pa_buffer_attr* attr, ma_pa_stream_flags_t flags); -typedef int (* ma_pa_stream_disconnect_proc) (ma_pa_stream* s); +typedef void (* ma_pa_stream_unref_proc) (ma_pa_stream* s); +typedef int (* ma_pa_stream_connect_playback_proc) (ma_pa_stream* s, const char* dev, const ma_pa_buffer_attr* attr, ma_pa_stream_flags_t flags, const ma_pa_cvolume* volume, ma_pa_stream* sync_stream); +typedef int (* ma_pa_stream_connect_record_proc) (ma_pa_stream* s, const char* dev, const ma_pa_buffer_attr* attr, ma_pa_stream_flags_t flags); +typedef int (* ma_pa_stream_disconnect_proc) (ma_pa_stream* s); typedef ma_pa_stream_state_t (* ma_pa_stream_get_state_proc) (ma_pa_stream* s); typedef const ma_pa_sample_spec* (* ma_pa_stream_get_sample_spec_proc) (ma_pa_stream* s); typedef const ma_pa_channel_map* (* ma_pa_stream_get_channel_map_proc) (ma_pa_stream* s); typedef const ma_pa_buffer_attr* (* ma_pa_stream_get_buffer_attr_proc) (ma_pa_stream* s); typedef ma_pa_operation* (* ma_pa_stream_set_buffer_attr_proc) (ma_pa_stream* s, const ma_pa_buffer_attr* attr, ma_pa_stream_success_cb_t cb, void* userdata); -typedef const char* (* ma_pa_stream_get_device_name_proc) (ma_pa_stream* s); -typedef void (* ma_pa_stream_set_write_callback_proc) (ma_pa_stream* s, ma_pa_stream_request_cb_t cb, void* userdata); -typedef void (* ma_pa_stream_set_read_callback_proc) (ma_pa_stream* s, ma_pa_stream_request_cb_t cb, void* userdata); +typedef const char* (* ma_pa_stream_get_device_name_proc) (ma_pa_stream* s); +typedef void (* ma_pa_stream_set_write_callback_proc) (ma_pa_stream* s, ma_pa_stream_request_cb_t cb, void* userdata); +typedef void (* ma_pa_stream_set_read_callback_proc) (ma_pa_stream* s, ma_pa_stream_request_cb_t cb, void* userdata); typedef ma_pa_operation* (* ma_pa_stream_flush_proc) (ma_pa_stream* s, ma_pa_stream_success_cb_t cb, void* userdata); typedef ma_pa_operation* (* ma_pa_stream_drain_proc) (ma_pa_stream* s, ma_pa_stream_success_cb_t cb, void* userdata); -typedef int (* ma_pa_stream_is_corked_proc) (ma_pa_stream* s); +typedef int (* ma_pa_stream_is_corked_proc) (ma_pa_stream* s); typedef ma_pa_operation* (* ma_pa_stream_cork_proc) (ma_pa_stream* s, int b, ma_pa_stream_success_cb_t cb, void* userdata); typedef ma_pa_operation* (* ma_pa_stream_trigger_proc) (ma_pa_stream* s, ma_pa_stream_success_cb_t cb, void* userdata); -typedef int (* ma_pa_stream_begin_write_proc) (ma_pa_stream* s, void** data, size_t* nbytes); -typedef int (* ma_pa_stream_write_proc) (ma_pa_stream* s, const void* data, size_t nbytes, ma_pa_free_cb_t free_cb, int64_t offset, ma_pa_seek_mode_t seek); -typedef int (* ma_pa_stream_peek_proc) (ma_pa_stream* s, const void** data, size_t* nbytes); -typedef int (* ma_pa_stream_drop_proc) (ma_pa_stream* s); -typedef size_t (* ma_pa_stream_writable_size_proc) (ma_pa_stream* s); -typedef size_t (* ma_pa_stream_readable_size_proc) (ma_pa_stream* s); +typedef int (* ma_pa_stream_begin_write_proc) (ma_pa_stream* s, void** data, size_t* nbytes); +typedef int (* ma_pa_stream_write_proc) (ma_pa_stream* s, const void* data, size_t nbytes, ma_pa_free_cb_t free_cb, int64_t offset, ma_pa_seek_mode_t seek); +typedef int (* ma_pa_stream_peek_proc) (ma_pa_stream* s, const void** data, size_t* nbytes); +typedef int (* ma_pa_stream_drop_proc) (ma_pa_stream* s); +typedef size_t (* ma_pa_stream_writable_size_proc) (ma_pa_stream* s); +typedef size_t (* ma_pa_stream_readable_size_proc) (ma_pa_stream* s); typedef struct { @@ -13875,6 +13984,8 @@ typedef struct void ma_context_enumerate_devices_sink_callback__pulse(ma_pa_context* pPulseContext, const ma_pa_sink_info* pSinkInfo, int endOfList, void* pUserData) { + (void)pPulseContext; + ma_context_enumerate_devices_callback_data__pulse* pData = (ma_context_enumerate_devices_callback_data__pulse*)pUserData; ma_assert(pData != NULL); @@ -13900,6 +14011,8 @@ void ma_context_enumerate_devices_sink_callback__pulse(ma_pa_context* pPulseCont void ma_context_enumerate_devices_source_callback__pulse(ma_pa_context* pPulseContext, const ma_pa_source_info* pSinkInfo, int endOfList, void* pUserData) { + (void)pPulseContext; + ma_context_enumerate_devices_callback_data__pulse* pData = (ma_context_enumerate_devices_callback_data__pulse*)pUserData; ma_assert(pData != NULL); @@ -13949,24 +14062,41 @@ ma_result ma_context_enumerate_devices__pulse(ma_context* pContext, ma_enum_devi return MA_FAILED_TO_INIT_BACKEND; } - ma_pa_context* pPulseContext = ((ma_pa_context_new_proc)pContext->pulse.pa_context_new)(pAPI, pContext->config.pulse.pApplicationName); + ma_pa_context* pPulseContext = ((ma_pa_context_new_proc)pContext->pulse.pa_context_new)(pAPI, pContext->pulse.pApplicationName); if (pPulseContext == NULL) { ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); return MA_FAILED_TO_INIT_BACKEND; } - int error = ((ma_pa_context_connect_proc)pContext->pulse.pa_context_connect)(pPulseContext, pContext->config.pulse.pServerName, 0, NULL); + int error = ((ma_pa_context_connect_proc)pContext->pulse.pa_context_connect)(pPulseContext, pContext->pulse.pServerName, (pContext->pulse.tryAutoSpawn) ? 0 : MA_PA_CONTEXT_NOAUTOSPAWN, NULL); if (error != MA_PA_OK) { ((ma_pa_context_unref_proc)pContext->pulse.pa_context_unref)(pPulseContext); ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); return ma_result_from_pulse(error); } - while (((ma_pa_context_get_state_proc)pContext->pulse.pa_context_get_state)(pPulseContext) != MA_PA_CONTEXT_READY) { - error = ((ma_pa_mainloop_iterate_proc)pContext->pulse.pa_mainloop_iterate)(pMainLoop, 1, NULL); - if (error < 0) { - result = ma_result_from_pulse(error); - goto done; + for (;;) { + ma_pa_context_state_t state = ((ma_pa_context_get_state_proc)pContext->pulse.pa_context_get_state)(pPulseContext); + if (state == MA_PA_CONTEXT_READY) { + break; /* Success. */ + } + if (state == MA_PA_CONTEXT_CONNECTING || state == MA_PA_CONTEXT_AUTHORIZING || state == MA_PA_CONTEXT_SETTING_NAME) { + error = ((ma_pa_mainloop_iterate_proc)pContext->pulse.pa_mainloop_iterate)(pMainLoop, 1, NULL); + if (error < 0) { + result = ma_result_from_pulse(error); + goto done; + } + +#ifdef MA_DEBUG_OUTPUT + printf("[PulseAudio] pa_context_get_state() returned %d. Waiting.\n", state); +#endif + continue; /* Keep trying. */ + } + if (state == MA_PA_CONTEXT_UNCONNECTED || state == MA_PA_CONTEXT_FAILED || state == MA_PA_CONTEXT_TERMINATED) { +#ifdef MA_DEBUG_OUTPUT + printf("[PulseAudio] pa_context_get_state() returned %d. Failed.\n", state); +#endif + goto done; /* Failed. */ } } @@ -14018,6 +14148,8 @@ typedef struct void ma_context_get_device_info_sink_callback__pulse(ma_pa_context* pPulseContext, const ma_pa_sink_info* pInfo, int endOfList, void* pUserData) { + (void)pPulseContext; + if (endOfList > 0) { return; } @@ -14044,6 +14176,8 @@ void ma_context_get_device_info_sink_callback__pulse(ma_pa_context* pPulseContex void ma_context_get_device_info_source_callback__pulse(ma_pa_context* pPulseContext, const ma_pa_source_info* pInfo, int endOfList, void* pUserData) { + (void)pPulseContext; + if (endOfList > 0) { return; } @@ -14096,24 +14230,41 @@ ma_result ma_context_get_device_info__pulse(ma_context* pContext, ma_device_type return MA_FAILED_TO_INIT_BACKEND; } - ma_pa_context* pPulseContext = ((ma_pa_context_new_proc)pContext->pulse.pa_context_new)(pAPI, pContext->config.pulse.pApplicationName); + ma_pa_context* pPulseContext = ((ma_pa_context_new_proc)pContext->pulse.pa_context_new)(pAPI, pContext->pulse.pApplicationName); if (pPulseContext == NULL) { ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); return MA_FAILED_TO_INIT_BACKEND; } - int error = ((ma_pa_context_connect_proc)pContext->pulse.pa_context_connect)(pPulseContext, pContext->config.pulse.pServerName, 0, NULL); + int error = ((ma_pa_context_connect_proc)pContext->pulse.pa_context_connect)(pPulseContext, pContext->pulse.pServerName, 0, NULL); if (error != MA_PA_OK) { ((ma_pa_context_unref_proc)pContext->pulse.pa_context_unref)(pPulseContext); ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); return ma_result_from_pulse(error); } - while (((ma_pa_context_get_state_proc)pContext->pulse.pa_context_get_state)(pPulseContext) != MA_PA_CONTEXT_READY) { - error = ((ma_pa_mainloop_iterate_proc)pContext->pulse.pa_mainloop_iterate)(pMainLoop, 1, NULL); - if (error < 0) { - result = ma_result_from_pulse(error); - goto done; + for (;;) { + ma_pa_context_state_t state = ((ma_pa_context_get_state_proc)pContext->pulse.pa_context_get_state)(pPulseContext); + if (state == MA_PA_CONTEXT_READY) { + break; /* Success. */ + } + if (state == MA_PA_CONTEXT_CONNECTING || state == MA_PA_CONTEXT_AUTHORIZING || state == MA_PA_CONTEXT_SETTING_NAME) { + error = ((ma_pa_mainloop_iterate_proc)pContext->pulse.pa_mainloop_iterate)(pMainLoop, 1, NULL); + if (error < 0) { + result = ma_result_from_pulse(error); + goto done; + } + +#ifdef MA_DEBUG_OUTPUT + printf("[PulseAudio] pa_context_get_state() returned %d. Waiting.\n", state); +#endif + continue; /* Keep trying. */ + } + if (state == MA_PA_CONTEXT_UNCONNECTED || state == MA_PA_CONTEXT_FAILED || state == MA_PA_CONTEXT_TERMINATED) { +#ifdef MA_DEBUG_OUTPUT + printf("[PulseAudio] pa_context_get_state() returned %d. Failed.\n", state); +#endif + goto done; /* Failed. */ } } @@ -14158,6 +14309,8 @@ void ma_pulse_device_state_callback(ma_pa_context* pPulseContext, void* pUserDat void ma_device_sink_info_callback(ma_pa_context* pPulseContext, const ma_pa_sink_info* pInfo, int endOfList, void* pUserData) { + (void)pPulseContext; + if (endOfList > 0) { return; } @@ -14170,6 +14323,8 @@ void ma_device_sink_info_callback(ma_pa_context* pPulseContext, const ma_pa_sink void ma_device_source_info_callback(ma_pa_context* pPulseContext, const ma_pa_source_info* pInfo, int endOfList, void* pUserData) { + (void)pPulseContext; + if (endOfList > 0) { return; } @@ -14182,6 +14337,8 @@ void ma_device_source_info_callback(ma_pa_context* pPulseContext, const ma_pa_so void ma_device_sink_name_callback(ma_pa_context* pPulseContext, const ma_pa_sink_info* pInfo, int endOfList, void* pUserData) { + (void)pPulseContext; + if (endOfList > 0) { return; } @@ -14194,6 +14351,8 @@ void ma_device_sink_name_callback(ma_pa_context* pPulseContext, const ma_pa_sink void ma_device_source_name_callback(ma_pa_context* pPulseContext, const ma_pa_source_info* pInfo, int endOfList, void* pUserData) { + (void)pPulseContext; + if (endOfList > 0) { return; } @@ -14309,13 +14468,13 @@ ma_result ma_device_init__pulse(ma_context* pContext, const ma_device_config* pC goto on_error1; } - pDevice->pulse.pPulseContext = ((ma_pa_context_new_proc)pContext->pulse.pa_context_new)((ma_pa_mainloop_api*)pDevice->pulse.pAPI, pContext->config.pulse.pApplicationName); + pDevice->pulse.pPulseContext = ((ma_pa_context_new_proc)pContext->pulse.pa_context_new)((ma_pa_mainloop_api*)pDevice->pulse.pAPI, pContext->pulse.pApplicationName); if (pDevice->pulse.pPulseContext == NULL) { result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to create PulseAudio context for device.", MA_FAILED_TO_INIT_BACKEND); goto on_error1; } - error = ((ma_pa_context_connect_proc)pContext->pulse.pa_context_connect)((ma_pa_context*)pDevice->pulse.pPulseContext, pContext->config.pulse.pServerName, (pContext->config.pulse.tryAutoSpawn) ? 0 : MA_PA_CONTEXT_NOAUTOSPAWN, NULL); + error = ((ma_pa_context_connect_proc)pContext->pulse.pa_context_connect)((ma_pa_context*)pDevice->pulse.pPulseContext, pContext->pulse.pServerName, (pContext->pulse.tryAutoSpawn) ? 0 : MA_PA_CONTEXT_NOAUTOSPAWN, NULL); if (error != MA_PA_OK) { result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to connect PulseAudio context.", ma_result_from_pulse(error)); goto on_error2; @@ -14329,16 +14488,9 @@ ma_result ma_device_init__pulse(ma_context* pContext, const ma_device_config* pC for (;;) { if (pDevice->pulse.pulseContextState == MA_PA_CONTEXT_READY) { break; - } else { - error = ((ma_pa_mainloop_iterate_proc)pContext->pulse.pa_mainloop_iterate)((ma_pa_mainloop*)pDevice->pulse.pMainLoop, 1, NULL); // 1 = block. - if (error < 0) { - result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] The PulseAudio main loop returned an error while connecting the PulseAudio context.", ma_result_from_pulse(error)); - goto on_error3; - } - continue; } - // An error may have occurred. + /* An error may have occurred. */ if (pDevice->pulse.pulseContextState == MA_PA_CONTEXT_FAILED || pDevice->pulse.pulseContextState == MA_PA_CONTEXT_TERMINATED) { result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] An error occurred while connecting the PulseAudio context.", MA_ERROR); goto on_error3; @@ -14576,6 +14728,8 @@ on_error0: void ma_pulse_operation_complete_callback(ma_pa_stream* pStream, int success, void* pUserData) { + (void)pStream; + ma_bool32* pIsSuccessful = (ma_bool32*)pUserData; ma_assert(pIsSuccessful != NULL); @@ -14720,12 +14874,14 @@ ma_result ma_device_write__pulse(ma_device* pDevice, const void* pPCMFrames, ma_ size_t writableSizeInBytes = ((ma_pa_stream_writable_size_proc)pDevice->pContext->pulse.pa_stream_writable_size)((ma_pa_stream*)pDevice->pulse.pStreamPlayback); if (writableSizeInBytes != (size_t)-1) { - size_t periodSizeInBytes = (pDevice->playback.internalBufferSizeInFrames / pDevice->playback.internalPeriods) * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels); - if (writableSizeInBytes >= periodSizeInBytes) { - //printf("TRACE: Data available.\n"); + //size_t periodSizeInBytes = (pDevice->playback.internalBufferSizeInFrames / pDevice->playback.internalPeriods) * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels); + if (writableSizeInBytes > 0) { + #if defined(MA_DEBUG_OUTPUT) + //printf("TRACE: Data available: %ld\n", writableSizeInBytes); + #endif /* Data is avaialable. */ - size_t bytesToMap = periodSizeInBytes; + size_t bytesToMap = writableSizeInBytes; int error = ((ma_pa_stream_begin_write_proc)pDevice->pContext->pulse.pa_stream_begin_write)((ma_pa_stream*)pDevice->pulse.pStreamPlayback, &pDevice->pulse.pMappedBufferPlayback, &bytesToMap); if (error < 0) { return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to map write buffer.", ma_result_from_pulse(error)); @@ -14737,7 +14893,9 @@ ma_result ma_device_write__pulse(ma_device* pDevice, const void* pPCMFrames, ma_ break; } else { /* No data available. Need to wait for more. */ - //printf("TRACE: Playback: pa_mainloop_iterate(). writableSizeInBytes=%d, periodSizeInBytes=%d\n", writableSizeInBytes, periodSizeInBytes); + #if defined(MA_DEBUG_OUTPUT) + //printf("TRACE: Playback: pa_mainloop_iterate(). writableSizeInBytes=%ld, periodSizeInBytes=%ld\n", writableSizeInBytes, periodSizeInBytes); + #endif int error = ((ma_pa_mainloop_iterate_proc)pDevice->pContext->pulse.pa_mainloop_iterate)((ma_pa_mainloop*)pDevice->pulse.pMainLoop, 1, NULL); if (error < 0) { @@ -14771,6 +14929,10 @@ ma_result ma_device_read__pulse(ma_device* pDevice, void* pPCMFrames, ma_uint32 ma_uint32 totalFramesRead = 0; while (totalFramesRead < frameCount) { + if (ma_device__get_state(pDevice) != MA_STATE_STARTED) { + break; + } + /* If a buffer is mapped we need to write to that first. Once it's consumed we reset the event and unmap it. */ if (pDevice->pulse.pMappedBufferCapture != NULL && pDevice->pulse.mappedBufferFramesRemainingCapture > 0) { ma_uint32 bpf = ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels); @@ -14820,6 +14982,10 @@ ma_result ma_device_read__pulse(ma_device* pDevice, void* pPCMFrames, ma_uint32 for (;;) { //printf("TRACE: Inner loop.\n"); + if (ma_device__get_state(pDevice) != MA_STATE_STARTED) { + break; + } + /* If the device has been corked, don't try to continue. */ if (((ma_pa_stream_is_corked_proc)pDevice->pContext->pulse.pa_stream_is_corked)((ma_pa_stream*)pDevice->pulse.pStreamCapture)) { break; @@ -14827,8 +14993,8 @@ ma_result ma_device_read__pulse(ma_device* pDevice, void* pPCMFrames, ma_uint32 size_t readableSizeInBytes = ((ma_pa_stream_readable_size_proc)pDevice->pContext->pulse.pa_stream_readable_size)((ma_pa_stream*)pDevice->pulse.pStreamCapture); if (readableSizeInBytes != (size_t)-1) { - size_t periodSizeInBytes = (pDevice->capture.internalBufferSizeInFrames / pDevice->capture.internalPeriods) * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels); - if (readableSizeInBytes >= periodSizeInBytes) { + //size_t periodSizeInBytes = (pDevice->capture.internalBufferSizeInFrames / pDevice->capture.internalPeriods) * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels); + if (readableSizeInBytes > 0) { /* Data is avaialable. */ size_t bytesMapped = (size_t)-1; int error = ((ma_pa_stream_peek_proc)pDevice->pContext->pulse.pa_stream_peek)((ma_pa_stream*)pDevice->pulse.pStreamCapture, &pDevice->pulse.pMappedBufferCapture, &bytesMapped); @@ -14836,7 +15002,9 @@ ma_result ma_device_read__pulse(ma_device* pDevice, void* pPCMFrames, ma_uint32 return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to peek capture buffer.", ma_result_from_pulse(error)); } - //printf("TRACE: Data available: bytesMapped=%d, readableSizeInBytes=%d, periodSizeInBytes=%d.\n", bytesMapped, readableSizeInBytes, periodSizeInBytes); + #if defined(MA_DEBUG_OUTPUT) + //printf("TRACE: Data available: bytesMapped=%ld, readableSizeInBytes=%ld.\n", bytesMapped, readableSizeInBytes); + #endif if (pDevice->pulse.pMappedBufferCapture == NULL && bytesMapped == 0) { /* Nothing available. This shouldn't happen because we checked earlier with pa_stream_readable_size(). I'm going to throw an error in this case. */ @@ -14849,13 +15017,25 @@ ma_result ma_device_read__pulse(ma_device* pDevice, void* pPCMFrames, ma_uint32 break; } else { /* No data available. Need to wait for more. */ - //printf("TRACE: Capture: pa_mainloop_iterate(). readableSizeInBytes=%d, periodSizeInBytes=%d\n", readableSizeInBytes, periodSizeInBytes); + #if defined(MA_DEBUG_OUTPUT) + //printf("TRACE: Capture: pa_mainloop_iterate(). readableSizeInBytes=%ld\n", readableSizeInBytes); + #endif - int error = ((ma_pa_mainloop_iterate_proc)pDevice->pContext->pulse.pa_mainloop_iterate)((ma_pa_mainloop*)pDevice->pulse.pMainLoop, 1, NULL); + /* + I have had reports of a deadlock in this part of the code. I have reproduced this when using the "Built-in Audio Analogue Stereo" device without + an actual microphone connected. I'm experimenting here by not blocking in pa_mainloop_iterate() and instead sleep for a bit when there are not + dispatches. + */ + int error = ((ma_pa_mainloop_iterate_proc)pDevice->pContext->pulse.pa_mainloop_iterate)((ma_pa_mainloop*)pDevice->pulse.pMainLoop, 0, NULL); if (error < 0) { return ma_result_from_pulse(error); } + /* Sleep for a bit if nothing was dispatched. */ + if (error == 0) { + ma_sleep(1); + } + continue; } } else { @@ -14873,6 +15053,12 @@ ma_result ma_context_uninit__pulse(ma_context* pContext) ma_assert(pContext != NULL); ma_assert(pContext->backend == ma_backend_pulseaudio); + ma_free(pContext->pulse.pServerName); + pContext->pulse.pServerName = NULL; + + ma_free(pContext->pulse.pApplicationName); + pContext->pulse.pApplicationName = NULL; + #ifndef MA_NO_RUNTIME_LINKING ma_dlclose(pContext->pulse.pulseSO); #endif @@ -14880,7 +15066,7 @@ ma_result ma_context_uninit__pulse(ma_context* pContext) return MA_SUCCESS; } -ma_result ma_context_init__pulse(ma_context* pContext) +ma_result ma_context_init__pulse(const ma_context_config* pConfig, ma_context* pContext) { ma_assert(pContext != NULL); @@ -14983,7 +15169,7 @@ ma_result ma_context_init__pulse(ma_context* pContext) ma_pa_stream_set_read_callback_proc _pa_stream_set_read_callback = pa_stream_set_read_callback; ma_pa_stream_flush_proc _pa_stream_flush = pa_stream_flush; ma_pa_stream_drain_proc _pa_stream_drain = pa_stream_drain; - ma_pa_stream_ic_corked_proc _pa_stream_is_corked = pa_stream_is_corked; + ma_pa_stream_is_corked_proc _pa_stream_is_corked = pa_stream_is_corked; ma_pa_stream_cork_proc _pa_stream_cork = pa_stream_cork; ma_pa_stream_trigger_proc _pa_stream_trigger = pa_stream_trigger; ma_pa_stream_begin_write_proc _pa_stream_begin_write = pa_stream_begin_write; @@ -15050,28 +15236,43 @@ ma_result ma_context_init__pulse(ma_context* pContext) pContext->onDeviceWrite = ma_device_write__pulse; pContext->onDeviceRead = ma_device_read__pulse; + if (pConfig->pulse.pApplicationName) { + pContext->pulse.pApplicationName = ma_copy_string(pConfig->pulse.pApplicationName); + } + if (pConfig->pulse.pServerName) { + pContext->pulse.pServerName = ma_copy_string(pConfig->pulse.pServerName); + } + pContext->pulse.tryAutoSpawn = pConfig->pulse.tryAutoSpawn; // Although we have found the libpulse library, it doesn't necessarily mean PulseAudio is useable. We need to initialize // and connect a dummy PulseAudio context to test PulseAudio's usability. ma_pa_mainloop* pMainLoop = ((ma_pa_mainloop_new_proc)pContext->pulse.pa_mainloop_new)(); if (pMainLoop == NULL) { + ma_free(pContext->pulse.pServerName); + ma_free(pContext->pulse.pApplicationName); return MA_NO_BACKEND; } ma_pa_mainloop_api* pAPI = ((ma_pa_mainloop_get_api_proc)pContext->pulse.pa_mainloop_get_api)(pMainLoop); if (pAPI == NULL) { + ma_free(pContext->pulse.pServerName); + ma_free(pContext->pulse.pApplicationName); ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); return MA_NO_BACKEND; } - ma_pa_context* pPulseContext = ((ma_pa_context_new_proc)pContext->pulse.pa_context_new)(pAPI, pContext->config.pulse.pApplicationName); + ma_pa_context* pPulseContext = ((ma_pa_context_new_proc)pContext->pulse.pa_context_new)(pAPI, pContext->pulse.pApplicationName); if (pPulseContext == NULL) { + ma_free(pContext->pulse.pServerName); + ma_free(pContext->pulse.pApplicationName); ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); return MA_NO_BACKEND; } - int error = ((ma_pa_context_connect_proc)pContext->pulse.pa_context_connect)(pPulseContext, pContext->config.pulse.pServerName, 0, NULL); + int error = ((ma_pa_context_connect_proc)pContext->pulse.pa_context_connect)(pPulseContext, pContext->pulse.pServerName, 0, NULL); if (error != MA_PA_OK) { + ma_free(pContext->pulse.pServerName); + ma_free(pContext->pulse.pApplicationName); ((ma_pa_context_unref_proc)pContext->pulse.pa_context_unref)(pPulseContext); ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); return MA_NO_BACKEND; @@ -15104,15 +15305,15 @@ typedef jack_port_t ma_jack_port_t; typedef JackProcessCallback ma_JackProcessCallback; typedef JackBufferSizeCallback ma_JackBufferSizeCallback; typedef JackShutdownCallback ma_JackShutdownCallback; -#define MA_JACK_DEFAULT_AUDIO_TYPE JACK_DEFAULT_AUDIO_TYPE -#define ma_JackNoStartServer JackNoStartServer -#define ma_JackPortIsInput JackPortIsInput -#define ma_JackPortIsOutput JackPortIsOutput -#define ma_JackPortIsPhysical JackPortIsPhysical +#define MA_JACK_DEFAULT_AUDIO_TYPE JACK_DEFAULT_AUDIO_TYPE +#define ma_JackNoStartServer JackNoStartServer +#define ma_JackPortIsInput JackPortIsInput +#define ma_JackPortIsOutput JackPortIsOutput +#define ma_JackPortIsPhysical JackPortIsPhysical #else typedef ma_uint32 ma_jack_nframes_t; -typedef int ma_jack_options_t; -typedef int ma_jack_status_t; +typedef int ma_jack_options_t; +typedef int ma_jack_status_t; typedef struct ma_jack_client_t ma_jack_client_t; typedef struct ma_jack_port_t ma_jack_port_t; typedef int (* ma_JackProcessCallback) (ma_jack_nframes_t nframes, void* arg); @@ -15126,21 +15327,21 @@ typedef void (* ma_JackShutdownCallback) (void* arg); #endif typedef ma_jack_client_t* (* ma_jack_client_open_proc) (const char* client_name, ma_jack_options_t options, ma_jack_status_t* status, ...); -typedef int (* ma_jack_client_close_proc) (ma_jack_client_t* client); -typedef int (* ma_jack_client_name_size_proc) (); -typedef int (* ma_jack_set_process_callback_proc) (ma_jack_client_t* client, ma_JackProcessCallback process_callback, void* arg); -typedef int (* ma_jack_set_buffer_size_callback_proc)(ma_jack_client_t* client, ma_JackBufferSizeCallback bufsize_callback, void* arg); -typedef void (* ma_jack_on_shutdown_proc) (ma_jack_client_t* client, ma_JackShutdownCallback function, void* arg); +typedef int (* ma_jack_client_close_proc) (ma_jack_client_t* client); +typedef int (* ma_jack_client_name_size_proc) (); +typedef int (* ma_jack_set_process_callback_proc) (ma_jack_client_t* client, ma_JackProcessCallback process_callback, void* arg); +typedef int (* ma_jack_set_buffer_size_callback_proc)(ma_jack_client_t* client, ma_JackBufferSizeCallback bufsize_callback, void* arg); +typedef void (* ma_jack_on_shutdown_proc) (ma_jack_client_t* client, ma_JackShutdownCallback function, void* arg); typedef ma_jack_nframes_t (* ma_jack_get_sample_rate_proc) (ma_jack_client_t* client); typedef ma_jack_nframes_t (* ma_jack_get_buffer_size_proc) (ma_jack_client_t* client); -typedef const char** (* ma_jack_get_ports_proc) (ma_jack_client_t* client, const char* port_name_pattern, const char* type_name_pattern, unsigned long flags); -typedef int (* ma_jack_activate_proc) (ma_jack_client_t* client); -typedef int (* ma_jack_deactivate_proc) (ma_jack_client_t* client); -typedef int (* ma_jack_connect_proc) (ma_jack_client_t* client, const char* source_port, const char* destination_port); +typedef const char** (* ma_jack_get_ports_proc) (ma_jack_client_t* client, const char* port_name_pattern, const char* type_name_pattern, unsigned long flags); +typedef int (* ma_jack_activate_proc) (ma_jack_client_t* client); +typedef int (* ma_jack_deactivate_proc) (ma_jack_client_t* client); +typedef int (* ma_jack_connect_proc) (ma_jack_client_t* client, const char* source_port, const char* destination_port); typedef ma_jack_port_t* (* ma_jack_port_register_proc) (ma_jack_client_t* client, const char* port_name, const char* port_type, unsigned long flags, unsigned long buffer_size); -typedef const char* (* ma_jack_port_name_proc) (const ma_jack_port_t* port); -typedef void* (* ma_jack_port_get_buffer_proc) (ma_jack_port_t* port, ma_jack_nframes_t nframes); -typedef void (* ma_jack_free_proc) (void* ptr); +typedef const char* (* ma_jack_port_name_proc) (const ma_jack_port_t* port); +typedef void* (* ma_jack_port_get_buffer_proc) (ma_jack_port_t* port, ma_jack_nframes_t nframes); +typedef void (* ma_jack_free_proc) (void* ptr); ma_result ma_context_open_client__jack(ma_context* pContext, ma_jack_client_t** ppClient) { @@ -15154,10 +15355,10 @@ ma_result ma_context_open_client__jack(ma_context* pContext, ma_jack_client_t** size_t maxClientNameSize = ((ma_jack_client_name_size_proc)pContext->jack.jack_client_name_size)(); // Includes null terminator. char clientName[256]; - ma_strncpy_s(clientName, ma_min(sizeof(clientName), maxClientNameSize), (pContext->config.jack.pClientName != NULL) ? pContext->config.jack.pClientName : "miniaudio", (size_t)-1); + ma_strncpy_s(clientName, ma_min(sizeof(clientName), maxClientNameSize), (pContext->jack.pClientName != NULL) ? pContext->jack.pClientName : "miniaudio", (size_t)-1); ma_jack_status_t status; - ma_jack_client_t* pClient = ((ma_jack_client_open_proc)pContext->jack.jack_client_open)(clientName, (pContext->config.jack.tryStartServer) ? 0 : ma_JackNoStartServer, &status, NULL); + ma_jack_client_t* pClient = ((ma_jack_client_open_proc)pContext->jack.jack_client_open)(clientName, (pContext->jack.tryStartServer) ? 0 : ma_JackNoStartServer, &status, NULL); if (pClient == NULL) { return MA_FAILED_TO_OPEN_BACKEND_DEVICE; } @@ -15596,6 +15797,9 @@ ma_result ma_context_uninit__jack(ma_context* pContext) ma_assert(pContext != NULL); ma_assert(pContext->backend == ma_backend_jack); + ma_free(pContext->jack.pClientName); + pContext->jack.pClientName = NULL; + #ifndef MA_NO_RUNTIME_LINKING ma_dlclose(pContext->jack.jackSO); #endif @@ -15603,7 +15807,7 @@ ma_result ma_context_uninit__jack(ma_context* pContext) return MA_SUCCESS; } -ma_result ma_context_init__jack(ma_context* pContext) +ma_result ma_context_init__jack(const ma_context_config* pConfig, ma_context* pContext) { ma_assert(pContext != NULL); @@ -15694,12 +15898,17 @@ ma_result ma_context_init__jack(ma_context* pContext) pContext->onDeviceStart = ma_device_start__jack; pContext->onDeviceStop = ma_device_stop__jack; + if (pConfig->jack.pClientName != NULL) { + pContext->jack.pClientName = ma_copy_string(pConfig->jack.pClientName); + } + pContext->jack.tryStartServer = pConfig->jack.tryStartServer; // Getting here means the JACK library is installed, but it doesn't necessarily mean it's usable. We need to quickly test this by connecting // a temporary client. ma_jack_client_t* pDummyClient; ma_result result = ma_context_open_client__jack(pContext, &pDummyClient); if (result != MA_SUCCESS) { + ma_free(pContext->jack.pClientName); return MA_NO_BACKEND; } @@ -17421,7 +17630,7 @@ ma_result ma_device_init_internal__coreaudio(ma_context* pContext, ma_device_typ // Audio unit. - OSStatus status = ((ma_AudioComponentInstanceNew_proc)pContext->coreaudio.AudioComponentInstanceNew)(pContext->coreaudio.component, (AudioUnit*)&pData->audioUnit); + OSStatus status = ((ma_AudioComponentInstanceNew_proc)pContext->coreaudio.AudioComponentInstanceNew)((AudioComponent)pContext->coreaudio.component, (AudioUnit*)&pData->audioUnit); if (status != noErr) { return ma_result_from_OSStatus(status); } @@ -17982,10 +18191,12 @@ ma_result ma_context_uninit__coreaudio(ma_context* pContext) return MA_SUCCESS; } -ma_result ma_context_init__coreaudio(ma_context* pContext) +ma_result ma_context_init__coreaudio(const ma_context_config* pConfig, ma_context* pContext) { ma_assert(pContext != NULL); + (void)pConfig; + #if defined(MA_APPLE_MOBILE) @autoreleasepool { AVAudioSession* pAudioSession = [AVAudioSession sharedInstance]; @@ -18139,13 +18350,13 @@ ma_result ma_context_init__coreaudio(ma_context* pContext) //#include //#endif -#define MA_SIO_DEVANY "default" -#define MA_SIO_PLAY 1 -#define MA_SIO_REC 2 -#define MA_SIO_NENC 8 -#define MA_SIO_NCHAN 8 -#define MA_SIO_NRATE 16 -#define MA_SIO_NCONF 4 +#define MA_SIO_DEVANY "default" +#define MA_SIO_PLAY 1 +#define MA_SIO_REC 2 +#define MA_SIO_NENC 8 +#define MA_SIO_NCHAN 8 +#define MA_SIO_NRATE 16 +#define MA_SIO_NCONF 4 struct ma_sio_hdl; // <-- Opaque @@ -18187,24 +18398,24 @@ struct ma_sio_conf struct ma_sio_cap { struct ma_sio_enc enc[MA_SIO_NENC]; - unsigned int rchan[MA_SIO_NCHAN]; - unsigned int pchan[MA_SIO_NCHAN]; - unsigned int rate[MA_SIO_NRATE]; - int __pad[7]; - unsigned int nconf; - struct ma_sio_conf confs[MA_SIO_NCONF]; + unsigned int rchan[MA_SIO_NCHAN]; + unsigned int pchan[MA_SIO_NCHAN]; + unsigned int rate[MA_SIO_NRATE]; + int __pad[7]; + unsigned int nconf; + struct ma_sio_conf confs[MA_SIO_NCONF]; }; typedef struct ma_sio_hdl* (* ma_sio_open_proc) (const char*, unsigned int, int); -typedef void (* ma_sio_close_proc) (struct ma_sio_hdl*); -typedef int (* ma_sio_setpar_proc) (struct ma_sio_hdl*, struct ma_sio_par*); -typedef int (* ma_sio_getpar_proc) (struct ma_sio_hdl*, struct ma_sio_par*); -typedef int (* ma_sio_getcap_proc) (struct ma_sio_hdl*, struct ma_sio_cap*); -typedef size_t (* ma_sio_write_proc) (struct ma_sio_hdl*, const void*, size_t); -typedef size_t (* ma_sio_read_proc) (struct ma_sio_hdl*, void*, size_t); -typedef int (* ma_sio_start_proc) (struct ma_sio_hdl*); -typedef int (* ma_sio_stop_proc) (struct ma_sio_hdl*); -typedef int (* ma_sio_initpar_proc)(struct ma_sio_par*); +typedef void (* ma_sio_close_proc) (struct ma_sio_hdl*); +typedef int (* ma_sio_setpar_proc) (struct ma_sio_hdl*, struct ma_sio_par*); +typedef int (* ma_sio_getpar_proc) (struct ma_sio_hdl*, struct ma_sio_par*); +typedef int (* ma_sio_getcap_proc) (struct ma_sio_hdl*, struct ma_sio_cap*); +typedef size_t (* ma_sio_write_proc) (struct ma_sio_hdl*, const void*, size_t); +typedef size_t (* ma_sio_read_proc) (struct ma_sio_hdl*, void*, size_t); +typedef int (* ma_sio_start_proc) (struct ma_sio_hdl*); +typedef int (* ma_sio_stop_proc) (struct ma_sio_hdl*); +typedef int (* ma_sio_initpar_proc)(struct ma_sio_par*); ma_format ma_format_from_sio_enc__sndio(unsigned int bits, unsigned int bps, unsigned int sig, unsigned int le, unsigned int msb) { @@ -18575,7 +18786,6 @@ void ma_device_uninit__sndio(ma_device* pDevice) ma_result ma_device_init_handle__sndio(ma_context* pContext, const ma_device_config* pConfig, ma_device_type deviceType, ma_device* pDevice) { - ma_result result; const char* pDeviceName; ma_ptr handle; int openFlags = 0; @@ -18727,7 +18937,7 @@ ma_result ma_device_init_handle__sndio(ma_context* pContext, const ma_device_con internalBufferSizeInFrames = par.appbufsz; if (deviceType == ma_device_type_capture) { - pDevice->sndio.handleCapture = handle; + pDevice->sndio.handleCapture = handle; pDevice->capture.internalFormat = internalFormat; pDevice->capture.internalChannels = internalChannels; pDevice->capture.internalSampleRate = internalSampleRate; @@ -18735,7 +18945,7 @@ ma_result ma_device_init_handle__sndio(ma_context* pContext, const ma_device_con pDevice->capture.internalBufferSizeInFrames = internalBufferSizeInFrames; pDevice->capture.internalPeriods = internalPeriods; } else { - pDevice->sndio.handlePlayback = handle; + pDevice->sndio.handlePlayback = handle; pDevice->playback.internalFormat = internalFormat; pDevice->playback.internalChannels = internalChannels; pDevice->playback.internalSampleRate = internalSampleRate; @@ -18841,10 +19051,12 @@ ma_result ma_context_uninit__sndio(ma_context* pContext) return MA_SUCCESS; } -ma_result ma_context_init__sndio(ma_context* pContext) +ma_result ma_context_init__sndio(const ma_context_config* pConfig, ma_context* pContext) { ma_assert(pContext != NULL); + (void)pConfig; + #ifndef MA_NO_RUNTIME_LINKING // libpulse.so const char* libsndioNames[] = { @@ -19262,7 +19474,7 @@ ma_result ma_device_init_fd__audio4(ma_context* pContext, const ma_device_config { const char* pDefaultDeviceNames[] = { "/dev/audio", - "/dev/audio0" + "/dev/audio0" }; int fd; int fdFlags = 0; @@ -19592,10 +19804,12 @@ ma_result ma_context_uninit__audio4(ma_context* pContext) return MA_SUCCESS; } -ma_result ma_context_init__audio4(ma_context* pContext) +ma_result ma_context_init__audio4(const ma_context_config* pConfig, ma_context* pContext) { ma_assert(pContext != NULL); + (void)pConfig; + pContext->onUninit = ma_context_uninit__audio4; pContext->onDeviceIDEqual = ma_context_is_device_id_equal__audio4; pContext->onEnumDevices = ma_context_enumerate_devices__audio4; @@ -20104,10 +20318,12 @@ ma_result ma_context_uninit__oss(ma_context* pContext) return MA_SUCCESS; } -ma_result ma_context_init__oss(ma_context* pContext) +ma_result ma_context_init__oss(const ma_context_config* pConfig, ma_context* pContext) { ma_assert(pContext != NULL); + (void)pConfig; + /* Try opening a temporary device first so we can get version information. This is closed at the end. */ int fd = ma_open_temp_device__oss(); if (fd == -1) { @@ -20687,10 +20903,11 @@ ma_result ma_context_uninit__aaudio(ma_context* pContext) return MA_SUCCESS; } -ma_result ma_context_init__aaudio(ma_context* pContext) +ma_result ma_context_init__aaudio(const ma_context_config* pConfig, ma_context* pContext) { ma_assert(pContext != NULL); - (void)pContext; + + (void)pConfig; const char* libNames[] = { "libaaudio.so" @@ -21638,10 +21855,11 @@ ma_result ma_context_uninit__opensl(ma_context* pContext) return MA_SUCCESS; } -ma_result ma_context_init__opensl(ma_context* pContext) +ma_result ma_context_init__opensl(const ma_context_config* pConfig, ma_context* pContext) { ma_assert(pContext != NULL); - (void)pContext; + + (void)pConfig; /* Initialize global data first if applicable. */ if (ma_atomic_increment_32(&g_maOpenSLInitCounter) == 1) { @@ -22177,9 +22395,11 @@ ma_result ma_context_uninit__webaudio(ma_context* pContext) return MA_SUCCESS; } -ma_result ma_context_init__webaudio(ma_context* pContext) +ma_result ma_context_init__webaudio(const ma_context_config* pConfig, ma_context* pContext) { ma_assert(pContext != NULL); + + (void)pConfig; /* Here is where our global JavaScript object is initialized. */ int resultFromJS = EM_ASM_INT({ @@ -22757,12 +22977,17 @@ ma_result ma_context_init(const ma_backend backends[], ma_uint32 backendCount, c ma_zero_object(pContext); // Always make sure the config is set first to ensure properties are available as soon as possible. + ma_context_config config; if (pConfig != NULL) { - pContext->config = *pConfig; + config = *pConfig; } else { - pContext->config = ma_context_config_init(); + config = ma_context_config_init(); } + pContext->logCallback = config.logCallback; + pContext->threadPriority = config.threadPriority; + pContext->pUserData = config.pUserData; + // Backend APIs need to be initialized first. This is where external libraries will be loaded and linked. ma_result result = ma_context_init_backend_apis(pContext); if (result != MA_SUCCESS) { @@ -22791,85 +23016,85 @@ ma_result ma_context_init(const ma_backend backends[], ma_uint32 backendCount, c #ifdef MA_HAS_WASAPI case ma_backend_wasapi: { - result = ma_context_init__wasapi(pContext); + result = ma_context_init__wasapi(&config, pContext); } break; #endif #ifdef MA_HAS_DSOUND case ma_backend_dsound: { - result = ma_context_init__dsound(pContext); + result = ma_context_init__dsound(&config, pContext); } break; #endif #ifdef MA_HAS_WINMM case ma_backend_winmm: { - result = ma_context_init__winmm(pContext); + result = ma_context_init__winmm(&config, pContext); } break; #endif #ifdef MA_HAS_ALSA case ma_backend_alsa: { - result = ma_context_init__alsa(pContext); + result = ma_context_init__alsa(&config, pContext); } break; #endif #ifdef MA_HAS_PULSEAUDIO case ma_backend_pulseaudio: { - result = ma_context_init__pulse(pContext); + result = ma_context_init__pulse(&config, pContext); } break; #endif #ifdef MA_HAS_JACK case ma_backend_jack: { - result = ma_context_init__jack(pContext); + result = ma_context_init__jack(&config, pContext); } break; #endif #ifdef MA_HAS_COREAUDIO case ma_backend_coreaudio: { - result = ma_context_init__coreaudio(pContext); + result = ma_context_init__coreaudio(&config, pContext); } break; #endif #ifdef MA_HAS_SNDIO case ma_backend_sndio: { - result = ma_context_init__sndio(pContext); + result = ma_context_init__sndio(&config, pContext); } break; #endif #ifdef MA_HAS_AUDIO4 case ma_backend_audio4: { - result = ma_context_init__audio4(pContext); + result = ma_context_init__audio4(&config, pContext); } break; #endif #ifdef MA_HAS_OSS case ma_backend_oss: { - result = ma_context_init__oss(pContext); + result = ma_context_init__oss(&config, pContext); } break; #endif #ifdef MA_HAS_AAUDIO case ma_backend_aaudio: { - result = ma_context_init__aaudio(pContext); + result = ma_context_init__aaudio(&config, pContext); } break; #endif #ifdef MA_HAS_OPENSL case ma_backend_opensl: { - result = ma_context_init__opensl(pContext); + result = ma_context_init__opensl(&config, pContext); } break; #endif #ifdef MA_HAS_WEBAUDIO case ma_backend_webaudio: { - result = ma_context_init__webaudio(pContext); + result = ma_context_init__webaudio(&config, pContext); } break; #endif #ifdef MA_HAS_NULL case ma_backend_null: { - result = ma_context_init__null(pContext); + result = ma_context_init__null(&config, pContext); } break; #endif @@ -23115,8 +23340,8 @@ ma_result ma_device_init(ma_context* pContext, const ma_device_config* pConfig, pDevice->onStop = config.stopCallback; if (((ma_uintptr)pDevice % sizeof(pDevice)) != 0) { - if (pContext->config.logCallback) { - pContext->config.logCallback(pContext, pDevice, MA_LOG_LEVEL_WARNING, "WARNING: ma_device_init() called for a device that is not properly aligned. Thread safety is not supported."); + if (pContext->logCallback) { + pContext->logCallback(pContext, pDevice, MA_LOG_LEVEL_WARNING, "WARNING: ma_device_init() called for a device that is not properly aligned. Thread safety is not supported."); } } @@ -31467,6 +31692,21 @@ Device REVISION HISTORY ================ +v0.9.3 - 2019-04-19 + - Fix compiler errors on GCC when compiling with -std=c99. + +v0.9.2 - 2019-04-08 + - Add support for per-context user data. + - Fix a potential bug with context configs. + - Fix some bugs with PulseAudio. + +v0.9.1 - 2019-03-17 + - Fix a bug where the output buffer is not getting zeroed out before calling the data callback. This happens when + the device is running in passthrough mode (not doing any data conversion). + - Fix an issue where the data callback is getting called too frequently on the WASAPI and DirectSound backends. + - Fix error on the UWP build. + - Fix a build error on Apple platforms. + v0.9 - 2019-03-06 - Rebranded to "miniaudio". All namespaces have been renamed from "mal" to "ma". - API CHANGE: ma_device_init() and ma_device_config_init() have changed significantly: diff --git a/src/raudio.h b/src/raudio.h index f98d68ff..e8701814 100644 --- a/src/raudio.h +++ b/src/raudio.h @@ -50,8 +50,8 @@ * **********************************************************************************************/ -#ifndef AUDIO_H -#define AUDIO_H +#ifndef RAUDIO_H +#define RAUDIO_H //---------------------------------------------------------------------------------- // Defines and Macros @@ -60,7 +60,6 @@ //---------------------------------------------------------------------------------- // Types and Structures Definition -// NOTE: Below types are required for CAMERA_STANDALONE usage //---------------------------------------------------------------------------------- #ifndef __cplusplus // Boolean type @@ -174,4 +173,4 @@ void SetAudioStreamPitch(AudioStream stream, float pitch); // Set pitch for } #endif -#endif // AUDIO_H \ No newline at end of file +#endif // RAUDIO_H \ No newline at end of file -- cgit v1.2.3 From 2d4c2ff351f0a295d2827c28ca747e3465422094 Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 22 Apr 2019 20:54:50 +0200 Subject: Review rnet errors --- src/raylib.h | 5 --- src/rnet.c | 20 ++++++------ src/rnet.h | 102 +++++++++++++++++++++++++++++++++-------------------------- 3 files changed, 68 insertions(+), 59 deletions(-) (limited to 'src') diff --git a/src/raylib.h b/src/raylib.h index 29850efd..424a9dd7 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -100,11 +100,6 @@ #define MAX_SHADER_LOCATIONS 32 // Maximum number of predefined locations stored in shader struct #define MAX_MATERIAL_MAPS 12 // Maximum number of texture maps stored in shader struct -// Network connection related defines -#define SOCKET_MAX_SOCK_OPTS (4) // Maximum socket options -#define SOCKET_MAX_UDPCHANNELS (32) // Maximum UDP channels -#define SOCKET_MAX_UDPADDRESSES (4) // Maximum bound UDP addresses - // NOTE: MSC C++ compiler does not support compound literals (C99 feature) // Plain structures in C++ (without constructors) can be initialized from { } initializers. #if defined(__cplusplus) diff --git a/src/rnet.c b/src/rnet.c index 07bc5ecc..79a6f07f 100644 --- a/src/rnet.c +++ b/src/rnet.c @@ -42,10 +42,10 @@ #include "raylib.h" -#include // Required for: assert() -#include // Required for: FILE, fopen(), fclose(), fread() -#include // Required for: malloc(), free() -#include // Required for: strcmp(), strncmp() +#include // Required for: assert() +#include // Required for: FILE, fopen(), fclose(), fread() +#include // Required for: malloc(), free() +#include // Required for: strcmp(), strncmp() //---------------------------------------------------------------------------------- // Module defines @@ -272,7 +272,7 @@ static char *SocketErrorCodeToString(int err) { #if defined(_WIN32) static char gaiStrErrorBuffer[GAI_STRERROR_BUFFER_SIZE]; - sprintf(gaiStrErrorBuffer, "%ws", gai_strerror(err)); + sprintf(gaiStrErrorBuffer, "%s", gai_strerror(err)); return gaiStrErrorBuffer; #else return gai_strerror(err); @@ -386,7 +386,7 @@ static bool CreateSocket(SocketConfig *config, SocketResult *outresult) char hoststr[NI_MAXHOST]; char portstr[NI_MAXSERV]; socklen_t client_len = sizeof(struct sockaddr_storage); - int rc = getnameinfo((struct sockaddr *) res->ai_addr, client_len, hoststr, sizeof(hoststr), portstr, sizeof(portstr), NI_NUMERICHOST | NI_NUMERICSERV); + int rc = getnameinfo((struct sockaddr *) res->ai_addr, client_len, hoststr, sizeof(hoststr), portstr, sizeof(portstr), NI_NUMERICHOST | NI_NUMERICSERV); TraceLog(LOG_INFO, "Successfully resolved host %s:%s", hoststr, portstr); } @@ -746,10 +746,10 @@ int ResolveHost(const char *address, const char *service, int addressType, int f hints.ai_family = addressType; // Either IPv4 or IPv6 (ADDRESS_TYPE_IPV4, ADDRESS_TYPE_IPV6) hints.ai_protocol = 0; // Automatically select correct protocol (IPPROTO_TCP), (IPPROTO_UDP) hints.ai_flags = flags; - assert(hints.ai_addrlen == NULL || hints.ai_addrlen == 0); - assert(hints.ai_canonname == NULL || hints.ai_canonname == 0); - assert(hints.ai_addr == NULL || hints.ai_addr == 0); - assert(hints.ai_next == NULL || hints.ai_next == 0); + assert((hints.ai_addrlen == NULL) || (hints.ai_addrlen == 0)); + assert((hints.ai_canonname == NULL) || (hints.ai_canonname == 0)); + assert((hints.ai_addr == NULL) || (hints.ai_addr == 0)); + assert((hints.ai_next == NULL) || (hints.ai_next == 0)); // When the address is NULL, populate the IP for me if (address == NULL) diff --git a/src/rnet.h b/src/rnet.h index a2233a3c..f5dde220 100644 --- a/src/rnet.h +++ b/src/rnet.h @@ -38,6 +38,9 @@ * **********************************************************************************************/ +#ifndef RNET_H +#define RNET_H + #include // Required for limits #include // Required for platform type sizes @@ -168,6 +171,10 @@ typedef int socklen_t; // Network connection related defines #define SOCKET_MAX_SET_SIZE (32) // Maximum sockets in a set #define SOCKET_MAX_QUEUE_SIZE (16) // Maximum socket queue size +#define SOCKET_MAX_SOCK_OPTS (4) // Maximum socket options +#define SOCKET_MAX_UDPCHANNELS (32) // Maximum UDP channels +#define SOCKET_MAX_UDPADDRESSES (4) // Maximum bound UDP addresses + // Network address related defines #define ADDRESS_IPV4_ADDRSTRLEN (22) // IPv4 string length @@ -216,6 +223,13 @@ typedef int socklen_t; // Types and Structures Definition //---------------------------------------------------------------------------------- +// Boolean type +#if defined(__STDC__) && __STDC_VERSION__ >= 199901L + #include +#elif !defined(__cplusplus) && !defined(bool) + typedef enum { false, true } bool; +#endif + // Network typedefs typedef uint32_t SocketChannel; typedef struct _AddressInformation * AddressInformation; @@ -301,7 +315,7 @@ typedef struct SocketResult Socket *socket; } SocketResult; -// +// Packet type typedef struct Packet { uint32_t size; // The total size of bytes in data @@ -325,64 +339,64 @@ extern "C" { // Prevents name mangling of functions //---------------------------------------------------------------------------------- // Initialisation and cleanup -RLAPI bool InitNetwork(void); -RLAPI void CloseNetwork(void); +bool InitNetwork(void); +void CloseNetwork(void); // Address API -RLAPI void ResolveIP(const char *ip, const char *service, int flags, char *outhost, char *outserv); -RLAPI int ResolveHost(const char *address, const char *service, int addressType, int flags, AddressInformation *outAddr); -RLAPI int GetAddressFamily(AddressInformation address); -RLAPI int GetAddressSocketType(AddressInformation address); -RLAPI int GetAddressProtocol(AddressInformation address); -RLAPI char* GetAddressCanonName(AddressInformation address); -RLAPI char* GetAddressHostAndPort(AddressInformation address, char *outhost, int *outport); -RLAPI void PrintAddressInfo(AddressInformation address); +void ResolveIP(const char *ip, const char *service, int flags, char *outhost, char *outserv); +int ResolveHost(const char *address, const char *service, int addressType, int flags, AddressInformation *outAddr); +int GetAddressFamily(AddressInformation address); +int GetAddressSocketType(AddressInformation address); +int GetAddressProtocol(AddressInformation address); +char* GetAddressCanonName(AddressInformation address); +char* GetAddressHostAndPort(AddressInformation address, char *outhost, int *outport); +void PrintAddressInfo(AddressInformation address); // Address Memory API -RLAPI AddressInformation AllocAddress(); -RLAPI void FreeAddress(AddressInformation *addressInfo); -RLAPI AddressInformation *AllocAddressList(int size); +AddressInformation AllocAddress(); +void FreeAddress(AddressInformation *addressInfo); +AddressInformation *AllocAddressList(int size); // Socket API -RLAPI bool SocketCreate(SocketConfig *config, SocketResult *result); -RLAPI bool SocketBind(SocketConfig *config, SocketResult *result); -RLAPI bool SocketListen(SocketConfig *config, SocketResult *result); -RLAPI bool SocketConnect(SocketConfig *config, SocketResult *result); -RLAPI Socket *SocketAccept(Socket *server, SocketConfig *config); +bool SocketCreate(SocketConfig *config, SocketResult *result); +bool SocketBind(SocketConfig *config, SocketResult *result); +bool SocketListen(SocketConfig *config, SocketResult *result); +bool SocketConnect(SocketConfig *config, SocketResult *result); +Socket *SocketAccept(Socket *server, SocketConfig *config); // UDP Socket API -RLAPI int SocketSetChannel(Socket *socket, int channel, const IPAddress *address); -RLAPI void SocketUnsetChannel(Socket *socket, int channel); +int SocketSetChannel(Socket *socket, int channel, const IPAddress *address); +void SocketUnsetChannel(Socket *socket, int channel); // UDP DataPacket API -RLAPI SocketDataPacket *AllocPacket(int size); -RLAPI int ResizePacket(SocketDataPacket *packet, int newsize); -RLAPI void FreePacket(SocketDataPacket *packet); -RLAPI SocketDataPacket **AllocPacketList(int count, int size); -RLAPI void FreePacketList(SocketDataPacket **packets); +SocketDataPacket *AllocPacket(int size); +int ResizePacket(SocketDataPacket *packet, int newsize); +void FreePacket(SocketDataPacket *packet); +SocketDataPacket **AllocPacketList(int count, int size); +void FreePacketList(SocketDataPacket **packets); // General Socket API -RLAPI int SocketSend(Socket *sock, const void *datap, int len); -RLAPI int SocketReceive(Socket *sock, void *data, int maxlen); -RLAPI void SocketClose(Socket *sock); -RLAPI SocketAddressStorage SocketGetPeerAddress(Socket *sock); -RLAPI char* GetSocketAddressHost(SocketAddressStorage storage); -RLAPI short GetSocketAddressPort(SocketAddressStorage storage); +int SocketSend(Socket *sock, const void *datap, int len); +int SocketReceive(Socket *sock, void *data, int maxlen); +void SocketClose(Socket *sock); +SocketAddressStorage SocketGetPeerAddress(Socket *sock); +char* GetSocketAddressHost(SocketAddressStorage storage); +short GetSocketAddressPort(SocketAddressStorage storage); // Socket Memory API -RLAPI Socket *AllocSocket(); -RLAPI void FreeSocket(Socket **sock); -RLAPI SocketResult *AllocSocketResult(); -RLAPI void FreeSocketResult(SocketResult **result); -RLAPI SocketSet *AllocSocketSet(int max); -RLAPI void FreeSocketSet(SocketSet *sockset); +Socket *AllocSocket(); +void FreeSocket(Socket **sock); +SocketResult *AllocSocketResult(); +void FreeSocketResult(SocketResult **result); +SocketSet *AllocSocketSet(int max); +void FreeSocketSet(SocketSet *sockset); // Socket I/O API -RLAPI bool IsSocketReady(Socket *sock); -RLAPI bool IsSocketConnected(Socket *sock); -RLAPI int AddSocket(SocketSet *set, Socket *sock); -RLAPI int RemoveSocket(SocketSet *set, Socket *sock); -RLAPI int CheckSockets(SocketSet *set, unsigned int timeout); +bool IsSocketReady(Socket *sock); +bool IsSocketConnected(Socket *sock); +int AddSocket(SocketSet *set, Socket *sock); +int RemoveSocket(SocketSet *set, Socket *sock); +int CheckSockets(SocketSet *set, unsigned int timeout); // Packet API void PacketSend(Packet *packet); @@ -400,4 +414,4 @@ uint64_t PacketRead64(Packet *packet); } #endif -#endif // RNET_H \ No newline at end of file +#endif // RNET_H \ No newline at end of file -- cgit v1.2.3 From e26cc01ba8262f89b948f56f7479f2c0d46e5287 Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 22 Apr 2019 21:50:45 +0200 Subject: More rnet review to avoid warnings/errors --- src/rnet.c | 3088 ++++++++++++++++++++++++++++++------------------------------ src/rnet.h | 220 ++--- 2 files changed, 1649 insertions(+), 1659 deletions(-) (limited to 'src') diff --git a/src/rnet.c b/src/rnet.c index 79a6f07f..55d4a26a 100644 --- a/src/rnet.c +++ b/src/rnet.c @@ -59,27 +59,27 @@ typedef struct _SocketAddress { - struct sockaddr address; + struct sockaddr address; } _SocketAddress; typedef struct _SocketAddressIPv4 { - struct sockaddr_in address; + struct sockaddr_in address; } _SocketAddressIPv4; typedef struct _SocketAddressIPv6 { - struct sockaddr_in6 address; + struct sockaddr_in6 address; } _SocketAddressIPv6; typedef struct _SocketAddressStorage { - struct sockaddr_storage address; + struct sockaddr_storage address; } _SocketAddressStorage; typedef struct _AddressInformation { - struct addrinfo addr; + struct addrinfo addr; } _AddressInformation; @@ -88,24 +88,24 @@ typedef struct _AddressInformation // Global module forward declarations //---------------------------------------------------------------------------------- -static void PrintSocket(struct sockaddr_storage *addr, const int family, const int socktype, const int protocol); +static void PrintSocket(struct sockaddr_storage *addr, const int family, const int socktype, const int protocol); static const char *SocketAddressToString(struct sockaddr_storage *sockaddr); -static bool IsIPv4Address(const char *ip); -static bool IsIPv6Address(const char *ip); -static void * GetSocketPortPtr(struct sockaddr_storage *sa); -static void * GetSocketAddressPtr(struct sockaddr_storage *sa); -static bool IsSocketValid(Socket *sock); -static void SocketSetLastError(int err); -static int SocketGetLastError(); -static char * SocketGetLastErrorString(); -static char * SocketErrorCodeToString(int err); -static bool SocketSetDefaults(SocketConfig *config); -static bool InitSocket(Socket *sock, struct addrinfo *addr); -static bool CreateSocket(SocketConfig *config, SocketResult *outresult); -static bool SocketSetBlocking(Socket *sock); -static bool SocketSetNonBlocking(Socket *sock); -static bool SocketSetOptions(SocketConfig *config, Socket *sock); -static void SocketSetHints(SocketConfig *config, struct addrinfo *hints); +static bool IsIPv4Address(const char *ip); +static bool IsIPv6Address(const char *ip); +static void *GetSocketPortPtr(struct sockaddr_storage *sa); +static void *GetSocketAddressPtr(struct sockaddr_storage *sa); +static bool IsSocketValid(Socket *sock); +static void SocketSetLastError(int err); +static int SocketGetLastError(); +static char *SocketGetLastErrorString(); +static char *SocketErrorCodeToString(int err); +static bool SocketSetDefaults(SocketConfig *config); +static bool InitSocket(Socket *sock, struct addrinfo *addr); +static bool CreateSocket(SocketConfig *config, SocketResult *outresult); +static bool SocketSetBlocking(Socket *sock); +static bool SocketSetNonBlocking(Socket *sock); +static bool SocketSetOptions(SocketConfig *config, Socket *sock); +static void SocketSetHints(SocketConfig *config, struct addrinfo *hints); //---------------------------------------------------------------------------------- // Global module implementation @@ -114,140 +114,146 @@ static void SocketSetHints(SocketConfig *config, struct addrinfo *hints); // Print socket information static void PrintSocket(struct sockaddr_storage *addr, const int family, const int socktype, const int protocol) { - switch (family) - { - case AF_UNSPEC: { TraceLog(LOG_DEBUG, "\tFamily: Unspecified"); - } - break; - case AF_INET: - { - TraceLog(LOG_DEBUG, "\tFamily: AF_INET (IPv4)"); - TraceLog(LOG_INFO, "\t- IPv4 address %s", SocketAddressToString(addr)); - } - break; - case AF_INET6: - { - TraceLog(LOG_DEBUG, "\tFamily: AF_INET6 (IPv6)"); - TraceLog(LOG_INFO, "\t- IPv6 address %s", SocketAddressToString(addr)); - } - break; - case AF_NETBIOS: - { - TraceLog(LOG_DEBUG, "\tFamily: AF_NETBIOS (NetBIOS)"); - } - break; - default: { TraceLog(LOG_DEBUG, "\tFamily: Other %ld", family); - } - break; - } - TraceLog(LOG_DEBUG, "\tSocket type:"); - switch (socktype) - { - case 0: TraceLog(LOG_DEBUG, "\t- Unspecified"); break; - case SOCK_STREAM: - TraceLog(LOG_DEBUG, "\t- SOCK_STREAM (stream)"); - break; - case SOCK_DGRAM: - TraceLog(LOG_DEBUG, "\t- SOCK_DGRAM (datagram)"); - break; - case SOCK_RAW: TraceLog(LOG_DEBUG, "\t- SOCK_RAW (raw)"); break; - case SOCK_RDM: - TraceLog(LOG_DEBUG, "\t- SOCK_RDM (reliable message datagram)"); - break; - case SOCK_SEQPACKET: - TraceLog(LOG_DEBUG, "\t- SOCK_SEQPACKET (pseudo-stream packet)"); - break; - default: TraceLog(LOG_DEBUG, "\t- Other %ld", socktype); break; - } - TraceLog(LOG_DEBUG, "\tProtocol:"); - switch (protocol) - { - case 0: TraceLog(LOG_DEBUG, "\t- Unspecified"); break; - case IPPROTO_TCP: TraceLog(LOG_DEBUG, "\t- IPPROTO_TCP (TCP)"); break; - case IPPROTO_UDP: TraceLog(LOG_DEBUG, "\t- IPPROTO_UDP (UDP)"); break; - default: TraceLog(LOG_DEBUG, "\t- Other %ld", protocol); break; - } + switch (family) + { + case AF_UNSPEC: { TraceLog(LOG_DEBUG, "\tFamily: Unspecified"); + } + break; + case AF_INET: + { + TraceLog(LOG_DEBUG, "\tFamily: AF_INET (IPv4)"); + TraceLog(LOG_INFO, "\t- IPv4 address %s", SocketAddressToString(addr)); + } + break; + case AF_INET6: + { + TraceLog(LOG_DEBUG, "\tFamily: AF_INET6 (IPv6)"); + TraceLog(LOG_INFO, "\t- IPv6 address %s", SocketAddressToString(addr)); + } + break; + case AF_NETBIOS: + { + TraceLog(LOG_DEBUG, "\tFamily: AF_NETBIOS (NetBIOS)"); + } + break; + default: { TraceLog(LOG_DEBUG, "\tFamily: Other %ld", family); + } + break; + } + TraceLog(LOG_DEBUG, "\tSocket type:"); + switch (socktype) + { + case 0: TraceLog(LOG_DEBUG, "\t- Unspecified"); break; + case SOCK_STREAM: + TraceLog(LOG_DEBUG, "\t- SOCK_STREAM (stream)"); + break; + case SOCK_DGRAM: + TraceLog(LOG_DEBUG, "\t- SOCK_DGRAM (datagram)"); + break; + case SOCK_RAW: TraceLog(LOG_DEBUG, "\t- SOCK_RAW (raw)"); break; + case SOCK_RDM: + TraceLog(LOG_DEBUG, "\t- SOCK_RDM (reliable message datagram)"); + break; + case SOCK_SEQPACKET: + TraceLog(LOG_DEBUG, "\t- SOCK_SEQPACKET (pseudo-stream packet)"); + break; + default: TraceLog(LOG_DEBUG, "\t- Other %ld", socktype); break; + } + TraceLog(LOG_DEBUG, "\tProtocol:"); + switch (protocol) + { + case 0: TraceLog(LOG_DEBUG, "\t- Unspecified"); break; + case IPPROTO_TCP: TraceLog(LOG_DEBUG, "\t- IPPROTO_TCP (TCP)"); break; + case IPPROTO_UDP: TraceLog(LOG_DEBUG, "\t- IPPROTO_UDP (UDP)"); break; + default: TraceLog(LOG_DEBUG, "\t- Other %ld", protocol); break; + } } // Convert network ordered socket address to human readable string (127.0.0.1) static const char *SocketAddressToString(struct sockaddr_storage *sockaddr) { - static const char* ipv6[INET6_ADDRSTRLEN]; - assert(sockaddr != NULL); - assert(sockaddr->ss_family == AF_INET || sockaddr->ss_family == AF_INET6); - switch (sockaddr->ss_family) - { - case AF_INET: - { - struct sockaddr_in *s = ((struct sockaddr_in *) sockaddr); - return inet_ntop(AF_INET, &s->sin_addr, ipv6, INET_ADDRSTRLEN); - } - break; - case AF_INET6: - { - struct sockaddr_in6 *s = ((struct sockaddr_in6 *) sockaddr); - return inet_ntop(AF_INET6, &s->sin6_addr, ipv6, INET6_ADDRSTRLEN); - } - break; - } - return NULL; + //static const char* ipv6[INET6_ADDRSTRLEN]; + assert(sockaddr != NULL); + assert(sockaddr->ss_family == AF_INET || sockaddr->ss_family == AF_INET6); + switch (sockaddr->ss_family) + { + case AF_INET: + { + //struct sockaddr_in *s = ((struct sockaddr_in *) sockaddr); + //return inet_ntop(AF_INET, &s->sin_addr, ipv6, INET_ADDRSTRLEN); // TODO. + } + break; + case AF_INET6: + { + //struct sockaddr_in6 *s = ((struct sockaddr_in6 *) sockaddr); + //return inet_ntop(AF_INET6, &s->sin6_addr, ipv6, INET6_ADDRSTRLEN); // TODO. + } + break; + } + return NULL; } // Check if the null terminated string ip is a valid IPv4 address static bool IsIPv4Address(const char *ip) { - struct sockaddr_in sa; - int result = inet_pton(AF_INET, ip, &(sa.sin_addr)); - return result != 0; + /* + struct sockaddr_in sa; + int result = inet_pton(AF_INET, ip, &(sa.sin_addr)); // TODO. + return (result != 0); + */ + return false; } // Check if the null terminated string ip is a valid IPv6 address static bool IsIPv6Address(const char *ip) { - struct sockaddr_in6 sa; - int result = inet_pton(AF_INET6, ip, &(sa.sin6_addr)); - return result != 0; + /* + struct sockaddr_in6 sa; + int result = inet_pton(AF_INET6, ip, &(sa.sin6_addr)); // TODO. + return result != 0; + */ + return false; } // Return a pointer to the port from the correct address family (IPv4, or IPv6) static void *GetSocketPortPtr(struct sockaddr_storage *sa) { - if (sa->ss_family == AF_INET) - { - return &(((struct sockaddr_in *) sa)->sin_port); - } + if (sa->ss_family == AF_INET) + { + return &(((struct sockaddr_in *) sa)->sin_port); + } - return &(((struct sockaddr_in6 *) sa)->sin6_port); + return &(((struct sockaddr_in6 *) sa)->sin6_port); } // Return a pointer to the address from the correct address family (IPv4, or IPv6) static void *GetSocketAddressPtr(struct sockaddr_storage *sa) { - if (sa->ss_family == AF_INET) - { - return &(((struct sockaddr_in *) sa)->sin_addr); - } + if (sa->ss_family == AF_INET) + { + return &(((struct sockaddr_in *) sa)->sin_addr); + } - return &(((struct sockaddr_in6 *) sa)->sin6_addr); + return &(((struct sockaddr_in6 *) sa)->sin6_addr); } // Is the socket in a valid state? static bool IsSocketValid(Socket *sock) { - if (sock != NULL) - { - return (sock->channel != INVALID_SOCKET); - } - return false; + if (sock != NULL) + { + return (sock->channel != INVALID_SOCKET); + } + return false; } // Sets the error code that can be retrieved through the WSAGetLastError function. static void SocketSetLastError(int err) { #if defined(_WIN32) - WSASetLastError(err); + WSASetLastError(err); #else - errno = err; + errno = err; #endif } @@ -255,1059 +261,1055 @@ static void SocketSetLastError(int err) static int SocketGetLastError() { #if defined(_WIN32) - return WSAGetLastError(); + return WSAGetLastError(); #else - return errno; + return errno; #endif } // Returns a human-readable string representing the last error message static char *SocketGetLastErrorString() { - return SocketErrorCodeToString(SocketGetLastError()); + return SocketErrorCodeToString(SocketGetLastError()); } // Returns a human-readable string representing the error message (err) static char *SocketErrorCodeToString(int err) { #if defined(_WIN32) - static char gaiStrErrorBuffer[GAI_STRERROR_BUFFER_SIZE]; - sprintf(gaiStrErrorBuffer, "%s", gai_strerror(err)); - return gaiStrErrorBuffer; + static char gaiStrErrorBuffer[GAI_STRERROR_BUFFER_SIZE]; + sprintf(gaiStrErrorBuffer, "%s", gai_strerror(err)); + return gaiStrErrorBuffer; #else - return gai_strerror(err); + return gai_strerror(err); #endif } // Set the defaults in the supplied SocketConfig if they're not already set static bool SocketSetDefaults(SocketConfig *config) { - if (config->backlog_size == 0) - { - config->backlog_size = SOCKET_MAX_QUEUE_SIZE; - } + if (config->backlog_size == 0) + { + config->backlog_size = SOCKET_MAX_QUEUE_SIZE; + } - return true; + return true; } // Create the socket channel static bool InitSocket(Socket *sock, struct addrinfo *addr) { - switch (sock->type) - { - case SOCKET_TCP: - if (addr->ai_family == AF_INET) - { - sock->channel = socket(AF_INET, SOCK_STREAM, 0); - } - else - { - sock->channel = socket(AF_INET6, SOCK_STREAM, 0); - } - break; - case SOCKET_UDP: - if (addr->ai_family == AF_INET) - { - sock->channel = socket(AF_INET, SOCK_DGRAM, 0); - } - else - { - sock->channel = socket(AF_INET6, SOCK_DGRAM, 0); - } - break; - default: - TraceLog(LOG_WARNING, "Invalid socket type specified."); - break; - } - return IsSocketValid(sock); -} - -// CreateSocket() - Interally called by CreateSocket() + switch (sock->type) + { + case SOCKET_TCP: + if (addr->ai_family == AF_INET) + { + sock->channel = socket(AF_INET, SOCK_STREAM, 0); + } + else + { + sock->channel = socket(AF_INET6, SOCK_STREAM, 0); + } + break; + case SOCKET_UDP: + if (addr->ai_family == AF_INET) + { + sock->channel = socket(AF_INET, SOCK_DGRAM, 0); + } + else + { + sock->channel = socket(AF_INET6, SOCK_DGRAM, 0); + } + break; + default: + TraceLog(LOG_WARNING, "Invalid socket type specified."); + break; + } + return IsSocketValid(sock); +} + +// CreateSocket() - Interally called by CreateSocket() // -// This here is the bread and butter of the socket API, This function will -// attempt to open a socket, bind and listen to it based on the config passed in +// This here is the bread and butter of the socket API, This function will +// attempt to open a socket, bind and listen to it based on the config passed in // -// SocketConfig* config - Configuration for which socket to open -// SocketResult* result - The results of this function (if any, including errors) +// SocketConfig* config - Configuration for which socket to open +// SocketResult* result - The results of this function (if any, including errors) // -// e.g. -// SocketConfig server_config = { SocketConfig client_config = { -// .host = "127.0.0.1", .host = "127.0.0.1", -// .port = 8080, .port = 8080, -// .server = true, }; -// .nonblocking = true, -// }; -// SocketResult server_res; SocketResult client_res; +// e.g. +// SocketConfig server_config = { SocketConfig client_config = { +// .host = "127.0.0.1", .host = "127.0.0.1", +// .port = 8080, .port = 8080, +// .server = true, }; +// .nonblocking = true, +// }; +// SocketResult server_res; SocketResult client_res; static bool CreateSocket(SocketConfig *config, SocketResult *outresult) { - bool success = true; - int addrstatus; - struct addrinfo hints; // Address flags (IPV4, IPV6, UDP?) - struct addrinfo *res; // A pointer to the resulting address list - outresult->socket->channel = INVALID_SOCKET; - outresult->status = RESULT_FAILURE; - - // Set the socket type - outresult->socket->type = config->type; - - // Set the hints based on information in the config - // - // AI_CANONNAME Causes the ai_canonname of the result to the filled out with the host's canonical (real) name. - // AI_PASSIVE: Causes the result's IP address to be filled out with INADDR_ANY (IPv4)or in6addr_any (IPv6); - // Note: This causes a subsequent call to bind() to auto-fill the IP address - // of the struct sockaddr with the address of the current host. - // - SocketSetHints(config, &hints); - - // Populate address information - addrstatus = getaddrinfo(config->host, // e.g. "www.example.com" or IP (Can be null if AI_PASSIVE flag is set - config->port, // e.g. "http" or port number - &hints, // e.g. SOCK_STREAM/SOCK_DGRAM - &res // The struct to populate - ); - - // Did we succeed? - if (addrstatus != 0) - { - outresult->socket->status = SocketGetLastError(); - TraceLog(LOG_WARNING, - "Socket Error: %s", - SocketErrorCodeToString(outresult->socket->status)); - SocketSetLastError(0); - TraceLog(LOG_WARNING, - "Failed to get resolve host %s:%s: %s", - config->host, - config->port, - SocketGetLastErrorString()); - return (success = false); - } - else - { - char hoststr[NI_MAXHOST]; - char portstr[NI_MAXSERV]; - socklen_t client_len = sizeof(struct sockaddr_storage); - int rc = getnameinfo((struct sockaddr *) res->ai_addr, client_len, hoststr, sizeof(hoststr), portstr, sizeof(portstr), NI_NUMERICHOST | NI_NUMERICSERV); - TraceLog(LOG_INFO, "Successfully resolved host %s:%s", hoststr, portstr); - } - - // Walk the address information linked-list - struct addrinfo *it; - for (it = res; it != NULL; it = it->ai_next) - { - // Initialise the socket - if (!InitSocket(outresult->socket, it)) - { - outresult->socket->status = SocketGetLastError(); - TraceLog(LOG_WARNING, - "Socket Error: %s", - SocketErrorCodeToString(outresult->socket->status)); - SocketSetLastError(0); - continue; - } - - // Set socket options - if (!SocketSetOptions(config, outresult->socket)) - { - outresult->socket->status = SocketGetLastError(); - TraceLog(LOG_WARNING, - "Socket Error: %s", - SocketErrorCodeToString(outresult->socket->status)); - SocketSetLastError(0); - freeaddrinfo(res); - return (success = false); - } - } - - if (!IsSocketValid(outresult->socket)) - { - outresult->socket->status = SocketGetLastError(); - TraceLog( - LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(outresult->status)); - SocketSetLastError(0); - freeaddrinfo(res); - return (success = false); - } - - if (success) - { - outresult->status = RESULT_SUCCESS; - outresult->socket->ready = 0; - outresult->socket->status = 0; - if (!(config->type == SOCKET_UDP)) - { - outresult->socket->isServer = config->server; - } - switch (res->ai_addr->sa_family) - { - case AF_INET: - { - outresult->socket->addripv4 = (struct _SocketAddressIPv4 *) malloc( - sizeof(*outresult->socket->addripv4)); - if (outresult->socket->addripv4 != NULL) - { - memset(outresult->socket->addripv4, 0, - sizeof(*outresult->socket->addripv4)); - if (outresult->socket->addripv4 != NULL) - { - memcpy(&outresult->socket->addripv4->address, - (struct sockaddr_in *) res->ai_addr, sizeof(struct sockaddr_in)); - outresult->socket->isIPv6 = false; - char hoststr[NI_MAXHOST]; - char portstr[NI_MAXSERV]; - socklen_t client_len = sizeof(struct sockaddr_storage); - getnameinfo( - (struct sockaddr *) &outresult->socket->addripv4->address, client_len, hoststr, sizeof(hoststr), portstr, sizeof(portstr), NI_NUMERICHOST | NI_NUMERICSERV); - TraceLog(LOG_INFO, "Socket address set to %s:%s", hoststr, portstr); - } - } - } - break; - case AF_INET6: - { - outresult->socket->addripv6 = (struct _SocketAddressIPv6 *) malloc( - sizeof(*outresult->socket->addripv6)); - if (outresult->socket->addripv6 != NULL) - { - memset(outresult->socket->addripv6, 0, - sizeof(*outresult->socket->addripv6)); - if (outresult->socket->addripv6 != NULL) - { - memcpy(&outresult->socket->addripv6->address, - (struct sockaddr_in6 *) res->ai_addr, sizeof(struct sockaddr_in6)); - outresult->socket->isIPv6 = true; - char hoststr[NI_MAXHOST]; - char portstr[NI_MAXSERV]; - socklen_t client_len = sizeof(struct sockaddr_storage); - getnameinfo( - (struct sockaddr *) &outresult->socket->addripv6->address, client_len, hoststr, sizeof(hoststr), portstr, sizeof(portstr), NI_NUMERICHOST | NI_NUMERICSERV); - TraceLog(LOG_INFO, "Socket address set to %s:%s", hoststr, portstr); - } - } - } - break; - } - } - freeaddrinfo(res); - return success; + bool success = true; + int addrstatus; + struct addrinfo hints; // Address flags (IPV4, IPV6, UDP?) + struct addrinfo *res; // A pointer to the resulting address list + outresult->socket->channel = INVALID_SOCKET; + outresult->status = RESULT_FAILURE; + + // Set the socket type + outresult->socket->type = config->type; + + // Set the hints based on information in the config + // + // AI_CANONNAME Causes the ai_canonname of the result to the filled out with the host's canonical (real) name. + // AI_PASSIVE: Causes the result's IP address to be filled out with INADDR_ANY (IPv4)or in6addr_any (IPv6); + // Note: This causes a subsequent call to bind() to auto-fill the IP address + // of the struct sockaddr with the address of the current host. + // + SocketSetHints(config, &hints); + + // Populate address information + addrstatus = getaddrinfo(config->host, // e.g. "www.example.com" or IP (Can be null if AI_PASSIVE flag is set + config->port, // e.g. "http" or port number + &hints, // e.g. SOCK_STREAM/SOCK_DGRAM + &res // The struct to populate + ); + + // Did we succeed? + if (addrstatus != 0) + { + outresult->socket->status = SocketGetLastError(); + TraceLog(LOG_WARNING, + "Socket Error: %s", + SocketErrorCodeToString(outresult->socket->status)); + SocketSetLastError(0); + TraceLog(LOG_WARNING, + "Failed to get resolve host %s:%s: %s", + config->host, + config->port, + SocketGetLastErrorString()); + return (success = false); + } + else + { + char hoststr[NI_MAXHOST]; + char portstr[NI_MAXSERV]; + //socklen_t client_len = sizeof(struct sockaddr_storage); + //int rc = getnameinfo((struct sockaddr *) res->ai_addr, client_len, hoststr, sizeof(hoststr), portstr, sizeof(portstr), NI_NUMERICHOST | NI_NUMERICSERV); + TraceLog(LOG_INFO, "Successfully resolved host %s:%s", hoststr, portstr); + } + + // Walk the address information linked-list + struct addrinfo *it; + for (it = res; it != NULL; it = it->ai_next) + { + // Initialise the socket + if (!InitSocket(outresult->socket, it)) + { + outresult->socket->status = SocketGetLastError(); + TraceLog(LOG_WARNING, + "Socket Error: %s", + SocketErrorCodeToString(outresult->socket->status)); + SocketSetLastError(0); + continue; + } + + // Set socket options + if (!SocketSetOptions(config, outresult->socket)) + { + outresult->socket->status = SocketGetLastError(); + TraceLog(LOG_WARNING, + "Socket Error: %s", + SocketErrorCodeToString(outresult->socket->status)); + SocketSetLastError(0); + freeaddrinfo(res); + return (success = false); + } + } + + if (!IsSocketValid(outresult->socket)) + { + outresult->socket->status = SocketGetLastError(); + TraceLog( + LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(outresult->status)); + SocketSetLastError(0); + freeaddrinfo(res); + return (success = false); + } + + if (success) + { + outresult->status = RESULT_SUCCESS; + outresult->socket->ready = 0; + outresult->socket->status = 0; + if (!(config->type == SOCKET_UDP)) + { + outresult->socket->isServer = config->server; + } + switch (res->ai_addr->sa_family) + { + case AF_INET: + { + outresult->socket->addripv4 = (struct _SocketAddressIPv4 *) malloc( + sizeof(*outresult->socket->addripv4)); + if (outresult->socket->addripv4 != NULL) + { + memset(outresult->socket->addripv4, 0, + sizeof(*outresult->socket->addripv4)); + if (outresult->socket->addripv4 != NULL) + { + memcpy(&outresult->socket->addripv4->address, + (struct sockaddr_in *) res->ai_addr, sizeof(struct sockaddr_in)); + outresult->socket->isIPv6 = false; + char hoststr[NI_MAXHOST]; + char portstr[NI_MAXSERV]; + socklen_t client_len = sizeof(struct sockaddr_storage); + getnameinfo( + (struct sockaddr *) &outresult->socket->addripv4->address, client_len, hoststr, sizeof(hoststr), portstr, sizeof(portstr), NI_NUMERICHOST | NI_NUMERICSERV); + TraceLog(LOG_INFO, "Socket address set to %s:%s", hoststr, portstr); + } + } + } + break; + case AF_INET6: + { + outresult->socket->addripv6 = (struct _SocketAddressIPv6 *) malloc( + sizeof(*outresult->socket->addripv6)); + if (outresult->socket->addripv6 != NULL) + { + memset(outresult->socket->addripv6, 0, + sizeof(*outresult->socket->addripv6)); + if (outresult->socket->addripv6 != NULL) + { + memcpy(&outresult->socket->addripv6->address, + (struct sockaddr_in6 *) res->ai_addr, sizeof(struct sockaddr_in6)); + outresult->socket->isIPv6 = true; + char hoststr[NI_MAXHOST]; + char portstr[NI_MAXSERV]; + socklen_t client_len = sizeof(struct sockaddr_storage); + getnameinfo( + (struct sockaddr *) &outresult->socket->addripv6->address, client_len, hoststr, sizeof(hoststr), portstr, sizeof(portstr), NI_NUMERICHOST | NI_NUMERICSERV); + TraceLog(LOG_INFO, "Socket address set to %s:%s", hoststr, portstr); + } + } + } + break; + } + } + freeaddrinfo(res); + return success; } // Set the state of the Socket sock to blocking static bool SocketSetBlocking(Socket *sock) { - bool ret = true; + bool ret = true; #if defined(_WIN32) - unsigned long mode = 0; - ret = ioctlsocket(sock->channel, FIONBIO, &mode); + unsigned long mode = 0; + ret = ioctlsocket(sock->channel, FIONBIO, &mode); #else - const int flags = fcntl(sock->channel, F_GETFL, 0); - if (!(flags & O_NONBLOCK)) - { - TraceLog(LOG_DEBUG, "Socket was already in blocking mode"); - return ret; - } - - ret = (0 == fcntl(sock->channel, F_SETFL, (flags ^ O_NONBLOCK))); + const int flags = fcntl(sock->channel, F_GETFL, 0); + if (!(flags & O_NONBLOCK)) + { + TraceLog(LOG_DEBUG, "Socket was already in blocking mode"); + return ret; + } + + ret = (0 == fcntl(sock->channel, F_SETFL, (flags ^ O_NONBLOCK))); #endif - return ret; + return ret; } // Set the state of the Socket sock to non-blocking static bool SocketSetNonBlocking(Socket *sock) { - bool ret = true; + bool ret = true; #if defined(_WIN32) - unsigned long mode = 1; - ret = ioctlsocket(sock->channel, FIONBIO, &mode); + unsigned long mode = 1; + ret = ioctlsocket(sock->channel, FIONBIO, &mode); #else - const int flags = fcntl(sock->channel, F_GETFL, 0); - if ((flags & O_NONBLOCK)) - { - TraceLog(LOG_DEBUG, "Socket was already in non-blocking mode"); - return ret; - } - ret = (0 == fcntl(sock->channel, F_SETFL, (flags | O_NONBLOCK))); + const int flags = fcntl(sock->channel, F_GETFL, 0); + if ((flags & O_NONBLOCK)) + { + TraceLog(LOG_DEBUG, "Socket was already in non-blocking mode"); + return ret; + } + ret = (0 == fcntl(sock->channel, F_SETFL, (flags | O_NONBLOCK))); #endif - return ret; + return ret; } // Set options specified in SocketConfig to Socket sock static bool SocketSetOptions(SocketConfig *config, Socket *sock) { - for (int i = 0; i < SOCKET_MAX_SOCK_OPTS; i++) - { - SocketOpt *opt = &config->sockopts[i]; - if (opt->id == 0) - { - break; - } + for (int i = 0; i < SOCKET_MAX_SOCK_OPTS; i++) + { + SocketOpt *opt = &config->sockopts[i]; + if (opt->id == 0) + { + break; + } - if (setsockopt(sock->channel, SOL_SOCKET, opt->id, opt->value, opt->valueLen) < 0) - { - return false; - } - } + if (setsockopt(sock->channel, SOL_SOCKET, opt->id, opt->value, opt->valueLen) < 0) + { + return false; + } + } - return true; + return true; } // Set "hints" in an addrinfo struct, to be passed to getaddrinfo. static void SocketSetHints(SocketConfig *config, struct addrinfo *hints) { - if (config == NULL || hints == NULL) - { - return; - } - memset(hints, 0, sizeof(*hints)); - - // Check if the ip supplied in the config is a valid ipv4 ip ipv6 address - if (IsIPv4Address(config->host)) - { - hints->ai_family = AF_INET; - hints->ai_flags |= AI_NUMERICHOST; - } - else - { - if (IsIPv6Address(config->host)) - { - hints->ai_family = AF_INET6; - hints->ai_flags |= AI_NUMERICHOST; - } - else - { - hints->ai_family = AF_UNSPEC; - } - } - - if (config->type == SOCKET_UDP) - { - hints->ai_socktype = SOCK_DGRAM; - } - else - { - hints->ai_socktype = SOCK_STREAM; - } - - // Set passive unless UDP client - if (!(config->type == SOCKET_UDP) || config->server) - { - hints->ai_flags = AI_PASSIVE; - } + if (config == NULL || hints == NULL) + { + return; + } + memset(hints, 0, sizeof(*hints)); + + // Check if the ip supplied in the config is a valid ipv4 ip ipv6 address + if (IsIPv4Address(config->host)) + { + hints->ai_family = AF_INET; + hints->ai_flags |= AI_NUMERICHOST; + } + else + { + if (IsIPv6Address(config->host)) + { + hints->ai_family = AF_INET6; + hints->ai_flags |= AI_NUMERICHOST; + } + else + { + hints->ai_family = AF_UNSPEC; + } + } + + if (config->type == SOCKET_UDP) + { + hints->ai_socktype = SOCK_DGRAM; + } + else + { + hints->ai_socktype = SOCK_STREAM; + } + + // Set passive unless UDP client + if (!(config->type == SOCKET_UDP) || config->server) + { + hints->ai_flags = AI_PASSIVE; + } } //---------------------------------------------------------------------------------- // Module implementation //---------------------------------------------------------------------------------- -// Initialise the network (requires for windows platforms only) +// Initialise the network (requires for windows platforms only) bool InitNetwork() { #if defined(_WIN32) - WORD wVersionRequested; - WSADATA wsaData; - int err; - - wVersionRequested = MAKEWORD(2, 2); - err = WSAStartup(wVersionRequested, &wsaData); - if (err != 0) - { - TraceLog(LOG_WARNING, "WinSock failed to initialise."); - return false; - } - else - { - TraceLog(LOG_INFO, "WinSock initialised."); - } - - if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) - { - TraceLog(LOG_WARNING, "WinSock failed to initialise."); - WSACleanup(); - return false; - } - - return true; + WORD wVersionRequested; + WSADATA wsaData; + int err; + + wVersionRequested = MAKEWORD(2, 2); + err = WSAStartup(wVersionRequested, &wsaData); + if (err != 0) + { + TraceLog(LOG_WARNING, "WinSock failed to initialise."); + return false; + } + else + { + TraceLog(LOG_INFO, "WinSock initialised."); + } + + if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) + { + TraceLog(LOG_WARNING, "WinSock failed to initialise."); + WSACleanup(); + return false; + } + + return true; #else - return true; + return true; #endif } -// Cleanup, and close the network +// Cleanup, and close the network void CloseNetwork() { #if defined(_WIN32) - WSACleanup(); + WSACleanup(); #endif } -// Protocol-independent name resolution from an address to an ANSI host name -// and from a port number to the ANSI service name. +// Protocol-independent name resolution from an address to an ANSI host name +// and from a port number to the ANSI service name. // -// The flags parameter can be used to customize processing of the getnameinfo function +// The flags parameter can be used to customize processing of the getnameinfo function // -// The following flags are available: +// The following flags are available: // -// NAME_INFO_DEFAULT 0x00 // No flags set -// NAME_INFO_NOFQDN 0x01 // Only return nodename portion for local hosts -// NAME_INFO_NUMERICHOST 0x02 // Return numeric form of the host's address -// NAME_INFO_NAMEREQD 0x04 // Error if the host's name not in DNS -// NAME_INFO_NUMERICSERV 0x08 // Return numeric form of the service (port #) -// NAME_INFO_DGRAM 0x10 // Service is a datagram service +// NAME_INFO_DEFAULT 0x00 // No flags set +// NAME_INFO_NOFQDN 0x01 // Only return nodename portion for local hosts +// NAME_INFO_NUMERICHOST 0x02 // Return numeric form of the host's address +// NAME_INFO_NAMEREQD 0x04 // Error if the host's name not in DNS +// NAME_INFO_NUMERICSERV 0x08 // Return numeric form of the service (port #) +// NAME_INFO_DGRAM 0x10 // Service is a datagram service void ResolveIP(const char *ip, const char *port, int flags, char *host, char *serv) { - // Variables - int status; // Status value to return (0) is success - struct addrinfo hints; // Address flags (IPV4, IPV6, UDP?) - struct addrinfo *res; // A pointer to the resulting address list - - // Set the hints - memset(&hints, 0, sizeof hints); - hints.ai_family = AF_UNSPEC; // Either IPv4 or IPv6 (AF_INET, AF_INET6) - hints.ai_protocol = 0; // Automatically select correct protocol (IPPROTO_TCP), (IPPROTO_UDP) - - // Populate address information - status = getaddrinfo(ip, // e.g. "www.example.com" or IP - port, // e.g. "http" or port number - &hints, // e.g. SOCK_STREAM/SOCK_DGRAM - &res // The struct to populate - ); - - // Did we succeed? - if (status != 0) - { - TraceLog(LOG_WARNING, "Failed to get resolve host %s:%s: %s", ip, port, gai_strerror(errno)); - } - else - { - TraceLog(LOG_DEBUG, "Resolving... %s::%s", ip, port); - } - - // Attempt to resolve network byte order ip to hostname - switch (res->ai_family) - { - case AF_INET: - status = getnameinfo(&*((struct sockaddr *) res->ai_addr), - sizeof(*((struct sockaddr_in *) res->ai_addr)), - host, - NI_MAXHOST, - serv, - NI_MAXSERV, - flags); - break; - case AF_INET6: - status = getnameinfo(&*((struct sockaddr_in6 *) res->ai_addr), - sizeof(*((struct sockaddr_in6 *) res->ai_addr)), - host, - NI_MAXHOST, - serv, - NI_MAXSERV, - flags); - break; - default: break; - } - - if (status != 0) - { - TraceLog(LOG_WARNING, "Failed to resolve ip %s: %s", ip, SocketGetLastErrorString()); - } - else - { - TraceLog(LOG_DEBUG, "Successfully resolved %s::%s to %s", ip, port, host); - } - - // Free the pointer to the data returned by addrinfo - freeaddrinfo(res); -} - -// Protocol-independent translation from an ANSI host name to an address + // Variables + int status; // Status value to return (0) is success + struct addrinfo hints; // Address flags (IPV4, IPV6, UDP?) + struct addrinfo *res; // A pointer to the resulting address list + + // Set the hints + memset(&hints, 0, sizeof hints); + hints.ai_family = AF_UNSPEC; // Either IPv4 or IPv6 (AF_INET, AF_INET6) + hints.ai_protocol = 0; // Automatically select correct protocol (IPPROTO_TCP), (IPPROTO_UDP) + + // Populate address information + status = getaddrinfo(ip, // e.g. "www.example.com" or IP + port, // e.g. "http" or port number + &hints, // e.g. SOCK_STREAM/SOCK_DGRAM + &res // The struct to populate + ); + + // Did we succeed? + if (status != 0) + { + TraceLog(LOG_WARNING, "Failed to get resolve host %s:%s: %s", ip, port, gai_strerror(errno)); + } + else + { + TraceLog(LOG_DEBUG, "Resolving... %s::%s", ip, port); + } + + // Attempt to resolve network byte order ip to hostname + switch (res->ai_family) + { + case AF_INET: + status = getnameinfo(&*((struct sockaddr *) res->ai_addr), + sizeof(*((struct sockaddr_in *) res->ai_addr)), + host, + NI_MAXHOST, + serv, + NI_MAXSERV, + flags); + break; + case AF_INET6: + /* + status = getnameinfo(&*((struct sockaddr_in6 *) res->ai_addr), // TODO. + sizeof(*((struct sockaddr_in6 *) res->ai_addr)), + host, NI_MAXHOST, serv, NI_MAXSERV, flags); + */ + break; + default: break; + } + + if (status != 0) + { + TraceLog(LOG_WARNING, "Failed to resolve ip %s: %s", ip, SocketGetLastErrorString()); + } + else + { + TraceLog(LOG_DEBUG, "Successfully resolved %s::%s to %s", ip, port, host); + } + + // Free the pointer to the data returned by addrinfo + freeaddrinfo(res); +} + +// Protocol-independent translation from an ANSI host name to an address // -// e.g. -// const char* address = "127.0.0.1" (local address) -// const char* port = "80" +// e.g. +// const char* address = "127.0.0.1" (local address) +// const char* port = "80" // // Parameters: // const char* address - A pointer to a NULL-terminated ANSI string that contains a host (node) name or a numeric host address string. // const char* service - A pointer to a NULL-terminated ANSI string that contains either a service name or port number represented as a string. // -// Returns: -// The total amount of addresses found, -1 on error +// Returns: +// The total amount of addresses found, -1 on error // int ResolveHost(const char *address, const char *service, int addressType, int flags, AddressInformation *outAddr) { - // Variables - int status; // Status value to return (0) is success - struct addrinfo hints; // Address flags (IPV4, IPV6, UDP?) - struct addrinfo *res; // will point to the results - struct addrinfo *iterator; - assert(((address != NULL || address != 0) || (service != NULL || service != 0))); - assert(((addressType == AF_INET) || (addressType == AF_INET6) || (addressType == AF_UNSPEC))); - - // Set the hints - memset(&hints, 0, sizeof hints); - hints.ai_family = addressType; // Either IPv4 or IPv6 (ADDRESS_TYPE_IPV4, ADDRESS_TYPE_IPV6) - hints.ai_protocol = 0; // Automatically select correct protocol (IPPROTO_TCP), (IPPROTO_UDP) - hints.ai_flags = flags; - assert((hints.ai_addrlen == NULL) || (hints.ai_addrlen == 0)); - assert((hints.ai_canonname == NULL) || (hints.ai_canonname == 0)); - assert((hints.ai_addr == NULL) || (hints.ai_addr == 0)); - assert((hints.ai_next == NULL) || (hints.ai_next == 0)); - - // When the address is NULL, populate the IP for me - if (address == NULL) - { - if ((hints.ai_flags & AI_PASSIVE) == 0) - { - hints.ai_flags |= AI_PASSIVE; - } - } - - TraceLog(LOG_INFO, "Resolving host..."); - - // Populate address information - status = getaddrinfo(address, // e.g. "www.example.com" or IP - service, // e.g. "http" or port number - &hints, // e.g. SOCK_STREAM/SOCK_DGRAM - &res // The struct to populate - ); - - // Did we succeed? - if (status != 0) - { - int error = SocketGetLastError(); - SocketSetLastError(0); - TraceLog(LOG_WARNING, "Failed to get resolve host: %s", SocketErrorCodeToString(error)); - return -1; - } - else - { - TraceLog(LOG_INFO, "Successfully resolved host %s:%s", address, service); - } - - // Calculate the size of the address information list - int size = 0; - for (iterator = res; iterator != NULL; iterator = iterator->ai_next) - { - size++; - } - - // Validate the size is > 0, otherwise return - if (size <= 0) - { - TraceLog(LOG_WARNING, "Error, no addresses found."); - return -1; - } - - // If not address list was allocated, allocate it dynamically with the known address size - if (outAddr == NULL) - { - outAddr = (AddressInformation *) malloc(size * sizeof(AddressInformation)); - } - - // Dynamically allocate an array of address information structs - if (outAddr != NULL) - { - int i; - for (i = 0; i < size; ++i) - { - outAddr[i] = AllocAddress(); - if (outAddr[i] == NULL) - { - break; - } - } - outAddr[i] = NULL; - if (i != size) - { - outAddr = NULL; - } - } - else - { - TraceLog(LOG_WARNING, - "Error, failed to dynamically allocate memory for the address list"); - return -1; - } - - // Copy all the address information from res into outAddrList - int i = 0; - for (iterator = res; iterator != NULL; iterator = iterator->ai_next) - { - if (i < size) - { - outAddr[i]->addr.ai_flags = iterator->ai_flags; - outAddr[i]->addr.ai_family = iterator->ai_family; - outAddr[i]->addr.ai_socktype = iterator->ai_socktype; - outAddr[i]->addr.ai_protocol = iterator->ai_protocol; - outAddr[i]->addr.ai_addrlen = iterator->ai_addrlen; - *outAddr[i]->addr.ai_addr = *iterator->ai_addr; + // Variables + int status; // Status value to return (0) is success + struct addrinfo hints; // Address flags (IPV4, IPV6, UDP?) + struct addrinfo *res; // will point to the results + struct addrinfo *iterator; + assert(((address != NULL || address != 0) || (service != NULL || service != 0))); + assert(((addressType == AF_INET) || (addressType == AF_INET6) || (addressType == AF_UNSPEC))); + + // Set the hints + memset(&hints, 0, sizeof hints); + hints.ai_family = addressType; // Either IPv4 or IPv6 (ADDRESS_TYPE_IPV4, ADDRESS_TYPE_IPV6) + hints.ai_protocol = 0; // Automatically select correct protocol (IPPROTO_TCP), (IPPROTO_UDP) + hints.ai_flags = flags; + assert((hints.ai_addrlen == 0) || (hints.ai_addrlen == 0)); + assert((hints.ai_canonname == 0) || (hints.ai_canonname == 0)); + assert((hints.ai_addr == 0) || (hints.ai_addr == 0)); + assert((hints.ai_next == 0) || (hints.ai_next == 0)); + + // When the address is NULL, populate the IP for me + if (address == NULL) + { + if ((hints.ai_flags & AI_PASSIVE) == 0) + { + hints.ai_flags |= AI_PASSIVE; + } + } + + TraceLog(LOG_INFO, "Resolving host..."); + + // Populate address information + status = getaddrinfo(address, // e.g. "www.example.com" or IP + service, // e.g. "http" or port number + &hints, // e.g. SOCK_STREAM/SOCK_DGRAM + &res // The struct to populate + ); + + // Did we succeed? + if (status != 0) + { + int error = SocketGetLastError(); + SocketSetLastError(0); + TraceLog(LOG_WARNING, "Failed to get resolve host: %s", SocketErrorCodeToString(error)); + return -1; + } + else + { + TraceLog(LOG_INFO, "Successfully resolved host %s:%s", address, service); + } + + // Calculate the size of the address information list + int size = 0; + for (iterator = res; iterator != NULL; iterator = iterator->ai_next) + { + size++; + } + + // Validate the size is > 0, otherwise return + if (size <= 0) + { + TraceLog(LOG_WARNING, "Error, no addresses found."); + return -1; + } + + // If not address list was allocated, allocate it dynamically with the known address size + if (outAddr == NULL) + { + outAddr = (AddressInformation *) malloc(size * sizeof(AddressInformation)); + } + + // Dynamically allocate an array of address information structs + if (outAddr != NULL) + { + int i; + for (i = 0; i < size; ++i) + { + outAddr[i] = AllocAddress(); + if (outAddr[i] == NULL) + { + break; + } + } + outAddr[i] = NULL; + if (i != size) + { + outAddr = NULL; + } + } + else + { + TraceLog(LOG_WARNING, + "Error, failed to dynamically allocate memory for the address list"); + return -1; + } + + // Copy all the address information from res into outAddrList + int i = 0; + for (iterator = res; iterator != NULL; iterator = iterator->ai_next) + { + if (i < size) + { + outAddr[i]->addr.ai_flags = iterator->ai_flags; + outAddr[i]->addr.ai_family = iterator->ai_family; + outAddr[i]->addr.ai_socktype = iterator->ai_socktype; + outAddr[i]->addr.ai_protocol = iterator->ai_protocol; + outAddr[i]->addr.ai_addrlen = iterator->ai_addrlen; + *outAddr[i]->addr.ai_addr = *iterator->ai_addr; #if NET_DEBUG_ENABLED - TraceLog(LOG_DEBUG, "GetAddressInformation"); - TraceLog(LOG_DEBUG, "\tFlags: 0x%x", iterator->ai_flags); - PrintSocket(outAddr[i]->addr.ai_addr, - outAddr[i]->addr.ai_family, - outAddr[i]->addr.ai_socktype, - outAddr[i]->addr.ai_protocol); - TraceLog(LOG_DEBUG, "Length of this sockaddr: %d", outAddr[i]->addr.ai_addrlen); - TraceLog(LOG_DEBUG, "Canonical name: %s", iterator->ai_canonname); + TraceLog(LOG_DEBUG, "GetAddressInformation"); + TraceLog(LOG_DEBUG, "\tFlags: 0x%x", iterator->ai_flags); + //PrintSocket(outAddr[i]->addr.ai_addr, outAddr[i]->addr.ai_family, outAddr[i]->addr.ai_socktype, outAddr[i]->addr.ai_protocol); + TraceLog(LOG_DEBUG, "Length of this sockaddr: %d", outAddr[i]->addr.ai_addrlen); + TraceLog(LOG_DEBUG, "Canonical name: %s", iterator->ai_canonname); #endif - i++; - } - } + i++; + } + } - // Free the pointer to the data returned by addrinfo - freeaddrinfo(res); + // Free the pointer to the data returned by addrinfo + freeaddrinfo(res); - // Return the total count of addresses found - return size; + // Return the total count of addresses found + return size; } -// This here is the bread and butter of the socket API, This function will -// attempt to open a socket, bind and listen to it based on the config passed in +// This here is the bread and butter of the socket API, This function will +// attempt to open a socket, bind and listen to it based on the config passed in // -// SocketConfig* config - Configuration for which socket to open -// SocketResult* result - The results of this function (if any, including errors) +// SocketConfig* config - Configuration for which socket to open +// SocketResult* result - The results of this function (if any, including errors) // -// e.g. -// SocketConfig server_config = { SocketConfig client_config = { -// .host = "127.0.0.1", .host = "127.0.0.1", -// .port = 8080, .port = 8080, -// .server = true, }; -// .nonblocking = true, -// }; -// SocketResult server_res; SocketResult client_res; +// e.g. +// SocketConfig server_config = { SocketConfig client_config = { +// .host = "127.0.0.1", .host = "127.0.0.1", +// .port = 8080, .port = 8080, +// .server = true, }; +// .nonblocking = true, +// }; +// SocketResult server_res; SocketResult client_res; bool SocketCreate(SocketConfig *config, SocketResult *result) { - // Socket creation result - bool success = true; - - // Make sure we've not received a null config or result pointer - if (config == NULL || result == NULL) - { - return (success = false); - } - - // Set the defaults based on the config - if (!SocketSetDefaults(config)) - { - TraceLog(LOG_WARNING, "Configuration Error."); - success = false; - } - else - { - // Create the socket - if (CreateSocket(config, result)) - { - if (config->nonblocking) - { - SocketSetNonBlocking(result->socket); - } - else - { - SocketSetBlocking(result->socket); - } - } - else - { - success = false; - } - } - return success; + // Socket creation result + bool success = true; + + // Make sure we've not received a null config or result pointer + if (config == NULL || result == NULL) + { + return (success = false); + } + + // Set the defaults based on the config + if (!SocketSetDefaults(config)) + { + TraceLog(LOG_WARNING, "Configuration Error."); + success = false; + } + else + { + // Create the socket + if (CreateSocket(config, result)) + { + if (config->nonblocking) + { + SocketSetNonBlocking(result->socket); + } + else + { + SocketSetBlocking(result->socket); + } + } + else + { + success = false; + } + } + return success; } // Bind a socket to a local address // Note: The bind function is required on an unconnected socket before subsequent calls to the listen function. bool SocketBind(SocketConfig *config, SocketResult *result) { - bool success = false; - result->status = RESULT_FAILURE; - struct sockaddr_storage *sock_addr = NULL; - - // Don't bind to a socket that isn't configured as a server - if (!IsSocketValid(result->socket) || !config->server) - { - TraceLog(LOG_WARNING, - "Cannot bind to socket marked as \"Client\" in SocketConfig."); - success = false; - } - else - { - if (result->socket->isIPv6) - { - sock_addr = (struct sockaddr_storage *) &result->socket->addripv6->address; - } - else - { - sock_addr = (struct sockaddr_storage *) &result->socket->addripv4->address; - } - if (sock_addr != NULL) - { - if (bind(result->socket->channel, (struct sockaddr *) sock_addr, sizeof(*sock_addr)) != SOCKET_ERROR) - { - TraceLog(LOG_INFO, "Successfully bound socket."); - success = true; - } - else - { - result->socket->status = SocketGetLastError(); - TraceLog(LOG_WARNING, "Socket Error: %s", - SocketErrorCodeToString(result->socket->status)); - SocketSetLastError(0); - success = false; - } - } - } - // Was the bind a success? - if (success) - { - result->status = RESULT_SUCCESS; - result->socket->ready = 0; - result->socket->status = 0; - socklen_t sock_len = sizeof(*sock_addr); - if (getsockname(result->socket->channel, (struct sockaddr *) sock_addr, &sock_len) < 0) - { - TraceLog(LOG_WARNING, "Couldn't get socket address"); - } - else - { - struct sockaddr_in *s = (struct sockaddr_in *) sock_addr; - // result->socket->address.host = s->sin_addr.s_addr; - // result->socket->address.port = s->sin_port; - - // - result->socket->addripv4 - = (struct _SocketAddressIPv4 *) malloc(sizeof(*result->socket->addripv4)); - if (result->socket->addripv4 != NULL) - { - memset(result->socket->addripv4, 0, sizeof(*result->socket->addripv4)); - } - memcpy(&result->socket->addripv4->address, (struct sockaddr_in *) &s->sin_addr, sizeof(struct sockaddr_in)); - // - } - } - return success; + bool success = false; + result->status = RESULT_FAILURE; + struct sockaddr_storage *sock_addr = NULL; + + // Don't bind to a socket that isn't configured as a server + if (!IsSocketValid(result->socket) || !config->server) + { + TraceLog(LOG_WARNING, + "Cannot bind to socket marked as \"Client\" in SocketConfig."); + success = false; + } + else + { + if (result->socket->isIPv6) + { + sock_addr = (struct sockaddr_storage *) &result->socket->addripv6->address; + } + else + { + sock_addr = (struct sockaddr_storage *) &result->socket->addripv4->address; + } + if (sock_addr != NULL) + { + if (bind(result->socket->channel, (struct sockaddr *) sock_addr, sizeof(*sock_addr)) != SOCKET_ERROR) + { + TraceLog(LOG_INFO, "Successfully bound socket."); + success = true; + } + else + { + result->socket->status = SocketGetLastError(); + TraceLog(LOG_WARNING, "Socket Error: %s", + SocketErrorCodeToString(result->socket->status)); + SocketSetLastError(0); + success = false; + } + } + } + // Was the bind a success? + if (success) + { + result->status = RESULT_SUCCESS; + result->socket->ready = 0; + result->socket->status = 0; + socklen_t sock_len = sizeof(*sock_addr); + if (getsockname(result->socket->channel, (struct sockaddr *) sock_addr, &sock_len) < 0) + { + TraceLog(LOG_WARNING, "Couldn't get socket address"); + } + else + { + struct sockaddr_in *s = (struct sockaddr_in *) sock_addr; + // result->socket->address.host = s->sin_addr.s_addr; + // result->socket->address.port = s->sin_port; + + // + result->socket->addripv4 + = (struct _SocketAddressIPv4 *) malloc(sizeof(*result->socket->addripv4)); + if (result->socket->addripv4 != NULL) + { + memset(result->socket->addripv4, 0, sizeof(*result->socket->addripv4)); + } + memcpy(&result->socket->addripv4->address, (struct sockaddr_in *) &s->sin_addr, sizeof(struct sockaddr_in)); + // + } + } + return success; } // Listens (and queues) incoming connections requests for a bound port. bool SocketListen(SocketConfig *config, SocketResult *result) { - bool success = false; - result->status = RESULT_FAILURE; - - // Don't bind to a socket that isn't configured as a server - if (!IsSocketValid(result->socket) || !config->server) - { - TraceLog(LOG_WARNING, - "Cannot listen on socket marked as \"Client\" in SocketConfig."); - success = false; - } - else - { - // Don't listen on UDP sockets - if (!(config->type == SOCKET_UDP)) - { - if (listen(result->socket->channel, config->backlog_size) != SOCKET_ERROR) - { - TraceLog(LOG_INFO, "Started listening on socket..."); - success = true; - } - else - { - success = false; - result->socket->status = SocketGetLastError(); - TraceLog(LOG_WARNING, "Socket Error: %s", - SocketErrorCodeToString(result->socket->status)); - SocketSetLastError(0); - } - } - else - { - TraceLog(LOG_WARNING, - "Cannot listen on socket marked as \"UDP\" (datagram) in SocketConfig."); - success = false; - } - } - - // Was the listen a success? - if (success) - { - result->status = RESULT_SUCCESS; - result->socket->ready = 0; - result->socket->status = 0; - } - return success; + bool success = false; + result->status = RESULT_FAILURE; + + // Don't bind to a socket that isn't configured as a server + if (!IsSocketValid(result->socket) || !config->server) + { + TraceLog(LOG_WARNING, + "Cannot listen on socket marked as \"Client\" in SocketConfig."); + success = false; + } + else + { + // Don't listen on UDP sockets + if (!(config->type == SOCKET_UDP)) + { + if (listen(result->socket->channel, config->backlog_size) != SOCKET_ERROR) + { + TraceLog(LOG_INFO, "Started listening on socket..."); + success = true; + } + else + { + success = false; + result->socket->status = SocketGetLastError(); + TraceLog(LOG_WARNING, "Socket Error: %s", + SocketErrorCodeToString(result->socket->status)); + SocketSetLastError(0); + } + } + else + { + TraceLog(LOG_WARNING, + "Cannot listen on socket marked as \"UDP\" (datagram) in SocketConfig."); + success = false; + } + } + + // Was the listen a success? + if (success) + { + result->status = RESULT_SUCCESS; + result->socket->ready = 0; + result->socket->status = 0; + } + return success; } // Connect the socket to the destination specified by "host" and "port" in SocketConfig bool SocketConnect(SocketConfig *config, SocketResult *result) { - bool success = true; - result->status = RESULT_FAILURE; - - // Only bind to sockets marked as server - if (config->server) - { - TraceLog(LOG_WARNING, - "Cannot connect to socket marked as \"Server\" in SocketConfig."); - success = false; - } - else - { - if (IsIPv4Address(config->host)) - { - struct sockaddr_in ip4addr; - ip4addr.sin_family = AF_INET; - unsigned long hport; - hport = strtoul(config->port, NULL, 0); - ip4addr.sin_port = htons(hport); - inet_pton(AF_INET, config->host, &ip4addr.sin_addr); - int connect_result = connect(result->socket->channel, (struct sockaddr *) &ip4addr, sizeof(ip4addr)); - if (connect_result == SOCKET_ERROR) - { - result->socket->status = SocketGetLastError(); - SocketSetLastError(0); - switch (result->socket->status) - { - case WSAEWOULDBLOCK: - { - success = true; - break; - } - default: - { - TraceLog(LOG_WARNING, "Socket Error: %s", - SocketErrorCodeToString(result->socket->status)); - success = false; - break; - } - } - } - else - { - TraceLog(LOG_INFO, "Successfully connected to socket."); - success = true; - } - } - else - { - if (IsIPv6Address(config->host)) - { - struct sockaddr_in6 ip6addr; - ip6addr.sin6_family = AF_INET6; - unsigned long hport; - hport = strtoul(config->port, NULL, 0); - ip6addr.sin6_port = htons(hport); - inet_pton(AF_INET6, config->host, &ip6addr.sin6_addr); - int connect_result = connect(result->socket->channel, (struct sockaddr *) &ip6addr, sizeof(ip6addr)); - if (connect_result == SOCKET_ERROR) - { - result->socket->status = SocketGetLastError(); - SocketSetLastError(0); - switch (result->socket->status) - { - case WSAEWOULDBLOCK: - { - success = true; - break; - } - default: - { - TraceLog(LOG_WARNING, "Socket Error: %s", - SocketErrorCodeToString(result->socket->status)); - success = false; - break; - } - } - } - else - { - TraceLog(LOG_INFO, "Successfully connected to socket."); - success = true; - } - } - } - } - - if (success) - { - result->status = RESULT_SUCCESS; - result->socket->ready = 0; - result->socket->status = 0; - } - - return success; -} - -// Closes an existing socket + bool success = true; + result->status = RESULT_FAILURE; + + // Only bind to sockets marked as server + if (config->server) + { + TraceLog(LOG_WARNING, + "Cannot connect to socket marked as \"Server\" in SocketConfig."); + success = false; + } + else + { + if (IsIPv4Address(config->host)) + { + struct sockaddr_in ip4addr; + ip4addr.sin_family = AF_INET; + unsigned long hport; + hport = strtoul(config->port, NULL, 0); + ip4addr.sin_port = htons(hport); + + // TODO: Changed the code to avoid the usage of inet_pton and inet_ntop replacing them with getnameinfo (that should have a better support on windows). + + //inet_pton(AF_INET, config->host, &ip4addr.sin_addr); + int connect_result = connect(result->socket->channel, (struct sockaddr *) &ip4addr, sizeof(ip4addr)); + if (connect_result == SOCKET_ERROR) + { + result->socket->status = SocketGetLastError(); + SocketSetLastError(0); + switch (result->socket->status) + { + case WSAEWOULDBLOCK: + { + success = true; + break; + } + default: + { + TraceLog(LOG_WARNING, "Socket Error: %s", + SocketErrorCodeToString(result->socket->status)); + success = false; + break; + } + } + } + else + { + TraceLog(LOG_INFO, "Successfully connected to socket."); + success = true; + } + } + else + { + if (IsIPv6Address(config->host)) + { + struct sockaddr_in6 ip6addr; + ip6addr.sin6_family = AF_INET6; + unsigned long hport; + hport = strtoul(config->port, NULL, 0); + ip6addr.sin6_port = htons(hport); + //inet_pton(AF_INET6, config->host, &ip6addr.sin6_addr); // TODO. + int connect_result = connect(result->socket->channel, (struct sockaddr *) &ip6addr, sizeof(ip6addr)); + if (connect_result == SOCKET_ERROR) + { + result->socket->status = SocketGetLastError(); + SocketSetLastError(0); + switch (result->socket->status) + { + case WSAEWOULDBLOCK: + { + success = true; + break; + } + default: + { + TraceLog(LOG_WARNING, "Socket Error: %s", + SocketErrorCodeToString(result->socket->status)); + success = false; + break; + } + } + } + else + { + TraceLog(LOG_INFO, "Successfully connected to socket."); + success = true; + } + } + } + } + + if (success) + { + result->status = RESULT_SUCCESS; + result->socket->ready = 0; + result->socket->status = 0; + } + + return success; +} + +// Closes an existing socket // -// SocketChannel socket - The id of the socket to close +// SocketChannel socket - The id of the socket to close void SocketClose(Socket *sock) { - if (sock != NULL) - { - if (sock->channel != INVALID_SOCKET) - { - closesocket(sock->channel); - } - } + if (sock != NULL) + { + if (sock->channel != INVALID_SOCKET) + { + closesocket(sock->channel); + } + } } // Returns the sockaddress for a specific socket in a generic storage struct SocketAddressStorage SocketGetPeerAddress(Socket *sock) { - if (sock->isServer) - { - return NULL; - } - if (sock->isIPv6) - { - return sock->addripv6; - } - else - { - return sock->addripv4; - } + // TODO. + /* + if (sock->isServer) return NULL; + if (sock->isIPv6) return sock->addripv6; + else return sock->addripv4; + */ + + return NULL; } // Return the address-type appropriate host portion of a socket address char *GetSocketAddressHost(SocketAddressStorage storage) { - assert(storage->address.ss_family == AF_INET || storage->address.ss_family == AF_INET6); - return SocketAddressToString((struct sockaddr_storage *) storage); + assert(storage->address.ss_family == AF_INET || storage->address.ss_family == AF_INET6); + return SocketAddressToString((struct sockaddr_storage *) storage); } // Return the address-type appropriate port(service) portion of a socket address short GetSocketAddressPort(SocketAddressStorage storage) { - return ntohs(GetSocketPortPtr(storage)); + //return ntohs(GetSocketPortPtr(storage)); // TODO. + + return 0; } -// The accept function permits an incoming connection attempt on a socket. +// The accept function permits an incoming connection attempt on a socket. // -// SocketChannel listener - The socket to listen for incoming connections on (i.e. server) -// SocketResult* out - The result of this function (if any, including errors) +// SocketChannel listener - The socket to listen for incoming connections on (i.e. server) +// SocketResult* out - The result of this function (if any, including errors) // -// e.g. +// e.g. // -// SocketResult connection; -// bool connected = false; -// if (!connected) -// { -// if (SocketAccept(server_res.socket.channel, &connection)) -// { -// connected = true; -// } -// } +// SocketResult connection; +// bool connected = false; +// if (!connected) +// { +// if (SocketAccept(server_res.socket.channel, &connection)) +// { +// connected = true; +// } +// } Socket *SocketAccept(Socket *server, SocketConfig *config) { - if (!server->isServer || server->type == SOCKET_UDP) - { - return NULL; - } - struct sockaddr_storage sock_addr; - socklen_t sock_alen; - Socket * sock; - sock = AllocSocket(); - server->ready = 0; - sock_alen = sizeof(sock_addr); - sock->channel = accept(server->channel, (struct sockaddr *) &sock_addr, &sock_alen); - if (sock->channel == INVALID_SOCKET) - { - sock->status = SocketGetLastError(); - TraceLog(LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(sock->status)); - SocketSetLastError(0); - SocketClose(sock); - return NULL; - } - (config->nonblocking) ? SocketSetNonBlocking(sock) : SocketSetBlocking(sock); - sock->isServer = false; - sock->ready = 0; - sock->type = server->type; - switch (sock_addr.ss_family) - { - case AF_INET: - { - struct sockaddr_in *s = ((struct sockaddr_in *) &sock_addr); - sock->addripv4 = (struct _SocketAddressIPv4 *) malloc(sizeof(*sock->addripv4)); - if (sock->addripv4 != NULL) - { - memset(sock->addripv4, 0, sizeof(*sock->addripv4)); - memcpy(&sock->addripv4->address, (struct sockaddr_in *) &s->sin_addr, sizeof(struct sockaddr_in)); - TraceLog(LOG_INFO, "Server: Got connection from %s::%hu", SocketAddressToString((struct sockaddr_storage *) s), - ntohs(sock->addripv4->address.sin_port)); - } - } - break; - case AF_INET6: - { - struct sockaddr_in6 *s = ((struct sockaddr_in6 *) &sock_addr); - sock->addripv6 = (struct _SocketAddressIPv6 *) malloc(sizeof(*sock->addripv6)); - if (sock->addripv6 != NULL) - { - memset(sock->addripv6, 0, sizeof(*sock->addripv6)); - memcpy(&sock->addripv6->address, (struct sockaddr_in6 *) &s->sin6_addr, sizeof(struct sockaddr_in6)); - TraceLog(LOG_INFO, "Server: Got connection from %s::%hu", SocketAddressToString((struct sockaddr_storage *) s), - ntohs(sock->addripv6->address.sin6_port)); - } - } - break; - } - return sock; + if (!server->isServer || server->type == SOCKET_UDP) + { + return NULL; + } + struct sockaddr_storage sock_addr; + socklen_t sock_alen; + Socket * sock; + sock = AllocSocket(); + server->ready = 0; + sock_alen = sizeof(sock_addr); + sock->channel = accept(server->channel, (struct sockaddr *) &sock_addr, &sock_alen); + if (sock->channel == INVALID_SOCKET) + { + sock->status = SocketGetLastError(); + TraceLog(LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(sock->status)); + SocketSetLastError(0); + SocketClose(sock); + return NULL; + } + (config->nonblocking) ? SocketSetNonBlocking(sock) : SocketSetBlocking(sock); + sock->isServer = false; + sock->ready = 0; + sock->type = server->type; + switch (sock_addr.ss_family) + { + case AF_INET: + { + struct sockaddr_in *s = ((struct sockaddr_in *) &sock_addr); + sock->addripv4 = (struct _SocketAddressIPv4 *) malloc(sizeof(*sock->addripv4)); + if (sock->addripv4 != NULL) + { + memset(sock->addripv4, 0, sizeof(*sock->addripv4)); + memcpy(&sock->addripv4->address, (struct sockaddr_in *) &s->sin_addr, sizeof(struct sockaddr_in)); + TraceLog(LOG_INFO, "Server: Got connection from %s::%hu", SocketAddressToString((struct sockaddr_storage *) s), + ntohs(sock->addripv4->address.sin_port)); + } + } + break; + case AF_INET6: + { + struct sockaddr_in6 *s = ((struct sockaddr_in6 *) &sock_addr); + sock->addripv6 = (struct _SocketAddressIPv6 *) malloc(sizeof(*sock->addripv6)); + if (sock->addripv6 != NULL) + { + memset(sock->addripv6, 0, sizeof(*sock->addripv6)); + memcpy(&sock->addripv6->address, (struct sockaddr_in6 *) &s->sin6_addr, sizeof(struct sockaddr_in6)); + TraceLog(LOG_INFO, "Server: Got connection from %s::%hu", SocketAddressToString((struct sockaddr_storage *) s), + ntohs(sock->addripv6->address.sin6_port)); + } + } + break; + } + return sock; } // Verify that the channel is in the valid range static int ValidChannel(int channel) { - if ((channel < 0) || (channel >= SOCKET_MAX_UDPCHANNELS)) - { - TraceLog(LOG_WARNING, "Invalid channel"); - return 0; - } - return 1; + if ((channel < 0) || (channel >= SOCKET_MAX_UDPCHANNELS)) + { + TraceLog(LOG_WARNING, "Invalid channel"); + return 0; + } + return 1; } // Set the socket channel int SocketSetChannel(Socket *socket, int channel, const IPAddress *address) { - struct UDPChannel *binding; - if (socket == NULL) - { - TraceLog(LOG_WARNING, "Passed a NULL socket"); - return (-1); - } - if (channel == -1) - { - for (channel = 0; channel < SOCKET_MAX_UDPCHANNELS; ++channel) - { - binding = &socket->binding[channel]; - if (binding->numbound < SOCKET_MAX_UDPADDRESSES) - { - break; - } - } - } - else - { - if (!ValidChannel(channel)) - { - return (-1); - } - binding = &socket->binding[channel]; - } - if (binding->numbound == SOCKET_MAX_UDPADDRESSES) - { - TraceLog(LOG_WARNING, "No room for new addresses"); - return (-1); - } - binding->address[binding->numbound++] = *address; - return (channel); + struct UDPChannel *binding; + if (socket == NULL) + { + TraceLog(LOG_WARNING, "Passed a NULL socket"); + return (-1); + } + if (channel == -1) + { + for (channel = 0; channel < SOCKET_MAX_UDPCHANNELS; ++channel) + { + binding = &socket->binding[channel]; + if (binding->numbound < SOCKET_MAX_UDPADDRESSES) + { + break; + } + } + } + else + { + if (!ValidChannel(channel)) + { + return (-1); + } + binding = &socket->binding[channel]; + } + if (binding->numbound == SOCKET_MAX_UDPADDRESSES) + { + TraceLog(LOG_WARNING, "No room for new addresses"); + return (-1); + } + binding->address[binding->numbound++] = *address; + return (channel); } // Remove the socket channel void SocketUnsetChannel(Socket *socket, int channel) { - if ((channel >= 0) && (channel < SOCKET_MAX_UDPCHANNELS)) - { - socket->binding[channel].numbound = 0; - } + if ((channel >= 0) && (channel < SOCKET_MAX_UDPCHANNELS)) + { + socket->binding[channel].numbound = 0; + } } /* Allocate/free a single UDP packet 'size' bytes long. @@ -1315,49 +1317,49 @@ void SocketUnsetChannel(Socket *socket, int channel) */ SocketDataPacket *AllocPacket(int size) { - SocketDataPacket *packet; - int error; - - error = 1; - packet = (SocketDataPacket *) malloc(sizeof(*packet)); - if (packet != NULL) - { - packet->maxlen = size; - packet->data = (uint8_t *) malloc(size); - if (packet->data != NULL) - { - error = 0; - } - } - if (error) - { - FreePacket(packet); - packet = NULL; - } - return (packet); + SocketDataPacket *packet; + int error; + + error = 1; + packet = (SocketDataPacket *) malloc(sizeof(*packet)); + if (packet != NULL) + { + packet->maxlen = size; + packet->data = (uint8_t *) malloc(size); + if (packet->data != NULL) + { + error = 0; + } + } + if (error) + { + FreePacket(packet); + packet = NULL; + } + return (packet); } int ResizePacket(SocketDataPacket *packet, int newsize) { - uint8_t *newdata; + uint8_t *newdata; - newdata = (uint8_t *) malloc(newsize); - if (newdata != NULL) - { - free(packet->data); - packet->data = newdata; - packet->maxlen = newsize; - } - return (packet->maxlen); + newdata = (uint8_t *) malloc(newsize); + if (newdata != NULL) + { + free(packet->data); + packet->data = newdata; + packet->maxlen = newsize; + } + return (packet->maxlen); } void FreePacket(SocketDataPacket *packet) { - if (packet) - { - free(packet->data); - free(packet); - } + if (packet) + { + free(packet->data); + free(packet); + } } /* Allocate/Free a UDP packet vector (array of packets) of 'howmany' packets, @@ -1367,656 +1369,656 @@ void FreePacket(SocketDataPacket *packet) */ SocketDataPacket **AllocPacketList(int howmany, int size) { - SocketDataPacket **packetV; - - packetV = (SocketDataPacket **) malloc((howmany + 1) * sizeof(*packetV)); - if (packetV != NULL) - { - int i; - for (i = 0; i < howmany; ++i) - { - packetV[i] = AllocPacket(size); - if (packetV[i] == NULL) - { - break; - } - } - packetV[i] = NULL; - - if (i != howmany) - { - FreePacketList(packetV); - packetV = NULL; - } - } - return (packetV); + SocketDataPacket **packetV; + + packetV = (SocketDataPacket **) malloc((howmany + 1) * sizeof(*packetV)); + if (packetV != NULL) + { + int i; + for (i = 0; i < howmany; ++i) + { + packetV[i] = AllocPacket(size); + if (packetV[i] == NULL) + { + break; + } + } + packetV[i] = NULL; + + if (i != howmany) + { + FreePacketList(packetV); + packetV = NULL; + } + } + return (packetV); } void FreePacketList(SocketDataPacket **packetV) { - if (packetV) - { - int i; - for (i = 0; packetV[i]; ++i) - { - FreePacket(packetV[i]); - } - free(packetV); - } + if (packetV) + { + int i; + for (i = 0; packetV[i]; ++i) + { + FreePacket(packetV[i]); + } + free(packetV); + } } -// Send 'len' bytes of 'data' over the non-server socket 'sock' +// Send 'len' bytes of 'data' over the non-server socket 'sock' // -// Example +// Example int SocketSend(Socket *sock, const void *datap, int length) { - int sent = 0; - int left = length; - int status = -1; - int numsent = 0; - const unsigned char *data = (const unsigned char *) datap; - - // Server sockets are for accepting connections only - if (sock->isServer) - { - TraceLog(LOG_WARNING, "Cannot send information on a server socket"); - return -1; - } - - // Which socket are we trying to send data on - switch (sock->type) - { - case SOCKET_TCP: - { - SocketSetLastError(0); - do - { - length = send(sock->channel, (const char *) data, left, 0); - if (length > 0) - { - sent += length; - left -= length; - data += length; - } - } while ((left > 0) && // While we still have bytes left to send - ((length > 0) || // The amount of bytes we actually sent is > 0 - (SocketGetLastError() == WSAEINTR)) // The socket was interupted - ); - - if (length == SOCKET_ERROR) - { - sock->status = SocketGetLastError(); - TraceLog(LOG_DEBUG, "Socket Error: %s", SocketErrorCodeToString(sock->status)); - SocketSetLastError(0); - } - else - { - TraceLog(LOG_DEBUG, "Successfully sent \"%s\" (%d bytes)", datap, sent); - } - - return sent; - } - break; - case SOCKET_UDP: - { - SocketSetLastError(0); - if (sock->isIPv6) - { - status = sendto(sock->channel, (const char *) data, left, 0, - (struct sockaddr *) &sock->addripv6->address, - sizeof(sock->addripv6->address)); - } - else - { - status = sendto(sock->channel, (const char *) data, left, 0, - (struct sockaddr *) &sock->addripv4->address, - sizeof(sock->addripv4->address)); - } - if (sent >= 0) - { - sock->status = 0; - ++numsent; - TraceLog(LOG_DEBUG, "Successfully sent \"%s\" (%d bytes)", datap, status); - } - else - { - sock->status = SocketGetLastError(); - TraceLog(LOG_DEBUG, "Socket Error: %s", SocketGetLastErrorString(sock->status)); - SocketSetLastError(0); - return 0; - } - return numsent; - } - break; - default: break; - } - return -1; -} - -// Receive up to 'maxlen' bytes of data over the non-server socket 'sock', -// and store them in the buffer pointed to by 'data'. -// This function returns the actual amount of data received. If the return -// value is less than or equal to zero, then either the remote connection was -// closed, or an unknown socket error occurred. + int sent = 0; + int left = length; + int status = -1; + int numsent = 0; + const unsigned char *data = (const unsigned char *) datap; + + // Server sockets are for accepting connections only + if (sock->isServer) + { + TraceLog(LOG_WARNING, "Cannot send information on a server socket"); + return -1; + } + + // Which socket are we trying to send data on + switch (sock->type) + { + case SOCKET_TCP: + { + SocketSetLastError(0); + do + { + length = send(sock->channel, (const char *) data, left, 0); + if (length > 0) + { + sent += length; + left -= length; + data += length; + } + } while ((left > 0) && // While we still have bytes left to send + ((length > 0) || // The amount of bytes we actually sent is > 0 + (SocketGetLastError() == WSAEINTR)) // The socket was interupted + ); + + if (length == SOCKET_ERROR) + { + sock->status = SocketGetLastError(); + TraceLog(LOG_DEBUG, "Socket Error: %s", SocketErrorCodeToString(sock->status)); + SocketSetLastError(0); + } + else + { + TraceLog(LOG_DEBUG, "Successfully sent \"%s\" (%d bytes)", datap, sent); + } + + return sent; + } + break; + case SOCKET_UDP: + { + SocketSetLastError(0); + if (sock->isIPv6) + { + status = sendto(sock->channel, (const char *) data, left, 0, + (struct sockaddr *) &sock->addripv6->address, + sizeof(sock->addripv6->address)); + } + else + { + status = sendto(sock->channel, (const char *) data, left, 0, + (struct sockaddr *) &sock->addripv4->address, + sizeof(sock->addripv4->address)); + } + if (sent >= 0) + { + sock->status = 0; + ++numsent; + TraceLog(LOG_DEBUG, "Successfully sent \"%s\" (%d bytes)", datap, status); + } + else + { + sock->status = SocketGetLastError(); + TraceLog(LOG_DEBUG, "Socket Error: %s", SocketGetLastErrorString(sock->status)); + SocketSetLastError(0); + return 0; + } + return numsent; + } + break; + default: break; + } + return -1; +} + +// Receive up to 'maxlen' bytes of data over the non-server socket 'sock', +// and store them in the buffer pointed to by 'data'. +// This function returns the actual amount of data received. If the return +// value is less than or equal to zero, then either the remote connection was +// closed, or an unknown socket error occurred. int SocketReceive(Socket *sock, void *data, int maxlen) { - int len = 0; - int numrecv = 0; - int status = 0; - socklen_t sock_len; - struct sockaddr_storage sock_addr; - char ip[INET6_ADDRSTRLEN]; - - // Server sockets are for accepting connections only - if (sock->isServer && sock->type == SOCKET_TCP) - { - sock->status = SocketGetLastError(); - TraceLog(LOG_DEBUG, "Socket Error: %s", - "Server sockets cannot be used to receive data"); - SocketSetLastError(0); - return 0; - } - - // Which socket are we trying to send data on - switch (sock->type) - { - case SOCKET_TCP: - { - SocketSetLastError(0); - do - { - len = recv(sock->channel, (char *) data, maxlen, 0); - } while (SocketGetLastError() == WSAEINTR); - - if (len > 0) - { - // Who sent the packet? - if (sock->type == SOCKET_UDP) - { - TraceLog( - LOG_DEBUG, "Received data from: %s", inet_ntop(sock_addr.ss_family, GetSocketAddressPtr((struct sockaddr *) &sock_addr), ip, sizeof(ip))); - } - ((unsigned char *) data)[len] = '\0'; // Add null terminating character to the end of the stream - TraceLog(LOG_DEBUG, "Received \"%s\" (%d bytes)", data, len); - } - sock->ready = 0; - return len; - } - break; - case SOCKET_UDP: - { - SocketSetLastError(0); - sock_len = sizeof(sock_addr); - status = recvfrom(sock->channel, // The receving channel + int len = 0; + int numrecv = 0; + int status = 0; + socklen_t sock_len; + struct sockaddr_storage sock_addr; + //char ip[INET6_ADDRSTRLEN]; + + // Server sockets are for accepting connections only + if (sock->isServer && sock->type == SOCKET_TCP) + { + sock->status = SocketGetLastError(); + TraceLog(LOG_DEBUG, "Socket Error: %s", "Server sockets cannot be used to receive data"); + SocketSetLastError(0); + return 0; + } + + // Which socket are we trying to send data on + switch (sock->type) + { + case SOCKET_TCP: + { + SocketSetLastError(0); + do + { + len = recv(sock->channel, (char *) data, maxlen, 0); + } while (SocketGetLastError() == WSAEINTR); + + if (len > 0) + { + // Who sent the packet? + if (sock->type == SOCKET_UDP) + { + //TraceLog(LOG_DEBUG, "Received data from: %s", inet_ntop(sock_addr.ss_family, GetSocketAddressPtr((struct sockaddr *) &sock_addr), ip, sizeof(ip))); + } + + ((unsigned char *) data)[len] = '\0'; // Add null terminating character to the end of the stream + TraceLog(LOG_DEBUG, "Received \"%s\" (%d bytes)", data, len); + } + + sock->ready = 0; + return len; + } + break; + case SOCKET_UDP: + { + SocketSetLastError(0); + sock_len = sizeof(sock_addr); + status = recvfrom(sock->channel, // The receving channel data, // A pointer to the data buffer to fill maxlen, // The max length of the data to fill 0, // Flags (struct sockaddr *) &sock_addr, // The address of the recevied data &sock_len // The length of the received data address ); - if (status >= 0) - { - ++numrecv; - } - else - { - sock->status = SocketGetLastError(); - switch (sock->status) - { - case WSAEWOULDBLOCK: { break; - } - default: - { - TraceLog(LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(sock->status)); - break; - } - } - SocketSetLastError(0); - return 0; - } - sock->ready = 0; - return numrecv; - } - break; - } - return -1; + if (status >= 0) + { + ++numrecv; + } + else + { + sock->status = SocketGetLastError(); + switch (sock->status) + { + case WSAEWOULDBLOCK: { break; + } + default: + { + TraceLog(LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(sock->status)); + break; + } + } + SocketSetLastError(0); + return 0; + } + sock->ready = 0; + return numrecv; + } + break; + } + return -1; } // Does the socket have it's 'ready' flag set? bool IsSocketReady(Socket *sock) { - return (sock != NULL) && (sock->ready); + return (sock != NULL) && (sock->ready); } // Check if the socket is considered connected bool IsSocketConnected(Socket *sock) { #if defined(_WIN32) - FD_SET writefds; - FD_ZERO(&writefds); - FD_SET(sock->channel, &writefds); - struct timeval timeout; - timeout.tv_sec = 1; - timeout.tv_usec = 1000000000UL; - int total = select(0, NULL, &writefds, NULL, &timeout); - if (total == -1) - { // Error - sock->status = SocketGetLastError(); - TraceLog(LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(sock->status)); - SocketSetLastError(0); - } - else if (total == 0) - { // Timeout - return false; - } - else - { - if (FD_ISSET(sock->channel, &writefds)) - { - return true; - } - } - return false; + FD_SET writefds; + FD_ZERO(&writefds); + FD_SET(sock->channel, &writefds); + struct timeval timeout; + timeout.tv_sec = 1; + timeout.tv_usec = 1000000000UL; + int total = select(0, NULL, &writefds, NULL, &timeout); + if (total == -1) + { // Error + sock->status = SocketGetLastError(); + TraceLog(LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(sock->status)); + SocketSetLastError(0); + } + else if (total == 0) + { // Timeout + return false; + } + else + { + if (FD_ISSET(sock->channel, &writefds)) + { + return true; + } + } + return false; #else - return true; + return true; #endif } // Allocate and return a SocketResult struct SocketResult *AllocSocketResult() { - struct SocketResult *res; - res = (struct SocketResult *) malloc(sizeof(*res)); - if (res != NULL) - { - memset(res, 0, sizeof(*res)); - if ((res->socket = AllocSocket()) == NULL) - { - free(res); - res = NULL; - } - } - return res; + struct SocketResult *res; + res = (struct SocketResult *) malloc(sizeof(*res)); + if (res != NULL) + { + memset(res, 0, sizeof(*res)); + if ((res->socket = AllocSocket()) == NULL) + { + free(res); + res = NULL; + } + } + return res; } // Free an allocated SocketResult void FreeSocketResult(SocketResult **result) { - if (*result != NULL) - { - if ((*result)->socket != NULL) - { - FreeSocket(&((*result)->socket)); - } - free(*result); - *result = NULL; - } + if (*result != NULL) + { + if ((*result)->socket != NULL) + { + FreeSocket(&((*result)->socket)); + } + free(*result); + *result = NULL; + } } // Allocate a Socket Socket *AllocSocket() { - // Allocate a socket if one already hasn't been - struct Socket *sock; - sock = (Socket *) malloc(sizeof(*sock)); - if (sock != NULL) - { - memset(sock, 0, sizeof(*sock)); - } - else - { - TraceLog( - LOG_WARNING, "Ran out of memory attempting to allocate a socket"); - SocketClose(sock); - free(sock); - sock = NULL; - } - return sock; + // Allocate a socket if one already hasn't been + struct Socket *sock; + sock = (Socket *) malloc(sizeof(*sock)); + if (sock != NULL) + { + memset(sock, 0, sizeof(*sock)); + } + else + { + TraceLog( + LOG_WARNING, "Ran out of memory attempting to allocate a socket"); + SocketClose(sock); + free(sock); + sock = NULL; + } + return sock; } // Free an allocated Socket void FreeSocket(Socket **sock) { - if (*sock != NULL) - { - free(*sock); - *sock = NULL; - } + if (*sock != NULL) + { + free(*sock); + *sock = NULL; + } } // Allocate a SocketSet SocketSet *AllocSocketSet(int max) { - struct SocketSet *set; - int i; - - set = (struct SocketSet *) malloc(sizeof(*set)); - if (set != NULL) - { - set->numsockets = 0; - set->maxsockets = max; - set->sockets = (struct Socket **) malloc(max * sizeof(*set->sockets)); - if (set->sockets != NULL) - { - for (i = 0; i < max; ++i) - { - set->sockets[i] = NULL; - } - } - else - { - free(set); - set = NULL; - } - } - return (set); + struct SocketSet *set; + int i; + + set = (struct SocketSet *) malloc(sizeof(*set)); + if (set != NULL) + { + set->numsockets = 0; + set->maxsockets = max; + set->sockets = (struct Socket **) malloc(max * sizeof(*set->sockets)); + if (set->sockets != NULL) + { + for (i = 0; i < max; ++i) + { + set->sockets[i] = NULL; + } + } + else + { + free(set); + set = NULL; + } + } + return (set); } // Free an allocated SocketSet void FreeSocketSet(SocketSet *set) { - if (set) - { - free(set->sockets); - free(set); - } + if (set) + { + free(set->sockets); + free(set); + } } // Add a Socket "sock" to the SocketSet "set" int AddSocket(SocketSet *set, Socket *sock) { - if (sock != NULL) - { - if (set->numsockets == set->maxsockets) - { - TraceLog(LOG_DEBUG, "Socket Error: %s", "SocketSet is full"); - SocketSetLastError(0); - return (-1); - } - set->sockets[set->numsockets++] = (struct Socket *) sock; - } - else - { - TraceLog(LOG_DEBUG, "Socket Error: %s", "Socket was null"); - SocketSetLastError(0); - return (-1); - } - return (set->numsockets); + if (sock != NULL) + { + if (set->numsockets == set->maxsockets) + { + TraceLog(LOG_DEBUG, "Socket Error: %s", "SocketSet is full"); + SocketSetLastError(0); + return (-1); + } + set->sockets[set->numsockets++] = (struct Socket *) sock; + } + else + { + TraceLog(LOG_DEBUG, "Socket Error: %s", "Socket was null"); + SocketSetLastError(0); + return (-1); + } + return (set->numsockets); } // Remove a Socket "sock" to the SocketSet "set" int RemoveSocket(SocketSet *set, Socket *sock) { - int i; - - if (sock != NULL) - { - for (i = 0; i < set->numsockets; ++i) - { - if (set->sockets[i] == (struct Socket *) sock) - { - break; - } - } - if (i == set->numsockets) - { - TraceLog(LOG_DEBUG, "Socket Error: %s", "Socket not found"); - SocketSetLastError(0); - return (-1); - } - --set->numsockets; - for (; i < set->numsockets; ++i) - { - set->sockets[i] = set->sockets[i + 1]; - } - } - return (set->numsockets); + int i; + + if (sock != NULL) + { + for (i = 0; i < set->numsockets; ++i) + { + if (set->sockets[i] == (struct Socket *) sock) + { + break; + } + } + if (i == set->numsockets) + { + TraceLog(LOG_DEBUG, "Socket Error: %s", "Socket not found"); + SocketSetLastError(0); + return (-1); + } + --set->numsockets; + for (; i < set->numsockets; ++i) + { + set->sockets[i] = set->sockets[i + 1]; + } + } + return (set->numsockets); } // Check the sockets in the socket set for pending information int CheckSockets(SocketSet *set, unsigned int timeout) { - int i; - SOCKET maxfd; - int retval; - struct timeval tv; - fd_set mask; - - /* Find the largest file descriptor */ - maxfd = 0; - for (i = set->numsockets - 1; i >= 0; --i) - { - if (set->sockets[i]->channel > maxfd) - { - maxfd = set->sockets[i]->channel; - } - } - - // Check the file descriptors for available data - do - { - SocketSetLastError(0); - - // Set up the mask of file descriptors - FD_ZERO(&mask); - for (i = set->numsockets - 1; i >= 0; --i) - { - FD_SET(set->sockets[i]->channel, &mask); - } // Set up the timeout - tv.tv_sec = timeout / 1000; - tv.tv_usec = (timeout % 1000) * 1000; - - /* Look! */ - retval = select(maxfd + 1, &mask, NULL, NULL, &tv); - } while (SocketGetLastError() == WSAEINTR); - - // Mark all file descriptors ready that have data available - if (retval > 0) - { - for (i = set->numsockets - 1; i >= 0; --i) - { - if (FD_ISSET(set->sockets[i]->channel, &mask)) - { - set->sockets[i]->ready = 1; - } - } - } - return (retval); + int i; + SOCKET maxfd; + int retval; + struct timeval tv; + fd_set mask; + + /* Find the largest file descriptor */ + maxfd = 0; + for (i = set->numsockets - 1; i >= 0; --i) + { + if (set->sockets[i]->channel > maxfd) + { + maxfd = set->sockets[i]->channel; + } + } + + // Check the file descriptors for available data + do + { + SocketSetLastError(0); + + // Set up the mask of file descriptors + FD_ZERO(&mask); + for (i = set->numsockets - 1; i >= 0; --i) + { + FD_SET(set->sockets[i]->channel, &mask); + } // Set up the timeout + tv.tv_sec = timeout / 1000; + tv.tv_usec = (timeout % 1000) * 1000; + + /* Look! */ + retval = select(maxfd + 1, &mask, NULL, NULL, &tv); + } while (SocketGetLastError() == WSAEINTR); + + // Mark all file descriptors ready that have data available + if (retval > 0) + { + for (i = set->numsockets - 1; i >= 0; --i) + { + if (FD_ISSET(set->sockets[i]->channel, &mask)) + { + set->sockets[i]->ready = 1; + } + } + } + return (retval); } // Allocate an AddressInformation AddressInformation AllocAddress() { - AddressInformation addressInfo = NULL; - addressInfo = (AddressInformation) calloc(1, sizeof(*addressInfo)); - if (addressInfo != NULL) - { - addressInfo->addr.ai_addr = (struct sockaddr *) calloc(1, sizeof(struct sockaddr)); - if (addressInfo->addr.ai_addr == NULL) - { - TraceLog(LOG_WARNING, - "Failed to allocate memory for \"struct sockaddr\""); - } - } - else - { - TraceLog(LOG_WARNING, - "Failed to allocate memory for \"struct AddressInformation\""); - } - return addressInfo; + AddressInformation addressInfo = NULL; + addressInfo = (AddressInformation) calloc(1, sizeof(*addressInfo)); + if (addressInfo != NULL) + { + addressInfo->addr.ai_addr = (struct sockaddr *) calloc(1, sizeof(struct sockaddr)); + if (addressInfo->addr.ai_addr == NULL) + { + TraceLog(LOG_WARNING, + "Failed to allocate memory for \"struct sockaddr\""); + } + } + else + { + TraceLog(LOG_WARNING, + "Failed to allocate memory for \"struct AddressInformation\""); + } + return addressInfo; } // Free an AddressInformation struct void FreeAddress(AddressInformation *addressInfo) { - if (*addressInfo != NULL) - { - if ((*addressInfo)->addr.ai_addr != NULL) - { - free((*addressInfo)->addr.ai_addr); - (*addressInfo)->addr.ai_addr = NULL; - } - free(*addressInfo); - *addressInfo = NULL; - } + if (*addressInfo != NULL) + { + if ((*addressInfo)->addr.ai_addr != NULL) + { + free((*addressInfo)->addr.ai_addr); + (*addressInfo)->addr.ai_addr = NULL; + } + free(*addressInfo); + *addressInfo = NULL; + } } // Allocate a list of AddressInformation AddressInformation *AllocAddressList(int size) { - AddressInformation *addr; - addr = (AddressInformation *) malloc(size * sizeof(AddressInformation)); - return addr; + AddressInformation *addr; + addr = (AddressInformation *) malloc(size * sizeof(AddressInformation)); + return addr; } // Opaque datatype accessor addrinfo->ai_family int GetAddressFamily(AddressInformation address) { - return address->addr.ai_family; + return address->addr.ai_family; } // Opaque datatype accessor addrinfo->ai_socktype int GetAddressSocketType(AddressInformation address) { - return address->addr.ai_socktype; + return address->addr.ai_socktype; } // Opaque datatype accessor addrinfo->ai_protocol int GetAddressProtocol(AddressInformation address) { - return address->addr.ai_protocol; + return address->addr.ai_protocol; } // Opaque datatype accessor addrinfo->ai_canonname char *GetAddressCanonName(AddressInformation address) { - return address->addr.ai_canonname; + return address->addr.ai_canonname; } // Opaque datatype accessor addrinfo->ai_addr char *GetAddressHostAndPort(AddressInformation address, char *outhost, int *outport) { - char * ip[INET6_ADDRSTRLEN]; - char * result = NULL; - struct sockaddr_storage *storage = (struct sockaddr_storage *) address->addr.ai_addr; - switch (storage->ss_family) - { - case AF_INET: - { - struct sockaddr_in *s = ((struct sockaddr_in *) address->addr.ai_addr); - result = inet_ntop(AF_INET, &s->sin_addr, ip, INET_ADDRSTRLEN); - *outport = ntohs(s->sin_port); - } - break; - case AF_INET6: - { - struct sockaddr_in6 *s = ((struct sockaddr_in6 *) address->addr.ai_addr); - result = inet_ntop(AF_INET6, &s->sin6_addr, ip, INET6_ADDRSTRLEN); - *outport = ntohs(s->sin6_port); - } - break; - } - if (result == NULL) - { - TraceLog(LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(SocketGetLastError())); - SocketSetLastError(0); - } - else - { - strcpy(outhost, result); - } - return result; + //char *ip[INET6_ADDRSTRLEN]; + char *result = NULL; + struct sockaddr_storage *storage = (struct sockaddr_storage *) address->addr.ai_addr; + switch (storage->ss_family) + { + case AF_INET: + { + struct sockaddr_in *s = ((struct sockaddr_in *) address->addr.ai_addr); + //result = inet_ntop(AF_INET, &s->sin_addr, ip, INET_ADDRSTRLEN); // TODO. + *outport = ntohs(s->sin_port); + } + break; + case AF_INET6: + { + struct sockaddr_in6 *s = ((struct sockaddr_in6 *) address->addr.ai_addr); + //result = inet_ntop(AF_INET6, &s->sin6_addr, ip, INET6_ADDRSTRLEN); // TODO. + *outport = ntohs(s->sin6_port); + } + break; + } + if (result == NULL) + { + TraceLog(LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(SocketGetLastError())); + SocketSetLastError(0); + } + else + { + strcpy(outhost, result); + } + return result; } // void PacketSend(Packet *packet) { - printf("Sending packet (%s) with size %d\n", packet->data, packet->size); + printf("Sending packet (%s) with size %d\n", packet->data, packet->size); } // void PacketReceive(Packet *packet) { - printf("Receiving packet (%s) with size %d\n", packet->data, packet->size); + printf("Receiving packet (%s) with size %d\n", packet->data, packet->size); } // void PacketWrite16(Packet *packet, uint16_t value) { - printf("Original: 0x%04" PRIX16 " - %" PRIu16 "\n", value, value); - uint8_t *data = packet->data + packet->offs; - *data++ = (uint8_t)(value >> 8); - *data++ = (uint8_t)(value); - packet->size += sizeof(uint16_t); - packet->offs += sizeof(uint16_t); - printf("Network: 0x%04" PRIX16 " - %" PRIu16 "\n", (uint16_t) *data, (uint16_t) *data); + printf("Original: 0x%04" PRIX16 " - %" PRIu16 "\n", value, value); + uint8_t *data = packet->data + packet->offs; + *data++ = (uint8_t)(value >> 8); + *data++ = (uint8_t)(value); + packet->size += sizeof(uint16_t); + packet->offs += sizeof(uint16_t); + printf("Network: 0x%04" PRIX16 " - %" PRIu16 "\n", (uint16_t) *data, (uint16_t) *data); } // void PacketWrite32(Packet *packet, uint32_t value) { - printf("Original: 0x%08" PRIX32 " - %" PRIu32 "\n", value, value); - uint8_t *data = packet->data + packet->offs; - *data++ = (uint8_t)(value >> 24); - *data++ = (uint8_t)(value >> 16); - *data++ = (uint8_t)(value >> 8); - *data++ = (uint8_t)(value); - packet->size += sizeof(uint32_t); - packet->offs += sizeof(uint32_t); - printf("Network: 0x%08" PRIX32 " - %" PRIu32 "\n", - (uint32_t)(((intptr_t) packet->data) - packet->offs), - (uint32_t)(((intptr_t) packet->data) - packet->offs)); + printf("Original: 0x%08" PRIX32 " - %" PRIu32 "\n", value, value); + uint8_t *data = packet->data + packet->offs; + *data++ = (uint8_t)(value >> 24); + *data++ = (uint8_t)(value >> 16); + *data++ = (uint8_t)(value >> 8); + *data++ = (uint8_t)(value); + packet->size += sizeof(uint32_t); + packet->offs += sizeof(uint32_t); + printf("Network: 0x%08" PRIX32 " - %" PRIu32 "\n", + (uint32_t)(((intptr_t) packet->data) - packet->offs), + (uint32_t)(((intptr_t) packet->data) - packet->offs)); } // void PacketWrite64(Packet *packet, uint64_t value) { - printf("Original: 0x%016" PRIX64 " - %" PRIu64 "\n", value, value); - uint8_t *data = packet->data + packet->offs; - *data++ = (uint8_t)(value >> 56); - *data++ = (uint8_t)(value >> 48); - *data++ = (uint8_t)(value >> 40); - *data++ = (uint8_t)(value >> 32); - *data++ = (uint8_t)(value >> 24); - *data++ = (uint8_t)(value >> 16); - *data++ = (uint8_t)(value >> 8); - *data++ = (uint8_t)(value); - packet->size += sizeof(uint64_t); - packet->offs += sizeof(uint64_t); - printf("Network: 0x%016" PRIX64 " - %" PRIu64 "\n", - (uint64_t)(packet->data - packet->offs), - (uint64_t)(packet->data - packet->offs)); + printf("Original: 0x%016" PRIX64 " - %" PRIu64 "\n", value, value); + uint8_t *data = packet->data + packet->offs; + *data++ = (uint8_t)(value >> 56); + *data++ = (uint8_t)(value >> 48); + *data++ = (uint8_t)(value >> 40); + *data++ = (uint8_t)(value >> 32); + *data++ = (uint8_t)(value >> 24); + *data++ = (uint8_t)(value >> 16); + *data++ = (uint8_t)(value >> 8); + *data++ = (uint8_t)(value); + packet->size += sizeof(uint64_t); + packet->offs += sizeof(uint64_t); + printf("Network: 0x%016" PRIX64 " - %" PRIu64 "\n", + (uint64_t)(packet->data - packet->offs), + (uint64_t)(packet->data - packet->offs)); } // uint16_t PacketRead16(Packet *packet) { - uint8_t *data = packet->data + packet->offs; - packet->size += sizeof(uint16_t); - packet->offs += sizeof(uint16_t); - uint16_t value = ((uint16_t) data[0] << 8) | data[1]; - printf("Original: 0x%04" PRIX16 " - %" PRIu16 "\n", value, value); - return value; + uint8_t *data = packet->data + packet->offs; + packet->size += sizeof(uint16_t); + packet->offs += sizeof(uint16_t); + uint16_t value = ((uint16_t) data[0] << 8) | data[1]; + printf("Original: 0x%04" PRIX16 " - %" PRIu16 "\n", value, value); + return value; } // uint32_t PacketRead32(Packet *packet) { - uint8_t *data = packet->data + packet->offs; - packet->size += sizeof(uint32_t); - packet->offs += sizeof(uint32_t); - uint32_t value = ((uint32_t) data[0] << 24) | ((uint32_t) data[1] << 16) | ((uint32_t) data[2] << 8) | data[3]; - printf("Original: 0x%08" PRIX32 " - %" PRIu32 "\n", value, value); - return value; + uint8_t *data = packet->data + packet->offs; + packet->size += sizeof(uint32_t); + packet->offs += sizeof(uint32_t); + uint32_t value = ((uint32_t) data[0] << 24) | ((uint32_t) data[1] << 16) | ((uint32_t) data[2] << 8) | data[3]; + printf("Original: 0x%08" PRIX32 " - %" PRIu32 "\n", value, value); + return value; } // uint64_t PacketRead64(Packet *packet) { - uint8_t *data = packet->data + packet->offs; - packet->size += sizeof(uint64_t); - packet->offs += sizeof(uint64_t); - uint64_t value = ((uint64_t) data[0] << 56) | ((uint64_t) data[1] << 48) | ((uint64_t) data[2] << 40) | ((uint64_t) data[3] << 32) | ((uint64_t) data[4] << 24) | ((uint64_t) data[5] << 16) | ((uint64_t) data[6] << 8) | data[7]; - printf("Original: 0x%016" PRIX64 " - %" PRIu64 "\n", value, value); - return value; + uint8_t *data = packet->data + packet->offs; + packet->size += sizeof(uint64_t); + packet->offs += sizeof(uint64_t); + uint64_t value = ((uint64_t) data[0] << 56) | ((uint64_t) data[1] << 48) | ((uint64_t) data[2] << 40) | ((uint64_t) data[3] << 32) | ((uint64_t) data[4] << 24) | ((uint64_t) data[5] << 16) | ((uint64_t) data[6] << 8) | data[7]; + printf("Original: 0x%016" PRIX64 " - %" PRIu64 "\n", value, value); + return value; } diff --git a/src/rnet.h b/src/rnet.h index f5dde220..6dbcb925 100644 --- a/src/rnet.h +++ b/src/rnet.h @@ -78,15 +78,15 @@ #define NOMSG // typedef MSG and associated routines #define NOOPENFILE // OpenFile(), OemToAnsi, AnsiToOem, and OF_* #define NOSCROLL // SB_* and scrolling routines -#define NOSERVICE // All Service Controller routines, SERVICE_ equates, etc. -#define NOSOUND // Sound driver routines -#define NOTEXTMETRIC // typedef TEXTMETRIC and associated routines -#define NOWH // SetWindowsHook and WH_* -#define NOWINOFFSETS // GWL_*, GCL_*, associated routines -#define NOCOMM // COMM driver routines -#define NOKANJI // Kanji support stuff. -#define NOHELP // Help engine interface. -#define NOPROFILER // Profiler interface. +#define NOSERVICE // All Service Controller routines, SERVICE_ equates, etc. +#define NOSOUND // Sound driver routines +#define NOTEXTMETRIC // typedef TEXTMETRIC and associated routines +#define NOWH // SetWindowsHook and WH_* +#define NOWINOFFSETS // GWL_*, GCL_*, associated routines +#define NOCOMM // COMM driver routines +#define NOKANJI // Kanji support stuff. +#define NOHELP // Help engine interface. +#define NOPROFILER // Profiler interface. #define NODEFERWINDOWPOS // DeferWindowPos routines #define NOMCX // Modem Configuration Extensions #define MMNOSOUND @@ -101,21 +101,21 @@ typedef int socklen_t; #endif #ifndef RESULT_SUCCESS -# define RESULT_SUCCESS 0 +# define RESULT_SUCCESS 0 #endif // RESULT_SUCCESS #ifndef RESULT_FAILURE -# define RESULT_FAILURE 1 +# define RESULT_FAILURE 1 #endif // RESULT_FAILURE #ifndef htonll -# ifdef _BIG_ENDIAN -# define htonll(x) (x) -# define ntohll(x) (x) -# else -# define htonll(x) ((((uint64) htonl(x)) << 32) + htonl(x >> 32)) -# define ntohll(x) ((((uint64) ntohl(x)) << 32) + ntohl(x >> 32)) -# endif // _BIG_ENDIAN +# ifdef _BIG_ENDIAN +# define htonll(x) (x) +# define ntohll(x) (x) +# else +# define htonll(x) ((((uint64) htonl(x)) << 32) + htonl(x >> 32)) +# define ntohll(x) ((((uint64) ntohl(x)) << 32) + ntohl(x >> 32)) +# endif // _BIG_ENDIAN #endif // htonll //---------------------------------------------------------------------------------- @@ -124,44 +124,42 @@ typedef int socklen_t; //---------------------------------------------------------------------------------- // Include system network headers - #if defined(_WIN32) -# pragma comment(lib, "ws2_32.lib") -# define __USE_W32_SOCKETS -# define WIN32_LEAN_AND_MEAN -# include -# include -# include -# define IPTOS_LOWDELAY 0x10 -#else /* UNIX */ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -#endif /* WIN32 */ + #define __USE_W32_SOCKETS + #define WIN32_LEAN_AND_MEAN + #include + #include + #include + #define IPTOS_LOWDELAY 0x10 +#else // Unix + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +#endif #ifndef INVALID_SOCKET -# define INVALID_SOCKET ~(0) + #define INVALID_SOCKET ~(0) #endif #ifndef __USE_W32_SOCKETS -# define closesocket close -# define SOCKET int -# define INVALID_SOCKET -1 -# define SOCKET_ERROR -1 + #define closesocket close + #define SOCKET int + #define INVALID_SOCKET -1 + #define SOCKET_ERROR -1 #endif #ifdef __USE_W32_SOCKETS -# ifndef EINTR -# define EINTR WSAEINTR -# endif + #ifndef EINTR + #define EINTR WSAEINTR + #endif #endif //---------------------------------------------------------------------------------- @@ -171,9 +169,9 @@ typedef int socklen_t; // Network connection related defines #define SOCKET_MAX_SET_SIZE (32) // Maximum sockets in a set #define SOCKET_MAX_QUEUE_SIZE (16) // Maximum socket queue size -#define SOCKET_MAX_SOCK_OPTS (4) // Maximum socket options -#define SOCKET_MAX_UDPCHANNELS (32) // Maximum UDP channels -#define SOCKET_MAX_UDPADDRESSES (4) // Maximum bound UDP addresses +#define SOCKET_MAX_SOCK_OPTS (4) // Maximum socket options +#define SOCKET_MAX_UDPCHANNELS (32) // Maximum UDP channels +#define SOCKET_MAX_UDPADDRESSES (4) // Maximum bound UDP addresses // Network address related defines @@ -231,97 +229,87 @@ typedef int socklen_t; #endif // Network typedefs -typedef uint32_t SocketChannel; -typedef struct _AddressInformation * AddressInformation; -typedef struct _SocketAddress * SocketAddress; -typedef struct _SocketAddressIPv4 * SocketAddressIPv4; -typedef struct _SocketAddressIPv6 * SocketAddressIPv6; +typedef uint32_t SocketChannel; +typedef struct _AddressInformation *AddressInformation; +typedef struct _SocketAddress *SocketAddress; +typedef struct _SocketAddressIPv4 *SocketAddressIPv4; +typedef struct _SocketAddressIPv6 *SocketAddressIPv6; typedef struct _SocketAddressStorage *SocketAddressStorage; // IPAddress definition (in network byte order) -typedef struct IPAddress -{ - unsigned long host; /* 32-bit IPv4 host address */ - unsigned short port; /* 16-bit protocol port */ +typedef struct IPAddress { + unsigned long host; /* 32-bit IPv4 host address */ + unsigned short port; /* 16-bit protocol port */ } IPAddress; // An option ID, value, sizeof(value) tuple for setsockopt(2). -typedef struct SocketOpt -{ - int id; - void *value; - int valueLen; +typedef struct SocketOpt { + int id; + void *value; + int valueLen; } SocketOpt; -typedef enum -{ - SOCKET_TCP = 0, // SOCK_STREAM - SOCKET_UDP = 1 // SOCK_DGRAM +typedef enum { + SOCKET_TCP = 0, // SOCK_STREAM + SOCKET_UDP = 1 // SOCK_DGRAM } SocketType; -typedef struct UDPChannel -{ - int numbound; // The total number of addresses this channel is bound to - IPAddress address[SOCKET_MAX_UDPADDRESSES]; // The list of remote addresses this channel is bound to +typedef struct UDPChannel { + int numbound; // The total number of addresses this channel is bound to + IPAddress address[SOCKET_MAX_UDPADDRESSES]; // The list of remote addresses this channel is bound to } UDPChannel; -typedef struct Socket -{ - int ready; // Is the socket ready? i.e. has information - int status; // The last status code to have occured using this socket - bool isServer; // Is this socket a server socket (i.e. TCP/UDP Listen Server) - SocketChannel channel; // The socket handle id - SocketType type; // Is this socket a TCP or UDP socket? - bool isIPv6; // Is this socket address an ipv6 address? - SocketAddressIPv4 addripv4; // The host/target IPv4 for this socket (in network byte order) - SocketAddressIPv6 addripv6; // The host/target IPv6 for this socket (in network byte order) - - struct UDPChannel binding[SOCKET_MAX_UDPCHANNELS]; // The amount of channels (if UDP) this socket is bound to +typedef struct Socket { + int ready; // Is the socket ready? i.e. has information + int status; // The last status code to have occured using this socket + bool isServer; // Is this socket a server socket (i.e. TCP/UDP Listen Server) + SocketChannel channel; // The socket handle id + SocketType type; // Is this socket a TCP or UDP socket? + bool isIPv6; // Is this socket address an ipv6 address? + SocketAddressIPv4 addripv4; // The host/target IPv4 for this socket (in network byte order) + SocketAddressIPv6 addripv6; // The host/target IPv6 for this socket (in network byte order) + + struct UDPChannel binding[SOCKET_MAX_UDPCHANNELS]; // The amount of channels (if UDP) this socket is bound to } Socket; -typedef struct SocketSet -{ - int numsockets; - int maxsockets; - struct Socket **sockets; +typedef struct SocketSet { + int numsockets; + int maxsockets; + struct Socket **sockets; } SocketSet; -typedef struct SocketDataPacket -{ - int channel; // The src/dst channel of the packet - unsigned char *data; // The packet data - int len; // The length of the packet data - int maxlen; // The size of the data buffer - int status; // packet status after sending - IPAddress address; // The source/dest address of an incoming/outgoing packet +typedef struct SocketDataPacket { + int channel; // The src/dst channel of the packet + unsigned char *data; // The packet data + int len; // The length of the packet data + int maxlen; // The size of the data buffer + int status; // packet status after sending + IPAddress address; // The source/dest address of an incoming/outgoing packet } SocketDataPacket; // Configuration for a socket. -typedef struct SocketConfig -{ - char * host; // The host address in xxx.xxx.xxx.xxx form - char * port; // The target port/service in the form "http" or "25565" - bool server; // Listen for incoming clients? - SocketType type; // The type of socket, TCP/UDP - bool nonblocking; // non-blocking operation? - int backlog_size; // set a custom backlog size - SocketOpt sockopts[SOCKET_MAX_SOCK_OPTS]; +typedef struct SocketConfig { + char * host; // The host address in xxx.xxx.xxx.xxx form + char * port; // The target port/service in the form "http" or "25565" + bool server; // Listen for incoming clients? + SocketType type; // The type of socket, TCP/UDP + bool nonblocking; // non-blocking operation? + int backlog_size; // set a custom backlog size + SocketOpt sockopts[SOCKET_MAX_SOCK_OPTS]; } SocketConfig; // Result from calling open with a given config. -typedef struct SocketResult -{ - int status; - Socket *socket; +typedef struct SocketResult { + int status; + Socket *socket; } SocketResult; // Packet type -typedef struct Packet -{ - uint32_t size; // The total size of bytes in data - uint32_t offs; // The offset to data access - uint32_t maxs; // The max size of data - uint8_t *data; // Data stored in network byte order +typedef struct Packet { + uint32_t size; // The total size of bytes in data + uint32_t offs; // The offset to data access + uint32_t maxs; // The max size of data + uint8_t *data; // Data stored in network byte order } Packet; -- cgit v1.2.3 From 7e444d5a45f3b141f9f1137859c6d698c3ca6ccd Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 22 Apr 2019 22:47:50 +0200 Subject: Renamed file to avoid breaking build --- src/rnet.c | 2024 ----------------------------------------------------- src/rnet.c.review | 2024 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 2024 insertions(+), 2024 deletions(-) delete mode 100644 src/rnet.c create mode 100644 src/rnet.c.review (limited to 'src') diff --git a/src/rnet.c b/src/rnet.c deleted file mode 100644 index 55d4a26a..00000000 --- a/src/rnet.c +++ /dev/null @@ -1,2024 +0,0 @@ -/********************************************************************************************* -* -* rnet - A simple and easy-to-use network module for raylib -* -* FEATURES: -* - Provides a simple and (hopefully) easy to use wrapper around the Berkeley socket API -* -* DEPENDENCIES: -* raylib.h - TraceLog -* rnet.h - platform-specific network includes -* -* CONTRIBUTORS: -* Jak Barnes (github: @syphonx) (Feb. 2019) - Initial version -* -* -* LICENSE: zlib/libpng -* -* Copyright (c) 2019 Jak Barnes (github: @syphonx) and Ramon Santamaria (@raysan5) -* -* 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, subject to the following restrictions: -* -* 1. The origin of this software must not be misrepresented; you must not claim that you -* wrote the original software. If you use this software in a product, an acknowledgment -* in the product documentation would be appreciated but is not required. -* -* 2. Altered source versions must be plainly marked as such, and must not be misrepresented -* as being the original software. -* -* 3. This notice may not be removed or altered from any source distribution. -* -**********************************************************************************************/ - -//---------------------------------------------------------------------------------- -// Check if config flags have been externally provided on compilation line -//---------------------------------------------------------------------------------- - -#include "rnet.h" - -#include "raylib.h" - -#include // Required for: assert() -#include // Required for: FILE, fopen(), fclose(), fread() -#include // Required for: malloc(), free() -#include // Required for: strcmp(), strncmp() - -//---------------------------------------------------------------------------------- -// Module defines -//---------------------------------------------------------------------------------- - -#define NET_DEBUG_ENABLED (1) - -//---------------------------------------------------------------------------------- -// Types and Structures Definition -//---------------------------------------------------------------------------------- - -typedef struct _SocketAddress -{ - struct sockaddr address; -} _SocketAddress; - -typedef struct _SocketAddressIPv4 -{ - struct sockaddr_in address; -} _SocketAddressIPv4; - -typedef struct _SocketAddressIPv6 -{ - struct sockaddr_in6 address; -} _SocketAddressIPv6; - -typedef struct _SocketAddressStorage -{ - struct sockaddr_storage address; -} _SocketAddressStorage; - -typedef struct _AddressInformation -{ - struct addrinfo addr; -} _AddressInformation; - - - -//---------------------------------------------------------------------------------- -// Global module forward declarations -//---------------------------------------------------------------------------------- - -static void PrintSocket(struct sockaddr_storage *addr, const int family, const int socktype, const int protocol); -static const char *SocketAddressToString(struct sockaddr_storage *sockaddr); -static bool IsIPv4Address(const char *ip); -static bool IsIPv6Address(const char *ip); -static void *GetSocketPortPtr(struct sockaddr_storage *sa); -static void *GetSocketAddressPtr(struct sockaddr_storage *sa); -static bool IsSocketValid(Socket *sock); -static void SocketSetLastError(int err); -static int SocketGetLastError(); -static char *SocketGetLastErrorString(); -static char *SocketErrorCodeToString(int err); -static bool SocketSetDefaults(SocketConfig *config); -static bool InitSocket(Socket *sock, struct addrinfo *addr); -static bool CreateSocket(SocketConfig *config, SocketResult *outresult); -static bool SocketSetBlocking(Socket *sock); -static bool SocketSetNonBlocking(Socket *sock); -static bool SocketSetOptions(SocketConfig *config, Socket *sock); -static void SocketSetHints(SocketConfig *config, struct addrinfo *hints); - -//---------------------------------------------------------------------------------- -// Global module implementation -//---------------------------------------------------------------------------------- - -// Print socket information -static void PrintSocket(struct sockaddr_storage *addr, const int family, const int socktype, const int protocol) -{ - switch (family) - { - case AF_UNSPEC: { TraceLog(LOG_DEBUG, "\tFamily: Unspecified"); - } - break; - case AF_INET: - { - TraceLog(LOG_DEBUG, "\tFamily: AF_INET (IPv4)"); - TraceLog(LOG_INFO, "\t- IPv4 address %s", SocketAddressToString(addr)); - } - break; - case AF_INET6: - { - TraceLog(LOG_DEBUG, "\tFamily: AF_INET6 (IPv6)"); - TraceLog(LOG_INFO, "\t- IPv6 address %s", SocketAddressToString(addr)); - } - break; - case AF_NETBIOS: - { - TraceLog(LOG_DEBUG, "\tFamily: AF_NETBIOS (NetBIOS)"); - } - break; - default: { TraceLog(LOG_DEBUG, "\tFamily: Other %ld", family); - } - break; - } - TraceLog(LOG_DEBUG, "\tSocket type:"); - switch (socktype) - { - case 0: TraceLog(LOG_DEBUG, "\t- Unspecified"); break; - case SOCK_STREAM: - TraceLog(LOG_DEBUG, "\t- SOCK_STREAM (stream)"); - break; - case SOCK_DGRAM: - TraceLog(LOG_DEBUG, "\t- SOCK_DGRAM (datagram)"); - break; - case SOCK_RAW: TraceLog(LOG_DEBUG, "\t- SOCK_RAW (raw)"); break; - case SOCK_RDM: - TraceLog(LOG_DEBUG, "\t- SOCK_RDM (reliable message datagram)"); - break; - case SOCK_SEQPACKET: - TraceLog(LOG_DEBUG, "\t- SOCK_SEQPACKET (pseudo-stream packet)"); - break; - default: TraceLog(LOG_DEBUG, "\t- Other %ld", socktype); break; - } - TraceLog(LOG_DEBUG, "\tProtocol:"); - switch (protocol) - { - case 0: TraceLog(LOG_DEBUG, "\t- Unspecified"); break; - case IPPROTO_TCP: TraceLog(LOG_DEBUG, "\t- IPPROTO_TCP (TCP)"); break; - case IPPROTO_UDP: TraceLog(LOG_DEBUG, "\t- IPPROTO_UDP (UDP)"); break; - default: TraceLog(LOG_DEBUG, "\t- Other %ld", protocol); break; - } -} - -// Convert network ordered socket address to human readable string (127.0.0.1) -static const char *SocketAddressToString(struct sockaddr_storage *sockaddr) -{ - //static const char* ipv6[INET6_ADDRSTRLEN]; - assert(sockaddr != NULL); - assert(sockaddr->ss_family == AF_INET || sockaddr->ss_family == AF_INET6); - switch (sockaddr->ss_family) - { - case AF_INET: - { - //struct sockaddr_in *s = ((struct sockaddr_in *) sockaddr); - //return inet_ntop(AF_INET, &s->sin_addr, ipv6, INET_ADDRSTRLEN); // TODO. - } - break; - case AF_INET6: - { - //struct sockaddr_in6 *s = ((struct sockaddr_in6 *) sockaddr); - //return inet_ntop(AF_INET6, &s->sin6_addr, ipv6, INET6_ADDRSTRLEN); // TODO. - } - break; - } - return NULL; -} - -// Check if the null terminated string ip is a valid IPv4 address -static bool IsIPv4Address(const char *ip) -{ - /* - struct sockaddr_in sa; - int result = inet_pton(AF_INET, ip, &(sa.sin_addr)); // TODO. - return (result != 0); - */ - return false; -} - -// Check if the null terminated string ip is a valid IPv6 address -static bool IsIPv6Address(const char *ip) -{ - /* - struct sockaddr_in6 sa; - int result = inet_pton(AF_INET6, ip, &(sa.sin6_addr)); // TODO. - return result != 0; - */ - return false; -} - -// Return a pointer to the port from the correct address family (IPv4, or IPv6) -static void *GetSocketPortPtr(struct sockaddr_storage *sa) -{ - if (sa->ss_family == AF_INET) - { - return &(((struct sockaddr_in *) sa)->sin_port); - } - - return &(((struct sockaddr_in6 *) sa)->sin6_port); -} - -// Return a pointer to the address from the correct address family (IPv4, or IPv6) -static void *GetSocketAddressPtr(struct sockaddr_storage *sa) -{ - if (sa->ss_family == AF_INET) - { - return &(((struct sockaddr_in *) sa)->sin_addr); - } - - return &(((struct sockaddr_in6 *) sa)->sin6_addr); -} - -// Is the socket in a valid state? -static bool IsSocketValid(Socket *sock) -{ - if (sock != NULL) - { - return (sock->channel != INVALID_SOCKET); - } - return false; -} - -// Sets the error code that can be retrieved through the WSAGetLastError function. -static void SocketSetLastError(int err) -{ -#if defined(_WIN32) - WSASetLastError(err); -#else - errno = err; -#endif -} - -// Returns the error status for the last Sockets operation that failed -static int SocketGetLastError() -{ -#if defined(_WIN32) - return WSAGetLastError(); -#else - return errno; -#endif -} - -// Returns a human-readable string representing the last error message -static char *SocketGetLastErrorString() -{ - return SocketErrorCodeToString(SocketGetLastError()); -} - -// Returns a human-readable string representing the error message (err) -static char *SocketErrorCodeToString(int err) -{ -#if defined(_WIN32) - static char gaiStrErrorBuffer[GAI_STRERROR_BUFFER_SIZE]; - sprintf(gaiStrErrorBuffer, "%s", gai_strerror(err)); - return gaiStrErrorBuffer; -#else - return gai_strerror(err); -#endif -} - -// Set the defaults in the supplied SocketConfig if they're not already set -static bool SocketSetDefaults(SocketConfig *config) -{ - if (config->backlog_size == 0) - { - config->backlog_size = SOCKET_MAX_QUEUE_SIZE; - } - - return true; -} - -// Create the socket channel -static bool InitSocket(Socket *sock, struct addrinfo *addr) -{ - switch (sock->type) - { - case SOCKET_TCP: - if (addr->ai_family == AF_INET) - { - sock->channel = socket(AF_INET, SOCK_STREAM, 0); - } - else - { - sock->channel = socket(AF_INET6, SOCK_STREAM, 0); - } - break; - case SOCKET_UDP: - if (addr->ai_family == AF_INET) - { - sock->channel = socket(AF_INET, SOCK_DGRAM, 0); - } - else - { - sock->channel = socket(AF_INET6, SOCK_DGRAM, 0); - } - break; - default: - TraceLog(LOG_WARNING, "Invalid socket type specified."); - break; - } - return IsSocketValid(sock); -} - -// CreateSocket() - Interally called by CreateSocket() -// -// This here is the bread and butter of the socket API, This function will -// attempt to open a socket, bind and listen to it based on the config passed in -// -// SocketConfig* config - Configuration for which socket to open -// SocketResult* result - The results of this function (if any, including errors) -// -// e.g. -// SocketConfig server_config = { SocketConfig client_config = { -// .host = "127.0.0.1", .host = "127.0.0.1", -// .port = 8080, .port = 8080, -// .server = true, }; -// .nonblocking = true, -// }; -// SocketResult server_res; SocketResult client_res; -static bool CreateSocket(SocketConfig *config, SocketResult *outresult) -{ - bool success = true; - int addrstatus; - struct addrinfo hints; // Address flags (IPV4, IPV6, UDP?) - struct addrinfo *res; // A pointer to the resulting address list - outresult->socket->channel = INVALID_SOCKET; - outresult->status = RESULT_FAILURE; - - // Set the socket type - outresult->socket->type = config->type; - - // Set the hints based on information in the config - // - // AI_CANONNAME Causes the ai_canonname of the result to the filled out with the host's canonical (real) name. - // AI_PASSIVE: Causes the result's IP address to be filled out with INADDR_ANY (IPv4)or in6addr_any (IPv6); - // Note: This causes a subsequent call to bind() to auto-fill the IP address - // of the struct sockaddr with the address of the current host. - // - SocketSetHints(config, &hints); - - // Populate address information - addrstatus = getaddrinfo(config->host, // e.g. "www.example.com" or IP (Can be null if AI_PASSIVE flag is set - config->port, // e.g. "http" or port number - &hints, // e.g. SOCK_STREAM/SOCK_DGRAM - &res // The struct to populate - ); - - // Did we succeed? - if (addrstatus != 0) - { - outresult->socket->status = SocketGetLastError(); - TraceLog(LOG_WARNING, - "Socket Error: %s", - SocketErrorCodeToString(outresult->socket->status)); - SocketSetLastError(0); - TraceLog(LOG_WARNING, - "Failed to get resolve host %s:%s: %s", - config->host, - config->port, - SocketGetLastErrorString()); - return (success = false); - } - else - { - char hoststr[NI_MAXHOST]; - char portstr[NI_MAXSERV]; - //socklen_t client_len = sizeof(struct sockaddr_storage); - //int rc = getnameinfo((struct sockaddr *) res->ai_addr, client_len, hoststr, sizeof(hoststr), portstr, sizeof(portstr), NI_NUMERICHOST | NI_NUMERICSERV); - TraceLog(LOG_INFO, "Successfully resolved host %s:%s", hoststr, portstr); - } - - // Walk the address information linked-list - struct addrinfo *it; - for (it = res; it != NULL; it = it->ai_next) - { - // Initialise the socket - if (!InitSocket(outresult->socket, it)) - { - outresult->socket->status = SocketGetLastError(); - TraceLog(LOG_WARNING, - "Socket Error: %s", - SocketErrorCodeToString(outresult->socket->status)); - SocketSetLastError(0); - continue; - } - - // Set socket options - if (!SocketSetOptions(config, outresult->socket)) - { - outresult->socket->status = SocketGetLastError(); - TraceLog(LOG_WARNING, - "Socket Error: %s", - SocketErrorCodeToString(outresult->socket->status)); - SocketSetLastError(0); - freeaddrinfo(res); - return (success = false); - } - } - - if (!IsSocketValid(outresult->socket)) - { - outresult->socket->status = SocketGetLastError(); - TraceLog( - LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(outresult->status)); - SocketSetLastError(0); - freeaddrinfo(res); - return (success = false); - } - - if (success) - { - outresult->status = RESULT_SUCCESS; - outresult->socket->ready = 0; - outresult->socket->status = 0; - if (!(config->type == SOCKET_UDP)) - { - outresult->socket->isServer = config->server; - } - switch (res->ai_addr->sa_family) - { - case AF_INET: - { - outresult->socket->addripv4 = (struct _SocketAddressIPv4 *) malloc( - sizeof(*outresult->socket->addripv4)); - if (outresult->socket->addripv4 != NULL) - { - memset(outresult->socket->addripv4, 0, - sizeof(*outresult->socket->addripv4)); - if (outresult->socket->addripv4 != NULL) - { - memcpy(&outresult->socket->addripv4->address, - (struct sockaddr_in *) res->ai_addr, sizeof(struct sockaddr_in)); - outresult->socket->isIPv6 = false; - char hoststr[NI_MAXHOST]; - char portstr[NI_MAXSERV]; - socklen_t client_len = sizeof(struct sockaddr_storage); - getnameinfo( - (struct sockaddr *) &outresult->socket->addripv4->address, client_len, hoststr, sizeof(hoststr), portstr, sizeof(portstr), NI_NUMERICHOST | NI_NUMERICSERV); - TraceLog(LOG_INFO, "Socket address set to %s:%s", hoststr, portstr); - } - } - } - break; - case AF_INET6: - { - outresult->socket->addripv6 = (struct _SocketAddressIPv6 *) malloc( - sizeof(*outresult->socket->addripv6)); - if (outresult->socket->addripv6 != NULL) - { - memset(outresult->socket->addripv6, 0, - sizeof(*outresult->socket->addripv6)); - if (outresult->socket->addripv6 != NULL) - { - memcpy(&outresult->socket->addripv6->address, - (struct sockaddr_in6 *) res->ai_addr, sizeof(struct sockaddr_in6)); - outresult->socket->isIPv6 = true; - char hoststr[NI_MAXHOST]; - char portstr[NI_MAXSERV]; - socklen_t client_len = sizeof(struct sockaddr_storage); - getnameinfo( - (struct sockaddr *) &outresult->socket->addripv6->address, client_len, hoststr, sizeof(hoststr), portstr, sizeof(portstr), NI_NUMERICHOST | NI_NUMERICSERV); - TraceLog(LOG_INFO, "Socket address set to %s:%s", hoststr, portstr); - } - } - } - break; - } - } - freeaddrinfo(res); - return success; -} - -// Set the state of the Socket sock to blocking -static bool SocketSetBlocking(Socket *sock) -{ - bool ret = true; -#if defined(_WIN32) - unsigned long mode = 0; - ret = ioctlsocket(sock->channel, FIONBIO, &mode); -#else - const int flags = fcntl(sock->channel, F_GETFL, 0); - if (!(flags & O_NONBLOCK)) - { - TraceLog(LOG_DEBUG, "Socket was already in blocking mode"); - return ret; - } - - ret = (0 == fcntl(sock->channel, F_SETFL, (flags ^ O_NONBLOCK))); -#endif - return ret; -} - -// Set the state of the Socket sock to non-blocking -static bool SocketSetNonBlocking(Socket *sock) -{ - bool ret = true; -#if defined(_WIN32) - unsigned long mode = 1; - ret = ioctlsocket(sock->channel, FIONBIO, &mode); -#else - const int flags = fcntl(sock->channel, F_GETFL, 0); - if ((flags & O_NONBLOCK)) - { - TraceLog(LOG_DEBUG, "Socket was already in non-blocking mode"); - return ret; - } - ret = (0 == fcntl(sock->channel, F_SETFL, (flags | O_NONBLOCK))); -#endif - return ret; -} - -// Set options specified in SocketConfig to Socket sock -static bool SocketSetOptions(SocketConfig *config, Socket *sock) -{ - for (int i = 0; i < SOCKET_MAX_SOCK_OPTS; i++) - { - SocketOpt *opt = &config->sockopts[i]; - if (opt->id == 0) - { - break; - } - - if (setsockopt(sock->channel, SOL_SOCKET, opt->id, opt->value, opt->valueLen) < 0) - { - return false; - } - } - - return true; -} - -// Set "hints" in an addrinfo struct, to be passed to getaddrinfo. -static void SocketSetHints(SocketConfig *config, struct addrinfo *hints) -{ - if (config == NULL || hints == NULL) - { - return; - } - memset(hints, 0, sizeof(*hints)); - - // Check if the ip supplied in the config is a valid ipv4 ip ipv6 address - if (IsIPv4Address(config->host)) - { - hints->ai_family = AF_INET; - hints->ai_flags |= AI_NUMERICHOST; - } - else - { - if (IsIPv6Address(config->host)) - { - hints->ai_family = AF_INET6; - hints->ai_flags |= AI_NUMERICHOST; - } - else - { - hints->ai_family = AF_UNSPEC; - } - } - - if (config->type == SOCKET_UDP) - { - hints->ai_socktype = SOCK_DGRAM; - } - else - { - hints->ai_socktype = SOCK_STREAM; - } - - // Set passive unless UDP client - if (!(config->type == SOCKET_UDP) || config->server) - { - hints->ai_flags = AI_PASSIVE; - } -} - -//---------------------------------------------------------------------------------- -// Module implementation -//---------------------------------------------------------------------------------- - -// Initialise the network (requires for windows platforms only) -bool InitNetwork() -{ -#if defined(_WIN32) - WORD wVersionRequested; - WSADATA wsaData; - int err; - - wVersionRequested = MAKEWORD(2, 2); - err = WSAStartup(wVersionRequested, &wsaData); - if (err != 0) - { - TraceLog(LOG_WARNING, "WinSock failed to initialise."); - return false; - } - else - { - TraceLog(LOG_INFO, "WinSock initialised."); - } - - if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) - { - TraceLog(LOG_WARNING, "WinSock failed to initialise."); - WSACleanup(); - return false; - } - - return true; -#else - return true; -#endif -} - -// Cleanup, and close the network -void CloseNetwork() -{ -#if defined(_WIN32) - WSACleanup(); -#endif -} - -// Protocol-independent name resolution from an address to an ANSI host name -// and from a port number to the ANSI service name. -// -// The flags parameter can be used to customize processing of the getnameinfo function -// -// The following flags are available: -// -// NAME_INFO_DEFAULT 0x00 // No flags set -// NAME_INFO_NOFQDN 0x01 // Only return nodename portion for local hosts -// NAME_INFO_NUMERICHOST 0x02 // Return numeric form of the host's address -// NAME_INFO_NAMEREQD 0x04 // Error if the host's name not in DNS -// NAME_INFO_NUMERICSERV 0x08 // Return numeric form of the service (port #) -// NAME_INFO_DGRAM 0x10 // Service is a datagram service -void ResolveIP(const char *ip, const char *port, int flags, char *host, char *serv) -{ - // Variables - int status; // Status value to return (0) is success - struct addrinfo hints; // Address flags (IPV4, IPV6, UDP?) - struct addrinfo *res; // A pointer to the resulting address list - - // Set the hints - memset(&hints, 0, sizeof hints); - hints.ai_family = AF_UNSPEC; // Either IPv4 or IPv6 (AF_INET, AF_INET6) - hints.ai_protocol = 0; // Automatically select correct protocol (IPPROTO_TCP), (IPPROTO_UDP) - - // Populate address information - status = getaddrinfo(ip, // e.g. "www.example.com" or IP - port, // e.g. "http" or port number - &hints, // e.g. SOCK_STREAM/SOCK_DGRAM - &res // The struct to populate - ); - - // Did we succeed? - if (status != 0) - { - TraceLog(LOG_WARNING, "Failed to get resolve host %s:%s: %s", ip, port, gai_strerror(errno)); - } - else - { - TraceLog(LOG_DEBUG, "Resolving... %s::%s", ip, port); - } - - // Attempt to resolve network byte order ip to hostname - switch (res->ai_family) - { - case AF_INET: - status = getnameinfo(&*((struct sockaddr *) res->ai_addr), - sizeof(*((struct sockaddr_in *) res->ai_addr)), - host, - NI_MAXHOST, - serv, - NI_MAXSERV, - flags); - break; - case AF_INET6: - /* - status = getnameinfo(&*((struct sockaddr_in6 *) res->ai_addr), // TODO. - sizeof(*((struct sockaddr_in6 *) res->ai_addr)), - host, NI_MAXHOST, serv, NI_MAXSERV, flags); - */ - break; - default: break; - } - - if (status != 0) - { - TraceLog(LOG_WARNING, "Failed to resolve ip %s: %s", ip, SocketGetLastErrorString()); - } - else - { - TraceLog(LOG_DEBUG, "Successfully resolved %s::%s to %s", ip, port, host); - } - - // Free the pointer to the data returned by addrinfo - freeaddrinfo(res); -} - -// Protocol-independent translation from an ANSI host name to an address -// -// e.g. -// const char* address = "127.0.0.1" (local address) -// const char* port = "80" -// -// Parameters: -// const char* address - A pointer to a NULL-terminated ANSI string that contains a host (node) name or a numeric host address string. -// const char* service - A pointer to a NULL-terminated ANSI string that contains either a service name or port number represented as a string. -// -// Returns: -// The total amount of addresses found, -1 on error -// -int ResolveHost(const char *address, const char *service, int addressType, int flags, AddressInformation *outAddr) -{ - // Variables - int status; // Status value to return (0) is success - struct addrinfo hints; // Address flags (IPV4, IPV6, UDP?) - struct addrinfo *res; // will point to the results - struct addrinfo *iterator; - assert(((address != NULL || address != 0) || (service != NULL || service != 0))); - assert(((addressType == AF_INET) || (addressType == AF_INET6) || (addressType == AF_UNSPEC))); - - // Set the hints - memset(&hints, 0, sizeof hints); - hints.ai_family = addressType; // Either IPv4 or IPv6 (ADDRESS_TYPE_IPV4, ADDRESS_TYPE_IPV6) - hints.ai_protocol = 0; // Automatically select correct protocol (IPPROTO_TCP), (IPPROTO_UDP) - hints.ai_flags = flags; - assert((hints.ai_addrlen == 0) || (hints.ai_addrlen == 0)); - assert((hints.ai_canonname == 0) || (hints.ai_canonname == 0)); - assert((hints.ai_addr == 0) || (hints.ai_addr == 0)); - assert((hints.ai_next == 0) || (hints.ai_next == 0)); - - // When the address is NULL, populate the IP for me - if (address == NULL) - { - if ((hints.ai_flags & AI_PASSIVE) == 0) - { - hints.ai_flags |= AI_PASSIVE; - } - } - - TraceLog(LOG_INFO, "Resolving host..."); - - // Populate address information - status = getaddrinfo(address, // e.g. "www.example.com" or IP - service, // e.g. "http" or port number - &hints, // e.g. SOCK_STREAM/SOCK_DGRAM - &res // The struct to populate - ); - - // Did we succeed? - if (status != 0) - { - int error = SocketGetLastError(); - SocketSetLastError(0); - TraceLog(LOG_WARNING, "Failed to get resolve host: %s", SocketErrorCodeToString(error)); - return -1; - } - else - { - TraceLog(LOG_INFO, "Successfully resolved host %s:%s", address, service); - } - - // Calculate the size of the address information list - int size = 0; - for (iterator = res; iterator != NULL; iterator = iterator->ai_next) - { - size++; - } - - // Validate the size is > 0, otherwise return - if (size <= 0) - { - TraceLog(LOG_WARNING, "Error, no addresses found."); - return -1; - } - - // If not address list was allocated, allocate it dynamically with the known address size - if (outAddr == NULL) - { - outAddr = (AddressInformation *) malloc(size * sizeof(AddressInformation)); - } - - // Dynamically allocate an array of address information structs - if (outAddr != NULL) - { - int i; - for (i = 0; i < size; ++i) - { - outAddr[i] = AllocAddress(); - if (outAddr[i] == NULL) - { - break; - } - } - outAddr[i] = NULL; - if (i != size) - { - outAddr = NULL; - } - } - else - { - TraceLog(LOG_WARNING, - "Error, failed to dynamically allocate memory for the address list"); - return -1; - } - - // Copy all the address information from res into outAddrList - int i = 0; - for (iterator = res; iterator != NULL; iterator = iterator->ai_next) - { - if (i < size) - { - outAddr[i]->addr.ai_flags = iterator->ai_flags; - outAddr[i]->addr.ai_family = iterator->ai_family; - outAddr[i]->addr.ai_socktype = iterator->ai_socktype; - outAddr[i]->addr.ai_protocol = iterator->ai_protocol; - outAddr[i]->addr.ai_addrlen = iterator->ai_addrlen; - *outAddr[i]->addr.ai_addr = *iterator->ai_addr; -#if NET_DEBUG_ENABLED - TraceLog(LOG_DEBUG, "GetAddressInformation"); - TraceLog(LOG_DEBUG, "\tFlags: 0x%x", iterator->ai_flags); - //PrintSocket(outAddr[i]->addr.ai_addr, outAddr[i]->addr.ai_family, outAddr[i]->addr.ai_socktype, outAddr[i]->addr.ai_protocol); - TraceLog(LOG_DEBUG, "Length of this sockaddr: %d", outAddr[i]->addr.ai_addrlen); - TraceLog(LOG_DEBUG, "Canonical name: %s", iterator->ai_canonname); -#endif - i++; - } - } - - // Free the pointer to the data returned by addrinfo - freeaddrinfo(res); - - // Return the total count of addresses found - return size; -} - -// This here is the bread and butter of the socket API, This function will -// attempt to open a socket, bind and listen to it based on the config passed in -// -// SocketConfig* config - Configuration for which socket to open -// SocketResult* result - The results of this function (if any, including errors) -// -// e.g. -// SocketConfig server_config = { SocketConfig client_config = { -// .host = "127.0.0.1", .host = "127.0.0.1", -// .port = 8080, .port = 8080, -// .server = true, }; -// .nonblocking = true, -// }; -// SocketResult server_res; SocketResult client_res; -bool SocketCreate(SocketConfig *config, SocketResult *result) -{ - // Socket creation result - bool success = true; - - // Make sure we've not received a null config or result pointer - if (config == NULL || result == NULL) - { - return (success = false); - } - - // Set the defaults based on the config - if (!SocketSetDefaults(config)) - { - TraceLog(LOG_WARNING, "Configuration Error."); - success = false; - } - else - { - // Create the socket - if (CreateSocket(config, result)) - { - if (config->nonblocking) - { - SocketSetNonBlocking(result->socket); - } - else - { - SocketSetBlocking(result->socket); - } - } - else - { - success = false; - } - } - return success; -} - -// Bind a socket to a local address -// Note: The bind function is required on an unconnected socket before subsequent calls to the listen function. -bool SocketBind(SocketConfig *config, SocketResult *result) -{ - bool success = false; - result->status = RESULT_FAILURE; - struct sockaddr_storage *sock_addr = NULL; - - // Don't bind to a socket that isn't configured as a server - if (!IsSocketValid(result->socket) || !config->server) - { - TraceLog(LOG_WARNING, - "Cannot bind to socket marked as \"Client\" in SocketConfig."); - success = false; - } - else - { - if (result->socket->isIPv6) - { - sock_addr = (struct sockaddr_storage *) &result->socket->addripv6->address; - } - else - { - sock_addr = (struct sockaddr_storage *) &result->socket->addripv4->address; - } - if (sock_addr != NULL) - { - if (bind(result->socket->channel, (struct sockaddr *) sock_addr, sizeof(*sock_addr)) != SOCKET_ERROR) - { - TraceLog(LOG_INFO, "Successfully bound socket."); - success = true; - } - else - { - result->socket->status = SocketGetLastError(); - TraceLog(LOG_WARNING, "Socket Error: %s", - SocketErrorCodeToString(result->socket->status)); - SocketSetLastError(0); - success = false; - } - } - } - // Was the bind a success? - if (success) - { - result->status = RESULT_SUCCESS; - result->socket->ready = 0; - result->socket->status = 0; - socklen_t sock_len = sizeof(*sock_addr); - if (getsockname(result->socket->channel, (struct sockaddr *) sock_addr, &sock_len) < 0) - { - TraceLog(LOG_WARNING, "Couldn't get socket address"); - } - else - { - struct sockaddr_in *s = (struct sockaddr_in *) sock_addr; - // result->socket->address.host = s->sin_addr.s_addr; - // result->socket->address.port = s->sin_port; - - // - result->socket->addripv4 - = (struct _SocketAddressIPv4 *) malloc(sizeof(*result->socket->addripv4)); - if (result->socket->addripv4 != NULL) - { - memset(result->socket->addripv4, 0, sizeof(*result->socket->addripv4)); - } - memcpy(&result->socket->addripv4->address, (struct sockaddr_in *) &s->sin_addr, sizeof(struct sockaddr_in)); - // - } - } - return success; -} - -// Listens (and queues) incoming connections requests for a bound port. -bool SocketListen(SocketConfig *config, SocketResult *result) -{ - bool success = false; - result->status = RESULT_FAILURE; - - // Don't bind to a socket that isn't configured as a server - if (!IsSocketValid(result->socket) || !config->server) - { - TraceLog(LOG_WARNING, - "Cannot listen on socket marked as \"Client\" in SocketConfig."); - success = false; - } - else - { - // Don't listen on UDP sockets - if (!(config->type == SOCKET_UDP)) - { - if (listen(result->socket->channel, config->backlog_size) != SOCKET_ERROR) - { - TraceLog(LOG_INFO, "Started listening on socket..."); - success = true; - } - else - { - success = false; - result->socket->status = SocketGetLastError(); - TraceLog(LOG_WARNING, "Socket Error: %s", - SocketErrorCodeToString(result->socket->status)); - SocketSetLastError(0); - } - } - else - { - TraceLog(LOG_WARNING, - "Cannot listen on socket marked as \"UDP\" (datagram) in SocketConfig."); - success = false; - } - } - - // Was the listen a success? - if (success) - { - result->status = RESULT_SUCCESS; - result->socket->ready = 0; - result->socket->status = 0; - } - return success; -} - -// Connect the socket to the destination specified by "host" and "port" in SocketConfig -bool SocketConnect(SocketConfig *config, SocketResult *result) -{ - bool success = true; - result->status = RESULT_FAILURE; - - // Only bind to sockets marked as server - if (config->server) - { - TraceLog(LOG_WARNING, - "Cannot connect to socket marked as \"Server\" in SocketConfig."); - success = false; - } - else - { - if (IsIPv4Address(config->host)) - { - struct sockaddr_in ip4addr; - ip4addr.sin_family = AF_INET; - unsigned long hport; - hport = strtoul(config->port, NULL, 0); - ip4addr.sin_port = htons(hport); - - // TODO: Changed the code to avoid the usage of inet_pton and inet_ntop replacing them with getnameinfo (that should have a better support on windows). - - //inet_pton(AF_INET, config->host, &ip4addr.sin_addr); - int connect_result = connect(result->socket->channel, (struct sockaddr *) &ip4addr, sizeof(ip4addr)); - if (connect_result == SOCKET_ERROR) - { - result->socket->status = SocketGetLastError(); - SocketSetLastError(0); - switch (result->socket->status) - { - case WSAEWOULDBLOCK: - { - success = true; - break; - } - default: - { - TraceLog(LOG_WARNING, "Socket Error: %s", - SocketErrorCodeToString(result->socket->status)); - success = false; - break; - } - } - } - else - { - TraceLog(LOG_INFO, "Successfully connected to socket."); - success = true; - } - } - else - { - if (IsIPv6Address(config->host)) - { - struct sockaddr_in6 ip6addr; - ip6addr.sin6_family = AF_INET6; - unsigned long hport; - hport = strtoul(config->port, NULL, 0); - ip6addr.sin6_port = htons(hport); - //inet_pton(AF_INET6, config->host, &ip6addr.sin6_addr); // TODO. - int connect_result = connect(result->socket->channel, (struct sockaddr *) &ip6addr, sizeof(ip6addr)); - if (connect_result == SOCKET_ERROR) - { - result->socket->status = SocketGetLastError(); - SocketSetLastError(0); - switch (result->socket->status) - { - case WSAEWOULDBLOCK: - { - success = true; - break; - } - default: - { - TraceLog(LOG_WARNING, "Socket Error: %s", - SocketErrorCodeToString(result->socket->status)); - success = false; - break; - } - } - } - else - { - TraceLog(LOG_INFO, "Successfully connected to socket."); - success = true; - } - } - } - } - - if (success) - { - result->status = RESULT_SUCCESS; - result->socket->ready = 0; - result->socket->status = 0; - } - - return success; -} - -// Closes an existing socket -// -// SocketChannel socket - The id of the socket to close -void SocketClose(Socket *sock) -{ - if (sock != NULL) - { - if (sock->channel != INVALID_SOCKET) - { - closesocket(sock->channel); - } - } -} - -// Returns the sockaddress for a specific socket in a generic storage struct -SocketAddressStorage SocketGetPeerAddress(Socket *sock) -{ - // TODO. - /* - if (sock->isServer) return NULL; - if (sock->isIPv6) return sock->addripv6; - else return sock->addripv4; - */ - - return NULL; -} - -// Return the address-type appropriate host portion of a socket address -char *GetSocketAddressHost(SocketAddressStorage storage) -{ - assert(storage->address.ss_family == AF_INET || storage->address.ss_family == AF_INET6); - return SocketAddressToString((struct sockaddr_storage *) storage); -} - -// Return the address-type appropriate port(service) portion of a socket address -short GetSocketAddressPort(SocketAddressStorage storage) -{ - //return ntohs(GetSocketPortPtr(storage)); // TODO. - - return 0; -} - -// The accept function permits an incoming connection attempt on a socket. -// -// SocketChannel listener - The socket to listen for incoming connections on (i.e. server) -// SocketResult* out - The result of this function (if any, including errors) -// -// e.g. -// -// SocketResult connection; -// bool connected = false; -// if (!connected) -// { -// if (SocketAccept(server_res.socket.channel, &connection)) -// { -// connected = true; -// } -// } -Socket *SocketAccept(Socket *server, SocketConfig *config) -{ - if (!server->isServer || server->type == SOCKET_UDP) - { - return NULL; - } - struct sockaddr_storage sock_addr; - socklen_t sock_alen; - Socket * sock; - sock = AllocSocket(); - server->ready = 0; - sock_alen = sizeof(sock_addr); - sock->channel = accept(server->channel, (struct sockaddr *) &sock_addr, &sock_alen); - if (sock->channel == INVALID_SOCKET) - { - sock->status = SocketGetLastError(); - TraceLog(LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(sock->status)); - SocketSetLastError(0); - SocketClose(sock); - return NULL; - } - (config->nonblocking) ? SocketSetNonBlocking(sock) : SocketSetBlocking(sock); - sock->isServer = false; - sock->ready = 0; - sock->type = server->type; - switch (sock_addr.ss_family) - { - case AF_INET: - { - struct sockaddr_in *s = ((struct sockaddr_in *) &sock_addr); - sock->addripv4 = (struct _SocketAddressIPv4 *) malloc(sizeof(*sock->addripv4)); - if (sock->addripv4 != NULL) - { - memset(sock->addripv4, 0, sizeof(*sock->addripv4)); - memcpy(&sock->addripv4->address, (struct sockaddr_in *) &s->sin_addr, sizeof(struct sockaddr_in)); - TraceLog(LOG_INFO, "Server: Got connection from %s::%hu", SocketAddressToString((struct sockaddr_storage *) s), - ntohs(sock->addripv4->address.sin_port)); - } - } - break; - case AF_INET6: - { - struct sockaddr_in6 *s = ((struct sockaddr_in6 *) &sock_addr); - sock->addripv6 = (struct _SocketAddressIPv6 *) malloc(sizeof(*sock->addripv6)); - if (sock->addripv6 != NULL) - { - memset(sock->addripv6, 0, sizeof(*sock->addripv6)); - memcpy(&sock->addripv6->address, (struct sockaddr_in6 *) &s->sin6_addr, sizeof(struct sockaddr_in6)); - TraceLog(LOG_INFO, "Server: Got connection from %s::%hu", SocketAddressToString((struct sockaddr_storage *) s), - ntohs(sock->addripv6->address.sin6_port)); - } - } - break; - } - return sock; -} - -// Verify that the channel is in the valid range -static int ValidChannel(int channel) -{ - if ((channel < 0) || (channel >= SOCKET_MAX_UDPCHANNELS)) - { - TraceLog(LOG_WARNING, "Invalid channel"); - return 0; - } - return 1; -} - -// Set the socket channel -int SocketSetChannel(Socket *socket, int channel, const IPAddress *address) -{ - struct UDPChannel *binding; - if (socket == NULL) - { - TraceLog(LOG_WARNING, "Passed a NULL socket"); - return (-1); - } - if (channel == -1) - { - for (channel = 0; channel < SOCKET_MAX_UDPCHANNELS; ++channel) - { - binding = &socket->binding[channel]; - if (binding->numbound < SOCKET_MAX_UDPADDRESSES) - { - break; - } - } - } - else - { - if (!ValidChannel(channel)) - { - return (-1); - } - binding = &socket->binding[channel]; - } - if (binding->numbound == SOCKET_MAX_UDPADDRESSES) - { - TraceLog(LOG_WARNING, "No room for new addresses"); - return (-1); - } - binding->address[binding->numbound++] = *address; - return (channel); -} - -// Remove the socket channel -void SocketUnsetChannel(Socket *socket, int channel) -{ - if ((channel >= 0) && (channel < SOCKET_MAX_UDPCHANNELS)) - { - socket->binding[channel].numbound = 0; - } -} - -/* Allocate/free a single UDP packet 'size' bytes long. - The new packet is returned, or NULL if the function ran out of memory. - */ -SocketDataPacket *AllocPacket(int size) -{ - SocketDataPacket *packet; - int error; - - error = 1; - packet = (SocketDataPacket *) malloc(sizeof(*packet)); - if (packet != NULL) - { - packet->maxlen = size; - packet->data = (uint8_t *) malloc(size); - if (packet->data != NULL) - { - error = 0; - } - } - if (error) - { - FreePacket(packet); - packet = NULL; - } - return (packet); -} - -int ResizePacket(SocketDataPacket *packet, int newsize) -{ - uint8_t *newdata; - - newdata = (uint8_t *) malloc(newsize); - if (newdata != NULL) - { - free(packet->data); - packet->data = newdata; - packet->maxlen = newsize; - } - return (packet->maxlen); -} - -void FreePacket(SocketDataPacket *packet) -{ - if (packet) - { - free(packet->data); - free(packet); - } -} - -/* Allocate/Free a UDP packet vector (array of packets) of 'howmany' packets, - each 'size' bytes long. - A pointer to the packet array is returned, or NULL if the function ran out - of memory. - */ -SocketDataPacket **AllocPacketList(int howmany, int size) -{ - SocketDataPacket **packetV; - - packetV = (SocketDataPacket **) malloc((howmany + 1) * sizeof(*packetV)); - if (packetV != NULL) - { - int i; - for (i = 0; i < howmany; ++i) - { - packetV[i] = AllocPacket(size); - if (packetV[i] == NULL) - { - break; - } - } - packetV[i] = NULL; - - if (i != howmany) - { - FreePacketList(packetV); - packetV = NULL; - } - } - return (packetV); -} - -void FreePacketList(SocketDataPacket **packetV) -{ - if (packetV) - { - int i; - for (i = 0; packetV[i]; ++i) - { - FreePacket(packetV[i]); - } - free(packetV); - } -} - -// Send 'len' bytes of 'data' over the non-server socket 'sock' -// -// Example -int SocketSend(Socket *sock, const void *datap, int length) -{ - int sent = 0; - int left = length; - int status = -1; - int numsent = 0; - const unsigned char *data = (const unsigned char *) datap; - - // Server sockets are for accepting connections only - if (sock->isServer) - { - TraceLog(LOG_WARNING, "Cannot send information on a server socket"); - return -1; - } - - // Which socket are we trying to send data on - switch (sock->type) - { - case SOCKET_TCP: - { - SocketSetLastError(0); - do - { - length = send(sock->channel, (const char *) data, left, 0); - if (length > 0) - { - sent += length; - left -= length; - data += length; - } - } while ((left > 0) && // While we still have bytes left to send - ((length > 0) || // The amount of bytes we actually sent is > 0 - (SocketGetLastError() == WSAEINTR)) // The socket was interupted - ); - - if (length == SOCKET_ERROR) - { - sock->status = SocketGetLastError(); - TraceLog(LOG_DEBUG, "Socket Error: %s", SocketErrorCodeToString(sock->status)); - SocketSetLastError(0); - } - else - { - TraceLog(LOG_DEBUG, "Successfully sent \"%s\" (%d bytes)", datap, sent); - } - - return sent; - } - break; - case SOCKET_UDP: - { - SocketSetLastError(0); - if (sock->isIPv6) - { - status = sendto(sock->channel, (const char *) data, left, 0, - (struct sockaddr *) &sock->addripv6->address, - sizeof(sock->addripv6->address)); - } - else - { - status = sendto(sock->channel, (const char *) data, left, 0, - (struct sockaddr *) &sock->addripv4->address, - sizeof(sock->addripv4->address)); - } - if (sent >= 0) - { - sock->status = 0; - ++numsent; - TraceLog(LOG_DEBUG, "Successfully sent \"%s\" (%d bytes)", datap, status); - } - else - { - sock->status = SocketGetLastError(); - TraceLog(LOG_DEBUG, "Socket Error: %s", SocketGetLastErrorString(sock->status)); - SocketSetLastError(0); - return 0; - } - return numsent; - } - break; - default: break; - } - return -1; -} - -// Receive up to 'maxlen' bytes of data over the non-server socket 'sock', -// and store them in the buffer pointed to by 'data'. -// This function returns the actual amount of data received. If the return -// value is less than or equal to zero, then either the remote connection was -// closed, or an unknown socket error occurred. -int SocketReceive(Socket *sock, void *data, int maxlen) -{ - int len = 0; - int numrecv = 0; - int status = 0; - socklen_t sock_len; - struct sockaddr_storage sock_addr; - //char ip[INET6_ADDRSTRLEN]; - - // Server sockets are for accepting connections only - if (sock->isServer && sock->type == SOCKET_TCP) - { - sock->status = SocketGetLastError(); - TraceLog(LOG_DEBUG, "Socket Error: %s", "Server sockets cannot be used to receive data"); - SocketSetLastError(0); - return 0; - } - - // Which socket are we trying to send data on - switch (sock->type) - { - case SOCKET_TCP: - { - SocketSetLastError(0); - do - { - len = recv(sock->channel, (char *) data, maxlen, 0); - } while (SocketGetLastError() == WSAEINTR); - - if (len > 0) - { - // Who sent the packet? - if (sock->type == SOCKET_UDP) - { - //TraceLog(LOG_DEBUG, "Received data from: %s", inet_ntop(sock_addr.ss_family, GetSocketAddressPtr((struct sockaddr *) &sock_addr), ip, sizeof(ip))); - } - - ((unsigned char *) data)[len] = '\0'; // Add null terminating character to the end of the stream - TraceLog(LOG_DEBUG, "Received \"%s\" (%d bytes)", data, len); - } - - sock->ready = 0; - return len; - } - break; - case SOCKET_UDP: - { - SocketSetLastError(0); - sock_len = sizeof(sock_addr); - status = recvfrom(sock->channel, // The receving channel - data, // A pointer to the data buffer to fill - maxlen, // The max length of the data to fill - 0, // Flags - (struct sockaddr *) &sock_addr, // The address of the recevied data - &sock_len // The length of the received data address - ); - if (status >= 0) - { - ++numrecv; - } - else - { - sock->status = SocketGetLastError(); - switch (sock->status) - { - case WSAEWOULDBLOCK: { break; - } - default: - { - TraceLog(LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(sock->status)); - break; - } - } - SocketSetLastError(0); - return 0; - } - sock->ready = 0; - return numrecv; - } - break; - } - return -1; -} - -// Does the socket have it's 'ready' flag set? -bool IsSocketReady(Socket *sock) -{ - return (sock != NULL) && (sock->ready); -} - -// Check if the socket is considered connected -bool IsSocketConnected(Socket *sock) -{ -#if defined(_WIN32) - FD_SET writefds; - FD_ZERO(&writefds); - FD_SET(sock->channel, &writefds); - struct timeval timeout; - timeout.tv_sec = 1; - timeout.tv_usec = 1000000000UL; - int total = select(0, NULL, &writefds, NULL, &timeout); - if (total == -1) - { // Error - sock->status = SocketGetLastError(); - TraceLog(LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(sock->status)); - SocketSetLastError(0); - } - else if (total == 0) - { // Timeout - return false; - } - else - { - if (FD_ISSET(sock->channel, &writefds)) - { - return true; - } - } - return false; -#else - return true; -#endif -} - -// Allocate and return a SocketResult struct -SocketResult *AllocSocketResult() -{ - struct SocketResult *res; - res = (struct SocketResult *) malloc(sizeof(*res)); - if (res != NULL) - { - memset(res, 0, sizeof(*res)); - if ((res->socket = AllocSocket()) == NULL) - { - free(res); - res = NULL; - } - } - return res; -} - -// Free an allocated SocketResult -void FreeSocketResult(SocketResult **result) -{ - if (*result != NULL) - { - if ((*result)->socket != NULL) - { - FreeSocket(&((*result)->socket)); - } - free(*result); - *result = NULL; - } -} - -// Allocate a Socket -Socket *AllocSocket() -{ - // Allocate a socket if one already hasn't been - struct Socket *sock; - sock = (Socket *) malloc(sizeof(*sock)); - if (sock != NULL) - { - memset(sock, 0, sizeof(*sock)); - } - else - { - TraceLog( - LOG_WARNING, "Ran out of memory attempting to allocate a socket"); - SocketClose(sock); - free(sock); - sock = NULL; - } - return sock; -} - -// Free an allocated Socket -void FreeSocket(Socket **sock) -{ - if (*sock != NULL) - { - free(*sock); - *sock = NULL; - } -} - -// Allocate a SocketSet -SocketSet *AllocSocketSet(int max) -{ - struct SocketSet *set; - int i; - - set = (struct SocketSet *) malloc(sizeof(*set)); - if (set != NULL) - { - set->numsockets = 0; - set->maxsockets = max; - set->sockets = (struct Socket **) malloc(max * sizeof(*set->sockets)); - if (set->sockets != NULL) - { - for (i = 0; i < max; ++i) - { - set->sockets[i] = NULL; - } - } - else - { - free(set); - set = NULL; - } - } - return (set); -} - -// Free an allocated SocketSet -void FreeSocketSet(SocketSet *set) -{ - if (set) - { - free(set->sockets); - free(set); - } -} - -// Add a Socket "sock" to the SocketSet "set" -int AddSocket(SocketSet *set, Socket *sock) -{ - if (sock != NULL) - { - if (set->numsockets == set->maxsockets) - { - TraceLog(LOG_DEBUG, "Socket Error: %s", "SocketSet is full"); - SocketSetLastError(0); - return (-1); - } - set->sockets[set->numsockets++] = (struct Socket *) sock; - } - else - { - TraceLog(LOG_DEBUG, "Socket Error: %s", "Socket was null"); - SocketSetLastError(0); - return (-1); - } - return (set->numsockets); -} - -// Remove a Socket "sock" to the SocketSet "set" -int RemoveSocket(SocketSet *set, Socket *sock) -{ - int i; - - if (sock != NULL) - { - for (i = 0; i < set->numsockets; ++i) - { - if (set->sockets[i] == (struct Socket *) sock) - { - break; - } - } - if (i == set->numsockets) - { - TraceLog(LOG_DEBUG, "Socket Error: %s", "Socket not found"); - SocketSetLastError(0); - return (-1); - } - --set->numsockets; - for (; i < set->numsockets; ++i) - { - set->sockets[i] = set->sockets[i + 1]; - } - } - return (set->numsockets); -} - -// Check the sockets in the socket set for pending information -int CheckSockets(SocketSet *set, unsigned int timeout) -{ - int i; - SOCKET maxfd; - int retval; - struct timeval tv; - fd_set mask; - - /* Find the largest file descriptor */ - maxfd = 0; - for (i = set->numsockets - 1; i >= 0; --i) - { - if (set->sockets[i]->channel > maxfd) - { - maxfd = set->sockets[i]->channel; - } - } - - // Check the file descriptors for available data - do - { - SocketSetLastError(0); - - // Set up the mask of file descriptors - FD_ZERO(&mask); - for (i = set->numsockets - 1; i >= 0; --i) - { - FD_SET(set->sockets[i]->channel, &mask); - } // Set up the timeout - tv.tv_sec = timeout / 1000; - tv.tv_usec = (timeout % 1000) * 1000; - - /* Look! */ - retval = select(maxfd + 1, &mask, NULL, NULL, &tv); - } while (SocketGetLastError() == WSAEINTR); - - // Mark all file descriptors ready that have data available - if (retval > 0) - { - for (i = set->numsockets - 1; i >= 0; --i) - { - if (FD_ISSET(set->sockets[i]->channel, &mask)) - { - set->sockets[i]->ready = 1; - } - } - } - return (retval); -} - -// Allocate an AddressInformation -AddressInformation AllocAddress() -{ - AddressInformation addressInfo = NULL; - addressInfo = (AddressInformation) calloc(1, sizeof(*addressInfo)); - if (addressInfo != NULL) - { - addressInfo->addr.ai_addr = (struct sockaddr *) calloc(1, sizeof(struct sockaddr)); - if (addressInfo->addr.ai_addr == NULL) - { - TraceLog(LOG_WARNING, - "Failed to allocate memory for \"struct sockaddr\""); - } - } - else - { - TraceLog(LOG_WARNING, - "Failed to allocate memory for \"struct AddressInformation\""); - } - return addressInfo; -} - -// Free an AddressInformation struct -void FreeAddress(AddressInformation *addressInfo) -{ - if (*addressInfo != NULL) - { - if ((*addressInfo)->addr.ai_addr != NULL) - { - free((*addressInfo)->addr.ai_addr); - (*addressInfo)->addr.ai_addr = NULL; - } - free(*addressInfo); - *addressInfo = NULL; - } -} - -// Allocate a list of AddressInformation -AddressInformation *AllocAddressList(int size) -{ - AddressInformation *addr; - addr = (AddressInformation *) malloc(size * sizeof(AddressInformation)); - return addr; -} - -// Opaque datatype accessor addrinfo->ai_family -int GetAddressFamily(AddressInformation address) -{ - return address->addr.ai_family; -} - -// Opaque datatype accessor addrinfo->ai_socktype -int GetAddressSocketType(AddressInformation address) -{ - return address->addr.ai_socktype; -} - -// Opaque datatype accessor addrinfo->ai_protocol -int GetAddressProtocol(AddressInformation address) -{ - return address->addr.ai_protocol; -} - -// Opaque datatype accessor addrinfo->ai_canonname -char *GetAddressCanonName(AddressInformation address) -{ - return address->addr.ai_canonname; -} - -// Opaque datatype accessor addrinfo->ai_addr -char *GetAddressHostAndPort(AddressInformation address, char *outhost, int *outport) -{ - //char *ip[INET6_ADDRSTRLEN]; - char *result = NULL; - struct sockaddr_storage *storage = (struct sockaddr_storage *) address->addr.ai_addr; - switch (storage->ss_family) - { - case AF_INET: - { - struct sockaddr_in *s = ((struct sockaddr_in *) address->addr.ai_addr); - //result = inet_ntop(AF_INET, &s->sin_addr, ip, INET_ADDRSTRLEN); // TODO. - *outport = ntohs(s->sin_port); - } - break; - case AF_INET6: - { - struct sockaddr_in6 *s = ((struct sockaddr_in6 *) address->addr.ai_addr); - //result = inet_ntop(AF_INET6, &s->sin6_addr, ip, INET6_ADDRSTRLEN); // TODO. - *outport = ntohs(s->sin6_port); - } - break; - } - if (result == NULL) - { - TraceLog(LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(SocketGetLastError())); - SocketSetLastError(0); - } - else - { - strcpy(outhost, result); - } - return result; -} - -// -void PacketSend(Packet *packet) -{ - printf("Sending packet (%s) with size %d\n", packet->data, packet->size); -} - -// -void PacketReceive(Packet *packet) -{ - printf("Receiving packet (%s) with size %d\n", packet->data, packet->size); -} - -// -void PacketWrite16(Packet *packet, uint16_t value) -{ - printf("Original: 0x%04" PRIX16 " - %" PRIu16 "\n", value, value); - uint8_t *data = packet->data + packet->offs; - *data++ = (uint8_t)(value >> 8); - *data++ = (uint8_t)(value); - packet->size += sizeof(uint16_t); - packet->offs += sizeof(uint16_t); - printf("Network: 0x%04" PRIX16 " - %" PRIu16 "\n", (uint16_t) *data, (uint16_t) *data); -} - -// -void PacketWrite32(Packet *packet, uint32_t value) -{ - printf("Original: 0x%08" PRIX32 " - %" PRIu32 "\n", value, value); - uint8_t *data = packet->data + packet->offs; - *data++ = (uint8_t)(value >> 24); - *data++ = (uint8_t)(value >> 16); - *data++ = (uint8_t)(value >> 8); - *data++ = (uint8_t)(value); - packet->size += sizeof(uint32_t); - packet->offs += sizeof(uint32_t); - printf("Network: 0x%08" PRIX32 " - %" PRIu32 "\n", - (uint32_t)(((intptr_t) packet->data) - packet->offs), - (uint32_t)(((intptr_t) packet->data) - packet->offs)); -} - -// -void PacketWrite64(Packet *packet, uint64_t value) -{ - printf("Original: 0x%016" PRIX64 " - %" PRIu64 "\n", value, value); - uint8_t *data = packet->data + packet->offs; - *data++ = (uint8_t)(value >> 56); - *data++ = (uint8_t)(value >> 48); - *data++ = (uint8_t)(value >> 40); - *data++ = (uint8_t)(value >> 32); - *data++ = (uint8_t)(value >> 24); - *data++ = (uint8_t)(value >> 16); - *data++ = (uint8_t)(value >> 8); - *data++ = (uint8_t)(value); - packet->size += sizeof(uint64_t); - packet->offs += sizeof(uint64_t); - printf("Network: 0x%016" PRIX64 " - %" PRIu64 "\n", - (uint64_t)(packet->data - packet->offs), - (uint64_t)(packet->data - packet->offs)); -} - -// -uint16_t PacketRead16(Packet *packet) -{ - uint8_t *data = packet->data + packet->offs; - packet->size += sizeof(uint16_t); - packet->offs += sizeof(uint16_t); - uint16_t value = ((uint16_t) data[0] << 8) | data[1]; - printf("Original: 0x%04" PRIX16 " - %" PRIu16 "\n", value, value); - return value; -} - -// -uint32_t PacketRead32(Packet *packet) -{ - uint8_t *data = packet->data + packet->offs; - packet->size += sizeof(uint32_t); - packet->offs += sizeof(uint32_t); - uint32_t value = ((uint32_t) data[0] << 24) | ((uint32_t) data[1] << 16) | ((uint32_t) data[2] << 8) | data[3]; - printf("Original: 0x%08" PRIX32 " - %" PRIu32 "\n", value, value); - return value; -} - -// -uint64_t PacketRead64(Packet *packet) -{ - uint8_t *data = packet->data + packet->offs; - packet->size += sizeof(uint64_t); - packet->offs += sizeof(uint64_t); - uint64_t value = ((uint64_t) data[0] << 56) | ((uint64_t) data[1] << 48) | ((uint64_t) data[2] << 40) | ((uint64_t) data[3] << 32) | ((uint64_t) data[4] << 24) | ((uint64_t) data[5] << 16) | ((uint64_t) data[6] << 8) | data[7]; - printf("Original: 0x%016" PRIX64 " - %" PRIu64 "\n", value, value); - return value; -} diff --git a/src/rnet.c.review b/src/rnet.c.review new file mode 100644 index 00000000..5f2c5306 --- /dev/null +++ b/src/rnet.c.review @@ -0,0 +1,2024 @@ +/********************************************************************************************* +* +* rnet - A simple and easy-to-use network module for raylib +* +* FEATURES: +* - Provides a simple and (hopefully) easy to use wrapper around the Berkeley socket API +* +* DEPENDENCIES: +* raylib.h - TraceLog +* rnet.h - platform-specific network includes +* +* CONTRIBUTORS: +* Jak Barnes (github: @syphonx) (Feb. 2019) - Initial version +* +* +* LICENSE: zlib/libpng +* +* Copyright (c) 2019 Jak Barnes (github: @syphonx) and Ramon Santamaria (@raysan5) +* +* 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, subject to the following restrictions: +* +* 1. The origin of this software must not be misrepresented; you must not claim that you +* wrote the original software. If you use this software in a product, an acknowledgment +* in the product documentation would be appreciated but is not required. +* +* 2. Altered source versions must be plainly marked as such, and must not be misrepresented +* as being the original software. +* +* 3. This notice may not be removed or altered from any source distribution. +* +**********************************************************************************************/ + +//---------------------------------------------------------------------------------- +// Check if config flags have been externally provided on compilation line +//---------------------------------------------------------------------------------- + +#include "rnet.h" + +#include "raylib.h" + +#include // Required for: assert() +#include // Required for: FILE, fopen(), fclose(), fread() +#include // Required for: malloc(), free() +#include // Required for: strcmp(), strncmp() + +//---------------------------------------------------------------------------------- +// Module defines +//---------------------------------------------------------------------------------- + +#define NET_DEBUG_ENABLED (1) + +//---------------------------------------------------------------------------------- +// Types and Structures Definition +//---------------------------------------------------------------------------------- + +typedef struct _SocketAddress +{ + struct sockaddr address; +} _SocketAddress; + +typedef struct _SocketAddressIPv4 +{ + struct sockaddr_in address; +} _SocketAddressIPv4; + +typedef struct _SocketAddressIPv6 +{ + struct sockaddr_in6 address; +} _SocketAddressIPv6; + +typedef struct _SocketAddressStorage +{ + struct sockaddr_storage address; +} _SocketAddressStorage; + +typedef struct _AddressInformation +{ + struct addrinfo addr; +} _AddressInformation; + + + +//---------------------------------------------------------------------------------- +// Global module forward declarations +//---------------------------------------------------------------------------------- + +static void PrintSocket(struct sockaddr_storage *addr, const int family, const int socktype, const int protocol); +static const char *SocketAddressToString(struct sockaddr_storage *sockaddr); +static bool IsIPv4Address(const char *ip); +static bool IsIPv6Address(const char *ip); +static void *GetSocketPortPtr(struct sockaddr_storage *sa); +static void *GetSocketAddressPtr(struct sockaddr_storage *sa); +static bool IsSocketValid(Socket *sock); +static void SocketSetLastError(int err); +static int SocketGetLastError(); +static char *SocketGetLastErrorString(); +static char *SocketErrorCodeToString(int err); +static bool SocketSetDefaults(SocketConfig *config); +static bool InitSocket(Socket *sock, struct addrinfo *addr); +static bool CreateSocket(SocketConfig *config, SocketResult *outresult); +static bool SocketSetBlocking(Socket *sock); +static bool SocketSetNonBlocking(Socket *sock); +static bool SocketSetOptions(SocketConfig *config, Socket *sock); +static void SocketSetHints(SocketConfig *config, struct addrinfo *hints); + +//---------------------------------------------------------------------------------- +// Global module implementation +//---------------------------------------------------------------------------------- + +// Print socket information +static void PrintSocket(struct sockaddr_storage *addr, const int family, const int socktype, const int protocol) +{ + switch (family) + { + case AF_UNSPEC: { TraceLog(LOG_DEBUG, "\tFamily: Unspecified"); + } + break; + case AF_INET: + { + TraceLog(LOG_DEBUG, "\tFamily: AF_INET (IPv4)"); + TraceLog(LOG_INFO, "\t- IPv4 address %s", SocketAddressToString(addr)); + } + break; + case AF_INET6: + { + TraceLog(LOG_DEBUG, "\tFamily: AF_INET6 (IPv6)"); + TraceLog(LOG_INFO, "\t- IPv6 address %s", SocketAddressToString(addr)); + } + break; + case AF_NETBIOS: + { + TraceLog(LOG_DEBUG, "\tFamily: AF_NETBIOS (NetBIOS)"); + } + break; + default: { TraceLog(LOG_DEBUG, "\tFamily: Other %ld", family); + } + break; + } + TraceLog(LOG_DEBUG, "\tSocket type:"); + switch (socktype) + { + case 0: TraceLog(LOG_DEBUG, "\t- Unspecified"); break; + case SOCK_STREAM: + TraceLog(LOG_DEBUG, "\t- SOCK_STREAM (stream)"); + break; + case SOCK_DGRAM: + TraceLog(LOG_DEBUG, "\t- SOCK_DGRAM (datagram)"); + break; + case SOCK_RAW: TraceLog(LOG_DEBUG, "\t- SOCK_RAW (raw)"); break; + case SOCK_RDM: + TraceLog(LOG_DEBUG, "\t- SOCK_RDM (reliable message datagram)"); + break; + case SOCK_SEQPACKET: + TraceLog(LOG_DEBUG, "\t- SOCK_SEQPACKET (pseudo-stream packet)"); + break; + default: TraceLog(LOG_DEBUG, "\t- Other %ld", socktype); break; + } + TraceLog(LOG_DEBUG, "\tProtocol:"); + switch (protocol) + { + case 0: TraceLog(LOG_DEBUG, "\t- Unspecified"); break; + case IPPROTO_TCP: TraceLog(LOG_DEBUG, "\t- IPPROTO_TCP (TCP)"); break; + case IPPROTO_UDP: TraceLog(LOG_DEBUG, "\t- IPPROTO_UDP (UDP)"); break; + default: TraceLog(LOG_DEBUG, "\t- Other %ld", protocol); break; + } +} + +// Convert network ordered socket address to human readable string (127.0.0.1) +static const char *SocketAddressToString(struct sockaddr_storage *sockaddr) +{ + //static const char* ipv6[INET6_ADDRSTRLEN]; + assert(sockaddr != NULL); + assert(sockaddr->ss_family == AF_INET || sockaddr->ss_family == AF_INET6); + switch (sockaddr->ss_family) + { + case AF_INET: + { + //struct sockaddr_in *s = ((struct sockaddr_in *) sockaddr); + //return inet_ntop(AF_INET, &s->sin_addr, ipv6, INET_ADDRSTRLEN); // TODO. + } + break; + case AF_INET6: + { + //struct sockaddr_in6 *s = ((struct sockaddr_in6 *) sockaddr); + //return inet_ntop(AF_INET6, &s->sin6_addr, ipv6, INET6_ADDRSTRLEN); // TODO. + } + break; + } + return NULL; +} + +// Check if the null terminated string ip is a valid IPv4 address +static bool IsIPv4Address(const char *ip) +{ + /* + struct sockaddr_in sa; + int result = inet_pton(AF_INET, ip, &(sa.sin_addr)); // TODO. + return (result != 0); + */ + return false; +} + +// Check if the null terminated string ip is a valid IPv6 address +static bool IsIPv6Address(const char *ip) +{ + /* + struct sockaddr_in6 sa; + int result = inet_pton(AF_INET6, ip, &(sa.sin6_addr)); // TODO. + return result != 0; + */ + return false; +} + +// Return a pointer to the port from the correct address family (IPv4, or IPv6) +static void *GetSocketPortPtr(struct sockaddr_storage *sa) +{ + if (sa->ss_family == AF_INET) + { + return &(((struct sockaddr_in *) sa)->sin_port); + } + + return &(((struct sockaddr_in6 *) sa)->sin6_port); +} + +// Return a pointer to the address from the correct address family (IPv4, or IPv6) +static void *GetSocketAddressPtr(struct sockaddr_storage *sa) +{ + if (sa->ss_family == AF_INET) + { + return &(((struct sockaddr_in *) sa)->sin_addr); + } + + return &(((struct sockaddr_in6 *) sa)->sin6_addr); +} + +// Is the socket in a valid state? +static bool IsSocketValid(Socket *sock) +{ + if (sock != NULL) + { + return (sock->channel != INVALID_SOCKET); + } + return false; +} + +// Sets the error code that can be retrieved through the WSAGetLastError function. +static void SocketSetLastError(int err) +{ +#if defined(_WIN32) + WSASetLastError(err); +#else + errno = err; +#endif +} + +// Returns the error status for the last Sockets operation that failed +static int SocketGetLastError() +{ +#if defined(_WIN32) + return WSAGetLastError(); +#else + return errno; +#endif +} + +// Returns a human-readable string representing the last error message +static char *SocketGetLastErrorString() +{ + return SocketErrorCodeToString(SocketGetLastError()); +} + +// Returns a human-readable string representing the error message (err) +static char *SocketErrorCodeToString(int err) +{ +#if defined(_WIN32) + static char gaiStrErrorBuffer[GAI_STRERROR_BUFFER_SIZE]; + sprintf(gaiStrErrorBuffer, "%s", gai_strerror(err)); + return gaiStrErrorBuffer; +#else + return gai_strerror(err); +#endif +} + +// Set the defaults in the supplied SocketConfig if they're not already set +static bool SocketSetDefaults(SocketConfig *config) +{ + if (config->backlog_size == 0) + { + config->backlog_size = SOCKET_MAX_QUEUE_SIZE; + } + + return true; +} + +// Create the socket channel +static bool InitSocket(Socket *sock, struct addrinfo *addr) +{ + switch (sock->type) + { + case SOCKET_TCP: + if (addr->ai_family == AF_INET) + { + sock->channel = socket(AF_INET, SOCK_STREAM, 0); + } + else + { + sock->channel = socket(AF_INET6, SOCK_STREAM, 0); + } + break; + case SOCKET_UDP: + if (addr->ai_family == AF_INET) + { + sock->channel = socket(AF_INET, SOCK_DGRAM, 0); + } + else + { + sock->channel = socket(AF_INET6, SOCK_DGRAM, 0); + } + break; + default: + TraceLog(LOG_WARNING, "Invalid socket type specified."); + break; + } + return IsSocketValid(sock); +} + +// CreateSocket() - Interally called by CreateSocket() +// +// This here is the bread and butter of the socket API, This function will +// attempt to open a socket, bind and listen to it based on the config passed in +// +// SocketConfig* config - Configuration for which socket to open +// SocketResult* result - The results of this function (if any, including errors) +// +// e.g. +// SocketConfig server_config = { SocketConfig client_config = { +// .host = "127.0.0.1", .host = "127.0.0.1", +// .port = 8080, .port = 8080, +// .server = true, }; +// .nonblocking = true, +// }; +// SocketResult server_res; SocketResult client_res; +static bool CreateSocket(SocketConfig *config, SocketResult *outresult) +{ + bool success = true; + int addrstatus; + struct addrinfo hints; // Address flags (IPV4, IPV6, UDP?) + struct addrinfo *res; // A pointer to the resulting address list + outresult->socket->channel = INVALID_SOCKET; + outresult->status = RESULT_FAILURE; + + // Set the socket type + outresult->socket->type = config->type; + + // Set the hints based on information in the config + // + // AI_CANONNAME Causes the ai_canonname of the result to the filled out with the host's canonical (real) name. + // AI_PASSIVE: Causes the result's IP address to be filled out with INADDR_ANY (IPv4)or in6addr_any (IPv6); + // Note: This causes a subsequent call to bind() to auto-fill the IP address + // of the struct sockaddr with the address of the current host. + // + SocketSetHints(config, &hints); + + // Populate address information + addrstatus = getaddrinfo(config->host, // e.g. "www.example.com" or IP (Can be null if AI_PASSIVE flag is set + config->port, // e.g. "http" or port number + &hints, // e.g. SOCK_STREAM/SOCK_DGRAM + &res // The struct to populate + ); + + // Did we succeed? + if (addrstatus != 0) + { + outresult->socket->status = SocketGetLastError(); + TraceLog(LOG_WARNING, + "Socket Error: %s", + SocketErrorCodeToString(outresult->socket->status)); + SocketSetLastError(0); + TraceLog(LOG_WARNING, + "Failed to get resolve host %s:%s: %s", + config->host, + config->port, + SocketGetLastErrorString()); + return (success = false); + } + else + { + char hoststr[NI_MAXHOST]; + char portstr[NI_MAXSERV]; + //socklen_t client_len = sizeof(struct sockaddr_storage); + //int rc = getnameinfo((struct sockaddr *) res->ai_addr, client_len, hoststr, sizeof(hoststr), portstr, sizeof(portstr), NI_NUMERICHOST | NI_NUMERICSERV); + TraceLog(LOG_INFO, "Successfully resolved host %s:%s", hoststr, portstr); + } + + // Walk the address information linked-list + struct addrinfo *it; + for (it = res; it != NULL; it = it->ai_next) + { + // Initialise the socket + if (!InitSocket(outresult->socket, it)) + { + outresult->socket->status = SocketGetLastError(); + TraceLog(LOG_WARNING, + "Socket Error: %s", + SocketErrorCodeToString(outresult->socket->status)); + SocketSetLastError(0); + continue; + } + + // Set socket options + if (!SocketSetOptions(config, outresult->socket)) + { + outresult->socket->status = SocketGetLastError(); + TraceLog(LOG_WARNING, + "Socket Error: %s", + SocketErrorCodeToString(outresult->socket->status)); + SocketSetLastError(0); + freeaddrinfo(res); + return (success = false); + } + } + + if (!IsSocketValid(outresult->socket)) + { + outresult->socket->status = SocketGetLastError(); + TraceLog( + LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(outresult->status)); + SocketSetLastError(0); + freeaddrinfo(res); + return (success = false); + } + + if (success) + { + outresult->status = RESULT_SUCCESS; + outresult->socket->ready = 0; + outresult->socket->status = 0; + if (!(config->type == SOCKET_UDP)) + { + outresult->socket->isServer = config->server; + } + switch (res->ai_addr->sa_family) + { + case AF_INET: + { + outresult->socket->addripv4 = (struct _SocketAddressIPv4 *) malloc( + sizeof(*outresult->socket->addripv4)); + if (outresult->socket->addripv4 != NULL) + { + memset(outresult->socket->addripv4, 0, + sizeof(*outresult->socket->addripv4)); + if (outresult->socket->addripv4 != NULL) + { + memcpy(&outresult->socket->addripv4->address, + (struct sockaddr_in *) res->ai_addr, sizeof(struct sockaddr_in)); + outresult->socket->isIPv6 = false; + char hoststr[NI_MAXHOST]; + char portstr[NI_MAXSERV]; + socklen_t client_len = sizeof(struct sockaddr_storage); + getnameinfo( + (struct sockaddr *) &outresult->socket->addripv4->address, client_len, hoststr, sizeof(hoststr), portstr, sizeof(portstr), NI_NUMERICHOST | NI_NUMERICSERV); + TraceLog(LOG_INFO, "Socket address set to %s:%s", hoststr, portstr); + } + } + } + break; + case AF_INET6: + { + outresult->socket->addripv6 = (struct _SocketAddressIPv6 *) malloc( + sizeof(*outresult->socket->addripv6)); + if (outresult->socket->addripv6 != NULL) + { + memset(outresult->socket->addripv6, 0, + sizeof(*outresult->socket->addripv6)); + if (outresult->socket->addripv6 != NULL) + { + memcpy(&outresult->socket->addripv6->address, + (struct sockaddr_in6 *) res->ai_addr, sizeof(struct sockaddr_in6)); + outresult->socket->isIPv6 = true; + char hoststr[NI_MAXHOST]; + char portstr[NI_MAXSERV]; + socklen_t client_len = sizeof(struct sockaddr_storage); + getnameinfo( + (struct sockaddr *) &outresult->socket->addripv6->address, client_len, hoststr, sizeof(hoststr), portstr, sizeof(portstr), NI_NUMERICHOST | NI_NUMERICSERV); + TraceLog(LOG_INFO, "Socket address set to %s:%s", hoststr, portstr); + } + } + } + break; + } + } + freeaddrinfo(res); + return success; +} + +// Set the state of the Socket sock to blocking +static bool SocketSetBlocking(Socket *sock) +{ + bool ret = true; +#if defined(_WIN32) + unsigned long mode = 0; + ret = ioctlsocket(sock->channel, FIONBIO, &mode); +#else + const int flags = fcntl(sock->channel, F_GETFL, 0); + if (!(flags & O_NONBLOCK)) + { + TraceLog(LOG_DEBUG, "Socket was already in blocking mode"); + return ret; + } + + ret = (0 == fcntl(sock->channel, F_SETFL, (flags ^ O_NONBLOCK))); +#endif + return ret; +} + +// Set the state of the Socket sock to non-blocking +static bool SocketSetNonBlocking(Socket *sock) +{ + bool ret = true; +#if defined(_WIN32) + unsigned long mode = 1; + ret = ioctlsocket(sock->channel, FIONBIO, &mode); +#else + const int flags = fcntl(sock->channel, F_GETFL, 0); + if ((flags & O_NONBLOCK)) + { + TraceLog(LOG_DEBUG, "Socket was already in non-blocking mode"); + return ret; + } + ret = (0 == fcntl(sock->channel, F_SETFL, (flags | O_NONBLOCK))); +#endif + return ret; +} + +// Set options specified in SocketConfig to Socket sock +static bool SocketSetOptions(SocketConfig *config, Socket *sock) +{ + for (int i = 0; i < SOCKET_MAX_SOCK_OPTS; i++) + { + SocketOpt *opt = &config->sockopts[i]; + if (opt->id == 0) + { + break; + } + + if (setsockopt(sock->channel, SOL_SOCKET, opt->id, opt->value, opt->valueLen) < 0) + { + return false; + } + } + + return true; +} + +// Set "hints" in an addrinfo struct, to be passed to getaddrinfo. +static void SocketSetHints(SocketConfig *config, struct addrinfo *hints) +{ + if (config == NULL || hints == NULL) + { + return; + } + memset(hints, 0, sizeof(*hints)); + + // Check if the ip supplied in the config is a valid ipv4 ip ipv6 address + if (IsIPv4Address(config->host)) + { + hints->ai_family = AF_INET; + hints->ai_flags |= AI_NUMERICHOST; + } + else + { + if (IsIPv6Address(config->host)) + { + hints->ai_family = AF_INET6; + hints->ai_flags |= AI_NUMERICHOST; + } + else + { + hints->ai_family = AF_UNSPEC; + } + } + + if (config->type == SOCKET_UDP) + { + hints->ai_socktype = SOCK_DGRAM; + } + else + { + hints->ai_socktype = SOCK_STREAM; + } + + // Set passive unless UDP client + if (!(config->type == SOCKET_UDP) || config->server) + { + hints->ai_flags = AI_PASSIVE; + } +} + +//---------------------------------------------------------------------------------- +// Module implementation +//---------------------------------------------------------------------------------- + +// Initialise the network (requires for windows platforms only) +bool InitNetwork() +{ +#if defined(_WIN32) + WORD wVersionRequested; + WSADATA wsaData; + int err; + + wVersionRequested = MAKEWORD(2, 2); + err = WSAStartup(wVersionRequested, &wsaData); + if (err != 0) + { + TraceLog(LOG_WARNING, "WinSock failed to initialise."); + return false; + } + else + { + TraceLog(LOG_INFO, "WinSock initialised."); + } + + if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) + { + TraceLog(LOG_WARNING, "WinSock failed to initialise."); + WSACleanup(); + return false; + } + + return true; +#else + return true; +#endif +} + +// Cleanup, and close the network +void CloseNetwork() +{ +#if defined(_WIN32) + WSACleanup(); +#endif +} + +// Protocol-independent name resolution from an address to an ANSI host name +// and from a port number to the ANSI service name. +// +// The flags parameter can be used to customize processing of the getnameinfo function +// +// The following flags are available: +// +// NAME_INFO_DEFAULT 0x00 // No flags set +// NAME_INFO_NOFQDN 0x01 // Only return nodename portion for local hosts +// NAME_INFO_NUMERICHOST 0x02 // Return numeric form of the host's address +// NAME_INFO_NAMEREQD 0x04 // Error if the host's name not in DNS +// NAME_INFO_NUMERICSERV 0x08 // Return numeric form of the service (port #) +// NAME_INFO_DGRAM 0x10 // Service is a datagram service +void ResolveIP(const char *ip, const char *port, int flags, char *host, char *serv) +{ + // Variables + int status; // Status value to return (0) is success + struct addrinfo hints; // Address flags (IPV4, IPV6, UDP?) + struct addrinfo *res; // A pointer to the resulting address list + + // Set the hints + memset(&hints, 0, sizeof hints); + hints.ai_family = AF_UNSPEC; // Either IPv4 or IPv6 (AF_INET, AF_INET6) + hints.ai_protocol = 0; // Automatically select correct protocol (IPPROTO_TCP), (IPPROTO_UDP) + + // Populate address information + status = getaddrinfo(ip, // e.g. "www.example.com" or IP + port, // e.g. "http" or port number + &hints, // e.g. SOCK_STREAM/SOCK_DGRAM + &res // The struct to populate + ); + + // Did we succeed? + if (status != 0) + { + TraceLog(LOG_WARNING, "Failed to get resolve host %s:%s: %s", ip, port, gai_strerror(errno)); + } + else + { + TraceLog(LOG_DEBUG, "Resolving... %s::%s", ip, port); + } + + // Attempt to resolve network byte order ip to hostname + switch (res->ai_family) + { + case AF_INET: + status = getnameinfo(&*((struct sockaddr *) res->ai_addr), + sizeof(*((struct sockaddr_in *) res->ai_addr)), + host, + NI_MAXHOST, + serv, + NI_MAXSERV, + flags); + break; + case AF_INET6: + /* + status = getnameinfo(&*((struct sockaddr_in6 *) res->ai_addr), // TODO. + sizeof(*((struct sockaddr_in6 *) res->ai_addr)), + host, NI_MAXHOST, serv, NI_MAXSERV, flags); + */ + break; + default: break; + } + + if (status != 0) + { + TraceLog(LOG_WARNING, "Failed to resolve ip %s: %s", ip, SocketGetLastErrorString()); + } + else + { + TraceLog(LOG_DEBUG, "Successfully resolved %s::%s to %s", ip, port, host); + } + + // Free the pointer to the data returned by addrinfo + freeaddrinfo(res); +} + +// Protocol-independent translation from an ANSI host name to an address +// +// e.g. +// const char* address = "127.0.0.1" (local address) +// const char* port = "80" +// +// Parameters: +// const char* address - A pointer to a NULL-terminated ANSI string that contains a host (node) name or a numeric host address string. +// const char* service - A pointer to a NULL-terminated ANSI string that contains either a service name or port number represented as a string. +// +// Returns: +// The total amount of addresses found, -1 on error +// +int ResolveHost(const char *address, const char *service, int addressType, int flags, AddressInformation *outAddr) +{ + // Variables + int status; // Status value to return (0) is success + struct addrinfo hints; // Address flags (IPV4, IPV6, UDP?) + struct addrinfo *res; // will point to the results + struct addrinfo *iterator; + assert(((address != NULL || address != 0) || (service != NULL || service != 0))); + assert(((addressType == AF_INET) || (addressType == AF_INET6) || (addressType == AF_UNSPEC))); + + // Set the hints + memset(&hints, 0, sizeof hints); + hints.ai_family = addressType; // Either IPv4 or IPv6 (ADDRESS_TYPE_IPV4, ADDRESS_TYPE_IPV6) + hints.ai_protocol = 0; // Automatically select correct protocol (IPPROTO_TCP), (IPPROTO_UDP) + hints.ai_flags = flags; + assert((hints.ai_addrlen == 0) || (hints.ai_addrlen == 0)); + assert((hints.ai_canonname == 0) || (hints.ai_canonname == 0)); + assert((hints.ai_addr == 0) || (hints.ai_addr == 0)); + assert((hints.ai_next == 0) || (hints.ai_next == 0)); + + // When the address is NULL, populate the IP for me + if (address == NULL) + { + if ((hints.ai_flags & AI_PASSIVE) == 0) + { + hints.ai_flags |= AI_PASSIVE; + } + } + + TraceLog(LOG_INFO, "Resolving host..."); + + // Populate address information + status = getaddrinfo(address, // e.g. "www.example.com" or IP + service, // e.g. "http" or port number + &hints, // e.g. SOCK_STREAM/SOCK_DGRAM + &res // The struct to populate + ); + + // Did we succeed? + if (status != 0) + { + int error = SocketGetLastError(); + SocketSetLastError(0); + TraceLog(LOG_WARNING, "Failed to get resolve host: %s", SocketErrorCodeToString(error)); + return -1; + } + else + { + TraceLog(LOG_INFO, "Successfully resolved host %s:%s", address, service); + } + + // Calculate the size of the address information list + int size = 0; + for (iterator = res; iterator != NULL; iterator = iterator->ai_next) + { + size++; + } + + // Validate the size is > 0, otherwise return + if (size <= 0) + { + TraceLog(LOG_WARNING, "Error, no addresses found."); + return -1; + } + + // If not address list was allocated, allocate it dynamically with the known address size + if (outAddr == NULL) + { + outAddr = (AddressInformation *) malloc(size * sizeof(AddressInformation)); + } + + // Dynamically allocate an array of address information structs + if (outAddr != NULL) + { + int i; + for (i = 0; i < size; ++i) + { + outAddr[i] = AllocAddress(); + if (outAddr[i] == NULL) + { + break; + } + } + outAddr[i] = NULL; + if (i != size) + { + outAddr = NULL; + } + } + else + { + TraceLog(LOG_WARNING, + "Error, failed to dynamically allocate memory for the address list"); + return -1; + } + + // Copy all the address information from res into outAddrList + int i = 0; + for (iterator = res; iterator != NULL; iterator = iterator->ai_next) + { + if (i < size) + { + outAddr[i]->addr.ai_flags = iterator->ai_flags; + outAddr[i]->addr.ai_family = iterator->ai_family; + outAddr[i]->addr.ai_socktype = iterator->ai_socktype; + outAddr[i]->addr.ai_protocol = iterator->ai_protocol; + outAddr[i]->addr.ai_addrlen = iterator->ai_addrlen; + *outAddr[i]->addr.ai_addr = *iterator->ai_addr; +#if NET_DEBUG_ENABLED + TraceLog(LOG_DEBUG, "GetAddressInformation"); + TraceLog(LOG_DEBUG, "\tFlags: 0x%x", iterator->ai_flags); + //PrintSocket(outAddr[i]->addr.ai_addr, outAddr[i]->addr.ai_family, outAddr[i]->addr.ai_socktype, outAddr[i]->addr.ai_protocol); + TraceLog(LOG_DEBUG, "Length of this sockaddr: %d", outAddr[i]->addr.ai_addrlen); + TraceLog(LOG_DEBUG, "Canonical name: %s", iterator->ai_canonname); +#endif + i++; + } + } + + // Free the pointer to the data returned by addrinfo + freeaddrinfo(res); + + // Return the total count of addresses found + return size; +} + +// This here is the bread and butter of the socket API, This function will +// attempt to open a socket, bind and listen to it based on the config passed in +// +// SocketConfig* config - Configuration for which socket to open +// SocketResult* result - The results of this function (if any, including errors) +// +// e.g. +// SocketConfig server_config = { SocketConfig client_config = { +// .host = "127.0.0.1", .host = "127.0.0.1", +// .port = 8080, .port = 8080, +// .server = true, }; +// .nonblocking = true, +// }; +// SocketResult server_res; SocketResult client_res; +bool SocketCreate(SocketConfig *config, SocketResult *result) +{ + // Socket creation result + bool success = true; + + // Make sure we've not received a null config or result pointer + if (config == NULL || result == NULL) + { + return (success = false); + } + + // Set the defaults based on the config + if (!SocketSetDefaults(config)) + { + TraceLog(LOG_WARNING, "Configuration Error."); + success = false; + } + else + { + // Create the socket + if (CreateSocket(config, result)) + { + if (config->nonblocking) + { + SocketSetNonBlocking(result->socket); + } + else + { + SocketSetBlocking(result->socket); + } + } + else + { + success = false; + } + } + return success; +} + +// Bind a socket to a local address +// Note: The bind function is required on an unconnected socket before subsequent calls to the listen function. +bool SocketBind(SocketConfig *config, SocketResult *result) +{ + bool success = false; + result->status = RESULT_FAILURE; + struct sockaddr_storage *sock_addr = NULL; + + // Don't bind to a socket that isn't configured as a server + if (!IsSocketValid(result->socket) || !config->server) + { + TraceLog(LOG_WARNING, + "Cannot bind to socket marked as \"Client\" in SocketConfig."); + success = false; + } + else + { + if (result->socket->isIPv6) + { + sock_addr = (struct sockaddr_storage *) &result->socket->addripv6->address; + } + else + { + sock_addr = (struct sockaddr_storage *) &result->socket->addripv4->address; + } + if (sock_addr != NULL) + { + if (bind(result->socket->channel, (struct sockaddr *) sock_addr, sizeof(*sock_addr)) != SOCKET_ERROR) + { + TraceLog(LOG_INFO, "Successfully bound socket."); + success = true; + } + else + { + result->socket->status = SocketGetLastError(); + TraceLog(LOG_WARNING, "Socket Error: %s", + SocketErrorCodeToString(result->socket->status)); + SocketSetLastError(0); + success = false; + } + } + } + // Was the bind a success? + if (success) + { + result->status = RESULT_SUCCESS; + result->socket->ready = 0; + result->socket->status = 0; + socklen_t sock_len = sizeof(*sock_addr); + if (getsockname(result->socket->channel, (struct sockaddr *) sock_addr, &sock_len) < 0) + { + TraceLog(LOG_WARNING, "Couldn't get socket address"); + } + else + { + struct sockaddr_in *s = (struct sockaddr_in *) sock_addr; + // result->socket->address.host = s->sin_addr.s_addr; + // result->socket->address.port = s->sin_port; + + // + result->socket->addripv4 + = (struct _SocketAddressIPv4 *) malloc(sizeof(*result->socket->addripv4)); + if (result->socket->addripv4 != NULL) + { + memset(result->socket->addripv4, 0, sizeof(*result->socket->addripv4)); + } + memcpy(&result->socket->addripv4->address, (struct sockaddr_in *) &s->sin_addr, sizeof(struct sockaddr_in)); + // + } + } + return success; +} + +// Listens (and queues) incoming connections requests for a bound port. +bool SocketListen(SocketConfig *config, SocketResult *result) +{ + bool success = false; + result->status = RESULT_FAILURE; + + // Don't bind to a socket that isn't configured as a server + if (!IsSocketValid(result->socket) || !config->server) + { + TraceLog(LOG_WARNING, + "Cannot listen on socket marked as \"Client\" in SocketConfig."); + success = false; + } + else + { + // Don't listen on UDP sockets + if (!(config->type == SOCKET_UDP)) + { + if (listen(result->socket->channel, config->backlog_size) != SOCKET_ERROR) + { + TraceLog(LOG_INFO, "Started listening on socket..."); + success = true; + } + else + { + success = false; + result->socket->status = SocketGetLastError(); + TraceLog(LOG_WARNING, "Socket Error: %s", + SocketErrorCodeToString(result->socket->status)); + SocketSetLastError(0); + } + } + else + { + TraceLog(LOG_WARNING, + "Cannot listen on socket marked as \"UDP\" (datagram) in SocketConfig."); + success = false; + } + } + + // Was the listen a success? + if (success) + { + result->status = RESULT_SUCCESS; + result->socket->ready = 0; + result->socket->status = 0; + } + return success; +} + +// Connect the socket to the destination specified by "host" and "port" in SocketConfig +bool SocketConnect(SocketConfig *config, SocketResult *result) +{ + bool success = true; + result->status = RESULT_FAILURE; + + // Only bind to sockets marked as server + if (config->server) + { + TraceLog(LOG_WARNING, + "Cannot connect to socket marked as \"Server\" in SocketConfig."); + success = false; + } + else + { + if (IsIPv4Address(config->host)) + { + struct sockaddr_in ip4addr; + ip4addr.sin_family = AF_INET; + unsigned long hport; + hport = strtoul(config->port, NULL, 0); + ip4addr.sin_port = htons(hport); + + // TODO: Changed the code to avoid the usage of inet_pton and inet_ntop replacing them with getnameinfo (that should have a better support on windows). + + //inet_pton(AF_INET, config->host, &ip4addr.sin_addr); + int connect_result = connect(result->socket->channel, (struct sockaddr *) &ip4addr, sizeof(ip4addr)); + if (connect_result == SOCKET_ERROR) + { + result->socket->status = SocketGetLastError(); + SocketSetLastError(0); + switch (result->socket->status) + { + case WSAEWOULDBLOCK: + { + success = true; + break; + } + default: + { + TraceLog(LOG_WARNING, "Socket Error: %s", + SocketErrorCodeToString(result->socket->status)); + success = false; + break; + } + } + } + else + { + TraceLog(LOG_INFO, "Successfully connected to socket."); + success = true; + } + } + else + { + if (IsIPv6Address(config->host)) + { + struct sockaddr_in6 ip6addr; + ip6addr.sin6_family = AF_INET6; + unsigned long hport; + hport = strtoul(config->port, NULL, 0); + ip6addr.sin6_port = htons(hport); + //inet_pton(AF_INET6, config->host, &ip6addr.sin6_addr); // TODO. + int connect_result = connect(result->socket->channel, (struct sockaddr *) &ip6addr, sizeof(ip6addr)); + if (connect_result == SOCKET_ERROR) + { + result->socket->status = SocketGetLastError(); + SocketSetLastError(0); + switch (result->socket->status) + { + case WSAEWOULDBLOCK: + { + success = true; + break; + } + default: + { + TraceLog(LOG_WARNING, "Socket Error: %s", + SocketErrorCodeToString(result->socket->status)); + success = false; + break; + } + } + } + else + { + TraceLog(LOG_INFO, "Successfully connected to socket."); + success = true; + } + } + } + } + + if (success) + { + result->status = RESULT_SUCCESS; + result->socket->ready = 0; + result->socket->status = 0; + } + + return success; +} + +// Closes an existing socket +// +// SocketChannel socket - The id of the socket to close +void SocketClose(Socket *sock) +{ + if (sock != NULL) + { + if (sock->channel != INVALID_SOCKET) + { + closesocket(sock->channel); + } + } +} + +// Returns the sockaddress for a specific socket in a generic storage struct +SocketAddressStorage SocketGetPeerAddress(Socket *sock) +{ + // TODO. + /* + if (sock->isServer) return NULL; + if (sock->isIPv6) return sock->addripv6; + else return sock->addripv4; + */ + + return NULL; +} + +// Return the address-type appropriate host portion of a socket address +char *GetSocketAddressHost(SocketAddressStorage storage) +{ + assert(storage->address.ss_family == AF_INET || storage->address.ss_family == AF_INET6); + return SocketAddressToString((struct sockaddr_storage *) storage); +} + +// Return the address-type appropriate port(service) portion of a socket address +short GetSocketAddressPort(SocketAddressStorage storage) +{ + //return ntohs(GetSocketPortPtr(storage)); // TODO. + + return 0; +} + +// The accept function permits an incoming connection attempt on a socket. +// +// SocketChannel listener - The socket to listen for incoming connections on (i.e. server) +// SocketResult* out - The result of this function (if any, including errors) +// +// e.g. +// +// SocketResult connection; +// bool connected = false; +// if (!connected) +// { +// if (SocketAccept(server_res.socket.channel, &connection)) +// { +// connected = true; +// } +// } +Socket *SocketAccept(Socket *server, SocketConfig *config) +{ + if (!server->isServer || server->type == SOCKET_UDP) + { + return NULL; + } + struct sockaddr_storage sock_addr; + socklen_t sock_alen; + Socket * sock; + sock = AllocSocket(); + server->ready = 0; + sock_alen = sizeof(sock_addr); + sock->channel = accept(server->channel, (struct sockaddr *) &sock_addr, &sock_alen); + if (sock->channel == INVALID_SOCKET) + { + sock->status = SocketGetLastError(); + TraceLog(LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(sock->status)); + SocketSetLastError(0); + SocketClose(sock); + return NULL; + } + (config->nonblocking) ? SocketSetNonBlocking(sock) : SocketSetBlocking(sock); + sock->isServer = false; + sock->ready = 0; + sock->type = server->type; + switch (sock_addr.ss_family) + { + case AF_INET: + { + struct sockaddr_in *s = ((struct sockaddr_in *) &sock_addr); + sock->addripv4 = (struct _SocketAddressIPv4 *) malloc(sizeof(*sock->addripv4)); + if (sock->addripv4 != NULL) + { + memset(sock->addripv4, 0, sizeof(*sock->addripv4)); + memcpy(&sock->addripv4->address, (struct sockaddr_in *) &s->sin_addr, sizeof(struct sockaddr_in)); + TraceLog(LOG_INFO, "Server: Got connection from %s::%hu", SocketAddressToString((struct sockaddr_storage *) s), + ntohs(sock->addripv4->address.sin_port)); + } + } + break; + case AF_INET6: + { + struct sockaddr_in6 *s = ((struct sockaddr_in6 *) &sock_addr); + sock->addripv6 = (struct _SocketAddressIPv6 *) malloc(sizeof(*sock->addripv6)); + if (sock->addripv6 != NULL) + { + memset(sock->addripv6, 0, sizeof(*sock->addripv6)); + memcpy(&sock->addripv6->address, (struct sockaddr_in6 *) &s->sin6_addr, sizeof(struct sockaddr_in6)); + TraceLog(LOG_INFO, "Server: Got connection from %s::%hu", SocketAddressToString((struct sockaddr_storage *) s), + ntohs(sock->addripv6->address.sin6_port)); + } + } + break; + } + return sock; +} + +// Verify that the channel is in the valid range +static int ValidChannel(int channel) +{ + if ((channel < 0) || (channel >= SOCKET_MAX_UDPCHANNELS)) + { + TraceLog(LOG_WARNING, "Invalid channel"); + return 0; + } + return 1; +} + +// Set the socket channel +int SocketSetChannel(Socket *socket, int channel, const IPAddress *address) +{ + struct UDPChannel *binding; + if (socket == NULL) + { + TraceLog(LOG_WARNING, "Passed a NULL socket"); + return (-1); + } + if (channel == -1) + { + for (channel = 0; channel < SOCKET_MAX_UDPCHANNELS; ++channel) + { + binding = &socket->binding[channel]; + if (binding->numbound < SOCKET_MAX_UDPADDRESSES) + { + break; + } + } + } + else + { + if (!ValidChannel(channel)) + { + return (-1); + } + binding = &socket->binding[channel]; + } + if (binding->numbound == SOCKET_MAX_UDPADDRESSES) + { + TraceLog(LOG_WARNING, "No room for new addresses"); + return (-1); + } + binding->address[binding->numbound++] = *address; + return (channel); +} + +// Remove the socket channel +void SocketUnsetChannel(Socket *socket, int channel) +{ + if ((channel >= 0) && (channel < SOCKET_MAX_UDPCHANNELS)) + { + socket->binding[channel].numbound = 0; + } +} + +/* Allocate/free a single UDP packet 'size' bytes long. + The new packet is returned, or NULL if the function ran out of memory. + */ +SocketDataPacket *AllocPacket(int size) +{ + SocketDataPacket *packet; + int error; + + error = 1; + packet = (SocketDataPacket *) malloc(sizeof(*packet)); + if (packet != NULL) + { + packet->maxlen = size; + packet->data = (uint8_t *) malloc(size); + if (packet->data != NULL) + { + error = 0; + } + } + if (error) + { + FreePacket(packet); + packet = NULL; + } + return (packet); +} + +int ResizePacket(SocketDataPacket *packet, int newsize) +{ + uint8_t *newdata; + + newdata = (uint8_t *) malloc(newsize); + if (newdata != NULL) + { + free(packet->data); + packet->data = newdata; + packet->maxlen = newsize; + } + return (packet->maxlen); +} + +void FreePacket(SocketDataPacket *packet) +{ + if (packet) + { + free(packet->data); + free(packet); + } +} + +/* Allocate/Free a UDP packet vector (array of packets) of 'howmany' packets, + each 'size' bytes long. + A pointer to the packet array is returned, or NULL if the function ran out + of memory. + */ +SocketDataPacket **AllocPacketList(int howmany, int size) +{ + SocketDataPacket **packetV; + + packetV = (SocketDataPacket **) malloc((howmany + 1) * sizeof(*packetV)); + if (packetV != NULL) + { + int i; + for (i = 0; i < howmany; ++i) + { + packetV[i] = AllocPacket(size); + if (packetV[i] == NULL) + { + break; + } + } + packetV[i] = NULL; + + if (i != howmany) + { + FreePacketList(packetV); + packetV = NULL; + } + } + return (packetV); +} + +void FreePacketList(SocketDataPacket **packetV) +{ + if (packetV) + { + int i; + for (i = 0; packetV[i]; ++i) + { + FreePacket(packetV[i]); + } + free(packetV); + } +} + +// Send 'len' bytes of 'data' over the non-server socket 'sock' +// +// Example +int SocketSend(Socket *sock, const void *datap, int length) +{ + int sent = 0; + int left = length; + int status = -1; + int numsent = 0; + const unsigned char *data = (const unsigned char *) datap; + + // Server sockets are for accepting connections only + if (sock->isServer) + { + TraceLog(LOG_WARNING, "Cannot send information on a server socket"); + return -1; + } + + // Which socket are we trying to send data on + switch (sock->type) + { + case SOCKET_TCP: + { + SocketSetLastError(0); + do + { + length = send(sock->channel, (const char *) data, left, 0); + if (length > 0) + { + sent += length; + left -= length; + data += length; + } + } while ((left > 0) && // While we still have bytes left to send + ((length > 0) || // The amount of bytes we actually sent is > 0 + (SocketGetLastError() == WSAEINTR)) // The socket was interupted + ); + + if (length == SOCKET_ERROR) + { + sock->status = SocketGetLastError(); + TraceLog(LOG_DEBUG, "Socket Error: %s", SocketErrorCodeToString(sock->status)); + SocketSetLastError(0); + } + else + { + TraceLog(LOG_DEBUG, "Successfully sent \"%s\" (%d bytes)", datap, sent); + } + + return sent; + } + break; + case SOCKET_UDP: + { + SocketSetLastError(0); + if (sock->isIPv6) + { + status = sendto(sock->channel, (const char *) data, left, 0, + (struct sockaddr *) &sock->addripv6->address, + sizeof(sock->addripv6->address)); + } + else + { + status = sendto(sock->channel, (const char *) data, left, 0, + (struct sockaddr *) &sock->addripv4->address, + sizeof(sock->addripv4->address)); + } + if (sent >= 0) + { + sock->status = 0; + ++numsent; + TraceLog(LOG_DEBUG, "Successfully sent \"%s\" (%d bytes)", datap, status); + } + else + { + sock->status = SocketGetLastError(); + TraceLog(LOG_DEBUG, "Socket Error: %s", SocketGetLastErrorString(sock->status)); + SocketSetLastError(0); + return 0; + } + return numsent; + } + break; + default: break; + } + return -1; +} + +// Receive up to 'maxlen' bytes of data over the non-server socket 'sock', +// and store them in the buffer pointed to by 'data'. +// This function returns the actual amount of data received. If the return +// value is less than or equal to zero, then either the remote connection was +// closed, or an unknown socket error occurred. +int SocketReceive(Socket *sock, void *data, int maxlen) +{ + int len = 0; + int numrecv = 0; + int status = 0; + socklen_t sock_len; + struct sockaddr_storage sock_addr; + //char ip[INET6_ADDRSTRLEN]; + + // Server sockets are for accepting connections only + if (sock->isServer && sock->type == SOCKET_TCP) + { + sock->status = SocketGetLastError(); + TraceLog(LOG_DEBUG, "Socket Error: %s", "Server sockets cannot be used to receive data"); + SocketSetLastError(0); + return 0; + } + + // Which socket are we trying to send data on + switch (sock->type) + { + case SOCKET_TCP: + { + SocketSetLastError(0); + do + { + len = recv(sock->channel, (char *) data, maxlen, 0); + } while (SocketGetLastError() == WSAEINTR); + + if (len > 0) + { + // Who sent the packet? + if (sock->type == SOCKET_UDP) + { + //TraceLog(LOG_DEBUG, "Received data from: %s", inet_ntop(sock_addr.ss_family, GetSocketAddressPtr((struct sockaddr *) &sock_addr), ip, sizeof(ip))); + } + + ((unsigned char *) data)[len] = '\0'; // Add null terminating character to the end of the stream + TraceLog(LOG_DEBUG, "Received \"%s\" (%d bytes)", data, len); + } + + sock->ready = 0; + return len; + } + break; + case SOCKET_UDP: + { + SocketSetLastError(0); + sock_len = sizeof(sock_addr); + status = recvfrom(sock->channel, // The receving channel + data, // A pointer to the data buffer to fill + maxlen, // The max length of the data to fill + 0, // Flags + (struct sockaddr *) &sock_addr, // The address of the recevied data + &sock_len // The length of the received data address + ); + if (status >= 0) + { + ++numrecv; + } + else + { + sock->status = SocketGetLastError(); + switch (sock->status) + { + case WSAEWOULDBLOCK: { break; + } + default: + { + TraceLog(LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(sock->status)); + break; + } + } + SocketSetLastError(0); + return 0; + } + sock->ready = 0; + return numrecv; + } + break; + } + return -1; +} + +// Does the socket have it's 'ready' flag set? +bool IsSocketReady(Socket *sock) +{ + return (sock != NULL) && (sock->ready); +} + +// Check if the socket is considered connected +bool IsSocketConnected(Socket *sock) +{ +#if defined(_WIN32) + FD_SET writefds; + FD_ZERO(&writefds); + FD_SET(sock->channel, &writefds); + struct timeval timeout; + timeout.tv_sec = 1; + timeout.tv_usec = 1000000000UL; + int total = select(0, NULL, &writefds, NULL, &timeout); + if (total == -1) + { // Error + sock->status = SocketGetLastError(); + TraceLog(LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(sock->status)); + SocketSetLastError(0); + } + else if (total == 0) + { // Timeout + return false; + } + else + { + if (FD_ISSET(sock->channel, &writefds)) + { + return true; + } + } + return false; +#else + return true; +#endif +} + +// Allocate and return a SocketResult struct +SocketResult *AllocSocketResult() +{ + struct SocketResult *res; + res = (struct SocketResult *) malloc(sizeof(*res)); + if (res != NULL) + { + memset(res, 0, sizeof(*res)); + if ((res->socket = AllocSocket()) == NULL) + { + free(res); + res = NULL; + } + } + return res; +} + +// Free an allocated SocketResult +void FreeSocketResult(SocketResult **result) +{ + if (*result != NULL) + { + if ((*result)->socket != NULL) + { + FreeSocket(&((*result)->socket)); + } + free(*result); + *result = NULL; + } +} + +// Allocate a Socket +Socket *AllocSocket() +{ + // Allocate a socket if one already hasn't been + struct Socket *sock; + sock = (Socket *) malloc(sizeof(*sock)); + if (sock != NULL) + { + memset(sock, 0, sizeof(*sock)); + } + else + { + TraceLog( + LOG_WARNING, "Ran out of memory attempting to allocate a socket"); + SocketClose(sock); + free(sock); + sock = NULL; + } + return sock; +} + +// Free an allocated Socket +void FreeSocket(Socket **sock) +{ + if (*sock != NULL) + { + free(*sock); + *sock = NULL; + } +} + +// Allocate a SocketSet +SocketSet *AllocSocketSet(int max) +{ + struct SocketSet *set; + int i; + + set = (struct SocketSet *) malloc(sizeof(*set)); + if (set != NULL) + { + set->numsockets = 0; + set->maxsockets = max; + set->sockets = (struct Socket **) malloc(max * sizeof(*set->sockets)); + if (set->sockets != NULL) + { + for (i = 0; i < max; ++i) + { + set->sockets[i] = NULL; + } + } + else + { + free(set); + set = NULL; + } + } + return (set); +} + +// Free an allocated SocketSet +void FreeSocketSet(SocketSet *set) +{ + if (set) + { + free(set->sockets); + free(set); + } +} + +// Add a Socket "sock" to the SocketSet "set" +int AddSocket(SocketSet *set, Socket *sock) +{ + if (sock != NULL) + { + if (set->numsockets == set->maxsockets) + { + TraceLog(LOG_DEBUG, "Socket Error: %s", "SocketSet is full"); + SocketSetLastError(0); + return (-1); + } + set->sockets[set->numsockets++] = (struct Socket *) sock; + } + else + { + TraceLog(LOG_DEBUG, "Socket Error: %s", "Socket was null"); + SocketSetLastError(0); + return (-1); + } + return (set->numsockets); +} + +// Remove a Socket "sock" to the SocketSet "set" +int RemoveSocket(SocketSet *set, Socket *sock) +{ + int i; + + if (sock != NULL) + { + for (i = 0; i < set->numsockets; ++i) + { + if (set->sockets[i] == (struct Socket *) sock) + { + break; + } + } + if (i == set->numsockets) + { + TraceLog(LOG_DEBUG, "Socket Error: %s", "Socket not found"); + SocketSetLastError(0); + return (-1); + } + --set->numsockets; + for (; i < set->numsockets; ++i) + { + set->sockets[i] = set->sockets[i + 1]; + } + } + return (set->numsockets); +} + +// Check the sockets in the socket set for pending information +int CheckSockets(SocketSet *set, unsigned int timeout) +{ + int i; + SOCKET maxfd; + int retval; + struct timeval tv; + fd_set mask; + + /* Find the largest file descriptor */ + maxfd = 0; + for (i = set->numsockets - 1; i >= 0; --i) + { + if (set->sockets[i]->channel > maxfd) + { + maxfd = set->sockets[i]->channel; + } + } + + // Check the file descriptors for available data + do + { + SocketSetLastError(0); + + // Set up the mask of file descriptors + FD_ZERO(&mask); + for (i = set->numsockets - 1; i >= 0; --i) + { + FD_SET(set->sockets[i]->channel, &mask); + } // Set up the timeout + tv.tv_sec = timeout / 1000; + tv.tv_usec = (timeout % 1000) * 1000; + + /* Look! */ + retval = select(maxfd + 1, &mask, NULL, NULL, &tv); + } while (SocketGetLastError() == WSAEINTR); + + // Mark all file descriptors ready that have data available + if (retval > 0) + { + for (i = set->numsockets - 1; i >= 0; --i) + { + if (FD_ISSET(set->sockets[i]->channel, &mask)) + { + set->sockets[i]->ready = 1; + } + } + } + return (retval); +} + +// Allocate an AddressInformation +AddressInformation AllocAddress() +{ + AddressInformation addressInfo = NULL; + addressInfo = (AddressInformation) calloc(1, sizeof(*addressInfo)); + if (addressInfo != NULL) + { + addressInfo->addr.ai_addr = (struct sockaddr *) calloc(1, sizeof(struct sockaddr)); + if (addressInfo->addr.ai_addr == NULL) + { + TraceLog(LOG_WARNING, + "Failed to allocate memory for \"struct sockaddr\""); + } + } + else + { + TraceLog(LOG_WARNING, + "Failed to allocate memory for \"struct AddressInformation\""); + } + return addressInfo; +} + +// Free an AddressInformation struct +void FreeAddress(AddressInformation *addressInfo) +{ + if (*addressInfo != NULL) + { + if ((*addressInfo)->addr.ai_addr != NULL) + { + free((*addressInfo)->addr.ai_addr); + (*addressInfo)->addr.ai_addr = NULL; + } + free(*addressInfo); + *addressInfo = NULL; + } +} + +// Allocate a list of AddressInformation +AddressInformation *AllocAddressList(int size) +{ + AddressInformation *addr; + addr = (AddressInformation *) malloc(size * sizeof(AddressInformation)); + return addr; +} + +// Opaque datatype accessor addrinfo->ai_family +int GetAddressFamily(AddressInformation address) +{ + return address->addr.ai_family; +} + +// Opaque datatype accessor addrinfo->ai_socktype +int GetAddressSocketType(AddressInformation address) +{ + return address->addr.ai_socktype; +} + +// Opaque datatype accessor addrinfo->ai_protocol +int GetAddressProtocol(AddressInformation address) +{ + return address->addr.ai_protocol; +} + +// Opaque datatype accessor addrinfo->ai_canonname +char *GetAddressCanonName(AddressInformation address) +{ + return address->addr.ai_canonname; +} + +// Opaque datatype accessor addrinfo->ai_addr +char *GetAddressHostAndPort(AddressInformation address, char *outhost, int *outport) +{ + //char *ip[INET6_ADDRSTRLEN]; + char *result = NULL; + struct sockaddr_storage *storage = (struct sockaddr_storage *) address->addr.ai_addr; + switch (storage->ss_family) + { + case AF_INET: + { + struct sockaddr_in *s = ((struct sockaddr_in *) address->addr.ai_addr); + //result = inet_ntop(AF_INET, &s->sin_addr, ip, INET_ADDRSTRLEN); // TODO. + *outport = ntohs(s->sin_port); + } + break; + case AF_INET6: + { + struct sockaddr_in6 *s = ((struct sockaddr_in6 *) address->addr.ai_addr); + //result = inet_ntop(AF_INET6, &s->sin6_addr, ip, INET6_ADDRSTRLEN); // TODO. + *outport = ntohs(s->sin6_port); + } + break; + } + if (result == NULL) + { + TraceLog(LOG_WARNING, "Socket Error: %s", SocketErrorCodeToString(SocketGetLastError())); + SocketSetLastError(0); + } + else + { + strcpy(outhost, result); + } + return result; +} + +// +void PacketSend(Packet *packet) +{ + printf("Sending packet (%s) with size %d\n", packet->data, packet->size); +} + +// +void PacketReceive(Packet *packet) +{ + printf("Receiving packet (%s) with size %d\n", packet->data, packet->size); +} + +// +void PacketWrite16(Packet *packet, uint16_t value) +{ + printf("Original: 0x%04" PRIX16 " - %" PRIu16 "\n", value, value); + uint8_t *data = packet->data + packet->offs; + *data++ = (uint8_t)(value >> 8); + *data++ = (uint8_t)(value); + packet->size += sizeof(uint16_t); + packet->offs += sizeof(uint16_t); + printf("Network: 0x%04" PRIX16 " - %" PRIu16 "\n", (uint16_t) *data, (uint16_t) *data); +} + +// +void PacketWrite32(Packet *packet, uint32_t value) +{ + printf("Original: 0x%08" PRIX32 " - %" PRIu32 "\n", value, value); + uint8_t *data = packet->data + packet->offs; + *data++ = (uint8_t)(value >> 24); + *data++ = (uint8_t)(value >> 16); + *data++ = (uint8_t)(value >> 8); + *data++ = (uint8_t)(value); + packet->size += sizeof(uint32_t); + packet->offs += sizeof(uint32_t); + printf("Network: 0x%08" PRIX32 " - %" PRIu32 "\n", + (uint32_t)(((intptr_t) packet->data) - packet->offs), + (uint32_t)(((intptr_t) packet->data) - packet->offs)); +} + +// +void PacketWrite64(Packet *packet, uint64_t value) +{ + printf("Original: 0x%016" PRIX64 " - %" PRIu64 "\n", value, value); + uint8_t *data = packet->data + packet->offs; + *data++ = (uint8_t)(value >> 56); + *data++ = (uint8_t)(value >> 48); + *data++ = (uint8_t)(value >> 40); + *data++ = (uint8_t)(value >> 32); + *data++ = (uint8_t)(value >> 24); + *data++ = (uint8_t)(value >> 16); + *data++ = (uint8_t)(value >> 8); + *data++ = (uint8_t)(value); + packet->size += sizeof(uint64_t); + packet->offs += sizeof(uint64_t); + printf("Network: 0x%016" PRIX64 " - %" PRIu64 "\n", + (uint64_t)(packet->data - packet->offs), + (uint64_t)(packet->data - packet->offs)); +} + +// +uint16_t PacketRead16(Packet *packet) +{ + uint8_t *data = packet->data + packet->offs; + packet->size += sizeof(uint16_t); + packet->offs += sizeof(uint16_t); + uint16_t value = ((uint16_t) data[0] << 8) | data[1]; + printf("Original: 0x%04" PRIX16 " - %" PRIu16 "\n", value, value); + return value; +} + +// +uint32_t PacketRead32(Packet *packet) +{ + uint8_t *data = packet->data + packet->offs; + packet->size += sizeof(uint32_t); + packet->offs += sizeof(uint32_t); + uint32_t value = ((uint32_t) data[0] << 24) | ((uint32_t) data[1] << 16) | ((uint32_t) data[2] << 8) | data[3]; + printf("Original: 0x%08" PRIX32 " - %" PRIu32 "\n", value, value); + return value; +} + +// +uint64_t PacketRead64(Packet *packet) +{ + uint8_t *data = packet->data + packet->offs; + packet->size += sizeof(uint64_t); + packet->offs += sizeof(uint64_t); + uint64_t value = ((uint64_t) data[0] << 56) | ((uint64_t) data[1] << 48) | ((uint64_t) data[2] << 40) | ((uint64_t) data[3] << 32) | ((uint64_t) data[4] << 24) | ((uint64_t) data[5] << 16) | ((uint64_t) data[6] << 8) | data[7]; + printf("Original: 0x%016" PRIX64 " - %" PRIu64 "\n", value, value); + return value; +} -- cgit v1.2.3 From 9835be7b7ade3e32696fb3c0c4075c02038276f1 Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 23 Apr 2019 14:50:58 +0200 Subject: Remove unnecesary GLFW deps (used by examples) --- src/external/glfw/deps/linmath.h | 574 - src/external/glfw/deps/nuklear.h | 25539 ---------------------------- src/external/glfw/deps/nuklear_glfw_gl2.h | 381 - src/external/glfw/deps/stb_image_write.h | 1048 -- src/external/glfw/deps/tinycthread.c | 594 - src/external/glfw/deps/tinycthread.h | 443 - 6 files changed, 28579 deletions(-) delete mode 100644 src/external/glfw/deps/linmath.h delete mode 100644 src/external/glfw/deps/nuklear.h delete mode 100644 src/external/glfw/deps/nuklear_glfw_gl2.h delete mode 100644 src/external/glfw/deps/stb_image_write.h delete mode 100644 src/external/glfw/deps/tinycthread.c delete mode 100644 src/external/glfw/deps/tinycthread.h (limited to 'src') diff --git a/src/external/glfw/deps/linmath.h b/src/external/glfw/deps/linmath.h deleted file mode 100644 index 9c2e2a0a..00000000 --- a/src/external/glfw/deps/linmath.h +++ /dev/null @@ -1,574 +0,0 @@ -#ifndef LINMATH_H -#define LINMATH_H - -#include - -#ifdef _MSC_VER -#define inline __inline -#endif - -#define LINMATH_H_DEFINE_VEC(n) \ -typedef float vec##n[n]; \ -static inline void vec##n##_add(vec##n r, vec##n const a, vec##n const b) \ -{ \ - int i; \ - for(i=0; i 1e-4) { - mat4x4 T, C, S = {{0}}; - - vec3_norm(u, u); - mat4x4_from_vec3_mul_outer(T, u, u); - - S[1][2] = u[0]; - S[2][1] = -u[0]; - S[2][0] = u[1]; - S[0][2] = -u[1]; - S[0][1] = u[2]; - S[1][0] = -u[2]; - - mat4x4_scale(S, S, s); - - mat4x4_identity(C); - mat4x4_sub(C, C, T); - - mat4x4_scale(C, C, c); - - mat4x4_add(T, T, C); - mat4x4_add(T, T, S); - - T[3][3] = 1.; - mat4x4_mul(R, M, T); - } else { - mat4x4_dup(R, M); - } -} -static inline void mat4x4_rotate_X(mat4x4 Q, mat4x4 M, float angle) -{ - float s = sinf(angle); - float c = cosf(angle); - mat4x4 R = { - {1.f, 0.f, 0.f, 0.f}, - {0.f, c, s, 0.f}, - {0.f, -s, c, 0.f}, - {0.f, 0.f, 0.f, 1.f} - }; - mat4x4_mul(Q, M, R); -} -static inline void mat4x4_rotate_Y(mat4x4 Q, mat4x4 M, float angle) -{ - float s = sinf(angle); - float c = cosf(angle); - mat4x4 R = { - { c, 0.f, s, 0.f}, - { 0.f, 1.f, 0.f, 0.f}, - { -s, 0.f, c, 0.f}, - { 0.f, 0.f, 0.f, 1.f} - }; - mat4x4_mul(Q, M, R); -} -static inline void mat4x4_rotate_Z(mat4x4 Q, mat4x4 M, float angle) -{ - float s = sinf(angle); - float c = cosf(angle); - mat4x4 R = { - { c, s, 0.f, 0.f}, - { -s, c, 0.f, 0.f}, - { 0.f, 0.f, 1.f, 0.f}, - { 0.f, 0.f, 0.f, 1.f} - }; - mat4x4_mul(Q, M, R); -} -static inline void mat4x4_invert(mat4x4 T, mat4x4 M) -{ - float idet; - float s[6]; - float c[6]; - s[0] = M[0][0]*M[1][1] - M[1][0]*M[0][1]; - s[1] = M[0][0]*M[1][2] - M[1][0]*M[0][2]; - s[2] = M[0][0]*M[1][3] - M[1][0]*M[0][3]; - s[3] = M[0][1]*M[1][2] - M[1][1]*M[0][2]; - s[4] = M[0][1]*M[1][3] - M[1][1]*M[0][3]; - s[5] = M[0][2]*M[1][3] - M[1][2]*M[0][3]; - - c[0] = M[2][0]*M[3][1] - M[3][0]*M[2][1]; - c[1] = M[2][0]*M[3][2] - M[3][0]*M[2][2]; - c[2] = M[2][0]*M[3][3] - M[3][0]*M[2][3]; - c[3] = M[2][1]*M[3][2] - M[3][1]*M[2][2]; - c[4] = M[2][1]*M[3][3] - M[3][1]*M[2][3]; - c[5] = M[2][2]*M[3][3] - M[3][2]*M[2][3]; - - /* Assumes it is invertible */ - idet = 1.0f/( s[0]*c[5]-s[1]*c[4]+s[2]*c[3]+s[3]*c[2]-s[4]*c[1]+s[5]*c[0] ); - - T[0][0] = ( M[1][1] * c[5] - M[1][2] * c[4] + M[1][3] * c[3]) * idet; - T[0][1] = (-M[0][1] * c[5] + M[0][2] * c[4] - M[0][3] * c[3]) * idet; - T[0][2] = ( M[3][1] * s[5] - M[3][2] * s[4] + M[3][3] * s[3]) * idet; - T[0][3] = (-M[2][1] * s[5] + M[2][2] * s[4] - M[2][3] * s[3]) * idet; - - T[1][0] = (-M[1][0] * c[5] + M[1][2] * c[2] - M[1][3] * c[1]) * idet; - T[1][1] = ( M[0][0] * c[5] - M[0][2] * c[2] + M[0][3] * c[1]) * idet; - T[1][2] = (-M[3][0] * s[5] + M[3][2] * s[2] - M[3][3] * s[1]) * idet; - T[1][3] = ( M[2][0] * s[5] - M[2][2] * s[2] + M[2][3] * s[1]) * idet; - - T[2][0] = ( M[1][0] * c[4] - M[1][1] * c[2] + M[1][3] * c[0]) * idet; - T[2][1] = (-M[0][0] * c[4] + M[0][1] * c[2] - M[0][3] * c[0]) * idet; - T[2][2] = ( M[3][0] * s[4] - M[3][1] * s[2] + M[3][3] * s[0]) * idet; - T[2][3] = (-M[2][0] * s[4] + M[2][1] * s[2] - M[2][3] * s[0]) * idet; - - T[3][0] = (-M[1][0] * c[3] + M[1][1] * c[1] - M[1][2] * c[0]) * idet; - T[3][1] = ( M[0][0] * c[3] - M[0][1] * c[1] + M[0][2] * c[0]) * idet; - T[3][2] = (-M[3][0] * s[3] + M[3][1] * s[1] - M[3][2] * s[0]) * idet; - T[3][3] = ( M[2][0] * s[3] - M[2][1] * s[1] + M[2][2] * s[0]) * idet; -} -static inline void mat4x4_orthonormalize(mat4x4 R, mat4x4 M) -{ - float s = 1.; - vec3 h; - - mat4x4_dup(R, M); - vec3_norm(R[2], R[2]); - - s = vec3_mul_inner(R[1], R[2]); - vec3_scale(h, R[2], s); - vec3_sub(R[1], R[1], h); - vec3_norm(R[2], R[2]); - - s = vec3_mul_inner(R[1], R[2]); - vec3_scale(h, R[2], s); - vec3_sub(R[1], R[1], h); - vec3_norm(R[1], R[1]); - - s = vec3_mul_inner(R[0], R[1]); - vec3_scale(h, R[1], s); - vec3_sub(R[0], R[0], h); - vec3_norm(R[0], R[0]); -} - -static inline void mat4x4_frustum(mat4x4 M, float l, float r, float b, float t, float n, float f) -{ - M[0][0] = 2.f*n/(r-l); - M[0][1] = M[0][2] = M[0][3] = 0.f; - - M[1][1] = 2.f*n/(t-b); - M[1][0] = M[1][2] = M[1][3] = 0.f; - - M[2][0] = (r+l)/(r-l); - M[2][1] = (t+b)/(t-b); - M[2][2] = -(f+n)/(f-n); - M[2][3] = -1.f; - - M[3][2] = -2.f*(f*n)/(f-n); - M[3][0] = M[3][1] = M[3][3] = 0.f; -} -static inline void mat4x4_ortho(mat4x4 M, float l, float r, float b, float t, float n, float f) -{ - M[0][0] = 2.f/(r-l); - M[0][1] = M[0][2] = M[0][3] = 0.f; - - M[1][1] = 2.f/(t-b); - M[1][0] = M[1][2] = M[1][3] = 0.f; - - M[2][2] = -2.f/(f-n); - M[2][0] = M[2][1] = M[2][3] = 0.f; - - M[3][0] = -(r+l)/(r-l); - M[3][1] = -(t+b)/(t-b); - M[3][2] = -(f+n)/(f-n); - M[3][3] = 1.f; -} -static inline void mat4x4_perspective(mat4x4 m, float y_fov, float aspect, float n, float f) -{ - /* NOTE: Degrees are an unhandy unit to work with. - * linmath.h uses radians for everything! */ - float const a = 1.f / (float) tan(y_fov / 2.f); - - m[0][0] = a / aspect; - m[0][1] = 0.f; - m[0][2] = 0.f; - m[0][3] = 0.f; - - m[1][0] = 0.f; - m[1][1] = a; - m[1][2] = 0.f; - m[1][3] = 0.f; - - m[2][0] = 0.f; - m[2][1] = 0.f; - m[2][2] = -((f + n) / (f - n)); - m[2][3] = -1.f; - - m[3][0] = 0.f; - m[3][1] = 0.f; - m[3][2] = -((2.f * f * n) / (f - n)); - m[3][3] = 0.f; -} -static inline void mat4x4_look_at(mat4x4 m, vec3 eye, vec3 center, vec3 up) -{ - /* Adapted from Android's OpenGL Matrix.java. */ - /* See the OpenGL GLUT documentation for gluLookAt for a description */ - /* of the algorithm. We implement it in a straightforward way: */ - - /* TODO: The negation of of can be spared by swapping the order of - * operands in the following cross products in the right way. */ - vec3 f; - vec3 s; - vec3 t; - - vec3_sub(f, center, eye); - vec3_norm(f, f); - - vec3_mul_cross(s, f, up); - vec3_norm(s, s); - - vec3_mul_cross(t, s, f); - - m[0][0] = s[0]; - m[0][1] = t[0]; - m[0][2] = -f[0]; - m[0][3] = 0.f; - - m[1][0] = s[1]; - m[1][1] = t[1]; - m[1][2] = -f[1]; - m[1][3] = 0.f; - - m[2][0] = s[2]; - m[2][1] = t[2]; - m[2][2] = -f[2]; - m[2][3] = 0.f; - - m[3][0] = 0.f; - m[3][1] = 0.f; - m[3][2] = 0.f; - m[3][3] = 1.f; - - mat4x4_translate_in_place(m, -eye[0], -eye[1], -eye[2]); -} - -typedef float quat[4]; -static inline void quat_identity(quat q) -{ - q[0] = q[1] = q[2] = 0.f; - q[3] = 1.f; -} -static inline void quat_add(quat r, quat a, quat b) -{ - int i; - for(i=0; i<4; ++i) - r[i] = a[i] + b[i]; -} -static inline void quat_sub(quat r, quat a, quat b) -{ - int i; - for(i=0; i<4; ++i) - r[i] = a[i] - b[i]; -} -static inline void quat_mul(quat r, quat p, quat q) -{ - vec3 w; - vec3_mul_cross(r, p, q); - vec3_scale(w, p, q[3]); - vec3_add(r, r, w); - vec3_scale(w, q, p[3]); - vec3_add(r, r, w); - r[3] = p[3]*q[3] - vec3_mul_inner(p, q); -} -static inline void quat_scale(quat r, quat v, float s) -{ - int i; - for(i=0; i<4; ++i) - r[i] = v[i] * s; -} -static inline float quat_inner_product(quat a, quat b) -{ - float p = 0.f; - int i; - for(i=0; i<4; ++i) - p += b[i]*a[i]; - return p; -} -static inline void quat_conj(quat r, quat q) -{ - int i; - for(i=0; i<3; ++i) - r[i] = -q[i]; - r[3] = q[3]; -} -static inline void quat_rotate(quat r, float angle, vec3 axis) { - int i; - vec3 v; - vec3_scale(v, axis, sinf(angle / 2)); - for(i=0; i<3; ++i) - r[i] = v[i]; - r[3] = cosf(angle / 2); -} -#define quat_norm vec4_norm -static inline void quat_mul_vec3(vec3 r, quat q, vec3 v) -{ -/* - * Method by Fabian 'ryg' Giessen (of Farbrausch) -t = 2 * cross(q.xyz, v) -v' = v + q.w * t + cross(q.xyz, t) - */ - vec3 t = {q[0], q[1], q[2]}; - vec3 u = {q[0], q[1], q[2]}; - - vec3_mul_cross(t, t, v); - vec3_scale(t, t, 2); - - vec3_mul_cross(u, u, t); - vec3_scale(t, t, q[3]); - - vec3_add(r, v, t); - vec3_add(r, r, u); -} -static inline void mat4x4_from_quat(mat4x4 M, quat q) -{ - float a = q[3]; - float b = q[0]; - float c = q[1]; - float d = q[2]; - float a2 = a*a; - float b2 = b*b; - float c2 = c*c; - float d2 = d*d; - - M[0][0] = a2 + b2 - c2 - d2; - M[0][1] = 2.f*(b*c + a*d); - M[0][2] = 2.f*(b*d - a*c); - M[0][3] = 0.f; - - M[1][0] = 2*(b*c - a*d); - M[1][1] = a2 - b2 + c2 - d2; - M[1][2] = 2.f*(c*d + a*b); - M[1][3] = 0.f; - - M[2][0] = 2.f*(b*d + a*c); - M[2][1] = 2.f*(c*d - a*b); - M[2][2] = a2 - b2 - c2 + d2; - M[2][3] = 0.f; - - M[3][0] = M[3][1] = M[3][2] = 0.f; - M[3][3] = 1.f; -} - -static inline void mat4x4o_mul_quat(mat4x4 R, mat4x4 M, quat q) -{ -/* XXX: The way this is written only works for othogonal matrices. */ -/* TODO: Take care of non-orthogonal case. */ - quat_mul_vec3(R[0], q, M[0]); - quat_mul_vec3(R[1], q, M[1]); - quat_mul_vec3(R[2], q, M[2]); - - R[3][0] = R[3][1] = R[3][2] = 0.f; - R[3][3] = 1.f; -} -static inline void quat_from_mat4x4(quat q, mat4x4 M) -{ - float r=0.f; - int i; - - int perm[] = { 0, 1, 2, 0, 1 }; - int *p = perm; - - for(i = 0; i<3; i++) { - float m = M[i][i]; - if( m < r ) - continue; - m = r; - p = &perm[i]; - } - - r = (float) sqrt(1.f + M[p[0]][p[0]] - M[p[1]][p[1]] - M[p[2]][p[2]] ); - - if(r < 1e-6) { - q[0] = 1.f; - q[1] = q[2] = q[3] = 0.f; - return; - } - - q[0] = r/2.f; - q[1] = (M[p[0]][p[1]] - M[p[1]][p[0]])/(2.f*r); - q[2] = (M[p[2]][p[0]] - M[p[0]][p[2]])/(2.f*r); - q[3] = (M[p[2]][p[1]] - M[p[1]][p[2]])/(2.f*r); -} - -#endif diff --git a/src/external/glfw/deps/nuklear.h b/src/external/glfw/deps/nuklear.h deleted file mode 100644 index 6c873535..00000000 --- a/src/external/glfw/deps/nuklear.h +++ /dev/null @@ -1,25539 +0,0 @@ -/* -/// # Nuklear -/// ![](https://cloud.githubusercontent.com/assets/8057201/11761525/ae06f0ca-a0c6-11e5-819d-5610b25f6ef4.gif) -/// -/// ## Contents -/// 1. About section -/// 2. Highlights section -/// 3. Features section -/// 4. Usage section -/// 1. Flags section -/// 2. Constants section -/// 3. Dependencies section -/// 5. Example section -/// 6. API section -/// 1. Context section -/// 2. Input section -/// 3. Drawing section -/// 4. Window section -/// 5. Layouting section -/// 6. Groups section -/// 7. Tree section -/// 8. Properties section -/// 7. License section -/// 8. Changelog section -/// 9. Gallery section -/// 10. Credits section -/// -/// ## About -/// This is a minimal state immediate mode graphical user interface toolkit -/// written in ANSI C and licensed under public domain. It was designed as a simple -/// embeddable user interface for application and does not have any dependencies, -/// a default renderbackend or OS window and input handling but instead provides a very modular -/// library approach by using simple input state for input and draw -/// commands describing primitive shapes as output. So instead of providing a -/// layered library that tries to abstract over a number of platform and -/// render backends it only focuses on the actual UI. -/// -/// ## Highlights -/// - Graphical user interface toolkit -/// - Single header library -/// - Written in C89 (a.k.a. ANSI C or ISO C90) -/// - Small codebase (~18kLOC) -/// - Focus on portability, efficiency and simplicity -/// - No dependencies (not even the standard library if not wanted) -/// - Fully skinnable and customizable -/// - Low memory footprint with total memory control if needed or wanted -/// - UTF-8 support -/// - No global or hidden state -/// - Customizable library modules (you can compile and use only what you need) -/// - Optional font baker and vertex buffer output -/// -/// ## Features -/// - Absolutely no platform dependent code -/// - Memory management control ranging from/to -/// - Ease of use by allocating everything from standard library -/// - Control every byte of memory inside the library -/// - Font handling control ranging from/to -/// - Use your own font implementation for everything -/// - Use this libraries internal font baking and handling API -/// - Drawing output control ranging from/to -/// - Simple shapes for more high level APIs which already have drawing capabilities -/// - Hardware accessible anti-aliased vertex buffer output -/// - Customizable colors and properties ranging from/to -/// - Simple changes to color by filling a simple color table -/// - Complete control with ability to use skinning to decorate widgets -/// - Bendable UI library with widget ranging from/to -/// - Basic widgets like buttons, checkboxes, slider, ... -/// - Advanced widget like abstract comboboxes, contextual menus,... -/// - Compile time configuration to only compile what you need -/// - Subset which can be used if you do not want to link or use the standard library -/// - Can be easily modified to only update on user input instead of frame updates -/// -/// ## Usage -/// This library is self contained in one single header file and can be used either -/// in header only mode or in implementation mode. The header only mode is used -/// by default when included and allows including this header in other headers -/// and does not contain the actual implementation.

-/// -/// The implementation mode requires to define the preprocessor macro -/// NK_IMPLEMENTATION in *one* .c/.cpp file before #includeing this file, e.g.: -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~C -/// #define NK_IMPLEMENTATION -/// #include "nuklear.h" -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Also optionally define the symbols listed in the section "OPTIONAL DEFINES" -/// below in header and implementation mode if you want to use additional functionality -/// or need more control over the library. -/// -/// !!! WARNING -/// Every time nuklear is included define the same compiler flags. This very important not doing so could lead to compiler errors or even worse stack corruptions. -/// -/// ### Flags -/// Flag | Description -/// --------------------------------|------------------------------------------ -/// NK_PRIVATE | If defined declares all functions as static, so they can only be accessed inside the file that contains the implementation -/// NK_INCLUDE_FIXED_TYPES | If defined it will include header `` for fixed sized types otherwise nuklear tries to select the correct type. If that fails it will throw a compiler error and you have to select the correct types yourself. -/// NK_INCLUDE_DEFAULT_ALLOCATOR | If defined it will include header `` and provide additional functions to use this library without caring for memory allocation control and therefore ease memory management. -/// NK_INCLUDE_STANDARD_IO | If defined it will include header `` and provide additional functions depending on file loading. -/// NK_INCLUDE_STANDARD_VARARGS | If defined it will include header and provide additional functions depending on file loading. -/// NK_INCLUDE_VERTEX_BUFFER_OUTPUT | Defining this adds a vertex draw command list backend to this library, which allows you to convert queue commands into vertex draw commands. This is mainly if you need a hardware accessible format for OpenGL, DirectX, Vulkan, Metal,... -/// NK_INCLUDE_FONT_BAKING | Defining this adds `stb_truetype` and `stb_rect_pack` implementation to this library and provides font baking and rendering. If you already have font handling or do not want to use this font handler you don't have to define it. -/// NK_INCLUDE_DEFAULT_FONT | Defining this adds the default font: ProggyClean.ttf into this library which can be loaded into a font atlas and allows using this library without having a truetype font -/// NK_INCLUDE_COMMAND_USERDATA | Defining this adds a userdata pointer into each command. Can be useful for example if you want to provide custom shaders depending on the used widget. Can be combined with the style structures. -/// NK_BUTTON_TRIGGER_ON_RELEASE | Different platforms require button clicks occurring either on buttons being pressed (up to down) or released (down to up). By default this library will react on buttons being pressed, but if you define this it will only trigger if a button is released. -/// NK_ZERO_COMMAND_MEMORY | Defining this will zero out memory for each drawing command added to a drawing queue (inside nk_command_buffer_push). Zeroing command memory is very useful for fast checking (using memcmp) if command buffers are equal and avoid drawing frames when nothing on screen has changed since previous frame. -/// -/// !!! WARNING -/// The following flags will pull in the standard C library: -/// - NK_INCLUDE_DEFAULT_ALLOCATOR -/// - NK_INCLUDE_STANDARD_IO -/// - NK_INCLUDE_STANDARD_VARARGS -/// -/// !!! WARNING -/// The following flags if defined need to be defined for both header and implementation: -/// - NK_INCLUDE_FIXED_TYPES -/// - NK_INCLUDE_DEFAULT_ALLOCATOR -/// - NK_INCLUDE_STANDARD_VARARGS -/// - NK_INCLUDE_VERTEX_BUFFER_OUTPUT -/// - NK_INCLUDE_FONT_BAKING -/// - NK_INCLUDE_DEFAULT_FONT -/// - NK_INCLUDE_STANDARD_VARARGS -/// - NK_INCLUDE_COMMAND_USERDATA -/// -/// ### Constants -/// Define | Description -/// --------------------------------|--------------------------------------- -/// NK_BUFFER_DEFAULT_INITIAL_SIZE | Initial buffer size allocated by all buffers while using the default allocator functions included by defining NK_INCLUDE_DEFAULT_ALLOCATOR. If you don't want to allocate the default 4k memory then redefine it. -/// NK_MAX_NUMBER_BUFFER | Maximum buffer size for the conversion buffer between float and string Under normal circumstances this should be more than sufficient. -/// NK_INPUT_MAX | Defines the max number of bytes which can be added as text input in one frame. Under normal circumstances this should be more than sufficient. -/// -/// !!! WARNING -/// The following constants if defined need to be defined for both header and implementation: -/// - NK_MAX_NUMBER_BUFFER -/// - NK_BUFFER_DEFAULT_INITIAL_SIZE -/// - NK_INPUT_MAX -/// -/// ### Dependencies -/// Function | Description -/// ------------|--------------------------------------------------------------- -/// NK_ASSERT | If you don't define this, nuklear will use with assert(). -/// NK_MEMSET | You can define this to 'memset' or your own memset implementation replacement. If not nuklear will use its own version. -/// NK_MEMCPY | You can define this to 'memcpy' or your own memcpy implementation replacement. If not nuklear will use its own version. -/// NK_SQRT | You can define this to 'sqrt' or your own sqrt implementation replacement. If not nuklear will use its own slow and not highly accurate version. -/// NK_SIN | You can define this to 'sinf' or your own sine implementation replacement. If not nuklear will use its own approximation implementation. -/// NK_COS | You can define this to 'cosf' or your own cosine implementation replacement. If not nuklear will use its own approximation implementation. -/// NK_STRTOD | You can define this to `strtod` or your own string to double conversion implementation replacement. If not defined nuklear will use its own imprecise and possibly unsafe version (does not handle nan or infinity!). -/// NK_DTOA | You can define this to `dtoa` or your own double to string conversion implementation replacement. If not defined nuklear will use its own imprecise and possibly unsafe version (does not handle nan or infinity!). -/// NK_VSNPRINTF| If you define `NK_INCLUDE_STANDARD_VARARGS` as well as `NK_INCLUDE_STANDARD_IO` and want to be safe define this to `vsnprintf` on compilers supporting later versions of C or C++. By default nuklear will check for your stdlib version in C as well as compiler version in C++. if `vsnprintf` is available it will define it to `vsnprintf` directly. If not defined and if you have older versions of C or C++ it will be defined to `vsprintf` which is unsafe. -/// -/// !!! WARNING -/// The following dependencies will pull in the standard C library if not redefined: -/// - NK_ASSERT -/// -/// !!! WARNING -/// The following dependencies if defined need to be defined for both header and implementation: -/// - NK_ASSERT -/// -/// !!! WARNING -/// The following dependencies if defined need to be defined only for the implementation part: -/// - NK_MEMSET -/// - NK_MEMCPY -/// - NK_SQRT -/// - NK_SIN -/// - NK_COS -/// - NK_STRTOD -/// - NK_DTOA -/// - NK_VSNPRINTF -/// -/// ## Example -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// // init gui state -/// enum {EASY, HARD}; -/// static int op = EASY; -/// static float value = 0.6f; -/// static int i = 20; -/// struct nk_context ctx; -/// -/// nk_init_fixed(&ctx, calloc(1, MAX_MEMORY), MAX_MEMORY, &font); -/// if (nk_begin(&ctx, "Show", nk_rect(50, 50, 220, 220), -/// NK_WINDOW_BORDER|NK_WINDOW_MOVABLE|NK_WINDOW_CLOSABLE)) { -/// // fixed widget pixel width -/// nk_layout_row_static(&ctx, 30, 80, 1); -/// if (nk_button_label(&ctx, "button")) { -/// // event handling -/// } -/// -/// // fixed widget window ratio width -/// nk_layout_row_dynamic(&ctx, 30, 2); -/// if (nk_option_label(&ctx, "easy", op == EASY)) op = EASY; -/// if (nk_option_label(&ctx, "hard", op == HARD)) op = HARD; -/// -/// // custom widget pixel width -/// nk_layout_row_begin(&ctx, NK_STATIC, 30, 2); -/// { -/// nk_layout_row_push(&ctx, 50); -/// nk_label(&ctx, "Volume:", NK_TEXT_LEFT); -/// nk_layout_row_push(&ctx, 110); -/// nk_slider_float(&ctx, 0, &value, 1.0f, 0.1f); -/// } -/// nk_layout_row_end(&ctx); -/// } -/// nk_end(&ctx); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// ![](https://cloud.githubusercontent.com/assets/8057201/10187981/584ecd68-675c-11e5-897c-822ef534a876.png) -/// -/// ## API -/// -*/ -#ifndef NK_SINGLE_FILE - #define NK_SINGLE_FILE -#endif - -#ifndef NK_NUKLEAR_H_ -#define NK_NUKLEAR_H_ - -#ifdef __cplusplus -extern "C" { -#endif -/* - * ============================================================== - * - * CONSTANTS - * - * =============================================================== - */ -#define NK_UNDEFINED (-1.0f) -#define NK_UTF_INVALID 0xFFFD /* internal invalid utf8 rune */ -#define NK_UTF_SIZE 4 /* describes the number of bytes a glyph consists of*/ -#ifndef NK_INPUT_MAX - #define NK_INPUT_MAX 16 -#endif -#ifndef NK_MAX_NUMBER_BUFFER - #define NK_MAX_NUMBER_BUFFER 64 -#endif -#ifndef NK_SCROLLBAR_HIDING_TIMEOUT - #define NK_SCROLLBAR_HIDING_TIMEOUT 4.0f -#endif -/* - * ============================================================== - * - * HELPER - * - * =============================================================== - */ -#ifndef NK_API - #ifdef NK_PRIVATE - #if (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199409L)) - #define NK_API static inline - #elif defined(__cplusplus) - #define NK_API static inline - #else - #define NK_API static - #endif - #else - #define NK_API extern - #endif -#endif -#ifndef NK_LIB - #ifdef NK_SINGLE_FILE - #define NK_LIB static - #else - #define NK_LIB extern - #endif -#endif - -#define NK_INTERN static -#define NK_STORAGE static -#define NK_GLOBAL static - -#define NK_FLAG(x) (1 << (x)) -#define NK_STRINGIFY(x) #x -#define NK_MACRO_STRINGIFY(x) NK_STRINGIFY(x) -#define NK_STRING_JOIN_IMMEDIATE(arg1, arg2) arg1 ## arg2 -#define NK_STRING_JOIN_DELAY(arg1, arg2) NK_STRING_JOIN_IMMEDIATE(arg1, arg2) -#define NK_STRING_JOIN(arg1, arg2) NK_STRING_JOIN_DELAY(arg1, arg2) - -#ifdef _MSC_VER - #define NK_UNIQUE_NAME(name) NK_STRING_JOIN(name,__COUNTER__) -#else - #define NK_UNIQUE_NAME(name) NK_STRING_JOIN(name,__LINE__) -#endif - -#ifndef NK_STATIC_ASSERT - #define NK_STATIC_ASSERT(exp) typedef char NK_UNIQUE_NAME(_dummy_array)[(exp)?1:-1] -#endif - -#ifndef NK_FILE_LINE -#ifdef _MSC_VER - #define NK_FILE_LINE __FILE__ ":" NK_MACRO_STRINGIFY(__COUNTER__) -#else - #define NK_FILE_LINE __FILE__ ":" NK_MACRO_STRINGIFY(__LINE__) -#endif -#endif - -#define NK_MIN(a,b) ((a) < (b) ? (a) : (b)) -#define NK_MAX(a,b) ((a) < (b) ? (b) : (a)) -#define NK_CLAMP(i,v,x) (NK_MAX(NK_MIN(v,x), i)) - -#ifdef NK_INCLUDE_STANDARD_VARARGS - #if defined(_MSC_VER) && (_MSC_VER >= 1600) /* VS 2010 and above */ - #include - #define NK_PRINTF_FORMAT_STRING _Printf_format_string_ - #else - #define NK_PRINTF_FORMAT_STRING - #endif - #if defined(__GNUC__) - #define NK_PRINTF_VARARG_FUNC(fmtargnumber) __attribute__((format(__printf__, fmtargnumber, fmtargnumber+1))) - #define NK_PRINTF_VALIST_FUNC(fmtargnumber) __attribute__((format(__printf__, fmtargnumber, 0))) - #else - #define NK_PRINTF_VARARG_FUNC(fmtargnumber) - #define NK_PRINTF_VALIST_FUNC(fmtargnumber) - #endif - #include /* valist, va_start, va_end, ... */ -#endif - -/* - * =============================================================== - * - * BASIC - * - * =============================================================== - */ -#ifdef NK_INCLUDE_FIXED_TYPES - #include - #define NK_INT8 int8_t - #define NK_UINT8 uint8_t - #define NK_INT16 int16_t - #define NK_UINT16 uint16_t - #define NK_INT32 int32_t - #define NK_UINT32 uint32_t - #define NK_SIZE_TYPE uintptr_t - #define NK_POINTER_TYPE uintptr_t -#else - #ifndef NK_INT8 - #define NK_INT8 char - #endif - #ifndef NK_UINT8 - #define NK_UINT8 unsigned char - #endif - #ifndef NK_INT16 - #define NK_INT16 signed short - #endif - #ifndef NK_UINT16 - #define NK_UINT16 unsigned short - #endif - #ifndef NK_INT32 - #if defined(_MSC_VER) - #define NK_INT32 __int32 - #else - #define NK_INT32 signed int - #endif - #endif - #ifndef NK_UINT32 - #if defined(_MSC_VER) - #define NK_UINT32 unsigned __int32 - #else - #define NK_UINT32 unsigned int - #endif - #endif - #ifndef NK_SIZE_TYPE - #if defined(_WIN64) && defined(_MSC_VER) - #define NK_SIZE_TYPE unsigned __int64 - #elif (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER) - #define NK_SIZE_TYPE unsigned __int32 - #elif defined(__GNUC__) || defined(__clang__) - #if defined(__x86_64__) || defined(__ppc64__) - #define NK_SIZE_TYPE unsigned long - #else - #define NK_SIZE_TYPE unsigned int - #endif - #else - #define NK_SIZE_TYPE unsigned long - #endif - #endif - #ifndef NK_POINTER_TYPE - #if defined(_WIN64) && defined(_MSC_VER) - #define NK_POINTER_TYPE unsigned __int64 - #elif (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER) - #define NK_POINTER_TYPE unsigned __int32 - #elif defined(__GNUC__) || defined(__clang__) - #if defined(__x86_64__) || defined(__ppc64__) - #define NK_POINTER_TYPE unsigned long - #else - #define NK_POINTER_TYPE unsigned int - #endif - #else - #define NK_POINTER_TYPE unsigned long - #endif - #endif -#endif - -typedef NK_INT8 nk_char; -typedef NK_UINT8 nk_uchar; -typedef NK_UINT8 nk_byte; -typedef NK_INT16 nk_short; -typedef NK_UINT16 nk_ushort; -typedef NK_INT32 nk_int; -typedef NK_UINT32 nk_uint; -typedef NK_SIZE_TYPE nk_size; -typedef NK_POINTER_TYPE nk_ptr; - -typedef nk_uint nk_hash; -typedef nk_uint nk_flags; -typedef nk_uint nk_rune; - -/* Make sure correct type size: - * This will fire with a negative subscript error if the type sizes - * are set incorrectly by the compiler, and compile out if not */ -NK_STATIC_ASSERT(sizeof(nk_short) == 2); -NK_STATIC_ASSERT(sizeof(nk_ushort) == 2); -NK_STATIC_ASSERT(sizeof(nk_uint) == 4); -NK_STATIC_ASSERT(sizeof(nk_int) == 4); -NK_STATIC_ASSERT(sizeof(nk_byte) == 1); -NK_STATIC_ASSERT(sizeof(nk_flags) >= 4); -NK_STATIC_ASSERT(sizeof(nk_rune) >= 4); -NK_STATIC_ASSERT(sizeof(nk_size) >= sizeof(void*)); -NK_STATIC_ASSERT(sizeof(nk_ptr) >= sizeof(void*)); - -/* ============================================================================ - * - * API - * - * =========================================================================== */ -struct nk_buffer; -struct nk_allocator; -struct nk_command_buffer; -struct nk_draw_command; -struct nk_convert_config; -struct nk_style_item; -struct nk_text_edit; -struct nk_draw_list; -struct nk_user_font; -struct nk_panel; -struct nk_context; -struct nk_draw_vertex_layout_element; -struct nk_style_button; -struct nk_style_toggle; -struct nk_style_selectable; -struct nk_style_slide; -struct nk_style_progress; -struct nk_style_scrollbar; -struct nk_style_edit; -struct nk_style_property; -struct nk_style_chart; -struct nk_style_combo; -struct nk_style_tab; -struct nk_style_window_header; -struct nk_style_window; - -enum {nk_false, nk_true}; -struct nk_color {nk_byte r,g,b,a;}; -struct nk_colorf {float r,g,b,a;}; -struct nk_vec2 {float x,y;}; -struct nk_vec2i {short x, y;}; -struct nk_rect {float x,y,w,h;}; -struct nk_recti {short x,y,w,h;}; -typedef char nk_glyph[NK_UTF_SIZE]; -typedef union {void *ptr; int id;} nk_handle; -struct nk_image {nk_handle handle;unsigned short w,h;unsigned short region[4];}; -struct nk_cursor {struct nk_image img; struct nk_vec2 size, offset;}; -struct nk_scroll {nk_uint x, y;}; - -enum nk_heading {NK_UP, NK_RIGHT, NK_DOWN, NK_LEFT}; -enum nk_button_behavior {NK_BUTTON_DEFAULT, NK_BUTTON_REPEATER}; -enum nk_modify {NK_FIXED = nk_false, NK_MODIFIABLE = nk_true}; -enum nk_orientation {NK_VERTICAL, NK_HORIZONTAL}; -enum nk_collapse_states {NK_MINIMIZED = nk_false, NK_MAXIMIZED = nk_true}; -enum nk_show_states {NK_HIDDEN = nk_false, NK_SHOWN = nk_true}; -enum nk_chart_type {NK_CHART_LINES, NK_CHART_COLUMN, NK_CHART_MAX}; -enum nk_chart_event {NK_CHART_HOVERING = 0x01, NK_CHART_CLICKED = 0x02}; -enum nk_color_format {NK_RGB, NK_RGBA}; -enum nk_popup_type {NK_POPUP_STATIC, NK_POPUP_DYNAMIC}; -enum nk_layout_format {NK_DYNAMIC, NK_STATIC}; -enum nk_tree_type {NK_TREE_NODE, NK_TREE_TAB}; - -typedef void*(*nk_plugin_alloc)(nk_handle, void *old, nk_size); -typedef void (*nk_plugin_free)(nk_handle, void *old); -typedef int(*nk_plugin_filter)(const struct nk_text_edit*, nk_rune unicode); -typedef void(*nk_plugin_paste)(nk_handle, struct nk_text_edit*); -typedef void(*nk_plugin_copy)(nk_handle, const char*, int len); - -struct nk_allocator { - nk_handle userdata; - nk_plugin_alloc alloc; - nk_plugin_free free; -}; -enum nk_symbol_type { - NK_SYMBOL_NONE, - NK_SYMBOL_X, - NK_SYMBOL_UNDERSCORE, - NK_SYMBOL_CIRCLE_SOLID, - NK_SYMBOL_CIRCLE_OUTLINE, - NK_SYMBOL_RECT_SOLID, - NK_SYMBOL_RECT_OUTLINE, - NK_SYMBOL_TRIANGLE_UP, - NK_SYMBOL_TRIANGLE_DOWN, - NK_SYMBOL_TRIANGLE_LEFT, - NK_SYMBOL_TRIANGLE_RIGHT, - NK_SYMBOL_PLUS, - NK_SYMBOL_MINUS, - NK_SYMBOL_MAX -}; -/* ============================================================================= - * - * CONTEXT - * - * =============================================================================*/ -/*/// ### Context -/// Contexts are the main entry point and the majestro of nuklear and contain all required state. -/// They are used for window, memory, input, style, stack, commands and time management and need -/// to be passed into all nuklear GUI specific functions. -/// -/// #### Usage -/// To use a context it first has to be initialized which can be achieved by calling -/// one of either `nk_init_default`, `nk_init_fixed`, `nk_init`, `nk_init_custom`. -/// Each takes in a font handle and a specific way of handling memory. Memory control -/// hereby ranges from standard library to just specifying a fixed sized block of memory -/// which nuklear has to manage itself from. -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// struct nk_context ctx; -/// nk_init_xxx(&ctx, ...); -/// while (1) { -/// // [...] -/// nk_clear(&ctx); -/// } -/// nk_free(&ctx); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// #### Reference -/// Function | Description -/// --------------------|------------------------------------------------------- -/// __nk_init_default__ | Initializes context with standard library memory allocation (malloc,free) -/// __nk_init_fixed__ | Initializes context from single fixed size memory block -/// __nk_init__ | Initializes context with memory allocator callbacks for alloc and free -/// __nk_init_custom__ | Initializes context from two buffers. One for draw commands the other for window/panel/table allocations -/// __nk_clear__ | Called at the end of the frame to reset and prepare the context for the next frame -/// __nk_free__ | Shutdown and free all memory allocated inside the context -/// __nk_set_user_data__| Utility function to pass user data to draw command - */ -#ifdef NK_INCLUDE_DEFAULT_ALLOCATOR -/*/// #### nk_init_default -/// Initializes a `nk_context` struct with a default standard library allocator. -/// Should be used if you don't want to be bothered with memory management in nuklear. -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// int nk_init_default(struct nk_context *ctx, const struct nk_user_font *font); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|--------------------------------------------------------------- -/// __ctx__ | Must point to an either stack or heap allocated `nk_context` struct -/// __font__ | Must point to a previously initialized font handle for more info look at font documentation -/// -/// Returns either `false(0)` on failure or `true(1)` on success. -/// -*/ -NK_API int nk_init_default(struct nk_context*, const struct nk_user_font*); -#endif -/*/// #### nk_init_fixed -/// Initializes a `nk_context` struct from single fixed size memory block -/// Should be used if you want complete control over nuklear's memory management. -/// Especially recommended for system with little memory or systems with virtual memory. -/// For the later case you can just allocate for example 16MB of virtual memory -/// and only the required amount of memory will actually be committed. -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// int nk_init_fixed(struct nk_context *ctx, void *memory, nk_size size, const struct nk_user_font *font); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// !!! Warning -/// make sure the passed memory block is aligned correctly for `nk_draw_commands`. -/// -/// Parameter | Description -/// ------------|-------------------------------------------------------------- -/// __ctx__ | Must point to an either stack or heap allocated `nk_context` struct -/// __memory__ | Must point to a previously allocated memory block -/// __size__ | Must contain the total size of __memory__ -/// __font__ | Must point to a previously initialized font handle for more info look at font documentation -/// -/// Returns either `false(0)` on failure or `true(1)` on success. -*/ -NK_API int nk_init_fixed(struct nk_context*, void *memory, nk_size size, const struct nk_user_font*); -/*/// #### nk_init -/// Initializes a `nk_context` struct with memory allocation callbacks for nuklear to allocate -/// memory from. Used internally for `nk_init_default` and provides a kitchen sink allocation -/// interface to nuklear. Can be useful for cases like monitoring memory consumption. -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// int nk_init(struct nk_context *ctx, struct nk_allocator *alloc, const struct nk_user_font *font); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|--------------------------------------------------------------- -/// __ctx__ | Must point to an either stack or heap allocated `nk_context` struct -/// __alloc__ | Must point to a previously allocated memory allocator -/// __font__ | Must point to a previously initialized font handle for more info look at font documentation -/// -/// Returns either `false(0)` on failure or `true(1)` on success. -*/ -NK_API int nk_init(struct nk_context*, struct nk_allocator*, const struct nk_user_font*); -/*/// #### nk_init_custom -/// Initializes a `nk_context` struct from two different either fixed or growing -/// buffers. The first buffer is for allocating draw commands while the second buffer is -/// used for allocating windows, panels and state tables. -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// int nk_init_custom(struct nk_context *ctx, struct nk_buffer *cmds, struct nk_buffer *pool, const struct nk_user_font *font); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|--------------------------------------------------------------- -/// __ctx__ | Must point to an either stack or heap allocated `nk_context` struct -/// __cmds__ | Must point to a previously initialized memory buffer either fixed or dynamic to store draw commands into -/// __pool__ | Must point to a previously initialized memory buffer either fixed or dynamic to store windows, panels and tables -/// __font__ | Must point to a previously initialized font handle for more info look at font documentation -/// -/// Returns either `false(0)` on failure or `true(1)` on success. -*/ -NK_API int nk_init_custom(struct nk_context*, struct nk_buffer *cmds, struct nk_buffer *pool, const struct nk_user_font*); -/*/// #### nk_clear -/// Resets the context state at the end of the frame. This includes mostly -/// garbage collector tasks like removing windows or table not called and therefore -/// used anymore. -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_clear(struct nk_context *ctx); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to a previously initialized `nk_context` struct -*/ -NK_API void nk_clear(struct nk_context*); -/*/// #### nk_free -/// Frees all memory allocated by nuklear. Not needed if context was -/// initialized with `nk_init_fixed`. -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_free(struct nk_context *ctx); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to a previously initialized `nk_context` struct -*/ -NK_API void nk_free(struct nk_context*); -#ifdef NK_INCLUDE_COMMAND_USERDATA -/*/// #### nk_set_user_data -/// Sets the currently passed userdata passed down into each draw command. -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_set_user_data(struct nk_context *ctx, nk_handle data); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|-------------------------------------------------------------- -/// __ctx__ | Must point to a previously initialized `nk_context` struct -/// __data__ | Handle with either pointer or index to be passed into every draw commands -*/ -NK_API void nk_set_user_data(struct nk_context*, nk_handle handle); -#endif -/* ============================================================================= - * - * INPUT - * - * =============================================================================*/ -/*/// ### Input -/// The input API is responsible for holding the current input state composed of -/// mouse, key and text input states. -/// It is worth noting that no direct OS or window handling is done in nuklear. -/// Instead all input state has to be provided by platform specific code. This on one hand -/// expects more work from the user and complicates usage but on the other hand -/// provides simple abstraction over a big number of platforms, libraries and other -/// already provided functionality. -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// nk_input_begin(&ctx); -/// while (GetEvent(&evt)) { -/// if (evt.type == MOUSE_MOVE) -/// nk_input_motion(&ctx, evt.motion.x, evt.motion.y); -/// else if (evt.type == [...]) { -/// // [...] -/// } -/// } nk_input_end(&ctx); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// #### Usage -/// Input state needs to be provided to nuklear by first calling `nk_input_begin` -/// which resets internal state like delta mouse position and button transistions. -/// After `nk_input_begin` all current input state needs to be provided. This includes -/// mouse motion, button and key pressed and released, text input and scrolling. -/// Both event- or state-based input handling are supported by this API -/// and should work without problems. Finally after all input state has been -/// mirrored `nk_input_end` needs to be called to finish input process. -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// struct nk_context ctx; -/// nk_init_xxx(&ctx, ...); -/// while (1) { -/// Event evt; -/// nk_input_begin(&ctx); -/// while (GetEvent(&evt)) { -/// if (evt.type == MOUSE_MOVE) -/// nk_input_motion(&ctx, evt.motion.x, evt.motion.y); -/// else if (evt.type == [...]) { -/// // [...] -/// } -/// } -/// nk_input_end(&ctx); -/// // [...] -/// nk_clear(&ctx); -/// } nk_free(&ctx); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// #### Reference -/// Function | Description -/// --------------------|------------------------------------------------------- -/// __nk_input_begin__ | Begins the input mirroring process. Needs to be called before all other `nk_input_xxx` calls -/// __nk_input_motion__ | Mirrors mouse cursor position -/// __nk_input_key__ | Mirrors key state with either pressed or released -/// __nk_input_button__ | Mirrors mouse button state with either pressed or released -/// __nk_input_scroll__ | Mirrors mouse scroll values -/// __nk_input_char__ | Adds a single ASCII text character into an internal text buffer -/// __nk_input_glyph__ | Adds a single multi-byte UTF-8 character into an internal text buffer -/// __nk_input_unicode__| Adds a single unicode rune into an internal text buffer -/// __nk_input_end__ | Ends the input mirroring process by calculating state changes. Don't call any `nk_input_xxx` function referenced above after this call -*/ -enum nk_keys { - NK_KEY_NONE, - NK_KEY_SHIFT, - NK_KEY_CTRL, - NK_KEY_DEL, - NK_KEY_ENTER, - NK_KEY_TAB, - NK_KEY_BACKSPACE, - NK_KEY_COPY, - NK_KEY_CUT, - NK_KEY_PASTE, - NK_KEY_UP, - NK_KEY_DOWN, - NK_KEY_LEFT, - NK_KEY_RIGHT, - /* Shortcuts: text field */ - NK_KEY_TEXT_INSERT_MODE, - NK_KEY_TEXT_REPLACE_MODE, - NK_KEY_TEXT_RESET_MODE, - NK_KEY_TEXT_LINE_START, - NK_KEY_TEXT_LINE_END, - NK_KEY_TEXT_START, - NK_KEY_TEXT_END, - NK_KEY_TEXT_UNDO, - NK_KEY_TEXT_REDO, - NK_KEY_TEXT_SELECT_ALL, - NK_KEY_TEXT_WORD_LEFT, - NK_KEY_TEXT_WORD_RIGHT, - /* Shortcuts: scrollbar */ - NK_KEY_SCROLL_START, - NK_KEY_SCROLL_END, - NK_KEY_SCROLL_DOWN, - NK_KEY_SCROLL_UP, - NK_KEY_MAX -}; -enum nk_buttons { - NK_BUTTON_LEFT, - NK_BUTTON_MIDDLE, - NK_BUTTON_RIGHT, - NK_BUTTON_DOUBLE, - NK_BUTTON_MAX -}; -/*/// #### nk_input_begin -/// Begins the input mirroring process by resetting text, scroll -/// mouse, previous mouse position and movement as well as key state transitions, -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_input_begin(struct nk_context*); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to a previously initialized `nk_context` struct -*/ -NK_API void nk_input_begin(struct nk_context*); -/*/// #### nk_input_motion -/// Mirrors current mouse position to nuklear -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_input_motion(struct nk_context *ctx, int x, int y); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to a previously initialized `nk_context` struct -/// __x__ | Must hold an integer describing the current mouse cursor x-position -/// __y__ | Must hold an integer describing the current mouse cursor y-position -*/ -NK_API void nk_input_motion(struct nk_context*, int x, int y); -/*/// #### nk_input_key -/// Mirrors the state of a specific key to nuklear -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_input_key(struct nk_context*, enum nk_keys key, int down); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to a previously initialized `nk_context` struct -/// __key__ | Must be any value specified in enum `nk_keys` that needs to be mirrored -/// __down__ | Must be 0 for key is up and 1 for key is down -*/ -NK_API void nk_input_key(struct nk_context*, enum nk_keys, int down); -/*/// #### nk_input_button -/// Mirrors the state of a specific mouse button to nuklear -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_input_button(struct nk_context *ctx, enum nk_buttons btn, int x, int y, int down); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to a previously initialized `nk_context` struct -/// __btn__ | Must be any value specified in enum `nk_buttons` that needs to be mirrored -/// __x__ | Must contain an integer describing mouse cursor x-position on click up/down -/// __y__ | Must contain an integer describing mouse cursor y-position on click up/down -/// __down__ | Must be 0 for key is up and 1 for key is down -*/ -NK_API void nk_input_button(struct nk_context*, enum nk_buttons, int x, int y, int down); -/*/// #### nk_input_scroll -/// Copies the last mouse scroll value to nuklear. Is generally -/// a scroll value. So does not have to come from mouse and could also originate -/// TODO finish this sentence -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_input_scroll(struct nk_context *ctx, struct nk_vec2 val); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to a previously initialized `nk_context` struct -/// __val__ | vector with both X- as well as Y-scroll value -*/ -NK_API void nk_input_scroll(struct nk_context*, struct nk_vec2 val); -/*/// #### nk_input_char -/// Copies a single ASCII character into an internal text buffer -/// This is basically a helper function to quickly push ASCII characters into -/// nuklear. -/// -/// !!! Note -/// Stores up to NK_INPUT_MAX bytes between `nk_input_begin` and `nk_input_end`. -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_input_char(struct nk_context *ctx, char c); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to a previously initialized `nk_context` struct -/// __c__ | Must be a single ASCII character preferable one that can be printed -*/ -NK_API void nk_input_char(struct nk_context*, char); -/*/// #### nk_input_glyph -/// Converts an encoded unicode rune into UTF-8 and copies the result into an -/// internal text buffer. -/// -/// !!! Note -/// Stores up to NK_INPUT_MAX bytes between `nk_input_begin` and `nk_input_end`. -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_input_glyph(struct nk_context *ctx, const nk_glyph g); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to a previously initialized `nk_context` struct -/// __g__ | UTF-32 unicode codepoint -*/ -NK_API void nk_input_glyph(struct nk_context*, const nk_glyph); -/*/// #### nk_input_unicode -/// Converts a unicode rune into UTF-8 and copies the result -/// into an internal text buffer. -/// !!! Note -/// Stores up to NK_INPUT_MAX bytes between `nk_input_begin` and `nk_input_end`. -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_input_unicode(struct nk_context*, nk_rune rune); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to a previously initialized `nk_context` struct -/// __rune__ | UTF-32 unicode codepoint -*/ -NK_API void nk_input_unicode(struct nk_context*, nk_rune); -/*/// #### nk_input_end -/// End the input mirroring process by resetting mouse grabbing -/// state to ensure the mouse cursor is not grabbed indefinitely. -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_input_end(struct nk_context *ctx); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to a previously initialized `nk_context` struct -*/ -NK_API void nk_input_end(struct nk_context*); -/* ============================================================================= - * - * DRAWING - * - * =============================================================================*/ -/*/// ### Drawing -/// This library was designed to be render backend agnostic so it does -/// not draw anything to screen directly. Instead all drawn shapes, widgets -/// are made of, are buffered into memory and make up a command queue. -/// Each frame therefore fills the command buffer with draw commands -/// that then need to be executed by the user and his own render backend. -/// After that the command buffer needs to be cleared and a new frame can be -/// started. It is probably important to note that the command buffer is the main -/// drawing API and the optional vertex buffer API only takes this format and -/// converts it into a hardware accessible format. -/// -/// #### Usage -/// To draw all draw commands accumulated over a frame you need your own render -/// backend able to draw a number of 2D primitives. This includes at least -/// filled and stroked rectangles, circles, text, lines, triangles and scissors. -/// As soon as this criterion is met you can iterate over each draw command -/// and execute each draw command in a interpreter like fashion: -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// const struct nk_command *cmd = 0; -/// nk_foreach(cmd, &ctx) { -/// switch (cmd->type) { -/// case NK_COMMAND_LINE: -/// your_draw_line_function(...) -/// break; -/// case NK_COMMAND_RECT -/// your_draw_rect_function(...) -/// break; -/// case //...: -/// //[...] -/// } -/// } -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// In program flow context draw commands need to be executed after input has been -/// gathered and the complete UI with windows and their contained widgets have -/// been executed and before calling `nk_clear` which frees all previously -/// allocated draw commands. -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// struct nk_context ctx; -/// nk_init_xxx(&ctx, ...); -/// while (1) { -/// Event evt; -/// nk_input_begin(&ctx); -/// while (GetEvent(&evt)) { -/// if (evt.type == MOUSE_MOVE) -/// nk_input_motion(&ctx, evt.motion.x, evt.motion.y); -/// else if (evt.type == [...]) { -/// [...] -/// } -/// } -/// nk_input_end(&ctx); -/// // -/// // [...] -/// // -/// const struct nk_command *cmd = 0; -/// nk_foreach(cmd, &ctx) { -/// switch (cmd->type) { -/// case NK_COMMAND_LINE: -/// your_draw_line_function(...) -/// break; -/// case NK_COMMAND_RECT -/// your_draw_rect_function(...) -/// break; -/// case ...: -/// // [...] -/// } -/// nk_clear(&ctx); -/// } -/// nk_free(&ctx); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// You probably noticed that you have to draw all of the UI each frame which is -/// quite wasteful. While the actual UI updating loop is quite fast rendering -/// without actually needing it is not. So there are multiple things you could do. -/// -/// First is only update on input. This of course is only an option if your -/// application only depends on the UI and does not require any outside calculations. -/// If you actually only update on input make sure to update the UI two times each -/// frame and call `nk_clear` directly after the first pass and only draw in -/// the second pass. In addition it is recommended to also add additional timers -/// to make sure the UI is not drawn more than a fixed number of frames per second. -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// struct nk_context ctx; -/// nk_init_xxx(&ctx, ...); -/// while (1) { -/// // [...wait for input ] -/// // [...do two UI passes ...] -/// do_ui(...) -/// nk_clear(&ctx); -/// do_ui(...) -/// // -/// // draw -/// const struct nk_command *cmd = 0; -/// nk_foreach(cmd, &ctx) { -/// switch (cmd->type) { -/// case NK_COMMAND_LINE: -/// your_draw_line_function(...) -/// break; -/// case NK_COMMAND_RECT -/// your_draw_rect_function(...) -/// break; -/// case ...: -/// //[...] -/// } -/// nk_clear(&ctx); -/// } -/// nk_free(&ctx); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// The second probably more applicable trick is to only draw if anything changed. -/// It is not really useful for applications with continuous draw loop but -/// quite useful for desktop applications. To actually get nuklear to only -/// draw on changes you first have to define `NK_ZERO_COMMAND_MEMORY` and -/// allocate a memory buffer that will store each unique drawing output. -/// After each frame you compare the draw command memory inside the library -/// with your allocated buffer by memcmp. If memcmp detects differences -/// you have to copy the command buffer into the allocated buffer -/// and then draw like usual (this example uses fixed memory but you could -/// use dynamically allocated memory). -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// //[... other defines ...] -/// #define NK_ZERO_COMMAND_MEMORY -/// #include "nuklear.h" -/// // -/// // setup context -/// struct nk_context ctx; -/// void *last = calloc(1,64*1024); -/// void *buf = calloc(1,64*1024); -/// nk_init_fixed(&ctx, buf, 64*1024); -/// // -/// // loop -/// while (1) { -/// // [...input...] -/// // [...ui...] -/// void *cmds = nk_buffer_memory(&ctx.memory); -/// if (memcmp(cmds, last, ctx.memory.allocated)) { -/// memcpy(last,cmds,ctx.memory.allocated); -/// const struct nk_command *cmd = 0; -/// nk_foreach(cmd, &ctx) { -/// switch (cmd->type) { -/// case NK_COMMAND_LINE: -/// your_draw_line_function(...) -/// break; -/// case NK_COMMAND_RECT -/// your_draw_rect_function(...) -/// break; -/// case ...: -/// // [...] -/// } -/// } -/// } -/// nk_clear(&ctx); -/// } -/// nk_free(&ctx); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Finally while using draw commands makes sense for higher abstracted platforms like -/// X11 and Win32 or drawing libraries it is often desirable to use graphics -/// hardware directly. Therefore it is possible to just define -/// `NK_INCLUDE_VERTEX_BUFFER_OUTPUT` which includes optional vertex output. -/// To access the vertex output you first have to convert all draw commands into -/// vertexes by calling `nk_convert` which takes in your preferred vertex format. -/// After successfully converting all draw commands just iterate over and execute all -/// vertex draw commands: -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// // fill configuration -/// struct nk_convert_config cfg = {}; -/// static const struct nk_draw_vertex_layout_element vertex_layout[] = { -/// {NK_VERTEX_POSITION, NK_FORMAT_FLOAT, NK_OFFSETOF(struct your_vertex, pos)}, -/// {NK_VERTEX_TEXCOORD, NK_FORMAT_FLOAT, NK_OFFSETOF(struct your_vertex, uv)}, -/// {NK_VERTEX_COLOR, NK_FORMAT_R8G8B8A8, NK_OFFSETOF(struct your_vertex, col)}, -/// {NK_VERTEX_LAYOUT_END} -/// }; -/// cfg.shape_AA = NK_ANTI_ALIASING_ON; -/// cfg.line_AA = NK_ANTI_ALIASING_ON; -/// cfg.vertex_layout = vertex_layout; -/// cfg.vertex_size = sizeof(struct your_vertex); -/// cfg.vertex_alignment = NK_ALIGNOF(struct your_vertex); -/// cfg.circle_segment_count = 22; -/// cfg.curve_segment_count = 22; -/// cfg.arc_segment_count = 22; -/// cfg.global_alpha = 1.0f; -/// cfg.null = dev->null; -/// // -/// // setup buffers and convert -/// struct nk_buffer cmds, verts, idx; -/// nk_buffer_init_default(&cmds); -/// nk_buffer_init_default(&verts); -/// nk_buffer_init_default(&idx); -/// nk_convert(&ctx, &cmds, &verts, &idx, &cfg); -/// // -/// // draw -/// nk_draw_foreach(cmd, &ctx, &cmds) { -/// if (!cmd->elem_count) continue; -/// //[...] -/// } -/// nk_buffer_free(&cms); -/// nk_buffer_free(&verts); -/// nk_buffer_free(&idx); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// #### Reference -/// Function | Description -/// --------------------|------------------------------------------------------- -/// __nk__begin__ | Returns the first draw command in the context draw command list to be drawn -/// __nk__next__ | Increments the draw command iterator to the next command inside the context draw command list -/// __nk_foreach__ | Iterates over each draw command inside the context draw command list -/// __nk_convert__ | Converts from the abstract draw commands list into a hardware accessible vertex format -/// __nk_draw_begin__ | Returns the first vertex command in the context vertex draw list to be executed -/// __nk__draw_next__ | Increments the vertex command iterator to the next command inside the context vertex command list -/// __nk__draw_end__ | Returns the end of the vertex draw list -/// __nk_draw_foreach__ | Iterates over each vertex draw command inside the vertex draw list -*/ -enum nk_anti_aliasing {NK_ANTI_ALIASING_OFF, NK_ANTI_ALIASING_ON}; -enum nk_convert_result { - NK_CONVERT_SUCCESS = 0, - NK_CONVERT_INVALID_PARAM = 1, - NK_CONVERT_COMMAND_BUFFER_FULL = NK_FLAG(1), - NK_CONVERT_VERTEX_BUFFER_FULL = NK_FLAG(2), - NK_CONVERT_ELEMENT_BUFFER_FULL = NK_FLAG(3) -}; -struct nk_draw_null_texture { - nk_handle texture; /* texture handle to a texture with a white pixel */ - struct nk_vec2 uv; /* coordinates to a white pixel in the texture */ -}; -struct nk_convert_config { - float global_alpha; /* global alpha value */ - enum nk_anti_aliasing line_AA; /* line anti-aliasing flag can be turned off if you are tight on memory */ - enum nk_anti_aliasing shape_AA; /* shape anti-aliasing flag can be turned off if you are tight on memory */ - unsigned circle_segment_count; /* number of segments used for circles: default to 22 */ - unsigned arc_segment_count; /* number of segments used for arcs: default to 22 */ - unsigned curve_segment_count; /* number of segments used for curves: default to 22 */ - struct nk_draw_null_texture null; /* handle to texture with a white pixel for shape drawing */ - const struct nk_draw_vertex_layout_element *vertex_layout; /* describes the vertex output format and packing */ - nk_size vertex_size; /* sizeof one vertex for vertex packing */ - nk_size vertex_alignment; /* vertex alignment: Can be obtained by NK_ALIGNOF */ -}; -/*/// #### nk__begin -/// Returns a draw command list iterator to iterate all draw -/// commands accumulated over one frame. -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// const struct nk_command* nk__begin(struct nk_context*); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | must point to an previously initialized `nk_context` struct at the end of a frame -/// -/// Returns draw command pointer pointing to the first command inside the draw command list -*/ -NK_API const struct nk_command* nk__begin(struct nk_context*); -/*/// #### nk__next -/// Returns draw command pointer pointing to the next command inside the draw command list -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// const struct nk_command* nk__next(struct nk_context*, const struct nk_command*); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct at the end of a frame -/// __cmd__ | Must point to an previously a draw command either returned by `nk__begin` or `nk__next` -/// -/// Returns draw command pointer pointing to the next command inside the draw command list -*/ -NK_API const struct nk_command* nk__next(struct nk_context*, const struct nk_command*); -/*/// #### nk_foreach -/// Iterates over each draw command inside the context draw command list -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// #define nk_foreach(c, ctx) -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct at the end of a frame -/// __cmd__ | Command pointer initialized to NULL -/// -/// Iterates over each draw command inside the context draw command list -*/ -#define nk_foreach(c, ctx) for((c) = nk__begin(ctx); (c) != 0; (c) = nk__next(ctx,c)) -#ifdef NK_INCLUDE_VERTEX_BUFFER_OUTPUT -/*/// #### nk_convert -/// Converts all internal draw commands into vertex draw commands and fills -/// three buffers with vertexes, vertex draw commands and vertex indices. The vertex format -/// as well as some other configuration values have to be configured by filling out a -/// `nk_convert_config` struct. -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// nk_flags nk_convert(struct nk_context *ctx, struct nk_buffer *cmds, -// struct nk_buffer *vertices, struct nk_buffer *elements, const struct nk_convert_config*); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct at the end of a frame -/// __cmds__ | Must point to a previously initialized buffer to hold converted vertex draw commands -/// __vertices__| Must point to a previously initialized buffer to hold all produced vertices -/// __elements__| Must point to a previously initialized buffer to hold all produced vertex indices -/// __config__ | Must point to a filled out `nk_config` struct to configure the conversion process -/// -/// Returns one of enum nk_convert_result error codes -/// -/// Parameter | Description -/// --------------------------------|----------------------------------------------------------- -/// NK_CONVERT_SUCCESS | Signals a successful draw command to vertex buffer conversion -/// NK_CONVERT_INVALID_PARAM | An invalid argument was passed in the function call -/// NK_CONVERT_COMMAND_BUFFER_FULL | The provided buffer for storing draw commands is full or failed to allocate more memory -/// NK_CONVERT_VERTEX_BUFFER_FULL | The provided buffer for storing vertices is full or failed to allocate more memory -/// NK_CONVERT_ELEMENT_BUFFER_FULL | The provided buffer for storing indicies is full or failed to allocate more memory -*/ -NK_API nk_flags nk_convert(struct nk_context*, struct nk_buffer *cmds, struct nk_buffer *vertices, struct nk_buffer *elements, const struct nk_convert_config*); -/*/// #### nk__draw_begin -/// Returns a draw vertex command buffer iterator to iterate over the vertex draw command buffer -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// const struct nk_draw_command* nk__draw_begin(const struct nk_context*, const struct nk_buffer*); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct at the end of a frame -/// __buf__ | Must point to an previously by `nk_convert` filled out vertex draw command buffer -/// -/// Returns vertex draw command pointer pointing to the first command inside the vertex draw command buffer -*/ -NK_API const struct nk_draw_command* nk__draw_begin(const struct nk_context*, const struct nk_buffer*); -/*/// #### nk__draw_end -/// Returns the vertex draw command at the end of the vertex draw command buffer -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// const struct nk_draw_command* nk__draw_end(const struct nk_context *ctx, const struct nk_buffer *buf); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct at the end of a frame -/// __buf__ | Must point to an previously by `nk_convert` filled out vertex draw command buffer -/// -/// Returns vertex draw command pointer pointing to the end of the last vertex draw command inside the vertex draw command buffer -*/ -NK_API const struct nk_draw_command* nk__draw_end(const struct nk_context*, const struct nk_buffer*); -/*/// #### nk__draw_next -/// Increments the vertex draw command buffer iterator -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// const struct nk_draw_command* nk__draw_next(const struct nk_draw_command*, const struct nk_buffer*, const struct nk_context*); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __cmd__ | Must point to an previously either by `nk__draw_begin` or `nk__draw_next` returned vertex draw command -/// __buf__ | Must point to an previously by `nk_convert` filled out vertex draw command buffer -/// __ctx__ | Must point to an previously initialized `nk_context` struct at the end of a frame -/// -/// Returns vertex draw command pointer pointing to the end of the last vertex draw command inside the vertex draw command buffer -*/ -NK_API const struct nk_draw_command* nk__draw_next(const struct nk_draw_command*, const struct nk_buffer*, const struct nk_context*); -/*/// #### nk_draw_foreach -/// Iterates over each vertex draw command inside a vertex draw command buffer -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// #define nk_draw_foreach(cmd,ctx, b) -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __cmd__ | `nk_draw_command`iterator set to NULL -/// __buf__ | Must point to an previously by `nk_convert` filled out vertex draw command buffer -/// __ctx__ | Must point to an previously initialized `nk_context` struct at the end of a frame -*/ -#define nk_draw_foreach(cmd,ctx, b) for((cmd)=nk__draw_begin(ctx, b); (cmd)!=0; (cmd)=nk__draw_next(cmd, b, ctx)) -#endif -/* ============================================================================= - * - * WINDOW - * - * ============================================================================= -/// ### Window -/// Windows are the main persistent state used inside nuklear and are life time -/// controlled by simply "retouching" (i.e. calling) each window each frame. -/// All widgets inside nuklear can only be added inside the function pair `nk_begin_xxx` -/// and `nk_end`. Calling any widgets outside these two functions will result in an -/// assert in debug or no state change in release mode.

-/// -/// Each window holds frame persistent state like position, size, flags, state tables, -/// and some garbage collected internal persistent widget state. Each window -/// is linked into a window stack list which determines the drawing and overlapping -/// order. The topmost window thereby is the currently active window.

-/// -/// To change window position inside the stack occurs either automatically by -/// user input by being clicked on or programmatically by calling `nk_window_focus`. -/// Windows by default are visible unless explicitly being defined with flag -/// `NK_WINDOW_HIDDEN`, the user clicked the close button on windows with flag -/// `NK_WINDOW_CLOSABLE` or if a window was explicitly hidden by calling -/// `nk_window_show`. To explicitly close and destroy a window call `nk_window_close`.

-/// -/// #### Usage -/// To create and keep a window you have to call one of the two `nk_begin_xxx` -/// functions to start window declarations and `nk_end` at the end. Furthermore it -/// is recommended to check the return value of `nk_begin_xxx` and only process -/// widgets inside the window if the value is not 0. Either way you have to call -/// `nk_end` at the end of window declarations. Furthermore, do not attempt to -/// nest `nk_begin_xxx` calls which will hopefully result in an assert or if not -/// in a segmentation fault. -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// if (nk_begin_xxx(...) { -/// // [... widgets ...] -/// } -/// nk_end(ctx); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// In the grand concept window and widget declarations need to occur after input -/// handling and before drawing to screen. Not doing so can result in higher -/// latency or at worst invalid behavior. Furthermore make sure that `nk_clear` -/// is called at the end of the frame. While nuklear's default platform backends -/// already call `nk_clear` for you if you write your own backend not calling -/// `nk_clear` can cause asserts or even worse undefined behavior. -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// struct nk_context ctx; -/// nk_init_xxx(&ctx, ...); -/// while (1) { -/// Event evt; -/// nk_input_begin(&ctx); -/// while (GetEvent(&evt)) { -/// if (evt.type == MOUSE_MOVE) -/// nk_input_motion(&ctx, evt.motion.x, evt.motion.y); -/// else if (evt.type == [...]) { -/// nk_input_xxx(...); -/// } -/// } -/// nk_input_end(&ctx); -/// -/// if (nk_begin_xxx(...) { -/// //[...] -/// } -/// nk_end(ctx); -/// -/// const struct nk_command *cmd = 0; -/// nk_foreach(cmd, &ctx) { -/// case NK_COMMAND_LINE: -/// your_draw_line_function(...) -/// break; -/// case NK_COMMAND_RECT -/// your_draw_rect_function(...) -/// break; -/// case //...: -/// //[...] -/// } -/// nk_clear(&ctx); -/// } -/// nk_free(&ctx); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// #### Reference -/// Function | Description -/// ------------------------------------|---------------------------------------- -/// nk_begin | Starts a new window; needs to be called every frame for every window (unless hidden) or otherwise the window gets removed -/// nk_begin_titled | Extended window start with separated title and identifier to allow multiple windows with same name but not title -/// nk_end | Needs to be called at the end of the window building process to process scaling, scrollbars and general cleanup -// -/// nk_window_find | Finds and returns the window with give name -/// nk_window_get_bounds | Returns a rectangle with screen position and size of the currently processed window. -/// nk_window_get_position | Returns the position of the currently processed window -/// nk_window_get_size | Returns the size with width and height of the currently processed window -/// nk_window_get_width | Returns the width of the currently processed window -/// nk_window_get_height | Returns the height of the currently processed window -/// nk_window_get_panel | Returns the underlying panel which contains all processing state of the current window -/// nk_window_get_content_region | Returns the position and size of the currently visible and non-clipped space inside the currently processed window -/// nk_window_get_content_region_min | Returns the upper rectangle position of the currently visible and non-clipped space inside the currently processed window -/// nk_window_get_content_region_max | Returns the upper rectangle position of the currently visible and non-clipped space inside the currently processed window -/// nk_window_get_content_region_size | Returns the size of the currently visible and non-clipped space inside the currently processed window -/// nk_window_get_canvas | Returns the draw command buffer. Can be used to draw custom widgets -/// nk_window_has_focus | Returns if the currently processed window is currently active -/// nk_window_is_collapsed | Returns if the window with given name is currently minimized/collapsed -/// nk_window_is_closed | Returns if the currently processed window was closed -/// nk_window_is_hidden | Returns if the currently processed window was hidden -/// nk_window_is_active | Same as nk_window_has_focus for some reason -/// nk_window_is_hovered | Returns if the currently processed window is currently being hovered by mouse -/// nk_window_is_any_hovered | Return if any window currently hovered -/// nk_item_is_any_active | Returns if any window or widgets is currently hovered or active -// -/// nk_window_set_bounds | Updates position and size of the currently processed window -/// nk_window_set_position | Updates position of the currently process window -/// nk_window_set_size | Updates the size of the currently processed window -/// nk_window_set_focus | Set the currently processed window as active window -// -/// nk_window_close | Closes the window with given window name which deletes the window at the end of the frame -/// nk_window_collapse | Collapses the window with given window name -/// nk_window_collapse_if | Collapses the window with given window name if the given condition was met -/// nk_window_show | Hides a visible or reshows a hidden window -/// nk_window_show_if | Hides/shows a window depending on condition -*/ -/* -/// #### nk_panel_flags -/// Flag | Description -/// ----------------------------|---------------------------------------- -/// NK_WINDOW_BORDER | Draws a border around the window to visually separate window from the background -/// NK_WINDOW_MOVABLE | The movable flag indicates that a window can be moved by user input or by dragging the window header -/// NK_WINDOW_SCALABLE | The scalable flag indicates that a window can be scaled by user input by dragging a scaler icon at the button of the window -/// NK_WINDOW_CLOSABLE | Adds a closable icon into the header -/// NK_WINDOW_MINIMIZABLE | Adds a minimize icon into the header -/// NK_WINDOW_NO_SCROLLBAR | Removes the scrollbar from the window -/// NK_WINDOW_TITLE | Forces a header at the top at the window showing the title -/// NK_WINDOW_SCROLL_AUTO_HIDE | Automatically hides the window scrollbar if no user interaction: also requires delta time in `nk_context` to be set each frame -/// NK_WINDOW_BACKGROUND | Always keep window in the background -/// NK_WINDOW_SCALE_LEFT | Puts window scaler in the left-ottom corner instead right-bottom -/// NK_WINDOW_NO_INPUT | Prevents window of scaling, moving or getting focus -/// -/// #### nk_collapse_states -/// State | Description -/// ----------------|----------------------------------------------------------- -/// __NK_MINIMIZED__| UI section is collased and not visibile until maximized -/// __NK_MAXIMIZED__| UI section is extended and visibile until minimized -///

-*/ -enum nk_panel_flags { - NK_WINDOW_BORDER = NK_FLAG(0), - NK_WINDOW_MOVABLE = NK_FLAG(1), - NK_WINDOW_SCALABLE = NK_FLAG(2), - NK_WINDOW_CLOSABLE = NK_FLAG(3), - NK_WINDOW_MINIMIZABLE = NK_FLAG(4), - NK_WINDOW_NO_SCROLLBAR = NK_FLAG(5), - NK_WINDOW_TITLE = NK_FLAG(6), - NK_WINDOW_SCROLL_AUTO_HIDE = NK_FLAG(7), - NK_WINDOW_BACKGROUND = NK_FLAG(8), - NK_WINDOW_SCALE_LEFT = NK_FLAG(9), - NK_WINDOW_NO_INPUT = NK_FLAG(10) -}; -/*/// #### nk_begin -/// Starts a new window; needs to be called every frame for every -/// window (unless hidden) or otherwise the window gets removed -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// int nk_begin(struct nk_context *ctx, const char *title, struct nk_rect bounds, nk_flags flags); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// __title__ | Window title and identifier. Needs to be persistent over frames to identify the window -/// __bounds__ | Initial position and window size. However if you do not define `NK_WINDOW_SCALABLE` or `NK_WINDOW_MOVABLE` you can set window position and size every frame -/// __flags__ | Window flags defined in the nk_panel_flags section with a number of different window behaviors -/// -/// Returns `true(1)` if the window can be filled up with widgets from this point -/// until `nk_end` or `false(0)` otherwise for example if minimized -*/ -NK_API int nk_begin(struct nk_context *ctx, const char *title, struct nk_rect bounds, nk_flags flags); -/*/// #### nk_begin_titled -/// Extended window start with separated title and identifier to allow multiple -/// windows with same title but not name -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// int nk_begin_titled(struct nk_context *ctx, const char *name, const char *title, struct nk_rect bounds, nk_flags flags); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// __name__ | Window identifier. Needs to be persistent over frames to identify the window -/// __title__ | Window title displayed inside header if flag `NK_WINDOW_TITLE` or either `NK_WINDOW_CLOSABLE` or `NK_WINDOW_MINIMIZED` was set -/// __bounds__ | Initial position and window size. However if you do not define `NK_WINDOW_SCALABLE` or `NK_WINDOW_MOVABLE` you can set window position and size every frame -/// __flags__ | Window flags defined in the nk_panel_flags section with a number of different window behaviors -/// -/// Returns `true(1)` if the window can be filled up with widgets from this point -/// until `nk_end` or `false(0)` otherwise for example if minimized -*/ -NK_API int nk_begin_titled(struct nk_context *ctx, const char *name, const char *title, struct nk_rect bounds, nk_flags flags); -/*/// #### nk_end -/// Needs to be called at the end of the window building process to process scaling, scrollbars and general cleanup. -/// All widget calls after this functions will result in asserts or no state changes -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_end(struct nk_context *ctx); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -*/ -NK_API void nk_end(struct nk_context *ctx); -/*/// #### nk_window_find -/// Finds and returns a window from passed name -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_end(struct nk_context *ctx); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// __name__ | Window identifier -/// -/// Returns a `nk_window` struct pointing to the identified window or NULL if -/// no window with the given name was found -*/ -NK_API struct nk_window *nk_window_find(struct nk_context *ctx, const char *name); -/*/// #### nk_window_get_bounds -/// Returns a rectangle with screen position and size of the currently processed window -/// -/// !!! WARNING -/// Only call this function between calls `nk_begin_xxx` and `nk_end` -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// struct nk_rect nk_window_get_bounds(const struct nk_context *ctx); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// -/// Returns a `nk_rect` struct with window upper left window position and size -*/ -NK_API struct nk_rect nk_window_get_bounds(const struct nk_context *ctx); -/*/// #### nk_window_get_position -/// Returns the position of the currently processed window. -/// -/// !!! WARNING -/// Only call this function between calls `nk_begin_xxx` and `nk_end` -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// struct nk_vec2 nk_window_get_position(const struct nk_context *ctx); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// -/// Returns a `nk_vec2` struct with window upper left position -*/ -NK_API struct nk_vec2 nk_window_get_position(const struct nk_context *ctx); -/*/// #### nk_window_get_size -/// Returns the size with width and height of the currently processed window. -/// -/// !!! WARNING -/// Only call this function between calls `nk_begin_xxx` and `nk_end` -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// struct nk_vec2 nk_window_get_size(const struct nk_context *ctx); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// -/// Returns a `nk_vec2` struct with window width and height -*/ -NK_API struct nk_vec2 nk_window_get_size(const struct nk_context*); -/*/// #### nk_window_get_width -/// Returns the width of the currently processed window. -/// -/// !!! WARNING -/// Only call this function between calls `nk_begin_xxx` and `nk_end` -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// float nk_window_get_width(const struct nk_context *ctx); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// -/// Returns the current window width -*/ -NK_API float nk_window_get_width(const struct nk_context*); -/*/// #### nk_window_get_height -/// Returns the height of the currently processed window. -/// -/// !!! WARNING -/// Only call this function between calls `nk_begin_xxx` and `nk_end` -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// float nk_window_get_height(const struct nk_context *ctx); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// -/// Returns the current window height -*/ -NK_API float nk_window_get_height(const struct nk_context*); -/*/// #### nk_window_get_panel -/// Returns the underlying panel which contains all processing state of the current window. -/// -/// !!! WARNING -/// Only call this function between calls `nk_begin_xxx` and `nk_end` -/// !!! WARNING -/// Do not keep the returned panel pointer around, it is only valid until `nk_end` -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// struct nk_panel* nk_window_get_panel(struct nk_context *ctx); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// -/// Returns a pointer to window internal `nk_panel` state. -*/ -NK_API struct nk_panel* nk_window_get_panel(struct nk_context*); -/*/// #### nk_window_get_content_region -/// Returns the position and size of the currently visible and non-clipped space -/// inside the currently processed window. -/// -/// !!! WARNING -/// Only call this function between calls `nk_begin_xxx` and `nk_end` -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// struct nk_rect nk_window_get_content_region(struct nk_context *ctx); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// -/// Returns `nk_rect` struct with screen position and size (no scrollbar offset) -/// of the visible space inside the current window -*/ -NK_API struct nk_rect nk_window_get_content_region(struct nk_context*); -/*/// #### nk_window_get_content_region_min -/// Returns the upper left position of the currently visible and non-clipped -/// space inside the currently processed window. -/// -/// !!! WARNING -/// Only call this function between calls `nk_begin_xxx` and `nk_end` -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// struct nk_vec2 nk_window_get_content_region_min(struct nk_context *ctx); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// -/// returns `nk_vec2` struct with upper left screen position (no scrollbar offset) -/// of the visible space inside the current window -*/ -NK_API struct nk_vec2 nk_window_get_content_region_min(struct nk_context*); -/*/// #### nk_window_get_content_region_max -/// Returns the lower right screen position of the currently visible and -/// non-clipped space inside the currently processed window. -/// -/// !!! WARNING -/// Only call this function between calls `nk_begin_xxx` and `nk_end` -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// struct nk_vec2 nk_window_get_content_region_max(struct nk_context *ctx); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// -/// Returns `nk_vec2` struct with lower right screen position (no scrollbar offset) -/// of the visible space inside the current window -*/ -NK_API struct nk_vec2 nk_window_get_content_region_max(struct nk_context*); -/*/// #### nk_window_get_content_region_size -/// Returns the size of the currently visible and non-clipped space inside the -/// currently processed window -/// -/// !!! WARNING -/// Only call this function between calls `nk_begin_xxx` and `nk_end` -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// struct nk_vec2 nk_window_get_content_region_size(struct nk_context *ctx); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// -/// Returns `nk_vec2` struct with size the visible space inside the current window -*/ -NK_API struct nk_vec2 nk_window_get_content_region_size(struct nk_context*); -/*/// #### nk_window_get_canvas -/// Returns the draw command buffer. Can be used to draw custom widgets -/// !!! WARNING -/// Only call this function between calls `nk_begin_xxx` and `nk_end` -/// !!! WARNING -/// Do not keep the returned command buffer pointer around it is only valid until `nk_end` -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// struct nk_command_buffer* nk_window_get_canvas(struct nk_context *ctx); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// -/// Returns a pointer to window internal `nk_command_buffer` struct used as -/// drawing canvas. Can be used to do custom drawing. -*/ -NK_API struct nk_command_buffer* nk_window_get_canvas(struct nk_context*); -/*/// #### nk_window_has_focus -/// Returns if the currently processed window is currently active -/// !!! WARNING -/// Only call this function between calls `nk_begin_xxx` and `nk_end` -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// int nk_window_has_focus(const struct nk_context *ctx); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// -/// Returns `false(0)` if current window is not active or `true(1)` if it is -*/ -NK_API int nk_window_has_focus(const struct nk_context*); -/*/// #### nk_window_is_hovered -/// Return if the current window is being hovered -/// !!! WARNING -/// Only call this function between calls `nk_begin_xxx` and `nk_end` -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// int nk_window_is_hovered(struct nk_context *ctx); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// -/// Returns `true(1)` if current window is hovered or `false(0)` otherwise -*/ -NK_API int nk_window_is_hovered(struct nk_context*); -/*/// #### nk_window_is_collapsed -/// Returns if the window with given name is currently minimized/collapsed -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// int nk_window_is_collapsed(struct nk_context *ctx, const char *name); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// __name__ | Identifier of window you want to check if it is collapsed -/// -/// Returns `true(1)` if current window is minimized and `false(0)` if window not -/// found or is not minimized -*/ -NK_API int nk_window_is_collapsed(struct nk_context *ctx, const char *name); -/*/// #### nk_window_is_closed -/// Returns if the window with given name was closed by calling `nk_close` -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// int nk_window_is_closed(struct nk_context *ctx, const char *name); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// __name__ | Identifier of window you want to check if it is closed -/// -/// Returns `true(1)` if current window was closed or `false(0)` window not found or not closed -*/ -NK_API int nk_window_is_closed(struct nk_context*, const char*); -/*/// #### nk_window_is_hidden -/// Returns if the window with given name is hidden -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// int nk_window_is_hidden(struct nk_context *ctx, const char *name); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// __name__ | Identifier of window you want to check if it is hidden -/// -/// Returns `true(1)` if current window is hidden or `false(0)` window not found or visible -*/ -NK_API int nk_window_is_hidden(struct nk_context*, const char*); -/*/// #### nk_window_is_active -/// Same as nk_window_has_focus for some reason -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// int nk_window_is_active(struct nk_context *ctx, const char *name); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// __name__ | Identifier of window you want to check if it is active -/// -/// Returns `true(1)` if current window is active or `false(0)` window not found or not active -*/ -NK_API int nk_window_is_active(struct nk_context*, const char*); -/*/// #### nk_window_is_any_hovered -/// Returns if the any window is being hovered -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// int nk_window_is_any_hovered(struct nk_context*); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// -/// Returns `true(1)` if any window is hovered or `false(0)` otherwise -*/ -NK_API int nk_window_is_any_hovered(struct nk_context*); -/*/// #### nk_item_is_any_active -/// Returns if the any window is being hovered or any widget is currently active. -/// Can be used to decide if input should be processed by UI or your specific input handling. -/// Example could be UI and 3D camera to move inside a 3D space. -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// int nk_item_is_any_active(struct nk_context*); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// -/// Returns `true(1)` if any window is hovered or any item is active or `false(0)` otherwise -*/ -NK_API int nk_item_is_any_active(struct nk_context*); -/*/// #### nk_window_set_bounds -/// Updates position and size of window with passed in name -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_window_set_bounds(struct nk_context*, const char *name, struct nk_rect bounds); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// __name__ | Identifier of the window to modify both position and size -/// __bounds__ | Must point to a `nk_rect` struct with the new position and size -*/ -NK_API void nk_window_set_bounds(struct nk_context*, const char *name, struct nk_rect bounds); -/*/// #### nk_window_set_position -/// Updates position of window with passed name -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_window_set_position(struct nk_context*, const char *name, struct nk_vec2 pos); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// __name__ | Identifier of the window to modify both position -/// __pos__ | Must point to a `nk_vec2` struct with the new position -*/ -NK_API void nk_window_set_position(struct nk_context*, const char *name, struct nk_vec2 pos); -/*/// #### nk_window_set_size -/// Updates size of window with passed in name -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_window_set_size(struct nk_context*, const char *name, struct nk_vec2); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// __name__ | Identifier of the window to modify both window size -/// __size__ | Must point to a `nk_vec2` struct with new window size -*/ -NK_API void nk_window_set_size(struct nk_context*, const char *name, struct nk_vec2); -/*/// #### nk_window_set_focus -/// Sets the window with given name as active -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_window_set_focus(struct nk_context*, const char *name); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// __name__ | Identifier of the window to set focus on -*/ -NK_API void nk_window_set_focus(struct nk_context*, const char *name); -/*/// #### nk_window_close -/// Closes a window and marks it for being freed at the end of the frame -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_window_close(struct nk_context *ctx, const char *name); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// __name__ | Identifier of the window to close -*/ -NK_API void nk_window_close(struct nk_context *ctx, const char *name); -/*/// #### nk_window_collapse -/// Updates collapse state of a window with given name -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_window_collapse(struct nk_context*, const char *name, enum nk_collapse_states state); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// __name__ | Identifier of the window to close -/// __state__ | value out of nk_collapse_states section -*/ -NK_API void nk_window_collapse(struct nk_context*, const char *name, enum nk_collapse_states state); -/*/// #### nk_window_collapse_if -/// Updates collapse state of a window with given name if given condition is met -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_window_collapse_if(struct nk_context*, const char *name, enum nk_collapse_states, int cond); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// __name__ | Identifier of the window to either collapse or maximize -/// __state__ | value out of nk_collapse_states section the window should be put into -/// __cond__ | condition that has to be met to actually commit the collapse state change -*/ -NK_API void nk_window_collapse_if(struct nk_context*, const char *name, enum nk_collapse_states, int cond); -/*/// #### nk_window_show -/// updates visibility state of a window with given name -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_window_show(struct nk_context*, const char *name, enum nk_show_states); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// __name__ | Identifier of the window to either collapse or maximize -/// __state__ | state with either visible or hidden to modify the window with -*/ -NK_API void nk_window_show(struct nk_context*, const char *name, enum nk_show_states); -/*/// #### nk_window_show_if -/// Updates visibility state of a window with given name if a given condition is met -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_window_show_if(struct nk_context*, const char *name, enum nk_show_states, int cond); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// __name__ | Identifier of the window to either hide or show -/// __state__ | state with either visible or hidden to modify the window with -/// __cond__ | condition that has to be met to actually commit the visbility state change -*/ -NK_API void nk_window_show_if(struct nk_context*, const char *name, enum nk_show_states, int cond); -/* ============================================================================= - * - * LAYOUT - * - * ============================================================================= -/// ### Layouting -/// Layouting in general describes placing widget inside a window with position and size. -/// While in this particular implementation there are five different APIs for layouting -/// each with different trade offs between control and ease of use.

-/// -/// All layouting methods in this library are based around the concept of a row. -/// A row has a height the window content grows by and a number of columns and each -/// layouting method specifies how each widget is placed inside the row. -/// After a row has been allocated by calling a layouting functions and then -/// filled with widgets will advance an internal pointer over the allocated row.

-/// -/// To actually define a layout you just call the appropriate layouting function -/// and each subsequent widget call will place the widget as specified. Important -/// here is that if you define more widgets then columns defined inside the layout -/// functions it will allocate the next row without you having to make another layouting

-/// call. -/// -/// Biggest limitation with using all these APIs outside the `nk_layout_space_xxx` API -/// is that you have to define the row height for each. However the row height -/// often depends on the height of the font.

-/// -/// To fix that internally nuklear uses a minimum row height that is set to the -/// height plus padding of currently active font and overwrites the row height -/// value if zero.

-/// -/// If you manually want to change the minimum row height then -/// use nk_layout_set_min_row_height, and use nk_layout_reset_min_row_height to -/// reset it back to be derived from font height.

-/// -/// Also if you change the font in nuklear it will automatically change the minimum -/// row height for you and. This means if you change the font but still want -/// a minimum row height smaller than the font you have to repush your value.

-/// -/// For actually more advanced UI I would even recommend using the `nk_layout_space_xxx` -/// layouting method in combination with a cassowary constraint solver (there are -/// some versions on github with permissive license model) to take over all control over widget -/// layouting yourself. However for quick and dirty layouting using all the other layouting -/// functions should be fine. -/// -/// #### Usage -/// 1. __nk_layout_row_dynamic__

-/// The easiest layouting function is `nk_layout_row_dynamic`. It provides each -/// widgets with same horizontal space inside the row and dynamically grows -/// if the owning window grows in width. So the number of columns dictates -/// the size of each widget dynamically by formula: -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// widget_width = (window_width - padding - spacing) * (1/colum_count) -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Just like all other layouting APIs if you define more widget than columns this -/// library will allocate a new row and keep all layouting parameters previously -/// defined. -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// if (nk_begin_xxx(...) { -/// // first row with height: 30 composed of two widgets -/// nk_layout_row_dynamic(&ctx, 30, 2); -/// nk_widget(...); -/// nk_widget(...); -/// // -/// // second row with same parameter as defined above -/// nk_widget(...); -/// nk_widget(...); -/// // -/// // third row uses 0 for height which will use auto layouting -/// nk_layout_row_dynamic(&ctx, 0, 2); -/// nk_widget(...); -/// nk_widget(...); -/// } -/// nk_end(...); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// 2. __nk_layout_row_static__

-/// Another easy layouting function is `nk_layout_row_static`. It provides each -/// widget with same horizontal pixel width inside the row and does not grow -/// if the owning window scales smaller or bigger. -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// if (nk_begin_xxx(...) { -/// // first row with height: 30 composed of two widgets with width: 80 -/// nk_layout_row_static(&ctx, 30, 80, 2); -/// nk_widget(...); -/// nk_widget(...); -/// // -/// // second row with same parameter as defined above -/// nk_widget(...); -/// nk_widget(...); -/// // -/// // third row uses 0 for height which will use auto layouting -/// nk_layout_row_static(&ctx, 0, 80, 2); -/// nk_widget(...); -/// nk_widget(...); -/// } -/// nk_end(...); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// 3. __nk_layout_row_xxx__

-/// A little bit more advanced layouting API are functions `nk_layout_row_begin`, -/// `nk_layout_row_push` and `nk_layout_row_end`. They allow to directly -/// specify each column pixel or window ratio in a row. It supports either -/// directly setting per column pixel width or widget window ratio but not -/// both. Furthermore it is a immediate mode API so each value is directly -/// pushed before calling a widget. Therefore the layout is not automatically -/// repeating like the last two layouting functions. -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// if (nk_begin_xxx(...) { -/// // first row with height: 25 composed of two widgets with width 60 and 40 -/// nk_layout_row_begin(ctx, NK_STATIC, 25, 2); -/// nk_layout_row_push(ctx, 60); -/// nk_widget(...); -/// nk_layout_row_push(ctx, 40); -/// nk_widget(...); -/// nk_layout_row_end(ctx); -/// // -/// // second row with height: 25 composed of two widgets with window ratio 0.25 and 0.75 -/// nk_layout_row_begin(ctx, NK_DYNAMIC, 25, 2); -/// nk_layout_row_push(ctx, 0.25f); -/// nk_widget(...); -/// nk_layout_row_push(ctx, 0.75f); -/// nk_widget(...); -/// nk_layout_row_end(ctx); -/// // -/// // third row with auto generated height: composed of two widgets with window ratio 0.25 and 0.75 -/// nk_layout_row_begin(ctx, NK_DYNAMIC, 0, 2); -/// nk_layout_row_push(ctx, 0.25f); -/// nk_widget(...); -/// nk_layout_row_push(ctx, 0.75f); -/// nk_widget(...); -/// nk_layout_row_end(ctx); -/// } -/// nk_end(...); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// 4. __nk_layout_row__

-/// The array counterpart to API nk_layout_row_xxx is the single nk_layout_row -/// functions. Instead of pushing either pixel or window ratio for every widget -/// it allows to define it by array. The trade of for less control is that -/// `nk_layout_row` is automatically repeating. Otherwise the behavior is the -/// same. -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// if (nk_begin_xxx(...) { -/// // two rows with height: 30 composed of two widgets with width 60 and 40 -/// const float size[] = {60,40}; -/// nk_layout_row(ctx, NK_STATIC, 30, 2, ratio); -/// nk_widget(...); -/// nk_widget(...); -/// nk_widget(...); -/// nk_widget(...); -/// // -/// // two rows with height: 30 composed of two widgets with window ratio 0.25 and 0.75 -/// const float ratio[] = {0.25, 0.75}; -/// nk_layout_row(ctx, NK_DYNAMIC, 30, 2, ratio); -/// nk_widget(...); -/// nk_widget(...); -/// nk_widget(...); -/// nk_widget(...); -/// // -/// // two rows with auto generated height composed of two widgets with window ratio 0.25 and 0.75 -/// const float ratio[] = {0.25, 0.75}; -/// nk_layout_row(ctx, NK_DYNAMIC, 30, 2, ratio); -/// nk_widget(...); -/// nk_widget(...); -/// nk_widget(...); -/// nk_widget(...); -/// } -/// nk_end(...); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// 5. __nk_layout_row_template_xxx__

-/// The most complex and second most flexible API is a simplified flexbox version without -/// line wrapping and weights for dynamic widgets. It is an immediate mode API but -/// unlike `nk_layout_row_xxx` it has auto repeat behavior and needs to be called -/// before calling the templated widgets. -/// The row template layout has three different per widget size specifier. The first -/// one is the `nk_layout_row_template_push_static` with fixed widget pixel width. -/// They do not grow if the row grows and will always stay the same. -/// The second size specifier is `nk_layout_row_template_push_variable` -/// which defines a minimum widget size but it also can grow if more space is available -/// not taken by other widgets. -/// Finally there are dynamic widgets with `nk_layout_row_template_push_dynamic` -/// which are completely flexible and unlike variable widgets can even shrink -/// to zero if not enough space is provided. -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// if (nk_begin_xxx(...) { -/// // two rows with height: 30 composed of three widgets -/// nk_layout_row_template_begin(ctx, 30); -/// nk_layout_row_template_push_dynamic(ctx); -/// nk_layout_row_template_push_variable(ctx, 80); -/// nk_layout_row_template_push_static(ctx, 80); -/// nk_layout_row_template_end(ctx); -/// // -/// // first row -/// nk_widget(...); // dynamic widget can go to zero if not enough space -/// nk_widget(...); // variable widget with min 80 pixel but can grow bigger if enough space -/// nk_widget(...); // static widget with fixed 80 pixel width -/// // -/// // second row same layout -/// nk_widget(...); -/// nk_widget(...); -/// nk_widget(...); -/// } -/// nk_end(...); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// 6. __nk_layout_space_xxx__

-/// Finally the most flexible API directly allows you to place widgets inside the -/// window. The space layout API is an immediate mode API which does not support -/// row auto repeat and directly sets position and size of a widget. Position -/// and size hereby can be either specified as ratio of allocated space or -/// allocated space local position and pixel size. Since this API is quite -/// powerful there are a number of utility functions to get the available space -/// and convert between local allocated space and screen space. -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// if (nk_begin_xxx(...) { -/// // static row with height: 500 (you can set column count to INT_MAX if you don't want to be bothered) -/// nk_layout_space_begin(ctx, NK_STATIC, 500, INT_MAX); -/// nk_layout_space_push(ctx, nk_rect(0,0,150,200)); -/// nk_widget(...); -/// nk_layout_space_push(ctx, nk_rect(200,200,100,200)); -/// nk_widget(...); -/// nk_layout_space_end(ctx); -/// // -/// // dynamic row with height: 500 (you can set column count to INT_MAX if you don't want to be bothered) -/// nk_layout_space_begin(ctx, NK_DYNAMIC, 500, INT_MAX); -/// nk_layout_space_push(ctx, nk_rect(0.5,0.5,0.1,0.1)); -/// nk_widget(...); -/// nk_layout_space_push(ctx, nk_rect(0.7,0.6,0.1,0.1)); -/// nk_widget(...); -/// } -/// nk_end(...); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// #### Reference -/// Function | Description -/// ----------------------------------------|------------------------------------ -/// nk_layout_set_min_row_height | Set the currently used minimum row height to a specified value -/// nk_layout_reset_min_row_height | Resets the currently used minimum row height to font height -/// nk_layout_widget_bounds | Calculates current width a static layout row can fit inside a window -/// nk_layout_ratio_from_pixel | Utility functions to calculate window ratio from pixel size -// -/// nk_layout_row_dynamic | Current layout is divided into n same sized growing columns -/// nk_layout_row_static | Current layout is divided into n same fixed sized columns -/// nk_layout_row_begin | Starts a new row with given height and number of columns -/// nk_layout_row_push | Pushes another column with given size or window ratio -/// nk_layout_row_end | Finished previously started row -/// nk_layout_row | Specifies row columns in array as either window ratio or size -// -/// nk_layout_row_template_begin | Begins the row template declaration -/// nk_layout_row_template_push_dynamic | Adds a dynamic column that dynamically grows and can go to zero if not enough space -/// nk_layout_row_template_push_variable | Adds a variable column that dynamically grows but does not shrink below specified pixel width -/// nk_layout_row_template_push_static | Adds a static column that does not grow and will always have the same size -/// nk_layout_row_template_end | Marks the end of the row template -// -/// nk_layout_space_begin | Begins a new layouting space that allows to specify each widgets position and size -/// nk_layout_space_push | Pushes position and size of the next widget in own coordinate space either as pixel or ratio -/// nk_layout_space_end | Marks the end of the layouting space -// -/// nk_layout_space_bounds | Callable after nk_layout_space_begin and returns total space allocated -/// nk_layout_space_to_screen | Converts vector from nk_layout_space coordinate space into screen space -/// nk_layout_space_to_local | Converts vector from screen space into nk_layout_space coordinates -/// nk_layout_space_rect_to_screen | Converts rectangle from nk_layout_space coordinate space into screen space -/// nk_layout_space_rect_to_local | Converts rectangle from screen space into nk_layout_space coordinates -*/ -/*/// #### nk_layout_set_min_row_height -/// Sets the currently used minimum row height. -/// !!! WARNING -/// The passed height needs to include both your preferred row height -/// as well as padding. No internal padding is added. -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_layout_set_min_row_height(struct nk_context*, float height); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx` -/// __height__ | New minimum row height to be used for auto generating the row height -*/ -NK_API void nk_layout_set_min_row_height(struct nk_context*, float height); -/*/// #### nk_layout_reset_min_row_height -/// Reset the currently used minimum row height back to `font_height + text_padding + padding` -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_layout_reset_min_row_height(struct nk_context*); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx` -*/ -NK_API void nk_layout_reset_min_row_height(struct nk_context*); -/*/// #### nk_layout_widget_bounds -/// Returns the width of the next row allocate by one of the layouting functions -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// struct nk_rect nk_layout_widget_bounds(struct nk_context*); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx` -/// -/// Return `nk_rect` with both position and size of the next row -*/ -NK_API struct nk_rect nk_layout_widget_bounds(struct nk_context*); -/*/// #### nk_layout_ratio_from_pixel -/// Utility functions to calculate window ratio from pixel size -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// float nk_layout_ratio_from_pixel(struct nk_context*, float pixel_width); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx` -/// __pixel__ | Pixel_width to convert to window ratio -/// -/// Returns `nk_rect` with both position and size of the next row -*/ -NK_API float nk_layout_ratio_from_pixel(struct nk_context*, float pixel_width); -/*/// #### nk_layout_row_dynamic -/// Sets current row layout to share horizontal space -/// between @cols number of widgets evenly. Once called all subsequent widget -/// calls greater than @cols will allocate a new row with same layout. -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_layout_row_dynamic(struct nk_context *ctx, float height, int cols); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx` -/// __height__ | Holds height of each widget in row or zero for auto layouting -/// __columns__ | Number of widget inside row -*/ -NK_API void nk_layout_row_dynamic(struct nk_context *ctx, float height, int cols); -/*/// #### nk_layout_row_static -/// Sets current row layout to fill @cols number of widgets -/// in row with same @item_width horizontal size. Once called all subsequent widget -/// calls greater than @cols will allocate a new row with same layout. -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_layout_row_static(struct nk_context *ctx, float height, int item_width, int cols); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx` -/// __height__ | Holds height of each widget in row or zero for auto layouting -/// __width__ | Holds pixel width of each widget in the row -/// __columns__ | Number of widget inside row -*/ -NK_API void nk_layout_row_static(struct nk_context *ctx, float height, int item_width, int cols); -/*/// #### nk_layout_row_begin -/// Starts a new dynamic or fixed row with given height and columns. -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_layout_row_begin(struct nk_context *ctx, enum nk_layout_format fmt, float row_height, int cols); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx` -/// __fmt__ | either `NK_DYNAMIC` for window ratio or `NK_STATIC` for fixed size columns -/// __height__ | holds height of each widget in row or zero for auto layouting -/// __columns__ | Number of widget inside row -*/ -NK_API void nk_layout_row_begin(struct nk_context *ctx, enum nk_layout_format fmt, float row_height, int cols); -/*/// #### nk_layout_row_push -/// Specifies either window ratio or width of a single column -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_layout_row_push(struct nk_context*, float value); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx` -/// __value__ | either a window ratio or fixed width depending on @fmt in previous `nk_layout_row_begin` call -*/ -NK_API void nk_layout_row_push(struct nk_context*, float value); -/*/// #### nk_layout_row_end -/// Finished previously started row -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_layout_row_end(struct nk_context*); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx` -*/ -NK_API void nk_layout_row_end(struct nk_context*); -/*/// #### nk_layout_row -/// Specifies row columns in array as either window ratio or size -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_layout_row(struct nk_context*, enum nk_layout_format, float height, int cols, const float *ratio); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx` -/// __fmt__ | Either `NK_DYNAMIC` for window ratio or `NK_STATIC` for fixed size columns -/// __height__ | Holds height of each widget in row or zero for auto layouting -/// __columns__ | Number of widget inside row -*/ -NK_API void nk_layout_row(struct nk_context*, enum nk_layout_format, float height, int cols, const float *ratio); -/*/// #### nk_layout_row_template_begin -/// Begins the row template declaration -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_layout_row_template_begin(struct nk_context*, float row_height); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx` -/// __height__ | Holds height of each widget in row or zero for auto layouting -*/ -NK_API void nk_layout_row_template_begin(struct nk_context*, float row_height); -/*/// #### nk_layout_row_template_push_dynamic -/// Adds a dynamic column that dynamically grows and can go to zero if not enough space -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_layout_row_template_push_dynamic(struct nk_context*); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx` -/// __height__ | Holds height of each widget in row or zero for auto layouting -*/ -NK_API void nk_layout_row_template_push_dynamic(struct nk_context*); -/*/// #### nk_layout_row_template_push_variable -/// Adds a variable column that dynamically grows but does not shrink below specified pixel width -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_layout_row_template_push_variable(struct nk_context*, float min_width); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx` -/// __width__ | Holds the minimum pixel width the next column must always be -*/ -NK_API void nk_layout_row_template_push_variable(struct nk_context*, float min_width); -/*/// #### nk_layout_row_template_push_static -/// Adds a static column that does not grow and will always have the same size -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_layout_row_template_push_static(struct nk_context*, float width); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx` -/// __width__ | Holds the absolute pixel width value the next column must be -*/ -NK_API void nk_layout_row_template_push_static(struct nk_context*, float width); -/*/// #### nk_layout_row_template_end -/// Marks the end of the row template -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_layout_row_template_end(struct nk_context*); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx` -*/ -NK_API void nk_layout_row_template_end(struct nk_context*); -/*/// #### nk_layout_space_begin -/// Begins a new layouting space that allows to specify each widgets position and size. -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_layout_space_begin(struct nk_context*, enum nk_layout_format, float height, int widget_count); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx` -/// __fmt__ | Either `NK_DYNAMIC` for window ratio or `NK_STATIC` for fixed size columns -/// __height__ | Holds height of each widget in row or zero for auto layouting -/// __columns__ | Number of widgets inside row -*/ -NK_API void nk_layout_space_begin(struct nk_context*, enum nk_layout_format, float height, int widget_count); -/*/// #### nk_layout_space_push -/// Pushes position and size of the next widget in own coordinate space either as pixel or ratio -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_layout_space_push(struct nk_context *ctx, struct nk_rect bounds); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_layout_space_begin` -/// __bounds__ | Position and size in laoyut space local coordinates -*/ -NK_API void nk_layout_space_push(struct nk_context*, struct nk_rect bounds); -/*/// #### nk_layout_space_end -/// Marks the end of the layout space -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_layout_space_end(struct nk_context*); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_layout_space_begin` -*/ -NK_API void nk_layout_space_end(struct nk_context*); -/*/// #### nk_layout_space_bounds -/// Utility function to calculate total space allocated for `nk_layout_space` -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// struct nk_rect nk_layout_space_bounds(struct nk_context*); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_layout_space_begin` -/// -/// Returns `nk_rect` holding the total space allocated -*/ -NK_API struct nk_rect nk_layout_space_bounds(struct nk_context*); -/*/// #### nk_layout_space_to_screen -/// Converts vector from nk_layout_space coordinate space into screen space -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// struct nk_vec2 nk_layout_space_to_screen(struct nk_context*, struct nk_vec2); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_layout_space_begin` -/// __vec__ | Position to convert from layout space into screen coordinate space -/// -/// Returns transformed `nk_vec2` in screen space coordinates -*/ -NK_API struct nk_vec2 nk_layout_space_to_screen(struct nk_context*, struct nk_vec2); -/*/// #### nk_layout_space_to_local -/// Converts vector from layout space into screen space -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// struct nk_vec2 nk_layout_space_to_local(struct nk_context*, struct nk_vec2); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_layout_space_begin` -/// __vec__ | Position to convert from screen space into layout coordinate space -/// -/// Returns transformed `nk_vec2` in layout space coordinates -*/ -NK_API struct nk_vec2 nk_layout_space_to_local(struct nk_context*, struct nk_vec2); -/*/// #### nk_layout_space_rect_to_screen -/// Converts rectangle from screen space into layout space -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// struct nk_rect nk_layout_space_rect_to_screen(struct nk_context*, struct nk_rect); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_layout_space_begin` -/// __bounds__ | Rectangle to convert from layout space into screen space -/// -/// Returns transformed `nk_rect` in screen space coordinates -*/ -NK_API struct nk_rect nk_layout_space_rect_to_screen(struct nk_context*, struct nk_rect); -/*/// #### nk_layout_space_rect_to_local -/// Converts rectangle from layout space into screen space -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// struct nk_rect nk_layout_space_rect_to_local(struct nk_context*, struct nk_rect); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_layout_space_begin` -/// __bounds__ | Rectangle to convert from layout space into screen space -/// -/// Returns transformed `nk_rect` in layout space coordinates -*/ -NK_API struct nk_rect nk_layout_space_rect_to_local(struct nk_context*, struct nk_rect); -/* ============================================================================= - * - * GROUP - * - * ============================================================================= -/// ### Groups -/// Groups are basically windows inside windows. They allow to subdivide space -/// in a window to layout widgets as a group. Almost all more complex widget -/// layouting requirements can be solved using groups and basic layouting -/// fuctionality. Groups just like windows are identified by an unique name and -/// internally keep track of scrollbar offsets by default. However additional -/// versions are provided to directly manage the scrollbar. -/// -/// #### Usage -/// To create a group you have to call one of the three `nk_group_begin_xxx` -/// functions to start group declarations and `nk_group_end` at the end. Furthermore it -/// is required to check the return value of `nk_group_begin_xxx` and only process -/// widgets inside the window if the value is not 0. -/// Nesting groups is possible and even encouraged since many layouting schemes -/// can only be achieved by nesting. Groups, unlike windows, need `nk_group_end` -/// to be only called if the corosponding `nk_group_begin_xxx` call does not return 0: -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// if (nk_group_begin_xxx(ctx, ...) { -/// // [... widgets ...] -/// nk_group_end(ctx); -/// } -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// In the grand concept groups can be called after starting a window -/// with `nk_begin_xxx` and before calling `nk_end`: -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// struct nk_context ctx; -/// nk_init_xxx(&ctx, ...); -/// while (1) { -/// // Input -/// Event evt; -/// nk_input_begin(&ctx); -/// while (GetEvent(&evt)) { -/// if (evt.type == MOUSE_MOVE) -/// nk_input_motion(&ctx, evt.motion.x, evt.motion.y); -/// else if (evt.type == [...]) { -/// nk_input_xxx(...); -/// } -/// } -/// nk_input_end(&ctx); -/// // -/// // Window -/// if (nk_begin_xxx(...) { -/// // [...widgets...] -/// nk_layout_row_dynamic(...); -/// if (nk_group_begin_xxx(ctx, ...) { -/// //[... widgets ...] -/// nk_group_end(ctx); -/// } -/// } -/// nk_end(ctx); -/// // -/// // Draw -/// const struct nk_command *cmd = 0; -/// nk_foreach(cmd, &ctx) { -/// switch (cmd->type) { -/// case NK_COMMAND_LINE: -/// your_draw_line_function(...) -/// break; -/// case NK_COMMAND_RECT -/// your_draw_rect_function(...) -/// break; -/// case ...: -/// // [...] -/// } -// nk_clear(&ctx); -/// } -/// nk_free(&ctx); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// #### Reference -/// Function | Description -/// --------------------------------|------------------------------------------- -/// nk_group_begin | Start a new group with internal scrollbar handling -/// nk_group_begin_titled | Start a new group with separeted name and title and internal scrollbar handling -/// nk_group_end | Ends a group. Should only be called if nk_group_begin returned non-zero -/// nk_group_scrolled_offset_begin | Start a new group with manual separated handling of scrollbar x- and y-offset -/// nk_group_scrolled_begin | Start a new group with manual scrollbar handling -/// nk_group_scrolled_end | Ends a group with manual scrollbar handling. Should only be called if nk_group_begin returned non-zero -*/ -/*/// #### nk_group_begin -/// Starts a new widget group. Requires a previous layouting function to specify a pos/size. -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// int nk_group_begin(struct nk_context*, const char *title, nk_flags); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// __title__ | Must be an unique identifier for this group that is also used for the group header -/// __flags__ | Window flags defined in the nk_panel_flags section with a number of different group behaviors -/// -/// Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise -*/ -NK_API int nk_group_begin(struct nk_context*, const char *title, nk_flags); -/*/// #### nk_group_begin_titled -/// Starts a new widget group. Requires a previous layouting function to specify a pos/size. -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// int nk_group_begin_titled(struct nk_context*, const char *name, const char *title, nk_flags); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// __id__ | Must be an unique identifier for this group -/// __title__ | Group header title -/// __flags__ | Window flags defined in the nk_panel_flags section with a number of different group behaviors -/// -/// Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise -*/ -NK_API int nk_group_begin_titled(struct nk_context*, const char *name, const char *title, nk_flags); -/*/// #### nk_group_end -/// Ends a widget group -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_group_end(struct nk_context*); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -*/ -NK_API void nk_group_end(struct nk_context*); -/*/// #### nk_group_scrolled_offset_begin -/// starts a new widget group. requires a previous layouting function to specify -/// a size. Does not keep track of scrollbar. -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// int nk_group_scrolled_offset_begin(struct nk_context*, nk_uint *x_offset, nk_uint *y_offset, const char *title, nk_flags flags); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// __x_offset__| Scrollbar x-offset to offset all widgets inside the group horizontally. -/// __y_offset__| Scrollbar y-offset to offset all widgets inside the group vertically -/// __title__ | Window unique group title used to both identify and display in the group header -/// __flags__ | Window flags from the nk_panel_flags section -/// -/// Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise -*/ -NK_API int nk_group_scrolled_offset_begin(struct nk_context*, nk_uint *x_offset, nk_uint *y_offset, const char *title, nk_flags flags); -/*/// #### nk_group_scrolled_begin -/// Starts a new widget group. requires a previous -/// layouting function to specify a size. Does not keep track of scrollbar. -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// int nk_group_scrolled_begin(struct nk_context*, struct nk_scroll *off, const char *title, nk_flags); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// __off__ | Both x- and y- scroll offset. Allows for manual scrollbar control -/// __title__ | Window unique group title used to both identify and display in the group header -/// __flags__ | Window flags from nk_panel_flags section -/// -/// Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise -*/ -NK_API int nk_group_scrolled_begin(struct nk_context*, struct nk_scroll *off, const char *title, nk_flags); -/*/// #### nk_group_scrolled_end -/// Ends a widget group after calling nk_group_scrolled_offset_begin or nk_group_scrolled_begin. -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_group_scrolled_end(struct nk_context*); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -*/ -NK_API void nk_group_scrolled_end(struct nk_context*); -/* ============================================================================= - * - * TREE - * - * ============================================================================= -/// ### Tree -/// Trees represent two different concept. First the concept of a collapsable -/// UI section that can be either in a hidden or visibile state. They allow the UI -/// user to selectively minimize the current set of visible UI to comprehend. -/// The second concept are tree widgets for visual UI representation of trees.

-/// -/// Trees thereby can be nested for tree representations and multiple nested -/// collapsable UI sections. All trees are started by calling of the -/// `nk_tree_xxx_push_tree` functions and ended by calling one of the -/// `nk_tree_xxx_pop_xxx()` functions. Each starting functions takes a title label -/// and optionally an image to be displayed and the initial collapse state from -/// the nk_collapse_states section.

-/// -/// The runtime state of the tree is either stored outside the library by the caller -/// or inside which requires a unique ID. The unique ID can either be generated -/// automatically from `__FILE__` and `__LINE__` with function `nk_tree_push`, -/// by `__FILE__` and a user provided ID generated for example by loop index with -/// function `nk_tree_push_id` or completely provided from outside by user with -/// function `nk_tree_push_hashed`. -/// -/// #### Usage -/// To create a tree you have to call one of the seven `nk_tree_xxx_push_xxx` -/// functions to start a collapsable UI section and `nk_tree_xxx_pop` to mark the -/// end. -/// Each starting function will either return `false(0)` if the tree is collapsed -/// or hidden and therefore does not need to be filled with content or `true(1)` -/// if visible and required to be filled. -/// -/// !!! Note -/// The tree header does not require and layouting function and instead -/// calculates a auto height based on the currently used font size -/// -/// The tree ending functions only need to be called if the tree content is -/// actually visible. So make sure the tree push function is guarded by `if` -/// and the pop call is only taken if the tree is visible. -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// if (nk_tree_push(ctx, NK_TREE_TAB, "Tree", NK_MINIMIZED)) { -/// nk_layout_row_dynamic(...); -/// nk_widget(...); -/// nk_tree_pop(ctx); -/// } -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// #### Reference -/// Function | Description -/// ----------------------------|------------------------------------------- -/// nk_tree_push | Start a collapsable UI section with internal state management -/// nk_tree_push_id | Start a collapsable UI section with internal state management callable in a look -/// nk_tree_push_hashed | Start a collapsable UI section with internal state management with full control over internal unique ID use to store state -/// nk_tree_image_push | Start a collapsable UI section with image and label header -/// nk_tree_image_push_id | Start a collapsable UI section with image and label header and internal state management callable in a look -/// nk_tree_image_push_hashed | Start a collapsable UI section with image and label header and internal state management with full control over internal unique ID use to store state -/// nk_tree_pop | Ends a collapsable UI section -// -/// nk_tree_state_push | Start a collapsable UI section with external state management -/// nk_tree_state_image_push | Start a collapsable UI section with image and label header and external state management -/// nk_tree_state_pop | Ends a collapsabale UI section -/// -/// #### nk_tree_type -/// Flag | Description -/// ----------------|---------------------------------------- -/// NK_TREE_NODE | Highlighted tree header to mark a collapsable UI section -/// NK_TREE_TAB | Non-highighted tree header closer to tree representations -*/ -/*/// #### nk_tree_push -/// Starts a collapsable UI section with internal state management -/// !!! WARNING -/// To keep track of the runtime tree collapsable state this function uses -/// defines `__FILE__` and `__LINE__` to generate a unique ID. If you want -/// to call this function in a loop please use `nk_tree_push_id` or -/// `nk_tree_push_hashed` instead. -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// #define nk_tree_push(ctx, type, title, state) -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// __type__ | Value from the nk_tree_type section to visually mark a tree node header as either a collapseable UI section or tree node -/// __title__ | Label printed in the tree header -/// __state__ | Initial tree state value out of nk_collapse_states -/// -/// Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise -*/ -#define nk_tree_push(ctx, type, title, state) nk_tree_push_hashed(ctx, type, title, state, NK_FILE_LINE,nk_strlen(NK_FILE_LINE),__LINE__) -/*/// #### nk_tree_push_id -/// Starts a collapsable UI section with internal state management callable in a look -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// #define nk_tree_push_id(ctx, type, title, state, id) -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// __type__ | Value from the nk_tree_type section to visually mark a tree node header as either a collapseable UI section or tree node -/// __title__ | Label printed in the tree header -/// __state__ | Initial tree state value out of nk_collapse_states -/// __id__ | Loop counter index if this function is called in a loop -/// -/// Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise -*/ -#define nk_tree_push_id(ctx, type, title, state, id) nk_tree_push_hashed(ctx, type, title, state, NK_FILE_LINE,nk_strlen(NK_FILE_LINE),id) -/*/// #### nk_tree_push_hashed -/// Start a collapsable UI section with internal state management with full -/// control over internal unique ID used to store state -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// int nk_tree_push_hashed(struct nk_context*, enum nk_tree_type, const char *title, enum nk_collapse_states initial_state, const char *hash, int len,int seed); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// __type__ | Value from the nk_tree_type section to visually mark a tree node header as either a collapseable UI section or tree node -/// __title__ | Label printed in the tree header -/// __state__ | Initial tree state value out of nk_collapse_states -/// __hash__ | Memory block or string to generate the ID from -/// __len__ | Size of passed memory block or string in __hash__ -/// __seed__ | Seeding value if this function is called in a loop or default to `0` -/// -/// Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise -*/ -NK_API int nk_tree_push_hashed(struct nk_context*, enum nk_tree_type, const char *title, enum nk_collapse_states initial_state, const char *hash, int len,int seed); -/*/// #### nk_tree_image_push -/// Start a collapsable UI section with image and label header -/// !!! WARNING -/// To keep track of the runtime tree collapsable state this function uses -/// defines `__FILE__` and `__LINE__` to generate a unique ID. If you want -/// to call this function in a loop please use `nk_tree_image_push_id` or -/// `nk_tree_image_push_hashed` instead. -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// #define nk_tree_image_push(ctx, type, img, title, state) -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// __type__ | Value from the nk_tree_type section to visually mark a tree node header as either a collapseable UI section or tree node -/// __img__ | Image to display inside the header on the left of the label -/// __title__ | Label printed in the tree header -/// __state__ | Initial tree state value out of nk_collapse_states -/// -/// Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise -*/ -#define nk_tree_image_push(ctx, type, img, title, state) nk_tree_image_push_hashed(ctx, type, img, title, state, NK_FILE_LINE,nk_strlen(NK_FILE_LINE),__LINE__) -/*/// #### nk_tree_image_push_id -/// Start a collapsable UI section with image and label header and internal state -/// management callable in a look -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// #define nk_tree_image_push_id(ctx, type, img, title, state, id) -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// __type__ | Value from the nk_tree_type section to visually mark a tree node header as either a collapseable UI section or tree node -/// __img__ | Image to display inside the header on the left of the label -/// __title__ | Label printed in the tree header -/// __state__ | Initial tree state value out of nk_collapse_states -/// __id__ | Loop counter index if this function is called in a loop -/// -/// Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise -*/ -#define nk_tree_image_push_id(ctx, type, img, title, state, id) nk_tree_image_push_hashed(ctx, type, img, title, state, NK_FILE_LINE,nk_strlen(NK_FILE_LINE),id) -/*/// #### nk_tree_image_push_hashed -/// Start a collapsable UI section with internal state management with full -/// control over internal unique ID used to store state -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// int nk_tree_image_push_hashed(struct nk_context*, enum nk_tree_type, struct nk_image, const char *title, enum nk_collapse_states initial_state, const char *hash, int len,int seed); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct -/// __type__ | Value from the nk_tree_type section to visually mark a tree node header as either a collapseable UI section or tree node -/// __img__ | Image to display inside the header on the left of the label -/// __title__ | Label printed in the tree header -/// __state__ | Initial tree state value out of nk_collapse_states -/// __hash__ | Memory block or string to generate the ID from -/// __len__ | Size of passed memory block or string in __hash__ -/// __seed__ | Seeding value if this function is called in a loop or default to `0` -/// -/// Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise -*/ -NK_API int nk_tree_image_push_hashed(struct nk_context*, enum nk_tree_type, struct nk_image, const char *title, enum nk_collapse_states initial_state, const char *hash, int len,int seed); -/*/// #### nk_tree_pop -/// Ends a collapsabale UI section -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_tree_pop(struct nk_context*); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct after calling `nk_tree_xxx_push_xxx` -*/ -NK_API void nk_tree_pop(struct nk_context*); -/*/// #### nk_tree_state_push -/// Start a collapsable UI section with external state management -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// int nk_tree_state_push(struct nk_context*, enum nk_tree_type, const char *title, enum nk_collapse_states *state); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct after calling `nk_tree_xxx_push_xxx` -/// __type__ | Value from the nk_tree_type section to visually mark a tree node header as either a collapseable UI section or tree node -/// __title__ | Label printed in the tree header -/// __state__ | Persistent state to update -/// -/// Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise -*/ -NK_API int nk_tree_state_push(struct nk_context*, enum nk_tree_type, const char *title, enum nk_collapse_states *state); -/*/// #### nk_tree_state_image_push -/// Start a collapsable UI section with image and label header and external state management -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// int nk_tree_state_image_push(struct nk_context*, enum nk_tree_type, struct nk_image, const char *title, enum nk_collapse_states *state); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct after calling `nk_tree_xxx_push_xxx` -/// __img__ | Image to display inside the header on the left of the label -/// __type__ | Value from the nk_tree_type section to visually mark a tree node header as either a collapseable UI section or tree node -/// __title__ | Label printed in the tree header -/// __state__ | Persistent state to update -/// -/// Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise -*/ -NK_API int nk_tree_state_image_push(struct nk_context*, enum nk_tree_type, struct nk_image, const char *title, enum nk_collapse_states *state); -/*/// #### nk_tree_state_pop -/// Ends a collapsabale UI section -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_tree_state_pop(struct nk_context*); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// ------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct after calling `nk_tree_xxx_push_xxx` -*/ -NK_API void nk_tree_state_pop(struct nk_context*); - -#define nk_tree_element_push(ctx, type, title, state, sel) nk_tree_element_push_hashed(ctx, type, title, state, sel, NK_FILE_LINE,nk_strlen(NK_FILE_LINE),__LINE__) -#define nk_tree_element_push_id(ctx, type, title, state, sel, id) nk_tree_element_push_hashed(ctx, type, title, state, sel, NK_FILE_LINE,nk_strlen(NK_FILE_LINE),id) -NK_API int nk_tree_element_push_hashed(struct nk_context*, enum nk_tree_type, const char *title, enum nk_collapse_states initial_state, int *selected, const char *hash, int len, int seed); -NK_API int nk_tree_element_image_push_hashed(struct nk_context*, enum nk_tree_type, struct nk_image, const char *title, enum nk_collapse_states initial_state, int *selected, const char *hash, int len,int seed); -NK_API void nk_tree_element_pop(struct nk_context*); - -/* ============================================================================= - * - * LIST VIEW - * - * ============================================================================= */ -struct nk_list_view { -/* public: */ - int begin, end, count; -/* private: */ - int total_height; - struct nk_context *ctx; - nk_uint *scroll_pointer; - nk_uint scroll_value; -}; -NK_API int nk_list_view_begin(struct nk_context*, struct nk_list_view *out, const char *id, nk_flags, int row_height, int row_count); -NK_API void nk_list_view_end(struct nk_list_view*); -/* ============================================================================= - * - * WIDGET - * - * ============================================================================= */ -enum nk_widget_layout_states { - NK_WIDGET_INVALID, /* The widget cannot be seen and is completely out of view */ - NK_WIDGET_VALID, /* The widget is completely inside the window and can be updated and drawn */ - NK_WIDGET_ROM /* The widget is partially visible and cannot be updated */ -}; -enum nk_widget_states { - NK_WIDGET_STATE_MODIFIED = NK_FLAG(1), - NK_WIDGET_STATE_INACTIVE = NK_FLAG(2), /* widget is neither active nor hovered */ - NK_WIDGET_STATE_ENTERED = NK_FLAG(3), /* widget has been hovered on the current frame */ - NK_WIDGET_STATE_HOVER = NK_FLAG(4), /* widget is being hovered */ - NK_WIDGET_STATE_ACTIVED = NK_FLAG(5),/* widget is currently activated */ - NK_WIDGET_STATE_LEFT = NK_FLAG(6), /* widget is from this frame on not hovered anymore */ - NK_WIDGET_STATE_HOVERED = NK_WIDGET_STATE_HOVER|NK_WIDGET_STATE_MODIFIED, /* widget is being hovered */ - NK_WIDGET_STATE_ACTIVE = NK_WIDGET_STATE_ACTIVED|NK_WIDGET_STATE_MODIFIED /* widget is currently activated */ -}; -NK_API enum nk_widget_layout_states nk_widget(struct nk_rect*, const struct nk_context*); -NK_API enum nk_widget_layout_states nk_widget_fitting(struct nk_rect*, struct nk_context*, struct nk_vec2); -NK_API struct nk_rect nk_widget_bounds(struct nk_context*); -NK_API struct nk_vec2 nk_widget_position(struct nk_context*); -NK_API struct nk_vec2 nk_widget_size(struct nk_context*); -NK_API float nk_widget_width(struct nk_context*); -NK_API float nk_widget_height(struct nk_context*); -NK_API int nk_widget_is_hovered(struct nk_context*); -NK_API int nk_widget_is_mouse_clicked(struct nk_context*, enum nk_buttons); -NK_API int nk_widget_has_mouse_click_down(struct nk_context*, enum nk_buttons, int down); -NK_API void nk_spacing(struct nk_context*, int cols); -/* ============================================================================= - * - * TEXT - * - * ============================================================================= */ -enum nk_text_align { - NK_TEXT_ALIGN_LEFT = 0x01, - NK_TEXT_ALIGN_CENTERED = 0x02, - NK_TEXT_ALIGN_RIGHT = 0x04, - NK_TEXT_ALIGN_TOP = 0x08, - NK_TEXT_ALIGN_MIDDLE = 0x10, - NK_TEXT_ALIGN_BOTTOM = 0x20 -}; -enum nk_text_alignment { - NK_TEXT_LEFT = NK_TEXT_ALIGN_MIDDLE|NK_TEXT_ALIGN_LEFT, - NK_TEXT_CENTERED = NK_TEXT_ALIGN_MIDDLE|NK_TEXT_ALIGN_CENTERED, - NK_TEXT_RIGHT = NK_TEXT_ALIGN_MIDDLE|NK_TEXT_ALIGN_RIGHT -}; -NK_API void nk_text(struct nk_context*, const char*, int, nk_flags); -NK_API void nk_text_colored(struct nk_context*, const char*, int, nk_flags, struct nk_color); -NK_API void nk_text_wrap(struct nk_context*, const char*, int); -NK_API void nk_text_wrap_colored(struct nk_context*, const char*, int, struct nk_color); -NK_API void nk_label(struct nk_context*, const char*, nk_flags align); -NK_API void nk_label_colored(struct nk_context*, const char*, nk_flags align, struct nk_color); -NK_API void nk_label_wrap(struct nk_context*, const char*); -NK_API void nk_label_colored_wrap(struct nk_context*, const char*, struct nk_color); -NK_API void nk_image(struct nk_context*, struct nk_image); -NK_API void nk_image_color(struct nk_context*, struct nk_image, struct nk_color); -#ifdef NK_INCLUDE_STANDARD_VARARGS -NK_API void nk_labelf(struct nk_context*, nk_flags, NK_PRINTF_FORMAT_STRING const char*, ...) NK_PRINTF_VARARG_FUNC(3); -NK_API void nk_labelf_colored(struct nk_context*, nk_flags, struct nk_color, NK_PRINTF_FORMAT_STRING const char*,...) NK_PRINTF_VARARG_FUNC(4); -NK_API void nk_labelf_wrap(struct nk_context*, NK_PRINTF_FORMAT_STRING const char*,...) NK_PRINTF_VARARG_FUNC(2); -NK_API void nk_labelf_colored_wrap(struct nk_context*, struct nk_color, NK_PRINTF_FORMAT_STRING const char*,...) NK_PRINTF_VARARG_FUNC(3); -NK_API void nk_labelfv(struct nk_context*, nk_flags, NK_PRINTF_FORMAT_STRING const char*, va_list) NK_PRINTF_VALIST_FUNC(3); -NK_API void nk_labelfv_colored(struct nk_context*, nk_flags, struct nk_color, NK_PRINTF_FORMAT_STRING const char*, va_list) NK_PRINTF_VALIST_FUNC(4); -NK_API void nk_labelfv_wrap(struct nk_context*, NK_PRINTF_FORMAT_STRING const char*, va_list) NK_PRINTF_VALIST_FUNC(2); -NK_API void nk_labelfv_colored_wrap(struct nk_context*, struct nk_color, NK_PRINTF_FORMAT_STRING const char*, va_list) NK_PRINTF_VALIST_FUNC(3); -NK_API void nk_value_bool(struct nk_context*, const char *prefix, int); -NK_API void nk_value_int(struct nk_context*, const char *prefix, int); -NK_API void nk_value_uint(struct nk_context*, const char *prefix, unsigned int); -NK_API void nk_value_float(struct nk_context*, const char *prefix, float); -NK_API void nk_value_color_byte(struct nk_context*, const char *prefix, struct nk_color); -NK_API void nk_value_color_float(struct nk_context*, const char *prefix, struct nk_color); -NK_API void nk_value_color_hex(struct nk_context*, const char *prefix, struct nk_color); -#endif -/* ============================================================================= - * - * BUTTON - * - * ============================================================================= */ -NK_API int nk_button_text(struct nk_context*, const char *title, int len); -NK_API int nk_button_label(struct nk_context*, const char *title); -NK_API int nk_button_color(struct nk_context*, struct nk_color); -NK_API int nk_button_symbol(struct nk_context*, enum nk_symbol_type); -NK_API int nk_button_image(struct nk_context*, struct nk_image img); -NK_API int nk_button_symbol_label(struct nk_context*, enum nk_symbol_type, const char*, nk_flags text_alignment); -NK_API int nk_button_symbol_text(struct nk_context*, enum nk_symbol_type, const char*, int, nk_flags alignment); -NK_API int nk_button_image_label(struct nk_context*, struct nk_image img, const char*, nk_flags text_alignment); -NK_API int nk_button_image_text(struct nk_context*, struct nk_image img, const char*, int, nk_flags alignment); -NK_API int nk_button_text_styled(struct nk_context*, const struct nk_style_button*, const char *title, int len); -NK_API int nk_button_label_styled(struct nk_context*, const struct nk_style_button*, const char *title); -NK_API int nk_button_symbol_styled(struct nk_context*, const struct nk_style_button*, enum nk_symbol_type); -NK_API int nk_button_image_styled(struct nk_context*, const struct nk_style_button*, struct nk_image img); -NK_API int nk_button_symbol_text_styled(struct nk_context*,const struct nk_style_button*, enum nk_symbol_type, const char*, int, nk_flags alignment); -NK_API int nk_button_symbol_label_styled(struct nk_context *ctx, const struct nk_style_button *style, enum nk_symbol_type symbol, const char *title, nk_flags align); -NK_API int nk_button_image_label_styled(struct nk_context*,const struct nk_style_button*, struct nk_image img, const char*, nk_flags text_alignment); -NK_API int nk_button_image_text_styled(struct nk_context*,const struct nk_style_button*, struct nk_image img, const char*, int, nk_flags alignment); -NK_API void nk_button_set_behavior(struct nk_context*, enum nk_button_behavior); -NK_API int nk_button_push_behavior(struct nk_context*, enum nk_button_behavior); -NK_API int nk_button_pop_behavior(struct nk_context*); -/* ============================================================================= - * - * CHECKBOX - * - * ============================================================================= */ -NK_API int nk_check_label(struct nk_context*, const char*, int active); -NK_API int nk_check_text(struct nk_context*, const char*, int,int active); -NK_API unsigned nk_check_flags_label(struct nk_context*, const char*, unsigned int flags, unsigned int value); -NK_API unsigned nk_check_flags_text(struct nk_context*, const char*, int, unsigned int flags, unsigned int value); -NK_API int nk_checkbox_label(struct nk_context*, const char*, int *active); -NK_API int nk_checkbox_text(struct nk_context*, const char*, int, int *active); -NK_API int nk_checkbox_flags_label(struct nk_context*, const char*, unsigned int *flags, unsigned int value); -NK_API int nk_checkbox_flags_text(struct nk_context*, const char*, int, unsigned int *flags, unsigned int value); -/* ============================================================================= - * - * RADIO BUTTON - * - * ============================================================================= */ -NK_API int nk_radio_label(struct nk_context*, const char*, int *active); -NK_API int nk_radio_text(struct nk_context*, const char*, int, int *active); -NK_API int nk_option_label(struct nk_context*, const char*, int active); -NK_API int nk_option_text(struct nk_context*, const char*, int, int active); -/* ============================================================================= - * - * SELECTABLE - * - * ============================================================================= */ -NK_API int nk_selectable_label(struct nk_context*, const char*, nk_flags align, int *value); -NK_API int nk_selectable_text(struct nk_context*, const char*, int, nk_flags align, int *value); -NK_API int nk_selectable_image_label(struct nk_context*,struct nk_image, const char*, nk_flags align, int *value); -NK_API int nk_selectable_image_text(struct nk_context*,struct nk_image, const char*, int, nk_flags align, int *value); -NK_API int nk_selectable_symbol_label(struct nk_context*,enum nk_symbol_type, const char*, nk_flags align, int *value); -NK_API int nk_selectable_symbol_text(struct nk_context*,enum nk_symbol_type, const char*, int, nk_flags align, int *value); - -NK_API int nk_select_label(struct nk_context*, const char*, nk_flags align, int value); -NK_API int nk_select_text(struct nk_context*, const char*, int, nk_flags align, int value); -NK_API int nk_select_image_label(struct nk_context*, struct nk_image,const char*, nk_flags align, int value); -NK_API int nk_select_image_text(struct nk_context*, struct nk_image,const char*, int, nk_flags align, int value); -NK_API int nk_select_symbol_label(struct nk_context*,enum nk_symbol_type, const char*, nk_flags align, int value); -NK_API int nk_select_symbol_text(struct nk_context*,enum nk_symbol_type, const char*, int, nk_flags align, int value); - -/* ============================================================================= - * - * SLIDER - * - * ============================================================================= */ -NK_API float nk_slide_float(struct nk_context*, float min, float val, float max, float step); -NK_API int nk_slide_int(struct nk_context*, int min, int val, int max, int step); -NK_API int nk_slider_float(struct nk_context*, float min, float *val, float max, float step); -NK_API int nk_slider_int(struct nk_context*, int min, int *val, int max, int step); -/* ============================================================================= - * - * PROGRESSBAR - * - * ============================================================================= */ -NK_API int nk_progress(struct nk_context*, nk_size *cur, nk_size max, int modifyable); -NK_API nk_size nk_prog(struct nk_context*, nk_size cur, nk_size max, int modifyable); - -/* ============================================================================= - * - * COLOR PICKER - * - * ============================================================================= */ -NK_API struct nk_colorf nk_color_picker(struct nk_context*, struct nk_colorf, enum nk_color_format); -NK_API int nk_color_pick(struct nk_context*, struct nk_colorf*, enum nk_color_format); -/* ============================================================================= - * - * PROPERTIES - * - * ============================================================================= -/// ### Properties -/// Properties are the main value modification widgets in Nuklear. Changing a value -/// can be achieved by dragging, adding/removing incremental steps on button click -/// or by directly typing a number. -/// -/// #### Usage -/// Each property requires a unique name for identifaction that is also used for -/// displaying a label. If you want to use the same name multiple times make sure -/// add a '#' before your name. The '#' will not be shown but will generate a -/// unique ID. Each propery also takes in a minimum and maximum value. If you want -/// to make use of the complete number range of a type just use the provided -/// type limits from `limits.h`. For example `INT_MIN` and `INT_MAX` for -/// `nk_property_int` and `nk_propertyi`. In additional each property takes in -/// a increment value that will be added or subtracted if either the increment -/// decrement button is clicked. Finally there is a value for increment per pixel -/// dragged that is added or subtracted from the value. -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// int value = 0; -/// struct nk_context ctx; -/// nk_init_xxx(&ctx, ...); -/// while (1) { -/// // Input -/// Event evt; -/// nk_input_begin(&ctx); -/// while (GetEvent(&evt)) { -/// if (evt.type == MOUSE_MOVE) -/// nk_input_motion(&ctx, evt.motion.x, evt.motion.y); -/// else if (evt.type == [...]) { -/// nk_input_xxx(...); -/// } -/// } -/// nk_input_end(&ctx); -/// // -/// // Window -/// if (nk_begin_xxx(...) { -/// // Property -/// nk_layout_row_dynamic(...); -/// nk_property_int(ctx, "ID", INT_MIN, &value, INT_MAX, 1, 1); -/// } -/// nk_end(ctx); -/// // -/// // Draw -/// const struct nk_command *cmd = 0; -/// nk_foreach(cmd, &ctx) { -/// switch (cmd->type) { -/// case NK_COMMAND_LINE: -/// your_draw_line_function(...) -/// break; -/// case NK_COMMAND_RECT -/// your_draw_rect_function(...) -/// break; -/// case ...: -/// // [...] -/// } -// nk_clear(&ctx); -/// } -/// nk_free(&ctx); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// #### Reference -/// Function | Description -/// --------------------|------------------------------------------- -/// nk_property_int | Integer property directly modifing a passed in value -/// nk_property_float | Float property directly modifing a passed in value -/// nk_property_double | Double property directly modifing a passed in value -/// nk_propertyi | Integer property returning the modified int value -/// nk_propertyf | Float property returning the modified float value -/// nk_propertyd | Double property returning the modified double value -/// -*/ -/*/// #### nk_property_int -/// Integer property directly modifing a passed in value -/// !!! WARNING -/// To generate a unique property ID using the same label make sure to insert -/// a `#` at the beginning. It will not be shown but guarantees correct behavior. -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_property_int(struct nk_context *ctx, const char *name, int min, int *val, int max, int step, float inc_per_pixel); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// --------------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct after calling a layouting function -/// __name__ | String used both as a label as well as a unique identifier -/// __min__ | Minimum value not allowed to be underflown -/// __val__ | Integer pointer to be modified -/// __max__ | Maximum value not allowed to be overflown -/// __step__ | Increment added and subtracted on increment and decrement button -/// __inc_per_pixel__ | Value per pixel added or subtracted on dragging -*/ -NK_API void nk_property_int(struct nk_context*, const char *name, int min, int *val, int max, int step, float inc_per_pixel); -/*/// #### nk_property_float -/// Float property directly modifing a passed in value -/// !!! WARNING -/// To generate a unique property ID using the same label make sure to insert -/// a `#` at the beginning. It will not be shown but guarantees correct behavior. -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_property_float(struct nk_context *ctx, const char *name, float min, float *val, float max, float step, float inc_per_pixel); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// --------------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct after calling a layouting function -/// __name__ | String used both as a label as well as a unique identifier -/// __min__ | Minimum value not allowed to be underflown -/// __val__ | Float pointer to be modified -/// __max__ | Maximum value not allowed to be overflown -/// __step__ | Increment added and subtracted on increment and decrement button -/// __inc_per_pixel__ | Value per pixel added or subtracted on dragging -*/ -NK_API void nk_property_float(struct nk_context*, const char *name, float min, float *val, float max, float step, float inc_per_pixel); -/*/// #### nk_property_double -/// Double property directly modifing a passed in value -/// !!! WARNING -/// To generate a unique property ID using the same label make sure to insert -/// a `#` at the beginning. It will not be shown but guarantees correct behavior. -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// void nk_property_double(struct nk_context *ctx, const char *name, double min, double *val, double max, double step, double inc_per_pixel); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// --------------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct after calling a layouting function -/// __name__ | String used both as a label as well as a unique identifier -/// __min__ | Minimum value not allowed to be underflown -/// __val__ | Double pointer to be modified -/// __max__ | Maximum value not allowed to be overflown -/// __step__ | Increment added and subtracted on increment and decrement button -/// __inc_per_pixel__ | Value per pixel added or subtracted on dragging -*/ -NK_API void nk_property_double(struct nk_context*, const char *name, double min, double *val, double max, double step, float inc_per_pixel); -/*/// #### nk_propertyi -/// Integer property modifing a passed in value and returning the new value -/// !!! WARNING -/// To generate a unique property ID using the same label make sure to insert -/// a `#` at the beginning. It will not be shown but guarantees correct behavior. -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// int nk_propertyi(struct nk_context *ctx, const char *name, int min, int val, int max, int step, float inc_per_pixel); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// --------------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct after calling a layouting function -/// __name__ | String used both as a label as well as a unique identifier -/// __min__ | Minimum value not allowed to be underflown -/// __val__ | Current integer value to be modified and returned -/// __max__ | Maximum value not allowed to be overflown -/// __step__ | Increment added and subtracted on increment and decrement button -/// __inc_per_pixel__ | Value per pixel added or subtracted on dragging -/// -/// Returns the new modified integer value -*/ -NK_API int nk_propertyi(struct nk_context*, const char *name, int min, int val, int max, int step, float inc_per_pixel); -/*/// #### nk_propertyf -/// Float property modifing a passed in value and returning the new value -/// !!! WARNING -/// To generate a unique property ID using the same label make sure to insert -/// a `#` at the beginning. It will not be shown but guarantees correct behavior. -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// float nk_propertyf(struct nk_context *ctx, const char *name, float min, float val, float max, float step, float inc_per_pixel); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// --------------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct after calling a layouting function -/// __name__ | String used both as a label as well as a unique identifier -/// __min__ | Minimum value not allowed to be underflown -/// __val__ | Current float value to be modified and returned -/// __max__ | Maximum value not allowed to be overflown -/// __step__ | Increment added and subtracted on increment and decrement button -/// __inc_per_pixel__ | Value per pixel added or subtracted on dragging -/// -/// Returns the new modified float value -*/ -NK_API float nk_propertyf(struct nk_context*, const char *name, float min, float val, float max, float step, float inc_per_pixel); -/*/// #### nk_propertyd -/// Float property modifing a passed in value and returning the new value -/// !!! WARNING -/// To generate a unique property ID using the same label make sure to insert -/// a `#` at the beginning. It will not be shown but guarantees correct behavior. -/// -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c -/// float nk_propertyd(struct nk_context *ctx, const char *name, double min, double val, double max, double step, double inc_per_pixel); -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -/// -/// Parameter | Description -/// --------------------|----------------------------------------------------------- -/// __ctx__ | Must point to an previously initialized `nk_context` struct after calling a layouting function -/// __name__ | String used both as a label as well as a unique identifier -/// __min__ | Minimum value not allowed to be underflown -/// __val__ | Current double value to be modified and returned -/// __max__ | Maximum value not allowed to be overflown -/// __step__ | Increment added and subtracted on increment and decrement button -/// __inc_per_pixel__ | Value per pixel added or subtracted on dragging -/// -/// Returns the new modified double value -*/ -NK_API double nk_propertyd(struct nk_context*, const char *name, double min, double val, double max, double step, float inc_per_pixel); -/* ============================================================================= - * - * TEXT EDIT - * - * ============================================================================= */ -enum nk_edit_flags { - NK_EDIT_DEFAULT = 0, - NK_EDIT_READ_ONLY = NK_FLAG(0), - NK_EDIT_AUTO_SELECT = NK_FLAG(1), - NK_EDIT_SIG_ENTER = NK_FLAG(2), - NK_EDIT_ALLOW_TAB = NK_FLAG(3), - NK_EDIT_NO_CURSOR = NK_FLAG(4), - NK_EDIT_SELECTABLE = NK_FLAG(5), - NK_EDIT_CLIPBOARD = NK_FLAG(6), - NK_EDIT_CTRL_ENTER_NEWLINE = NK_FLAG(7), - NK_EDIT_NO_HORIZONTAL_SCROLL = NK_FLAG(8), - NK_EDIT_ALWAYS_INSERT_MODE = NK_FLAG(9), - NK_EDIT_MULTILINE = NK_FLAG(10), - NK_EDIT_GOTO_END_ON_ACTIVATE = NK_FLAG(11) -}; -enum nk_edit_types { - NK_EDIT_SIMPLE = NK_EDIT_ALWAYS_INSERT_MODE, - NK_EDIT_FIELD = NK_EDIT_SIMPLE|NK_EDIT_SELECTABLE|NK_EDIT_CLIPBOARD, - NK_EDIT_BOX = NK_EDIT_ALWAYS_INSERT_MODE| NK_EDIT_SELECTABLE| NK_EDIT_MULTILINE|NK_EDIT_ALLOW_TAB|NK_EDIT_CLIPBOARD, - NK_EDIT_EDITOR = NK_EDIT_SELECTABLE|NK_EDIT_MULTILINE|NK_EDIT_ALLOW_TAB| NK_EDIT_CLIPBOARD -}; -enum nk_edit_events { - NK_EDIT_ACTIVE = NK_FLAG(0), /* edit widget is currently being modified */ - NK_EDIT_INACTIVE = NK_FLAG(1), /* edit widget is not active and is not being modified */ - NK_EDIT_ACTIVATED = NK_FLAG(2), /* edit widget went from state inactive to state active */ - NK_EDIT_DEACTIVATED = NK_FLAG(3), /* edit widget went from state active to state inactive */ - NK_EDIT_COMMITED = NK_FLAG(4) /* edit widget has received an enter and lost focus */ -}; -NK_API nk_flags nk_edit_string(struct nk_context*, nk_flags, char *buffer, int *len, int max, nk_plugin_filter); -NK_API nk_flags nk_edit_string_zero_terminated(struct nk_context*, nk_flags, char *buffer, int max, nk_plugin_filter); -NK_API nk_flags nk_edit_buffer(struct nk_context*, nk_flags, struct nk_text_edit*, nk_plugin_filter); -NK_API void nk_edit_focus(struct nk_context*, nk_flags flags); -NK_API void nk_edit_unfocus(struct nk_context*); -/* ============================================================================= - * - * CHART - * - * ============================================================================= */ -NK_API int nk_chart_begin(struct nk_context*, enum nk_chart_type, int num, float min, float max); -NK_API int nk_chart_begin_colored(struct nk_context*, enum nk_chart_type, struct nk_color, struct nk_color active, int num, float min, float max); -NK_API void nk_chart_add_slot(struct nk_context *ctx, const enum nk_chart_type, int count, float min_value, float max_value); -NK_API void nk_chart_add_slot_colored(struct nk_context *ctx, const enum nk_chart_type, struct nk_color, struct nk_color active, int count, float min_value, float max_value); -NK_API nk_flags nk_chart_push(struct nk_context*, float); -NK_API nk_flags nk_chart_push_slot(struct nk_context*, float, int); -NK_API void nk_chart_end(struct nk_context*); -NK_API void nk_plot(struct nk_context*, enum nk_chart_type, const float *values, int count, int offset); -NK_API void nk_plot_function(struct nk_context*, enum nk_chart_type, void *userdata, float(*value_getter)(void* user, int index), int count, int offset); -/* ============================================================================= - * - * POPUP - * - * ============================================================================= */ -NK_API int nk_popup_begin(struct nk_context*, enum nk_popup_type, const char*, nk_flags, struct nk_rect bounds); -NK_API void nk_popup_close(struct nk_context*); -NK_API void nk_popup_end(struct nk_context*); -/* ============================================================================= - * - * COMBOBOX - * - * ============================================================================= */ -NK_API int nk_combo(struct nk_context*, const char **items, int count, int selected, int item_height, struct nk_vec2 size); -NK_API int nk_combo_separator(struct nk_context*, const char *items_separated_by_separator, int separator, int selected, int count, int item_height, struct nk_vec2 size); -NK_API int nk_combo_string(struct nk_context*, const char *items_separated_by_zeros, int selected, int count, int item_height, struct nk_vec2 size); -NK_API int nk_combo_callback(struct nk_context*, void(*item_getter)(void*, int, const char**), void *userdata, int selected, int count, int item_height, struct nk_vec2 size); -NK_API void nk_combobox(struct nk_context*, const char **items, int count, int *selected, int item_height, struct nk_vec2 size); -NK_API void nk_combobox_string(struct nk_context*, const char *items_separated_by_zeros, int *selected, int count, int item_height, struct nk_vec2 size); -NK_API void nk_combobox_separator(struct nk_context*, const char *items_separated_by_separator, int separator,int *selected, int count, int item_height, struct nk_vec2 size); -NK_API void nk_combobox_callback(struct nk_context*, void(*item_getter)(void*, int, const char**), void*, int *selected, int count, int item_height, struct nk_vec2 size); -/* ============================================================================= - * - * ABSTRACT COMBOBOX - * - * ============================================================================= */ -NK_API int nk_combo_begin_text(struct nk_context*, const char *selected, int, struct nk_vec2 size); -NK_API int nk_combo_begin_label(struct nk_context*, const char *selected, struct nk_vec2 size); -NK_API int nk_combo_begin_color(struct nk_context*, struct nk_color color, struct nk_vec2 size); -NK_API int nk_combo_begin_symbol(struct nk_context*, enum nk_symbol_type, struct nk_vec2 size); -NK_API int nk_combo_begin_symbol_label(struct nk_context*, const char *selected, enum nk_symbol_type, struct nk_vec2 size); -NK_API int nk_combo_begin_symbol_text(struct nk_context*, const char *selected, int, enum nk_symbol_type, struct nk_vec2 size); -NK_API int nk_combo_begin_image(struct nk_context*, struct nk_image img, struct nk_vec2 size); -NK_API int nk_combo_begin_image_label(struct nk_context*, const char *selected, struct nk_image, struct nk_vec2 size); -NK_API int nk_combo_begin_image_text(struct nk_context*, const char *selected, int, struct nk_image, struct nk_vec2 size); -NK_API int nk_combo_item_label(struct nk_context*, const char*, nk_flags alignment); -NK_API int nk_combo_item_text(struct nk_context*, const char*,int, nk_flags alignment); -NK_API int nk_combo_item_image_label(struct nk_context*, struct nk_image, const char*, nk_flags alignment); -NK_API int nk_combo_item_image_text(struct nk_context*, struct nk_image, const char*, int,nk_flags alignment); -NK_API int nk_combo_item_symbol_label(struct nk_context*, enum nk_symbol_type, const char*, nk_flags alignment); -NK_API int nk_combo_item_symbol_text(struct nk_context*, enum nk_symbol_type, const char*, int, nk_flags alignment); -NK_API void nk_combo_close(struct nk_context*); -NK_API void nk_combo_end(struct nk_context*); -/* ============================================================================= - * - * CONTEXTUAL - * - * ============================================================================= */ -NK_API int nk_contextual_begin(struct nk_context*, nk_flags, struct nk_vec2, struct nk_rect trigger_bounds); -NK_API int nk_contextual_item_text(struct nk_context*, const char*, int,nk_flags align); -NK_API int nk_contextual_item_label(struct nk_context*, const char*, nk_flags align); -NK_API int nk_contextual_item_image_label(struct nk_context*, struct nk_image, const char*, nk_flags alignment); -NK_API int nk_contextual_item_image_text(struct nk_context*, struct nk_image, const char*, int len, nk_flags alignment); -NK_API int nk_contextual_item_symbol_label(struct nk_context*, enum nk_symbol_type, const char*, nk_flags alignment); -NK_API int nk_contextual_item_symbol_text(struct nk_context*, enum nk_symbol_type, const char*, int, nk_flags alignment); -NK_API void nk_contextual_close(struct nk_context*); -NK_API void nk_contextual_end(struct nk_context*); -/* ============================================================================= - * - * TOOLTIP - * - * ============================================================================= */ -NK_API void nk_tooltip(struct nk_context*, const char*); -#ifdef NK_INCLUDE_STANDARD_VARARGS -NK_API void nk_tooltipf(struct nk_context*, NK_PRINTF_FORMAT_STRING const char*, ...) NK_PRINTF_VARARG_FUNC(2); -NK_API void nk_tooltipfv(struct nk_context*, NK_PRINTF_FORMAT_STRING const char*, va_list) NK_PRINTF_VALIST_FUNC(2); -#endif -NK_API int nk_tooltip_begin(struct nk_context*, float width); -NK_API void nk_tooltip_end(struct nk_context*); -/* ============================================================================= - * - * MENU - * - * ============================================================================= */ -NK_API void nk_menubar_begin(struct nk_context*); -NK_API void nk_menubar_end(struct nk_context*); -NK_API int nk_menu_begin_text(struct nk_context*, const char* title, int title_len, nk_flags align, struct nk_vec2 size); -NK_API int nk_menu_begin_label(struct nk_context*, const char*, nk_flags align, struct nk_vec2 size); -NK_API int nk_menu_begin_image(struct nk_context*, const char*, struct nk_image, struct nk_vec2 size); -NK_API int nk_menu_begin_image_text(struct nk_context*, const char*, int,nk_flags align,struct nk_image, struct nk_vec2 size); -NK_API int nk_menu_begin_image_label(struct nk_context*, const char*, nk_flags align,struct nk_image, struct nk_vec2 size); -NK_API int nk_menu_begin_symbol(struct nk_context*, const char*, enum nk_symbol_type, struct nk_vec2 size); -NK_API int nk_menu_begin_symbol_text(struct nk_context*, const char*, int,nk_flags align,enum nk_symbol_type, struct nk_vec2 size); -NK_API int nk_menu_begin_symbol_label(struct nk_context*, const char*, nk_flags align,enum nk_symbol_type, struct nk_vec2 size); -NK_API int nk_menu_item_text(struct nk_context*, const char*, int,nk_flags align); -NK_API int nk_menu_item_label(struct nk_context*, const char*, nk_flags alignment); -NK_API int nk_menu_item_image_label(struct nk_context*, struct nk_image, const char*, nk_flags alignment); -NK_API int nk_menu_item_image_text(struct nk_context*, struct nk_image, const char*, int len, nk_flags alignment); -NK_API int nk_menu_item_symbol_text(struct nk_context*, enum nk_symbol_type, const char*, int, nk_flags alignment); -NK_API int nk_menu_item_symbol_label(struct nk_context*, enum nk_symbol_type, const char*, nk_flags alignment); -NK_API void nk_menu_close(struct nk_context*); -NK_API void nk_menu_end(struct nk_context*); -/* ============================================================================= - * - * STYLE - * - * ============================================================================= */ -enum nk_style_colors { - NK_COLOR_TEXT, - NK_COLOR_WINDOW, - NK_COLOR_HEADER, - NK_COLOR_BORDER, - NK_COLOR_BUTTON, - NK_COLOR_BUTTON_HOVER, - NK_COLOR_BUTTON_ACTIVE, - NK_COLOR_TOGGLE, - NK_COLOR_TOGGLE_HOVER, - NK_COLOR_TOGGLE_CURSOR, - NK_COLOR_SELECT, - NK_COLOR_SELECT_ACTIVE, - NK_COLOR_SLIDER, - NK_COLOR_SLIDER_CURSOR, - NK_COLOR_SLIDER_CURSOR_HOVER, - NK_COLOR_SLIDER_CURSOR_ACTIVE, - NK_COLOR_PROPERTY, - NK_COLOR_EDIT, - NK_COLOR_EDIT_CURSOR, - NK_COLOR_COMBO, - NK_COLOR_CHART, - NK_COLOR_CHART_COLOR, - NK_COLOR_CHART_COLOR_HIGHLIGHT, - NK_COLOR_SCROLLBAR, - NK_COLOR_SCROLLBAR_CURSOR, - NK_COLOR_SCROLLBAR_CURSOR_HOVER, - NK_COLOR_SCROLLBAR_CURSOR_ACTIVE, - NK_COLOR_TAB_HEADER, - NK_COLOR_COUNT -}; -enum nk_style_cursor { - NK_CURSOR_ARROW, - NK_CURSOR_TEXT, - NK_CURSOR_MOVE, - NK_CURSOR_RESIZE_VERTICAL, - NK_CURSOR_RESIZE_HORIZONTAL, - NK_CURSOR_RESIZE_TOP_LEFT_DOWN_RIGHT, - NK_CURSOR_RESIZE_TOP_RIGHT_DOWN_LEFT, - NK_CURSOR_COUNT -}; -NK_API void nk_style_default(struct nk_context*); -NK_API void nk_style_from_table(struct nk_context*, const struct nk_color*); -NK_API void nk_style_load_cursor(struct nk_context*, enum nk_style_cursor, const struct nk_cursor*); -NK_API void nk_style_load_all_cursors(struct nk_context*, struct nk_cursor*); -NK_API const char* nk_style_get_color_by_name(enum nk_style_colors); -NK_API void nk_style_set_font(struct nk_context*, const struct nk_user_font*); -NK_API int nk_style_set_cursor(struct nk_context*, enum nk_style_cursor); -NK_API void nk_style_show_cursor(struct nk_context*); -NK_API void nk_style_hide_cursor(struct nk_context*); - -NK_API int nk_style_push_font(struct nk_context*, const struct nk_user_font*); -NK_API int nk_style_push_float(struct nk_context*, float*, float); -NK_API int nk_style_push_vec2(struct nk_context*, struct nk_vec2*, struct nk_vec2); -NK_API int nk_style_push_style_item(struct nk_context*, struct nk_style_item*, struct nk_style_item); -NK_API int nk_style_push_flags(struct nk_context*, nk_flags*, nk_flags); -NK_API int nk_style_push_color(struct nk_context*, struct nk_color*, struct nk_color); - -NK_API int nk_style_pop_font(struct nk_context*); -NK_API int nk_style_pop_float(struct nk_context*); -NK_API int nk_style_pop_vec2(struct nk_context*); -NK_API int nk_style_pop_style_item(struct nk_context*); -NK_API int nk_style_pop_flags(struct nk_context*); -NK_API int nk_style_pop_color(struct nk_context*); -/* ============================================================================= - * - * COLOR - * - * ============================================================================= */ -NK_API struct nk_color nk_rgb(int r, int g, int b); -NK_API struct nk_color nk_rgb_iv(const int *rgb); -NK_API struct nk_color nk_rgb_bv(const nk_byte* rgb); -NK_API struct nk_color nk_rgb_f(float r, float g, float b); -NK_API struct nk_color nk_rgb_fv(const float *rgb); -NK_API struct nk_color nk_rgb_cf(struct nk_colorf c); -NK_API struct nk_color nk_rgb_hex(const char *rgb); - -NK_API struct nk_color nk_rgba(int r, int g, int b, int a); -NK_API struct nk_color nk_rgba_u32(nk_uint); -NK_API struct nk_color nk_rgba_iv(const int *rgba); -NK_API struct nk_color nk_rgba_bv(const nk_byte *rgba); -NK_API struct nk_color nk_rgba_f(float r, float g, float b, float a); -NK_API struct nk_color nk_rgba_fv(const float *rgba); -NK_API struct nk_color nk_rgba_cf(struct nk_colorf c); -NK_API struct nk_color nk_rgba_hex(const char *rgb); - -NK_API struct nk_colorf nk_hsva_colorf(float h, float s, float v, float a); -NK_API struct nk_colorf nk_hsva_colorfv(float *c); -NK_API void nk_colorf_hsva_f(float *out_h, float *out_s, float *out_v, float *out_a, struct nk_colorf in); -NK_API void nk_colorf_hsva_fv(float *hsva, struct nk_colorf in); - -NK_API struct nk_color nk_hsv(int h, int s, int v); -NK_API struct nk_color nk_hsv_iv(const int *hsv); -NK_API struct nk_color nk_hsv_bv(const nk_byte *hsv); -NK_API struct nk_color nk_hsv_f(float h, float s, float v); -NK_API struct nk_color nk_hsv_fv(const float *hsv); - -NK_API struct nk_color nk_hsva(int h, int s, int v, int a); -NK_API struct nk_color nk_hsva_iv(const int *hsva); -NK_API struct nk_color nk_hsva_bv(const nk_byte *hsva); -NK_API struct nk_color nk_hsva_f(float h, float s, float v, float a); -NK_API struct nk_color nk_hsva_fv(const float *hsva); - -/* color (conversion nuklear --> user) */ -NK_API void nk_color_f(float *r, float *g, float *b, float *a, struct nk_color); -NK_API void nk_color_fv(float *rgba_out, struct nk_color); -NK_API struct nk_colorf nk_color_cf(struct nk_color); -NK_API void nk_color_d(double *r, double *g, double *b, double *a, struct nk_color); -NK_API void nk_color_dv(double *rgba_out, struct nk_color); - -NK_API nk_uint nk_color_u32(struct nk_color); -NK_API void nk_color_hex_rgba(char *output, struct nk_color); -NK_API void nk_color_hex_rgb(char *output, struct nk_color); - -NK_API void nk_color_hsv_i(int *out_h, int *out_s, int *out_v, struct nk_color); -NK_API void nk_color_hsv_b(nk_byte *out_h, nk_byte *out_s, nk_byte *out_v, struct nk_color); -NK_API void nk_color_hsv_iv(int *hsv_out, struct nk_color); -NK_API void nk_color_hsv_bv(nk_byte *hsv_out, struct nk_color); -NK_API void nk_color_hsv_f(float *out_h, float *out_s, float *out_v, struct nk_color); -NK_API void nk_color_hsv_fv(float *hsv_out, struct nk_color); - -NK_API void nk_color_hsva_i(int *h, int *s, int *v, int *a, struct nk_color); -NK_API void nk_color_hsva_b(nk_byte *h, nk_byte *s, nk_byte *v, nk_byte *a, struct nk_color); -NK_API void nk_color_hsva_iv(int *hsva_out, struct nk_color); -NK_API void nk_color_hsva_bv(nk_byte *hsva_out, struct nk_color); -NK_API void nk_color_hsva_f(float *out_h, float *out_s, float *out_v, float *out_a, struct nk_color); -NK_API void nk_color_hsva_fv(float *hsva_out, struct nk_color); -/* ============================================================================= - * - * IMAGE - * - * ============================================================================= */ -NK_API nk_handle nk_handle_ptr(void*); -NK_API nk_handle nk_handle_id(int); -NK_API struct nk_image nk_image_handle(nk_handle); -NK_API struct nk_image nk_image_ptr(void*); -NK_API struct nk_image nk_image_id(int); -NK_API int nk_image_is_subimage(const struct nk_image* img); -NK_API struct nk_image nk_subimage_ptr(void*, unsigned short w, unsigned short h, struct nk_rect sub_region); -NK_API struct nk_image nk_subimage_id(int, unsigned short w, unsigned short h, struct nk_rect sub_region); -NK_API struct nk_image nk_subimage_handle(nk_handle, unsigned short w, unsigned short h, struct nk_rect sub_region); -/* ============================================================================= - * - * MATH - * - * ============================================================================= */ -NK_API nk_hash nk_murmur_hash(const void *key, int len, nk_hash seed); -NK_API void nk_triangle_from_direction(struct nk_vec2 *result, struct nk_rect r, float pad_x, float pad_y, enum nk_heading); - -NK_API struct nk_vec2 nk_vec2(float x, float y); -NK_API struct nk_vec2 nk_vec2i(int x, int y); -NK_API struct nk_vec2 nk_vec2v(const float *xy); -NK_API struct nk_vec2 nk_vec2iv(const int *xy); - -NK_API struct nk_rect nk_get_null_rect(void); -NK_API struct nk_rect nk_rect(float x, float y, float w, float h); -NK_API struct nk_rect nk_recti(int x, int y, int w, int h); -NK_API struct nk_rect nk_recta(struct nk_vec2 pos, struct nk_vec2 size); -NK_API struct nk_rect nk_rectv(const float *xywh); -NK_API struct nk_rect nk_rectiv(const int *xywh); -NK_API struct nk_vec2 nk_rect_pos(struct nk_rect); -NK_API struct nk_vec2 nk_rect_size(struct nk_rect); -/* ============================================================================= - * - * STRING - * - * ============================================================================= */ -NK_API int nk_strlen(const char *str); -NK_API int nk_stricmp(const char *s1, const char *s2); -NK_API int nk_stricmpn(const char *s1, const char *s2, int n); -NK_API int nk_strtoi(const char *str, const char **endptr); -NK_API float nk_strtof(const char *str, const char **endptr); -NK_API double nk_strtod(const char *str, const char **endptr); -NK_API int nk_strfilter(const char *text, const char *regexp); -NK_API int nk_strmatch_fuzzy_string(char const *str, char const *pattern, int *out_score); -NK_API int nk_strmatch_fuzzy_text(const char *txt, int txt_len, const char *pattern, int *out_score); -/* ============================================================================= - * - * UTF-8 - * - * ============================================================================= */ -NK_API int nk_utf_decode(const char*, nk_rune*, int); -NK_API int nk_utf_encode(nk_rune, char*, int); -NK_API int nk_utf_len(const char*, int byte_len); -NK_API const char* nk_utf_at(const char *buffer, int length, int index, nk_rune *unicode, int *len); -/* =============================================================== - * - * FONT - * - * ===============================================================*/ -/* Font handling in this library was designed to be quite customizable and lets - you decide what you want to use and what you want to provide. There are three - different ways to use the font atlas. The first two will use your font - handling scheme and only requires essential data to run nuklear. The next - slightly more advanced features is font handling with vertex buffer output. - Finally the most complex API wise is using nuklear's font baking API. - - 1.) Using your own implementation without vertex buffer output - -------------------------------------------------------------- - So first up the easiest way to do font handling is by just providing a - `nk_user_font` struct which only requires the height in pixel of the used - font and a callback to calculate the width of a string. This way of handling - fonts is best fitted for using the normal draw shape command API where you - do all the text drawing yourself and the library does not require any kind - of deeper knowledge about which font handling mechanism you use. - IMPORTANT: the `nk_user_font` pointer provided to nuklear has to persist - over the complete life time! I know this sucks but it is currently the only - way to switch between fonts. - - float your_text_width_calculation(nk_handle handle, float height, const char *text, int len) - { - your_font_type *type = handle.ptr; - float text_width = ...; - return text_width; - } - - struct nk_user_font font; - font.userdata.ptr = &your_font_class_or_struct; - font.height = your_font_height; - font.width = your_text_width_calculation; - - struct nk_context ctx; - nk_init_default(&ctx, &font); - - 2.) Using your own implementation with vertex buffer output - -------------------------------------------------------------- - While the first approach works fine if you don't want to use the optional - vertex buffer output it is not enough if you do. To get font handling working - for these cases you have to provide two additional parameters inside the - `nk_user_font`. First a texture atlas handle used to draw text as subimages - of a bigger font atlas texture and a callback to query a character's glyph - information (offset, size, ...). So it is still possible to provide your own - font and use the vertex buffer output. - - float your_text_width_calculation(nk_handle handle, float height, const char *text, int len) - { - your_font_type *type = handle.ptr; - float text_width = ...; - return text_width; - } - void query_your_font_glyph(nk_handle handle, float font_height, struct nk_user_font_glyph *glyph, nk_rune codepoint, nk_rune next_codepoint) - { - your_font_type *type = handle.ptr; - glyph.width = ...; - glyph.height = ...; - glyph.xadvance = ...; - glyph.uv[0].x = ...; - glyph.uv[0].y = ...; - glyph.uv[1].x = ...; - glyph.uv[1].y = ...; - glyph.offset.x = ...; - glyph.offset.y = ...; - } - - struct nk_user_font font; - font.userdata.ptr = &your_font_class_or_struct; - font.height = your_font_height; - font.width = your_text_width_calculation; - font.query = query_your_font_glyph; - font.texture.id = your_font_texture; - - struct nk_context ctx; - nk_init_default(&ctx, &font); - - 3.) Nuklear font baker - ------------------------------------ - The final approach if you do not have a font handling functionality or don't - want to use it in this library is by using the optional font baker. - The font baker APIs can be used to create a font plus font atlas texture - and can be used with or without the vertex buffer output. - - It still uses the `nk_user_font` struct and the two different approaches - previously stated still work. The font baker is not located inside - `nk_context` like all other systems since it can be understood as more of - an extension to nuklear and does not really depend on any `nk_context` state. - - Font baker need to be initialized first by one of the nk_font_atlas_init_xxx - functions. If you don't care about memory just call the default version - `nk_font_atlas_init_default` which will allocate all memory from the standard library. - If you want to control memory allocation but you don't care if the allocated - memory is temporary and therefore can be freed directly after the baking process - is over or permanent you can call `nk_font_atlas_init`. - - After successfully initializing the font baker you can add Truetype(.ttf) fonts from - different sources like memory or from file by calling one of the `nk_font_atlas_add_xxx`. - functions. Adding font will permanently store each font, font config and ttf memory block(!) - inside the font atlas and allows to reuse the font atlas. If you don't want to reuse - the font baker by for example adding additional fonts you can call - `nk_font_atlas_cleanup` after the baking process is over (after calling nk_font_atlas_end). - - As soon as you added all fonts you wanted you can now start the baking process - for every selected glyph to image by calling `nk_font_atlas_bake`. - The baking process returns image memory, width and height which can be used to - either create your own image object or upload it to any graphics library. - No matter which case you finally have to call `nk_font_atlas_end` which - will free all temporary memory including the font atlas image so make sure - you created our texture beforehand. `nk_font_atlas_end` requires a handle - to your font texture or object and optionally fills a `struct nk_draw_null_texture` - which can be used for the optional vertex output. If you don't want it just - set the argument to `NULL`. - - At this point you are done and if you don't want to reuse the font atlas you - can call `nk_font_atlas_cleanup` to free all truetype blobs and configuration - memory. Finally if you don't use the font atlas and any of it's fonts anymore - you need to call `nk_font_atlas_clear` to free all memory still being used. - - struct nk_font_atlas atlas; - nk_font_atlas_init_default(&atlas); - nk_font_atlas_begin(&atlas); - nk_font *font = nk_font_atlas_add_from_file(&atlas, "Path/To/Your/TTF_Font.ttf", 13, 0); - nk_font *font2 = nk_font_atlas_add_from_file(&atlas, "Path/To/Your/TTF_Font2.ttf", 16, 0); - const void* img = nk_font_atlas_bake(&atlas, &img_width, &img_height, NK_FONT_ATLAS_RGBA32); - nk_font_atlas_end(&atlas, nk_handle_id(texture), 0); - - struct nk_context ctx; - nk_init_default(&ctx, &font->handle); - while (1) { - - } - nk_font_atlas_clear(&atlas); - - The font baker API is probably the most complex API inside this library and - I would suggest reading some of my examples `example/` to get a grip on how - to use the font atlas. There are a number of details I left out. For example - how to merge fonts, configure a font with `nk_font_config` to use other languages, - use another texture coordinate format and a lot more: - - struct nk_font_config cfg = nk_font_config(font_pixel_height); - cfg.merge_mode = nk_false or nk_true; - cfg.range = nk_font_korean_glyph_ranges(); - cfg.coord_type = NK_COORD_PIXEL; - nk_font *font = nk_font_atlas_add_from_file(&atlas, "Path/To/Your/TTF_Font.ttf", 13, &cfg); - -*/ -struct nk_user_font_glyph; -typedef float(*nk_text_width_f)(nk_handle, float h, const char*, int len); -typedef void(*nk_query_font_glyph_f)(nk_handle handle, float font_height, - struct nk_user_font_glyph *glyph, - nk_rune codepoint, nk_rune next_codepoint); - -#if defined(NK_INCLUDE_VERTEX_BUFFER_OUTPUT) || defined(NK_INCLUDE_SOFTWARE_FONT) -struct nk_user_font_glyph { - struct nk_vec2 uv[2]; - /* texture coordinates */ - struct nk_vec2 offset; - /* offset between top left and glyph */ - float width, height; - /* size of the glyph */ - float xadvance; - /* offset to the next glyph */ -}; -#endif - -struct nk_user_font { - nk_handle userdata; - /* user provided font handle */ - float height; - /* max height of the font */ - nk_text_width_f width; - /* font string width in pixel callback */ -#ifdef NK_INCLUDE_VERTEX_BUFFER_OUTPUT - nk_query_font_glyph_f query; - /* font glyph callback to query drawing info */ - nk_handle texture; - /* texture handle to the used font atlas or texture */ -#endif -}; - -#ifdef NK_INCLUDE_FONT_BAKING -enum nk_font_coord_type { - NK_COORD_UV, /* texture coordinates inside font glyphs are clamped between 0-1 */ - NK_COORD_PIXEL /* texture coordinates inside font glyphs are in absolute pixel */ -}; - -struct nk_font; -struct nk_baked_font { - float height; - /* height of the font */ - float ascent, descent; - /* font glyphs ascent and descent */ - nk_rune glyph_offset; - /* glyph array offset inside the font glyph baking output array */ - nk_rune glyph_count; - /* number of glyphs of this font inside the glyph baking array output */ - const nk_rune *ranges; - /* font codepoint ranges as pairs of (from/to) and 0 as last element */ -}; - -struct nk_font_config { - struct nk_font_config *next; - /* NOTE: only used internally */ - void *ttf_blob; - /* pointer to loaded TTF file memory block. - * NOTE: not needed for nk_font_atlas_add_from_memory and nk_font_atlas_add_from_file. */ - nk_size ttf_size; - /* size of the loaded TTF file memory block - * NOTE: not needed for nk_font_atlas_add_from_memory and nk_font_atlas_add_from_file. */ - - unsigned char ttf_data_owned_by_atlas; - /* used inside font atlas: default to: 0*/ - unsigned char merge_mode; - /* merges this font into the last font */ - unsigned char pixel_snap; - /* align every character to pixel boundary (if true set oversample (1,1)) */ - unsigned char oversample_v, oversample_h; - /* rasterize at hight quality for sub-pixel position */ - unsigned char padding[3]; - - float size; - /* baked pixel height of the font */ - enum nk_font_coord_type coord_type; - /* texture coordinate format with either pixel or UV coordinates */ - struct nk_vec2 spacing; - /* extra pixel spacing between glyphs */ - const nk_rune *range; - /* list of unicode ranges (2 values per range, zero terminated) */ - struct nk_baked_font *font; - /* font to setup in the baking process: NOTE: not needed for font atlas */ - nk_rune fallback_glyph; - /* fallback glyph to use if a given rune is not found */ - struct nk_font_config *n; - struct nk_font_config *p; -}; - -struct nk_font_glyph { - nk_rune codepoint; - float xadvance; - float x0, y0, x1, y1, w, h; - float u0, v0, u1, v1; -}; - -struct nk_font { - struct nk_font *next; - struct nk_user_font handle; - struct nk_baked_font info; - float scale; - struct nk_font_glyph *glyphs; - const struct nk_font_glyph *fallback; - nk_rune fallback_codepoint; - nk_handle texture; - struct nk_font_config *config; -}; - -enum nk_font_atlas_format { - NK_FONT_ATLAS_ALPHA8, - NK_FONT_ATLAS_RGBA32 -}; - -struct nk_font_atlas { - void *pixel; - int tex_width; - int tex_height; - - struct nk_allocator permanent; - struct nk_allocator temporary; - - struct nk_recti custom; - struct nk_cursor cursors[NK_CURSOR_COUNT]; - - int glyph_count; - struct nk_font_glyph *glyphs; - struct nk_font *default_font; - struct nk_font *fonts; - struct nk_font_config *config; - int font_num; -}; - -/* some language glyph codepoint ranges */ -NK_API const nk_rune *nk_font_default_glyph_ranges(void); -NK_API const nk_rune *nk_font_chinese_glyph_ranges(void); -NK_API const nk_rune *nk_font_cyrillic_glyph_ranges(void); -NK_API const nk_rune *nk_font_korean_glyph_ranges(void); - -#ifdef NK_INCLUDE_DEFAULT_ALLOCATOR -NK_API void nk_font_atlas_init_default(struct nk_font_atlas*); -#endif -NK_API void nk_font_atlas_init(struct nk_font_atlas*, struct nk_allocator*); -NK_API void nk_font_atlas_init_custom(struct nk_font_atlas*, struct nk_allocator *persistent, struct nk_allocator *transient); -NK_API void nk_font_atlas_begin(struct nk_font_atlas*); -NK_API struct nk_font_config nk_font_config(float pixel_height); -NK_API struct nk_font *nk_font_atlas_add(struct nk_font_atlas*, const struct nk_font_config*); -#ifdef NK_INCLUDE_DEFAULT_FONT -NK_API struct nk_font* nk_font_atlas_add_default(struct nk_font_atlas*, float height, const struct nk_font_config*); -#endif -NK_API struct nk_font* nk_font_atlas_add_from_memory(struct nk_font_atlas *atlas, void *memory, nk_size size, float height, const struct nk_font_config *config); -#ifdef NK_INCLUDE_STANDARD_IO -NK_API struct nk_font* nk_font_atlas_add_from_file(struct nk_font_atlas *atlas, const char *file_path, float height, const struct nk_font_config*); -#endif -NK_API struct nk_font *nk_font_atlas_add_compressed(struct nk_font_atlas*, void *memory, nk_size size, float height, const struct nk_font_config*); -NK_API struct nk_font* nk_font_atlas_add_compressed_base85(struct nk_font_atlas*, const char *data, float height, const struct nk_font_config *config); -NK_API const void* nk_font_atlas_bake(struct nk_font_atlas*, int *width, int *height, enum nk_font_atlas_format); -NK_API void nk_font_atlas_end(struct nk_font_atlas*, nk_handle tex, struct nk_draw_null_texture*); -NK_API const struct nk_font_glyph* nk_font_find_glyph(struct nk_font*, nk_rune unicode); -NK_API void nk_font_atlas_cleanup(struct nk_font_atlas *atlas); -NK_API void nk_font_atlas_clear(struct nk_font_atlas*); - -#endif - -/* ============================================================== - * - * MEMORY BUFFER - * - * ===============================================================*/ -/* A basic (double)-buffer with linear allocation and resetting as only - freeing policy. The buffer's main purpose is to control all memory management - inside the GUI toolkit and still leave memory control as much as possible in - the hand of the user while also making sure the library is easy to use if - not as much control is needed. - In general all memory inside this library can be provided from the user in - three different ways. - - The first way and the one providing most control is by just passing a fixed - size memory block. In this case all control lies in the hand of the user - since he can exactly control where the memory comes from and how much memory - the library should consume. Of course using the fixed size API removes the - ability to automatically resize a buffer if not enough memory is provided so - you have to take over the resizing. While being a fixed sized buffer sounds - quite limiting, it is very effective in this library since the actual memory - consumption is quite stable and has a fixed upper bound for a lot of cases. - - If you don't want to think about how much memory the library should allocate - at all time or have a very dynamic UI with unpredictable memory consumption - habits but still want control over memory allocation you can use the dynamic - allocator based API. The allocator consists of two callbacks for allocating - and freeing memory and optional userdata so you can plugin your own allocator. - - The final and easiest way can be used by defining - NK_INCLUDE_DEFAULT_ALLOCATOR which uses the standard library memory - allocation functions malloc and free and takes over complete control over - memory in this library. -*/ -struct nk_memory_status { - void *memory; - unsigned int type; - nk_size size; - nk_size allocated; - nk_size needed; - nk_size calls; -}; - -enum nk_allocation_type { - NK_BUFFER_FIXED, - NK_BUFFER_DYNAMIC -}; - -enum nk_buffer_allocation_type { - NK_BUFFER_FRONT, - NK_BUFFER_BACK, - NK_BUFFER_MAX -}; - -struct nk_buffer_marker { - int active; - nk_size offset; -}; - -struct nk_memory {void *ptr;nk_size size;}; -struct nk_buffer { - struct nk_buffer_marker marker[NK_BUFFER_MAX]; - /* buffer marker to free a buffer to a certain offset */ - struct nk_allocator pool; - /* allocator callback for dynamic buffers */ - enum nk_allocation_type type; - /* memory management type */ - struct nk_memory memory; - /* memory and size of the current memory block */ - float grow_factor; - /* growing factor for dynamic memory management */ - nk_size allocated; - /* total amount of memory allocated */ - nk_size needed; - /* totally consumed memory given that enough memory is present */ - nk_size calls; - /* number of allocation calls */ - nk_size size; - /* current size of the buffer */ -}; - -#ifdef NK_INCLUDE_DEFAULT_ALLOCATOR -NK_API void nk_buffer_init_default(struct nk_buffer*); -#endif -NK_API void nk_buffer_init(struct nk_buffer*, const struct nk_allocator*, nk_size size); -NK_API void nk_buffer_init_fixed(struct nk_buffer*, void *memory, nk_size size); -NK_API void nk_buffer_info(struct nk_memory_status*, struct nk_buffer*); -NK_API void nk_buffer_push(struct nk_buffer*, enum nk_buffer_allocation_type type, const void *memory, nk_size size, nk_size align); -NK_API void nk_buffer_mark(struct nk_buffer*, enum nk_buffer_allocation_type type); -NK_API void nk_buffer_reset(struct nk_buffer*, enum nk_buffer_allocation_type type); -NK_API void nk_buffer_clear(struct nk_buffer*); -NK_API void nk_buffer_free(struct nk_buffer*); -NK_API void *nk_buffer_memory(struct nk_buffer*); -NK_API const void *nk_buffer_memory_const(const struct nk_buffer*); -NK_API nk_size nk_buffer_total(struct nk_buffer*); - -/* ============================================================== - * - * STRING - * - * ===============================================================*/ -/* Basic string buffer which is only used in context with the text editor - * to manage and manipulate dynamic or fixed size string content. This is _NOT_ - * the default string handling method. The only instance you should have any contact - * with this API is if you interact with an `nk_text_edit` object inside one of the - * copy and paste functions and even there only for more advanced cases. */ -struct nk_str { - struct nk_buffer buffer; - int len; /* in codepoints/runes/glyphs */ -}; - -#ifdef NK_INCLUDE_DEFAULT_ALLOCATOR -NK_API void nk_str_init_default(struct nk_str*); -#endif -NK_API void nk_str_init(struct nk_str*, const struct nk_allocator*, nk_size size); -NK_API void nk_str_init_fixed(struct nk_str*, void *memory, nk_size size); -NK_API void nk_str_clear(struct nk_str*); -NK_API void nk_str_free(struct nk_str*); - -NK_API int nk_str_append_text_char(struct nk_str*, const char*, int); -NK_API int nk_str_append_str_char(struct nk_str*, const char*); -NK_API int nk_str_append_text_utf8(struct nk_str*, const char*, int); -NK_API int nk_str_append_str_utf8(struct nk_str*, const char*); -NK_API int nk_str_append_text_runes(struct nk_str*, const nk_rune*, int); -NK_API int nk_str_append_str_runes(struct nk_str*, const nk_rune*); - -NK_API int nk_str_insert_at_char(struct nk_str*, int pos, const char*, int); -NK_API int nk_str_insert_at_rune(struct nk_str*, int pos, const char*, int); - -NK_API int nk_str_insert_text_char(struct nk_str*, int pos, const char*, int); -NK_API int nk_str_insert_str_char(struct nk_str*, int pos, const char*); -NK_API int nk_str_insert_text_utf8(struct nk_str*, int pos, const char*, int); -NK_API int nk_str_insert_str_utf8(struct nk_str*, int pos, const char*); -NK_API int nk_str_insert_text_runes(struct nk_str*, int pos, const nk_rune*, int); -NK_API int nk_str_insert_str_runes(struct nk_str*, int pos, const nk_rune*); - -NK_API void nk_str_remove_chars(struct nk_str*, int len); -NK_API void nk_str_remove_runes(struct nk_str *str, int len); -NK_API void nk_str_delete_chars(struct nk_str*, int pos, int len); -NK_API void nk_str_delete_runes(struct nk_str*, int pos, int len); - -NK_API char *nk_str_at_char(struct nk_str*, int pos); -NK_API char *nk_str_at_rune(struct nk_str*, int pos, nk_rune *unicode, int *len); -NK_API nk_rune nk_str_rune_at(const struct nk_str*, int pos); -NK_API const char *nk_str_at_char_const(const struct nk_str*, int pos); -NK_API const char *nk_str_at_const(const struct nk_str*, int pos, nk_rune *unicode, int *len); - -NK_API char *nk_str_get(struct nk_str*); -NK_API const char *nk_str_get_const(const struct nk_str*); -NK_API int nk_str_len(struct nk_str*); -NK_API int nk_str_len_char(struct nk_str*); - -/*=============================================================== - * - * TEXT EDITOR - * - * ===============================================================*/ -/* Editing text in this library is handled by either `nk_edit_string` or - * `nk_edit_buffer`. But like almost everything in this library there are multiple - * ways of doing it and a balance between control and ease of use with memory - * as well as functionality controlled by flags. - * - * This library generally allows three different levels of memory control: - * First of is the most basic way of just providing a simple char array with - * string length. This method is probably the easiest way of handling simple - * user text input. Main upside is complete control over memory while the biggest - * downside in comparison with the other two approaches is missing undo/redo. - * - * For UIs that require undo/redo the second way was created. It is based on - * a fixed size nk_text_edit struct, which has an internal undo/redo stack. - * This is mainly useful if you want something more like a text editor but don't want - * to have a dynamically growing buffer. - * - * The final way is using a dynamically growing nk_text_edit struct, which - * has both a default version if you don't care where memory comes from and an - * allocator version if you do. While the text editor is quite powerful for its - * complexity I would not recommend editing gigabytes of data with it. - * It is rather designed for uses cases which make sense for a GUI library not for - * an full blown text editor. - */ -#ifndef NK_TEXTEDIT_UNDOSTATECOUNT -#define NK_TEXTEDIT_UNDOSTATECOUNT 99 -#endif - -#ifndef NK_TEXTEDIT_UNDOCHARCOUNT -#define NK_TEXTEDIT_UNDOCHARCOUNT 999 -#endif - -struct nk_text_edit; -struct nk_clipboard { - nk_handle userdata; - nk_plugin_paste paste; - nk_plugin_copy copy; -}; - -struct nk_text_undo_record { - int where; - short insert_length; - short delete_length; - short char_storage; -}; - -struct nk_text_undo_state { - struct nk_text_undo_record undo_rec[NK_TEXTEDIT_UNDOSTATECOUNT]; - nk_rune undo_char[NK_TEXTEDIT_UNDOCHARCOUNT]; - short undo_point; - short redo_point; - short undo_char_point; - short redo_char_point; -}; - -enum nk_text_edit_type { - NK_TEXT_EDIT_SINGLE_LINE, - NK_TEXT_EDIT_MULTI_LINE -}; - -enum nk_text_edit_mode { - NK_TEXT_EDIT_MODE_VIEW, - NK_TEXT_EDIT_MODE_INSERT, - NK_TEXT_EDIT_MODE_REPLACE -}; - -struct nk_text_edit { - struct nk_clipboard clip; - struct nk_str string; - nk_plugin_filter filter; - struct nk_vec2 scrollbar; - - int cursor; - int select_start; - int select_end; - unsigned char mode; - unsigned char cursor_at_end_of_line; - unsigned char initialized; - unsigned char has_preferred_x; - unsigned char single_line; - unsigned char active; - unsigned char padding1; - float preferred_x; - struct nk_text_undo_state undo; -}; - -/* filter function */ -NK_API int nk_filter_default(const struct nk_text_edit*, nk_rune unicode); -NK_API int nk_filter_ascii(const struct nk_text_edit*, nk_rune unicode); -NK_API int nk_filter_float(const struct nk_text_edit*, nk_rune unicode); -NK_API int nk_filter_decimal(const struct nk_text_edit*, nk_rune unicode); -NK_API int nk_filter_hex(const struct nk_text_edit*, nk_rune unicode); -NK_API int nk_filter_oct(const struct nk_text_edit*, nk_rune unicode); -NK_API int nk_filter_binary(const struct nk_text_edit*, nk_rune unicode); - -/* text editor */ -#ifdef NK_INCLUDE_DEFAULT_ALLOCATOR -NK_API void nk_textedit_init_default(struct nk_text_edit*); -#endif -NK_API void nk_textedit_init(struct nk_text_edit*, struct nk_allocator*, nk_size size); -NK_API void nk_textedit_init_fixed(struct nk_text_edit*, void *memory, nk_size size); -NK_API void nk_textedit_free(struct nk_text_edit*); -NK_API void nk_textedit_text(struct nk_text_edit*, const char*, int total_len); -NK_API void nk_textedit_delete(struct nk_text_edit*, int where, int len); -NK_API void nk_textedit_delete_selection(struct nk_text_edit*); -NK_API void nk_textedit_select_all(struct nk_text_edit*); -NK_API int nk_textedit_cut(struct nk_text_edit*); -NK_API int nk_textedit_paste(struct nk_text_edit*, char const*, int len); -NK_API void nk_textedit_undo(struct nk_text_edit*); -NK_API void nk_textedit_redo(struct nk_text_edit*); - -/* =============================================================== - * - * DRAWING - * - * ===============================================================*/ -/* This library was designed to be render backend agnostic so it does - not draw anything to screen. Instead all drawn shapes, widgets - are made of, are buffered into memory and make up a command queue. - Each frame therefore fills the command buffer with draw commands - that then need to be executed by the user and his own render backend. - After that the command buffer needs to be cleared and a new frame can be - started. It is probably important to note that the command buffer is the main - drawing API and the optional vertex buffer API only takes this format and - converts it into a hardware accessible format. - - To use the command queue to draw your own widgets you can access the - command buffer of each window by calling `nk_window_get_canvas` after - previously having called `nk_begin`: - - void draw_red_rectangle_widget(struct nk_context *ctx) - { - struct nk_command_buffer *canvas; - struct nk_input *input = &ctx->input; - canvas = nk_window_get_canvas(ctx); - - struct nk_rect space; - enum nk_widget_layout_states state; - state = nk_widget(&space, ctx); - if (!state) return; - - if (state != NK_WIDGET_ROM) - update_your_widget_by_user_input(...); - nk_fill_rect(canvas, space, 0, nk_rgb(255,0,0)); - } - - if (nk_begin(...)) { - nk_layout_row_dynamic(ctx, 25, 1); - draw_red_rectangle_widget(ctx); - } - nk_end(..) - - Important to know if you want to create your own widgets is the `nk_widget` - call. It allocates space on the panel reserved for this widget to be used, - but also returns the state of the widget space. If your widget is not seen and does - not have to be updated it is '0' and you can just return. If it only has - to be drawn the state will be `NK_WIDGET_ROM` otherwise you can do both - update and draw your widget. The reason for separating is to only draw and - update what is actually necessary which is crucial for performance. -*/ -enum nk_command_type { - NK_COMMAND_NOP, - NK_COMMAND_SCISSOR, - NK_COMMAND_LINE, - NK_COMMAND_CURVE, - NK_COMMAND_RECT, - NK_COMMAND_RECT_FILLED, - NK_COMMAND_RECT_MULTI_COLOR, - NK_COMMAND_CIRCLE, - NK_COMMAND_CIRCLE_FILLED, - NK_COMMAND_ARC, - NK_COMMAND_ARC_FILLED, - NK_COMMAND_TRIANGLE, - NK_COMMAND_TRIANGLE_FILLED, - NK_COMMAND_POLYGON, - NK_COMMAND_POLYGON_FILLED, - NK_COMMAND_POLYLINE, - NK_COMMAND_TEXT, - NK_COMMAND_IMAGE, - NK_COMMAND_CUSTOM -}; - -/* command base and header of every command inside the buffer */ -struct nk_command { - enum nk_command_type type; - nk_size next; -#ifdef NK_INCLUDE_COMMAND_USERDATA - nk_handle userdata; -#endif -}; - -struct nk_command_scissor { - struct nk_command header; - short x, y; - unsigned short w, h; -}; - -struct nk_command_line { - struct nk_command header; - unsigned short line_thickness; - struct nk_vec2i begin; - struct nk_vec2i end; - struct nk_color color; -}; - -struct nk_command_curve { - struct nk_command header; - unsigned short line_thickness; - struct nk_vec2i begin; - struct nk_vec2i end; - struct nk_vec2i ctrl[2]; - struct nk_color color; -}; - -struct nk_command_rect { - struct nk_command header; - unsigned short rounding; - unsigned short line_thickness; - short x, y; - unsigned short w, h; - struct nk_color color; -}; - -struct nk_command_rect_filled { - struct nk_command header; - unsigned short rounding; - short x, y; - unsigned short w, h; - struct nk_color color; -}; - -struct nk_command_rect_multi_color { - struct nk_command header; - short x, y; - unsigned short w, h; - struct nk_color left; - struct nk_color top; - struct nk_color bottom; - struct nk_color right; -}; - -struct nk_command_triangle { - struct nk_command header; - unsigned short line_thickness; - struct nk_vec2i a; - struct nk_vec2i b; - struct nk_vec2i c; - struct nk_color color; -}; - -struct nk_command_triangle_filled { - struct nk_command header; - struct nk_vec2i a; - struct nk_vec2i b; - struct nk_vec2i c; - struct nk_color color; -}; - -struct nk_command_circle { - struct nk_command header; - short x, y; - unsigned short line_thickness; - unsigned short w, h; - struct nk_color color; -}; - -struct nk_command_circle_filled { - struct nk_command header; - short x, y; - unsigned short w, h; - struct nk_color color; -}; - -struct nk_command_arc { - struct nk_command header; - short cx, cy; - unsigned short r; - unsigned short line_thickness; - float a[2]; - struct nk_color color; -}; - -struct nk_command_arc_filled { - struct nk_command header; - short cx, cy; - unsigned short r; - float a[2]; - struct nk_color color; -}; - -struct nk_command_polygon { - struct nk_command header; - struct nk_color color; - unsigned short line_thickness; - unsigned short point_count; - struct nk_vec2i points[1]; -}; - -struct nk_command_polygon_filled { - struct nk_command header; - struct nk_color color; - unsigned short point_count; - struct nk_vec2i points[1]; -}; - -struct nk_command_polyline { - struct nk_command header; - struct nk_color color; - unsigned short line_thickness; - unsigned short point_count; - struct nk_vec2i points[1]; -}; - -struct nk_command_image { - struct nk_command header; - short x, y; - unsigned short w, h; - struct nk_image img; - struct nk_color col; -}; - -typedef void (*nk_command_custom_callback)(void *canvas, short x,short y, - unsigned short w, unsigned short h, nk_handle callback_data); -struct nk_command_custom { - struct nk_command header; - short x, y; - unsigned short w, h; - nk_handle callback_data; - nk_command_custom_callback callback; -}; - -struct nk_command_text { - struct nk_command header; - const struct nk_user_font *font; - struct nk_color background; - struct nk_color foreground; - short x, y; - unsigned short w, h; - float height; - int length; - char string[1]; -}; - -enum nk_command_clipping { - NK_CLIPPING_OFF = nk_false, - NK_CLIPPING_ON = nk_true -}; - -struct nk_command_buffer { - struct nk_buffer *base; - struct nk_rect clip; - int use_clipping; - nk_handle userdata; - nk_size begin, end, last; -}; - -/* shape outlines */ -NK_API void nk_stroke_line(struct nk_command_buffer *b, float x0, float y0, float x1, float y1, float line_thickness, struct nk_color); -NK_API void nk_stroke_curve(struct nk_command_buffer*, float, float, float, float, float, float, float, float, float line_thickness, struct nk_color); -NK_API void nk_stroke_rect(struct nk_command_buffer*, struct nk_rect, float rounding, float line_thickness, struct nk_color); -NK_API void nk_stroke_circle(struct nk_command_buffer*, struct nk_rect, float line_thickness, struct nk_color); -NK_API void nk_stroke_arc(struct nk_command_buffer*, float cx, float cy, float radius, float a_min, float a_max, float line_thickness, struct nk_color); -NK_API void nk_stroke_triangle(struct nk_command_buffer*, float, float, float, float, float, float, float line_thichness, struct nk_color); -NK_API void nk_stroke_polyline(struct nk_command_buffer*, float *points, int point_count, float line_thickness, struct nk_color col); -NK_API void nk_stroke_polygon(struct nk_command_buffer*, float*, int point_count, float line_thickness, struct nk_color); - -/* filled shades */ -NK_API void nk_fill_rect(struct nk_command_buffer*, struct nk_rect, float rounding, struct nk_color); -NK_API void nk_fill_rect_multi_color(struct nk_command_buffer*, struct nk_rect, struct nk_color left, struct nk_color top, struct nk_color right, struct nk_color bottom); -NK_API void nk_fill_circle(struct nk_command_buffer*, struct nk_rect, struct nk_color); -NK_API void nk_fill_arc(struct nk_command_buffer*, float cx, float cy, float radius, float a_min, float a_max, struct nk_color); -NK_API void nk_fill_triangle(struct nk_command_buffer*, float x0, float y0, float x1, float y1, float x2, float y2, struct nk_color); -NK_API void nk_fill_polygon(struct nk_command_buffer*, float*, int point_count, struct nk_color); - -/* misc */ -NK_API void nk_draw_image(struct nk_command_buffer*, struct nk_rect, const struct nk_image*, struct nk_color); -NK_API void nk_draw_text(struct nk_command_buffer*, struct nk_rect, const char *text, int len, const struct nk_user_font*, struct nk_color, struct nk_color); -NK_API void nk_push_scissor(struct nk_command_buffer*, struct nk_rect); -NK_API void nk_push_custom(struct nk_command_buffer*, struct nk_rect, nk_command_custom_callback, nk_handle usr); - -/* =============================================================== - * - * INPUT - * - * ===============================================================*/ -struct nk_mouse_button { - int down; - unsigned int clicked; - struct nk_vec2 clicked_pos; -}; -struct nk_mouse { - struct nk_mouse_button buttons[NK_BUTTON_MAX]; - struct nk_vec2 pos; - struct nk_vec2 prev; - struct nk_vec2 delta; - struct nk_vec2 scroll_delta; - unsigned char grab; - unsigned char grabbed; - unsigned char ungrab; -}; - -struct nk_key { - int down; - unsigned int clicked; -}; -struct nk_keyboard { - struct nk_key keys[NK_KEY_MAX]; - char text[NK_INPUT_MAX]; - int text_len; -}; - -struct nk_input { - struct nk_keyboard keyboard; - struct nk_mouse mouse; -}; - -NK_API int nk_input_has_mouse_click(const struct nk_input*, enum nk_buttons); -NK_API int nk_input_has_mouse_click_in_rect(const struct nk_input*, enum nk_buttons, struct nk_rect); -NK_API int nk_input_has_mouse_click_down_in_rect(const struct nk_input*, enum nk_buttons, struct nk_rect, int down); -NK_API int nk_input_is_mouse_click_in_rect(const struct nk_input*, enum nk_buttons, struct nk_rect); -NK_API int nk_input_is_mouse_click_down_in_rect(const struct nk_input *i, enum nk_buttons id, struct nk_rect b, int down); -NK_API int nk_input_any_mouse_click_in_rect(const struct nk_input*, struct nk_rect); -NK_API int nk_input_is_mouse_prev_hovering_rect(const struct nk_input*, struct nk_rect); -NK_API int nk_input_is_mouse_hovering_rect(const struct nk_input*, struct nk_rect); -NK_API int nk_input_mouse_clicked(const struct nk_input*, enum nk_buttons, struct nk_rect); -NK_API int nk_input_is_mouse_down(const struct nk_input*, enum nk_buttons); -NK_API int nk_input_is_mouse_pressed(const struct nk_input*, enum nk_buttons); -NK_API int nk_input_is_mouse_released(const struct nk_input*, enum nk_buttons); -NK_API int nk_input_is_key_pressed(const struct nk_input*, enum nk_keys); -NK_API int nk_input_is_key_released(const struct nk_input*, enum nk_keys); -NK_API int nk_input_is_key_down(const struct nk_input*, enum nk_keys); - -/* =============================================================== - * - * DRAW LIST - * - * ===============================================================*/ -#ifdef NK_INCLUDE_VERTEX_BUFFER_OUTPUT -/* The optional vertex buffer draw list provides a 2D drawing context - with antialiasing functionality which takes basic filled or outlined shapes - or a path and outputs vertexes, elements and draw commands. - The actual draw list API is not required to be used directly while using this - library since converting the default library draw command output is done by - just calling `nk_convert` but I decided to still make this library accessible - since it can be useful. - - The draw list is based on a path buffering and polygon and polyline - rendering API which allows a lot of ways to draw 2D content to screen. - In fact it is probably more powerful than needed but allows even more crazy - things than this library provides by default. -*/ -typedef nk_ushort nk_draw_index; -enum nk_draw_list_stroke { - NK_STROKE_OPEN = nk_false, - /* build up path has no connection back to the beginning */ - NK_STROKE_CLOSED = nk_true - /* build up path has a connection back to the beginning */ -}; - -enum nk_draw_vertex_layout_attribute { - NK_VERTEX_POSITION, - NK_VERTEX_COLOR, - NK_VERTEX_TEXCOORD, - NK_VERTEX_ATTRIBUTE_COUNT -}; - -enum nk_draw_vertex_layout_format { - NK_FORMAT_SCHAR, - NK_FORMAT_SSHORT, - NK_FORMAT_SINT, - NK_FORMAT_UCHAR, - NK_FORMAT_USHORT, - NK_FORMAT_UINT, - NK_FORMAT_FLOAT, - NK_FORMAT_DOUBLE, - -NK_FORMAT_COLOR_BEGIN, - NK_FORMAT_R8G8B8 = NK_FORMAT_COLOR_BEGIN, - NK_FORMAT_R16G15B16, - NK_FORMAT_R32G32B32, - - NK_FORMAT_R8G8B8A8, - NK_FORMAT_B8G8R8A8, - NK_FORMAT_R16G15B16A16, - NK_FORMAT_R32G32B32A32, - NK_FORMAT_R32G32B32A32_FLOAT, - NK_FORMAT_R32G32B32A32_DOUBLE, - - NK_FORMAT_RGB32, - NK_FORMAT_RGBA32, -NK_FORMAT_COLOR_END = NK_FORMAT_RGBA32, - NK_FORMAT_COUNT -}; - -#define NK_VERTEX_LAYOUT_END NK_VERTEX_ATTRIBUTE_COUNT,NK_FORMAT_COUNT,0 -struct nk_draw_vertex_layout_element { - enum nk_draw_vertex_layout_attribute attribute; - enum nk_draw_vertex_layout_format format; - nk_size offset; -}; - -struct nk_draw_command { - unsigned int elem_count; - /* number of elements in the current draw batch */ - struct nk_rect clip_rect; - /* current screen clipping rectangle */ - nk_handle texture; - /* current texture to set */ -#ifdef NK_INCLUDE_COMMAND_USERDATA - nk_handle userdata; -#endif -}; - -struct nk_draw_list { - struct nk_rect clip_rect; - struct nk_vec2 circle_vtx[12]; - struct nk_convert_config config; - - struct nk_buffer *buffer; - struct nk_buffer *vertices; - struct nk_buffer *elements; - - unsigned int element_count; - unsigned int vertex_count; - unsigned int cmd_count; - nk_size cmd_offset; - - unsigned int path_count; - unsigned int path_offset; - - enum nk_anti_aliasing line_AA; - enum nk_anti_aliasing shape_AA; - -#ifdef NK_INCLUDE_COMMAND_USERDATA - nk_handle userdata; -#endif -}; - -/* draw list */ -NK_API void nk_draw_list_init(struct nk_draw_list*); -NK_API void nk_draw_list_setup(struct nk_draw_list*, const struct nk_convert_config*, struct nk_buffer *cmds, struct nk_buffer *vertices, struct nk_buffer *elements, enum nk_anti_aliasing line_aa,enum nk_anti_aliasing shape_aa); - -/* drawing */ -#define nk_draw_list_foreach(cmd, can, b) for((cmd)=nk__draw_list_begin(can, b); (cmd)!=0; (cmd)=nk__draw_list_next(cmd, b, can)) -NK_API const struct nk_draw_command* nk__draw_list_begin(const struct nk_draw_list*, const struct nk_buffer*); -NK_API const struct nk_draw_command* nk__draw_list_next(const struct nk_draw_command*, const struct nk_buffer*, const struct nk_draw_list*); -NK_API const struct nk_draw_command* nk__draw_list_end(const struct nk_draw_list*, const struct nk_buffer*); - -/* path */ -NK_API void nk_draw_list_path_clear(struct nk_draw_list*); -NK_API void nk_draw_list_path_line_to(struct nk_draw_list*, struct nk_vec2 pos); -NK_API void nk_draw_list_path_arc_to_fast(struct nk_draw_list*, struct nk_vec2 center, float radius, int a_min, int a_max); -NK_API void nk_draw_list_path_arc_to(struct nk_draw_list*, struct nk_vec2 center, float radius, float a_min, float a_max, unsigned int segments); -NK_API void nk_draw_list_path_rect_to(struct nk_draw_list*, struct nk_vec2 a, struct nk_vec2 b, float rounding); -NK_API void nk_draw_list_path_curve_to(struct nk_draw_list*, struct nk_vec2 p2, struct nk_vec2 p3, struct nk_vec2 p4, unsigned int num_segments); -NK_API void nk_draw_list_path_fill(struct nk_draw_list*, struct nk_color); -NK_API void nk_draw_list_path_stroke(struct nk_draw_list*, struct nk_color, enum nk_draw_list_stroke closed, float thickness); - -/* stroke */ -NK_API void nk_draw_list_stroke_line(struct nk_draw_list*, struct nk_vec2 a, struct nk_vec2 b, struct nk_color, float thickness); -NK_API void nk_draw_list_stroke_rect(struct nk_draw_list*, struct nk_rect rect, struct nk_color, float rounding, float thickness); -NK_API void nk_draw_list_stroke_triangle(struct nk_draw_list*, struct nk_vec2 a, struct nk_vec2 b, struct nk_vec2 c, struct nk_color, float thickness); -NK_API void nk_draw_list_stroke_circle(struct nk_draw_list*, struct nk_vec2 center, float radius, struct nk_color, unsigned int segs, float thickness); -NK_API void nk_draw_list_stroke_curve(struct nk_draw_list*, struct nk_vec2 p0, struct nk_vec2 cp0, struct nk_vec2 cp1, struct nk_vec2 p1, struct nk_color, unsigned int segments, float thickness); -NK_API void nk_draw_list_stroke_poly_line(struct nk_draw_list*, const struct nk_vec2 *pnts, const unsigned int cnt, struct nk_color, enum nk_draw_list_stroke, float thickness, enum nk_anti_aliasing); - -/* fill */ -NK_API void nk_draw_list_fill_rect(struct nk_draw_list*, struct nk_rect rect, struct nk_color, float rounding); -NK_API void nk_draw_list_fill_rect_multi_color(struct nk_draw_list*, struct nk_rect rect, struct nk_color left, struct nk_color top, struct nk_color right, struct nk_color bottom); -NK_API void nk_draw_list_fill_triangle(struct nk_draw_list*, struct nk_vec2 a, struct nk_vec2 b, struct nk_vec2 c, struct nk_color); -NK_API void nk_draw_list_fill_circle(struct nk_draw_list*, struct nk_vec2 center, float radius, struct nk_color col, unsigned int segs); -NK_API void nk_draw_list_fill_poly_convex(struct nk_draw_list*, const struct nk_vec2 *points, const unsigned int count, struct nk_color, enum nk_anti_aliasing); - -/* misc */ -NK_API void nk_draw_list_add_image(struct nk_draw_list*, struct nk_image texture, struct nk_rect rect, struct nk_color); -NK_API void nk_draw_list_add_text(struct nk_draw_list*, const struct nk_user_font*, struct nk_rect, const char *text, int len, float font_height, struct nk_color); -#ifdef NK_INCLUDE_COMMAND_USERDATA -NK_API void nk_draw_list_push_userdata(struct nk_draw_list*, nk_handle userdata); -#endif - -#endif - -/* =============================================================== - * - * GUI - * - * ===============================================================*/ -enum nk_style_item_type { - NK_STYLE_ITEM_COLOR, - NK_STYLE_ITEM_IMAGE -}; - -union nk_style_item_data { - struct nk_image image; - struct nk_color color; -}; - -struct nk_style_item { - enum nk_style_item_type type; - union nk_style_item_data data; -}; - -struct nk_style_text { - struct nk_color color; - struct nk_vec2 padding; -}; - -struct nk_style_button { - /* background */ - struct nk_style_item normal; - struct nk_style_item hover; - struct nk_style_item active; - struct nk_color border_color; - - /* text */ - struct nk_color text_background; - struct nk_color text_normal; - struct nk_color text_hover; - struct nk_color text_active; - nk_flags text_alignment; - - /* properties */ - float border; - float rounding; - struct nk_vec2 padding; - struct nk_vec2 image_padding; - struct nk_vec2 touch_padding; - - /* optional user callbacks */ - nk_handle userdata; - void(*draw_begin)(struct nk_command_buffer*, nk_handle userdata); - void(*draw_end)(struct nk_command_buffer*, nk_handle userdata); -}; - -struct nk_style_toggle { - /* background */ - struct nk_style_item normal; - struct nk_style_item hover; - struct nk_style_item active; - struct nk_color border_color; - - /* cursor */ - struct nk_style_item cursor_normal; - struct nk_style_item cursor_hover; - - /* text */ - struct nk_color text_normal; - struct nk_color text_hover; - struct nk_color text_active; - struct nk_color text_background; - nk_flags text_alignment; - - /* properties */ - struct nk_vec2 padding; - struct nk_vec2 touch_padding; - float spacing; - float border; - - /* optional user callbacks */ - nk_handle userdata; - void(*draw_begin)(struct nk_command_buffer*, nk_handle); - void(*draw_end)(struct nk_command_buffer*, nk_handle); -}; - -struct nk_style_selectable { - /* background (inactive) */ - struct nk_style_item normal; - struct nk_style_item hover; - struct nk_style_item pressed; - - /* background (active) */ - struct nk_style_item normal_active; - struct nk_style_item hover_active; - struct nk_style_item pressed_active; - - /* text color (inactive) */ - struct nk_color text_normal; - struct nk_color text_hover; - struct nk_color text_pressed; - - /* text color (active) */ - struct nk_color text_normal_active; - struct nk_color text_hover_active; - struct nk_color text_pressed_active; - struct nk_color text_background; - nk_flags text_alignment; - - /* properties */ - float rounding; - struct nk_vec2 padding; - struct nk_vec2 touch_padding; - struct nk_vec2 image_padding; - - /* optional user callbacks */ - nk_handle userdata; - void(*draw_begin)(struct nk_command_buffer*, nk_handle); - void(*draw_end)(struct nk_command_buffer*, nk_handle); -}; - -struct nk_style_slider { - /* background */ - struct nk_style_item normal; - struct nk_style_item hover; - struct nk_style_item active; - struct nk_color border_color; - - /* background bar */ - struct nk_color bar_normal; - struct nk_color bar_hover; - struct nk_color bar_active; - struct nk_color bar_filled; - - /* cursor */ - struct nk_style_item cursor_normal; - struct nk_style_item cursor_hover; - struct nk_style_item cursor_active; - - /* properties */ - float border; - float rounding; - float bar_height; - struct nk_vec2 padding; - struct nk_vec2 spacing; - struct nk_vec2 cursor_size; - - /* optional buttons */ - int show_buttons; - struct nk_style_button inc_button; - struct nk_style_button dec_button; - enum nk_symbol_type inc_symbol; - enum nk_symbol_type dec_symbol; - - /* optional user callbacks */ - nk_handle userdata; - void(*draw_begin)(struct nk_command_buffer*, nk_handle); - void(*draw_end)(struct nk_command_buffer*, nk_handle); -}; - -struct nk_style_progress { - /* background */ - struct nk_style_item normal; - struct nk_style_item hover; - struct nk_style_item active; - struct nk_color border_color; - - /* cursor */ - struct nk_style_item cursor_normal; - struct nk_style_item cursor_hover; - struct nk_style_item cursor_active; - struct nk_color cursor_border_color; - - /* properties */ - float rounding; - float border; - float cursor_border; - float cursor_rounding; - struct nk_vec2 padding; - - /* optional user callbacks */ - nk_handle userdata; - void(*draw_begin)(struct nk_command_buffer*, nk_handle); - void(*draw_end)(struct nk_command_buffer*, nk_handle); -}; - -struct nk_style_scrollbar { - /* background */ - struct nk_style_item normal; - struct nk_style_item hover; - struct nk_style_item active; - struct nk_color border_color; - - /* cursor */ - struct nk_style_item cursor_normal; - struct nk_style_item cursor_hover; - struct nk_style_item cursor_active; - struct nk_color cursor_border_color; - - /* properties */ - float border; - float rounding; - float border_cursor; - float rounding_cursor; - struct nk_vec2 padding; - - /* optional buttons */ - int show_buttons; - struct nk_style_button inc_button; - struct nk_style_button dec_button; - enum nk_symbol_type inc_symbol; - enum nk_symbol_type dec_symbol; - - /* optional user callbacks */ - nk_handle userdata; - void(*draw_begin)(struct nk_command_buffer*, nk_handle); - void(*draw_end)(struct nk_command_buffer*, nk_handle); -}; - -struct nk_style_edit { - /* background */ - struct nk_style_item normal; - struct nk_style_item hover; - struct nk_style_item active; - struct nk_color border_color; - struct nk_style_scrollbar scrollbar; - - /* cursor */ - struct nk_color cursor_normal; - struct nk_color cursor_hover; - struct nk_color cursor_text_normal; - struct nk_color cursor_text_hover; - - /* text (unselected) */ - struct nk_color text_normal; - struct nk_color text_hover; - struct nk_color text_active; - - /* text (selected) */ - struct nk_color selected_normal; - struct nk_color selected_hover; - struct nk_color selected_text_normal; - struct nk_color selected_text_hover; - - /* properties */ - float border; - float rounding; - float cursor_size; - struct nk_vec2 scrollbar_size; - struct nk_vec2 padding; - float row_padding; -}; - -struct nk_style_property { - /* background */ - struct nk_style_item normal; - struct nk_style_item hover; - struct nk_style_item active; - struct nk_color border_color; - - /* text */ - struct nk_color label_normal; - struct nk_color label_hover; - struct nk_color label_active; - - /* symbols */ - enum nk_symbol_type sym_left; - enum nk_symbol_type sym_right; - - /* properties */ - float border; - float rounding; - struct nk_vec2 padding; - - struct nk_style_edit edit; - struct nk_style_button inc_button; - struct nk_style_button dec_button; - - /* optional user callbacks */ - nk_handle userdata; - void(*draw_begin)(struct nk_command_buffer*, nk_handle); - void(*draw_end)(struct nk_command_buffer*, nk_handle); -}; - -struct nk_style_chart { - /* colors */ - struct nk_style_item background; - struct nk_color border_color; - struct nk_color selected_color; - struct nk_color color; - - /* properties */ - float border; - float rounding; - struct nk_vec2 padding; -}; - -struct nk_style_combo { - /* background */ - struct nk_style_item normal; - struct nk_style_item hover; - struct nk_style_item active; - struct nk_color border_color; - - /* label */ - struct nk_color label_normal; - struct nk_color label_hover; - struct nk_color label_active; - - /* symbol */ - struct nk_color symbol_normal; - struct nk_color symbol_hover; - struct nk_color symbol_active; - - /* button */ - struct nk_style_button button; - enum nk_symbol_type sym_normal; - enum nk_symbol_type sym_hover; - enum nk_symbol_type sym_active; - - /* properties */ - float border; - float rounding; - struct nk_vec2 content_padding; - struct nk_vec2 button_padding; - struct nk_vec2 spacing; -}; - -struct nk_style_tab { - /* background */ - struct nk_style_item background; - struct nk_color border_color; - struct nk_color text; - - /* button */ - struct nk_style_button tab_maximize_button; - struct nk_style_button tab_minimize_button; - struct nk_style_button node_maximize_button; - struct nk_style_button node_minimize_button; - enum nk_symbol_type sym_minimize; - enum nk_symbol_type sym_maximize; - - /* properties */ - float border; - float rounding; - float indent; - struct nk_vec2 padding; - struct nk_vec2 spacing; -}; - -enum nk_style_header_align { - NK_HEADER_LEFT, - NK_HEADER_RIGHT -}; -struct nk_style_window_header { - /* background */ - struct nk_style_item normal; - struct nk_style_item hover; - struct nk_style_item active; - - /* button */ - struct nk_style_button close_button; - struct nk_style_button minimize_button; - enum nk_symbol_type close_symbol; - enum nk_symbol_type minimize_symbol; - enum nk_symbol_type maximize_symbol; - - /* title */ - struct nk_color label_normal; - struct nk_color label_hover; - struct nk_color label_active; - - /* properties */ - enum nk_style_header_align align; - struct nk_vec2 padding; - struct nk_vec2 label_padding; - struct nk_vec2 spacing; -}; - -struct nk_style_window { - struct nk_style_window_header header; - struct nk_style_item fixed_background; - struct nk_color background; - - struct nk_color border_color; - struct nk_color popup_border_color; - struct nk_color combo_border_color; - struct nk_color contextual_border_color; - struct nk_color menu_border_color; - struct nk_color group_border_color; - struct nk_color tooltip_border_color; - struct nk_style_item scaler; - - float border; - float combo_border; - float contextual_border; - float menu_border; - float group_border; - float tooltip_border; - float popup_border; - float min_row_height_padding; - - float rounding; - struct nk_vec2 spacing; - struct nk_vec2 scrollbar_size; - struct nk_vec2 min_size; - - struct nk_vec2 padding; - struct nk_vec2 group_padding; - struct nk_vec2 popup_padding; - struct nk_vec2 combo_padding; - struct nk_vec2 contextual_padding; - struct nk_vec2 menu_padding; - struct nk_vec2 tooltip_padding; -}; - -struct nk_style { - const struct nk_user_font *font; - const struct nk_cursor *cursors[NK_CURSOR_COUNT]; - const struct nk_cursor *cursor_active; - struct nk_cursor *cursor_last; - int cursor_visible; - - struct nk_style_text text; - struct nk_style_button button; - struct nk_style_button contextual_button; - struct nk_style_button menu_button; - struct nk_style_toggle option; - struct nk_style_toggle checkbox; - struct nk_style_selectable selectable; - struct nk_style_slider slider; - struct nk_style_progress progress; - struct nk_style_property property; - struct nk_style_edit edit; - struct nk_style_chart chart; - struct nk_style_scrollbar scrollh; - struct nk_style_scrollbar scrollv; - struct nk_style_tab tab; - struct nk_style_combo combo; - struct nk_style_window window; -}; - -NK_API struct nk_style_item nk_style_item_image(struct nk_image img); -NK_API struct nk_style_item nk_style_item_color(struct nk_color); -NK_API struct nk_style_item nk_style_item_hide(void); - -/*============================================================== - * PANEL - * =============================================================*/ -#ifndef NK_MAX_LAYOUT_ROW_TEMPLATE_COLUMNS -#define NK_MAX_LAYOUT_ROW_TEMPLATE_COLUMNS 16 -#endif -#ifndef NK_CHART_MAX_SLOT -#define NK_CHART_MAX_SLOT 4 -#endif - -enum nk_panel_type { - NK_PANEL_NONE = 0, - NK_PANEL_WINDOW = NK_FLAG(0), - NK_PANEL_GROUP = NK_FLAG(1), - NK_PANEL_POPUP = NK_FLAG(2), - NK_PANEL_CONTEXTUAL = NK_FLAG(4), - NK_PANEL_COMBO = NK_FLAG(5), - NK_PANEL_MENU = NK_FLAG(6), - NK_PANEL_TOOLTIP = NK_FLAG(7) -}; -enum nk_panel_set { - NK_PANEL_SET_NONBLOCK = NK_PANEL_CONTEXTUAL|NK_PANEL_COMBO|NK_PANEL_MENU|NK_PANEL_TOOLTIP, - NK_PANEL_SET_POPUP = NK_PANEL_SET_NONBLOCK|NK_PANEL_POPUP, - NK_PANEL_SET_SUB = NK_PANEL_SET_POPUP|NK_PANEL_GROUP -}; - -struct nk_chart_slot { - enum nk_chart_type type; - struct nk_color color; - struct nk_color highlight; - float min, max, range; - int count; - struct nk_vec2 last; - int index; -}; - -struct nk_chart { - int slot; - float x, y, w, h; - struct nk_chart_slot slots[NK_CHART_MAX_SLOT]; -}; - -enum nk_panel_row_layout_type { - NK_LAYOUT_DYNAMIC_FIXED = 0, - NK_LAYOUT_DYNAMIC_ROW, - NK_LAYOUT_DYNAMIC_FREE, - NK_LAYOUT_DYNAMIC, - NK_LAYOUT_STATIC_FIXED, - NK_LAYOUT_STATIC_ROW, - NK_LAYOUT_STATIC_FREE, - NK_LAYOUT_STATIC, - NK_LAYOUT_TEMPLATE, - NK_LAYOUT_COUNT -}; -struct nk_row_layout { - enum nk_panel_row_layout_type type; - int index; - float height; - float min_height; - int columns; - const float *ratio; - float item_width; - float item_height; - float item_offset; - float filled; - struct nk_rect item; - int tree_depth; - float templates[NK_MAX_LAYOUT_ROW_TEMPLATE_COLUMNS]; -}; - -struct nk_popup_buffer { - nk_size begin; - nk_size parent; - nk_size last; - nk_size end; - int active; -}; - -struct nk_menu_state { - float x, y, w, h; - struct nk_scroll offset; -}; - -struct nk_panel { - enum nk_panel_type type; - nk_flags flags; - struct nk_rect bounds; - nk_uint *offset_x; - nk_uint *offset_y; - float at_x, at_y, max_x; - float footer_height; - float header_height; - float border; - unsigned int has_scrolling; - struct nk_rect clip; - struct nk_menu_state menu; - struct nk_row_layout row; - struct nk_chart chart; - struct nk_command_buffer *buffer; - struct nk_panel *parent; -}; - -/*============================================================== - * WINDOW - * =============================================================*/ -#ifndef NK_WINDOW_MAX_NAME -#define NK_WINDOW_MAX_NAME 64 -#endif - -struct nk_table; -enum nk_window_flags { - NK_WINDOW_PRIVATE = NK_FLAG(11), - NK_WINDOW_DYNAMIC = NK_WINDOW_PRIVATE, - /* special window type growing up in height while being filled to a certain maximum height */ - NK_WINDOW_ROM = NK_FLAG(12), - /* sets window widgets into a read only mode and does not allow input changes */ - NK_WINDOW_NOT_INTERACTIVE = NK_WINDOW_ROM|NK_WINDOW_NO_INPUT, - /* prevents all interaction caused by input to either window or widgets inside */ - NK_WINDOW_HIDDEN = NK_FLAG(13), - /* Hides window and stops any window interaction and drawing */ - NK_WINDOW_CLOSED = NK_FLAG(14), - /* Directly closes and frees the window at the end of the frame */ - NK_WINDOW_MINIMIZED = NK_FLAG(15), - /* marks the window as minimized */ - NK_WINDOW_REMOVE_ROM = NK_FLAG(16) - /* Removes read only mode at the end of the window */ -}; - -struct nk_popup_state { - struct nk_window *win; - enum nk_panel_type type; - struct nk_popup_buffer buf; - nk_hash name; - int active; - unsigned combo_count; - unsigned con_count, con_old; - unsigned active_con; - struct nk_rect header; -}; - -struct nk_edit_state { - nk_hash name; - unsigned int seq; - unsigned int old; - int active, prev; - int cursor; - int sel_start; - int sel_end; - struct nk_scroll scrollbar; - unsigned char mode; - unsigned char single_line; -}; - -struct nk_property_state { - int active, prev; - char buffer[NK_MAX_NUMBER_BUFFER]; - int length; - int cursor; - int select_start; - int select_end; - nk_hash name; - unsigned int seq; - unsigned int old; - int state; -}; - -struct nk_window { - unsigned int seq; - nk_hash name; - char name_string[NK_WINDOW_MAX_NAME]; - nk_flags flags; - - struct nk_rect bounds; - struct nk_scroll scrollbar; - struct nk_command_buffer buffer; - struct nk_panel *layout; - float scrollbar_hiding_timer; - - /* persistent widget state */ - struct nk_property_state property; - struct nk_popup_state popup; - struct nk_edit_state edit; - unsigned int scrolled; - - struct nk_table *tables; - unsigned int table_count; - - /* window list hooks */ - struct nk_window *next; - struct nk_window *prev; - struct nk_window *parent; -}; - -/*============================================================== - * STACK - * =============================================================*/ -/* The style modifier stack can be used to temporarily change a - * property inside `nk_style`. For example if you want a special - * red button you can temporarily push the old button color onto a stack - * draw the button with a red color and then you just pop the old color - * back from the stack: - * - * nk_style_push_style_item(ctx, &ctx->style.button.normal, nk_style_item_color(nk_rgb(255,0,0))); - * nk_style_push_style_item(ctx, &ctx->style.button.hover, nk_style_item_color(nk_rgb(255,0,0))); - * nk_style_push_style_item(ctx, &ctx->style.button.active, nk_style_item_color(nk_rgb(255,0,0))); - * nk_style_push_vec2(ctx, &cx->style.button.padding, nk_vec2(2,2)); - * - * nk_button(...); - * - * nk_style_pop_style_item(ctx); - * nk_style_pop_style_item(ctx); - * nk_style_pop_style_item(ctx); - * nk_style_pop_vec2(ctx); - * - * Nuklear has a stack for style_items, float properties, vector properties, - * flags, colors, fonts and for button_behavior. Each has it's own fixed size stack - * which can be changed at compile time. - */ -#ifndef NK_BUTTON_BEHAVIOR_STACK_SIZE -#define NK_BUTTON_BEHAVIOR_STACK_SIZE 8 -#endif - -#ifndef NK_FONT_STACK_SIZE -#define NK_FONT_STACK_SIZE 8 -#endif - -#ifndef NK_STYLE_ITEM_STACK_SIZE -#define NK_STYLE_ITEM_STACK_SIZE 16 -#endif - -#ifndef NK_FLOAT_STACK_SIZE -#define NK_FLOAT_STACK_SIZE 32 -#endif - -#ifndef NK_VECTOR_STACK_SIZE -#define NK_VECTOR_STACK_SIZE 16 -#endif - -#ifndef NK_FLAGS_STACK_SIZE -#define NK_FLAGS_STACK_SIZE 32 -#endif - -#ifndef NK_COLOR_STACK_SIZE -#define NK_COLOR_STACK_SIZE 32 -#endif - -#define NK_CONFIGURATION_STACK_TYPE(prefix, name, type)\ - struct nk_config_stack_##name##_element {\ - prefix##_##type *address;\ - prefix##_##type old_value;\ - } -#define NK_CONFIG_STACK(type,size)\ - struct nk_config_stack_##type {\ - int head;\ - struct nk_config_stack_##type##_element elements[size];\ - } - -#define nk_float float -NK_CONFIGURATION_STACK_TYPE(struct nk, style_item, style_item); -NK_CONFIGURATION_STACK_TYPE(nk ,float, float); -NK_CONFIGURATION_STACK_TYPE(struct nk, vec2, vec2); -NK_CONFIGURATION_STACK_TYPE(nk ,flags, flags); -NK_CONFIGURATION_STACK_TYPE(struct nk, color, color); -NK_CONFIGURATION_STACK_TYPE(const struct nk, user_font, user_font*); -NK_CONFIGURATION_STACK_TYPE(enum nk, button_behavior, button_behavior); - -NK_CONFIG_STACK(style_item, NK_STYLE_ITEM_STACK_SIZE); -NK_CONFIG_STACK(float, NK_FLOAT_STACK_SIZE); -NK_CONFIG_STACK(vec2, NK_VECTOR_STACK_SIZE); -NK_CONFIG_STACK(flags, NK_FLAGS_STACK_SIZE); -NK_CONFIG_STACK(color, NK_COLOR_STACK_SIZE); -NK_CONFIG_STACK(user_font, NK_FONT_STACK_SIZE); -NK_CONFIG_STACK(button_behavior, NK_BUTTON_BEHAVIOR_STACK_SIZE); - -struct nk_configuration_stacks { - struct nk_config_stack_style_item style_items; - struct nk_config_stack_float floats; - struct nk_config_stack_vec2 vectors; - struct nk_config_stack_flags flags; - struct nk_config_stack_color colors; - struct nk_config_stack_user_font fonts; - struct nk_config_stack_button_behavior button_behaviors; -}; - -/*============================================================== - * CONTEXT - * =============================================================*/ -#define NK_VALUE_PAGE_CAPACITY \ - (((NK_MAX(sizeof(struct nk_window),sizeof(struct nk_panel)) / sizeof(nk_uint))) / 2) - -struct nk_table { - unsigned int seq; - unsigned int size; - nk_hash keys[NK_VALUE_PAGE_CAPACITY]; - nk_uint values[NK_VALUE_PAGE_CAPACITY]; - struct nk_table *next, *prev; -}; - -union nk_page_data { - struct nk_table tbl; - struct nk_panel pan; - struct nk_window win; -}; - -struct nk_page_element { - union nk_page_data data; - struct nk_page_element *next; - struct nk_page_element *prev; -}; - -struct nk_page { - unsigned int size; - struct nk_page *next; - struct nk_page_element win[1]; -}; - -struct nk_pool { - struct nk_allocator alloc; - enum nk_allocation_type type; - unsigned int page_count; - struct nk_page *pages; - struct nk_page_element *freelist; - unsigned capacity; - nk_size size; - nk_size cap; -}; - -struct nk_context { -/* public: can be accessed freely */ - struct nk_input input; - struct nk_style style; - struct nk_buffer memory; - struct nk_clipboard clip; - nk_flags last_widget_state; - enum nk_button_behavior button_behavior; - struct nk_configuration_stacks stacks; - float delta_time_seconds; - -/* private: - should only be accessed if you - know what you are doing */ -#ifdef NK_INCLUDE_VERTEX_BUFFER_OUTPUT - struct nk_draw_list draw_list; -#endif -#ifdef NK_INCLUDE_COMMAND_USERDATA - nk_handle userdata; -#endif - /* text editor objects are quite big because of an internal - * undo/redo stack. Therefore it does not make sense to have one for - * each window for temporary use cases, so I only provide *one* instance - * for all windows. This works because the content is cleared anyway */ - struct nk_text_edit text_edit; - /* draw buffer used for overlay drawing operation like cursor */ - struct nk_command_buffer overlay; - - /* windows */ - int build; - int use_pool; - struct nk_pool pool; - struct nk_window *begin; - struct nk_window *end; - struct nk_window *active; - struct nk_window *current; - struct nk_page_element *freelist; - unsigned int count; - unsigned int seq; -}; - -/* ============================================================== - * MATH - * =============================================================== */ -#define NK_PI 3.141592654f -#define NK_UTF_INVALID 0xFFFD -#define NK_MAX_FLOAT_PRECISION 2 - -#define NK_UNUSED(x) ((void)(x)) -#define NK_SATURATE(x) (NK_MAX(0, NK_MIN(1.0f, x))) -#define NK_LEN(a) (sizeof(a)/sizeof(a)[0]) -#define NK_ABS(a) (((a) < 0) ? -(a) : (a)) -#define NK_BETWEEN(x, a, b) ((a) <= (x) && (x) < (b)) -#define NK_INBOX(px, py, x, y, w, h)\ - (NK_BETWEEN(px,x,x+w) && NK_BETWEEN(py,y,y+h)) -#define NK_INTERSECT(x0, y0, w0, h0, x1, y1, w1, h1) \ - (!(((x1 > (x0 + w0)) || ((x1 + w1) < x0) || (y1 > (y0 + h0)) || (y1 + h1) < y0))) -#define NK_CONTAINS(x, y, w, h, bx, by, bw, bh)\ - (NK_INBOX(x,y, bx, by, bw, bh) && NK_INBOX(x+w,y+h, bx, by, bw, bh)) - -#define nk_vec2_sub(a, b) nk_vec2((a).x - (b).x, (a).y - (b).y) -#define nk_vec2_add(a, b) nk_vec2((a).x + (b).x, (a).y + (b).y) -#define nk_vec2_len_sqr(a) ((a).x*(a).x+(a).y*(a).y) -#define nk_vec2_muls(a, t) nk_vec2((a).x * (t), (a).y * (t)) - -#define nk_ptr_add(t, p, i) ((t*)((void*)((nk_byte*)(p) + (i)))) -#define nk_ptr_add_const(t, p, i) ((const t*)((const void*)((const nk_byte*)(p) + (i)))) -#define nk_zero_struct(s) nk_zero(&s, sizeof(s)) - -/* ============================================================== - * ALIGNMENT - * =============================================================== */ -/* Pointer to Integer type conversion for pointer alignment */ -#if defined(__PTRDIFF_TYPE__) /* This case should work for GCC*/ -# define NK_UINT_TO_PTR(x) ((void*)(__PTRDIFF_TYPE__)(x)) -# define NK_PTR_TO_UINT(x) ((nk_size)(__PTRDIFF_TYPE__)(x)) -#elif !defined(__GNUC__) /* works for compilers other than LLVM */ -# define NK_UINT_TO_PTR(x) ((void*)&((char*)0)[x]) -# define NK_PTR_TO_UINT(x) ((nk_size)(((char*)x)-(char*)0)) -#elif defined(NK_USE_FIXED_TYPES) /* used if we have */ -# define NK_UINT_TO_PTR(x) ((void*)(uintptr_t)(x)) -# define NK_PTR_TO_UINT(x) ((uintptr_t)(x)) -#else /* generates warning but works */ -# define NK_UINT_TO_PTR(x) ((void*)(x)) -# define NK_PTR_TO_UINT(x) ((nk_size)(x)) -#endif - -#define NK_ALIGN_PTR(x, mask)\ - (NK_UINT_TO_PTR((NK_PTR_TO_UINT((nk_byte*)(x) + (mask-1)) & ~(mask-1)))) -#define NK_ALIGN_PTR_BACK(x, mask)\ - (NK_UINT_TO_PTR((NK_PTR_TO_UINT((nk_byte*)(x)) & ~(mask-1)))) - -#define NK_OFFSETOF(st,m) ((nk_ptr)&(((st*)0)->m)) -#define NK_CONTAINER_OF(ptr,type,member)\ - (type*)((void*)((char*)(1 ? (ptr): &((type*)0)->member) - NK_OFFSETOF(type, member))) - -#ifdef __cplusplus -} -#endif - -#ifdef __cplusplus -template struct nk_alignof; -template struct nk_helper{enum {value = size_diff};}; -template struct nk_helper{enum {value = nk_alignof::value};}; -template struct nk_alignof{struct Big {T x; char c;}; enum { - diff = sizeof(Big) - sizeof(T), value = nk_helper::value};}; -#define NK_ALIGNOF(t) (nk_alignof::value) -#elif defined(_MSC_VER) -#define NK_ALIGNOF(t) (__alignof(t)) -#else -#define NK_ALIGNOF(t) ((char*)(&((struct {char c; t _h;}*)0)->_h) - (char*)0) -#endif - -#endif /* NK_NUKLEAR_H_ */ - - -#ifdef NK_IMPLEMENTATION - -#ifndef NK_INTERNAL_H -#define NK_INTERNAL_H - -#ifndef NK_POOL_DEFAULT_CAPACITY -#define NK_POOL_DEFAULT_CAPACITY 16 -#endif - -#ifndef NK_DEFAULT_COMMAND_BUFFER_SIZE -#define NK_DEFAULT_COMMAND_BUFFER_SIZE (4*1024) -#endif - -#ifndef NK_BUFFER_DEFAULT_INITIAL_SIZE -#define NK_BUFFER_DEFAULT_INITIAL_SIZE (4*1024) -#endif - -/* standard library headers */ -#ifdef NK_INCLUDE_DEFAULT_ALLOCATOR -#include /* malloc, free */ -#endif -#ifdef NK_INCLUDE_STANDARD_IO -#include /* fopen, fclose,... */ -#endif -#ifndef NK_ASSERT -#include -#define NK_ASSERT(expr) assert(expr) -#endif - -#ifndef NK_MEMSET -#define NK_MEMSET nk_memset -#endif -#ifndef NK_MEMCPY -#define NK_MEMCPY nk_memcopy -#endif -#ifndef NK_SQRT -#define NK_SQRT nk_sqrt -#endif -#ifndef NK_SIN -#define NK_SIN nk_sin -#endif -#ifndef NK_COS -#define NK_COS nk_cos -#endif -#ifndef NK_STRTOD -#define NK_STRTOD nk_strtod -#endif -#ifndef NK_DTOA -#define NK_DTOA nk_dtoa -#endif - -#define NK_DEFAULT (-1) - -#ifndef NK_VSNPRINTF -/* If your compiler does support `vsnprintf` I would highly recommend - * defining this to vsnprintf instead since `vsprintf` is basically - * unbelievable unsafe and should *NEVER* be used. But I have to support - * it since C89 only provides this unsafe version. */ - #if (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) ||\ - (defined(__cplusplus) && (__cplusplus >= 201103L)) || \ - (defined(_POSIX_C_SOURCE) && (_POSIX_C_SOURCE >= 200112L)) ||\ - (defined(_XOPEN_SOURCE) && (_XOPEN_SOURCE >= 500)) ||\ - defined(_ISOC99_SOURCE) || defined(_BSD_SOURCE) - #define NK_VSNPRINTF(s,n,f,a) vsnprintf(s,n,f,a) - #else - #define NK_VSNPRINTF(s,n,f,a) vsprintf(s,f,a) - #endif -#endif - -#define NK_SCHAR_MIN (-127) -#define NK_SCHAR_MAX 127 -#define NK_UCHAR_MIN 0 -#define NK_UCHAR_MAX 256 -#define NK_SSHORT_MIN (-32767) -#define NK_SSHORT_MAX 32767 -#define NK_USHORT_MIN 0 -#define NK_USHORT_MAX 65535 -#define NK_SINT_MIN (-2147483647) -#define NK_SINT_MAX 2147483647 -#define NK_UINT_MIN 0 -#define NK_UINT_MAX 4294967295u - -/* Make sure correct type size: - * This will fire with a negative subscript error if the type sizes - * are set incorrectly by the compiler, and compile out if not */ -NK_STATIC_ASSERT(sizeof(nk_size) >= sizeof(void*)); -NK_STATIC_ASSERT(sizeof(nk_ptr) == sizeof(void*)); -NK_STATIC_ASSERT(sizeof(nk_flags) >= 4); -NK_STATIC_ASSERT(sizeof(nk_rune) >= 4); -NK_STATIC_ASSERT(sizeof(nk_ushort) == 2); -NK_STATIC_ASSERT(sizeof(nk_short) == 2); -NK_STATIC_ASSERT(sizeof(nk_uint) == 4); -NK_STATIC_ASSERT(sizeof(nk_int) == 4); -NK_STATIC_ASSERT(sizeof(nk_byte) == 1); - -NK_GLOBAL const struct nk_rect nk_null_rect = {-8192.0f, -8192.0f, 16384, 16384}; -#define NK_FLOAT_PRECISION 0.00000000000001 - -NK_GLOBAL const struct nk_color nk_red = {255,0,0,255}; -NK_GLOBAL const struct nk_color nk_green = {0,255,0,255}; -NK_GLOBAL const struct nk_color nk_blue = {0,0,255,255}; -NK_GLOBAL const struct nk_color nk_white = {255,255,255,255}; -NK_GLOBAL const struct nk_color nk_black = {0,0,0,255}; -NK_GLOBAL const struct nk_color nk_yellow = {255,255,0,255}; - -/* widget */ -#define nk_widget_state_reset(s)\ - if ((*(s)) & NK_WIDGET_STATE_MODIFIED)\ - (*(s)) = NK_WIDGET_STATE_INACTIVE|NK_WIDGET_STATE_MODIFIED;\ - else (*(s)) = NK_WIDGET_STATE_INACTIVE; - -/* math */ -NK_LIB float nk_inv_sqrt(float n); -NK_LIB float nk_sqrt(float x); -NK_LIB float nk_sin(float x); -NK_LIB float nk_cos(float x); -NK_LIB nk_uint nk_round_up_pow2(nk_uint v); -NK_LIB struct nk_rect nk_shrink_rect(struct nk_rect r, float amount); -NK_LIB struct nk_rect nk_pad_rect(struct nk_rect r, struct nk_vec2 pad); -NK_LIB void nk_unify(struct nk_rect *clip, const struct nk_rect *a, float x0, float y0, float x1, float y1); -NK_LIB double nk_pow(double x, int n); -NK_LIB int nk_ifloord(double x); -NK_LIB int nk_ifloorf(float x); -NK_LIB int nk_iceilf(float x); -NK_LIB int nk_log10(double n); - -/* util */ -enum {NK_DO_NOT_STOP_ON_NEW_LINE, NK_STOP_ON_NEW_LINE}; -NK_LIB int nk_is_lower(int c); -NK_LIB int nk_is_upper(int c); -NK_LIB int nk_to_upper(int c); -NK_LIB int nk_to_lower(int c); -NK_LIB void* nk_memcopy(void *dst, const void *src, nk_size n); -NK_LIB void nk_memset(void *ptr, int c0, nk_size size); -NK_LIB void nk_zero(void *ptr, nk_size size); -NK_LIB char *nk_itoa(char *s, long n); -NK_LIB int nk_string_float_limit(char *string, int prec); -NK_LIB char *nk_dtoa(char *s, double n); -NK_LIB int nk_text_clamp(const struct nk_user_font *font, const char *text, int text_len, float space, int *glyphs, float *text_width, nk_rune *sep_list, int sep_count); -NK_LIB struct nk_vec2 nk_text_calculate_text_bounds(const struct nk_user_font *font, const char *begin, int byte_len, float row_height, const char **remaining, struct nk_vec2 *out_offset, int *glyphs, int op); -#ifdef NK_INCLUDE_STANDARD_VARARGS -NK_LIB int nk_strfmt(char *buf, int buf_size, const char *fmt, va_list args); -#endif -#ifdef NK_INCLUDE_STANDARD_IO -NK_LIB char *nk_file_load(const char* path, nk_size* siz, struct nk_allocator *alloc); -#endif - -/* buffer */ -#ifdef NK_INCLUDE_DEFAULT_ALLOCATOR -NK_LIB void* nk_malloc(nk_handle unused, void *old,nk_size size); -NK_LIB void nk_mfree(nk_handle unused, void *ptr); -#endif -NK_LIB void* nk_buffer_align(void *unaligned, nk_size align, nk_size *alignment, enum nk_buffer_allocation_type type); -NK_LIB void* nk_buffer_alloc(struct nk_buffer *b, enum nk_buffer_allocation_type type, nk_size size, nk_size align); -NK_LIB void* nk_buffer_realloc(struct nk_buffer *b, nk_size capacity, nk_size *size); - -/* draw */ -NK_LIB void nk_command_buffer_init(struct nk_command_buffer *cb, struct nk_buffer *b, enum nk_command_clipping clip); -NK_LIB void nk_command_buffer_reset(struct nk_command_buffer *b); -NK_LIB void* nk_command_buffer_push(struct nk_command_buffer* b, enum nk_command_type t, nk_size size); -NK_LIB void nk_draw_symbol(struct nk_command_buffer *out, enum nk_symbol_type type, struct nk_rect content, struct nk_color background, struct nk_color foreground, float border_width, const struct nk_user_font *font); - -/* buffering */ -NK_LIB void nk_start_buffer(struct nk_context *ctx, struct nk_command_buffer *b); -NK_LIB void nk_start(struct nk_context *ctx, struct nk_window *win); -NK_LIB void nk_start_popup(struct nk_context *ctx, struct nk_window *win); -NK_LIB void nk_finish_popup(struct nk_context *ctx, struct nk_window*); -NK_LIB void nk_finish_buffer(struct nk_context *ctx, struct nk_command_buffer *b); -NK_LIB void nk_finish(struct nk_context *ctx, struct nk_window *w); -NK_LIB void nk_build(struct nk_context *ctx); - -/* text editor */ -NK_LIB void nk_textedit_clear_state(struct nk_text_edit *state, enum nk_text_edit_type type, nk_plugin_filter filter); -NK_LIB void nk_textedit_click(struct nk_text_edit *state, float x, float y, const struct nk_user_font *font, float row_height); -NK_LIB void nk_textedit_drag(struct nk_text_edit *state, float x, float y, const struct nk_user_font *font, float row_height); -NK_LIB void nk_textedit_key(struct nk_text_edit *state, enum nk_keys key, int shift_mod, const struct nk_user_font *font, float row_height); - -/* window */ -enum nk_window_insert_location { - NK_INSERT_BACK, /* inserts window into the back of list (front of screen) */ - NK_INSERT_FRONT /* inserts window into the front of list (back of screen) */ -}; -NK_LIB void *nk_create_window(struct nk_context *ctx); -NK_LIB void nk_remove_window(struct nk_context*, struct nk_window*); -NK_LIB void nk_free_window(struct nk_context *ctx, struct nk_window *win); -NK_LIB struct nk_window *nk_find_window(struct nk_context *ctx, nk_hash hash, const char *name); -NK_LIB void nk_insert_window(struct nk_context *ctx, struct nk_window *win, enum nk_window_insert_location loc); - -/* pool */ -NK_LIB void nk_pool_init(struct nk_pool *pool, struct nk_allocator *alloc, unsigned int capacity); -NK_LIB void nk_pool_free(struct nk_pool *pool); -NK_LIB void nk_pool_init_fixed(struct nk_pool *pool, void *memory, nk_size size); -NK_LIB struct nk_page_element *nk_pool_alloc(struct nk_pool *pool); - -/* page-element */ -NK_LIB struct nk_page_element* nk_create_page_element(struct nk_context *ctx); -NK_LIB void nk_link_page_element_into_freelist(struct nk_context *ctx, struct nk_page_element *elem); -NK_LIB void nk_free_page_element(struct nk_context *ctx, struct nk_page_element *elem); - -/* table */ -NK_LIB struct nk_table* nk_create_table(struct nk_context *ctx); -NK_LIB void nk_remove_table(struct nk_window *win, struct nk_table *tbl); -NK_LIB void nk_free_table(struct nk_context *ctx, struct nk_table *tbl); -NK_LIB void nk_push_table(struct nk_window *win, struct nk_table *tbl); -NK_LIB nk_uint *nk_add_value(struct nk_context *ctx, struct nk_window *win, nk_hash name, nk_uint value); -NK_LIB nk_uint *nk_find_value(struct nk_window *win, nk_hash name); - -/* panel */ -NK_LIB void *nk_create_panel(struct nk_context *ctx); -NK_LIB void nk_free_panel(struct nk_context*, struct nk_panel *pan); -NK_LIB int nk_panel_has_header(nk_flags flags, const char *title); -NK_LIB struct nk_vec2 nk_panel_get_padding(const struct nk_style *style, enum nk_panel_type type); -NK_LIB float nk_panel_get_border(const struct nk_style *style, nk_flags flags, enum nk_panel_type type); -NK_LIB struct nk_color nk_panel_get_border_color(const struct nk_style *style, enum nk_panel_type type); -NK_LIB int nk_panel_is_sub(enum nk_panel_type type); -NK_LIB int nk_panel_is_nonblock(enum nk_panel_type type); -NK_LIB int nk_panel_begin(struct nk_context *ctx, const char *title, enum nk_panel_type panel_type); -NK_LIB void nk_panel_end(struct nk_context *ctx); - -/* layout */ -NK_LIB float nk_layout_row_calculate_usable_space(const struct nk_style *style, enum nk_panel_type type, float total_space, int columns); -NK_LIB void nk_panel_layout(const struct nk_context *ctx, struct nk_window *win, float height, int cols); -NK_LIB void nk_row_layout(struct nk_context *ctx, enum nk_layout_format fmt, float height, int cols, int width); -NK_LIB void nk_panel_alloc_row(const struct nk_context *ctx, struct nk_window *win); -NK_LIB void nk_layout_widget_space(struct nk_rect *bounds, const struct nk_context *ctx, struct nk_window *win, int modify); -NK_LIB void nk_panel_alloc_space(struct nk_rect *bounds, const struct nk_context *ctx); -NK_LIB void nk_layout_peek(struct nk_rect *bounds, struct nk_context *ctx); - -/* popup */ -NK_LIB int nk_nonblock_begin(struct nk_context *ctx, nk_flags flags, struct nk_rect body, struct nk_rect header, enum nk_panel_type panel_type); - -/* text */ -struct nk_text { - struct nk_vec2 padding; - struct nk_color background; - struct nk_color text; -}; -NK_LIB void nk_widget_text(struct nk_command_buffer *o, struct nk_rect b, const char *string, int len, const struct nk_text *t, nk_flags a, const struct nk_user_font *f); -NK_LIB void nk_widget_text_wrap(struct nk_command_buffer *o, struct nk_rect b, const char *string, int len, const struct nk_text *t, const struct nk_user_font *f); - -/* button */ -NK_LIB int nk_button_behavior(nk_flags *state, struct nk_rect r, const struct nk_input *i, enum nk_button_behavior behavior); -NK_LIB const struct nk_style_item* nk_draw_button(struct nk_command_buffer *out, const struct nk_rect *bounds, nk_flags state, const struct nk_style_button *style); -NK_LIB int nk_do_button(nk_flags *state, struct nk_command_buffer *out, struct nk_rect r, const struct nk_style_button *style, const struct nk_input *in, enum nk_button_behavior behavior, struct nk_rect *content); -NK_LIB void nk_draw_button_text(struct nk_command_buffer *out, const struct nk_rect *bounds, const struct nk_rect *content, nk_flags state, const struct nk_style_button *style, const char *txt, int len, nk_flags text_alignment, const struct nk_user_font *font); -NK_LIB int nk_do_button_text(nk_flags *state, struct nk_command_buffer *out, struct nk_rect bounds, const char *string, int len, nk_flags align, enum nk_button_behavior behavior, const struct nk_style_button *style, const struct nk_input *in, const struct nk_user_font *font); -NK_LIB void nk_draw_button_symbol(struct nk_command_buffer *out, const struct nk_rect *bounds, const struct nk_rect *content, nk_flags state, const struct nk_style_button *style, enum nk_symbol_type type, const struct nk_user_font *font); -NK_LIB int nk_do_button_symbol(nk_flags *state, struct nk_command_buffer *out, struct nk_rect bounds, enum nk_symbol_type symbol, enum nk_button_behavior behavior, const struct nk_style_button *style, const struct nk_input *in, const struct nk_user_font *font); -NK_LIB void nk_draw_button_image(struct nk_command_buffer *out, const struct nk_rect *bounds, const struct nk_rect *content, nk_flags state, const struct nk_style_button *style, const struct nk_image *img); -NK_LIB int nk_do_button_image(nk_flags *state, struct nk_command_buffer *out, struct nk_rect bounds, struct nk_image img, enum nk_button_behavior b, const struct nk_style_button *style, const struct nk_input *in); -NK_LIB void nk_draw_button_text_symbol(struct nk_command_buffer *out, const struct nk_rect *bounds, const struct nk_rect *label, const struct nk_rect *symbol, nk_flags state, const struct nk_style_button *style, const char *str, int len, enum nk_symbol_type type, const struct nk_user_font *font); -NK_LIB int nk_do_button_text_symbol(nk_flags *state, struct nk_command_buffer *out, struct nk_rect bounds, enum nk_symbol_type symbol, const char *str, int len, nk_flags align, enum nk_button_behavior behavior, const struct nk_style_button *style, const struct nk_user_font *font, const struct nk_input *in); -NK_LIB void nk_draw_button_text_image(struct nk_command_buffer *out, const struct nk_rect *bounds, const struct nk_rect *label, const struct nk_rect *image, nk_flags state, const struct nk_style_button *style, const char *str, int len, const struct nk_user_font *font, const struct nk_image *img); -NK_LIB int nk_do_button_text_image(nk_flags *state, struct nk_command_buffer *out, struct nk_rect bounds, struct nk_image img, const char* str, int len, nk_flags align, enum nk_button_behavior behavior, const struct nk_style_button *style, const struct nk_user_font *font, const struct nk_input *in); - -/* toggle */ -enum nk_toggle_type { - NK_TOGGLE_CHECK, - NK_TOGGLE_OPTION -}; -NK_LIB int nk_toggle_behavior(const struct nk_input *in, struct nk_rect select, nk_flags *state, int active); -NK_LIB void nk_draw_checkbox(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, int active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font); -NK_LIB void nk_draw_option(struct nk_command_buffer *out, nk_flags state, const struct nk_style_toggle *style, int active, const struct nk_rect *label, const struct nk_rect *selector, const struct nk_rect *cursors, const char *string, int len, const struct nk_user_font *font); -NK_LIB int nk_do_toggle(nk_flags *state, struct nk_command_buffer *out, struct nk_rect r, int *active, const char *str, int len, enum nk_toggle_type type, const struct nk_style_toggle *style, const struct nk_input *in, const struct nk_user_font *font); - -/* progress */ -NK_LIB nk_size nk_progress_behavior(nk_flags *state, struct nk_input *in, struct nk_rect r, struct nk_rect cursor, nk_size max, nk_size value, int modifiable); -NK_LIB void nk_draw_progress(struct nk_command_buffer *out, nk_flags state, const struct nk_style_progress *style, const struct nk_rect *bounds, const struct nk_rect *scursor, nk_size value, nk_size max); -NK_LIB nk_size nk_do_progress(nk_flags *state, struct nk_command_buffer *out, struct nk_rect bounds, nk_size value, nk_size max, int modifiable, const struct nk_style_progress *style, struct nk_input *in); - -/* slider */ -NK_LIB float nk_slider_behavior(nk_flags *state, struct nk_rect *logical_cursor, struct nk_rect *visual_cursor, struct nk_input *in, struct nk_rect bounds, float slider_min, float slider_max, float slider_value, float slider_step, float slider_steps); -NK_LIB void nk_draw_slider(struct nk_command_buffer *out, nk_flags state, const struct nk_style_slider *style, const struct nk_rect *bounds, const struct nk_rect *visual_cursor, float min, float value, float max); -NK_LIB float nk_do_slider(nk_flags *state, struct nk_command_buffer *out, struct nk_rect bounds, float min, float val, float max, float step, const struct nk_style_slider *style, struct nk_input *in, const struct nk_user_font *font); - -/* scrollbar */ -NK_LIB float nk_scrollbar_behavior(nk_flags *state, struct nk_input *in, int has_scrolling, const struct nk_rect *scroll, const struct nk_rect *cursor, const struct nk_rect *empty0, const struct nk_rect *empty1, float scroll_offset, float target, float scroll_step, enum nk_orientation o); -NK_LIB void nk_draw_scrollbar(struct nk_command_buffer *out, nk_flags state, const struct nk_style_scrollbar *style, const struct nk_rect *bounds, const struct nk_rect *scroll); -NK_LIB float nk_do_scrollbarv(nk_flags *state, struct nk_command_buffer *out, struct nk_rect scroll, int has_scrolling, float offset, float target, float step, float button_pixel_inc, const struct nk_style_scrollbar *style, struct nk_input *in, const struct nk_user_font *font); -NK_LIB float nk_do_scrollbarh(nk_flags *state, struct nk_command_buffer *out, struct nk_rect scroll, int has_scrolling, float offset, float target, float step, float button_pixel_inc, const struct nk_style_scrollbar *style, struct nk_input *in, const struct nk_user_font *font); - -/* selectable */ -NK_LIB void nk_draw_selectable(struct nk_command_buffer *out, nk_flags state, const struct nk_style_selectable *style, int active, const struct nk_rect *bounds, const struct nk_rect *icon, const struct nk_image *img, enum nk_symbol_type sym, const char *string, int len, nk_flags align, const struct nk_user_font *font); -NK_LIB int nk_do_selectable(nk_flags *state, struct nk_command_buffer *out, struct nk_rect bounds, const char *str, int len, nk_flags align, int *value, const struct nk_style_selectable *style, const struct nk_input *in, const struct nk_user_font *font); -NK_LIB int nk_do_selectable_image(nk_flags *state, struct nk_command_buffer *out, struct nk_rect bounds, const char *str, int len, nk_flags align, int *value, const struct nk_image *img, const struct nk_style_selectable *style, const struct nk_input *in, const struct nk_user_font *font); - -/* edit */ -NK_LIB void nk_edit_draw_text(struct nk_command_buffer *out, const struct nk_style_edit *style, float pos_x, float pos_y, float x_offset, const char *text, int byte_len, float row_height, const struct nk_user_font *font, struct nk_color background, struct nk_color foreground, int is_selected); -NK_LIB nk_flags nk_do_edit(nk_flags *state, struct nk_command_buffer *out, struct nk_rect bounds, nk_flags flags, nk_plugin_filter filter, struct nk_text_edit *edit, const struct nk_style_edit *style, struct nk_input *in, const struct nk_user_font *font); - -/* color-picker */ -NK_LIB int nk_color_picker_behavior(nk_flags *state, const struct nk_rect *bounds, const struct nk_rect *matrix, const struct nk_rect *hue_bar, const struct nk_rect *alpha_bar, struct nk_colorf *color, const struct nk_input *in); -NK_LIB void nk_draw_color_picker(struct nk_command_buffer *o, const struct nk_rect *matrix, const struct nk_rect *hue_bar, const struct nk_rect *alpha_bar, struct nk_colorf col); -NK_LIB int nk_do_color_picker(nk_flags *state, struct nk_command_buffer *out, struct nk_colorf *col, enum nk_color_format fmt, struct nk_rect bounds, struct nk_vec2 padding, const struct nk_input *in, const struct nk_user_font *font); - -/* property */ -enum nk_property_status { - NK_PROPERTY_DEFAULT, - NK_PROPERTY_EDIT, - NK_PROPERTY_DRAG -}; -enum nk_property_filter { - NK_FILTER_INT, - NK_FILTER_FLOAT -}; -enum nk_property_kind { - NK_PROPERTY_INT, - NK_PROPERTY_FLOAT, - NK_PROPERTY_DOUBLE -}; -union nk_property { - int i; - float f; - double d; -}; -struct nk_property_variant { - enum nk_property_kind kind; - union nk_property value; - union nk_property min_value; - union nk_property max_value; - union nk_property step; -}; -NK_LIB struct nk_property_variant nk_property_variant_int(int value, int min_value, int max_value, int step); -NK_LIB struct nk_property_variant nk_property_variant_float(float value, float min_value, float max_value, float step); -NK_LIB struct nk_property_variant nk_property_variant_double(double value, double min_value, double max_value, double step); - -NK_LIB void nk_drag_behavior(nk_flags *state, const struct nk_input *in, struct nk_rect drag, struct nk_property_variant *variant, float inc_per_pixel); -NK_LIB void nk_property_behavior(nk_flags *ws, const struct nk_input *in, struct nk_rect property, struct nk_rect label, struct nk_rect edit, struct nk_rect empty, int *state, struct nk_property_variant *variant, float inc_per_pixel); -NK_LIB void nk_draw_property(struct nk_command_buffer *out, const struct nk_style_property *style, const struct nk_rect *bounds, const struct nk_rect *label, nk_flags state, const char *name, int len, const struct nk_user_font *font); -NK_LIB void nk_do_property(nk_flags *ws, struct nk_command_buffer *out, struct nk_rect property, const char *name, struct nk_property_variant *variant, float inc_per_pixel, char *buffer, int *len, int *state, int *cursor, int *select_begin, int *select_end, const struct nk_style_property *style, enum nk_property_filter filter, struct nk_input *in, const struct nk_user_font *font, struct nk_text_edit *text_edit, enum nk_button_behavior behavior); -NK_LIB void nk_property(struct nk_context *ctx, const char *name, struct nk_property_variant *variant, float inc_per_pixel, const enum nk_property_filter filter); - -#endif - - - - - -/* =============================================================== - * - * MATH - * - * ===============================================================*/ -/* Since nuklear is supposed to work on all systems providing floating point - math without any dependencies I also had to implement my own math functions - for sqrt, sin and cos. Since the actual highly accurate implementations for - the standard library functions are quite complex and I do not need high - precision for my use cases I use approximations. - - Sqrt - ---- - For square root nuklear uses the famous fast inverse square root: - https://en.wikipedia.org/wiki/Fast_inverse_square_root with - slightly tweaked magic constant. While on today's hardware it is - probably not faster it is still fast and accurate enough for - nuklear's use cases. IMPORTANT: this requires float format IEEE 754 - - Sine/Cosine - ----------- - All constants inside both function are generated Remez's minimax - approximations for value range 0...2*PI. The reason why I decided to - approximate exactly that range is that nuklear only needs sine and - cosine to generate circles which only requires that exact range. - In addition I used Remez instead of Taylor for additional precision: - www.lolengine.net/blog/2011/12/21/better-function-approximations. - - The tool I used to generate constants for both sine and cosine - (it can actually approximate a lot more functions) can be - found here: www.lolengine.net/wiki/oss/lolremez -*/ -NK_LIB float -nk_inv_sqrt(float n) -{ - float x2; - const float threehalfs = 1.5f; - union {nk_uint i; float f;} conv = {0}; - conv.f = n; - x2 = n * 0.5f; - conv.i = 0x5f375A84 - (conv.i >> 1); - conv.f = conv.f * (threehalfs - (x2 * conv.f * conv.f)); - return conv.f; -} -NK_LIB float -nk_sqrt(float x) -{ - return x * nk_inv_sqrt(x); -} -NK_LIB float -nk_sin(float x) -{ - NK_STORAGE const float a0 = +1.91059300966915117e-31f; - NK_STORAGE const float a1 = +1.00086760103908896f; - NK_STORAGE const float a2 = -1.21276126894734565e-2f; - NK_STORAGE const float a3 = -1.38078780785773762e-1f; - NK_STORAGE const float a4 = -2.67353392911981221e-2f; - NK_STORAGE const float a5 = +2.08026600266304389e-2f; - NK_STORAGE const float a6 = -3.03996055049204407e-3f; - NK_STORAGE const float a7 = +1.38235642404333740e-4f; - return a0 + x*(a1 + x*(a2 + x*(a3 + x*(a4 + x*(a5 + x*(a6 + x*a7)))))); -} -NK_LIB float -nk_cos(float x) -{ - NK_STORAGE const float a0 = +1.00238601909309722f; - NK_STORAGE const float a1 = -3.81919947353040024e-2f; - NK_STORAGE const float a2 = -3.94382342128062756e-1f; - NK_STORAGE const float a3 = -1.18134036025221444e-1f; - NK_STORAGE const float a4 = +1.07123798512170878e-1f; - NK_STORAGE const float a5 = -1.86637164165180873e-2f; - NK_STORAGE const float a6 = +9.90140908664079833e-4f; - NK_STORAGE const float a7 = -5.23022132118824778e-14f; - return a0 + x*(a1 + x*(a2 + x*(a3 + x*(a4 + x*(a5 + x*(a6 + x*a7)))))); -} -NK_LIB nk_uint -nk_round_up_pow2(nk_uint v) -{ - v--; - v |= v >> 1; - v |= v >> 2; - v |= v >> 4; - v |= v >> 8; - v |= v >> 16; - v++; - return v; -} -NK_LIB double -nk_pow(double x, int n) -{ - /* check the sign of n */ - double r = 1; - int plus = n >= 0; - n = (plus) ? n : -n; - while (n > 0) { - if ((n & 1) == 1) - r *= x; - n /= 2; - x *= x; - } - return plus ? r : 1.0 / r; -} -NK_LIB int -nk_ifloord(double x) -{ - x = (double)((int)x - ((x < 0.0) ? 1 : 0)); - return (int)x; -} -NK_LIB int -nk_ifloorf(float x) -{ - x = (float)((int)x - ((x < 0.0f) ? 1 : 0)); - return (int)x; -} -NK_LIB int -nk_iceilf(float x) -{ - if (x >= 0) { - int i = (int)x; - return (x > i) ? i+1: i; - } else { - int t = (int)x; - float r = x - (float)t; - return (r > 0.0f) ? t+1: t; - } -} -NK_LIB int -nk_log10(double n) -{ - int neg; - int ret; - int exp = 0; - - neg = (n < 0) ? 1 : 0; - ret = (neg) ? (int)-n : (int)n; - while ((ret / 10) > 0) { - ret /= 10; - exp++; - } - if (neg) exp = -exp; - return exp; -} -NK_API struct nk_rect -nk_get_null_rect(void) -{ - return nk_null_rect; -} -NK_API struct nk_rect -nk_rect(float x, float y, float w, float h) -{ - struct nk_rect r; - r.x = x; r.y = y; - r.w = w; r.h = h; - return r; -} -NK_API struct nk_rect -nk_recti(int x, int y, int w, int h) -{ - struct nk_rect r; - r.x = (float)x; - r.y = (float)y; - r.w = (float)w; - r.h = (float)h; - return r; -} -NK_API struct nk_rect -nk_recta(struct nk_vec2 pos, struct nk_vec2 size) -{ - return nk_rect(pos.x, pos.y, size.x, size.y); -} -NK_API struct nk_rect -nk_rectv(const float *r) -{ - return nk_rect(r[0], r[1], r[2], r[3]); -} -NK_API struct nk_rect -nk_rectiv(const int *r) -{ - return nk_recti(r[0], r[1], r[2], r[3]); -} -NK_API struct nk_vec2 -nk_rect_pos(struct nk_rect r) -{ - struct nk_vec2 ret; - ret.x = r.x; ret.y = r.y; - return ret; -} -NK_API struct nk_vec2 -nk_rect_size(struct nk_rect r) -{ - struct nk_vec2 ret; - ret.x = r.w; ret.y = r.h; - return ret; -} -NK_LIB struct nk_rect -nk_shrink_rect(struct nk_rect r, float amount) -{ - struct nk_rect res; - r.w = NK_MAX(r.w, 2 * amount); - r.h = NK_MAX(r.h, 2 * amount); - res.x = r.x + amount; - res.y = r.y + amount; - res.w = r.w - 2 * amount; - res.h = r.h - 2 * amount; - return res; -} -NK_LIB struct nk_rect -nk_pad_rect(struct nk_rect r, struct nk_vec2 pad) -{ - r.w = NK_MAX(r.w, 2 * pad.x); - r.h = NK_MAX(r.h, 2 * pad.y); - r.x += pad.x; r.y += pad.y; - r.w -= 2 * pad.x; - r.h -= 2 * pad.y; - return r; -} -NK_API struct nk_vec2 -nk_vec2(float x, float y) -{ - struct nk_vec2 ret; - ret.x = x; ret.y = y; - return ret; -} -NK_API struct nk_vec2 -nk_vec2i(int x, int y) -{ - struct nk_vec2 ret; - ret.x = (float)x; - ret.y = (float)y; - return ret; -} -NK_API struct nk_vec2 -nk_vec2v(const float *v) -{ - return nk_vec2(v[0], v[1]); -} -NK_API struct nk_vec2 -nk_vec2iv(const int *v) -{ - return nk_vec2i(v[0], v[1]); -} -NK_LIB void -nk_unify(struct nk_rect *clip, const struct nk_rect *a, float x0, float y0, - float x1, float y1) -{ - NK_ASSERT(a); - NK_ASSERT(clip); - clip->x = NK_MAX(a->x, x0); - clip->y = NK_MAX(a->y, y0); - clip->w = NK_MIN(a->x + a->w, x1) - clip->x; - clip->h = NK_MIN(a->y + a->h, y1) - clip->y; - clip->w = NK_MAX(0, clip->w); - clip->h = NK_MAX(0, clip->h); -} - -NK_API void -nk_triangle_from_direction(struct nk_vec2 *result, struct nk_rect r, - float pad_x, float pad_y, enum nk_heading direction) -{ - float w_half, h_half; - NK_ASSERT(result); - - r.w = NK_MAX(2 * pad_x, r.w); - r.h = NK_MAX(2 * pad_y, r.h); - r.w = r.w - 2 * pad_x; - r.h = r.h - 2 * pad_y; - - r.x = r.x + pad_x; - r.y = r.y + pad_y; - - w_half = r.w / 2.0f; - h_half = r.h / 2.0f; - - if (direction == NK_UP) { - result[0] = nk_vec2(r.x + w_half, r.y); - result[1] = nk_vec2(r.x + r.w, r.y + r.h); - result[2] = nk_vec2(r.x, r.y + r.h); - } else if (direction == NK_RIGHT) { - result[0] = nk_vec2(r.x, r.y); - result[1] = nk_vec2(r.x + r.w, r.y + h_half); - result[2] = nk_vec2(r.x, r.y + r.h); - } else if (direction == NK_DOWN) { - result[0] = nk_vec2(r.x, r.y); - result[1] = nk_vec2(r.x + r.w, r.y); - result[2] = nk_vec2(r.x + w_half, r.y + r.h); - } else { - result[0] = nk_vec2(r.x, r.y + h_half); - result[1] = nk_vec2(r.x + r.w, r.y); - result[2] = nk_vec2(r.x + r.w, r.y + r.h); - } -} - - - - - -/* =============================================================== - * - * UTIL - * - * ===============================================================*/ -NK_INTERN int nk_str_match_here(const char *regexp, const char *text); -NK_INTERN int nk_str_match_star(int c, const char *regexp, const char *text); -NK_LIB int nk_is_lower(int c) {return (c >= 'a' && c <= 'z') || (c >= 0xE0 && c <= 0xFF);} -NK_LIB int nk_is_upper(int c){return (c >= 'A' && c <= 'Z') || (c >= 0xC0 && c <= 0xDF);} -NK_LIB int nk_to_upper(int c) {return (c >= 'a' && c <= 'z') ? (c - ('a' - 'A')) : c;} -NK_LIB int nk_to_lower(int c) {return (c >= 'A' && c <= 'Z') ? (c - ('a' + 'A')) : c;} - -NK_LIB void* -nk_memcopy(void *dst0, const void *src0, nk_size length) -{ - nk_ptr t; - char *dst = (char*)dst0; - const char *src = (const char*)src0; - if (length == 0 || dst == src) - goto done; - - #define nk_word int - #define nk_wsize sizeof(nk_word) - #define nk_wmask (nk_wsize-1) - #define NK_TLOOP(s) if (t) NK_TLOOP1(s) - #define NK_TLOOP1(s) do { s; } while (--t) - - if (dst < src) { - t = (nk_ptr)src; /* only need low bits */ - if ((t | (nk_ptr)dst) & nk_wmask) { - if ((t ^ (nk_ptr)dst) & nk_wmask || length < nk_wsize) - t = length; - else - t = nk_wsize - (t & nk_wmask); - length -= t; - NK_TLOOP1(*dst++ = *src++); - } - t = length / nk_wsize; - NK_TLOOP(*(nk_word*)(void*)dst = *(const nk_word*)(const void*)src; - src += nk_wsize; dst += nk_wsize); - t = length & nk_wmask; - NK_TLOOP(*dst++ = *src++); - } else { - src += length; - dst += length; - t = (nk_ptr)src; - if ((t | (nk_ptr)dst) & nk_wmask) { - if ((t ^ (nk_ptr)dst) & nk_wmask || length <= nk_wsize) - t = length; - else - t &= nk_wmask; - length -= t; - NK_TLOOP1(*--dst = *--src); - } - t = length / nk_wsize; - NK_TLOOP(src -= nk_wsize; dst -= nk_wsize; - *(nk_word*)(void*)dst = *(const nk_word*)(const void*)src); - t = length & nk_wmask; - NK_TLOOP(*--dst = *--src); - } - #undef nk_word - #undef nk_wsize - #undef nk_wmask - #undef NK_TLOOP - #undef NK_TLOOP1 -done: - return (dst0); -} -NK_LIB void -nk_memset(void *ptr, int c0, nk_size size) -{ - #define nk_word unsigned - #define nk_wsize sizeof(nk_word) - #define nk_wmask (nk_wsize - 1) - nk_byte *dst = (nk_byte*)ptr; - unsigned c = 0; - nk_size t = 0; - - if ((c = (nk_byte)c0) != 0) { - c = (c << 8) | c; /* at least 16-bits */ - if (sizeof(unsigned int) > 2) - c = (c << 16) | c; /* at least 32-bits*/ - } - - /* too small of a word count */ - dst = (nk_byte*)ptr; - if (size < 3 * nk_wsize) { - while (size--) *dst++ = (nk_byte)c0; - return; - } - - /* align destination */ - if ((t = NK_PTR_TO_UINT(dst) & nk_wmask) != 0) { - t = nk_wsize -t; - size -= t; - do { - *dst++ = (nk_byte)c0; - } while (--t != 0); - } - - /* fill word */ - t = size / nk_wsize; - do { - *(nk_word*)((void*)dst) = c; - dst += nk_wsize; - } while (--t != 0); - - /* fill trailing bytes */ - t = (size & nk_wmask); - if (t != 0) { - do { - *dst++ = (nk_byte)c0; - } while (--t != 0); - } - - #undef nk_word - #undef nk_wsize - #undef nk_wmask -} -NK_LIB void -nk_zero(void *ptr, nk_size size) -{ - NK_ASSERT(ptr); - NK_MEMSET(ptr, 0, size); -} -NK_API int -nk_strlen(const char *str) -{ - int siz = 0; - NK_ASSERT(str); - while (str && *str++ != '\0') siz++; - return siz; -} -NK_API int -nk_strtoi(const char *str, const char **endptr) -{ - int neg = 1; - const char *p = str; - int value = 0; - - NK_ASSERT(str); - if (!str) return 0; - - /* skip whitespace */ - while (*p == ' ') p++; - if (*p == '-') { - neg = -1; - p++; - } - while (*p && *p >= '0' && *p <= '9') { - value = value * 10 + (int) (*p - '0'); - p++; - } - if (endptr) - *endptr = p; - return neg*value; -} -NK_API double -nk_strtod(const char *str, const char **endptr) -{ - double m; - double neg = 1.0; - const char *p = str; - double value = 0; - double number = 0; - - NK_ASSERT(str); - if (!str) return 0; - - /* skip whitespace */ - while (*p == ' ') p++; - if (*p == '-') { - neg = -1.0; - p++; - } - - while (*p && *p != '.' && *p != 'e') { - value = value * 10.0 + (double) (*p - '0'); - p++; - } - - if (*p == '.') { - p++; - for(m = 0.1; *p && *p != 'e'; p++ ) { - value = value + (double) (*p - '0') * m; - m *= 0.1; - } - } - if (*p == 'e') { - int i, pow, div; - p++; - if (*p == '-') { - div = nk_true; - p++; - } else if (*p == '+') { - div = nk_false; - p++; - } else div = nk_false; - - for (pow = 0; *p; p++) - pow = pow * 10 + (int) (*p - '0'); - - for (m = 1.0, i = 0; i < pow; i++) - m *= 10.0; - - if (div) - value /= m; - else value *= m; - } - number = value * neg; - if (endptr) - *endptr = p; - return number; -} -NK_API float -nk_strtof(const char *str, const char **endptr) -{ - float float_value; - double double_value; - double_value = NK_STRTOD(str, endptr); - float_value = (float)double_value; - return float_value; -} -NK_API int -nk_stricmp(const char *s1, const char *s2) -{ - nk_int c1,c2,d; - do { - c1 = *s1++; - c2 = *s2++; - d = c1 - c2; - while (d) { - if (c1 <= 'Z' && c1 >= 'A') { - d += ('a' - 'A'); - if (!d) break; - } - if (c2 <= 'Z' && c2 >= 'A') { - d -= ('a' - 'A'); - if (!d) break; - } - return ((d >= 0) << 1) - 1; - } - } while (c1); - return 0; -} -NK_API int -nk_stricmpn(const char *s1, const char *s2, int n) -{ - int c1,c2,d; - NK_ASSERT(n >= 0); - do { - c1 = *s1++; - c2 = *s2++; - if (!n--) return 0; - - d = c1 - c2; - while (d) { - if (c1 <= 'Z' && c1 >= 'A') { - d += ('a' - 'A'); - if (!d) break; - } - if (c2 <= 'Z' && c2 >= 'A') { - d -= ('a' - 'A'); - if (!d) break; - } - return ((d >= 0) << 1) - 1; - } - } while (c1); - return 0; -} -NK_INTERN int -nk_str_match_here(const char *regexp, const char *text) -{ - if (regexp[0] == '\0') - return 1; - if (regexp[1] == '*') - return nk_str_match_star(regexp[0], regexp+2, text); - if (regexp[0] == '$' && regexp[1] == '\0') - return *text == '\0'; - if (*text!='\0' && (regexp[0]=='.' || regexp[0]==*text)) - return nk_str_match_here(regexp+1, text+1); - return 0; -} -NK_INTERN int -nk_str_match_star(int c, const char *regexp, const char *text) -{ - do {/* a '* matches zero or more instances */ - if (nk_str_match_here(regexp, text)) - return 1; - } while (*text != '\0' && (*text++ == c || c == '.')); - return 0; -} -NK_API int -nk_strfilter(const char *text, const char *regexp) -{ - /* - c matches any literal character c - . matches any single character - ^ matches the beginning of the input string - $ matches the end of the input string - * matches zero or more occurrences of the previous character*/ - if (regexp[0] == '^') - return nk_str_match_here(regexp+1, text); - do { /* must look even if string is empty */ - if (nk_str_match_here(regexp, text)) - return 1; - } while (*text++ != '\0'); - return 0; -} -NK_API int -nk_strmatch_fuzzy_text(const char *str, int str_len, - const char *pattern, int *out_score) -{ - /* Returns true if each character in pattern is found sequentially within str - * if found then out_score is also set. Score value has no intrinsic meaning. - * Range varies with pattern. Can only compare scores with same search pattern. */ - - /* bonus for adjacent matches */ - #define NK_ADJACENCY_BONUS 5 - /* bonus if match occurs after a separator */ - #define NK_SEPARATOR_BONUS 10 - /* bonus if match is uppercase and prev is lower */ - #define NK_CAMEL_BONUS 10 - /* penalty applied for every letter in str before the first match */ - #define NK_LEADING_LETTER_PENALTY (-3) - /* maximum penalty for leading letters */ - #define NK_MAX_LEADING_LETTER_PENALTY (-9) - /* penalty for every letter that doesn't matter */ - #define NK_UNMATCHED_LETTER_PENALTY (-1) - - /* loop variables */ - int score = 0; - char const * pattern_iter = pattern; - int str_iter = 0; - int prev_matched = nk_false; - int prev_lower = nk_false; - /* true so if first letter match gets separator bonus*/ - int prev_separator = nk_true; - - /* use "best" matched letter if multiple string letters match the pattern */ - char const * best_letter = 0; - int best_letter_score = 0; - - /* loop over strings */ - NK_ASSERT(str); - NK_ASSERT(pattern); - if (!str || !str_len || !pattern) return 0; - while (str_iter < str_len) - { - const char pattern_letter = *pattern_iter; - const char str_letter = str[str_iter]; - - int next_match = *pattern_iter != '\0' && - nk_to_lower(pattern_letter) == nk_to_lower(str_letter); - int rematch = best_letter && nk_to_upper(*best_letter) == nk_to_upper(str_letter); - - int advanced = next_match && best_letter; - int pattern_repeat = best_letter && *pattern_iter != '\0'; - pattern_repeat = pattern_repeat && - nk_to_lower(*best_letter) == nk_to_lower(pattern_letter); - - if (advanced || pattern_repeat) { - score += best_letter_score; - best_letter = 0; - best_letter_score = 0; - } - - if (next_match || rematch) - { - int new_score = 0; - /* Apply penalty for each letter before the first pattern match */ - if (pattern_iter == pattern) { - int count = (int)(&str[str_iter] - str); - int penalty = NK_LEADING_LETTER_PENALTY * count; - if (penalty < NK_MAX_LEADING_LETTER_PENALTY) - penalty = NK_MAX_LEADING_LETTER_PENALTY; - - score += penalty; - } - - /* apply bonus for consecutive bonuses */ - if (prev_matched) - new_score += NK_ADJACENCY_BONUS; - - /* apply bonus for matches after a separator */ - if (prev_separator) - new_score += NK_SEPARATOR_BONUS; - - /* apply bonus across camel case boundaries */ - if (prev_lower && nk_is_upper(str_letter)) - new_score += NK_CAMEL_BONUS; - - /* update pattern iter IFF the next pattern letter was matched */ - if (next_match) - ++pattern_iter; - - /* update best letter in str which may be for a "next" letter or a rematch */ - if (new_score >= best_letter_score) { - /* apply penalty for now skipped letter */ - if (best_letter != 0) - score += NK_UNMATCHED_LETTER_PENALTY; - - best_letter = &str[str_iter]; - best_letter_score = new_score; - } - prev_matched = nk_true; - } else { - score += NK_UNMATCHED_LETTER_PENALTY; - prev_matched = nk_false; - } - - /* separators should be more easily defined */ - prev_lower = nk_is_lower(str_letter) != 0; - prev_separator = str_letter == '_' || str_letter == ' '; - - ++str_iter; - } - - /* apply score for last match */ - if (best_letter) - score += best_letter_score; - - /* did not match full pattern */ - if (*pattern_iter != '\0') - return nk_false; - - if (out_score) - *out_score = score; - return nk_true; -} -NK_API int -nk_strmatch_fuzzy_string(char const *str, char const *pattern, int *out_score) -{ - return nk_strmatch_fuzzy_text(str, nk_strlen(str), pattern, out_score); -} -NK_LIB int -nk_string_float_limit(char *string, int prec) -{ - int dot = 0; - char *c = string; - while (*c) { - if (*c == '.') { - dot = 1; - c++; - continue; - } - if (dot == (prec+1)) { - *c = 0; - break; - } - if (dot > 0) dot++; - c++; - } - return (int)(c - string); -} -NK_INTERN void -nk_strrev_ascii(char *s) -{ - int len = nk_strlen(s); - int end = len / 2; - int i = 0; - char t; - for (; i < end; ++i) { - t = s[i]; - s[i] = s[len - 1 - i]; - s[len -1 - i] = t; - } -} -NK_LIB char* -nk_itoa(char *s, long n) -{ - long i = 0; - if (n == 0) { - s[i++] = '0'; - s[i] = 0; - return s; - } - if (n < 0) { - s[i++] = '-'; - n = -n; - } - while (n > 0) { - s[i++] = (char)('0' + (n % 10)); - n /= 10; - } - s[i] = 0; - if (s[0] == '-') - ++s; - - nk_strrev_ascii(s); - return s; -} -NK_LIB char* -nk_dtoa(char *s, double n) -{ - int useExp = 0; - int digit = 0, m = 0, m1 = 0; - char *c = s; - int neg = 0; - - NK_ASSERT(s); - if (!s) return 0; - - if (n == 0.0) { - s[0] = '0'; s[1] = '\0'; - return s; - } - - neg = (n < 0); - if (neg) n = -n; - - /* calculate magnitude */ - m = nk_log10(n); - useExp = (m >= 14 || (neg && m >= 9) || m <= -9); - if (neg) *(c++) = '-'; - - /* set up for scientific notation */ - if (useExp) { - if (m < 0) - m -= 1; - n = n / (double)nk_pow(10.0, m); - m1 = m; - m = 0; - } - if (m < 1.0) { - m = 0; - } - - /* convert the number */ - while (n > NK_FLOAT_PRECISION || m >= 0) { - double weight = nk_pow(10.0, m); - if (weight > 0) { - double t = (double)n / weight; - digit = nk_ifloord(t); - n -= ((double)digit * weight); - *(c++) = (char)('0' + (char)digit); - } - if (m == 0 && n > 0) - *(c++) = '.'; - m--; - } - - if (useExp) { - /* convert the exponent */ - int i, j; - *(c++) = 'e'; - if (m1 > 0) { - *(c++) = '+'; - } else { - *(c++) = '-'; - m1 = -m1; - } - m = 0; - while (m1 > 0) { - *(c++) = (char)('0' + (char)(m1 % 10)); - m1 /= 10; - m++; - } - c -= m; - for (i = 0, j = m-1; i= buf_size) break; - iter++; - - /* flag arguments */ - while (*iter) { - if (*iter == '-') flag |= NK_ARG_FLAG_LEFT; - else if (*iter == '+') flag |= NK_ARG_FLAG_PLUS; - else if (*iter == ' ') flag |= NK_ARG_FLAG_SPACE; - else if (*iter == '#') flag |= NK_ARG_FLAG_NUM; - else if (*iter == '0') flag |= NK_ARG_FLAG_ZERO; - else break; - iter++; - } - - /* width argument */ - width = NK_DEFAULT; - if (*iter >= '1' && *iter <= '9') { - const char *end; - width = nk_strtoi(iter, &end); - if (end == iter) - width = -1; - else iter = end; - } else if (*iter == '*') { - width = va_arg(args, int); - iter++; - } - - /* precision argument */ - precision = NK_DEFAULT; - if (*iter == '.') { - iter++; - if (*iter == '*') { - precision = va_arg(args, int); - iter++; - } else { - const char *end; - precision = nk_strtoi(iter, &end); - if (end == iter) - precision = -1; - else iter = end; - } - } - - /* length modifier */ - if (*iter == 'h') { - if (*(iter+1) == 'h') { - arg_type = NK_ARG_TYPE_CHAR; - iter++; - } else arg_type = NK_ARG_TYPE_SHORT; - iter++; - } else if (*iter == 'l') { - arg_type = NK_ARG_TYPE_LONG; - iter++; - } else arg_type = NK_ARG_TYPE_DEFAULT; - - /* specifier */ - if (*iter == '%') { - NK_ASSERT(arg_type == NK_ARG_TYPE_DEFAULT); - NK_ASSERT(precision == NK_DEFAULT); - NK_ASSERT(width == NK_DEFAULT); - if (len < buf_size) - buf[len++] = '%'; - } else if (*iter == 's') { - /* string */ - const char *str = va_arg(args, const char*); - NK_ASSERT(str != buf && "buffer and argument are not allowed to overlap!"); - NK_ASSERT(arg_type == NK_ARG_TYPE_DEFAULT); - NK_ASSERT(precision == NK_DEFAULT); - NK_ASSERT(width == NK_DEFAULT); - if (str == buf) return -1; - while (str && *str && len < buf_size) - buf[len++] = *str++; - } else if (*iter == 'n') { - /* current length callback */ - signed int *n = va_arg(args, int*); - NK_ASSERT(arg_type == NK_ARG_TYPE_DEFAULT); - NK_ASSERT(precision == NK_DEFAULT); - NK_ASSERT(width == NK_DEFAULT); - if (n) *n = len; - } else if (*iter == 'c' || *iter == 'i' || *iter == 'd') { - /* signed integer */ - long value = 0; - const char *num_iter; - int num_len, num_print, padding; - int cur_precision = NK_MAX(precision, 1); - int cur_width = NK_MAX(width, 0); - - /* retrieve correct value type */ - if (arg_type == NK_ARG_TYPE_CHAR) - value = (signed char)va_arg(args, int); - else if (arg_type == NK_ARG_TYPE_SHORT) - value = (signed short)va_arg(args, int); - else if (arg_type == NK_ARG_TYPE_LONG) - value = va_arg(args, signed long); - else if (*iter == 'c') - value = (unsigned char)va_arg(args, int); - else value = va_arg(args, signed int); - - /* convert number to string */ - nk_itoa(number_buffer, value); - num_len = nk_strlen(number_buffer); - padding = NK_MAX(cur_width - NK_MAX(cur_precision, num_len), 0); - if ((flag & NK_ARG_FLAG_PLUS) || (flag & NK_ARG_FLAG_SPACE)) - padding = NK_MAX(padding-1, 0); - - /* fill left padding up to a total of `width` characters */ - if (!(flag & NK_ARG_FLAG_LEFT)) { - while (padding-- > 0 && (len < buf_size)) { - if ((flag & NK_ARG_FLAG_ZERO) && (precision == NK_DEFAULT)) - buf[len++] = '0'; - else buf[len++] = ' '; - } - } - - /* copy string value representation into buffer */ - if ((flag & NK_ARG_FLAG_PLUS) && value >= 0 && len < buf_size) - buf[len++] = '+'; - else if ((flag & NK_ARG_FLAG_SPACE) && value >= 0 && len < buf_size) - buf[len++] = ' '; - - /* fill up to precision number of digits with '0' */ - num_print = NK_MAX(cur_precision, num_len); - while (precision && (num_print > num_len) && (len < buf_size)) { - buf[len++] = '0'; - num_print--; - } - - /* copy string value representation into buffer */ - num_iter = number_buffer; - while (precision && *num_iter && len < buf_size) - buf[len++] = *num_iter++; - - /* fill right padding up to width characters */ - if (flag & NK_ARG_FLAG_LEFT) { - while ((padding-- > 0) && (len < buf_size)) - buf[len++] = ' '; - } - } else if (*iter == 'o' || *iter == 'x' || *iter == 'X' || *iter == 'u') { - /* unsigned integer */ - unsigned long value = 0; - int num_len = 0, num_print, padding = 0; - int cur_precision = NK_MAX(precision, 1); - int cur_width = NK_MAX(width, 0); - unsigned int base = (*iter == 'o') ? 8: (*iter == 'u')? 10: 16; - - /* print oct/hex/dec value */ - const char *upper_output_format = "0123456789ABCDEF"; - const char *lower_output_format = "0123456789abcdef"; - const char *output_format = (*iter == 'x') ? - lower_output_format: upper_output_format; - - /* retrieve correct value type */ - if (arg_type == NK_ARG_TYPE_CHAR) - value = (unsigned char)va_arg(args, int); - else if (arg_type == NK_ARG_TYPE_SHORT) - value = (unsigned short)va_arg(args, int); - else if (arg_type == NK_ARG_TYPE_LONG) - value = va_arg(args, unsigned long); - else value = va_arg(args, unsigned int); - - do { - /* convert decimal number into hex/oct number */ - int digit = output_format[value % base]; - if (num_len < NK_MAX_NUMBER_BUFFER) - number_buffer[num_len++] = (char)digit; - value /= base; - } while (value > 0); - - num_print = NK_MAX(cur_precision, num_len); - padding = NK_MAX(cur_width - NK_MAX(cur_precision, num_len), 0); - if (flag & NK_ARG_FLAG_NUM) - padding = NK_MAX(padding-1, 0); - - /* fill left padding up to a total of `width` characters */ - if (!(flag & NK_ARG_FLAG_LEFT)) { - while ((padding-- > 0) && (len < buf_size)) { - if ((flag & NK_ARG_FLAG_ZERO) && (precision == NK_DEFAULT)) - buf[len++] = '0'; - else buf[len++] = ' '; - } - } - - /* fill up to precision number of digits */ - if (num_print && (flag & NK_ARG_FLAG_NUM)) { - if ((*iter == 'o') && (len < buf_size)) { - buf[len++] = '0'; - } else if ((*iter == 'x') && ((len+1) < buf_size)) { - buf[len++] = '0'; - buf[len++] = 'x'; - } else if ((*iter == 'X') && ((len+1) < buf_size)) { - buf[len++] = '0'; - buf[len++] = 'X'; - } - } - while (precision && (num_print > num_len) && (len < buf_size)) { - buf[len++] = '0'; - num_print--; - } - - /* reverse number direction */ - while (num_len > 0) { - if (precision && (len < buf_size)) - buf[len++] = number_buffer[num_len-1]; - num_len--; - } - - /* fill right padding up to width characters */ - if (flag & NK_ARG_FLAG_LEFT) { - while ((padding-- > 0) && (len < buf_size)) - buf[len++] = ' '; - } - } else if (*iter == 'f') { - /* floating point */ - const char *num_iter; - int cur_precision = (precision < 0) ? 6: precision; - int prefix, cur_width = NK_MAX(width, 0); - double value = va_arg(args, double); - int num_len = 0, frac_len = 0, dot = 0; - int padding = 0; - - NK_ASSERT(arg_type == NK_ARG_TYPE_DEFAULT); - NK_DTOA(number_buffer, value); - num_len = nk_strlen(number_buffer); - - /* calculate padding */ - num_iter = number_buffer; - while (*num_iter && *num_iter != '.') - num_iter++; - - prefix = (*num_iter == '.')?(int)(num_iter - number_buffer)+1:0; - padding = NK_MAX(cur_width - (prefix + NK_MIN(cur_precision, num_len - prefix)) , 0); - if ((flag & NK_ARG_FLAG_PLUS) || (flag & NK_ARG_FLAG_SPACE)) - padding = NK_MAX(padding-1, 0); - - /* fill left padding up to a total of `width` characters */ - if (!(flag & NK_ARG_FLAG_LEFT)) { - while (padding-- > 0 && (len < buf_size)) { - if (flag & NK_ARG_FLAG_ZERO) - buf[len++] = '0'; - else buf[len++] = ' '; - } - } - - /* copy string value representation into buffer */ - num_iter = number_buffer; - if ((flag & NK_ARG_FLAG_PLUS) && (value >= 0) && (len < buf_size)) - buf[len++] = '+'; - else if ((flag & NK_ARG_FLAG_SPACE) && (value >= 0) && (len < buf_size)) - buf[len++] = ' '; - while (*num_iter) { - if (dot) frac_len++; - if (len < buf_size) - buf[len++] = *num_iter; - if (*num_iter == '.') dot = 1; - if (frac_len >= cur_precision) break; - num_iter++; - } - - /* fill number up to precision */ - while (frac_len < cur_precision) { - if (!dot && len < buf_size) { - buf[len++] = '.'; - dot = 1; - } - if (len < buf_size) - buf[len++] = '0'; - frac_len++; - } - - /* fill right padding up to width characters */ - if (flag & NK_ARG_FLAG_LEFT) { - while ((padding-- > 0) && (len < buf_size)) - buf[len++] = ' '; - } - } else { - /* Specifier not supported: g,G,e,E,p,z */ - NK_ASSERT(0 && "specifier is not supported!"); - return result; - } - } - buf[(len >= buf_size)?(buf_size-1):len] = 0; - result = (len >= buf_size)?-1:len; - return result; -} -#endif -NK_LIB int -nk_strfmt(char *buf, int buf_size, const char *fmt, va_list args) -{ - int result = -1; - NK_ASSERT(buf); - NK_ASSERT(buf_size); - if (!buf || !buf_size || !fmt) return 0; -#ifdef NK_INCLUDE_STANDARD_IO - result = NK_VSNPRINTF(buf, (nk_size)buf_size, fmt, args); - result = (result >= buf_size) ? -1: result; - buf[buf_size-1] = 0; -#else - result = nk_vsnprintf(buf, buf_size, fmt, args); -#endif - return result; -} -#endif -NK_API nk_hash -nk_murmur_hash(const void * key, int len, nk_hash seed) -{ - /* 32-Bit MurmurHash3: https://code.google.com/p/smhasher/wiki/MurmurHash3*/ - #define NK_ROTL(x,r) ((x) << (r) | ((x) >> (32 - r))) - union {const nk_uint *i; const nk_byte *b;} conv = {0}; - const nk_byte *data = (const nk_byte*)key; - const int nblocks = len/4; - nk_uint h1 = seed; - const nk_uint c1 = 0xcc9e2d51; - const nk_uint c2 = 0x1b873593; - const nk_byte *tail; - const nk_uint *blocks; - nk_uint k1; - int i; - - /* body */ - if (!key) return 0; - conv.b = (data + nblocks*4); - blocks = (const nk_uint*)conv.i; - for (i = -nblocks; i; ++i) { - k1 = blocks[i]; - k1 *= c1; - k1 = NK_ROTL(k1,15); - k1 *= c2; - - h1 ^= k1; - h1 = NK_ROTL(h1,13); - h1 = h1*5+0xe6546b64; - } - - /* tail */ - tail = (const nk_byte*)(data + nblocks*4); - k1 = 0; - switch (len & 3) { - case 3: k1 ^= (nk_uint)(tail[2] << 16); /* fallthrough */ - case 2: k1 ^= (nk_uint)(tail[1] << 8u); /* fallthrough */ - case 1: k1 ^= tail[0]; - k1 *= c1; - k1 = NK_ROTL(k1,15); - k1 *= c2; - h1 ^= k1; - break; - default: break; - } - - /* finalization */ - h1 ^= (nk_uint)len; - /* fmix32 */ - h1 ^= h1 >> 16; - h1 *= 0x85ebca6b; - h1 ^= h1 >> 13; - h1 *= 0xc2b2ae35; - h1 ^= h1 >> 16; - - #undef NK_ROTL - return h1; -} -#ifdef NK_INCLUDE_STANDARD_IO -NK_LIB char* -nk_file_load(const char* path, nk_size* siz, struct nk_allocator *alloc) -{ - char *buf; - FILE *fd; - long ret; - - NK_ASSERT(path); - NK_ASSERT(siz); - NK_ASSERT(alloc); - if (!path || !siz || !alloc) - return 0; - - fd = fopen(path, "rb"); - if (!fd) return 0; - fseek(fd, 0, SEEK_END); - ret = ftell(fd); - if (ret < 0) { - fclose(fd); - return 0; - } - *siz = (nk_size)ret; - fseek(fd, 0, SEEK_SET); - buf = (char*)alloc->alloc(alloc->userdata,0, *siz); - NK_ASSERT(buf); - if (!buf) { - fclose(fd); - return 0; - } - *siz = (nk_size)fread(buf, 1,*siz, fd); - fclose(fd); - return buf; -} -#endif -NK_LIB int -nk_text_clamp(const struct nk_user_font *font, const char *text, - int text_len, float space, int *glyphs, float *text_width, - nk_rune *sep_list, int sep_count) -{ - int i = 0; - int glyph_len = 0; - float last_width = 0; - nk_rune unicode = 0; - float width = 0; - int len = 0; - int g = 0; - float s; - - int sep_len = 0; - int sep_g = 0; - float sep_width = 0; - sep_count = NK_MAX(sep_count,0); - - glyph_len = nk_utf_decode(text, &unicode, text_len); - while (glyph_len && (width < space) && (len < text_len)) { - len += glyph_len; - s = font->width(font->userdata, font->height, text, len); - for (i = 0; i < sep_count; ++i) { - if (unicode != sep_list[i]) continue; - sep_width = last_width = width; - sep_g = g+1; - sep_len = len; - break; - } - if (i == sep_count){ - last_width = sep_width = width; - sep_g = g+1; - } - width = s; - glyph_len = nk_utf_decode(&text[len], &unicode, text_len - len); - g++; - } - if (len >= text_len) { - *glyphs = g; - *text_width = last_width; - return len; - } else { - *glyphs = sep_g; - *text_width = sep_width; - return (!sep_len) ? len: sep_len; - } -} -NK_LIB struct nk_vec2 -nk_text_calculate_text_bounds(const struct nk_user_font *font, - const char *begin, int byte_len, float row_height, const char **remaining, - struct nk_vec2 *out_offset, int *glyphs, int op) -{ - float line_height = row_height; - struct nk_vec2 text_size = nk_vec2(0,0); - float line_width = 0.0f; - - float glyph_width; - int glyph_len = 0; - nk_rune unicode = 0; - int text_len = 0; - if (!begin || byte_len <= 0 || !font) - return nk_vec2(0,row_height); - - glyph_len = nk_utf_decode(begin, &unicode, byte_len); - if (!glyph_len) return text_size; - glyph_width = font->width(font->userdata, font->height, begin, glyph_len); - - *glyphs = 0; - while ((text_len < byte_len) && glyph_len) { - if (unicode == '\n') { - text_size.x = NK_MAX(text_size.x, line_width); - text_size.y += line_height; - line_width = 0; - *glyphs+=1; - if (op == NK_STOP_ON_NEW_LINE) - break; - - text_len++; - glyph_len = nk_utf_decode(begin + text_len, &unicode, byte_len-text_len); - continue; - } - - if (unicode == '\r') { - text_len++; - *glyphs+=1; - glyph_len = nk_utf_decode(begin + text_len, &unicode, byte_len-text_len); - continue; - } - - *glyphs = *glyphs + 1; - text_len += glyph_len; - line_width += (float)glyph_width; - glyph_len = nk_utf_decode(begin + text_len, &unicode, byte_len-text_len); - glyph_width = font->width(font->userdata, font->height, begin+text_len, glyph_len); - continue; - } - - if (text_size.x < line_width) - text_size.x = line_width; - if (out_offset) - *out_offset = nk_vec2(line_width, text_size.y + line_height); - if (line_width > 0 || text_size.y == 0.0f) - text_size.y += line_height; - if (remaining) - *remaining = begin+text_len; - return text_size; -} - - - - - -/* ============================================================== - * - * COLOR - * - * ===============================================================*/ -NK_INTERN int -nk_parse_hex(const char *p, int length) -{ - int i = 0; - int len = 0; - while (len < length) { - i <<= 4; - if (p[len] >= 'a' && p[len] <= 'f') - i += ((p[len] - 'a') + 10); - else if (p[len] >= 'A' && p[len] <= 'F') - i += ((p[len] - 'A') + 10); - else i += (p[len] - '0'); - len++; - } - return i; -} -NK_API struct nk_color -nk_rgba(int r, int g, int b, int a) -{ - struct nk_color ret; - ret.r = (nk_byte)NK_CLAMP(0, r, 255); - ret.g = (nk_byte)NK_CLAMP(0, g, 255); - ret.b = (nk_byte)NK_CLAMP(0, b, 255); - ret.a = (nk_byte)NK_CLAMP(0, a, 255); - return ret; -} -NK_API struct nk_color -nk_rgb_hex(const char *rgb) -{ - struct nk_color col; - const char *c = rgb; - if (*c == '#') c++; - col.r = (nk_byte)nk_parse_hex(c, 2); - col.g = (nk_byte)nk_parse_hex(c+2, 2); - col.b = (nk_byte)nk_parse_hex(c+4, 2); - col.a = 255; - return col; -} -NK_API struct nk_color -nk_rgba_hex(const char *rgb) -{ - struct nk_color col; - const char *c = rgb; - if (*c == '#') c++; - col.r = (nk_byte)nk_parse_hex(c, 2); - col.g = (nk_byte)nk_parse_hex(c+2, 2); - col.b = (nk_byte)nk_parse_hex(c+4, 2); - col.a = (nk_byte)nk_parse_hex(c+6, 2); - return col; -} -NK_API void -nk_color_hex_rgba(char *output, struct nk_color col) -{ - #define NK_TO_HEX(i) ((i) <= 9 ? '0' + (i): 'A' - 10 + (i)) - output[0] = (char)NK_TO_HEX((col.r & 0xF0) >> 4); - output[1] = (char)NK_TO_HEX((col.r & 0x0F)); - output[2] = (char)NK_TO_HEX((col.g & 0xF0) >> 4); - output[3] = (char)NK_TO_HEX((col.g & 0x0F)); - output[4] = (char)NK_TO_HEX((col.b & 0xF0) >> 4); - output[5] = (char)NK_TO_HEX((col.b & 0x0F)); - output[6] = (char)NK_TO_HEX((col.a & 0xF0) >> 4); - output[7] = (char)NK_TO_HEX((col.a & 0x0F)); - output[8] = '\0'; - #undef NK_TO_HEX -} -NK_API void -nk_color_hex_rgb(char *output, struct nk_color col) -{ - #define NK_TO_HEX(i) ((i) <= 9 ? '0' + (i): 'A' - 10 + (i)) - output[0] = (char)NK_TO_HEX((col.r & 0xF0) >> 4); - output[1] = (char)NK_TO_HEX((col.r & 0x0F)); - output[2] = (char)NK_TO_HEX((col.g & 0xF0) >> 4); - output[3] = (char)NK_TO_HEX((col.g & 0x0F)); - output[4] = (char)NK_TO_HEX((col.b & 0xF0) >> 4); - output[5] = (char)NK_TO_HEX((col.b & 0x0F)); - output[6] = '\0'; - #undef NK_TO_HEX -} -NK_API struct nk_color -nk_rgba_iv(const int *c) -{ - return nk_rgba(c[0], c[1], c[2], c[3]); -} -NK_API struct nk_color -nk_rgba_bv(const nk_byte *c) -{ - return nk_rgba(c[0], c[1], c[2], c[3]); -} -NK_API struct nk_color -nk_rgb(int r, int g, int b) -{ - struct nk_color ret; - ret.r = (nk_byte)NK_CLAMP(0, r, 255); - ret.g = (nk_byte)NK_CLAMP(0, g, 255); - ret.b = (nk_byte)NK_CLAMP(0, b, 255); - ret.a = (nk_byte)255; - return ret; -} -NK_API struct nk_color -nk_rgb_iv(const int *c) -{ - return nk_rgb(c[0], c[1], c[2]); -} -NK_API struct nk_color -nk_rgb_bv(const nk_byte* c) -{ - return nk_rgb(c[0], c[1], c[2]); -} -NK_API struct nk_color -nk_rgba_u32(nk_uint in) -{ - struct nk_color ret; - ret.r = (in & 0xFF); - ret.g = ((in >> 8) & 0xFF); - ret.b = ((in >> 16) & 0xFF); - ret.a = (nk_byte)((in >> 24) & 0xFF); - return ret; -} -NK_API struct nk_color -nk_rgba_f(float r, float g, float b, float a) -{ - struct nk_color ret; - ret.r = (nk_byte)(NK_SATURATE(r) * 255.0f); - ret.g = (nk_byte)(NK_SATURATE(g) * 255.0f); - ret.b = (nk_byte)(NK_SATURATE(b) * 255.0f); - ret.a = (nk_byte)(NK_SATURATE(a) * 255.0f); - return ret; -} -NK_API struct nk_color -nk_rgba_fv(const float *c) -{ - return nk_rgba_f(c[0], c[1], c[2], c[3]); -} -NK_API struct nk_color -nk_rgba_cf(struct nk_colorf c) -{ - return nk_rgba_f(c.r, c.g, c.b, c.a); -} -NK_API struct nk_color -nk_rgb_f(float r, float g, float b) -{ - struct nk_color ret; - ret.r = (nk_byte)(NK_SATURATE(r) * 255.0f); - ret.g = (nk_byte)(NK_SATURATE(g) * 255.0f); - ret.b = (nk_byte)(NK_SATURATE(b) * 255.0f); - ret.a = 255; - return ret; -} -NK_API struct nk_color -nk_rgb_fv(const float *c) -{ - return nk_rgb_f(c[0], c[1], c[2]); -} -NK_API struct nk_color -nk_rgb_cf(struct nk_colorf c) -{ - return nk_rgb_f(c.r, c.g, c.b); -} -NK_API struct nk_color -nk_hsv(int h, int s, int v) -{ - return nk_hsva(h, s, v, 255); -} -NK_API struct nk_color -nk_hsv_iv(const int *c) -{ - return nk_hsv(c[0], c[1], c[2]); -} -NK_API struct nk_color -nk_hsv_bv(const nk_byte *c) -{ - return nk_hsv(c[0], c[1], c[2]); -} -NK_API struct nk_color -nk_hsv_f(float h, float s, float v) -{ - return nk_hsva_f(h, s, v, 1.0f); -} -NK_API struct nk_color -nk_hsv_fv(const float *c) -{ - return nk_hsv_f(c[0], c[1], c[2]); -} -NK_API struct nk_color -nk_hsva(int h, int s, int v, int a) -{ - float hf = ((float)NK_CLAMP(0, h, 255)) / 255.0f; - float sf = ((float)NK_CLAMP(0, s, 255)) / 255.0f; - float vf = ((float)NK_CLAMP(0, v, 255)) / 255.0f; - float af = ((float)NK_CLAMP(0, a, 255)) / 255.0f; - return nk_hsva_f(hf, sf, vf, af); -} -NK_API struct nk_color -nk_hsva_iv(const int *c) -{ - return nk_hsva(c[0], c[1], c[2], c[3]); -} -NK_API struct nk_color -nk_hsva_bv(const nk_byte *c) -{ - return nk_hsva(c[0], c[1], c[2], c[3]); -} -NK_API struct nk_colorf -nk_hsva_colorf(float h, float s, float v, float a) -{ - int i; - float p, q, t, f; - struct nk_colorf out = {0,0,0,0}; - if (s <= 0.0f) { - out.r = v; out.g = v; out.b = v; out.a = a; - return out; - } - h = h / (60.0f/360.0f); - i = (int)h; - f = h - (float)i; - p = v * (1.0f - s); - q = v * (1.0f - (s * f)); - t = v * (1.0f - s * (1.0f - f)); - - switch (i) { - case 0: default: out.r = v; out.g = t; out.b = p; break; - case 1: out.r = q; out.g = v; out.b = p; break; - case 2: out.r = p; out.g = v; out.b = t; break; - case 3: out.r = p; out.g = q; out.b = v; break; - case 4: out.r = t; out.g = p; out.b = v; break; - case 5: out.r = v; out.g = p; out.b = q; break;} - out.a = a; - return out; -} -NK_API struct nk_colorf -nk_hsva_colorfv(float *c) -{ - return nk_hsva_colorf(c[0], c[1], c[2], c[3]); -} -NK_API struct nk_color -nk_hsva_f(float h, float s, float v, float a) -{ - struct nk_colorf c = nk_hsva_colorf(h, s, v, a); - return nk_rgba_f(c.r, c.g, c.b, c.a); -} -NK_API struct nk_color -nk_hsva_fv(const float *c) -{ - return nk_hsva_f(c[0], c[1], c[2], c[3]); -} -NK_API nk_uint -nk_color_u32(struct nk_color in) -{ - nk_uint out = (nk_uint)in.r; - out |= ((nk_uint)in.g << 8); - out |= ((nk_uint)in.b << 16); - out |= ((nk_uint)in.a << 24); - return out; -} -NK_API void -nk_color_f(float *r, float *g, float *b, float *a, struct nk_color in) -{ - NK_STORAGE const float s = 1.0f/255.0f; - *r = (float)in.r * s; - *g = (float)in.g * s; - *b = (float)in.b * s; - *a = (float)in.a * s; -} -NK_API void -nk_color_fv(float *c, struct nk_color in) -{ - nk_color_f(&c[0], &c[1], &c[2], &c[3], in); -} -NK_API struct nk_colorf -nk_color_cf(struct nk_color in) -{ - struct nk_colorf o; - nk_color_f(&o.r, &o.g, &o.b, &o.a, in); - return o; -} -NK_API void -nk_color_d(double *r, double *g, double *b, double *a, struct nk_color in) -{ - NK_STORAGE const double s = 1.0/255.0; - *r = (double)in.r * s; - *g = (double)in.g * s; - *b = (double)in.b * s; - *a = (double)in.a * s; -} -NK_API void -nk_color_dv(double *c, struct nk_color in) -{ - nk_color_d(&c[0], &c[1], &c[2], &c[3], in); -} -NK_API void -nk_color_hsv_f(float *out_h, float *out_s, float *out_v, struct nk_color in) -{ - float a; - nk_color_hsva_f(out_h, out_s, out_v, &a, in); -} -NK_API void -nk_color_hsv_fv(float *out, struct nk_color in) -{ - float a; - nk_color_hsva_f(&out[0], &out[1], &out[2], &a, in); -} -NK_API void -nk_colorf_hsva_f(float *out_h, float *out_s, - float *out_v, float *out_a, struct nk_colorf in) -{ - float chroma; - float K = 0.0f; - if (in.g < in.b) { - const float t = in.g; in.g = in.b; in.b = t; - K = -1.f; - } - if (in.r < in.g) { - const float t = in.r; in.r = in.g; in.g = t; - K = -2.f/6.0f - K; - } - chroma = in.r - ((in.g < in.b) ? in.g: in.b); - *out_h = NK_ABS(K + (in.g - in.b)/(6.0f * chroma + 1e-20f)); - *out_s = chroma / (in.r + 1e-20f); - *out_v = in.r; - *out_a = in.a; - -} -NK_API void -nk_colorf_hsva_fv(float *hsva, struct nk_colorf in) -{ - nk_colorf_hsva_f(&hsva[0], &hsva[1], &hsva[2], &hsva[3], in); -} -NK_API void -nk_color_hsva_f(float *out_h, float *out_s, - float *out_v, float *out_a, struct nk_color in) -{ - struct nk_colorf col; - nk_color_f(&col.r,&col.g,&col.b,&col.a, in); - nk_colorf_hsva_f(out_h, out_s, out_v, out_a, col); -} -NK_API void -nk_color_hsva_fv(float *out, struct nk_color in) -{ - nk_color_hsva_f(&out[0], &out[1], &out[2], &out[3], in); -} -NK_API void -nk_color_hsva_i(int *out_h, int *out_s, int *out_v, - int *out_a, struct nk_color in) -{ - float h,s,v,a; - nk_color_hsva_f(&h, &s, &v, &a, in); - *out_h = (nk_byte)(h * 255.0f); - *out_s = (nk_byte)(s * 255.0f); - *out_v = (nk_byte)(v * 255.0f); - *out_a = (nk_byte)(a * 255.0f); -} -NK_API void -nk_color_hsva_iv(int *out, struct nk_color in) -{ - nk_color_hsva_i(&out[0], &out[1], &out[2], &out[3], in); -} -NK_API void -nk_color_hsva_bv(nk_byte *out, struct nk_color in) -{ - int tmp[4]; - nk_color_hsva_i(&tmp[0], &tmp[1], &tmp[2], &tmp[3], in); - out[0] = (nk_byte)tmp[0]; - out[1] = (nk_byte)tmp[1]; - out[2] = (nk_byte)tmp[2]; - out[3] = (nk_byte)tmp[3]; -} -NK_API void -nk_color_hsva_b(nk_byte *h, nk_byte *s, nk_byte *v, nk_byte *a, struct nk_color in) -{ - int tmp[4]; - nk_color_hsva_i(&tmp[0], &tmp[1], &tmp[2], &tmp[3], in); - *h = (nk_byte)tmp[0]; - *s = (nk_byte)tmp[1]; - *v = (nk_byte)tmp[2]; - *a = (nk_byte)tmp[3]; -} -NK_API void -nk_color_hsv_i(int *out_h, int *out_s, int *out_v, struct nk_color in) -{ - int a; - nk_color_hsva_i(out_h, out_s, out_v, &a, in); -} -NK_API void -nk_color_hsv_b(nk_byte *out_h, nk_byte *out_s, nk_byte *out_v, struct nk_color in) -{ - int tmp[4]; - nk_color_hsva_i(&tmp[0], &tmp[1], &tmp[2], &tmp[3], in); - *out_h = (nk_byte)tmp[0]; - *out_s = (nk_byte)tmp[1]; - *out_v = (nk_byte)tmp[2]; -} -NK_API void -nk_color_hsv_iv(int *out, struct nk_color in) -{ - nk_color_hsv_i(&out[0], &out[1], &out[2], in); -} -NK_API void -nk_color_hsv_bv(nk_byte *out, struct nk_color in) -{ - int tmp[4]; - nk_color_hsv_i(&tmp[0], &tmp[1], &tmp[2], in); - out[0] = (nk_byte)tmp[0]; - out[1] = (nk_byte)tmp[1]; - out[2] = (nk_byte)tmp[2]; -} - - - - - -/* =============================================================== - * - * UTF-8 - * - * ===============================================================*/ -NK_GLOBAL const nk_byte nk_utfbyte[NK_UTF_SIZE+1] = {0x80, 0, 0xC0, 0xE0, 0xF0}; -NK_GLOBAL const nk_byte nk_utfmask[NK_UTF_SIZE+1] = {0xC0, 0x80, 0xE0, 0xF0, 0xF8}; -NK_GLOBAL const nk_uint nk_utfmin[NK_UTF_SIZE+1] = {0, 0, 0x80, 0x800, 0x10000}; -NK_GLOBAL const nk_uint nk_utfmax[NK_UTF_SIZE+1] = {0x10FFFF, 0x7F, 0x7FF, 0xFFFF, 0x10FFFF}; - -NK_INTERN int -nk_utf_validate(nk_rune *u, int i) -{ - NK_ASSERT(u); - if (!u) return 0; - if (!NK_BETWEEN(*u, nk_utfmin[i], nk_utfmax[i]) || - NK_BETWEEN(*u, 0xD800, 0xDFFF)) - *u = NK_UTF_INVALID; - for (i = 1; *u > nk_utfmax[i]; ++i); - return i; -} -NK_INTERN nk_rune -nk_utf_decode_byte(char c, int *i) -{ - NK_ASSERT(i); - if (!i) return 0; - for(*i = 0; *i < (int)NK_LEN(nk_utfmask); ++(*i)) { - if (((nk_byte)c & nk_utfmask[*i]) == nk_utfbyte[*i]) - return (nk_byte)(c & ~nk_utfmask[*i]); - } - return 0; -} -NK_API int -nk_utf_decode(const char *c, nk_rune *u, int clen) -{ - int i, j, len, type=0; - nk_rune udecoded; - - NK_ASSERT(c); - NK_ASSERT(u); - - if (!c || !u) return 0; - if (!clen) return 0; - *u = NK_UTF_INVALID; - - udecoded = nk_utf_decode_byte(c[0], &len); - if (!NK_BETWEEN(len, 1, NK_UTF_SIZE)) - return 1; - - for (i = 1, j = 1; i < clen && j < len; ++i, ++j) { - udecoded = (udecoded << 6) | nk_utf_decode_byte(c[i], &type); - if (type != 0) - return j; - } - if (j < len) - return 0; - *u = udecoded; - nk_utf_validate(u, len); - return len; -} -NK_INTERN char -nk_utf_encode_byte(nk_rune u, int i) -{ - return (char)((nk_utfbyte[i]) | ((nk_byte)u & ~nk_utfmask[i])); -} -NK_API int -nk_utf_encode(nk_rune u, char *c, int clen) -{ - int len, i; - len = nk_utf_validate(&u, 0); - if (clen < len || !len || len > NK_UTF_SIZE) - return 0; - - for (i = len - 1; i != 0; --i) { - c[i] = nk_utf_encode_byte(u, 0); - u >>= 6; - } - c[0] = nk_utf_encode_byte(u, len); - return len; -} -NK_API int -nk_utf_len(const char *str, int len) -{ - const char *text; - int glyphs = 0; - int text_len; - int glyph_len; - int src_len = 0; - nk_rune unicode; - - NK_ASSERT(str); - if (!str || !len) return 0; - - text = str; - text_len = len; - glyph_len = nk_utf_decode(text, &unicode, text_len); - while (glyph_len && src_len < len) { - glyphs++; - src_len = src_len + glyph_len; - glyph_len = nk_utf_decode(text + src_len, &unicode, text_len - src_len); - } - return glyphs; -} -NK_API const char* -nk_utf_at(const char *buffer, int length, int index, - nk_rune *unicode, int *len) -{ - int i = 0; - int src_len = 0; - int glyph_len = 0; - const char *text; - int text_len; - - NK_ASSERT(buffer); - NK_ASSERT(unicode); - NK_ASSERT(len); - - if (!buffer || !unicode || !len) return 0; - if (index < 0) { - *unicode = NK_UTF_INVALID; - *len = 0; - return 0; - } - - text = buffer; - text_len = length; - glyph_len = nk_utf_decode(text, unicode, text_len); - while (glyph_len) { - if (i == index) { - *len = glyph_len; - break; - } - - i++; - src_len = src_len + glyph_len; - glyph_len = nk_utf_decode(text + src_len, unicode, text_len - src_len); - } - if (i != index) return 0; - return buffer + src_len; -} - - - - - -/* ============================================================== - * - * BUFFER - * - * ===============================================================*/ -#ifdef NK_INCLUDE_DEFAULT_ALLOCATOR -NK_LIB void* -nk_malloc(nk_handle unused, void *old,nk_size size) -{ - NK_UNUSED(unused); - NK_UNUSED(old); - return malloc(size); -} -NK_LIB void -nk_mfree(nk_handle unused, void *ptr) -{ - NK_UNUSED(unused); - free(ptr); -} -NK_API void -nk_buffer_init_default(struct nk_buffer *buffer) -{ - struct nk_allocator alloc; - alloc.userdata.ptr = 0; - alloc.alloc = nk_malloc; - alloc.free = nk_mfree; - nk_buffer_init(buffer, &alloc, NK_BUFFER_DEFAULT_INITIAL_SIZE); -} -#endif - -NK_API void -nk_buffer_init(struct nk_buffer *b, const struct nk_allocator *a, - nk_size initial_size) -{ - NK_ASSERT(b); - NK_ASSERT(a); - NK_ASSERT(initial_size); - if (!b || !a || !initial_size) return; - - nk_zero(b, sizeof(*b)); - b->type = NK_BUFFER_DYNAMIC; - b->memory.ptr = a->alloc(a->userdata,0, initial_size); - b->memory.size = initial_size; - b->size = initial_size; - b->grow_factor = 2.0f; - b->pool = *a; -} -NK_API void -nk_buffer_init_fixed(struct nk_buffer *b, void *m, nk_size size) -{ - NK_ASSERT(b); - NK_ASSERT(m); - NK_ASSERT(size); - if (!b || !m || !size) return; - - nk_zero(b, sizeof(*b)); - b->type = NK_BUFFER_FIXED; - b->memory.ptr = m; - b->memory.size = size; - b->size = size; -} -NK_LIB void* -nk_buffer_align(void *unaligned, - nk_size align, nk_size *alignment, - enum nk_buffer_allocation_type type) -{ - void *memory = 0; - switch (type) { - default: - case NK_BUFFER_MAX: - case NK_BUFFER_FRONT: - if (align) { - memory = NK_ALIGN_PTR(unaligned, align); - *alignment = (nk_size)((nk_byte*)memory - (nk_byte*)unaligned); - } else { - memory = unaligned; - *alignment = 0; - } - break; - case NK_BUFFER_BACK: - if (align) { - memory = NK_ALIGN_PTR_BACK(unaligned, align); - *alignment = (nk_size)((nk_byte*)unaligned - (nk_byte*)memory); - } else { - memory = unaligned; - *alignment = 0; - } - break; - } - return memory; -} -NK_LIB void* -nk_buffer_realloc(struct nk_buffer *b, nk_size capacity, nk_size *size) -{ - void *temp; - nk_size buffer_size; - - NK_ASSERT(b); - NK_ASSERT(size); - if (!b || !size || !b->pool.alloc || !b->pool.free) - return 0; - - buffer_size = b->memory.size; - temp = b->pool.alloc(b->pool.userdata, b->memory.ptr, capacity); - NK_ASSERT(temp); - if (!temp) return 0; - - *size = capacity; - if (temp != b->memory.ptr) { - NK_MEMCPY(temp, b->memory.ptr, buffer_size); - b->pool.free(b->pool.userdata, b->memory.ptr); - } - - if (b->size == buffer_size) { - /* no back buffer so just set correct size */ - b->size = capacity; - return temp; - } else { - /* copy back buffer to the end of the new buffer */ - void *dst, *src; - nk_size back_size; - back_size = buffer_size - b->size; - dst = nk_ptr_add(void, temp, capacity - back_size); - src = nk_ptr_add(void, temp, b->size); - NK_MEMCPY(dst, src, back_size); - b->size = capacity - back_size; - } - return temp; -} -NK_LIB void* -nk_buffer_alloc(struct nk_buffer *b, enum nk_buffer_allocation_type type, - nk_size size, nk_size align) -{ - int full; - nk_size alignment; - void *unaligned; - void *memory; - - NK_ASSERT(b); - NK_ASSERT(size); - if (!b || !size) return 0; - b->needed += size; - - /* calculate total size with needed alignment + size */ - if (type == NK_BUFFER_FRONT) - unaligned = nk_ptr_add(void, b->memory.ptr, b->allocated); - else unaligned = nk_ptr_add(void, b->memory.ptr, b->size - size); - memory = nk_buffer_align(unaligned, align, &alignment, type); - - /* check if buffer has enough memory*/ - if (type == NK_BUFFER_FRONT) - full = ((b->allocated + size + alignment) > b->size); - else full = ((b->size - NK_MIN(b->size,(size + alignment))) <= b->allocated); - - if (full) { - nk_size capacity; - if (b->type != NK_BUFFER_DYNAMIC) - return 0; - NK_ASSERT(b->pool.alloc && b->pool.free); - if (b->type != NK_BUFFER_DYNAMIC || !b->pool.alloc || !b->pool.free) - return 0; - - /* buffer is full so allocate bigger buffer if dynamic */ - capacity = (nk_size)((float)b->memory.size * b->grow_factor); - capacity = NK_MAX(capacity, nk_round_up_pow2((nk_uint)(b->allocated + size))); - b->memory.ptr = nk_buffer_realloc(b, capacity, &b->memory.size); - if (!b->memory.ptr) return 0; - - /* align newly allocated pointer */ - if (type == NK_BUFFER_FRONT) - unaligned = nk_ptr_add(void, b->memory.ptr, b->allocated); - else unaligned = nk_ptr_add(void, b->memory.ptr, b->size - size); - memory = nk_buffer_align(unaligned, align, &alignment, type); - } - if (type == NK_BUFFER_FRONT) - b->allocated += size + alignment; - else b->size -= (size + alignment); - b->needed += alignment; - b->calls++; - return memory; -} -NK_API void -nk_buffer_push(struct nk_buffer *b, enum nk_buffer_allocation_type type, - const void *memory, nk_size size, nk_size align) -{ - void *mem = nk_buffer_alloc(b, type, size, align); - if (!mem) return; - NK_MEMCPY(mem, memory, size); -} -NK_API void -nk_buffer_mark(struct nk_buffer *buffer, enum nk_buffer_allocation_type type) -{ - NK_ASSERT(buffer); - if (!buffer) return; - buffer->marker[type].active = nk_true; - if (type == NK_BUFFER_BACK) - buffer->marker[type].offset = buffer->size; - else buffer->marker[type].offset = buffer->allocated; -} -NK_API void -nk_buffer_reset(struct nk_buffer *buffer, enum nk_buffer_allocation_type type) -{ - NK_ASSERT(buffer); - if (!buffer) return; - if (type == NK_BUFFER_BACK) { - /* reset back buffer either back to marker or empty */ - buffer->needed -= (buffer->memory.size - buffer->marker[type].offset); - if (buffer->marker[type].active) - buffer->size = buffer->marker[type].offset; - else buffer->size = buffer->memory.size; - buffer->marker[type].active = nk_false; - } else { - /* reset front buffer either back to back marker or empty */ - buffer->needed -= (buffer->allocated - buffer->marker[type].offset); - if (buffer->marker[type].active) - buffer->allocated = buffer->marker[type].offset; - else buffer->allocated = 0; - buffer->marker[type].active = nk_false; - } -} -NK_API void -nk_buffer_clear(struct nk_buffer *b) -{ - NK_ASSERT(b); - if (!b) return; - b->allocated = 0; - b->size = b->memory.size; - b->calls = 0; - b->needed = 0; -} -NK_API void -nk_buffer_free(struct nk_buffer *b) -{ - NK_ASSERT(b); - if (!b || !b->memory.ptr) return; - if (b->type == NK_BUFFER_FIXED) return; - if (!b->pool.free) return; - NK_ASSERT(b->pool.free); - b->pool.free(b->pool.userdata, b->memory.ptr); -} -NK_API void -nk_buffer_info(struct nk_memory_status *s, struct nk_buffer *b) -{ - NK_ASSERT(b); - NK_ASSERT(s); - if (!s || !b) return; - s->allocated = b->allocated; - s->size = b->memory.size; - s->needed = b->needed; - s->memory = b->memory.ptr; - s->calls = b->calls; -} -NK_API void* -nk_buffer_memory(struct nk_buffer *buffer) -{ - NK_ASSERT(buffer); - if (!buffer) return 0; - return buffer->memory.ptr; -} -NK_API const void* -nk_buffer_memory_const(const struct nk_buffer *buffer) -{ - NK_ASSERT(buffer); - if (!buffer) return 0; - return buffer->memory.ptr; -} -NK_API nk_size -nk_buffer_total(struct nk_buffer *buffer) -{ - NK_ASSERT(buffer); - if (!buffer) return 0; - return buffer->memory.size; -} - - - - - -/* =============================================================== - * - * STRING - * - * ===============================================================*/ -#ifdef NK_INCLUDE_DEFAULT_ALLOCATOR -NK_API void -nk_str_init_default(struct nk_str *str) -{ - struct nk_allocator alloc; - alloc.userdata.ptr = 0; - alloc.alloc = nk_malloc; - alloc.free = nk_mfree; - nk_buffer_init(&str->buffer, &alloc, 32); - str->len = 0; -} -#endif - -NK_API void -nk_str_init(struct nk_str *str, const struct nk_allocator *alloc, nk_size size) -{ - nk_buffer_init(&str->buffer, alloc, size); - str->len = 0; -} -NK_API void -nk_str_init_fixed(struct nk_str *str, void *memory, nk_size size) -{ - nk_buffer_init_fixed(&str->buffer, memory, size); - str->len = 0; -} -NK_API int -nk_str_append_text_char(struct nk_str *s, const char *str, int len) -{ - char *mem; - NK_ASSERT(s); - NK_ASSERT(str); - if (!s || !str || !len) return 0; - mem = (char*)nk_buffer_alloc(&s->buffer, NK_BUFFER_FRONT, (nk_size)len * sizeof(char), 0); - if (!mem) return 0; - NK_MEMCPY(mem, str, (nk_size)len * sizeof(char)); - s->len += nk_utf_len(str, len); - return len; -} -NK_API int -nk_str_append_str_char(struct nk_str *s, const char *str) -{ - return nk_str_append_text_char(s, str, nk_strlen(str)); -} -NK_API int -nk_str_append_text_utf8(struct nk_str *str, const char *text, int len) -{ - int i = 0; - int byte_len = 0; - nk_rune unicode; - if (!str || !text || !len) return 0; - for (i = 0; i < len; ++i) - byte_len += nk_utf_decode(text+byte_len, &unicode, 4); - nk_str_append_text_char(str, text, byte_len); - return len; -} -NK_API int -nk_str_append_str_utf8(struct nk_str *str, const char *text) -{ - int runes = 0; - int byte_len = 0; - int num_runes = 0; - int glyph_len = 0; - nk_rune unicode; - if (!str || !text) return 0; - - glyph_len = byte_len = nk_utf_decode(text+byte_len, &unicode, 4); - while (unicode != '\0' && glyph_len) { - glyph_len = nk_utf_decode(text+byte_len, &unicode, 4); - byte_len += glyph_len; - num_runes++; - } - nk_str_append_text_char(str, text, byte_len); - return runes; -} -NK_API int -nk_str_append_text_runes(struct nk_str *str, const nk_rune *text, int len) -{ - int i = 0; - int byte_len = 0; - nk_glyph glyph; - - NK_ASSERT(str); - if (!str || !text || !len) return 0; - for (i = 0; i < len; ++i) { - byte_len = nk_utf_encode(text[i], glyph, NK_UTF_SIZE); - if (!byte_len) break; - nk_str_append_text_char(str, glyph, byte_len); - } - return len; -} -NK_API int -nk_str_append_str_runes(struct nk_str *str, const nk_rune *runes) -{ - int i = 0; - nk_glyph glyph; - int byte_len; - NK_ASSERT(str); - if (!str || !runes) return 0; - while (runes[i] != '\0') { - byte_len = nk_utf_encode(runes[i], glyph, NK_UTF_SIZE); - nk_str_append_text_char(str, glyph, byte_len); - i++; - } - return i; -} -NK_API int -nk_str_insert_at_char(struct nk_str *s, int pos, const char *str, int len) -{ - int i; - void *mem; - char *src; - char *dst; - - int copylen; - NK_ASSERT(s); - NK_ASSERT(str); - NK_ASSERT(len >= 0); - if (!s || !str || !len || (nk_size)pos > s->buffer.allocated) return 0; - if ((s->buffer.allocated + (nk_size)len >= s->buffer.memory.size) && - (s->buffer.type == NK_BUFFER_FIXED)) return 0; - - copylen = (int)s->buffer.allocated - pos; - if (!copylen) { - nk_str_append_text_char(s, str, len); - return 1; - } - mem = nk_buffer_alloc(&s->buffer, NK_BUFFER_FRONT, (nk_size)len * sizeof(char), 0); - if (!mem) return 0; - - /* memmove */ - NK_ASSERT(((int)pos + (int)len + ((int)copylen - 1)) >= 0); - NK_ASSERT(((int)pos + ((int)copylen - 1)) >= 0); - dst = nk_ptr_add(char, s->buffer.memory.ptr, pos + len + (copylen - 1)); - src = nk_ptr_add(char, s->buffer.memory.ptr, pos + (copylen-1)); - for (i = 0; i < copylen; ++i) *dst-- = *src--; - mem = nk_ptr_add(void, s->buffer.memory.ptr, pos); - NK_MEMCPY(mem, str, (nk_size)len * sizeof(char)); - s->len = nk_utf_len((char *)s->buffer.memory.ptr, (int)s->buffer.allocated); - return 1; -} -NK_API int -nk_str_insert_at_rune(struct nk_str *str, int pos, const char *cstr, int len) -{ - int glyph_len; - nk_rune unicode; - const char *begin; - const char *buffer; - - NK_ASSERT(str); - NK_ASSERT(cstr); - NK_ASSERT(len); - if (!str || !cstr || !len) return 0; - begin = nk_str_at_rune(str, pos, &unicode, &glyph_len); - if (!str->len) - return nk_str_append_text_char(str, cstr, len); - buffer = nk_str_get_const(str); - if (!begin) return 0; - return nk_str_insert_at_char(str, (int)(begin - buffer), cstr, len); -} -NK_API int -nk_str_insert_text_char(struct nk_str *str, int pos, const char *text, int len) -{ - return nk_str_insert_text_utf8(str, pos, text, len); -} -NK_API int -nk_str_insert_str_char(struct nk_str *str, int pos, const char *text) -{ - return nk_str_insert_text_utf8(str, pos, text, nk_strlen(text)); -} -NK_API int -nk_str_insert_text_utf8(struct nk_str *str, int pos, const char *text, int len) -{ - int i = 0; - int byte_len = 0; - nk_rune unicode; - - NK_ASSERT(str); - NK_ASSERT(text); - if (!str || !text || !len) return 0; - for (i = 0; i < len; ++i) - byte_len += nk_utf_decode(text+byte_len, &unicode, 4); - nk_str_insert_at_rune(str, pos, text, byte_len); - return len; -} -NK_API int -nk_str_insert_str_utf8(struct nk_str *str, int pos, const char *text) -{ - int runes = 0; - int byte_len = 0; - int num_runes = 0; - int glyph_len = 0; - nk_rune unicode; - if (!str || !text) return 0; - - glyph_len = byte_len = nk_utf_decode(text+byte_len, &unicode, 4); - while (unicode != '\0' && glyph_len) { - glyph_len = nk_utf_decode(text+byte_len, &unicode, 4); - byte_len += glyph_len; - num_runes++; - } - nk_str_insert_at_rune(str, pos, text, byte_len); - return runes; -} -NK_API int -nk_str_insert_text_runes(struct nk_str *str, int pos, const nk_rune *runes, int len) -{ - int i = 0; - int byte_len = 0; - nk_glyph glyph; - - NK_ASSERT(str); - if (!str || !runes || !len) return 0; - for (i = 0; i < len; ++i) { - byte_len = nk_utf_encode(runes[i], glyph, NK_UTF_SIZE); - if (!byte_len) break; - nk_str_insert_at_rune(str, pos+i, glyph, byte_len); - } - return len; -} -NK_API int -nk_str_insert_str_runes(struct nk_str *str, int pos, const nk_rune *runes) -{ - int i = 0; - nk_glyph glyph; - int byte_len; - NK_ASSERT(str); - if (!str || !runes) return 0; - while (runes[i] != '\0') { - byte_len = nk_utf_encode(runes[i], glyph, NK_UTF_SIZE); - nk_str_insert_at_rune(str, pos+i, glyph, byte_len); - i++; - } - return i; -} -NK_API void -nk_str_remove_chars(struct nk_str *s, int len) -{ - NK_ASSERT(s); - NK_ASSERT(len >= 0); - if (!s || len < 0 || (nk_size)len > s->buffer.allocated) return; - NK_ASSERT(((int)s->buffer.allocated - (int)len) >= 0); - s->buffer.allocated -= (nk_size)len; - s->len = nk_utf_len((char *)s->buffer.memory.ptr, (int)s->buffer.allocated); -} -NK_API void -nk_str_remove_runes(struct nk_str *str, int len) -{ - int index; - const char *begin; - const char *end; - nk_rune unicode; - - NK_ASSERT(str); - NK_ASSERT(len >= 0); - if (!str || len < 0) return; - if (len >= str->len) { - str->len = 0; - return; - } - - index = str->len - len; - begin = nk_str_at_rune(str, index, &unicode, &len); - end = (const char*)str->buffer.memory.ptr + str->buffer.allocated; - nk_str_remove_chars(str, (int)(end-begin)+1); -} -NK_API void -nk_str_delete_chars(struct nk_str *s, int pos, int len) -{ - NK_ASSERT(s); - if (!s || !len || (nk_size)pos > s->buffer.allocated || - (nk_size)(pos + len) > s->buffer.allocated) return; - - if ((nk_size)(pos + len) < s->buffer.allocated) { - /* memmove */ - char *dst = nk_ptr_add(char, s->buffer.memory.ptr, pos); - char *src = nk_ptr_add(char, s->buffer.memory.ptr, pos + len); - NK_MEMCPY(dst, src, s->buffer.allocated - (nk_size)(pos + len)); - NK_ASSERT(((int)s->buffer.allocated - (int)len) >= 0); - s->buffer.allocated -= (nk_size)len; - } else nk_str_remove_chars(s, len); - s->len = nk_utf_len((char *)s->buffer.memory.ptr, (int)s->buffer.allocated); -} -NK_API void -nk_str_delete_runes(struct nk_str *s, int pos, int len) -{ - char *temp; - nk_rune unicode; - char *begin; - char *end; - int unused; - - NK_ASSERT(s); - NK_ASSERT(s->len >= pos + len); - if (s->len < pos + len) - len = NK_CLAMP(0, (s->len - pos), s->len); - if (!len) return; - - temp = (char *)s->buffer.memory.ptr; - begin = nk_str_at_rune(s, pos, &unicode, &unused); - if (!begin) return; - s->buffer.memory.ptr = begin; - end = nk_str_at_rune(s, len, &unicode, &unused); - s->buffer.memory.ptr = temp; - if (!end) return; - nk_str_delete_chars(s, (int)(begin - temp), (int)(end - begin)); -} -NK_API char* -nk_str_at_char(struct nk_str *s, int pos) -{ - NK_ASSERT(s); - if (!s || pos > (int)s->buffer.allocated) return 0; - return nk_ptr_add(char, s->buffer.memory.ptr, pos); -} -NK_API char* -nk_str_at_rune(struct nk_str *str, int pos, nk_rune *unicode, int *len) -{ - int i = 0; - int src_len = 0; - int glyph_len = 0; - char *text; - int text_len; - - NK_ASSERT(str); - NK_ASSERT(unicode); - NK_ASSERT(len); - - if (!str || !unicode || !len) return 0; - if (pos < 0) { - *unicode = 0; - *len = 0; - return 0; - } - - text = (char*)str->buffer.memory.ptr; - text_len = (int)str->buffer.allocated; - glyph_len = nk_utf_decode(text, unicode, text_len); - while (glyph_len) { - if (i == pos) { - *len = glyph_len; - break; - } - - i++; - src_len = src_len + glyph_len; - glyph_len = nk_utf_decode(text + src_len, unicode, text_len - src_len); - } - if (i != pos) return 0; - return text + src_len; -} -NK_API const char* -nk_str_at_char_const(const struct nk_str *s, int pos) -{ - NK_ASSERT(s); - if (!s || pos > (int)s->buffer.allocated) return 0; - return nk_ptr_add(char, s->buffer.memory.ptr, pos); -} -NK_API const char* -nk_str_at_const(const struct nk_str *str, int pos, nk_rune *unicode, int *len) -{ - int i = 0; - int src_len = 0; - int glyph_len = 0; - char *text; - int text_len; - - NK_ASSERT(str); - NK_ASSERT(unicode); - NK_ASSERT(len); - - if (!str || !unicode || !len) return 0; - if (pos < 0) { - *unicode = 0; - *len = 0; - return 0; - } - - text = (char*)str->buffer.memory.ptr; - text_len = (int)str->buffer.allocated; - glyph_len = nk_utf_decode(text, unicode, text_len); - while (glyph_len) { - if (i == pos) { - *len = glyph_len; - break; - } - - i++; - src_len = src_len + glyph_len; - glyph_len = nk_utf_decode(text + src_len, unicode, text_len - src_len); - } - if (i != pos) return 0; - return text + src_len; -} -NK_API nk_rune -nk_str_rune_at(const struct nk_str *str, int pos) -{ - int len; - nk_rune unicode = 0; - nk_str_at_const(str, pos, &unicode, &len); - return unicode; -} -NK_API char* -nk_str_get(struct nk_str *s) -{ - NK_ASSERT(s); - if (!s || !s->len || !s->buffer.allocated) return 0; - return (char*)s->buffer.memory.ptr; -} -NK_API const char* -nk_str_get_const(const struct nk_str *s) -{ - NK_ASSERT(s); - if (!s || !s->len || !s->buffer.allocated) return 0; - return (const char*)s->buffer.memory.ptr; -} -NK_API int -nk_str_len(struct nk_str *s) -{ - NK_ASSERT(s); - if (!s || !s->len || !s->buffer.allocated) return 0; - return s->len; -} -NK_API int -nk_str_len_char(struct nk_str *s) -{ - NK_ASSERT(s); - if (!s || !s->len || !s->buffer.allocated) return 0; - return (int)s->buffer.allocated; -} -NK_API void -nk_str_clear(struct nk_str *str) -{ - NK_ASSERT(str); - nk_buffer_clear(&str->buffer); - str->len = 0; -} -NK_API void -nk_str_free(struct nk_str *str) -{ - NK_ASSERT(str); - nk_buffer_free(&str->buffer); - str->len = 0; -} - - - - - -/* ============================================================== - * - * DRAW - * - * ===============================================================*/ -NK_LIB void -nk_command_buffer_init(struct nk_command_buffer *cb, - struct nk_buffer *b, enum nk_command_clipping clip) -{ - NK_ASSERT(cb); - NK_ASSERT(b); - if (!cb || !b) return; - cb->base = b; - cb->use_clipping = (int)clip; - cb->begin = b->allocated; - cb->end = b->allocated; - cb->last = b->allocated; -} -NK_LIB void -nk_command_buffer_reset(struct nk_command_buffer *b) -{ - NK_ASSERT(b); - if (!b) return; - b->begin = 0; - b->end = 0; - b->last = 0; - b->clip = nk_null_rect; -#ifdef NK_INCLUDE_COMMAND_USERDATA - b->userdata.ptr = 0; -#endif -} -NK_LIB void* -nk_command_buffer_push(struct nk_command_buffer* b, - enum nk_command_type t, nk_size size) -{ - NK_STORAGE const nk_size align = NK_ALIGNOF(struct nk_command); - struct nk_command *cmd; - nk_size alignment; - void *unaligned; - void *memory; - - NK_ASSERT(b); - NK_ASSERT(b->base); - if (!b) return 0; - cmd = (struct nk_command*)nk_buffer_alloc(b->base,NK_BUFFER_FRONT,size,align); - if (!cmd) return 0; - - /* make sure the offset to the next command is aligned */ - b->last = (nk_size)((nk_byte*)cmd - (nk_byte*)b->base->memory.ptr); - unaligned = (nk_byte*)cmd + size; - memory = NK_ALIGN_PTR(unaligned, align); - alignment = (nk_size)((nk_byte*)memory - (nk_byte*)unaligned); -#ifdef NK_ZERO_COMMAND_MEMORY - NK_MEMSET(cmd, 0, size + alignment); -#endif - - cmd->type = t; - cmd->next = b->base->allocated + alignment; -#ifdef NK_INCLUDE_COMMAND_USERDATA - cmd->userdata = b->userdata; -#endif - b->end = cmd->next; - return cmd; -} -NK_API void -nk_push_scissor(struct nk_command_buffer *b, struct nk_rect r) -{ - struct nk_command_scissor *cmd; - NK_ASSERT(b); - if (!b) return; - - b->clip.x = r.x; - b->clip.y = r.y; - b->clip.w = r.w; - b->clip.h = r.h; - cmd = (struct nk_command_scissor*) - nk_command_buffer_push(b, NK_COMMAND_SCISSOR, sizeof(*cmd)); - - if (!cmd) return; - cmd->x = (short)r.x; - cmd->y = (short)r.y; - cmd->w = (unsigned short)NK_MAX(0, r.w); - cmd->h = (unsigned short)NK_MAX(0, r.h); -} -NK_API void -nk_stroke_line(struct nk_command_buffer *b, float x0, float y0, - float x1, float y1, float line_thickness, struct nk_color c) -{ - struct nk_command_line *cmd; - NK_ASSERT(b); - if (!b || line_thickness <= 0) return; - cmd = (struct nk_command_line*) - nk_command_buffer_push(b, NK_COMMAND_LINE, sizeof(*cmd)); - if (!cmd) return; - cmd->line_thickness = (unsigned short)line_thickness; - cmd->begin.x = (short)x0; - cmd->begin.y = (short)y0; - cmd->end.x = (short)x1; - cmd->end.y = (short)y1; - cmd->color = c; -} -NK_API void -nk_stroke_curve(struct nk_command_buffer *b, float ax, float ay, - float ctrl0x, float ctrl0y, float ctrl1x, float ctrl1y, - float bx, float by, float line_thickness, struct nk_color col) -{ - struct nk_command_curve *cmd; - NK_ASSERT(b); - if (!b || col.a == 0 || line_thickness <= 0) return; - - cmd = (struct nk_command_curve*) - nk_command_buffer_push(b, NK_COMMAND_CURVE, sizeof(*cmd)); - if (!cmd) return; - cmd->line_thickness = (unsigned short)line_thickness; - cmd->begin.x = (short)ax; - cmd->begin.y = (short)ay; - cmd->ctrl[0].x = (short)ctrl0x; - cmd->ctrl[0].y = (short)ctrl0y; - cmd->ctrl[1].x = (short)ctrl1x; - cmd->ctrl[1].y = (short)ctrl1y; - cmd->end.x = (short)bx; - cmd->end.y = (short)by; - cmd->color = col; -} -NK_API void -nk_stroke_rect(struct nk_command_buffer *b, struct nk_rect rect, - float rounding, float line_thickness, struct nk_color c) -{ - struct nk_command_rect *cmd; - NK_ASSERT(b); - if (!b || c.a == 0 || rect.w == 0 || rect.h == 0 || line_thickness <= 0) return; - if (b->use_clipping) { - const struct nk_rect *clip = &b->clip; - if (!NK_INTERSECT(rect.x, rect.y, rect.w, rect.h, - clip->x, clip->y, clip->w, clip->h)) return; - } - cmd = (struct nk_command_rect*) - nk_command_buffer_push(b, NK_COMMAND_RECT, sizeof(*cmd)); - if (!cmd) return; - cmd->rounding = (unsigned short)rounding; - cmd->line_thickness = (unsigned short)line_thickness; - cmd->x = (short)rect.x; - cmd->y = (short)rect.y; - cmd->w = (unsigned short)NK_MAX(0, rect.w); - cmd->h = (unsigned short)NK_MAX(0, rect.h); - cmd->color = c; -} -NK_API void -nk_fill_rect(struct nk_command_buffer *b, struct nk_rect rect, - float rounding, struct nk_color c) -{ - struct nk_command_rect_filled *cmd; - NK_ASSERT(b); - if (!b || c.a == 0 || rect.w == 0 || rect.h == 0) return; - if (b->use_clipping) { - const struct nk_rect *clip = &b->clip; - if (!NK_INTERSECT(rect.x, rect.y, rect.w, rect.h, - clip->x, clip->y, clip->w, clip->h)) return; - } - - cmd = (struct nk_command_rect_filled*) - nk_command_buffer_push(b, NK_COMMAND_RECT_FILLED, sizeof(*cmd)); - if (!cmd) return; - cmd->rounding = (unsigned short)rounding; - cmd->x = (short)rect.x; - cmd->y = (short)rect.y; - cmd->w = (unsigned short)NK_MAX(0, rect.w); - cmd->h = (unsigned short)NK_MAX(0, rect.h); - cmd->color = c; -} -NK_API void -nk_fill_rect_multi_color(struct nk_command_buffer *b, struct nk_rect rect, - struct nk_color left, struct nk_color top, struct nk_color right, - struct nk_color bottom) -{ - struct nk_command_rect_multi_color *cmd; - NK_ASSERT(b); - if (!b || rect.w == 0 || rect.h == 0) return; - if (b->use_clipping) { - const struct nk_rect *clip = &b->clip; - if (!NK_INTERSECT(rect.x, rect.y, rect.w, rect.h, - clip->x, clip->y, clip->w, clip->h)) return; - } - - cmd = (struct nk_command_rect_multi_color*) - nk_command_buffer_push(b, NK_COMMAND_RECT_MULTI_COLOR, sizeof(*cmd)); - if (!cmd) return; - cmd->x = (short)rect.x; - cmd->y = (short)rect.y; - cmd->w = (unsigned short)NK_MAX(0, rect.w); - cmd->h = (unsigned short)NK_MAX(0, rect.h); - cmd->left = left; - cmd->top = top; - cmd->right = right; - cmd->bottom = bottom; -} -NK_API void -nk_stroke_circle(struct nk_command_buffer *b, struct nk_rect r, - float line_thickness, struct nk_color c) -{ - struct nk_command_circle *cmd; - if (!b || r.w == 0 || r.h == 0 || line_thickness <= 0) return; - if (b->use_clipping) { - const struct nk_rect *clip = &b->clip; - if (!NK_INTERSECT(r.x, r.y, r.w, r.h, clip->x, clip->y, clip->w, clip->h)) - return; - } - - cmd = (struct nk_command_circle*) - nk_command_buffer_push(b, NK_COMMAND_CIRCLE, sizeof(*cmd)); - if (!cmd) return; - cmd->line_thickness = (unsigned short)line_thickness; - cmd->x = (short)r.x; - cmd->y = (short)r.y; - cmd->w = (unsigned short)NK_MAX(r.w, 0); - cmd->h = (unsigned short)NK_MAX(r.h, 0); - cmd->color = c; -} -NK_API void -nk_fill_circle(struct nk_command_buffer *b, struct nk_rect r, struct nk_color c) -{ - struct nk_command_circle_filled *cmd; - NK_ASSERT(b); - if (!b || c.a == 0 || r.w == 0 || r.h == 0) return; - if (b->use_clipping) { - const struct nk_rect *clip = &b->clip; - if (!NK_INTERSECT(r.x, r.y, r.w, r.h, clip->x, clip->y, clip->w, clip->h)) - return; - } - - cmd = (struct nk_command_circle_filled*) - nk_command_buffer_push(b, NK_COMMAND_CIRCLE_FILLED, sizeof(*cmd)); - if (!cmd) return; - cmd->x = (short)r.x; - cmd->y = (short)r.y; - cmd->w = (unsigned short)NK_MAX(r.w, 0); - cmd->h = (unsigned short)NK_MAX(r.h, 0); - cmd->color = c; -} -NK_API void -nk_stroke_arc(struct nk_command_buffer *b, float cx, float cy, float radius, - float a_min, float a_max, float line_thickness, struct nk_color c) -{ - struct nk_command_arc *cmd; - if (!b || c.a == 0 || line_thickness <= 0) return; - cmd = (struct nk_command_arc*) - nk_command_buffer_push(b, NK_COMMAND_ARC, sizeof(*cmd)); - if (!cmd) return; - cmd->line_thickness = (unsigned short)line_thickness; - cmd->cx = (short)cx; - cmd->cy = (short)cy; - cmd->r = (unsigned short)radius; - cmd->a[0] = a_min; - cmd->a[1] = a_max; - cmd->color = c; -} -NK_API void -nk_fill_arc(struct nk_command_buffer *b, float cx, float cy, float radius, - float a_min, float a_max, struct nk_color c) -{ - struct nk_command_arc_filled *cmd; - NK_ASSERT(b); - if (!b || c.a == 0) return; - cmd = (struct nk_command_arc_filled*) - nk_command_buffer_push(b, NK_COMMAND_ARC_FILLED, sizeof(*cmd)); - if (!cmd) return; - cmd->cx = (short)cx; - cmd->cy = (short)cy; - cmd->r = (unsigned short)radius; - cmd->a[0] = a_min; - cmd->a[1] = a_max; - cmd->color = c; -} -NK_API void -nk_stroke_triangle(struct nk_command_buffer *b, float x0, float y0, float x1, - float y1, float x2, float y2, float line_thickness, struct nk_color c) -{ - struct nk_command_triangle *cmd; - NK_ASSERT(b); - if (!b || c.a == 0 || line_thickness <= 0) return; - if (b->use_clipping) { - const struct nk_rect *clip = &b->clip; - if (!NK_INBOX(x0, y0, clip->x, clip->y, clip->w, clip->h) && - !NK_INBOX(x1, y1, clip->x, clip->y, clip->w, clip->h) && - !NK_INBOX(x2, y2, clip->x, clip->y, clip->w, clip->h)) - return; - } - - cmd = (struct nk_command_triangle*) - nk_command_buffer_push(b, NK_COMMAND_TRIANGLE, sizeof(*cmd)); - if (!cmd) return; - cmd->line_thickness = (unsigned short)line_thickness; - cmd->a.x = (short)x0; - cmd->a.y = (short)y0; - cmd->b.x = (short)x1; - cmd->b.y = (short)y1; - cmd->c.x = (short)x2; - cmd->c.y = (short)y2; - cmd->color = c; -} -NK_API void -nk_fill_triangle(struct nk_command_buffer *b, float x0, float y0, float x1, - float y1, float x2, float y2, struct nk_color c) -{ - struct nk_command_triangle_filled *cmd; - NK_ASSERT(b); - if (!b || c.a == 0) return; - if (!b) return; - if (b->use_clipping) { - const struct nk_rect *clip = &b->clip; - if (!NK_INBOX(x0, y0, clip->x, clip->y, clip->w, clip->h) && - !NK_INBOX(x1, y1, clip->x, clip->y, clip->w, clip->h) && - !NK_INBOX(x2, y2, clip->x, clip->y, clip->w, clip->h)) - return; - } - - cmd = (struct nk_command_triangle_filled*) - nk_command_buffer_push(b, NK_COMMAND_TRIANGLE_FILLED, sizeof(*cmd)); - if (!cmd) return; - cmd->a.x = (short)x0; - cmd->a.y = (short)y0; - cmd->b.x = (short)x1; - cmd->b.y = (short)y1; - cmd->c.x = (short)x2; - cmd->c.y = (short)y2; - cmd->color = c; -} -NK_API void -nk_stroke_polygon(struct nk_command_buffer *b, float *points, int point_count, - float line_thickness, struct nk_color col) -{ - int i; - nk_size size = 0; - struct nk_command_polygon *cmd; - - NK_ASSERT(b); - if (!b || col.a == 0 || line_thickness <= 0) return; - size = sizeof(*cmd) + sizeof(short) * 2 * (nk_size)point_count; - cmd = (struct nk_command_polygon*) nk_command_buffer_push(b, NK_COMMAND_POLYGON, size); - if (!cmd) return; - cmd->color = col; - cmd->line_thickness = (unsigned short)line_thickness; - cmd->point_count = (unsigned short)point_count; - for (i = 0; i < point_count; ++i) { - cmd->points[i].x = (short)points[i*2]; - cmd->points[i].y = (short)points[i*2+1]; - } -} -NK_API void -nk_fill_polygon(struct nk_command_buffer *b, float *points, int point_count, - struct nk_color col) -{ - int i; - nk_size size = 0; - struct nk_command_polygon_filled *cmd; - - NK_ASSERT(b); - if (!b || col.a == 0) return; - size = sizeof(*cmd) + sizeof(short) * 2 * (nk_size)point_count; - cmd = (struct nk_command_polygon_filled*) - nk_command_buffer_push(b, NK_COMMAND_POLYGON_FILLED, size); - if (!cmd) return; - cmd->color = col; - cmd->point_count = (unsigned short)point_count; - for (i = 0; i < point_count; ++i) { - cmd->points[i].x = (short)points[i*2+0]; - cmd->points[i].y = (short)points[i*2+1]; - } -} -NK_API void -nk_stroke_polyline(struct nk_command_buffer *b, float *points, int point_count, - float line_thickness, struct nk_color col) -{ - int i; - nk_size size = 0; - struct nk_command_polyline *cmd; - - NK_ASSERT(b); - if (!b || col.a == 0 || line_thickness <= 0) return; - size = sizeof(*cmd) + sizeof(short) * 2 * (nk_size)point_count; - cmd = (struct nk_command_polyline*) nk_command_buffer_push(b, NK_COMMAND_POLYLINE, size); - if (!cmd) return; - cmd->color = col; - cmd->point_count = (unsigned short)point_count; - cmd->line_thickness = (unsigned short)line_thickness; - for (i = 0; i < point_count; ++i) { - cmd->points[i].x = (short)points[i*2]; - cmd->points[i].y = (short)points[i*2+1]; - } -} -NK_API void -nk_draw_image(struct nk_command_buffer *b, struct nk_rect r, - const struct nk_image *img, struct nk_color col) -{ - struct nk_command_image *cmd; - NK_ASSERT(b); - if (!b) return; - if (b->use_clipping) { - const struct nk_rect *c = &b->clip; - if (c->w == 0 || c->h == 0 || !NK_INTERSECT(r.x, r.y, r.w, r.h, c->x, c->y, c->w, c->h)) - return; - } - - cmd = (struct nk_command_image*) - nk_command_buffer_push(b, NK_COMMAND_IMAGE, sizeof(*cmd)); - if (!cmd) return; - cmd->x = (short)r.x; - cmd->y = (short)r.y; - cmd->w = (unsigned short)NK_MAX(0, r.w); - cmd->h = (unsigned short)NK_MAX(0, r.h); - cmd->img = *img; - cmd->col = col; -} -NK_API void -nk_push_custom(struct nk_command_buffer *b, struct nk_rect r, - nk_command_custom_callback cb, nk_handle usr) -{ - struct nk_command_custom *cmd; - NK_ASSERT(b); - if (!b) return; - if (b->use_clipping) { - const struct nk_rect *c = &b->clip; - if (c->w == 0 || c->h == 0 || !NK_INTERSECT(r.x, r.y, r.w, r.h, c->x, c->y, c->w, c->h)) - return; - } - - cmd = (struct nk_command_custom*) - nk_command_buffer_push(b, NK_COMMAND_CUSTOM, sizeof(*cmd)); - if (!cmd) return; - cmd->x = (short)r.x; - cmd->y = (short)r.y; - cmd->w = (unsigned short)NK_MAX(0, r.w); - cmd->h = (unsigned short)NK_MAX(0, r.h); - cmd->callback_data = usr; - cmd->callback = cb; -} -NK_API void -nk_draw_text(struct nk_command_buffer *b, struct nk_rect r, - const char *string, int length, const struct nk_user_font *font, - struct nk_color bg, struct nk_color fg) -{ - float text_width = 0; - struct nk_command_text *cmd; - - NK_ASSERT(b); - NK_ASSERT(font); - if (!b || !string || !length || (bg.a == 0 && fg.a == 0)) return; - if (b->use_clipping) { - const struct nk_rect *c = &b->clip; - if (c->w == 0 || c->h == 0 || !NK_INTERSECT(r.x, r.y, r.w, r.h, c->x, c->y, c->w, c->h)) - return; - } - - /* make sure text fits inside bounds */ - text_width = font->width(font->userdata, font->height, string, length); - if (text_width > r.w){ - int glyphs = 0; - float txt_width = (float)text_width; - length = nk_text_clamp(font, string, length, r.w, &glyphs, &txt_width, 0,0); - } - - if (!length) return; - cmd = (struct nk_command_text*) - nk_command_buffer_push(b, NK_COMMAND_TEXT, sizeof(*cmd) + (nk_size)(length + 1)); - if (!cmd) return; - cmd->x = (short)r.x; - cmd->y = (short)r.y; - cmd->w = (unsigned short)r.w; - cmd->h = (unsigned short)r.h; - cmd->background = bg; - cmd->foreground = fg; - cmd->font = font; - cmd->length = length; - cmd->height = font->height; - NK_MEMCPY(cmd->string, string, (nk_size)length); - cmd->string[length] = '\0'; -} - - - - - -/* =============================================================== - * - * VERTEX - * - * ===============================================================*/ -#ifdef NK_INCLUDE_VERTEX_BUFFER_OUTPUT -NK_API void -nk_draw_list_init(struct nk_draw_list *list) -{ - nk_size i = 0; - NK_ASSERT(list); - if (!list) return; - nk_zero(list, sizeof(*list)); - for (i = 0; i < NK_LEN(list->circle_vtx); ++i) { - const float a = ((float)i / (float)NK_LEN(list->circle_vtx)) * 2 * NK_PI; - list->circle_vtx[i].x = (float)NK_COS(a); - list->circle_vtx[i].y = (float)NK_SIN(a); - } -} -NK_API void -nk_draw_list_setup(struct nk_draw_list *canvas, const struct nk_convert_config *config, - struct nk_buffer *cmds, struct nk_buffer *vertices, struct nk_buffer *elements, - enum nk_anti_aliasing line_aa, enum nk_anti_aliasing shape_aa) -{ - NK_ASSERT(canvas); - NK_ASSERT(config); - NK_ASSERT(cmds); - NK_ASSERT(vertices); - NK_ASSERT(elements); - if (!canvas || !config || !cmds || !vertices || !elements) - return; - - canvas->buffer = cmds; - canvas->config = *config; - canvas->elements = elements; - canvas->vertices = vertices; - canvas->line_AA = line_aa; - canvas->shape_AA = shape_aa; - canvas->clip_rect = nk_null_rect; - - canvas->cmd_offset = 0; - canvas->element_count = 0; - canvas->vertex_count = 0; - canvas->cmd_offset = 0; - canvas->cmd_count = 0; - canvas->path_count = 0; -} -NK_API const struct nk_draw_command* -nk__draw_list_begin(const struct nk_draw_list *canvas, const struct nk_buffer *buffer) -{ - nk_byte *memory; - nk_size offset; - const struct nk_draw_command *cmd; - - NK_ASSERT(buffer); - if (!buffer || !buffer->size || !canvas->cmd_count) - return 0; - - memory = (nk_byte*)buffer->memory.ptr; - offset = buffer->memory.size - canvas->cmd_offset; - cmd = nk_ptr_add(const struct nk_draw_command, memory, offset); - return cmd; -} -NK_API const struct nk_draw_command* -nk__draw_list_end(const struct nk_draw_list *canvas, const struct nk_buffer *buffer) -{ - nk_size size; - nk_size offset; - nk_byte *memory; - const struct nk_draw_command *end; - - NK_ASSERT(buffer); - NK_ASSERT(canvas); - if (!buffer || !canvas) - return 0; - - memory = (nk_byte*)buffer->memory.ptr; - size = buffer->memory.size; - offset = size - canvas->cmd_offset; - end = nk_ptr_add(const struct nk_draw_command, memory, offset); - end -= (canvas->cmd_count-1); - return end; -} -NK_API const struct nk_draw_command* -nk__draw_list_next(const struct nk_draw_command *cmd, - const struct nk_buffer *buffer, const struct nk_draw_list *canvas) -{ - const struct nk_draw_command *end; - NK_ASSERT(buffer); - NK_ASSERT(canvas); - if (!cmd || !buffer || !canvas) - return 0; - - end = nk__draw_list_end(canvas, buffer); - if (cmd <= end) return 0; - return (cmd-1); -} -NK_INTERN struct nk_vec2* -nk_draw_list_alloc_path(struct nk_draw_list *list, int count) -{ - struct nk_vec2 *points; - NK_STORAGE const nk_size point_align = NK_ALIGNOF(struct nk_vec2); - NK_STORAGE const nk_size point_size = sizeof(struct nk_vec2); - points = (struct nk_vec2*) - nk_buffer_alloc(list->buffer, NK_BUFFER_FRONT, - point_size * (nk_size)count, point_align); - - if (!points) return 0; - if (!list->path_offset) { - void *memory = nk_buffer_memory(list->buffer); - list->path_offset = (unsigned int)((nk_byte*)points - (nk_byte*)memory); - } - list->path_count += (unsigned int)count; - return points; -} -NK_INTERN struct nk_vec2 -nk_draw_list_path_last(struct nk_draw_list *list) -{ - void *memory; - struct nk_vec2 *point; - NK_ASSERT(list->path_count); - memory = nk_buffer_memory(list->buffer); - point = nk_ptr_add(struct nk_vec2, memory, list->path_offset); - point += (list->path_count-1); - return *point; -} -NK_INTERN struct nk_draw_command* -nk_draw_list_push_command(struct nk_draw_list *list, struct nk_rect clip, - nk_handle texture) -{ - NK_STORAGE const nk_size cmd_align = NK_ALIGNOF(struct nk_draw_command); - NK_STORAGE const nk_size cmd_size = sizeof(struct nk_draw_command); - struct nk_draw_command *cmd; - - NK_ASSERT(list); - cmd = (struct nk_draw_command*) - nk_buffer_alloc(list->buffer, NK_BUFFER_BACK, cmd_size, cmd_align); - - if (!cmd) return 0; - if (!list->cmd_count) { - nk_byte *memory = (nk_byte*)nk_buffer_memory(list->buffer); - nk_size total = nk_buffer_total(list->buffer); - memory = nk_ptr_add(nk_byte, memory, total); - list->cmd_offset = (nk_size)(memory - (nk_byte*)cmd); - } - - cmd->elem_count = 0; - cmd->clip_rect = clip; - cmd->texture = texture; -#ifdef NK_INCLUDE_COMMAND_USERDATA - cmd->userdata = list->userdata; -#endif - - list->cmd_count++; - list->clip_rect = clip; - return cmd; -} -NK_INTERN struct nk_draw_command* -nk_draw_list_command_last(struct nk_draw_list *list) -{ - void *memory; - nk_size size; - struct nk_draw_command *cmd; - NK_ASSERT(list->cmd_count); - - memory = nk_buffer_memory(list->buffer); - size = nk_buffer_total(list->buffer); - cmd = nk_ptr_add(struct nk_draw_command, memory, size - list->cmd_offset); - return (cmd - (list->cmd_count-1)); -} -NK_INTERN void -nk_draw_list_add_clip(struct nk_draw_list *list, struct nk_rect rect) -{ - NK_ASSERT(list); - if (!list) return; - if (!list->cmd_count) { - nk_draw_list_push_command(list, rect, list->config.null.texture); - } else { - struct nk_draw_command *prev = nk_draw_list_command_last(list); - if (prev->elem_count == 0) - prev->clip_rect = rect; - nk_draw_list_push_command(list, rect, prev->texture); - } -} -NK_INTERN void -nk_draw_list_push_image(struct nk_draw_list *list, nk_handle texture) -{ - NK_ASSERT(list); - if (!list) return; - if (!list->cmd_count) { - nk_draw_list_push_command(list, nk_null_rect, texture); - } else { - struct nk_draw_command *prev = nk_draw_list_command_last(list); - if (prev->elem_count == 0) { - prev->texture = texture; - #ifdef NK_INCLUDE_COMMAND_USERDATA - prev->userdata = list->userdata; - #endif - } else if (prev->texture.id != texture.id - #ifdef NK_INCLUDE_COMMAND_USERDATA - || prev->userdata.id != list->userdata.id - #endif - ) nk_draw_list_push_command(list, prev->clip_rect, texture); - } -} -#ifdef NK_INCLUDE_COMMAND_USERDATA -NK_API void -nk_draw_list_push_userdata(struct nk_draw_list *list, nk_handle userdata) -{ - list->userdata = userdata; -} -#endif -NK_INTERN void* -nk_draw_list_alloc_vertices(struct nk_draw_list *list, nk_size count) -{ - void *vtx; - NK_ASSERT(list); - if (!list) return 0; - vtx = nk_buffer_alloc(list->vertices, NK_BUFFER_FRONT, - list->config.vertex_size*count, list->config.vertex_alignment); - if (!vtx) return 0; - list->vertex_count += (unsigned int)count; - - /* This assert triggers because your are drawing a lot of stuff and nuklear - * defined `nk_draw_index` as `nk_ushort` to safe space be default. - * - * So you reached the maximum number of indicies or rather vertexes. - * To solve this issue please change typdef `nk_draw_index` to `nk_uint` - * and don't forget to specify the new element size in your drawing - * backend (OpenGL, DirectX, ...). For example in OpenGL for `glDrawElements` - * instead of specifing `GL_UNSIGNED_SHORT` you have to define `GL_UNSIGNED_INT`. - * Sorry for the inconvenience. */ - NK_ASSERT((sizeof(nk_draw_index) == 2 && list->vertex_count < NK_USHORT_MAX && - "To many verticies for 16-bit vertex indicies. Please read comment above on how to solve this problem")); - return vtx; -} -NK_INTERN nk_draw_index* -nk_draw_list_alloc_elements(struct nk_draw_list *list, nk_size count) -{ - nk_draw_index *ids; - struct nk_draw_command *cmd; - NK_STORAGE const nk_size elem_align = NK_ALIGNOF(nk_draw_index); - NK_STORAGE const nk_size elem_size = sizeof(nk_draw_index); - NK_ASSERT(list); - if (!list) return 0; - - ids = (nk_draw_index*) - nk_buffer_alloc(list->elements, NK_BUFFER_FRONT, elem_size*count, elem_align); - if (!ids) return 0; - cmd = nk_draw_list_command_last(list); - list->element_count += (unsigned int)count; - cmd->elem_count += (unsigned int)count; - return ids; -} -NK_INTERN int -nk_draw_vertex_layout_element_is_end_of_layout( - const struct nk_draw_vertex_layout_element *element) -{ - return (element->attribute == NK_VERTEX_ATTRIBUTE_COUNT || - element->format == NK_FORMAT_COUNT); -} -NK_INTERN void -nk_draw_vertex_color(void *attr, const float *vals, - enum nk_draw_vertex_layout_format format) -{ - /* if this triggers you tried to provide a value format for a color */ - float val[4]; - NK_ASSERT(format >= NK_FORMAT_COLOR_BEGIN); - NK_ASSERT(format <= NK_FORMAT_COLOR_END); - if (format < NK_FORMAT_COLOR_BEGIN || format > NK_FORMAT_COLOR_END) return; - - val[0] = NK_SATURATE(vals[0]); - val[1] = NK_SATURATE(vals[1]); - val[2] = NK_SATURATE(vals[2]); - val[3] = NK_SATURATE(vals[3]); - - switch (format) { - default: NK_ASSERT(0 && "Invalid vertex layout color format"); break; - case NK_FORMAT_R8G8B8A8: - case NK_FORMAT_R8G8B8: { - struct nk_color col = nk_rgba_fv(val); - NK_MEMCPY(attr, &col.r, sizeof(col)); - } break; - case NK_FORMAT_B8G8R8A8: { - struct nk_color col = nk_rgba_fv(val); - struct nk_color bgra = nk_rgba(col.b, col.g, col.r, col.a); - NK_MEMCPY(attr, &bgra, sizeof(bgra)); - } break; - case NK_FORMAT_R16G15B16: { - nk_ushort col[3]; - col[0] = (nk_ushort)(val[0]*(float)NK_USHORT_MAX); - col[1] = (nk_ushort)(val[1]*(float)NK_USHORT_MAX); - col[2] = (nk_ushort)(val[2]*(float)NK_USHORT_MAX); - NK_MEMCPY(attr, col, sizeof(col)); - } break; - case NK_FORMAT_R16G15B16A16: { - nk_ushort col[4]; - col[0] = (nk_ushort)(val[0]*(float)NK_USHORT_MAX); - col[1] = (nk_ushort)(val[1]*(float)NK_USHORT_MAX); - col[2] = (nk_ushort)(val[2]*(float)NK_USHORT_MAX); - col[3] = (nk_ushort)(val[3]*(float)NK_USHORT_MAX); - NK_MEMCPY(attr, col, sizeof(col)); - } break; - case NK_FORMAT_R32G32B32: { - nk_uint col[3]; - col[0] = (nk_uint)(val[0]*(float)NK_UINT_MAX); - col[1] = (nk_uint)(val[1]*(float)NK_UINT_MAX); - col[2] = (nk_uint)(val[2]*(float)NK_UINT_MAX); - NK_MEMCPY(attr, col, sizeof(col)); - } break; - case NK_FORMAT_R32G32B32A32: { - nk_uint col[4]; - col[0] = (nk_uint)(val[0]*(float)NK_UINT_MAX); - col[1] = (nk_uint)(val[1]*(float)NK_UINT_MAX); - col[2] = (nk_uint)(val[2]*(float)NK_UINT_MAX); - col[3] = (nk_uint)(val[3]*(float)NK_UINT_MAX); - NK_MEMCPY(attr, col, sizeof(col)); - } break; - case NK_FORMAT_R32G32B32A32_FLOAT: - NK_MEMCPY(attr, val, sizeof(float)*4); - break; - case NK_FORMAT_R32G32B32A32_DOUBLE: { - double col[4]; - col[0] = (double)val[0]; - col[1] = (double)val[1]; - col[2] = (double)val[2]; - col[3] = (double)val[3]; - NK_MEMCPY(attr, col, sizeof(col)); - } break; - case NK_FORMAT_RGB32: - case NK_FORMAT_RGBA32: { - struct nk_color col = nk_rgba_fv(val); - nk_uint color = nk_color_u32(col); - NK_MEMCPY(attr, &color, sizeof(color)); - } break; } -} -NK_INTERN void -nk_draw_vertex_element(void *dst, const float *values, int value_count, - enum nk_draw_vertex_layout_format format) -{ - int value_index; - void *attribute = dst; - /* if this triggers you tried to provide a color format for a value */ - NK_ASSERT(format < NK_FORMAT_COLOR_BEGIN); - if (format >= NK_FORMAT_COLOR_BEGIN && format <= NK_FORMAT_COLOR_END) return; - for (value_index = 0; value_index < value_count; ++value_index) { - switch (format) { - default: NK_ASSERT(0 && "invalid vertex layout format"); break; - case NK_FORMAT_SCHAR: { - char value = (char)NK_CLAMP((float)NK_SCHAR_MIN, values[value_index], (float)NK_SCHAR_MAX); - NK_MEMCPY(attribute, &value, sizeof(value)); - attribute = (void*)((char*)attribute + sizeof(char)); - } break; - case NK_FORMAT_SSHORT: { - nk_short value = (nk_short)NK_CLAMP((float)NK_SSHORT_MIN, values[value_index], (float)NK_SSHORT_MAX); - NK_MEMCPY(attribute, &value, sizeof(value)); - attribute = (void*)((char*)attribute + sizeof(value)); - } break; - case NK_FORMAT_SINT: { - nk_int value = (nk_int)NK_CLAMP((float)NK_SINT_MIN, values[value_index], (float)NK_SINT_MAX); - NK_MEMCPY(attribute, &value, sizeof(value)); - attribute = (void*)((char*)attribute + sizeof(nk_int)); - } break; - case NK_FORMAT_UCHAR: { - unsigned char value = (unsigned char)NK_CLAMP((float)NK_UCHAR_MIN, values[value_index], (float)NK_UCHAR_MAX); - NK_MEMCPY(attribute, &value, sizeof(value)); - attribute = (void*)((char*)attribute + sizeof(unsigned char)); - } break; - case NK_FORMAT_USHORT: { - nk_ushort value = (nk_ushort)NK_CLAMP((float)NK_USHORT_MIN, values[value_index], (float)NK_USHORT_MAX); - NK_MEMCPY(attribute, &value, sizeof(value)); - attribute = (void*)((char*)attribute + sizeof(value)); - } break; - case NK_FORMAT_UINT: { - nk_uint value = (nk_uint)NK_CLAMP((float)NK_UINT_MIN, values[value_index], (float)NK_UINT_MAX); - NK_MEMCPY(attribute, &value, sizeof(value)); - attribute = (void*)((char*)attribute + sizeof(nk_uint)); - } break; - case NK_FORMAT_FLOAT: - NK_MEMCPY(attribute, &values[value_index], sizeof(values[value_index])); - attribute = (void*)((char*)attribute + sizeof(float)); - break; - case NK_FORMAT_DOUBLE: { - double value = (double)values[value_index]; - NK_MEMCPY(attribute, &value, sizeof(value)); - attribute = (void*)((char*)attribute + sizeof(double)); - } break; - } - } -} -NK_INTERN void* -nk_draw_vertex(void *dst, const struct nk_convert_config *config, - struct nk_vec2 pos, struct nk_vec2 uv, struct nk_colorf color) -{ - void *result = (void*)((char*)dst + config->vertex_size); - const struct nk_draw_vertex_layout_element *elem_iter = config->vertex_layout; - while (!nk_draw_vertex_layout_element_is_end_of_layout(elem_iter)) { - void *address = (void*)((char*)dst + elem_iter->offset); - switch (elem_iter->attribute) { - case NK_VERTEX_ATTRIBUTE_COUNT: - default: NK_ASSERT(0 && "wrong element attribute"); break; - case NK_VERTEX_POSITION: nk_draw_vertex_element(address, &pos.x, 2, elem_iter->format); break; - case NK_VERTEX_TEXCOORD: nk_draw_vertex_element(address, &uv.x, 2, elem_iter->format); break; - case NK_VERTEX_COLOR: nk_draw_vertex_color(address, &color.r, elem_iter->format); break; - } - elem_iter++; - } - return result; -} -NK_API void -nk_draw_list_stroke_poly_line(struct nk_draw_list *list, const struct nk_vec2 *points, - const unsigned int points_count, struct nk_color color, enum nk_draw_list_stroke closed, - float thickness, enum nk_anti_aliasing aliasing) -{ - nk_size count; - int thick_line; - struct nk_colorf col; - struct nk_colorf col_trans; - NK_ASSERT(list); - if (!list || points_count < 2) return; - - color.a = (nk_byte)((float)color.a * list->config.global_alpha); - count = points_count; - if (!closed) count = points_count-1; - thick_line = thickness > 1.0f; - -#ifdef NK_INCLUDE_COMMAND_USERDATA - nk_draw_list_push_userdata(list, list->userdata); -#endif - - color.a = (nk_byte)((float)color.a * list->config.global_alpha); - nk_color_fv(&col.r, color); - col_trans = col; - col_trans.a = 0; - - if (aliasing == NK_ANTI_ALIASING_ON) { - /* ANTI-ALIASED STROKE */ - const float AA_SIZE = 1.0f; - NK_STORAGE const nk_size pnt_align = NK_ALIGNOF(struct nk_vec2); - NK_STORAGE const nk_size pnt_size = sizeof(struct nk_vec2); - - /* allocate vertices and elements */ - nk_size i1 = 0; - nk_size vertex_offset; - nk_size index = list->vertex_count; - - const nk_size idx_count = (thick_line) ? (count * 18) : (count * 12); - const nk_size vtx_count = (thick_line) ? (points_count * 4): (points_count *3); - - void *vtx = nk_draw_list_alloc_vertices(list, vtx_count); - nk_draw_index *ids = nk_draw_list_alloc_elements(list, idx_count); - - nk_size size; - struct nk_vec2 *normals, *temp; - if (!vtx || !ids) return; - - /* temporary allocate normals + points */ - vertex_offset = (nk_size)((nk_byte*)vtx - (nk_byte*)list->vertices->memory.ptr); - nk_buffer_mark(list->vertices, NK_BUFFER_FRONT); - size = pnt_size * ((thick_line) ? 5 : 3) * points_count; - normals = (struct nk_vec2*) nk_buffer_alloc(list->vertices, NK_BUFFER_FRONT, size, pnt_align); - if (!normals) return; - temp = normals + points_count; - - /* make sure vertex pointer is still correct */ - vtx = (void*)((nk_byte*)list->vertices->memory.ptr + vertex_offset); - - /* calculate normals */ - for (i1 = 0; i1 < count; ++i1) { - const nk_size i2 = ((i1 + 1) == points_count) ? 0 : (i1 + 1); - struct nk_vec2 diff = nk_vec2_sub(points[i2], points[i1]); - float len; - - /* vec2 inverted length */ - len = nk_vec2_len_sqr(diff); - if (len != 0.0f) - len = nk_inv_sqrt(len); - else len = 1.0f; - - diff = nk_vec2_muls(diff, len); - normals[i1].x = diff.y; - normals[i1].y = -diff.x; - } - - if (!closed) - normals[points_count-1] = normals[points_count-2]; - - if (!thick_line) { - nk_size idx1, i; - if (!closed) { - struct nk_vec2 d; - temp[0] = nk_vec2_add(points[0], nk_vec2_muls(normals[0], AA_SIZE)); - temp[1] = nk_vec2_sub(points[0], nk_vec2_muls(normals[0], AA_SIZE)); - d = nk_vec2_muls(normals[points_count-1], AA_SIZE); - temp[(points_count-1) * 2 + 0] = nk_vec2_add(points[points_count-1], d); - temp[(points_count-1) * 2 + 1] = nk_vec2_sub(points[points_count-1], d); - } - - /* fill elements */ - idx1 = index; - for (i1 = 0; i1 < count; i1++) { - struct nk_vec2 dm; - float dmr2; - nk_size i2 = ((i1 + 1) == points_count) ? 0 : (i1 + 1); - nk_size idx2 = ((i1+1) == points_count) ? index: (idx1 + 3); - - /* average normals */ - dm = nk_vec2_muls(nk_vec2_add(normals[i1], normals[i2]), 0.5f); - dmr2 = dm.x * dm.x + dm.y* dm.y; - if (dmr2 > 0.000001f) { - float scale = 1.0f/dmr2; - scale = NK_MIN(100.0f, scale); - dm = nk_vec2_muls(dm, scale); - } - - dm = nk_vec2_muls(dm, AA_SIZE); - temp[i2*2+0] = nk_vec2_add(points[i2], dm); - temp[i2*2+1] = nk_vec2_sub(points[i2], dm); - - ids[0] = (nk_draw_index)(idx2 + 0); ids[1] = (nk_draw_index)(idx1+0); - ids[2] = (nk_draw_index)(idx1 + 2); ids[3] = (nk_draw_index)(idx1+2); - ids[4] = (nk_draw_index)(idx2 + 2); ids[5] = (nk_draw_index)(idx2+0); - ids[6] = (nk_draw_index)(idx2 + 1); ids[7] = (nk_draw_index)(idx1+1); - ids[8] = (nk_draw_index)(idx1 + 0); ids[9] = (nk_draw_index)(idx1+0); - ids[10]= (nk_draw_index)(idx2 + 0); ids[11]= (nk_draw_index)(idx2+1); - ids += 12; - idx1 = idx2; - } - - /* fill vertices */ - for (i = 0; i < points_count; ++i) { - const struct nk_vec2 uv = list->config.null.uv; - vtx = nk_draw_vertex(vtx, &list->config, points[i], uv, col); - vtx = nk_draw_vertex(vtx, &list->config, temp[i*2+0], uv, col_trans); - vtx = nk_draw_vertex(vtx, &list->config, temp[i*2+1], uv, col_trans); - } - } else { - nk_size idx1, i; - const float half_inner_thickness = (thickness - AA_SIZE) * 0.5f; - if (!closed) { - struct nk_vec2 d1 = nk_vec2_muls(normals[0], half_inner_thickness + AA_SIZE); - struct nk_vec2 d2 = nk_vec2_muls(normals[0], half_inner_thickness); - - temp[0] = nk_vec2_add(points[0], d1); - temp[1] = nk_vec2_add(points[0], d2); - temp[2] = nk_vec2_sub(points[0], d2); - temp[3] = nk_vec2_sub(points[0], d1); - - d1 = nk_vec2_muls(normals[points_count-1], half_inner_thickness + AA_SIZE); - d2 = nk_vec2_muls(normals[points_count-1], half_inner_thickness); - - temp[(points_count-1)*4+0] = nk_vec2_add(points[points_count-1], d1); - temp[(points_count-1)*4+1] = nk_vec2_add(points[points_count-1], d2); - temp[(points_count-1)*4+2] = nk_vec2_sub(points[points_count-1], d2); - temp[(points_count-1)*4+3] = nk_vec2_sub(points[points_count-1], d1); - } - - /* add all elements */ - idx1 = index; - for (i1 = 0; i1 < count; ++i1) { - struct nk_vec2 dm_out, dm_in; - const nk_size i2 = ((i1+1) == points_count) ? 0: (i1 + 1); - nk_size idx2 = ((i1+1) == points_count) ? index: (idx1 + 4); - - /* average normals */ - struct nk_vec2 dm = nk_vec2_muls(nk_vec2_add(normals[i1], normals[i2]), 0.5f); - float dmr2 = dm.x * dm.x + dm.y* dm.y; - if (dmr2 > 0.000001f) { - float scale = 1.0f/dmr2; - scale = NK_MIN(100.0f, scale); - dm = nk_vec2_muls(dm, scale); - } - - dm_out = nk_vec2_muls(dm, ((half_inner_thickness) + AA_SIZE)); - dm_in = nk_vec2_muls(dm, half_inner_thickness); - temp[i2*4+0] = nk_vec2_add(points[i2], dm_out); - temp[i2*4+1] = nk_vec2_add(points[i2], dm_in); - temp[i2*4+2] = nk_vec2_sub(points[i2], dm_in); - temp[i2*4+3] = nk_vec2_sub(points[i2], dm_out); - - /* add indexes */ - ids[0] = (nk_draw_index)(idx2 + 1); ids[1] = (nk_draw_index)(idx1+1); - ids[2] = (nk_draw_index)(idx1 + 2); ids[3] = (nk_draw_index)(idx1+2); - ids[4] = (nk_draw_index)(idx2 + 2); ids[5] = (nk_draw_index)(idx2+1); - ids[6] = (nk_draw_index)(idx2 + 1); ids[7] = (nk_draw_index)(idx1+1); - ids[8] = (nk_draw_index)(idx1 + 0); ids[9] = (nk_draw_index)(idx1+0); - ids[10]= (nk_draw_index)(idx2 + 0); ids[11] = (nk_draw_index)(idx2+1); - ids[12]= (nk_draw_index)(idx2 + 2); ids[13] = (nk_draw_index)(idx1+2); - ids[14]= (nk_draw_index)(idx1 + 3); ids[15] = (nk_draw_index)(idx1+3); - ids[16]= (nk_draw_index)(idx2 + 3); ids[17] = (nk_draw_index)(idx2+2); - ids += 18; - idx1 = idx2; - } - - /* add vertices */ - for (i = 0; i < points_count; ++i) { - const struct nk_vec2 uv = list->config.null.uv; - vtx = nk_draw_vertex(vtx, &list->config, temp[i*4+0], uv, col_trans); - vtx = nk_draw_vertex(vtx, &list->config, temp[i*4+1], uv, col); - vtx = nk_draw_vertex(vtx, &list->config, temp[i*4+2], uv, col); - vtx = nk_draw_vertex(vtx, &list->config, temp[i*4+3], uv, col_trans); - } - } - /* free temporary normals + points */ - nk_buffer_reset(list->vertices, NK_BUFFER_FRONT); - } else { - /* NON ANTI-ALIASED STROKE */ - nk_size i1 = 0; - nk_size idx = list->vertex_count; - const nk_size idx_count = count * 6; - const nk_size vtx_count = count * 4; - void *vtx = nk_draw_list_alloc_vertices(list, vtx_count); - nk_draw_index *ids = nk_draw_list_alloc_elements(list, idx_count); - if (!vtx || !ids) return; - - for (i1 = 0; i1 < count; ++i1) { - float dx, dy; - const struct nk_vec2 uv = list->config.null.uv; - const nk_size i2 = ((i1+1) == points_count) ? 0 : i1 + 1; - const struct nk_vec2 p1 = points[i1]; - const struct nk_vec2 p2 = points[i2]; - struct nk_vec2 diff = nk_vec2_sub(p2, p1); - float len; - - /* vec2 inverted length */ - len = nk_vec2_len_sqr(diff); - if (len != 0.0f) - len = nk_inv_sqrt(len); - else len = 1.0f; - diff = nk_vec2_muls(diff, len); - - /* add vertices */ - dx = diff.x * (thickness * 0.5f); - dy = diff.y * (thickness * 0.5f); - - vtx = nk_draw_vertex(vtx, &list->config, nk_vec2(p1.x + dy, p1.y - dx), uv, col); - vtx = nk_draw_vertex(vtx, &list->config, nk_vec2(p2.x + dy, p2.y - dx), uv, col); - vtx = nk_draw_vertex(vtx, &list->config, nk_vec2(p2.x - dy, p2.y + dx), uv, col); - vtx = nk_draw_vertex(vtx, &list->config, nk_vec2(p1.x - dy, p1.y + dx), uv, col); - - ids[0] = (nk_draw_index)(idx+0); ids[1] = (nk_draw_index)(idx+1); - ids[2] = (nk_draw_index)(idx+2); ids[3] = (nk_draw_index)(idx+0); - ids[4] = (nk_draw_index)(idx+2); ids[5] = (nk_draw_index)(idx+3); - - ids += 6; - idx += 4; - } - } -} -NK_API void -nk_draw_list_fill_poly_convex(struct nk_draw_list *list, - const struct nk_vec2 *points, const unsigned int points_count, - struct nk_color color, enum nk_anti_aliasing aliasing) -{ - struct nk_colorf col; - struct nk_colorf col_trans; - - NK_STORAGE const nk_size pnt_align = NK_ALIGNOF(struct nk_vec2); - NK_STORAGE const nk_size pnt_size = sizeof(struct nk_vec2); - NK_ASSERT(list); - if (!list || points_count < 3) return; - -#ifdef NK_INCLUDE_COMMAND_USERDATA - nk_draw_list_push_userdata(list, list->userdata); -#endif - - color.a = (nk_byte)((float)color.a * list->config.global_alpha); - nk_color_fv(&col.r, color); - col_trans = col; - col_trans.a = 0; - - if (aliasing == NK_ANTI_ALIASING_ON) { - nk_size i = 0; - nk_size i0 = 0; - nk_size i1 = 0; - - const float AA_SIZE = 1.0f; - nk_size vertex_offset = 0; - nk_size index = list->vertex_count; - - const nk_size idx_count = (points_count-2)*3 + points_count*6; - const nk_size vtx_count = (points_count*2); - - void *vtx = nk_draw_list_alloc_vertices(list, vtx_count); - nk_draw_index *ids = nk_draw_list_alloc_elements(list, idx_count); - - nk_size size = 0; - struct nk_vec2 *normals = 0; - unsigned int vtx_inner_idx = (unsigned int)(index + 0); - unsigned int vtx_outer_idx = (unsigned int)(index + 1); - if (!vtx || !ids) return; - - /* temporary allocate normals */ - vertex_offset = (nk_size)((nk_byte*)vtx - (nk_byte*)list->vertices->memory.ptr); - nk_buffer_mark(list->vertices, NK_BUFFER_FRONT); - size = pnt_size * points_count; - normals = (struct nk_vec2*) nk_buffer_alloc(list->vertices, NK_BUFFER_FRONT, size, pnt_align); - if (!normals) return; - vtx = (void*)((nk_byte*)list->vertices->memory.ptr + vertex_offset); - - /* add elements */ - for (i = 2; i < points_count; i++) { - ids[0] = (nk_draw_index)(vtx_inner_idx); - ids[1] = (nk_draw_index)(vtx_inner_idx + ((i-1) << 1)); - ids[2] = (nk_draw_index)(vtx_inner_idx + (i << 1)); - ids += 3; - } - - /* compute normals */ - for (i0 = points_count-1, i1 = 0; i1 < points_count; i0 = i1++) { - struct nk_vec2 p0 = points[i0]; - struct nk_vec2 p1 = points[i1]; - struct nk_vec2 diff = nk_vec2_sub(p1, p0); - - /* vec2 inverted length */ - float len = nk_vec2_len_sqr(diff); - if (len != 0.0f) - len = nk_inv_sqrt(len); - else len = 1.0f; - diff = nk_vec2_muls(diff, len); - - normals[i0].x = diff.y; - normals[i0].y = -diff.x; - } - - /* add vertices + indexes */ - for (i0 = points_count-1, i1 = 0; i1 < points_count; i0 = i1++) { - const struct nk_vec2 uv = list->config.null.uv; - struct nk_vec2 n0 = normals[i0]; - struct nk_vec2 n1 = normals[i1]; - struct nk_vec2 dm = nk_vec2_muls(nk_vec2_add(n0, n1), 0.5f); - float dmr2 = dm.x*dm.x + dm.y*dm.y; - if (dmr2 > 0.000001f) { - float scale = 1.0f / dmr2; - scale = NK_MIN(scale, 100.0f); - dm = nk_vec2_muls(dm, scale); - } - dm = nk_vec2_muls(dm, AA_SIZE * 0.5f); - - /* add vertices */ - vtx = nk_draw_vertex(vtx, &list->config, nk_vec2_sub(points[i1], dm), uv, col); - vtx = nk_draw_vertex(vtx, &list->config, nk_vec2_add(points[i1], dm), uv, col_trans); - - /* add indexes */ - ids[0] = (nk_draw_index)(vtx_inner_idx+(i1<<1)); - ids[1] = (nk_draw_index)(vtx_inner_idx+(i0<<1)); - ids[2] = (nk_draw_index)(vtx_outer_idx+(i0<<1)); - ids[3] = (nk_draw_index)(vtx_outer_idx+(i0<<1)); - ids[4] = (nk_draw_index)(vtx_outer_idx+(i1<<1)); - ids[5] = (nk_draw_index)(vtx_inner_idx+(i1<<1)); - ids += 6; - } - /* free temporary normals + points */ - nk_buffer_reset(list->vertices, NK_BUFFER_FRONT); - } else { - nk_size i = 0; - nk_size index = list->vertex_count; - const nk_size idx_count = (points_count-2)*3; - const nk_size vtx_count = points_count; - void *vtx = nk_draw_list_alloc_vertices(list, vtx_count); - nk_draw_index *ids = nk_draw_list_alloc_elements(list, idx_count); - - if (!vtx || !ids) return; - for (i = 0; i < vtx_count; ++i) - vtx = nk_draw_vertex(vtx, &list->config, points[i], list->config.null.uv, col); - for (i = 2; i < points_count; ++i) { - ids[0] = (nk_draw_index)index; - ids[1] = (nk_draw_index)(index+ i - 1); - ids[2] = (nk_draw_index)(index+i); - ids += 3; - } - } -} -NK_API void -nk_draw_list_path_clear(struct nk_draw_list *list) -{ - NK_ASSERT(list); - if (!list) return; - nk_buffer_reset(list->buffer, NK_BUFFER_FRONT); - list->path_count = 0; - list->path_offset = 0; -} -NK_API void -nk_draw_list_path_line_to(struct nk_draw_list *list, struct nk_vec2 pos) -{ - struct nk_vec2 *points = 0; - struct nk_draw_command *cmd = 0; - NK_ASSERT(list); - if (!list) return; - if (!list->cmd_count) - nk_draw_list_add_clip(list, nk_null_rect); - - cmd = nk_draw_list_command_last(list); - if (cmd && cmd->texture.ptr != list->config.null.texture.ptr) - nk_draw_list_push_image(list, list->config.null.texture); - - points = nk_draw_list_alloc_path(list, 1); - if (!points) return; - points[0] = pos; -} -NK_API void -nk_draw_list_path_arc_to_fast(struct nk_draw_list *list, struct nk_vec2 center, - float radius, int a_min, int a_max) -{ - int a = 0; - NK_ASSERT(list); - if (!list) return; - if (a_min <= a_max) { - for (a = a_min; a <= a_max; a++) { - const struct nk_vec2 c = list->circle_vtx[(nk_size)a % NK_LEN(list->circle_vtx)]; - const float x = center.x + c.x * radius; - const float y = center.y + c.y * radius; - nk_draw_list_path_line_to(list, nk_vec2(x, y)); - } - } -} -NK_API void -nk_draw_list_path_arc_to(struct nk_draw_list *list, struct nk_vec2 center, - float radius, float a_min, float a_max, unsigned int segments) -{ - unsigned int i = 0; - NK_ASSERT(list); - if (!list) return; - if (radius == 0.0f) return; - - /* This algorithm for arc drawing relies on these two trigonometric identities[1]: - sin(a + b) = sin(a) * cos(b) + cos(a) * sin(b) - cos(a + b) = cos(a) * cos(b) - sin(a) * sin(b) - - Two coordinates (x, y) of a point on a circle centered on - the origin can be written in polar form as: - x = r * cos(a) - y = r * sin(a) - where r is the radius of the circle, - a is the angle between (x, y) and the origin. - - This allows us to rotate the coordinates around the - origin by an angle b using the following transformation: - x' = r * cos(a + b) = x * cos(b) - y * sin(b) - y' = r * sin(a + b) = y * cos(b) + x * sin(b) - - [1] https://en.wikipedia.org/wiki/List_of_trigonometric_identities#Angle_sum_and_difference_identities - */ - {const float d_angle = (a_max - a_min) / (float)segments; - const float sin_d = (float)NK_SIN(d_angle); - const float cos_d = (float)NK_COS(d_angle); - - float cx = (float)NK_COS(a_min) * radius; - float cy = (float)NK_SIN(a_min) * radius; - for(i = 0; i <= segments; ++i) { - float new_cx, new_cy; - const float x = center.x + cx; - const float y = center.y + cy; - nk_draw_list_path_line_to(list, nk_vec2(x, y)); - - new_cx = cx * cos_d - cy * sin_d; - new_cy = cy * cos_d + cx * sin_d; - cx = new_cx; - cy = new_cy; - }} -} -NK_API void -nk_draw_list_path_rect_to(struct nk_draw_list *list, struct nk_vec2 a, - struct nk_vec2 b, float rounding) -{ - float r; - NK_ASSERT(list); - if (!list) return; - r = rounding; - r = NK_MIN(r, ((b.x-a.x) < 0) ? -(b.x-a.x): (b.x-a.x)); - r = NK_MIN(r, ((b.y-a.y) < 0) ? -(b.y-a.y): (b.y-a.y)); - - if (r == 0.0f) { - nk_draw_list_path_line_to(list, a); - nk_draw_list_path_line_to(list, nk_vec2(b.x,a.y)); - nk_draw_list_path_line_to(list, b); - nk_draw_list_path_line_to(list, nk_vec2(a.x,b.y)); - } else { - nk_draw_list_path_arc_to_fast(list, nk_vec2(a.x + r, a.y + r), r, 6, 9); - nk_draw_list_path_arc_to_fast(list, nk_vec2(b.x - r, a.y + r), r, 9, 12); - nk_draw_list_path_arc_to_fast(list, nk_vec2(b.x - r, b.y - r), r, 0, 3); - nk_draw_list_path_arc_to_fast(list, nk_vec2(a.x + r, b.y - r), r, 3, 6); - } -} -NK_API void -nk_draw_list_path_curve_to(struct nk_draw_list *list, struct nk_vec2 p2, - struct nk_vec2 p3, struct nk_vec2 p4, unsigned int num_segments) -{ - float t_step; - unsigned int i_step; - struct nk_vec2 p1; - - NK_ASSERT(list); - NK_ASSERT(list->path_count); - if (!list || !list->path_count) return; - num_segments = NK_MAX(num_segments, 1); - - p1 = nk_draw_list_path_last(list); - t_step = 1.0f/(float)num_segments; - for (i_step = 1; i_step <= num_segments; ++i_step) { - float t = t_step * (float)i_step; - float u = 1.0f - t; - float w1 = u*u*u; - float w2 = 3*u*u*t; - float w3 = 3*u*t*t; - float w4 = t * t *t; - float x = w1 * p1.x + w2 * p2.x + w3 * p3.x + w4 * p4.x; - float y = w1 * p1.y + w2 * p2.y + w3 * p3.y + w4 * p4.y; - nk_draw_list_path_line_to(list, nk_vec2(x,y)); - } -} -NK_API void -nk_draw_list_path_fill(struct nk_draw_list *list, struct nk_color color) -{ - struct nk_vec2 *points; - NK_ASSERT(list); - if (!list) return; - points = (struct nk_vec2*)nk_buffer_memory(list->buffer); - nk_draw_list_fill_poly_convex(list, points, list->path_count, color, list->config.shape_AA); - nk_draw_list_path_clear(list); -} -NK_API void -nk_draw_list_path_stroke(struct nk_draw_list *list, struct nk_color color, - enum nk_draw_list_stroke closed, float thickness) -{ - struct nk_vec2 *points; - NK_ASSERT(list); - if (!list) return; - points = (struct nk_vec2*)nk_buffer_memory(list->buffer); - nk_draw_list_stroke_poly_line(list, points, list->path_count, color, - closed, thickness, list->config.line_AA); - nk_draw_list_path_clear(list); -} -NK_API void -nk_draw_list_stroke_line(struct nk_draw_list *list, struct nk_vec2 a, - struct nk_vec2 b, struct nk_color col, float thickness) -{ - NK_ASSERT(list); - if (!list || !col.a) return; - if (list->line_AA == NK_ANTI_ALIASING_ON) { - nk_draw_list_path_line_to(list, a); - nk_draw_list_path_line_to(list, b); - } else { - nk_draw_list_path_line_to(list, nk_vec2_sub(a,nk_vec2(0.5f,0.5f))); - nk_draw_list_path_line_to(list, nk_vec2_sub(b,nk_vec2(0.5f,0.5f))); - } - nk_draw_list_path_stroke(list, col, NK_STROKE_OPEN, thickness); -} -NK_API void -nk_draw_list_fill_rect(struct nk_draw_list *list, struct nk_rect rect, - struct nk_color col, float rounding) -{ - NK_ASSERT(list); - if (!list || !col.a) return; - - if (list->line_AA == NK_ANTI_ALIASING_ON) { - nk_draw_list_path_rect_to(list, nk_vec2(rect.x, rect.y), - nk_vec2(rect.x + rect.w, rect.y + rect.h), rounding); - } else { - nk_draw_list_path_rect_to(list, nk_vec2(rect.x-0.5f, rect.y-0.5f), - nk_vec2(rect.x + rect.w, rect.y + rect.h), rounding); - } nk_draw_list_path_fill(list, col); -} -NK_API void -nk_draw_list_stroke_rect(struct nk_draw_list *list, struct nk_rect rect, - struct nk_color col, float rounding, float thickness) -{ - NK_ASSERT(list); - if (!list || !col.a) return; - if (list->line_AA == NK_ANTI_ALIASING_ON) { - nk_draw_list_path_rect_to(list, nk_vec2(rect.x, rect.y), - nk_vec2(rect.x + rect.w, rect.y + rect.h), rounding); - } else { - nk_draw_list_path_rect_to(list, nk_vec2(rect.x-0.5f, rect.y-0.5f), - nk_vec2(rect.x + rect.w, rect.y + rect.h), rounding); - } nk_draw_list_path_stroke(list, col, NK_STROKE_CLOSED, thickness); -} -NK_API void -nk_draw_list_fill_rect_multi_color(struct nk_draw_list *list, struct nk_rect rect, - struct nk_color left, struct nk_color top, struct nk_color right, - struct nk_color bottom) -{ - void *vtx; - struct nk_colorf col_left, col_top; - struct nk_colorf col_right, col_bottom; - nk_draw_index *idx; - nk_draw_index index; - - nk_color_fv(&col_left.r, left); - nk_color_fv(&col_right.r, right); - nk_color_fv(&col_top.r, top); - nk_color_fv(&col_bottom.r, bottom); - - NK_ASSERT(list); - if (!list) return; - - nk_draw_list_push_image(list, list->config.null.texture); - index = (nk_draw_index)list->vertex_count; - vtx = nk_draw_list_alloc_vertices(list, 4); - idx = nk_draw_list_alloc_elements(list, 6); - if (!vtx || !idx) return; - - idx[0] = (nk_draw_index)(index+0); idx[1] = (nk_draw_index)(index+1); - idx[2] = (nk_draw_index)(index+2); idx[3] = (nk_draw_index)(index+0); - idx[4] = (nk_draw_index)(index+2); idx[5] = (nk_draw_index)(index+3); - - vtx = nk_draw_vertex(vtx, &list->config, nk_vec2(rect.x, rect.y), list->config.null.uv, col_left); - vtx = nk_draw_vertex(vtx, &list->config, nk_vec2(rect.x + rect.w, rect.y), list->config.null.uv, col_top); - vtx = nk_draw_vertex(vtx, &list->config, nk_vec2(rect.x + rect.w, rect.y + rect.h), list->config.null.uv, col_right); - vtx = nk_draw_vertex(vtx, &list->config, nk_vec2(rect.x, rect.y + rect.h), list->config.null.uv, col_bottom); -} -NK_API void -nk_draw_list_fill_triangle(struct nk_draw_list *list, struct nk_vec2 a, - struct nk_vec2 b, struct nk_vec2 c, struct nk_color col) -{ - NK_ASSERT(list); - if (!list || !col.a) return; - nk_draw_list_path_line_to(list, a); - nk_draw_list_path_line_to(list, b); - nk_draw_list_path_line_to(list, c); - nk_draw_list_path_fill(list, col); -} -NK_API void -nk_draw_list_stroke_triangle(struct nk_draw_list *list, struct nk_vec2 a, - struct nk_vec2 b, struct nk_vec2 c, struct nk_color col, float thickness) -{ - NK_ASSERT(list); - if (!list || !col.a) return; - nk_draw_list_path_line_to(list, a); - nk_draw_list_path_line_to(list, b); - nk_draw_list_path_line_to(list, c); - nk_draw_list_path_stroke(list, col, NK_STROKE_CLOSED, thickness); -} -NK_API void -nk_draw_list_fill_circle(struct nk_draw_list *list, struct nk_vec2 center, - float radius, struct nk_color col, unsigned int segs) -{ - float a_max; - NK_ASSERT(list); - if (!list || !col.a) return; - a_max = NK_PI * 2.0f * ((float)segs - 1.0f) / (float)segs; - nk_draw_list_path_arc_to(list, center, radius, 0.0f, a_max, segs); - nk_draw_list_path_fill(list, col); -} -NK_API void -nk_draw_list_stroke_circle(struct nk_draw_list *list, struct nk_vec2 center, - float radius, struct nk_color col, unsigned int segs, float thickness) -{ - float a_max; - NK_ASSERT(list); - if (!list || !col.a) return; - a_max = NK_PI * 2.0f * ((float)segs - 1.0f) / (float)segs; - nk_draw_list_path_arc_to(list, center, radius, 0.0f, a_max, segs); - nk_draw_list_path_stroke(list, col, NK_STROKE_CLOSED, thickness); -} -NK_API void -nk_draw_list_stroke_curve(struct nk_draw_list *list, struct nk_vec2 p0, - struct nk_vec2 cp0, struct nk_vec2 cp1, struct nk_vec2 p1, - struct nk_color col, unsigned int segments, float thickness) -{ - NK_ASSERT(list); - if (!list || !col.a) return; - nk_draw_list_path_line_to(list, p0); - nk_draw_list_path_curve_to(list, cp0, cp1, p1, segments); - nk_draw_list_path_stroke(list, col, NK_STROKE_OPEN, thickness); -} -NK_INTERN void -nk_draw_list_push_rect_uv(struct nk_draw_list *list, struct nk_vec2 a, - struct nk_vec2 c, struct nk_vec2 uva, struct nk_vec2 uvc, - struct nk_color color) -{ - void *vtx; - struct nk_vec2 uvb; - struct nk_vec2 uvd; - struct nk_vec2 b; - struct nk_vec2 d; - - struct nk_colorf col; - nk_draw_index *idx; - nk_draw_index index; - NK_ASSERT(list); - if (!list) return; - - nk_color_fv(&col.r, color); - uvb = nk_vec2(uvc.x, uva.y); - uvd = nk_vec2(uva.x, uvc.y); - b = nk_vec2(c.x, a.y); - d = nk_vec2(a.x, c.y); - - index = (nk_draw_index)list->vertex_count; - vtx = nk_draw_list_alloc_vertices(list, 4); - idx = nk_draw_list_alloc_elements(list, 6); - if (!vtx || !idx) return; - - idx[0] = (nk_draw_index)(index+0); idx[1] = (nk_draw_index)(index+1); - idx[2] = (nk_draw_index)(index+2); idx[3] = (nk_draw_index)(index+0); - idx[4] = (nk_draw_index)(index+2); idx[5] = (nk_draw_index)(index+3); - - vtx = nk_draw_vertex(vtx, &list->config, a, uva, col); - vtx = nk_draw_vertex(vtx, &list->config, b, uvb, col); - vtx = nk_draw_vertex(vtx, &list->config, c, uvc, col); - vtx = nk_draw_vertex(vtx, &list->config, d, uvd, col); -} -NK_API void -nk_draw_list_add_image(struct nk_draw_list *list, struct nk_image texture, - struct nk_rect rect, struct nk_color color) -{ - NK_ASSERT(list); - if (!list) return; - /* push new command with given texture */ - nk_draw_list_push_image(list, texture.handle); - if (nk_image_is_subimage(&texture)) { - /* add region inside of the texture */ - struct nk_vec2 uv[2]; - uv[0].x = (float)texture.region[0]/(float)texture.w; - uv[0].y = (float)texture.region[1]/(float)texture.h; - uv[1].x = (float)(texture.region[0] + texture.region[2])/(float)texture.w; - uv[1].y = (float)(texture.region[1] + texture.region[3])/(float)texture.h; - nk_draw_list_push_rect_uv(list, nk_vec2(rect.x, rect.y), - nk_vec2(rect.x + rect.w, rect.y + rect.h), uv[0], uv[1], color); - } else nk_draw_list_push_rect_uv(list, nk_vec2(rect.x, rect.y), - nk_vec2(rect.x + rect.w, rect.y + rect.h), - nk_vec2(0.0f, 0.0f), nk_vec2(1.0f, 1.0f),color); -} -NK_API void -nk_draw_list_add_text(struct nk_draw_list *list, const struct nk_user_font *font, - struct nk_rect rect, const char *text, int len, float font_height, - struct nk_color fg) -{ - float x = 0; - int text_len = 0; - nk_rune unicode = 0; - nk_rune next = 0; - int glyph_len = 0; - int next_glyph_len = 0; - struct nk_user_font_glyph g; - - NK_ASSERT(list); - if (!list || !len || !text) return; - if (!NK_INTERSECT(rect.x, rect.y, rect.w, rect.h, - list->clip_rect.x, list->clip_rect.y, list->clip_rect.w, list->clip_rect.h)) return; - - nk_draw_list_push_image(list, font->texture); - x = rect.x; - glyph_len = nk_utf_decode(text, &unicode, len); - if (!glyph_len) return; - - /* draw every glyph image */ - fg.a = (nk_byte)((float)fg.a * list->config.global_alpha); - while (text_len < len && glyph_len) { - float gx, gy, gh, gw; - float char_width = 0; - if (unicode == NK_UTF_INVALID) break; - - /* query currently drawn glyph information */ - next_glyph_len = nk_utf_decode(text + text_len + glyph_len, &next, (int)len - text_len); - font->query(font->userdata, font_height, &g, unicode, - (next == NK_UTF_INVALID) ? '\0' : next); - - /* calculate and draw glyph drawing rectangle and image */ - gx = x + g.offset.x; - gy = rect.y + g.offset.y; - gw = g.width; gh = g.height; - char_width = g.xadvance; - nk_draw_list_push_rect_uv(list, nk_vec2(gx,gy), nk_vec2(gx + gw, gy+ gh), - g.uv[0], g.uv[1], fg); - - /* offset next glyph */ - text_len += glyph_len; - x += char_width; - glyph_len = next_glyph_len; - unicode = next; - } -} -NK_API nk_flags -nk_convert(struct nk_context *ctx, struct nk_buffer *cmds, - struct nk_buffer *vertices, struct nk_buffer *elements, - const struct nk_convert_config *config) -{ - nk_flags res = NK_CONVERT_SUCCESS; - const struct nk_command *cmd; - NK_ASSERT(ctx); - NK_ASSERT(cmds); - NK_ASSERT(vertices); - NK_ASSERT(elements); - NK_ASSERT(config); - NK_ASSERT(config->vertex_layout); - NK_ASSERT(config->vertex_size); - if (!ctx || !cmds || !vertices || !elements || !config || !config->vertex_layout) - return NK_CONVERT_INVALID_PARAM; - - nk_draw_list_setup(&ctx->draw_list, config, cmds, vertices, elements, - config->line_AA, config->shape_AA); - nk_foreach(cmd, ctx) - { -#ifdef NK_INCLUDE_COMMAND_USERDATA - ctx->draw_list.userdata = cmd->userdata; -#endif - switch (cmd->type) { - case NK_COMMAND_NOP: break; - case NK_COMMAND_SCISSOR: { - const struct nk_command_scissor *s = (const struct nk_command_scissor*)cmd; - nk_draw_list_add_clip(&ctx->draw_list, nk_rect(s->x, s->y, s->w, s->h)); - } break; - case NK_COMMAND_LINE: { - const struct nk_command_line *l = (const struct nk_command_line*)cmd; - nk_draw_list_stroke_line(&ctx->draw_list, nk_vec2(l->begin.x, l->begin.y), - nk_vec2(l->end.x, l->end.y), l->color, l->line_thickness); - } break; - case NK_COMMAND_CURVE: { - const struct nk_command_curve *q = (const struct nk_command_curve*)cmd; - nk_draw_list_stroke_curve(&ctx->draw_list, nk_vec2(q->begin.x, q->begin.y), - nk_vec2(q->ctrl[0].x, q->ctrl[0].y), nk_vec2(q->ctrl[1].x, - q->ctrl[1].y), nk_vec2(q->end.x, q->end.y), q->color, - config->curve_segment_count, q->line_thickness); - } break; - case NK_COMMAND_RECT: { - const struct nk_command_rect *r = (const struct nk_command_rect*)cmd; - nk_draw_list_stroke_rect(&ctx->draw_list, nk_rect(r->x, r->y, r->w, r->h), - r->color, (float)r->rounding, r->line_thickness); - } break; - case NK_COMMAND_RECT_FILLED: { - const struct nk_command_rect_filled *r = (const struct nk_command_rect_filled*)cmd; - nk_draw_list_fill_rect(&ctx->draw_list, nk_rect(r->x, r->y, r->w, r->h), - r->color, (float)r->rounding); - } break; - case NK_COMMAND_RECT_MULTI_COLOR: { - const struct nk_command_rect_multi_color *r = (const struct nk_command_rect_multi_color*)cmd; - nk_draw_list_fill_rect_multi_color(&ctx->draw_list, nk_rect(r->x, r->y, r->w, r->h), - r->left, r->top, r->right, r->bottom); - } break; - case NK_COMMAND_CIRCLE: { - const struct nk_command_circle *c = (const struct nk_command_circle*)cmd; - nk_draw_list_stroke_circle(&ctx->draw_list, nk_vec2((float)c->x + (float)c->w/2, - (float)c->y + (float)c->h/2), (float)c->w/2, c->color, - config->circle_segment_count, c->line_thickness); - } break; - case NK_COMMAND_CIRCLE_FILLED: { - const struct nk_command_circle_filled *c = (const struct nk_command_circle_filled *)cmd; - nk_draw_list_fill_circle(&ctx->draw_list, nk_vec2((float)c->x + (float)c->w/2, - (float)c->y + (float)c->h/2), (float)c->w/2, c->color, - config->circle_segment_count); - } break; - case NK_COMMAND_ARC: { - const struct nk_command_arc *c = (const struct nk_command_arc*)cmd; - nk_draw_list_path_line_to(&ctx->draw_list, nk_vec2(c->cx, c->cy)); - nk_draw_list_path_arc_to(&ctx->draw_list, nk_vec2(c->cx, c->cy), c->r, - c->a[0], c->a[1], config->arc_segment_count); - nk_draw_list_path_stroke(&ctx->draw_list, c->color, NK_STROKE_CLOSED, c->line_thickness); - } break; - case NK_COMMAND_ARC_FILLED: { - const struct nk_command_arc_filled *c = (const struct nk_command_arc_filled*)cmd; - nk_draw_list_path_line_to(&ctx->draw_list, nk_vec2(c->cx, c->cy)); - nk_draw_list_path_arc_to(&ctx->draw_list, nk_vec2(c->cx, c->cy), c->r, - c->a[0], c->a[1], config->arc_segment_count); - nk_draw_list_path_fill(&ctx->draw_list, c->color); - } break; - case NK_COMMAND_TRIANGLE: { - const struct nk_command_triangle *t = (const struct nk_command_triangle*)cmd; - nk_draw_list_stroke_triangle(&ctx->draw_list, nk_vec2(t->a.x, t->a.y), - nk_vec2(t->b.x, t->b.y), nk_vec2(t->c.x, t->c.y), t->color, - t->line_thickness); - } break; - case NK_COMMAND_TRIANGLE_FILLED: { - const struct nk_command_triangle_filled *t = (const struct nk_command_triangle_filled*)cmd; - nk_draw_list_fill_triangle(&ctx->draw_list, nk_vec2(t->a.x, t->a.y), - nk_vec2(t->b.x, t->b.y), nk_vec2(t->c.x, t->c.y), t->color); - } break; - case NK_COMMAND_POLYGON: { - int i; - const struct nk_command_polygon*p = (const struct nk_command_polygon*)cmd; - for (i = 0; i < p->point_count; ++i) { - struct nk_vec2 pnt = nk_vec2((float)p->points[i].x, (float)p->points[i].y); - nk_draw_list_path_line_to(&ctx->draw_list, pnt); - } - nk_draw_list_path_stroke(&ctx->draw_list, p->color, NK_STROKE_CLOSED, p->line_thickness); - } break; - case NK_COMMAND_POLYGON_FILLED: { - int i; - const struct nk_command_polygon_filled *p = (const struct nk_command_polygon_filled*)cmd; - for (i = 0; i < p->point_count; ++i) { - struct nk_vec2 pnt = nk_vec2((float)p->points[i].x, (float)p->points[i].y); - nk_draw_list_path_line_to(&ctx->draw_list, pnt); - } - nk_draw_list_path_fill(&ctx->draw_list, p->color); - } break; - case NK_COMMAND_POLYLINE: { - int i; - const struct nk_command_polyline *p = (const struct nk_command_polyline*)cmd; - for (i = 0; i < p->point_count; ++i) { - struct nk_vec2 pnt = nk_vec2((float)p->points[i].x, (float)p->points[i].y); - nk_draw_list_path_line_to(&ctx->draw_list, pnt); - } - nk_draw_list_path_stroke(&ctx->draw_list, p->color, NK_STROKE_OPEN, p->line_thickness); - } break; - case NK_COMMAND_TEXT: { - const struct nk_command_text *t = (const struct nk_command_text*)cmd; - nk_draw_list_add_text(&ctx->draw_list, t->font, nk_rect(t->x, t->y, t->w, t->h), - t->string, t->length, t->height, t->foreground); - } break; - case NK_COMMAND_IMAGE: { - const struct nk_command_image *i = (const struct nk_command_image*)cmd; - nk_draw_list_add_image(&ctx->draw_list, i->img, nk_rect(i->x, i->y, i->w, i->h), i->col); - } break; - case NK_COMMAND_CUSTOM: { - const struct nk_command_custom *c = (const struct nk_command_custom*)cmd; - c->callback(&ctx->draw_list, c->x, c->y, c->w, c->h, c->callback_data); - } break; - default: break; - } - } - res |= (cmds->needed > cmds->allocated + (cmds->memory.size - cmds->size)) ? NK_CONVERT_COMMAND_BUFFER_FULL: 0; - res |= (vertices->needed > vertices->allocated) ? NK_CONVERT_VERTEX_BUFFER_FULL: 0; - res |= (elements->needed > elements->allocated) ? NK_CONVERT_ELEMENT_BUFFER_FULL: 0; - return res; -} -NK_API const struct nk_draw_command* -nk__draw_begin(const struct nk_context *ctx, - const struct nk_buffer *buffer) -{ - return nk__draw_list_begin(&ctx->draw_list, buffer); -} -NK_API const struct nk_draw_command* -nk__draw_end(const struct nk_context *ctx, const struct nk_buffer *buffer) -{ - return nk__draw_list_end(&ctx->draw_list, buffer); -} -NK_API const struct nk_draw_command* -nk__draw_next(const struct nk_draw_command *cmd, - const struct nk_buffer *buffer, const struct nk_context *ctx) -{ - return nk__draw_list_next(cmd, buffer, &ctx->draw_list); -} -#endif - - - - - -#ifdef NK_INCLUDE_FONT_BAKING -/* ------------------------------------------------------------- - * - * RECT PACK - * - * --------------------------------------------------------------*/ -/* stb_rect_pack.h - v0.05 - public domain - rectangle packing */ -/* Sean Barrett 2014 */ -#define NK_RP__MAXVAL 0xffff -typedef unsigned short nk_rp_coord; - -struct nk_rp_rect { - /* reserved for your use: */ - int id; - /* input: */ - nk_rp_coord w, h; - /* output: */ - nk_rp_coord x, y; - int was_packed; - /* non-zero if valid packing */ -}; /* 16 bytes, nominally */ - -struct nk_rp_node { - nk_rp_coord x,y; - struct nk_rp_node *next; -}; - -struct nk_rp_context { - int width; - int height; - int align; - int init_mode; - int heuristic; - int num_nodes; - struct nk_rp_node *active_head; - struct nk_rp_node *free_head; - struct nk_rp_node extra[2]; - /* we allocate two extra nodes so optimal user-node-count is 'width' not 'width+2' */ -}; - -struct nk_rp__findresult { - int x,y; - struct nk_rp_node **prev_link; -}; - -enum NK_RP_HEURISTIC { - NK_RP_HEURISTIC_Skyline_default=0, - NK_RP_HEURISTIC_Skyline_BL_sortHeight = NK_RP_HEURISTIC_Skyline_default, - NK_RP_HEURISTIC_Skyline_BF_sortHeight -}; -enum NK_RP_INIT_STATE{NK_RP__INIT_skyline = 1}; - -NK_INTERN void -nk_rp_setup_allow_out_of_mem(struct nk_rp_context *context, int allow_out_of_mem) -{ - if (allow_out_of_mem) - /* if it's ok to run out of memory, then don't bother aligning them; */ - /* this gives better packing, but may fail due to OOM (even though */ - /* the rectangles easily fit). @TODO a smarter approach would be to only */ - /* quantize once we've hit OOM, then we could get rid of this parameter. */ - context->align = 1; - else { - /* if it's not ok to run out of memory, then quantize the widths */ - /* so that num_nodes is always enough nodes. */ - /* */ - /* I.e. num_nodes * align >= width */ - /* align >= width / num_nodes */ - /* align = ceil(width/num_nodes) */ - context->align = (context->width + context->num_nodes-1) / context->num_nodes; - } -} -NK_INTERN void -nk_rp_init_target(struct nk_rp_context *context, int width, int height, - struct nk_rp_node *nodes, int num_nodes) -{ - int i; -#ifndef STBRP_LARGE_RECTS - NK_ASSERT(width <= 0xffff && height <= 0xffff); -#endif - - for (i=0; i < num_nodes-1; ++i) - nodes[i].next = &nodes[i+1]; - nodes[i].next = 0; - context->init_mode = NK_RP__INIT_skyline; - context->heuristic = NK_RP_HEURISTIC_Skyline_default; - context->free_head = &nodes[0]; - context->active_head = &context->extra[0]; - context->width = width; - context->height = height; - context->num_nodes = num_nodes; - nk_rp_setup_allow_out_of_mem(context, 0); - - /* node 0 is the full width, node 1 is the sentinel (lets us not store width explicitly) */ - context->extra[0].x = 0; - context->extra[0].y = 0; - context->extra[0].next = &context->extra[1]; - context->extra[1].x = (nk_rp_coord) width; - context->extra[1].y = 65535; - context->extra[1].next = 0; -} -/* find minimum y position if it starts at x1 */ -NK_INTERN int -nk_rp__skyline_find_min_y(struct nk_rp_context *c, struct nk_rp_node *first, - int x0, int width, int *pwaste) -{ - struct nk_rp_node *node = first; - int x1 = x0 + width; - int min_y, visited_width, waste_area; - NK_ASSERT(first->x <= x0); - NK_UNUSED(c); - - NK_ASSERT(node->next->x > x0); - /* we ended up handling this in the caller for efficiency */ - NK_ASSERT(node->x <= x0); - - min_y = 0; - waste_area = 0; - visited_width = 0; - while (node->x < x1) - { - if (node->y > min_y) { - /* raise min_y higher. */ - /* we've accounted for all waste up to min_y, */ - /* but we'll now add more waste for everything we've visited */ - waste_area += visited_width * (node->y - min_y); - min_y = node->y; - /* the first time through, visited_width might be reduced */ - if (node->x < x0) - visited_width += node->next->x - x0; - else - visited_width += node->next->x - node->x; - } else { - /* add waste area */ - int under_width = node->next->x - node->x; - if (under_width + visited_width > width) - under_width = width - visited_width; - waste_area += under_width * (min_y - node->y); - visited_width += under_width; - } - node = node->next; - } - *pwaste = waste_area; - return min_y; -} -NK_INTERN struct nk_rp__findresult -nk_rp__skyline_find_best_pos(struct nk_rp_context *c, int width, int height) -{ - int best_waste = (1<<30), best_x, best_y = (1 << 30); - struct nk_rp__findresult fr; - struct nk_rp_node **prev, *node, *tail, **best = 0; - - /* align to multiple of c->align */ - width = (width + c->align - 1); - width -= width % c->align; - NK_ASSERT(width % c->align == 0); - - node = c->active_head; - prev = &c->active_head; - while (node->x + width <= c->width) { - int y,waste; - y = nk_rp__skyline_find_min_y(c, node, node->x, width, &waste); - /* actually just want to test BL */ - if (c->heuristic == NK_RP_HEURISTIC_Skyline_BL_sortHeight) { - /* bottom left */ - if (y < best_y) { - best_y = y; - best = prev; - } - } else { - /* best-fit */ - if (y + height <= c->height) { - /* can only use it if it first vertically */ - if (y < best_y || (y == best_y && waste < best_waste)) { - best_y = y; - best_waste = waste; - best = prev; - } - } - } - prev = &node->next; - node = node->next; - } - best_x = (best == 0) ? 0 : (*best)->x; - - /* if doing best-fit (BF), we also have to try aligning right edge to each node position */ - /* */ - /* e.g, if fitting */ - /* */ - /* ____________________ */ - /* |____________________| */ - /* */ - /* into */ - /* */ - /* | | */ - /* | ____________| */ - /* |____________| */ - /* */ - /* then right-aligned reduces waste, but bottom-left BL is always chooses left-aligned */ - /* */ - /* This makes BF take about 2x the time */ - if (c->heuristic == NK_RP_HEURISTIC_Skyline_BF_sortHeight) - { - tail = c->active_head; - node = c->active_head; - prev = &c->active_head; - /* find first node that's admissible */ - while (tail->x < width) - tail = tail->next; - while (tail) - { - int xpos = tail->x - width; - int y,waste; - NK_ASSERT(xpos >= 0); - /* find the left position that matches this */ - while (node->next->x <= xpos) { - prev = &node->next; - node = node->next; - } - NK_ASSERT(node->next->x > xpos && node->x <= xpos); - y = nk_rp__skyline_find_min_y(c, node, xpos, width, &waste); - if (y + height < c->height) { - if (y <= best_y) { - if (y < best_y || waste < best_waste || (waste==best_waste && xpos < best_x)) { - best_x = xpos; - NK_ASSERT(y <= best_y); - best_y = y; - best_waste = waste; - best = prev; - } - } - } - tail = tail->next; - } - } - fr.prev_link = best; - fr.x = best_x; - fr.y = best_y; - return fr; -} -NK_INTERN struct nk_rp__findresult -nk_rp__skyline_pack_rectangle(struct nk_rp_context *context, int width, int height) -{ - /* find best position according to heuristic */ - struct nk_rp__findresult res = nk_rp__skyline_find_best_pos(context, width, height); - struct nk_rp_node *node, *cur; - - /* bail if: */ - /* 1. it failed */ - /* 2. the best node doesn't fit (we don't always check this) */ - /* 3. we're out of memory */ - if (res.prev_link == 0 || res.y + height > context->height || context->free_head == 0) { - res.prev_link = 0; - return res; - } - - /* on success, create new node */ - node = context->free_head; - node->x = (nk_rp_coord) res.x; - node->y = (nk_rp_coord) (res.y + height); - - context->free_head = node->next; - - /* insert the new node into the right starting point, and */ - /* let 'cur' point to the remaining nodes needing to be */ - /* stitched back in */ - cur = *res.prev_link; - if (cur->x < res.x) { - /* preserve the existing one, so start testing with the next one */ - struct nk_rp_node *next = cur->next; - cur->next = node; - cur = next; - } else { - *res.prev_link = node; - } - - /* from here, traverse cur and free the nodes, until we get to one */ - /* that shouldn't be freed */ - while (cur->next && cur->next->x <= res.x + width) { - struct nk_rp_node *next = cur->next; - /* move the current node to the free list */ - cur->next = context->free_head; - context->free_head = cur; - cur = next; - } - /* stitch the list back in */ - node->next = cur; - - if (cur->x < res.x + width) - cur->x = (nk_rp_coord) (res.x + width); - return res; -} -NK_INTERN int -nk_rect_height_compare(const void *a, const void *b) -{ - const struct nk_rp_rect *p = (const struct nk_rp_rect *) a; - const struct nk_rp_rect *q = (const struct nk_rp_rect *) b; - if (p->h > q->h) - return -1; - if (p->h < q->h) - return 1; - return (p->w > q->w) ? -1 : (p->w < q->w); -} -NK_INTERN int -nk_rect_original_order(const void *a, const void *b) -{ - const struct nk_rp_rect *p = (const struct nk_rp_rect *) a; - const struct nk_rp_rect *q = (const struct nk_rp_rect *) b; - return (p->was_packed < q->was_packed) ? -1 : (p->was_packed > q->was_packed); -} -NK_INTERN void -nk_rp_qsort(struct nk_rp_rect *array, unsigned int len, int(*cmp)(const void*,const void*)) -{ - /* iterative quick sort */ - #define NK_MAX_SORT_STACK 64 - unsigned right, left = 0, stack[NK_MAX_SORT_STACK], pos = 0; - unsigned seed = len/2 * 69069+1; - for (;;) { - for (; left+1 < len; len++) { - struct nk_rp_rect pivot, tmp; - if (pos == NK_MAX_SORT_STACK) len = stack[pos = 0]; - pivot = array[left+seed%(len-left)]; - seed = seed * 69069 + 1; - stack[pos++] = len; - for (right = left-1;;) { - while (cmp(&array[++right], &pivot) < 0); - while (cmp(&pivot, &array[--len]) < 0); - if (right >= len) break; - tmp = array[right]; - array[right] = array[len]; - array[len] = tmp; - } - } - if (pos == 0) break; - left = len; - len = stack[--pos]; - } - #undef NK_MAX_SORT_STACK -} -NK_INTERN void -nk_rp_pack_rects(struct nk_rp_context *context, struct nk_rp_rect *rects, int num_rects) -{ - int i; - /* we use the 'was_packed' field internally to allow sorting/unsorting */ - for (i=0; i < num_rects; ++i) { - rects[i].was_packed = i; - } - - /* sort according to heuristic */ - nk_rp_qsort(rects, (unsigned)num_rects, nk_rect_height_compare); - - for (i=0; i < num_rects; ++i) { - struct nk_rp__findresult fr = nk_rp__skyline_pack_rectangle(context, rects[i].w, rects[i].h); - if (fr.prev_link) { - rects[i].x = (nk_rp_coord) fr.x; - rects[i].y = (nk_rp_coord) fr.y; - } else { - rects[i].x = rects[i].y = NK_RP__MAXVAL; - } - } - - /* unsort */ - nk_rp_qsort(rects, (unsigned)num_rects, nk_rect_original_order); - - /* set was_packed flags */ - for (i=0; i < num_rects; ++i) - rects[i].was_packed = !(rects[i].x == NK_RP__MAXVAL && rects[i].y == NK_RP__MAXVAL); -} - -/* - * ============================================================== - * - * TRUETYPE - * - * =============================================================== - */ -/* stb_truetype.h - v1.07 - public domain */ -#define NK_TT_MAX_OVERSAMPLE 8 -#define NK_TT__OVER_MASK (NK_TT_MAX_OVERSAMPLE-1) - -struct nk_tt_bakedchar { - unsigned short x0,y0,x1,y1; - /* coordinates of bbox in bitmap */ - float xoff,yoff,xadvance; -}; - -struct nk_tt_aligned_quad{ - float x0,y0,s0,t0; /* top-left */ - float x1,y1,s1,t1; /* bottom-right */ -}; - -struct nk_tt_packedchar { - unsigned short x0,y0,x1,y1; - /* coordinates of bbox in bitmap */ - float xoff,yoff,xadvance; - float xoff2,yoff2; -}; - -struct nk_tt_pack_range { - float font_size; - int first_unicode_codepoint_in_range; - /* if non-zero, then the chars are continuous, and this is the first codepoint */ - int *array_of_unicode_codepoints; - /* if non-zero, then this is an array of unicode codepoints */ - int num_chars; - struct nk_tt_packedchar *chardata_for_range; /* output */ - unsigned char h_oversample, v_oversample; - /* don't set these, they're used internally */ -}; - -struct nk_tt_pack_context { - void *pack_info; - int width; - int height; - int stride_in_bytes; - int padding; - unsigned int h_oversample, v_oversample; - unsigned char *pixels; - void *nodes; -}; - -struct nk_tt_fontinfo { - const unsigned char* data; /* pointer to .ttf file */ - int fontstart;/* offset of start of font */ - int numGlyphs;/* number of glyphs, needed for range checking */ - int loca,head,glyf,hhea,hmtx,kern; /* table locations as offset from start of .ttf */ - int index_map; /* a cmap mapping for our chosen character encoding */ - int indexToLocFormat; /* format needed to map from glyph index to glyph */ -}; - -enum { - NK_TT_vmove=1, - NK_TT_vline, - NK_TT_vcurve -}; - -struct nk_tt_vertex { - short x,y,cx,cy; - unsigned char type,padding; -}; - -struct nk_tt__bitmap{ - int w,h,stride; - unsigned char *pixels; -}; - -struct nk_tt__hheap_chunk { - struct nk_tt__hheap_chunk *next; -}; -struct nk_tt__hheap { - struct nk_allocator alloc; - struct nk_tt__hheap_chunk *head; - void *first_free; - int num_remaining_in_head_chunk; -}; - -struct nk_tt__edge { - float x0,y0, x1,y1; - int invert; -}; - -struct nk_tt__active_edge { - struct nk_tt__active_edge *next; - float fx,fdx,fdy; - float direction; - float sy; - float ey; -}; -struct nk_tt__point {float x,y;}; - -#define NK_TT_MACSTYLE_DONTCARE 0 -#define NK_TT_MACSTYLE_BOLD 1 -#define NK_TT_MACSTYLE_ITALIC 2 -#define NK_TT_MACSTYLE_UNDERSCORE 4 -#define NK_TT_MACSTYLE_NONE 8 -/* <= not same as 0, this makes us check the bitfield is 0 */ - -enum { /* platformID */ - NK_TT_PLATFORM_ID_UNICODE =0, - NK_TT_PLATFORM_ID_MAC =1, - NK_TT_PLATFORM_ID_ISO =2, - NK_TT_PLATFORM_ID_MICROSOFT =3 -}; - -enum { /* encodingID for NK_TT_PLATFORM_ID_UNICODE */ - NK_TT_UNICODE_EID_UNICODE_1_0 =0, - NK_TT_UNICODE_EID_UNICODE_1_1 =1, - NK_TT_UNICODE_EID_ISO_10646 =2, - NK_TT_UNICODE_EID_UNICODE_2_0_BMP=3, - NK_TT_UNICODE_EID_UNICODE_2_0_FULL=4 -}; - -enum { /* encodingID for NK_TT_PLATFORM_ID_MICROSOFT */ - NK_TT_MS_EID_SYMBOL =0, - NK_TT_MS_EID_UNICODE_BMP =1, - NK_TT_MS_EID_SHIFTJIS =2, - NK_TT_MS_EID_UNICODE_FULL =10 -}; - -enum { /* encodingID for NK_TT_PLATFORM_ID_MAC; same as Script Manager codes */ - NK_TT_MAC_EID_ROMAN =0, NK_TT_MAC_EID_ARABIC =4, - NK_TT_MAC_EID_JAPANESE =1, NK_TT_MAC_EID_HEBREW =5, - NK_TT_MAC_EID_CHINESE_TRAD =2, NK_TT_MAC_EID_GREEK =6, - NK_TT_MAC_EID_KOREAN =3, NK_TT_MAC_EID_RUSSIAN =7 -}; - -enum { /* languageID for NK_TT_PLATFORM_ID_MICROSOFT; same as LCID... */ - /* problematic because there are e.g. 16 english LCIDs and 16 arabic LCIDs */ - NK_TT_MS_LANG_ENGLISH =0x0409, NK_TT_MS_LANG_ITALIAN =0x0410, - NK_TT_MS_LANG_CHINESE =0x0804, NK_TT_MS_LANG_JAPANESE =0x0411, - NK_TT_MS_LANG_DUTCH =0x0413, NK_TT_MS_LANG_KOREAN =0x0412, - NK_TT_MS_LANG_FRENCH =0x040c, NK_TT_MS_LANG_RUSSIAN =0x0419, - NK_TT_MS_LANG_GERMAN =0x0407, NK_TT_MS_LANG_SPANISH =0x0409, - NK_TT_MS_LANG_HEBREW =0x040d, NK_TT_MS_LANG_SWEDISH =0x041D -}; - -enum { /* languageID for NK_TT_PLATFORM_ID_MAC */ - NK_TT_MAC_LANG_ENGLISH =0 , NK_TT_MAC_LANG_JAPANESE =11, - NK_TT_MAC_LANG_ARABIC =12, NK_TT_MAC_LANG_KOREAN =23, - NK_TT_MAC_LANG_DUTCH =4 , NK_TT_MAC_LANG_RUSSIAN =32, - NK_TT_MAC_LANG_FRENCH =1 , NK_TT_MAC_LANG_SPANISH =6 , - NK_TT_MAC_LANG_GERMAN =2 , NK_TT_MAC_LANG_SWEDISH =5 , - NK_TT_MAC_LANG_HEBREW =10, NK_TT_MAC_LANG_CHINESE_SIMPLIFIED =33, - NK_TT_MAC_LANG_ITALIAN =3 , NK_TT_MAC_LANG_CHINESE_TRAD =19 -}; - -#define nk_ttBYTE(p) (* (const nk_byte *) (p)) -#define nk_ttCHAR(p) (* (const char *) (p)) - -#if defined(NK_BIGENDIAN) && !defined(NK_ALLOW_UNALIGNED_TRUETYPE) - #define nk_ttUSHORT(p) (* (nk_ushort *) (p)) - #define nk_ttSHORT(p) (* (nk_short *) (p)) - #define nk_ttULONG(p) (* (nk_uint *) (p)) - #define nk_ttLONG(p) (* (nk_int *) (p)) -#else - static nk_ushort nk_ttUSHORT(const nk_byte *p) { return (nk_ushort)(p[0]*256 + p[1]); } - static nk_short nk_ttSHORT(const nk_byte *p) { return (nk_short)(p[0]*256 + p[1]); } - static nk_uint nk_ttULONG(const nk_byte *p) { return (nk_uint)((p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]); } -#endif - -#define nk_tt_tag4(p,c0,c1,c2,c3)\ - ((p)[0] == (c0) && (p)[1] == (c1) && (p)[2] == (c2) && (p)[3] == (c3)) -#define nk_tt_tag(p,str) nk_tt_tag4(p,str[0],str[1],str[2],str[3]) - -NK_INTERN int nk_tt_GetGlyphShape(const struct nk_tt_fontinfo *info, struct nk_allocator *alloc, - int glyph_index, struct nk_tt_vertex **pvertices); - -NK_INTERN nk_uint -nk_tt__find_table(const nk_byte *data, nk_uint fontstart, const char *tag) -{ - /* @OPTIMIZE: binary search */ - nk_int num_tables = nk_ttUSHORT(data+fontstart+4); - nk_uint tabledir = fontstart + 12; - nk_int i; - for (i = 0; i < num_tables; ++i) { - nk_uint loc = tabledir + (nk_uint)(16*i); - if (nk_tt_tag(data+loc+0, tag)) - return nk_ttULONG(data+loc+8); - } - return 0; -} -NK_INTERN int -nk_tt_InitFont(struct nk_tt_fontinfo *info, const unsigned char *data2, int fontstart) -{ - nk_uint cmap, t; - nk_int i,numTables; - const nk_byte *data = (const nk_byte *) data2; - - info->data = data; - info->fontstart = fontstart; - - cmap = nk_tt__find_table(data, (nk_uint)fontstart, "cmap"); /* required */ - info->loca = (int)nk_tt__find_table(data, (nk_uint)fontstart, "loca"); /* required */ - info->head = (int)nk_tt__find_table(data, (nk_uint)fontstart, "head"); /* required */ - info->glyf = (int)nk_tt__find_table(data, (nk_uint)fontstart, "glyf"); /* required */ - info->hhea = (int)nk_tt__find_table(data, (nk_uint)fontstart, "hhea"); /* required */ - info->hmtx = (int)nk_tt__find_table(data, (nk_uint)fontstart, "hmtx"); /* required */ - info->kern = (int)nk_tt__find_table(data, (nk_uint)fontstart, "kern"); /* not required */ - if (!cmap || !info->loca || !info->head || !info->glyf || !info->hhea || !info->hmtx) - return 0; - - t = nk_tt__find_table(data, (nk_uint)fontstart, "maxp"); - if (t) info->numGlyphs = nk_ttUSHORT(data+t+4); - else info->numGlyphs = 0xffff; - - /* find a cmap encoding table we understand *now* to avoid searching */ - /* later. (todo: could make this installable) */ - /* the same regardless of glyph. */ - numTables = nk_ttUSHORT(data + cmap + 2); - info->index_map = 0; - for (i=0; i < numTables; ++i) - { - nk_uint encoding_record = cmap + 4 + 8 * (nk_uint)i; - /* find an encoding we understand: */ - switch(nk_ttUSHORT(data+encoding_record)) { - case NK_TT_PLATFORM_ID_MICROSOFT: - switch (nk_ttUSHORT(data+encoding_record+2)) { - case NK_TT_MS_EID_UNICODE_BMP: - case NK_TT_MS_EID_UNICODE_FULL: - /* MS/Unicode */ - info->index_map = (int)(cmap + nk_ttULONG(data+encoding_record+4)); - break; - default: break; - } break; - case NK_TT_PLATFORM_ID_UNICODE: - /* Mac/iOS has these */ - /* all the encodingIDs are unicode, so we don't bother to check it */ - info->index_map = (int)(cmap + nk_ttULONG(data+encoding_record+4)); - break; - default: break; - } - } - if (info->index_map == 0) - return 0; - info->indexToLocFormat = nk_ttUSHORT(data+info->head + 50); - return 1; -} -NK_INTERN int -nk_tt_FindGlyphIndex(const struct nk_tt_fontinfo *info, int unicode_codepoint) -{ - const nk_byte *data = info->data; - nk_uint index_map = (nk_uint)info->index_map; - - nk_ushort format = nk_ttUSHORT(data + index_map + 0); - if (format == 0) { /* apple byte encoding */ - nk_int bytes = nk_ttUSHORT(data + index_map + 2); - if (unicode_codepoint < bytes-6) - return nk_ttBYTE(data + index_map + 6 + unicode_codepoint); - return 0; - } else if (format == 6) { - nk_uint first = nk_ttUSHORT(data + index_map + 6); - nk_uint count = nk_ttUSHORT(data + index_map + 8); - if ((nk_uint) unicode_codepoint >= first && (nk_uint) unicode_codepoint < first+count) - return nk_ttUSHORT(data + index_map + 10 + (unicode_codepoint - (int)first)*2); - return 0; - } else if (format == 2) { - NK_ASSERT(0); /* @TODO: high-byte mapping for japanese/chinese/korean */ - return 0; - } else if (format == 4) { /* standard mapping for windows fonts: binary search collection of ranges */ - nk_ushort segcount = nk_ttUSHORT(data+index_map+6) >> 1; - nk_ushort searchRange = nk_ttUSHORT(data+index_map+8) >> 1; - nk_ushort entrySelector = nk_ttUSHORT(data+index_map+10); - nk_ushort rangeShift = nk_ttUSHORT(data+index_map+12) >> 1; - - /* do a binary search of the segments */ - nk_uint endCount = index_map + 14; - nk_uint search = endCount; - - if (unicode_codepoint > 0xffff) - return 0; - - /* they lie from endCount .. endCount + segCount */ - /* but searchRange is the nearest power of two, so... */ - if (unicode_codepoint >= nk_ttUSHORT(data + search + rangeShift*2)) - search += (nk_uint)(rangeShift*2); - - /* now decrement to bias correctly to find smallest */ - search -= 2; - while (entrySelector) { - nk_ushort end; - searchRange >>= 1; - end = nk_ttUSHORT(data + search + searchRange*2); - if (unicode_codepoint > end) - search += (nk_uint)(searchRange*2); - --entrySelector; - } - search += 2; - - { - nk_ushort offset, start; - nk_ushort item = (nk_ushort) ((search - endCount) >> 1); - - NK_ASSERT(unicode_codepoint <= nk_ttUSHORT(data + endCount + 2*item)); - start = nk_ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item); - if (unicode_codepoint < start) - return 0; - - offset = nk_ttUSHORT(data + index_map + 14 + segcount*6 + 2 + 2*item); - if (offset == 0) - return (nk_ushort) (unicode_codepoint + nk_ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item)); - - return nk_ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item); - } - } else if (format == 12 || format == 13) { - nk_uint ngroups = nk_ttULONG(data+index_map+12); - nk_int low,high; - low = 0; high = (nk_int)ngroups; - /* Binary search the right group. */ - while (low < high) { - nk_int mid = low + ((high-low) >> 1); /* rounds down, so low <= mid < high */ - nk_uint start_char = nk_ttULONG(data+index_map+16+mid*12); - nk_uint end_char = nk_ttULONG(data+index_map+16+mid*12+4); - if ((nk_uint) unicode_codepoint < start_char) - high = mid; - else if ((nk_uint) unicode_codepoint > end_char) - low = mid+1; - else { - nk_uint start_glyph = nk_ttULONG(data+index_map+16+mid*12+8); - if (format == 12) - return (int)start_glyph + (int)unicode_codepoint - (int)start_char; - else /* format == 13 */ - return (int)start_glyph; - } - } - return 0; /* not found */ - } - /* @TODO */ - NK_ASSERT(0); - return 0; -} -NK_INTERN void -nk_tt_setvertex(struct nk_tt_vertex *v, nk_byte type, nk_int x, nk_int y, nk_int cx, nk_int cy) -{ - v->type = type; - v->x = (nk_short) x; - v->y = (nk_short) y; - v->cx = (nk_short) cx; - v->cy = (nk_short) cy; -} -NK_INTERN int -nk_tt__GetGlyfOffset(const struct nk_tt_fontinfo *info, int glyph_index) -{ - int g1,g2; - if (glyph_index >= info->numGlyphs) return -1; /* glyph index out of range */ - if (info->indexToLocFormat >= 2) return -1; /* unknown index->glyph map format */ - - if (info->indexToLocFormat == 0) { - g1 = info->glyf + nk_ttUSHORT(info->data + info->loca + glyph_index * 2) * 2; - g2 = info->glyf + nk_ttUSHORT(info->data + info->loca + glyph_index * 2 + 2) * 2; - } else { - g1 = info->glyf + (int)nk_ttULONG (info->data + info->loca + glyph_index * 4); - g2 = info->glyf + (int)nk_ttULONG (info->data + info->loca + glyph_index * 4 + 4); - } - return g1==g2 ? -1 : g1; /* if length is 0, return -1 */ -} -NK_INTERN int -nk_tt_GetGlyphBox(const struct nk_tt_fontinfo *info, int glyph_index, - int *x0, int *y0, int *x1, int *y1) -{ - int g = nk_tt__GetGlyfOffset(info, glyph_index); - if (g < 0) return 0; - - if (x0) *x0 = nk_ttSHORT(info->data + g + 2); - if (y0) *y0 = nk_ttSHORT(info->data + g + 4); - if (x1) *x1 = nk_ttSHORT(info->data + g + 6); - if (y1) *y1 = nk_ttSHORT(info->data + g + 8); - return 1; -} -NK_INTERN int -nk_tt__close_shape(struct nk_tt_vertex *vertices, int num_vertices, int was_off, - int start_off, nk_int sx, nk_int sy, nk_int scx, nk_int scy, nk_int cx, nk_int cy) -{ - if (start_off) { - if (was_off) - nk_tt_setvertex(&vertices[num_vertices++], NK_TT_vcurve, (cx+scx)>>1, (cy+scy)>>1, cx,cy); - nk_tt_setvertex(&vertices[num_vertices++], NK_TT_vcurve, sx,sy,scx,scy); - } else { - if (was_off) - nk_tt_setvertex(&vertices[num_vertices++], NK_TT_vcurve,sx,sy,cx,cy); - else - nk_tt_setvertex(&vertices[num_vertices++], NK_TT_vline,sx,sy,0,0); - } - return num_vertices; -} -NK_INTERN int -nk_tt_GetGlyphShape(const struct nk_tt_fontinfo *info, struct nk_allocator *alloc, - int glyph_index, struct nk_tt_vertex **pvertices) -{ - nk_short numberOfContours; - const nk_byte *endPtsOfContours; - const nk_byte *data = info->data; - struct nk_tt_vertex *vertices=0; - int num_vertices=0; - int g = nk_tt__GetGlyfOffset(info, glyph_index); - *pvertices = 0; - - if (g < 0) return 0; - numberOfContours = nk_ttSHORT(data + g); - if (numberOfContours > 0) { - nk_byte flags=0,flagcount; - nk_int ins, i,j=0,m,n, next_move, was_off=0, off, start_off=0; - nk_int x,y,cx,cy,sx,sy, scx,scy; - const nk_byte *points; - endPtsOfContours = (data + g + 10); - ins = nk_ttUSHORT(data + g + 10 + numberOfContours * 2); - points = data + g + 10 + numberOfContours * 2 + 2 + ins; - - n = 1+nk_ttUSHORT(endPtsOfContours + numberOfContours*2-2); - m = n + 2*numberOfContours; /* a loose bound on how many vertices we might need */ - vertices = (struct nk_tt_vertex *)alloc->alloc(alloc->userdata, 0, (nk_size)m * sizeof(vertices[0])); - if (vertices == 0) - return 0; - - next_move = 0; - flagcount=0; - - /* in first pass, we load uninterpreted data into the allocated array */ - /* above, shifted to the end of the array so we won't overwrite it when */ - /* we create our final data starting from the front */ - off = m - n; /* starting offset for uninterpreted data, regardless of how m ends up being calculated */ - - /* first load flags */ - for (i=0; i < n; ++i) { - if (flagcount == 0) { - flags = *points++; - if (flags & 8) - flagcount = *points++; - } else --flagcount; - vertices[off+i].type = flags; - } - - /* now load x coordinates */ - x=0; - for (i=0; i < n; ++i) { - flags = vertices[off+i].type; - if (flags & 2) { - nk_short dx = *points++; - x += (flags & 16) ? dx : -dx; /* ??? */ - } else { - if (!(flags & 16)) { - x = x + (nk_short) (points[0]*256 + points[1]); - points += 2; - } - } - vertices[off+i].x = (nk_short) x; - } - - /* now load y coordinates */ - y=0; - for (i=0; i < n; ++i) { - flags = vertices[off+i].type; - if (flags & 4) { - nk_short dy = *points++; - y += (flags & 32) ? dy : -dy; /* ??? */ - } else { - if (!(flags & 32)) { - y = y + (nk_short) (points[0]*256 + points[1]); - points += 2; - } - } - vertices[off+i].y = (nk_short) y; - } - - /* now convert them to our format */ - num_vertices=0; - sx = sy = cx = cy = scx = scy = 0; - for (i=0; i < n; ++i) - { - flags = vertices[off+i].type; - x = (nk_short) vertices[off+i].x; - y = (nk_short) vertices[off+i].y; - - if (next_move == i) { - if (i != 0) - num_vertices = nk_tt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy); - - /* now start the new one */ - start_off = !(flags & 1); - if (start_off) { - /* if we start off with an off-curve point, then when we need to find a point on the curve */ - /* where we can start, and we need to save some state for when we wraparound. */ - scx = x; - scy = y; - if (!(vertices[off+i+1].type & 1)) { - /* next point is also a curve point, so interpolate an on-point curve */ - sx = (x + (nk_int) vertices[off+i+1].x) >> 1; - sy = (y + (nk_int) vertices[off+i+1].y) >> 1; - } else { - /* otherwise just use the next point as our start point */ - sx = (nk_int) vertices[off+i+1].x; - sy = (nk_int) vertices[off+i+1].y; - ++i; /* we're using point i+1 as the starting point, so skip it */ - } - } else { - sx = x; - sy = y; - } - nk_tt_setvertex(&vertices[num_vertices++], NK_TT_vmove,sx,sy,0,0); - was_off = 0; - next_move = 1 + nk_ttUSHORT(endPtsOfContours+j*2); - ++j; - } else { - if (!(flags & 1)) - { /* if it's a curve */ - if (was_off) /* two off-curve control points in a row means interpolate an on-curve midpoint */ - nk_tt_setvertex(&vertices[num_vertices++], NK_TT_vcurve, (cx+x)>>1, (cy+y)>>1, cx, cy); - cx = x; - cy = y; - was_off = 1; - } else { - if (was_off) - nk_tt_setvertex(&vertices[num_vertices++], NK_TT_vcurve, x,y, cx, cy); - else nk_tt_setvertex(&vertices[num_vertices++], NK_TT_vline, x,y,0,0); - was_off = 0; - } - } - } - num_vertices = nk_tt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy); - } else if (numberOfContours == -1) { - /* Compound shapes. */ - int more = 1; - const nk_byte *comp = data + g + 10; - num_vertices = 0; - vertices = 0; - - while (more) - { - nk_ushort flags, gidx; - int comp_num_verts = 0, i; - struct nk_tt_vertex *comp_verts = 0, *tmp = 0; - float mtx[6] = {1,0,0,1,0,0}, m, n; - - flags = (nk_ushort)nk_ttSHORT(comp); comp+=2; - gidx = (nk_ushort)nk_ttSHORT(comp); comp+=2; - - if (flags & 2) { /* XY values */ - if (flags & 1) { /* shorts */ - mtx[4] = nk_ttSHORT(comp); comp+=2; - mtx[5] = nk_ttSHORT(comp); comp+=2; - } else { - mtx[4] = nk_ttCHAR(comp); comp+=1; - mtx[5] = nk_ttCHAR(comp); comp+=1; - } - } else { - /* @TODO handle matching point */ - NK_ASSERT(0); - } - if (flags & (1<<3)) { /* WE_HAVE_A_SCALE */ - mtx[0] = mtx[3] = nk_ttSHORT(comp)/16384.0f; comp+=2; - mtx[1] = mtx[2] = 0; - } else if (flags & (1<<6)) { /* WE_HAVE_AN_X_AND_YSCALE */ - mtx[0] = nk_ttSHORT(comp)/16384.0f; comp+=2; - mtx[1] = mtx[2] = 0; - mtx[3] = nk_ttSHORT(comp)/16384.0f; comp+=2; - } else if (flags & (1<<7)) { /* WE_HAVE_A_TWO_BY_TWO */ - mtx[0] = nk_ttSHORT(comp)/16384.0f; comp+=2; - mtx[1] = nk_ttSHORT(comp)/16384.0f; comp+=2; - mtx[2] = nk_ttSHORT(comp)/16384.0f; comp+=2; - mtx[3] = nk_ttSHORT(comp)/16384.0f; comp+=2; - } - - /* Find transformation scales. */ - m = (float) NK_SQRT(mtx[0]*mtx[0] + mtx[1]*mtx[1]); - n = (float) NK_SQRT(mtx[2]*mtx[2] + mtx[3]*mtx[3]); - - /* Get indexed glyph. */ - comp_num_verts = nk_tt_GetGlyphShape(info, alloc, gidx, &comp_verts); - if (comp_num_verts > 0) - { - /* Transform vertices. */ - for (i = 0; i < comp_num_verts; ++i) { - struct nk_tt_vertex* v = &comp_verts[i]; - short x,y; - x=v->x; y=v->y; - v->x = (short)(m * (mtx[0]*x + mtx[2]*y + mtx[4])); - v->y = (short)(n * (mtx[1]*x + mtx[3]*y + mtx[5])); - x=v->cx; y=v->cy; - v->cx = (short)(m * (mtx[0]*x + mtx[2]*y + mtx[4])); - v->cy = (short)(n * (mtx[1]*x + mtx[3]*y + mtx[5])); - } - /* Append vertices. */ - tmp = (struct nk_tt_vertex*)alloc->alloc(alloc->userdata, 0, - (nk_size)(num_vertices+comp_num_verts)*sizeof(struct nk_tt_vertex)); - if (!tmp) { - if (vertices) alloc->free(alloc->userdata, vertices); - if (comp_verts) alloc->free(alloc->userdata, comp_verts); - return 0; - } - if (num_vertices > 0) NK_MEMCPY(tmp, vertices, (nk_size)num_vertices*sizeof(struct nk_tt_vertex)); - NK_MEMCPY(tmp+num_vertices, comp_verts, (nk_size)comp_num_verts*sizeof(struct nk_tt_vertex)); - if (vertices) alloc->free(alloc->userdata,vertices); - vertices = tmp; - alloc->free(alloc->userdata,comp_verts); - num_vertices += comp_num_verts; - } - /* More components ? */ - more = flags & (1<<5); - } - } else if (numberOfContours < 0) { - /* @TODO other compound variations? */ - NK_ASSERT(0); - } else { - /* numberOfCounters == 0, do nothing */ - } - *pvertices = vertices; - return num_vertices; -} -NK_INTERN void -nk_tt_GetGlyphHMetrics(const struct nk_tt_fontinfo *info, int glyph_index, - int *advanceWidth, int *leftSideBearing) -{ - nk_ushort numOfLongHorMetrics = nk_ttUSHORT(info->data+info->hhea + 34); - if (glyph_index < numOfLongHorMetrics) { - if (advanceWidth) - *advanceWidth = nk_ttSHORT(info->data + info->hmtx + 4*glyph_index); - if (leftSideBearing) - *leftSideBearing = nk_ttSHORT(info->data + info->hmtx + 4*glyph_index + 2); - } else { - if (advanceWidth) - *advanceWidth = nk_ttSHORT(info->data + info->hmtx + 4*(numOfLongHorMetrics-1)); - if (leftSideBearing) - *leftSideBearing = nk_ttSHORT(info->data + info->hmtx + 4*numOfLongHorMetrics + 2*(glyph_index - numOfLongHorMetrics)); - } -} -NK_INTERN void -nk_tt_GetFontVMetrics(const struct nk_tt_fontinfo *info, - int *ascent, int *descent, int *lineGap) -{ - if (ascent ) *ascent = nk_ttSHORT(info->data+info->hhea + 4); - if (descent) *descent = nk_ttSHORT(info->data+info->hhea + 6); - if (lineGap) *lineGap = nk_ttSHORT(info->data+info->hhea + 8); -} -NK_INTERN float -nk_tt_ScaleForPixelHeight(const struct nk_tt_fontinfo *info, float height) -{ - int fheight = nk_ttSHORT(info->data + info->hhea + 4) - nk_ttSHORT(info->data + info->hhea + 6); - return (float) height / (float)fheight; -} -NK_INTERN float -nk_tt_ScaleForMappingEmToPixels(const struct nk_tt_fontinfo *info, float pixels) -{ - int unitsPerEm = nk_ttUSHORT(info->data + info->head + 18); - return pixels / (float)unitsPerEm; -} - -/*------------------------------------------------------------- - * antialiasing software rasterizer - * --------------------------------------------------------------*/ -NK_INTERN void -nk_tt_GetGlyphBitmapBoxSubpixel(const struct nk_tt_fontinfo *font, - int glyph, float scale_x, float scale_y,float shift_x, float shift_y, - int *ix0, int *iy0, int *ix1, int *iy1) -{ - int x0,y0,x1,y1; - if (!nk_tt_GetGlyphBox(font, glyph, &x0,&y0,&x1,&y1)) { - /* e.g. space character */ - if (ix0) *ix0 = 0; - if (iy0) *iy0 = 0; - if (ix1) *ix1 = 0; - if (iy1) *iy1 = 0; - } else { - /* move to integral bboxes (treating pixels as little squares, what pixels get touched)? */ - if (ix0) *ix0 = nk_ifloorf((float)x0 * scale_x + shift_x); - if (iy0) *iy0 = nk_ifloorf((float)-y1 * scale_y + shift_y); - if (ix1) *ix1 = nk_iceilf ((float)x1 * scale_x + shift_x); - if (iy1) *iy1 = nk_iceilf ((float)-y0 * scale_y + shift_y); - } -} -NK_INTERN void -nk_tt_GetGlyphBitmapBox(const struct nk_tt_fontinfo *font, int glyph, - float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1) -{ - nk_tt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y,0.0f,0.0f, ix0, iy0, ix1, iy1); -} - -/*------------------------------------------------------------- - * Rasterizer - * --------------------------------------------------------------*/ -NK_INTERN void* -nk_tt__hheap_alloc(struct nk_tt__hheap *hh, nk_size size) -{ - if (hh->first_free) { - void *p = hh->first_free; - hh->first_free = * (void **) p; - return p; - } else { - if (hh->num_remaining_in_head_chunk == 0) { - int count = (size < 32 ? 2000 : size < 128 ? 800 : 100); - struct nk_tt__hheap_chunk *c = (struct nk_tt__hheap_chunk *) - hh->alloc.alloc(hh->alloc.userdata, 0, - sizeof(struct nk_tt__hheap_chunk) + size * (nk_size)count); - if (c == 0) return 0; - c->next = hh->head; - hh->head = c; - hh->num_remaining_in_head_chunk = count; - } - --hh->num_remaining_in_head_chunk; - return (char *) (hh->head) + size * (nk_size)hh->num_remaining_in_head_chunk; - } -} -NK_INTERN void -nk_tt__hheap_free(struct nk_tt__hheap *hh, void *p) -{ - *(void **) p = hh->first_free; - hh->first_free = p; -} -NK_INTERN void -nk_tt__hheap_cleanup(struct nk_tt__hheap *hh) -{ - struct nk_tt__hheap_chunk *c = hh->head; - while (c) { - struct nk_tt__hheap_chunk *n = c->next; - hh->alloc.free(hh->alloc.userdata, c); - c = n; - } -} -NK_INTERN struct nk_tt__active_edge* -nk_tt__new_active(struct nk_tt__hheap *hh, struct nk_tt__edge *e, - int off_x, float start_point) -{ - struct nk_tt__active_edge *z = (struct nk_tt__active_edge *) - nk_tt__hheap_alloc(hh, sizeof(*z)); - float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0); - /*STBTT_assert(e->y0 <= start_point); */ - if (!z) return z; - z->fdx = dxdy; - z->fdy = (dxdy != 0) ? (1/dxdy): 0; - z->fx = e->x0 + dxdy * (start_point - e->y0); - z->fx -= (float)off_x; - z->direction = e->invert ? 1.0f : -1.0f; - z->sy = e->y0; - z->ey = e->y1; - z->next = 0; - return z; -} -NK_INTERN void -nk_tt__handle_clipped_edge(float *scanline, int x, struct nk_tt__active_edge *e, - float x0, float y0, float x1, float y1) -{ - if (y0 == y1) return; - NK_ASSERT(y0 < y1); - NK_ASSERT(e->sy <= e->ey); - if (y0 > e->ey) return; - if (y1 < e->sy) return; - if (y0 < e->sy) { - x0 += (x1-x0) * (e->sy - y0) / (y1-y0); - y0 = e->sy; - } - if (y1 > e->ey) { - x1 += (x1-x0) * (e->ey - y1) / (y1-y0); - y1 = e->ey; - } - - if (x0 == x) NK_ASSERT(x1 <= x+1); - else if (x0 == x+1) NK_ASSERT(x1 >= x); - else if (x0 <= x) NK_ASSERT(x1 <= x); - else if (x0 >= x+1) NK_ASSERT(x1 >= x+1); - else NK_ASSERT(x1 >= x && x1 <= x+1); - - if (x0 <= x && x1 <= x) - scanline[x] += e->direction * (y1-y0); - else if (x0 >= x+1 && x1 >= x+1); - else { - NK_ASSERT(x0 >= x && x0 <= x+1 && x1 >= x && x1 <= x+1); - /* coverage = 1 - average x position */ - scanline[x] += (float)e->direction * (float)(y1-y0) * (1.0f-((x0-(float)x)+(x1-(float)x))/2.0f); - } -} -NK_INTERN void -nk_tt__fill_active_edges_new(float *scanline, float *scanline_fill, int len, - struct nk_tt__active_edge *e, float y_top) -{ - float y_bottom = y_top+1; - while (e) - { - /* brute force every pixel */ - /* compute intersection points with top & bottom */ - NK_ASSERT(e->ey >= y_top); - if (e->fdx == 0) { - float x0 = e->fx; - if (x0 < len) { - if (x0 >= 0) { - nk_tt__handle_clipped_edge(scanline,(int) x0,e, x0,y_top, x0,y_bottom); - nk_tt__handle_clipped_edge(scanline_fill-1,(int) x0+1,e, x0,y_top, x0,y_bottom); - } else { - nk_tt__handle_clipped_edge(scanline_fill-1,0,e, x0,y_top, x0,y_bottom); - } - } - } else { - float x0 = e->fx; - float dx = e->fdx; - float xb = x0 + dx; - float x_top, x_bottom; - float y0,y1; - float dy = e->fdy; - NK_ASSERT(e->sy <= y_bottom && e->ey >= y_top); - - /* compute endpoints of line segment clipped to this scanline (if the */ - /* line segment starts on this scanline. x0 is the intersection of the */ - /* line with y_top, but that may be off the line segment. */ - if (e->sy > y_top) { - x_top = x0 + dx * (e->sy - y_top); - y0 = e->sy; - } else { - x_top = x0; - y0 = y_top; - } - - if (e->ey < y_bottom) { - x_bottom = x0 + dx * (e->ey - y_top); - y1 = e->ey; - } else { - x_bottom = xb; - y1 = y_bottom; - } - - if (x_top >= 0 && x_bottom >= 0 && x_top < len && x_bottom < len) - { - /* from here on, we don't have to range check x values */ - if ((int) x_top == (int) x_bottom) { - float height; - /* simple case, only spans one pixel */ - int x = (int) x_top; - height = y1 - y0; - NK_ASSERT(x >= 0 && x < len); - scanline[x] += e->direction * (1.0f-(((float)x_top - (float)x) + ((float)x_bottom-(float)x))/2.0f) * (float)height; - scanline_fill[x] += e->direction * (float)height; /* everything right of this pixel is filled */ - } else { - int x,x1,x2; - float y_crossing, step, sign, area; - /* covers 2+ pixels */ - if (x_top > x_bottom) - { - /* flip scanline vertically; signed area is the same */ - float t; - y0 = y_bottom - (y0 - y_top); - y1 = y_bottom - (y1 - y_top); - t = y0; y0 = y1; y1 = t; - t = x_bottom; x_bottom = x_top; x_top = t; - dx = -dx; - dy = -dy; - t = x0; x0 = xb; xb = t; - } - - x1 = (int) x_top; - x2 = (int) x_bottom; - /* compute intersection with y axis at x1+1 */ - y_crossing = ((float)x1+1 - (float)x0) * (float)dy + (float)y_top; - - sign = e->direction; - /* area of the rectangle covered from y0..y_crossing */ - area = sign * (y_crossing-y0); - /* area of the triangle (x_top,y0), (x+1,y0), (x+1,y_crossing) */ - scanline[x1] += area * (1.0f-((float)((float)x_top - (float)x1)+(float)(x1+1-x1))/2.0f); - - step = sign * dy; - for (x = x1+1; x < x2; ++x) { - scanline[x] += area + step/2; - area += step; - } - y_crossing += (float)dy * (float)(x2 - (x1+1)); - - scanline[x2] += area + sign * (1.0f-((float)(x2-x2)+((float)x_bottom-(float)x2))/2.0f) * (y1-y_crossing); - scanline_fill[x2] += sign * (y1-y0); - } - } - else - { - /* if edge goes outside of box we're drawing, we require */ - /* clipping logic. since this does not match the intended use */ - /* of this library, we use a different, very slow brute */ - /* force implementation */ - int x; - for (x=0; x < len; ++x) - { - /* cases: */ - /* */ - /* there can be up to two intersections with the pixel. any intersection */ - /* with left or right edges can be handled by splitting into two (or three) */ - /* regions. intersections with top & bottom do not necessitate case-wise logic. */ - /* */ - /* the old way of doing this found the intersections with the left & right edges, */ - /* then used some simple logic to produce up to three segments in sorted order */ - /* from top-to-bottom. however, this had a problem: if an x edge was epsilon */ - /* across the x border, then the corresponding y position might not be distinct */ - /* from the other y segment, and it might ignored as an empty segment. to avoid */ - /* that, we need to explicitly produce segments based on x positions. */ - - /* rename variables to clear pairs */ - float ya = y_top; - float x1 = (float) (x); - float x2 = (float) (x+1); - float x3 = xb; - float y3 = y_bottom; - float yb,y2; - - yb = ((float)x - x0) / dx + y_top; - y2 = ((float)x+1 - x0) / dx + y_top; - - if (x0 < x1 && x3 > x2) { /* three segments descending down-right */ - nk_tt__handle_clipped_edge(scanline,x,e, x0,ya, x1,yb); - nk_tt__handle_clipped_edge(scanline,x,e, x1,yb, x2,y2); - nk_tt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); - } else if (x3 < x1 && x0 > x2) { /* three segments descending down-left */ - nk_tt__handle_clipped_edge(scanline,x,e, x0,ya, x2,y2); - nk_tt__handle_clipped_edge(scanline,x,e, x2,y2, x1,yb); - nk_tt__handle_clipped_edge(scanline,x,e, x1,yb, x3,y3); - } else if (x0 < x1 && x3 > x1) { /* two segments across x, down-right */ - nk_tt__handle_clipped_edge(scanline,x,e, x0,ya, x1,yb); - nk_tt__handle_clipped_edge(scanline,x,e, x1,yb, x3,y3); - } else if (x3 < x1 && x0 > x1) { /* two segments across x, down-left */ - nk_tt__handle_clipped_edge(scanline,x,e, x0,ya, x1,yb); - nk_tt__handle_clipped_edge(scanline,x,e, x1,yb, x3,y3); - } else if (x0 < x2 && x3 > x2) { /* two segments across x+1, down-right */ - nk_tt__handle_clipped_edge(scanline,x,e, x0,ya, x2,y2); - nk_tt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); - } else if (x3 < x2 && x0 > x2) { /* two segments across x+1, down-left */ - nk_tt__handle_clipped_edge(scanline,x,e, x0,ya, x2,y2); - nk_tt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); - } else { /* one segment */ - nk_tt__handle_clipped_edge(scanline,x,e, x0,ya, x3,y3); - } - } - } - } - e = e->next; - } -} -NK_INTERN void -nk_tt__rasterize_sorted_edges(struct nk_tt__bitmap *result, struct nk_tt__edge *e, - int n, int vsubsample, int off_x, int off_y, struct nk_allocator *alloc) -{ - /* directly AA rasterize edges w/o supersampling */ - struct nk_tt__hheap hh; - struct nk_tt__active_edge *active = 0; - int y,j=0, i; - float scanline_data[129], *scanline, *scanline2; - - NK_UNUSED(vsubsample); - nk_zero_struct(hh); - hh.alloc = *alloc; - - if (result->w > 64) - scanline = (float *) alloc->alloc(alloc->userdata,0, (nk_size)(result->w*2+1) * sizeof(float)); - else scanline = scanline_data; - - scanline2 = scanline + result->w; - y = off_y; - e[n].y0 = (float) (off_y + result->h) + 1; - - while (j < result->h) - { - /* find center of pixel for this scanline */ - float scan_y_top = (float)y + 0.0f; - float scan_y_bottom = (float)y + 1.0f; - struct nk_tt__active_edge **step = &active; - - NK_MEMSET(scanline , 0, (nk_size)result->w*sizeof(scanline[0])); - NK_MEMSET(scanline2, 0, (nk_size)(result->w+1)*sizeof(scanline[0])); - - /* update all active edges; */ - /* remove all active edges that terminate before the top of this scanline */ - while (*step) { - struct nk_tt__active_edge * z = *step; - if (z->ey <= scan_y_top) { - *step = z->next; /* delete from list */ - NK_ASSERT(z->direction); - z->direction = 0; - nk_tt__hheap_free(&hh, z); - } else { - step = &((*step)->next); /* advance through list */ - } - } - - /* insert all edges that start before the bottom of this scanline */ - while (e->y0 <= scan_y_bottom) { - if (e->y0 != e->y1) { - struct nk_tt__active_edge *z = nk_tt__new_active(&hh, e, off_x, scan_y_top); - if (z != 0) { - NK_ASSERT(z->ey >= scan_y_top); - /* insert at front */ - z->next = active; - active = z; - } - } - ++e; - } - - /* now process all active edges */ - if (active) - nk_tt__fill_active_edges_new(scanline, scanline2+1, result->w, active, scan_y_top); - - { - float sum = 0; - for (i=0; i < result->w; ++i) { - float k; - int m; - sum += scanline2[i]; - k = scanline[i] + sum; - k = (float) NK_ABS(k) * 255.0f + 0.5f; - m = (int) k; - if (m > 255) m = 255; - result->pixels[j*result->stride + i] = (unsigned char) m; - } - } - /* advance all the edges */ - step = &active; - while (*step) { - struct nk_tt__active_edge *z = *step; - z->fx += z->fdx; /* advance to position for current scanline */ - step = &((*step)->next); /* advance through list */ - } - ++y; - ++j; - } - nk_tt__hheap_cleanup(&hh); - if (scanline != scanline_data) - alloc->free(alloc->userdata, scanline); -} -NK_INTERN void -nk_tt__sort_edges_ins_sort(struct nk_tt__edge *p, int n) -{ - int i,j; - #define NK_TT__COMPARE(a,b) ((a)->y0 < (b)->y0) - for (i=1; i < n; ++i) { - struct nk_tt__edge t = p[i], *a = &t; - j = i; - while (j > 0) { - struct nk_tt__edge *b = &p[j-1]; - int c = NK_TT__COMPARE(a,b); - if (!c) break; - p[j] = p[j-1]; - --j; - } - if (i != j) - p[j] = t; - } -} -NK_INTERN void -nk_tt__sort_edges_quicksort(struct nk_tt__edge *p, int n) -{ - /* threshold for transitioning to insertion sort */ - while (n > 12) { - struct nk_tt__edge t; - int c01,c12,c,m,i,j; - - /* compute median of three */ - m = n >> 1; - c01 = NK_TT__COMPARE(&p[0],&p[m]); - c12 = NK_TT__COMPARE(&p[m],&p[n-1]); - - /* if 0 >= mid >= end, or 0 < mid < end, then use mid */ - if (c01 != c12) { - /* otherwise, we'll need to swap something else to middle */ - int z; - c = NK_TT__COMPARE(&p[0],&p[n-1]); - /* 0>mid && midn => n; 0 0 */ - /* 0n: 0>n => 0; 0 n */ - z = (c == c12) ? 0 : n-1; - t = p[z]; - p[z] = p[m]; - p[m] = t; - } - - /* now p[m] is the median-of-three */ - /* swap it to the beginning so it won't move around */ - t = p[0]; - p[0] = p[m]; - p[m] = t; - - /* partition loop */ - i=1; - j=n-1; - for(;;) { - /* handling of equality is crucial here */ - /* for sentinels & efficiency with duplicates */ - for (;;++i) { - if (!NK_TT__COMPARE(&p[i], &p[0])) break; - } - for (;;--j) { - if (!NK_TT__COMPARE(&p[0], &p[j])) break; - } - - /* make sure we haven't crossed */ - if (i >= j) break; - t = p[i]; - p[i] = p[j]; - p[j] = t; - - ++i; - --j; - - } - - /* recurse on smaller side, iterate on larger */ - if (j < (n-i)) { - nk_tt__sort_edges_quicksort(p,j); - p = p+i; - n = n-i; - } else { - nk_tt__sort_edges_quicksort(p+i, n-i); - n = j; - } - } -} -NK_INTERN void -nk_tt__sort_edges(struct nk_tt__edge *p, int n) -{ - nk_tt__sort_edges_quicksort(p, n); - nk_tt__sort_edges_ins_sort(p, n); -} -NK_INTERN void -nk_tt__rasterize(struct nk_tt__bitmap *result, struct nk_tt__point *pts, - int *wcount, int windings, float scale_x, float scale_y, - float shift_x, float shift_y, int off_x, int off_y, int invert, - struct nk_allocator *alloc) -{ - float y_scale_inv = invert ? -scale_y : scale_y; - struct nk_tt__edge *e; - int n,i,j,k,m; - int vsubsample = 1; - /* vsubsample should divide 255 evenly; otherwise we won't reach full opacity */ - - /* now we have to blow out the windings into explicit edge lists */ - n = 0; - for (i=0; i < windings; ++i) - n += wcount[i]; - - e = (struct nk_tt__edge*) - alloc->alloc(alloc->userdata, 0,(sizeof(*e) * (nk_size)(n+1))); - if (e == 0) return; - n = 0; - - m=0; - for (i=0; i < windings; ++i) - { - struct nk_tt__point *p = pts + m; - m += wcount[i]; - j = wcount[i]-1; - for (k=0; k < wcount[i]; j=k++) { - int a=k,b=j; - /* skip the edge if horizontal */ - if (p[j].y == p[k].y) - continue; - - /* add edge from j to k to the list */ - e[n].invert = 0; - if (invert ? p[j].y > p[k].y : p[j].y < p[k].y) { - e[n].invert = 1; - a=j,b=k; - } - e[n].x0 = p[a].x * scale_x + shift_x; - e[n].y0 = (p[a].y * y_scale_inv + shift_y) * (float)vsubsample; - e[n].x1 = p[b].x * scale_x + shift_x; - e[n].y1 = (p[b].y * y_scale_inv + shift_y) * (float)vsubsample; - ++n; - } - } - - /* now sort the edges by their highest point (should snap to integer, and then by x) */ - /*STBTT_sort(e, n, sizeof(e[0]), nk_tt__edge_compare); */ - nk_tt__sort_edges(e, n); - /* now, traverse the scanlines and find the intersections on each scanline, use xor winding rule */ - nk_tt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y, alloc); - alloc->free(alloc->userdata, e); -} -NK_INTERN void -nk_tt__add_point(struct nk_tt__point *points, int n, float x, float y) -{ - if (!points) return; /* during first pass, it's unallocated */ - points[n].x = x; - points[n].y = y; -} -NK_INTERN int -nk_tt__tesselate_curve(struct nk_tt__point *points, int *num_points, - float x0, float y0, float x1, float y1, float x2, float y2, - float objspace_flatness_squared, int n) -{ - /* tesselate until threshold p is happy... - * @TODO warped to compensate for non-linear stretching */ - /* midpoint */ - float mx = (x0 + 2*x1 + x2)/4; - float my = (y0 + 2*y1 + y2)/4; - /* versus directly drawn line */ - float dx = (x0+x2)/2 - mx; - float dy = (y0+y2)/2 - my; - if (n > 16) /* 65536 segments on one curve better be enough! */ - return 1; - - /* half-pixel error allowed... need to be smaller if AA */ - if (dx*dx+dy*dy > objspace_flatness_squared) { - nk_tt__tesselate_curve(points, num_points, x0,y0, - (x0+x1)/2.0f,(y0+y1)/2.0f, mx,my, objspace_flatness_squared,n+1); - nk_tt__tesselate_curve(points, num_points, mx,my, - (x1+x2)/2.0f,(y1+y2)/2.0f, x2,y2, objspace_flatness_squared,n+1); - } else { - nk_tt__add_point(points, *num_points,x2,y2); - *num_points = *num_points+1; - } - return 1; -} -NK_INTERN struct nk_tt__point* -nk_tt_FlattenCurves(struct nk_tt_vertex *vertices, int num_verts, - float objspace_flatness, int **contour_lengths, int *num_contours, - struct nk_allocator *alloc) -{ - /* returns number of contours */ - struct nk_tt__point *points=0; - int num_points=0; - float objspace_flatness_squared = objspace_flatness * objspace_flatness; - int i; - int n=0; - int start=0; - int pass; - - /* count how many "moves" there are to get the contour count */ - for (i=0; i < num_verts; ++i) - if (vertices[i].type == NK_TT_vmove) ++n; - - *num_contours = n; - if (n == 0) return 0; - - *contour_lengths = (int *) - alloc->alloc(alloc->userdata,0, (sizeof(**contour_lengths) * (nk_size)n)); - if (*contour_lengths == 0) { - *num_contours = 0; - return 0; - } - - /* make two passes through the points so we don't need to realloc */ - for (pass=0; pass < 2; ++pass) - { - float x=0,y=0; - if (pass == 1) { - points = (struct nk_tt__point *) - alloc->alloc(alloc->userdata,0, (nk_size)num_points * sizeof(points[0])); - if (points == 0) goto error; - } - num_points = 0; - n= -1; - - for (i=0; i < num_verts; ++i) - { - switch (vertices[i].type) { - case NK_TT_vmove: - /* start the next contour */ - if (n >= 0) - (*contour_lengths)[n] = num_points - start; - ++n; - start = num_points; - - x = vertices[i].x, y = vertices[i].y; - nk_tt__add_point(points, num_points++, x,y); - break; - case NK_TT_vline: - x = vertices[i].x, y = vertices[i].y; - nk_tt__add_point(points, num_points++, x, y); - break; - case NK_TT_vcurve: - nk_tt__tesselate_curve(points, &num_points, x,y, - vertices[i].cx, vertices[i].cy, - vertices[i].x, vertices[i].y, - objspace_flatness_squared, 0); - x = vertices[i].x, y = vertices[i].y; - break; - default: break; - } - } - (*contour_lengths)[n] = num_points - start; - } - return points; - -error: - alloc->free(alloc->userdata, points); - alloc->free(alloc->userdata, *contour_lengths); - *contour_lengths = 0; - *num_contours = 0; - return 0; -} -NK_INTERN void -nk_tt_Rasterize(struct nk_tt__bitmap *result, float flatness_in_pixels, - struct nk_tt_vertex *vertices, int num_verts, - float scale_x, float scale_y, float shift_x, float shift_y, - int x_off, int y_off, int invert, struct nk_allocator *alloc) -{ - float scale = scale_x > scale_y ? scale_y : scale_x; - int winding_count, *winding_lengths; - struct nk_tt__point *windings = nk_tt_FlattenCurves(vertices, num_verts, - flatness_in_pixels / scale, &winding_lengths, &winding_count, alloc); - - NK_ASSERT(alloc); - if (windings) { - nk_tt__rasterize(result, windings, winding_lengths, winding_count, - scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert, alloc); - alloc->free(alloc->userdata, winding_lengths); - alloc->free(alloc->userdata, windings); - } -} -NK_INTERN void -nk_tt_MakeGlyphBitmapSubpixel(const struct nk_tt_fontinfo *info, unsigned char *output, - int out_w, int out_h, int out_stride, float scale_x, float scale_y, - float shift_x, float shift_y, int glyph, struct nk_allocator *alloc) -{ - int ix0,iy0; - struct nk_tt_vertex *vertices; - int num_verts = nk_tt_GetGlyphShape(info, alloc, glyph, &vertices); - struct nk_tt__bitmap gbm; - - nk_tt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, - shift_y, &ix0,&iy0,0,0); - gbm.pixels = output; - gbm.w = out_w; - gbm.h = out_h; - gbm.stride = out_stride; - - if (gbm.w && gbm.h) - nk_tt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, - shift_x, shift_y, ix0,iy0, 1, alloc); - alloc->free(alloc->userdata, vertices); -} - -/*------------------------------------------------------------- - * Bitmap baking - * --------------------------------------------------------------*/ -NK_INTERN int -nk_tt_PackBegin(struct nk_tt_pack_context *spc, unsigned char *pixels, - int pw, int ph, int stride_in_bytes, int padding, struct nk_allocator *alloc) -{ - int num_nodes = pw - padding; - struct nk_rp_context *context = (struct nk_rp_context *) - alloc->alloc(alloc->userdata,0, sizeof(*context)); - struct nk_rp_node *nodes = (struct nk_rp_node*) - alloc->alloc(alloc->userdata,0, (sizeof(*nodes ) * (nk_size)num_nodes)); - - if (context == 0 || nodes == 0) { - if (context != 0) alloc->free(alloc->userdata, context); - if (nodes != 0) alloc->free(alloc->userdata, nodes); - return 0; - } - - spc->width = pw; - spc->height = ph; - spc->pixels = pixels; - spc->pack_info = context; - spc->nodes = nodes; - spc->padding = padding; - spc->stride_in_bytes = (stride_in_bytes != 0) ? stride_in_bytes : pw; - spc->h_oversample = 1; - spc->v_oversample = 1; - - nk_rp_init_target(context, pw-padding, ph-padding, nodes, num_nodes); - if (pixels) - NK_MEMSET(pixels, 0, (nk_size)(pw*ph)); /* background of 0 around pixels */ - return 1; -} -NK_INTERN void -nk_tt_PackEnd(struct nk_tt_pack_context *spc, struct nk_allocator *alloc) -{ - alloc->free(alloc->userdata, spc->nodes); - alloc->free(alloc->userdata, spc->pack_info); -} -NK_INTERN void -nk_tt_PackSetOversampling(struct nk_tt_pack_context *spc, - unsigned int h_oversample, unsigned int v_oversample) -{ - NK_ASSERT(h_oversample <= NK_TT_MAX_OVERSAMPLE); - NK_ASSERT(v_oversample <= NK_TT_MAX_OVERSAMPLE); - if (h_oversample <= NK_TT_MAX_OVERSAMPLE) - spc->h_oversample = h_oversample; - if (v_oversample <= NK_TT_MAX_OVERSAMPLE) - spc->v_oversample = v_oversample; -} -NK_INTERN void -nk_tt__h_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, - int kernel_width) -{ - unsigned char buffer[NK_TT_MAX_OVERSAMPLE]; - int safe_w = w - kernel_width; - int j; - - for (j=0; j < h; ++j) - { - int i; - unsigned int total; - NK_MEMSET(buffer, 0, (nk_size)kernel_width); - - total = 0; - - /* make kernel_width a constant in common cases so compiler can optimize out the divide */ - switch (kernel_width) { - case 2: - for (i=0; i <= safe_w; ++i) { - total += (unsigned int)(pixels[i] - buffer[i & NK_TT__OVER_MASK]); - buffer[(i+kernel_width) & NK_TT__OVER_MASK] = pixels[i]; - pixels[i] = (unsigned char) (total / 2); - } - break; - case 3: - for (i=0; i <= safe_w; ++i) { - total += (unsigned int)(pixels[i] - buffer[i & NK_TT__OVER_MASK]); - buffer[(i+kernel_width) & NK_TT__OVER_MASK] = pixels[i]; - pixels[i] = (unsigned char) (total / 3); - } - break; - case 4: - for (i=0; i <= safe_w; ++i) { - total += (unsigned int)pixels[i] - buffer[i & NK_TT__OVER_MASK]; - buffer[(i+kernel_width) & NK_TT__OVER_MASK] = pixels[i]; - pixels[i] = (unsigned char) (total / 4); - } - break; - case 5: - for (i=0; i <= safe_w; ++i) { - total += (unsigned int)(pixels[i] - buffer[i & NK_TT__OVER_MASK]); - buffer[(i+kernel_width) & NK_TT__OVER_MASK] = pixels[i]; - pixels[i] = (unsigned char) (total / 5); - } - break; - default: - for (i=0; i <= safe_w; ++i) { - total += (unsigned int)(pixels[i] - buffer[i & NK_TT__OVER_MASK]); - buffer[(i+kernel_width) & NK_TT__OVER_MASK] = pixels[i]; - pixels[i] = (unsigned char) (total / (unsigned int)kernel_width); - } - break; - } - - for (; i < w; ++i) { - NK_ASSERT(pixels[i] == 0); - total -= (unsigned int)(buffer[i & NK_TT__OVER_MASK]); - pixels[i] = (unsigned char) (total / (unsigned int)kernel_width); - } - pixels += stride_in_bytes; - } -} -NK_INTERN void -nk_tt__v_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, - int kernel_width) -{ - unsigned char buffer[NK_TT_MAX_OVERSAMPLE]; - int safe_h = h - kernel_width; - int j; - - for (j=0; j < w; ++j) - { - int i; - unsigned int total; - NK_MEMSET(buffer, 0, (nk_size)kernel_width); - - total = 0; - - /* make kernel_width a constant in common cases so compiler can optimize out the divide */ - switch (kernel_width) { - case 2: - for (i=0; i <= safe_h; ++i) { - total += (unsigned int)(pixels[i*stride_in_bytes] - buffer[i & NK_TT__OVER_MASK]); - buffer[(i+kernel_width) & NK_TT__OVER_MASK] = pixels[i*stride_in_bytes]; - pixels[i*stride_in_bytes] = (unsigned char) (total / 2); - } - break; - case 3: - for (i=0; i <= safe_h; ++i) { - total += (unsigned int)(pixels[i*stride_in_bytes] - buffer[i & NK_TT__OVER_MASK]); - buffer[(i+kernel_width) & NK_TT__OVER_MASK] = pixels[i*stride_in_bytes]; - pixels[i*stride_in_bytes] = (unsigned char) (total / 3); - } - break; - case 4: - for (i=0; i <= safe_h; ++i) { - total += (unsigned int)(pixels[i*stride_in_bytes] - buffer[i & NK_TT__OVER_MASK]); - buffer[(i+kernel_width) & NK_TT__OVER_MASK] = pixels[i*stride_in_bytes]; - pixels[i*stride_in_bytes] = (unsigned char) (total / 4); - } - break; - case 5: - for (i=0; i <= safe_h; ++i) { - total += (unsigned int)(pixels[i*stride_in_bytes] - buffer[i & NK_TT__OVER_MASK]); - buffer[(i+kernel_width) & NK_TT__OVER_MASK] = pixels[i*stride_in_bytes]; - pixels[i*stride_in_bytes] = (unsigned char) (total / 5); - } - break; - default: - for (i=0; i <= safe_h; ++i) { - total += (unsigned int)(pixels[i*stride_in_bytes] - buffer[i & NK_TT__OVER_MASK]); - buffer[(i+kernel_width) & NK_TT__OVER_MASK] = pixels[i*stride_in_bytes]; - pixels[i*stride_in_bytes] = (unsigned char) (total / (unsigned int)kernel_width); - } - break; - } - - for (; i < h; ++i) { - NK_ASSERT(pixels[i*stride_in_bytes] == 0); - total -= (unsigned int)(buffer[i & NK_TT__OVER_MASK]); - pixels[i*stride_in_bytes] = (unsigned char) (total / (unsigned int)kernel_width); - } - pixels += 1; - } -} -NK_INTERN float -nk_tt__oversample_shift(int oversample) -{ - if (!oversample) - return 0.0f; - - /* The prefilter is a box filter of width "oversample", */ - /* which shifts phase by (oversample - 1)/2 pixels in */ - /* oversampled space. We want to shift in the opposite */ - /* direction to counter this. */ - return (float)-(oversample - 1) / (2.0f * (float)oversample); -} -NK_INTERN int -nk_tt_PackFontRangesGatherRects(struct nk_tt_pack_context *spc, - struct nk_tt_fontinfo *info, struct nk_tt_pack_range *ranges, - int num_ranges, struct nk_rp_rect *rects) -{ - /* rects array must be big enough to accommodate all characters in the given ranges */ - int i,j,k; - k = 0; - - for (i=0; i < num_ranges; ++i) { - float fh = ranges[i].font_size; - float scale = (fh > 0) ? nk_tt_ScaleForPixelHeight(info, fh): - nk_tt_ScaleForMappingEmToPixels(info, -fh); - ranges[i].h_oversample = (unsigned char) spc->h_oversample; - ranges[i].v_oversample = (unsigned char) spc->v_oversample; - for (j=0; j < ranges[i].num_chars; ++j) { - int x0,y0,x1,y1; - int codepoint = ranges[i].first_unicode_codepoint_in_range ? - ranges[i].first_unicode_codepoint_in_range + j : - ranges[i].array_of_unicode_codepoints[j]; - - int glyph = nk_tt_FindGlyphIndex(info, codepoint); - nk_tt_GetGlyphBitmapBoxSubpixel(info,glyph, scale * (float)spc->h_oversample, - scale * (float)spc->v_oversample, 0,0, &x0,&y0,&x1,&y1); - rects[k].w = (nk_rp_coord) (x1-x0 + spc->padding + (int)spc->h_oversample-1); - rects[k].h = (nk_rp_coord) (y1-y0 + spc->padding + (int)spc->v_oversample-1); - ++k; - } - } - return k; -} -NK_INTERN int -nk_tt_PackFontRangesRenderIntoRects(struct nk_tt_pack_context *spc, - struct nk_tt_fontinfo *info, struct nk_tt_pack_range *ranges, - int num_ranges, struct nk_rp_rect *rects, struct nk_allocator *alloc) -{ - int i,j,k, return_value = 1; - /* save current values */ - int old_h_over = (int)spc->h_oversample; - int old_v_over = (int)spc->v_oversample; - /* rects array must be big enough to accommodate all characters in the given ranges */ - - k = 0; - for (i=0; i < num_ranges; ++i) - { - float fh = ranges[i].font_size; - float recip_h,recip_v,sub_x,sub_y; - float scale = fh > 0 ? nk_tt_ScaleForPixelHeight(info, fh): - nk_tt_ScaleForMappingEmToPixels(info, -fh); - - spc->h_oversample = ranges[i].h_oversample; - spc->v_oversample = ranges[i].v_oversample; - - recip_h = 1.0f / (float)spc->h_oversample; - recip_v = 1.0f / (float)spc->v_oversample; - - sub_x = nk_tt__oversample_shift((int)spc->h_oversample); - sub_y = nk_tt__oversample_shift((int)spc->v_oversample); - - for (j=0; j < ranges[i].num_chars; ++j) - { - struct nk_rp_rect *r = &rects[k]; - if (r->was_packed) - { - struct nk_tt_packedchar *bc = &ranges[i].chardata_for_range[j]; - int advance, lsb, x0,y0,x1,y1; - int codepoint = ranges[i].first_unicode_codepoint_in_range ? - ranges[i].first_unicode_codepoint_in_range + j : - ranges[i].array_of_unicode_codepoints[j]; - int glyph = nk_tt_FindGlyphIndex(info, codepoint); - nk_rp_coord pad = (nk_rp_coord) spc->padding; - - /* pad on left and top */ - r->x = (nk_rp_coord)((int)r->x + (int)pad); - r->y = (nk_rp_coord)((int)r->y + (int)pad); - r->w = (nk_rp_coord)((int)r->w - (int)pad); - r->h = (nk_rp_coord)((int)r->h - (int)pad); - - nk_tt_GetGlyphHMetrics(info, glyph, &advance, &lsb); - nk_tt_GetGlyphBitmapBox(info, glyph, scale * (float)spc->h_oversample, - (scale * (float)spc->v_oversample), &x0,&y0,&x1,&y1); - nk_tt_MakeGlyphBitmapSubpixel(info, spc->pixels + r->x + r->y*spc->stride_in_bytes, - (int)(r->w - spc->h_oversample+1), (int)(r->h - spc->v_oversample+1), - spc->stride_in_bytes, scale * (float)spc->h_oversample, - scale * (float)spc->v_oversample, 0,0, glyph, alloc); - - if (spc->h_oversample > 1) - nk_tt__h_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes, - r->w, r->h, spc->stride_in_bytes, (int)spc->h_oversample); - - if (spc->v_oversample > 1) - nk_tt__v_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes, - r->w, r->h, spc->stride_in_bytes, (int)spc->v_oversample); - - bc->x0 = (nk_ushort) r->x; - bc->y0 = (nk_ushort) r->y; - bc->x1 = (nk_ushort) (r->x + r->w); - bc->y1 = (nk_ushort) (r->y + r->h); - bc->xadvance = scale * (float)advance; - bc->xoff = (float) x0 * recip_h + sub_x; - bc->yoff = (float) y0 * recip_v + sub_y; - bc->xoff2 = ((float)x0 + r->w) * recip_h + sub_x; - bc->yoff2 = ((float)y0 + r->h) * recip_v + sub_y; - } else { - return_value = 0; /* if any fail, report failure */ - } - ++k; - } - } - /* restore original values */ - spc->h_oversample = (unsigned int)old_h_over; - spc->v_oversample = (unsigned int)old_v_over; - return return_value; -} -NK_INTERN void -nk_tt_GetPackedQuad(struct nk_tt_packedchar *chardata, int pw, int ph, - int char_index, float *xpos, float *ypos, struct nk_tt_aligned_quad *q, - int align_to_integer) -{ - float ipw = 1.0f / (float)pw, iph = 1.0f / (float)ph; - struct nk_tt_packedchar *b = (struct nk_tt_packedchar*)(chardata + char_index); - if (align_to_integer) { - int tx = nk_ifloorf((*xpos + b->xoff) + 0.5f); - int ty = nk_ifloorf((*ypos + b->yoff) + 0.5f); - - float x = (float)tx; - float y = (float)ty; - - q->x0 = x; - q->y0 = y; - q->x1 = x + b->xoff2 - b->xoff; - q->y1 = y + b->yoff2 - b->yoff; - } else { - q->x0 = *xpos + b->xoff; - q->y0 = *ypos + b->yoff; - q->x1 = *xpos + b->xoff2; - q->y1 = *ypos + b->yoff2; - } - q->s0 = b->x0 * ipw; - q->t0 = b->y0 * iph; - q->s1 = b->x1 * ipw; - q->t1 = b->y1 * iph; - *xpos += b->xadvance; -} - -/* ------------------------------------------------------------- - * - * FONT BAKING - * - * --------------------------------------------------------------*/ -struct nk_font_bake_data { - struct nk_tt_fontinfo info; - struct nk_rp_rect *rects; - struct nk_tt_pack_range *ranges; - nk_rune range_count; -}; - -struct nk_font_baker { - struct nk_allocator alloc; - struct nk_tt_pack_context spc; - struct nk_font_bake_data *build; - struct nk_tt_packedchar *packed_chars; - struct nk_rp_rect *rects; - struct nk_tt_pack_range *ranges; -}; - -NK_GLOBAL const nk_size nk_rect_align = NK_ALIGNOF(struct nk_rp_rect); -NK_GLOBAL const nk_size nk_range_align = NK_ALIGNOF(struct nk_tt_pack_range); -NK_GLOBAL const nk_size nk_char_align = NK_ALIGNOF(struct nk_tt_packedchar); -NK_GLOBAL const nk_size nk_build_align = NK_ALIGNOF(struct nk_font_bake_data); -NK_GLOBAL const nk_size nk_baker_align = NK_ALIGNOF(struct nk_font_baker); - -NK_INTERN int -nk_range_count(const nk_rune *range) -{ - const nk_rune *iter = range; - NK_ASSERT(range); - if (!range) return 0; - while (*(iter++) != 0); - return (iter == range) ? 0 : (int)((iter - range)/2); -} -NK_INTERN int -nk_range_glyph_count(const nk_rune *range, int count) -{ - int i = 0; - int total_glyphs = 0; - for (i = 0; i < count; ++i) { - int diff; - nk_rune f = range[(i*2)+0]; - nk_rune t = range[(i*2)+1]; - NK_ASSERT(t >= f); - diff = (int)((t - f) + 1); - total_glyphs += diff; - } - return total_glyphs; -} -NK_API const nk_rune* -nk_font_default_glyph_ranges(void) -{ - NK_STORAGE const nk_rune ranges[] = {0x0020, 0x00FF, 0}; - return ranges; -} -NK_API const nk_rune* -nk_font_chinese_glyph_ranges(void) -{ - NK_STORAGE const nk_rune ranges[] = { - 0x0020, 0x00FF, - 0x3000, 0x30FF, - 0x31F0, 0x31FF, - 0xFF00, 0xFFEF, - 0x4e00, 0x9FAF, - 0 - }; - return ranges; -} -NK_API const nk_rune* -nk_font_cyrillic_glyph_ranges(void) -{ - NK_STORAGE const nk_rune ranges[] = { - 0x0020, 0x00FF, - 0x0400, 0x052F, - 0x2DE0, 0x2DFF, - 0xA640, 0xA69F, - 0 - }; - return ranges; -} -NK_API const nk_rune* -nk_font_korean_glyph_ranges(void) -{ - NK_STORAGE const nk_rune ranges[] = { - 0x0020, 0x00FF, - 0x3131, 0x3163, - 0xAC00, 0xD79D, - 0 - }; - return ranges; -} -NK_INTERN void -nk_font_baker_memory(nk_size *temp, int *glyph_count, - struct nk_font_config *config_list, int count) -{ - int range_count = 0; - int total_range_count = 0; - struct nk_font_config *iter, *i; - - NK_ASSERT(config_list); - NK_ASSERT(glyph_count); - if (!config_list) { - *temp = 0; - *glyph_count = 0; - return; - } - *glyph_count = 0; - for (iter = config_list; iter; iter = iter->next) { - i = iter; - do {if (!i->range) iter->range = nk_font_default_glyph_ranges(); - range_count = nk_range_count(i->range); - total_range_count += range_count; - *glyph_count += nk_range_glyph_count(i->range, range_count); - } while ((i = i->n) != iter); - } - *temp = (nk_size)*glyph_count * sizeof(struct nk_rp_rect); - *temp += (nk_size)total_range_count * sizeof(struct nk_tt_pack_range); - *temp += (nk_size)*glyph_count * sizeof(struct nk_tt_packedchar); - *temp += (nk_size)count * sizeof(struct nk_font_bake_data); - *temp += sizeof(struct nk_font_baker); - *temp += nk_rect_align + nk_range_align + nk_char_align; - *temp += nk_build_align + nk_baker_align; -} -NK_INTERN struct nk_font_baker* -nk_font_baker(void *memory, int glyph_count, int count, struct nk_allocator *alloc) -{ - struct nk_font_baker *baker; - if (!memory) return 0; - /* setup baker inside a memory block */ - baker = (struct nk_font_baker*)NK_ALIGN_PTR(memory, nk_baker_align); - baker->build = (struct nk_font_bake_data*)NK_ALIGN_PTR((baker + 1), nk_build_align); - baker->packed_chars = (struct nk_tt_packedchar*)NK_ALIGN_PTR((baker->build + count), nk_char_align); - baker->rects = (struct nk_rp_rect*)NK_ALIGN_PTR((baker->packed_chars + glyph_count), nk_rect_align); - baker->ranges = (struct nk_tt_pack_range*)NK_ALIGN_PTR((baker->rects + glyph_count), nk_range_align); - baker->alloc = *alloc; - return baker; -} -NK_INTERN int -nk_font_bake_pack(struct nk_font_baker *baker, - nk_size *image_memory, int *width, int *height, struct nk_recti *custom, - const struct nk_font_config *config_list, int count, - struct nk_allocator *alloc) -{ - NK_STORAGE const nk_size max_height = 1024 * 32; - const struct nk_font_config *config_iter, *it; - int total_glyph_count = 0; - int total_range_count = 0; - int range_count = 0; - int i = 0; - - NK_ASSERT(image_memory); - NK_ASSERT(width); - NK_ASSERT(height); - NK_ASSERT(config_list); - NK_ASSERT(count); - NK_ASSERT(alloc); - - if (!image_memory || !width || !height || !config_list || !count) return nk_false; - for (config_iter = config_list; config_iter; config_iter = config_iter->next) { - it = config_iter; - do {range_count = nk_range_count(it->range); - total_range_count += range_count; - total_glyph_count += nk_range_glyph_count(it->range, range_count); - } while ((it = it->n) != config_iter); - } - /* setup font baker from temporary memory */ - for (config_iter = config_list; config_iter; config_iter = config_iter->next) { - it = config_iter; - do {if (!nk_tt_InitFont(&baker->build[i++].info, (const unsigned char*)it->ttf_blob, 0)) - return nk_false; - } while ((it = it->n) != config_iter); - } - *height = 0; - *width = (total_glyph_count > 1000) ? 1024 : 512; - nk_tt_PackBegin(&baker->spc, 0, (int)*width, (int)max_height, 0, 1, alloc); - { - int input_i = 0; - int range_n = 0; - int rect_n = 0; - int char_n = 0; - - if (custom) { - /* pack custom user data first so it will be in the upper left corner*/ - struct nk_rp_rect custom_space; - nk_zero(&custom_space, sizeof(custom_space)); - custom_space.w = (nk_rp_coord)(custom->w); - custom_space.h = (nk_rp_coord)(custom->h); - - nk_tt_PackSetOversampling(&baker->spc, 1, 1); - nk_rp_pack_rects((struct nk_rp_context*)baker->spc.pack_info, &custom_space, 1); - *height = NK_MAX(*height, (int)(custom_space.y + custom_space.h)); - - custom->x = (short)custom_space.x; - custom->y = (short)custom_space.y; - custom->w = (short)custom_space.w; - custom->h = (short)custom_space.h; - } - - /* first font pass: pack all glyphs */ - for (input_i = 0, config_iter = config_list; input_i < count && config_iter; - config_iter = config_iter->next) { - it = config_iter; - do {int n = 0; - int glyph_count; - const nk_rune *in_range; - const struct nk_font_config *cfg = it; - struct nk_font_bake_data *tmp = &baker->build[input_i++]; - - /* count glyphs + ranges in current font */ - glyph_count = 0; range_count = 0; - for (in_range = cfg->range; in_range[0] && in_range[1]; in_range += 2) { - glyph_count += (int)(in_range[1] - in_range[0]) + 1; - range_count++; - } - - /* setup ranges */ - tmp->ranges = baker->ranges + range_n; - tmp->range_count = (nk_rune)range_count; - range_n += range_count; - for (i = 0; i < range_count; ++i) { - in_range = &cfg->range[i * 2]; - tmp->ranges[i].font_size = cfg->size; - tmp->ranges[i].first_unicode_codepoint_in_range = (int)in_range[0]; - tmp->ranges[i].num_chars = (int)(in_range[1]- in_range[0]) + 1; - tmp->ranges[i].chardata_for_range = baker->packed_chars + char_n; - char_n += tmp->ranges[i].num_chars; - } - - /* pack */ - tmp->rects = baker->rects + rect_n; - rect_n += glyph_count; - nk_tt_PackSetOversampling(&baker->spc, cfg->oversample_h, cfg->oversample_v); - n = nk_tt_PackFontRangesGatherRects(&baker->spc, &tmp->info, - tmp->ranges, (int)tmp->range_count, tmp->rects); - nk_rp_pack_rects((struct nk_rp_context*)baker->spc.pack_info, tmp->rects, (int)n); - - /* texture height */ - for (i = 0; i < n; ++i) { - if (tmp->rects[i].was_packed) - *height = NK_MAX(*height, tmp->rects[i].y + tmp->rects[i].h); - } - } while ((it = it->n) != config_iter); - } - NK_ASSERT(rect_n == total_glyph_count); - NK_ASSERT(char_n == total_glyph_count); - NK_ASSERT(range_n == total_range_count); - } - *height = (int)nk_round_up_pow2((nk_uint)*height); - *image_memory = (nk_size)(*width) * (nk_size)(*height); - return nk_true; -} -NK_INTERN void -nk_font_bake(struct nk_font_baker *baker, void *image_memory, int width, int height, - struct nk_font_glyph *glyphs, int glyphs_count, - const struct nk_font_config *config_list, int font_count) -{ - int input_i = 0; - nk_rune glyph_n = 0; - const struct nk_font_config *config_iter; - const struct nk_font_config *it; - - NK_ASSERT(image_memory); - NK_ASSERT(width); - NK_ASSERT(height); - NK_ASSERT(config_list); - NK_ASSERT(baker); - NK_ASSERT(font_count); - NK_ASSERT(glyphs_count); - if (!image_memory || !width || !height || !config_list || - !font_count || !glyphs || !glyphs_count) - return; - - /* second font pass: render glyphs */ - nk_zero(image_memory, (nk_size)((nk_size)width * (nk_size)height)); - baker->spc.pixels = (unsigned char*)image_memory; - baker->spc.height = (int)height; - for (input_i = 0, config_iter = config_list; input_i < font_count && config_iter; - config_iter = config_iter->next) { - it = config_iter; - do {const struct nk_font_config *cfg = it; - struct nk_font_bake_data *tmp = &baker->build[input_i++]; - nk_tt_PackSetOversampling(&baker->spc, cfg->oversample_h, cfg->oversample_v); - nk_tt_PackFontRangesRenderIntoRects(&baker->spc, &tmp->info, tmp->ranges, - (int)tmp->range_count, tmp->rects, &baker->alloc); - } while ((it = it->n) != config_iter); - } nk_tt_PackEnd(&baker->spc, &baker->alloc); - - /* third pass: setup font and glyphs */ - for (input_i = 0, config_iter = config_list; input_i < font_count && config_iter; - config_iter = config_iter->next) { - it = config_iter; - do {nk_size i = 0; - int char_idx = 0; - nk_rune glyph_count = 0; - const struct nk_font_config *cfg = it; - struct nk_font_bake_data *tmp = &baker->build[input_i++]; - struct nk_baked_font *dst_font = cfg->font; - - float font_scale = nk_tt_ScaleForPixelHeight(&tmp->info, cfg->size); - int unscaled_ascent, unscaled_descent, unscaled_line_gap; - nk_tt_GetFontVMetrics(&tmp->info, &unscaled_ascent, &unscaled_descent, - &unscaled_line_gap); - - /* fill baked font */ - if (!cfg->merge_mode) { - dst_font->ranges = cfg->range; - dst_font->height = cfg->size; - dst_font->ascent = ((float)unscaled_ascent * font_scale); - dst_font->descent = ((float)unscaled_descent * font_scale); - dst_font->glyph_offset = glyph_n; - } - - /* fill own baked font glyph array */ - for (i = 0; i < tmp->range_count; ++i) { - struct nk_tt_pack_range *range = &tmp->ranges[i]; - for (char_idx = 0; char_idx < range->num_chars; char_idx++) - { - nk_rune codepoint = 0; - float dummy_x = 0, dummy_y = 0; - struct nk_tt_aligned_quad q; - struct nk_font_glyph *glyph; - - /* query glyph bounds from stb_truetype */ - const struct nk_tt_packedchar *pc = &range->chardata_for_range[char_idx]; - if (!pc->x0 && !pc->x1 && !pc->y0 && !pc->y1) continue; - codepoint = (nk_rune)(range->first_unicode_codepoint_in_range + char_idx); - nk_tt_GetPackedQuad(range->chardata_for_range, (int)width, - (int)height, char_idx, &dummy_x, &dummy_y, &q, 0); - - /* fill own glyph type with data */ - glyph = &glyphs[dst_font->glyph_offset + dst_font->glyph_count + (unsigned int)glyph_count]; - glyph->codepoint = codepoint; - glyph->x0 = q.x0; glyph->y0 = q.y0; - glyph->x1 = q.x1; glyph->y1 = q.y1; - glyph->y0 += (dst_font->ascent + 0.5f); - glyph->y1 += (dst_font->ascent + 0.5f); - glyph->w = glyph->x1 - glyph->x0 + 0.5f; - glyph->h = glyph->y1 - glyph->y0; - - if (cfg->coord_type == NK_COORD_PIXEL) { - glyph->u0 = q.s0 * (float)width; - glyph->v0 = q.t0 * (float)height; - glyph->u1 = q.s1 * (float)width; - glyph->v1 = q.t1 * (float)height; - } else { - glyph->u0 = q.s0; - glyph->v0 = q.t0; - glyph->u1 = q.s1; - glyph->v1 = q.t1; - } - glyph->xadvance = (pc->xadvance + cfg->spacing.x); - if (cfg->pixel_snap) - glyph->xadvance = (float)(int)(glyph->xadvance + 0.5f); - glyph_count++; - } - } - dst_font->glyph_count += glyph_count; - glyph_n += glyph_count; - } while ((it = it->n) != config_iter); - } -} -NK_INTERN void -nk_font_bake_custom_data(void *img_memory, int img_width, int img_height, - struct nk_recti img_dst, const char *texture_data_mask, int tex_width, - int tex_height, char white, char black) -{ - nk_byte *pixels; - int y = 0; - int x = 0; - int n = 0; - - NK_ASSERT(img_memory); - NK_ASSERT(img_width); - NK_ASSERT(img_height); - NK_ASSERT(texture_data_mask); - NK_UNUSED(tex_height); - if (!img_memory || !img_width || !img_height || !texture_data_mask) - return; - - pixels = (nk_byte*)img_memory; - for (y = 0, n = 0; y < tex_height; ++y) { - for (x = 0; x < tex_width; ++x, ++n) { - const int off0 = ((img_dst.x + x) + (img_dst.y + y) * img_width); - const int off1 = off0 + 1 + tex_width; - pixels[off0] = (texture_data_mask[n] == white) ? 0xFF : 0x00; - pixels[off1] = (texture_data_mask[n] == black) ? 0xFF : 0x00; - } - } -} -NK_INTERN void -nk_font_bake_convert(void *out_memory, int img_width, int img_height, - const void *in_memory) -{ - int n = 0; - nk_rune *dst; - const nk_byte *src; - - NK_ASSERT(out_memory); - NK_ASSERT(in_memory); - NK_ASSERT(img_width); - NK_ASSERT(img_height); - if (!out_memory || !in_memory || !img_height || !img_width) return; - - dst = (nk_rune*)out_memory; - src = (const nk_byte*)in_memory; - for (n = (int)(img_width * img_height); n > 0; n--) - *dst++ = ((nk_rune)(*src++) << 24) | 0x00FFFFFF; -} - -/* ------------------------------------------------------------- - * - * FONT - * - * --------------------------------------------------------------*/ -NK_INTERN float -nk_font_text_width(nk_handle handle, float height, const char *text, int len) -{ - nk_rune unicode; - int text_len = 0; - float text_width = 0; - int glyph_len = 0; - float scale = 0; - - struct nk_font *font = (struct nk_font*)handle.ptr; - NK_ASSERT(font); - NK_ASSERT(font->glyphs); - if (!font || !text || !len) - return 0; - - scale = height/font->info.height; - glyph_len = text_len = nk_utf_decode(text, &unicode, (int)len); - if (!glyph_len) return 0; - while (text_len <= (int)len && glyph_len) { - const struct nk_font_glyph *g; - if (unicode == NK_UTF_INVALID) break; - - /* query currently drawn glyph information */ - g = nk_font_find_glyph(font, unicode); - text_width += g->xadvance * scale; - - /* offset next glyph */ - glyph_len = nk_utf_decode(text + text_len, &unicode, (int)len - text_len); - text_len += glyph_len; - } - return text_width; -} -#ifdef NK_INCLUDE_VERTEX_BUFFER_OUTPUT -NK_INTERN void -nk_font_query_font_glyph(nk_handle handle, float height, - struct nk_user_font_glyph *glyph, nk_rune codepoint, nk_rune next_codepoint) -{ - float scale; - const struct nk_font_glyph *g; - struct nk_font *font; - - NK_ASSERT(glyph); - NK_UNUSED(next_codepoint); - - font = (struct nk_font*)handle.ptr; - NK_ASSERT(font); - NK_ASSERT(font->glyphs); - if (!font || !glyph) - return; - - scale = height/font->info.height; - g = nk_font_find_glyph(font, codepoint); - glyph->width = (g->x1 - g->x0) * scale; - glyph->height = (g->y1 - g->y0) * scale; - glyph->offset = nk_vec2(g->x0 * scale, g->y0 * scale); - glyph->xadvance = (g->xadvance * scale); - glyph->uv[0] = nk_vec2(g->u0, g->v0); - glyph->uv[1] = nk_vec2(g->u1, g->v1); -} -#endif -NK_API const struct nk_font_glyph* -nk_font_find_glyph(struct nk_font *font, nk_rune unicode) -{ - int i = 0; - int count; - int total_glyphs = 0; - const struct nk_font_glyph *glyph = 0; - const struct nk_font_config *iter = 0; - - NK_ASSERT(font); - NK_ASSERT(font->glyphs); - NK_ASSERT(font->info.ranges); - if (!font || !font->glyphs) return 0; - - glyph = font->fallback; - iter = font->config; - do {count = nk_range_count(iter->range); - for (i = 0; i < count; ++i) { - nk_rune f = iter->range[(i*2)+0]; - nk_rune t = iter->range[(i*2)+1]; - int diff = (int)((t - f) + 1); - if (unicode >= f && unicode <= t) - return &font->glyphs[((nk_rune)total_glyphs + (unicode - f))]; - total_glyphs += diff; - } - } while ((iter = iter->n) != font->config); - return glyph; -} -NK_INTERN void -nk_font_init(struct nk_font *font, float pixel_height, - nk_rune fallback_codepoint, struct nk_font_glyph *glyphs, - const struct nk_baked_font *baked_font, nk_handle atlas) -{ - struct nk_baked_font baked; - NK_ASSERT(font); - NK_ASSERT(glyphs); - NK_ASSERT(baked_font); - if (!font || !glyphs || !baked_font) - return; - - baked = *baked_font; - font->fallback = 0; - font->info = baked; - font->scale = (float)pixel_height / (float)font->info.height; - font->glyphs = &glyphs[baked_font->glyph_offset]; - font->texture = atlas; - font->fallback_codepoint = fallback_codepoint; - font->fallback = nk_font_find_glyph(font, fallback_codepoint); - - font->handle.height = font->info.height * font->scale; - font->handle.width = nk_font_text_width; - font->handle.userdata.ptr = font; -#ifdef NK_INCLUDE_VERTEX_BUFFER_OUTPUT - font->handle.query = nk_font_query_font_glyph; - font->handle.texture = font->texture; -#endif -} - -/* --------------------------------------------------------------------------- - * - * DEFAULT FONT - * - * ProggyClean.ttf - * Copyright (c) 2004, 2005 Tristan Grimmer - * MIT license (see License.txt in http://www.upperbounds.net/download/ProggyClean.ttf.zip) - * Download and more information at http://upperbounds.net - *-----------------------------------------------------------------------------*/ -#ifdef __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Woverlength-strings" -#elif defined(__GNUC__) || defined(__GNUG__) -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Woverlength-strings" -#endif - -#ifdef NK_INCLUDE_DEFAULT_FONT - -NK_GLOBAL const char nk_proggy_clean_ttf_compressed_data_base85[11980+1] = - "7])#######hV0qs'/###[),##/l:$#Q6>##5[n42>c-TH`->>#/e>11NNV=Bv(*:.F?uu#(gRU.o0XGH`$vhLG1hxt9?W`#,5LsCp#-i>.r$<$6pD>Lb';9Crc6tgXmKVeU2cD4Eo3R/" - "2*>]b(MC;$jPfY.;h^`IWM9Qo#t'X#(v#Y9w0#1D$CIf;W'#pWUPXOuxXuU(H9M(1=Ke$$'5F%)]0^#0X@U.a$FBjVQTSDgEKnIS7EM9>ZY9w0#L;>>#Mx&4Mvt//L[MkA#W@lK.N'[0#7RL_&#w+F%HtG9M#XL`N&.,GM4Pg;--VsM.M0rJfLH2eTM`*oJMHRC`N" - "kfimM2J,W-jXS:)r0wK#@Fge$U>`w'N7G#$#fB#$E^$#:9:hk+eOe--6x)F7*E%?76%^GMHePW-Z5l'&GiF#$956:rS?dA#fiK:)Yr+`�j@'DbG&#^$PG.Ll+DNa&VZ>1i%h1S9u5o@YaaW$e+bROPOpxTO7Stwi1::iB1q)C_=dV26J;2,]7op$]uQr@_V7$q^%lQwtuHY]=DX,n3L#0PHDO4f9>dC@O>HBuKPpP*E,N+b3L#lpR/MrTEH.IAQk.a>D[.e;mc." - "x]Ip.PH^'/aqUO/$1WxLoW0[iLAw=4h(9.`G" - "CRUxHPeR`5Mjol(dUWxZa(>STrPkrJiWx`5U7F#.g*jrohGg`cg:lSTvEY/EV_7H4Q9[Z%cnv;JQYZ5q.l7Zeas:HOIZOB?Ggv:[7MI2k).'2($5FNP&EQ(,)" - "U]W]+fh18.vsai00);D3@4ku5P?DP8aJt+;qUM]=+b'8@;mViBKx0DE[-auGl8:PJ&Dj+M6OC]O^((##]`0i)drT;-7X`=-H3[igUnPG-NZlo.#k@h#=Ork$m>a>$-?Tm$UV(?#P6YY#" - "'/###xe7q.73rI3*pP/$1>s9)W,JrM7SN]'/4C#v$U`0#V.[0>xQsH$fEmPMgY2u7Kh(G%siIfLSoS+MK2eTM$=5,M8p`A.;_R%#u[K#$x4AG8.kK/HSB==-'Ie/QTtG?-.*^N-4B/ZM" - "_3YlQC7(p7q)&](`6_c)$/*JL(L-^(]$wIM`dPtOdGA,U3:w2M-0+WomX2u7lqM2iEumMTcsF?-aT=Z-97UEnXglEn1K-bnEO`gu" - "Ft(c%=;Am_Qs@jLooI&NX;]0#j4#F14;gl8-GQpgwhrq8'=l_f-b49'UOqkLu7-##oDY2L(te+Mch&gLYtJ,MEtJfLh'x'M=$CS-ZZ%P]8bZ>#S?YY#%Q&q'3^Fw&?D)UDNrocM3A76/" - "/oL?#h7gl85[qW/NDOk%16ij;+:1a'iNIdb-ou8.P*w,v5#EI$TWS>Pot-R*H'-SEpA:g)f+O$%%`kA#G=8RMmG1&O`>to8bC]T&$,n.LoO>29sp3dt-52U%VM#q7'DHpg+#Z9%H[Ket`e;)f#Km8&+DC$I46>#Kr]]u-[=99tts1.qb#q72g1WJO81q+eN'03'eM>&1XxY-caEnO" - "j%2n8)),?ILR5^.Ibn<-X-Mq7[a82Lq:F&#ce+S9wsCK*x`569E8ew'He]h:sI[2LM$[guka3ZRd6:t%IG:;$%YiJ:Nq=?eAw;/:nnDq0(CYcMpG)qLN4$##&J-XTt,%OVU4)S1+R-#dg0/Nn?Ku1^0f$B*P:Rowwm-`0PKjYDDM'3]d39VZHEl4,.j']Pk-M.h^&:0FACm$maq-&sgw0t7/6(^xtk%" - "LuH88Fj-ekm>GA#_>568x6(OFRl-IZp`&b,_P'$MhLbxfc$mj`,O;&%W2m`Zh:/)Uetw:aJ%]K9h:TcF]u_-Sj9,VK3M.*'&0D[Ca]J9gp8,kAW]" - "%(?A%R$f<->Zts'^kn=-^@c4%-pY6qI%J%1IGxfLU9CP8cbPlXv);C=b),<2mOvP8up,UVf3839acAWAW-W?#ao/^#%KYo8fRULNd2.>%m]UK:n%r$'sw]J;5pAoO_#2mO3n,'=H5(et" - "Hg*`+RLgv>=4U8guD$I%D:W>-r5V*%j*W:Kvej.Lp$'?;++O'>()jLR-^u68PHm8ZFWe+ej8h:9r6L*0//c&iH&R8pRbA#Kjm%upV1g:" - "a_#Ur7FuA#(tRh#.Y5K+@?3<-8m0$PEn;J:rh6?I6uG<-`wMU'ircp0LaE_OtlMb&1#6T.#FDKu#1Lw%u%+GM+X'e?YLfjM[VO0MbuFp7;>Q&#WIo)0@F%q7c#4XAXN-U&VBpqB>0ie&jhZ[?iLR@@_AvA-iQC(=ksRZRVp7`.=+NpBC%rh&3]R:8XDmE5^V8O(x<-+k?'(^](H.aREZSi,#1:[IXaZFOm<-ui#qUq2$##Ri;u75OK#(RtaW-K-F`S+cF]uN`-KMQ%rP/Xri.LRcB##=YL3BgM/3M" - "D?@f&1'BW-)Ju#bmmWCMkk&#TR`C,5d>g)F;t,4:@_l8G/5h4vUd%&%950:VXD'QdWoY-F$BtUwmfe$YqL'8(PWX(" - "P?^@Po3$##`MSs?DWBZ/S>+4%>fX,VWv/w'KD`LP5IbH;rTV>n3cEK8U#bX]l-/V+^lj3;vlMb&[5YQ8#pekX9JP3XUC72L,,?+Ni&co7ApnO*5NK,((W-i:$,kp'UDAO(G0Sq7MVjJs" - "bIu)'Z,*[>br5fX^:FPAWr-m2KgLQ_nN6'8uTGT5g)uLv:873UpTLgH+#FgpH'_o1780Ph8KmxQJ8#H72L4@768@Tm&Q" - "h4CB/5OvmA&,Q&QbUoi$a_%3M01H)4x7I^&KQVgtFnV+;[Pc>[m4k//,]1?#`VY[Jr*3&&slRfLiVZJ:]?=K3Sw=[$=uRB?3xk48@aege0jT6'N#(q%.O=?2S]u*(m<-" - "V8J'(1)G][68hW$5'q[GC&5j`TE?m'esFGNRM)j,ffZ?-qx8;->g4t*:CIP/[Qap7/9'#(1sao7w-.qNUdkJ)tCF&#B^;xGvn2r9FEPFFFcL@.iFNkTve$m%#QvQS8U@)2Z+3K:AKM5i" - "sZ88+dKQ)W6>J%CL`.d*(B`-n8D9oK-XV1q['-5k'cAZ69e;D_?$ZPP&s^+7])$*$#@QYi9,5P r+$%CE=68>K8r0=dSC%%(@p7" - ".m7jilQ02'0-VWAgTlGW'b)Tq7VT9q^*^$$.:&N@@" - "$&)WHtPm*5_rO0&e%K&#-30j(E4#'Zb.o/(Tpm$>K'f@[PvFl,hfINTNU6u'0pao7%XUp9]5.>%h`8_=VYbxuel.NTSsJfLacFu3B'lQSu/m6-Oqem8T+oE--$0a/k]uj9EwsG>%veR*" - "hv^BFpQj:K'#SJ,sB-'#](j.Lg92rTw-*n%@/;39rrJF,l#qV%OrtBeC6/,;qB3ebNW[?,Hqj2L.1NP&GjUR=1D8QaS3Up&@*9wP?+lo7b?@%'k4`p0Z$22%K3+iCZj?XJN4Nm&+YF]u" - "@-W$U%VEQ/,,>>#)D#%8cY#YZ?=,`Wdxu/ae&#" - "w6)R89tI#6@s'(6Bf7a&?S=^ZI_kS&ai`&=tE72L_D,;^R)7[$so8lKN%5/$(vdfq7+ebA#" - "u1p]ovUKW&Y%q]'>$1@-[xfn$7ZTp7mM,G,Ko7a&Gu%G[RMxJs[0MM%wci.LFDK)(%:_i2B5CsR8&9Z&#=mPEnm0f`<&c)QL5uJ#%u%lJj+D-r;BoFDoS97h5g)E#o:&S4weDF,9^Hoe`h*L+_a*NrLW-1pG_&2UdB8" - "6e%B/:=>)N4xeW.*wft-;$'58-ESqr#U`'6AQ]m&6/`Z>#S?YY#Vc;r7U2&326d=w&H####?TZ`*4?&.MK?LP8Vxg>$[QXc%QJv92.(Db*B)gb*BM9dM*hJMAo*c&#" - "b0v=Pjer]$gG&JXDf->'StvU7505l9$AFvgYRI^&<^b68?j#q9QX4SM'RO#&sL1IM.rJfLUAj221]d##DW=m83u5;'bYx,*Sl0hL(W;;$doB&O/TQ:(Z^xBdLjLV#*8U_72Lh+2Q8Cj0i:6hp&$C/:p(HK>T8Y[gHQ4`4)'$Ab(Nof%V'8hL&#SfD07&6D@M.*J:;$-rv29'M]8qMv-tLp,'886iaC=Hb*YJoKJ,(j%K=H`K.v9HggqBIiZu'QvBT.#=)0ukruV&.)3=(^1`o*Pj4<-#MJ+gLq9-##@HuZPN0]u:h7.T..G:;$/Usj(T7`Q8tT72LnYl<-qx8;-HV7Q-&Xdx%1a,hC=0u+HlsV>nuIQL-5" - "_>@kXQtMacfD.m-VAb8;IReM3$wf0''hra*so568'Ip&vRs849'MRYSp%:t:h5qSgwpEr$B>Q,;s(C#$)`svQuF$##-D,##,g68@2[T;.XSdN9Qe)rpt._K-#5wF)sP'##p#C0c%-Gb%" - "hd+<-j'Ai*x&&HMkT]C'OSl##5RG[JXaHN;d'uA#x._U;.`PU@(Z3dt4r152@:v,'R.Sj'w#0<-;kPI)FfJ&#AYJ&#//)>-k=m=*XnK$>=)72L]0I%>.G690a:$##<,);?;72#?x9+d;" - "^V'9;jY@;)br#q^YQpx:X#Te$Z^'=-=bGhLf:D6&bNwZ9-ZD#n^9HhLMr5G;']d&6'wYmTFmLq9wI>P(9mI[>kC-ekLC/R&CH+s'B;K-M6$EB%is00:" - "+A4[7xks.LrNk0&E)wILYF@2L'0Nb$+pv<(2.768/FrY&h$^3i&@+G%JT'<-,v`3;_)I9M^AE]CN?Cl2AZg+%4iTpT3$U4O]GKx'm9)b@p7YsvK3w^YR-" - "CdQ*:Ir<($u&)#(&?L9Rg3H)4fiEp^iI9O8KnTj,]H?D*r7'M;PwZ9K0E^k&-cpI;.p/6_vwoFMV<->#%Xi.LxVnrU(4&8/P+:hLSKj$#U%]49t'I:rgMi'FL@a:0Y-uA[39',(vbma*" - "hU%<-SRF`Tt:542R_VV$p@[p8DV[A,?1839FWdFTi1O*H&#(AL8[_P%.M>v^-))qOT*F5Cq0`Ye%+$B6i:7@0IXSsDiWP,##P`%/L-" - "S(qw%sf/@%#B6;/U7K]uZbi^Oc^2n%t<)'mEVE''n`WnJra$^TKvX5B>;_aSEK',(hwa0:i4G?.Bci.(X[?b*($,=-n<.Q%`(X=?+@Am*Js0&=3bh8K]mL69=Lb,OcZV/);TTm8VI;?%OtJ<(b4mq7M6:u?KRdFl*:xP?Yb.5)%w_I?7uk5JC+FS(m#i'k.'a0i)9<7b'fs'59hq$*5Uhv##pi^8+hIEBF`nvo`;'l0.^S1<-wUK2/Coh58KKhLj" - "M=SO*rfO`+qC`W-On.=AJ56>>i2@2LH6A:&5q`?9I3@@'04&p2/LVa*T-4<-i3;M9UvZd+N7>b*eIwg:CC)c<>nO&#$(>.Z-I&J(Q0Hd5Q%7Co-b`-cP)hI;*_F]u`Rb[.j8_Q/<&>uu+VsH$sM9TA%?)(vmJ80),P7E>)tjD%2L=-t#fK[%`v=Q8WlA2);Sa" - ">gXm8YB`1d@K#n]76-a$U,mF%Ul:#/'xoFM9QX-$.QN'>" - "[%$Z$uF6pA6Ki2O5:8w*vP1<-1`[G,)-m#>0`P&#eb#.3i)rtB61(o'$?X3B2Qft^ae_5tKL9MUe9b*sLEQ95C&`=G?@Mj=wh*'3E>=-<)Gt*Iw)'QG:`@I" - "wOf7&]1i'S01B+Ev/Nac#9S;=;YQpg_6U`*kVY39xK,[/6Aj7:'1Bm-_1EYfa1+o&o4hp7KN_Q(OlIo@S%;jVdn0'1h19w,WQhLI)3S#f$2(eb,jr*b;3Vw]*7NH%$c4Vs,eD9>XW8?N]o+(*pgC%/72LV-uW%iewS8W6m2rtCpo'RS1R84=@paTKt)>=%&1[)*vp'u+x,VrwN;&]kuO9JDbg=pO$J*.jVe;u'm0dr9l,<*wMK*Oe=g8lV_KEBFkO'oU]^=[-792#ok,)" - "i]lR8qQ2oA8wcRCZ^7w/Njh;?.stX?Q1>S1q4Bn$)K1<-rGdO'$Wr.Lc.CG)$/*JL4tNR/,SVO3,aUw'DJN:)Ss;wGn9A32ijw%FL+Z0Fn.U9;reSq)bmI32U==5ALuG&#Vf1398/pVo" - "1*c-(aY168o<`JsSbk-,1N;$>0:OUas(3:8Z972LSfF8eb=c-;>SPw7.6hn3m`9^Xkn(r.qS[0;T%&Qc=+STRxX'q1BNk3&*eu2;&8q$&x>Q#Q7^Tf+6<(d%ZVmj2bDi%.3L2n+4W'$P" - "iDDG)g,r%+?,$@?uou5tSe2aN_AQU*'IAO" - "URQ##V^Fv-XFbGM7Fl(N<3DhLGF%q.1rC$#:T__&Pi68%0xi_&[qFJ(77j_&JWoF.V735&T,[R*:xFR*K5>>#`bW-?4Ne_&6Ne_&6Ne_&n`kr-#GJcM6X;uM6X;uM(.a..^2TkL%oR(#" - ";u.T%fAr%4tJ8&><1=GHZ_+m9/#H1F^R#SC#*N=BA9(D?v[UiFY>>^8p,KKF.W]L29uLkLlu/+4T" - "w$)F./^n3+rlo+DB;5sIYGNk+i1t-69Jg--0pao7Sm#K)pdHW&;LuDNH@H>#/X-TI(;P>#,Gc>#0Su>#4`1?#8lC?#xL$#B.`$#F:r$#JF.%#NR@%#R_R%#Vke%#Zww%#_-4^Rh%Sflr-k'MS.o?.5/sWel/wpEM0%3'/1)K^f1-d>G21&v(35>V`39V7A4=onx4" - "A1OY5EI0;6Ibgr6M$HS7Q<)58C5w,;WoA*#[%T*#`1g*#d=#+#hI5+#lUG+#pbY+#tnl+#x$),#&1;,#*=M,#.I`,#2Ur,#6b.-#;w[H#iQtA#m^0B#qjBB#uvTB##-hB#'9$C#+E6C#" - "/QHC#3^ZC#7jmC#;v)D#?,)4kMYD4lVu`4m`:&5niUA5@(A5BA1]PBB:xlBCC=2CDLXMCEUtiCf&0g2'tN?PGT4CPGT4CPGT4CPGT4CPGT4CPGT4CPGT4CP" - "GT4CPGT4CPGT4CPGT4CPGT4CPGT4CP-qekC`.9kEg^+F$kwViFJTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5o,^<-28ZI'O?;xp" - "O?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xp;7q-#lLYI:xvD=#"; - -#endif /* NK_INCLUDE_DEFAULT_FONT */ - -#define NK_CURSOR_DATA_W 90 -#define NK_CURSOR_DATA_H 27 -NK_GLOBAL const char nk_custom_cursor_data[NK_CURSOR_DATA_W * NK_CURSOR_DATA_H + 1] = -{ - "..- -XXXXXXX- X - X -XXXXXXX - XXXXXXX" - "..- -X.....X- X.X - X.X -X.....X - X.....X" - "--- -XXX.XXX- X...X - X...X -X....X - X....X" - "X - X.X - X.....X - X.....X -X...X - X...X" - "XX - X.X -X.......X- X.......X -X..X.X - X.X..X" - "X.X - X.X -XXXX.XXXX- XXXX.XXXX -X.X X.X - X.X X.X" - "X..X - X.X - X.X - X.X -XX X.X - X.X XX" - "X...X - X.X - X.X - XX X.X XX - X.X - X.X " - "X....X - X.X - X.X - X.X X.X X.X - X.X - X.X " - "X.....X - X.X - X.X - X..X X.X X..X - X.X - X.X " - "X......X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X XX-XX X.X " - "X.......X - X.X - X.X -X.....................X- X.X X.X-X.X X.X " - "X........X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X..X-X..X.X " - "X.........X -XXX.XXX- X.X - X..X X.X X..X - X...X-X...X " - "X..........X-X.....X- X.X - X.X X.X X.X - X....X-X....X " - "X......XXXXX-XXXXXXX- X.X - XX X.X XX - X.....X-X.....X " - "X...X..X --------- X.X - X.X - XXXXXXX-XXXXXXX " - "X..X X..X - -XXXX.XXXX- XXXX.XXXX ------------------------------------" - "X.X X..X - -X.......X- X.......X - XX XX - " - "XX X..X - - X.....X - X.....X - X.X X.X - " - " X..X - X...X - X...X - X..X X..X - " - " XX - X.X - X.X - X...XXXXXXXXXXXXX...X - " - "------------ - X - X -X.....................X- " - " ----------------------------------- X...XXXXXXXXXXXXX...X - " - " - X..X X..X - " - " - X.X X.X - " - " - XX XX - " -}; - -#ifdef __clang__ -#pragma clang diagnostic pop -#elif defined(__GNUC__) || defined(__GNUG__) -#pragma GCC diagnostic pop -#endif - -NK_GLOBAL unsigned char *nk__barrier; -NK_GLOBAL unsigned char *nk__barrier2; -NK_GLOBAL unsigned char *nk__barrier3; -NK_GLOBAL unsigned char *nk__barrier4; -NK_GLOBAL unsigned char *nk__dout; - -NK_INTERN unsigned int -nk_decompress_length(unsigned char *input) -{ - return (unsigned int)((input[8] << 24) + (input[9] << 16) + (input[10] << 8) + input[11]); -} -NK_INTERN void -nk__match(unsigned char *data, unsigned int length) -{ - /* INVERSE of memmove... write each byte before copying the next...*/ - NK_ASSERT (nk__dout + length <= nk__barrier); - if (nk__dout + length > nk__barrier) { nk__dout += length; return; } - if (data < nk__barrier4) { nk__dout = nk__barrier+1; return; } - while (length--) *nk__dout++ = *data++; -} -NK_INTERN void -nk__lit(unsigned char *data, unsigned int length) -{ - NK_ASSERT (nk__dout + length <= nk__barrier); - if (nk__dout + length > nk__barrier) { nk__dout += length; return; } - if (data < nk__barrier2) { nk__dout = nk__barrier+1; return; } - NK_MEMCPY(nk__dout, data, length); - nk__dout += length; -} -NK_INTERN unsigned char* -nk_decompress_token(unsigned char *i) -{ - #define nk__in2(x) ((i[x] << 8) + i[(x)+1]) - #define nk__in3(x) ((i[x] << 16) + nk__in2((x)+1)) - #define nk__in4(x) ((i[x] << 24) + nk__in3((x)+1)) - - if (*i >= 0x20) { /* use fewer if's for cases that expand small */ - if (*i >= 0x80) nk__match(nk__dout-i[1]-1, (unsigned int)i[0] - 0x80 + 1), i += 2; - else if (*i >= 0x40) nk__match(nk__dout-(nk__in2(0) - 0x4000 + 1), (unsigned int)i[2]+1), i += 3; - else /* *i >= 0x20 */ nk__lit(i+1, (unsigned int)i[0] - 0x20 + 1), i += 1 + (i[0] - 0x20 + 1); - } else { /* more ifs for cases that expand large, since overhead is amortized */ - if (*i >= 0x18) nk__match(nk__dout-(unsigned int)(nk__in3(0) - 0x180000 + 1), (unsigned int)i[3]+1), i += 4; - else if (*i >= 0x10) nk__match(nk__dout-(unsigned int)(nk__in3(0) - 0x100000 + 1), (unsigned int)nk__in2(3)+1), i += 5; - else if (*i >= 0x08) nk__lit(i+2, (unsigned int)nk__in2(0) - 0x0800 + 1), i += 2 + (nk__in2(0) - 0x0800 + 1); - else if (*i == 0x07) nk__lit(i+3, (unsigned int)nk__in2(1) + 1), i += 3 + (nk__in2(1) + 1); - else if (*i == 0x06) nk__match(nk__dout-(unsigned int)(nk__in3(1)+1), i[4]+1u), i += 5; - else if (*i == 0x04) nk__match(nk__dout-(unsigned int)(nk__in3(1)+1), (unsigned int)nk__in2(4)+1u), i += 6; - } - return i; -} -NK_INTERN unsigned int -nk_adler32(unsigned int adler32, unsigned char *buffer, unsigned int buflen) -{ - const unsigned long ADLER_MOD = 65521; - unsigned long s1 = adler32 & 0xffff, s2 = adler32 >> 16; - unsigned long blocklen, i; - - blocklen = buflen % 5552; - while (buflen) { - for (i=0; i + 7 < blocklen; i += 8) { - s1 += buffer[0]; s2 += s1; - s1 += buffer[1]; s2 += s1; - s1 += buffer[2]; s2 += s1; - s1 += buffer[3]; s2 += s1; - s1 += buffer[4]; s2 += s1; - s1 += buffer[5]; s2 += s1; - s1 += buffer[6]; s2 += s1; - s1 += buffer[7]; s2 += s1; - buffer += 8; - } - for (; i < blocklen; ++i) { - s1 += *buffer++; s2 += s1; - } - - s1 %= ADLER_MOD; s2 %= ADLER_MOD; - buflen -= (unsigned int)blocklen; - blocklen = 5552; - } - return (unsigned int)(s2 << 16) + (unsigned int)s1; -} -NK_INTERN unsigned int -nk_decompress(unsigned char *output, unsigned char *i, unsigned int length) -{ - unsigned int olen; - if (nk__in4(0) != 0x57bC0000) return 0; - if (nk__in4(4) != 0) return 0; /* error! stream is > 4GB */ - olen = nk_decompress_length(i); - nk__barrier2 = i; - nk__barrier3 = i+length; - nk__barrier = output + olen; - nk__barrier4 = output; - i += 16; - - nk__dout = output; - for (;;) { - unsigned char *old_i = i; - i = nk_decompress_token(i); - if (i == old_i) { - if (*i == 0x05 && i[1] == 0xfa) { - NK_ASSERT(nk__dout == output + olen); - if (nk__dout != output + olen) return 0; - if (nk_adler32(1, output, olen) != (unsigned int) nk__in4(2)) - return 0; - return olen; - } else { - NK_ASSERT(0); /* NOTREACHED */ - return 0; - } - } - NK_ASSERT(nk__dout <= output + olen); - if (nk__dout > output + olen) - return 0; - } -} -NK_INTERN unsigned int -nk_decode_85_byte(char c) -{ - return (unsigned int)((c >= '\\') ? c-36 : c-35); -} -NK_INTERN void -nk_decode_85(unsigned char* dst, const unsigned char* src) -{ - while (*src) - { - unsigned int tmp = - nk_decode_85_byte((char)src[0]) + - 85 * (nk_decode_85_byte((char)src[1]) + - 85 * (nk_decode_85_byte((char)src[2]) + - 85 * (nk_decode_85_byte((char)src[3]) + - 85 * nk_decode_85_byte((char)src[4])))); - - /* we can't assume little-endianess. */ - dst[0] = (unsigned char)((tmp >> 0) & 0xFF); - dst[1] = (unsigned char)((tmp >> 8) & 0xFF); - dst[2] = (unsigned char)((tmp >> 16) & 0xFF); - dst[3] = (unsigned char)((tmp >> 24) & 0xFF); - - src += 5; - dst += 4; - } -} - -/* ------------------------------------------------------------- - * - * FONT ATLAS - * - * --------------------------------------------------------------*/ -NK_API struct nk_font_config -nk_font_config(float pixel_height) -{ - struct nk_font_config cfg; - nk_zero_struct(cfg); - cfg.ttf_blob = 0; - cfg.ttf_size = 0; - cfg.ttf_data_owned_by_atlas = 0; - cfg.size = pixel_height; - cfg.oversample_h = 3; - cfg.oversample_v = 1; - cfg.pixel_snap = 0; - cfg.coord_type = NK_COORD_UV; - cfg.spacing = nk_vec2(0,0); - cfg.range = nk_font_default_glyph_ranges(); - cfg.merge_mode = 0; - cfg.fallback_glyph = '?'; - cfg.font = 0; - cfg.n = 0; - return cfg; -} -#ifdef NK_INCLUDE_DEFAULT_ALLOCATOR -NK_API void -nk_font_atlas_init_default(struct nk_font_atlas *atlas) -{ - NK_ASSERT(atlas); - if (!atlas) return; - nk_zero_struct(*atlas); - atlas->temporary.userdata.ptr = 0; - atlas->temporary.alloc = nk_malloc; - atlas->temporary.free = nk_mfree; - atlas->permanent.userdata.ptr = 0; - atlas->permanent.alloc = nk_malloc; - atlas->permanent.free = nk_mfree; -} -#endif -NK_API void -nk_font_atlas_init(struct nk_font_atlas *atlas, struct nk_allocator *alloc) -{ - NK_ASSERT(atlas); - NK_ASSERT(alloc); - if (!atlas || !alloc) return; - nk_zero_struct(*atlas); - atlas->permanent = *alloc; - atlas->temporary = *alloc; -} -NK_API void -nk_font_atlas_init_custom(struct nk_font_atlas *atlas, - struct nk_allocator *permanent, struct nk_allocator *temporary) -{ - NK_ASSERT(atlas); - NK_ASSERT(permanent); - NK_ASSERT(temporary); - if (!atlas || !permanent || !temporary) return; - nk_zero_struct(*atlas); - atlas->permanent = *permanent; - atlas->temporary = *temporary; -} -NK_API void -nk_font_atlas_begin(struct nk_font_atlas *atlas) -{ - NK_ASSERT(atlas); - NK_ASSERT(atlas->temporary.alloc && atlas->temporary.free); - NK_ASSERT(atlas->permanent.alloc && atlas->permanent.free); - if (!atlas || !atlas->permanent.alloc || !atlas->permanent.free || - !atlas->temporary.alloc || !atlas->temporary.free) return; - if (atlas->glyphs) { - atlas->permanent.free(atlas->permanent.userdata, atlas->glyphs); - atlas->glyphs = 0; - } - if (atlas->pixel) { - atlas->permanent.free(atlas->permanent.userdata, atlas->pixel); - atlas->pixel = 0; - } -} -NK_API struct nk_font* -nk_font_atlas_add(struct nk_font_atlas *atlas, const struct nk_font_config *config) -{ - struct nk_font *font = 0; - struct nk_font_config *cfg; - - NK_ASSERT(atlas); - NK_ASSERT(atlas->permanent.alloc); - NK_ASSERT(atlas->permanent.free); - NK_ASSERT(atlas->temporary.alloc); - NK_ASSERT(atlas->temporary.free); - - NK_ASSERT(config); - NK_ASSERT(config->ttf_blob); - NK_ASSERT(config->ttf_size); - NK_ASSERT(config->size > 0.0f); - - if (!atlas || !config || !config->ttf_blob || !config->ttf_size || config->size <= 0.0f|| - !atlas->permanent.alloc || !atlas->permanent.free || - !atlas->temporary.alloc || !atlas->temporary.free) - return 0; - - /* allocate font config */ - cfg = (struct nk_font_config*) - atlas->permanent.alloc(atlas->permanent.userdata,0, sizeof(struct nk_font_config)); - NK_MEMCPY(cfg, config, sizeof(*config)); - cfg->n = cfg; - cfg->p = cfg; - - if (!config->merge_mode) { - /* insert font config into list */ - if (!atlas->config) { - atlas->config = cfg; - cfg->next = 0; - } else { - struct nk_font_config *i = atlas->config; - while (i->next) i = i->next; - i->next = cfg; - cfg->next = 0; - } - /* allocate new font */ - font = (struct nk_font*) - atlas->permanent.alloc(atlas->permanent.userdata,0, sizeof(struct nk_font)); - NK_ASSERT(font); - nk_zero(font, sizeof(*font)); - if (!font) return 0; - font->config = cfg; - - /* insert font into list */ - if (!atlas->fonts) { - atlas->fonts = font; - font->next = 0; - } else { - struct nk_font *i = atlas->fonts; - while (i->next) i = i->next; - i->next = font; - font->next = 0; - } - cfg->font = &font->info; - } else { - /* extend previously added font */ - struct nk_font *f = 0; - struct nk_font_config *c = 0; - NK_ASSERT(atlas->font_num); - f = atlas->fonts; - c = f->config; - cfg->font = &f->info; - - cfg->n = c; - cfg->p = c->p; - c->p->n = cfg; - c->p = cfg; - } - /* create own copy of .TTF font blob */ - if (!config->ttf_data_owned_by_atlas) { - cfg->ttf_blob = atlas->permanent.alloc(atlas->permanent.userdata,0, cfg->ttf_size); - NK_ASSERT(cfg->ttf_blob); - if (!cfg->ttf_blob) { - atlas->font_num++; - return 0; - } - NK_MEMCPY(cfg->ttf_blob, config->ttf_blob, cfg->ttf_size); - cfg->ttf_data_owned_by_atlas = 1; - } - atlas->font_num++; - return font; -} -NK_API struct nk_font* -nk_font_atlas_add_from_memory(struct nk_font_atlas *atlas, void *memory, - nk_size size, float height, const struct nk_font_config *config) -{ - struct nk_font_config cfg; - NK_ASSERT(memory); - NK_ASSERT(size); - - NK_ASSERT(atlas); - NK_ASSERT(atlas->temporary.alloc); - NK_ASSERT(atlas->temporary.free); - NK_ASSERT(atlas->permanent.alloc); - NK_ASSERT(atlas->permanent.free); - if (!atlas || !atlas->temporary.alloc || !atlas->temporary.free || !memory || !size || - !atlas->permanent.alloc || !atlas->permanent.free) - return 0; - - cfg = (config) ? *config: nk_font_config(height); - cfg.ttf_blob = memory; - cfg.ttf_size = size; - cfg.size = height; - cfg.ttf_data_owned_by_atlas = 0; - return nk_font_atlas_add(atlas, &cfg); -} -#ifdef NK_INCLUDE_STANDARD_IO -NK_API struct nk_font* -nk_font_atlas_add_from_file(struct nk_font_atlas *atlas, const char *file_path, - float height, const struct nk_font_config *config) -{ - nk_size size; - char *memory; - struct nk_font_config cfg; - - NK_ASSERT(atlas); - NK_ASSERT(atlas->temporary.alloc); - NK_ASSERT(atlas->temporary.free); - NK_ASSERT(atlas->permanent.alloc); - NK_ASSERT(atlas->permanent.free); - - if (!atlas || !file_path) return 0; - memory = nk_file_load(file_path, &size, &atlas->permanent); - if (!memory) return 0; - - cfg = (config) ? *config: nk_font_config(height); - cfg.ttf_blob = memory; - cfg.ttf_size = size; - cfg.size = height; - cfg.ttf_data_owned_by_atlas = 1; - return nk_font_atlas_add(atlas, &cfg); -} -#endif -NK_API struct nk_font* -nk_font_atlas_add_compressed(struct nk_font_atlas *atlas, - void *compressed_data, nk_size compressed_size, float height, - const struct nk_font_config *config) -{ - unsigned int decompressed_size; - void *decompressed_data; - struct nk_font_config cfg; - - NK_ASSERT(atlas); - NK_ASSERT(atlas->temporary.alloc); - NK_ASSERT(atlas->temporary.free); - NK_ASSERT(atlas->permanent.alloc); - NK_ASSERT(atlas->permanent.free); - - NK_ASSERT(compressed_data); - NK_ASSERT(compressed_size); - if (!atlas || !compressed_data || !atlas->temporary.alloc || !atlas->temporary.free || - !atlas->permanent.alloc || !atlas->permanent.free) - return 0; - - decompressed_size = nk_decompress_length((unsigned char*)compressed_data); - decompressed_data = atlas->permanent.alloc(atlas->permanent.userdata,0,decompressed_size); - NK_ASSERT(decompressed_data); - if (!decompressed_data) return 0; - nk_decompress((unsigned char*)decompressed_data, (unsigned char*)compressed_data, - (unsigned int)compressed_size); - - cfg = (config) ? *config: nk_font_config(height); - cfg.ttf_blob = decompressed_data; - cfg.ttf_size = decompressed_size; - cfg.size = height; - cfg.ttf_data_owned_by_atlas = 1; - return nk_font_atlas_add(atlas, &cfg); -} -NK_API struct nk_font* -nk_font_atlas_add_compressed_base85(struct nk_font_atlas *atlas, - const char *data_base85, float height, const struct nk_font_config *config) -{ - int compressed_size; - void *compressed_data; - struct nk_font *font; - - NK_ASSERT(atlas); - NK_ASSERT(atlas->temporary.alloc); - NK_ASSERT(atlas->temporary.free); - NK_ASSERT(atlas->permanent.alloc); - NK_ASSERT(atlas->permanent.free); - - NK_ASSERT(data_base85); - if (!atlas || !data_base85 || !atlas->temporary.alloc || !atlas->temporary.free || - !atlas->permanent.alloc || !atlas->permanent.free) - return 0; - - compressed_size = (((int)nk_strlen(data_base85) + 4) / 5) * 4; - compressed_data = atlas->temporary.alloc(atlas->temporary.userdata,0, (nk_size)compressed_size); - NK_ASSERT(compressed_data); - if (!compressed_data) return 0; - nk_decode_85((unsigned char*)compressed_data, (const unsigned char*)data_base85); - font = nk_font_atlas_add_compressed(atlas, compressed_data, - (nk_size)compressed_size, height, config); - atlas->temporary.free(atlas->temporary.userdata, compressed_data); - return font; -} - -#ifdef NK_INCLUDE_DEFAULT_FONT -NK_API struct nk_font* -nk_font_atlas_add_default(struct nk_font_atlas *atlas, - float pixel_height, const struct nk_font_config *config) -{ - NK_ASSERT(atlas); - NK_ASSERT(atlas->temporary.alloc); - NK_ASSERT(atlas->temporary.free); - NK_ASSERT(atlas->permanent.alloc); - NK_ASSERT(atlas->permanent.free); - return nk_font_atlas_add_compressed_base85(atlas, - nk_proggy_clean_ttf_compressed_data_base85, pixel_height, config); -} -#endif -NK_API const void* -nk_font_atlas_bake(struct nk_font_atlas *atlas, int *width, int *height, - enum nk_font_atlas_format fmt) -{ - int i = 0; - void *tmp = 0; - nk_size tmp_size, img_size; - struct nk_font *font_iter; - struct nk_font_baker *baker; - - NK_ASSERT(atlas); - NK_ASSERT(atlas->temporary.alloc); - NK_ASSERT(atlas->temporary.free); - NK_ASSERT(atlas->permanent.alloc); - NK_ASSERT(atlas->permanent.free); - - NK_ASSERT(width); - NK_ASSERT(height); - if (!atlas || !width || !height || - !atlas->temporary.alloc || !atlas->temporary.free || - !atlas->permanent.alloc || !atlas->permanent.free) - return 0; - -#ifdef NK_INCLUDE_DEFAULT_FONT - /* no font added so just use default font */ - if (!atlas->font_num) - atlas->default_font = nk_font_atlas_add_default(atlas, 13.0f, 0); -#endif - NK_ASSERT(atlas->font_num); - if (!atlas->font_num) return 0; - - /* allocate temporary baker memory required for the baking process */ - nk_font_baker_memory(&tmp_size, &atlas->glyph_count, atlas->config, atlas->font_num); - tmp = atlas->temporary.alloc(atlas->temporary.userdata,0, tmp_size); - NK_ASSERT(tmp); - if (!tmp) goto failed; - - /* allocate glyph memory for all fonts */ - baker = nk_font_baker(tmp, atlas->glyph_count, atlas->font_num, &atlas->temporary); - atlas->glyphs = (struct nk_font_glyph*)atlas->permanent.alloc( - atlas->permanent.userdata,0, sizeof(struct nk_font_glyph)*(nk_size)atlas->glyph_count); - NK_ASSERT(atlas->glyphs); - if (!atlas->glyphs) - goto failed; - - /* pack all glyphs into a tight fit space */ - atlas->custom.w = (NK_CURSOR_DATA_W*2)+1; - atlas->custom.h = NK_CURSOR_DATA_H + 1; - if (!nk_font_bake_pack(baker, &img_size, width, height, &atlas->custom, - atlas->config, atlas->font_num, &atlas->temporary)) - goto failed; - - /* allocate memory for the baked image font atlas */ - atlas->pixel = atlas->temporary.alloc(atlas->temporary.userdata,0, img_size); - NK_ASSERT(atlas->pixel); - if (!atlas->pixel) - goto failed; - - /* bake glyphs and custom white pixel into image */ - nk_font_bake(baker, atlas->pixel, *width, *height, - atlas->glyphs, atlas->glyph_count, atlas->config, atlas->font_num); - nk_font_bake_custom_data(atlas->pixel, *width, *height, atlas->custom, - nk_custom_cursor_data, NK_CURSOR_DATA_W, NK_CURSOR_DATA_H, '.', 'X'); - - if (fmt == NK_FONT_ATLAS_RGBA32) { - /* convert alpha8 image into rgba32 image */ - void *img_rgba = atlas->temporary.alloc(atlas->temporary.userdata,0, - (nk_size)(*width * *height * 4)); - NK_ASSERT(img_rgba); - if (!img_rgba) goto failed; - nk_font_bake_convert(img_rgba, *width, *height, atlas->pixel); - atlas->temporary.free(atlas->temporary.userdata, atlas->pixel); - atlas->pixel = img_rgba; - } - atlas->tex_width = *width; - atlas->tex_height = *height; - - /* initialize each font */ - for (font_iter = atlas->fonts; font_iter; font_iter = font_iter->next) { - struct nk_font *font = font_iter; - struct nk_font_config *config = font->config; - nk_font_init(font, config->size, config->fallback_glyph, atlas->glyphs, - config->font, nk_handle_ptr(0)); - } - - /* initialize each cursor */ - {NK_STORAGE const struct nk_vec2 nk_cursor_data[NK_CURSOR_COUNT][3] = { - /* Pos Size Offset */ - {{ 0, 3}, {12,19}, { 0, 0}}, - {{13, 0}, { 7,16}, { 4, 8}}, - {{31, 0}, {23,23}, {11,11}}, - {{21, 0}, { 9, 23}, { 5,11}}, - {{55,18}, {23, 9}, {11, 5}}, - {{73, 0}, {17,17}, { 9, 9}}, - {{55, 0}, {17,17}, { 9, 9}} - }; - for (i = 0; i < NK_CURSOR_COUNT; ++i) { - struct nk_cursor *cursor = &atlas->cursors[i]; - cursor->img.w = (unsigned short)*width; - cursor->img.h = (unsigned short)*height; - cursor->img.region[0] = (unsigned short)(atlas->custom.x + nk_cursor_data[i][0].x); - cursor->img.region[1] = (unsigned short)(atlas->custom.y + nk_cursor_data[i][0].y); - cursor->img.region[2] = (unsigned short)nk_cursor_data[i][1].x; - cursor->img.region[3] = (unsigned short)nk_cursor_data[i][1].y; - cursor->size = nk_cursor_data[i][1]; - cursor->offset = nk_cursor_data[i][2]; - }} - /* free temporary memory */ - atlas->temporary.free(atlas->temporary.userdata, tmp); - return atlas->pixel; - -failed: - /* error so cleanup all memory */ - if (tmp) atlas->temporary.free(atlas->temporary.userdata, tmp); - if (atlas->glyphs) { - atlas->permanent.free(atlas->permanent.userdata, atlas->glyphs); - atlas->glyphs = 0; - } - if (atlas->pixel) { - atlas->temporary.free(atlas->temporary.userdata, atlas->pixel); - atlas->pixel = 0; - } - return 0; -} -NK_API void -nk_font_atlas_end(struct nk_font_atlas *atlas, nk_handle texture, - struct nk_draw_null_texture *null) -{ - int i = 0; - struct nk_font *font_iter; - NK_ASSERT(atlas); - if (!atlas) { - if (!null) return; - null->texture = texture; - null->uv = nk_vec2(0.5f,0.5f); - } - if (null) { - null->texture = texture; - null->uv.x = (atlas->custom.x + 0.5f)/(float)atlas->tex_width; - null->uv.y = (atlas->custom.y + 0.5f)/(float)atlas->tex_height; - } - for (font_iter = atlas->fonts; font_iter; font_iter = font_iter->next) { - font_iter->texture = texture; -#ifdef NK_INCLUDE_VERTEX_BUFFER_OUTPUT - font_iter->handle.texture = texture; -#endif - } - for (i = 0; i < NK_CURSOR_COUNT; ++i) - atlas->cursors[i].img.handle = texture; - - atlas->temporary.free(atlas->temporary.userdata, atlas->pixel); - atlas->pixel = 0; - atlas->tex_width = 0; - atlas->tex_height = 0; - atlas->custom.x = 0; - atlas->custom.y = 0; - atlas->custom.w = 0; - atlas->custom.h = 0; -} -NK_API void -nk_font_atlas_cleanup(struct nk_font_atlas *atlas) -{ - NK_ASSERT(atlas); - NK_ASSERT(atlas->temporary.alloc); - NK_ASSERT(atlas->temporary.free); - NK_ASSERT(atlas->permanent.alloc); - NK_ASSERT(atlas->permanent.free); - if (!atlas || !atlas->permanent.alloc || !atlas->permanent.free) return; - if (atlas->config) { - struct nk_font_config *iter; - for (iter = atlas->config; iter; iter = iter->next) { - struct nk_font_config *i; - for (i = iter->n; i != iter; i = i->n) { - atlas->permanent.free(atlas->permanent.userdata, i->ttf_blob); - i->ttf_blob = 0; - } - atlas->permanent.free(atlas->permanent.userdata, iter->ttf_blob); - iter->ttf_blob = 0; - } - } -} -NK_API void -nk_font_atlas_clear(struct nk_font_atlas *atlas) -{ - NK_ASSERT(atlas); - NK_ASSERT(atlas->temporary.alloc); - NK_ASSERT(atlas->temporary.free); - NK_ASSERT(atlas->permanent.alloc); - NK_ASSERT(atlas->permanent.free); - if (!atlas || !atlas->permanent.alloc || !atlas->permanent.free) return; - - if (atlas->config) { - struct nk_font_config *iter, *next; - for (iter = atlas->config; iter; iter = next) { - struct nk_font_config *i, *n; - for (i = iter->n; i != iter; i = n) { - n = i->n; - if (i->ttf_blob) - atlas->permanent.free(atlas->permanent.userdata, i->ttf_blob); - atlas->permanent.free(atlas->permanent.userdata, i); - } - next = iter->next; - if (i->ttf_blob) - atlas->permanent.free(atlas->permanent.userdata, iter->ttf_blob); - atlas->permanent.free(atlas->permanent.userdata, iter); - } - atlas->config = 0; - } - if (atlas->fonts) { - struct nk_font *iter, *next; - for (iter = atlas->fonts; iter; iter = next) { - next = iter->next; - atlas->permanent.free(atlas->permanent.userdata, iter); - } - atlas->fonts = 0; - } - if (atlas->glyphs) - atlas->permanent.free(atlas->permanent.userdata, atlas->glyphs); - nk_zero_struct(*atlas); -} -#endif - - - - - -/* =============================================================== - * - * INPUT - * - * ===============================================================*/ -NK_API void -nk_input_begin(struct nk_context *ctx) -{ - int i; - struct nk_input *in; - NK_ASSERT(ctx); - if (!ctx) return; - in = &ctx->input; - for (i = 0; i < NK_BUTTON_MAX; ++i) - in->mouse.buttons[i].clicked = 0; - - in->keyboard.text_len = 0; - in->mouse.scroll_delta = nk_vec2(0,0); - in->mouse.prev.x = in->mouse.pos.x; - in->mouse.prev.y = in->mouse.pos.y; - in->mouse.delta.x = 0; - in->mouse.delta.y = 0; - for (i = 0; i < NK_KEY_MAX; i++) - in->keyboard.keys[i].clicked = 0; -} -NK_API void -nk_input_end(struct nk_context *ctx) -{ - struct nk_input *in; - NK_ASSERT(ctx); - if (!ctx) return; - in = &ctx->input; - if (in->mouse.grab) - in->mouse.grab = 0; - if (in->mouse.ungrab) { - in->mouse.grabbed = 0; - in->mouse.ungrab = 0; - in->mouse.grab = 0; - } -} -NK_API void -nk_input_motion(struct nk_context *ctx, int x, int y) -{ - struct nk_input *in; - NK_ASSERT(ctx); - if (!ctx) return; - in = &ctx->input; - in->mouse.pos.x = (float)x; - in->mouse.pos.y = (float)y; - in->mouse.delta.x = in->mouse.pos.x - in->mouse.prev.x; - in->mouse.delta.y = in->mouse.pos.y - in->mouse.prev.y; -} -NK_API void -nk_input_key(struct nk_context *ctx, enum nk_keys key, int down) -{ - struct nk_input *in; - NK_ASSERT(ctx); - if (!ctx) return; - in = &ctx->input; - if (in->keyboard.keys[key].down != down) - in->keyboard.keys[key].clicked++; - in->keyboard.keys[key].down = down; -} -NK_API void -nk_input_button(struct nk_context *ctx, enum nk_buttons id, int x, int y, int down) -{ - struct nk_mouse_button *btn; - struct nk_input *in; - NK_ASSERT(ctx); - if (!ctx) return; - in = &ctx->input; - if (in->mouse.buttons[id].down == down) return; - - btn = &in->mouse.buttons[id]; - btn->clicked_pos.x = (float)x; - btn->clicked_pos.y = (float)y; - btn->down = down; - btn->clicked++; -} -NK_API void -nk_input_scroll(struct nk_context *ctx, struct nk_vec2 val) -{ - NK_ASSERT(ctx); - if (!ctx) return; - ctx->input.mouse.scroll_delta.x += val.x; - ctx->input.mouse.scroll_delta.y += val.y; -} -NK_API void -nk_input_glyph(struct nk_context *ctx, const nk_glyph glyph) -{ - int len = 0; - nk_rune unicode; - struct nk_input *in; - - NK_ASSERT(ctx); - if (!ctx) return; - in = &ctx->input; - - len = nk_utf_decode(glyph, &unicode, NK_UTF_SIZE); - if (len && ((in->keyboard.text_len + len) < NK_INPUT_MAX)) { - nk_utf_encode(unicode, &in->keyboard.text[in->keyboard.text_len], - NK_INPUT_MAX - in->keyboard.text_len); - in->keyboard.text_len += len; - } -} -NK_API void -nk_input_char(struct nk_context *ctx, char c) -{ - nk_glyph glyph; - NK_ASSERT(ctx); - if (!ctx) return; - glyph[0] = c; - nk_input_glyph(ctx, glyph); -} -NK_API void -nk_input_unicode(struct nk_context *ctx, nk_rune unicode) -{ - nk_glyph rune; - NK_ASSERT(ctx); - if (!ctx) return; - nk_utf_encode(unicode, rune, NK_UTF_SIZE); - nk_input_glyph(ctx, rune); -} -NK_API int -nk_input_has_mouse_click(const struct nk_input *i, enum nk_buttons id) -{ - const struct nk_mouse_button *btn; - if (!i) return nk_false; - btn = &i->mouse.buttons[id]; - return (btn->clicked && btn->down == nk_false) ? nk_true : nk_false; -} -NK_API int -nk_input_has_mouse_click_in_rect(const struct nk_input *i, enum nk_buttons id, - struct nk_rect b) -{ - const struct nk_mouse_button *btn; - if (!i) return nk_false; - btn = &i->mouse.buttons[id]; - if (!NK_INBOX(btn->clicked_pos.x,btn->clicked_pos.y,b.x,b.y,b.w,b.h)) - return nk_false; - return nk_true; -} -NK_API int -nk_input_has_mouse_click_down_in_rect(const struct nk_input *i, enum nk_buttons id, - struct nk_rect b, int down) -{ - const struct nk_mouse_button *btn; - if (!i) return nk_false; - btn = &i->mouse.buttons[id]; - return nk_input_has_mouse_click_in_rect(i, id, b) && (btn->down == down); -} -NK_API int -nk_input_is_mouse_click_in_rect(const struct nk_input *i, enum nk_buttons id, - struct nk_rect b) -{ - const struct nk_mouse_button *btn; - if (!i) return nk_false; - btn = &i->mouse.buttons[id]; - return (nk_input_has_mouse_click_down_in_rect(i, id, b, nk_false) && - btn->clicked) ? nk_true : nk_false; -} -NK_API int -nk_input_is_mouse_click_down_in_rect(const struct nk_input *i, enum nk_buttons id, - struct nk_rect b, int down) -{ - const struct nk_mouse_button *btn; - if (!i) return nk_false; - btn = &i->mouse.buttons[id]; - return (nk_input_has_mouse_click_down_in_rect(i, id, b, down) && - btn->clicked) ? nk_true : nk_false; -} -NK_API int -nk_input_any_mouse_click_in_rect(const struct nk_input *in, struct nk_rect b) -{ - int i, down = 0; - for (i = 0; i < NK_BUTTON_MAX; ++i) - down = down || nk_input_is_mouse_click_in_rect(in, (enum nk_buttons)i, b); - return down; -} -NK_API int -nk_input_is_mouse_hovering_rect(const struct nk_input *i, struct nk_rect rect) -{ - if (!i) return nk_false; - return NK_INBOX(i->mouse.pos.x, i->mouse.pos.y, rect.x, rect.y, rect.w, rect.h); -} -NK_API int -nk_input_is_mouse_prev_hovering_rect(const struct nk_input *i, struct nk_rect rect) -{ - if (!i) return nk_false; - return NK_INBOX(i->mouse.prev.x, i->mouse.prev.y, rect.x, rect.y, rect.w, rect.h); -} -NK_API int -nk_input_mouse_clicked(const struct nk_input *i, enum nk_buttons id, struct nk_rect rect) -{ - if (!i) return nk_false; - if (!nk_input_is_mouse_hovering_rect(i, rect)) return nk_false; - return nk_input_is_mouse_click_in_rect(i, id, rect); -} -NK_API int -nk_input_is_mouse_down(const struct nk_input *i, enum nk_buttons id) -{ - if (!i) return nk_false; - return i->mouse.buttons[id].down; -} -NK_API int -nk_input_is_mouse_pressed(const struct nk_input *i, enum nk_buttons id) -{ - const struct nk_mouse_button *b; - if (!i) return nk_false; - b = &i->mouse.buttons[id]; - if (b->down && b->clicked) - return nk_true; - return nk_false; -} -NK_API int -nk_input_is_mouse_released(const struct nk_input *i, enum nk_buttons id) -{ - if (!i) return nk_false; - return (!i->mouse.buttons[id].down && i->mouse.buttons[id].clicked); -} -NK_API int -nk_input_is_key_pressed(const struct nk_input *i, enum nk_keys key) -{ - const struct nk_key *k; - if (!i) return nk_false; - k = &i->keyboard.keys[key]; - if ((k->down && k->clicked) || (!k->down && k->clicked >= 2)) - return nk_true; - return nk_false; -} -NK_API int -nk_input_is_key_released(const struct nk_input *i, enum nk_keys key) -{ - const struct nk_key *k; - if (!i) return nk_false; - k = &i->keyboard.keys[key]; - if ((!k->down && k->clicked) || (k->down && k->clicked >= 2)) - return nk_true; - return nk_false; -} -NK_API int -nk_input_is_key_down(const struct nk_input *i, enum nk_keys key) -{ - const struct nk_key *k; - if (!i) return nk_false; - k = &i->keyboard.keys[key]; - if (k->down) return nk_true; - return nk_false; -} - - - - - -/* =============================================================== - * - * STYLE - * - * ===============================================================*/ -NK_API void nk_style_default(struct nk_context *ctx){nk_style_from_table(ctx, 0);} -#define NK_COLOR_MAP(NK_COLOR)\ - NK_COLOR(NK_COLOR_TEXT, 175,175,175,255) \ - NK_COLOR(NK_COLOR_WINDOW, 45, 45, 45, 255) \ - NK_COLOR(NK_COLOR_HEADER, 40, 40, 40, 255) \ - NK_COLOR(NK_COLOR_BORDER, 65, 65, 65, 255) \ - NK_COLOR(NK_COLOR_BUTTON, 50, 50, 50, 255) \ - NK_COLOR(NK_COLOR_BUTTON_HOVER, 40, 40, 40, 255) \ - NK_COLOR(NK_COLOR_BUTTON_ACTIVE, 35, 35, 35, 255) \ - NK_COLOR(NK_COLOR_TOGGLE, 100,100,100,255) \ - NK_COLOR(NK_COLOR_TOGGLE_HOVER, 120,120,120,255) \ - NK_COLOR(NK_COLOR_TOGGLE_CURSOR, 45, 45, 45, 255) \ - NK_COLOR(NK_COLOR_SELECT, 45, 45, 45, 255) \ - NK_COLOR(NK_COLOR_SELECT_ACTIVE, 35, 35, 35,255) \ - NK_COLOR(NK_COLOR_SLIDER, 38, 38, 38, 255) \ - NK_COLOR(NK_COLOR_SLIDER_CURSOR, 100,100,100,255) \ - NK_COLOR(NK_COLOR_SLIDER_CURSOR_HOVER, 120,120,120,255) \ - NK_COLOR(NK_COLOR_SLIDER_CURSOR_ACTIVE, 150,150,150,255) \ - NK_COLOR(NK_COLOR_PROPERTY, 38, 38, 38, 255) \ - NK_COLOR(NK_COLOR_EDIT, 38, 38, 38, 255) \ - NK_COLOR(NK_COLOR_EDIT_CURSOR, 175,175,175,255) \ - NK_COLOR(NK_COLOR_COMBO, 45, 45, 45, 255) \ - NK_COLOR(NK_COLOR_CHART, 120,120,120,255) \ - NK_COLOR(NK_COLOR_CHART_COLOR, 45, 45, 45, 255) \ - NK_COLOR(NK_COLOR_CHART_COLOR_HIGHLIGHT, 255, 0, 0, 255) \ - NK_COLOR(NK_COLOR_SCROLLBAR, 40, 40, 40, 255) \ - NK_COLOR(NK_COLOR_SCROLLBAR_CURSOR, 100,100,100,255) \ - NK_COLOR(NK_COLOR_SCROLLBAR_CURSOR_HOVER, 120,120,120,255) \ - NK_COLOR(NK_COLOR_SCROLLBAR_CURSOR_ACTIVE, 150,150,150,255) \ - NK_COLOR(NK_COLOR_TAB_HEADER, 40, 40, 40,255) - -NK_GLOBAL const struct nk_color -nk_default_color_style[NK_COLOR_COUNT] = { -#define NK_COLOR(a,b,c,d,e) {b,c,d,e}, - NK_COLOR_MAP(NK_COLOR) -#undef NK_COLOR -}; -NK_GLOBAL const char *nk_color_names[NK_COLOR_COUNT] = { -#define NK_COLOR(a,b,c,d,e) #a, - NK_COLOR_MAP(NK_COLOR) -#undef NK_COLOR -}; - -NK_API const char* -nk_style_get_color_by_name(enum nk_style_colors c) -{ - return nk_color_names[c]; -} -NK_API struct nk_style_item -nk_style_item_image(struct nk_image img) -{ - struct nk_style_item i; - i.type = NK_STYLE_ITEM_IMAGE; - i.data.image = img; - return i; -} -NK_API struct nk_style_item -nk_style_item_color(struct nk_color col) -{ - struct nk_style_item i; - i.type = NK_STYLE_ITEM_COLOR; - i.data.color = col; - return i; -} -NK_API struct nk_style_item -nk_style_item_hide(void) -{ - struct nk_style_item i; - i.type = NK_STYLE_ITEM_COLOR; - i.data.color = nk_rgba(0,0,0,0); - return i; -} -NK_API void -nk_style_from_table(struct nk_context *ctx, const struct nk_color *table) -{ - struct nk_style *style; - struct nk_style_text *text; - struct nk_style_button *button; - struct nk_style_toggle *toggle; - struct nk_style_selectable *select; - struct nk_style_slider *slider; - struct nk_style_progress *prog; - struct nk_style_scrollbar *scroll; - struct nk_style_edit *edit; - struct nk_style_property *property; - struct nk_style_combo *combo; - struct nk_style_chart *chart; - struct nk_style_tab *tab; - struct nk_style_window *win; - - NK_ASSERT(ctx); - if (!ctx) return; - style = &ctx->style; - table = (!table) ? nk_default_color_style: table; - - /* default text */ - text = &style->text; - text->color = table[NK_COLOR_TEXT]; - text->padding = nk_vec2(0,0); - - /* default button */ - button = &style->button; - nk_zero_struct(*button); - button->normal = nk_style_item_color(table[NK_COLOR_BUTTON]); - button->hover = nk_style_item_color(table[NK_COLOR_BUTTON_HOVER]); - button->active = nk_style_item_color(table[NK_COLOR_BUTTON_ACTIVE]); - button->border_color = table[NK_COLOR_BORDER]; - button->text_background = table[NK_COLOR_BUTTON]; - button->text_normal = table[NK_COLOR_TEXT]; - button->text_hover = table[NK_COLOR_TEXT]; - button->text_active = table[NK_COLOR_TEXT]; - button->padding = nk_vec2(2.0f,2.0f); - button->image_padding = nk_vec2(0.0f,0.0f); - button->touch_padding = nk_vec2(0.0f, 0.0f); - button->userdata = nk_handle_ptr(0); - button->text_alignment = NK_TEXT_CENTERED; - button->border = 1.0f; - button->rounding = 4.0f; - button->draw_begin = 0; - button->draw_end = 0; - - /* contextual button */ - button = &style->contextual_button; - nk_zero_struct(*button); - button->normal = nk_style_item_color(table[NK_COLOR_WINDOW]); - button->hover = nk_style_item_color(table[NK_COLOR_BUTTON_HOVER]); - button->active = nk_style_item_color(table[NK_COLOR_BUTTON_ACTIVE]); - button->border_color = table[NK_COLOR_WINDOW]; - button->text_background = table[NK_COLOR_WINDOW]; - button->text_normal = table[NK_COLOR_TEXT]; - button->text_hover = table[NK_COLOR_TEXT]; - button->text_active = table[NK_COLOR_TEXT]; - button->padding = nk_vec2(2.0f,2.0f); - button->touch_padding = nk_vec2(0.0f,0.0f); - button->userdata = nk_handle_ptr(0); - button->text_alignment = NK_TEXT_CENTERED; - button->border = 0.0f; - button->rounding = 0.0f; - button->draw_begin = 0; - button->draw_end = 0; - - /* menu button */ - button = &style->menu_button; - nk_zero_struct(*button); - button->normal = nk_style_item_color(table[NK_COLOR_WINDOW]); - button->hover = nk_style_item_color(table[NK_COLOR_WINDOW]); - button->active = nk_style_item_color(table[NK_COLOR_WINDOW]); - button->border_color = table[NK_COLOR_WINDOW]; - button->text_background = table[NK_COLOR_WINDOW]; - button->text_normal = table[NK_COLOR_TEXT]; - button->text_hover = table[NK_COLOR_TEXT]; - button->text_active = table[NK_COLOR_TEXT]; - button->padding = nk_vec2(2.0f,2.0f); - button->touch_padding = nk_vec2(0.0f,0.0f); - button->userdata = nk_handle_ptr(0); - button->text_alignment = NK_TEXT_CENTERED; - button->border = 0.0f; - button->rounding = 1.0f; - button->draw_begin = 0; - button->draw_end = 0; - - /* checkbox toggle */ - toggle = &style->checkbox; - nk_zero_struct(*toggle); - toggle->normal = nk_style_item_color(table[NK_COLOR_TOGGLE]); - toggle->hover = nk_style_item_color(table[NK_COLOR_TOGGLE_HOVER]); - toggle->active = nk_style_item_color(table[NK_COLOR_TOGGLE_HOVER]); - toggle->cursor_normal = nk_style_item_color(table[NK_COLOR_TOGGLE_CURSOR]); - toggle->cursor_hover = nk_style_item_color(table[NK_COLOR_TOGGLE_CURSOR]); - toggle->userdata = nk_handle_ptr(0); - toggle->text_background = table[NK_COLOR_WINDOW]; - toggle->text_normal = table[NK_COLOR_TEXT]; - toggle->text_hover = table[NK_COLOR_TEXT]; - toggle->text_active = table[NK_COLOR_TEXT]; - toggle->padding = nk_vec2(2.0f, 2.0f); - toggle->touch_padding = nk_vec2(0,0); - toggle->border_color = nk_rgba(0,0,0,0); - toggle->border = 0.0f; - toggle->spacing = 4; - - /* option toggle */ - toggle = &style->option; - nk_zero_struct(*toggle); - toggle->normal = nk_style_item_color(table[NK_COLOR_TOGGLE]); - toggle->hover = nk_style_item_color(table[NK_COLOR_TOGGLE_HOVER]); - toggle->active = nk_style_item_color(table[NK_COLOR_TOGGLE_HOVER]); - toggle->cursor_normal = nk_style_item_color(table[NK_COLOR_TOGGLE_CURSOR]); - toggle->cursor_hover = nk_style_item_color(table[NK_COLOR_TOGGLE_CURSOR]); - toggle->userdata = nk_handle_ptr(0); - toggle->text_background = table[NK_COLOR_WINDOW]; - toggle->text_normal = table[NK_COLOR_TEXT]; - toggle->text_hover = table[NK_COLOR_TEXT]; - toggle->text_active = table[NK_COLOR_TEXT]; - toggle->padding = nk_vec2(3.0f, 3.0f); - toggle->touch_padding = nk_vec2(0,0); - toggle->border_color = nk_rgba(0,0,0,0); - toggle->border = 0.0f; - toggle->spacing = 4; - - /* selectable */ - select = &style->selectable; - nk_zero_struct(*select); - select->normal = nk_style_item_color(table[NK_COLOR_SELECT]); - select->hover = nk_style_item_color(table[NK_COLOR_SELECT]); - select->pressed = nk_style_item_color(table[NK_COLOR_SELECT]); - select->normal_active = nk_style_item_color(table[NK_COLOR_SELECT_ACTIVE]); - select->hover_active = nk_style_item_color(table[NK_COLOR_SELECT_ACTIVE]); - select->pressed_active = nk_style_item_color(table[NK_COLOR_SELECT_ACTIVE]); - select->text_normal = table[NK_COLOR_TEXT]; - select->text_hover = table[NK_COLOR_TEXT]; - select->text_pressed = table[NK_COLOR_TEXT]; - select->text_normal_active = table[NK_COLOR_TEXT]; - select->text_hover_active = table[NK_COLOR_TEXT]; - select->text_pressed_active = table[NK_COLOR_TEXT]; - select->padding = nk_vec2(2.0f,2.0f); - select->image_padding = nk_vec2(2.0f,2.0f); - select->touch_padding = nk_vec2(0,0); - select->userdata = nk_handle_ptr(0); - select->rounding = 0.0f; - select->draw_begin = 0; - select->draw_end = 0; - - /* slider */ - slider = &style->slider; - nk_zero_struct(*slider); - slider->normal = nk_style_item_hide(); - slider->hover = nk_style_item_hide(); - slider->active = nk_style_item_hide(); - slider->bar_normal = table[NK_COLOR_SLIDER]; - slider->bar_hover = table[NK_COLOR_SLIDER]; - slider->bar_active = table[NK_COLOR_SLIDER]; - slider->bar_filled = table[NK_COLOR_SLIDER_CURSOR]; - slider->cursor_normal = nk_style_item_color(table[NK_COLOR_SLIDER_CURSOR]); - slider->cursor_hover = nk_style_item_color(table[NK_COLOR_SLIDER_CURSOR_HOVER]); - slider->cursor_active = nk_style_item_color(table[NK_COLOR_SLIDER_CURSOR_ACTIVE]); - slider->inc_symbol = NK_SYMBOL_TRIANGLE_RIGHT; - slider->dec_symbol = NK_SYMBOL_TRIANGLE_LEFT; - slider->cursor_size = nk_vec2(16,16); - slider->padding = nk_vec2(2,2); - slider->spacing = nk_vec2(2,2); - slider->userdata = nk_handle_ptr(0); - slider->show_buttons = nk_false; - slider->bar_height = 8; - slider->rounding = 0; - slider->draw_begin = 0; - slider->draw_end = 0; - - /* slider buttons */ - button = &style->slider.inc_button; - button->normal = nk_style_item_color(nk_rgb(40,40,40)); - button->hover = nk_style_item_color(nk_rgb(42,42,42)); - button->active = nk_style_item_color(nk_rgb(44,44,44)); - button->border_color = nk_rgb(65,65,65); - button->text_background = nk_rgb(40,40,40); - button->text_normal = nk_rgb(175,175,175); - button->text_hover = nk_rgb(175,175,175); - button->text_active = nk_rgb(175,175,175); - button->padding = nk_vec2(8.0f,8.0f); - button->touch_padding = nk_vec2(0.0f,0.0f); - button->userdata = nk_handle_ptr(0); - button->text_alignment = NK_TEXT_CENTERED; - button->border = 1.0f; - button->rounding = 0.0f; - button->draw_begin = 0; - button->draw_end = 0; - style->slider.dec_button = style->slider.inc_button; - - /* progressbar */ - prog = &style->progress; - nk_zero_struct(*prog); - prog->normal = nk_style_item_color(table[NK_COLOR_SLIDER]); - prog->hover = nk_style_item_color(table[NK_COLOR_SLIDER]); - prog->active = nk_style_item_color(table[NK_COLOR_SLIDER]); - prog->cursor_normal = nk_style_item_color(table[NK_COLOR_SLIDER_CURSOR]); - prog->cursor_hover = nk_style_item_color(table[NK_COLOR_SLIDER_CURSOR_HOVER]); - prog->cursor_active = nk_style_item_color(table[NK_COLOR_SLIDER_CURSOR_ACTIVE]); - prog->border_color = nk_rgba(0,0,0,0); - prog->cursor_border_color = nk_rgba(0,0,0,0); - prog->userdata = nk_handle_ptr(0); - prog->padding = nk_vec2(4,4); - prog->rounding = 0; - prog->border = 0; - prog->cursor_rounding = 0; - prog->cursor_border = 0; - prog->draw_begin = 0; - prog->draw_end = 0; - - /* scrollbars */ - scroll = &style->scrollh; - nk_zero_struct(*scroll); - scroll->normal = nk_style_item_color(table[NK_COLOR_SCROLLBAR]); - scroll->hover = nk_style_item_color(table[NK_COLOR_SCROLLBAR]); - scroll->active = nk_style_item_color(table[NK_COLOR_SCROLLBAR]); - scroll->cursor_normal = nk_style_item_color(table[NK_COLOR_SCROLLBAR_CURSOR]); - scroll->cursor_hover = nk_style_item_color(table[NK_COLOR_SCROLLBAR_CURSOR_HOVER]); - scroll->cursor_active = nk_style_item_color(table[NK_COLOR_SCROLLBAR_CURSOR_ACTIVE]); - scroll->dec_symbol = NK_SYMBOL_CIRCLE_SOLID; - scroll->inc_symbol = NK_SYMBOL_CIRCLE_SOLID; - scroll->userdata = nk_handle_ptr(0); - scroll->border_color = table[NK_COLOR_SCROLLBAR]; - scroll->cursor_border_color = table[NK_COLOR_SCROLLBAR]; - scroll->padding = nk_vec2(0,0); - scroll->show_buttons = nk_false; - scroll->border = 0; - scroll->rounding = 0; - scroll->border_cursor = 0; - scroll->rounding_cursor = 0; - scroll->draw_begin = 0; - scroll->draw_end = 0; - style->scrollv = style->scrollh; - - /* scrollbars buttons */ - button = &style->scrollh.inc_button; - button->normal = nk_style_item_color(nk_rgb(40,40,40)); - button->hover = nk_style_item_color(nk_rgb(42,42,42)); - button->active = nk_style_item_color(nk_rgb(44,44,44)); - button->border_color = nk_rgb(65,65,65); - button->text_background = nk_rgb(40,40,40); - button->text_normal = nk_rgb(175,175,175); - button->text_hover = nk_rgb(175,175,175); - button->text_active = nk_rgb(175,175,175); - button->padding = nk_vec2(4.0f,4.0f); - button->touch_padding = nk_vec2(0.0f,0.0f); - button->userdata = nk_handle_ptr(0); - button->text_alignment = NK_TEXT_CENTERED; - button->border = 1.0f; - button->rounding = 0.0f; - button->draw_begin = 0; - button->draw_end = 0; - style->scrollh.dec_button = style->scrollh.inc_button; - style->scrollv.inc_button = style->scrollh.inc_button; - style->scrollv.dec_button = style->scrollh.inc_button; - - /* edit */ - edit = &style->edit; - nk_zero_struct(*edit); - edit->normal = nk_style_item_color(table[NK_COLOR_EDIT]); - edit->hover = nk_style_item_color(table[NK_COLOR_EDIT]); - edit->active = nk_style_item_color(table[NK_COLOR_EDIT]); - edit->cursor_normal = table[NK_COLOR_TEXT]; - edit->cursor_hover = table[NK_COLOR_TEXT]; - edit->cursor_text_normal= table[NK_COLOR_EDIT]; - edit->cursor_text_hover = table[NK_COLOR_EDIT]; - edit->border_color = table[NK_COLOR_BORDER]; - edit->text_normal = table[NK_COLOR_TEXT]; - edit->text_hover = table[NK_COLOR_TEXT]; - edit->text_active = table[NK_COLOR_TEXT]; - edit->selected_normal = table[NK_COLOR_TEXT]; - edit->selected_hover = table[NK_COLOR_TEXT]; - edit->selected_text_normal = table[NK_COLOR_EDIT]; - edit->selected_text_hover = table[NK_COLOR_EDIT]; - edit->scrollbar_size = nk_vec2(10,10); - edit->scrollbar = style->scrollv; - edit->padding = nk_vec2(4,4); - edit->row_padding = 2; - edit->cursor_size = 4; - edit->border = 1; - edit->rounding = 0; - - /* property */ - property = &style->property; - nk_zero_struct(*property); - property->normal = nk_style_item_color(table[NK_COLOR_PROPERTY]); - property->hover = nk_style_item_color(table[NK_COLOR_PROPERTY]); - property->active = nk_style_item_color(table[NK_COLOR_PROPERTY]); - property->border_color = table[NK_COLOR_BORDER]; - property->label_normal = table[NK_COLOR_TEXT]; - property->label_hover = table[NK_COLOR_TEXT]; - property->label_active = table[NK_COLOR_TEXT]; - property->sym_left = NK_SYMBOL_TRIANGLE_LEFT; - property->sym_right = NK_SYMBOL_TRIANGLE_RIGHT; - property->userdata = nk_handle_ptr(0); - property->padding = nk_vec2(4,4); - property->border = 1; - property->rounding = 10; - property->draw_begin = 0; - property->draw_end = 0; - - /* property buttons */ - button = &style->property.dec_button; - nk_zero_struct(*button); - button->normal = nk_style_item_color(table[NK_COLOR_PROPERTY]); - button->hover = nk_style_item_color(table[NK_COLOR_PROPERTY]); - button->active = nk_style_item_color(table[NK_COLOR_PROPERTY]); - button->border_color = nk_rgba(0,0,0,0); - button->text_background = table[NK_COLOR_PROPERTY]; - button->text_normal = table[NK_COLOR_TEXT]; - button->text_hover = table[NK_COLOR_TEXT]; - button->text_active = table[NK_COLOR_TEXT]; - button->padding = nk_vec2(0.0f,0.0f); - button->touch_padding = nk_vec2(0.0f,0.0f); - button->userdata = nk_handle_ptr(0); - button->text_alignment = NK_TEXT_CENTERED; - button->border = 0.0f; - button->rounding = 0.0f; - button->draw_begin = 0; - button->draw_end = 0; - style->property.inc_button = style->property.dec_button; - - /* property edit */ - edit = &style->property.edit; - nk_zero_struct(*edit); - edit->normal = nk_style_item_color(table[NK_COLOR_PROPERTY]); - edit->hover = nk_style_item_color(table[NK_COLOR_PROPERTY]); - edit->active = nk_style_item_color(table[NK_COLOR_PROPERTY]); - edit->border_color = nk_rgba(0,0,0,0); - edit->cursor_normal = table[NK_COLOR_TEXT]; - edit->cursor_hover = table[NK_COLOR_TEXT]; - edit->cursor_text_normal= table[NK_COLOR_EDIT]; - edit->cursor_text_hover = table[NK_COLOR_EDIT]; - edit->text_normal = table[NK_COLOR_TEXT]; - edit->text_hover = table[NK_COLOR_TEXT]; - edit->text_active = table[NK_COLOR_TEXT]; - edit->selected_normal = table[NK_COLOR_TEXT]; - edit->selected_hover = table[NK_COLOR_TEXT]; - edit->selected_text_normal = table[NK_COLOR_EDIT]; - edit->selected_text_hover = table[NK_COLOR_EDIT]; - edit->padding = nk_vec2(0,0); - edit->cursor_size = 8; - edit->border = 0; - edit->rounding = 0; - - /* chart */ - chart = &style->chart; - nk_zero_struct(*chart); - chart->background = nk_style_item_color(table[NK_COLOR_CHART]); - chart->border_color = table[NK_COLOR_BORDER]; - chart->selected_color = table[NK_COLOR_CHART_COLOR_HIGHLIGHT]; - chart->color = table[NK_COLOR_CHART_COLOR]; - chart->padding = nk_vec2(4,4); - chart->border = 0; - chart->rounding = 0; - - /* combo */ - combo = &style->combo; - combo->normal = nk_style_item_color(table[NK_COLOR_COMBO]); - combo->hover = nk_style_item_color(table[NK_COLOR_COMBO]); - combo->active = nk_style_item_color(table[NK_COLOR_COMBO]); - combo->border_color = table[NK_COLOR_BORDER]; - combo->label_normal = table[NK_COLOR_TEXT]; - combo->label_hover = table[NK_COLOR_TEXT]; - combo->label_active = table[NK_COLOR_TEXT]; - combo->sym_normal = NK_SYMBOL_TRIANGLE_DOWN; - combo->sym_hover = NK_SYMBOL_TRIANGLE_DOWN; - combo->sym_active = NK_SYMBOL_TRIANGLE_DOWN; - combo->content_padding = nk_vec2(4,4); - combo->button_padding = nk_vec2(0,4); - combo->spacing = nk_vec2(4,0); - combo->border = 1; - combo->rounding = 0; - - /* combo button */ - button = &style->combo.button; - nk_zero_struct(*button); - button->normal = nk_style_item_color(table[NK_COLOR_COMBO]); - button->hover = nk_style_item_color(table[NK_COLOR_COMBO]); - button->active = nk_style_item_color(table[NK_COLOR_COMBO]); - button->border_color = nk_rgba(0,0,0,0); - button->text_background = table[NK_COLOR_COMBO]; - button->text_normal = table[NK_COLOR_TEXT]; - button->text_hover = table[NK_COLOR_TEXT]; - button->text_active = table[NK_COLOR_TEXT]; - button->padding = nk_vec2(2.0f,2.0f); - button->touch_padding = nk_vec2(0.0f,0.0f); - button->userdata = nk_handle_ptr(0); - button->text_alignment = NK_TEXT_CENTERED; - button->border = 0.0f; - button->rounding = 0.0f; - button->draw_begin = 0; - button->draw_end = 0; - - /* tab */ - tab = &style->tab; - tab->background = nk_style_item_color(table[NK_COLOR_TAB_HEADER]); - tab->border_color = table[NK_COLOR_BORDER]; - tab->text = table[NK_COLOR_TEXT]; - tab->sym_minimize = NK_SYMBOL_TRIANGLE_RIGHT; - tab->sym_maximize = NK_SYMBOL_TRIANGLE_DOWN; - tab->padding = nk_vec2(4,4); - tab->spacing = nk_vec2(4,4); - tab->indent = 10.0f; - tab->border = 1; - tab->rounding = 0; - - /* tab button */ - button = &style->tab.tab_minimize_button; - nk_zero_struct(*button); - button->normal = nk_style_item_color(table[NK_COLOR_TAB_HEADER]); - button->hover = nk_style_item_color(table[NK_COLOR_TAB_HEADER]); - button->active = nk_style_item_color(table[NK_COLOR_TAB_HEADER]); - button->border_color = nk_rgba(0,0,0,0); - button->text_background = table[NK_COLOR_TAB_HEADER]; - button->text_normal = table[NK_COLOR_TEXT]; - button->text_hover = table[NK_COLOR_TEXT]; - button->text_active = table[NK_COLOR_TEXT]; - button->padding = nk_vec2(2.0f,2.0f); - button->touch_padding = nk_vec2(0.0f,0.0f); - button->userdata = nk_handle_ptr(0); - button->text_alignment = NK_TEXT_CENTERED; - button->border = 0.0f; - button->rounding = 0.0f; - button->draw_begin = 0; - button->draw_end = 0; - style->tab.tab_maximize_button =*button; - - /* node button */ - button = &style->tab.node_minimize_button; - nk_zero_struct(*button); - button->normal = nk_style_item_color(table[NK_COLOR_WINDOW]); - button->hover = nk_style_item_color(table[NK_COLOR_WINDOW]); - button->active = nk_style_item_color(table[NK_COLOR_WINDOW]); - button->border_color = nk_rgba(0,0,0,0); - button->text_background = table[NK_COLOR_TAB_HEADER]; - button->text_normal = table[NK_COLOR_TEXT]; - button->text_hover = table[NK_COLOR_TEXT]; - button->text_active = table[NK_COLOR_TEXT]; - button->padding = nk_vec2(2.0f,2.0f); - button->touch_padding = nk_vec2(0.0f,0.0f); - button->userdata = nk_handle_ptr(0); - button->text_alignment = NK_TEXT_CENTERED; - button->border = 0.0f; - button->rounding = 0.0f; - button->draw_begin = 0; - button->draw_end = 0; - style->tab.node_maximize_button =*button; - - /* window header */ - win = &style->window; - win->header.align = NK_HEADER_RIGHT; - win->header.close_symbol = NK_SYMBOL_X; - win->header.minimize_symbol = NK_SYMBOL_MINUS; - win->header.maximize_symbol = NK_SYMBOL_PLUS; - win->header.normal = nk_style_item_color(table[NK_COLOR_HEADER]); - win->header.hover = nk_style_item_color(table[NK_COLOR_HEADER]); - win->header.active = nk_style_item_color(table[NK_COLOR_HEADER]); - win->header.label_normal = table[NK_COLOR_TEXT]; - win->header.label_hover = table[NK_COLOR_TEXT]; - win->header.label_active = table[NK_COLOR_TEXT]; - win->header.label_padding = nk_vec2(4,4); - win->header.padding = nk_vec2(4,4); - win->header.spacing = nk_vec2(0,0); - - /* window header close button */ - button = &style->window.header.close_button; - nk_zero_struct(*button); - button->normal = nk_style_item_color(table[NK_COLOR_HEADER]); - button->hover = nk_style_item_color(table[NK_COLOR_HEADER]); - button->active = nk_style_item_color(table[NK_COLOR_HEADER]); - button->border_color = nk_rgba(0,0,0,0); - button->text_background = table[NK_COLOR_HEADER]; - button->text_normal = table[NK_COLOR_TEXT]; - button->text_hover = table[NK_COLOR_TEXT]; - button->text_active = table[NK_COLOR_TEXT]; - button->padding = nk_vec2(0.0f,0.0f); - button->touch_padding = nk_vec2(0.0f,0.0f); - button->userdata = nk_handle_ptr(0); - button->text_alignment = NK_TEXT_CENTERED; - button->border = 0.0f; - button->rounding = 0.0f; - button->draw_begin = 0; - button->draw_end = 0; - - /* window header minimize button */ - button = &style->window.header.minimize_button; - nk_zero_struct(*button); - button->normal = nk_style_item_color(table[NK_COLOR_HEADER]); - button->hover = nk_style_item_color(table[NK_COLOR_HEADER]); - button->active = nk_style_item_color(table[NK_COLOR_HEADER]); - button->border_color = nk_rgba(0,0,0,0); - button->text_background = table[NK_COLOR_HEADER]; - button->text_normal = table[NK_COLOR_TEXT]; - button->text_hover = table[NK_COLOR_TEXT]; - button->text_active = table[NK_COLOR_TEXT]; - button->padding = nk_vec2(0.0f,0.0f); - button->touch_padding = nk_vec2(0.0f,0.0f); - button->userdata = nk_handle_ptr(0); - button->text_alignment = NK_TEXT_CENTERED; - button->border = 0.0f; - button->rounding = 0.0f; - button->draw_begin = 0; - button->draw_end = 0; - - /* window */ - win->background = table[NK_COLOR_WINDOW]; - win->fixed_background = nk_style_item_color(table[NK_COLOR_WINDOW]); - win->border_color = table[NK_COLOR_BORDER]; - win->popup_border_color = table[NK_COLOR_BORDER]; - win->combo_border_color = table[NK_COLOR_BORDER]; - win->contextual_border_color = table[NK_COLOR_BORDER]; - win->menu_border_color = table[NK_COLOR_BORDER]; - win->group_border_color = table[NK_COLOR_BORDER]; - win->tooltip_border_color = table[NK_COLOR_BORDER]; - win->scaler = nk_style_item_color(table[NK_COLOR_TEXT]); - - win->rounding = 0.0f; - win->spacing = nk_vec2(4,4); - win->scrollbar_size = nk_vec2(10,10); - win->min_size = nk_vec2(64,64); - - win->combo_border = 1.0f; - win->contextual_border = 1.0f; - win->menu_border = 1.0f; - win->group_border = 1.0f; - win->tooltip_border = 1.0f; - win->popup_border = 1.0f; - win->border = 2.0f; - win->min_row_height_padding = 8; - - win->padding = nk_vec2(4,4); - win->group_padding = nk_vec2(4,4); - win->popup_padding = nk_vec2(4,4); - win->combo_padding = nk_vec2(4,4); - win->contextual_padding = nk_vec2(4,4); - win->menu_padding = nk_vec2(4,4); - win->tooltip_padding = nk_vec2(4,4); -} -NK_API void -nk_style_set_font(struct nk_context *ctx, const struct nk_user_font *font) -{ - struct nk_style *style; - NK_ASSERT(ctx); - - if (!ctx) return; - style = &ctx->style; - style->font = font; - ctx->stacks.fonts.head = 0; - if (ctx->current) - nk_layout_reset_min_row_height(ctx); -} -NK_API int -nk_style_push_font(struct nk_context *ctx, const struct nk_user_font *font) -{ - struct nk_config_stack_user_font *font_stack; - struct nk_config_stack_user_font_element *element; - - NK_ASSERT(ctx); - if (!ctx) return 0; - - font_stack = &ctx->stacks.fonts; - NK_ASSERT(font_stack->head < (int)NK_LEN(font_stack->elements)); - if (font_stack->head >= (int)NK_LEN(font_stack->elements)) - return 0; - - element = &font_stack->elements[font_stack->head++]; - element->address = &ctx->style.font; - element->old_value = ctx->style.font; - ctx->style.font = font; - return 1; -} -NK_API int -nk_style_pop_font(struct nk_context *ctx) -{ - struct nk_config_stack_user_font *font_stack; - struct nk_config_stack_user_font_element *element; - - NK_ASSERT(ctx); - if (!ctx) return 0; - - font_stack = &ctx->stacks.fonts; - NK_ASSERT(font_stack->head > 0); - if (font_stack->head < 1) - return 0; - - element = &font_stack->elements[--font_stack->head]; - *element->address = element->old_value; - return 1; -} -#define NK_STYLE_PUSH_IMPLEMENATION(prefix, type, stack) \ -nk_style_push_##type(struct nk_context *ctx, prefix##_##type *address, prefix##_##type value)\ -{\ - struct nk_config_stack_##type * type_stack;\ - struct nk_config_stack_##type##_element *element;\ - NK_ASSERT(ctx);\ - if (!ctx) return 0;\ - type_stack = &ctx->stacks.stack;\ - NK_ASSERT(type_stack->head < (int)NK_LEN(type_stack->elements));\ - if (type_stack->head >= (int)NK_LEN(type_stack->elements))\ - return 0;\ - element = &type_stack->elements[type_stack->head++];\ - element->address = address;\ - element->old_value = *address;\ - *address = value;\ - return 1;\ -} -#define NK_STYLE_POP_IMPLEMENATION(type, stack) \ -nk_style_pop_##type(struct nk_context *ctx)\ -{\ - struct nk_config_stack_##type *type_stack;\ - struct nk_config_stack_##type##_element *element;\ - NK_ASSERT(ctx);\ - if (!ctx) return 0;\ - type_stack = &ctx->stacks.stack;\ - NK_ASSERT(type_stack->head > 0);\ - if (type_stack->head < 1)\ - return 0;\ - element = &type_stack->elements[--type_stack->head];\ - *element->address = element->old_value;\ - return 1;\ -} -NK_API int NK_STYLE_PUSH_IMPLEMENATION(struct nk, style_item, style_items) -NK_API int NK_STYLE_PUSH_IMPLEMENATION(nk,float, floats) -NK_API int NK_STYLE_PUSH_IMPLEMENATION(struct nk, vec2, vectors) -NK_API int NK_STYLE_PUSH_IMPLEMENATION(nk,flags, flags) -NK_API int NK_STYLE_PUSH_IMPLEMENATION(struct nk,color, colors) - -NK_API int NK_STYLE_POP_IMPLEMENATION(style_item, style_items) -NK_API int NK_STYLE_POP_IMPLEMENATION(float,floats) -NK_API int NK_STYLE_POP_IMPLEMENATION(vec2, vectors) -NK_API int NK_STYLE_POP_IMPLEMENATION(flags,flags) -NK_API int NK_STYLE_POP_IMPLEMENATION(color,colors) - -NK_API int -nk_style_set_cursor(struct nk_context *ctx, enum nk_style_cursor c) -{ - struct nk_style *style; - NK_ASSERT(ctx); - if (!ctx) return 0; - style = &ctx->style; - if (style->cursors[c]) { - style->cursor_active = style->cursors[c]; - return 1; - } - return 0; -} -NK_API void -nk_style_show_cursor(struct nk_context *ctx) -{ - ctx->style.cursor_visible = nk_true; -} -NK_API void -nk_style_hide_cursor(struct nk_context *ctx) -{ - ctx->style.cursor_visible = nk_false; -} -NK_API void -nk_style_load_cursor(struct nk_context *ctx, enum nk_style_cursor cursor, - const struct nk_cursor *c) -{ - struct nk_style *style; - NK_ASSERT(ctx); - if (!ctx) return; - style = &ctx->style; - style->cursors[cursor] = c; -} -NK_API void -nk_style_load_all_cursors(struct nk_context *ctx, struct nk_cursor *cursors) -{ - int i = 0; - struct nk_style *style; - NK_ASSERT(ctx); - if (!ctx) return; - style = &ctx->style; - for (i = 0; i < NK_CURSOR_COUNT; ++i) - style->cursors[i] = &cursors[i]; - style->cursor_visible = nk_true; -} - - - - - -/* ============================================================== - * - * CONTEXT - * - * ===============================================================*/ -NK_INTERN void -nk_setup(struct nk_context *ctx, const struct nk_user_font *font) -{ - NK_ASSERT(ctx); - if (!ctx) return; - nk_zero_struct(*ctx); - nk_style_default(ctx); - ctx->seq = 1; - if (font) ctx->style.font = font; -#ifdef NK_INCLUDE_VERTEX_BUFFER_OUTPUT - nk_draw_list_init(&ctx->draw_list); -#endif -} -#ifdef NK_INCLUDE_DEFAULT_ALLOCATOR -NK_API int -nk_init_default(struct nk_context *ctx, const struct nk_user_font *font) -{ - struct nk_allocator alloc; - alloc.userdata.ptr = 0; - alloc.alloc = nk_malloc; - alloc.free = nk_mfree; - return nk_init(ctx, &alloc, font); -} -#endif -NK_API int -nk_init_fixed(struct nk_context *ctx, void *memory, nk_size size, - const struct nk_user_font *font) -{ - NK_ASSERT(memory); - if (!memory) return 0; - nk_setup(ctx, font); - nk_buffer_init_fixed(&ctx->memory, memory, size); - ctx->use_pool = nk_false; - return 1; -} -NK_API int -nk_init_custom(struct nk_context *ctx, struct nk_buffer *cmds, - struct nk_buffer *pool, const struct nk_user_font *font) -{ - NK_ASSERT(cmds); - NK_ASSERT(pool); - if (!cmds || !pool) return 0; - - nk_setup(ctx, font); - ctx->memory = *cmds; - if (pool->type == NK_BUFFER_FIXED) { - /* take memory from buffer and alloc fixed pool */ - nk_pool_init_fixed(&ctx->pool, pool->memory.ptr, pool->memory.size); - } else { - /* create dynamic pool from buffer allocator */ - struct nk_allocator *alloc = &pool->pool; - nk_pool_init(&ctx->pool, alloc, NK_POOL_DEFAULT_CAPACITY); - } - ctx->use_pool = nk_true; - return 1; -} -NK_API int -nk_init(struct nk_context *ctx, struct nk_allocator *alloc, - const struct nk_user_font *font) -{ - NK_ASSERT(alloc); - if (!alloc) return 0; - nk_setup(ctx, font); - nk_buffer_init(&ctx->memory, alloc, NK_DEFAULT_COMMAND_BUFFER_SIZE); - nk_pool_init(&ctx->pool, alloc, NK_POOL_DEFAULT_CAPACITY); - ctx->use_pool = nk_true; - return 1; -} -#ifdef NK_INCLUDE_COMMAND_USERDATA -NK_API void -nk_set_user_data(struct nk_context *ctx, nk_handle handle) -{ - if (!ctx) return; - ctx->userdata = handle; - if (ctx->current) - ctx->current->buffer.userdata = handle; -} -#endif -NK_API void -nk_free(struct nk_context *ctx) -{ - NK_ASSERT(ctx); - if (!ctx) return; - nk_buffer_free(&ctx->memory); - if (ctx->use_pool) - nk_pool_free(&ctx->pool); - - nk_zero(&ctx->input, sizeof(ctx->input)); - nk_zero(&ctx->style, sizeof(ctx->style)); - nk_zero(&ctx->memory, sizeof(ctx->memory)); - - ctx->seq = 0; - ctx->build = 0; - ctx->begin = 0; - ctx->end = 0; - ctx->active = 0; - ctx->current = 0; - ctx->freelist = 0; - ctx->count = 0; -} -NK_API void -nk_clear(struct nk_context *ctx) -{ - struct nk_window *iter; - struct nk_window *next; - NK_ASSERT(ctx); - - if (!ctx) return; - if (ctx->use_pool) - nk_buffer_clear(&ctx->memory); - else nk_buffer_reset(&ctx->memory, NK_BUFFER_FRONT); - - ctx->build = 0; - ctx->memory.calls = 0; - ctx->last_widget_state = 0; - ctx->style.cursor_active = ctx->style.cursors[NK_CURSOR_ARROW]; - NK_MEMSET(&ctx->overlay, 0, sizeof(ctx->overlay)); - - /* garbage collector */ - iter = ctx->begin; - while (iter) { - /* make sure valid minimized windows do not get removed */ - if ((iter->flags & NK_WINDOW_MINIMIZED) && - !(iter->flags & NK_WINDOW_CLOSED) && - iter->seq == ctx->seq) { - iter = iter->next; - continue; - } - /* remove hotness from hidden or closed windows*/ - if (((iter->flags & NK_WINDOW_HIDDEN) || - (iter->flags & NK_WINDOW_CLOSED)) && - iter == ctx->active) { - ctx->active = iter->prev; - ctx->end = iter->prev; - if (!ctx->end) - ctx->begin = 0; - if (ctx->active) - ctx->active->flags &= ~(unsigned)NK_WINDOW_ROM; - } - /* free unused popup windows */ - if (iter->popup.win && iter->popup.win->seq != ctx->seq) { - nk_free_window(ctx, iter->popup.win); - iter->popup.win = 0; - } - /* remove unused window state tables */ - {struct nk_table *n, *it = iter->tables; - while (it) { - n = it->next; - if (it->seq != ctx->seq) { - nk_remove_table(iter, it); - nk_zero(it, sizeof(union nk_page_data)); - nk_free_table(ctx, it); - if (it == iter->tables) - iter->tables = n; - } it = n; - }} - /* window itself is not used anymore so free */ - if (iter->seq != ctx->seq || iter->flags & NK_WINDOW_CLOSED) { - next = iter->next; - nk_remove_window(ctx, iter); - nk_free_window(ctx, iter); - iter = next; - } else iter = iter->next; - } - ctx->seq++; -} -NK_LIB void -nk_start_buffer(struct nk_context *ctx, struct nk_command_buffer *buffer) -{ - NK_ASSERT(ctx); - NK_ASSERT(buffer); - if (!ctx || !buffer) return; - buffer->begin = ctx->memory.allocated; - buffer->end = buffer->begin; - buffer->last = buffer->begin; - buffer->clip = nk_null_rect; -} -NK_LIB void -nk_start(struct nk_context *ctx, struct nk_window *win) -{ - NK_ASSERT(ctx); - NK_ASSERT(win); - nk_start_buffer(ctx, &win->buffer); -} -NK_LIB void -nk_start_popup(struct nk_context *ctx, struct nk_window *win) -{ - struct nk_popup_buffer *buf; - NK_ASSERT(ctx); - NK_ASSERT(win); - if (!ctx || !win) return; - - /* save buffer fill state for popup */ - buf = &win->popup.buf; - buf->begin = win->buffer.end; - buf->end = win->buffer.end; - buf->parent = win->buffer.last; - buf->last = buf->begin; - buf->active = nk_true; -} -NK_LIB void -nk_finish_popup(struct nk_context *ctx, struct nk_window *win) -{ - struct nk_popup_buffer *buf; - NK_ASSERT(ctx); - NK_ASSERT(win); - if (!ctx || !win) return; - - buf = &win->popup.buf; - buf->last = win->buffer.last; - buf->end = win->buffer.end; -} -NK_LIB void -nk_finish_buffer(struct nk_context *ctx, struct nk_command_buffer *buffer) -{ - NK_ASSERT(ctx); - NK_ASSERT(buffer); - if (!ctx || !buffer) return; - buffer->end = ctx->memory.allocated; -} -NK_LIB void -nk_finish(struct nk_context *ctx, struct nk_window *win) -{ - struct nk_popup_buffer *buf; - struct nk_command *parent_last; - void *memory; - - NK_ASSERT(ctx); - NK_ASSERT(win); - if (!ctx || !win) return; - nk_finish_buffer(ctx, &win->buffer); - if (!win->popup.buf.active) return; - - buf = &win->popup.buf; - memory = ctx->memory.memory.ptr; - parent_last = nk_ptr_add(struct nk_command, memory, buf->parent); - parent_last->next = buf->end; -} -NK_LIB void -nk_build(struct nk_context *ctx) -{ - struct nk_window *it = 0; - struct nk_command *cmd = 0; - nk_byte *buffer = 0; - - /* draw cursor overlay */ - if (!ctx->style.cursor_active) - ctx->style.cursor_active = ctx->style.cursors[NK_CURSOR_ARROW]; - if (ctx->style.cursor_active && !ctx->input.mouse.grabbed && ctx->style.cursor_visible) { - struct nk_rect mouse_bounds; - const struct nk_cursor *cursor = ctx->style.cursor_active; - nk_command_buffer_init(&ctx->overlay, &ctx->memory, NK_CLIPPING_OFF); - nk_start_buffer(ctx, &ctx->overlay); - - mouse_bounds.x = ctx->input.mouse.pos.x - cursor->offset.x; - mouse_bounds.y = ctx->input.mouse.pos.y - cursor->offset.y; - mouse_bounds.w = cursor->size.x; - mouse_bounds.h = cursor->size.y; - - nk_draw_image(&ctx->overlay, mouse_bounds, &cursor->img, nk_white); - nk_finish_buffer(ctx, &ctx->overlay); - } - /* build one big draw command list out of all window buffers */ - it = ctx->begin; - buffer = (nk_byte*)ctx->memory.memory.ptr; - while (it != 0) { - struct nk_window *next = it->next; - if (it->buffer.last == it->buffer.begin || (it->flags & NK_WINDOW_HIDDEN)|| - it->seq != ctx->seq) - goto cont; - - cmd = nk_ptr_add(struct nk_command, buffer, it->buffer.last); - while (next && ((next->buffer.last == next->buffer.begin) || - (next->flags & NK_WINDOW_HIDDEN) || next->seq != ctx->seq)) - next = next->next; /* skip empty command buffers */ - - if (next) cmd->next = next->buffer.begin; - cont: it = next; - } - /* append all popup draw commands into lists */ - it = ctx->begin; - while (it != 0) { - struct nk_window *next = it->next; - struct nk_popup_buffer *buf; - if (!it->popup.buf.active) - goto skip; - - buf = &it->popup.buf; - cmd->next = buf->begin; - cmd = nk_ptr_add(struct nk_command, buffer, buf->last); - buf->active = nk_false; - skip: it = next; - } - if (cmd) { - /* append overlay commands */ - if (ctx->overlay.end != ctx->overlay.begin) - cmd->next = ctx->overlay.begin; - else cmd->next = ctx->memory.allocated; - } -} -NK_API const struct nk_command* -nk__begin(struct nk_context *ctx) -{ - struct nk_window *iter; - nk_byte *buffer; - NK_ASSERT(ctx); - if (!ctx) return 0; - if (!ctx->count) return 0; - - buffer = (nk_byte*)ctx->memory.memory.ptr; - if (!ctx->build) { - nk_build(ctx); - ctx->build = nk_true; - } - iter = ctx->begin; - while (iter && ((iter->buffer.begin == iter->buffer.end) || - (iter->flags & NK_WINDOW_HIDDEN) || iter->seq != ctx->seq)) - iter = iter->next; - if (!iter) return 0; - return nk_ptr_add_const(struct nk_command, buffer, iter->buffer.begin); -} - -NK_API const struct nk_command* -nk__next(struct nk_context *ctx, const struct nk_command *cmd) -{ - nk_byte *buffer; - const struct nk_command *next; - NK_ASSERT(ctx); - if (!ctx || !cmd || !ctx->count) return 0; - if (cmd->next >= ctx->memory.allocated) return 0; - buffer = (nk_byte*)ctx->memory.memory.ptr; - next = nk_ptr_add_const(struct nk_command, buffer, cmd->next); - return next; -} - - - - - - -/* =============================================================== - * - * POOL - * - * ===============================================================*/ -NK_LIB void -nk_pool_init(struct nk_pool *pool, struct nk_allocator *alloc, - unsigned int capacity) -{ - nk_zero(pool, sizeof(*pool)); - pool->alloc = *alloc; - pool->capacity = capacity; - pool->type = NK_BUFFER_DYNAMIC; - pool->pages = 0; -} -NK_LIB void -nk_pool_free(struct nk_pool *pool) -{ - struct nk_page *iter = pool->pages; - if (!pool) return; - if (pool->type == NK_BUFFER_FIXED) return; - while (iter) { - struct nk_page *next = iter->next; - pool->alloc.free(pool->alloc.userdata, iter); - iter = next; - } -} -NK_LIB void -nk_pool_init_fixed(struct nk_pool *pool, void *memory, nk_size size) -{ - nk_zero(pool, sizeof(*pool)); - NK_ASSERT(size >= sizeof(struct nk_page)); - if (size < sizeof(struct nk_page)) return; - pool->capacity = (unsigned)(size - sizeof(struct nk_page)) / sizeof(struct nk_page_element); - pool->pages = (struct nk_page*)memory; - pool->type = NK_BUFFER_FIXED; - pool->size = size; -} -NK_LIB struct nk_page_element* -nk_pool_alloc(struct nk_pool *pool) -{ - if (!pool->pages || pool->pages->size >= pool->capacity) { - /* allocate new page */ - struct nk_page *page; - if (pool->type == NK_BUFFER_FIXED) { - NK_ASSERT(pool->pages); - if (!pool->pages) return 0; - NK_ASSERT(pool->pages->size < pool->capacity); - return 0; - } else { - nk_size size = sizeof(struct nk_page); - size += NK_POOL_DEFAULT_CAPACITY * sizeof(union nk_page_data); - page = (struct nk_page*)pool->alloc.alloc(pool->alloc.userdata,0, size); - page->next = pool->pages; - pool->pages = page; - page->size = 0; - } - } return &pool->pages->win[pool->pages->size++]; -} - - - - - -/* =============================================================== - * - * PAGE ELEMENT - * - * ===============================================================*/ -NK_LIB struct nk_page_element* -nk_create_page_element(struct nk_context *ctx) -{ - struct nk_page_element *elem; - if (ctx->freelist) { - /* unlink page element from free list */ - elem = ctx->freelist; - ctx->freelist = elem->next; - } else if (ctx->use_pool) { - /* allocate page element from memory pool */ - elem = nk_pool_alloc(&ctx->pool); - NK_ASSERT(elem); - if (!elem) return 0; - } else { - /* allocate new page element from back of fixed size memory buffer */ - NK_STORAGE const nk_size size = sizeof(struct nk_page_element); - NK_STORAGE const nk_size align = NK_ALIGNOF(struct nk_page_element); - elem = (struct nk_page_element*)nk_buffer_alloc(&ctx->memory, NK_BUFFER_BACK, size, align); - NK_ASSERT(elem); - if (!elem) return 0; - } - nk_zero_struct(*elem); - elem->next = 0; - elem->prev = 0; - return elem; -} -NK_LIB void -nk_link_page_element_into_freelist(struct nk_context *ctx, - struct nk_page_element *elem) -{ - /* link table into freelist */ - if (!ctx->freelist) { - ctx->freelist = elem; - } else { - elem->next = ctx->freelist; - ctx->freelist = elem; - } -} -NK_LIB void -nk_free_page_element(struct nk_context *ctx, struct nk_page_element *elem) -{ - /* we have a pool so just add to free list */ - if (ctx->use_pool) { - nk_link_page_element_into_freelist(ctx, elem); - return; - } - /* if possible remove last element from back of fixed memory buffer */ - {void *elem_end = (void*)(elem + 1); - void *buffer_end = (nk_byte*)ctx->memory.memory.ptr + ctx->memory.size; - if (elem_end == buffer_end) - ctx->memory.size -= sizeof(struct nk_page_element); - else nk_link_page_element_into_freelist(ctx, elem);} -} - - - - - -/* =============================================================== - * - * TABLE - * - * ===============================================================*/ -NK_LIB struct nk_table* -nk_create_table(struct nk_context *ctx) -{ - struct nk_page_element *elem; - elem = nk_create_page_element(ctx); - if (!elem) return 0; - nk_zero_struct(*elem); - return &elem->data.tbl; -} -NK_LIB void -nk_free_table(struct nk_context *ctx, struct nk_table *tbl) -{ - union nk_page_data *pd = NK_CONTAINER_OF(tbl, union nk_page_data, tbl); - struct nk_page_element *pe = NK_CONTAINER_OF(pd, struct nk_page_element, data); - nk_free_page_element(ctx, pe); -} -NK_LIB void -nk_push_table(struct nk_window *win, struct nk_table *tbl) -{ - if (!win->tables) { - win->tables = tbl; - tbl->next = 0; - tbl->prev = 0; - tbl->size = 0; - win->table_count = 1; - return; - } - win->tables->prev = tbl; - tbl->next = win->tables; - tbl->prev = 0; - tbl->size = 0; - win->tables = tbl; - win->table_count++; -} -NK_LIB void -nk_remove_table(struct nk_window *win, struct nk_table *tbl) -{ - if (win->tables == tbl) - win->tables = tbl->next; - if (tbl->next) - tbl->next->prev = tbl->prev; - if (tbl->prev) - tbl->prev->next = tbl->next; - tbl->next = 0; - tbl->prev = 0; -} -NK_LIB nk_uint* -nk_add_value(struct nk_context *ctx, struct nk_window *win, - nk_hash name, nk_uint value) -{ - NK_ASSERT(ctx); - NK_ASSERT(win); - if (!win || !ctx) return 0; - if (!win->tables || win->tables->size >= NK_VALUE_PAGE_CAPACITY) { - struct nk_table *tbl = nk_create_table(ctx); - NK_ASSERT(tbl); - if (!tbl) return 0; - nk_push_table(win, tbl); - } - win->tables->seq = win->seq; - win->tables->keys[win->tables->size] = name; - win->tables->values[win->tables->size] = value; - return &win->tables->values[win->tables->size++]; -} -NK_LIB nk_uint* -nk_find_value(struct nk_window *win, nk_hash name) -{ - struct nk_table *iter = win->tables; - while (iter) { - unsigned int i = 0; - unsigned int size = iter->size; - for (i = 0; i < size; ++i) { - if (iter->keys[i] == name) { - iter->seq = win->seq; - return &iter->values[i]; - } - } size = NK_VALUE_PAGE_CAPACITY; - iter = iter->next; - } - return 0; -} - - - - - -/* =============================================================== - * - * PANEL - * - * ===============================================================*/ -NK_LIB void* -nk_create_panel(struct nk_context *ctx) -{ - struct nk_page_element *elem; - elem = nk_create_page_element(ctx); - if (!elem) return 0; - nk_zero_struct(*elem); - return &elem->data.pan; -} -NK_LIB void -nk_free_panel(struct nk_context *ctx, struct nk_panel *pan) -{ - union nk_page_data *pd = NK_CONTAINER_OF(pan, union nk_page_data, pan); - struct nk_page_element *pe = NK_CONTAINER_OF(pd, struct nk_page_element, data); - nk_free_page_element(ctx, pe); -} -NK_LIB int -nk_panel_has_header(nk_flags flags, const char *title) -{ - int active = 0; - active = (flags & (NK_WINDOW_CLOSABLE|NK_WINDOW_MINIMIZABLE)); - active = active || (flags & NK_WINDOW_TITLE); - active = active && !(flags & NK_WINDOW_HIDDEN) && title; - return active; -} -NK_LIB struct nk_vec2 -nk_panel_get_padding(const struct nk_style *style, enum nk_panel_type type) -{ - switch (type) { - default: - case NK_PANEL_WINDOW: return style->window.padding; - case NK_PANEL_GROUP: return style->window.group_padding; - case NK_PANEL_POPUP: return style->window.popup_padding; - case NK_PANEL_CONTEXTUAL: return style->window.contextual_padding; - case NK_PANEL_COMBO: return style->window.combo_padding; - case NK_PANEL_MENU: return style->window.menu_padding; - case NK_PANEL_TOOLTIP: return style->window.menu_padding;} -} -NK_LIB float -nk_panel_get_border(const struct nk_style *style, nk_flags flags, - enum nk_panel_type type) -{ - if (flags & NK_WINDOW_BORDER) { - switch (type) { - default: - case NK_PANEL_WINDOW: return style->window.border; - case NK_PANEL_GROUP: return style->window.group_border; - case NK_PANEL_POPUP: return style->window.popup_border; - case NK_PANEL_CONTEXTUAL: return style->window.contextual_border; - case NK_PANEL_COMBO: return style->window.combo_border; - case NK_PANEL_MENU: return style->window.menu_border; - case NK_PANEL_TOOLTIP: return style->window.menu_border; - }} else return 0; -} -NK_LIB struct nk_color -nk_panel_get_border_color(const struct nk_style *style, enum nk_panel_type type) -{ - switch (type) { - default: - case NK_PANEL_WINDOW: return style->window.border_color; - case NK_PANEL_GROUP: return style->window.group_border_color; - case NK_PANEL_POPUP: return style->window.popup_border_color; - case NK_PANEL_CONTEXTUAL: return style->window.contextual_border_color; - case NK_PANEL_COMBO: return style->window.combo_border_color; - case NK_PANEL_MENU: return style->window.menu_border_color; - case NK_PANEL_TOOLTIP: return style->window.menu_border_color;} -} -NK_LIB int -nk_panel_is_sub(enum nk_panel_type type) -{ - return (type & NK_PANEL_SET_SUB)?1:0; -} -NK_LIB int -nk_panel_is_nonblock(enum nk_panel_type type) -{ - return (type & NK_PANEL_SET_NONBLOCK)?1:0; -} -NK_LIB int -nk_panel_begin(struct nk_context *ctx, const char *title, enum nk_panel_type panel_type) -{ - struct nk_input *in; - struct nk_window *win; - struct nk_panel *layout; - struct nk_command_buffer *out; - const struct nk_style *style; - const struct nk_user_font *font; - - struct nk_vec2 scrollbar_size; - struct nk_vec2 panel_padding; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) return 0; - nk_zero(ctx->current->layout, sizeof(*ctx->current->layout)); - if ((ctx->current->flags & NK_WINDOW_HIDDEN) || (ctx->current->flags & NK_WINDOW_CLOSED)) { - nk_zero(ctx->current->layout, sizeof(struct nk_panel)); - ctx->current->layout->type = panel_type; - return 0; - } - /* pull state into local stack */ - style = &ctx->style; - font = style->font; - win = ctx->current; - layout = win->layout; - out = &win->buffer; - in = (win->flags & NK_WINDOW_NO_INPUT) ? 0: &ctx->input; -#ifdef NK_INCLUDE_COMMAND_USERDATA - win->buffer.userdata = ctx->userdata; -#endif - /* pull style configuration into local stack */ - scrollbar_size = style->window.scrollbar_size; - panel_padding = nk_panel_get_padding(style, panel_type); - - /* window movement */ - if ((win->flags & NK_WINDOW_MOVABLE) && !(win->flags & NK_WINDOW_ROM)) { - int left_mouse_down; - int left_mouse_clicked; - int left_mouse_click_in_cursor; - - /* calculate draggable window space */ - struct nk_rect header; - header.x = win->bounds.x; - header.y = win->bounds.y; - header.w = win->bounds.w; - if (nk_panel_has_header(win->flags, title)) { - header.h = font->height + 2.0f * style->window.header.padding.y; - header.h += 2.0f * style->window.header.label_padding.y; - } else header.h = panel_padding.y; - - /* window movement by dragging */ - left_mouse_down = in->mouse.buttons[NK_BUTTON_LEFT].down; - left_mouse_clicked = (int)in->mouse.buttons[NK_BUTTON_LEFT].clicked; - left_mouse_click_in_cursor = nk_input_has_mouse_click_down_in_rect(in, - NK_BUTTON_LEFT, header, nk_true); - if (left_mouse_down && left_mouse_click_in_cursor && !left_mouse_clicked) { - win->bounds.x = win->bounds.x + in->mouse.delta.x; - win->bounds.y = win->bounds.y + in->mouse.delta.y; - in->mouse.buttons[NK_BUTTON_LEFT].clicked_pos.x += in->mouse.delta.x; - in->mouse.buttons[NK_BUTTON_LEFT].clicked_pos.y += in->mouse.delta.y; - ctx->style.cursor_active = ctx->style.cursors[NK_CURSOR_MOVE]; - } - } - - /* setup panel */ - layout->type = panel_type; - layout->flags = win->flags; - layout->bounds = win->bounds; - layout->bounds.x += panel_padding.x; - layout->bounds.w -= 2*panel_padding.x; - if (win->flags & NK_WINDOW_BORDER) { - layout->border = nk_panel_get_border(style, win->flags, panel_type); - layout->bounds = nk_shrink_rect(layout->bounds, layout->border); - } else layout->border = 0; - layout->at_y = layout->bounds.y; - layout->at_x = layout->bounds.x; - layout->max_x = 0; - layout->header_height = 0; - layout->footer_height = 0; - nk_layout_reset_min_row_height(ctx); - layout->row.index = 0; - layout->row.columns = 0; - layout->row.ratio = 0; - layout->row.item_width = 0; - layout->row.tree_depth = 0; - layout->row.height = panel_padding.y; - layout->has_scrolling = nk_true; - if (!(win->flags & NK_WINDOW_NO_SCROLLBAR)) - layout->bounds.w -= scrollbar_size.x; - if (!nk_panel_is_nonblock(panel_type)) { - layout->footer_height = 0; - if (!(win->flags & NK_WINDOW_NO_SCROLLBAR) || win->flags & NK_WINDOW_SCALABLE) - layout->footer_height = scrollbar_size.y; - layout->bounds.h -= layout->footer_height; - } - - /* panel header */ - if (nk_panel_has_header(win->flags, title)) - { - struct nk_text text; - struct nk_rect header; - const struct nk_style_item *background = 0; - - /* calculate header bounds */ - header.x = win->bounds.x; - header.y = win->bounds.y; - header.w = win->bounds.w; - header.h = font->height + 2.0f * style->window.header.padding.y; - header.h += (2.0f * style->window.header.label_padding.y); - - /* shrink panel by header */ - layout->header_height = header.h; - layout->bounds.y += header.h; - layout->bounds.h -= header.h; - layout->at_y += header.h; - - /* select correct header background and text color */ - if (ctx->active == win) { - background = &style->window.header.active; - text.text = style->window.header.label_active; - } else if (nk_input_is_mouse_hovering_rect(&ctx->input, header)) { - background = &style->window.header.hover; - text.text = style->window.header.label_hover; - } else { - background = &style->window.header.normal; - text.text = style->window.header.label_normal; - } - - /* draw header background */ - header.h += 1.0f; - if (background->type == NK_STYLE_ITEM_IMAGE) { - text.background = nk_rgba(0,0,0,0); - nk_draw_image(&win->buffer, header, &background->data.image, nk_white); - } else { - text.background = background->data.color; - nk_fill_rect(out, header, 0, background->data.color); - } - - /* window close button */ - {struct nk_rect button; - button.y = header.y + style->window.header.padding.y; - button.h = header.h - 2 * style->window.header.padding.y; - button.w = button.h; - if (win->flags & NK_WINDOW_CLOSABLE) { - nk_flags ws = 0; - if (style->window.header.align == NK_HEADER_RIGHT) { - button.x = (header.w + header.x) - (button.w + style->window.header.padding.x); - header.w -= button.w + style->window.header.spacing.x + style->window.header.padding.x; - } else { - button.x = header.x + style->window.header.padding.x; - header.x += button.w + style->window.header.spacing.x + style->window.header.padding.x; - } - - if (nk_do_button_symbol(&ws, &win->buffer, button, - style->window.header.close_symbol, NK_BUTTON_DEFAULT, - &style->window.header.close_button, in, style->font) && !(win->flags & NK_WINDOW_ROM)) - { - layout->flags |= NK_WINDOW_HIDDEN; - layout->flags &= (nk_flags)~NK_WINDOW_MINIMIZED; - } - } - - /* window minimize button */ - if (win->flags & NK_WINDOW_MINIMIZABLE) { - nk_flags ws = 0; - if (style->window.header.align == NK_HEADER_RIGHT) { - button.x = (header.w + header.x) - button.w; - if (!(win->flags & NK_WINDOW_CLOSABLE)) { - button.x -= style->window.header.padding.x; - header.w -= style->window.header.padding.x; - } - header.w -= button.w + style->window.header.spacing.x; - } else { - button.x = header.x; - header.x += button.w + style->window.header.spacing.x + style->window.header.padding.x; - } - if (nk_do_button_symbol(&ws, &win->buffer, button, (layout->flags & NK_WINDOW_MINIMIZED)? - style->window.header.maximize_symbol: style->window.header.minimize_symbol, - NK_BUTTON_DEFAULT, &style->window.header.minimize_button, in, style->font) && !(win->flags & NK_WINDOW_ROM)) - layout->flags = (layout->flags & NK_WINDOW_MINIMIZED) ? - layout->flags & (nk_flags)~NK_WINDOW_MINIMIZED: - layout->flags | NK_WINDOW_MINIMIZED; - }} - - {/* window header title */ - int text_len = nk_strlen(title); - struct nk_rect label = {0,0,0,0}; - float t = font->width(font->userdata, font->height, title, text_len); - text.padding = nk_vec2(0,0); - - label.x = header.x + style->window.header.padding.x; - label.x += style->window.header.label_padding.x; - label.y = header.y + style->window.header.label_padding.y; - label.h = font->height + 2 * style->window.header.label_padding.y; - label.w = t + 2 * style->window.header.spacing.x; - label.w = NK_CLAMP(0, label.w, header.x + header.w - label.x); - nk_widget_text(out, label,(const char*)title, text_len, &text, NK_TEXT_LEFT, font);} - } - - /* draw window background */ - if (!(layout->flags & NK_WINDOW_MINIMIZED) && !(layout->flags & NK_WINDOW_DYNAMIC)) { - struct nk_rect body; - body.x = win->bounds.x; - body.w = win->bounds.w; - body.y = (win->bounds.y + layout->header_height); - body.h = (win->bounds.h - layout->header_height); - if (style->window.fixed_background.type == NK_STYLE_ITEM_IMAGE) - nk_draw_image(out, body, &style->window.fixed_background.data.image, nk_white); - else nk_fill_rect(out, body, 0, style->window.fixed_background.data.color); - } - - /* set clipping rectangle */ - {struct nk_rect clip; - layout->clip = layout->bounds; - nk_unify(&clip, &win->buffer.clip, layout->clip.x, layout->clip.y, - layout->clip.x + layout->clip.w, layout->clip.y + layout->clip.h); - nk_push_scissor(out, clip); - layout->clip = clip;} - return !(layout->flags & NK_WINDOW_HIDDEN) && !(layout->flags & NK_WINDOW_MINIMIZED); -} -NK_LIB void -nk_panel_end(struct nk_context *ctx) -{ - struct nk_input *in; - struct nk_window *window; - struct nk_panel *layout; - const struct nk_style *style; - struct nk_command_buffer *out; - - struct nk_vec2 scrollbar_size; - struct nk_vec2 panel_padding; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return; - - window = ctx->current; - layout = window->layout; - style = &ctx->style; - out = &window->buffer; - in = (layout->flags & NK_WINDOW_ROM || layout->flags & NK_WINDOW_NO_INPUT) ? 0 :&ctx->input; - if (!nk_panel_is_sub(layout->type)) - nk_push_scissor(out, nk_null_rect); - - /* cache configuration data */ - scrollbar_size = style->window.scrollbar_size; - panel_padding = nk_panel_get_padding(style, layout->type); - - /* update the current cursor Y-position to point over the last added widget */ - layout->at_y += layout->row.height; - - /* dynamic panels */ - if (layout->flags & NK_WINDOW_DYNAMIC && !(layout->flags & NK_WINDOW_MINIMIZED)) - { - /* update panel height to fit dynamic growth */ - struct nk_rect empty_space; - if (layout->at_y < (layout->bounds.y + layout->bounds.h)) - layout->bounds.h = layout->at_y - layout->bounds.y; - - /* fill top empty space */ - empty_space.x = window->bounds.x; - empty_space.y = layout->bounds.y; - empty_space.h = panel_padding.y; - empty_space.w = window->bounds.w; - nk_fill_rect(out, empty_space, 0, style->window.background); - - /* fill left empty space */ - empty_space.x = window->bounds.x; - empty_space.y = layout->bounds.y; - empty_space.w = panel_padding.x + layout->border; - empty_space.h = layout->bounds.h; - nk_fill_rect(out, empty_space, 0, style->window.background); - - /* fill right empty space */ - empty_space.x = layout->bounds.x + layout->bounds.w - layout->border; - empty_space.y = layout->bounds.y; - empty_space.w = panel_padding.x + layout->border; - empty_space.h = layout->bounds.h; - if (*layout->offset_y == 0 && !(layout->flags & NK_WINDOW_NO_SCROLLBAR)) - empty_space.w += scrollbar_size.x; - nk_fill_rect(out, empty_space, 0, style->window.background); - - /* fill bottom empty space */ - if (*layout->offset_x != 0 && !(layout->flags & NK_WINDOW_NO_SCROLLBAR)) { - empty_space.x = window->bounds.x; - empty_space.y = layout->bounds.y + layout->bounds.h; - empty_space.w = window->bounds.w; - empty_space.h = scrollbar_size.y; - nk_fill_rect(out, empty_space, 0, style->window.background); - } - } - - /* scrollbars */ - if (!(layout->flags & NK_WINDOW_NO_SCROLLBAR) && - !(layout->flags & NK_WINDOW_MINIMIZED) && - window->scrollbar_hiding_timer < NK_SCROLLBAR_HIDING_TIMEOUT) - { - struct nk_rect scroll; - int scroll_has_scrolling; - float scroll_target; - float scroll_offset; - float scroll_step; - float scroll_inc; - - /* mouse wheel scrolling */ - if (nk_panel_is_sub(layout->type)) - { - /* sub-window mouse wheel scrolling */ - struct nk_window *root_window = window; - struct nk_panel *root_panel = window->layout; - while (root_panel->parent) - root_panel = root_panel->parent; - while (root_window->parent) - root_window = root_window->parent; - - /* only allow scrolling if parent window is active */ - scroll_has_scrolling = 0; - if ((root_window == ctx->active) && layout->has_scrolling) { - /* and panel is being hovered and inside clip rect*/ - if (nk_input_is_mouse_hovering_rect(in, layout->bounds) && - NK_INTERSECT(layout->bounds.x, layout->bounds.y, layout->bounds.w, layout->bounds.h, - root_panel->clip.x, root_panel->clip.y, root_panel->clip.w, root_panel->clip.h)) - { - /* deactivate all parent scrolling */ - root_panel = window->layout; - while (root_panel->parent) { - root_panel->has_scrolling = nk_false; - root_panel = root_panel->parent; - } - root_panel->has_scrolling = nk_false; - scroll_has_scrolling = nk_true; - } - } - } else if (!nk_panel_is_sub(layout->type)) { - /* window mouse wheel scrolling */ - scroll_has_scrolling = (window == ctx->active) && layout->has_scrolling; - if (in && (in->mouse.scroll_delta.y > 0 || in->mouse.scroll_delta.x > 0) && scroll_has_scrolling) - window->scrolled = nk_true; - else window->scrolled = nk_false; - } else scroll_has_scrolling = nk_false; - - { - /* vertical scrollbar */ - nk_flags state = 0; - scroll.x = layout->bounds.x + layout->bounds.w + panel_padding.x; - scroll.y = layout->bounds.y; - scroll.w = scrollbar_size.x; - scroll.h = layout->bounds.h; - - scroll_offset = (float)*layout->offset_y; - scroll_step = scroll.h * 0.10f; - scroll_inc = scroll.h * 0.01f; - scroll_target = (float)(int)(layout->at_y - scroll.y); - scroll_offset = nk_do_scrollbarv(&state, out, scroll, scroll_has_scrolling, - scroll_offset, scroll_target, scroll_step, scroll_inc, - &ctx->style.scrollv, in, style->font); - *layout->offset_y = (nk_uint)scroll_offset; - if (in && scroll_has_scrolling) - in->mouse.scroll_delta.y = 0; - } - { - /* horizontal scrollbar */ - nk_flags state = 0; - scroll.x = layout->bounds.x; - scroll.y = layout->bounds.y + layout->bounds.h; - scroll.w = layout->bounds.w; - scroll.h = scrollbar_size.y; - - scroll_offset = (float)*layout->offset_x; - scroll_target = (float)(int)(layout->max_x - scroll.x); - scroll_step = layout->max_x * 0.05f; - scroll_inc = layout->max_x * 0.005f; - scroll_offset = nk_do_scrollbarh(&state, out, scroll, scroll_has_scrolling, - scroll_offset, scroll_target, scroll_step, scroll_inc, - &ctx->style.scrollh, in, style->font); - *layout->offset_x = (nk_uint)scroll_offset; - } - } - - /* hide scroll if no user input */ - if (window->flags & NK_WINDOW_SCROLL_AUTO_HIDE) { - int has_input = ctx->input.mouse.delta.x != 0 || ctx->input.mouse.delta.y != 0 || ctx->input.mouse.scroll_delta.y != 0; - int is_window_hovered = nk_window_is_hovered(ctx); - int any_item_active = (ctx->last_widget_state & NK_WIDGET_STATE_MODIFIED); - if ((!has_input && is_window_hovered) || (!is_window_hovered && !any_item_active)) - window->scrollbar_hiding_timer += ctx->delta_time_seconds; - else window->scrollbar_hiding_timer = 0; - } else window->scrollbar_hiding_timer = 0; - - /* window border */ - if (layout->flags & NK_WINDOW_BORDER) - { - struct nk_color border_color = nk_panel_get_border_color(style, layout->type); - const float padding_y = (layout->flags & NK_WINDOW_MINIMIZED) - ? (style->window.border + window->bounds.y + layout->header_height) - : ((layout->flags & NK_WINDOW_DYNAMIC) - ? (layout->bounds.y + layout->bounds.h + layout->footer_height) - : (window->bounds.y + window->bounds.h)); - struct nk_rect b = window->bounds; - b.h = padding_y - window->bounds.y; - nk_stroke_rect(out, b, 0, layout->border, border_color); - } - - /* scaler */ - if ((layout->flags & NK_WINDOW_SCALABLE) && in && !(layout->flags & NK_WINDOW_MINIMIZED)) - { - /* calculate scaler bounds */ - struct nk_rect scaler; - scaler.w = scrollbar_size.x; - scaler.h = scrollbar_size.y; - scaler.y = layout->bounds.y + layout->bounds.h; - if (layout->flags & NK_WINDOW_SCALE_LEFT) - scaler.x = layout->bounds.x - panel_padding.x * 0.5f; - else scaler.x = layout->bounds.x + layout->bounds.w + panel_padding.x; - if (layout->flags & NK_WINDOW_NO_SCROLLBAR) - scaler.x -= scaler.w; - - /* draw scaler */ - {const struct nk_style_item *item = &style->window.scaler; - if (item->type == NK_STYLE_ITEM_IMAGE) - nk_draw_image(out, scaler, &item->data.image, nk_white); - else { - if (layout->flags & NK_WINDOW_SCALE_LEFT) { - nk_fill_triangle(out, scaler.x, scaler.y, scaler.x, - scaler.y + scaler.h, scaler.x + scaler.w, - scaler.y + scaler.h, item->data.color); - } else { - nk_fill_triangle(out, scaler.x + scaler.w, scaler.y, scaler.x + scaler.w, - scaler.y + scaler.h, scaler.x, scaler.y + scaler.h, item->data.color); - } - }} - - /* do window scaling */ - if (!(window->flags & NK_WINDOW_ROM)) { - struct nk_vec2 window_size = style->window.min_size; - int left_mouse_down = in->mouse.buttons[NK_BUTTON_LEFT].down; - int left_mouse_click_in_scaler = nk_input_has_mouse_click_down_in_rect(in, - NK_BUTTON_LEFT, scaler, nk_true); - - if (left_mouse_down && left_mouse_click_in_scaler) { - float delta_x = in->mouse.delta.x; - if (layout->flags & NK_WINDOW_SCALE_LEFT) { - delta_x = -delta_x; - window->bounds.x += in->mouse.delta.x; - } - /* dragging in x-direction */ - if (window->bounds.w + delta_x >= window_size.x) { - if ((delta_x < 0) || (delta_x > 0 && in->mouse.pos.x >= scaler.x)) { - window->bounds.w = window->bounds.w + delta_x; - scaler.x += in->mouse.delta.x; - } - } - /* dragging in y-direction (only possible if static window) */ - if (!(layout->flags & NK_WINDOW_DYNAMIC)) { - if (window_size.y < window->bounds.h + in->mouse.delta.y) { - if ((in->mouse.delta.y < 0) || (in->mouse.delta.y > 0 && in->mouse.pos.y >= scaler.y)) { - window->bounds.h = window->bounds.h + in->mouse.delta.y; - scaler.y += in->mouse.delta.y; - } - } - } - ctx->style.cursor_active = ctx->style.cursors[NK_CURSOR_RESIZE_TOP_RIGHT_DOWN_LEFT]; - in->mouse.buttons[NK_BUTTON_LEFT].clicked_pos.x = scaler.x + scaler.w/2.0f; - in->mouse.buttons[NK_BUTTON_LEFT].clicked_pos.y = scaler.y + scaler.h/2.0f; - } - } - } - if (!nk_panel_is_sub(layout->type)) { - /* window is hidden so clear command buffer */ - if (layout->flags & NK_WINDOW_HIDDEN) - nk_command_buffer_reset(&window->buffer); - /* window is visible and not tab */ - else nk_finish(ctx, window); - } - - /* NK_WINDOW_REMOVE_ROM flag was set so remove NK_WINDOW_ROM */ - if (layout->flags & NK_WINDOW_REMOVE_ROM) { - layout->flags &= ~(nk_flags)NK_WINDOW_ROM; - layout->flags &= ~(nk_flags)NK_WINDOW_REMOVE_ROM; - } - window->flags = layout->flags; - - /* property garbage collector */ - if (window->property.active && window->property.old != window->property.seq && - window->property.active == window->property.prev) { - nk_zero(&window->property, sizeof(window->property)); - } else { - window->property.old = window->property.seq; - window->property.prev = window->property.active; - window->property.seq = 0; - } - /* edit garbage collector */ - if (window->edit.active && window->edit.old != window->edit.seq && - window->edit.active == window->edit.prev) { - nk_zero(&window->edit, sizeof(window->edit)); - } else { - window->edit.old = window->edit.seq; - window->edit.prev = window->edit.active; - window->edit.seq = 0; - } - /* contextual garbage collector */ - if (window->popup.active_con && window->popup.con_old != window->popup.con_count) { - window->popup.con_count = 0; - window->popup.con_old = 0; - window->popup.active_con = 0; - } else { - window->popup.con_old = window->popup.con_count; - window->popup.con_count = 0; - } - window->popup.combo_count = 0; - /* helper to make sure you have a 'nk_tree_push' for every 'nk_tree_pop' */ - NK_ASSERT(!layout->row.tree_depth); -} - - - - - -/* =============================================================== - * - * WINDOW - * - * ===============================================================*/ -NK_LIB void* -nk_create_window(struct nk_context *ctx) -{ - struct nk_page_element *elem; - elem = nk_create_page_element(ctx); - if (!elem) return 0; - elem->data.win.seq = ctx->seq; - return &elem->data.win; -} -NK_LIB void -nk_free_window(struct nk_context *ctx, struct nk_window *win) -{ - /* unlink windows from list */ - struct nk_table *it = win->tables; - if (win->popup.win) { - nk_free_window(ctx, win->popup.win); - win->popup.win = 0; - } - win->next = 0; - win->prev = 0; - - while (it) { - /*free window state tables */ - struct nk_table *n = it->next; - nk_remove_table(win, it); - nk_free_table(ctx, it); - if (it == win->tables) - win->tables = n; - it = n; - } - - /* link windows into freelist */ - {union nk_page_data *pd = NK_CONTAINER_OF(win, union nk_page_data, win); - struct nk_page_element *pe = NK_CONTAINER_OF(pd, struct nk_page_element, data); - nk_free_page_element(ctx, pe);} -} -NK_LIB struct nk_window* -nk_find_window(struct nk_context *ctx, nk_hash hash, const char *name) -{ - struct nk_window *iter; - iter = ctx->begin; - while (iter) { - NK_ASSERT(iter != iter->next); - if (iter->name == hash) { - int max_len = nk_strlen(iter->name_string); - if (!nk_stricmpn(iter->name_string, name, max_len)) - return iter; - } - iter = iter->next; - } - return 0; -} -NK_LIB void -nk_insert_window(struct nk_context *ctx, struct nk_window *win, - enum nk_window_insert_location loc) -{ - const struct nk_window *iter; - NK_ASSERT(ctx); - NK_ASSERT(win); - if (!win || !ctx) return; - - iter = ctx->begin; - while (iter) { - NK_ASSERT(iter != iter->next); - NK_ASSERT(iter != win); - if (iter == win) return; - iter = iter->next; - } - - if (!ctx->begin) { - win->next = 0; - win->prev = 0; - ctx->begin = win; - ctx->end = win; - ctx->count = 1; - return; - } - if (loc == NK_INSERT_BACK) { - struct nk_window *end; - end = ctx->end; - end->flags |= NK_WINDOW_ROM; - end->next = win; - win->prev = ctx->end; - win->next = 0; - ctx->end = win; - ctx->active = ctx->end; - ctx->end->flags &= ~(nk_flags)NK_WINDOW_ROM; - } else { - /*ctx->end->flags |= NK_WINDOW_ROM;*/ - ctx->begin->prev = win; - win->next = ctx->begin; - win->prev = 0; - ctx->begin = win; - ctx->begin->flags &= ~(nk_flags)NK_WINDOW_ROM; - } - ctx->count++; -} -NK_LIB void -nk_remove_window(struct nk_context *ctx, struct nk_window *win) -{ - if (win == ctx->begin || win == ctx->end) { - if (win == ctx->begin) { - ctx->begin = win->next; - if (win->next) - win->next->prev = 0; - } - if (win == ctx->end) { - ctx->end = win->prev; - if (win->prev) - win->prev->next = 0; - } - } else { - if (win->next) - win->next->prev = win->prev; - if (win->prev) - win->prev->next = win->next; - } - if (win == ctx->active || !ctx->active) { - ctx->active = ctx->end; - if (ctx->end) - ctx->end->flags &= ~(nk_flags)NK_WINDOW_ROM; - } - win->next = 0; - win->prev = 0; - ctx->count--; -} -NK_API int -nk_begin(struct nk_context *ctx, const char *title, - struct nk_rect bounds, nk_flags flags) -{ - return nk_begin_titled(ctx, title, title, bounds, flags); -} -NK_API int -nk_begin_titled(struct nk_context *ctx, const char *name, const char *title, - struct nk_rect bounds, nk_flags flags) -{ - struct nk_window *win; - struct nk_style *style; - nk_hash title_hash; - int title_len; - int ret = 0; - - NK_ASSERT(ctx); - NK_ASSERT(name); - NK_ASSERT(title); - NK_ASSERT(ctx->style.font && ctx->style.font->width && "if this triggers you forgot to add a font"); - NK_ASSERT(!ctx->current && "if this triggers you missed a `nk_end` call"); - if (!ctx || ctx->current || !title || !name) - return 0; - - /* find or create window */ - style = &ctx->style; - title_len = (int)nk_strlen(name); - title_hash = nk_murmur_hash(name, (int)title_len, NK_WINDOW_TITLE); - win = nk_find_window(ctx, title_hash, name); - if (!win) { - /* create new window */ - nk_size name_length = (nk_size)nk_strlen(name); - win = (struct nk_window*)nk_create_window(ctx); - NK_ASSERT(win); - if (!win) return 0; - - if (flags & NK_WINDOW_BACKGROUND) - nk_insert_window(ctx, win, NK_INSERT_FRONT); - else nk_insert_window(ctx, win, NK_INSERT_BACK); - nk_command_buffer_init(&win->buffer, &ctx->memory, NK_CLIPPING_ON); - - win->flags = flags; - win->bounds = bounds; - win->name = title_hash; - name_length = NK_MIN(name_length, NK_WINDOW_MAX_NAME-1); - NK_MEMCPY(win->name_string, name, name_length); - win->name_string[name_length] = 0; - win->popup.win = 0; - if (!ctx->active) - ctx->active = win; - } else { - /* update window */ - win->flags &= ~(nk_flags)(NK_WINDOW_PRIVATE-1); - win->flags |= flags; - if (!(win->flags & (NK_WINDOW_MOVABLE | NK_WINDOW_SCALABLE))) - win->bounds = bounds; - /* If this assert triggers you either: - * - * I.) Have more than one window with the same name or - * II.) You forgot to actually draw the window. - * More specific you did not call `nk_clear` (nk_clear will be - * automatically called for you if you are using one of the - * provided demo backends). */ - NK_ASSERT(win->seq != ctx->seq); - win->seq = ctx->seq; - if (!ctx->active && !(win->flags & NK_WINDOW_HIDDEN)) { - ctx->active = win; - ctx->end = win; - } - } - if (win->flags & NK_WINDOW_HIDDEN) { - ctx->current = win; - win->layout = 0; - return 0; - } else nk_start(ctx, win); - - /* window overlapping */ - if (!(win->flags & NK_WINDOW_HIDDEN) && !(win->flags & NK_WINDOW_NO_INPUT)) - { - int inpanel, ishovered; - struct nk_window *iter = win; - float h = ctx->style.font->height + 2.0f * style->window.header.padding.y + - (2.0f * style->window.header.label_padding.y); - struct nk_rect win_bounds = (!(win->flags & NK_WINDOW_MINIMIZED))? - win->bounds: nk_rect(win->bounds.x, win->bounds.y, win->bounds.w, h); - - /* activate window if hovered and no other window is overlapping this window */ - inpanel = nk_input_has_mouse_click_down_in_rect(&ctx->input, NK_BUTTON_LEFT, win_bounds, nk_true); - inpanel = inpanel && ctx->input.mouse.buttons[NK_BUTTON_LEFT].clicked; - ishovered = nk_input_is_mouse_hovering_rect(&ctx->input, win_bounds); - if ((win != ctx->active) && ishovered && !ctx->input.mouse.buttons[NK_BUTTON_LEFT].down) { - iter = win->next; - while (iter) { - struct nk_rect iter_bounds = (!(iter->flags & NK_WINDOW_MINIMIZED))? - iter->bounds: nk_rect(iter->bounds.x, iter->bounds.y, iter->bounds.w, h); - if (NK_INTERSECT(win_bounds.x, win_bounds.y, win_bounds.w, win_bounds.h, - iter_bounds.x, iter_bounds.y, iter_bounds.w, iter_bounds.h) && - (!(iter->flags & NK_WINDOW_HIDDEN))) - break; - - if (iter->popup.win && iter->popup.active && !(iter->flags & NK_WINDOW_HIDDEN) && - NK_INTERSECT(win->bounds.x, win_bounds.y, win_bounds.w, win_bounds.h, - iter->popup.win->bounds.x, iter->popup.win->bounds.y, - iter->popup.win->bounds.w, iter->popup.win->bounds.h)) - break; - iter = iter->next; - } - } - - /* activate window if clicked */ - if (iter && inpanel && (win != ctx->end)) { - iter = win->next; - while (iter) { - /* try to find a panel with higher priority in the same position */ - struct nk_rect iter_bounds = (!(iter->flags & NK_WINDOW_MINIMIZED))? - iter->bounds: nk_rect(iter->bounds.x, iter->bounds.y, iter->bounds.w, h); - if (NK_INBOX(ctx->input.mouse.pos.x, ctx->input.mouse.pos.y, - iter_bounds.x, iter_bounds.y, iter_bounds.w, iter_bounds.h) && - !(iter->flags & NK_WINDOW_HIDDEN)) - break; - if (iter->popup.win && iter->popup.active && !(iter->flags & NK_WINDOW_HIDDEN) && - NK_INTERSECT(win_bounds.x, win_bounds.y, win_bounds.w, win_bounds.h, - iter->popup.win->bounds.x, iter->popup.win->bounds.y, - iter->popup.win->bounds.w, iter->popup.win->bounds.h)) - break; - iter = iter->next; - } - } - if (iter && !(win->flags & NK_WINDOW_ROM) && (win->flags & NK_WINDOW_BACKGROUND)) { - win->flags |= (nk_flags)NK_WINDOW_ROM; - iter->flags &= ~(nk_flags)NK_WINDOW_ROM; - ctx->active = iter; - if (!(iter->flags & NK_WINDOW_BACKGROUND)) { - /* current window is active in that position so transfer to top - * at the highest priority in stack */ - nk_remove_window(ctx, iter); - nk_insert_window(ctx, iter, NK_INSERT_BACK); - } - } else { - if (!iter && ctx->end != win) { - if (!(win->flags & NK_WINDOW_BACKGROUND)) { - /* current window is active in that position so transfer to top - * at the highest priority in stack */ - nk_remove_window(ctx, win); - nk_insert_window(ctx, win, NK_INSERT_BACK); - } - win->flags &= ~(nk_flags)NK_WINDOW_ROM; - ctx->active = win; - } - if (ctx->end != win && !(win->flags & NK_WINDOW_BACKGROUND)) - win->flags |= NK_WINDOW_ROM; - } - } - win->layout = (struct nk_panel*)nk_create_panel(ctx); - ctx->current = win; - ret = nk_panel_begin(ctx, title, NK_PANEL_WINDOW); - win->layout->offset_x = &win->scrollbar.x; - win->layout->offset_y = &win->scrollbar.y; - return ret; -} -NK_API void -nk_end(struct nk_context *ctx) -{ - struct nk_panel *layout; - NK_ASSERT(ctx); - NK_ASSERT(ctx->current && "if this triggers you forgot to call `nk_begin`"); - if (!ctx || !ctx->current) - return; - - layout = ctx->current->layout; - if (!layout || (layout->type == NK_PANEL_WINDOW && (ctx->current->flags & NK_WINDOW_HIDDEN))) { - ctx->current = 0; - return; - } - nk_panel_end(ctx); - nk_free_panel(ctx, ctx->current->layout); - ctx->current = 0; -} -NK_API struct nk_rect -nk_window_get_bounds(const struct nk_context *ctx) -{ - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - if (!ctx || !ctx->current) return nk_rect(0,0,0,0); - return ctx->current->bounds; -} -NK_API struct nk_vec2 -nk_window_get_position(const struct nk_context *ctx) -{ - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - if (!ctx || !ctx->current) return nk_vec2(0,0); - return nk_vec2(ctx->current->bounds.x, ctx->current->bounds.y); -} -NK_API struct nk_vec2 -nk_window_get_size(const struct nk_context *ctx) -{ - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - if (!ctx || !ctx->current) return nk_vec2(0,0); - return nk_vec2(ctx->current->bounds.w, ctx->current->bounds.h); -} -NK_API float -nk_window_get_width(const struct nk_context *ctx) -{ - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - if (!ctx || !ctx->current) return 0; - return ctx->current->bounds.w; -} -NK_API float -nk_window_get_height(const struct nk_context *ctx) -{ - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - if (!ctx || !ctx->current) return 0; - return ctx->current->bounds.h; -} -NK_API struct nk_rect -nk_window_get_content_region(struct nk_context *ctx) -{ - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - if (!ctx || !ctx->current) return nk_rect(0,0,0,0); - return ctx->current->layout->clip; -} -NK_API struct nk_vec2 -nk_window_get_content_region_min(struct nk_context *ctx) -{ - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current) return nk_vec2(0,0); - return nk_vec2(ctx->current->layout->clip.x, ctx->current->layout->clip.y); -} -NK_API struct nk_vec2 -nk_window_get_content_region_max(struct nk_context *ctx) -{ - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current) return nk_vec2(0,0); - return nk_vec2(ctx->current->layout->clip.x + ctx->current->layout->clip.w, - ctx->current->layout->clip.y + ctx->current->layout->clip.h); -} -NK_API struct nk_vec2 -nk_window_get_content_region_size(struct nk_context *ctx) -{ - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current) return nk_vec2(0,0); - return nk_vec2(ctx->current->layout->clip.w, ctx->current->layout->clip.h); -} -NK_API struct nk_command_buffer* -nk_window_get_canvas(struct nk_context *ctx) -{ - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current) return 0; - return &ctx->current->buffer; -} -NK_API struct nk_panel* -nk_window_get_panel(struct nk_context *ctx) -{ - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - if (!ctx || !ctx->current) return 0; - return ctx->current->layout; -} -NK_API int -nk_window_has_focus(const struct nk_context *ctx) -{ - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current) return 0; - return ctx->current == ctx->active; -} -NK_API int -nk_window_is_hovered(struct nk_context *ctx) -{ - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - if (!ctx || !ctx->current) return 0; - if(ctx->current->flags & NK_WINDOW_HIDDEN) - return 0; - return nk_input_is_mouse_hovering_rect(&ctx->input, ctx->current->bounds); -} -NK_API int -nk_window_is_any_hovered(struct nk_context *ctx) -{ - struct nk_window *iter; - NK_ASSERT(ctx); - if (!ctx) return 0; - iter = ctx->begin; - while (iter) { - /* check if window is being hovered */ - if(!(iter->flags & NK_WINDOW_HIDDEN)) { - /* check if window popup is being hovered */ - if (iter->popup.active && iter->popup.win && nk_input_is_mouse_hovering_rect(&ctx->input, iter->popup.win->bounds)) - return 1; - - if (iter->flags & NK_WINDOW_MINIMIZED) { - struct nk_rect header = iter->bounds; - header.h = ctx->style.font->height + 2 * ctx->style.window.header.padding.y; - if (nk_input_is_mouse_hovering_rect(&ctx->input, header)) - return 1; - } else if (nk_input_is_mouse_hovering_rect(&ctx->input, iter->bounds)) { - return 1; - } - } - iter = iter->next; - } - return 0; -} -NK_API int -nk_item_is_any_active(struct nk_context *ctx) -{ - int any_hovered = nk_window_is_any_hovered(ctx); - int any_active = (ctx->last_widget_state & NK_WIDGET_STATE_MODIFIED); - return any_hovered || any_active; -} -NK_API int -nk_window_is_collapsed(struct nk_context *ctx, const char *name) -{ - int title_len; - nk_hash title_hash; - struct nk_window *win; - NK_ASSERT(ctx); - if (!ctx) return 0; - - title_len = (int)nk_strlen(name); - title_hash = nk_murmur_hash(name, (int)title_len, NK_WINDOW_TITLE); - win = nk_find_window(ctx, title_hash, name); - if (!win) return 0; - return win->flags & NK_WINDOW_MINIMIZED; -} -NK_API int -nk_window_is_closed(struct nk_context *ctx, const char *name) -{ - int title_len; - nk_hash title_hash; - struct nk_window *win; - NK_ASSERT(ctx); - if (!ctx) return 1; - - title_len = (int)nk_strlen(name); - title_hash = nk_murmur_hash(name, (int)title_len, NK_WINDOW_TITLE); - win = nk_find_window(ctx, title_hash, name); - if (!win) return 1; - return (win->flags & NK_WINDOW_CLOSED); -} -NK_API int -nk_window_is_hidden(struct nk_context *ctx, const char *name) -{ - int title_len; - nk_hash title_hash; - struct nk_window *win; - NK_ASSERT(ctx); - if (!ctx) return 1; - - title_len = (int)nk_strlen(name); - title_hash = nk_murmur_hash(name, (int)title_len, NK_WINDOW_TITLE); - win = nk_find_window(ctx, title_hash, name); - if (!win) return 1; - return (win->flags & NK_WINDOW_HIDDEN); -} -NK_API int -nk_window_is_active(struct nk_context *ctx, const char *name) -{ - int title_len; - nk_hash title_hash; - struct nk_window *win; - NK_ASSERT(ctx); - if (!ctx) return 0; - - title_len = (int)nk_strlen(name); - title_hash = nk_murmur_hash(name, (int)title_len, NK_WINDOW_TITLE); - win = nk_find_window(ctx, title_hash, name); - if (!win) return 0; - return win == ctx->active; -} -NK_API struct nk_window* -nk_window_find(struct nk_context *ctx, const char *name) -{ - int title_len; - nk_hash title_hash; - title_len = (int)nk_strlen(name); - title_hash = nk_murmur_hash(name, (int)title_len, NK_WINDOW_TITLE); - return nk_find_window(ctx, title_hash, name); -} -NK_API void -nk_window_close(struct nk_context *ctx, const char *name) -{ - struct nk_window *win; - NK_ASSERT(ctx); - if (!ctx) return; - win = nk_window_find(ctx, name); - if (!win) return; - NK_ASSERT(ctx->current != win && "You cannot close a currently active window"); - if (ctx->current == win) return; - win->flags |= NK_WINDOW_HIDDEN; - win->flags |= NK_WINDOW_CLOSED; -} -NK_API void -nk_window_set_bounds(struct nk_context *ctx, - const char *name, struct nk_rect bounds) -{ - struct nk_window *win; - NK_ASSERT(ctx); - if (!ctx) return; - win = nk_window_find(ctx, name); - if (!win) return; - NK_ASSERT(ctx->current != win && "You cannot update a currently in procecss window"); - win->bounds = bounds; -} -NK_API void -nk_window_set_position(struct nk_context *ctx, - const char *name, struct nk_vec2 pos) -{ - struct nk_window *win = nk_window_find(ctx, name); - if (!win) return; - win->bounds.x = pos.x; - win->bounds.y = pos.y; -} -NK_API void -nk_window_set_size(struct nk_context *ctx, - const char *name, struct nk_vec2 size) -{ - struct nk_window *win = nk_window_find(ctx, name); - if (!win) return; - win->bounds.w = size.x; - win->bounds.h = size.y; -} -NK_API void -nk_window_collapse(struct nk_context *ctx, const char *name, - enum nk_collapse_states c) -{ - int title_len; - nk_hash title_hash; - struct nk_window *win; - NK_ASSERT(ctx); - if (!ctx) return; - - title_len = (int)nk_strlen(name); - title_hash = nk_murmur_hash(name, (int)title_len, NK_WINDOW_TITLE); - win = nk_find_window(ctx, title_hash, name); - if (!win) return; - if (c == NK_MINIMIZED) - win->flags |= NK_WINDOW_MINIMIZED; - else win->flags &= ~(nk_flags)NK_WINDOW_MINIMIZED; -} -NK_API void -nk_window_collapse_if(struct nk_context *ctx, const char *name, - enum nk_collapse_states c, int cond) -{ - NK_ASSERT(ctx); - if (!ctx || !cond) return; - nk_window_collapse(ctx, name, c); -} -NK_API void -nk_window_show(struct nk_context *ctx, const char *name, enum nk_show_states s) -{ - int title_len; - nk_hash title_hash; - struct nk_window *win; - NK_ASSERT(ctx); - if (!ctx) return; - - title_len = (int)nk_strlen(name); - title_hash = nk_murmur_hash(name, (int)title_len, NK_WINDOW_TITLE); - win = nk_find_window(ctx, title_hash, name); - if (!win) return; - if (s == NK_HIDDEN) { - win->flags |= NK_WINDOW_HIDDEN; - } else win->flags &= ~(nk_flags)NK_WINDOW_HIDDEN; -} -NK_API void -nk_window_show_if(struct nk_context *ctx, const char *name, - enum nk_show_states s, int cond) -{ - NK_ASSERT(ctx); - if (!ctx || !cond) return; - nk_window_show(ctx, name, s); -} - -NK_API void -nk_window_set_focus(struct nk_context *ctx, const char *name) -{ - int title_len; - nk_hash title_hash; - struct nk_window *win; - NK_ASSERT(ctx); - if (!ctx) return; - - title_len = (int)nk_strlen(name); - title_hash = nk_murmur_hash(name, (int)title_len, NK_WINDOW_TITLE); - win = nk_find_window(ctx, title_hash, name); - if (win && ctx->end != win) { - nk_remove_window(ctx, win); - nk_insert_window(ctx, win, NK_INSERT_BACK); - } - ctx->active = win; -} - - - - - -/* =============================================================== - * - * POPUP - * - * ===============================================================*/ -NK_API int -nk_popup_begin(struct nk_context *ctx, enum nk_popup_type type, - const char *title, nk_flags flags, struct nk_rect rect) -{ - struct nk_window *popup; - struct nk_window *win; - struct nk_panel *panel; - - int title_len; - nk_hash title_hash; - nk_size allocated; - - NK_ASSERT(ctx); - NK_ASSERT(title); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return 0; - - win = ctx->current; - panel = win->layout; - NK_ASSERT(!(panel->type & NK_PANEL_SET_POPUP) && "popups are not allowed to have popups"); - (void)panel; - title_len = (int)nk_strlen(title); - title_hash = nk_murmur_hash(title, (int)title_len, NK_PANEL_POPUP); - - popup = win->popup.win; - if (!popup) { - popup = (struct nk_window*)nk_create_window(ctx); - popup->parent = win; - win->popup.win = popup; - win->popup.active = 0; - win->popup.type = NK_PANEL_POPUP; - } - - /* make sure we have correct popup */ - if (win->popup.name != title_hash) { - if (!win->popup.active) { - nk_zero(popup, sizeof(*popup)); - win->popup.name = title_hash; - win->popup.active = 1; - win->popup.type = NK_PANEL_POPUP; - } else return 0; - } - - /* popup position is local to window */ - ctx->current = popup; - rect.x += win->layout->clip.x; - rect.y += win->layout->clip.y; - - /* setup popup data */ - popup->parent = win; - popup->bounds = rect; - popup->seq = ctx->seq; - popup->layout = (struct nk_panel*)nk_create_panel(ctx); - popup->flags = flags; - popup->flags |= NK_WINDOW_BORDER; - if (type == NK_POPUP_DYNAMIC) - popup->flags |= NK_WINDOW_DYNAMIC; - - popup->buffer = win->buffer; - nk_start_popup(ctx, win); - allocated = ctx->memory.allocated; - nk_push_scissor(&popup->buffer, nk_null_rect); - - if (nk_panel_begin(ctx, title, NK_PANEL_POPUP)) { - /* popup is running therefore invalidate parent panels */ - struct nk_panel *root; - root = win->layout; - while (root) { - root->flags |= NK_WINDOW_ROM; - root->flags &= ~(nk_flags)NK_WINDOW_REMOVE_ROM; - root = root->parent; - } - win->popup.active = 1; - popup->layout->offset_x = &popup->scrollbar.x; - popup->layout->offset_y = &popup->scrollbar.y; - popup->layout->parent = win->layout; - return 1; - } else { - /* popup was closed/is invalid so cleanup */ - struct nk_panel *root; - root = win->layout; - while (root) { - root->flags |= NK_WINDOW_REMOVE_ROM; - root = root->parent; - } - win->popup.buf.active = 0; - win->popup.active = 0; - ctx->memory.allocated = allocated; - ctx->current = win; - nk_free_panel(ctx, popup->layout); - popup->layout = 0; - return 0; - } -} -NK_LIB int -nk_nonblock_begin(struct nk_context *ctx, - nk_flags flags, struct nk_rect body, struct nk_rect header, - enum nk_panel_type panel_type) -{ - struct nk_window *popup; - struct nk_window *win; - struct nk_panel *panel; - int is_active = nk_true; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return 0; - - /* popups cannot have popups */ - win = ctx->current; - panel = win->layout; - NK_ASSERT(!(panel->type & NK_PANEL_SET_POPUP)); - (void)panel; - popup = win->popup.win; - if (!popup) { - /* create window for nonblocking popup */ - popup = (struct nk_window*)nk_create_window(ctx); - popup->parent = win; - win->popup.win = popup; - win->popup.type = panel_type; - nk_command_buffer_init(&popup->buffer, &ctx->memory, NK_CLIPPING_ON); - } else { - /* close the popup if user pressed outside or in the header */ - int pressed, in_body, in_header; - pressed = nk_input_is_mouse_pressed(&ctx->input, NK_BUTTON_LEFT); - in_body = nk_input_is_mouse_hovering_rect(&ctx->input, body); - in_header = nk_input_is_mouse_hovering_rect(&ctx->input, header); - if (pressed && (!in_body || in_header)) - is_active = nk_false; - } - win->popup.header = header; - - if (!is_active) { - /* remove read only mode from all parent panels */ - struct nk_panel *root = win->layout; - while (root) { - root->flags |= NK_WINDOW_REMOVE_ROM; - root = root->parent; - } - return is_active; - } - popup->bounds = body; - popup->parent = win; - popup->layout = (struct nk_panel*)nk_create_panel(ctx); - popup->flags = flags; - popup->flags |= NK_WINDOW_BORDER; - popup->flags |= NK_WINDOW_DYNAMIC; - popup->seq = ctx->seq; - win->popup.active = 1; - NK_ASSERT(popup->layout); - - nk_start_popup(ctx, win); - popup->buffer = win->buffer; - nk_push_scissor(&popup->buffer, nk_null_rect); - ctx->current = popup; - - nk_panel_begin(ctx, 0, panel_type); - win->buffer = popup->buffer; - popup->layout->parent = win->layout; - popup->layout->offset_x = &popup->scrollbar.x; - popup->layout->offset_y = &popup->scrollbar.y; - - /* set read only mode to all parent panels */ - {struct nk_panel *root; - root = win->layout; - while (root) { - root->flags |= NK_WINDOW_ROM; - root = root->parent; - }} - return is_active; -} -NK_API void -nk_popup_close(struct nk_context *ctx) -{ - struct nk_window *popup; - NK_ASSERT(ctx); - if (!ctx || !ctx->current) return; - - popup = ctx->current; - NK_ASSERT(popup->parent); - NK_ASSERT(popup->layout->type & NK_PANEL_SET_POPUP); - popup->flags |= NK_WINDOW_HIDDEN; -} -NK_API void -nk_popup_end(struct nk_context *ctx) -{ - struct nk_window *win; - struct nk_window *popup; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return; - - popup = ctx->current; - if (!popup->parent) return; - win = popup->parent; - if (popup->flags & NK_WINDOW_HIDDEN) { - struct nk_panel *root; - root = win->layout; - while (root) { - root->flags |= NK_WINDOW_REMOVE_ROM; - root = root->parent; - } - win->popup.active = 0; - } - nk_push_scissor(&popup->buffer, nk_null_rect); - nk_end(ctx); - - win->buffer = popup->buffer; - nk_finish_popup(ctx, win); - ctx->current = win; - nk_push_scissor(&win->buffer, win->layout->clip); -} - - - - - -/* ============================================================== - * - * CONTEXTUAL - * - * ===============================================================*/ -NK_API int -nk_contextual_begin(struct nk_context *ctx, nk_flags flags, struct nk_vec2 size, - struct nk_rect trigger_bounds) -{ - struct nk_window *win; - struct nk_window *popup; - struct nk_rect body; - - NK_STORAGE const struct nk_rect null_rect = {-1,-1,0,0}; - int is_clicked = 0; - int is_open = 0; - int ret = 0; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return 0; - - win = ctx->current; - ++win->popup.con_count; - if (ctx->current != ctx->active) - return 0; - - /* check if currently active contextual is active */ - popup = win->popup.win; - is_open = (popup && win->popup.type == NK_PANEL_CONTEXTUAL); - is_clicked = nk_input_mouse_clicked(&ctx->input, NK_BUTTON_RIGHT, trigger_bounds); - if (win->popup.active_con && win->popup.con_count != win->popup.active_con) - return 0; - if (!is_open && win->popup.active_con) - win->popup.active_con = 0; - if ((!is_open && !is_clicked)) - return 0; - - /* calculate contextual position on click */ - win->popup.active_con = win->popup.con_count; - if (is_clicked) { - body.x = ctx->input.mouse.pos.x; - body.y = ctx->input.mouse.pos.y; - } else { - body.x = popup->bounds.x; - body.y = popup->bounds.y; - } - body.w = size.x; - body.h = size.y; - - /* start nonblocking contextual popup */ - ret = nk_nonblock_begin(ctx, flags|NK_WINDOW_NO_SCROLLBAR, body, - null_rect, NK_PANEL_CONTEXTUAL); - if (ret) win->popup.type = NK_PANEL_CONTEXTUAL; - else { - win->popup.active_con = 0; - win->popup.type = NK_PANEL_NONE; - if (win->popup.win) - win->popup.win->flags = 0; - } - return ret; -} -NK_API int -nk_contextual_item_text(struct nk_context *ctx, const char *text, int len, - nk_flags alignment) -{ - struct nk_window *win; - const struct nk_input *in; - const struct nk_style *style; - - struct nk_rect bounds; - enum nk_widget_layout_states state; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return 0; - - win = ctx->current; - style = &ctx->style; - state = nk_widget_fitting(&bounds, ctx, style->contextual_button.padding); - if (!state) return nk_false; - - in = (state == NK_WIDGET_ROM || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; - if (nk_do_button_text(&ctx->last_widget_state, &win->buffer, bounds, - text, len, alignment, NK_BUTTON_DEFAULT, &style->contextual_button, in, style->font)) { - nk_contextual_close(ctx); - return nk_true; - } - return nk_false; -} -NK_API int -nk_contextual_item_label(struct nk_context *ctx, const char *label, nk_flags align) -{ - return nk_contextual_item_text(ctx, label, nk_strlen(label), align); -} -NK_API int -nk_contextual_item_image_text(struct nk_context *ctx, struct nk_image img, - const char *text, int len, nk_flags align) -{ - struct nk_window *win; - const struct nk_input *in; - const struct nk_style *style; - - struct nk_rect bounds; - enum nk_widget_layout_states state; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return 0; - - win = ctx->current; - style = &ctx->style; - state = nk_widget_fitting(&bounds, ctx, style->contextual_button.padding); - if (!state) return nk_false; - - in = (state == NK_WIDGET_ROM || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; - if (nk_do_button_text_image(&ctx->last_widget_state, &win->buffer, bounds, - img, text, len, align, NK_BUTTON_DEFAULT, &style->contextual_button, style->font, in)){ - nk_contextual_close(ctx); - return nk_true; - } - return nk_false; -} -NK_API int -nk_contextual_item_image_label(struct nk_context *ctx, struct nk_image img, - const char *label, nk_flags align) -{ - return nk_contextual_item_image_text(ctx, img, label, nk_strlen(label), align); -} -NK_API int -nk_contextual_item_symbol_text(struct nk_context *ctx, enum nk_symbol_type symbol, - const char *text, int len, nk_flags align) -{ - struct nk_window *win; - const struct nk_input *in; - const struct nk_style *style; - - struct nk_rect bounds; - enum nk_widget_layout_states state; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return 0; - - win = ctx->current; - style = &ctx->style; - state = nk_widget_fitting(&bounds, ctx, style->contextual_button.padding); - if (!state) return nk_false; - - in = (state == NK_WIDGET_ROM || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; - if (nk_do_button_text_symbol(&ctx->last_widget_state, &win->buffer, bounds, - symbol, text, len, align, NK_BUTTON_DEFAULT, &style->contextual_button, style->font, in)) { - nk_contextual_close(ctx); - return nk_true; - } - return nk_false; -} -NK_API int -nk_contextual_item_symbol_label(struct nk_context *ctx, enum nk_symbol_type symbol, - const char *text, nk_flags align) -{ - return nk_contextual_item_symbol_text(ctx, symbol, text, nk_strlen(text), align); -} -NK_API void -nk_contextual_close(struct nk_context *ctx) -{ - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) return; - nk_popup_close(ctx); -} -NK_API void -nk_contextual_end(struct nk_context *ctx) -{ - struct nk_window *popup; - struct nk_panel *panel; - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - if (!ctx || !ctx->current) return; - - popup = ctx->current; - panel = popup->layout; - NK_ASSERT(popup->parent); - NK_ASSERT(panel->type & NK_PANEL_SET_POPUP); - if (panel->flags & NK_WINDOW_DYNAMIC) { - /* Close behavior - This is a bit of a hack solution since we do not know before we end our popup - how big it will be. We therefore do not directly know when a - click outside the non-blocking popup must close it at that direct frame. - Instead it will be closed in the next frame.*/ - struct nk_rect body = {0,0,0,0}; - if (panel->at_y < (panel->bounds.y + panel->bounds.h)) { - struct nk_vec2 padding = nk_panel_get_padding(&ctx->style, panel->type); - body = panel->bounds; - body.y = (panel->at_y + panel->footer_height + panel->border + padding.y + panel->row.height); - body.h = (panel->bounds.y + panel->bounds.h) - body.y; - } - {int pressed = nk_input_is_mouse_pressed(&ctx->input, NK_BUTTON_LEFT); - int in_body = nk_input_is_mouse_hovering_rect(&ctx->input, body); - if (pressed && in_body) - popup->flags |= NK_WINDOW_HIDDEN; - } - } - if (popup->flags & NK_WINDOW_HIDDEN) - popup->seq = 0; - nk_popup_end(ctx); - return; -} - - - - - -/* =============================================================== - * - * MENU - * - * ===============================================================*/ -NK_API void -nk_menubar_begin(struct nk_context *ctx) -{ - struct nk_panel *layout; - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return; - - layout = ctx->current->layout; - NK_ASSERT(layout->at_y == layout->bounds.y); - /* if this assert triggers you allocated space between nk_begin and nk_menubar_begin. - If you want a menubar the first nuklear function after `nk_begin` has to be a - `nk_menubar_begin` call. Inside the menubar you then have to allocate space for - widgets (also supports multiple rows). - Example: - if (nk_begin(...)) { - nk_menubar_begin(...); - nk_layout_xxxx(...); - nk_button(...); - nk_layout_xxxx(...); - nk_button(...); - nk_menubar_end(...); - } - nk_end(...); - */ - if (layout->flags & NK_WINDOW_HIDDEN || layout->flags & NK_WINDOW_MINIMIZED) - return; - - layout->menu.x = layout->at_x; - layout->menu.y = layout->at_y + layout->row.height; - layout->menu.w = layout->bounds.w; - layout->menu.offset.x = *layout->offset_x; - layout->menu.offset.y = *layout->offset_y; - *layout->offset_y = 0; -} -NK_API void -nk_menubar_end(struct nk_context *ctx) -{ - struct nk_window *win; - struct nk_panel *layout; - struct nk_command_buffer *out; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return; - - win = ctx->current; - out = &win->buffer; - layout = win->layout; - if (layout->flags & NK_WINDOW_HIDDEN || layout->flags & NK_WINDOW_MINIMIZED) - return; - - layout->menu.h = layout->at_y - layout->menu.y; - layout->bounds.y += layout->menu.h + ctx->style.window.spacing.y + layout->row.height; - layout->bounds.h -= layout->menu.h + ctx->style.window.spacing.y + layout->row.height; - - *layout->offset_x = layout->menu.offset.x; - *layout->offset_y = layout->menu.offset.y; - layout->at_y = layout->bounds.y - layout->row.height; - - layout->clip.y = layout->bounds.y; - layout->clip.h = layout->bounds.h; - nk_push_scissor(out, layout->clip); -} -NK_INTERN int -nk_menu_begin(struct nk_context *ctx, struct nk_window *win, - const char *id, int is_clicked, struct nk_rect header, struct nk_vec2 size) -{ - int is_open = 0; - int is_active = 0; - struct nk_rect body; - struct nk_window *popup; - nk_hash hash = nk_murmur_hash(id, (int)nk_strlen(id), NK_PANEL_MENU); - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return 0; - - body.x = header.x; - body.w = size.x; - body.y = header.y + header.h; - body.h = size.y; - - popup = win->popup.win; - is_open = popup ? nk_true : nk_false; - is_active = (popup && (win->popup.name == hash) && win->popup.type == NK_PANEL_MENU); - if ((is_clicked && is_open && !is_active) || (is_open && !is_active) || - (!is_open && !is_active && !is_clicked)) return 0; - if (!nk_nonblock_begin(ctx, NK_WINDOW_NO_SCROLLBAR, body, header, NK_PANEL_MENU)) - return 0; - - win->popup.type = NK_PANEL_MENU; - win->popup.name = hash; - return 1; -} -NK_API int -nk_menu_begin_text(struct nk_context *ctx, const char *title, int len, - nk_flags align, struct nk_vec2 size) -{ - struct nk_window *win; - const struct nk_input *in; - struct nk_rect header; - int is_clicked = nk_false; - nk_flags state; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return 0; - - win = ctx->current; - state = nk_widget(&header, ctx); - if (!state) return 0; - in = (state == NK_WIDGET_ROM || win->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; - if (nk_do_button_text(&ctx->last_widget_state, &win->buffer, header, - title, len, align, NK_BUTTON_DEFAULT, &ctx->style.menu_button, in, ctx->style.font)) - is_clicked = nk_true; - return nk_menu_begin(ctx, win, title, is_clicked, header, size); -} -NK_API int nk_menu_begin_label(struct nk_context *ctx, - const char *text, nk_flags align, struct nk_vec2 size) -{ - return nk_menu_begin_text(ctx, text, nk_strlen(text), align, size); -} -NK_API int -nk_menu_begin_image(struct nk_context *ctx, const char *id, struct nk_image img, - struct nk_vec2 size) -{ - struct nk_window *win; - struct nk_rect header; - const struct nk_input *in; - int is_clicked = nk_false; - nk_flags state; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return 0; - - win = ctx->current; - state = nk_widget(&header, ctx); - if (!state) return 0; - in = (state == NK_WIDGET_ROM || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; - if (nk_do_button_image(&ctx->last_widget_state, &win->buffer, header, - img, NK_BUTTON_DEFAULT, &ctx->style.menu_button, in)) - is_clicked = nk_true; - return nk_menu_begin(ctx, win, id, is_clicked, header, size); -} -NK_API int -nk_menu_begin_symbol(struct nk_context *ctx, const char *id, - enum nk_symbol_type sym, struct nk_vec2 size) -{ - struct nk_window *win; - const struct nk_input *in; - struct nk_rect header; - int is_clicked = nk_false; - nk_flags state; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return 0; - - win = ctx->current; - state = nk_widget(&header, ctx); - if (!state) return 0; - in = (state == NK_WIDGET_ROM || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; - if (nk_do_button_symbol(&ctx->last_widget_state, &win->buffer, header, - sym, NK_BUTTON_DEFAULT, &ctx->style.menu_button, in, ctx->style.font)) - is_clicked = nk_true; - return nk_menu_begin(ctx, win, id, is_clicked, header, size); -} -NK_API int -nk_menu_begin_image_text(struct nk_context *ctx, const char *title, int len, - nk_flags align, struct nk_image img, struct nk_vec2 size) -{ - struct nk_window *win; - struct nk_rect header; - const struct nk_input *in; - int is_clicked = nk_false; - nk_flags state; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return 0; - - win = ctx->current; - state = nk_widget(&header, ctx); - if (!state) return 0; - in = (state == NK_WIDGET_ROM || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; - if (nk_do_button_text_image(&ctx->last_widget_state, &win->buffer, - header, img, title, len, align, NK_BUTTON_DEFAULT, &ctx->style.menu_button, - ctx->style.font, in)) - is_clicked = nk_true; - return nk_menu_begin(ctx, win, title, is_clicked, header, size); -} -NK_API int -nk_menu_begin_image_label(struct nk_context *ctx, - const char *title, nk_flags align, struct nk_image img, struct nk_vec2 size) -{ - return nk_menu_begin_image_text(ctx, title, nk_strlen(title), align, img, size); -} -NK_API int -nk_menu_begin_symbol_text(struct nk_context *ctx, const char *title, int len, - nk_flags align, enum nk_symbol_type sym, struct nk_vec2 size) -{ - struct nk_window *win; - struct nk_rect header; - const struct nk_input *in; - int is_clicked = nk_false; - nk_flags state; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return 0; - - win = ctx->current; - state = nk_widget(&header, ctx); - if (!state) return 0; - - in = (state == NK_WIDGET_ROM || win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; - if (nk_do_button_text_symbol(&ctx->last_widget_state, &win->buffer, - header, sym, title, len, align, NK_BUTTON_DEFAULT, &ctx->style.menu_button, - ctx->style.font, in)) is_clicked = nk_true; - return nk_menu_begin(ctx, win, title, is_clicked, header, size); -} -NK_API int -nk_menu_begin_symbol_label(struct nk_context *ctx, - const char *title, nk_flags align, enum nk_symbol_type sym, struct nk_vec2 size ) -{ - return nk_menu_begin_symbol_text(ctx, title, nk_strlen(title), align,sym,size); -} -NK_API int -nk_menu_item_text(struct nk_context *ctx, const char *title, int len, nk_flags align) -{ - return nk_contextual_item_text(ctx, title, len, align); -} -NK_API int -nk_menu_item_label(struct nk_context *ctx, const char *label, nk_flags align) -{ - return nk_contextual_item_label(ctx, label, align); -} -NK_API int -nk_menu_item_image_label(struct nk_context *ctx, struct nk_image img, - const char *label, nk_flags align) -{ - return nk_contextual_item_image_label(ctx, img, label, align); -} -NK_API int -nk_menu_item_image_text(struct nk_context *ctx, struct nk_image img, - const char *text, int len, nk_flags align) -{ - return nk_contextual_item_image_text(ctx, img, text, len, align); -} -NK_API int nk_menu_item_symbol_text(struct nk_context *ctx, enum nk_symbol_type sym, - const char *text, int len, nk_flags align) -{ - return nk_contextual_item_symbol_text(ctx, sym, text, len, align); -} -NK_API int nk_menu_item_symbol_label(struct nk_context *ctx, enum nk_symbol_type sym, - const char *label, nk_flags align) -{ - return nk_contextual_item_symbol_label(ctx, sym, label, align); -} -NK_API void nk_menu_close(struct nk_context *ctx) -{ - nk_contextual_close(ctx); -} -NK_API void -nk_menu_end(struct nk_context *ctx) -{ - nk_contextual_end(ctx); -} - - - - - -/* =============================================================== - * - * LAYOUT - * - * ===============================================================*/ -NK_API void -nk_layout_set_min_row_height(struct nk_context *ctx, float height) -{ - struct nk_window *win; - struct nk_panel *layout; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return; - - win = ctx->current; - layout = win->layout; - layout->row.min_height = height; -} -NK_API void -nk_layout_reset_min_row_height(struct nk_context *ctx) -{ - struct nk_window *win; - struct nk_panel *layout; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return; - - win = ctx->current; - layout = win->layout; - layout->row.min_height = ctx->style.font->height; - layout->row.min_height += ctx->style.text.padding.y*2; - layout->row.min_height += ctx->style.window.min_row_height_padding*2; -} -NK_LIB float -nk_layout_row_calculate_usable_space(const struct nk_style *style, enum nk_panel_type type, - float total_space, int columns) -{ - float panel_padding; - float panel_spacing; - float panel_space; - - struct nk_vec2 spacing; - struct nk_vec2 padding; - - spacing = style->window.spacing; - padding = nk_panel_get_padding(style, type); - - /* calculate the usable panel space */ - panel_padding = 2 * padding.x; - panel_spacing = (float)NK_MAX(columns - 1, 0) * spacing.x; - panel_space = total_space - panel_padding - panel_spacing; - return panel_space; -} -NK_LIB void -nk_panel_layout(const struct nk_context *ctx, struct nk_window *win, - float height, int cols) -{ - struct nk_panel *layout; - const struct nk_style *style; - struct nk_command_buffer *out; - - struct nk_vec2 item_spacing; - struct nk_color color; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return; - - /* prefetch some configuration data */ - layout = win->layout; - style = &ctx->style; - out = &win->buffer; - color = style->window.background; - item_spacing = style->window.spacing; - - /* if one of these triggers you forgot to add an `if` condition around either - a window, group, popup, combobox or contextual menu `begin` and `end` block. - Example: - if (nk_begin(...) {...} nk_end(...); or - if (nk_group_begin(...) { nk_group_end(...);} */ - NK_ASSERT(!(layout->flags & NK_WINDOW_MINIMIZED)); - NK_ASSERT(!(layout->flags & NK_WINDOW_HIDDEN)); - NK_ASSERT(!(layout->flags & NK_WINDOW_CLOSED)); - - /* update the current row and set the current row layout */ - layout->row.index = 0; - layout->at_y += layout->row.height; - layout->row.columns = cols; - if (height == 0.0f) - layout->row.height = NK_MAX(height, layout->row.min_height) + item_spacing.y; - else layout->row.height = height + item_spacing.y; - - layout->row.item_offset = 0; - if (layout->flags & NK_WINDOW_DYNAMIC) { - /* draw background for dynamic panels */ - struct nk_rect background; - background.x = win->bounds.x; - background.w = win->bounds.w; - background.y = layout->at_y - 1.0f; - background.h = layout->row.height + 1.0f; - nk_fill_rect(out, background, 0, color); - } -} -NK_LIB void -nk_row_layout(struct nk_context *ctx, enum nk_layout_format fmt, - float height, int cols, int width) -{ - /* update the current row and set the current row layout */ - struct nk_window *win; - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return; - - win = ctx->current; - nk_panel_layout(ctx, win, height, cols); - if (fmt == NK_DYNAMIC) - win->layout->row.type = NK_LAYOUT_DYNAMIC_FIXED; - else win->layout->row.type = NK_LAYOUT_STATIC_FIXED; - - win->layout->row.ratio = 0; - win->layout->row.filled = 0; - win->layout->row.item_offset = 0; - win->layout->row.item_width = (float)width; -} -NK_API float -nk_layout_ratio_from_pixel(struct nk_context *ctx, float pixel_width) -{ - struct nk_window *win; - NK_ASSERT(ctx); - NK_ASSERT(pixel_width); - if (!ctx || !ctx->current || !ctx->current->layout) return 0; - win = ctx->current; - return NK_CLAMP(0.0f, pixel_width/win->bounds.x, 1.0f); -} -NK_API void -nk_layout_row_dynamic(struct nk_context *ctx, float height, int cols) -{ - nk_row_layout(ctx, NK_DYNAMIC, height, cols, 0); -} -NK_API void -nk_layout_row_static(struct nk_context *ctx, float height, int item_width, int cols) -{ - nk_row_layout(ctx, NK_STATIC, height, cols, item_width); -} -NK_API void -nk_layout_row_begin(struct nk_context *ctx, enum nk_layout_format fmt, - float row_height, int cols) -{ - struct nk_window *win; - struct nk_panel *layout; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return; - - win = ctx->current; - layout = win->layout; - nk_panel_layout(ctx, win, row_height, cols); - if (fmt == NK_DYNAMIC) - layout->row.type = NK_LAYOUT_DYNAMIC_ROW; - else layout->row.type = NK_LAYOUT_STATIC_ROW; - - layout->row.ratio = 0; - layout->row.filled = 0; - layout->row.item_width = 0; - layout->row.item_offset = 0; - layout->row.columns = cols; -} -NK_API void -nk_layout_row_push(struct nk_context *ctx, float ratio_or_width) -{ - struct nk_window *win; - struct nk_panel *layout; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return; - - win = ctx->current; - layout = win->layout; - NK_ASSERT(layout->row.type == NK_LAYOUT_STATIC_ROW || layout->row.type == NK_LAYOUT_DYNAMIC_ROW); - if (layout->row.type != NK_LAYOUT_STATIC_ROW && layout->row.type != NK_LAYOUT_DYNAMIC_ROW) - return; - - if (layout->row.type == NK_LAYOUT_DYNAMIC_ROW) { - float ratio = ratio_or_width; - if ((ratio + layout->row.filled) > 1.0f) return; - if (ratio > 0.0f) - layout->row.item_width = NK_SATURATE(ratio); - else layout->row.item_width = 1.0f - layout->row.filled; - } else layout->row.item_width = ratio_or_width; -} -NK_API void -nk_layout_row_end(struct nk_context *ctx) -{ - struct nk_window *win; - struct nk_panel *layout; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return; - - win = ctx->current; - layout = win->layout; - NK_ASSERT(layout->row.type == NK_LAYOUT_STATIC_ROW || layout->row.type == NK_LAYOUT_DYNAMIC_ROW); - if (layout->row.type != NK_LAYOUT_STATIC_ROW && layout->row.type != NK_LAYOUT_DYNAMIC_ROW) - return; - layout->row.item_width = 0; - layout->row.item_offset = 0; -} -NK_API void -nk_layout_row(struct nk_context *ctx, enum nk_layout_format fmt, - float height, int cols, const float *ratio) -{ - int i; - int n_undef = 0; - struct nk_window *win; - struct nk_panel *layout; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return; - - win = ctx->current; - layout = win->layout; - nk_panel_layout(ctx, win, height, cols); - if (fmt == NK_DYNAMIC) { - /* calculate width of undefined widget ratios */ - float r = 0; - layout->row.ratio = ratio; - for (i = 0; i < cols; ++i) { - if (ratio[i] < 0.0f) - n_undef++; - else r += ratio[i]; - } - r = NK_SATURATE(1.0f - r); - layout->row.type = NK_LAYOUT_DYNAMIC; - layout->row.item_width = (r > 0 && n_undef > 0) ? (r / (float)n_undef):0; - } else { - layout->row.ratio = ratio; - layout->row.type = NK_LAYOUT_STATIC; - layout->row.item_width = 0; - layout->row.item_offset = 0; - } - layout->row.item_offset = 0; - layout->row.filled = 0; -} -NK_API void -nk_layout_row_template_begin(struct nk_context *ctx, float height) -{ - struct nk_window *win; - struct nk_panel *layout; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return; - - win = ctx->current; - layout = win->layout; - nk_panel_layout(ctx, win, height, 1); - layout->row.type = NK_LAYOUT_TEMPLATE; - layout->row.columns = 0; - layout->row.ratio = 0; - layout->row.item_width = 0; - layout->row.item_height = 0; - layout->row.item_offset = 0; - layout->row.filled = 0; - layout->row.item.x = 0; - layout->row.item.y = 0; - layout->row.item.w = 0; - layout->row.item.h = 0; -} -NK_API void -nk_layout_row_template_push_dynamic(struct nk_context *ctx) -{ - struct nk_window *win; - struct nk_panel *layout; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return; - - win = ctx->current; - layout = win->layout; - NK_ASSERT(layout->row.type == NK_LAYOUT_TEMPLATE); - NK_ASSERT(layout->row.columns < NK_MAX_LAYOUT_ROW_TEMPLATE_COLUMNS); - if (layout->row.type != NK_LAYOUT_TEMPLATE) return; - if (layout->row.columns >= NK_MAX_LAYOUT_ROW_TEMPLATE_COLUMNS) return; - layout->row.templates[layout->row.columns++] = -1.0f; -} -NK_API void -nk_layout_row_template_push_variable(struct nk_context *ctx, float min_width) -{ - struct nk_window *win; - struct nk_panel *layout; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return; - - win = ctx->current; - layout = win->layout; - NK_ASSERT(layout->row.type == NK_LAYOUT_TEMPLATE); - NK_ASSERT(layout->row.columns < NK_MAX_LAYOUT_ROW_TEMPLATE_COLUMNS); - if (layout->row.type != NK_LAYOUT_TEMPLATE) return; - if (layout->row.columns >= NK_MAX_LAYOUT_ROW_TEMPLATE_COLUMNS) return; - layout->row.templates[layout->row.columns++] = -min_width; -} -NK_API void -nk_layout_row_template_push_static(struct nk_context *ctx, float width) -{ - struct nk_window *win; - struct nk_panel *layout; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return; - - win = ctx->current; - layout = win->layout; - NK_ASSERT(layout->row.type == NK_LAYOUT_TEMPLATE); - NK_ASSERT(layout->row.columns < NK_MAX_LAYOUT_ROW_TEMPLATE_COLUMNS); - if (layout->row.type != NK_LAYOUT_TEMPLATE) return; - if (layout->row.columns >= NK_MAX_LAYOUT_ROW_TEMPLATE_COLUMNS) return; - layout->row.templates[layout->row.columns++] = width; -} -NK_API void -nk_layout_row_template_end(struct nk_context *ctx) -{ - struct nk_window *win; - struct nk_panel *layout; - - int i = 0; - int variable_count = 0; - int min_variable_count = 0; - float min_fixed_width = 0.0f; - float total_fixed_width = 0.0f; - float max_variable_width = 0.0f; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return; - - win = ctx->current; - layout = win->layout; - NK_ASSERT(layout->row.type == NK_LAYOUT_TEMPLATE); - if (layout->row.type != NK_LAYOUT_TEMPLATE) return; - for (i = 0; i < layout->row.columns; ++i) { - float width = layout->row.templates[i]; - if (width >= 0.0f) { - total_fixed_width += width; - min_fixed_width += width; - } else if (width < -1.0f) { - width = -width; - total_fixed_width += width; - max_variable_width = NK_MAX(max_variable_width, width); - variable_count++; - } else { - min_variable_count++; - variable_count++; - } - } - if (variable_count) { - float space = nk_layout_row_calculate_usable_space(&ctx->style, layout->type, - layout->bounds.w, layout->row.columns); - float var_width = (NK_MAX(space-min_fixed_width,0.0f)) / (float)variable_count; - int enough_space = var_width >= max_variable_width; - if (!enough_space) - var_width = (NK_MAX(space-total_fixed_width,0)) / (float)min_variable_count; - for (i = 0; i < layout->row.columns; ++i) { - float *width = &layout->row.templates[i]; - *width = (*width >= 0.0f)? *width: (*width < -1.0f && !enough_space)? -(*width): var_width; - } - } -} -NK_API void -nk_layout_space_begin(struct nk_context *ctx, enum nk_layout_format fmt, - float height, int widget_count) -{ - struct nk_window *win; - struct nk_panel *layout; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return; - - win = ctx->current; - layout = win->layout; - nk_panel_layout(ctx, win, height, widget_count); - if (fmt == NK_STATIC) - layout->row.type = NK_LAYOUT_STATIC_FREE; - else layout->row.type = NK_LAYOUT_DYNAMIC_FREE; - - layout->row.ratio = 0; - layout->row.filled = 0; - layout->row.item_width = 0; - layout->row.item_offset = 0; -} -NK_API void -nk_layout_space_end(struct nk_context *ctx) -{ - struct nk_window *win; - struct nk_panel *layout; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return; - - win = ctx->current; - layout = win->layout; - layout->row.item_width = 0; - layout->row.item_height = 0; - layout->row.item_offset = 0; - nk_zero(&layout->row.item, sizeof(layout->row.item)); -} -NK_API void -nk_layout_space_push(struct nk_context *ctx, struct nk_rect rect) -{ - struct nk_window *win; - struct nk_panel *layout; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return; - - win = ctx->current; - layout = win->layout; - layout->row.item = rect; -} -NK_API struct nk_rect -nk_layout_space_bounds(struct nk_context *ctx) -{ - struct nk_rect ret; - struct nk_window *win; - struct nk_panel *layout; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - win = ctx->current; - layout = win->layout; - - ret.x = layout->clip.x; - ret.y = layout->clip.y; - ret.w = layout->clip.w; - ret.h = layout->row.height; - return ret; -} -NK_API struct nk_rect -nk_layout_widget_bounds(struct nk_context *ctx) -{ - struct nk_rect ret; - struct nk_window *win; - struct nk_panel *layout; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - win = ctx->current; - layout = win->layout; - - ret.x = layout->at_x; - ret.y = layout->at_y; - ret.w = layout->bounds.w - NK_MAX(layout->at_x - layout->bounds.x,0); - ret.h = layout->row.height; - return ret; -} -NK_API struct nk_vec2 -nk_layout_space_to_screen(struct nk_context *ctx, struct nk_vec2 ret) -{ - struct nk_window *win; - struct nk_panel *layout; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - win = ctx->current; - layout = win->layout; - - ret.x += layout->at_x - (float)*layout->offset_x; - ret.y += layout->at_y - (float)*layout->offset_y; - return ret; -} -NK_API struct nk_vec2 -nk_layout_space_to_local(struct nk_context *ctx, struct nk_vec2 ret) -{ - struct nk_window *win; - struct nk_panel *layout; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - win = ctx->current; - layout = win->layout; - - ret.x += -layout->at_x + (float)*layout->offset_x; - ret.y += -layout->at_y + (float)*layout->offset_y; - return ret; -} -NK_API struct nk_rect -nk_layout_space_rect_to_screen(struct nk_context *ctx, struct nk_rect ret) -{ - struct nk_window *win; - struct nk_panel *layout; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - win = ctx->current; - layout = win->layout; - - ret.x += layout->at_x - (float)*layout->offset_x; - ret.y += layout->at_y - (float)*layout->offset_y; - return ret; -} -NK_API struct nk_rect -nk_layout_space_rect_to_local(struct nk_context *ctx, struct nk_rect ret) -{ - struct nk_window *win; - struct nk_panel *layout; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - win = ctx->current; - layout = win->layout; - - ret.x += -layout->at_x + (float)*layout->offset_x; - ret.y += -layout->at_y + (float)*layout->offset_y; - return ret; -} -NK_LIB void -nk_panel_alloc_row(const struct nk_context *ctx, struct nk_window *win) -{ - struct nk_panel *layout = win->layout; - struct nk_vec2 spacing = ctx->style.window.spacing; - const float row_height = layout->row.height - spacing.y; - nk_panel_layout(ctx, win, row_height, layout->row.columns); -} -NK_LIB void -nk_layout_widget_space(struct nk_rect *bounds, const struct nk_context *ctx, - struct nk_window *win, int modify) -{ - struct nk_panel *layout; - const struct nk_style *style; - - struct nk_vec2 spacing; - struct nk_vec2 padding; - - float item_offset = 0; - float item_width = 0; - float item_spacing = 0; - float panel_space = 0; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return; - - win = ctx->current; - layout = win->layout; - style = &ctx->style; - NK_ASSERT(bounds); - - spacing = style->window.spacing; - padding = nk_panel_get_padding(style, layout->type); - panel_space = nk_layout_row_calculate_usable_space(&ctx->style, layout->type, - layout->bounds.w, layout->row.columns); - - /* calculate the width of one item inside the current layout space */ - switch (layout->row.type) { - case NK_LAYOUT_DYNAMIC_FIXED: { - /* scaling fixed size widgets item width */ - item_width = NK_MAX(1.0f,panel_space) / (float)layout->row.columns; - item_offset = (float)layout->row.index * item_width; - item_spacing = (float)layout->row.index * spacing.x; - } break; - case NK_LAYOUT_DYNAMIC_ROW: { - /* scaling single ratio widget width */ - item_width = layout->row.item_width * panel_space; - item_offset = layout->row.item_offset; - item_spacing = 0; - - if (modify) { - layout->row.item_offset += item_width + spacing.x; - layout->row.filled += layout->row.item_width; - layout->row.index = 0; - } - } break; - case NK_LAYOUT_DYNAMIC_FREE: { - /* panel width depended free widget placing */ - bounds->x = layout->at_x + (layout->bounds.w * layout->row.item.x); - bounds->x -= (float)*layout->offset_x; - bounds->y = layout->at_y + (layout->row.height * layout->row.item.y); - bounds->y -= (float)*layout->offset_y; - bounds->w = layout->bounds.w * layout->row.item.w; - bounds->h = layout->row.height * layout->row.item.h; - return; - } - case NK_LAYOUT_DYNAMIC: { - /* scaling arrays of panel width ratios for every widget */ - float ratio; - NK_ASSERT(layout->row.ratio); - ratio = (layout->row.ratio[layout->row.index] < 0) ? - layout->row.item_width : layout->row.ratio[layout->row.index]; - - item_spacing = (float)layout->row.index * spacing.x; - item_width = (ratio * panel_space); - item_offset = layout->row.item_offset; - - if (modify) { - layout->row.item_offset += item_width; - layout->row.filled += ratio; - } - } break; - case NK_LAYOUT_STATIC_FIXED: { - /* non-scaling fixed widgets item width */ - item_width = layout->row.item_width; - item_offset = (float)layout->row.index * item_width; - item_spacing = (float)layout->row.index * spacing.x; - } break; - case NK_LAYOUT_STATIC_ROW: { - /* scaling single ratio widget width */ - item_width = layout->row.item_width; - item_offset = layout->row.item_offset; - item_spacing = (float)layout->row.index * spacing.x; - if (modify) layout->row.item_offset += item_width; - } break; - case NK_LAYOUT_STATIC_FREE: { - /* free widget placing */ - bounds->x = layout->at_x + layout->row.item.x; - bounds->w = layout->row.item.w; - if (((bounds->x + bounds->w) > layout->max_x) && modify) - layout->max_x = (bounds->x + bounds->w); - bounds->x -= (float)*layout->offset_x; - bounds->y = layout->at_y + layout->row.item.y; - bounds->y -= (float)*layout->offset_y; - bounds->h = layout->row.item.h; - return; - } - case NK_LAYOUT_STATIC: { - /* non-scaling array of panel pixel width for every widget */ - item_spacing = (float)layout->row.index * spacing.x; - item_width = layout->row.ratio[layout->row.index]; - item_offset = layout->row.item_offset; - if (modify) layout->row.item_offset += item_width; - } break; - case NK_LAYOUT_TEMPLATE: { - /* stretchy row layout with combined dynamic/static widget width*/ - NK_ASSERT(layout->row.index < layout->row.columns); - NK_ASSERT(layout->row.index < NK_MAX_LAYOUT_ROW_TEMPLATE_COLUMNS); - item_width = layout->row.templates[layout->row.index]; - item_offset = layout->row.item_offset; - item_spacing = (float)layout->row.index * spacing.x; - if (modify) layout->row.item_offset += item_width; - } break; - default: NK_ASSERT(0); break; - }; - - /* set the bounds of the newly allocated widget */ - bounds->w = item_width; - bounds->h = layout->row.height - spacing.y; - bounds->y = layout->at_y - (float)*layout->offset_y; - bounds->x = layout->at_x + item_offset + item_spacing + padding.x; - if (((bounds->x + bounds->w) > layout->max_x) && modify) - layout->max_x = bounds->x + bounds->w; - bounds->x -= (float)*layout->offset_x; -} -NK_LIB void -nk_panel_alloc_space(struct nk_rect *bounds, const struct nk_context *ctx) -{ - struct nk_window *win; - struct nk_panel *layout; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return; - - /* check if the end of the row has been hit and begin new row if so */ - win = ctx->current; - layout = win->layout; - if (layout->row.index >= layout->row.columns) - nk_panel_alloc_row(ctx, win); - - /* calculate widget position and size */ - nk_layout_widget_space(bounds, ctx, win, nk_true); - layout->row.index++; -} -NK_LIB void -nk_layout_peek(struct nk_rect *bounds, struct nk_context *ctx) -{ - float y; - int index; - struct nk_window *win; - struct nk_panel *layout; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return; - - win = ctx->current; - layout = win->layout; - y = layout->at_y; - index = layout->row.index; - if (layout->row.index >= layout->row.columns) { - layout->at_y += layout->row.height; - layout->row.index = 0; - } - nk_layout_widget_space(bounds, ctx, win, nk_false); - if (!layout->row.index) { - bounds->x -= layout->row.item_offset; - } - layout->at_y = y; - layout->row.index = index; -} - - - - - -/* =============================================================== - * - * TREE - * - * ===============================================================*/ -NK_INTERN int -nk_tree_state_base(struct nk_context *ctx, enum nk_tree_type type, - struct nk_image *img, const char *title, enum nk_collapse_states *state) -{ - struct nk_window *win; - struct nk_panel *layout; - const struct nk_style *style; - struct nk_command_buffer *out; - const struct nk_input *in; - const struct nk_style_button *button; - enum nk_symbol_type symbol; - float row_height; - - struct nk_vec2 item_spacing; - struct nk_rect header = {0,0,0,0}; - struct nk_rect sym = {0,0,0,0}; - struct nk_text text; - - nk_flags ws = 0; - enum nk_widget_layout_states widget_state; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return 0; - - /* cache some data */ - win = ctx->current; - layout = win->layout; - out = &win->buffer; - style = &ctx->style; - item_spacing = style->window.spacing; - - /* calculate header bounds and draw background */ - row_height = style->font->height + 2 * style->tab.padding.y; - nk_layout_set_min_row_height(ctx, row_height); - nk_layout_row_dynamic(ctx, row_height, 1); - nk_layout_reset_min_row_height(ctx); - - widget_state = nk_widget(&header, ctx); - if (type == NK_TREE_TAB) { - const struct nk_style_item *background = &style->tab.background; - if (background->type == NK_STYLE_ITEM_IMAGE) { - nk_draw_image(out, header, &background->data.image, nk_white); - text.background = nk_rgba(0,0,0,0); - } else { - text.background = background->data.color; - nk_fill_rect(out, header, 0, style->tab.border_color); - nk_fill_rect(out, nk_shrink_rect(header, style->tab.border), - style->tab.rounding, background->data.color); - } - } else text.background = style->window.background; - - /* update node state */ - in = (!(layout->flags & NK_WINDOW_ROM)) ? &ctx->input: 0; - in = (in && widget_state == NK_WIDGET_VALID) ? &ctx->input : 0; - if (nk_button_behavior(&ws, header, in, NK_BUTTON_DEFAULT)) - *state = (*state == NK_MAXIMIZED) ? NK_MINIMIZED : NK_MAXIMIZED; - - /* select correct button style */ - if (*state == NK_MAXIMIZED) { - symbol = style->tab.sym_maximize; - if (type == NK_TREE_TAB) - button = &style->tab.tab_maximize_button; - else button = &style->tab.node_maximize_button; - } else { - symbol = style->tab.sym_minimize; - if (type == NK_TREE_TAB) - button = &style->tab.tab_minimize_button; - else button = &style->tab.node_minimize_button; - } - - {/* draw triangle button */ - sym.w = sym.h = style->font->height; - sym.y = header.y + style->tab.padding.y; - sym.x = header.x + style->tab.padding.x; - nk_do_button_symbol(&ws, &win->buffer, sym, symbol, NK_BUTTON_DEFAULT, - button, 0, style->font); - - if (img) { - /* draw optional image icon */ - sym.x = sym.x + sym.w + 4 * item_spacing.x; - nk_draw_image(&win->buffer, sym, img, nk_white); - sym.w = style->font->height + style->tab.spacing.x;} - } - - {/* draw label */ - struct nk_rect label; - header.w = NK_MAX(header.w, sym.w + item_spacing.x); - label.x = sym.x + sym.w + item_spacing.x; - label.y = sym.y; - label.w = header.w - (sym.w + item_spacing.y + style->tab.indent); - label.h = style->font->height; - text.text = style->tab.text; - text.padding = nk_vec2(0,0); - nk_widget_text(out, label, title, nk_strlen(title), &text, - NK_TEXT_LEFT, style->font);} - - /* increase x-axis cursor widget position pointer */ - if (*state == NK_MAXIMIZED) { - layout->at_x = header.x + (float)*layout->offset_x + style->tab.indent; - layout->bounds.w = NK_MAX(layout->bounds.w, style->tab.indent); - layout->bounds.w -= (style->tab.indent + style->window.padding.x); - layout->row.tree_depth++; - return nk_true; - } else return nk_false; -} -NK_INTERN int -nk_tree_base(struct nk_context *ctx, enum nk_tree_type type, - struct nk_image *img, const char *title, enum nk_collapse_states initial_state, - const char *hash, int len, int line) -{ - struct nk_window *win = ctx->current; - int title_len = 0; - nk_hash tree_hash = 0; - nk_uint *state = 0; - - /* retrieve tree state from internal widget state tables */ - if (!hash) { - title_len = (int)nk_strlen(title); - tree_hash = nk_murmur_hash(title, (int)title_len, (nk_hash)line); - } else tree_hash = nk_murmur_hash(hash, len, (nk_hash)line); - state = nk_find_value(win, tree_hash); - if (!state) { - state = nk_add_value(ctx, win, tree_hash, 0); - *state = initial_state; - } - return nk_tree_state_base(ctx, type, img, title, (enum nk_collapse_states*)state); -} -NK_API int -nk_tree_state_push(struct nk_context *ctx, enum nk_tree_type type, - const char *title, enum nk_collapse_states *state) -{ - return nk_tree_state_base(ctx, type, 0, title, state); -} -NK_API int -nk_tree_state_image_push(struct nk_context *ctx, enum nk_tree_type type, - struct nk_image img, const char *title, enum nk_collapse_states *state) -{ - return nk_tree_state_base(ctx, type, &img, title, state); -} -NK_API void -nk_tree_state_pop(struct nk_context *ctx) -{ - struct nk_window *win = 0; - struct nk_panel *layout = 0; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return; - - win = ctx->current; - layout = win->layout; - layout->at_x -= ctx->style.tab.indent + ctx->style.window.padding.x; - layout->bounds.w += ctx->style.tab.indent + ctx->style.window.padding.x; - NK_ASSERT(layout->row.tree_depth); - layout->row.tree_depth--; -} -NK_API int -nk_tree_push_hashed(struct nk_context *ctx, enum nk_tree_type type, - const char *title, enum nk_collapse_states initial_state, - const char *hash, int len, int line) -{ - return nk_tree_base(ctx, type, 0, title, initial_state, hash, len, line); -} -NK_API int -nk_tree_image_push_hashed(struct nk_context *ctx, enum nk_tree_type type, - struct nk_image img, const char *title, enum nk_collapse_states initial_state, - const char *hash, int len,int seed) -{ - return nk_tree_base(ctx, type, &img, title, initial_state, hash, len, seed); -} -NK_API void -nk_tree_pop(struct nk_context *ctx) -{ - nk_tree_state_pop(ctx); -} -NK_INTERN int -nk_tree_element_image_push_hashed_base(struct nk_context *ctx, enum nk_tree_type type, - struct nk_image *img, const char *title, int title_len, - enum nk_collapse_states *state, int *selected) -{ - struct nk_window *win; - struct nk_panel *layout; - const struct nk_style *style; - struct nk_command_buffer *out; - const struct nk_input *in; - const struct nk_style_button *button; - enum nk_symbol_type symbol; - float row_height; - struct nk_vec2 padding; - - int text_len; - float text_width; - - struct nk_vec2 item_spacing; - struct nk_rect header = {0,0,0,0}; - struct nk_rect sym = {0,0,0,0}; - struct nk_text text; - - nk_flags ws = 0; - enum nk_widget_layout_states widget_state; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return 0; - - /* cache some data */ - win = ctx->current; - layout = win->layout; - out = &win->buffer; - style = &ctx->style; - item_spacing = style->window.spacing; - padding = style->selectable.padding; - - /* calculate header bounds and draw background */ - row_height = style->font->height + 2 * style->tab.padding.y; - nk_layout_set_min_row_height(ctx, row_height); - nk_layout_row_dynamic(ctx, row_height, 1); - nk_layout_reset_min_row_height(ctx); - - widget_state = nk_widget(&header, ctx); - if (type == NK_TREE_TAB) { - const struct nk_style_item *background = &style->tab.background; - if (background->type == NK_STYLE_ITEM_IMAGE) { - nk_draw_image(out, header, &background->data.image, nk_white); - text.background = nk_rgba(0,0,0,0); - } else { - text.background = background->data.color; - nk_fill_rect(out, header, 0, style->tab.border_color); - nk_fill_rect(out, nk_shrink_rect(header, style->tab.border), - style->tab.rounding, background->data.color); - } - } else text.background = style->window.background; - - in = (!(layout->flags & NK_WINDOW_ROM)) ? &ctx->input: 0; - in = (in && widget_state == NK_WIDGET_VALID) ? &ctx->input : 0; - - /* select correct button style */ - if (*state == NK_MAXIMIZED) { - symbol = style->tab.sym_maximize; - if (type == NK_TREE_TAB) - button = &style->tab.tab_maximize_button; - else button = &style->tab.node_maximize_button; - } else { - symbol = style->tab.sym_minimize; - if (type == NK_TREE_TAB) - button = &style->tab.tab_minimize_button; - else button = &style->tab.node_minimize_button; - } - {/* draw triangle button */ - sym.w = sym.h = style->font->height; - sym.y = header.y + style->tab.padding.y; - sym.x = header.x + style->tab.padding.x; - if (nk_do_button_symbol(&ws, &win->buffer, sym, symbol, NK_BUTTON_DEFAULT, button, in, style->font)) - *state = (*state == NK_MAXIMIZED) ? NK_MINIMIZED : NK_MAXIMIZED;} - - /* draw label */ - {nk_flags dummy = 0; - struct nk_rect label; - /* calculate size of the text and tooltip */ - text_len = nk_strlen(title); - text_width = style->font->width(style->font->userdata, style->font->height, title, text_len); - text_width += (4 * padding.x); - - header.w = NK_MAX(header.w, sym.w + item_spacing.x); - label.x = sym.x + sym.w + item_spacing.x; - label.y = sym.y; - label.w = NK_MIN(header.w - (sym.w + item_spacing.y + style->tab.indent), text_width); - label.h = style->font->height; - - if (img) { - nk_do_selectable_image(&dummy, &win->buffer, label, title, title_len, NK_TEXT_LEFT, - selected, img, &style->selectable, in, style->font); - } else nk_do_selectable(&dummy, &win->buffer, label, title, title_len, NK_TEXT_LEFT, - selected, &style->selectable, in, style->font); - } - /* increase x-axis cursor widget position pointer */ - if (*state == NK_MAXIMIZED) { - layout->at_x = header.x + (float)*layout->offset_x + style->tab.indent; - layout->bounds.w = NK_MAX(layout->bounds.w, style->tab.indent); - layout->bounds.w -= (style->tab.indent + style->window.padding.x); - layout->row.tree_depth++; - return nk_true; - } else return nk_false; -} -NK_INTERN int -nk_tree_element_base(struct nk_context *ctx, enum nk_tree_type type, - struct nk_image *img, const char *title, enum nk_collapse_states initial_state, - int *selected, const char *hash, int len, int line) -{ - struct nk_window *win = ctx->current; - int title_len = 0; - nk_hash tree_hash = 0; - nk_uint *state = 0; - - /* retrieve tree state from internal widget state tables */ - if (!hash) { - title_len = (int)nk_strlen(title); - tree_hash = nk_murmur_hash(title, (int)title_len, (nk_hash)line); - } else tree_hash = nk_murmur_hash(hash, len, (nk_hash)line); - state = nk_find_value(win, tree_hash); - if (!state) { - state = nk_add_value(ctx, win, tree_hash, 0); - *state = initial_state; - } return nk_tree_element_image_push_hashed_base(ctx, type, img, title, - nk_strlen(title), (enum nk_collapse_states*)state, selected); -} -NK_API int -nk_tree_element_push_hashed(struct nk_context *ctx, enum nk_tree_type type, - const char *title, enum nk_collapse_states initial_state, - int *selected, const char *hash, int len, int seed) -{ - return nk_tree_element_base(ctx, type, 0, title, initial_state, selected, hash, len, seed); -} -NK_API int -nk_tree_element_image_push_hashed(struct nk_context *ctx, enum nk_tree_type type, - struct nk_image img, const char *title, enum nk_collapse_states initial_state, - int *selected, const char *hash, int len,int seed) -{ - return nk_tree_element_base(ctx, type, &img, title, initial_state, selected, hash, len, seed); -} -NK_API void -nk_tree_element_pop(struct nk_context *ctx) -{ - nk_tree_state_pop(ctx); -} - - - - - -/* =============================================================== - * - * GROUP - * - * ===============================================================*/ -NK_API int -nk_group_scrolled_offset_begin(struct nk_context *ctx, - nk_uint *x_offset, nk_uint *y_offset, const char *title, nk_flags flags) -{ - struct nk_rect bounds; - struct nk_window panel; - struct nk_window *win; - - win = ctx->current; - nk_panel_alloc_space(&bounds, ctx); - {const struct nk_rect *c = &win->layout->clip; - if (!NK_INTERSECT(c->x, c->y, c->w, c->h, bounds.x, bounds.y, bounds.w, bounds.h) && - !(flags & NK_WINDOW_MOVABLE)) { - return 0; - }} - if (win->flags & NK_WINDOW_ROM) - flags |= NK_WINDOW_ROM; - - /* initialize a fake window to create the panel from */ - nk_zero(&panel, sizeof(panel)); - panel.bounds = bounds; - panel.flags = flags; - panel.scrollbar.x = *x_offset; - panel.scrollbar.y = *y_offset; - panel.buffer = win->buffer; - panel.layout = (struct nk_panel*)nk_create_panel(ctx); - ctx->current = &panel; - nk_panel_begin(ctx, (flags & NK_WINDOW_TITLE) ? title: 0, NK_PANEL_GROUP); - - win->buffer = panel.buffer; - win->buffer.clip = panel.layout->clip; - panel.layout->offset_x = x_offset; - panel.layout->offset_y = y_offset; - panel.layout->parent = win->layout; - win->layout = panel.layout; - - ctx->current = win; - if ((panel.layout->flags & NK_WINDOW_CLOSED) || - (panel.layout->flags & NK_WINDOW_MINIMIZED)) - { - nk_flags f = panel.layout->flags; - nk_group_scrolled_end(ctx); - if (f & NK_WINDOW_CLOSED) - return NK_WINDOW_CLOSED; - if (f & NK_WINDOW_MINIMIZED) - return NK_WINDOW_MINIMIZED; - } - return 1; -} -NK_API void -nk_group_scrolled_end(struct nk_context *ctx) -{ - struct nk_window *win; - struct nk_panel *parent; - struct nk_panel *g; - - struct nk_rect clip; - struct nk_window pan; - struct nk_vec2 panel_padding; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - if (!ctx || !ctx->current) - return; - - /* make sure nk_group_begin was called correctly */ - NK_ASSERT(ctx->current); - win = ctx->current; - NK_ASSERT(win->layout); - g = win->layout; - NK_ASSERT(g->parent); - parent = g->parent; - - /* dummy window */ - nk_zero_struct(pan); - panel_padding = nk_panel_get_padding(&ctx->style, NK_PANEL_GROUP); - pan.bounds.y = g->bounds.y - (g->header_height + g->menu.h); - pan.bounds.x = g->bounds.x - panel_padding.x; - pan.bounds.w = g->bounds.w + 2 * panel_padding.x; - pan.bounds.h = g->bounds.h + g->header_height + g->menu.h; - if (g->flags & NK_WINDOW_BORDER) { - pan.bounds.x -= g->border; - pan.bounds.y -= g->border; - pan.bounds.w += 2*g->border; - pan.bounds.h += 2*g->border; - } - if (!(g->flags & NK_WINDOW_NO_SCROLLBAR)) { - pan.bounds.w += ctx->style.window.scrollbar_size.x; - pan.bounds.h += ctx->style.window.scrollbar_size.y; - } - pan.scrollbar.x = *g->offset_x; - pan.scrollbar.y = *g->offset_y; - pan.flags = g->flags; - pan.buffer = win->buffer; - pan.layout = g; - pan.parent = win; - ctx->current = &pan; - - /* make sure group has correct clipping rectangle */ - nk_unify(&clip, &parent->clip, pan.bounds.x, pan.bounds.y, - pan.bounds.x + pan.bounds.w, pan.bounds.y + pan.bounds.h + panel_padding.x); - nk_push_scissor(&pan.buffer, clip); - nk_end(ctx); - - win->buffer = pan.buffer; - nk_push_scissor(&win->buffer, parent->clip); - ctx->current = win; - win->layout = parent; - g->bounds = pan.bounds; - return; -} -NK_API int -nk_group_scrolled_begin(struct nk_context *ctx, - struct nk_scroll *scroll, const char *title, nk_flags flags) -{ - return nk_group_scrolled_offset_begin(ctx, &scroll->x, &scroll->y, title, flags); -} -NK_API int -nk_group_begin_titled(struct nk_context *ctx, const char *id, - const char *title, nk_flags flags) -{ - int id_len; - nk_hash id_hash; - struct nk_window *win; - nk_uint *x_offset; - nk_uint *y_offset; - - NK_ASSERT(ctx); - NK_ASSERT(id); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout || !id) - return 0; - - /* find persistent group scrollbar value */ - win = ctx->current; - id_len = (int)nk_strlen(id); - id_hash = nk_murmur_hash(id, (int)id_len, NK_PANEL_GROUP); - x_offset = nk_find_value(win, id_hash); - if (!x_offset) { - x_offset = nk_add_value(ctx, win, id_hash, 0); - y_offset = nk_add_value(ctx, win, id_hash+1, 0); - - NK_ASSERT(x_offset); - NK_ASSERT(y_offset); - if (!x_offset || !y_offset) return 0; - *x_offset = *y_offset = 0; - } else y_offset = nk_find_value(win, id_hash+1); - return nk_group_scrolled_offset_begin(ctx, x_offset, y_offset, title, flags); -} -NK_API int -nk_group_begin(struct nk_context *ctx, const char *title, nk_flags flags) -{ - return nk_group_begin_titled(ctx, title, title, flags); -} -NK_API void -nk_group_end(struct nk_context *ctx) -{ - nk_group_scrolled_end(ctx); -} - - - - - -/* =============================================================== - * - * LIST VIEW - * - * ===============================================================*/ -NK_API int -nk_list_view_begin(struct nk_context *ctx, struct nk_list_view *view, - const char *title, nk_flags flags, int row_height, int row_count) -{ - int title_len; - nk_hash title_hash; - nk_uint *x_offset; - nk_uint *y_offset; - - int result; - struct nk_window *win; - struct nk_panel *layout; - const struct nk_style *style; - struct nk_vec2 item_spacing; - - NK_ASSERT(ctx); - NK_ASSERT(view); - NK_ASSERT(title); - if (!ctx || !view || !title) return 0; - - win = ctx->current; - style = &ctx->style; - item_spacing = style->window.spacing; - row_height += NK_MAX(0, (int)item_spacing.y); - - /* find persistent list view scrollbar offset */ - title_len = (int)nk_strlen(title); - title_hash = nk_murmur_hash(title, (int)title_len, NK_PANEL_GROUP); - x_offset = nk_find_value(win, title_hash); - if (!x_offset) { - x_offset = nk_add_value(ctx, win, title_hash, 0); - y_offset = nk_add_value(ctx, win, title_hash+1, 0); - - NK_ASSERT(x_offset); - NK_ASSERT(y_offset); - if (!x_offset || !y_offset) return 0; - *x_offset = *y_offset = 0; - } else y_offset = nk_find_value(win, title_hash+1); - view->scroll_value = *y_offset; - view->scroll_pointer = y_offset; - - *y_offset = 0; - result = nk_group_scrolled_offset_begin(ctx, x_offset, y_offset, title, flags); - win = ctx->current; - layout = win->layout; - - view->total_height = row_height * NK_MAX(row_count,1); - view->begin = (int)NK_MAX(((float)view->scroll_value / (float)row_height), 0.0f); - view->count = (int)NK_MAX(nk_iceilf((layout->clip.h)/(float)row_height),0); - view->count = NK_MIN(view->count, row_count - view->begin); - view->end = view->begin + view->count; - view->ctx = ctx; - return result; -} -NK_API void -nk_list_view_end(struct nk_list_view *view) -{ - struct nk_context *ctx; - struct nk_window *win; - struct nk_panel *layout; - - NK_ASSERT(view); - NK_ASSERT(view->ctx); - NK_ASSERT(view->scroll_pointer); - if (!view || !view->ctx) return; - - ctx = view->ctx; - win = ctx->current; - layout = win->layout; - layout->at_y = layout->bounds.y + (float)view->total_height; - *view->scroll_pointer = *view->scroll_pointer + view->scroll_value; - nk_group_end(view->ctx); -} - - - - - -/* =============================================================== - * - * WIDGET - * - * ===============================================================*/ -NK_API struct nk_rect -nk_widget_bounds(struct nk_context *ctx) -{ - struct nk_rect bounds; - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - if (!ctx || !ctx->current) - return nk_rect(0,0,0,0); - nk_layout_peek(&bounds, ctx); - return bounds; -} -NK_API struct nk_vec2 -nk_widget_position(struct nk_context *ctx) -{ - struct nk_rect bounds; - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - if (!ctx || !ctx->current) - return nk_vec2(0,0); - - nk_layout_peek(&bounds, ctx); - return nk_vec2(bounds.x, bounds.y); -} -NK_API struct nk_vec2 -nk_widget_size(struct nk_context *ctx) -{ - struct nk_rect bounds; - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - if (!ctx || !ctx->current) - return nk_vec2(0,0); - - nk_layout_peek(&bounds, ctx); - return nk_vec2(bounds.w, bounds.h); -} -NK_API float -nk_widget_width(struct nk_context *ctx) -{ - struct nk_rect bounds; - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - if (!ctx || !ctx->current) - return 0; - - nk_layout_peek(&bounds, ctx); - return bounds.w; -} -NK_API float -nk_widget_height(struct nk_context *ctx) -{ - struct nk_rect bounds; - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - if (!ctx || !ctx->current) - return 0; - - nk_layout_peek(&bounds, ctx); - return bounds.h; -} -NK_API int -nk_widget_is_hovered(struct nk_context *ctx) -{ - struct nk_rect c, v; - struct nk_rect bounds; - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - if (!ctx || !ctx->current || ctx->active != ctx->current) - return 0; - - c = ctx->current->layout->clip; - c.x = (float)((int)c.x); - c.y = (float)((int)c.y); - c.w = (float)((int)c.w); - c.h = (float)((int)c.h); - - nk_layout_peek(&bounds, ctx); - nk_unify(&v, &c, bounds.x, bounds.y, bounds.x + bounds.w, bounds.y + bounds.h); - if (!NK_INTERSECT(c.x, c.y, c.w, c.h, bounds.x, bounds.y, bounds.w, bounds.h)) - return 0; - return nk_input_is_mouse_hovering_rect(&ctx->input, bounds); -} -NK_API int -nk_widget_is_mouse_clicked(struct nk_context *ctx, enum nk_buttons btn) -{ - struct nk_rect c, v; - struct nk_rect bounds; - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - if (!ctx || !ctx->current || ctx->active != ctx->current) - return 0; - - c = ctx->current->layout->clip; - c.x = (float)((int)c.x); - c.y = (float)((int)c.y); - c.w = (float)((int)c.w); - c.h = (float)((int)c.h); - - nk_layout_peek(&bounds, ctx); - nk_unify(&v, &c, bounds.x, bounds.y, bounds.x + bounds.w, bounds.y + bounds.h); - if (!NK_INTERSECT(c.x, c.y, c.w, c.h, bounds.x, bounds.y, bounds.w, bounds.h)) - return 0; - return nk_input_mouse_clicked(&ctx->input, btn, bounds); -} -NK_API int -nk_widget_has_mouse_click_down(struct nk_context *ctx, enum nk_buttons btn, int down) -{ - struct nk_rect c, v; - struct nk_rect bounds; - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - if (!ctx || !ctx->current || ctx->active != ctx->current) - return 0; - - c = ctx->current->layout->clip; - c.x = (float)((int)c.x); - c.y = (float)((int)c.y); - c.w = (float)((int)c.w); - c.h = (float)((int)c.h); - - nk_layout_peek(&bounds, ctx); - nk_unify(&v, &c, bounds.x, bounds.y, bounds.x + bounds.w, bounds.y + bounds.h); - if (!NK_INTERSECT(c.x, c.y, c.w, c.h, bounds.x, bounds.y, bounds.w, bounds.h)) - return 0; - return nk_input_has_mouse_click_down_in_rect(&ctx->input, btn, bounds, down); -} -NK_API enum nk_widget_layout_states -nk_widget(struct nk_rect *bounds, const struct nk_context *ctx) -{ - struct nk_rect c, v; - struct nk_window *win; - struct nk_panel *layout; - const struct nk_input *in; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return NK_WIDGET_INVALID; - - /* allocate space and check if the widget needs to be updated and drawn */ - nk_panel_alloc_space(bounds, ctx); - win = ctx->current; - layout = win->layout; - in = &ctx->input; - c = layout->clip; - - /* if one of these triggers you forgot to add an `if` condition around either - a window, group, popup, combobox or contextual menu `begin` and `end` block. - Example: - if (nk_begin(...) {...} nk_end(...); or - if (nk_group_begin(...) { nk_group_end(...);} */ - NK_ASSERT(!(layout->flags & NK_WINDOW_MINIMIZED)); - NK_ASSERT(!(layout->flags & NK_WINDOW_HIDDEN)); - NK_ASSERT(!(layout->flags & NK_WINDOW_CLOSED)); - - /* need to convert to int here to remove floating point errors */ - bounds->x = (float)((int)bounds->x); - bounds->y = (float)((int)bounds->y); - bounds->w = (float)((int)bounds->w); - bounds->h = (float)((int)bounds->h); - - c.x = (float)((int)c.x); - c.y = (float)((int)c.y); - c.w = (float)((int)c.w); - c.h = (float)((int)c.h); - - nk_unify(&v, &c, bounds->x, bounds->y, bounds->x + bounds->w, bounds->y + bounds->h); - if (!NK_INTERSECT(c.x, c.y, c.w, c.h, bounds->x, bounds->y, bounds->w, bounds->h)) - return NK_WIDGET_INVALID; - if (!NK_INBOX(in->mouse.pos.x, in->mouse.pos.y, v.x, v.y, v.w, v.h)) - return NK_WIDGET_ROM; - return NK_WIDGET_VALID; -} -NK_API enum nk_widget_layout_states -nk_widget_fitting(struct nk_rect *bounds, struct nk_context *ctx, - struct nk_vec2 item_padding) -{ - /* update the bounds to stand without padding */ - struct nk_window *win; - struct nk_style *style; - struct nk_panel *layout; - enum nk_widget_layout_states state; - struct nk_vec2 panel_padding; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return NK_WIDGET_INVALID; - - win = ctx->current; - style = &ctx->style; - layout = win->layout; - state = nk_widget(bounds, ctx); - - panel_padding = nk_panel_get_padding(style, layout->type); - if (layout->row.index == 1) { - bounds->w += panel_padding.x; - bounds->x -= panel_padding.x; - } else bounds->x -= item_padding.x; - - if (layout->row.index == layout->row.columns) - bounds->w += panel_padding.x; - else bounds->w += item_padding.x; - return state; -} -NK_API void -nk_spacing(struct nk_context *ctx, int cols) -{ - struct nk_window *win; - struct nk_panel *layout; - struct nk_rect none; - int i, index, rows; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return; - - /* spacing over row boundaries */ - win = ctx->current; - layout = win->layout; - index = (layout->row.index + cols) % layout->row.columns; - rows = (layout->row.index + cols) / layout->row.columns; - if (rows) { - for (i = 0; i < rows; ++i) - nk_panel_alloc_row(ctx, win); - cols = index; - } - /* non table layout need to allocate space */ - if (layout->row.type != NK_LAYOUT_DYNAMIC_FIXED && - layout->row.type != NK_LAYOUT_STATIC_FIXED) { - for (i = 0; i < cols; ++i) - nk_panel_alloc_space(&none, ctx); - } layout->row.index = index; -} - - - - - -/* =============================================================== - * - * TEXT - * - * ===============================================================*/ -NK_LIB void -nk_widget_text(struct nk_command_buffer *o, struct nk_rect b, - const char *string, int len, const struct nk_text *t, - nk_flags a, const struct nk_user_font *f) -{ - struct nk_rect label; - float text_width; - - NK_ASSERT(o); - NK_ASSERT(t); - if (!o || !t) return; - - b.h = NK_MAX(b.h, 2 * t->padding.y); - label.x = 0; label.w = 0; - label.y = b.y + t->padding.y; - label.h = NK_MIN(f->height, b.h - 2 * t->padding.y); - - text_width = f->width(f->userdata, f->height, (const char*)string, len); - text_width += (2.0f * t->padding.x); - - /* align in x-axis */ - if (a & NK_TEXT_ALIGN_LEFT) { - label.x = b.x + t->padding.x; - label.w = NK_MAX(0, b.w - 2 * t->padding.x); - } else if (a & NK_TEXT_ALIGN_CENTERED) { - label.w = NK_MAX(1, 2 * t->padding.x + (float)text_width); - label.x = (b.x + t->padding.x + ((b.w - 2 * t->padding.x) - label.w) / 2); - label.x = NK_MAX(b.x + t->padding.x, label.x); - label.w = NK_MIN(b.x + b.w, label.x + label.w); - if (label.w >= label.x) label.w -= label.x; - } else if (a & NK_TEXT_ALIGN_RIGHT) { - label.x = NK_MAX(b.x + t->padding.x, (b.x + b.w) - (2 * t->padding.x + (float)text_width)); - label.w = (float)text_width + 2 * t->padding.x; - } else return; - - /* align in y-axis */ - if (a & NK_TEXT_ALIGN_MIDDLE) { - label.y = b.y + b.h/2.0f - (float)f->height/2.0f; - label.h = NK_MAX(b.h/2.0f, b.h - (b.h/2.0f + f->height/2.0f)); - } else if (a & NK_TEXT_ALIGN_BOTTOM) { - label.y = b.y + b.h - f->height; - label.h = f->height; - } - nk_draw_text(o, label, (const char*)string, len, f, t->background, t->text); -} -NK_LIB void -nk_widget_text_wrap(struct nk_command_buffer *o, struct nk_rect b, - const char *string, int len, const struct nk_text *t, - const struct nk_user_font *f) -{ - float width; - int glyphs = 0; - int fitting = 0; - int done = 0; - struct nk_rect line; - struct nk_text text; - NK_INTERN nk_rune seperator[] = {' '}; - - NK_ASSERT(o); - NK_ASSERT(t); - if (!o || !t) return; - - text.padding = nk_vec2(0,0); - text.background = t->background; - text.text = t->text; - - b.w = NK_MAX(b.w, 2 * t->padding.x); - b.h = NK_MAX(b.h, 2 * t->padding.y); - b.h = b.h - 2 * t->padding.y; - - line.x = b.x + t->padding.x; - line.y = b.y + t->padding.y; - line.w = b.w - 2 * t->padding.x; - line.h = 2 * t->padding.y + f->height; - - fitting = nk_text_clamp(f, string, len, line.w, &glyphs, &width, seperator,NK_LEN(seperator)); - while (done < len) { - if (!fitting || line.y + line.h >= (b.y + b.h)) break; - nk_widget_text(o, line, &string[done], fitting, &text, NK_TEXT_LEFT, f); - done += fitting; - line.y += f->height + 2 * t->padding.y; - fitting = nk_text_clamp(f, &string[done], len - done, line.w, &glyphs, &width, seperator,NK_LEN(seperator)); - } -} -NK_API void -nk_text_colored(struct nk_context *ctx, const char *str, int len, - nk_flags alignment, struct nk_color color) -{ - struct nk_window *win; - const struct nk_style *style; - - struct nk_vec2 item_padding; - struct nk_rect bounds; - struct nk_text text; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) return; - - win = ctx->current; - style = &ctx->style; - nk_panel_alloc_space(&bounds, ctx); - item_padding = style->text.padding; - - text.padding.x = item_padding.x; - text.padding.y = item_padding.y; - text.background = style->window.background; - text.text = color; - nk_widget_text(&win->buffer, bounds, str, len, &text, alignment, style->font); -} -NK_API void -nk_text_wrap_colored(struct nk_context *ctx, const char *str, - int len, struct nk_color color) -{ - struct nk_window *win; - const struct nk_style *style; - - struct nk_vec2 item_padding; - struct nk_rect bounds; - struct nk_text text; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) return; - - win = ctx->current; - style = &ctx->style; - nk_panel_alloc_space(&bounds, ctx); - item_padding = style->text.padding; - - text.padding.x = item_padding.x; - text.padding.y = item_padding.y; - text.background = style->window.background; - text.text = color; - nk_widget_text_wrap(&win->buffer, bounds, str, len, &text, style->font); -} -#ifdef NK_INCLUDE_STANDARD_VARARGS -NK_API void -nk_labelf_colored(struct nk_context *ctx, nk_flags flags, - struct nk_color color, const char *fmt, ...) -{ - va_list args; - va_start(args, fmt); - nk_labelfv_colored(ctx, flags, color, fmt, args); - va_end(args); -} -NK_API void -nk_labelf_colored_wrap(struct nk_context *ctx, struct nk_color color, - const char *fmt, ...) -{ - va_list args; - va_start(args, fmt); - nk_labelfv_colored_wrap(ctx, color, fmt, args); - va_end(args); -} -NK_API void -nk_labelf(struct nk_context *ctx, nk_flags flags, const char *fmt, ...) -{ - va_list args; - va_start(args, fmt); - nk_labelfv(ctx, flags, fmt, args); - va_end(args); -} -NK_API void -nk_labelf_wrap(struct nk_context *ctx, const char *fmt,...) -{ - va_list args; - va_start(args, fmt); - nk_labelfv_wrap(ctx, fmt, args); - va_end(args); -} -NK_API void -nk_labelfv_colored(struct nk_context *ctx, nk_flags flags, - struct nk_color color, const char *fmt, va_list args) -{ - char buf[256]; - nk_strfmt(buf, NK_LEN(buf), fmt, args); - nk_label_colored(ctx, buf, flags, color); -} - -NK_API void -nk_labelfv_colored_wrap(struct nk_context *ctx, struct nk_color color, - const char *fmt, va_list args) -{ - char buf[256]; - nk_strfmt(buf, NK_LEN(buf), fmt, args); - nk_label_colored_wrap(ctx, buf, color); -} - -NK_API void -nk_labelfv(struct nk_context *ctx, nk_flags flags, const char *fmt, va_list args) -{ - char buf[256]; - nk_strfmt(buf, NK_LEN(buf), fmt, args); - nk_label(ctx, buf, flags); -} - -NK_API void -nk_labelfv_wrap(struct nk_context *ctx, const char *fmt, va_list args) -{ - char buf[256]; - nk_strfmt(buf, NK_LEN(buf), fmt, args); - nk_label_wrap(ctx, buf); -} - -NK_API void -nk_value_bool(struct nk_context *ctx, const char *prefix, int value) -{ - nk_labelf(ctx, NK_TEXT_LEFT, "%s: %s", prefix, ((value) ? "true": "false")); -} -NK_API void -nk_value_int(struct nk_context *ctx, const char *prefix, int value) -{ - nk_labelf(ctx, NK_TEXT_LEFT, "%s: %d", prefix, value); -} -NK_API void -nk_value_uint(struct nk_context *ctx, const char *prefix, unsigned int value) -{ - nk_labelf(ctx, NK_TEXT_LEFT, "%s: %u", prefix, value); -} -NK_API void -nk_value_float(struct nk_context *ctx, const char *prefix, float value) -{ - double double_value = (double)value; - nk_labelf(ctx, NK_TEXT_LEFT, "%s: %.3f", prefix, double_value); -} -NK_API void -nk_value_color_byte(struct nk_context *ctx, const char *p, struct nk_color c) -{ - nk_labelf(ctx, NK_TEXT_LEFT, "%s: (%d, %d, %d, %d)", p, c.r, c.g, c.b, c.a); -} -NK_API void -nk_value_color_float(struct nk_context *ctx, const char *p, struct nk_color color) -{ - double c[4]; nk_color_dv(c, color); - nk_labelf(ctx, NK_TEXT_LEFT, "%s: (%.2f, %.2f, %.2f, %.2f)", - p, c[0], c[1], c[2], c[3]); -} -NK_API void -nk_value_color_hex(struct nk_context *ctx, const char *prefix, struct nk_color color) -{ - char hex[16]; - nk_color_hex_rgba(hex, color); - nk_labelf(ctx, NK_TEXT_LEFT, "%s: %s", prefix, hex); -} -#endif -NK_API void -nk_text(struct nk_context *ctx, const char *str, int len, nk_flags alignment) -{ - NK_ASSERT(ctx); - if (!ctx) return; - nk_text_colored(ctx, str, len, alignment, ctx->style.text.color); -} -NK_API void -nk_text_wrap(struct nk_context *ctx, const char *str, int len) -{ - NK_ASSERT(ctx); - if (!ctx) return; - nk_text_wrap_colored(ctx, str, len, ctx->style.text.color); -} -NK_API void -nk_label(struct nk_context *ctx, const char *str, nk_flags alignment) -{ - nk_text(ctx, str, nk_strlen(str), alignment); -} -NK_API void -nk_label_colored(struct nk_context *ctx, const char *str, nk_flags align, - struct nk_color color) -{ - nk_text_colored(ctx, str, nk_strlen(str), align, color); -} -NK_API void -nk_label_wrap(struct nk_context *ctx, const char *str) -{ - nk_text_wrap(ctx, str, nk_strlen(str)); -} -NK_API void -nk_label_colored_wrap(struct nk_context *ctx, const char *str, struct nk_color color) -{ - nk_text_wrap_colored(ctx, str, nk_strlen(str), color); -} - - - - - -/* =============================================================== - * - * IMAGE - * - * ===============================================================*/ -NK_API nk_handle -nk_handle_ptr(void *ptr) -{ - nk_handle handle = {0}; - handle.ptr = ptr; - return handle; -} -NK_API nk_handle -nk_handle_id(int id) -{ - nk_handle handle; - nk_zero_struct(handle); - handle.id = id; - return handle; -} -NK_API struct nk_image -nk_subimage_ptr(void *ptr, unsigned short w, unsigned short h, struct nk_rect r) -{ - struct nk_image s; - nk_zero(&s, sizeof(s)); - s.handle.ptr = ptr; - s.w = w; s.h = h; - s.region[0] = (unsigned short)r.x; - s.region[1] = (unsigned short)r.y; - s.region[2] = (unsigned short)r.w; - s.region[3] = (unsigned short)r.h; - return s; -} -NK_API struct nk_image -nk_subimage_id(int id, unsigned short w, unsigned short h, struct nk_rect r) -{ - struct nk_image s; - nk_zero(&s, sizeof(s)); - s.handle.id = id; - s.w = w; s.h = h; - s.region[0] = (unsigned short)r.x; - s.region[1] = (unsigned short)r.y; - s.region[2] = (unsigned short)r.w; - s.region[3] = (unsigned short)r.h; - return s; -} -NK_API struct nk_image -nk_subimage_handle(nk_handle handle, unsigned short w, unsigned short h, - struct nk_rect r) -{ - struct nk_image s; - nk_zero(&s, sizeof(s)); - s.handle = handle; - s.w = w; s.h = h; - s.region[0] = (unsigned short)r.x; - s.region[1] = (unsigned short)r.y; - s.region[2] = (unsigned short)r.w; - s.region[3] = (unsigned short)r.h; - return s; -} -NK_API struct nk_image -nk_image_handle(nk_handle handle) -{ - struct nk_image s; - nk_zero(&s, sizeof(s)); - s.handle = handle; - s.w = 0; s.h = 0; - s.region[0] = 0; - s.region[1] = 0; - s.region[2] = 0; - s.region[3] = 0; - return s; -} -NK_API struct nk_image -nk_image_ptr(void *ptr) -{ - struct nk_image s; - nk_zero(&s, sizeof(s)); - NK_ASSERT(ptr); - s.handle.ptr = ptr; - s.w = 0; s.h = 0; - s.region[0] = 0; - s.region[1] = 0; - s.region[2] = 0; - s.region[3] = 0; - return s; -} -NK_API struct nk_image -nk_image_id(int id) -{ - struct nk_image s; - nk_zero(&s, sizeof(s)); - s.handle.id = id; - s.w = 0; s.h = 0; - s.region[0] = 0; - s.region[1] = 0; - s.region[2] = 0; - s.region[3] = 0; - return s; -} -NK_API int -nk_image_is_subimage(const struct nk_image* img) -{ - NK_ASSERT(img); - return !(img->w == 0 && img->h == 0); -} -NK_API void -nk_image(struct nk_context *ctx, struct nk_image img) -{ - struct nk_window *win; - struct nk_rect bounds; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) return; - - win = ctx->current; - if (!nk_widget(&bounds, ctx)) return; - nk_draw_image(&win->buffer, bounds, &img, nk_white); -} -NK_API void -nk_image_color(struct nk_context *ctx, struct nk_image img, struct nk_color col) -{ - struct nk_window *win; - struct nk_rect bounds; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) return; - - win = ctx->current; - if (!nk_widget(&bounds, ctx)) return; - nk_draw_image(&win->buffer, bounds, &img, col); -} - - - - - -/* ============================================================== - * - * BUTTON - * - * ===============================================================*/ -NK_LIB void -nk_draw_symbol(struct nk_command_buffer *out, enum nk_symbol_type type, - struct nk_rect content, struct nk_color background, struct nk_color foreground, - float border_width, const struct nk_user_font *font) -{ - switch (type) { - case NK_SYMBOL_X: - case NK_SYMBOL_UNDERSCORE: - case NK_SYMBOL_PLUS: - case NK_SYMBOL_MINUS: { - /* single character text symbol */ - const char *X = (type == NK_SYMBOL_X) ? "x": - (type == NK_SYMBOL_UNDERSCORE) ? "_": - (type == NK_SYMBOL_PLUS) ? "+": "-"; - struct nk_text text; - text.padding = nk_vec2(0,0); - text.background = background; - text.text = foreground; - nk_widget_text(out, content, X, 1, &text, NK_TEXT_CENTERED, font); - } break; - case NK_SYMBOL_CIRCLE_SOLID: - case NK_SYMBOL_CIRCLE_OUTLINE: - case NK_SYMBOL_RECT_SOLID: - case NK_SYMBOL_RECT_OUTLINE: { - /* simple empty/filled shapes */ - if (type == NK_SYMBOL_RECT_SOLID || type == NK_SYMBOL_RECT_OUTLINE) { - nk_fill_rect(out, content, 0, foreground); - if (type == NK_SYMBOL_RECT_OUTLINE) - nk_fill_rect(out, nk_shrink_rect(content, border_width), 0, background); - } else { - nk_fill_circle(out, content, foreground); - if (type == NK_SYMBOL_CIRCLE_OUTLINE) - nk_fill_circle(out, nk_shrink_rect(content, 1), background); - } - } break; - case NK_SYMBOL_TRIANGLE_UP: - case NK_SYMBOL_TRIANGLE_DOWN: - case NK_SYMBOL_TRIANGLE_LEFT: - case NK_SYMBOL_TRIANGLE_RIGHT: { - enum nk_heading heading; - struct nk_vec2 points[3]; - heading = (type == NK_SYMBOL_TRIANGLE_RIGHT) ? NK_RIGHT : - (type == NK_SYMBOL_TRIANGLE_LEFT) ? NK_LEFT: - (type == NK_SYMBOL_TRIANGLE_UP) ? NK_UP: NK_DOWN; - nk_triangle_from_direction(points, content, 0, 0, heading); - nk_fill_triangle(out, points[0].x, points[0].y, points[1].x, points[1].y, - points[2].x, points[2].y, foreground); - } break; - default: - case NK_SYMBOL_NONE: - case NK_SYMBOL_MAX: break; - } -} -NK_LIB int -nk_button_behavior(nk_flags *state, struct nk_rect r, - const struct nk_input *i, enum nk_button_behavior behavior) -{ - int ret = 0; - nk_widget_state_reset(state); - if (!i) return 0; - if (nk_input_is_mouse_hovering_rect(i, r)) { - *state = NK_WIDGET_STATE_HOVERED; - if (nk_input_is_mouse_down(i, NK_BUTTON_LEFT)) - *state = NK_WIDGET_STATE_ACTIVE; - if (nk_input_has_mouse_click_in_rect(i, NK_BUTTON_LEFT, r)) { - ret = (behavior != NK_BUTTON_DEFAULT) ? - nk_input_is_mouse_down(i, NK_BUTTON_LEFT): -#ifdef NK_BUTTON_TRIGGER_ON_RELEASE - nk_input_is_mouse_released(i, NK_BUTTON_LEFT); -#else - nk_input_is_mouse_pressed(i, NK_BUTTON_LEFT); -#endif - } - } - if (*state & NK_WIDGET_STATE_HOVER && !nk_input_is_mouse_prev_hovering_rect(i, r)) - *state |= NK_WIDGET_STATE_ENTERED; - else if (nk_input_is_mouse_prev_hovering_rect(i, r)) - *state |= NK_WIDGET_STATE_LEFT; - return ret; -} -NK_LIB const struct nk_style_item* -nk_draw_button(struct nk_command_buffer *out, - const struct nk_rect *bounds, nk_flags state, - const struct nk_style_button *style) -{ - const struct nk_style_item *background; - if (state & NK_WIDGET_STATE_HOVER) - background = &style->hover; - else if (state & NK_WIDGET_STATE_ACTIVED) - background = &style->active; - else background = &style->normal; - - if (background->type == NK_STYLE_ITEM_IMAGE) { - nk_draw_image(out, *bounds, &background->data.image, nk_white); - } else { - nk_fill_rect(out, *bounds, style->rounding, background->data.color); - nk_stroke_rect(out, *bounds, style->rounding, style->border, style->border_color); - } - return background; -} -NK_LIB int -nk_do_button(nk_flags *state, struct nk_command_buffer *out, struct nk_rect r, - const struct nk_style_button *style, const struct nk_input *in, - enum nk_button_behavior behavior, struct nk_rect *content) -{ - struct nk_rect bounds; - NK_ASSERT(style); - NK_ASSERT(state); - NK_ASSERT(out); - if (!out || !style) - return nk_false; - - /* calculate button content space */ - content->x = r.x + style->padding.x + style->border + style->rounding; - content->y = r.y + style->padding.y + style->border + style->rounding; - content->w = r.w - (2 * style->padding.x + style->border + style->rounding*2); - content->h = r.h - (2 * style->padding.y + style->border + style->rounding*2); - - /* execute button behavior */ - bounds.x = r.x - style->touch_padding.x; - bounds.y = r.y - style->touch_padding.y; - bounds.w = r.w + 2 * style->touch_padding.x; - bounds.h = r.h + 2 * style->touch_padding.y; - return nk_button_behavior(state, bounds, in, behavior); -} -NK_LIB void -nk_draw_button_text(struct nk_command_buffer *out, - const struct nk_rect *bounds, const struct nk_rect *content, nk_flags state, - const struct nk_style_button *style, const char *txt, int len, - nk_flags text_alignment, const struct nk_user_font *font) -{ - struct nk_text text; - const struct nk_style_item *background; - background = nk_draw_button(out, bounds, state, style); - - /* select correct colors/images */ - if (background->type == NK_STYLE_ITEM_COLOR) - text.background = background->data.color; - else text.background = style->text_background; - if (state & NK_WIDGET_STATE_HOVER) - text.text = style->text_hover; - else if (state & NK_WIDGET_STATE_ACTIVED) - text.text = style->text_active; - else text.text = style->text_normal; - - text.padding = nk_vec2(0,0); - nk_widget_text(out, *content, txt, len, &text, text_alignment, font); -} -NK_LIB int -nk_do_button_text(nk_flags *state, - struct nk_command_buffer *out, struct nk_rect bounds, - const char *string, int len, nk_flags align, enum nk_button_behavior behavior, - const struct nk_style_button *style, const struct nk_input *in, - const struct nk_user_font *font) -{ - struct nk_rect content; - int ret = nk_false; - - NK_ASSERT(state); - NK_ASSERT(style); - NK_ASSERT(out); - NK_ASSERT(string); - NK_ASSERT(font); - if (!out || !style || !font || !string) - return nk_false; - - ret = nk_do_button(state, out, bounds, style, in, behavior, &content); - if (style->draw_begin) style->draw_begin(out, style->userdata); - nk_draw_button_text(out, &bounds, &content, *state, style, string, len, align, font); - if (style->draw_end) style->draw_end(out, style->userdata); - return ret; -} -NK_LIB void -nk_draw_button_symbol(struct nk_command_buffer *out, - const struct nk_rect *bounds, const struct nk_rect *content, - nk_flags state, const struct nk_style_button *style, - enum nk_symbol_type type, const struct nk_user_font *font) -{ - struct nk_color sym, bg; - const struct nk_style_item *background; - - /* select correct colors/images */ - background = nk_draw_button(out, bounds, state, style); - if (background->type == NK_STYLE_ITEM_COLOR) - bg = background->data.color; - else bg = style->text_background; - - if (state & NK_WIDGET_STATE_HOVER) - sym = style->text_hover; - else if (state & NK_WIDGET_STATE_ACTIVED) - sym = style->text_active; - else sym = style->text_normal; - nk_draw_symbol(out, type, *content, bg, sym, 1, font); -} -NK_LIB int -nk_do_button_symbol(nk_flags *state, - struct nk_command_buffer *out, struct nk_rect bounds, - enum nk_symbol_type symbol, enum nk_button_behavior behavior, - const struct nk_style_button *style, const struct nk_input *in, - const struct nk_user_font *font) -{ - int ret; - struct nk_rect content; - - NK_ASSERT(state); - NK_ASSERT(style); - NK_ASSERT(font); - NK_ASSERT(out); - if (!out || !style || !font || !state) - return nk_false; - - ret = nk_do_button(state, out, bounds, style, in, behavior, &content); - if (style->draw_begin) style->draw_begin(out, style->userdata); - nk_draw_button_symbol(out, &bounds, &content, *state, style, symbol, font); - if (style->draw_end) style->draw_end(out, style->userdata); - return ret; -} -NK_LIB void -nk_draw_button_image(struct nk_command_buffer *out, - const struct nk_rect *bounds, const struct nk_rect *content, - nk_flags state, const struct nk_style_button *style, const struct nk_image *img) -{ - nk_draw_button(out, bounds, state, style); - nk_draw_image(out, *content, img, nk_white); -} -NK_LIB int -nk_do_button_image(nk_flags *state, - struct nk_command_buffer *out, struct nk_rect bounds, - struct nk_image img, enum nk_button_behavior b, - const struct nk_style_button *style, const struct nk_input *in) -{ - int ret; - struct nk_rect content; - - NK_ASSERT(state); - NK_ASSERT(style); - NK_ASSERT(out); - if (!out || !style || !state) - return nk_false; - - ret = nk_do_button(state, out, bounds, style, in, b, &content); - content.x += style->image_padding.x; - content.y += style->image_padding.y; - content.w -= 2 * style->image_padding.x; - content.h -= 2 * style->image_padding.y; - - if (style->draw_begin) style->draw_begin(out, style->userdata); - nk_draw_button_image(out, &bounds, &content, *state, style, &img); - if (style->draw_end) style->draw_end(out, style->userdata); - return ret; -} -NK_LIB void -nk_draw_button_text_symbol(struct nk_command_buffer *out, - const struct nk_rect *bounds, const struct nk_rect *label, - const struct nk_rect *symbol, nk_flags state, const struct nk_style_button *style, - const char *str, int len, enum nk_symbol_type type, - const struct nk_user_font *font) -{ - struct nk_color sym; - struct nk_text text; - const struct nk_style_item *background; - - /* select correct background colors/images */ - background = nk_draw_button(out, bounds, state, style); - if (background->type == NK_STYLE_ITEM_COLOR) - text.background = background->data.color; - else text.background = style->text_background; - - /* select correct text colors */ - if (state & NK_WIDGET_STATE_HOVER) { - sym = style->text_hover; - text.text = style->text_hover; - } else if (state & NK_WIDGET_STATE_ACTIVED) { - sym = style->text_active; - text.text = style->text_active; - } else { - sym = style->text_normal; - text.text = style->text_normal; - } - - text.padding = nk_vec2(0,0); - nk_draw_symbol(out, type, *symbol, style->text_background, sym, 0, font); - nk_widget_text(out, *label, str, len, &text, NK_TEXT_CENTERED, font); -} -NK_LIB int -nk_do_button_text_symbol(nk_flags *state, - struct nk_command_buffer *out, struct nk_rect bounds, - enum nk_symbol_type symbol, const char *str, int len, nk_flags align, - enum nk_button_behavior behavior, const struct nk_style_button *style, - const struct nk_user_font *font, const struct nk_input *in) -{ - int ret; - struct nk_rect tri = {0,0,0,0}; - struct nk_rect content; - - NK_ASSERT(style); - NK_ASSERT(out); - NK_ASSERT(font); - if (!out || !style || !font) - return nk_false; - - ret = nk_do_button(state, out, bounds, style, in, behavior, &content); - tri.y = content.y + (content.h/2) - font->height/2; - tri.w = font->height; tri.h = font->height; - if (align & NK_TEXT_ALIGN_LEFT) { - tri.x = (content.x + content.w) - (2 * style->padding.x + tri.w); - tri.x = NK_MAX(tri.x, 0); - } else tri.x = content.x + 2 * style->padding.x; - - /* draw button */ - if (style->draw_begin) style->draw_begin(out, style->userdata); - nk_draw_button_text_symbol(out, &bounds, &content, &tri, - *state, style, str, len, symbol, font); - if (style->draw_end) style->draw_end(out, style->userdata); - return ret; -} -NK_LIB void -nk_draw_button_text_image(struct nk_command_buffer *out, - const struct nk_rect *bounds, const struct nk_rect *label, - const struct nk_rect *image, nk_flags state, const struct nk_style_button *style, - const char *str, int len, const struct nk_user_font *font, - const struct nk_image *img) -{ - struct nk_text text; - const struct nk_style_item *background; - background = nk_draw_button(out, bounds, state, style); - - /* select correct colors */ - if (background->type == NK_STYLE_ITEM_COLOR) - text.background = background->data.color; - else text.background = style->text_background; - if (state & NK_WIDGET_STATE_HOVER) - text.text = style->text_hover; - else if (state & NK_WIDGET_STATE_ACTIVED) - text.text = style->text_active; - else text.text = style->text_normal; - - text.padding = nk_vec2(0,0); - nk_widget_text(out, *label, str, len, &text, NK_TEXT_CENTERED, font); - nk_draw_image(out, *image, img, nk_white); -} -NK_LIB int -nk_do_button_text_image(nk_flags *state, - struct nk_command_buffer *out, struct nk_rect bounds, - struct nk_image img, const char* str, int len, nk_flags align, - enum nk_button_behavior behavior, const struct nk_style_button *style, - const struct nk_user_font *font, const struct nk_input *in) -{ - int ret; - struct nk_rect icon; - struct nk_rect content; - - NK_ASSERT(style); - NK_ASSERT(state); - NK_ASSERT(font); - NK_ASSERT(out); - if (!out || !font || !style || !str) - return nk_false; - - ret = nk_do_button(state, out, bounds, style, in, behavior, &content); - icon.y = bounds.y + style->padding.y; - icon.w = icon.h = bounds.h - 2 * style->padding.y; - if (align & NK_TEXT_ALIGN_LEFT) { - icon.x = (bounds.x + bounds.w) - (2 * style->padding.x + icon.w); - icon.x = NK_MAX(icon.x, 0); - } else icon.x = bounds.x + 2 * style->padding.x; - - icon.x += style->image_padding.x; - icon.y += style->image_padding.y; - icon.w -= 2 * style->image_padding.x; - icon.h -= 2 * style->image_padding.y; - - if (style->draw_begin) style->draw_begin(out, style->userdata); - nk_draw_button_text_image(out, &bounds, &content, &icon, *state, style, str, len, font, &img); - if (style->draw_end) style->draw_end(out, style->userdata); - return ret; -} -NK_API void -nk_button_set_behavior(struct nk_context *ctx, enum nk_button_behavior behavior) -{ - NK_ASSERT(ctx); - if (!ctx) return; - ctx->button_behavior = behavior; -} -NK_API int -nk_button_push_behavior(struct nk_context *ctx, enum nk_button_behavior behavior) -{ - struct nk_config_stack_button_behavior *button_stack; - struct nk_config_stack_button_behavior_element *element; - - NK_ASSERT(ctx); - if (!ctx) return 0; - - button_stack = &ctx->stacks.button_behaviors; - NK_ASSERT(button_stack->head < (int)NK_LEN(button_stack->elements)); - if (button_stack->head >= (int)NK_LEN(button_stack->elements)) - return 0; - - element = &button_stack->elements[button_stack->head++]; - element->address = &ctx->button_behavior; - element->old_value = ctx->button_behavior; - ctx->button_behavior = behavior; - return 1; -} -NK_API int -nk_button_pop_behavior(struct nk_context *ctx) -{ - struct nk_config_stack_button_behavior *button_stack; - struct nk_config_stack_button_behavior_element *element; - - NK_ASSERT(ctx); - if (!ctx) return 0; - - button_stack = &ctx->stacks.button_behaviors; - NK_ASSERT(button_stack->head > 0); - if (button_stack->head < 1) - return 0; - - element = &button_stack->elements[--button_stack->head]; - *element->address = element->old_value; - return 1; -} -NK_API int -nk_button_text_styled(struct nk_context *ctx, - const struct nk_style_button *style, const char *title, int len) -{ - struct nk_window *win; - struct nk_panel *layout; - const struct nk_input *in; - - struct nk_rect bounds; - enum nk_widget_layout_states state; - - NK_ASSERT(ctx); - NK_ASSERT(style); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!style || !ctx || !ctx->current || !ctx->current->layout) return 0; - - win = ctx->current; - layout = win->layout; - state = nk_widget(&bounds, ctx); - - if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; - return nk_do_button_text(&ctx->last_widget_state, &win->buffer, bounds, - title, len, style->text_alignment, ctx->button_behavior, - style, in, ctx->style.font); -} -NK_API int -nk_button_text(struct nk_context *ctx, const char *title, int len) -{ - NK_ASSERT(ctx); - if (!ctx) return 0; - return nk_button_text_styled(ctx, &ctx->style.button, title, len); -} -NK_API int nk_button_label_styled(struct nk_context *ctx, - const struct nk_style_button *style, const char *title) -{ - return nk_button_text_styled(ctx, style, title, nk_strlen(title)); -} -NK_API int nk_button_label(struct nk_context *ctx, const char *title) -{ - return nk_button_text(ctx, title, nk_strlen(title)); -} -NK_API int -nk_button_color(struct nk_context *ctx, struct nk_color color) -{ - struct nk_window *win; - struct nk_panel *layout; - const struct nk_input *in; - struct nk_style_button button; - - int ret = 0; - struct nk_rect bounds; - struct nk_rect content; - enum nk_widget_layout_states state; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return 0; - - win = ctx->current; - layout = win->layout; - - state = nk_widget(&bounds, ctx); - if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; - - button = ctx->style.button; - button.normal = nk_style_item_color(color); - button.hover = nk_style_item_color(color); - button.active = nk_style_item_color(color); - ret = nk_do_button(&ctx->last_widget_state, &win->buffer, bounds, - &button, in, ctx->button_behavior, &content); - nk_draw_button(&win->buffer, &bounds, ctx->last_widget_state, &button); - return ret; -} -NK_API int -nk_button_symbol_styled(struct nk_context *ctx, - const struct nk_style_button *style, enum nk_symbol_type symbol) -{ - struct nk_window *win; - struct nk_panel *layout; - const struct nk_input *in; - - struct nk_rect bounds; - enum nk_widget_layout_states state; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return 0; - - win = ctx->current; - layout = win->layout; - state = nk_widget(&bounds, ctx); - if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; - return nk_do_button_symbol(&ctx->last_widget_state, &win->buffer, bounds, - symbol, ctx->button_behavior, style, in, ctx->style.font); -} -NK_API int -nk_button_symbol(struct nk_context *ctx, enum nk_symbol_type symbol) -{ - NK_ASSERT(ctx); - if (!ctx) return 0; - return nk_button_symbol_styled(ctx, &ctx->style.button, symbol); -} -NK_API int -nk_button_image_styled(struct nk_context *ctx, const struct nk_style_button *style, - struct nk_image img) -{ - struct nk_window *win; - struct nk_panel *layout; - const struct nk_input *in; - - struct nk_rect bounds; - enum nk_widget_layout_states state; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return 0; - - win = ctx->current; - layout = win->layout; - - state = nk_widget(&bounds, ctx); - if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; - return nk_do_button_image(&ctx->last_widget_state, &win->buffer, bounds, - img, ctx->button_behavior, style, in); -} -NK_API int -nk_button_image(struct nk_context *ctx, struct nk_image img) -{ - NK_ASSERT(ctx); - if (!ctx) return 0; - return nk_button_image_styled(ctx, &ctx->style.button, img); -} -NK_API int -nk_button_symbol_text_styled(struct nk_context *ctx, - const struct nk_style_button *style, enum nk_symbol_type symbol, - const char *text, int len, nk_flags align) -{ - struct nk_window *win; - struct nk_panel *layout; - const struct nk_input *in; - - struct nk_rect bounds; - enum nk_widget_layout_states state; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return 0; - - win = ctx->current; - layout = win->layout; - - state = nk_widget(&bounds, ctx); - if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; - return nk_do_button_text_symbol(&ctx->last_widget_state, &win->buffer, bounds, - symbol, text, len, align, ctx->button_behavior, - style, ctx->style.font, in); -} -NK_API int -nk_button_symbol_text(struct nk_context *ctx, enum nk_symbol_type symbol, - const char* text, int len, nk_flags align) -{ - NK_ASSERT(ctx); - if (!ctx) return 0; - return nk_button_symbol_text_styled(ctx, &ctx->style.button, symbol, text, len, align); -} -NK_API int nk_button_symbol_label(struct nk_context *ctx, enum nk_symbol_type symbol, - const char *label, nk_flags align) -{ - return nk_button_symbol_text(ctx, symbol, label, nk_strlen(label), align); -} -NK_API int nk_button_symbol_label_styled(struct nk_context *ctx, - const struct nk_style_button *style, enum nk_symbol_type symbol, - const char *title, nk_flags align) -{ - return nk_button_symbol_text_styled(ctx, style, symbol, title, nk_strlen(title), align); -} -NK_API int -nk_button_image_text_styled(struct nk_context *ctx, - const struct nk_style_button *style, struct nk_image img, const char *text, - int len, nk_flags align) -{ - struct nk_window *win; - struct nk_panel *layout; - const struct nk_input *in; - - struct nk_rect bounds; - enum nk_widget_layout_states state; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return 0; - - win = ctx->current; - layout = win->layout; - - state = nk_widget(&bounds, ctx); - if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; - return nk_do_button_text_image(&ctx->last_widget_state, &win->buffer, - bounds, img, text, len, align, ctx->button_behavior, - style, ctx->style.font, in); -} -NK_API int -nk_button_image_text(struct nk_context *ctx, struct nk_image img, - const char *text, int len, nk_flags align) -{ - return nk_button_image_text_styled(ctx, &ctx->style.button,img, text, len, align); -} -NK_API int nk_button_image_label(struct nk_context *ctx, struct nk_image img, - const char *label, nk_flags align) -{ - return nk_button_image_text(ctx, img, label, nk_strlen(label), align); -} -NK_API int nk_button_image_label_styled(struct nk_context *ctx, - const struct nk_style_button *style, struct nk_image img, - const char *label, nk_flags text_alignment) -{ - return nk_button_image_text_styled(ctx, style, img, label, nk_strlen(label), text_alignment); -} - - - - - -/* =============================================================== - * - * TOGGLE - * - * ===============================================================*/ -NK_LIB int -nk_toggle_behavior(const struct nk_input *in, struct nk_rect select, - nk_flags *state, int active) -{ - nk_widget_state_reset(state); - if (nk_button_behavior(state, select, in, NK_BUTTON_DEFAULT)) { - *state = NK_WIDGET_STATE_ACTIVE; - active = !active; - } - if (*state & NK_WIDGET_STATE_HOVER && !nk_input_is_mouse_prev_hovering_rect(in, select)) - *state |= NK_WIDGET_STATE_ENTERED; - else if (nk_input_is_mouse_prev_hovering_rect(in, select)) - *state |= NK_WIDGET_STATE_LEFT; - return active; -} -NK_LIB void -nk_draw_checkbox(struct nk_command_buffer *out, - nk_flags state, const struct nk_style_toggle *style, int active, - const struct nk_rect *label, const struct nk_rect *selector, - const struct nk_rect *cursors, const char *string, int len, - const struct nk_user_font *font) -{ - const struct nk_style_item *background; - const struct nk_style_item *cursor; - struct nk_text text; - - /* select correct colors/images */ - if (state & NK_WIDGET_STATE_HOVER) { - background = &style->hover; - cursor = &style->cursor_hover; - text.text = style->text_hover; - } else if (state & NK_WIDGET_STATE_ACTIVED) { - background = &style->hover; - cursor = &style->cursor_hover; - text.text = style->text_active; - } else { - background = &style->normal; - cursor = &style->cursor_normal; - text.text = style->text_normal; - } - - /* draw background and cursor */ - if (background->type == NK_STYLE_ITEM_COLOR) { - nk_fill_rect(out, *selector, 0, style->border_color); - nk_fill_rect(out, nk_shrink_rect(*selector, style->border), 0, background->data.color); - } else nk_draw_image(out, *selector, &background->data.image, nk_white); - if (active) { - if (cursor->type == NK_STYLE_ITEM_IMAGE) - nk_draw_image(out, *cursors, &cursor->data.image, nk_white); - else nk_fill_rect(out, *cursors, 0, cursor->data.color); - } - - text.padding.x = 0; - text.padding.y = 0; - text.background = style->text_background; - nk_widget_text(out, *label, string, len, &text, NK_TEXT_LEFT, font); -} -NK_LIB void -nk_draw_option(struct nk_command_buffer *out, - nk_flags state, const struct nk_style_toggle *style, int active, - const struct nk_rect *label, const struct nk_rect *selector, - const struct nk_rect *cursors, const char *string, int len, - const struct nk_user_font *font) -{ - const struct nk_style_item *background; - const struct nk_style_item *cursor; - struct nk_text text; - - /* select correct colors/images */ - if (state & NK_WIDGET_STATE_HOVER) { - background = &style->hover; - cursor = &style->cursor_hover; - text.text = style->text_hover; - } else if (state & NK_WIDGET_STATE_ACTIVED) { - background = &style->hover; - cursor = &style->cursor_hover; - text.text = style->text_active; - } else { - background = &style->normal; - cursor = &style->cursor_normal; - text.text = style->text_normal; - } - - /* draw background and cursor */ - if (background->type == NK_STYLE_ITEM_COLOR) { - nk_fill_circle(out, *selector, style->border_color); - nk_fill_circle(out, nk_shrink_rect(*selector, style->border), background->data.color); - } else nk_draw_image(out, *selector, &background->data.image, nk_white); - if (active) { - if (cursor->type == NK_STYLE_ITEM_IMAGE) - nk_draw_image(out, *cursors, &cursor->data.image, nk_white); - else nk_fill_circle(out, *cursors, cursor->data.color); - } - - text.padding.x = 0; - text.padding.y = 0; - text.background = style->text_background; - nk_widget_text(out, *label, string, len, &text, NK_TEXT_LEFT, font); -} -NK_LIB int -nk_do_toggle(nk_flags *state, - struct nk_command_buffer *out, struct nk_rect r, - int *active, const char *str, int len, enum nk_toggle_type type, - const struct nk_style_toggle *style, const struct nk_input *in, - const struct nk_user_font *font) -{ - int was_active; - struct nk_rect bounds; - struct nk_rect select; - struct nk_rect cursor; - struct nk_rect label; - - NK_ASSERT(style); - NK_ASSERT(out); - NK_ASSERT(font); - if (!out || !style || !font || !active) - return 0; - - r.w = NK_MAX(r.w, font->height + 2 * style->padding.x); - r.h = NK_MAX(r.h, font->height + 2 * style->padding.y); - - /* add additional touch padding for touch screen devices */ - bounds.x = r.x - style->touch_padding.x; - bounds.y = r.y - style->touch_padding.y; - bounds.w = r.w + 2 * style->touch_padding.x; - bounds.h = r.h + 2 * style->touch_padding.y; - - /* calculate the selector space */ - select.w = font->height; - select.h = select.w; - select.y = r.y + r.h/2.0f - select.h/2.0f; - select.x = r.x; - - /* calculate the bounds of the cursor inside the selector */ - cursor.x = select.x + style->padding.x + style->border; - cursor.y = select.y + style->padding.y + style->border; - cursor.w = select.w - (2 * style->padding.x + 2 * style->border); - cursor.h = select.h - (2 * style->padding.y + 2 * style->border); - - /* label behind the selector */ - label.x = select.x + select.w + style->spacing; - label.y = select.y; - label.w = NK_MAX(r.x + r.w, label.x) - label.x; - label.h = select.w; - - /* update selector */ - was_active = *active; - *active = nk_toggle_behavior(in, bounds, state, *active); - - /* draw selector */ - if (style->draw_begin) - style->draw_begin(out, style->userdata); - if (type == NK_TOGGLE_CHECK) { - nk_draw_checkbox(out, *state, style, *active, &label, &select, &cursor, str, len, font); - } else { - nk_draw_option(out, *state, style, *active, &label, &select, &cursor, str, len, font); - } - if (style->draw_end) - style->draw_end(out, style->userdata); - return (was_active != *active); -} -/*---------------------------------------------------------------- - * - * CHECKBOX - * - * --------------------------------------------------------------*/ -NK_API int -nk_check_text(struct nk_context *ctx, const char *text, int len, int active) -{ - struct nk_window *win; - struct nk_panel *layout; - const struct nk_input *in; - const struct nk_style *style; - - struct nk_rect bounds; - enum nk_widget_layout_states state; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return active; - - win = ctx->current; - style = &ctx->style; - layout = win->layout; - - state = nk_widget(&bounds, ctx); - if (!state) return active; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; - nk_do_toggle(&ctx->last_widget_state, &win->buffer, bounds, &active, - text, len, NK_TOGGLE_CHECK, &style->checkbox, in, style->font); - return active; -} -NK_API unsigned int -nk_check_flags_text(struct nk_context *ctx, const char *text, int len, - unsigned int flags, unsigned int value) -{ - int old_active; - NK_ASSERT(ctx); - NK_ASSERT(text); - if (!ctx || !text) return flags; - old_active = (int)((flags & value) & value); - if (nk_check_text(ctx, text, len, old_active)) - flags |= value; - else flags &= ~value; - return flags; -} -NK_API int -nk_checkbox_text(struct nk_context *ctx, const char *text, int len, int *active) -{ - int old_val; - NK_ASSERT(ctx); - NK_ASSERT(text); - NK_ASSERT(active); - if (!ctx || !text || !active) return 0; - old_val = *active; - *active = nk_check_text(ctx, text, len, *active); - return old_val != *active; -} -NK_API int -nk_checkbox_flags_text(struct nk_context *ctx, const char *text, int len, - unsigned int *flags, unsigned int value) -{ - int active; - NK_ASSERT(ctx); - NK_ASSERT(text); - NK_ASSERT(flags); - if (!ctx || !text || !flags) return 0; - - active = (int)((*flags & value) & value); - if (nk_checkbox_text(ctx, text, len, &active)) { - if (active) *flags |= value; - else *flags &= ~value; - return 1; - } - return 0; -} -NK_API int nk_check_label(struct nk_context *ctx, const char *label, int active) -{ - return nk_check_text(ctx, label, nk_strlen(label), active); -} -NK_API unsigned int nk_check_flags_label(struct nk_context *ctx, const char *label, - unsigned int flags, unsigned int value) -{ - return nk_check_flags_text(ctx, label, nk_strlen(label), flags, value); -} -NK_API int nk_checkbox_label(struct nk_context *ctx, const char *label, int *active) -{ - return nk_checkbox_text(ctx, label, nk_strlen(label), active); -} -NK_API int nk_checkbox_flags_label(struct nk_context *ctx, const char *label, - unsigned int *flags, unsigned int value) -{ - return nk_checkbox_flags_text(ctx, label, nk_strlen(label), flags, value); -} -/*---------------------------------------------------------------- - * - * OPTION - * - * --------------------------------------------------------------*/ -NK_API int -nk_option_text(struct nk_context *ctx, const char *text, int len, int is_active) -{ - struct nk_window *win; - struct nk_panel *layout; - const struct nk_input *in; - const struct nk_style *style; - - struct nk_rect bounds; - enum nk_widget_layout_states state; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return is_active; - - win = ctx->current; - style = &ctx->style; - layout = win->layout; - - state = nk_widget(&bounds, ctx); - if (!state) return (int)state; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; - nk_do_toggle(&ctx->last_widget_state, &win->buffer, bounds, &is_active, - text, len, NK_TOGGLE_OPTION, &style->option, in, style->font); - return is_active; -} -NK_API int -nk_radio_text(struct nk_context *ctx, const char *text, int len, int *active) -{ - int old_value; - NK_ASSERT(ctx); - NK_ASSERT(text); - NK_ASSERT(active); - if (!ctx || !text || !active) return 0; - old_value = *active; - *active = nk_option_text(ctx, text, len, old_value); - return old_value != *active; -} -NK_API int -nk_option_label(struct nk_context *ctx, const char *label, int active) -{ - return nk_option_text(ctx, label, nk_strlen(label), active); -} -NK_API int -nk_radio_label(struct nk_context *ctx, const char *label, int *active) -{ - return nk_radio_text(ctx, label, nk_strlen(label), active); -} - - - - - -/* =============================================================== - * - * SELECTABLE - * - * ===============================================================*/ -NK_LIB void -nk_draw_selectable(struct nk_command_buffer *out, - nk_flags state, const struct nk_style_selectable *style, int active, - const struct nk_rect *bounds, - const struct nk_rect *icon, const struct nk_image *img, enum nk_symbol_type sym, - const char *string, int len, nk_flags align, const struct nk_user_font *font) -{ - const struct nk_style_item *background; - struct nk_text text; - text.padding = style->padding; - - /* select correct colors/images */ - if (!active) { - if (state & NK_WIDGET_STATE_ACTIVED) { - background = &style->pressed; - text.text = style->text_pressed; - } else if (state & NK_WIDGET_STATE_HOVER) { - background = &style->hover; - text.text = style->text_hover; - } else { - background = &style->normal; - text.text = style->text_normal; - } - } else { - if (state & NK_WIDGET_STATE_ACTIVED) { - background = &style->pressed_active; - text.text = style->text_pressed_active; - } else if (state & NK_WIDGET_STATE_HOVER) { - background = &style->hover_active; - text.text = style->text_hover_active; - } else { - background = &style->normal_active; - text.text = style->text_normal_active; - } - } - /* draw selectable background and text */ - if (background->type == NK_STYLE_ITEM_IMAGE) { - nk_draw_image(out, *bounds, &background->data.image, nk_white); - text.background = nk_rgba(0,0,0,0); - } else { - nk_fill_rect(out, *bounds, style->rounding, background->data.color); - text.background = background->data.color; - } - if (icon) { - if (img) nk_draw_image(out, *icon, img, nk_white); - else nk_draw_symbol(out, sym, *icon, text.background, text.text, 1, font); - } - nk_widget_text(out, *bounds, string, len, &text, align, font); -} -NK_LIB int -nk_do_selectable(nk_flags *state, struct nk_command_buffer *out, - struct nk_rect bounds, const char *str, int len, nk_flags align, int *value, - const struct nk_style_selectable *style, const struct nk_input *in, - const struct nk_user_font *font) -{ - int old_value; - struct nk_rect touch; - - NK_ASSERT(state); - NK_ASSERT(out); - NK_ASSERT(str); - NK_ASSERT(len); - NK_ASSERT(value); - NK_ASSERT(style); - NK_ASSERT(font); - - if (!state || !out || !str || !len || !value || !style || !font) return 0; - old_value = *value; - - /* remove padding */ - touch.x = bounds.x - style->touch_padding.x; - touch.y = bounds.y - style->touch_padding.y; - touch.w = bounds.w + style->touch_padding.x * 2; - touch.h = bounds.h + style->touch_padding.y * 2; - - /* update button */ - if (nk_button_behavior(state, touch, in, NK_BUTTON_DEFAULT)) - *value = !(*value); - - /* draw selectable */ - if (style->draw_begin) style->draw_begin(out, style->userdata); - nk_draw_selectable(out, *state, style, *value, &bounds, 0,0,NK_SYMBOL_NONE, str, len, align, font); - if (style->draw_end) style->draw_end(out, style->userdata); - return old_value != *value; -} -NK_LIB int -nk_do_selectable_image(nk_flags *state, struct nk_command_buffer *out, - struct nk_rect bounds, const char *str, int len, nk_flags align, int *value, - const struct nk_image *img, const struct nk_style_selectable *style, - const struct nk_input *in, const struct nk_user_font *font) -{ - int old_value; - struct nk_rect touch; - struct nk_rect icon; - - NK_ASSERT(state); - NK_ASSERT(out); - NK_ASSERT(str); - NK_ASSERT(len); - NK_ASSERT(value); - NK_ASSERT(style); - NK_ASSERT(font); - - if (!state || !out || !str || !len || !value || !style || !font) return 0; - old_value = *value; - - /* toggle behavior */ - touch.x = bounds.x - style->touch_padding.x; - touch.y = bounds.y - style->touch_padding.y; - touch.w = bounds.w + style->touch_padding.x * 2; - touch.h = bounds.h + style->touch_padding.y * 2; - if (nk_button_behavior(state, touch, in, NK_BUTTON_DEFAULT)) - *value = !(*value); - - icon.y = bounds.y + style->padding.y; - icon.w = icon.h = bounds.h - 2 * style->padding.y; - if (align & NK_TEXT_ALIGN_LEFT) { - icon.x = (bounds.x + bounds.w) - (2 * style->padding.x + icon.w); - icon.x = NK_MAX(icon.x, 0); - } else icon.x = bounds.x + 2 * style->padding.x; - - icon.x += style->image_padding.x; - icon.y += style->image_padding.y; - icon.w -= 2 * style->image_padding.x; - icon.h -= 2 * style->image_padding.y; - - /* draw selectable */ - if (style->draw_begin) style->draw_begin(out, style->userdata); - nk_draw_selectable(out, *state, style, *value, &bounds, &icon, img, NK_SYMBOL_NONE, str, len, align, font); - if (style->draw_end) style->draw_end(out, style->userdata); - return old_value != *value; -} -NK_LIB int -nk_do_selectable_symbol(nk_flags *state, struct nk_command_buffer *out, - struct nk_rect bounds, const char *str, int len, nk_flags align, int *value, - enum nk_symbol_type sym, const struct nk_style_selectable *style, - const struct nk_input *in, const struct nk_user_font *font) -{ - int old_value; - struct nk_rect touch; - struct nk_rect icon; - - NK_ASSERT(state); - NK_ASSERT(out); - NK_ASSERT(str); - NK_ASSERT(len); - NK_ASSERT(value); - NK_ASSERT(style); - NK_ASSERT(font); - - if (!state || !out || !str || !len || !value || !style || !font) return 0; - old_value = *value; - - /* toggle behavior */ - touch.x = bounds.x - style->touch_padding.x; - touch.y = bounds.y - style->touch_padding.y; - touch.w = bounds.w + style->touch_padding.x * 2; - touch.h = bounds.h + style->touch_padding.y * 2; - if (nk_button_behavior(state, touch, in, NK_BUTTON_DEFAULT)) - *value = !(*value); - - icon.y = bounds.y + style->padding.y; - icon.w = icon.h = bounds.h - 2 * style->padding.y; - if (align & NK_TEXT_ALIGN_LEFT) { - icon.x = (bounds.x + bounds.w) - (2 * style->padding.x + icon.w); - icon.x = NK_MAX(icon.x, 0); - } else icon.x = bounds.x + 2 * style->padding.x; - - icon.x += style->image_padding.x; - icon.y += style->image_padding.y; - icon.w -= 2 * style->image_padding.x; - icon.h -= 2 * style->image_padding.y; - - /* draw selectable */ - if (style->draw_begin) style->draw_begin(out, style->userdata); - nk_draw_selectable(out, *state, style, *value, &bounds, &icon, 0, sym, str, len, align, font); - if (style->draw_end) style->draw_end(out, style->userdata); - return old_value != *value; -} - -NK_API int -nk_selectable_text(struct nk_context *ctx, const char *str, int len, - nk_flags align, int *value) -{ - struct nk_window *win; - struct nk_panel *layout; - const struct nk_input *in; - const struct nk_style *style; - - enum nk_widget_layout_states state; - struct nk_rect bounds; - - NK_ASSERT(ctx); - NK_ASSERT(value); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout || !value) - return 0; - - win = ctx->current; - layout = win->layout; - style = &ctx->style; - - state = nk_widget(&bounds, ctx); - if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; - return nk_do_selectable(&ctx->last_widget_state, &win->buffer, bounds, - str, len, align, value, &style->selectable, in, style->font); -} -NK_API int -nk_selectable_image_text(struct nk_context *ctx, struct nk_image img, - const char *str, int len, nk_flags align, int *value) -{ - struct nk_window *win; - struct nk_panel *layout; - const struct nk_input *in; - const struct nk_style *style; - - enum nk_widget_layout_states state; - struct nk_rect bounds; - - NK_ASSERT(ctx); - NK_ASSERT(value); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout || !value) - return 0; - - win = ctx->current; - layout = win->layout; - style = &ctx->style; - - state = nk_widget(&bounds, ctx); - if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; - return nk_do_selectable_image(&ctx->last_widget_state, &win->buffer, bounds, - str, len, align, value, &img, &style->selectable, in, style->font); -} -NK_API int -nk_selectable_symbol_text(struct nk_context *ctx, enum nk_symbol_type sym, - const char *str, int len, nk_flags align, int *value) -{ - struct nk_window *win; - struct nk_panel *layout; - const struct nk_input *in; - const struct nk_style *style; - - enum nk_widget_layout_states state; - struct nk_rect bounds; - - NK_ASSERT(ctx); - NK_ASSERT(value); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout || !value) - return 0; - - win = ctx->current; - layout = win->layout; - style = &ctx->style; - - state = nk_widget(&bounds, ctx); - if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; - return nk_do_selectable_symbol(&ctx->last_widget_state, &win->buffer, bounds, - str, len, align, value, sym, &style->selectable, in, style->font); -} -NK_API int -nk_selectable_symbol_label(struct nk_context *ctx, enum nk_symbol_type sym, - const char *title, nk_flags align, int *value) -{ - return nk_selectable_symbol_text(ctx, sym, title, nk_strlen(title), align, value); -} -NK_API int nk_select_text(struct nk_context *ctx, const char *str, int len, - nk_flags align, int value) -{ - nk_selectable_text(ctx, str, len, align, &value);return value; -} -NK_API int nk_selectable_label(struct nk_context *ctx, const char *str, nk_flags align, int *value) -{ - return nk_selectable_text(ctx, str, nk_strlen(str), align, value); -} -NK_API int nk_selectable_image_label(struct nk_context *ctx,struct nk_image img, - const char *str, nk_flags align, int *value) -{ - return nk_selectable_image_text(ctx, img, str, nk_strlen(str), align, value); -} -NK_API int nk_select_label(struct nk_context *ctx, const char *str, nk_flags align, int value) -{ - nk_selectable_text(ctx, str, nk_strlen(str), align, &value);return value; -} -NK_API int nk_select_image_label(struct nk_context *ctx, struct nk_image img, - const char *str, nk_flags align, int value) -{ - nk_selectable_image_text(ctx, img, str, nk_strlen(str), align, &value);return value; -} -NK_API int nk_select_image_text(struct nk_context *ctx, struct nk_image img, - const char *str, int len, nk_flags align, int value) -{ - nk_selectable_image_text(ctx, img, str, len, align, &value);return value; -} -NK_API int -nk_select_symbol_text(struct nk_context *ctx, enum nk_symbol_type sym, - const char *title, int title_len, nk_flags align, int value) -{ - nk_selectable_symbol_text(ctx, sym, title, title_len, align, &value);return value; -} -NK_API int -nk_select_symbol_label(struct nk_context *ctx, enum nk_symbol_type sym, - const char *title, nk_flags align, int value) -{ - return nk_select_symbol_text(ctx, sym, title, nk_strlen(title), align, value); -} - - - - - -/* =============================================================== - * - * SLIDER - * - * ===============================================================*/ -NK_LIB float -nk_slider_behavior(nk_flags *state, struct nk_rect *logical_cursor, - struct nk_rect *visual_cursor, struct nk_input *in, - struct nk_rect bounds, float slider_min, float slider_max, float slider_value, - float slider_step, float slider_steps) -{ - int left_mouse_down; - int left_mouse_click_in_cursor; - - /* check if visual cursor is being dragged */ - nk_widget_state_reset(state); - left_mouse_down = in && in->mouse.buttons[NK_BUTTON_LEFT].down; - left_mouse_click_in_cursor = in && nk_input_has_mouse_click_down_in_rect(in, - NK_BUTTON_LEFT, *visual_cursor, nk_true); - - if (left_mouse_down && left_mouse_click_in_cursor) { - float ratio = 0; - const float d = in->mouse.pos.x - (visual_cursor->x+visual_cursor->w*0.5f); - const float pxstep = bounds.w / slider_steps; - - /* only update value if the next slider step is reached */ - *state = NK_WIDGET_STATE_ACTIVE; - if (NK_ABS(d) >= pxstep) { - const float steps = (float)((int)(NK_ABS(d) / pxstep)); - slider_value += (d > 0) ? (slider_step*steps) : -(slider_step*steps); - slider_value = NK_CLAMP(slider_min, slider_value, slider_max); - ratio = (slider_value - slider_min)/slider_step; - logical_cursor->x = bounds.x + (logical_cursor->w * ratio); - in->mouse.buttons[NK_BUTTON_LEFT].clicked_pos.x = logical_cursor->x; - } - } - - /* slider widget state */ - if (nk_input_is_mouse_hovering_rect(in, bounds)) - *state = NK_WIDGET_STATE_HOVERED; - if (*state & NK_WIDGET_STATE_HOVER && - !nk_input_is_mouse_prev_hovering_rect(in, bounds)) - *state |= NK_WIDGET_STATE_ENTERED; - else if (nk_input_is_mouse_prev_hovering_rect(in, bounds)) - *state |= NK_WIDGET_STATE_LEFT; - return slider_value; -} -NK_LIB void -nk_draw_slider(struct nk_command_buffer *out, nk_flags state, - const struct nk_style_slider *style, const struct nk_rect *bounds, - const struct nk_rect *visual_cursor, float min, float value, float max) -{ - struct nk_rect fill; - struct nk_rect bar; - const struct nk_style_item *background; - - /* select correct slider images/colors */ - struct nk_color bar_color; - const struct nk_style_item *cursor; - - NK_UNUSED(min); - NK_UNUSED(max); - NK_UNUSED(value); - - if (state & NK_WIDGET_STATE_ACTIVED) { - background = &style->active; - bar_color = style->bar_active; - cursor = &style->cursor_active; - } else if (state & NK_WIDGET_STATE_HOVER) { - background = &style->hover; - bar_color = style->bar_hover; - cursor = &style->cursor_hover; - } else { - background = &style->normal; - bar_color = style->bar_normal; - cursor = &style->cursor_normal; - } - /* calculate slider background bar */ - bar.x = bounds->x; - bar.y = (visual_cursor->y + visual_cursor->h/2) - bounds->h/12; - bar.w = bounds->w; - bar.h = bounds->h/6; - - /* filled background bar style */ - fill.w = (visual_cursor->x + (visual_cursor->w/2.0f)) - bar.x; - fill.x = bar.x; - fill.y = bar.y; - fill.h = bar.h; - - /* draw background */ - if (background->type == NK_STYLE_ITEM_IMAGE) { - nk_draw_image(out, *bounds, &background->data.image, nk_white); - } else { - nk_fill_rect(out, *bounds, style->rounding, background->data.color); - nk_stroke_rect(out, *bounds, style->rounding, style->border, style->border_color); - } - - /* draw slider bar */ - nk_fill_rect(out, bar, style->rounding, bar_color); - nk_fill_rect(out, fill, style->rounding, style->bar_filled); - - /* draw cursor */ - if (cursor->type == NK_STYLE_ITEM_IMAGE) - nk_draw_image(out, *visual_cursor, &cursor->data.image, nk_white); - else nk_fill_circle(out, *visual_cursor, cursor->data.color); -} -NK_LIB float -nk_do_slider(nk_flags *state, - struct nk_command_buffer *out, struct nk_rect bounds, - float min, float val, float max, float step, - const struct nk_style_slider *style, struct nk_input *in, - const struct nk_user_font *font) -{ - float slider_range; - float slider_min; - float slider_max; - float slider_value; - float slider_steps; - float cursor_offset; - - struct nk_rect visual_cursor; - struct nk_rect logical_cursor; - - NK_ASSERT(style); - NK_ASSERT(out); - if (!out || !style) - return 0; - - /* remove padding from slider bounds */ - bounds.x = bounds.x + style->padding.x; - bounds.y = bounds.y + style->padding.y; - bounds.h = NK_MAX(bounds.h, 2*style->padding.y); - bounds.w = NK_MAX(bounds.w, 2*style->padding.x + style->cursor_size.x); - bounds.w -= 2 * style->padding.x; - bounds.h -= 2 * style->padding.y; - - /* optional buttons */ - if (style->show_buttons) { - nk_flags ws; - struct nk_rect button; - button.y = bounds.y; - button.w = bounds.h; - button.h = bounds.h; - - /* decrement button */ - button.x = bounds.x; - if (nk_do_button_symbol(&ws, out, button, style->dec_symbol, NK_BUTTON_DEFAULT, - &style->dec_button, in, font)) - val -= step; - - /* increment button */ - button.x = (bounds.x + bounds.w) - button.w; - if (nk_do_button_symbol(&ws, out, button, style->inc_symbol, NK_BUTTON_DEFAULT, - &style->inc_button, in, font)) - val += step; - - bounds.x = bounds.x + button.w + style->spacing.x; - bounds.w = bounds.w - (2*button.w + 2*style->spacing.x); - } - - /* remove one cursor size to support visual cursor */ - bounds.x += style->cursor_size.x*0.5f; - bounds.w -= style->cursor_size.x; - - /* make sure the provided values are correct */ - slider_max = NK_MAX(min, max); - slider_min = NK_MIN(min, max); - slider_value = NK_CLAMP(slider_min, val, slider_max); - slider_range = slider_max - slider_min; - slider_steps = slider_range / step; - cursor_offset = (slider_value - slider_min) / step; - - /* calculate cursor - Basically you have two cursors. One for visual representation and interaction - and one for updating the actual cursor value. */ - logical_cursor.h = bounds.h; - logical_cursor.w = bounds.w / slider_steps; - logical_cursor.x = bounds.x + (logical_cursor.w * cursor_offset); - logical_cursor.y = bounds.y; - - visual_cursor.h = style->cursor_size.y; - visual_cursor.w = style->cursor_size.x; - visual_cursor.y = (bounds.y + bounds.h*0.5f) - visual_cursor.h*0.5f; - visual_cursor.x = logical_cursor.x - visual_cursor.w*0.5f; - - slider_value = nk_slider_behavior(state, &logical_cursor, &visual_cursor, - in, bounds, slider_min, slider_max, slider_value, step, slider_steps); - visual_cursor.x = logical_cursor.x - visual_cursor.w*0.5f; - - /* draw slider */ - if (style->draw_begin) style->draw_begin(out, style->userdata); - nk_draw_slider(out, *state, style, &bounds, &visual_cursor, slider_min, slider_value, slider_max); - if (style->draw_end) style->draw_end(out, style->userdata); - return slider_value; -} -NK_API int -nk_slider_float(struct nk_context *ctx, float min_value, float *value, float max_value, - float value_step) -{ - struct nk_window *win; - struct nk_panel *layout; - struct nk_input *in; - const struct nk_style *style; - - int ret = 0; - float old_value; - struct nk_rect bounds; - enum nk_widget_layout_states state; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - NK_ASSERT(value); - if (!ctx || !ctx->current || !ctx->current->layout || !value) - return ret; - - win = ctx->current; - style = &ctx->style; - layout = win->layout; - - state = nk_widget(&bounds, ctx); - if (!state) return ret; - in = (/*state == NK_WIDGET_ROM || */ layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; - - old_value = *value; - *value = nk_do_slider(&ctx->last_widget_state, &win->buffer, bounds, min_value, - old_value, max_value, value_step, &style->slider, in, style->font); - return (old_value > *value || old_value < *value); -} -NK_API float -nk_slide_float(struct nk_context *ctx, float min, float val, float max, float step) -{ - nk_slider_float(ctx, min, &val, max, step); return val; -} -NK_API int -nk_slide_int(struct nk_context *ctx, int min, int val, int max, int step) -{ - float value = (float)val; - nk_slider_float(ctx, (float)min, &value, (float)max, (float)step); - return (int)value; -} -NK_API int -nk_slider_int(struct nk_context *ctx, int min, int *val, int max, int step) -{ - int ret; - float value = (float)*val; - ret = nk_slider_float(ctx, (float)min, &value, (float)max, (float)step); - *val = (int)value; - return ret; -} - - - - - -/* =============================================================== - * - * PROGRESS - * - * ===============================================================*/ -NK_LIB nk_size -nk_progress_behavior(nk_flags *state, struct nk_input *in, - struct nk_rect r, struct nk_rect cursor, nk_size max, nk_size value, int modifiable) -{ - int left_mouse_down = 0; - int left_mouse_click_in_cursor = 0; - - nk_widget_state_reset(state); - if (!in || !modifiable) return value; - left_mouse_down = in && in->mouse.buttons[NK_BUTTON_LEFT].down; - left_mouse_click_in_cursor = in && nk_input_has_mouse_click_down_in_rect(in, - NK_BUTTON_LEFT, cursor, nk_true); - if (nk_input_is_mouse_hovering_rect(in, r)) - *state = NK_WIDGET_STATE_HOVERED; - - if (in && left_mouse_down && left_mouse_click_in_cursor) { - if (left_mouse_down && left_mouse_click_in_cursor) { - float ratio = NK_MAX(0, (float)(in->mouse.pos.x - cursor.x)) / (float)cursor.w; - value = (nk_size)NK_CLAMP(0, (float)max * ratio, (float)max); - in->mouse.buttons[NK_BUTTON_LEFT].clicked_pos.x = cursor.x + cursor.w/2.0f; - *state |= NK_WIDGET_STATE_ACTIVE; - } - } - /* set progressbar widget state */ - if (*state & NK_WIDGET_STATE_HOVER && !nk_input_is_mouse_prev_hovering_rect(in, r)) - *state |= NK_WIDGET_STATE_ENTERED; - else if (nk_input_is_mouse_prev_hovering_rect(in, r)) - *state |= NK_WIDGET_STATE_LEFT; - return value; -} -NK_LIB void -nk_draw_progress(struct nk_command_buffer *out, nk_flags state, - const struct nk_style_progress *style, const struct nk_rect *bounds, - const struct nk_rect *scursor, nk_size value, nk_size max) -{ - const struct nk_style_item *background; - const struct nk_style_item *cursor; - - NK_UNUSED(max); - NK_UNUSED(value); - - /* select correct colors/images to draw */ - if (state & NK_WIDGET_STATE_ACTIVED) { - background = &style->active; - cursor = &style->cursor_active; - } else if (state & NK_WIDGET_STATE_HOVER){ - background = &style->hover; - cursor = &style->cursor_hover; - } else { - background = &style->normal; - cursor = &style->cursor_normal; - } - - /* draw background */ - if (background->type == NK_STYLE_ITEM_COLOR) { - nk_fill_rect(out, *bounds, style->rounding, background->data.color); - nk_stroke_rect(out, *bounds, style->rounding, style->border, style->border_color); - } else nk_draw_image(out, *bounds, &background->data.image, nk_white); - - /* draw cursor */ - if (cursor->type == NK_STYLE_ITEM_COLOR) { - nk_fill_rect(out, *scursor, style->rounding, cursor->data.color); - nk_stroke_rect(out, *scursor, style->rounding, style->border, style->border_color); - } else nk_draw_image(out, *scursor, &cursor->data.image, nk_white); -} -NK_LIB nk_size -nk_do_progress(nk_flags *state, - struct nk_command_buffer *out, struct nk_rect bounds, - nk_size value, nk_size max, int modifiable, - const struct nk_style_progress *style, struct nk_input *in) -{ - float prog_scale; - nk_size prog_value; - struct nk_rect cursor; - - NK_ASSERT(style); - NK_ASSERT(out); - if (!out || !style) return 0; - - /* calculate progressbar cursor */ - cursor.w = NK_MAX(bounds.w, 2 * style->padding.x + 2 * style->border); - cursor.h = NK_MAX(bounds.h, 2 * style->padding.y + 2 * style->border); - cursor = nk_pad_rect(bounds, nk_vec2(style->padding.x + style->border, style->padding.y + style->border)); - prog_scale = (float)value / (float)max; - - /* update progressbar */ - prog_value = NK_MIN(value, max); - prog_value = nk_progress_behavior(state, in, bounds, cursor,max, prog_value, modifiable); - cursor.w = cursor.w * prog_scale; - - /* draw progressbar */ - if (style->draw_begin) style->draw_begin(out, style->userdata); - nk_draw_progress(out, *state, style, &bounds, &cursor, value, max); - if (style->draw_end) style->draw_end(out, style->userdata); - return prog_value; -} -NK_API int -nk_progress(struct nk_context *ctx, nk_size *cur, nk_size max, int is_modifyable) -{ - struct nk_window *win; - struct nk_panel *layout; - const struct nk_style *style; - struct nk_input *in; - - struct nk_rect bounds; - enum nk_widget_layout_states state; - nk_size old_value; - - NK_ASSERT(ctx); - NK_ASSERT(cur); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout || !cur) - return 0; - - win = ctx->current; - style = &ctx->style; - layout = win->layout; - state = nk_widget(&bounds, ctx); - if (!state) return 0; - - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; - old_value = *cur; - *cur = nk_do_progress(&ctx->last_widget_state, &win->buffer, bounds, - *cur, max, is_modifyable, &style->progress, in); - return (*cur != old_value); -} -NK_API nk_size -nk_prog(struct nk_context *ctx, nk_size cur, nk_size max, int modifyable) -{ - nk_progress(ctx, &cur, max, modifyable); - return cur; -} - - - - - -/* =============================================================== - * - * SCROLLBAR - * - * ===============================================================*/ -NK_LIB float -nk_scrollbar_behavior(nk_flags *state, struct nk_input *in, - int has_scrolling, const struct nk_rect *scroll, - const struct nk_rect *cursor, const struct nk_rect *empty0, - const struct nk_rect *empty1, float scroll_offset, - float target, float scroll_step, enum nk_orientation o) -{ - nk_flags ws = 0; - int left_mouse_down; - int left_mouse_click_in_cursor; - float scroll_delta; - - nk_widget_state_reset(state); - if (!in) return scroll_offset; - - left_mouse_down = in->mouse.buttons[NK_BUTTON_LEFT].down; - left_mouse_click_in_cursor = nk_input_has_mouse_click_down_in_rect(in, - NK_BUTTON_LEFT, *cursor, nk_true); - if (nk_input_is_mouse_hovering_rect(in, *scroll)) - *state = NK_WIDGET_STATE_HOVERED; - - scroll_delta = (o == NK_VERTICAL) ? in->mouse.scroll_delta.y: in->mouse.scroll_delta.x; - if (left_mouse_down && left_mouse_click_in_cursor) { - /* update cursor by mouse dragging */ - float pixel, delta; - *state = NK_WIDGET_STATE_ACTIVE; - if (o == NK_VERTICAL) { - float cursor_y; - pixel = in->mouse.delta.y; - delta = (pixel / scroll->h) * target; - scroll_offset = NK_CLAMP(0, scroll_offset + delta, target - scroll->h); - cursor_y = scroll->y + ((scroll_offset/target) * scroll->h); - in->mouse.buttons[NK_BUTTON_LEFT].clicked_pos.y = cursor_y + cursor->h/2.0f; - } else { - float cursor_x; - pixel = in->mouse.delta.x; - delta = (pixel / scroll->w) * target; - scroll_offset = NK_CLAMP(0, scroll_offset + delta, target - scroll->w); - cursor_x = scroll->x + ((scroll_offset/target) * scroll->w); - in->mouse.buttons[NK_BUTTON_LEFT].clicked_pos.x = cursor_x + cursor->w/2.0f; - } - } else if ((nk_input_is_key_pressed(in, NK_KEY_SCROLL_UP) && o == NK_VERTICAL && has_scrolling)|| - nk_button_behavior(&ws, *empty0, in, NK_BUTTON_DEFAULT)) { - /* scroll page up by click on empty space or shortcut */ - if (o == NK_VERTICAL) - scroll_offset = NK_MAX(0, scroll_offset - scroll->h); - else scroll_offset = NK_MAX(0, scroll_offset - scroll->w); - } else if ((nk_input_is_key_pressed(in, NK_KEY_SCROLL_DOWN) && o == NK_VERTICAL && has_scrolling) || - nk_button_behavior(&ws, *empty1, in, NK_BUTTON_DEFAULT)) { - /* scroll page down by click on empty space or shortcut */ - if (o == NK_VERTICAL) - scroll_offset = NK_MIN(scroll_offset + scroll->h, target - scroll->h); - else scroll_offset = NK_MIN(scroll_offset + scroll->w, target - scroll->w); - } else if (has_scrolling) { - if ((scroll_delta < 0 || (scroll_delta > 0))) { - /* update cursor by mouse scrolling */ - scroll_offset = scroll_offset + scroll_step * (-scroll_delta); - if (o == NK_VERTICAL) - scroll_offset = NK_CLAMP(0, scroll_offset, target - scroll->h); - else scroll_offset = NK_CLAMP(0, scroll_offset, target - scroll->w); - } else if (nk_input_is_key_pressed(in, NK_KEY_SCROLL_START)) { - /* update cursor to the beginning */ - if (o == NK_VERTICAL) scroll_offset = 0; - } else if (nk_input_is_key_pressed(in, NK_KEY_SCROLL_END)) { - /* update cursor to the end */ - if (o == NK_VERTICAL) scroll_offset = target - scroll->h; - } - } - if (*state & NK_WIDGET_STATE_HOVER && !nk_input_is_mouse_prev_hovering_rect(in, *scroll)) - *state |= NK_WIDGET_STATE_ENTERED; - else if (nk_input_is_mouse_prev_hovering_rect(in, *scroll)) - *state |= NK_WIDGET_STATE_LEFT; - return scroll_offset; -} -NK_LIB void -nk_draw_scrollbar(struct nk_command_buffer *out, nk_flags state, - const struct nk_style_scrollbar *style, const struct nk_rect *bounds, - const struct nk_rect *scroll) -{ - const struct nk_style_item *background; - const struct nk_style_item *cursor; - - /* select correct colors/images to draw */ - if (state & NK_WIDGET_STATE_ACTIVED) { - background = &style->active; - cursor = &style->cursor_active; - } else if (state & NK_WIDGET_STATE_HOVER) { - background = &style->hover; - cursor = &style->cursor_hover; - } else { - background = &style->normal; - cursor = &style->cursor_normal; - } - - /* draw background */ - if (background->type == NK_STYLE_ITEM_COLOR) { - nk_fill_rect(out, *bounds, style->rounding, background->data.color); - nk_stroke_rect(out, *bounds, style->rounding, style->border, style->border_color); - } else { - nk_draw_image(out, *bounds, &background->data.image, nk_white); - } - - /* draw cursor */ - if (cursor->type == NK_STYLE_ITEM_COLOR) { - nk_fill_rect(out, *scroll, style->rounding_cursor, cursor->data.color); - nk_stroke_rect(out, *scroll, style->rounding_cursor, style->border_cursor, style->cursor_border_color); - } else nk_draw_image(out, *scroll, &cursor->data.image, nk_white); -} -NK_LIB float -nk_do_scrollbarv(nk_flags *state, - struct nk_command_buffer *out, struct nk_rect scroll, int has_scrolling, - float offset, float target, float step, float button_pixel_inc, - const struct nk_style_scrollbar *style, struct nk_input *in, - const struct nk_user_font *font) -{ - struct nk_rect empty_north; - struct nk_rect empty_south; - struct nk_rect cursor; - - float scroll_step; - float scroll_offset; - float scroll_off; - float scroll_ratio; - - NK_ASSERT(out); - NK_ASSERT(style); - NK_ASSERT(state); - if (!out || !style) return 0; - - scroll.w = NK_MAX(scroll.w, 1); - scroll.h = NK_MAX(scroll.h, 0); - if (target <= scroll.h) return 0; - - /* optional scrollbar buttons */ - if (style->show_buttons) { - nk_flags ws; - float scroll_h; - struct nk_rect button; - - button.x = scroll.x; - button.w = scroll.w; - button.h = scroll.w; - - scroll_h = NK_MAX(scroll.h - 2 * button.h,0); - scroll_step = NK_MIN(step, button_pixel_inc); - - /* decrement button */ - button.y = scroll.y; - if (nk_do_button_symbol(&ws, out, button, style->dec_symbol, - NK_BUTTON_REPEATER, &style->dec_button, in, font)) - offset = offset - scroll_step; - - /* increment button */ - button.y = scroll.y + scroll.h - button.h; - if (nk_do_button_symbol(&ws, out, button, style->inc_symbol, - NK_BUTTON_REPEATER, &style->inc_button, in, font)) - offset = offset + scroll_step; - - scroll.y = scroll.y + button.h; - scroll.h = scroll_h; - } - - /* calculate scrollbar constants */ - scroll_step = NK_MIN(step, scroll.h); - scroll_offset = NK_CLAMP(0, offset, target - scroll.h); - scroll_ratio = scroll.h / target; - scroll_off = scroll_offset / target; - - /* calculate scrollbar cursor bounds */ - cursor.h = NK_MAX((scroll_ratio * scroll.h) - (2*style->border + 2*style->padding.y), 0); - cursor.y = scroll.y + (scroll_off * scroll.h) + style->border + style->padding.y; - cursor.w = scroll.w - (2 * style->border + 2 * style->padding.x); - cursor.x = scroll.x + style->border + style->padding.x; - - /* calculate empty space around cursor */ - empty_north.x = scroll.x; - empty_north.y = scroll.y; - empty_north.w = scroll.w; - empty_north.h = NK_MAX(cursor.y - scroll.y, 0); - - empty_south.x = scroll.x; - empty_south.y = cursor.y + cursor.h; - empty_south.w = scroll.w; - empty_south.h = NK_MAX((scroll.y + scroll.h) - (cursor.y + cursor.h), 0); - - /* update scrollbar */ - scroll_offset = nk_scrollbar_behavior(state, in, has_scrolling, &scroll, &cursor, - &empty_north, &empty_south, scroll_offset, target, scroll_step, NK_VERTICAL); - scroll_off = scroll_offset / target; - cursor.y = scroll.y + (scroll_off * scroll.h) + style->border_cursor + style->padding.y; - - /* draw scrollbar */ - if (style->draw_begin) style->draw_begin(out, style->userdata); - nk_draw_scrollbar(out, *state, style, &scroll, &cursor); - if (style->draw_end) style->draw_end(out, style->userdata); - return scroll_offset; -} -NK_LIB float -nk_do_scrollbarh(nk_flags *state, - struct nk_command_buffer *out, struct nk_rect scroll, int has_scrolling, - float offset, float target, float step, float button_pixel_inc, - const struct nk_style_scrollbar *style, struct nk_input *in, - const struct nk_user_font *font) -{ - struct nk_rect cursor; - struct nk_rect empty_west; - struct nk_rect empty_east; - - float scroll_step; - float scroll_offset; - float scroll_off; - float scroll_ratio; - - NK_ASSERT(out); - NK_ASSERT(style); - if (!out || !style) return 0; - - /* scrollbar background */ - scroll.h = NK_MAX(scroll.h, 1); - scroll.w = NK_MAX(scroll.w, 2 * scroll.h); - if (target <= scroll.w) return 0; - - /* optional scrollbar buttons */ - if (style->show_buttons) { - nk_flags ws; - float scroll_w; - struct nk_rect button; - button.y = scroll.y; - button.w = scroll.h; - button.h = scroll.h; - - scroll_w = scroll.w - 2 * button.w; - scroll_step = NK_MIN(step, button_pixel_inc); - - /* decrement button */ - button.x = scroll.x; - if (nk_do_button_symbol(&ws, out, button, style->dec_symbol, - NK_BUTTON_REPEATER, &style->dec_button, in, font)) - offset = offset - scroll_step; - - /* increment button */ - button.x = scroll.x + scroll.w - button.w; - if (nk_do_button_symbol(&ws, out, button, style->inc_symbol, - NK_BUTTON_REPEATER, &style->inc_button, in, font)) - offset = offset + scroll_step; - - scroll.x = scroll.x + button.w; - scroll.w = scroll_w; - } - - /* calculate scrollbar constants */ - scroll_step = NK_MIN(step, scroll.w); - scroll_offset = NK_CLAMP(0, offset, target - scroll.w); - scroll_ratio = scroll.w / target; - scroll_off = scroll_offset / target; - - /* calculate cursor bounds */ - cursor.w = (scroll_ratio * scroll.w) - (2*style->border + 2*style->padding.x); - cursor.x = scroll.x + (scroll_off * scroll.w) + style->border + style->padding.x; - cursor.h = scroll.h - (2 * style->border + 2 * style->padding.y); - cursor.y = scroll.y + style->border + style->padding.y; - - /* calculate empty space around cursor */ - empty_west.x = scroll.x; - empty_west.y = scroll.y; - empty_west.w = cursor.x - scroll.x; - empty_west.h = scroll.h; - - empty_east.x = cursor.x + cursor.w; - empty_east.y = scroll.y; - empty_east.w = (scroll.x + scroll.w) - (cursor.x + cursor.w); - empty_east.h = scroll.h; - - /* update scrollbar */ - scroll_offset = nk_scrollbar_behavior(state, in, has_scrolling, &scroll, &cursor, - &empty_west, &empty_east, scroll_offset, target, scroll_step, NK_HORIZONTAL); - scroll_off = scroll_offset / target; - cursor.x = scroll.x + (scroll_off * scroll.w); - - /* draw scrollbar */ - if (style->draw_begin) style->draw_begin(out, style->userdata); - nk_draw_scrollbar(out, *state, style, &scroll, &cursor); - if (style->draw_end) style->draw_end(out, style->userdata); - return scroll_offset; -} - - - - - -/* =============================================================== - * - * TEXT EDITOR - * - * ===============================================================*/ -/* stb_textedit.h - v1.8 - public domain - Sean Barrett */ -struct nk_text_find { - float x,y; /* position of n'th character */ - float height; /* height of line */ - int first_char, length; /* first char of row, and length */ - int prev_first; /*_ first char of previous row */ -}; - -struct nk_text_edit_row { - float x0,x1; - /* starting x location, end x location (allows for align=right, etc) */ - float baseline_y_delta; - /* position of baseline relative to previous row's baseline*/ - float ymin,ymax; - /* height of row above and below baseline */ - int num_chars; -}; - -/* forward declarations */ -NK_INTERN void nk_textedit_makeundo_delete(struct nk_text_edit*, int, int); -NK_INTERN void nk_textedit_makeundo_insert(struct nk_text_edit*, int, int); -NK_INTERN void nk_textedit_makeundo_replace(struct nk_text_edit*, int, int, int); -#define NK_TEXT_HAS_SELECTION(s) ((s)->select_start != (s)->select_end) - -NK_INTERN float -nk_textedit_get_width(const struct nk_text_edit *edit, int line_start, int char_id, - const struct nk_user_font *font) -{ - int len = 0; - nk_rune unicode = 0; - const char *str = nk_str_at_const(&edit->string, line_start + char_id, &unicode, &len); - return font->width(font->userdata, font->height, str, len); -} -NK_INTERN void -nk_textedit_layout_row(struct nk_text_edit_row *r, struct nk_text_edit *edit, - int line_start_id, float row_height, const struct nk_user_font *font) -{ - int l; - int glyphs = 0; - nk_rune unicode; - const char *remaining; - int len = nk_str_len_char(&edit->string); - const char *end = nk_str_get_const(&edit->string) + len; - const char *text = nk_str_at_const(&edit->string, line_start_id, &unicode, &l); - const struct nk_vec2 size = nk_text_calculate_text_bounds(font, - text, (int)(end - text), row_height, &remaining, 0, &glyphs, NK_STOP_ON_NEW_LINE); - - r->x0 = 0.0f; - r->x1 = size.x; - r->baseline_y_delta = size.y; - r->ymin = 0.0f; - r->ymax = size.y; - r->num_chars = glyphs; -} -NK_INTERN int -nk_textedit_locate_coord(struct nk_text_edit *edit, float x, float y, - const struct nk_user_font *font, float row_height) -{ - struct nk_text_edit_row r; - int n = edit->string.len; - float base_y = 0, prev_x; - int i=0, k; - - r.x0 = r.x1 = 0; - r.ymin = r.ymax = 0; - r.num_chars = 0; - - /* search rows to find one that straddles 'y' */ - while (i < n) { - nk_textedit_layout_row(&r, edit, i, row_height, font); - if (r.num_chars <= 0) - return n; - - if (i==0 && y < base_y + r.ymin) - return 0; - - if (y < base_y + r.ymax) - break; - - i += r.num_chars; - base_y += r.baseline_y_delta; - } - - /* below all text, return 'after' last character */ - if (i >= n) - return n; - - /* check if it's before the beginning of the line */ - if (x < r.x0) - return i; - - /* check if it's before the end of the line */ - if (x < r.x1) { - /* search characters in row for one that straddles 'x' */ - k = i; - prev_x = r.x0; - for (i=0; i < r.num_chars; ++i) { - float w = nk_textedit_get_width(edit, k, i, font); - if (x < prev_x+w) { - if (x < prev_x+w/2) - return k+i; - else return k+i+1; - } - prev_x += w; - } - /* shouldn't happen, but if it does, fall through to end-of-line case */ - } - - /* if the last character is a newline, return that. - * otherwise return 'after' the last character */ - if (nk_str_rune_at(&edit->string, i+r.num_chars-1) == '\n') - return i+r.num_chars-1; - else return i+r.num_chars; -} -NK_LIB void -nk_textedit_click(struct nk_text_edit *state, float x, float y, - const struct nk_user_font *font, float row_height) -{ - /* API click: on mouse down, move the cursor to the clicked location, - * and reset the selection */ - state->cursor = nk_textedit_locate_coord(state, x, y, font, row_height); - state->select_start = state->cursor; - state->select_end = state->cursor; - state->has_preferred_x = 0; -} -NK_LIB void -nk_textedit_drag(struct nk_text_edit *state, float x, float y, - const struct nk_user_font *font, float row_height) -{ - /* API drag: on mouse drag, move the cursor and selection endpoint - * to the clicked location */ - int p = nk_textedit_locate_coord(state, x, y, font, row_height); - if (state->select_start == state->select_end) - state->select_start = state->cursor; - state->cursor = state->select_end = p; -} -NK_INTERN void -nk_textedit_find_charpos(struct nk_text_find *find, struct nk_text_edit *state, - int n, int single_line, const struct nk_user_font *font, float row_height) -{ - /* find the x/y location of a character, and remember info about the previous - * row in case we get a move-up event (for page up, we'll have to rescan) */ - struct nk_text_edit_row r; - int prev_start = 0; - int z = state->string.len; - int i=0, first; - - nk_zero_struct(r); - if (n == z) { - /* if it's at the end, then find the last line -- simpler than trying to - explicitly handle this case in the regular code */ - nk_textedit_layout_row(&r, state, 0, row_height, font); - if (single_line) { - find->first_char = 0; - find->length = z; - } else { - while (i < z) { - prev_start = i; - i += r.num_chars; - nk_textedit_layout_row(&r, state, i, row_height, font); - } - - find->first_char = i; - find->length = r.num_chars; - } - find->x = r.x1; - find->y = r.ymin; - find->height = r.ymax - r.ymin; - find->prev_first = prev_start; - return; - } - - /* search rows to find the one that straddles character n */ - find->y = 0; - - for(;;) { - nk_textedit_layout_row(&r, state, i, row_height, font); - if (n < i + r.num_chars) break; - prev_start = i; - i += r.num_chars; - find->y += r.baseline_y_delta; - } - - find->first_char = first = i; - find->length = r.num_chars; - find->height = r.ymax - r.ymin; - find->prev_first = prev_start; - - /* now scan to find xpos */ - find->x = r.x0; - for (i=0; first+i < n; ++i) - find->x += nk_textedit_get_width(state, first, i, font); -} -NK_INTERN void -nk_textedit_clamp(struct nk_text_edit *state) -{ - /* make the selection/cursor state valid if client altered the string */ - int n = state->string.len; - if (NK_TEXT_HAS_SELECTION(state)) { - if (state->select_start > n) state->select_start = n; - if (state->select_end > n) state->select_end = n; - /* if clamping forced them to be equal, move the cursor to match */ - if (state->select_start == state->select_end) - state->cursor = state->select_start; - } - if (state->cursor > n) state->cursor = n; -} -NK_API void -nk_textedit_delete(struct nk_text_edit *state, int where, int len) -{ - /* delete characters while updating undo */ - nk_textedit_makeundo_delete(state, where, len); - nk_str_delete_runes(&state->string, where, len); - state->has_preferred_x = 0; -} -NK_API void -nk_textedit_delete_selection(struct nk_text_edit *state) -{ - /* delete the section */ - nk_textedit_clamp(state); - if (NK_TEXT_HAS_SELECTION(state)) { - if (state->select_start < state->select_end) { - nk_textedit_delete(state, state->select_start, - state->select_end - state->select_start); - state->select_end = state->cursor = state->select_start; - } else { - nk_textedit_delete(state, state->select_end, - state->select_start - state->select_end); - state->select_start = state->cursor = state->select_end; - } - state->has_preferred_x = 0; - } -} -NK_INTERN void -nk_textedit_sortselection(struct nk_text_edit *state) -{ - /* canonicalize the selection so start <= end */ - if (state->select_end < state->select_start) { - int temp = state->select_end; - state->select_end = state->select_start; - state->select_start = temp; - } -} -NK_INTERN void -nk_textedit_move_to_first(struct nk_text_edit *state) -{ - /* move cursor to first character of selection */ - if (NK_TEXT_HAS_SELECTION(state)) { - nk_textedit_sortselection(state); - state->cursor = state->select_start; - state->select_end = state->select_start; - state->has_preferred_x = 0; - } -} -NK_INTERN void -nk_textedit_move_to_last(struct nk_text_edit *state) -{ - /* move cursor to last character of selection */ - if (NK_TEXT_HAS_SELECTION(state)) { - nk_textedit_sortselection(state); - nk_textedit_clamp(state); - state->cursor = state->select_end; - state->select_start = state->select_end; - state->has_preferred_x = 0; - } -} -NK_INTERN int -nk_is_word_boundary( struct nk_text_edit *state, int idx) -{ - int len; - nk_rune c; - if (idx <= 0) return 1; - if (!nk_str_at_rune(&state->string, idx, &c, &len)) return 1; - return (c == ' ' || c == '\t' ||c == 0x3000 || c == ',' || c == ';' || - c == '(' || c == ')' || c == '{' || c == '}' || c == '[' || c == ']' || - c == '|'); -} -NK_INTERN int -nk_textedit_move_to_word_previous(struct nk_text_edit *state) -{ - int c = state->cursor - 1; - while( c >= 0 && !nk_is_word_boundary(state, c)) - --c; - - if( c < 0 ) - c = 0; - - return c; -} -NK_INTERN int -nk_textedit_move_to_word_next(struct nk_text_edit *state) -{ - const int len = state->string.len; - int c = state->cursor+1; - while( c < len && !nk_is_word_boundary(state, c)) - ++c; - - if( c > len ) - c = len; - - return c; -} -NK_INTERN void -nk_textedit_prep_selection_at_cursor(struct nk_text_edit *state) -{ - /* update selection and cursor to match each other */ - if (!NK_TEXT_HAS_SELECTION(state)) - state->select_start = state->select_end = state->cursor; - else state->cursor = state->select_end; -} -NK_API int -nk_textedit_cut(struct nk_text_edit *state) -{ - /* API cut: delete selection */ - if (state->mode == NK_TEXT_EDIT_MODE_VIEW) - return 0; - if (NK_TEXT_HAS_SELECTION(state)) { - nk_textedit_delete_selection(state); /* implicitly clamps */ - state->has_preferred_x = 0; - return 1; - } - return 0; -} -NK_API int -nk_textedit_paste(struct nk_text_edit *state, char const *ctext, int len) -{ - /* API paste: replace existing selection with passed-in text */ - int glyphs; - const char *text = (const char *) ctext; - if (state->mode == NK_TEXT_EDIT_MODE_VIEW) return 0; - - /* if there's a selection, the paste should delete it */ - nk_textedit_clamp(state); - nk_textedit_delete_selection(state); - - /* try to insert the characters */ - glyphs = nk_utf_len(ctext, len); - if (nk_str_insert_text_char(&state->string, state->cursor, text, len)) { - nk_textedit_makeundo_insert(state, state->cursor, glyphs); - state->cursor += len; - state->has_preferred_x = 0; - return 1; - } - /* remove the undo since we didn't actually insert the characters */ - if (state->undo.undo_point) - --state->undo.undo_point; - return 0; -} -NK_API void -nk_textedit_text(struct nk_text_edit *state, const char *text, int total_len) -{ - nk_rune unicode; - int glyph_len; - int text_len = 0; - - NK_ASSERT(state); - NK_ASSERT(text); - if (!text || !total_len || state->mode == NK_TEXT_EDIT_MODE_VIEW) return; - - glyph_len = nk_utf_decode(text, &unicode, total_len); - while ((text_len < total_len) && glyph_len) - { - /* don't insert a backward delete, just process the event */ - if (unicode == 127) goto next; - /* can't add newline in single-line mode */ - if (unicode == '\n' && state->single_line) goto next; - /* filter incoming text */ - if (state->filter && !state->filter(state, unicode)) goto next; - - if (!NK_TEXT_HAS_SELECTION(state) && - state->cursor < state->string.len) - { - if (state->mode == NK_TEXT_EDIT_MODE_REPLACE) { - nk_textedit_makeundo_replace(state, state->cursor, 1, 1); - nk_str_delete_runes(&state->string, state->cursor, 1); - } - if (nk_str_insert_text_utf8(&state->string, state->cursor, - text+text_len, 1)) - { - ++state->cursor; - state->has_preferred_x = 0; - } - } else { - nk_textedit_delete_selection(state); /* implicitly clamps */ - if (nk_str_insert_text_utf8(&state->string, state->cursor, - text+text_len, 1)) - { - nk_textedit_makeundo_insert(state, state->cursor, 1); - ++state->cursor; - state->has_preferred_x = 0; - } - } - next: - text_len += glyph_len; - glyph_len = nk_utf_decode(text + text_len, &unicode, total_len-text_len); - } -} -NK_LIB void -nk_textedit_key(struct nk_text_edit *state, enum nk_keys key, int shift_mod, - const struct nk_user_font *font, float row_height) -{ -retry: - switch (key) - { - case NK_KEY_NONE: - case NK_KEY_CTRL: - case NK_KEY_ENTER: - case NK_KEY_SHIFT: - case NK_KEY_TAB: - case NK_KEY_COPY: - case NK_KEY_CUT: - case NK_KEY_PASTE: - case NK_KEY_MAX: - default: break; - case NK_KEY_TEXT_UNDO: - nk_textedit_undo(state); - state->has_preferred_x = 0; - break; - - case NK_KEY_TEXT_REDO: - nk_textedit_redo(state); - state->has_preferred_x = 0; - break; - - case NK_KEY_TEXT_SELECT_ALL: - nk_textedit_select_all(state); - state->has_preferred_x = 0; - break; - - case NK_KEY_TEXT_INSERT_MODE: - if (state->mode == NK_TEXT_EDIT_MODE_VIEW) - state->mode = NK_TEXT_EDIT_MODE_INSERT; - break; - case NK_KEY_TEXT_REPLACE_MODE: - if (state->mode == NK_TEXT_EDIT_MODE_VIEW) - state->mode = NK_TEXT_EDIT_MODE_REPLACE; - break; - case NK_KEY_TEXT_RESET_MODE: - if (state->mode == NK_TEXT_EDIT_MODE_INSERT || - state->mode == NK_TEXT_EDIT_MODE_REPLACE) - state->mode = NK_TEXT_EDIT_MODE_VIEW; - break; - - case NK_KEY_LEFT: - if (shift_mod) { - nk_textedit_clamp(state); - nk_textedit_prep_selection_at_cursor(state); - /* move selection left */ - if (state->select_end > 0) - --state->select_end; - state->cursor = state->select_end; - state->has_preferred_x = 0; - } else { - /* if currently there's a selection, - * move cursor to start of selection */ - if (NK_TEXT_HAS_SELECTION(state)) - nk_textedit_move_to_first(state); - else if (state->cursor > 0) - --state->cursor; - state->has_preferred_x = 0; - } break; - - case NK_KEY_RIGHT: - if (shift_mod) { - nk_textedit_prep_selection_at_cursor(state); - /* move selection right */ - ++state->select_end; - nk_textedit_clamp(state); - state->cursor = state->select_end; - state->has_preferred_x = 0; - } else { - /* if currently there's a selection, - * move cursor to end of selection */ - if (NK_TEXT_HAS_SELECTION(state)) - nk_textedit_move_to_last(state); - else ++state->cursor; - nk_textedit_clamp(state); - state->has_preferred_x = 0; - } break; - - case NK_KEY_TEXT_WORD_LEFT: - if (shift_mod) { - if( !NK_TEXT_HAS_SELECTION( state ) ) - nk_textedit_prep_selection_at_cursor(state); - state->cursor = nk_textedit_move_to_word_previous(state); - state->select_end = state->cursor; - nk_textedit_clamp(state ); - } else { - if (NK_TEXT_HAS_SELECTION(state)) - nk_textedit_move_to_first(state); - else { - state->cursor = nk_textedit_move_to_word_previous(state); - nk_textedit_clamp(state ); - } - } break; - - case NK_KEY_TEXT_WORD_RIGHT: - if (shift_mod) { - if( !NK_TEXT_HAS_SELECTION( state ) ) - nk_textedit_prep_selection_at_cursor(state); - state->cursor = nk_textedit_move_to_word_next(state); - state->select_end = state->cursor; - nk_textedit_clamp(state); - } else { - if (NK_TEXT_HAS_SELECTION(state)) - nk_textedit_move_to_last(state); - else { - state->cursor = nk_textedit_move_to_word_next(state); - nk_textedit_clamp(state ); - } - } break; - - case NK_KEY_DOWN: { - struct nk_text_find find; - struct nk_text_edit_row row; - int i, sel = shift_mod; - - if (state->single_line) { - /* on windows, up&down in single-line behave like left&right */ - key = NK_KEY_RIGHT; - goto retry; - } - - if (sel) - nk_textedit_prep_selection_at_cursor(state); - else if (NK_TEXT_HAS_SELECTION(state)) - nk_textedit_move_to_last(state); - - /* compute current position of cursor point */ - nk_textedit_clamp(state); - nk_textedit_find_charpos(&find, state, state->cursor, state->single_line, - font, row_height); - - /* now find character position down a row */ - if (find.length) - { - float x; - float goal_x = state->has_preferred_x ? state->preferred_x : find.x; - int start = find.first_char + find.length; - - state->cursor = start; - nk_textedit_layout_row(&row, state, state->cursor, row_height, font); - x = row.x0; - - for (i=0; i < row.num_chars && x < row.x1; ++i) { - float dx = nk_textedit_get_width(state, start, i, font); - x += dx; - if (x > goal_x) - break; - ++state->cursor; - } - nk_textedit_clamp(state); - - state->has_preferred_x = 1; - state->preferred_x = goal_x; - if (sel) - state->select_end = state->cursor; - } - } break; - - case NK_KEY_UP: { - struct nk_text_find find; - struct nk_text_edit_row row; - int i, sel = shift_mod; - - if (state->single_line) { - /* on windows, up&down become left&right */ - key = NK_KEY_LEFT; - goto retry; - } - - if (sel) - nk_textedit_prep_selection_at_cursor(state); - else if (NK_TEXT_HAS_SELECTION(state)) - nk_textedit_move_to_first(state); - - /* compute current position of cursor point */ - nk_textedit_clamp(state); - nk_textedit_find_charpos(&find, state, state->cursor, state->single_line, - font, row_height); - - /* can only go up if there's a previous row */ - if (find.prev_first != find.first_char) { - /* now find character position up a row */ - float x; - float goal_x = state->has_preferred_x ? state->preferred_x : find.x; - - state->cursor = find.prev_first; - nk_textedit_layout_row(&row, state, state->cursor, row_height, font); - x = row.x0; - - for (i=0; i < row.num_chars && x < row.x1; ++i) { - float dx = nk_textedit_get_width(state, find.prev_first, i, font); - x += dx; - if (x > goal_x) - break; - ++state->cursor; - } - nk_textedit_clamp(state); - - state->has_preferred_x = 1; - state->preferred_x = goal_x; - if (sel) state->select_end = state->cursor; - } - } break; - - case NK_KEY_DEL: - if (state->mode == NK_TEXT_EDIT_MODE_VIEW) - break; - if (NK_TEXT_HAS_SELECTION(state)) - nk_textedit_delete_selection(state); - else { - int n = state->string.len; - if (state->cursor < n) - nk_textedit_delete(state, state->cursor, 1); - } - state->has_preferred_x = 0; - break; - - case NK_KEY_BACKSPACE: - if (state->mode == NK_TEXT_EDIT_MODE_VIEW) - break; - if (NK_TEXT_HAS_SELECTION(state)) - nk_textedit_delete_selection(state); - else { - nk_textedit_clamp(state); - if (state->cursor > 0) { - nk_textedit_delete(state, state->cursor-1, 1); - --state->cursor; - } - } - state->has_preferred_x = 0; - break; - - case NK_KEY_TEXT_START: - if (shift_mod) { - nk_textedit_prep_selection_at_cursor(state); - state->cursor = state->select_end = 0; - state->has_preferred_x = 0; - } else { - state->cursor = state->select_start = state->select_end = 0; - state->has_preferred_x = 0; - } - break; - - case NK_KEY_TEXT_END: - if (shift_mod) { - nk_textedit_prep_selection_at_cursor(state); - state->cursor = state->select_end = state->string.len; - state->has_preferred_x = 0; - } else { - state->cursor = state->string.len; - state->select_start = state->select_end = 0; - state->has_preferred_x = 0; - } - break; - - case NK_KEY_TEXT_LINE_START: { - if (shift_mod) { - struct nk_text_find find; - nk_textedit_clamp(state); - nk_textedit_prep_selection_at_cursor(state); - if (state->string.len && state->cursor == state->string.len) - --state->cursor; - nk_textedit_find_charpos(&find, state,state->cursor, state->single_line, - font, row_height); - state->cursor = state->select_end = find.first_char; - state->has_preferred_x = 0; - } else { - struct nk_text_find find; - if (state->string.len && state->cursor == state->string.len) - --state->cursor; - nk_textedit_clamp(state); - nk_textedit_move_to_first(state); - nk_textedit_find_charpos(&find, state, state->cursor, state->single_line, - font, row_height); - state->cursor = find.first_char; - state->has_preferred_x = 0; - } - } break; - - case NK_KEY_TEXT_LINE_END: { - if (shift_mod) { - struct nk_text_find find; - nk_textedit_clamp(state); - nk_textedit_prep_selection_at_cursor(state); - nk_textedit_find_charpos(&find, state, state->cursor, state->single_line, - font, row_height); - state->has_preferred_x = 0; - state->cursor = find.first_char + find.length; - if (find.length > 0 && nk_str_rune_at(&state->string, state->cursor-1) == '\n') - --state->cursor; - state->select_end = state->cursor; - } else { - struct nk_text_find find; - nk_textedit_clamp(state); - nk_textedit_move_to_first(state); - nk_textedit_find_charpos(&find, state, state->cursor, state->single_line, - font, row_height); - - state->has_preferred_x = 0; - state->cursor = find.first_char + find.length; - if (find.length > 0 && nk_str_rune_at(&state->string, state->cursor-1) == '\n') - --state->cursor; - }} break; - } -} -NK_INTERN void -nk_textedit_flush_redo(struct nk_text_undo_state *state) -{ - state->redo_point = NK_TEXTEDIT_UNDOSTATECOUNT; - state->redo_char_point = NK_TEXTEDIT_UNDOCHARCOUNT; -} -NK_INTERN void -nk_textedit_discard_undo(struct nk_text_undo_state *state) -{ - /* discard the oldest entry in the undo list */ - if (state->undo_point > 0) { - /* if the 0th undo state has characters, clean those up */ - if (state->undo_rec[0].char_storage >= 0) { - int n = state->undo_rec[0].insert_length, i; - /* delete n characters from all other records */ - state->undo_char_point = (short)(state->undo_char_point - n); - NK_MEMCPY(state->undo_char, state->undo_char + n, - (nk_size)state->undo_char_point*sizeof(nk_rune)); - for (i=0; i < state->undo_point; ++i) { - if (state->undo_rec[i].char_storage >= 0) - state->undo_rec[i].char_storage = (short) - (state->undo_rec[i].char_storage - n); - } - } - --state->undo_point; - NK_MEMCPY(state->undo_rec, state->undo_rec+1, - (nk_size)((nk_size)state->undo_point * sizeof(state->undo_rec[0]))); - } -} -NK_INTERN void -nk_textedit_discard_redo(struct nk_text_undo_state *state) -{ -/* discard the oldest entry in the redo list--it's bad if this - ever happens, but because undo & redo have to store the actual - characters in different cases, the redo character buffer can - fill up even though the undo buffer didn't */ - nk_size num; - int k = NK_TEXTEDIT_UNDOSTATECOUNT-1; - if (state->redo_point <= k) { - /* if the k'th undo state has characters, clean those up */ - if (state->undo_rec[k].char_storage >= 0) { - int n = state->undo_rec[k].insert_length, i; - /* delete n characters from all other records */ - state->redo_char_point = (short)(state->redo_char_point + n); - num = (nk_size)(NK_TEXTEDIT_UNDOCHARCOUNT - state->redo_char_point); - NK_MEMCPY(state->undo_char + state->redo_char_point, - state->undo_char + state->redo_char_point-n, num * sizeof(char)); - for (i = state->redo_point; i < k; ++i) { - if (state->undo_rec[i].char_storage >= 0) { - state->undo_rec[i].char_storage = (short) - (state->undo_rec[i].char_storage + n); - } - } - } - ++state->redo_point; - num = (nk_size)(NK_TEXTEDIT_UNDOSTATECOUNT - state->redo_point); - if (num) NK_MEMCPY(state->undo_rec + state->redo_point-1, - state->undo_rec + state->redo_point, num * sizeof(state->undo_rec[0])); - } -} -NK_INTERN struct nk_text_undo_record* -nk_textedit_create_undo_record(struct nk_text_undo_state *state, int numchars) -{ - /* any time we create a new undo record, we discard redo*/ - nk_textedit_flush_redo(state); - - /* if we have no free records, we have to make room, - * by sliding the existing records down */ - if (state->undo_point == NK_TEXTEDIT_UNDOSTATECOUNT) - nk_textedit_discard_undo(state); - - /* if the characters to store won't possibly fit in the buffer, - * we can't undo */ - if (numchars > NK_TEXTEDIT_UNDOCHARCOUNT) { - state->undo_point = 0; - state->undo_char_point = 0; - return 0; - } - - /* if we don't have enough free characters in the buffer, - * we have to make room */ - while (state->undo_char_point + numchars > NK_TEXTEDIT_UNDOCHARCOUNT) - nk_textedit_discard_undo(state); - return &state->undo_rec[state->undo_point++]; -} -NK_INTERN nk_rune* -nk_textedit_createundo(struct nk_text_undo_state *state, int pos, - int insert_len, int delete_len) -{ - struct nk_text_undo_record *r = nk_textedit_create_undo_record(state, insert_len); - if (r == 0) - return 0; - - r->where = pos; - r->insert_length = (short) insert_len; - r->delete_length = (short) delete_len; - - if (insert_len == 0) { - r->char_storage = -1; - return 0; - } else { - r->char_storage = state->undo_char_point; - state->undo_char_point = (short)(state->undo_char_point + insert_len); - return &state->undo_char[r->char_storage]; - } -} -NK_API void -nk_textedit_undo(struct nk_text_edit *state) -{ - struct nk_text_undo_state *s = &state->undo; - struct nk_text_undo_record u, *r; - if (s->undo_point == 0) - return; - - /* we need to do two things: apply the undo record, and create a redo record */ - u = s->undo_rec[s->undo_point-1]; - r = &s->undo_rec[s->redo_point-1]; - r->char_storage = -1; - - r->insert_length = u.delete_length; - r->delete_length = u.insert_length; - r->where = u.where; - - if (u.delete_length) - { - /* if the undo record says to delete characters, then the redo record will - need to re-insert the characters that get deleted, so we need to store - them. - there are three cases: - - there's enough room to store the characters - - characters stored for *redoing* don't leave room for redo - - characters stored for *undoing* don't leave room for redo - if the last is true, we have to bail */ - if (s->undo_char_point + u.delete_length >= NK_TEXTEDIT_UNDOCHARCOUNT) { - /* the undo records take up too much character space; there's no space - * to store the redo characters */ - r->insert_length = 0; - } else { - int i; - /* there's definitely room to store the characters eventually */ - while (s->undo_char_point + u.delete_length > s->redo_char_point) { - /* there's currently not enough room, so discard a redo record */ - nk_textedit_discard_redo(s); - /* should never happen: */ - if (s->redo_point == NK_TEXTEDIT_UNDOSTATECOUNT) - return; - } - - r = &s->undo_rec[s->redo_point-1]; - r->char_storage = (short)(s->redo_char_point - u.delete_length); - s->redo_char_point = (short)(s->redo_char_point - u.delete_length); - - /* now save the characters */ - for (i=0; i < u.delete_length; ++i) - s->undo_char[r->char_storage + i] = - nk_str_rune_at(&state->string, u.where + i); - } - /* now we can carry out the deletion */ - nk_str_delete_runes(&state->string, u.where, u.delete_length); - } - - /* check type of recorded action: */ - if (u.insert_length) { - /* easy case: was a deletion, so we need to insert n characters */ - nk_str_insert_text_runes(&state->string, u.where, - &s->undo_char[u.char_storage], u.insert_length); - s->undo_char_point = (short)(s->undo_char_point - u.insert_length); - } - state->cursor = (short)(u.where + u.insert_length); - - s->undo_point--; - s->redo_point--; -} -NK_API void -nk_textedit_redo(struct nk_text_edit *state) -{ - struct nk_text_undo_state *s = &state->undo; - struct nk_text_undo_record *u, r; - if (s->redo_point == NK_TEXTEDIT_UNDOSTATECOUNT) - return; - - /* we need to do two things: apply the redo record, and create an undo record */ - u = &s->undo_rec[s->undo_point]; - r = s->undo_rec[s->redo_point]; - - /* we KNOW there must be room for the undo record, because the redo record - was derived from an undo record */ - u->delete_length = r.insert_length; - u->insert_length = r.delete_length; - u->where = r.where; - u->char_storage = -1; - - if (r.delete_length) { - /* the redo record requires us to delete characters, so the undo record - needs to store the characters */ - if (s->undo_char_point + u->insert_length > s->redo_char_point) { - u->insert_length = 0; - u->delete_length = 0; - } else { - int i; - u->char_storage = s->undo_char_point; - s->undo_char_point = (short)(s->undo_char_point + u->insert_length); - - /* now save the characters */ - for (i=0; i < u->insert_length; ++i) { - s->undo_char[u->char_storage + i] = - nk_str_rune_at(&state->string, u->where + i); - } - } - nk_str_delete_runes(&state->string, r.where, r.delete_length); - } - - if (r.insert_length) { - /* easy case: need to insert n characters */ - nk_str_insert_text_runes(&state->string, r.where, - &s->undo_char[r.char_storage], r.insert_length); - } - state->cursor = r.where + r.insert_length; - - s->undo_point++; - s->redo_point++; -} -NK_INTERN void -nk_textedit_makeundo_insert(struct nk_text_edit *state, int where, int length) -{ - nk_textedit_createundo(&state->undo, where, 0, length); -} -NK_INTERN void -nk_textedit_makeundo_delete(struct nk_text_edit *state, int where, int length) -{ - int i; - nk_rune *p = nk_textedit_createundo(&state->undo, where, length, 0); - if (p) { - for (i=0; i < length; ++i) - p[i] = nk_str_rune_at(&state->string, where+i); - } -} -NK_INTERN void -nk_textedit_makeundo_replace(struct nk_text_edit *state, int where, - int old_length, int new_length) -{ - int i; - nk_rune *p = nk_textedit_createundo(&state->undo, where, old_length, new_length); - if (p) { - for (i=0; i < old_length; ++i) - p[i] = nk_str_rune_at(&state->string, where+i); - } -} -NK_LIB void -nk_textedit_clear_state(struct nk_text_edit *state, enum nk_text_edit_type type, - nk_plugin_filter filter) -{ - /* reset the state to default */ - state->undo.undo_point = 0; - state->undo.undo_char_point = 0; - state->undo.redo_point = NK_TEXTEDIT_UNDOSTATECOUNT; - state->undo.redo_char_point = NK_TEXTEDIT_UNDOCHARCOUNT; - state->select_end = state->select_start = 0; - state->cursor = 0; - state->has_preferred_x = 0; - state->preferred_x = 0; - state->cursor_at_end_of_line = 0; - state->initialized = 1; - state->single_line = (unsigned char)(type == NK_TEXT_EDIT_SINGLE_LINE); - state->mode = NK_TEXT_EDIT_MODE_VIEW; - state->filter = filter; - state->scrollbar = nk_vec2(0,0); -} -NK_API void -nk_textedit_init_fixed(struct nk_text_edit *state, void *memory, nk_size size) -{ - NK_ASSERT(state); - NK_ASSERT(memory); - if (!state || !memory || !size) return; - NK_MEMSET(state, 0, sizeof(struct nk_text_edit)); - nk_textedit_clear_state(state, NK_TEXT_EDIT_SINGLE_LINE, 0); - nk_str_init_fixed(&state->string, memory, size); -} -NK_API void -nk_textedit_init(struct nk_text_edit *state, struct nk_allocator *alloc, nk_size size) -{ - NK_ASSERT(state); - NK_ASSERT(alloc); - if (!state || !alloc) return; - NK_MEMSET(state, 0, sizeof(struct nk_text_edit)); - nk_textedit_clear_state(state, NK_TEXT_EDIT_SINGLE_LINE, 0); - nk_str_init(&state->string, alloc, size); -} -#ifdef NK_INCLUDE_DEFAULT_ALLOCATOR -NK_API void -nk_textedit_init_default(struct nk_text_edit *state) -{ - NK_ASSERT(state); - if (!state) return; - NK_MEMSET(state, 0, sizeof(struct nk_text_edit)); - nk_textedit_clear_state(state, NK_TEXT_EDIT_SINGLE_LINE, 0); - nk_str_init_default(&state->string); -} -#endif -NK_API void -nk_textedit_select_all(struct nk_text_edit *state) -{ - NK_ASSERT(state); - state->select_start = 0; - state->select_end = state->string.len; -} -NK_API void -nk_textedit_free(struct nk_text_edit *state) -{ - NK_ASSERT(state); - if (!state) return; - nk_str_free(&state->string); -} - - - - - -/* =============================================================== - * - * FILTER - * - * ===============================================================*/ -NK_API int -nk_filter_default(const struct nk_text_edit *box, nk_rune unicode) -{ - NK_UNUSED(unicode); - NK_UNUSED(box); - return nk_true; -} -NK_API int -nk_filter_ascii(const struct nk_text_edit *box, nk_rune unicode) -{ - NK_UNUSED(box); - if (unicode > 128) return nk_false; - else return nk_true; -} -NK_API int -nk_filter_float(const struct nk_text_edit *box, nk_rune unicode) -{ - NK_UNUSED(box); - if ((unicode < '0' || unicode > '9') && unicode != '.' && unicode != '-') - return nk_false; - else return nk_true; -} -NK_API int -nk_filter_decimal(const struct nk_text_edit *box, nk_rune unicode) -{ - NK_UNUSED(box); - if ((unicode < '0' || unicode > '9') && unicode != '-') - return nk_false; - else return nk_true; -} -NK_API int -nk_filter_hex(const struct nk_text_edit *box, nk_rune unicode) -{ - NK_UNUSED(box); - if ((unicode < '0' || unicode > '9') && - (unicode < 'a' || unicode > 'f') && - (unicode < 'A' || unicode > 'F')) - return nk_false; - else return nk_true; -} -NK_API int -nk_filter_oct(const struct nk_text_edit *box, nk_rune unicode) -{ - NK_UNUSED(box); - if (unicode < '0' || unicode > '7') - return nk_false; - else return nk_true; -} -NK_API int -nk_filter_binary(const struct nk_text_edit *box, nk_rune unicode) -{ - NK_UNUSED(box); - if (unicode != '0' && unicode != '1') - return nk_false; - else return nk_true; -} - -/* =============================================================== - * - * EDIT - * - * ===============================================================*/ -NK_LIB void -nk_edit_draw_text(struct nk_command_buffer *out, - const struct nk_style_edit *style, float pos_x, float pos_y, - float x_offset, const char *text, int byte_len, float row_height, - const struct nk_user_font *font, struct nk_color background, - struct nk_color foreground, int is_selected) -{ - NK_ASSERT(out); - NK_ASSERT(font); - NK_ASSERT(style); - if (!text || !byte_len || !out || !style) return; - - {int glyph_len = 0; - nk_rune unicode = 0; - int text_len = 0; - float line_width = 0; - float glyph_width; - const char *line = text; - float line_offset = 0; - int line_count = 0; - - struct nk_text txt; - txt.padding = nk_vec2(0,0); - txt.background = background; - txt.text = foreground; - - glyph_len = nk_utf_decode(text+text_len, &unicode, byte_len-text_len); - if (!glyph_len) return; - while ((text_len < byte_len) && glyph_len) - { - if (unicode == '\n') { - /* new line separator so draw previous line */ - struct nk_rect label; - label.y = pos_y + line_offset; - label.h = row_height; - label.w = line_width; - label.x = pos_x; - if (!line_count) - label.x += x_offset; - - if (is_selected) /* selection needs to draw different background color */ - nk_fill_rect(out, label, 0, background); - nk_widget_text(out, label, line, (int)((text + text_len) - line), - &txt, NK_TEXT_CENTERED, font); - - text_len++; - line_count++; - line_width = 0; - line = text + text_len; - line_offset += row_height; - glyph_len = nk_utf_decode(text + text_len, &unicode, (int)(byte_len-text_len)); - continue; - } - if (unicode == '\r') { - text_len++; - glyph_len = nk_utf_decode(text + text_len, &unicode, byte_len-text_len); - continue; - } - glyph_width = font->width(font->userdata, font->height, text+text_len, glyph_len); - line_width += (float)glyph_width; - text_len += glyph_len; - glyph_len = nk_utf_decode(text + text_len, &unicode, byte_len-text_len); - continue; - } - if (line_width > 0) { - /* draw last line */ - struct nk_rect label; - label.y = pos_y + line_offset; - label.h = row_height; - label.w = line_width; - label.x = pos_x; - if (!line_count) - label.x += x_offset; - - if (is_selected) - nk_fill_rect(out, label, 0, background); - nk_widget_text(out, label, line, (int)((text + text_len) - line), - &txt, NK_TEXT_LEFT, font); - }} -} -NK_LIB nk_flags -nk_do_edit(nk_flags *state, struct nk_command_buffer *out, - struct nk_rect bounds, nk_flags flags, nk_plugin_filter filter, - struct nk_text_edit *edit, const struct nk_style_edit *style, - struct nk_input *in, const struct nk_user_font *font) -{ - struct nk_rect area; - nk_flags ret = 0; - float row_height; - char prev_state = 0; - char is_hovered = 0; - char select_all = 0; - char cursor_follow = 0; - struct nk_rect old_clip; - struct nk_rect clip; - - NK_ASSERT(state); - NK_ASSERT(out); - NK_ASSERT(style); - if (!state || !out || !style) - return ret; - - /* visible text area calculation */ - area.x = bounds.x + style->padding.x + style->border; - area.y = bounds.y + style->padding.y + style->border; - area.w = bounds.w - (2.0f * style->padding.x + 2 * style->border); - area.h = bounds.h - (2.0f * style->padding.y + 2 * style->border); - if (flags & NK_EDIT_MULTILINE) - area.w = NK_MAX(0, area.w - style->scrollbar_size.x); - row_height = (flags & NK_EDIT_MULTILINE)? font->height + style->row_padding: area.h; - - /* calculate clipping rectangle */ - old_clip = out->clip; - nk_unify(&clip, &old_clip, area.x, area.y, area.x + area.w, area.y + area.h); - - /* update edit state */ - prev_state = (char)edit->active; - is_hovered = (char)nk_input_is_mouse_hovering_rect(in, bounds); - if (in && in->mouse.buttons[NK_BUTTON_LEFT].clicked && in->mouse.buttons[NK_BUTTON_LEFT].down) { - edit->active = NK_INBOX(in->mouse.pos.x, in->mouse.pos.y, - bounds.x, bounds.y, bounds.w, bounds.h); - } - - /* (de)activate text editor */ - if (!prev_state && edit->active) { - const enum nk_text_edit_type type = (flags & NK_EDIT_MULTILINE) ? - NK_TEXT_EDIT_MULTI_LINE: NK_TEXT_EDIT_SINGLE_LINE; - nk_textedit_clear_state(edit, type, filter); - if (flags & NK_EDIT_AUTO_SELECT) - select_all = nk_true; - if (flags & NK_EDIT_GOTO_END_ON_ACTIVATE) { - edit->cursor = edit->string.len; - in = 0; - } - } else if (!edit->active) edit->mode = NK_TEXT_EDIT_MODE_VIEW; - if (flags & NK_EDIT_READ_ONLY) - edit->mode = NK_TEXT_EDIT_MODE_VIEW; - else if (flags & NK_EDIT_ALWAYS_INSERT_MODE) - edit->mode = NK_TEXT_EDIT_MODE_INSERT; - - ret = (edit->active) ? NK_EDIT_ACTIVE: NK_EDIT_INACTIVE; - if (prev_state != edit->active) - ret |= (edit->active) ? NK_EDIT_ACTIVATED: NK_EDIT_DEACTIVATED; - - /* handle user input */ - if (edit->active && in) - { - int shift_mod = in->keyboard.keys[NK_KEY_SHIFT].down; - const float mouse_x = (in->mouse.pos.x - area.x) + edit->scrollbar.x; - const float mouse_y = (in->mouse.pos.y - area.y) + edit->scrollbar.y; - - /* mouse click handler */ - is_hovered = (char)nk_input_is_mouse_hovering_rect(in, area); - if (select_all) { - nk_textedit_select_all(edit); - } else if (is_hovered && in->mouse.buttons[NK_BUTTON_LEFT].down && - in->mouse.buttons[NK_BUTTON_LEFT].clicked) { - nk_textedit_click(edit, mouse_x, mouse_y, font, row_height); - } else if (is_hovered && in->mouse.buttons[NK_BUTTON_LEFT].down && - (in->mouse.delta.x != 0.0f || in->mouse.delta.y != 0.0f)) { - nk_textedit_drag(edit, mouse_x, mouse_y, font, row_height); - cursor_follow = nk_true; - } else if (is_hovered && in->mouse.buttons[NK_BUTTON_RIGHT].clicked && - in->mouse.buttons[NK_BUTTON_RIGHT].down) { - nk_textedit_key(edit, NK_KEY_TEXT_WORD_LEFT, nk_false, font, row_height); - nk_textedit_key(edit, NK_KEY_TEXT_WORD_RIGHT, nk_true, font, row_height); - cursor_follow = nk_true; - } - - {int i; /* keyboard input */ - int old_mode = edit->mode; - for (i = 0; i < NK_KEY_MAX; ++i) { - if (i == NK_KEY_ENTER || i == NK_KEY_TAB) continue; /* special case */ - if (nk_input_is_key_pressed(in, (enum nk_keys)i)) { - nk_textedit_key(edit, (enum nk_keys)i, shift_mod, font, row_height); - cursor_follow = nk_true; - } - } - if (old_mode != edit->mode) { - in->keyboard.text_len = 0; - }} - - /* text input */ - edit->filter = filter; - if (in->keyboard.text_len) { - nk_textedit_text(edit, in->keyboard.text, in->keyboard.text_len); - cursor_follow = nk_true; - in->keyboard.text_len = 0; - } - - /* enter key handler */ - if (nk_input_is_key_pressed(in, NK_KEY_ENTER)) { - cursor_follow = nk_true; - if (flags & NK_EDIT_CTRL_ENTER_NEWLINE && shift_mod) - nk_textedit_text(edit, "\n", 1); - else if (flags & NK_EDIT_SIG_ENTER) - ret |= NK_EDIT_COMMITED; - else nk_textedit_text(edit, "\n", 1); - } - - /* cut & copy handler */ - {int copy= nk_input_is_key_pressed(in, NK_KEY_COPY); - int cut = nk_input_is_key_pressed(in, NK_KEY_CUT); - if ((copy || cut) && (flags & NK_EDIT_CLIPBOARD)) - { - int glyph_len; - nk_rune unicode; - const char *text; - int b = edit->select_start; - int e = edit->select_end; - - int begin = NK_MIN(b, e); - int end = NK_MAX(b, e); - text = nk_str_at_const(&edit->string, begin, &unicode, &glyph_len); - if (edit->clip.copy) - edit->clip.copy(edit->clip.userdata, text, end - begin); - if (cut && !(flags & NK_EDIT_READ_ONLY)){ - nk_textedit_cut(edit); - cursor_follow = nk_true; - } - }} - - /* paste handler */ - {int paste = nk_input_is_key_pressed(in, NK_KEY_PASTE); - if (paste && (flags & NK_EDIT_CLIPBOARD) && edit->clip.paste) { - edit->clip.paste(edit->clip.userdata, edit); - cursor_follow = nk_true; - }} - - /* tab handler */ - {int tab = nk_input_is_key_pressed(in, NK_KEY_TAB); - if (tab && (flags & NK_EDIT_ALLOW_TAB)) { - nk_textedit_text(edit, " ", 4); - cursor_follow = nk_true; - }} - } - - /* set widget state */ - if (edit->active) - *state = NK_WIDGET_STATE_ACTIVE; - else nk_widget_state_reset(state); - - if (is_hovered) - *state |= NK_WIDGET_STATE_HOVERED; - - /* DRAW EDIT */ - {const char *text = nk_str_get_const(&edit->string); - int len = nk_str_len_char(&edit->string); - - {/* select background colors/images */ - const struct nk_style_item *background; - if (*state & NK_WIDGET_STATE_ACTIVED) - background = &style->active; - else if (*state & NK_WIDGET_STATE_HOVER) - background = &style->hover; - else background = &style->normal; - - /* draw background frame */ - if (background->type == NK_STYLE_ITEM_COLOR) { - nk_stroke_rect(out, bounds, style->rounding, style->border, style->border_color); - nk_fill_rect(out, bounds, style->rounding, background->data.color); - } else nk_draw_image(out, bounds, &background->data.image, nk_white);} - - area.w = NK_MAX(0, area.w - style->cursor_size); - if (edit->active) - { - int total_lines = 1; - struct nk_vec2 text_size = nk_vec2(0,0); - - /* text pointer positions */ - const char *cursor_ptr = 0; - const char *select_begin_ptr = 0; - const char *select_end_ptr = 0; - - /* 2D pixel positions */ - struct nk_vec2 cursor_pos = nk_vec2(0,0); - struct nk_vec2 selection_offset_start = nk_vec2(0,0); - struct nk_vec2 selection_offset_end = nk_vec2(0,0); - - int selection_begin = NK_MIN(edit->select_start, edit->select_end); - int selection_end = NK_MAX(edit->select_start, edit->select_end); - - /* calculate total line count + total space + cursor/selection position */ - float line_width = 0.0f; - if (text && len) - { - /* utf8 encoding */ - float glyph_width; - int glyph_len = 0; - nk_rune unicode = 0; - int text_len = 0; - int glyphs = 0; - int row_begin = 0; - - glyph_len = nk_utf_decode(text, &unicode, len); - glyph_width = font->width(font->userdata, font->height, text, glyph_len); - line_width = 0; - - /* iterate all lines */ - while ((text_len < len) && glyph_len) - { - /* set cursor 2D position and line */ - if (!cursor_ptr && glyphs == edit->cursor) - { - int glyph_offset; - struct nk_vec2 out_offset; - struct nk_vec2 row_size; - const char *remaining; - - /* calculate 2d position */ - cursor_pos.y = (float)(total_lines-1) * row_height; - row_size = nk_text_calculate_text_bounds(font, text+row_begin, - text_len-row_begin, row_height, &remaining, - &out_offset, &glyph_offset, NK_STOP_ON_NEW_LINE); - cursor_pos.x = row_size.x; - cursor_ptr = text + text_len; - } - - /* set start selection 2D position and line */ - if (!select_begin_ptr && edit->select_start != edit->select_end && - glyphs == selection_begin) - { - int glyph_offset; - struct nk_vec2 out_offset; - struct nk_vec2 row_size; - const char *remaining; - - /* calculate 2d position */ - selection_offset_start.y = (float)(NK_MAX(total_lines-1,0)) * row_height; - row_size = nk_text_calculate_text_bounds(font, text+row_begin, - text_len-row_begin, row_height, &remaining, - &out_offset, &glyph_offset, NK_STOP_ON_NEW_LINE); - selection_offset_start.x = row_size.x; - select_begin_ptr = text + text_len; - } - - /* set end selection 2D position and line */ - if (!select_end_ptr && edit->select_start != edit->select_end && - glyphs == selection_end) - { - int glyph_offset; - struct nk_vec2 out_offset; - struct nk_vec2 row_size; - const char *remaining; - - /* calculate 2d position */ - selection_offset_end.y = (float)(total_lines-1) * row_height; - row_size = nk_text_calculate_text_bounds(font, text+row_begin, - text_len-row_begin, row_height, &remaining, - &out_offset, &glyph_offset, NK_STOP_ON_NEW_LINE); - selection_offset_end.x = row_size.x; - select_end_ptr = text + text_len; - } - if (unicode == '\n') { - text_size.x = NK_MAX(text_size.x, line_width); - total_lines++; - line_width = 0; - text_len++; - glyphs++; - row_begin = text_len; - glyph_len = nk_utf_decode(text + text_len, &unicode, len-text_len); - glyph_width = font->width(font->userdata, font->height, text+text_len, glyph_len); - continue; - } - - glyphs++; - text_len += glyph_len; - line_width += (float)glyph_width; - - glyph_len = nk_utf_decode(text + text_len, &unicode, len-text_len); - glyph_width = font->width(font->userdata, font->height, - text+text_len, glyph_len); - continue; - } - text_size.y = (float)total_lines * row_height; - - /* handle case when cursor is at end of text buffer */ - if (!cursor_ptr && edit->cursor == edit->string.len) { - cursor_pos.x = line_width; - cursor_pos.y = text_size.y - row_height; - } - } - { - /* scrollbar */ - if (cursor_follow) - { - /* update scrollbar to follow cursor */ - if (!(flags & NK_EDIT_NO_HORIZONTAL_SCROLL)) { - /* horizontal scroll */ - const float scroll_increment = area.w * 0.25f; - if (cursor_pos.x < edit->scrollbar.x) - edit->scrollbar.x = (float)(int)NK_MAX(0.0f, cursor_pos.x - scroll_increment); - if (cursor_pos.x >= edit->scrollbar.x + area.w) - edit->scrollbar.x = (float)(int)NK_MAX(0.0f, edit->scrollbar.x + scroll_increment); - } else edit->scrollbar.x = 0; - - if (flags & NK_EDIT_MULTILINE) { - /* vertical scroll */ - if (cursor_pos.y < edit->scrollbar.y) - edit->scrollbar.y = NK_MAX(0.0f, cursor_pos.y - row_height); - if (cursor_pos.y >= edit->scrollbar.y + area.h) - edit->scrollbar.y = edit->scrollbar.y + row_height; - } else edit->scrollbar.y = 0; - } - - /* scrollbar widget */ - if (flags & NK_EDIT_MULTILINE) - { - nk_flags ws; - struct nk_rect scroll; - float scroll_target; - float scroll_offset; - float scroll_step; - float scroll_inc; - - scroll = area; - scroll.x = (bounds.x + bounds.w - style->border) - style->scrollbar_size.x; - scroll.w = style->scrollbar_size.x; - - scroll_offset = edit->scrollbar.y; - scroll_step = scroll.h * 0.10f; - scroll_inc = scroll.h * 0.01f; - scroll_target = text_size.y; - edit->scrollbar.y = nk_do_scrollbarv(&ws, out, scroll, 0, - scroll_offset, scroll_target, scroll_step, scroll_inc, - &style->scrollbar, in, font); - } - } - - /* draw text */ - {struct nk_color background_color; - struct nk_color text_color; - struct nk_color sel_background_color; - struct nk_color sel_text_color; - struct nk_color cursor_color; - struct nk_color cursor_text_color; - const struct nk_style_item *background; - nk_push_scissor(out, clip); - - /* select correct colors to draw */ - if (*state & NK_WIDGET_STATE_ACTIVED) { - background = &style->active; - text_color = style->text_active; - sel_text_color = style->selected_text_hover; - sel_background_color = style->selected_hover; - cursor_color = style->cursor_hover; - cursor_text_color = style->cursor_text_hover; - } else if (*state & NK_WIDGET_STATE_HOVER) { - background = &style->hover; - text_color = style->text_hover; - sel_text_color = style->selected_text_hover; - sel_background_color = style->selected_hover; - cursor_text_color = style->cursor_text_hover; - cursor_color = style->cursor_hover; - } else { - background = &style->normal; - text_color = style->text_normal; - sel_text_color = style->selected_text_normal; - sel_background_color = style->selected_normal; - cursor_color = style->cursor_normal; - cursor_text_color = style->cursor_text_normal; - } - if (background->type == NK_STYLE_ITEM_IMAGE) - background_color = nk_rgba(0,0,0,0); - else background_color = background->data.color; - - - if (edit->select_start == edit->select_end) { - /* no selection so just draw the complete text */ - const char *begin = nk_str_get_const(&edit->string); - int l = nk_str_len_char(&edit->string); - nk_edit_draw_text(out, style, area.x - edit->scrollbar.x, - area.y - edit->scrollbar.y, 0, begin, l, row_height, font, - background_color, text_color, nk_false); - } else { - /* edit has selection so draw 1-3 text chunks */ - if (edit->select_start != edit->select_end && selection_begin > 0){ - /* draw unselected text before selection */ - const char *begin = nk_str_get_const(&edit->string); - NK_ASSERT(select_begin_ptr); - nk_edit_draw_text(out, style, area.x - edit->scrollbar.x, - area.y - edit->scrollbar.y, 0, begin, (int)(select_begin_ptr - begin), - row_height, font, background_color, text_color, nk_false); - } - if (edit->select_start != edit->select_end) { - /* draw selected text */ - NK_ASSERT(select_begin_ptr); - if (!select_end_ptr) { - const char *begin = nk_str_get_const(&edit->string); - select_end_ptr = begin + nk_str_len_char(&edit->string); - } - nk_edit_draw_text(out, style, - area.x - edit->scrollbar.x, - area.y + selection_offset_start.y - edit->scrollbar.y, - selection_offset_start.x, - select_begin_ptr, (int)(select_end_ptr - select_begin_ptr), - row_height, font, sel_background_color, sel_text_color, nk_true); - } - if ((edit->select_start != edit->select_end && - selection_end < edit->string.len)) - { - /* draw unselected text after selected text */ - const char *begin = select_end_ptr; - const char *end = nk_str_get_const(&edit->string) + - nk_str_len_char(&edit->string); - NK_ASSERT(select_end_ptr); - nk_edit_draw_text(out, style, - area.x - edit->scrollbar.x, - area.y + selection_offset_end.y - edit->scrollbar.y, - selection_offset_end.x, - begin, (int)(end - begin), row_height, font, - background_color, text_color, nk_true); - } - } - - /* cursor */ - if (edit->select_start == edit->select_end) - { - if (edit->cursor >= nk_str_len(&edit->string) || - (cursor_ptr && *cursor_ptr == '\n')) { - /* draw cursor at end of line */ - struct nk_rect cursor; - cursor.w = style->cursor_size; - cursor.h = font->height; - cursor.x = area.x + cursor_pos.x - edit->scrollbar.x; - cursor.y = area.y + cursor_pos.y + row_height/2.0f - cursor.h/2.0f; - cursor.y -= edit->scrollbar.y; - nk_fill_rect(out, cursor, 0, cursor_color); - } else { - /* draw cursor inside text */ - int glyph_len; - struct nk_rect label; - struct nk_text txt; - - nk_rune unicode; - NK_ASSERT(cursor_ptr); - glyph_len = nk_utf_decode(cursor_ptr, &unicode, 4); - - label.x = area.x + cursor_pos.x - edit->scrollbar.x; - label.y = area.y + cursor_pos.y - edit->scrollbar.y; - label.w = font->width(font->userdata, font->height, cursor_ptr, glyph_len); - label.h = row_height; - - txt.padding = nk_vec2(0,0); - txt.background = cursor_color;; - txt.text = cursor_text_color; - nk_fill_rect(out, label, 0, cursor_color); - nk_widget_text(out, label, cursor_ptr, glyph_len, &txt, NK_TEXT_LEFT, font); - } - }} - } else { - /* not active so just draw text */ - int l = nk_str_len_char(&edit->string); - const char *begin = nk_str_get_const(&edit->string); - - const struct nk_style_item *background; - struct nk_color background_color; - struct nk_color text_color; - nk_push_scissor(out, clip); - if (*state & NK_WIDGET_STATE_ACTIVED) { - background = &style->active; - text_color = style->text_active; - } else if (*state & NK_WIDGET_STATE_HOVER) { - background = &style->hover; - text_color = style->text_hover; - } else { - background = &style->normal; - text_color = style->text_normal; - } - if (background->type == NK_STYLE_ITEM_IMAGE) - background_color = nk_rgba(0,0,0,0); - else background_color = background->data.color; - nk_edit_draw_text(out, style, area.x - edit->scrollbar.x, - area.y - edit->scrollbar.y, 0, begin, l, row_height, font, - background_color, text_color, nk_false); - } - nk_push_scissor(out, old_clip);} - return ret; -} -NK_API void -nk_edit_focus(struct nk_context *ctx, nk_flags flags) -{ - nk_hash hash; - struct nk_window *win; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - if (!ctx || !ctx->current) return; - - win = ctx->current; - hash = win->edit.seq; - win->edit.active = nk_true; - win->edit.name = hash; - if (flags & NK_EDIT_ALWAYS_INSERT_MODE) - win->edit.mode = NK_TEXT_EDIT_MODE_INSERT; -} -NK_API void -nk_edit_unfocus(struct nk_context *ctx) -{ - struct nk_window *win; - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - if (!ctx || !ctx->current) return; - - win = ctx->current; - win->edit.active = nk_false; - win->edit.name = 0; -} -NK_API nk_flags -nk_edit_string(struct nk_context *ctx, nk_flags flags, - char *memory, int *len, int max, nk_plugin_filter filter) -{ - nk_hash hash; - nk_flags state; - struct nk_text_edit *edit; - struct nk_window *win; - - NK_ASSERT(ctx); - NK_ASSERT(memory); - NK_ASSERT(len); - if (!ctx || !memory || !len) - return 0; - - filter = (!filter) ? nk_filter_default: filter; - win = ctx->current; - hash = win->edit.seq; - edit = &ctx->text_edit; - nk_textedit_clear_state(&ctx->text_edit, (flags & NK_EDIT_MULTILINE)? - NK_TEXT_EDIT_MULTI_LINE: NK_TEXT_EDIT_SINGLE_LINE, filter); - - if (win->edit.active && hash == win->edit.name) { - if (flags & NK_EDIT_NO_CURSOR) - edit->cursor = nk_utf_len(memory, *len); - else edit->cursor = win->edit.cursor; - if (!(flags & NK_EDIT_SELECTABLE)) { - edit->select_start = win->edit.cursor; - edit->select_end = win->edit.cursor; - } else { - edit->select_start = win->edit.sel_start; - edit->select_end = win->edit.sel_end; - } - edit->mode = win->edit.mode; - edit->scrollbar.x = (float)win->edit.scrollbar.x; - edit->scrollbar.y = (float)win->edit.scrollbar.y; - edit->active = nk_true; - } else edit->active = nk_false; - - max = NK_MAX(1, max); - *len = NK_MIN(*len, max-1); - nk_str_init_fixed(&edit->string, memory, (nk_size)max); - edit->string.buffer.allocated = (nk_size)*len; - edit->string.len = nk_utf_len(memory, *len); - state = nk_edit_buffer(ctx, flags, edit, filter); - *len = (int)edit->string.buffer.allocated; - - if (edit->active) { - win->edit.cursor = edit->cursor; - win->edit.sel_start = edit->select_start; - win->edit.sel_end = edit->select_end; - win->edit.mode = edit->mode; - win->edit.scrollbar.x = (nk_uint)edit->scrollbar.x; - win->edit.scrollbar.y = (nk_uint)edit->scrollbar.y; - } return state; -} -NK_API nk_flags -nk_edit_buffer(struct nk_context *ctx, nk_flags flags, - struct nk_text_edit *edit, nk_plugin_filter filter) -{ - struct nk_window *win; - struct nk_style *style; - struct nk_input *in; - - enum nk_widget_layout_states state; - struct nk_rect bounds; - - nk_flags ret_flags = 0; - unsigned char prev_state; - nk_hash hash; - - /* make sure correct values */ - NK_ASSERT(ctx); - NK_ASSERT(edit); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return 0; - - win = ctx->current; - style = &ctx->style; - state = nk_widget(&bounds, ctx); - if (!state) return state; - in = (win->layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; - - /* check if edit is currently hot item */ - hash = win->edit.seq++; - if (win->edit.active && hash == win->edit.name) { - if (flags & NK_EDIT_NO_CURSOR) - edit->cursor = edit->string.len; - if (!(flags & NK_EDIT_SELECTABLE)) { - edit->select_start = edit->cursor; - edit->select_end = edit->cursor; - } - if (flags & NK_EDIT_CLIPBOARD) - edit->clip = ctx->clip; - edit->active = (unsigned char)win->edit.active; - } else edit->active = nk_false; - edit->mode = win->edit.mode; - - filter = (!filter) ? nk_filter_default: filter; - prev_state = (unsigned char)edit->active; - in = (flags & NK_EDIT_READ_ONLY) ? 0: in; - ret_flags = nk_do_edit(&ctx->last_widget_state, &win->buffer, bounds, flags, - filter, edit, &style->edit, in, style->font); - - if (ctx->last_widget_state & NK_WIDGET_STATE_HOVER) - ctx->style.cursor_active = ctx->style.cursors[NK_CURSOR_TEXT]; - if (edit->active && prev_state != edit->active) { - /* current edit is now hot */ - win->edit.active = nk_true; - win->edit.name = hash; - } else if (prev_state && !edit->active) { - /* current edit is now cold */ - win->edit.active = nk_false; - } return ret_flags; -} -NK_API nk_flags -nk_edit_string_zero_terminated(struct nk_context *ctx, nk_flags flags, - char *buffer, int max, nk_plugin_filter filter) -{ - nk_flags result; - int len = nk_strlen(buffer); - result = nk_edit_string(ctx, flags, buffer, &len, max, filter); - buffer[NK_MIN(NK_MAX(max-1,0), len)] = '\0'; - return result; -} - - - - - -/* =============================================================== - * - * PROPERTY - * - * ===============================================================*/ -NK_LIB void -nk_drag_behavior(nk_flags *state, const struct nk_input *in, - struct nk_rect drag, struct nk_property_variant *variant, - float inc_per_pixel) -{ - int left_mouse_down = in && in->mouse.buttons[NK_BUTTON_LEFT].down; - int left_mouse_click_in_cursor = in && - nk_input_has_mouse_click_down_in_rect(in, NK_BUTTON_LEFT, drag, nk_true); - - nk_widget_state_reset(state); - if (nk_input_is_mouse_hovering_rect(in, drag)) - *state = NK_WIDGET_STATE_HOVERED; - - if (left_mouse_down && left_mouse_click_in_cursor) { - float delta, pixels; - pixels = in->mouse.delta.x; - delta = pixels * inc_per_pixel; - switch (variant->kind) { - default: break; - case NK_PROPERTY_INT: - variant->value.i = variant->value.i + (int)delta; - variant->value.i = NK_CLAMP(variant->min_value.i, variant->value.i, variant->max_value.i); - break; - case NK_PROPERTY_FLOAT: - variant->value.f = variant->value.f + (float)delta; - variant->value.f = NK_CLAMP(variant->min_value.f, variant->value.f, variant->max_value.f); - break; - case NK_PROPERTY_DOUBLE: - variant->value.d = variant->value.d + (double)delta; - variant->value.d = NK_CLAMP(variant->min_value.d, variant->value.d, variant->max_value.d); - break; - } - *state = NK_WIDGET_STATE_ACTIVE; - } - if (*state & NK_WIDGET_STATE_HOVER && !nk_input_is_mouse_prev_hovering_rect(in, drag)) - *state |= NK_WIDGET_STATE_ENTERED; - else if (nk_input_is_mouse_prev_hovering_rect(in, drag)) - *state |= NK_WIDGET_STATE_LEFT; -} -NK_LIB void -nk_property_behavior(nk_flags *ws, const struct nk_input *in, - struct nk_rect property, struct nk_rect label, struct nk_rect edit, - struct nk_rect empty, int *state, struct nk_property_variant *variant, - float inc_per_pixel) -{ - if (in && *state == NK_PROPERTY_DEFAULT) { - if (nk_button_behavior(ws, edit, in, NK_BUTTON_DEFAULT)) - *state = NK_PROPERTY_EDIT; - else if (nk_input_is_mouse_click_down_in_rect(in, NK_BUTTON_LEFT, label, nk_true)) - *state = NK_PROPERTY_DRAG; - else if (nk_input_is_mouse_click_down_in_rect(in, NK_BUTTON_LEFT, empty, nk_true)) - *state = NK_PROPERTY_DRAG; - } - if (*state == NK_PROPERTY_DRAG) { - nk_drag_behavior(ws, in, property, variant, inc_per_pixel); - if (!(*ws & NK_WIDGET_STATE_ACTIVED)) *state = NK_PROPERTY_DEFAULT; - } -} -NK_LIB void -nk_draw_property(struct nk_command_buffer *out, const struct nk_style_property *style, - const struct nk_rect *bounds, const struct nk_rect *label, nk_flags state, - const char *name, int len, const struct nk_user_font *font) -{ - struct nk_text text; - const struct nk_style_item *background; - - /* select correct background and text color */ - if (state & NK_WIDGET_STATE_ACTIVED) { - background = &style->active; - text.text = style->label_active; - } else if (state & NK_WIDGET_STATE_HOVER) { - background = &style->hover; - text.text = style->label_hover; - } else { - background = &style->normal; - text.text = style->label_normal; - } - - /* draw background */ - if (background->type == NK_STYLE_ITEM_IMAGE) { - nk_draw_image(out, *bounds, &background->data.image, nk_white); - text.background = nk_rgba(0,0,0,0); - } else { - text.background = background->data.color; - nk_fill_rect(out, *bounds, style->rounding, background->data.color); - nk_stroke_rect(out, *bounds, style->rounding, style->border, background->data.color); - } - - /* draw label */ - text.padding = nk_vec2(0,0); - nk_widget_text(out, *label, name, len, &text, NK_TEXT_CENTERED, font); -} -NK_LIB void -nk_do_property(nk_flags *ws, - struct nk_command_buffer *out, struct nk_rect property, - const char *name, struct nk_property_variant *variant, - float inc_per_pixel, char *buffer, int *len, - int *state, int *cursor, int *select_begin, int *select_end, - const struct nk_style_property *style, - enum nk_property_filter filter, struct nk_input *in, - const struct nk_user_font *font, struct nk_text_edit *text_edit, - enum nk_button_behavior behavior) -{ - const nk_plugin_filter filters[] = { - nk_filter_decimal, - nk_filter_float - }; - int active, old; - int num_len, name_len; - char string[NK_MAX_NUMBER_BUFFER]; - float size; - - char *dst = 0; - int *length; - - struct nk_rect left; - struct nk_rect right; - struct nk_rect label; - struct nk_rect edit; - struct nk_rect empty; - - /* left decrement button */ - left.h = font->height/2; - left.w = left.h; - left.x = property.x + style->border + style->padding.x; - left.y = property.y + style->border + property.h/2.0f - left.h/2; - - /* text label */ - name_len = nk_strlen(name); - size = font->width(font->userdata, font->height, name, name_len); - label.x = left.x + left.w + style->padding.x; - label.w = (float)size + 2 * style->padding.x; - label.y = property.y + style->border + style->padding.y; - label.h = property.h - (2 * style->border + 2 * style->padding.y); - - /* right increment button */ - right.y = left.y; - right.w = left.w; - right.h = left.h; - right.x = property.x + property.w - (right.w + style->padding.x); - - /* edit */ - if (*state == NK_PROPERTY_EDIT) { - size = font->width(font->userdata, font->height, buffer, *len); - size += style->edit.cursor_size; - length = len; - dst = buffer; - } else { - switch (variant->kind) { - default: break; - case NK_PROPERTY_INT: - nk_itoa(string, variant->value.i); - num_len = nk_strlen(string); - break; - case NK_PROPERTY_FLOAT: - NK_DTOA(string, (double)variant->value.f); - num_len = nk_string_float_limit(string, NK_MAX_FLOAT_PRECISION); - break; - case NK_PROPERTY_DOUBLE: - NK_DTOA(string, variant->value.d); - num_len = nk_string_float_limit(string, NK_MAX_FLOAT_PRECISION); - break; - } - size = font->width(font->userdata, font->height, string, num_len); - dst = string; - length = &num_len; - } - - edit.w = (float)size + 2 * style->padding.x; - edit.w = NK_MIN(edit.w, right.x - (label.x + label.w)); - edit.x = right.x - (edit.w + style->padding.x); - edit.y = property.y + style->border; - edit.h = property.h - (2 * style->border); - - /* empty left space activator */ - empty.w = edit.x - (label.x + label.w); - empty.x = label.x + label.w; - empty.y = property.y; - empty.h = property.h; - - /* update property */ - old = (*state == NK_PROPERTY_EDIT); - nk_property_behavior(ws, in, property, label, edit, empty, state, variant, inc_per_pixel); - - /* draw property */ - if (style->draw_begin) style->draw_begin(out, style->userdata); - nk_draw_property(out, style, &property, &label, *ws, name, name_len, font); - if (style->draw_end) style->draw_end(out, style->userdata); - - /* execute right button */ - if (nk_do_button_symbol(ws, out, left, style->sym_left, behavior, &style->dec_button, in, font)) { - switch (variant->kind) { - default: break; - case NK_PROPERTY_INT: - variant->value.i = NK_CLAMP(variant->min_value.i, variant->value.i - variant->step.i, variant->max_value.i); break; - case NK_PROPERTY_FLOAT: - variant->value.f = NK_CLAMP(variant->min_value.f, variant->value.f - variant->step.f, variant->max_value.f); break; - case NK_PROPERTY_DOUBLE: - variant->value.d = NK_CLAMP(variant->min_value.d, variant->value.d - variant->step.d, variant->max_value.d); break; - } - } - /* execute left button */ - if (nk_do_button_symbol(ws, out, right, style->sym_right, behavior, &style->inc_button, in, font)) { - switch (variant->kind) { - default: break; - case NK_PROPERTY_INT: - variant->value.i = NK_CLAMP(variant->min_value.i, variant->value.i + variant->step.i, variant->max_value.i); break; - case NK_PROPERTY_FLOAT: - variant->value.f = NK_CLAMP(variant->min_value.f, variant->value.f + variant->step.f, variant->max_value.f); break; - case NK_PROPERTY_DOUBLE: - variant->value.d = NK_CLAMP(variant->min_value.d, variant->value.d + variant->step.d, variant->max_value.d); break; - } - } - if (old != NK_PROPERTY_EDIT && (*state == NK_PROPERTY_EDIT)) { - /* property has been activated so setup buffer */ - NK_MEMCPY(buffer, dst, (nk_size)*length); - *cursor = nk_utf_len(buffer, *length); - *len = *length; - length = len; - dst = buffer; - active = 0; - } else active = (*state == NK_PROPERTY_EDIT); - - /* execute and run text edit field */ - nk_textedit_clear_state(text_edit, NK_TEXT_EDIT_SINGLE_LINE, filters[filter]); - text_edit->active = (unsigned char)active; - text_edit->string.len = *length; - text_edit->cursor = NK_CLAMP(0, *cursor, *length); - text_edit->select_start = NK_CLAMP(0,*select_begin, *length); - text_edit->select_end = NK_CLAMP(0,*select_end, *length); - text_edit->string.buffer.allocated = (nk_size)*length; - text_edit->string.buffer.memory.size = NK_MAX_NUMBER_BUFFER; - text_edit->string.buffer.memory.ptr = dst; - text_edit->string.buffer.size = NK_MAX_NUMBER_BUFFER; - text_edit->mode = NK_TEXT_EDIT_MODE_INSERT; - nk_do_edit(ws, out, edit, NK_EDIT_FIELD|NK_EDIT_AUTO_SELECT, - filters[filter], text_edit, &style->edit, (*state == NK_PROPERTY_EDIT) ? in: 0, font); - - *length = text_edit->string.len; - *cursor = text_edit->cursor; - *select_begin = text_edit->select_start; - *select_end = text_edit->select_end; - if (text_edit->active && nk_input_is_key_pressed(in, NK_KEY_ENTER)) - text_edit->active = nk_false; - - if (active && !text_edit->active) { - /* property is now not active so convert edit text to value*/ - *state = NK_PROPERTY_DEFAULT; - buffer[*len] = '\0'; - switch (variant->kind) { - default: break; - case NK_PROPERTY_INT: - variant->value.i = nk_strtoi(buffer, 0); - variant->value.i = NK_CLAMP(variant->min_value.i, variant->value.i, variant->max_value.i); - break; - case NK_PROPERTY_FLOAT: - nk_string_float_limit(buffer, NK_MAX_FLOAT_PRECISION); - variant->value.f = nk_strtof(buffer, 0); - variant->value.f = NK_CLAMP(variant->min_value.f, variant->value.f, variant->max_value.f); - break; - case NK_PROPERTY_DOUBLE: - nk_string_float_limit(buffer, NK_MAX_FLOAT_PRECISION); - variant->value.d = nk_strtod(buffer, 0); - variant->value.d = NK_CLAMP(variant->min_value.d, variant->value.d, variant->max_value.d); - break; - } - } -} -NK_LIB struct nk_property_variant -nk_property_variant_int(int value, int min_value, int max_value, int step) -{ - struct nk_property_variant result; - result.kind = NK_PROPERTY_INT; - result.value.i = value; - result.min_value.i = min_value; - result.max_value.i = max_value; - result.step.i = step; - return result; -} -NK_LIB struct nk_property_variant -nk_property_variant_float(float value, float min_value, float max_value, float step) -{ - struct nk_property_variant result; - result.kind = NK_PROPERTY_FLOAT; - result.value.f = value; - result.min_value.f = min_value; - result.max_value.f = max_value; - result.step.f = step; - return result; -} -NK_LIB struct nk_property_variant -nk_property_variant_double(double value, double min_value, double max_value, - double step) -{ - struct nk_property_variant result; - result.kind = NK_PROPERTY_DOUBLE; - result.value.d = value; - result.min_value.d = min_value; - result.max_value.d = max_value; - result.step.d = step; - return result; -} -NK_LIB void -nk_property(struct nk_context *ctx, const char *name, struct nk_property_variant *variant, - float inc_per_pixel, const enum nk_property_filter filter) -{ - struct nk_window *win; - struct nk_panel *layout; - struct nk_input *in; - const struct nk_style *style; - - struct nk_rect bounds; - enum nk_widget_layout_states s; - - int *state = 0; - nk_hash hash = 0; - char *buffer = 0; - int *len = 0; - int *cursor = 0; - int *select_begin = 0; - int *select_end = 0; - int old_state; - - char dummy_buffer[NK_MAX_NUMBER_BUFFER]; - int dummy_state = NK_PROPERTY_DEFAULT; - int dummy_length = 0; - int dummy_cursor = 0; - int dummy_select_begin = 0; - int dummy_select_end = 0; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return; - - win = ctx->current; - layout = win->layout; - style = &ctx->style; - s = nk_widget(&bounds, ctx); - if (!s) return; - - /* calculate hash from name */ - if (name[0] == '#') { - hash = nk_murmur_hash(name, (int)nk_strlen(name), win->property.seq++); - name++; /* special number hash */ - } else hash = nk_murmur_hash(name, (int)nk_strlen(name), 42); - - /* check if property is currently hot item */ - if (win->property.active && hash == win->property.name) { - buffer = win->property.buffer; - len = &win->property.length; - cursor = &win->property.cursor; - state = &win->property.state; - select_begin = &win->property.select_start; - select_end = &win->property.select_end; - } else { - buffer = dummy_buffer; - len = &dummy_length; - cursor = &dummy_cursor; - state = &dummy_state; - select_begin = &dummy_select_begin; - select_end = &dummy_select_end; - } - - /* execute property widget */ - old_state = *state; - ctx->text_edit.clip = ctx->clip; - in = ((s == NK_WIDGET_ROM && !win->property.active) || - layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; - nk_do_property(&ctx->last_widget_state, &win->buffer, bounds, name, - variant, inc_per_pixel, buffer, len, state, cursor, select_begin, - select_end, &style->property, filter, in, style->font, &ctx->text_edit, - ctx->button_behavior); - - if (in && *state != NK_PROPERTY_DEFAULT && !win->property.active) { - /* current property is now hot */ - win->property.active = 1; - NK_MEMCPY(win->property.buffer, buffer, (nk_size)*len); - win->property.length = *len; - win->property.cursor = *cursor; - win->property.state = *state; - win->property.name = hash; - win->property.select_start = *select_begin; - win->property.select_end = *select_end; - if (*state == NK_PROPERTY_DRAG) { - ctx->input.mouse.grab = nk_true; - ctx->input.mouse.grabbed = nk_true; - } - } - /* check if previously active property is now inactive */ - if (*state == NK_PROPERTY_DEFAULT && old_state != NK_PROPERTY_DEFAULT) { - if (old_state == NK_PROPERTY_DRAG) { - ctx->input.mouse.grab = nk_false; - ctx->input.mouse.grabbed = nk_false; - ctx->input.mouse.ungrab = nk_true; - } - win->property.select_start = 0; - win->property.select_end = 0; - win->property.active = 0; - } -} -NK_API void -nk_property_int(struct nk_context *ctx, const char *name, - int min, int *val, int max, int step, float inc_per_pixel) -{ - struct nk_property_variant variant; - NK_ASSERT(ctx); - NK_ASSERT(name); - NK_ASSERT(val); - - if (!ctx || !ctx->current || !name || !val) return; - variant = nk_property_variant_int(*val, min, max, step); - nk_property(ctx, name, &variant, inc_per_pixel, NK_FILTER_INT); - *val = variant.value.i; -} -NK_API void -nk_property_float(struct nk_context *ctx, const char *name, - float min, float *val, float max, float step, float inc_per_pixel) -{ - struct nk_property_variant variant; - NK_ASSERT(ctx); - NK_ASSERT(name); - NK_ASSERT(val); - - if (!ctx || !ctx->current || !name || !val) return; - variant = nk_property_variant_float(*val, min, max, step); - nk_property(ctx, name, &variant, inc_per_pixel, NK_FILTER_FLOAT); - *val = variant.value.f; -} -NK_API void -nk_property_double(struct nk_context *ctx, const char *name, - double min, double *val, double max, double step, float inc_per_pixel) -{ - struct nk_property_variant variant; - NK_ASSERT(ctx); - NK_ASSERT(name); - NK_ASSERT(val); - - if (!ctx || !ctx->current || !name || !val) return; - variant = nk_property_variant_double(*val, min, max, step); - nk_property(ctx, name, &variant, inc_per_pixel, NK_FILTER_FLOAT); - *val = variant.value.d; -} -NK_API int -nk_propertyi(struct nk_context *ctx, const char *name, int min, int val, - int max, int step, float inc_per_pixel) -{ - struct nk_property_variant variant; - NK_ASSERT(ctx); - NK_ASSERT(name); - - if (!ctx || !ctx->current || !name) return val; - variant = nk_property_variant_int(val, min, max, step); - nk_property(ctx, name, &variant, inc_per_pixel, NK_FILTER_INT); - val = variant.value.i; - return val; -} -NK_API float -nk_propertyf(struct nk_context *ctx, const char *name, float min, - float val, float max, float step, float inc_per_pixel) -{ - struct nk_property_variant variant; - NK_ASSERT(ctx); - NK_ASSERT(name); - - if (!ctx || !ctx->current || !name) return val; - variant = nk_property_variant_float(val, min, max, step); - nk_property(ctx, name, &variant, inc_per_pixel, NK_FILTER_FLOAT); - val = variant.value.f; - return val; -} -NK_API double -nk_propertyd(struct nk_context *ctx, const char *name, double min, - double val, double max, double step, float inc_per_pixel) -{ - struct nk_property_variant variant; - NK_ASSERT(ctx); - NK_ASSERT(name); - - if (!ctx || !ctx->current || !name) return val; - variant = nk_property_variant_double(val, min, max, step); - nk_property(ctx, name, &variant, inc_per_pixel, NK_FILTER_FLOAT); - val = variant.value.d; - return val; -} - - - - - -/* ============================================================== - * - * CHART - * - * ===============================================================*/ -NK_API int -nk_chart_begin_colored(struct nk_context *ctx, enum nk_chart_type type, - struct nk_color color, struct nk_color highlight, - int count, float min_value, float max_value) -{ - struct nk_window *win; - struct nk_chart *chart; - const struct nk_style *config; - const struct nk_style_chart *style; - - const struct nk_style_item *background; - struct nk_rect bounds = {0, 0, 0, 0}; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - - if (!ctx || !ctx->current || !ctx->current->layout) return 0; - if (!nk_widget(&bounds, ctx)) { - chart = &ctx->current->layout->chart; - nk_zero(chart, sizeof(*chart)); - return 0; - } - - win = ctx->current; - config = &ctx->style; - chart = &win->layout->chart; - style = &config->chart; - - /* setup basic generic chart */ - nk_zero(chart, sizeof(*chart)); - chart->x = bounds.x + style->padding.x; - chart->y = bounds.y + style->padding.y; - chart->w = bounds.w - 2 * style->padding.x; - chart->h = bounds.h - 2 * style->padding.y; - chart->w = NK_MAX(chart->w, 2 * style->padding.x); - chart->h = NK_MAX(chart->h, 2 * style->padding.y); - - /* add first slot into chart */ - {struct nk_chart_slot *slot = &chart->slots[chart->slot++]; - slot->type = type; - slot->count = count; - slot->color = color; - slot->highlight = highlight; - slot->min = NK_MIN(min_value, max_value); - slot->max = NK_MAX(min_value, max_value); - slot->range = slot->max - slot->min;} - - /* draw chart background */ - background = &style->background; - if (background->type == NK_STYLE_ITEM_IMAGE) { - nk_draw_image(&win->buffer, bounds, &background->data.image, nk_white); - } else { - nk_fill_rect(&win->buffer, bounds, style->rounding, style->border_color); - nk_fill_rect(&win->buffer, nk_shrink_rect(bounds, style->border), - style->rounding, style->background.data.color); - } - return 1; -} -NK_API int -nk_chart_begin(struct nk_context *ctx, const enum nk_chart_type type, - int count, float min_value, float max_value) -{ - return nk_chart_begin_colored(ctx, type, ctx->style.chart.color, - ctx->style.chart.selected_color, count, min_value, max_value); -} -NK_API void -nk_chart_add_slot_colored(struct nk_context *ctx, const enum nk_chart_type type, - struct nk_color color, struct nk_color highlight, - int count, float min_value, float max_value) -{ - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - NK_ASSERT(ctx->current->layout->chart.slot < NK_CHART_MAX_SLOT); - if (!ctx || !ctx->current || !ctx->current->layout) return; - if (ctx->current->layout->chart.slot >= NK_CHART_MAX_SLOT) return; - - /* add another slot into the graph */ - {struct nk_chart *chart = &ctx->current->layout->chart; - struct nk_chart_slot *slot = &chart->slots[chart->slot++]; - slot->type = type; - slot->count = count; - slot->color = color; - slot->highlight = highlight; - slot->min = NK_MIN(min_value, max_value); - slot->max = NK_MAX(min_value, max_value); - slot->range = slot->max - slot->min;} -} -NK_API void -nk_chart_add_slot(struct nk_context *ctx, const enum nk_chart_type type, - int count, float min_value, float max_value) -{ - nk_chart_add_slot_colored(ctx, type, ctx->style.chart.color, - ctx->style.chart.selected_color, count, min_value, max_value); -} -NK_INTERN nk_flags -nk_chart_push_line(struct nk_context *ctx, struct nk_window *win, - struct nk_chart *g, float value, int slot) -{ - struct nk_panel *layout = win->layout; - const struct nk_input *i = &ctx->input; - struct nk_command_buffer *out = &win->buffer; - - nk_flags ret = 0; - struct nk_vec2 cur; - struct nk_rect bounds; - struct nk_color color; - float step; - float range; - float ratio; - - NK_ASSERT(slot >= 0 && slot < NK_CHART_MAX_SLOT); - step = g->w / (float)g->slots[slot].count; - range = g->slots[slot].max - g->slots[slot].min; - ratio = (value - g->slots[slot].min) / range; - - if (g->slots[slot].index == 0) { - /* first data point does not have a connection */ - g->slots[slot].last.x = g->x; - g->slots[slot].last.y = (g->y + g->h) - ratio * (float)g->h; - - bounds.x = g->slots[slot].last.x - 2; - bounds.y = g->slots[slot].last.y - 2; - bounds.w = bounds.h = 4; - - color = g->slots[slot].color; - if (!(layout->flags & NK_WINDOW_ROM) && - NK_INBOX(i->mouse.pos.x,i->mouse.pos.y, g->slots[slot].last.x-3, g->slots[slot].last.y-3, 6, 6)){ - ret = nk_input_is_mouse_hovering_rect(i, bounds) ? NK_CHART_HOVERING : 0; - ret |= (i->mouse.buttons[NK_BUTTON_LEFT].down && - i->mouse.buttons[NK_BUTTON_LEFT].clicked) ? NK_CHART_CLICKED: 0; - color = g->slots[slot].highlight; - } - nk_fill_rect(out, bounds, 0, color); - g->slots[slot].index += 1; - return ret; - } - - /* draw a line between the last data point and the new one */ - color = g->slots[slot].color; - cur.x = g->x + (float)(step * (float)g->slots[slot].index); - cur.y = (g->y + g->h) - (ratio * (float)g->h); - nk_stroke_line(out, g->slots[slot].last.x, g->slots[slot].last.y, cur.x, cur.y, 1.0f, color); - - bounds.x = cur.x - 3; - bounds.y = cur.y - 3; - bounds.w = bounds.h = 6; - - /* user selection of current data point */ - if (!(layout->flags & NK_WINDOW_ROM)) { - if (nk_input_is_mouse_hovering_rect(i, bounds)) { - ret = NK_CHART_HOVERING; - ret |= (!i->mouse.buttons[NK_BUTTON_LEFT].down && - i->mouse.buttons[NK_BUTTON_LEFT].clicked) ? NK_CHART_CLICKED: 0; - color = g->slots[slot].highlight; - } - } - nk_fill_rect(out, nk_rect(cur.x - 2, cur.y - 2, 4, 4), 0, color); - - /* save current data point position */ - g->slots[slot].last.x = cur.x; - g->slots[slot].last.y = cur.y; - g->slots[slot].index += 1; - return ret; -} -NK_INTERN nk_flags -nk_chart_push_column(const struct nk_context *ctx, struct nk_window *win, - struct nk_chart *chart, float value, int slot) -{ - struct nk_command_buffer *out = &win->buffer; - const struct nk_input *in = &ctx->input; - struct nk_panel *layout = win->layout; - - float ratio; - nk_flags ret = 0; - struct nk_color color; - struct nk_rect item = {0,0,0,0}; - - NK_ASSERT(slot >= 0 && slot < NK_CHART_MAX_SLOT); - if (chart->slots[slot].index >= chart->slots[slot].count) - return nk_false; - if (chart->slots[slot].count) { - float padding = (float)(chart->slots[slot].count-1); - item.w = (chart->w - padding) / (float)(chart->slots[slot].count); - } - - /* calculate bounds of current bar chart entry */ - color = chart->slots[slot].color;; - item.h = chart->h * NK_ABS((value/chart->slots[slot].range)); - if (value >= 0) { - ratio = (value + NK_ABS(chart->slots[slot].min)) / NK_ABS(chart->slots[slot].range); - item.y = (chart->y + chart->h) - chart->h * ratio; - } else { - ratio = (value - chart->slots[slot].max) / chart->slots[slot].range; - item.y = chart->y + (chart->h * NK_ABS(ratio)) - item.h; - } - item.x = chart->x + ((float)chart->slots[slot].index * item.w); - item.x = item.x + ((float)chart->slots[slot].index); - - /* user chart bar selection */ - if (!(layout->flags & NK_WINDOW_ROM) && - NK_INBOX(in->mouse.pos.x,in->mouse.pos.y,item.x,item.y,item.w,item.h)) { - ret = NK_CHART_HOVERING; - ret |= (!in->mouse.buttons[NK_BUTTON_LEFT].down && - in->mouse.buttons[NK_BUTTON_LEFT].clicked) ? NK_CHART_CLICKED: 0; - color = chart->slots[slot].highlight; - } - nk_fill_rect(out, item, 0, color); - chart->slots[slot].index += 1; - return ret; -} -NK_API nk_flags -nk_chart_push_slot(struct nk_context *ctx, float value, int slot) -{ - nk_flags flags; - struct nk_window *win; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(slot >= 0 && slot < NK_CHART_MAX_SLOT); - NK_ASSERT(slot < ctx->current->layout->chart.slot); - if (!ctx || !ctx->current || slot >= NK_CHART_MAX_SLOT) return nk_false; - if (slot >= ctx->current->layout->chart.slot) return nk_false; - - win = ctx->current; - if (win->layout->chart.slot < slot) return nk_false; - switch (win->layout->chart.slots[slot].type) { - case NK_CHART_LINES: - flags = nk_chart_push_line(ctx, win, &win->layout->chart, value, slot); break; - case NK_CHART_COLUMN: - flags = nk_chart_push_column(ctx, win, &win->layout->chart, value, slot); break; - default: - case NK_CHART_MAX: - flags = 0; - } - return flags; -} -NK_API nk_flags -nk_chart_push(struct nk_context *ctx, float value) -{ - return nk_chart_push_slot(ctx, value, 0); -} -NK_API void -nk_chart_end(struct nk_context *ctx) -{ - struct nk_window *win; - struct nk_chart *chart; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - if (!ctx || !ctx->current) - return; - - win = ctx->current; - chart = &win->layout->chart; - NK_MEMSET(chart, 0, sizeof(*chart)); - return; -} -NK_API void -nk_plot(struct nk_context *ctx, enum nk_chart_type type, const float *values, - int count, int offset) -{ - int i = 0; - float min_value; - float max_value; - - NK_ASSERT(ctx); - NK_ASSERT(values); - if (!ctx || !values || !count) return; - - min_value = values[offset]; - max_value = values[offset]; - for (i = 0; i < count; ++i) { - min_value = NK_MIN(values[i + offset], min_value); - max_value = NK_MAX(values[i + offset], max_value); - } - - if (nk_chart_begin(ctx, type, count, min_value, max_value)) { - for (i = 0; i < count; ++i) - nk_chart_push(ctx, values[i + offset]); - nk_chart_end(ctx); - } -} -NK_API void -nk_plot_function(struct nk_context *ctx, enum nk_chart_type type, void *userdata, - float(*value_getter)(void* user, int index), int count, int offset) -{ - int i = 0; - float min_value; - float max_value; - - NK_ASSERT(ctx); - NK_ASSERT(value_getter); - if (!ctx || !value_getter || !count) return; - - max_value = min_value = value_getter(userdata, offset); - for (i = 0; i < count; ++i) { - float value = value_getter(userdata, i + offset); - min_value = NK_MIN(value, min_value); - max_value = NK_MAX(value, max_value); - } - - if (nk_chart_begin(ctx, type, count, min_value, max_value)) { - for (i = 0; i < count; ++i) - nk_chart_push(ctx, value_getter(userdata, i + offset)); - nk_chart_end(ctx); - } -} - - - - - -/* ============================================================== - * - * COLOR PICKER - * - * ===============================================================*/ -NK_LIB int -nk_color_picker_behavior(nk_flags *state, - const struct nk_rect *bounds, const struct nk_rect *matrix, - const struct nk_rect *hue_bar, const struct nk_rect *alpha_bar, - struct nk_colorf *color, const struct nk_input *in) -{ - float hsva[4]; - int value_changed = 0; - int hsv_changed = 0; - - NK_ASSERT(state); - NK_ASSERT(matrix); - NK_ASSERT(hue_bar); - NK_ASSERT(color); - - /* color matrix */ - nk_colorf_hsva_fv(hsva, *color); - if (nk_button_behavior(state, *matrix, in, NK_BUTTON_REPEATER)) { - hsva[1] = NK_SATURATE((in->mouse.pos.x - matrix->x) / (matrix->w-1)); - hsva[2] = 1.0f - NK_SATURATE((in->mouse.pos.y - matrix->y) / (matrix->h-1)); - value_changed = hsv_changed = 1; - } - /* hue bar */ - if (nk_button_behavior(state, *hue_bar, in, NK_BUTTON_REPEATER)) { - hsva[0] = NK_SATURATE((in->mouse.pos.y - hue_bar->y) / (hue_bar->h-1)); - value_changed = hsv_changed = 1; - } - /* alpha bar */ - if (alpha_bar) { - if (nk_button_behavior(state, *alpha_bar, in, NK_BUTTON_REPEATER)) { - hsva[3] = 1.0f - NK_SATURATE((in->mouse.pos.y - alpha_bar->y) / (alpha_bar->h-1)); - value_changed = 1; - } - } - nk_widget_state_reset(state); - if (hsv_changed) { - *color = nk_hsva_colorfv(hsva); - *state = NK_WIDGET_STATE_ACTIVE; - } - if (value_changed) { - color->a = hsva[3]; - *state = NK_WIDGET_STATE_ACTIVE; - } - /* set color picker widget state */ - if (nk_input_is_mouse_hovering_rect(in, *bounds)) - *state = NK_WIDGET_STATE_HOVERED; - if (*state & NK_WIDGET_STATE_HOVER && !nk_input_is_mouse_prev_hovering_rect(in, *bounds)) - *state |= NK_WIDGET_STATE_ENTERED; - else if (nk_input_is_mouse_prev_hovering_rect(in, *bounds)) - *state |= NK_WIDGET_STATE_LEFT; - return value_changed; -} -NK_LIB void -nk_draw_color_picker(struct nk_command_buffer *o, const struct nk_rect *matrix, - const struct nk_rect *hue_bar, const struct nk_rect *alpha_bar, - struct nk_colorf col) -{ - NK_STORAGE const struct nk_color black = {0,0,0,255}; - NK_STORAGE const struct nk_color white = {255, 255, 255, 255}; - NK_STORAGE const struct nk_color black_trans = {0,0,0,0}; - - const float crosshair_size = 7.0f; - struct nk_color temp; - float hsva[4]; - float line_y; - int i; - - NK_ASSERT(o); - NK_ASSERT(matrix); - NK_ASSERT(hue_bar); - - /* draw hue bar */ - nk_colorf_hsva_fv(hsva, col); - for (i = 0; i < 6; ++i) { - NK_GLOBAL const struct nk_color hue_colors[] = { - {255, 0, 0, 255}, {255,255,0,255}, {0,255,0,255}, {0, 255,255,255}, - {0,0,255,255}, {255, 0, 255, 255}, {255, 0, 0, 255} - }; - nk_fill_rect_multi_color(o, - nk_rect(hue_bar->x, hue_bar->y + (float)i * (hue_bar->h/6.0f) + 0.5f, - hue_bar->w, (hue_bar->h/6.0f) + 0.5f), hue_colors[i], hue_colors[i], - hue_colors[i+1], hue_colors[i+1]); - } - line_y = (float)(int)(hue_bar->y + hsva[0] * matrix->h + 0.5f); - nk_stroke_line(o, hue_bar->x-1, line_y, hue_bar->x + hue_bar->w + 2, - line_y, 1, nk_rgb(255,255,255)); - - /* draw alpha bar */ - if (alpha_bar) { - float alpha = NK_SATURATE(col.a); - line_y = (float)(int)(alpha_bar->y + (1.0f - alpha) * matrix->h + 0.5f); - - nk_fill_rect_multi_color(o, *alpha_bar, white, white, black, black); - nk_stroke_line(o, alpha_bar->x-1, line_y, alpha_bar->x + alpha_bar->w + 2, - line_y, 1, nk_rgb(255,255,255)); - } - - /* draw color matrix */ - temp = nk_hsv_f(hsva[0], 1.0f, 1.0f); - nk_fill_rect_multi_color(o, *matrix, white, temp, temp, white); - nk_fill_rect_multi_color(o, *matrix, black_trans, black_trans, black, black); - - /* draw cross-hair */ - {struct nk_vec2 p; float S = hsva[1]; float V = hsva[2]; - p.x = (float)(int)(matrix->x + S * matrix->w); - p.y = (float)(int)(matrix->y + (1.0f - V) * matrix->h); - nk_stroke_line(o, p.x - crosshair_size, p.y, p.x-2, p.y, 1.0f, white); - nk_stroke_line(o, p.x + crosshair_size + 1, p.y, p.x+3, p.y, 1.0f, white); - nk_stroke_line(o, p.x, p.y + crosshair_size + 1, p.x, p.y+3, 1.0f, white); - nk_stroke_line(o, p.x, p.y - crosshair_size, p.x, p.y-2, 1.0f, white);} -} -NK_LIB int -nk_do_color_picker(nk_flags *state, - struct nk_command_buffer *out, struct nk_colorf *col, - enum nk_color_format fmt, struct nk_rect bounds, - struct nk_vec2 padding, const struct nk_input *in, - const struct nk_user_font *font) -{ - int ret = 0; - struct nk_rect matrix; - struct nk_rect hue_bar; - struct nk_rect alpha_bar; - float bar_w; - - NK_ASSERT(out); - NK_ASSERT(col); - NK_ASSERT(state); - NK_ASSERT(font); - if (!out || !col || !state || !font) - return ret; - - bar_w = font->height; - bounds.x += padding.x; - bounds.y += padding.x; - bounds.w -= 2 * padding.x; - bounds.h -= 2 * padding.y; - - matrix.x = bounds.x; - matrix.y = bounds.y; - matrix.h = bounds.h; - matrix.w = bounds.w - (3 * padding.x + 2 * bar_w); - - hue_bar.w = bar_w; - hue_bar.y = bounds.y; - hue_bar.h = matrix.h; - hue_bar.x = matrix.x + matrix.w + padding.x; - - alpha_bar.x = hue_bar.x + hue_bar.w + padding.x; - alpha_bar.y = bounds.y; - alpha_bar.w = bar_w; - alpha_bar.h = matrix.h; - - ret = nk_color_picker_behavior(state, &bounds, &matrix, &hue_bar, - (fmt == NK_RGBA) ? &alpha_bar:0, col, in); - nk_draw_color_picker(out, &matrix, &hue_bar, (fmt == NK_RGBA) ? &alpha_bar:0, *col); - return ret; -} -NK_API int -nk_color_pick(struct nk_context * ctx, struct nk_colorf *color, - enum nk_color_format fmt) -{ - struct nk_window *win; - struct nk_panel *layout; - const struct nk_style *config; - const struct nk_input *in; - - enum nk_widget_layout_states state; - struct nk_rect bounds; - - NK_ASSERT(ctx); - NK_ASSERT(color); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout || !color) - return 0; - - win = ctx->current; - config = &ctx->style; - layout = win->layout; - state = nk_widget(&bounds, ctx); - if (!state) return 0; - in = (state == NK_WIDGET_ROM || layout->flags & NK_WINDOW_ROM) ? 0 : &ctx->input; - return nk_do_color_picker(&ctx->last_widget_state, &win->buffer, color, fmt, bounds, - nk_vec2(0,0), in, config->font); -} -NK_API struct nk_colorf -nk_color_picker(struct nk_context *ctx, struct nk_colorf color, - enum nk_color_format fmt) -{ - nk_color_pick(ctx, &color, fmt); - return color; -} - - - - - -/* ============================================================== - * - * COMBO - * - * ===============================================================*/ -NK_INTERN int -nk_combo_begin(struct nk_context *ctx, struct nk_window *win, - struct nk_vec2 size, int is_clicked, struct nk_rect header) -{ - struct nk_window *popup; - int is_open = 0; - int is_active = 0; - struct nk_rect body; - nk_hash hash; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return 0; - - popup = win->popup.win; - body.x = header.x; - body.w = size.x; - body.y = header.y + header.h-ctx->style.window.combo_border; - body.h = size.y; - - hash = win->popup.combo_count++; - is_open = (popup) ? nk_true:nk_false; - is_active = (popup && (win->popup.name == hash) && win->popup.type == NK_PANEL_COMBO); - if ((is_clicked && is_open && !is_active) || (is_open && !is_active) || - (!is_open && !is_active && !is_clicked)) return 0; - if (!nk_nonblock_begin(ctx, 0, body, - (is_clicked && is_open)?nk_rect(0,0,0,0):header, NK_PANEL_COMBO)) return 0; - - win->popup.type = NK_PANEL_COMBO; - win->popup.name = hash; - return 1; -} -NK_API int -nk_combo_begin_text(struct nk_context *ctx, const char *selected, int len, - struct nk_vec2 size) -{ - const struct nk_input *in; - struct nk_window *win; - struct nk_style *style; - - enum nk_widget_layout_states s; - int is_clicked = nk_false; - struct nk_rect header; - const struct nk_style_item *background; - struct nk_text text; - - NK_ASSERT(ctx); - NK_ASSERT(selected); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout || !selected) - return 0; - - win = ctx->current; - style = &ctx->style; - s = nk_widget(&header, ctx); - if (s == NK_WIDGET_INVALID) - return 0; - - in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_ROM)? 0: &ctx->input; - if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT)) - is_clicked = nk_true; - - /* draw combo box header background and border */ - if (ctx->last_widget_state & NK_WIDGET_STATE_ACTIVED) { - background = &style->combo.active; - text.text = style->combo.label_active; - } else if (ctx->last_widget_state & NK_WIDGET_STATE_HOVER) { - background = &style->combo.hover; - text.text = style->combo.label_hover; - } else { - background = &style->combo.normal; - text.text = style->combo.label_normal; - } - if (background->type == NK_STYLE_ITEM_IMAGE) { - text.background = nk_rgba(0,0,0,0); - nk_draw_image(&win->buffer, header, &background->data.image, nk_white); - } else { - text.background = background->data.color; - nk_fill_rect(&win->buffer, header, style->combo.rounding, background->data.color); - nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, style->combo.border_color); - } - { - /* print currently selected text item */ - struct nk_rect label; - struct nk_rect button; - struct nk_rect content; - - enum nk_symbol_type sym; - if (ctx->last_widget_state & NK_WIDGET_STATE_HOVER) - sym = style->combo.sym_hover; - else if (is_clicked) - sym = style->combo.sym_active; - else sym = style->combo.sym_normal; - - /* calculate button */ - button.w = header.h - 2 * style->combo.button_padding.y; - button.x = (header.x + header.w - header.h) - style->combo.button_padding.x; - button.y = header.y + style->combo.button_padding.y; - button.h = button.w; - - content.x = button.x + style->combo.button.padding.x; - content.y = button.y + style->combo.button.padding.y; - content.w = button.w - 2 * style->combo.button.padding.x; - content.h = button.h - 2 * style->combo.button.padding.y; - - /* draw selected label */ - text.padding = nk_vec2(0,0); - label.x = header.x + style->combo.content_padding.x; - label.y = header.y + style->combo.content_padding.y; - label.w = button.x - (style->combo.content_padding.x + style->combo.spacing.x) - label.x;; - label.h = header.h - 2 * style->combo.content_padding.y; - nk_widget_text(&win->buffer, label, selected, len, &text, - NK_TEXT_LEFT, ctx->style.font); - - /* draw open/close button */ - nk_draw_button_symbol(&win->buffer, &button, &content, ctx->last_widget_state, - &ctx->style.combo.button, sym, style->font); - } - return nk_combo_begin(ctx, win, size, is_clicked, header); -} -NK_API int -nk_combo_begin_label(struct nk_context *ctx, const char *selected, struct nk_vec2 size) -{ - return nk_combo_begin_text(ctx, selected, nk_strlen(selected), size); -} -NK_API int -nk_combo_begin_color(struct nk_context *ctx, struct nk_color color, struct nk_vec2 size) -{ - struct nk_window *win; - struct nk_style *style; - const struct nk_input *in; - - struct nk_rect header; - int is_clicked = nk_false; - enum nk_widget_layout_states s; - const struct nk_style_item *background; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return 0; - - win = ctx->current; - style = &ctx->style; - s = nk_widget(&header, ctx); - if (s == NK_WIDGET_INVALID) - return 0; - - in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_ROM)? 0: &ctx->input; - if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT)) - is_clicked = nk_true; - - /* draw combo box header background and border */ - if (ctx->last_widget_state & NK_WIDGET_STATE_ACTIVED) - background = &style->combo.active; - else if (ctx->last_widget_state & NK_WIDGET_STATE_HOVER) - background = &style->combo.hover; - else background = &style->combo.normal; - - if (background->type == NK_STYLE_ITEM_IMAGE) { - nk_draw_image(&win->buffer, header, &background->data.image,nk_white); - } else { - nk_fill_rect(&win->buffer, header, style->combo.rounding, background->data.color); - nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, style->combo.border_color); - } - { - struct nk_rect content; - struct nk_rect button; - struct nk_rect bounds; - - enum nk_symbol_type sym; - if (ctx->last_widget_state & NK_WIDGET_STATE_HOVER) - sym = style->combo.sym_hover; - else if (is_clicked) - sym = style->combo.sym_active; - else sym = style->combo.sym_normal; - - /* calculate button */ - button.w = header.h - 2 * style->combo.button_padding.y; - button.x = (header.x + header.w - header.h) - style->combo.button_padding.x; - button.y = header.y + style->combo.button_padding.y; - button.h = button.w; - - content.x = button.x + style->combo.button.padding.x; - content.y = button.y + style->combo.button.padding.y; - content.w = button.w - 2 * style->combo.button.padding.x; - content.h = button.h - 2 * style->combo.button.padding.y; - - /* draw color */ - bounds.h = header.h - 4 * style->combo.content_padding.y; - bounds.y = header.y + 2 * style->combo.content_padding.y; - bounds.x = header.x + 2 * style->combo.content_padding.x; - bounds.w = (button.x - (style->combo.content_padding.x + style->combo.spacing.x)) - bounds.x; - nk_fill_rect(&win->buffer, bounds, 0, color); - - /* draw open/close button */ - nk_draw_button_symbol(&win->buffer, &button, &content, ctx->last_widget_state, - &ctx->style.combo.button, sym, style->font); - } - return nk_combo_begin(ctx, win, size, is_clicked, header); -} -NK_API int -nk_combo_begin_symbol(struct nk_context *ctx, enum nk_symbol_type symbol, struct nk_vec2 size) -{ - struct nk_window *win; - struct nk_style *style; - const struct nk_input *in; - - struct nk_rect header; - int is_clicked = nk_false; - enum nk_widget_layout_states s; - const struct nk_style_item *background; - struct nk_color sym_background; - struct nk_color symbol_color; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return 0; - - win = ctx->current; - style = &ctx->style; - s = nk_widget(&header, ctx); - if (s == NK_WIDGET_INVALID) - return 0; - - in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_ROM)? 0: &ctx->input; - if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT)) - is_clicked = nk_true; - - /* draw combo box header background and border */ - if (ctx->last_widget_state & NK_WIDGET_STATE_ACTIVED) { - background = &style->combo.active; - symbol_color = style->combo.symbol_active; - } else if (ctx->last_widget_state & NK_WIDGET_STATE_HOVER) { - background = &style->combo.hover; - symbol_color = style->combo.symbol_hover; - } else { - background = &style->combo.normal; - symbol_color = style->combo.symbol_hover; - } - - if (background->type == NK_STYLE_ITEM_IMAGE) { - sym_background = nk_rgba(0,0,0,0); - nk_draw_image(&win->buffer, header, &background->data.image, nk_white); - } else { - sym_background = background->data.color; - nk_fill_rect(&win->buffer, header, style->combo.rounding, background->data.color); - nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, style->combo.border_color); - } - { - struct nk_rect bounds = {0,0,0,0}; - struct nk_rect content; - struct nk_rect button; - - enum nk_symbol_type sym; - if (ctx->last_widget_state & NK_WIDGET_STATE_HOVER) - sym = style->combo.sym_hover; - else if (is_clicked) - sym = style->combo.sym_active; - else sym = style->combo.sym_normal; - - /* calculate button */ - button.w = header.h - 2 * style->combo.button_padding.y; - button.x = (header.x + header.w - header.h) - style->combo.button_padding.y; - button.y = header.y + style->combo.button_padding.y; - button.h = button.w; - - content.x = button.x + style->combo.button.padding.x; - content.y = button.y + style->combo.button.padding.y; - content.w = button.w - 2 * style->combo.button.padding.x; - content.h = button.h - 2 * style->combo.button.padding.y; - - /* draw symbol */ - bounds.h = header.h - 2 * style->combo.content_padding.y; - bounds.y = header.y + style->combo.content_padding.y; - bounds.x = header.x + style->combo.content_padding.x; - bounds.w = (button.x - style->combo.content_padding.y) - bounds.x; - nk_draw_symbol(&win->buffer, symbol, bounds, sym_background, symbol_color, - 1.0f, style->font); - - /* draw open/close button */ - nk_draw_button_symbol(&win->buffer, &bounds, &content, ctx->last_widget_state, - &ctx->style.combo.button, sym, style->font); - } - return nk_combo_begin(ctx, win, size, is_clicked, header); -} -NK_API int -nk_combo_begin_symbol_text(struct nk_context *ctx, const char *selected, int len, - enum nk_symbol_type symbol, struct nk_vec2 size) -{ - struct nk_window *win; - struct nk_style *style; - struct nk_input *in; - - struct nk_rect header; - int is_clicked = nk_false; - enum nk_widget_layout_states s; - const struct nk_style_item *background; - struct nk_color symbol_color; - struct nk_text text; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return 0; - - win = ctx->current; - style = &ctx->style; - s = nk_widget(&header, ctx); - if (!s) return 0; - - in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_ROM)? 0: &ctx->input; - if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT)) - is_clicked = nk_true; - - /* draw combo box header background and border */ - if (ctx->last_widget_state & NK_WIDGET_STATE_ACTIVED) { - background = &style->combo.active; - symbol_color = style->combo.symbol_active; - text.text = style->combo.label_active; - } else if (ctx->last_widget_state & NK_WIDGET_STATE_HOVER) { - background = &style->combo.hover; - symbol_color = style->combo.symbol_hover; - text.text = style->combo.label_hover; - } else { - background = &style->combo.normal; - symbol_color = style->combo.symbol_normal; - text.text = style->combo.label_normal; - } - if (background->type == NK_STYLE_ITEM_IMAGE) { - text.background = nk_rgba(0,0,0,0); - nk_draw_image(&win->buffer, header, &background->data.image, nk_white); - } else { - text.background = background->data.color; - nk_fill_rect(&win->buffer, header, style->combo.rounding, background->data.color); - nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, style->combo.border_color); - } - { - struct nk_rect content; - struct nk_rect button; - struct nk_rect label; - struct nk_rect image; - - enum nk_symbol_type sym; - if (ctx->last_widget_state & NK_WIDGET_STATE_HOVER) - sym = style->combo.sym_hover; - else if (is_clicked) - sym = style->combo.sym_active; - else sym = style->combo.sym_normal; - - /* calculate button */ - button.w = header.h - 2 * style->combo.button_padding.y; - button.x = (header.x + header.w - header.h) - style->combo.button_padding.x; - button.y = header.y + style->combo.button_padding.y; - button.h = button.w; - - content.x = button.x + style->combo.button.padding.x; - content.y = button.y + style->combo.button.padding.y; - content.w = button.w - 2 * style->combo.button.padding.x; - content.h = button.h - 2 * style->combo.button.padding.y; - nk_draw_button_symbol(&win->buffer, &button, &content, ctx->last_widget_state, - &ctx->style.combo.button, sym, style->font); - - /* draw symbol */ - image.x = header.x + style->combo.content_padding.x; - image.y = header.y + style->combo.content_padding.y; - image.h = header.h - 2 * style->combo.content_padding.y; - image.w = image.h; - nk_draw_symbol(&win->buffer, symbol, image, text.background, symbol_color, - 1.0f, style->font); - - /* draw label */ - text.padding = nk_vec2(0,0); - label.x = image.x + image.w + style->combo.spacing.x + style->combo.content_padding.x; - label.y = header.y + style->combo.content_padding.y; - label.w = (button.x - style->combo.content_padding.x) - label.x; - label.h = header.h - 2 * style->combo.content_padding.y; - nk_widget_text(&win->buffer, label, selected, len, &text, NK_TEXT_LEFT, style->font); - } - return nk_combo_begin(ctx, win, size, is_clicked, header); -} -NK_API int -nk_combo_begin_image(struct nk_context *ctx, struct nk_image img, struct nk_vec2 size) -{ - struct nk_window *win; - struct nk_style *style; - const struct nk_input *in; - - struct nk_rect header; - int is_clicked = nk_false; - enum nk_widget_layout_states s; - const struct nk_style_item *background; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return 0; - - win = ctx->current; - style = &ctx->style; - s = nk_widget(&header, ctx); - if (s == NK_WIDGET_INVALID) - return 0; - - in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_ROM)? 0: &ctx->input; - if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT)) - is_clicked = nk_true; - - /* draw combo box header background and border */ - if (ctx->last_widget_state & NK_WIDGET_STATE_ACTIVED) - background = &style->combo.active; - else if (ctx->last_widget_state & NK_WIDGET_STATE_HOVER) - background = &style->combo.hover; - else background = &style->combo.normal; - - if (background->type == NK_STYLE_ITEM_IMAGE) { - nk_draw_image(&win->buffer, header, &background->data.image, nk_white); - } else { - nk_fill_rect(&win->buffer, header, style->combo.rounding, background->data.color); - nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, style->combo.border_color); - } - { - struct nk_rect bounds = {0,0,0,0}; - struct nk_rect content; - struct nk_rect button; - - enum nk_symbol_type sym; - if (ctx->last_widget_state & NK_WIDGET_STATE_HOVER) - sym = style->combo.sym_hover; - else if (is_clicked) - sym = style->combo.sym_active; - else sym = style->combo.sym_normal; - - /* calculate button */ - button.w = header.h - 2 * style->combo.button_padding.y; - button.x = (header.x + header.w - header.h) - style->combo.button_padding.y; - button.y = header.y + style->combo.button_padding.y; - button.h = button.w; - - content.x = button.x + style->combo.button.padding.x; - content.y = button.y + style->combo.button.padding.y; - content.w = button.w - 2 * style->combo.button.padding.x; - content.h = button.h - 2 * style->combo.button.padding.y; - - /* draw image */ - bounds.h = header.h - 2 * style->combo.content_padding.y; - bounds.y = header.y + style->combo.content_padding.y; - bounds.x = header.x + style->combo.content_padding.x; - bounds.w = (button.x - style->combo.content_padding.y) - bounds.x; - nk_draw_image(&win->buffer, bounds, &img, nk_white); - - /* draw open/close button */ - nk_draw_button_symbol(&win->buffer, &bounds, &content, ctx->last_widget_state, - &ctx->style.combo.button, sym, style->font); - } - return nk_combo_begin(ctx, win, size, is_clicked, header); -} -NK_API int -nk_combo_begin_image_text(struct nk_context *ctx, const char *selected, int len, - struct nk_image img, struct nk_vec2 size) -{ - struct nk_window *win; - struct nk_style *style; - struct nk_input *in; - - struct nk_rect header; - int is_clicked = nk_false; - enum nk_widget_layout_states s; - const struct nk_style_item *background; - struct nk_text text; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return 0; - - win = ctx->current; - style = &ctx->style; - s = nk_widget(&header, ctx); - if (!s) return 0; - - in = (win->layout->flags & NK_WINDOW_ROM || s == NK_WIDGET_ROM)? 0: &ctx->input; - if (nk_button_behavior(&ctx->last_widget_state, header, in, NK_BUTTON_DEFAULT)) - is_clicked = nk_true; - - /* draw combo box header background and border */ - if (ctx->last_widget_state & NK_WIDGET_STATE_ACTIVED) { - background = &style->combo.active; - text.text = style->combo.label_active; - } else if (ctx->last_widget_state & NK_WIDGET_STATE_HOVER) { - background = &style->combo.hover; - text.text = style->combo.label_hover; - } else { - background = &style->combo.normal; - text.text = style->combo.label_normal; - } - if (background->type == NK_STYLE_ITEM_IMAGE) { - text.background = nk_rgba(0,0,0,0); - nk_draw_image(&win->buffer, header, &background->data.image, nk_white); - } else { - text.background = background->data.color; - nk_fill_rect(&win->buffer, header, style->combo.rounding, background->data.color); - nk_stroke_rect(&win->buffer, header, style->combo.rounding, style->combo.border, style->combo.border_color); - } - { - struct nk_rect content; - struct nk_rect button; - struct nk_rect label; - struct nk_rect image; - - enum nk_symbol_type sym; - if (ctx->last_widget_state & NK_WIDGET_STATE_HOVER) - sym = style->combo.sym_hover; - else if (is_clicked) - sym = style->combo.sym_active; - else sym = style->combo.sym_normal; - - /* calculate button */ - button.w = header.h - 2 * style->combo.button_padding.y; - button.x = (header.x + header.w - header.h) - style->combo.button_padding.x; - button.y = header.y + style->combo.button_padding.y; - button.h = button.w; - - content.x = button.x + style->combo.button.padding.x; - content.y = button.y + style->combo.button.padding.y; - content.w = button.w - 2 * style->combo.button.padding.x; - content.h = button.h - 2 * style->combo.button.padding.y; - nk_draw_button_symbol(&win->buffer, &button, &content, ctx->last_widget_state, - &ctx->style.combo.button, sym, style->font); - - /* draw image */ - image.x = header.x + style->combo.content_padding.x; - image.y = header.y + style->combo.content_padding.y; - image.h = header.h - 2 * style->combo.content_padding.y; - image.w = image.h; - nk_draw_image(&win->buffer, image, &img, nk_white); - - /* draw label */ - text.padding = nk_vec2(0,0); - label.x = image.x + image.w + style->combo.spacing.x + style->combo.content_padding.x; - label.y = header.y + style->combo.content_padding.y; - label.w = (button.x - style->combo.content_padding.x) - label.x; - label.h = header.h - 2 * style->combo.content_padding.y; - nk_widget_text(&win->buffer, label, selected, len, &text, NK_TEXT_LEFT, style->font); - } - return nk_combo_begin(ctx, win, size, is_clicked, header); -} -NK_API int -nk_combo_begin_symbol_label(struct nk_context *ctx, - const char *selected, enum nk_symbol_type type, struct nk_vec2 size) -{ - return nk_combo_begin_symbol_text(ctx, selected, nk_strlen(selected), type, size); -} -NK_API int -nk_combo_begin_image_label(struct nk_context *ctx, - const char *selected, struct nk_image img, struct nk_vec2 size) -{ - return nk_combo_begin_image_text(ctx, selected, nk_strlen(selected), img, size); -} -NK_API int -nk_combo_item_text(struct nk_context *ctx, const char *text, int len,nk_flags align) -{ - return nk_contextual_item_text(ctx, text, len, align); -} -NK_API int -nk_combo_item_label(struct nk_context *ctx, const char *label, nk_flags align) -{ - return nk_contextual_item_label(ctx, label, align); -} -NK_API int -nk_combo_item_image_text(struct nk_context *ctx, struct nk_image img, const char *text, - int len, nk_flags alignment) -{ - return nk_contextual_item_image_text(ctx, img, text, len, alignment); -} -NK_API int -nk_combo_item_image_label(struct nk_context *ctx, struct nk_image img, - const char *text, nk_flags alignment) -{ - return nk_contextual_item_image_label(ctx, img, text, alignment); -} -NK_API int -nk_combo_item_symbol_text(struct nk_context *ctx, enum nk_symbol_type sym, - const char *text, int len, nk_flags alignment) -{ - return nk_contextual_item_symbol_text(ctx, sym, text, len, alignment); -} -NK_API int -nk_combo_item_symbol_label(struct nk_context *ctx, enum nk_symbol_type sym, - const char *label, nk_flags alignment) -{ - return nk_contextual_item_symbol_label(ctx, sym, label, alignment); -} -NK_API void nk_combo_end(struct nk_context *ctx) -{ - nk_contextual_end(ctx); -} -NK_API void nk_combo_close(struct nk_context *ctx) -{ - nk_contextual_close(ctx); -} -NK_API int -nk_combo(struct nk_context *ctx, const char **items, int count, - int selected, int item_height, struct nk_vec2 size) -{ - int i = 0; - int max_height; - struct nk_vec2 item_spacing; - struct nk_vec2 window_padding; - - NK_ASSERT(ctx); - NK_ASSERT(items); - NK_ASSERT(ctx->current); - if (!ctx || !items ||!count) - return selected; - - item_spacing = ctx->style.window.spacing; - window_padding = nk_panel_get_padding(&ctx->style, ctx->current->layout->type); - max_height = count * item_height + count * (int)item_spacing.y; - max_height += (int)item_spacing.y * 2 + (int)window_padding.y * 2; - size.y = NK_MIN(size.y, (float)max_height); - if (nk_combo_begin_label(ctx, items[selected], size)) { - nk_layout_row_dynamic(ctx, (float)item_height, 1); - for (i = 0; i < count; ++i) { - if (nk_combo_item_label(ctx, items[i], NK_TEXT_LEFT)) - selected = i; - } - nk_combo_end(ctx); - } - return selected; -} -NK_API int -nk_combo_separator(struct nk_context *ctx, const char *items_separated_by_separator, - int separator, int selected, int count, int item_height, struct nk_vec2 size) -{ - int i; - int max_height; - struct nk_vec2 item_spacing; - struct nk_vec2 window_padding; - const char *current_item; - const char *iter; - int length = 0; - - NK_ASSERT(ctx); - NK_ASSERT(items_separated_by_separator); - if (!ctx || !items_separated_by_separator) - return selected; - - /* calculate popup window */ - item_spacing = ctx->style.window.spacing; - window_padding = nk_panel_get_padding(&ctx->style, ctx->current->layout->type); - max_height = count * item_height + count * (int)item_spacing.y; - max_height += (int)item_spacing.y * 2 + (int)window_padding.y * 2; - size.y = NK_MIN(size.y, (float)max_height); - - /* find selected item */ - current_item = items_separated_by_separator; - for (i = 0; i < count; ++i) { - iter = current_item; - while (*iter && *iter != separator) iter++; - length = (int)(iter - current_item); - if (i == selected) break; - current_item = iter + 1; - } - - if (nk_combo_begin_text(ctx, current_item, length, size)) { - current_item = items_separated_by_separator; - nk_layout_row_dynamic(ctx, (float)item_height, 1); - for (i = 0; i < count; ++i) { - iter = current_item; - while (*iter && *iter != separator) iter++; - length = (int)(iter - current_item); - if (nk_combo_item_text(ctx, current_item, length, NK_TEXT_LEFT)) - selected = i; - current_item = current_item + length + 1; - } - nk_combo_end(ctx); - } - return selected; -} -NK_API int -nk_combo_string(struct nk_context *ctx, const char *items_separated_by_zeros, - int selected, int count, int item_height, struct nk_vec2 size) -{ - return nk_combo_separator(ctx, items_separated_by_zeros, '\0', selected, count, item_height, size); -} -NK_API int -nk_combo_callback(struct nk_context *ctx, void(*item_getter)(void*, int, const char**), - void *userdata, int selected, int count, int item_height, struct nk_vec2 size) -{ - int i; - int max_height; - struct nk_vec2 item_spacing; - struct nk_vec2 window_padding; - const char *item; - - NK_ASSERT(ctx); - NK_ASSERT(item_getter); - if (!ctx || !item_getter) - return selected; - - /* calculate popup window */ - item_spacing = ctx->style.window.spacing; - window_padding = nk_panel_get_padding(&ctx->style, ctx->current->layout->type); - max_height = count * item_height + count * (int)item_spacing.y; - max_height += (int)item_spacing.y * 2 + (int)window_padding.y * 2; - size.y = NK_MIN(size.y, (float)max_height); - - item_getter(userdata, selected, &item); - if (nk_combo_begin_label(ctx, item, size)) { - nk_layout_row_dynamic(ctx, (float)item_height, 1); - for (i = 0; i < count; ++i) { - item_getter(userdata, i, &item); - if (nk_combo_item_label(ctx, item, NK_TEXT_LEFT)) - selected = i; - } - nk_combo_end(ctx); - } return selected; -} -NK_API void -nk_combobox(struct nk_context *ctx, const char **items, int count, - int *selected, int item_height, struct nk_vec2 size) -{ - *selected = nk_combo(ctx, items, count, *selected, item_height, size); -} -NK_API void -nk_combobox_string(struct nk_context *ctx, const char *items_separated_by_zeros, - int *selected, int count, int item_height, struct nk_vec2 size) -{ - *selected = nk_combo_string(ctx, items_separated_by_zeros, *selected, count, item_height, size); -} -NK_API void -nk_combobox_separator(struct nk_context *ctx, const char *items_separated_by_separator, - int separator,int *selected, int count, int item_height, struct nk_vec2 size) -{ - *selected = nk_combo_separator(ctx, items_separated_by_separator, separator, - *selected, count, item_height, size); -} -NK_API void -nk_combobox_callback(struct nk_context *ctx, - void(*item_getter)(void* data, int id, const char **out_text), - void *userdata, int *selected, int count, int item_height, struct nk_vec2 size) -{ - *selected = nk_combo_callback(ctx, item_getter, userdata, *selected, count, item_height, size); -} - - - - - -/* =============================================================== - * - * TOOLTIP - * - * ===============================================================*/ -NK_API int -nk_tooltip_begin(struct nk_context *ctx, float width) -{ - int x,y,w,h; - struct nk_window *win; - const struct nk_input *in; - struct nk_rect bounds; - int ret; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - if (!ctx || !ctx->current || !ctx->current->layout) - return 0; - - /* make sure that no nonblocking popup is currently active */ - win = ctx->current; - in = &ctx->input; - if (win->popup.win && (win->popup.type & NK_PANEL_SET_NONBLOCK)) - return 0; - - w = nk_iceilf(width); - h = nk_iceilf(nk_null_rect.h); - x = nk_ifloorf(in->mouse.pos.x + 1) - (int)win->layout->clip.x; - y = nk_ifloorf(in->mouse.pos.y + 1) - (int)win->layout->clip.y; - - bounds.x = (float)x; - bounds.y = (float)y; - bounds.w = (float)w; - bounds.h = (float)h; - - ret = nk_popup_begin(ctx, NK_POPUP_DYNAMIC, - "__##Tooltip##__", NK_WINDOW_NO_SCROLLBAR|NK_WINDOW_BORDER, bounds); - if (ret) win->layout->flags &= ~(nk_flags)NK_WINDOW_ROM; - win->popup.type = NK_PANEL_TOOLTIP; - ctx->current->layout->type = NK_PANEL_TOOLTIP; - return ret; -} - -NK_API void -nk_tooltip_end(struct nk_context *ctx) -{ - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - if (!ctx || !ctx->current) return; - ctx->current->seq--; - nk_popup_close(ctx); - nk_popup_end(ctx); -} -NK_API void -nk_tooltip(struct nk_context *ctx, const char *text) -{ - const struct nk_style *style; - struct nk_vec2 padding; - - int text_len; - float text_width; - float text_height; - - NK_ASSERT(ctx); - NK_ASSERT(ctx->current); - NK_ASSERT(ctx->current->layout); - NK_ASSERT(text); - if (!ctx || !ctx->current || !ctx->current->layout || !text) - return; - - /* fetch configuration data */ - style = &ctx->style; - padding = style->window.padding; - - /* calculate size of the text and tooltip */ - text_len = nk_strlen(text); - text_width = style->font->width(style->font->userdata, - style->font->height, text, text_len); - text_width += (4 * padding.x); - text_height = (style->font->height + 2 * padding.y); - - /* execute tooltip and fill with text */ - if (nk_tooltip_begin(ctx, (float)text_width)) { - nk_layout_row_dynamic(ctx, (float)text_height, 1); - nk_text(ctx, text, text_len, NK_TEXT_LEFT); - nk_tooltip_end(ctx); - } -} -#ifdef NK_INCLUDE_STANDARD_VARARGS -NK_API void -nk_tooltipf(struct nk_context *ctx, const char *fmt, ...) -{ - va_list args; - va_start(args, fmt); - nk_tooltipfv(ctx, fmt, args); - va_end(args); -} -NK_API void -nk_tooltipfv(struct nk_context *ctx, const char *fmt, va_list args) -{ - char buf[256]; - nk_strfmt(buf, NK_LEN(buf), fmt, args); - nk_tooltip(ctx, buf); -} -#endif - - - -#endif /* NK_IMPLEMENTATION */ - -/* -/// ## License -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~none -/// ------------------------------------------------------------------------------ -/// This software is available under 2 licenses -- choose whichever you prefer. -/// ------------------------------------------------------------------------------ -/// ALTERNATIVE A - MIT License -/// Copyright (c) 2016-2018 Micha Mettke -/// Permission is hereby granted, free of charge, to any person obtaining a copy of -/// this software and associated documentation files (the "Software"), to deal in -/// the Software without restriction, including without limitation the rights to -/// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -/// of the Software, and to permit persons to whom the Software is furnished to do -/// so, subject to the following conditions: -/// The above copyright notice and this permission notice shall be included in all -/// copies or substantial portions of the Software. -/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -/// SOFTWARE. -/// ------------------------------------------------------------------------------ -/// ALTERNATIVE B - Public Domain (www.unlicense.org) -/// This is free and unencumbered software released into the public domain. -/// Anyone is free to copy, modify, publish, use, compile, sell, or distribute this -/// software, either in source code form or as a compiled binary, for any purpose, -/// commercial or non-commercial, and by any means. -/// In jurisdictions that recognize copyright laws, the author or authors of this -/// software dedicate any and all copyright interest in the software to the public -/// domain. We make this dedication for the benefit of the public at large and to -/// the detriment of our heirs and successors. We intend this dedication to be an -/// overt act of relinquishment in perpetuity of all present and future rights to -/// this software under copyright law. -/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -/// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN -/// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -/// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -/// ------------------------------------------------------------------------------ -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -/// ## Changelog -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~none -/// [date][x.yy.zz]-[description] -/// -[date]: date on which the change has been pushed -/// -[x.yy.zz]: Numerical version string representation. Each version number on the right -/// resets back to zero if version on the left is incremented. -/// - [x]: Major version with API and library breaking changes -/// - [yy]: Minor version with non-breaking API and library changes -/// - [zz]: Bug fix version with no direct changes to API -/// -/// - 2018/04/01 (4.00.1) - Fixed calling `nk_convert` multiple time per single frame -/// - 2018/04/01 (4.00.0) - BREAKING CHANGE: nk_draw_list_clear no longer tries to -/// clear provided buffers. So make sure to either free -/// or clear each passed buffer after calling nk_convert. -/// - 2018/02/23 (3.00.6) - Fixed slider dragging behavior -/// - 2018/01/31 (3.00.5) - Fixed overcalculation of cursor data in font baking process -/// - 2018/01/31 (3.00.4) - Removed name collision with stb_truetype -/// - 2018/01/28 (3.00.3) - Fixed panel window border drawing bug -/// - 2018/01/12 (3.00.2) - Added `nk_group_begin_titled` for separed group identifier and title -/// - 2018/01/07 (3.00.1) - Started to change documentation style -/// - 2018/01/05 (3.00.0) - BREAKING CHANGE: The previous color picker API was broken -/// because of conversions between float and byte color representation. -/// Color pickers now use floating point values to represent -/// HSV values. To get back the old behavior I added some additional -/// color conversion functions to cast between nk_color and -/// nk_colorf. -/// - 2017/12/23 (2.00.7) - Fixed small warning -/// - 2017/12/23 (2.00.7) - Fixed nk_edit_buffer behavior if activated to allow input -/// - 2017/12/23 (2.00.7) - Fixed modifyable progressbar dragging visuals and input behavior -/// - 2017/12/04 (2.00.6) - Added formated string tooltip widget -/// - 2017/11/18 (2.00.5) - Fixed window becoming hidden with flag NK_WINDOW_NO_INPUT -/// - 2017/11/15 (2.00.4) - Fixed font merging -/// - 2017/11/07 (2.00.3) - Fixed window size and position modifier functions -/// - 2017/09/14 (2.00.2) - Fixed nk_edit_buffer and nk_edit_focus behavior -/// - 2017/09/14 (2.00.1) - Fixed window closing behavior -/// - 2017/09/14 (2.00.0) - BREAKING CHANGE: Modifing window position and size funtions now -/// require the name of the window and must happen outside the window -/// building process (between function call nk_begin and nk_end). -/// - 2017/09/11 (1.40.9) - Fixed window background flag if background window is declared last -/// - 2017/08/27 (1.40.8) - Fixed `nk_item_is_any_active` for hidden windows -/// - 2017/08/27 (1.40.7) - Fixed window background flag -/// - 2017/07/07 (1.40.6) - Fixed missing clipping rect check for hovering/clicked -/// query for widgets -/// - 2017/07/07 (1.40.5) - Fixed drawing bug for vertex output for lines and stroked -/// and filled rectangles -/// - 2017/07/07 (1.40.4) - Fixed bug in nk_convert trying to add windows that are in -/// process of being destroyed. -/// - 2017/07/07 (1.40.3) - Fixed table internal bug caused by storing table size in -/// window instead of directly in table. -/// - 2017/06/30 (1.40.2) - Removed unneeded semicolon in C++ NK_ALIGNOF macro -/// - 2017/06/30 (1.40.1) - Fixed drawing lines smaller or equal zero -/// - 2017/06/08 (1.40.0) - Removed the breaking part of last commit. Auto layout now only -/// comes in effect if you pass in zero was row height argument -/// - 2017/06/08 (1.40.0) - BREAKING CHANGE: while not directly API breaking it will change -/// how layouting works. From now there will be an internal minimum -/// row height derived from font height. If you need a row smaller than -/// that you can directly set it by `nk_layout_set_min_row_height` and -/// reset the value back by calling `nk_layout_reset_min_row_height. -/// - 2017/06/08 (1.39.1) - Fixed property text edit handling bug caused by past `nk_widget` fix -/// - 2017/06/08 (1.39.0) - Added function to retrieve window space without calling a nk_layout_xxx function -/// - 2017/06/06 (1.38.5) - Fixed `nk_convert` return flag for command buffer -/// - 2017/05/23 (1.38.4) - Fixed activation behavior for widgets partially clipped -/// - 2017/05/10 (1.38.3) - Fixed wrong min window size mouse scaling over boundries -/// - 2017/05/09 (1.38.2) - Fixed vertical scrollbar drawing with not enough space -/// - 2017/05/09 (1.38.1) - Fixed scaler dragging behavior if window size hits minimum size -/// - 2017/05/06 (1.38.0) - Added platform double-click support -/// - 2017/04/20 (1.37.1) - Fixed key repeat found inside glfw demo backends -/// - 2017/04/20 (1.37.0) - Extended properties with selection and clipbard support -/// - 2017/04/20 (1.36.2) - Fixed #405 overlapping rows with zero padding and spacing -/// - 2017/04/09 (1.36.1) - Fixed #403 with another widget float error -/// - 2017/04/09 (1.36.0) - Added window `NK_WINDOW_NO_INPUT` and `NK_WINDOW_NOT_INTERACTIVE` flags -/// - 2017/04/09 (1.35.3) - Fixed buffer heap corruption -/// - 2017/03/25 (1.35.2) - Fixed popup overlapping for `NK_WINDOW_BACKGROUND` windows -/// - 2017/03/25 (1.35.1) - Fixed windows closing behavior -/// - 2017/03/18 (1.35.0) - Added horizontal scroll requested in #377 -/// - 2017/03/18 (1.34.3) - Fixed long window header titles -/// - 2017/03/04 (1.34.2) - Fixed text edit filtering -/// - 2017/03/04 (1.34.1) - Fixed group closable flag -/// - 2017/02/25 (1.34.0) - Added custom draw command for better language binding support -/// - 2017/01/24 (1.33.0) - Added programatic way of remove edit focus -/// - 2017/01/24 (1.32.3) - Fixed wrong define for basic type definitions for windows -/// - 2017/01/21 (1.32.2) - Fixed input capture from hidden or closed windows -/// - 2017/01/21 (1.32.1) - Fixed slider behavior and drawing -/// - 2017/01/13 (1.32.0) - Added flag to put scaler into the bottom left corner -/// - 2017/01/13 (1.31.0) - Added additional row layouting method to combine both -/// dynamic and static widgets. -/// - 2016/12/31 (1.30.0) - Extended scrollbar offset from 16-bit to 32-bit -/// - 2016/12/31 (1.29.2)- Fixed closing window bug of minimized windows -/// - 2016/12/03 (1.29.1)- Fixed wrapped text with no seperator and C89 error -/// - 2016/12/03 (1.29.0) - Changed text wrapping to process words not characters -/// - 2016/11/22 (1.28.6)- Fixed window minimized closing bug -/// - 2016/11/19 (1.28.5)- Fixed abstract combo box closing behavior -/// - 2016/11/19 (1.28.4)- Fixed tooltip flickering -/// - 2016/11/19 (1.28.3)- Fixed memory leak caused by popup repeated closing -/// - 2016/11/18 (1.28.2)- Fixed memory leak caused by popup panel allocation -/// - 2016/11/10 (1.28.1)- Fixed some warnings and C++ error -/// - 2016/11/10 (1.28.0)- Added additional `nk_button` versions which allows to directly -/// pass in a style struct to change buttons visual. -/// - 2016/11/10 (1.27.0)- Added additional 'nk_tree' versions to support external state -/// storage. Just like last the `nk_group` commit the main -/// advantage is that you optionally can minimize nuklears runtime -/// memory consumption or handle hash collisions. -/// - 2016/11/09 (1.26.0)- Added additional `nk_group` version to support external scrollbar -/// offset storage. Main advantage is that you can externalize -/// the memory management for the offset. It could also be helpful -/// if you have a hash collision in `nk_group_begin` but really -/// want the name. In addition I added `nk_list_view` which allows -/// to draw big lists inside a group without actually having to -/// commit the whole list to nuklear (issue #269). -/// - 2016/10/30 (1.25.1)- Fixed clipping rectangle bug inside `nk_draw_list` -/// - 2016/10/29 (1.25.0)- Pulled `nk_panel` memory management into nuklear and out of -/// the hands of the user. From now on users don't have to care -/// about panels unless they care about some information. If you -/// still need the panel just call `nk_window_get_panel`. -/// - 2016/10/21 (1.24.0)- Changed widget border drawing to stroked rectangle from filled -/// rectangle for less overdraw and widget background transparency. -/// - 2016/10/18 (1.23.0)- Added `nk_edit_focus` for manually edit widget focus control -/// - 2016/09/29 (1.22.7)- Fixed deduction of basic type in non `` compilation -/// - 2016/09/29 (1.22.6)- Fixed edit widget UTF-8 text cursor drawing bug -/// - 2016/09/28 (1.22.5)- Fixed edit widget UTF-8 text appending/inserting/removing -/// - 2016/09/28 (1.22.4)- Fixed drawing bug inside edit widgets which offset all text -/// text in every edit widget if one of them is scrolled. -/// - 2016/09/28 (1.22.3)- Fixed small bug in edit widgets if not active. The wrong -/// text length is passed. It should have been in bytes but -/// was passed as glyphes. -/// - 2016/09/20 (1.22.2)- Fixed color button size calculation -/// - 2016/09/20 (1.22.1)- Fixed some `nk_vsnprintf` behavior bugs and removed -/// `` again from `NK_INCLUDE_STANDARD_VARARGS`. -/// - 2016/09/18 (1.22.0)- C89 does not support vsnprintf only C99 and newer as well -/// as C++11 and newer. In addition to use vsnprintf you have -/// to include . So just defining `NK_INCLUDE_STD_VAR_ARGS` -/// is not enough. That behavior is now fixed. By default if -/// both varargs as well as stdio is selected I try to use -/// vsnprintf if not possible I will revert to vsprintf. If -/// varargs but not stdio was defined I will use my own function. -/// - 2016/09/15 (1.21.2)- Fixed panel `close` behavior for deeper panel levels -/// - 2016/09/15 (1.21.1)- Fixed C++ errors and wrong argument to `nk_panel_get_xxxx` -/// - 2016/09/13 (1.21.0) - !BREAKING! Fixed nonblocking popup behavior in menu, combo, -/// and contextual which prevented closing in y-direction if -/// popup did not reach max height. -/// In addition the height parameter was changed into vec2 -/// for width and height to have more control over the popup size. -/// - 2016/09/13 (1.20.3) - Cleaned up and extended type selection -/// - 2016/09/13 (1.20.2)- Fixed slider behavior hopefully for the last time. This time -/// all calculation are correct so no more hackery. -/// - 2016/09/13 (1.20.1)- Internal change to divide window/panel flags into panel flags and types. -/// Suprisinly spend years in C and still happened to confuse types -/// with flags. Probably something to take note. -/// - 2016/09/08 (1.20.0)- Added additional helper function to make it easier to just -/// take the produced buffers from `nk_convert` and unplug the -/// iteration process from `nk_context`. So now you can -/// just use the vertex,element and command buffer + two pointer -/// inside the command buffer retrieved by calls `nk__draw_begin` -/// and `nk__draw_end` and macro `nk_draw_foreach_bounded`. -/// - 2016/09/08 (1.19.0)- Added additional asserts to make sure every `nk_xxx_begin` call -/// for windows, popups, combobox, menu and contextual is guarded by -/// `if` condition and does not produce false drawing output. -/// - 2016/09/08 (1.18.0)- Changed confusing name for `NK_SYMBOL_RECT_FILLED`, `NK_SYMBOL_RECT` -/// to hopefully easier to understand `NK_SYMBOL_RECT_FILLED` and -/// `NK_SYMBOL_RECT_OUTLINE`. -/// - 2016/09/08 (1.17.0)- Changed confusing name for `NK_SYMBOL_CIRLCE_FILLED`, `NK_SYMBOL_CIRCLE` -/// to hopefully easier to understand `NK_SYMBOL_CIRCLE_FILLED` and -/// `NK_SYMBOL_CIRCLE_OUTLINE`. -/// - 2016/09/08 (1.16.0)- Added additional checks to select correct types if `NK_INCLUDE_FIXED_TYPES` -/// is not defined by supporting the biggest compiler GCC, clang and MSVC. -/// - 2016/09/07 (1.15.3)- Fixed `NK_INCLUDE_COMMAND_USERDATA` define to not cause an error -/// - 2016/09/04 (1.15.2)- Fixed wrong combobox height calculation -/// - 2016/09/03 (1.15.1)- Fixed gaps inside combo boxes in OpenGL -/// - 2016/09/02 (1.15.0) - Changed nuklear to not have any default vertex layout and -/// instead made it user provided. The range of types to convert -/// to is quite limited at the moment, but I would be more than -/// happy to accept PRs to add additional. -/// - 2016/08/30 (1.14.2) - Removed unused variables -/// - 2016/08/30 (1.14.1) - Fixed C++ build errors -/// - 2016/08/30 (1.14.0) - Removed mouse dragging from SDL demo since it does not work correctly -/// - 2016/08/30 (1.13.4) - Tweaked some default styling variables -/// - 2016/08/30 (1.13.3) - Hopefully fixed drawing bug in slider, in general I would -/// refrain from using slider with a big number of steps. -/// - 2016/08/30 (1.13.2) - Fixed close and minimize button which would fire even if the -/// window was in Read Only Mode. -/// - 2016/08/30 (1.13.1) - Fixed popup panel padding handling which was previously just -/// a hack for combo box and menu. -/// - 2016/08/30 (1.13.0) - Removed `NK_WINDOW_DYNAMIC` flag from public API since -/// it is bugged and causes issues in window selection. -/// - 2016/08/30 (1.12.0) - Removed scaler size. The size of the scaler is now -/// determined by the scrollbar size -/// - 2016/08/30 (1.11.2) - Fixed some drawing bugs caused by changes from 1.11 -/// - 2016/08/30 (1.11.1) - Fixed overlapping minimized window selection -/// - 2016/08/30 (1.11.0) - Removed some internal complexity and overly complex code -/// handling panel padding and panel border. -/// - 2016/08/29 (1.10.0) - Added additional height parameter to `nk_combobox_xxx` -/// - 2016/08/29 (1.10.0) - Fixed drawing bug in dynamic popups -/// - 2016/08/29 (1.10.0) - Added experimental mouse scrolling to popups, menus and comboboxes -/// - 2016/08/26 (1.10.0) - Added window name string prepresentation to account for -/// hash collisions. Currently limited to NK_WINDOW_MAX_NAME -/// which in term can be redefined if not big enough. -/// - 2016/08/26 (1.10.0) - Added stacks for temporary style/UI changes in code -/// - 2016/08/25 (1.10.0) - Changed `nk_input_is_key_pressed` and 'nk_input_is_key_released' -/// to account for key press and release happening in one frame. -/// - 2016/08/25 (1.10.0) - Added additional nk_edit flag to directly jump to the end on activate -/// - 2016/08/17 (1.09.6)- Removed invalid check for value zero in nk_propertyx -/// - 2016/08/16 (1.09.5)- Fixed ROM mode for deeper levels of popup windows parents. -/// - 2016/08/15 (1.09.4)- Editbox are now still active if enter was pressed with flag -/// `NK_EDIT_SIG_ENTER`. Main reasoning is to be able to keep -/// typing after commiting. -/// - 2016/08/15 (1.09.4)- Removed redundant code -/// - 2016/08/15 (1.09.4)- Fixed negative numbers in `nk_strtoi` and remove unused variable -/// - 2016/08/15 (1.09.3)- Fixed `NK_WINDOW_BACKGROUND` flag behavior to select a background -/// window only as selected by hovering and not by clicking. -/// - 2016/08/14 (1.09.2)- Fixed a bug in font atlas which caused wrong loading -/// of glyphes for font with multiple ranges. -/// - 2016/08/12 (1.09.1)- Added additional function to check if window is currently -/// hidden and therefore not visible. -/// - 2016/08/12 (1.09.1)- nk_window_is_closed now queries the correct flag `NK_WINDOW_CLOSED` -/// instead of the old flag `NK_WINDOW_HIDDEN` -/// - 2016/08/09 (1.09.0) - Added additional double version to nk_property and changed -/// the underlying implementation to not cast to float and instead -/// work directly on the given values. -/// - 2016/08/09 (1.08.0) - Added additional define to overwrite library internal -/// floating pointer number to string conversion for additional -/// precision. -/// - 2016/08/09 (1.08.0) - Added additional define to overwrite library internal -/// string to floating point number conversion for additional -/// precision. -/// - 2016/08/08 (1.07.2)- Fixed compiling error without define NK_INCLUDE_FIXED_TYPE -/// - 2016/08/08 (1.07.1)- Fixed possible floating point error inside `nk_widget` leading -/// to wrong wiget width calculation which results in widgets falsly -/// becomming tagged as not inside window and cannot be accessed. -/// - 2016/08/08 (1.07.0) - Nuklear now differentiates between hiding a window (NK_WINDOW_HIDDEN) and -/// closing a window (NK_WINDOW_CLOSED). A window can be hidden/shown -/// by using `nk_window_show` and closed by either clicking the close -/// icon in a window or by calling `nk_window_close`. Only closed -/// windows get removed at the end of the frame while hidden windows -/// remain. -/// - 2016/08/08 (1.06.0) - Added `nk_edit_string_zero_terminated` as a second option to -/// `nk_edit_string` which takes, edits and outputs a '\0' terminated string. -/// - 2016/08/08 (1.05.4)- Fixed scrollbar auto hiding behavior -/// - 2016/08/08 (1.05.3)- Fixed wrong panel padding selection in `nk_layout_widget_space` -/// - 2016/08/07 (1.05.2)- Fixed old bug in dynamic immediate mode layout API, calculating -/// wrong item spacing and panel width. -///- 2016/08/07 (1.05.1)- Hopefully finally fixed combobox popup drawing bug -///- 2016/08/07 (1.05.0) - Split varargs away from NK_INCLUDE_STANDARD_IO into own -/// define NK_INCLUDE_STANDARD_VARARGS to allow more fine -/// grained controlled over library includes. -/// - 2016/08/06 (1.04.5)- Changed memset calls to NK_MEMSET -/// - 2016/08/04 (1.04.4)- Fixed fast window scaling behavior -/// - 2016/08/04 (1.04.3)- Fixed window scaling, movement bug which appears if you -/// move/scale a window and another window is behind it. -/// If you are fast enough then the window behind gets activated -/// and the operation is blocked. I now require activating -/// by hovering only if mouse is not pressed. -/// - 2016/08/04 (1.04.2)- Fixed changing fonts -/// - 2016/08/03 (1.04.1)- Fixed `NK_WINDOW_BACKGROUND` behavior -/// - 2016/08/03 (1.04.0) - Added color parameter to `nk_draw_image` -/// - 2016/08/03 (1.04.0) - Added additional window padding style attributes for -/// sub windows (combo, menu, ...) -/// - 2016/08/03 (1.04.0) - Added functions to show/hide software cursor -/// - 2016/08/03 (1.04.0) - Added `NK_WINDOW_BACKGROUND` flag to force a window -/// to be always in the background of the screen -/// - 2016/08/03 (1.03.2)- Removed invalid assert macro for NK_RGB color picker -/// - 2016/08/01 (1.03.1)- Added helper macros into header include guard -/// - 2016/07/29 (1.03.0) - Moved the window/table pool into the header part to -/// simplify memory management by removing the need to -/// allocate the pool. -/// - 2016/07/29 (1.02.0) - Added auto scrollbar hiding window flag which if enabled -/// will hide the window scrollbar after NK_SCROLLBAR_HIDING_TIMEOUT -/// seconds without window interaction. To make it work -/// you have to also set a delta time inside the `nk_context`. -/// - 2016/07/25 (1.01.1) - Fixed small panel and panel border drawing bugs -/// - 2016/07/15 (1.01.0) - Added software cursor to `nk_style` and `nk_context` -/// - 2016/07/15 (1.01.0) - Added const correctness to `nk_buffer_push' data argument -/// - 2016/07/15 (1.01.0) - Removed internal font baking API and simplified -/// font atlas memory management by converting pointer -/// arrays for fonts and font configurations to lists. -/// - 2016/07/15 (1.00.0) - Changed button API to use context dependend button -/// behavior instead of passing it for every function call. -/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -/// ## Gallery -/// ![Figure [blue]: Feature overview with blue color styling](https://cloud.githubusercontent.com/assets/8057201/13538240/acd96876-e249-11e5-9547-5ac0b19667a0.png) -/// ![Figure [red]: Feature overview with red color styling](https://cloud.githubusercontent.com/assets/8057201/13538243/b04acd4c-e249-11e5-8fd2-ad7744a5b446.png) -/// ![Figure [widgets]: Widget overview](https://cloud.githubusercontent.com/assets/8057201/11282359/3325e3c6-8eff-11e5-86cb-cf02b0596087.png) -/// ![Figure [blackwhite]: Black and white](https://cloud.githubusercontent.com/assets/8057201/11033668/59ab5d04-86e5-11e5-8091-c56f16411565.png) -/// ![Figure [filexp]: File explorer](https://cloud.githubusercontent.com/assets/8057201/10718115/02a9ba08-7b6b-11e5-950f-adacdd637739.png) -/// ![Figure [opengl]: OpenGL Editor](https://cloud.githubusercontent.com/assets/8057201/12779619/2a20d72c-ca69-11e5-95fe-4edecf820d5c.png) -/// ![Figure [nodedit]: Node Editor](https://cloud.githubusercontent.com/assets/8057201/9976995/e81ac04a-5ef7-11e5-872b-acd54fbeee03.gif) -/// ![Figure [skinning]: Using skinning in Nuklear](https://cloud.githubusercontent.com/assets/8057201/15991632/76494854-30b8-11e6-9555-a69840d0d50b.png) -/// ![Figure [bf]: Heavy modified version](https://cloud.githubusercontent.com/assets/8057201/14902576/339926a8-0d9c-11e6-9fee-a8b73af04473.png) -/// -/// ## Credits -/// Developed by Micha Mettke and every direct or indirect github contributor.

-/// -/// Embeds [stb_texedit](https://github.com/nothings/stb/blob/master/stb_textedit.h), [stb_truetype](https://github.com/nothings/stb/blob/master/stb_truetype.h) and [stb_rectpack](https://github.com/nothings/stb/blob/master/stb_rect_pack.h) by Sean Barret (public domain)
-/// Uses [stddoc.c](https://github.com/r-lyeh/stddoc.c) from r-lyeh@github.com for documentation generation

-/// Embeds ProggyClean.ttf font by Tristan Grimmer (MIT license).
-/// -/// Big thank you to Omar Cornut (ocornut@github) for his [imgui library](https://github.com/ocornut/imgui) and -/// giving me the inspiration for this library, Casey Muratori for handmade hero -/// and his original immediate mode graphical user interface idea and Sean -/// Barret for his amazing single header libraries which restored my faith -/// in libraries and brought me to create some of my own. Finally Apoorva Joshi -/// for his single header file packer. -*/ - diff --git a/src/external/glfw/deps/nuklear_glfw_gl2.h b/src/external/glfw/deps/nuklear_glfw_gl2.h deleted file mode 100644 index 61acc29c..00000000 --- a/src/external/glfw/deps/nuklear_glfw_gl2.h +++ /dev/null @@ -1,381 +0,0 @@ -/* - * Nuklear - v1.32.0 - public domain - * no warrenty implied; use at your own risk. - * authored from 2015-2017 by Micha Mettke - */ -/* - * ============================================================== - * - * API - * - * =============================================================== - */ -#ifndef NK_GLFW_GL2_H_ -#define NK_GLFW_GL2_H_ - -#include - -enum nk_glfw_init_state{ - NK_GLFW3_DEFAULT = 0, - NK_GLFW3_INSTALL_CALLBACKS -}; -NK_API struct nk_context* nk_glfw3_init(GLFWwindow *win, enum nk_glfw_init_state); -NK_API void nk_glfw3_font_stash_begin(struct nk_font_atlas **atlas); -NK_API void nk_glfw3_font_stash_end(void); - -NK_API void nk_glfw3_new_frame(void); -NK_API void nk_glfw3_render(enum nk_anti_aliasing); -NK_API void nk_glfw3_shutdown(void); - -NK_API void nk_glfw3_char_callback(GLFWwindow *win, unsigned int codepoint); -NK_API void nk_gflw3_scroll_callback(GLFWwindow *win, double xoff, double yoff); - -#endif - -/* - * ============================================================== - * - * IMPLEMENTATION - * - * =============================================================== - */ -#ifdef NK_GLFW_GL2_IMPLEMENTATION - -#ifndef NK_GLFW_TEXT_MAX -#define NK_GLFW_TEXT_MAX 256 -#endif -#ifndef NK_GLFW_DOUBLE_CLICK_LO -#define NK_GLFW_DOUBLE_CLICK_LO 0.02 -#endif -#ifndef NK_GLFW_DOUBLE_CLICK_HI -#define NK_GLFW_DOUBLE_CLICK_HI 0.2 -#endif - -struct nk_glfw_device { - struct nk_buffer cmds; - struct nk_draw_null_texture null; - GLuint font_tex; -}; - -struct nk_glfw_vertex { - float position[2]; - float uv[2]; - nk_byte col[4]; -}; - -static struct nk_glfw { - GLFWwindow *win; - int width, height; - int display_width, display_height; - struct nk_glfw_device ogl; - struct nk_context ctx; - struct nk_font_atlas atlas; - struct nk_vec2 fb_scale; - unsigned int text[NK_GLFW_TEXT_MAX]; - int text_len; - struct nk_vec2 scroll; - double last_button_click; - int is_double_click_down; - struct nk_vec2 double_click_pos; -} glfw; - -NK_INTERN void -nk_glfw3_device_upload_atlas(const void *image, int width, int height) -{ - struct nk_glfw_device *dev = &glfw.ogl; - glGenTextures(1, &dev->font_tex); - glBindTexture(GL_TEXTURE_2D, dev->font_tex); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, (GLsizei)width, (GLsizei)height, 0, - GL_RGBA, GL_UNSIGNED_BYTE, image); -} - -NK_API void -nk_glfw3_render(enum nk_anti_aliasing AA) -{ - /* setup global state */ - struct nk_glfw_device *dev = &glfw.ogl; - glPushAttrib(GL_ENABLE_BIT|GL_COLOR_BUFFER_BIT|GL_TRANSFORM_BIT); - glDisable(GL_CULL_FACE); - glDisable(GL_DEPTH_TEST); - glEnable(GL_SCISSOR_TEST); - glEnable(GL_BLEND); - glEnable(GL_TEXTURE_2D); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - - /* setup viewport/project */ - glViewport(0,0,(GLsizei)glfw.display_width,(GLsizei)glfw.display_height); - glMatrixMode(GL_PROJECTION); - glPushMatrix(); - glLoadIdentity(); - glOrtho(0.0f, glfw.width, glfw.height, 0.0f, -1.0f, 1.0f); - glMatrixMode(GL_MODELVIEW); - glPushMatrix(); - glLoadIdentity(); - - glEnableClientState(GL_VERTEX_ARRAY); - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - glEnableClientState(GL_COLOR_ARRAY); - { - GLsizei vs = sizeof(struct nk_glfw_vertex); - size_t vp = offsetof(struct nk_glfw_vertex, position); - size_t vt = offsetof(struct nk_glfw_vertex, uv); - size_t vc = offsetof(struct nk_glfw_vertex, col); - - /* convert from command queue into draw list and draw to screen */ - const struct nk_draw_command *cmd; - const nk_draw_index *offset = NULL; - struct nk_buffer vbuf, ebuf; - - /* fill convert configuration */ - struct nk_convert_config config; - static const struct nk_draw_vertex_layout_element vertex_layout[] = { - {NK_VERTEX_POSITION, NK_FORMAT_FLOAT, NK_OFFSETOF(struct nk_glfw_vertex, position)}, - {NK_VERTEX_TEXCOORD, NK_FORMAT_FLOAT, NK_OFFSETOF(struct nk_glfw_vertex, uv)}, - {NK_VERTEX_COLOR, NK_FORMAT_R8G8B8A8, NK_OFFSETOF(struct nk_glfw_vertex, col)}, - {NK_VERTEX_LAYOUT_END} - }; - NK_MEMSET(&config, 0, sizeof(config)); - config.vertex_layout = vertex_layout; - config.vertex_size = sizeof(struct nk_glfw_vertex); - config.vertex_alignment = NK_ALIGNOF(struct nk_glfw_vertex); - config.null = dev->null; - config.circle_segment_count = 22; - config.curve_segment_count = 22; - config.arc_segment_count = 22; - config.global_alpha = 1.0f; - config.shape_AA = AA; - config.line_AA = AA; - - /* convert shapes into vertexes */ - nk_buffer_init_default(&vbuf); - nk_buffer_init_default(&ebuf); - nk_convert(&glfw.ctx, &dev->cmds, &vbuf, &ebuf, &config); - - /* setup vertex buffer pointer */ - {const void *vertices = nk_buffer_memory_const(&vbuf); - glVertexPointer(2, GL_FLOAT, vs, (const void*)((const nk_byte*)vertices + vp)); - glTexCoordPointer(2, GL_FLOAT, vs, (const void*)((const nk_byte*)vertices + vt)); - glColorPointer(4, GL_UNSIGNED_BYTE, vs, (const void*)((const nk_byte*)vertices + vc));} - - /* iterate over and execute each draw command */ - offset = (const nk_draw_index*)nk_buffer_memory_const(&ebuf); - nk_draw_foreach(cmd, &glfw.ctx, &dev->cmds) - { - if (!cmd->elem_count) continue; - glBindTexture(GL_TEXTURE_2D, (GLuint)cmd->texture.id); - glScissor( - (GLint)(cmd->clip_rect.x * glfw.fb_scale.x), - (GLint)((glfw.height - (GLint)(cmd->clip_rect.y + cmd->clip_rect.h)) * glfw.fb_scale.y), - (GLint)(cmd->clip_rect.w * glfw.fb_scale.x), - (GLint)(cmd->clip_rect.h * glfw.fb_scale.y)); - glDrawElements(GL_TRIANGLES, (GLsizei)cmd->elem_count, GL_UNSIGNED_SHORT, offset); - offset += cmd->elem_count; - } - nk_clear(&glfw.ctx); - nk_buffer_free(&vbuf); - nk_buffer_free(&ebuf); - } - - /* default OpenGL state */ - glDisableClientState(GL_VERTEX_ARRAY); - glDisableClientState(GL_TEXTURE_COORD_ARRAY); - glDisableClientState(GL_COLOR_ARRAY); - - glDisable(GL_CULL_FACE); - glDisable(GL_DEPTH_TEST); - glDisable(GL_SCISSOR_TEST); - glDisable(GL_BLEND); - glDisable(GL_TEXTURE_2D); - - glBindTexture(GL_TEXTURE_2D, 0); - glMatrixMode(GL_MODELVIEW); - glPopMatrix(); - glMatrixMode(GL_PROJECTION); - glPopMatrix(); - glPopAttrib(); -} - -NK_API void -nk_glfw3_char_callback(GLFWwindow *win, unsigned int codepoint) -{ - (void)win; - if (glfw.text_len < NK_GLFW_TEXT_MAX) - glfw.text[glfw.text_len++] = codepoint; -} - -NK_API void -nk_gflw3_scroll_callback(GLFWwindow *win, double xoff, double yoff) -{ - (void)win; (void)xoff; - glfw.scroll.x += (float)xoff; - glfw.scroll.y += (float)yoff; -} - -NK_API void -nk_glfw3_mouse_button_callback(GLFWwindow* window, int button, int action, int mods) -{ - double x, y; - if (button != GLFW_MOUSE_BUTTON_LEFT) return; - glfwGetCursorPos(window, &x, &y); - if (action == GLFW_PRESS) { - double dt = glfwGetTime() - glfw.last_button_click; - if (dt > NK_GLFW_DOUBLE_CLICK_LO && dt < NK_GLFW_DOUBLE_CLICK_HI) { - glfw.is_double_click_down = nk_true; - glfw.double_click_pos = nk_vec2((float)x, (float)y); - } - glfw.last_button_click = glfwGetTime(); - } else glfw.is_double_click_down = nk_false; -} - -NK_INTERN void -nk_glfw3_clipbard_paste(nk_handle usr, struct nk_text_edit *edit) -{ - const char *text = glfwGetClipboardString(glfw.win); - if (text) nk_textedit_paste(edit, text, nk_strlen(text)); - (void)usr; -} - -NK_INTERN void -nk_glfw3_clipbard_copy(nk_handle usr, const char *text, int len) -{ - char *str = 0; - (void)usr; - if (!len) return; - str = (char*)malloc((size_t)len+1); - if (!str) return; - NK_MEMCPY(str, text, (size_t)len); - str[len] = '\0'; - glfwSetClipboardString(glfw.win, str); - free(str); -} - -NK_API struct nk_context* -nk_glfw3_init(GLFWwindow *win, enum nk_glfw_init_state init_state) -{ - glfw.win = win; - if (init_state == NK_GLFW3_INSTALL_CALLBACKS) { - glfwSetScrollCallback(win, nk_gflw3_scroll_callback); - glfwSetCharCallback(win, nk_glfw3_char_callback); - glfwSetMouseButtonCallback(win, nk_glfw3_mouse_button_callback); - } - nk_init_default(&glfw.ctx, 0); - glfw.ctx.clip.copy = nk_glfw3_clipbard_copy; - glfw.ctx.clip.paste = nk_glfw3_clipbard_paste; - glfw.ctx.clip.userdata = nk_handle_ptr(0); - nk_buffer_init_default(&glfw.ogl.cmds); - - glfw.is_double_click_down = nk_false; - glfw.double_click_pos = nk_vec2(0, 0); - - return &glfw.ctx; -} - -NK_API void -nk_glfw3_font_stash_begin(struct nk_font_atlas **atlas) -{ - nk_font_atlas_init_default(&glfw.atlas); - nk_font_atlas_begin(&glfw.atlas); - *atlas = &glfw.atlas; -} - -NK_API void -nk_glfw3_font_stash_end(void) -{ - const void *image; int w, h; - image = nk_font_atlas_bake(&glfw.atlas, &w, &h, NK_FONT_ATLAS_RGBA32); - nk_glfw3_device_upload_atlas(image, w, h); - nk_font_atlas_end(&glfw.atlas, nk_handle_id((int)glfw.ogl.font_tex), &glfw.ogl.null); - if (glfw.atlas.default_font) - nk_style_set_font(&glfw.ctx, &glfw.atlas.default_font->handle); -} - -NK_API void -nk_glfw3_new_frame(void) -{ - int i; - double x, y; - struct nk_context *ctx = &glfw.ctx; - struct GLFWwindow *win = glfw.win; - - glfwGetWindowSize(win, &glfw.width, &glfw.height); - glfwGetFramebufferSize(win, &glfw.display_width, &glfw.display_height); - glfw.fb_scale.x = (float)glfw.display_width/(float)glfw.width; - glfw.fb_scale.y = (float)glfw.display_height/(float)glfw.height; - - nk_input_begin(ctx); - for (i = 0; i < glfw.text_len; ++i) - nk_input_unicode(ctx, glfw.text[i]); - - /* optional grabbing behavior */ - if (ctx->input.mouse.grab) - glfwSetInputMode(glfw.win, GLFW_CURSOR, GLFW_CURSOR_HIDDEN); - else if (ctx->input.mouse.ungrab) - glfwSetInputMode(glfw.win, GLFW_CURSOR, GLFW_CURSOR_NORMAL); - - nk_input_key(ctx, NK_KEY_DEL, glfwGetKey(win, GLFW_KEY_DELETE) == GLFW_PRESS); - nk_input_key(ctx, NK_KEY_ENTER, glfwGetKey(win, GLFW_KEY_ENTER) == GLFW_PRESS); - nk_input_key(ctx, NK_KEY_TAB, glfwGetKey(win, GLFW_KEY_TAB) == GLFW_PRESS); - nk_input_key(ctx, NK_KEY_BACKSPACE, glfwGetKey(win, GLFW_KEY_BACKSPACE) == GLFW_PRESS); - nk_input_key(ctx, NK_KEY_UP, glfwGetKey(win, GLFW_KEY_UP) == GLFW_PRESS); - nk_input_key(ctx, NK_KEY_DOWN, glfwGetKey(win, GLFW_KEY_DOWN) == GLFW_PRESS); - nk_input_key(ctx, NK_KEY_TEXT_START, glfwGetKey(win, GLFW_KEY_HOME) == GLFW_PRESS); - nk_input_key(ctx, NK_KEY_TEXT_END, glfwGetKey(win, GLFW_KEY_END) == GLFW_PRESS); - nk_input_key(ctx, NK_KEY_SCROLL_START, glfwGetKey(win, GLFW_KEY_HOME) == GLFW_PRESS); - nk_input_key(ctx, NK_KEY_SCROLL_END, glfwGetKey(win, GLFW_KEY_END) == GLFW_PRESS); - nk_input_key(ctx, NK_KEY_SCROLL_DOWN, glfwGetKey(win, GLFW_KEY_PAGE_DOWN) == GLFW_PRESS); - nk_input_key(ctx, NK_KEY_SCROLL_UP, glfwGetKey(win, GLFW_KEY_PAGE_UP) == GLFW_PRESS); - nk_input_key(ctx, NK_KEY_SHIFT, glfwGetKey(win, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS|| - glfwGetKey(win, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS); - - if (glfwGetKey(win, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS || - glfwGetKey(win, GLFW_KEY_RIGHT_CONTROL) == GLFW_PRESS) { - nk_input_key(ctx, NK_KEY_COPY, glfwGetKey(win, GLFW_KEY_C) == GLFW_PRESS); - nk_input_key(ctx, NK_KEY_PASTE, glfwGetKey(win, GLFW_KEY_V) == GLFW_PRESS); - nk_input_key(ctx, NK_KEY_CUT, glfwGetKey(win, GLFW_KEY_X) == GLFW_PRESS); - nk_input_key(ctx, NK_KEY_TEXT_UNDO, glfwGetKey(win, GLFW_KEY_Z) == GLFW_PRESS); - nk_input_key(ctx, NK_KEY_TEXT_REDO, glfwGetKey(win, GLFW_KEY_R) == GLFW_PRESS); - nk_input_key(ctx, NK_KEY_TEXT_WORD_LEFT, glfwGetKey(win, GLFW_KEY_LEFT) == GLFW_PRESS); - nk_input_key(ctx, NK_KEY_TEXT_WORD_RIGHT, glfwGetKey(win, GLFW_KEY_RIGHT) == GLFW_PRESS); - nk_input_key(ctx, NK_KEY_TEXT_LINE_START, glfwGetKey(win, GLFW_KEY_B) == GLFW_PRESS); - nk_input_key(ctx, NK_KEY_TEXT_LINE_END, glfwGetKey(win, GLFW_KEY_E) == GLFW_PRESS); - } else { - nk_input_key(ctx, NK_KEY_LEFT, glfwGetKey(win, GLFW_KEY_LEFT) == GLFW_PRESS); - nk_input_key(ctx, NK_KEY_RIGHT, glfwGetKey(win, GLFW_KEY_RIGHT) == GLFW_PRESS); - nk_input_key(ctx, NK_KEY_COPY, 0); - nk_input_key(ctx, NK_KEY_PASTE, 0); - nk_input_key(ctx, NK_KEY_CUT, 0); - nk_input_key(ctx, NK_KEY_SHIFT, 0); - } - - glfwGetCursorPos(win, &x, &y); - nk_input_motion(ctx, (int)x, (int)y); - if (ctx->input.mouse.grabbed) { - glfwSetCursorPos(glfw.win, (double)ctx->input.mouse.prev.x, (double)ctx->input.mouse.prev.y); - ctx->input.mouse.pos.x = ctx->input.mouse.prev.x; - ctx->input.mouse.pos.y = ctx->input.mouse.prev.y; - } - - nk_input_button(ctx, NK_BUTTON_LEFT, (int)x, (int)y, glfwGetMouseButton(win, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS); - nk_input_button(ctx, NK_BUTTON_MIDDLE, (int)x, (int)y, glfwGetMouseButton(win, GLFW_MOUSE_BUTTON_MIDDLE) == GLFW_PRESS); - nk_input_button(ctx, NK_BUTTON_RIGHT, (int)x, (int)y, glfwGetMouseButton(win, GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS); - nk_input_button(ctx, NK_BUTTON_DOUBLE, (int)glfw.double_click_pos.x, (int)glfw.double_click_pos.y, glfw.is_double_click_down); - nk_input_scroll(ctx, glfw.scroll); - nk_input_end(&glfw.ctx); - glfw.text_len = 0; - glfw.scroll = nk_vec2(0,0); -} - -NK_API -void nk_glfw3_shutdown(void) -{ - struct nk_glfw_device *dev = &glfw.ogl; - nk_font_atlas_clear(&glfw.atlas); - nk_free(&glfw.ctx); - glDeleteTextures(1, &dev->font_tex); - nk_buffer_free(&dev->cmds); - NK_MEMSET(&glfw, 0, sizeof(glfw)); -} - -#endif diff --git a/src/external/glfw/deps/stb_image_write.h b/src/external/glfw/deps/stb_image_write.h deleted file mode 100644 index 4319c0de..00000000 --- a/src/external/glfw/deps/stb_image_write.h +++ /dev/null @@ -1,1048 +0,0 @@ -/* stb_image_write - v1.02 - public domain - http://nothings.org/stb/stb_image_write.h - writes out PNG/BMP/TGA images to C stdio - Sean Barrett 2010-2015 - no warranty implied; use at your own risk - - Before #including, - - #define STB_IMAGE_WRITE_IMPLEMENTATION - - in the file that you want to have the implementation. - - Will probably not work correctly with strict-aliasing optimizations. - -ABOUT: - - This header file is a library for writing images to C stdio. It could be - adapted to write to memory or a general streaming interface; let me know. - - The PNG output is not optimal; it is 20-50% larger than the file - written by a decent optimizing implementation. This library is designed - for source code compactness and simplicity, not optimal image file size - or run-time performance. - -BUILDING: - - You can #define STBIW_ASSERT(x) before the #include to avoid using assert.h. - You can #define STBIW_MALLOC(), STBIW_REALLOC(), and STBIW_FREE() to replace - malloc,realloc,free. - You can define STBIW_MEMMOVE() to replace memmove() - -USAGE: - - There are four functions, one for each image file format: - - int stbi_write_png(char const *filename, int w, int h, int comp, const void *data, int stride_in_bytes); - int stbi_write_bmp(char const *filename, int w, int h, int comp, const void *data); - int stbi_write_tga(char const *filename, int w, int h, int comp, const void *data); - int stbi_write_hdr(char const *filename, int w, int h, int comp, const float *data); - - There are also four equivalent functions that use an arbitrary write function. You are - expected to open/close your file-equivalent before and after calling these: - - int stbi_write_png_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data, int stride_in_bytes); - int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); - int stbi_write_tga_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); - int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const float *data); - - where the callback is: - void stbi_write_func(void *context, void *data, int size); - - You can define STBI_WRITE_NO_STDIO to disable the file variant of these - functions, so the library will not use stdio.h at all. However, this will - also disable HDR writing, because it requires stdio for formatted output. - - Each function returns 0 on failure and non-0 on success. - - The functions create an image file defined by the parameters. The image - is a rectangle of pixels stored from left-to-right, top-to-bottom. - Each pixel contains 'comp' channels of data stored interleaved with 8-bits - per channel, in the following order: 1=Y, 2=YA, 3=RGB, 4=RGBA. (Y is - monochrome color.) The rectangle is 'w' pixels wide and 'h' pixels tall. - The *data pointer points to the first byte of the top-left-most pixel. - For PNG, "stride_in_bytes" is the distance in bytes from the first byte of - a row of pixels to the first byte of the next row of pixels. - - PNG creates output files with the same number of components as the input. - The BMP format expands Y to RGB in the file format and does not - output alpha. - - PNG supports writing rectangles of data even when the bytes storing rows of - data are not consecutive in memory (e.g. sub-rectangles of a larger image), - by supplying the stride between the beginning of adjacent rows. The other - formats do not. (Thus you cannot write a native-format BMP through the BMP - writer, both because it is in BGR order and because it may have padding - at the end of the line.) - - HDR expects linear float data. Since the format is always 32-bit rgb(e) - data, alpha (if provided) is discarded, and for monochrome data it is - replicated across all three channels. - - TGA supports RLE or non-RLE compressed data. To use non-RLE-compressed - data, set the global variable 'stbi_write_tga_with_rle' to 0. - -CREDITS: - - PNG/BMP/TGA - Sean Barrett - HDR - Baldur Karlsson - TGA monochrome: - Jean-Sebastien Guay - misc enhancements: - Tim Kelsey - TGA RLE - Alan Hickman - initial file IO callback implementation - Emmanuel Julien - bugfixes: - github:Chribba - Guillaume Chereau - github:jry2 - github:romigrou - Sergio Gonzalez - Jonas Karlsson - Filip Wasil - Thatcher Ulrich - -LICENSE - -This software is dual-licensed to the public domain and under the following -license: you are granted a perpetual, irrevocable license to copy, modify, -publish, and distribute this file as you see fit. - -*/ - -#ifndef INCLUDE_STB_IMAGE_WRITE_H -#define INCLUDE_STB_IMAGE_WRITE_H - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef STB_IMAGE_WRITE_STATIC -#define STBIWDEF static -#else -#define STBIWDEF extern -extern int stbi_write_tga_with_rle; -#endif - -#ifndef STBI_WRITE_NO_STDIO -STBIWDEF int stbi_write_png(char const *filename, int w, int h, int comp, const void *data, int stride_in_bytes); -STBIWDEF int stbi_write_bmp(char const *filename, int w, int h, int comp, const void *data); -STBIWDEF int stbi_write_tga(char const *filename, int w, int h, int comp, const void *data); -STBIWDEF int stbi_write_hdr(char const *filename, int w, int h, int comp, const float *data); -#endif - -typedef void stbi_write_func(void *context, void *data, int size); - -STBIWDEF int stbi_write_png_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data, int stride_in_bytes); -STBIWDEF int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); -STBIWDEF int stbi_write_tga_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); -STBIWDEF int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const float *data); - -#ifdef __cplusplus -} -#endif - -#endif//INCLUDE_STB_IMAGE_WRITE_H - -#ifdef STB_IMAGE_WRITE_IMPLEMENTATION - -#ifdef _WIN32 - #ifndef _CRT_SECURE_NO_WARNINGS - #define _CRT_SECURE_NO_WARNINGS - #endif - #ifndef _CRT_NONSTDC_NO_DEPRECATE - #define _CRT_NONSTDC_NO_DEPRECATE - #endif -#endif - -#ifndef STBI_WRITE_NO_STDIO -#include -#endif // STBI_WRITE_NO_STDIO - -#include -#include -#include -#include - -#if defined(STBIW_MALLOC) && defined(STBIW_FREE) && (defined(STBIW_REALLOC) || defined(STBIW_REALLOC_SIZED)) -// ok -#elif !defined(STBIW_MALLOC) && !defined(STBIW_FREE) && !defined(STBIW_REALLOC) && !defined(STBIW_REALLOC_SIZED) -// ok -#else -#error "Must define all or none of STBIW_MALLOC, STBIW_FREE, and STBIW_REALLOC (or STBIW_REALLOC_SIZED)." -#endif - -#ifndef STBIW_MALLOC -#define STBIW_MALLOC(sz) malloc(sz) -#define STBIW_REALLOC(p,newsz) realloc(p,newsz) -#define STBIW_FREE(p) free(p) -#endif - -#ifndef STBIW_REALLOC_SIZED -#define STBIW_REALLOC_SIZED(p,oldsz,newsz) STBIW_REALLOC(p,newsz) -#endif - - -#ifndef STBIW_MEMMOVE -#define STBIW_MEMMOVE(a,b,sz) memmove(a,b,sz) -#endif - - -#ifndef STBIW_ASSERT -#include -#define STBIW_ASSERT(x) assert(x) -#endif - -#define STBIW_UCHAR(x) (unsigned char) ((x) & 0xff) - -typedef struct -{ - stbi_write_func *func; - void *context; -} stbi__write_context; - -// initialize a callback-based context -static void stbi__start_write_callbacks(stbi__write_context *s, stbi_write_func *c, void *context) -{ - s->func = c; - s->context = context; -} - -#ifndef STBI_WRITE_NO_STDIO - -static void stbi__stdio_write(void *context, void *data, int size) -{ - fwrite(data,1,size,(FILE*) context); -} - -static int stbi__start_write_file(stbi__write_context *s, const char *filename) -{ - FILE *f = fopen(filename, "wb"); - stbi__start_write_callbacks(s, stbi__stdio_write, (void *) f); - return f != NULL; -} - -static void stbi__end_write_file(stbi__write_context *s) -{ - fclose((FILE *)s->context); -} - -#endif // !STBI_WRITE_NO_STDIO - -typedef unsigned int stbiw_uint32; -typedef int stb_image_write_test[sizeof(stbiw_uint32)==4 ? 1 : -1]; - -#ifdef STB_IMAGE_WRITE_STATIC -static int stbi_write_tga_with_rle = 1; -#else -int stbi_write_tga_with_rle = 1; -#endif - -static void stbiw__writefv(stbi__write_context *s, const char *fmt, va_list v) -{ - while (*fmt) { - switch (*fmt++) { - case ' ': break; - case '1': { unsigned char x = STBIW_UCHAR(va_arg(v, int)); - s->func(s->context,&x,1); - break; } - case '2': { int x = va_arg(v,int); - unsigned char b[2]; - b[0] = STBIW_UCHAR(x); - b[1] = STBIW_UCHAR(x>>8); - s->func(s->context,b,2); - break; } - case '4': { stbiw_uint32 x = va_arg(v,int); - unsigned char b[4]; - b[0]=STBIW_UCHAR(x); - b[1]=STBIW_UCHAR(x>>8); - b[2]=STBIW_UCHAR(x>>16); - b[3]=STBIW_UCHAR(x>>24); - s->func(s->context,b,4); - break; } - default: - STBIW_ASSERT(0); - return; - } - } -} - -static void stbiw__writef(stbi__write_context *s, const char *fmt, ...) -{ - va_list v; - va_start(v, fmt); - stbiw__writefv(s, fmt, v); - va_end(v); -} - -static void stbiw__write3(stbi__write_context *s, unsigned char a, unsigned char b, unsigned char c) -{ - unsigned char arr[3]; - arr[0] = a, arr[1] = b, arr[2] = c; - s->func(s->context, arr, 3); -} - -static void stbiw__write_pixel(stbi__write_context *s, int rgb_dir, int comp, int write_alpha, int expand_mono, unsigned char *d) -{ - unsigned char bg[3] = { 255, 0, 255}, px[3]; - int k; - - if (write_alpha < 0) - s->func(s->context, &d[comp - 1], 1); - - switch (comp) { - case 1: - s->func(s->context,d,1); - break; - case 2: - if (expand_mono) - stbiw__write3(s, d[0], d[0], d[0]); // monochrome bmp - else - s->func(s->context, d, 1); // monochrome TGA - break; - case 4: - if (!write_alpha) { - // composite against pink background - for (k = 0; k < 3; ++k) - px[k] = bg[k] + ((d[k] - bg[k]) * d[3]) / 255; - stbiw__write3(s, px[1 - rgb_dir], px[1], px[1 + rgb_dir]); - break; - } - /* FALLTHROUGH */ - case 3: - stbiw__write3(s, d[1 - rgb_dir], d[1], d[1 + rgb_dir]); - break; - } - if (write_alpha > 0) - s->func(s->context, &d[comp - 1], 1); -} - -static void stbiw__write_pixels(stbi__write_context *s, int rgb_dir, int vdir, int x, int y, int comp, void *data, int write_alpha, int scanline_pad, int expand_mono) -{ - stbiw_uint32 zero = 0; - int i,j, j_end; - - if (y <= 0) - return; - - if (vdir < 0) - j_end = -1, j = y-1; - else - j_end = y, j = 0; - - for (; j != j_end; j += vdir) { - for (i=0; i < x; ++i) { - unsigned char *d = (unsigned char *) data + (j*x+i)*comp; - stbiw__write_pixel(s, rgb_dir, comp, write_alpha, expand_mono, d); - } - s->func(s->context, &zero, scanline_pad); - } -} - -static int stbiw__outfile(stbi__write_context *s, int rgb_dir, int vdir, int x, int y, int comp, int expand_mono, void *data, int alpha, int pad, const char *fmt, ...) -{ - if (y < 0 || x < 0) { - return 0; - } else { - va_list v; - va_start(v, fmt); - stbiw__writefv(s, fmt, v); - va_end(v); - stbiw__write_pixels(s,rgb_dir,vdir,x,y,comp,data,alpha,pad, expand_mono); - return 1; - } -} - -static int stbi_write_bmp_core(stbi__write_context *s, int x, int y, int comp, const void *data) -{ - int pad = (-x*3) & 3; - return stbiw__outfile(s,-1,-1,x,y,comp,1,(void *) data,0,pad, - "11 4 22 4" "4 44 22 444444", - 'B', 'M', 14+40+(x*3+pad)*y, 0,0, 14+40, // file header - 40, x,y, 1,24, 0,0,0,0,0,0); // bitmap header -} - -STBIWDEF int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data) -{ - stbi__write_context s; - stbi__start_write_callbacks(&s, func, context); - return stbi_write_bmp_core(&s, x, y, comp, data); -} - -#ifndef STBI_WRITE_NO_STDIO -STBIWDEF int stbi_write_bmp(char const *filename, int x, int y, int comp, const void *data) -{ - stbi__write_context s; - if (stbi__start_write_file(&s,filename)) { - int r = stbi_write_bmp_core(&s, x, y, comp, data); - stbi__end_write_file(&s); - return r; - } else - return 0; -} -#endif //!STBI_WRITE_NO_STDIO - -static int stbi_write_tga_core(stbi__write_context *s, int x, int y, int comp, void *data) -{ - int has_alpha = (comp == 2 || comp == 4); - int colorbytes = has_alpha ? comp-1 : comp; - int format = colorbytes < 2 ? 3 : 2; // 3 color channels (RGB/RGBA) = 2, 1 color channel (Y/YA) = 3 - - if (y < 0 || x < 0) - return 0; - - if (!stbi_write_tga_with_rle) { - return stbiw__outfile(s, -1, -1, x, y, comp, 0, (void *) data, has_alpha, 0, - "111 221 2222 11", 0, 0, format, 0, 0, 0, 0, 0, x, y, (colorbytes + has_alpha) * 8, has_alpha * 8); - } else { - int i,j,k; - - stbiw__writef(s, "111 221 2222 11", 0,0,format+8, 0,0,0, 0,0,x,y, (colorbytes + has_alpha) * 8, has_alpha * 8); - - for (j = y - 1; j >= 0; --j) { - unsigned char *row = (unsigned char *) data + j * x * comp; - int len; - - for (i = 0; i < x; i += len) { - unsigned char *begin = row + i * comp; - int diff = 1; - len = 1; - - if (i < x - 1) { - ++len; - diff = memcmp(begin, row + (i + 1) * comp, comp); - if (diff) { - const unsigned char *prev = begin; - for (k = i + 2; k < x && len < 128; ++k) { - if (memcmp(prev, row + k * comp, comp)) { - prev += comp; - ++len; - } else { - --len; - break; - } - } - } else { - for (k = i + 2; k < x && len < 128; ++k) { - if (!memcmp(begin, row + k * comp, comp)) { - ++len; - } else { - break; - } - } - } - } - - if (diff) { - unsigned char header = STBIW_UCHAR(len - 1); - s->func(s->context, &header, 1); - for (k = 0; k < len; ++k) { - stbiw__write_pixel(s, -1, comp, has_alpha, 0, begin + k * comp); - } - } else { - unsigned char header = STBIW_UCHAR(len - 129); - s->func(s->context, &header, 1); - stbiw__write_pixel(s, -1, comp, has_alpha, 0, begin); - } - } - } - } - return 1; -} - -int stbi_write_tga_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data) -{ - stbi__write_context s; - stbi__start_write_callbacks(&s, func, context); - return stbi_write_tga_core(&s, x, y, comp, (void *) data); -} - -#ifndef STBI_WRITE_NO_STDIO -int stbi_write_tga(char const *filename, int x, int y, int comp, const void *data) -{ - stbi__write_context s; - if (stbi__start_write_file(&s,filename)) { - int r = stbi_write_tga_core(&s, x, y, comp, (void *) data); - stbi__end_write_file(&s); - return r; - } else - return 0; -} -#endif - -// ************************************************************************************************* -// Radiance RGBE HDR writer -// by Baldur Karlsson -#ifndef STBI_WRITE_NO_STDIO - -#define stbiw__max(a, b) ((a) > (b) ? (a) : (b)) - -void stbiw__linear_to_rgbe(unsigned char *rgbe, float *linear) -{ - int exponent; - float maxcomp = stbiw__max(linear[0], stbiw__max(linear[1], linear[2])); - - if (maxcomp < 1e-32f) { - rgbe[0] = rgbe[1] = rgbe[2] = rgbe[3] = 0; - } else { - float normalize = (float) frexp(maxcomp, &exponent) * 256.0f/maxcomp; - - rgbe[0] = (unsigned char)(linear[0] * normalize); - rgbe[1] = (unsigned char)(linear[1] * normalize); - rgbe[2] = (unsigned char)(linear[2] * normalize); - rgbe[3] = (unsigned char)(exponent + 128); - } -} - -void stbiw__write_run_data(stbi__write_context *s, int length, unsigned char databyte) -{ - unsigned char lengthbyte = STBIW_UCHAR(length+128); - STBIW_ASSERT(length+128 <= 255); - s->func(s->context, &lengthbyte, 1); - s->func(s->context, &databyte, 1); -} - -void stbiw__write_dump_data(stbi__write_context *s, int length, unsigned char *data) -{ - unsigned char lengthbyte = STBIW_UCHAR(length); - STBIW_ASSERT(length <= 128); // inconsistent with spec but consistent with official code - s->func(s->context, &lengthbyte, 1); - s->func(s->context, data, length); -} - -void stbiw__write_hdr_scanline(stbi__write_context *s, int width, int ncomp, unsigned char *scratch, float *scanline) -{ - unsigned char scanlineheader[4] = { 2, 2, 0, 0 }; - unsigned char rgbe[4]; - float linear[3]; - int x; - - scanlineheader[2] = (width&0xff00)>>8; - scanlineheader[3] = (width&0x00ff); - - /* skip RLE for images too small or large */ - if (width < 8 || width >= 32768) { - for (x=0; x < width; x++) { - switch (ncomp) { - case 4: /* fallthrough */ - case 3: linear[2] = scanline[x*ncomp + 2]; - linear[1] = scanline[x*ncomp + 1]; - linear[0] = scanline[x*ncomp + 0]; - break; - default: - linear[0] = linear[1] = linear[2] = scanline[x*ncomp + 0]; - break; - } - stbiw__linear_to_rgbe(rgbe, linear); - s->func(s->context, rgbe, 4); - } - } else { - int c,r; - /* encode into scratch buffer */ - for (x=0; x < width; x++) { - switch(ncomp) { - case 4: /* fallthrough */ - case 3: linear[2] = scanline[x*ncomp + 2]; - linear[1] = scanline[x*ncomp + 1]; - linear[0] = scanline[x*ncomp + 0]; - break; - default: - linear[0] = linear[1] = linear[2] = scanline[x*ncomp + 0]; - break; - } - stbiw__linear_to_rgbe(rgbe, linear); - scratch[x + width*0] = rgbe[0]; - scratch[x + width*1] = rgbe[1]; - scratch[x + width*2] = rgbe[2]; - scratch[x + width*3] = rgbe[3]; - } - - s->func(s->context, scanlineheader, 4); - - /* RLE each component separately */ - for (c=0; c < 4; c++) { - unsigned char *comp = &scratch[width*c]; - - x = 0; - while (x < width) { - // find first run - r = x; - while (r+2 < width) { - if (comp[r] == comp[r+1] && comp[r] == comp[r+2]) - break; - ++r; - } - if (r+2 >= width) - r = width; - // dump up to first run - while (x < r) { - int len = r-x; - if (len > 128) len = 128; - stbiw__write_dump_data(s, len, &comp[x]); - x += len; - } - // if there's a run, output it - if (r+2 < width) { // same test as what we break out of in search loop, so only true if we break'd - // find next byte after run - while (r < width && comp[r] == comp[x]) - ++r; - // output run up to r - while (x < r) { - int len = r-x; - if (len > 127) len = 127; - stbiw__write_run_data(s, len, comp[x]); - x += len; - } - } - } - } - } -} - -static int stbi_write_hdr_core(stbi__write_context *s, int x, int y, int comp, float *data) -{ - if (y <= 0 || x <= 0 || data == NULL) - return 0; - else { - // Each component is stored separately. Allocate scratch space for full output scanline. - unsigned char *scratch = (unsigned char *) STBIW_MALLOC(x*4); - int i, len; - char buffer[128]; - char header[] = "#?RADIANCE\n# Written by stb_image_write.h\nFORMAT=32-bit_rle_rgbe\n"; - s->func(s->context, header, sizeof(header)-1); - - len = sprintf(buffer, "EXPOSURE= 1.0000000000000\n\n-Y %d +X %d\n", y, x); - s->func(s->context, buffer, len); - - for(i=0; i < y; i++) - stbiw__write_hdr_scanline(s, x, comp, scratch, data + comp*i*x); - STBIW_FREE(scratch); - return 1; - } -} - -int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const float *data) -{ - stbi__write_context s; - stbi__start_write_callbacks(&s, func, context); - return stbi_write_hdr_core(&s, x, y, comp, (float *) data); -} - -int stbi_write_hdr(char const *filename, int x, int y, int comp, const float *data) -{ - stbi__write_context s; - if (stbi__start_write_file(&s,filename)) { - int r = stbi_write_hdr_core(&s, x, y, comp, (float *) data); - stbi__end_write_file(&s); - return r; - } else - return 0; -} -#endif // STBI_WRITE_NO_STDIO - - -////////////////////////////////////////////////////////////////////////////// -// -// PNG writer -// - -// stretchy buffer; stbiw__sbpush() == vector<>::push_back() -- stbiw__sbcount() == vector<>::size() -#define stbiw__sbraw(a) ((int *) (a) - 2) -#define stbiw__sbm(a) stbiw__sbraw(a)[0] -#define stbiw__sbn(a) stbiw__sbraw(a)[1] - -#define stbiw__sbneedgrow(a,n) ((a)==0 || stbiw__sbn(a)+n >= stbiw__sbm(a)) -#define stbiw__sbmaybegrow(a,n) (stbiw__sbneedgrow(a,(n)) ? stbiw__sbgrow(a,n) : 0) -#define stbiw__sbgrow(a,n) stbiw__sbgrowf((void **) &(a), (n), sizeof(*(a))) - -#define stbiw__sbpush(a, v) (stbiw__sbmaybegrow(a,1), (a)[stbiw__sbn(a)++] = (v)) -#define stbiw__sbcount(a) ((a) ? stbiw__sbn(a) : 0) -#define stbiw__sbfree(a) ((a) ? STBIW_FREE(stbiw__sbraw(a)),0 : 0) - -static void *stbiw__sbgrowf(void **arr, int increment, int itemsize) -{ - int m = *arr ? 2*stbiw__sbm(*arr)+increment : increment+1; - void *p = STBIW_REALLOC_SIZED(*arr ? stbiw__sbraw(*arr) : 0, *arr ? (stbiw__sbm(*arr)*itemsize + sizeof(int)*2) : 0, itemsize * m + sizeof(int)*2); - STBIW_ASSERT(p); - if (p) { - if (!*arr) ((int *) p)[1] = 0; - *arr = (void *) ((int *) p + 2); - stbiw__sbm(*arr) = m; - } - return *arr; -} - -static unsigned char *stbiw__zlib_flushf(unsigned char *data, unsigned int *bitbuffer, int *bitcount) -{ - while (*bitcount >= 8) { - stbiw__sbpush(data, STBIW_UCHAR(*bitbuffer)); - *bitbuffer >>= 8; - *bitcount -= 8; - } - return data; -} - -static int stbiw__zlib_bitrev(int code, int codebits) -{ - int res=0; - while (codebits--) { - res = (res << 1) | (code & 1); - code >>= 1; - } - return res; -} - -static unsigned int stbiw__zlib_countm(unsigned char *a, unsigned char *b, int limit) -{ - int i; - for (i=0; i < limit && i < 258; ++i) - if (a[i] != b[i]) break; - return i; -} - -static unsigned int stbiw__zhash(unsigned char *data) -{ - stbiw_uint32 hash = data[0] + (data[1] << 8) + (data[2] << 16); - hash ^= hash << 3; - hash += hash >> 5; - hash ^= hash << 4; - hash += hash >> 17; - hash ^= hash << 25; - hash += hash >> 6; - return hash; -} - -#define stbiw__zlib_flush() (out = stbiw__zlib_flushf(out, &bitbuf, &bitcount)) -#define stbiw__zlib_add(code,codebits) \ - (bitbuf |= (code) << bitcount, bitcount += (codebits), stbiw__zlib_flush()) -#define stbiw__zlib_huffa(b,c) stbiw__zlib_add(stbiw__zlib_bitrev(b,c),c) -// default huffman tables -#define stbiw__zlib_huff1(n) stbiw__zlib_huffa(0x30 + (n), 8) -#define stbiw__zlib_huff2(n) stbiw__zlib_huffa(0x190 + (n)-144, 9) -#define stbiw__zlib_huff3(n) stbiw__zlib_huffa(0 + (n)-256,7) -#define stbiw__zlib_huff4(n) stbiw__zlib_huffa(0xc0 + (n)-280,8) -#define stbiw__zlib_huff(n) ((n) <= 143 ? stbiw__zlib_huff1(n) : (n) <= 255 ? stbiw__zlib_huff2(n) : (n) <= 279 ? stbiw__zlib_huff3(n) : stbiw__zlib_huff4(n)) -#define stbiw__zlib_huffb(n) ((n) <= 143 ? stbiw__zlib_huff1(n) : stbiw__zlib_huff2(n)) - -#define stbiw__ZHASH 16384 - -unsigned char * stbi_zlib_compress(unsigned char *data, int data_len, int *out_len, int quality) -{ - static unsigned short lengthc[] = { 3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258, 259 }; - static unsigned char lengtheb[]= { 0,0,0,0,0,0,0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 }; - static unsigned short distc[] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577, 32768 }; - static unsigned char disteb[] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13 }; - unsigned int bitbuf=0; - int i,j, bitcount=0; - unsigned char *out = NULL; - unsigned char ***hash_table = (unsigned char***) STBIW_MALLOC(stbiw__ZHASH * sizeof(char**)); - if (quality < 5) quality = 5; - - stbiw__sbpush(out, 0x78); // DEFLATE 32K window - stbiw__sbpush(out, 0x5e); // FLEVEL = 1 - stbiw__zlib_add(1,1); // BFINAL = 1 - stbiw__zlib_add(1,2); // BTYPE = 1 -- fixed huffman - - for (i=0; i < stbiw__ZHASH; ++i) - hash_table[i] = NULL; - - i=0; - while (i < data_len-3) { - // hash next 3 bytes of data to be compressed - int h = stbiw__zhash(data+i)&(stbiw__ZHASH-1), best=3; - unsigned char *bestloc = 0; - unsigned char **hlist = hash_table[h]; - int n = stbiw__sbcount(hlist); - for (j=0; j < n; ++j) { - if (hlist[j]-data > i-32768) { // if entry lies within window - int d = stbiw__zlib_countm(hlist[j], data+i, data_len-i); - if (d >= best) best=d,bestloc=hlist[j]; - } - } - // when hash table entry is too long, delete half the entries - if (hash_table[h] && stbiw__sbn(hash_table[h]) == 2*quality) { - STBIW_MEMMOVE(hash_table[h], hash_table[h]+quality, sizeof(hash_table[h][0])*quality); - stbiw__sbn(hash_table[h]) = quality; - } - stbiw__sbpush(hash_table[h],data+i); - - if (bestloc) { - // "lazy matching" - check match at *next* byte, and if it's better, do cur byte as literal - h = stbiw__zhash(data+i+1)&(stbiw__ZHASH-1); - hlist = hash_table[h]; - n = stbiw__sbcount(hlist); - for (j=0; j < n; ++j) { - if (hlist[j]-data > i-32767) { - int e = stbiw__zlib_countm(hlist[j], data+i+1, data_len-i-1); - if (e > best) { // if next match is better, bail on current match - bestloc = NULL; - break; - } - } - } - } - - if (bestloc) { - int d = (int) (data+i - bestloc); // distance back - STBIW_ASSERT(d <= 32767 && best <= 258); - for (j=0; best > lengthc[j+1]-1; ++j); - stbiw__zlib_huff(j+257); - if (lengtheb[j]) stbiw__zlib_add(best - lengthc[j], lengtheb[j]); - for (j=0; d > distc[j+1]-1; ++j); - stbiw__zlib_add(stbiw__zlib_bitrev(j,5),5); - if (disteb[j]) stbiw__zlib_add(d - distc[j], disteb[j]); - i += best; - } else { - stbiw__zlib_huffb(data[i]); - ++i; - } - } - // write out final bytes - for (;i < data_len; ++i) - stbiw__zlib_huffb(data[i]); - stbiw__zlib_huff(256); // end of block - // pad with 0 bits to byte boundary - while (bitcount) - stbiw__zlib_add(0,1); - - for (i=0; i < stbiw__ZHASH; ++i) - (void) stbiw__sbfree(hash_table[i]); - STBIW_FREE(hash_table); - - { - // compute adler32 on input - unsigned int s1=1, s2=0; - int blocklen = (int) (data_len % 5552); - j=0; - while (j < data_len) { - for (i=0; i < blocklen; ++i) s1 += data[j+i], s2 += s1; - s1 %= 65521, s2 %= 65521; - j += blocklen; - blocklen = 5552; - } - stbiw__sbpush(out, STBIW_UCHAR(s2 >> 8)); - stbiw__sbpush(out, STBIW_UCHAR(s2)); - stbiw__sbpush(out, STBIW_UCHAR(s1 >> 8)); - stbiw__sbpush(out, STBIW_UCHAR(s1)); - } - *out_len = stbiw__sbn(out); - // make returned pointer freeable - STBIW_MEMMOVE(stbiw__sbraw(out), out, *out_len); - return (unsigned char *) stbiw__sbraw(out); -} - -static unsigned int stbiw__crc32(unsigned char *buffer, int len) -{ - static unsigned int crc_table[256] = - { - 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, - 0x0eDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, - 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, - 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, - 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, - 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, - 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, - 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, - 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, - 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, - 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, - 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, - 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, - 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, - 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, - 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, - 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, - 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, - 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, - 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, - 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, - 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, - 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, - 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, - 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, - 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, - 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, - 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, - 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, - 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, - 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, - 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D - }; - - unsigned int crc = ~0u; - int i; - for (i=0; i < len; ++i) - crc = (crc >> 8) ^ crc_table[buffer[i] ^ (crc & 0xff)]; - return ~crc; -} - -#define stbiw__wpng4(o,a,b,c,d) ((o)[0]=STBIW_UCHAR(a),(o)[1]=STBIW_UCHAR(b),(o)[2]=STBIW_UCHAR(c),(o)[3]=STBIW_UCHAR(d),(o)+=4) -#define stbiw__wp32(data,v) stbiw__wpng4(data, (v)>>24,(v)>>16,(v)>>8,(v)); -#define stbiw__wptag(data,s) stbiw__wpng4(data, s[0],s[1],s[2],s[3]) - -static void stbiw__wpcrc(unsigned char **data, int len) -{ - unsigned int crc = stbiw__crc32(*data - len - 4, len+4); - stbiw__wp32(*data, crc); -} - -static unsigned char stbiw__paeth(int a, int b, int c) -{ - int p = a + b - c, pa = abs(p-a), pb = abs(p-b), pc = abs(p-c); - if (pa <= pb && pa <= pc) return STBIW_UCHAR(a); - if (pb <= pc) return STBIW_UCHAR(b); - return STBIW_UCHAR(c); -} - -unsigned char *stbi_write_png_to_mem(unsigned char *pixels, int stride_bytes, int x, int y, int n, int *out_len) -{ - int ctype[5] = { -1, 0, 4, 2, 6 }; - unsigned char sig[8] = { 137,80,78,71,13,10,26,10 }; - unsigned char *out,*o, *filt, *zlib; - signed char *line_buffer; - int i,j,k,p,zlen; - - if (stride_bytes == 0) - stride_bytes = x * n; - - filt = (unsigned char *) STBIW_MALLOC((x*n+1) * y); if (!filt) return 0; - line_buffer = (signed char *) STBIW_MALLOC(x * n); if (!line_buffer) { STBIW_FREE(filt); return 0; } - for (j=0; j < y; ++j) { - static int mapping[] = { 0,1,2,3,4 }; - static int firstmap[] = { 0,1,0,5,6 }; - int *mymap = j ? mapping : firstmap; - int best = 0, bestval = 0x7fffffff; - for (p=0; p < 2; ++p) { - for (k= p?best:0; k < 5; ++k) { - int type = mymap[k],est=0; - unsigned char *z = pixels + stride_bytes*j; - for (i=0; i < n; ++i) - switch (type) { - case 0: line_buffer[i] = z[i]; break; - case 1: line_buffer[i] = z[i]; break; - case 2: line_buffer[i] = z[i] - z[i-stride_bytes]; break; - case 3: line_buffer[i] = z[i] - (z[i-stride_bytes]>>1); break; - case 4: line_buffer[i] = (signed char) (z[i] - stbiw__paeth(0,z[i-stride_bytes],0)); break; - case 5: line_buffer[i] = z[i]; break; - case 6: line_buffer[i] = z[i]; break; - } - for (i=n; i < x*n; ++i) { - switch (type) { - case 0: line_buffer[i] = z[i]; break; - case 1: line_buffer[i] = z[i] - z[i-n]; break; - case 2: line_buffer[i] = z[i] - z[i-stride_bytes]; break; - case 3: line_buffer[i] = z[i] - ((z[i-n] + z[i-stride_bytes])>>1); break; - case 4: line_buffer[i] = z[i] - stbiw__paeth(z[i-n], z[i-stride_bytes], z[i-stride_bytes-n]); break; - case 5: line_buffer[i] = z[i] - (z[i-n]>>1); break; - case 6: line_buffer[i] = z[i] - stbiw__paeth(z[i-n], 0,0); break; - } - } - if (p) break; - for (i=0; i < x*n; ++i) - est += abs((signed char) line_buffer[i]); - if (est < bestval) { bestval = est; best = k; } - } - } - // when we get here, best contains the filter type, and line_buffer contains the data - filt[j*(x*n+1)] = (unsigned char) best; - STBIW_MEMMOVE(filt+j*(x*n+1)+1, line_buffer, x*n); - } - STBIW_FREE(line_buffer); - zlib = stbi_zlib_compress(filt, y*( x*n+1), &zlen, 8); // increase 8 to get smaller but use more memory - STBIW_FREE(filt); - if (!zlib) return 0; - - // each tag requires 12 bytes of overhead - out = (unsigned char *) STBIW_MALLOC(8 + 12+13 + 12+zlen + 12); - if (!out) return 0; - *out_len = 8 + 12+13 + 12+zlen + 12; - - o=out; - STBIW_MEMMOVE(o,sig,8); o+= 8; - stbiw__wp32(o, 13); // header length - stbiw__wptag(o, "IHDR"); - stbiw__wp32(o, x); - stbiw__wp32(o, y); - *o++ = 8; - *o++ = STBIW_UCHAR(ctype[n]); - *o++ = 0; - *o++ = 0; - *o++ = 0; - stbiw__wpcrc(&o,13); - - stbiw__wp32(o, zlen); - stbiw__wptag(o, "IDAT"); - STBIW_MEMMOVE(o, zlib, zlen); - o += zlen; - STBIW_FREE(zlib); - stbiw__wpcrc(&o, zlen); - - stbiw__wp32(o,0); - stbiw__wptag(o, "IEND"); - stbiw__wpcrc(&o,0); - - STBIW_ASSERT(o == out + *out_len); - - return out; -} - -#ifndef STBI_WRITE_NO_STDIO -STBIWDEF int stbi_write_png(char const *filename, int x, int y, int comp, const void *data, int stride_bytes) -{ - FILE *f; - int len; - unsigned char *png = stbi_write_png_to_mem((unsigned char *) data, stride_bytes, x, y, comp, &len); - if (png == NULL) return 0; - f = fopen(filename, "wb"); - if (!f) { STBIW_FREE(png); return 0; } - fwrite(png, 1, len, f); - fclose(f); - STBIW_FREE(png); - return 1; -} -#endif - -STBIWDEF int stbi_write_png_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int stride_bytes) -{ - int len; - unsigned char *png = stbi_write_png_to_mem((unsigned char *) data, stride_bytes, x, y, comp, &len); - if (png == NULL) return 0; - func(context, png, len); - STBIW_FREE(png); - return 1; -} - -#endif // STB_IMAGE_WRITE_IMPLEMENTATION - -/* Revision history - 1.02 (2016-04-02) - avoid allocating large structures on the stack - 1.01 (2016-01-16) - STBIW_REALLOC_SIZED: support allocators with no realloc support - avoid race-condition in crc initialization - minor compile issues - 1.00 (2015-09-14) - installable file IO function - 0.99 (2015-09-13) - warning fixes; TGA rle support - 0.98 (2015-04-08) - added STBIW_MALLOC, STBIW_ASSERT etc - 0.97 (2015-01-18) - fixed HDR asserts, rewrote HDR rle logic - 0.96 (2015-01-17) - add HDR output - fix monochrome BMP - 0.95 (2014-08-17) - add monochrome TGA output - 0.94 (2014-05-31) - rename private functions to avoid conflicts with stb_image.h - 0.93 (2014-05-27) - warning fixes - 0.92 (2010-08-01) - casts to unsigned char to fix warnings - 0.91 (2010-07-17) - first public release - 0.90 first internal release -*/ diff --git a/src/external/glfw/deps/tinycthread.c b/src/external/glfw/deps/tinycthread.c deleted file mode 100644 index f9cea2ed..00000000 --- a/src/external/glfw/deps/tinycthread.c +++ /dev/null @@ -1,594 +0,0 @@ -/* -*- mode: c; tab-width: 2; indent-tabs-mode: nil; -*- -Copyright (c) 2012 Marcus Geelnard - -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, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - - 3. This notice may not be removed or altered from any source - distribution. -*/ - -/* 2013-01-06 Camilla Lรถwy - * - * Added casts from time_t to DWORD to avoid warnings on VC++. - * Fixed time retrieval on POSIX systems. - */ - -#include "tinycthread.h" -#include - -/* Platform specific includes */ -#if defined(_TTHREAD_POSIX_) - #include - #include - #include - #include - #include -#elif defined(_TTHREAD_WIN32_) - #include - #include -#endif - -/* Standard, good-to-have defines */ -#ifndef NULL - #define NULL (void*)0 -#endif -#ifndef TRUE - #define TRUE 1 -#endif -#ifndef FALSE - #define FALSE 0 -#endif - -int mtx_init(mtx_t *mtx, int type) -{ -#if defined(_TTHREAD_WIN32_) - mtx->mAlreadyLocked = FALSE; - mtx->mRecursive = type & mtx_recursive; - InitializeCriticalSection(&mtx->mHandle); - return thrd_success; -#else - int ret; - pthread_mutexattr_t attr; - pthread_mutexattr_init(&attr); - if (type & mtx_recursive) - { - pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); - } - ret = pthread_mutex_init(mtx, &attr); - pthread_mutexattr_destroy(&attr); - return ret == 0 ? thrd_success : thrd_error; -#endif -} - -void mtx_destroy(mtx_t *mtx) -{ -#if defined(_TTHREAD_WIN32_) - DeleteCriticalSection(&mtx->mHandle); -#else - pthread_mutex_destroy(mtx); -#endif -} - -int mtx_lock(mtx_t *mtx) -{ -#if defined(_TTHREAD_WIN32_) - EnterCriticalSection(&mtx->mHandle); - if (!mtx->mRecursive) - { - while(mtx->mAlreadyLocked) Sleep(1000); /* Simulate deadlock... */ - mtx->mAlreadyLocked = TRUE; - } - return thrd_success; -#else - return pthread_mutex_lock(mtx) == 0 ? thrd_success : thrd_error; -#endif -} - -int mtx_timedlock(mtx_t *mtx, const struct timespec *ts) -{ - /* FIXME! */ - (void)mtx; - (void)ts; - return thrd_error; -} - -int mtx_trylock(mtx_t *mtx) -{ -#if defined(_TTHREAD_WIN32_) - int ret = TryEnterCriticalSection(&mtx->mHandle) ? thrd_success : thrd_busy; - if ((!mtx->mRecursive) && (ret == thrd_success) && mtx->mAlreadyLocked) - { - LeaveCriticalSection(&mtx->mHandle); - ret = thrd_busy; - } - return ret; -#else - return (pthread_mutex_trylock(mtx) == 0) ? thrd_success : thrd_busy; -#endif -} - -int mtx_unlock(mtx_t *mtx) -{ -#if defined(_TTHREAD_WIN32_) - mtx->mAlreadyLocked = FALSE; - LeaveCriticalSection(&mtx->mHandle); - return thrd_success; -#else - return pthread_mutex_unlock(mtx) == 0 ? thrd_success : thrd_error;; -#endif -} - -#if defined(_TTHREAD_WIN32_) -#define _CONDITION_EVENT_ONE 0 -#define _CONDITION_EVENT_ALL 1 -#endif - -int cnd_init(cnd_t *cond) -{ -#if defined(_TTHREAD_WIN32_) - cond->mWaitersCount = 0; - - /* Init critical section */ - InitializeCriticalSection(&cond->mWaitersCountLock); - - /* Init events */ - cond->mEvents[_CONDITION_EVENT_ONE] = CreateEvent(NULL, FALSE, FALSE, NULL); - if (cond->mEvents[_CONDITION_EVENT_ONE] == NULL) - { - cond->mEvents[_CONDITION_EVENT_ALL] = NULL; - return thrd_error; - } - cond->mEvents[_CONDITION_EVENT_ALL] = CreateEvent(NULL, TRUE, FALSE, NULL); - if (cond->mEvents[_CONDITION_EVENT_ALL] == NULL) - { - CloseHandle(cond->mEvents[_CONDITION_EVENT_ONE]); - cond->mEvents[_CONDITION_EVENT_ONE] = NULL; - return thrd_error; - } - - return thrd_success; -#else - return pthread_cond_init(cond, NULL) == 0 ? thrd_success : thrd_error; -#endif -} - -void cnd_destroy(cnd_t *cond) -{ -#if defined(_TTHREAD_WIN32_) - if (cond->mEvents[_CONDITION_EVENT_ONE] != NULL) - { - CloseHandle(cond->mEvents[_CONDITION_EVENT_ONE]); - } - if (cond->mEvents[_CONDITION_EVENT_ALL] != NULL) - { - CloseHandle(cond->mEvents[_CONDITION_EVENT_ALL]); - } - DeleteCriticalSection(&cond->mWaitersCountLock); -#else - pthread_cond_destroy(cond); -#endif -} - -int cnd_signal(cnd_t *cond) -{ -#if defined(_TTHREAD_WIN32_) - int haveWaiters; - - /* Are there any waiters? */ - EnterCriticalSection(&cond->mWaitersCountLock); - haveWaiters = (cond->mWaitersCount > 0); - LeaveCriticalSection(&cond->mWaitersCountLock); - - /* If we have any waiting threads, send them a signal */ - if(haveWaiters) - { - if (SetEvent(cond->mEvents[_CONDITION_EVENT_ONE]) == 0) - { - return thrd_error; - } - } - - return thrd_success; -#else - return pthread_cond_signal(cond) == 0 ? thrd_success : thrd_error; -#endif -} - -int cnd_broadcast(cnd_t *cond) -{ -#if defined(_TTHREAD_WIN32_) - int haveWaiters; - - /* Are there any waiters? */ - EnterCriticalSection(&cond->mWaitersCountLock); - haveWaiters = (cond->mWaitersCount > 0); - LeaveCriticalSection(&cond->mWaitersCountLock); - - /* If we have any waiting threads, send them a signal */ - if(haveWaiters) - { - if (SetEvent(cond->mEvents[_CONDITION_EVENT_ALL]) == 0) - { - return thrd_error; - } - } - - return thrd_success; -#else - return pthread_cond_signal(cond) == 0 ? thrd_success : thrd_error; -#endif -} - -#if defined(_TTHREAD_WIN32_) -static int _cnd_timedwait_win32(cnd_t *cond, mtx_t *mtx, DWORD timeout) -{ - int result, lastWaiter; - - /* Increment number of waiters */ - EnterCriticalSection(&cond->mWaitersCountLock); - ++ cond->mWaitersCount; - LeaveCriticalSection(&cond->mWaitersCountLock); - - /* Release the mutex while waiting for the condition (will decrease - the number of waiters when done)... */ - mtx_unlock(mtx); - - /* Wait for either event to become signaled due to cnd_signal() or - cnd_broadcast() being called */ - result = WaitForMultipleObjects(2, cond->mEvents, FALSE, timeout); - if (result == WAIT_TIMEOUT) - { - return thrd_timeout; - } - else if (result == (int)WAIT_FAILED) - { - return thrd_error; - } - - /* Check if we are the last waiter */ - EnterCriticalSection(&cond->mWaitersCountLock); - -- cond->mWaitersCount; - lastWaiter = (result == (WAIT_OBJECT_0 + _CONDITION_EVENT_ALL)) && - (cond->mWaitersCount == 0); - LeaveCriticalSection(&cond->mWaitersCountLock); - - /* If we are the last waiter to be notified to stop waiting, reset the event */ - if (lastWaiter) - { - if (ResetEvent(cond->mEvents[_CONDITION_EVENT_ALL]) == 0) - { - return thrd_error; - } - } - - /* Re-acquire the mutex */ - mtx_lock(mtx); - - return thrd_success; -} -#endif - -int cnd_wait(cnd_t *cond, mtx_t *mtx) -{ -#if defined(_TTHREAD_WIN32_) - return _cnd_timedwait_win32(cond, mtx, INFINITE); -#else - return pthread_cond_wait(cond, mtx) == 0 ? thrd_success : thrd_error; -#endif -} - -int cnd_timedwait(cnd_t *cond, mtx_t *mtx, const struct timespec *ts) -{ -#if defined(_TTHREAD_WIN32_) - struct timespec now; - if (clock_gettime(CLOCK_REALTIME, &now) == 0) - { - DWORD delta = (DWORD) ((ts->tv_sec - now.tv_sec) * 1000 + - (ts->tv_nsec - now.tv_nsec + 500000) / 1000000); - return _cnd_timedwait_win32(cond, mtx, delta); - } - else - return thrd_error; -#else - int ret; - ret = pthread_cond_timedwait(cond, mtx, ts); - if (ret == ETIMEDOUT) - { - return thrd_timeout; - } - return ret == 0 ? thrd_success : thrd_error; -#endif -} - - -/** Information to pass to the new thread (what to run). */ -typedef struct { - thrd_start_t mFunction; /**< Pointer to the function to be executed. */ - void * mArg; /**< Function argument for the thread function. */ -} _thread_start_info; - -/* Thread wrapper function. */ -#if defined(_TTHREAD_WIN32_) -static unsigned WINAPI _thrd_wrapper_function(void * aArg) -#elif defined(_TTHREAD_POSIX_) -static void * _thrd_wrapper_function(void * aArg) -#endif -{ - thrd_start_t fun; - void *arg; - int res; -#if defined(_TTHREAD_POSIX_) - void *pres; -#endif - - /* Get thread startup information */ - _thread_start_info *ti = (_thread_start_info *) aArg; - fun = ti->mFunction; - arg = ti->mArg; - - /* The thread is responsible for freeing the startup information */ - free((void *)ti); - - /* Call the actual client thread function */ - res = fun(arg); - -#if defined(_TTHREAD_WIN32_) - return res; -#else - pres = malloc(sizeof(int)); - if (pres != NULL) - { - *(int*)pres = res; - } - return pres; -#endif -} - -int thrd_create(thrd_t *thr, thrd_start_t func, void *arg) -{ - /* Fill out the thread startup information (passed to the thread wrapper, - which will eventually free it) */ - _thread_start_info* ti = (_thread_start_info*)malloc(sizeof(_thread_start_info)); - if (ti == NULL) - { - return thrd_nomem; - } - ti->mFunction = func; - ti->mArg = arg; - - /* Create the thread */ -#if defined(_TTHREAD_WIN32_) - *thr = (HANDLE)_beginthreadex(NULL, 0, _thrd_wrapper_function, (void *)ti, 0, NULL); -#elif defined(_TTHREAD_POSIX_) - if(pthread_create(thr, NULL, _thrd_wrapper_function, (void *)ti) != 0) - { - *thr = 0; - } -#endif - - /* Did we fail to create the thread? */ - if(!*thr) - { - free(ti); - return thrd_error; - } - - return thrd_success; -} - -thrd_t thrd_current(void) -{ -#if defined(_TTHREAD_WIN32_) - return GetCurrentThread(); -#else - return pthread_self(); -#endif -} - -int thrd_detach(thrd_t thr) -{ - /* FIXME! */ - (void)thr; - return thrd_error; -} - -int thrd_equal(thrd_t thr0, thrd_t thr1) -{ -#if defined(_TTHREAD_WIN32_) - return thr0 == thr1; -#else - return pthread_equal(thr0, thr1); -#endif -} - -void thrd_exit(int res) -{ -#if defined(_TTHREAD_WIN32_) - ExitThread(res); -#else - void *pres = malloc(sizeof(int)); - if (pres != NULL) - { - *(int*)pres = res; - } - pthread_exit(pres); -#endif -} - -int thrd_join(thrd_t thr, int *res) -{ -#if defined(_TTHREAD_WIN32_) - if (WaitForSingleObject(thr, INFINITE) == WAIT_FAILED) - { - return thrd_error; - } - if (res != NULL) - { - DWORD dwRes; - GetExitCodeThread(thr, &dwRes); - *res = dwRes; - } -#elif defined(_TTHREAD_POSIX_) - void *pres; - int ires = 0; - if (pthread_join(thr, &pres) != 0) - { - return thrd_error; - } - if (pres != NULL) - { - ires = *(int*)pres; - free(pres); - } - if (res != NULL) - { - *res = ires; - } -#endif - return thrd_success; -} - -int thrd_sleep(const struct timespec *time_point, struct timespec *remaining) -{ - struct timespec now; -#if defined(_TTHREAD_WIN32_) - DWORD delta; -#else - long delta; -#endif - - /* Get the current time */ - if (clock_gettime(CLOCK_REALTIME, &now) != 0) - return -2; // FIXME: Some specific error code? - -#if defined(_TTHREAD_WIN32_) - /* Delta in milliseconds */ - delta = (DWORD) ((time_point->tv_sec - now.tv_sec) * 1000 + - (time_point->tv_nsec - now.tv_nsec + 500000) / 1000000); - if (delta > 0) - { - Sleep(delta); - } -#else - /* Delta in microseconds */ - delta = (time_point->tv_sec - now.tv_sec) * 1000000L + - (time_point->tv_nsec - now.tv_nsec + 500L) / 1000L; - - /* On some systems, the usleep argument must be < 1000000 */ - while (delta > 999999L) - { - usleep(999999); - delta -= 999999L; - } - if (delta > 0L) - { - usleep((useconds_t)delta); - } -#endif - - /* We don't support waking up prematurely (yet) */ - if (remaining) - { - remaining->tv_sec = 0; - remaining->tv_nsec = 0; - } - return 0; -} - -void thrd_yield(void) -{ -#if defined(_TTHREAD_WIN32_) - Sleep(0); -#else - sched_yield(); -#endif -} - -int tss_create(tss_t *key, tss_dtor_t dtor) -{ -#if defined(_TTHREAD_WIN32_) - /* FIXME: The destructor function is not supported yet... */ - if (dtor != NULL) - { - return thrd_error; - } - *key = TlsAlloc(); - if (*key == TLS_OUT_OF_INDEXES) - { - return thrd_error; - } -#else - if (pthread_key_create(key, dtor) != 0) - { - return thrd_error; - } -#endif - return thrd_success; -} - -void tss_delete(tss_t key) -{ -#if defined(_TTHREAD_WIN32_) - TlsFree(key); -#else - pthread_key_delete(key); -#endif -} - -void *tss_get(tss_t key) -{ -#if defined(_TTHREAD_WIN32_) - return TlsGetValue(key); -#else - return pthread_getspecific(key); -#endif -} - -int tss_set(tss_t key, void *val) -{ -#if defined(_TTHREAD_WIN32_) - if (TlsSetValue(key, val) == 0) - { - return thrd_error; - } -#else - if (pthread_setspecific(key, val) != 0) - { - return thrd_error; - } -#endif - return thrd_success; -} - -#if defined(_TTHREAD_EMULATE_CLOCK_GETTIME_) -int _tthread_clock_gettime(clockid_t clk_id, struct timespec *ts) -{ -#if defined(_TTHREAD_WIN32_) - struct _timeb tb; - _ftime(&tb); - ts->tv_sec = (time_t)tb.time; - ts->tv_nsec = 1000000L * (long)tb.millitm; -#else - struct timeval tv; - gettimeofday(&tv, NULL); - ts->tv_sec = (time_t)tv.tv_sec; - ts->tv_nsec = 1000L * (long)tv.tv_usec; -#endif - return 0; -} -#endif // _TTHREAD_EMULATE_CLOCK_GETTIME_ - diff --git a/src/external/glfw/deps/tinycthread.h b/src/external/glfw/deps/tinycthread.h deleted file mode 100644 index 42958c39..00000000 --- a/src/external/glfw/deps/tinycthread.h +++ /dev/null @@ -1,443 +0,0 @@ -/* -*- mode: c; tab-width: 2; indent-tabs-mode: nil; -*- -Copyright (c) 2012 Marcus Geelnard - -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, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - - 3. This notice may not be removed or altered from any source - distribution. -*/ - -#ifndef _TINYCTHREAD_H_ -#define _TINYCTHREAD_H_ - -/** -* @file -* @mainpage TinyCThread API Reference -* -* @section intro_sec Introduction -* TinyCThread is a minimal, portable implementation of basic threading -* classes for C. -* -* They closely mimic the functionality and naming of the C11 standard, and -* should be easily replaceable with the corresponding standard variants. -* -* @section port_sec Portability -* The Win32 variant uses the native Win32 API for implementing the thread -* classes, while for other systems, the POSIX threads API (pthread) is used. -* -* @section misc_sec Miscellaneous -* The following special keywords are available: #_Thread_local. -* -* For more detailed information, browse the different sections of this -* documentation. A good place to start is: -* tinycthread.h. -*/ - -/* Which platform are we on? */ -#if !defined(_TTHREAD_PLATFORM_DEFINED_) - #if defined(_WIN32) || defined(__WIN32__) || defined(__WINDOWS__) - #define _TTHREAD_WIN32_ - #else - #define _TTHREAD_POSIX_ - #endif - #define _TTHREAD_PLATFORM_DEFINED_ -#endif - -/* Activate some POSIX functionality (e.g. clock_gettime and recursive mutexes) */ -#if defined(_TTHREAD_POSIX_) - #undef _FEATURES_H - #if !defined(_GNU_SOURCE) - #define _GNU_SOURCE - #endif - #if !defined(_POSIX_C_SOURCE) || ((_POSIX_C_SOURCE - 0) < 199309L) - #undef _POSIX_C_SOURCE - #define _POSIX_C_SOURCE 199309L - #endif - #if !defined(_XOPEN_SOURCE) || ((_XOPEN_SOURCE - 0) < 500) - #undef _XOPEN_SOURCE - #define _XOPEN_SOURCE 500 - #endif -#endif - -/* Generic includes */ -#include - -/* Platform specific includes */ -#if defined(_TTHREAD_POSIX_) - #include - #include -#elif defined(_TTHREAD_WIN32_) - #ifndef WIN32_LEAN_AND_MEAN - #define WIN32_LEAN_AND_MEAN - #define __UNDEF_LEAN_AND_MEAN - #endif - #include - #ifdef __UNDEF_LEAN_AND_MEAN - #undef WIN32_LEAN_AND_MEAN - #undef __UNDEF_LEAN_AND_MEAN - #endif -#endif - -/* Workaround for missing TIME_UTC: If time.h doesn't provide TIME_UTC, - it's quite likely that libc does not support it either. Hence, fall back to - the only other supported time specifier: CLOCK_REALTIME (and if that fails, - we're probably emulating clock_gettime anyway, so anything goes). */ -#ifndef TIME_UTC - #ifdef CLOCK_REALTIME - #define TIME_UTC CLOCK_REALTIME - #else - #define TIME_UTC 0 - #endif -#endif - -/* Workaround for missing clock_gettime (most Windows compilers, afaik) */ -#if defined(_TTHREAD_WIN32_) || defined(__APPLE_CC__) -#define _TTHREAD_EMULATE_CLOCK_GETTIME_ -/* Emulate struct timespec */ -#if defined(_TTHREAD_WIN32_) -struct _ttherad_timespec { - time_t tv_sec; - long tv_nsec; -}; -#define timespec _ttherad_timespec -#endif - -/* Emulate clockid_t */ -typedef int _tthread_clockid_t; -#define clockid_t _tthread_clockid_t - -/* Emulate clock_gettime */ -int _tthread_clock_gettime(clockid_t clk_id, struct timespec *ts); -#define clock_gettime _tthread_clock_gettime -#ifndef CLOCK_REALTIME - #define CLOCK_REALTIME 0 -#endif -#endif - - -/** TinyCThread version (major number). */ -#define TINYCTHREAD_VERSION_MAJOR 1 -/** TinyCThread version (minor number). */ -#define TINYCTHREAD_VERSION_MINOR 1 -/** TinyCThread version (full version). */ -#define TINYCTHREAD_VERSION (TINYCTHREAD_VERSION_MAJOR * 100 + TINYCTHREAD_VERSION_MINOR) - -/** -* @def _Thread_local -* Thread local storage keyword. -* A variable that is declared with the @c _Thread_local keyword makes the -* value of the variable local to each thread (known as thread-local storage, -* or TLS). Example usage: -* @code -* // This variable is local to each thread. -* _Thread_local int variable; -* @endcode -* @note The @c _Thread_local keyword is a macro that maps to the corresponding -* compiler directive (e.g. @c __declspec(thread)). -* @note This directive is currently not supported on Mac OS X (it will give -* a compiler error), since compile-time TLS is not supported in the Mac OS X -* executable format. Also, some older versions of MinGW (before GCC 4.x) do -* not support this directive. -* @hideinitializer -*/ - -/* FIXME: Check for a PROPER value of __STDC_VERSION__ to know if we have C11 */ -#if !(defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201102L)) && !defined(_Thread_local) - #if defined(__GNUC__) || defined(__INTEL_COMPILER) || defined(__SUNPRO_CC) || defined(__IBMCPP__) - #define _Thread_local __thread - #else - #define _Thread_local __declspec(thread) - #endif -#endif - -/* Macros */ -#define TSS_DTOR_ITERATIONS 0 - -/* Function return values */ -#define thrd_error 0 /**< The requested operation failed */ -#define thrd_success 1 /**< The requested operation succeeded */ -#define thrd_timeout 2 /**< The time specified in the call was reached without acquiring the requested resource */ -#define thrd_busy 3 /**< The requested operation failed because a tesource requested by a test and return function is already in use */ -#define thrd_nomem 4 /**< The requested operation failed because it was unable to allocate memory */ - -/* Mutex types */ -#define mtx_plain 1 -#define mtx_timed 2 -#define mtx_try 4 -#define mtx_recursive 8 - -/* Mutex */ -#if defined(_TTHREAD_WIN32_) -typedef struct { - CRITICAL_SECTION mHandle; /* Critical section handle */ - int mAlreadyLocked; /* TRUE if the mutex is already locked */ - int mRecursive; /* TRUE if the mutex is recursive */ -} mtx_t; -#else -typedef pthread_mutex_t mtx_t; -#endif - -/** Create a mutex object. -* @param mtx A mutex object. -* @param type Bit-mask that must have one of the following six values: -* @li @c mtx_plain for a simple non-recursive mutex -* @li @c mtx_timed for a non-recursive mutex that supports timeout -* @li @c mtx_try for a non-recursive mutex that supports test and return -* @li @c mtx_plain | @c mtx_recursive (same as @c mtx_plain, but recursive) -* @li @c mtx_timed | @c mtx_recursive (same as @c mtx_timed, but recursive) -* @li @c mtx_try | @c mtx_recursive (same as @c mtx_try, but recursive) -* @return @ref thrd_success on success, or @ref thrd_error if the request could -* not be honored. -*/ -int mtx_init(mtx_t *mtx, int type); - -/** Release any resources used by the given mutex. -* @param mtx A mutex object. -*/ -void mtx_destroy(mtx_t *mtx); - -/** Lock the given mutex. -* Blocks until the given mutex can be locked. If the mutex is non-recursive, and -* the calling thread already has a lock on the mutex, this call will block -* forever. -* @param mtx A mutex object. -* @return @ref thrd_success on success, or @ref thrd_error if the request could -* not be honored. -*/ -int mtx_lock(mtx_t *mtx); - -/** NOT YET IMPLEMENTED. -*/ -int mtx_timedlock(mtx_t *mtx, const struct timespec *ts); - -/** Try to lock the given mutex. -* The specified mutex shall support either test and return or timeout. If the -* mutex is already locked, the function returns without blocking. -* @param mtx A mutex object. -* @return @ref thrd_success on success, or @ref thrd_busy if the resource -* requested is already in use, or @ref thrd_error if the request could not be -* honored. -*/ -int mtx_trylock(mtx_t *mtx); - -/** Unlock the given mutex. -* @param mtx A mutex object. -* @return @ref thrd_success on success, or @ref thrd_error if the request could -* not be honored. -*/ -int mtx_unlock(mtx_t *mtx); - -/* Condition variable */ -#if defined(_TTHREAD_WIN32_) -typedef struct { - HANDLE mEvents[2]; /* Signal and broadcast event HANDLEs. */ - unsigned int mWaitersCount; /* Count of the number of waiters. */ - CRITICAL_SECTION mWaitersCountLock; /* Serialize access to mWaitersCount. */ -} cnd_t; -#else -typedef pthread_cond_t cnd_t; -#endif - -/** Create a condition variable object. -* @param cond A condition variable object. -* @return @ref thrd_success on success, or @ref thrd_error if the request could -* not be honored. -*/ -int cnd_init(cnd_t *cond); - -/** Release any resources used by the given condition variable. -* @param cond A condition variable object. -*/ -void cnd_destroy(cnd_t *cond); - -/** Signal a condition variable. -* Unblocks one of the threads that are blocked on the given condition variable -* at the time of the call. If no threads are blocked on the condition variable -* at the time of the call, the function does nothing and return success. -* @param cond A condition variable object. -* @return @ref thrd_success on success, or @ref thrd_error if the request could -* not be honored. -*/ -int cnd_signal(cnd_t *cond); - -/** Broadcast a condition variable. -* Unblocks all of the threads that are blocked on the given condition variable -* at the time of the call. If no threads are blocked on the condition variable -* at the time of the call, the function does nothing and return success. -* @param cond A condition variable object. -* @return @ref thrd_success on success, or @ref thrd_error if the request could -* not be honored. -*/ -int cnd_broadcast(cnd_t *cond); - -/** Wait for a condition variable to become signaled. -* The function atomically unlocks the given mutex and endeavors to block until -* the given condition variable is signaled by a call to cnd_signal or to -* cnd_broadcast. When the calling thread becomes unblocked it locks the mutex -* before it returns. -* @param cond A condition variable object. -* @param mtx A mutex object. -* @return @ref thrd_success on success, or @ref thrd_error if the request could -* not be honored. -*/ -int cnd_wait(cnd_t *cond, mtx_t *mtx); - -/** Wait for a condition variable to become signaled. -* The function atomically unlocks the given mutex and endeavors to block until -* the given condition variable is signaled by a call to cnd_signal or to -* cnd_broadcast, or until after the specified time. When the calling thread -* becomes unblocked it locks the mutex before it returns. -* @param cond A condition variable object. -* @param mtx A mutex object. -* @param xt A point in time at which the request will time out (absolute time). -* @return @ref thrd_success upon success, or @ref thrd_timeout if the time -* specified in the call was reached without acquiring the requested resource, or -* @ref thrd_error if the request could not be honored. -*/ -int cnd_timedwait(cnd_t *cond, mtx_t *mtx, const struct timespec *ts); - -/* Thread */ -#if defined(_TTHREAD_WIN32_) -typedef HANDLE thrd_t; -#else -typedef pthread_t thrd_t; -#endif - -/** Thread start function. -* Any thread that is started with the @ref thrd_create() function must be -* started through a function of this type. -* @param arg The thread argument (the @c arg argument of the corresponding -* @ref thrd_create() call). -* @return The thread return value, which can be obtained by another thread -* by using the @ref thrd_join() function. -*/ -typedef int (*thrd_start_t)(void *arg); - -/** Create a new thread. -* @param thr Identifier of the newly created thread. -* @param func A function pointer to the function that will be executed in -* the new thread. -* @param arg An argument to the thread function. -* @return @ref thrd_success on success, or @ref thrd_nomem if no memory could -* be allocated for the thread requested, or @ref thrd_error if the request -* could not be honored. -* @note A threadโ€™s identifier may be reused for a different thread once the -* original thread has exited and either been detached or joined to another -* thread. -*/ -int thrd_create(thrd_t *thr, thrd_start_t func, void *arg); - -/** Identify the calling thread. -* @return The identifier of the calling thread. -*/ -thrd_t thrd_current(void); - -/** NOT YET IMPLEMENTED. -*/ -int thrd_detach(thrd_t thr); - -/** Compare two thread identifiers. -* The function determines if two thread identifiers refer to the same thread. -* @return Zero if the two thread identifiers refer to different threads. -* Otherwise a nonzero value is returned. -*/ -int thrd_equal(thrd_t thr0, thrd_t thr1); - -/** Terminate execution of the calling thread. -* @param res Result code of the calling thread. -*/ -void thrd_exit(int res); - -/** Wait for a thread to terminate. -* The function joins the given thread with the current thread by blocking -* until the other thread has terminated. -* @param thr The thread to join with. -* @param res If this pointer is not NULL, the function will store the result -* code of the given thread in the integer pointed to by @c res. -* @return @ref thrd_success on success, or @ref thrd_error if the request could -* not be honored. -*/ -int thrd_join(thrd_t thr, int *res); - -/** Put the calling thread to sleep. -* Suspend execution of the calling thread. -* @param time_point A point in time at which the thread will resume (absolute time). -* @param remaining If non-NULL, this parameter will hold the remaining time until -* time_point upon return. This will typically be zero, but if -* the thread was woken up by a signal that is not ignored before -* time_point was reached @c remaining will hold a positive -* time. -* @return 0 (zero) on successful sleep, or -1 if an interrupt occurred. -*/ -int thrd_sleep(const struct timespec *time_point, struct timespec *remaining); - -/** Yield execution to another thread. -* Permit other threads to run, even if the current thread would ordinarily -* continue to run. -*/ -void thrd_yield(void); - -/* Thread local storage */ -#if defined(_TTHREAD_WIN32_) -typedef DWORD tss_t; -#else -typedef pthread_key_t tss_t; -#endif - -/** Destructor function for a thread-specific storage. -* @param val The value of the destructed thread-specific storage. -*/ -typedef void (*tss_dtor_t)(void *val); - -/** Create a thread-specific storage. -* @param key The unique key identifier that will be set if the function is -* successful. -* @param dtor Destructor function. This can be NULL. -* @return @ref thrd_success on success, or @ref thrd_error if the request could -* not be honored. -* @note The destructor function is not supported under Windows. If @c dtor is -* not NULL when calling this function under Windows, the function will fail -* and return @ref thrd_error. -*/ -int tss_create(tss_t *key, tss_dtor_t dtor); - -/** Delete a thread-specific storage. -* The function releases any resources used by the given thread-specific -* storage. -* @param key The key that shall be deleted. -*/ -void tss_delete(tss_t key); - -/** Get the value for a thread-specific storage. -* @param key The thread-specific storage identifier. -* @return The value for the current thread held in the given thread-specific -* storage. -*/ -void *tss_get(tss_t key); - -/** Set the value for a thread-specific storage. -* @param key The thread-specific storage identifier. -* @param val The value of the thread-specific storage to set for the current -* thread. -* @return @ref thrd_success on success, or @ref thrd_error if the request could -* not be honored. -*/ -int tss_set(tss_t key, void *val); - - -#endif /* _TINYTHREAD_H_ */ - -- cgit v1.2.3 From 8ed71b9d5a90ccca5551aaf069318e3c8b4a87e6 Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 23 Apr 2019 14:51:32 +0200 Subject: Some tweaks to custom memory management system --- src/external/rgif.h | 40 ++++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 20 deletions(-) (limited to 'src') diff --git a/src/external/rgif.h b/src/external/rgif.h index 44ee13b3..13c7ff3e 100644 --- a/src/external/rgif.h +++ b/src/external/rgif.h @@ -32,7 +32,7 @@ * * ALTERNATIVE A - MIT License * -* Copyright (c) 2017 Ramon Santamaria +* Copyright (c) 2017-2019 Ramon Santamaria (@raysan5) * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in @@ -76,8 +76,8 @@ * **********************************************************************************************/ -#ifndef GIF_H -#define GIF_H +#ifndef RGIF_H +#define RGIF_H #include // Required for: FILE @@ -101,7 +101,7 @@ RGIFDEF bool GifBegin(const char *filename, unsigned int width, unsigned int hei RGIFDEF bool GifWriteFrame(const unsigned char *image, unsigned int width, unsigned int height, unsigned int delay, int bitDepth, bool dither); RGIFDEF bool GifEnd(); -#endif // GIF_H +#endif // RGIF_H /*********************************************************************************** @@ -116,23 +116,23 @@ RGIFDEF bool GifEnd(); #include // Required for: memcpy() // Define these macros to hook into a custom memory allocator. -// GIF_TEMP_MALLOC and GIF_TEMP_FREE will only be called in stack fashion - frees in the reverse order of mallocs +// RGIF_TEMP_MALLOC and RGIF_TEMP_FREE will only be called in stack fashion - frees in the reverse order of mallocs // and any temp memory allocated by a function will be freed before it exits. -#if !defined(GIF_TEMP_MALLOC) +#if !defined(RGIF_TEMP_MALLOC) #include - #define GIF_TEMP_MALLOC malloc - #define GIF_TEMP_FREE free + #define RGIF_TEMP_MALLOC malloc + #define RGIF_TEMP_FREE free #endif // Check if custom malloc/free functions defined, if not, using standard ones -// GIF_MALLOC and GIF_FREE are used only by GifBegin and GifEnd respectively, +// RGIF_MALLOC and RGIF_FREE are used only by GifBegin and GifEnd respectively, // to allocate a buffer the size of the image, which is used to find changed pixels for delta-encoding. -#if !defined(GIF_MALLOC) +#if !defined(RGIF_MALLOC) #include // Required for: malloc(), free() - #define GIF_MALLOC(size) malloc(size) - #define GIF_FREE(ptr) free(ptr) + #define RGIF_MALLOC(size) malloc(size) + #define RGIF_FREE(ptr) free(ptr) #endif //---------------------------------------------------------------------------------- @@ -223,7 +223,7 @@ RGIFDEF bool GifBegin(const char *filename, unsigned int width, unsigned int hei if (!gifFile) return false; // Allocate space for one gif frame - gifFrame = (unsigned char *)GIF_MALLOC(width*height*4); + gifFrame = (unsigned char *)RGIF_MALLOC(width*height*4); // GIF Header fputs("GIF89a",gifFile); @@ -300,7 +300,7 @@ RGIFDEF bool GifEnd() fputc(0x3b, gifFile); // Trailer (end of file) fclose(gifFile); - GIF_FREE(gifFrame); + RGIF_FREE(gifFrame); gifFile = NULL; gifFrame = NULL; @@ -589,7 +589,7 @@ static void GifMakePalette(const unsigned char *lastFrame, const unsigned char * // SplitPalette is destructive (it sorts the pixels by color) so // we must create a copy of the image for it to destroy int imageSize = width*height*4*sizeof(unsigned char); - unsigned char *destroyableImage = (unsigned char*)GIF_TEMP_MALLOC(imageSize); + unsigned char *destroyableImage = (unsigned char*)RGIF_TEMP_MALLOC(imageSize); memcpy(destroyableImage, nextFrame, imageSize); int numPixels = width*height; @@ -602,7 +602,7 @@ static void GifMakePalette(const unsigned char *lastFrame, const unsigned char * GifSplitPalette(destroyableImage, numPixels, 1, lastElt, splitElt, splitDist, 1, buildForDither, pPal); - GIF_TEMP_FREE(destroyableImage); + RGIF_TEMP_FREE(destroyableImage); // add the bottom node for the transparency index pPal->treeSplit[1 << (bitDepth-1)] = 0; @@ -619,7 +619,7 @@ static void GifDitherImage(const unsigned char *lastFrame, const unsigned char * // quantPixels initially holds color*256 for all pixels // The extra 8 bits of precision allow for sub-single-color error values // to be propagated - int *quantPixels = (int*)GIF_TEMP_MALLOC(sizeof(int)*numPixels*4); + int *quantPixels = (int*)RGIF_TEMP_MALLOC(sizeof(int)*numPixels*4); for (int ii=0; ii Date: Tue, 23 Apr 2019 14:55:35 +0200 Subject: Support custom memory management macros Users can define their custom memory management macros. NOTE: Most external libraries support custom macros in the same way, raylib should redefine those macros to raylib ones, to unify custom memory loading. That redefinition is only implemented as example for stb_image.h in [textures] module. --- src/core.c | 24 ++--- src/models.c | 291 +++++++++++++++++++++++++++++---------------------------- src/raudio.c | 38 ++++---- src/raudio.h | 11 ++- src/raylib.h | 11 +++ src/rlgl.h | 88 ++++++++--------- src/text.c | 54 +++++------ src/textures.c | 181 ++++++++++++++++++----------------- src/utils.c | 6 +- 9 files changed, 365 insertions(+), 339 deletions(-) (limited to 'src') diff --git a/src/core.c b/src/core.c index 6bb54c51..844994d0 100644 --- a/src/core.c +++ b/src/core.c @@ -1113,7 +1113,7 @@ void EndDrawing(void) unsigned char *screenData = rlReadScreenPixels(screenWidth, screenHeight); GifWriteFrame(screenData, screenWidth, screenHeight, 10, 8, false); - free(screenData); // Free image data + RL_FREE(screenData); // Free image data } if (((gifFramesCounter/15)%2) == 1) @@ -1595,7 +1595,7 @@ void TakeScreenshot(const char *fileName) #endif ExportImage(image, path); - free(imgData); + RL_FREE(imgData); #if defined(PLATFORM_WEB) // Download file from MEMFS (emscripten memory filesystem) @@ -1742,8 +1742,8 @@ char **GetDirectoryFiles(const char *dirPath, int *fileCount) ClearDirectoryFiles(); // Memory allocation for MAX_DIRECTORY_FILES - dirFilesPath = (char **)malloc(sizeof(char *)*MAX_DIRECTORY_FILES); - for (int i = 0; i < MAX_DIRECTORY_FILES; i++) dirFilesPath[i] = (char *)malloc(sizeof(char)*MAX_FILEPATH_LENGTH); + dirFilesPath = (char **)RL_MALLOC(sizeof(char *)*MAX_DIRECTORY_FILES); + for (int i = 0; i < MAX_DIRECTORY_FILES; i++) dirFilesPath[i] = (char *)RL_MALLOC(sizeof(char)*MAX_FILEPATH_LENGTH); int counter = 0; struct dirent *ent; @@ -1776,9 +1776,9 @@ void ClearDirectoryFiles(void) { if (dirFilesCount > 0) { - for (int i = 0; i < dirFilesCount; i++) free(dirFilesPath[i]); + for (int i = 0; i < dirFilesCount; i++) RL_FREE(dirFilesPath[i]); - free(dirFilesPath); + RL_FREE(dirFilesPath); dirFilesCount = 0; } } @@ -1808,9 +1808,9 @@ void ClearDroppedFiles(void) { if (dropFilesCount > 0) { - for (int i = 0; i < dropFilesCount; i++) free(dropFilesPath[i]); + for (int i = 0; i < dropFilesCount; i++) RL_FREE(dropFilesPath[i]); - free(dropFilesPath); + RL_FREE(dropFilesPath); dropFilesCount = 0; } @@ -1925,7 +1925,7 @@ void OpenURL(const char *url) } else { - char *cmd = (char *)calloc(strlen(url) + 10, sizeof(char)); + char *cmd = (char *)RL_CALLOC(strlen(url) + 10, sizeof(char)); #if defined(_WIN32) sprintf(cmd, "explorer %s", url); @@ -1935,7 +1935,7 @@ void OpenURL(const char *url) sprintf(cmd, "open '%s'", url); #endif system(cmd); - free(cmd); + RL_FREE(cmd); } } @@ -3455,11 +3455,11 @@ static void WindowDropCallback(GLFWwindow *window, int count, const char **paths { ClearDroppedFiles(); - dropFilesPath = (char **)malloc(sizeof(char *)*count); + dropFilesPath = (char **)RL_MALLOC(sizeof(char *)*count); for (int i = 0; i < count; i++) { - dropFilesPath[i] = (char *)malloc(sizeof(char)*MAX_FILEPATH_LENGTH); + dropFilesPath[i] = (char *)RL_MALLOC(sizeof(char)*MAX_FILEPATH_LENGTH); strcpy(dropFilesPath[i], paths[i]); } diff --git a/src/models.c b/src/models.c index 631c4942..c81dfe19 100644 --- a/src/models.c +++ b/src/models.c @@ -651,7 +651,7 @@ Model LoadModel(const char *fileName) TraceLog(LOG_WARNING, "[%s] No meshes can be loaded, default to cube mesh", fileName); model.meshCount = 1; - model.meshes = (Mesh *)calloc(model.meshCount, sizeof(Mesh)); + model.meshes = (Mesh *)RL_CALLOC(model.meshCount, sizeof(Mesh)); model.meshes[0] = GenMeshCube(1.0f, 1.0f, 1.0f); } else @@ -665,10 +665,10 @@ Model LoadModel(const char *fileName) TraceLog(LOG_WARNING, "[%s] No materials can be loaded, default to white material", fileName); model.materialCount = 1; - model.materials = (Material *)calloc(model.materialCount, sizeof(Material)); + model.materials = (Material *)RL_CALLOC(model.materialCount, sizeof(Material)); model.materials[0] = LoadMaterialDefault(); - model.meshMaterial = (int *)calloc(model.meshCount, sizeof(int)); + model.meshMaterial = (int *)RL_CALLOC(model.meshCount, sizeof(int)); } return model; @@ -685,14 +685,14 @@ Model LoadModelFromMesh(Mesh mesh) model.transform = MatrixIdentity(); model.meshCount = 1; - model.meshes = (Mesh *)malloc(model.meshCount*sizeof(Mesh)); + model.meshes = (Mesh *)RL_MALLOC(model.meshCount*sizeof(Mesh)); model.meshes[0] = mesh; model.materialCount = 1; - model.materials = (Material *)malloc(model.materialCount*sizeof(Material)); + model.materials = (Material *)RL_MALLOC(model.materialCount*sizeof(Material)); model.materials[0] = LoadMaterialDefault(); - model.meshMaterial = (int *)malloc(model.meshCount*sizeof(int)); + model.meshMaterial = (int *)RL_MALLOC(model.meshCount*sizeof(int)); model.meshMaterial[0] = 0; // First material index return model; @@ -704,13 +704,13 @@ void UnloadModel(Model model) for (int i = 0; i < model.meshCount; i++) UnloadMesh(&model.meshes[i]); for (int i = 0; i < model.materialCount; i++) UnloadMaterial(model.materials[i]); - free(model.meshes); - free(model.materials); - free(model.meshMaterial); + RL_FREE(model.meshes); + RL_FREE(model.materials); + RL_FREE(model.meshMaterial); // Unload animation data - free(model.bones); - free(model.bindPose); + RL_FREE(model.bones); + RL_FREE(model.bindPose); TraceLog(LOG_INFO, "Unloaded model data from RAM and VRAM"); } @@ -866,7 +866,7 @@ void SetModelMeshMaterial(Model *model, int meshId, int materialId) // Load model animations from file ModelAnimation *LoadModelAnimations(const char *filename, int *animCount) { - ModelAnimation *animations = (ModelAnimation *)malloc(1*sizeof(ModelAnimation)); + ModelAnimation *animations = (ModelAnimation *)RL_MALLOC(1*sizeof(ModelAnimation)); int count = 1; #define IQM_MAGIC "INTERQUAKEMODEL" // IQM file magic number @@ -935,12 +935,12 @@ ModelAnimation *LoadModelAnimations(const char *filename, int *animCount) // bones IQMPose *poses; - poses = malloc(sizeof(IQMPose)*iqm.num_poses); + poses = RL_MALLOC(sizeof(IQMPose)*iqm.num_poses); fseek(iqmFile, iqm.ofs_poses, SEEK_SET); fread(poses, sizeof(IQMPose)*iqm.num_poses, 1, iqmFile); animation.boneCount = iqm.num_poses; - animation.bones = malloc(sizeof(BoneInfo)*iqm.num_poses); + animation.bones = RL_MALLOC(sizeof(BoneInfo)*iqm.num_poses); for (int j = 0; j < iqm.num_poses; j++) { @@ -957,12 +957,12 @@ ModelAnimation *LoadModelAnimations(const char *filename, int *animCount) //animation.framerate = anim.framerate; // frameposes - unsigned short *framedata = malloc(sizeof(unsigned short)*iqm.num_frames*iqm.num_framechannels); + unsigned short *framedata = RL_MALLOC(sizeof(unsigned short)*iqm.num_frames*iqm.num_framechannels); fseek(iqmFile, iqm.ofs_frames, SEEK_SET); fread(framedata, sizeof(unsigned short)*iqm.num_frames*iqm.num_framechannels, 1, iqmFile); - animation.framePoses = malloc(sizeof(Transform*)*anim.num_frames); - for (int j = 0; j < anim.num_frames; j++) animation.framePoses[j] = malloc(sizeof(Transform)*iqm.num_poses); + animation.framePoses = RL_MALLOC(sizeof(Transform*)*anim.num_frames); + for (int j = 0; j < anim.num_frames; j++) animation.framePoses[j] = RL_MALLOC(sizeof(Transform)*iqm.num_poses); int dcounter = anim.first_frame*iqm.num_framechannels; @@ -1069,8 +1069,8 @@ ModelAnimation *LoadModelAnimations(const char *filename, int *animCount) } } - free(framedata); - free(poses); + RL_FREE(framedata); + RL_FREE(poses); fclose(iqmFile); @@ -1145,10 +1145,10 @@ void UpdateModelAnimation(Model model, ModelAnimation anim, int frame) // Unload animation data void UnloadModelAnimation(ModelAnimation anim) { - for (int i = 0; i < anim.frameCount; i++) free(anim.framePoses[i]); + for (int i = 0; i < anim.frameCount; i++) RL_FREE(anim.framePoses[i]); - free(anim.bones); - free(anim.framePoses); + RL_FREE(anim.bones); + RL_FREE(anim.framePoses); } // Check model animation skeleton match @@ -1177,7 +1177,7 @@ Mesh GenMeshPoly(int sides, float radius) int vertexCount = sides*3; // Vertices definition - Vector3 *vertices = (Vector3 *)malloc(vertexCount*sizeof(Vector3)); + Vector3 *vertices = (Vector3 *)RL_MALLOC(vertexCount*sizeof(Vector3)); for (int i = 0, v = 0; i < 360; i += 360/sides, v += 3) { vertices[v] = (Vector3){ 0.0f, 0.0f, 0.0f }; @@ -1186,18 +1186,18 @@ Mesh GenMeshPoly(int sides, float radius) } // Normals definition - Vector3 *normals = (Vector3 *)malloc(vertexCount*sizeof(Vector3)); + Vector3 *normals = (Vector3 *)RL_MALLOC(vertexCount*sizeof(Vector3)); for (int n = 0; n < vertexCount; n++) normals[n] = (Vector3){ 0.0f, 1.0f, 0.0f }; // Vector3.up; // TexCoords definition - Vector2 *texcoords = (Vector2 *)malloc(vertexCount*sizeof(Vector2)); + Vector2 *texcoords = (Vector2 *)RL_MALLOC(vertexCount*sizeof(Vector2)); for (int n = 0; n < vertexCount; n++) texcoords[n] = (Vector2){ 0.0f, 0.0f }; mesh.vertexCount = vertexCount; mesh.triangleCount = sides; - mesh.vertices = (float *)malloc(mesh.vertexCount*3*sizeof(float)); - mesh.texcoords = (float *)malloc(mesh.vertexCount*2*sizeof(float)); - mesh.normals = (float *)malloc(mesh.vertexCount*3*sizeof(float)); + mesh.vertices = (float *)RL_MALLOC(mesh.vertexCount*3*sizeof(float)); + mesh.texcoords = (float *)RL_MALLOC(mesh.vertexCount*2*sizeof(float)); + mesh.normals = (float *)RL_MALLOC(mesh.vertexCount*3*sizeof(float)); // Mesh vertices position array for (int i = 0; i < mesh.vertexCount; i++) @@ -1222,9 +1222,9 @@ Mesh GenMeshPoly(int sides, float radius) mesh.normals[3*i + 2] = normals[i].z; } - free(vertices); - free(normals); - free(texcoords); + RL_FREE(vertices); + RL_FREE(normals); + RL_FREE(texcoords); // Upload vertex data to GPU (static mesh) rlLoadMesh(&mesh, false); @@ -1245,7 +1245,7 @@ Mesh GenMeshPlane(float width, float length, int resX, int resZ) // Vertices definition int vertexCount = resX*resZ; // vertices get reused for the faces - Vector3 *vertices = (Vector3 *)malloc(vertexCount*sizeof(Vector3)); + Vector3 *vertices = (Vector3 *)RL_MALLOC(vertexCount*sizeof(Vector3)); for (int z = 0; z < resZ; z++) { // [-length/2, length/2] @@ -1259,11 +1259,11 @@ Mesh GenMeshPlane(float width, float length, int resX, int resZ) } // Normals definition - Vector3 *normals = (Vector3 *)malloc(vertexCount*sizeof(Vector3)); + Vector3 *normals = (Vector3 *)RL_MALLOC(vertexCount*sizeof(Vector3)); for (int n = 0; n < vertexCount; n++) normals[n] = (Vector3){ 0.0f, 1.0f, 0.0f }; // Vector3.up; // TexCoords definition - Vector2 *texcoords = (Vector2 *)malloc(vertexCount*sizeof(Vector2)); + Vector2 *texcoords = (Vector2 *)RL_MALLOC(vertexCount*sizeof(Vector2)); for (int v = 0; v < resZ; v++) { for (int u = 0; u < resX; u++) @@ -1274,7 +1274,7 @@ Mesh GenMeshPlane(float width, float length, int resX, int resZ) // Triangles definition (indices) int numFaces = (resX - 1)*(resZ - 1); - int *triangles = (int *)malloc(numFaces*6*sizeof(int)); + int *triangles = (int *)RL_MALLOC(numFaces*6*sizeof(int)); int t = 0; for (int face = 0; face < numFaces; face++) { @@ -1292,10 +1292,10 @@ Mesh GenMeshPlane(float width, float length, int resX, int resZ) mesh.vertexCount = vertexCount; mesh.triangleCount = numFaces*2; - mesh.vertices = (float *)malloc(mesh.vertexCount*3*sizeof(float)); - mesh.texcoords = (float *)malloc(mesh.vertexCount*2*sizeof(float)); - mesh.normals = (float *)malloc(mesh.vertexCount*3*sizeof(float)); - mesh.indices = (unsigned short *)malloc(mesh.triangleCount*3*sizeof(unsigned short)); + mesh.vertices = (float *)RL_MALLOC(mesh.vertexCount*3*sizeof(float)); + mesh.texcoords = (float *)RL_MALLOC(mesh.vertexCount*2*sizeof(float)); + mesh.normals = (float *)RL_MALLOC(mesh.vertexCount*3*sizeof(float)); + mesh.indices = (unsigned short *)RL_MALLOC(mesh.triangleCount*3*sizeof(unsigned short)); // Mesh vertices position array for (int i = 0; i < mesh.vertexCount; i++) @@ -1323,10 +1323,10 @@ Mesh GenMeshPlane(float width, float length, int resX, int resZ) // Mesh indices array initialization for (int i = 0; i < mesh.triangleCount*3; i++) mesh.indices[i] = triangles[i]; - free(vertices); - free(normals); - free(texcoords); - free(triangles); + RL_FREE(vertices); + RL_FREE(normals); + RL_FREE(texcoords); + RL_FREE(triangles); #else // Use par_shapes library to generate plane mesh @@ -1335,9 +1335,9 @@ Mesh GenMeshPlane(float width, float length, int resX, int resZ) par_shapes_rotate(plane, -PI/2.0f, (float[]){ 1, 0, 0 }); par_shapes_translate(plane, -width/2, 0.0f, length/2); - mesh.vertices = (float *)malloc(plane->ntriangles*3*3*sizeof(float)); - mesh.texcoords = (float *)malloc(plane->ntriangles*3*2*sizeof(float)); - mesh.normals = (float *)malloc(plane->ntriangles*3*3*sizeof(float)); + mesh.vertices = (float *)RL_MALLOC(plane->ntriangles*3*3*sizeof(float)); + mesh.texcoords = (float *)RL_MALLOC(plane->ntriangles*3*2*sizeof(float)); + mesh.normals = (float *)RL_MALLOC(plane->ntriangles*3*3*sizeof(float)); mesh.vertexCount = plane->ntriangles*3; mesh.triangleCount = plane->ntriangles; @@ -1453,16 +1453,16 @@ Mesh GenMeshCube(float width, float height, float length) -1.0f, 0.0f, 0.0f }; - mesh.vertices = (float *)malloc(24*3*sizeof(float)); + mesh.vertices = (float *)RL_MALLOC(24*3*sizeof(float)); memcpy(mesh.vertices, vertices, 24*3*sizeof(float)); - mesh.texcoords = (float *)malloc(24*2*sizeof(float)); + mesh.texcoords = (float *)RL_MALLOC(24*2*sizeof(float)); memcpy(mesh.texcoords, texcoords, 24*2*sizeof(float)); - mesh.normals = (float *)malloc(24*3*sizeof(float)); + mesh.normals = (float *)RL_MALLOC(24*3*sizeof(float)); memcpy(mesh.normals, normals, 24*3*sizeof(float)); - mesh.indices = (unsigned short *)malloc(36*sizeof(unsigned short)); + mesh.indices = (unsigned short *)RL_MALLOC(36*sizeof(unsigned short)); int k = 0; @@ -1500,9 +1500,9 @@ par_shapes_mesh* par_shapes_create_icosahedron(); // 20 sides polyhedron par_shapes_translate(cube, -width/2, 0.0f, -length/2); par_shapes_compute_normals(cube); - mesh.vertices = (float *)malloc(cube->ntriangles*3*3*sizeof(float)); - mesh.texcoords = (float *)malloc(cube->ntriangles*3*2*sizeof(float)); - mesh.normals = (float *)malloc(cube->ntriangles*3*3*sizeof(float)); + mesh.vertices = (float *)RL_MALLOC(cube->ntriangles*3*3*sizeof(float)); + mesh.texcoords = (float *)RL_MALLOC(cube->ntriangles*3*2*sizeof(float)); + mesh.normals = (float *)RL_MALLOC(cube->ntriangles*3*3*sizeof(float)); mesh.vertexCount = cube->ntriangles*3; mesh.triangleCount = cube->ntriangles; @@ -1539,9 +1539,9 @@ RLAPI Mesh GenMeshSphere(float radius, int rings, int slices) par_shapes_scale(sphere, radius, radius, radius); // NOTE: Soft normals are computed internally - mesh.vertices = (float *)malloc(sphere->ntriangles*3*3*sizeof(float)); - mesh.texcoords = (float *)malloc(sphere->ntriangles*3*2*sizeof(float)); - mesh.normals = (float *)malloc(sphere->ntriangles*3*3*sizeof(float)); + mesh.vertices = (float *)RL_MALLOC(sphere->ntriangles*3*3*sizeof(float)); + mesh.texcoords = (float *)RL_MALLOC(sphere->ntriangles*3*2*sizeof(float)); + mesh.normals = (float *)RL_MALLOC(sphere->ntriangles*3*3*sizeof(float)); mesh.vertexCount = sphere->ntriangles*3; mesh.triangleCount = sphere->ntriangles; @@ -1577,9 +1577,9 @@ RLAPI Mesh GenMeshHemiSphere(float radius, int rings, int slices) par_shapes_scale(sphere, radius, radius, radius); // NOTE: Soft normals are computed internally - mesh.vertices = (float *)malloc(sphere->ntriangles*3*3*sizeof(float)); - mesh.texcoords = (float *)malloc(sphere->ntriangles*3*2*sizeof(float)); - mesh.normals = (float *)malloc(sphere->ntriangles*3*3*sizeof(float)); + mesh.vertices = (float *)RL_MALLOC(sphere->ntriangles*3*3*sizeof(float)); + mesh.texcoords = (float *)RL_MALLOC(sphere->ntriangles*3*2*sizeof(float)); + mesh.normals = (float *)RL_MALLOC(sphere->ntriangles*3*3*sizeof(float)); mesh.vertexCount = sphere->ntriangles*3; mesh.triangleCount = sphere->ntriangles; @@ -1635,9 +1635,9 @@ Mesh GenMeshCylinder(float radius, float height, int slices) par_shapes_merge_and_free(cylinder, capTop); par_shapes_merge_and_free(cylinder, capBottom); - mesh.vertices = (float *)malloc(cylinder->ntriangles*3*3*sizeof(float)); - mesh.texcoords = (float *)malloc(cylinder->ntriangles*3*2*sizeof(float)); - mesh.normals = (float *)malloc(cylinder->ntriangles*3*3*sizeof(float)); + mesh.vertices = (float *)RL_MALLOC(cylinder->ntriangles*3*3*sizeof(float)); + mesh.texcoords = (float *)RL_MALLOC(cylinder->ntriangles*3*2*sizeof(float)); + mesh.normals = (float *)RL_MALLOC(cylinder->ntriangles*3*3*sizeof(float)); mesh.vertexCount = cylinder->ntriangles*3; mesh.triangleCount = cylinder->ntriangles; @@ -1677,9 +1677,9 @@ Mesh GenMeshTorus(float radius, float size, int radSeg, int sides) par_shapes_mesh *torus = par_shapes_create_torus(radSeg, sides, radius); par_shapes_scale(torus, size/2, size/2, size/2); - mesh.vertices = (float *)malloc(torus->ntriangles*3*3*sizeof(float)); - mesh.texcoords = (float *)malloc(torus->ntriangles*3*2*sizeof(float)); - mesh.normals = (float *)malloc(torus->ntriangles*3*3*sizeof(float)); + mesh.vertices = (float *)RL_MALLOC(torus->ntriangles*3*3*sizeof(float)); + mesh.texcoords = (float *)RL_MALLOC(torus->ntriangles*3*2*sizeof(float)); + mesh.normals = (float *)RL_MALLOC(torus->ntriangles*3*3*sizeof(float)); mesh.vertexCount = torus->ntriangles*3; mesh.triangleCount = torus->ntriangles; @@ -1717,9 +1717,9 @@ Mesh GenMeshKnot(float radius, float size, int radSeg, int sides) par_shapes_mesh *knot = par_shapes_create_trefoil_knot(radSeg, sides, radius); par_shapes_scale(knot, size, size, size); - mesh.vertices = (float *)malloc(knot->ntriangles*3*3*sizeof(float)); - mesh.texcoords = (float *)malloc(knot->ntriangles*3*2*sizeof(float)); - mesh.normals = (float *)malloc(knot->ntriangles*3*3*sizeof(float)); + mesh.vertices = (float *)RL_MALLOC(knot->ntriangles*3*3*sizeof(float)); + mesh.texcoords = (float *)RL_MALLOC(knot->ntriangles*3*2*sizeof(float)); + mesh.normals = (float *)RL_MALLOC(knot->ntriangles*3*3*sizeof(float)); mesh.vertexCount = knot->ntriangles*3; mesh.triangleCount = knot->ntriangles; @@ -1764,9 +1764,9 @@ Mesh GenMeshHeightmap(Image heightmap, Vector3 size) mesh.vertexCount = mesh.triangleCount*3; - mesh.vertices = (float *)malloc(mesh.vertexCount*3*sizeof(float)); - mesh.normals = (float *)malloc(mesh.vertexCount*3*sizeof(float)); - mesh.texcoords = (float *)malloc(mesh.vertexCount*2*sizeof(float)); + mesh.vertices = (float *)RL_MALLOC(mesh.vertexCount*3*sizeof(float)); + mesh.normals = (float *)RL_MALLOC(mesh.vertexCount*3*sizeof(float)); + mesh.texcoords = (float *)RL_MALLOC(mesh.vertexCount*2*sizeof(float)); mesh.colors = NULL; int vCounter = 0; // Used to count vertices float by float @@ -1848,7 +1848,7 @@ Mesh GenMeshHeightmap(Image heightmap, Vector3 size) } } - free(pixels); + RL_FREE(pixels); // Upload vertex data to GPU (static mesh) rlLoadMesh(&mesh, false); @@ -1878,9 +1878,9 @@ Mesh GenMeshCubicmap(Image cubicmap, Vector3 cubeSize) float h = cubeSize.z; float h2 = cubeSize.y; - Vector3 *mapVertices = (Vector3 *)malloc(maxTriangles*3*sizeof(Vector3)); - Vector2 *mapTexcoords = (Vector2 *)malloc(maxTriangles*3*sizeof(Vector2)); - Vector3 *mapNormals = (Vector3 *)malloc(maxTriangles*3*sizeof(Vector3)); + Vector3 *mapVertices = (Vector3 *)RL_MALLOC(maxTriangles*3*sizeof(Vector3)); + Vector2 *mapTexcoords = (Vector2 *)RL_MALLOC(maxTriangles*3*sizeof(Vector2)); + Vector3 *mapNormals = (Vector3 *)RL_MALLOC(maxTriangles*3*sizeof(Vector3)); // Define the 6 normals of the cube, we will combine them accordingly later... Vector3 n1 = { 1.0f, 0.0f, 0.0f }; @@ -2167,9 +2167,9 @@ Mesh GenMeshCubicmap(Image cubicmap, Vector3 cubeSize) mesh.vertexCount = vCounter; mesh.triangleCount = vCounter/3; - mesh.vertices = (float *)malloc(mesh.vertexCount*3*sizeof(float)); - mesh.normals = (float *)malloc(mesh.vertexCount*3*sizeof(float)); - mesh.texcoords = (float *)malloc(mesh.vertexCount*2*sizeof(float)); + mesh.vertices = (float *)RL_MALLOC(mesh.vertexCount*3*sizeof(float)); + mesh.normals = (float *)RL_MALLOC(mesh.vertexCount*3*sizeof(float)); + mesh.texcoords = (float *)RL_MALLOC(mesh.vertexCount*2*sizeof(float)); mesh.colors = NULL; int fCounter = 0; @@ -2204,11 +2204,11 @@ Mesh GenMeshCubicmap(Image cubicmap, Vector3 cubeSize) fCounter += 2; } - free(mapVertices); - free(mapNormals); - free(mapTexcoords); + RL_FREE(mapVertices); + RL_FREE(mapNormals); + RL_FREE(mapTexcoords); - free(cubicmapPixels); // Free image pixel data + RL_FREE(cubicmapPixels); // Free image pixel data // Upload vertex data to GPU (static mesh) rlLoadMesh(&mesh, false); @@ -2250,11 +2250,11 @@ BoundingBox MeshBoundingBox(Mesh mesh) // Implementation base don: https://answers.unity.com/questions/7789/calculating-tangents-vector4.html void MeshTangents(Mesh *mesh) { - if (mesh->tangents == NULL) mesh->tangents = (float *)malloc(mesh->vertexCount*4*sizeof(float)); + if (mesh->tangents == NULL) mesh->tangents = (float *)RL_MALLOC(mesh->vertexCount*4*sizeof(float)); else TraceLog(LOG_WARNING, "Mesh tangents already exist"); - Vector3 *tan1 = (Vector3 *)malloc(mesh->vertexCount*sizeof(Vector3)); - Vector3 *tan2 = (Vector3 *)malloc(mesh->vertexCount*sizeof(Vector3)); + Vector3 *tan1 = (Vector3 *)RL_MALLOC(mesh->vertexCount*sizeof(Vector3)); + Vector3 *tan2 = (Vector3 *)RL_MALLOC(mesh->vertexCount*sizeof(Vector3)); for (int i = 0; i < mesh->vertexCount; i += 3) { @@ -2318,8 +2318,8 @@ void MeshTangents(Mesh *mesh) #endif } - free(tan1); - free(tan2); + RL_FREE(tan1); + RL_FREE(tan2); // Load a new tangent attributes buffer mesh->vboId[LOC_VERTEX_TANGENT] = rlLoadAttribBuffer(mesh->vaoId, LOC_VERTEX_TANGENT, mesh->tangents, mesh->vertexCount*4*sizeof(float), false); @@ -2746,7 +2746,7 @@ static Model LoadOBJ(const char *fileName) long length = ftell(objFile); // Get file size fseek(objFile, 0, SEEK_SET); // Reset file pointer - data = (char *)malloc(length); + data = (char *)RL_MALLOC(length); fread(data, length, 1, objFile); dataLength = length; @@ -2763,12 +2763,12 @@ static Model LoadOBJ(const char *fileName) // Init model meshes array model.meshCount = meshCount; - model.meshes = (Mesh *)malloc(model.meshCount*sizeof(Mesh)); + model.meshes = (Mesh *)RL_MALLOC(model.meshCount*sizeof(Mesh)); // Init model materials array model.materialCount = materialCount; - model.materials = (Material *)malloc(model.materialCount*sizeof(Material)); - model.meshMaterial = (int *)calloc(model.meshCount, sizeof(int)); + model.materials = (Material *)RL_MALLOC(model.materialCount*sizeof(Material)); + model.meshMaterial = (int *)RL_CALLOC(model.meshCount, sizeof(int)); /* // Multiple meshes data reference @@ -2787,9 +2787,9 @@ static Model LoadOBJ(const char *fileName) memset(&mesh, 0, sizeof(Mesh)); mesh.vertexCount = attrib.num_faces*3; mesh.triangleCount = attrib.num_faces; - mesh.vertices = (float *)malloc(mesh.vertexCount*3*sizeof(float)); - mesh.texcoords = (float *)malloc(mesh.vertexCount*2*sizeof(float)); - mesh.normals = (float *)malloc(mesh.vertexCount*3*sizeof(float)); + mesh.vertices = (float *)RL_MALLOC(mesh.vertexCount*3*sizeof(float)); + mesh.texcoords = (float *)RL_MALLOC(mesh.vertexCount*2*sizeof(float)); + mesh.normals = (float *)RL_MALLOC(mesh.vertexCount*3*sizeof(float)); int vCount = 0; int vtCount = 0; @@ -2934,17 +2934,26 @@ static Model LoadIQM(const char *fileName) typedef struct IQMTriangle { unsigned int vertex[3]; } IQMTriangle; - - // NOTE: Adjacency unused by default - typedef struct IQMAdjacency { - unsigned int triangle[3]; - } IQMAdjacency; - + typedef struct IQMJoint { unsigned int name; int parent; float translate[3], rotate[4], scale[3]; } IQMJoint; + + typedef struct IQMVertexArray { + unsigned int type; + unsigned int flags; + unsigned int format; + unsigned int size; + unsigned int offset; + } IQMVertexArray; + + // NOTE: Below IQM structures are not used but listed for reference + /* + typedef struct IQMAdjacency { + unsigned int triangle[3]; + } IQMAdjacency; typedef struct IQMPose { int parent; @@ -2960,19 +2969,11 @@ static Model LoadIQM(const char *fileName) unsigned int flags; } IQMAnim; - typedef struct IQMVertexArray { - unsigned int type; - unsigned int flags; - unsigned int format; - unsigned int size; - unsigned int offset; - } IQMVertexArray; - - // NOTE: Bounds unused by default typedef struct IQMBounds { float bbmin[3], bbmax[3]; float xyradius, radius; } IQMBounds; + */ //----------------------------------------------------------------------------------- // IQM vertex data types @@ -3028,12 +3029,12 @@ static Model LoadIQM(const char *fileName) } // Meshes data processing - imesh = malloc(sizeof(IQMMesh)*iqm.num_meshes); + imesh = RL_MALLOC(sizeof(IQMMesh)*iqm.num_meshes); fseek(iqmFile, iqm.ofs_meshes, SEEK_SET); fread(imesh, sizeof(IQMMesh)*iqm.num_meshes, 1, iqmFile); model.meshCount = iqm.num_meshes; - model.meshes = malloc(model.meshCount*sizeof(Mesh)); + model.meshes = RL_MALLOC(model.meshCount*sizeof(Mesh)); char name[MESH_NAME_LENGTH]; @@ -3043,24 +3044,24 @@ static Model LoadIQM(const char *fileName) fread(name, sizeof(char)*MESH_NAME_LENGTH, 1, iqmFile); // Mesh name not used... model.meshes[i].vertexCount = imesh[i].num_vertexes; - model.meshes[i].vertices = malloc(sizeof(float)*model.meshes[i].vertexCount*3); // Default vertex positions - model.meshes[i].normals = malloc(sizeof(float)*model.meshes[i].vertexCount*3); // Default vertex normals - model.meshes[i].texcoords = malloc(sizeof(float)*model.meshes[i].vertexCount*2); // Default vertex texcoords + model.meshes[i].vertices = RL_MALLOC(sizeof(float)*model.meshes[i].vertexCount*3); // Default vertex positions + model.meshes[i].normals = RL_MALLOC(sizeof(float)*model.meshes[i].vertexCount*3); // Default vertex normals + model.meshes[i].texcoords = RL_MALLOC(sizeof(float)*model.meshes[i].vertexCount*2); // Default vertex texcoords - model.meshes[i].boneIds = malloc(sizeof(int)*model.meshes[i].vertexCount*4); // Up-to 4 bones supported! - model.meshes[i].boneWeights = malloc(sizeof(float)*model.meshes[i].vertexCount*4); // Up-to 4 bones supported! + model.meshes[i].boneIds = RL_MALLOC(sizeof(int)*model.meshes[i].vertexCount*4); // Up-to 4 bones supported! + model.meshes[i].boneWeights = RL_MALLOC(sizeof(float)*model.meshes[i].vertexCount*4); // Up-to 4 bones supported! model.meshes[i].triangleCount = imesh[i].num_triangles; - model.meshes[i].indices = malloc(sizeof(unsigned short)*model.meshes[i].triangleCount*3); + model.meshes[i].indices = RL_MALLOC(sizeof(unsigned short)*model.meshes[i].triangleCount*3); // Animated verted data, what we actually process for rendering // NOTE: Animated vertex should be re-uploaded to GPU (if not using GPU skinning) - model.meshes[i].animVertices = malloc(sizeof(float)*model.meshes[i].vertexCount*3); - model.meshes[i].animNormals = malloc(sizeof(float)*model.meshes[i].vertexCount*3); + model.meshes[i].animVertices = RL_MALLOC(sizeof(float)*model.meshes[i].vertexCount*3); + model.meshes[i].animNormals = RL_MALLOC(sizeof(float)*model.meshes[i].vertexCount*3); } // Triangles data processing - tri = malloc(sizeof(IQMTriangle)*iqm.num_triangles); + tri = RL_MALLOC(sizeof(IQMTriangle)*iqm.num_triangles); fseek(iqmFile, iqm.ofs_triangles, SEEK_SET); fread(tri, sizeof(IQMTriangle)*iqm.num_triangles, 1, iqmFile); @@ -3079,7 +3080,7 @@ static Model LoadIQM(const char *fileName) } // Vertex arrays data processing - va = malloc(sizeof(IQMVertexArray)*iqm.num_vertexarrays); + va = RL_MALLOC(sizeof(IQMVertexArray)*iqm.num_vertexarrays); fseek(iqmFile, iqm.ofs_vertexarrays, SEEK_SET); fread(va, sizeof(IQMVertexArray)*iqm.num_vertexarrays, 1, iqmFile); @@ -3089,7 +3090,7 @@ static Model LoadIQM(const char *fileName) { case IQM_POSITION: { - vertex = malloc(sizeof(float)*iqm.num_vertexes*3); + vertex = RL_MALLOC(sizeof(float)*iqm.num_vertexes*3); fseek(iqmFile, va[i].offset, SEEK_SET); fread(vertex, sizeof(float)*iqm.num_vertexes*3, 1, iqmFile); @@ -3106,7 +3107,7 @@ static Model LoadIQM(const char *fileName) } break; case IQM_NORMAL: { - normal = malloc(sizeof(float)*iqm.num_vertexes*3); + normal = RL_MALLOC(sizeof(float)*iqm.num_vertexes*3); fseek(iqmFile, va[i].offset, SEEK_SET); fread(normal, sizeof(float)*iqm.num_vertexes*3, 1, iqmFile); @@ -3123,7 +3124,7 @@ static Model LoadIQM(const char *fileName) } break; case IQM_TEXCOORD: { - text = malloc(sizeof(float)*iqm.num_vertexes*2); + text = RL_MALLOC(sizeof(float)*iqm.num_vertexes*2); fseek(iqmFile, va[i].offset, SEEK_SET); fread(text, sizeof(float)*iqm.num_vertexes*2, 1, iqmFile); @@ -3139,7 +3140,7 @@ static Model LoadIQM(const char *fileName) } break; case IQM_BLENDINDEXES: { - blendi = malloc(sizeof(char)*iqm.num_vertexes*4); + blendi = RL_MALLOC(sizeof(char)*iqm.num_vertexes*4); fseek(iqmFile, va[i].offset, SEEK_SET); fread(blendi, sizeof(char)*iqm.num_vertexes*4, 1, iqmFile); @@ -3155,7 +3156,7 @@ static Model LoadIQM(const char *fileName) } break; case IQM_BLENDWEIGHTS: { - blendw = malloc(sizeof(unsigned char)*iqm.num_vertexes*4); + blendw = RL_MALLOC(sizeof(unsigned char)*iqm.num_vertexes*4); fseek(iqmFile,va[i].offset,SEEK_SET); fread(blendw,sizeof(unsigned char)*iqm.num_vertexes*4,1,iqmFile); @@ -3173,13 +3174,13 @@ static Model LoadIQM(const char *fileName) } // Bones (joints) data processing - ijoint = malloc(sizeof(IQMJoint)*iqm.num_joints); + ijoint = RL_MALLOC(sizeof(IQMJoint)*iqm.num_joints); fseek(iqmFile, iqm.ofs_joints, SEEK_SET); fread(ijoint, sizeof(IQMJoint)*iqm.num_joints, 1, iqmFile); model.boneCount = iqm.num_joints; - model.bones = malloc(sizeof(BoneInfo)*iqm.num_joints); - model.bindPose = malloc(sizeof(Transform)*iqm.num_joints); + model.bones = RL_MALLOC(sizeof(BoneInfo)*iqm.num_joints); + model.bindPose = RL_MALLOC(sizeof(Transform)*iqm.num_joints); for (int i = 0; i < iqm.num_joints; i++) { @@ -3216,15 +3217,15 @@ static Model LoadIQM(const char *fileName) } fclose(iqmFile); - free(imesh); - free(tri); - free(va); - free(vertex); - free(normal); - free(text); - free(blendi); - free(blendw); - free(ijoint); + RL_FREE(imesh); + RL_FREE(tri); + RL_FREE(va); + RL_FREE(vertex); + RL_FREE(normal); + RL_FREE(text); + RL_FREE(blendi); + RL_FREE(blendw); + RL_FREE(ijoint); return model; } @@ -3249,7 +3250,7 @@ static Model LoadGLTF(const char *fileName) int size = ftell(gltfFile); fseek(gltfFile, 0, SEEK_SET); - void *buffer = malloc(size); + void *buffer = RL_MALLOC(size); fread(buffer, size, 1, gltfFile); fclose(gltfFile); @@ -3259,7 +3260,7 @@ static Model LoadGLTF(const char *fileName) cgltf_data *data; cgltf_result result = cgltf_parse(&options, buffer, size, &data); - free(buffer); + RL_FREE(buffer); if (result == cgltf_result_success) { @@ -3270,7 +3271,7 @@ static Model LoadGLTF(const char *fileName) // Process glTF data and map to model model.meshCount = data->meshes_count; - model.meshes = malloc(model.meshCount*sizeof(Mesh)); + model.meshes = RL_MALLOC(model.meshCount*sizeof(Mesh)); for (int i = 0; i < model.meshCount; i++) { @@ -3282,11 +3283,11 @@ static Model LoadGLTF(const char *fileName) model.meshes[i].triangleCount = data->meshes[i].primitives_count; // data.meshes[i].weights not used (array of weights to be applied to the Morph Targets) - model.meshes[i].vertices = malloc(sizeof(float)*model.meshes[i].vertexCount*3); // Default vertex positions - model.meshes[i].normals = malloc(sizeof(float)*model.meshes[i].vertexCount*3); // Default vertex normals - model.meshes[i].texcoords = malloc(sizeof(float)*model.meshes[i].vertexCount*2); // Default vertex texcoords + model.meshes[i].vertices = RL_MALLOC(sizeof(float)*model.meshes[i].vertexCount*3); // Default vertex positions + model.meshes[i].normals = RL_MALLOC(sizeof(float)*model.meshes[i].vertexCount*3); // Default vertex normals + model.meshes[i].texcoords = RL_MALLOC(sizeof(float)*model.meshes[i].vertexCount*2); // Default vertex texcoords - model.meshes[i].indices = malloc(sizeof(unsigned short)*model.meshes[i].triangleCount*3); + model.meshes[i].indices = RL_MALLOC(sizeof(unsigned short)*model.meshes[i].triangleCount*3); } } diff --git a/src/raudio.c b/src/raudio.c index 636d15b8..9108a903 100644 --- a/src/raudio.c +++ b/src/raudio.c @@ -567,7 +567,7 @@ void SetMasterVolume(float volume) // Create a new audio buffer. Initially filled with silence AudioBuffer *CreateAudioBuffer(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, ma_uint32 bufferSizeInFrames, AudioBufferUsage usage) { - AudioBuffer *audioBuffer = (AudioBuffer *)calloc(sizeof(*audioBuffer) + (bufferSizeInFrames*channels*ma_get_bytes_per_sample(format)), 1); + AudioBuffer *audioBuffer = (AudioBuffer *)RL_CALLOC(sizeof(*audioBuffer) + (bufferSizeInFrames*channels*ma_get_bytes_per_sample(format)), 1); if (audioBuffer == NULL) { TraceLog(LOG_ERROR, "CreateAudioBuffer() : Failed to allocate memory for audio buffer"); @@ -591,7 +591,7 @@ AudioBuffer *CreateAudioBuffer(ma_format format, ma_uint32 channels, ma_uint32 s if (result != MA_SUCCESS) { TraceLog(LOG_ERROR, "CreateAudioBuffer() : Failed to create data conversion pipeline"); - free(audioBuffer); + RL_FREE(audioBuffer); return NULL; } @@ -623,7 +623,7 @@ void DeleteAudioBuffer(AudioBuffer *audioBuffer) } UntrackAudioBuffer(audioBuffer); - free(audioBuffer); + RL_FREE(audioBuffer); } // Check if an audio buffer is playing @@ -863,7 +863,7 @@ Sound LoadSoundFromWave(Wave wave) // Unload wave data void UnloadWave(Wave wave) { - if (wave.data != NULL) free(wave.data); + if (wave.data != NULL) RL_FREE(wave.data); TraceLog(LOG_INFO, "Unloaded wave data from RAM"); } @@ -1017,7 +1017,7 @@ void WaveFormat(Wave *wave, int sampleRate, int sampleSize, int channels) return; } - void *data = malloc(frameCount*channels*(sampleSize/8)); + void *data = RL_MALLOC(frameCount*channels*(sampleSize/8)); frameCount = (ma_uint32)ma_convert_frames(data, formatOut, channels, sampleRate, wave->data, formatIn, wave->channels, wave->sampleRate, frameCountIn); if (frameCount == 0) @@ -1030,7 +1030,7 @@ void WaveFormat(Wave *wave, int sampleRate, int sampleSize, int channels) wave->sampleSize = sampleSize; wave->sampleRate = sampleRate; wave->channels = channels; - free(wave->data); + RL_FREE(wave->data); wave->data = data; } @@ -1039,7 +1039,7 @@ Wave WaveCopy(Wave wave) { Wave newWave = { 0 }; - newWave.data = malloc(wave.sampleCount*wave.sampleSize/8*wave.channels); + newWave.data = RL_MALLOC(wave.sampleCount*wave.sampleSize/8*wave.channels); if (newWave.data != NULL) { @@ -1064,11 +1064,11 @@ void WaveCrop(Wave *wave, int initSample, int finalSample) { int sampleCount = finalSample - initSample; - void *data = malloc(sampleCount*wave->sampleSize/8*wave->channels); + void *data = RL_MALLOC(sampleCount*wave->sampleSize/8*wave->channels); memcpy(data, (unsigned char *)wave->data + (initSample*wave->channels*wave->sampleSize/8), sampleCount*wave->channels*wave->sampleSize/8); - free(wave->data); + RL_FREE(wave->data); wave->data = data; } else TraceLog(LOG_WARNING, "Wave crop range out of bounds"); @@ -1078,7 +1078,7 @@ void WaveCrop(Wave *wave, int initSample, int finalSample) // NOTE: Returned sample values are normalized to range [-1..1] float *GetWaveData(Wave wave) { - float *samples = (float *)malloc(wave.sampleCount*wave.channels*sizeof(float)); + float *samples = (float *)RL_MALLOC(wave.sampleCount*wave.channels*sizeof(float)); for (unsigned int i = 0; i < wave.sampleCount; i++) { @@ -1100,7 +1100,7 @@ float *GetWaveData(Wave wave) // Load music stream from file Music LoadMusicStream(const char *fileName) { - Music music = (MusicData *)malloc(sizeof(MusicData)); + Music music = (MusicData *)RL_MALLOC(sizeof(MusicData)); bool musicLoaded = true; #if defined(SUPPORT_FILEFORMAT_OGG) @@ -1228,7 +1228,7 @@ Music LoadMusicStream(const char *fileName) if (false) {} #endif #if defined(SUPPORT_FILEFORMAT_FLAC) - else if (music->ctxType == MUSIC_AUDIO_FLAC) drflac_free(music->ctxFlac); + else if (music->ctxType == MUSIC_AUDIO_FLAC) drflac_RL_FREE(music->ctxFlac); #endif #if defined(SUPPORT_FILEFORMAT_MP3) else if (music->ctxType == MUSIC_AUDIO_MP3) drmp3_uninit(&music->ctxMp3); @@ -1240,7 +1240,7 @@ Music LoadMusicStream(const char *fileName) else if (music->ctxType == MUSIC_MODULE_MOD) jar_mod_unload(&music->ctxMod); #endif - free(music); + RL_FREE(music); music = NULL; TraceLog(LOG_WARNING, "[%s] Music file could not be opened", fileName); @@ -1262,7 +1262,7 @@ void UnloadMusicStream(Music music) if (false) {} #endif #if defined(SUPPORT_FILEFORMAT_FLAC) - else if (music->ctxType == MUSIC_AUDIO_FLAC) drflac_free(music->ctxFlac); + else if (music->ctxType == MUSIC_AUDIO_FLAC) drflac_RL_FREE(music->ctxFlac); #endif #if defined(SUPPORT_FILEFORMAT_MP3) else if (music->ctxType == MUSIC_AUDIO_MP3) drmp3_uninit(&music->ctxMp3); @@ -1274,7 +1274,7 @@ void UnloadMusicStream(Music music) else if (music->ctxType == MUSIC_MODULE_MOD) jar_mod_unload(&music->ctxMod); #endif - free(music); + RL_FREE(music); } // Start music playing (open stream) @@ -1357,7 +1357,7 @@ void UpdateMusicStream(Music music) unsigned int subBufferSizeInFrames = ((AudioBuffer *)music->stream.audioBuffer)->bufferSizeInFrames/2; // NOTE: Using dynamic allocation because it could require more than 16KB - void *pcm = calloc(subBufferSizeInFrames*music->stream.channels*music->stream.sampleSize/8, 1); + void *pcm = RL_CALLOC(subBufferSizeInFrames*music->stream.channels*music->stream.sampleSize/8, 1); int samplesCount = 0; // Total size of data steamed in L+R samples for xm floats, individual L or R for ogg shorts @@ -1427,7 +1427,7 @@ void UpdateMusicStream(Music music) } // Free allocated pcm data - free(pcm); + RL_FREE(pcm); // Reset audio stream for looping if (streamEnding) @@ -1750,7 +1750,7 @@ static Wave LoadWAV(const char *fileName) else { // Allocate memory for data - wave.data = malloc(wavData.subChunkSize); + wave.data = RL_MALLOC(wavData.subChunkSize); // Read in the sound data into the soundData variable fread(wave.data, wavData.subChunkSize, 1, wavFile); @@ -1891,7 +1891,7 @@ static Wave LoadOGG(const char *fileName) float totalSeconds = stb_vorbis_stream_length_in_seconds(oggFile); if (totalSeconds > 10) TraceLog(LOG_WARNING, "[%s] Ogg audio length is larger than 10 seconds (%f), that's a big file in memory, consider music streaming", fileName, totalSeconds); - wave.data = (short *)malloc(wave.sampleCount*wave.channels*sizeof(short)); + wave.data = (short *)RL_MALLOC(wave.sampleCount*wave.channels*sizeof(short)); // NOTE: Returns the number of samples to process (be careful! we ask for number of shorts!) int numSamplesOgg = stb_vorbis_get_samples_short_interleaved(oggFile, info.channels, (short *)wave.data, wave.sampleCount*wave.channels); diff --git a/src/raudio.h b/src/raudio.h index e8701814..f71a3083 100644 --- a/src/raudio.h +++ b/src/raudio.h @@ -56,7 +56,16 @@ //---------------------------------------------------------------------------------- // Defines and Macros //---------------------------------------------------------------------------------- -//... +// Allow custom memory allocators +#ifndef RL_MALLOC + #define RL_MALLOC(sz) malloc(sz) +#endif +#ifndef RL_CALLOC + #define RL_CALLOC(n,sz) calloc(n,sz) +#endif +#ifndef RL_FREE + #define RL_FREE(p) free(p) +#endif //---------------------------------------------------------------------------------- // Types and Structures Definition diff --git a/src/raylib.h b/src/raylib.h index 424a9dd7..43260e06 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -99,6 +99,17 @@ // Shader and material limits #define MAX_SHADER_LOCATIONS 32 // Maximum number of predefined locations stored in shader struct #define MAX_MATERIAL_MAPS 12 // Maximum number of texture maps stored in shader struct + +// Allow custom memory allocators +#ifndef RL_MALLOC + #define RL_MALLOC(sz) malloc(sz) +#endif +#ifndef RL_CALLOC + #define RL_CALLOC(n,sz) calloc(n,sz) +#endif +#ifndef RL_FREE + #define RL_FREE(p) free(p) +#endif // NOTE: MSC C++ compiler does not support compound literals (C99 feature) // Plain structures in C++ (without constructors) can be initialized from { } initializers. diff --git a/src/rlgl.h b/src/rlgl.h index 0356858a..c2ddd028 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -1492,7 +1492,7 @@ void rlglInit(int width, int height) glGetIntegerv(GL_NUM_EXTENSIONS, &numExt); #if defined(_MSC_VER) - const char **extList = malloc(sizeof(const char *)*numExt); + const char **extList = RL_MALLOC(sizeof(const char *)*numExt); #else const char *extList[numExt]; #endif @@ -1504,7 +1504,7 @@ void rlglInit(int width, int height) // NOTE: We have to duplicate string because glGetString() returns a const string int len = strlen(extensions) + 1; - char *extensionsDup = (char *)malloc(len); + char *extensionsDup = (char *)RL_MALLOC(len); strcpy(extensionsDup, extensions); // NOTE: String could be splitted using strtok() function (string.h) @@ -1520,7 +1520,7 @@ void rlglInit(int width, int height) extList[numExt] = strtok(NULL, " "); } - free(extensionsDup); // Duplicated string must be deallocated + RL_FREE(extensionsDup); // Duplicated string must be deallocated numExt -= 1; #endif @@ -1595,7 +1595,7 @@ void rlglInit(int width, int height) } #if defined(_WIN32) && defined(_MSC_VER) - free(extList); + RL_FREE(extList); #endif #if defined(GRAPHICS_API_OPENGL_ES2) @@ -1640,7 +1640,7 @@ void rlglInit(int width, int height) transformMatrix = MatrixIdentity(); // Init draw calls tracking system - draws = (DrawCall *)malloc(sizeof(DrawCall)*MAX_DRAWCALL_REGISTERED); + draws = (DrawCall *)RL_MALLOC(sizeof(DrawCall)*MAX_DRAWCALL_REGISTERED); for (int i = 0; i < MAX_DRAWCALL_REGISTERED; i++) { @@ -1710,7 +1710,7 @@ void rlglClose(void) TraceLog(LOG_INFO, "[TEX ID %i] Unloaded texture data (base white texture) from VRAM", defaultTextureId); - free(draws); + RL_FREE(draws); #endif } @@ -2300,7 +2300,7 @@ void rlGenerateMipmaps(Texture2D *texture) } texture->mipmaps = mipmapCount + 1; - free(data); // Once mipmaps have been generated and data has been uploaded to GPU VRAM, we can discard RAM data + RL_FREE(data); // Once mipmaps have been generated and data has been uploaded to GPU VRAM, we can discard RAM data TraceLog(LOG_WARNING, "[TEX ID %i] Mipmaps [%i] generated manually on CPU side", texture->id, texture->mipmaps); } @@ -2735,18 +2735,18 @@ void rlDrawMesh(Mesh mesh, Material material, Matrix transform) // Unload mesh data from CPU and GPU void rlUnloadMesh(Mesh *mesh) { - free(mesh->vertices); - free(mesh->texcoords); - free(mesh->normals); - free(mesh->colors); - free(mesh->tangents); - free(mesh->texcoords2); - free(mesh->indices); - - free(mesh->animVertices); - free(mesh->animNormals); - free(mesh->boneWeights); - free(mesh->boneIds); + RL_FREE(mesh->vertices); + RL_FREE(mesh->texcoords); + RL_FREE(mesh->normals); + RL_FREE(mesh->colors); + RL_FREE(mesh->tangents); + RL_FREE(mesh->texcoords2); + RL_FREE(mesh->indices); + + RL_FREE(mesh->animVertices); + RL_FREE(mesh->animNormals); + RL_FREE(mesh->boneWeights); + RL_FREE(mesh->boneIds); rlDeleteBuffers(mesh->vboId[0]); // vertex rlDeleteBuffers(mesh->vboId[1]); // texcoords @@ -2762,14 +2762,14 @@ void rlUnloadMesh(Mesh *mesh) // Read screen pixel data (color buffer) unsigned char *rlReadScreenPixels(int width, int height) { - unsigned char *screenData = (unsigned char *)calloc(width*height*4, sizeof(unsigned char)); + unsigned char *screenData = (unsigned char *)RL_CALLOC(width*height*4, sizeof(unsigned char)); // NOTE 1: glReadPixels returns image flipped vertically -> (0,0) is the bottom left corner of the framebuffer // NOTE 2: We are getting alpha channel! Be careful, it can be transparent if not cleared properly! glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, screenData); // Flip image vertically! - unsigned char *imgData = (unsigned char *)malloc(width*height*sizeof(unsigned char)*4); + unsigned char *imgData = (unsigned char *)RL_MALLOC(width*height*sizeof(unsigned char)*4); for (int y = height - 1; y >= 0; y--) { @@ -2783,7 +2783,7 @@ unsigned char *rlReadScreenPixels(int width, int height) } } - free(screenData); + RL_FREE(screenData); return imgData; // NOTE: image data should be freed } @@ -2815,7 +2815,7 @@ void *rlReadTexturePixels(Texture2D texture) if ((glInternalFormat != -1) && (texture.format < COMPRESSED_DXT1_RGB)) { - pixels = (unsigned char *)malloc(size); + pixels = (unsigned char *)RL_MALLOC(size); glGetTexImage(GL_TEXTURE_2D, 0, glFormat, glType, pixels); } else TraceLog(LOG_WARNING, "Texture data retrieval not suported for pixel format"); @@ -2841,7 +2841,7 @@ void *rlReadTexturePixels(Texture2D texture) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture.id, 0); // Allocate enough memory to read back our texture data - pixels = (unsigned char *)malloc(GetPixelDataSize(texture.width, texture.height, texture.format)); + pixels = (unsigned char *)RL_MALLOC(GetPixelDataSize(texture.width, texture.height, texture.format)); // Get OpenGL internal formats and data type from our texture format unsigned int glInternalFormat, glFormat, glType; @@ -2911,7 +2911,7 @@ char *LoadText(const char *fileName) if (size > 0) { - text = (char *)malloc(sizeof(char)*(size + 1)); + text = (char *)RL_MALLOC(sizeof(char)*(size + 1)); int count = fread(text, sizeof(char), size, textFile); text[count] = '\0'; } @@ -2938,8 +2938,8 @@ Shader LoadShader(const char *vsFileName, const char *fsFileName) shader = LoadShaderCode(vShaderStr, fShaderStr); - if (vShaderStr != NULL) free(vShaderStr); - if (fShaderStr != NULL) free(fShaderStr); + if (vShaderStr != NULL) RL_FREE(vShaderStr); + if (fShaderStr != NULL) RL_FREE(fShaderStr); return shader; } @@ -3758,7 +3758,7 @@ static unsigned int CompileShader(const char *shaderStr, int type) glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength); #if defined(_MSC_VER) - char *log = malloc(maxLength); + char *log = RL_MALLOC(maxLength); #else char log[maxLength]; #endif @@ -3767,7 +3767,7 @@ static unsigned int CompileShader(const char *shaderStr, int type) TraceLog(LOG_INFO, "%s", log); #if defined(_MSC_VER) - free(log); + RL_FREE(log); #endif } else TraceLog(LOG_INFO, "[SHDR ID %i] Shader compiled successfully", shader); @@ -3814,7 +3814,7 @@ static unsigned int LoadShaderProgram(unsigned int vShaderId, unsigned int fShad glGetProgramiv(program, GL_INFO_LOG_LENGTH, &maxLength); #if defined(_MSC_VER) - char *log = malloc(maxLength); + char *log = RL_MALLOC(maxLength); #else char log[maxLength]; #endif @@ -3823,7 +3823,7 @@ static unsigned int LoadShaderProgram(unsigned int vShaderId, unsigned int fShad TraceLog(LOG_INFO, "%s", log); #if defined(_MSC_VER) - free(log); + RL_FREE(log); #endif glDeleteProgram(program); @@ -3984,13 +3984,13 @@ static void LoadBuffersDefault(void) //-------------------------------------------------------------------------------------------- for (int i = 0; i < MAX_BATCH_BUFFERING; i++) { - vertexData[i].vertices = (float *)malloc(sizeof(float)*3*4*MAX_BATCH_ELEMENTS); // 3 float by vertex, 4 vertex by quad - vertexData[i].texcoords = (float *)malloc(sizeof(float)*2*4*MAX_BATCH_ELEMENTS); // 2 float by texcoord, 4 texcoord by quad - vertexData[i].colors = (unsigned char *)malloc(sizeof(unsigned char)*4*4*MAX_BATCH_ELEMENTS); // 4 float by color, 4 colors by quad + vertexData[i].vertices = (float *)RL_MALLOC(sizeof(float)*3*4*MAX_BATCH_ELEMENTS); // 3 float by vertex, 4 vertex by quad + vertexData[i].texcoords = (float *)RL_MALLOC(sizeof(float)*2*4*MAX_BATCH_ELEMENTS); // 2 float by texcoord, 4 texcoord by quad + vertexData[i].colors = (unsigned char *)RL_MALLOC(sizeof(unsigned char)*4*4*MAX_BATCH_ELEMENTS); // 4 float by color, 4 colors by quad #if defined(GRAPHICS_API_OPENGL_33) - vertexData[i].indices = (unsigned int *)malloc(sizeof(unsigned int)*6*MAX_BATCH_ELEMENTS); // 6 int by quad (indices) + vertexData[i].indices = (unsigned int *)RL_MALLOC(sizeof(unsigned int)*6*MAX_BATCH_ELEMENTS); // 6 int by quad (indices) #elif defined(GRAPHICS_API_OPENGL_ES2) - vertexData[i].indices = (unsigned short *)malloc(sizeof(unsigned short)*6*MAX_BATCH_ELEMENTS); // 6 int by quad (indices) + vertexData[i].indices = (unsigned short *)RL_MALLOC(sizeof(unsigned short)*6*MAX_BATCH_ELEMENTS); // 6 int by quad (indices) #endif for (int j = 0; j < (3*4*MAX_BATCH_ELEMENTS); j++) vertexData[i].vertices[j] = 0.0f; @@ -4266,10 +4266,10 @@ static void UnloadBuffersDefault(void) if (vaoSupported) glDeleteVertexArrays(1, &vertexData[i].vaoId); // Free vertex arrays memory from CPU (RAM) - free(vertexData[i].vertices); - free(vertexData[i].texcoords); - free(vertexData[i].colors); - free(vertexData[i].indices); + RL_FREE(vertexData[i].vertices); + RL_FREE(vertexData[i].texcoords); + RL_FREE(vertexData[i].colors); + RL_FREE(vertexData[i].indices); } } @@ -4444,7 +4444,7 @@ static int GenerateMipmaps(unsigned char *data, int baseWidth, int baseHeight) // Generate mipmaps // NOTE: Every mipmap data is stored after data - Color *image = (Color *)malloc(width*height*sizeof(Color)); + Color *image = (Color *)RL_MALLOC(width*height*sizeof(Color)); Color *mipmap = NULL; int offset = 0; int j = 0; @@ -4481,13 +4481,13 @@ static int GenerateMipmaps(unsigned char *data, int baseWidth, int baseHeight) j++; } - free(image); + RL_FREE(image); image = mipmap; mipmap = NULL; } - free(mipmap); // free mipmap data + RL_FREE(mipmap); // free mipmap data return mipmapCount; } @@ -4501,7 +4501,7 @@ static Color *GenNextMipmap(Color *srcData, int srcWidth, int srcHeight) int width = srcWidth/2; int height = srcHeight/2; - Color *mipmap = (Color *)malloc(width*height*sizeof(Color)); + Color *mipmap = (Color *)RL_MALLOC(width*height*sizeof(Color)); // Scaling algorithm works perfectly (box-filter) for (int y = 0; y < height; y++) diff --git a/src/text.c b/src/text.c index bd9e09f0..22bd7659 100644 --- a/src/text.c +++ b/src/text.c @@ -174,7 +174,7 @@ extern void LoadDefaultFont(void) int imWidth = 128; int imHeight = 128; - Color *imagePixels = (Color *)malloc(imWidth*imHeight*sizeof(Color)); + Color *imagePixels = (Color *)RL_MALLOC(imWidth*imHeight*sizeof(Color)); for (int i = 0; i < imWidth*imHeight; i++) imagePixels[i] = BLANK; // Initialize array @@ -196,7 +196,7 @@ extern void LoadDefaultFont(void) Image image = LoadImageEx(imagePixels, imWidth, imHeight); ImageFormat(&image, UNCOMPRESSED_GRAY_ALPHA); - free(imagePixels); + RL_FREE(imagePixels); defaultFont.texture = LoadTextureFromImage(image); UnloadImage(image); @@ -206,7 +206,7 @@ extern void LoadDefaultFont(void) // Allocate space for our characters info data // NOTE: This memory should be freed at end! --> CloseWindow() - defaultFont.chars = (CharInfo *)malloc(defaultFont.charsCount*sizeof(CharInfo)); + defaultFont.chars = (CharInfo *)RL_MALLOC(defaultFont.charsCount*sizeof(CharInfo)); int currentLine = 0; int currentPosX = charsDivisor; @@ -249,7 +249,7 @@ extern void LoadDefaultFont(void) extern void UnloadDefaultFont(void) { UnloadTexture(defaultFont.texture); - free(defaultFont.chars); + RL_FREE(defaultFont.chars); } #endif // SUPPORT_DEFAULT_FONT @@ -407,7 +407,7 @@ Font LoadFontFromImage(Image image, Color key, int firstChar) // Create a new image with the processed color data (key color replaced by BLANK) Image fontClear = LoadImageEx(pixels, image.width, image.height); - free(pixels); // Free pixels array memory + RL_FREE(pixels); // Free pixels array memory // Create spritefont with all data parsed from image Font spriteFont = { 0 }; @@ -419,7 +419,7 @@ Font LoadFontFromImage(Image image, Color key, int firstChar) // We got tempCharValues and tempCharsRecs populated with chars data // Now we move temp data to sized charValues and charRecs arrays - spriteFont.chars = (CharInfo *)malloc(spriteFont.charsCount*sizeof(CharInfo)); + spriteFont.chars = (CharInfo *)RL_MALLOC(spriteFont.charsCount*sizeof(CharInfo)); for (int i = 0; i < spriteFont.charsCount; i++) { @@ -466,7 +466,7 @@ CharInfo *LoadFontData(const char *fileName, int fontSize, int *fontChars, int c long size = ftell(fontFile); // Get file size fseek(fontFile, 0, SEEK_SET); // Reset file pointer - unsigned char *fontBuffer = (unsigned char *)malloc(size); + unsigned char *fontBuffer = (unsigned char *)RL_MALLOC(size); fread(fontBuffer, size, 1, fontFile); fclose(fontFile); @@ -491,12 +491,12 @@ CharInfo *LoadFontData(const char *fileName, int fontSize, int *fontChars, int c int genFontChars = false; if (fontChars == NULL) { - fontChars = (int *)malloc(charsCount*sizeof(int)); + fontChars = (int *)RL_MALLOC(charsCount*sizeof(int)); for (int i = 0; i < charsCount; i++) fontChars[i] = i + 32; genFontChars = true; } - chars = (CharInfo *)malloc(charsCount*sizeof(CharInfo)); + chars = (CharInfo *)RL_MALLOC(charsCount*sizeof(CharInfo)); // NOTE: Using simple packaging, one char after another for (int i = 0; i < charsCount; i++) @@ -540,8 +540,8 @@ CharInfo *LoadFontData(const char *fileName, int fontSize, int *fontChars, int c chars[i].advanceX *= scaleFactor; } - free(fontBuffer); - if (genFontChars) free(fontChars); + RL_FREE(fontBuffer); + if (genFontChars) RL_FREE(fontChars); } else TraceLog(LOG_WARNING, "[%s] TTF file could not be opened", fileName); #else @@ -572,7 +572,7 @@ Image GenImageFontAtlas(CharInfo *chars, int charsCount, int fontSize, int paddi atlas.width = imageSize; // Atlas bitmap width atlas.height = imageSize; // Atlas bitmap height - atlas.data = (unsigned char *)calloc(1, atlas.width*atlas.height); // Create a bitmap to store characters (8 bpp) + atlas.data = (unsigned char *)RL_CALLOC(1, atlas.width*atlas.height); // Create a bitmap to store characters (8 bpp) atlas.format = UNCOMPRESSED_GRAYSCALE; atlas.mipmaps = 1; @@ -619,11 +619,11 @@ Image GenImageFontAtlas(CharInfo *chars, int charsCount, int fontSize, int paddi { TraceLog(LOG_DEBUG, "Using Skyline packing algorythm!"); - stbrp_context *context = (stbrp_context *)malloc(sizeof(*context)); - stbrp_node *nodes = (stbrp_node *)malloc(charsCount*sizeof(*nodes)); + stbrp_context *context = (stbrp_context *)RL_MALLOC(sizeof(*context)); + stbrp_node *nodes = (stbrp_node *)RL_MALLOC(charsCount*sizeof(*nodes)); stbrp_init_target(context, atlas.width, atlas.height, nodes, charsCount); - stbrp_rect *rects = (stbrp_rect *)malloc(charsCount*sizeof(stbrp_rect)); + stbrp_rect *rects = (stbrp_rect *)RL_MALLOC(charsCount*sizeof(stbrp_rect)); // Fill rectangles for packaging for (int i = 0; i < charsCount; i++) @@ -655,16 +655,16 @@ Image GenImageFontAtlas(CharInfo *chars, int charsCount, int fontSize, int paddi else TraceLog(LOG_WARNING, "Character could not be packed: %i", i); } - free(rects); - free(nodes); - free(context); + RL_FREE(rects); + RL_FREE(nodes); + RL_FREE(context); } // TODO: Crop image if required for smaller size // Convert image data from GRAYSCALE to GRAY_ALPHA // WARNING: ImageAlphaMask(&atlas, atlas) does not work in this case, requires manual operation - unsigned char *dataGrayAlpha = (unsigned char *)malloc(imageSize*imageSize*sizeof(unsigned char)*2); // Two channels + unsigned char *dataGrayAlpha = (unsigned char *)RL_MALLOC(imageSize*imageSize*sizeof(unsigned char)*2); // Two channels for (int i = 0, k = 0; i < atlas.width*atlas.height; i++, k += 2) { @@ -672,7 +672,7 @@ Image GenImageFontAtlas(CharInfo *chars, int charsCount, int fontSize, int paddi dataGrayAlpha[k + 1] = ((unsigned char *)atlas.data)[i]; } - free(atlas.data); + RL_FREE(atlas.data); atlas.data = dataGrayAlpha; atlas.format = UNCOMPRESSED_GRAY_ALPHA; @@ -688,10 +688,10 @@ void UnloadFont(Font font) { for (int i = 0; i < font.charsCount; i++) { - free(font.chars[i].data); + RL_FREE(font.chars[i].data); } UnloadTexture(font.texture); - free(font.chars); + RL_FREE(font.chars); TraceLog(LOG_DEBUG, "Unloaded sprite font data"); } @@ -1214,7 +1214,7 @@ const char *TextReplace(char *text, const char *replace, const char *by) for (count = 0; (temp = strstr(insertPoint, replace)); count++) insertPoint = temp + replaceLen; // Allocate returning string and point temp to it - temp = result = malloc(strlen(text) + (byLen - replaceLen)*count + 1); + temp = result = RL_MALLOC(strlen(text) + (byLen - replaceLen)*count + 1); if (!result) return NULL; // Memory could not be allocated @@ -1245,7 +1245,7 @@ const char *TextInsert(const char *text, const char *insert, int position) int textLen = strlen(text); int insertLen = strlen(insert); - char *result = (char *)malloc(textLen + insertLen + 1); + char *result = (char *)RL_MALLOC(textLen + insertLen + 1); for (int i = 0; i < position; i++) result[i] = text[i]; for (int i = position; i < insertLen + position; i++) result[i] = insert[i]; @@ -1477,7 +1477,7 @@ static Font LoadBMFont(const char *fileName) } // NOTE: We need some extra space to avoid memory corruption on next allocations! - texPath = malloc(strlen(fileName) - strlen(lastSlash) + strlen(texFileName) + 4); + texPath = RL_MALLOC(strlen(fileName) - strlen(lastSlash) + strlen(texFileName) + 4); // NOTE: strcat() and strncat() required a '\0' terminated string to work! *texPath = '\0'; @@ -1501,13 +1501,13 @@ static Font LoadBMFont(const char *fileName) else font.texture = LoadTextureFromImage(imFont); UnloadImage(imFont); - free(texPath); + RL_FREE(texPath); // Fill font characters info data font.baseSize = fontSize; font.charsCount = charsCount; - font.chars = (CharInfo *)malloc(charsCount*sizeof(CharInfo)); + font.chars = (CharInfo *)RL_MALLOC(charsCount*sizeof(CharInfo)); int charId, charX, charY, charWidth, charHeight, charOffsetX, charOffsetY, charAdvanceX; diff --git a/src/textures.c b/src/textures.c index 7059fabb..eb743026 100644 --- a/src/textures.c +++ b/src/textures.c @@ -112,9 +112,14 @@ defined(SUPPORT_FILEFORMAT_GIF) || \ defined(SUPPORT_FILEFORMAT_PIC) || \ defined(SUPPORT_FILEFORMAT_HDR)) + + #define STBI_MALLOC RL_MALLOC + #define STBI_FREE RL_FREE + #define STBI_REALLOC(p,newsz) realloc(p,newsz) + #define STB_IMAGE_IMPLEMENTATION - #include "external/stb_image.h" // Required for: stbi_load_from_file() - // NOTE: Used to read image data (multiple formats support) + #include "external/stb_image.h" // Required for: stbi_load_from_file() + // NOTE: Used to read image data (multiple formats support) #endif #if defined(SUPPORT_IMAGE_EXPORT) @@ -305,7 +310,7 @@ Image LoadImageEx(Color *pixels, int width, int height) int k = 0; - image.data = (unsigned char *)malloc(image.width*image.height*4*sizeof(unsigned char)); + image.data = (unsigned char *)RL_MALLOC(image.width*image.height*4*sizeof(unsigned char)); for (int i = 0; i < image.width*image.height*4; i += 4) { @@ -353,7 +358,7 @@ Image LoadImageRaw(const char *fileName, int width, int height, int format, int unsigned int size = GetPixelDataSize(width, height, format); - image.data = malloc(size); // Allocate required memory in bytes + image.data = RL_MALLOC(size); // Allocate required memory in bytes // NOTE: fread() returns num read elements instead of bytes, // to get bytes we need to read (1 byte size, elements) instead of (x byte size, 1 element) @@ -364,7 +369,7 @@ Image LoadImageRaw(const char *fileName, int width, int height, int format, int { TraceLog(LOG_WARNING, "[%s] RAW image data can not be read, wrong requested format or size", fileName); - free(image.data); + RL_FREE(image.data); } else { @@ -425,7 +430,7 @@ RenderTexture2D LoadRenderTexture(int width, int height) // Unload image from CPU memory (RAM) void UnloadImage(Image image) { - free(image.data); + RL_FREE(image.data); } // Unload texture from GPU memory (VRAM) @@ -448,7 +453,7 @@ void UnloadRenderTexture(RenderTexture2D target) // Get pixel data from image in the form of Color struct array Color *GetImageData(Image image) { - Color *pixels = (Color *)malloc(image.width*image.height*sizeof(Color)); + Color *pixels = (Color *)RL_MALLOC(image.width*image.height*sizeof(Color)); if (image.format >= COMPRESSED_DXT1_RGB) TraceLog(LOG_WARNING, "Pixel data retrieval not supported for compressed image formats"); else @@ -563,7 +568,7 @@ Color *GetImageData(Image image) // Get pixel data from image as Vector4 array (float normalized) Vector4 *GetImageDataNormalized(Image image) { - Vector4 *pixels = (Vector4 *)malloc(image.width*image.height*sizeof(Vector4)); + Vector4 *pixels = (Vector4 *)RL_MALLOC(image.width*image.height*sizeof(Vector4)); if (image.format >= COMPRESSED_DXT1_RGB) TraceLog(LOG_WARNING, "Pixel data retrieval not supported for compressed image formats"); else @@ -797,7 +802,7 @@ void ExportImage(Image image, const char *fileName) fclose(rawFile); } - free(imgData); + RL_FREE(imgData); #endif if (success != 0) TraceLog(LOG_INFO, "Image exported successfully: %s", fileName); @@ -863,7 +868,7 @@ Image ImageCopy(Image image) if (height < 1) height = 1; } - newImage.data = malloc(size); + newImage.data = RL_MALLOC(size); if (newImage.data != NULL) { @@ -896,7 +901,7 @@ void ImageToPOT(Image *image, Color fillColor) Color *pixelsPOT = NULL; // Generate POT array from NPOT data - pixelsPOT = (Color *)malloc(potWidth*potHeight*sizeof(Color)); + pixelsPOT = (Color *)RL_MALLOC(potWidth*potHeight*sizeof(Color)); for (int j = 0; j < potHeight; j++) { @@ -909,15 +914,15 @@ void ImageToPOT(Image *image, Color fillColor) TraceLog(LOG_WARNING, "Image converted to POT: (%ix%i) -> (%ix%i)", image->width, image->height, potWidth, potHeight); - free(pixels); // Free pixels data - free(image->data); // Free old image data + RL_FREE(pixels); // Free pixels data + RL_FREE(image->data); // Free old image data int format = image->format; // Store image data format to reconvert later // NOTE: Image size changes, new width and height *image = LoadImageEx(pixelsPOT, potWidth, potHeight); - free(pixelsPOT); // Free POT pixels data + RL_FREE(pixelsPOT); // Free POT pixels data ImageFormat(image, format); // Reconvert image to previous format } @@ -932,7 +937,7 @@ void ImageFormat(Image *image, int newFormat) { Vector4 *pixels = GetImageDataNormalized(*image); // Supports 8 to 32 bit per channel - free(image->data); // WARNING! We loose mipmaps data --> Regenerated at the end... + RL_FREE(image->data); // WARNING! We loose mipmaps data --> Regenerated at the end... image->data = NULL; image->format = newFormat; @@ -942,7 +947,7 @@ void ImageFormat(Image *image, int newFormat) { case UNCOMPRESSED_GRAYSCALE: { - image->data = (unsigned char *)malloc(image->width*image->height*sizeof(unsigned char)); + image->data = (unsigned char *)RL_MALLOC(image->width*image->height*sizeof(unsigned char)); for (int i = 0; i < image->width*image->height; i++) { @@ -952,7 +957,7 @@ void ImageFormat(Image *image, int newFormat) } break; case UNCOMPRESSED_GRAY_ALPHA: { - image->data = (unsigned char *)malloc(image->width*image->height*2*sizeof(unsigned char)); + image->data = (unsigned char *)RL_MALLOC(image->width*image->height*2*sizeof(unsigned char)); for (int i = 0; i < image->width*image->height*2; i += 2, k++) { @@ -963,7 +968,7 @@ void ImageFormat(Image *image, int newFormat) } break; case UNCOMPRESSED_R5G6B5: { - image->data = (unsigned short *)malloc(image->width*image->height*sizeof(unsigned short)); + image->data = (unsigned short *)RL_MALLOC(image->width*image->height*sizeof(unsigned short)); unsigned char r = 0; unsigned char g = 0; @@ -981,7 +986,7 @@ void ImageFormat(Image *image, int newFormat) } break; case UNCOMPRESSED_R8G8B8: { - image->data = (unsigned char *)malloc(image->width*image->height*3*sizeof(unsigned char)); + image->data = (unsigned char *)RL_MALLOC(image->width*image->height*3*sizeof(unsigned char)); for (int i = 0, k = 0; i < image->width*image->height*3; i += 3, k++) { @@ -994,7 +999,7 @@ void ImageFormat(Image *image, int newFormat) { #define ALPHA_THRESHOLD 50 - image->data = (unsigned short *)malloc(image->width*image->height*sizeof(unsigned short)); + image->data = (unsigned short *)RL_MALLOC(image->width*image->height*sizeof(unsigned short)); unsigned char r = 0; unsigned char g = 0; @@ -1014,7 +1019,7 @@ void ImageFormat(Image *image, int newFormat) } break; case UNCOMPRESSED_R4G4B4A4: { - image->data = (unsigned short *)malloc(image->width*image->height*sizeof(unsigned short)); + image->data = (unsigned short *)RL_MALLOC(image->width*image->height*sizeof(unsigned short)); unsigned char r = 0; unsigned char g = 0; @@ -1034,7 +1039,7 @@ void ImageFormat(Image *image, int newFormat) } break; case UNCOMPRESSED_R8G8B8A8: { - image->data = (unsigned char *)malloc(image->width*image->height*4*sizeof(unsigned char)); + image->data = (unsigned char *)RL_MALLOC(image->width*image->height*4*sizeof(unsigned char)); for (int i = 0, k = 0; i < image->width*image->height*4; i += 4, k++) { @@ -1048,7 +1053,7 @@ void ImageFormat(Image *image, int newFormat) { // WARNING: Image is converted to GRAYSCALE eqeuivalent 32bit - image->data = (float *)malloc(image->width*image->height*sizeof(float)); + image->data = (float *)RL_MALLOC(image->width*image->height*sizeof(float)); for (int i = 0; i < image->width*image->height; i++) { @@ -1057,7 +1062,7 @@ void ImageFormat(Image *image, int newFormat) } break; case UNCOMPRESSED_R32G32B32: { - image->data = (float *)malloc(image->width*image->height*3*sizeof(float)); + image->data = (float *)RL_MALLOC(image->width*image->height*3*sizeof(float)); for (int i = 0, k = 0; i < image->width*image->height*3; i += 3, k++) { @@ -1068,7 +1073,7 @@ void ImageFormat(Image *image, int newFormat) } break; case UNCOMPRESSED_R32G32B32A32: { - image->data = (float *)malloc(image->width*image->height*4*sizeof(float)); + image->data = (float *)RL_MALLOC(image->width*image->height*4*sizeof(float)); for (int i = 0, k = 0; i < image->width*image->height*4; i += 4, k++) { @@ -1081,7 +1086,7 @@ void ImageFormat(Image *image, int newFormat) default: break; } - free(pixels); + RL_FREE(pixels); pixels = NULL; // In case original image had mipmaps, generate mipmaps for formated image @@ -1286,7 +1291,7 @@ void ImageCrop(Image *image, Rectangle crop) { // Start the cropping process Color *pixels = GetImageData(*image); // Get data as Color pixels array - Color *cropPixels = (Color *)malloc((int)crop.width*(int)crop.height*sizeof(Color)); + Color *cropPixels = (Color *)RL_MALLOC((int)crop.width*(int)crop.height*sizeof(Color)); for (int j = (int)crop.y; j < (int)(crop.y + crop.height); j++) { @@ -1296,7 +1301,7 @@ void ImageCrop(Image *image, Rectangle crop) } } - free(pixels); + RL_FREE(pixels); int format = image->format; @@ -1304,7 +1309,7 @@ void ImageCrop(Image *image, Rectangle crop) *image = LoadImageEx(cropPixels, (int)crop.width, (int)crop.height); - free(cropPixels); + RL_FREE(cropPixels); // Reformat 32bit RGBA image to original format ImageFormat(image, format); @@ -1341,7 +1346,7 @@ void ImageAlphaCrop(Image *image, float threshold) Rectangle crop = { xMin, yMin, (xMax + 1) - xMin, (yMax + 1) - yMin }; - free(pixels); + RL_FREE(pixels); // Check for not empty image brefore cropping if (!((xMax < xMin) || (yMax < yMin))) ImageCrop(image, crop); @@ -1355,7 +1360,7 @@ void ImageResize(Image *image, int newWidth, int newHeight) { // Get data as Color pixels array to work with it Color *pixels = GetImageData(*image); - Color *output = (Color *)malloc(newWidth*newHeight*sizeof(Color)); + Color *output = (Color *)RL_MALLOC(newWidth*newHeight*sizeof(Color)); // NOTE: Color data is casted to (unsigned char *), there shouldn't been any problem... stbir_resize_uint8((unsigned char *)pixels, image->width, image->height, 0, (unsigned char *)output, newWidth, newHeight, 0, 4); @@ -1367,15 +1372,15 @@ void ImageResize(Image *image, int newWidth, int newHeight) *image = LoadImageEx(output, newWidth, newHeight); ImageFormat(image, format); // Reformat 32bit RGBA image to original format - free(output); - free(pixels); + RL_FREE(output); + RL_FREE(pixels); } // Resize and image to new size using Nearest-Neighbor scaling algorithm void ImageResizeNN(Image *image,int newWidth,int newHeight) { Color *pixels = GetImageData(*image); - Color *output = (Color *)malloc(newWidth*newHeight*sizeof(Color)); + Color *output = (Color *)RL_MALLOC(newWidth*newHeight*sizeof(Color)); // EDIT: added +1 to account for an early rounding problem int xRatio = (int)((image->width << 16)/newWidth) + 1; @@ -1400,8 +1405,8 @@ void ImageResizeNN(Image *image,int newWidth,int newHeight) *image = LoadImageEx(output, newWidth, newHeight); ImageFormat(image, format); // Reformat 32bit RGBA image to original format - free(output); - free(pixels); + RL_FREE(output); + RL_FREE(pixels); } // Resize canvas and fill with color @@ -1555,7 +1560,7 @@ void ImageDither(Image *image, int rBpp, int gBpp, int bBpp, int aBpp) { Color *pixels = GetImageData(*image); - free(image->data); // free old image data + RL_FREE(image->data); // free old image data if ((image->format != UNCOMPRESSED_R8G8B8) && (image->format != UNCOMPRESSED_R8G8B8A8)) { @@ -1573,7 +1578,7 @@ void ImageDither(Image *image, int rBpp, int gBpp, int bBpp, int aBpp) } // NOTE: We will store the dithered data as unsigned short (16bpp) - image->data = (unsigned short *)malloc(image->width*image->height*sizeof(unsigned short)); + image->data = (unsigned short *)RL_MALLOC(image->width*image->height*sizeof(unsigned short)); Color oldPixel = WHITE; Color newPixel = WHITE; @@ -1641,7 +1646,7 @@ void ImageDither(Image *image, int rBpp, int gBpp, int bBpp, int aBpp) } } - free(pixels); + RL_FREE(pixels); } } @@ -1652,7 +1657,7 @@ Color *ImageExtractPalette(Image image, int maxPaletteSize, int *extractCount) #define COLOR_EQUAL(col1, col2) ((col1.r == col2.r)&&(col1.g == col2.g)&&(col1.b == col2.b)&&(col1.a == col2.a)) Color *pixels = GetImageData(image); - Color *palette = (Color *)malloc(maxPaletteSize*sizeof(Color)); + Color *palette = (Color *)RL_MALLOC(maxPaletteSize*sizeof(Color)); int palCount = 0; for (int i = 0; i < maxPaletteSize; i++) palette[i] = BLANK; // Set all colors to BLANK @@ -1689,7 +1694,7 @@ Color *ImageExtractPalette(Image image, int maxPaletteSize, int *extractCount) } } - free(pixels); + RL_FREE(pixels); *extractCount = palCount; @@ -1799,8 +1804,8 @@ void ImageDraw(Image *dst, Image src, Rectangle srcRec, Rectangle dstRec) *dst = LoadImageEx(dstPixels, (int)dst->width, (int)dst->height); ImageFormat(dst, dst->format); - free(srcPixels); - free(dstPixels); + RL_FREE(srcPixels); + RL_FREE(dstPixels); } // Create an image from text (default font) @@ -1933,7 +1938,7 @@ void ImageDrawTextEx(Image *dst, Vector2 position, Font font, const char *text, void ImageFlipVertical(Image *image) { Color *srcPixels = GetImageData(*image); - Color *dstPixels = (Color *)malloc(image->width*image->height*sizeof(Color)); + Color *dstPixels = (Color *)RL_MALLOC(image->width*image->height*sizeof(Color)); for (int y = 0; y < image->height; y++) { @@ -1947,8 +1952,8 @@ void ImageFlipVertical(Image *image) ImageFormat(&processed, image->format); UnloadImage(*image); - free(srcPixels); - free(dstPixels); + RL_FREE(srcPixels); + RL_FREE(dstPixels); image->data = processed.data; } @@ -1957,7 +1962,7 @@ void ImageFlipVertical(Image *image) void ImageFlipHorizontal(Image *image) { Color *srcPixels = GetImageData(*image); - Color *dstPixels = (Color *)malloc(image->width*image->height*sizeof(Color)); + Color *dstPixels = (Color *)RL_MALLOC(image->width*image->height*sizeof(Color)); for (int y = 0; y < image->height; y++) { @@ -1971,8 +1976,8 @@ void ImageFlipHorizontal(Image *image) ImageFormat(&processed, image->format); UnloadImage(*image); - free(srcPixels); - free(dstPixels); + RL_FREE(srcPixels); + RL_FREE(dstPixels); image->data = processed.data; } @@ -1981,7 +1986,7 @@ void ImageFlipHorizontal(Image *image) void ImageRotateCW(Image *image) { Color *srcPixels = GetImageData(*image); - Color *rotPixels = (Color *)malloc(image->width*image->height*sizeof(Color)); + Color *rotPixels = (Color *)RL_MALLOC(image->width*image->height*sizeof(Color)); for (int y = 0; y < image->height; y++) { @@ -1995,8 +2000,8 @@ void ImageRotateCW(Image *image) ImageFormat(&processed, image->format); UnloadImage(*image); - free(srcPixels); - free(rotPixels); + RL_FREE(srcPixels); + RL_FREE(rotPixels); image->data = processed.data; image->width = processed.width; @@ -2007,7 +2012,7 @@ void ImageRotateCW(Image *image) void ImageRotateCCW(Image *image) { Color *srcPixels = GetImageData(*image); - Color *rotPixels = (Color *)malloc(image->width*image->height*sizeof(Color)); + Color *rotPixels = (Color *)RL_MALLOC(image->width*image->height*sizeof(Color)); for (int y = 0; y < image->height; y++) { @@ -2021,8 +2026,8 @@ void ImageRotateCCW(Image *image) ImageFormat(&processed, image->format); UnloadImage(*image); - free(srcPixels); - free(rotPixels); + RL_FREE(srcPixels); + RL_FREE(rotPixels); image->data = processed.data; image->width = processed.width; @@ -2059,7 +2064,7 @@ void ImageColorTint(Image *image, Color color) Image processed = LoadImageEx(pixels, image->width, image->height); ImageFormat(&processed, image->format); UnloadImage(*image); - free(pixels); + RL_FREE(pixels); image->data = processed.data; } @@ -2082,7 +2087,7 @@ void ImageColorInvert(Image *image) Image processed = LoadImageEx(pixels, image->width, image->height); ImageFormat(&processed, image->format); UnloadImage(*image); - free(pixels); + RL_FREE(pixels); image->data = processed.data; } @@ -2142,7 +2147,7 @@ void ImageColorContrast(Image *image, float contrast) Image processed = LoadImageEx(pixels, image->width, image->height); ImageFormat(&processed, image->format); UnloadImage(*image); - free(pixels); + RL_FREE(pixels); image->data = processed.data; } @@ -2182,7 +2187,7 @@ void ImageColorBrightness(Image *image, int brightness) Image processed = LoadImageEx(pixels, image->width, image->height); ImageFormat(&processed, image->format); UnloadImage(*image); - free(pixels); + RL_FREE(pixels); image->data = processed.data; } @@ -2212,7 +2217,7 @@ void ImageColorReplace(Image *image, Color color, Color replace) Image processed = LoadImageEx(pixels, image->width, image->height); ImageFormat(&processed, image->format); UnloadImage(*image); - free(pixels); + RL_FREE(pixels); image->data = processed.data; } @@ -2221,13 +2226,13 @@ void ImageColorReplace(Image *image, Color color, Color replace) // Generate image: plain color Image GenImageColor(int width, int height, Color color) { - Color *pixels = (Color *)calloc(width*height, sizeof(Color)); + Color *pixels = (Color *)RL_CALLOC(width*height, sizeof(Color)); for (int i = 0; i < width*height; i++) pixels[i] = color; Image image = LoadImageEx(pixels, width, height); - free(pixels); + RL_FREE(pixels); return image; } @@ -2236,7 +2241,7 @@ Image GenImageColor(int width, int height, Color color) // Generate image: vertical gradient Image GenImageGradientV(int width, int height, Color top, Color bottom) { - Color *pixels = (Color *)malloc(width*height*sizeof(Color)); + Color *pixels = (Color *)RL_MALLOC(width*height*sizeof(Color)); for (int j = 0; j < height; j++) { @@ -2251,7 +2256,7 @@ Image GenImageGradientV(int width, int height, Color top, Color bottom) } Image image = LoadImageEx(pixels, width, height); - free(pixels); + RL_FREE(pixels); return image; } @@ -2259,7 +2264,7 @@ Image GenImageGradientV(int width, int height, Color top, Color bottom) // Generate image: horizontal gradient Image GenImageGradientH(int width, int height, Color left, Color right) { - Color *pixels = (Color *)malloc(width*height*sizeof(Color)); + Color *pixels = (Color *)RL_MALLOC(width*height*sizeof(Color)); for (int i = 0; i < width; i++) { @@ -2274,7 +2279,7 @@ Image GenImageGradientH(int width, int height, Color left, Color right) } Image image = LoadImageEx(pixels, width, height); - free(pixels); + RL_FREE(pixels); return image; } @@ -2282,7 +2287,7 @@ Image GenImageGradientH(int width, int height, Color left, Color right) // Generate image: radial gradient Image GenImageGradientRadial(int width, int height, float density, Color inner, Color outer) { - Color *pixels = (Color *)malloc(width*height*sizeof(Color)); + Color *pixels = (Color *)RL_MALLOC(width*height*sizeof(Color)); float radius = (width < height)? (float)width/2.0f : (float)height/2.0f; float centerX = (float)width/2.0f; @@ -2306,7 +2311,7 @@ Image GenImageGradientRadial(int width, int height, float density, Color inner, } Image image = LoadImageEx(pixels, width, height); - free(pixels); + RL_FREE(pixels); return image; } @@ -2314,7 +2319,7 @@ Image GenImageGradientRadial(int width, int height, float density, Color inner, // Generate image: checked Image GenImageChecked(int width, int height, int checksX, int checksY, Color col1, Color col2) { - Color *pixels = (Color *)malloc(width*height*sizeof(Color)); + Color *pixels = (Color *)RL_MALLOC(width*height*sizeof(Color)); for (int y = 0; y < height; y++) { @@ -2326,7 +2331,7 @@ Image GenImageChecked(int width, int height, int checksX, int checksY, Color col } Image image = LoadImageEx(pixels, width, height); - free(pixels); + RL_FREE(pixels); return image; } @@ -2334,7 +2339,7 @@ Image GenImageChecked(int width, int height, int checksX, int checksY, Color col // Generate image: white noise Image GenImageWhiteNoise(int width, int height, float factor) { - Color *pixels = (Color *)malloc(width*height*sizeof(Color)); + Color *pixels = (Color *)RL_MALLOC(width*height*sizeof(Color)); for (int i = 0; i < width*height; i++) { @@ -2343,7 +2348,7 @@ Image GenImageWhiteNoise(int width, int height, float factor) } Image image = LoadImageEx(pixels, width, height); - free(pixels); + RL_FREE(pixels); return image; } @@ -2351,7 +2356,7 @@ Image GenImageWhiteNoise(int width, int height, float factor) // Generate image: perlin noise Image GenImagePerlinNoise(int width, int height, int offsetX, int offsetY, float scale) { - Color *pixels = (Color *)malloc(width*height*sizeof(Color)); + Color *pixels = (Color *)RL_MALLOC(width*height*sizeof(Color)); for (int y = 0; y < height; y++) { @@ -2374,7 +2379,7 @@ Image GenImagePerlinNoise(int width, int height, int offsetX, int offsetY, float } Image image = LoadImageEx(pixels, width, height); - free(pixels); + RL_FREE(pixels); return image; } @@ -2382,13 +2387,13 @@ Image GenImagePerlinNoise(int width, int height, int offsetX, int offsetY, float // Generate image: cellular algorithm. Bigger tileSize means bigger cells Image GenImageCellular(int width, int height, int tileSize) { - Color *pixels = (Color *)malloc(width*height*sizeof(Color)); + Color *pixels = (Color *)RL_MALLOC(width*height*sizeof(Color)); int seedsPerRow = width/tileSize; int seedsPerCol = height/tileSize; int seedsCount = seedsPerRow * seedsPerCol; - Vector2 *seeds = (Vector2 *)malloc(seedsCount*sizeof(Vector2)); + Vector2 *seeds = (Vector2 *)RL_MALLOC(seedsCount*sizeof(Vector2)); for (int i = 0; i < seedsCount; i++) { @@ -2431,10 +2436,10 @@ Image GenImageCellular(int width, int height, int tileSize) } } - free(seeds); + RL_FREE(seeds); Image image = LoadImageEx(pixels, width, height); - free(pixels); + RL_FREE(pixels); return image; } @@ -2921,7 +2926,7 @@ static Image LoadDDS(const char *fileName) { if (ddsHeader.ddspf.flags == 0x40) // no alpha channel { - image.data = (unsigned short *)malloc(image.width*image.height*sizeof(unsigned short)); + image.data = (unsigned short *)RL_MALLOC(image.width*image.height*sizeof(unsigned short)); fread(image.data, image.width*image.height*sizeof(unsigned short), 1, ddsFile); image.format = UNCOMPRESSED_R5G6B5; @@ -2930,7 +2935,7 @@ static Image LoadDDS(const char *fileName) { if (ddsHeader.ddspf.aBitMask == 0x8000) // 1bit alpha { - image.data = (unsigned short *)malloc(image.width*image.height*sizeof(unsigned short)); + image.data = (unsigned short *)RL_MALLOC(image.width*image.height*sizeof(unsigned short)); fread(image.data, image.width*image.height*sizeof(unsigned short), 1, ddsFile); unsigned char alpha = 0; @@ -2947,7 +2952,7 @@ static Image LoadDDS(const char *fileName) } else if (ddsHeader.ddspf.aBitMask == 0xf000) // 4bit alpha { - image.data = (unsigned short *)malloc(image.width*image.height*sizeof(unsigned short)); + image.data = (unsigned short *)RL_MALLOC(image.width*image.height*sizeof(unsigned short)); fread(image.data, image.width*image.height*sizeof(unsigned short), 1, ddsFile); unsigned char alpha = 0; @@ -2967,14 +2972,14 @@ static Image LoadDDS(const char *fileName) if (ddsHeader.ddspf.flags == 0x40 && ddsHeader.ddspf.rgbBitCount == 24) // DDS_RGB, no compressed { // NOTE: not sure if this case exists... - image.data = (unsigned char *)malloc(image.width*image.height*3*sizeof(unsigned char)); + image.data = (unsigned char *)RL_MALLOC(image.width*image.height*3*sizeof(unsigned char)); fread(image.data, image.width*image.height*3, 1, ddsFile); image.format = UNCOMPRESSED_R8G8B8; } else if (ddsHeader.ddspf.flags == 0x41 && ddsHeader.ddspf.rgbBitCount == 32) // DDS_RGBA, no compressed { - image.data = (unsigned char *)malloc(image.width*image.height*4*sizeof(unsigned char)); + image.data = (unsigned char *)RL_MALLOC(image.width*image.height*4*sizeof(unsigned char)); fread(image.data, image.width*image.height*4, 1, ddsFile); unsigned char blue = 0; @@ -3001,7 +3006,7 @@ static Image LoadDDS(const char *fileName) TraceLog(LOG_DEBUG, "Pitch or linear size: %i", ddsHeader.pitchOrLinearSize); - image.data = (unsigned char *)malloc(size*sizeof(unsigned char)); + image.data = (unsigned char *)RL_MALLOC(size*sizeof(unsigned char)); fread(image.data, size, 1, ddsFile); @@ -3098,7 +3103,7 @@ static Image LoadPKM(const char *fileName) int size = image.width*image.height*bpp/8; // Total data size in bytes - image.data = (unsigned char *)malloc(size*sizeof(unsigned char)); + image.data = (unsigned char *)RL_MALLOC(size*sizeof(unsigned char)); fread(image.data, size, 1, pkmFile); @@ -3192,7 +3197,7 @@ static Image LoadKTX(const char *fileName) int dataSize; fread(&dataSize, sizeof(unsigned int), 1, ktxFile); - image.data = (unsigned char *)malloc(dataSize*sizeof(unsigned char)); + image.data = (unsigned char *)RL_MALLOC(dataSize*sizeof(unsigned char)); fread(image.data, dataSize, 1, ktxFile); @@ -3441,7 +3446,7 @@ static Image LoadPVR(const char *fileName) } int dataSize = image.width*image.height*bpp/8; // Total data size in bytes - image.data = (unsigned char *)malloc(dataSize*sizeof(unsigned char)); + image.data = (unsigned char *)RL_MALLOC(dataSize*sizeof(unsigned char)); // Read data from file fread(image.data, dataSize, 1, pvrFile); @@ -3518,7 +3523,7 @@ static Image LoadASTC(const char *fileName) { int dataSize = image.width*image.height*bpp/8; // Data size in bytes - image.data = (unsigned char *)malloc(dataSize*sizeof(unsigned char)); + image.data = (unsigned char *)RL_MALLOC(dataSize*sizeof(unsigned char)); fread(image.data, dataSize, 1, astcFile); if (bpp == 8) image.format = COMPRESSED_ASTC_4x4_RGBA; diff --git a/src/utils.c b/src/utils.c index 10cce9b9..3cff472b 100644 --- a/src/utils.c +++ b/src/utils.c @@ -45,10 +45,10 @@ #include // Required for: Android assets manager: AAsset, AAssetManager_open(), ... #endif -#include // Required for: malloc(), free() -#include // Required for: fopen(), fclose(), fputc(), fwrite(), printf(), fprintf(), funopen() +#include // Required for: exit() +#include // Required for: printf(), sprintf() #include // Required for: va_list, va_start(), vfprintf(), va_end() -#include // Required for: strlen(), strrchr(), strcmp() +#include // Required for: strcpy(), strcat() #define MAX_TRACELOG_BUFFER_SIZE 128 // Max length of one trace-log message -- cgit v1.2.3 From 10c2eea14be1f75f1e01ecd7db6d8bd2788ce67c Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 23 Apr 2019 15:07:28 +0200 Subject: Correct RL_FREE bug --- src/raudio.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/raudio.c b/src/raudio.c index 9108a903..e5aef5cf 100644 --- a/src/raudio.c +++ b/src/raudio.c @@ -1228,7 +1228,7 @@ Music LoadMusicStream(const char *fileName) if (false) {} #endif #if defined(SUPPORT_FILEFORMAT_FLAC) - else if (music->ctxType == MUSIC_AUDIO_FLAC) drflac_RL_FREE(music->ctxFlac); + else if (music->ctxType == MUSIC_AUDIO_FLAC) drflac_free(music->ctxFlac); #endif #if defined(SUPPORT_FILEFORMAT_MP3) else if (music->ctxType == MUSIC_AUDIO_MP3) drmp3_uninit(&music->ctxMp3); @@ -1262,7 +1262,7 @@ void UnloadMusicStream(Music music) if (false) {} #endif #if defined(SUPPORT_FILEFORMAT_FLAC) - else if (music->ctxType == MUSIC_AUDIO_FLAC) drflac_RL_FREE(music->ctxFlac); + else if (music->ctxType == MUSIC_AUDIO_FLAC) drflac_free(music->ctxFlac); #endif #if defined(SUPPORT_FILEFORMAT_MP3) else if (music->ctxType == MUSIC_AUDIO_MP3) drmp3_uninit(&music->ctxMp3); -- cgit v1.2.3 From 87b75a6c95db503e2a1688e389e9db9e53936d62 Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 23 Apr 2019 15:12:08 +0200 Subject: Review issues on OpenGL 1.1 --- src/rlgl.h | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src') diff --git a/src/rlgl.h b/src/rlgl.h index c2ddd028..bb421d1f 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -1429,8 +1429,10 @@ void rlClearScreenBuffers(void) // Update GPU buffer with new data void rlUpdateBuffer(int bufferId, void *data, int dataSize) { +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) glBindBuffer(GL_ARRAY_BUFFER, bufferId); glBufferSubData(GL_ARRAY_BUFFER, 0, dataSize, data); +#endif } //---------------------------------------------------------------------------------- @@ -3533,6 +3535,7 @@ void CloseVrSimulator(void) // Set stereo rendering configuration parameters void SetVrConfiguration(VrDeviceInfo hmd, Shader distortion) { +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) // Reset vrConfig for a new values assignment memset(&vrConfig, 0, sizeof(vrConfig)); @@ -3610,6 +3613,7 @@ void SetVrConfiguration(VrDeviceInfo hmd, Shader distortion) SetShaderValue(vrConfig.distortionShader, GetShaderLocation(vrConfig.distortionShader, "hmdWarpParam"), hmd.lensDistortionValues, UNIFORM_VEC4); SetShaderValue(vrConfig.distortionShader, GetShaderLocation(vrConfig.distortionShader, "chromaAbParam"), hmd.chromaAbCorrection, UNIFORM_VEC4); } +#endif } // Detect if VR simulator is running -- cgit v1.2.3 From 4ad81ba2d47890303dfa0ee33d39097fcce856b8 Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 23 Apr 2019 15:14:15 +0200 Subject: Alloc custom allocators on standalone mode --- src/rlgl.h | 11 +++++++++++ 1 file changed, 11 insertions(+) (limited to 'src') diff --git a/src/rlgl.h b/src/rlgl.h index bb421d1f..dd2929ca 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -72,6 +72,17 @@ #else #define RLAPI // We are building or using raylib as a static library (or Linux shared library) #endif + + // Allow custom memory allocators + #ifndef RL_MALLOC + #define RL_MALLOC(sz) malloc(sz) + #endif + #ifndef RL_CALLOC + #define RL_CALLOC(n,sz) calloc(n,sz) + #endif + #ifndef RL_FREE + #define RL_FREE(p) free(p) + #endif #else #include "raylib.h" // Required for: Model, Shader, Texture2D, TraceLog() #endif -- cgit v1.2.3 From 372d77957fdc73991dca3f406c71a2c9a24b9e03 Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 23 Apr 2019 16:01:18 +0200 Subject: Update STB libraries to latest version --- src/external/par_shapes.h | 2 +- src/external/stb_image.h | 44 +++++++++++++++++++++++++++++------------ src/external/stb_image_resize.h | 9 ++++++--- src/external/stb_image_write.h | 37 ++++++++++++++++------------------ src/external/stb_rect_pack.h | 13 ++++++++++-- src/external/stb_truetype.h | 16 ++------------- 6 files changed, 68 insertions(+), 53 deletions(-) (limited to 'src') diff --git a/src/external/par_shapes.h b/src/external/par_shapes.h index 39831c8b..af06804d 100644 --- a/src/external/par_shapes.h +++ b/src/external/par_shapes.h @@ -10,7 +10,7 @@ // In addition to the comment block above each function declaration, the API // has informal documentation here: // -// http://github.prideout.net/shapes/ +// https://prideout.net/shapes // // For our purposes, a "mesh" is a list of points and a list of triangles; the // former is a flattened list of three-tuples (32-bit floats) and the latter is diff --git a/src/external/stb_image.h b/src/external/stb_image.h index 5a6c863f..a6202a31 100644 --- a/src/external/stb_image.h +++ b/src/external/stb_image.h @@ -1,4 +1,4 @@ -/* stb_image - v2.20 - public domain image loader - http://nothings.org/stb +/* stb_image - v2.22 - public domain image loader - http://nothings.org/stb no warranty implied; use at your own risk Do this: @@ -48,6 +48,8 @@ LICENSE RECENT REVISION HISTORY: + 2.22 (2019-03-04) gif fixes, fix warnings + 2.21 (2019-02-25) fix typo in comment 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs 2.19 (2018-02-11) fix warning 2.18 (2018-01-30) fix warnings @@ -168,7 +170,7 @@ RECENT REVISION HISTORY: // If compiling for Windows and you wish to use Unicode filenames, compile // with // #define STBI_WINDOWS_UTF8 -// and pass utf8-encoded filenames. Call stbiw_convert_wchar_to_utf8 to convert +// and pass utf8-encoded filenames. Call stbi_convert_wchar_to_utf8 to convert // Windows wchar_t filenames to utf8. // // =========================================================================== @@ -338,11 +340,13 @@ typedef unsigned short stbi_us; extern "C" { #endif +#ifndef STBIDEF #ifdef STB_IMAGE_STATIC #define STBIDEF static #else #define STBIDEF extern #endif +#endif ////////////////////////////////////////////////////////////////////////////// // @@ -1181,7 +1185,7 @@ STBI_EXTERN __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int #if defined(_MSC_VER) && defined(STBI_WINDOWS_UTF8) STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input) { - return WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer, bufferlen, NULL, NULL); + return WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer, (int) bufferlen, NULL, NULL); } #endif @@ -3658,7 +3662,7 @@ static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp int k; unsigned int i,j; stbi_uc *output; - stbi_uc *coutput[4]; + stbi_uc *coutput[4] = { NULL, NULL, NULL, NULL }; stbi__resample res_comp[4]; @@ -6411,18 +6415,22 @@ static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, i // on first frame, any non-written pixels get the background colour (non-transparent) first_frame = 0; if (g->out == 0) { - if (!stbi__gif_header(s, g, comp,0)) return 0; // stbi__g_failure_reason set by stbi__gif_header - g->out = (stbi_uc *) stbi__malloc(4 * g->w * g->h); - g->background = (stbi_uc *) stbi__malloc(4 * g->w * g->h); - g->history = (stbi_uc *) stbi__malloc(g->w * g->h); - if (g->out == 0) return stbi__errpuc("outofmem", "Out of memory"); + if (!stbi__gif_header(s, g, comp,0)) return 0; // stbi__g_failure_reason set by stbi__gif_header + if (!stbi__mad3sizes_valid(4, g->w, g->h, 0)) + return stbi__errpuc("too large", "GIF image is too large"); + pcount = g->w * g->h; + g->out = (stbi_uc *) stbi__malloc(4 * pcount); + g->background = (stbi_uc *) stbi__malloc(4 * pcount); + g->history = (stbi_uc *) stbi__malloc(pcount); + if (!g->out || !g->background || !g->history) + return stbi__errpuc("outofmem", "Out of memory"); // image is treated as "transparent" at the start - ie, nothing overwrites the current background; // background colour is only used for pixels that are not rendered first frame, after that "background" // color refers to the color that was there the previous frame. - memset( g->out, 0x00, 4 * g->w * g->h ); - memset( g->background, 0x00, 4 * g->w * g->h ); // state of the background (starts transparent) - memset( g->history, 0x00, g->w * g->h ); // pixels that were affected previous frame + memset(g->out, 0x00, 4 * pcount); + memset(g->background, 0x00, 4 * pcount); // state of the background (starts transparent) + memset(g->history, 0x00, pcount); // pixels that were affected previous frame first_frame = 1; } else { // second frame - how do we dispoase of the previous one? @@ -6483,6 +6491,13 @@ static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, i g->cur_x = g->start_x; g->cur_y = g->start_y; + // if the width of the specified rectangle is 0, that means + // we may not see *any* pixels or the image is malformed; + // to make sure this is caught, move the current y down to + // max_y (which is what out_gif_code checks). + if (w == 0) + g->cur_y = g->max_y; + g->lflags = stbi__get8(s); if (g->lflags & 0x40) { @@ -6502,7 +6517,7 @@ static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, i return stbi__errpuc("missing color table", "Corrupt GIF"); o = stbi__process_gif_raster(s, g); - if (o == NULL) return NULL; + if (!o) return NULL; // if this was the first frame, pcount = g->w * g->h; @@ -6642,6 +6657,9 @@ static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req // can be done for multiple frames. if (req_comp && req_comp != 4) u = stbi__convert_format(u, 4, req_comp, g.w, g.h); + } else if (g.out) { + // if there was an error and we allocated an image buffer, free it! + STBI_FREE(g.out); } // free buffers needed for multiple frame loading; diff --git a/src/external/stb_image_resize.h b/src/external/stb_image_resize.h index 031ca99d..4f6ad35e 100644 --- a/src/external/stb_image_resize.h +++ b/src/external/stb_image_resize.h @@ -1,4 +1,4 @@ -/* stb_image_resize - v0.95 - public domain image resizing +/* stb_image_resize - v0.96 - public domain image resizing by Jorge L Rodriguez (@VinoBS) - 2014 http://github.com/nothings/stb @@ -159,6 +159,7 @@ Nathan Reed: warning fixes REVISIONS + 0.96 (2019-03-04) fixed warnings 0.95 (2017-07-23) fixed warnings 0.94 (2017-03-18) fixed warnings 0.93 (2017-03-03) fixed bug with certain combinations of heights @@ -193,6 +194,7 @@ typedef uint16_t stbir_uint16; typedef uint32_t stbir_uint32; #endif +#ifndef STBIRDEF #ifdef STB_IMAGE_RESIZE_STATIC #define STBIRDEF static #else @@ -202,7 +204,7 @@ typedef uint32_t stbir_uint32; #define STBIRDEF extern #endif #endif - +#endif ////////////////////////////////////////////////////////////////////////////// // @@ -2324,8 +2326,9 @@ static int stbir__resize_allocated(stbir__info *info, if (alpha_channel < 0) flags |= STBIR_FLAG_ALPHA_USES_COLORSPACE | STBIR_FLAG_ALPHA_PREMULTIPLIED; - if (!(flags&STBIR_FLAG_ALPHA_USES_COLORSPACE) || !(flags&STBIR_FLAG_ALPHA_PREMULTIPLIED)) + if (!(flags&STBIR_FLAG_ALPHA_USES_COLORSPACE) || !(flags&STBIR_FLAG_ALPHA_PREMULTIPLIED)) { STBIR_ASSERT(alpha_channel >= 0 && alpha_channel < info->channels); + } if (alpha_channel >= info->channels) return 0; diff --git a/src/external/stb_image_write.h b/src/external/stb_image_write.h index 00ab092a..a19b548a 100644 --- a/src/external/stb_image_write.h +++ b/src/external/stb_image_write.h @@ -1,4 +1,4 @@ -/* stb_image_write - v1.10 - public domain - http://nothings.org/stb/stb_image_write.h +/* stb_image_write - v1.13 - public domain - http://nothings.org/stb/stb_image_write.h writes out PNG/BMP/TGA/JPEG/HDR images to C stdio - Sean Barrett 2010-2015 no warranty implied; use at your own risk @@ -299,7 +299,7 @@ STBIW_EXTERN __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned in STBIWDEF int stbiw_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input) { - return WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer, bufferlen, NULL, NULL); + return WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer, (int) bufferlen, NULL, NULL); } #endif @@ -393,7 +393,7 @@ static void stbiw__putc(stbi__write_context *s, unsigned char c) static void stbiw__write3(stbi__write_context *s, unsigned char a, unsigned char b, unsigned char c) { unsigned char arr[3]; - arr[0] = a, arr[1] = b, arr[2] = c; + arr[0] = a; arr[1] = b; arr[2] = c; s->func(s->context, arr, 3); } @@ -441,10 +441,11 @@ static void stbiw__write_pixels(stbi__write_context *s, int rgb_dir, int vdir, i if (stbi__flip_vertically_on_write) vdir *= -1; - if (vdir < 0) - j_end = -1, j = y-1; - else - j_end = y, j = 0; + if (vdir < 0) { + j_end = -1; j = y-1; + } else { + j_end = y; j = 0; + } for (; j != j_end; j += vdir) { for (i=0; i < x; ++i) { @@ -736,8 +737,8 @@ static int stbi_write_hdr_core(stbi__write_context *s, int x, int y, int comp, f char header[] = "#?RADIANCE\n# Written by stb_image_write.h\nFORMAT=32-bit_rle_rgbe\n"; s->func(s->context, header, sizeof(header)-1); -#ifdef STBI_MSC_SECURE_CRT - len = sprintf_s(buffer, "EXPOSURE= 1.0000000000000\n\n-Y %d +X %d\n", y, x); +#ifdef __STDC_WANT_SECURE_LIB__ + len = sprintf_s(buffer, sizeof(buffer), "EXPOSURE= 1.0000000000000\n\n-Y %d +X %d\n", y, x); #else len = sprintf(buffer, "EXPOSURE= 1.0000000000000\n\n-Y %d +X %d\n", y, x); #endif @@ -895,7 +896,7 @@ STBIWDEF unsigned char * stbi_zlib_compress(unsigned char *data, int data_len, i for (j=0; j < n; ++j) { if (hlist[j]-data > i-32768) { // if entry lies within window int d = stbiw__zlib_countm(hlist[j], data+i, data_len-i); - if (d >= best) best=d,bestloc=hlist[j]; + if (d >= best) { best=d; bestloc=hlist[j]; } } } // when hash table entry is too long, delete half the entries @@ -954,8 +955,8 @@ STBIWDEF unsigned char * stbi_zlib_compress(unsigned char *data, int data_len, i int blocklen = (int) (data_len % 5552); j=0; while (j < data_len) { - for (i=0; i < blocklen; ++i) s1 += data[j+i], s2 += s1; - s1 %= 65521, s2 %= 65521; + for (i=0; i < blocklen; ++i) { s1 += data[j+i]; s2 += s1; } + s1 %= 65521; s2 %= 65521; j += blocklen; blocklen = 5552; } @@ -1476,17 +1477,13 @@ static int stbi_write_jpg_core(stbi__write_context *s, int width, int height, in for(x = 0; x < width; x += 8) { float YDU[64], UDU[64], VDU[64]; for(row = y, pos = 0; row < y+8; ++row) { - int p; - if(row < height) { - p = (stbi__flip_vertically_on_write ? (height-1-row) : row)*width*comp; - } else { - // row >= height => use last input row (=> first if flipping) - p = stbi__flip_vertically_on_write ? 0 : ((height-1)*width*comp); - } + // row >= height => use last input row + int clamped_row = (row < height) ? row : height - 1; + int base_p = (stbi__flip_vertically_on_write ? (height-1-clamped_row) : clamped_row)*width*comp; for(col = x; col < x+8; ++col, ++pos) { float r, g, b; // if col >= width => use pixel from last input column - p += ((col < width) ? col : (width-1))*comp; + int p = base_p + ((col < width) ? col : (width-1))*comp; r = imageData[p+0]; g = imageData[p+ofsG]; diff --git a/src/external/stb_rect_pack.h b/src/external/stb_rect_pack.h index 3632c85a..d32c8f9e 100644 --- a/src/external/stb_rect_pack.h +++ b/src/external/stb_rect_pack.h @@ -1,4 +1,4 @@ -// stb_rect_pack.h - v0.99 - public domain - rectangle packing +// stb_rect_pack.h - v1.00 - public domain - rectangle packing // Sean Barrett 2014 // // Useful for e.g. packing rectangular textures into an atlas. @@ -31,9 +31,11 @@ // // Bugfixes / warning fixes // Jeremy Jaussaud +// Fabian Giesen // // Version history: // +// 1.00 (2019-02-25) avoid small space waste; gracefully fail too-wide rectangles // 0.99 (2019-02-07) warning fixes // 0.11 (2017-03-03) return packing success/fail result // 0.10 (2016-10-25) remove cast-away-const to avoid warnings @@ -348,6 +350,13 @@ static stbrp__findresult stbrp__skyline_find_best_pos(stbrp_context *c, int widt width -= width % c->align; STBRP_ASSERT(width % c->align == 0); + // if it can't possibly fit, bail immediately + if (width > c->width || height > c->height) { + fr.prev_link = NULL; + fr.x = fr.y = 0; + return fr; + } + node = c->active_head; prev = &c->active_head; while (node->x + width <= c->width) { @@ -411,7 +420,7 @@ static stbrp__findresult stbrp__skyline_find_best_pos(stbrp_context *c, int widt } STBRP_ASSERT(node->next->x > xpos && node->x <= xpos); y = stbrp__skyline_find_min_y(c, node, xpos, width, &waste); - if (y + height < c->height) { + if (y + height <= c->height) { if (y <= best_y) { if (y < best_y || waste < best_waste || (waste==best_waste && xpos < best_x)) { best_x = xpos; diff --git a/src/external/stb_truetype.h b/src/external/stb_truetype.h index a4d387c5..767f005a 100644 --- a/src/external/stb_truetype.h +++ b/src/external/stb_truetype.h @@ -1,4 +1,4 @@ -// stb_truetype.h - v1.20 - public domain +// stb_truetype.h - v1.21 - public domain // authored from 2009-2016 by Sean Barrett / RAD Game Tools // // This library processes TrueType files: @@ -49,6 +49,7 @@ // // VERSION HISTORY // +// 1.21 (2019-02-25) fix warning // 1.20 (2019-02-07) PackFontRange skips missing codepoints; GetScaleFontVMetrics() // 1.19 (2018-02-11) GPOS kerning, STBTT_fmod // 1.18 (2018-01-29) add missing function @@ -243,19 +244,6 @@ // recommend it. // // -// SOURCE STATISTICS (based on v0.6c, 2050 LOC) -// -// Documentation & header file 520 LOC \___ 660 LOC documentation -// Sample code 140 LOC / -// Truetype parsing 620 LOC ---- 620 LOC TrueType -// Software rasterization 240 LOC \ -// Curve tessellation 120 LOC \__ 550 LOC Bitmap creation -// Bitmap management 100 LOC / -// Baked bitmap interface 70 LOC / -// Font name matching & access 150 LOC ---- 150 -// C runtime library abstraction 60 LOC ---- 60 -// -// // PERFORMANCE MEASUREMENTS FOR 1.06: // // 32-bit 64-bit -- cgit v1.2.3 From 3aafa9d5ba3fa0a2cbb5759b569c8772a0385d41 Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 23 Apr 2019 16:01:38 +0200 Subject: Set a version for rGIF library --- src/external/rgif.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/external/rgif.h b/src/external/rgif.h index 13c7ff3e..ae7db35c 100644 --- a/src/external/rgif.h +++ b/src/external/rgif.h @@ -1,6 +1,8 @@ /********************************************************************************************** * -* rgif.h original implementation (gif.h) by Charlie Tangora [ctangora -at- gmail -dot- com] +* rgif.h v0.5 +* +* Original implementation (gif.h) by Charlie Tangora [ctangora -at- gmail -dot- com] * adapted to C99, reformatted and renamed by Ramon Santamaria (@raysan5) * * This file offers a simple, very limited way to create animated GIFs directly in code. -- cgit v1.2.3 From 0c567cd259285fb33b3e2ab514c48322da0a0000 Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 23 Apr 2019 18:10:38 +0200 Subject: WARNING: Issues on web building Found some issues when building for web using latest emscripten 1.38.30, traced the error and found that eglGetProcAdress does not return function pointers for VAO functionality, supported by extension. It requires more investigation but now it works (avoiding VAO usage) --- src/Makefile | 2 +- src/core.c | 3 ++- src/external/cgltf.h | 4 ++-- src/external/miniaudio.h | 2 -- src/rlgl.h | 12 ++++++++++++ 5 files changed, 17 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/Makefile b/src/Makefile index 997f041c..ea09aa9f 100644 --- a/src/Makefile +++ b/src/Makefile @@ -42,7 +42,7 @@ .PHONY: all clean install uninstall # Define required raylib variables -RAYLIB_VERSION = 2.4.0 +RAYLIB_VERSION = 2.5.0 RAYLIB_API_VERSION = 2 # See below for alternatives. diff --git a/src/core.c b/src/core.c index 844994d0..5ec3b76a 100644 --- a/src/core.c +++ b/src/core.c @@ -3172,7 +3172,8 @@ static void PollInputEvents(void) // NOTE: GLFW3 joystick functionality not available in web #if defined(PLATFORM_WEB) // Get number of gamepads connected - int numGamepads = emscripten_get_num_gamepads(); + int numGamepads = 0; + if (emscripten_sample_gamepad_data() == EMSCRIPTEN_RESULT_SUCCESS) numGamepads = emscripten_get_num_gamepads(); for (int i = 0; (i < numGamepads) && (i < MAX_GAMEPADS); i++) { diff --git a/src/external/cgltf.h b/src/external/cgltf.h index 4302e77b..85d5c985 100644 --- a/src/external/cgltf.h +++ b/src/external/cgltf.h @@ -369,7 +369,7 @@ typedef struct cgltf_light { cgltf_float spot_outer_cone_angle; } cgltf_light; -typedef struct cgltf_node { +struct cgltf_node { char* name; cgltf_node* parent; cgltf_node** children; @@ -388,7 +388,7 @@ typedef struct cgltf_node { cgltf_float rotation[4]; cgltf_float scale[3]; cgltf_float matrix[16]; -} cgltf_node; +}; typedef struct cgltf_scene { char* name; diff --git a/src/external/miniaudio.h b/src/external/miniaudio.h index a5646c71..dae605f2 100644 --- a/src/external/miniaudio.h +++ b/src/external/miniaudio.h @@ -21915,8 +21915,6 @@ extern "C" { #endif EMSCRIPTEN_KEEPALIVE void ma_device_process_pcm_frames_capture__webaudio(ma_device* pDevice, int frameCount, float* pFrames) { - ma_result result; - if (pDevice->type == ma_device_type_duplex) { ma_device__handle_duplex_callback_capture(pDevice, (ma_uint32)frameCount, pFrames, &pDevice->webaudio.duplexRB); } else { diff --git a/src/rlgl.h b/src/rlgl.h index dd2929ca..71a1dc4b 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -1559,7 +1559,19 @@ void rlglInit(int width, int height) glBindVertexArray = (PFNGLBINDVERTEXARRAYOESPROC)eglGetProcAddress("glBindVertexArrayOES"); glDeleteVertexArrays = (PFNGLDELETEVERTEXARRAYSOESPROC)eglGetProcAddress("glDeleteVertexArraysOES"); //glIsVertexArray = (PFNGLISVERTEXARRAYOESPROC)eglGetProcAddress("glIsVertexArrayOES"); // NOTE: Fails in WebGL, omitted + + if (glGenVertexArrays == NULL) printf("glGenVertexArrays is NULL.\n"); // WEB: ISSUE FOUND! ...but why? + if (glBindVertexArray == NULL) printf("glBindVertexArray is NULL.\n"); // WEB: ISSUE FOUND! ...but why? } + + // TODO: HACK REVIEW! + // For some reason on raylib 2.5, VAO usage breaks the build + // error seems related to function pointers but I can not get detailed info... + // Avoiding VAO usage is the only solution for now... :( + // Ref: https://emscripten.org/docs/porting/guidelines/function_pointer_issues.html + #if defined(PLATFORM_WEB) + vaoSupported = false; + #endif // Check NPOT textures support // NOTE: Only check on OpenGL ES, OpenGL 3.3 has NPOT textures full support as core feature -- cgit v1.2.3 From 0e683005b4d485131a0c727676dd83836298a964 Mon Sep 17 00:00:00 2001 From: Demizdor Date: Tue, 23 Apr 2019 20:48:00 +0300 Subject: Fix for DrawRectangleRounded --- src/shapes.c | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 56 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/shapes.c b/src/shapes.c index f407f0d2..ecef287c 100644 --- a/src/shapes.c +++ b/src/shapes.c @@ -758,7 +758,9 @@ void DrawRectangleRounded(Rectangle rec, float roundness, int segments, Color co #if defined(SUPPORT_QUADS_DRAW_MODE) if (rlCheckBufferLimit(16*segments/2 + 5*4)) rlglDraw(); - + + rlEnableTexture(GetShapesTexture().id); + rlBegin(RL_QUADS); // Draw all of the 4 corners: [1] Upper Left Corner, [3] Upper Right Corner, [5] Lower Right Corner, [7] Lower Left Corner for (int k = 0; k < 4; ++k) // Hope the compiler is smart enough to unroll this loop @@ -769,9 +771,13 @@ void DrawRectangleRounded(Rectangle rec, float roundness, int segments, Color co for (int i = 0; i < segments/2; i++) { rlColor4ub(color.r, color.g, color.b, color.a); + rlTexCoord2f(recTexShapes.x/texShapes.width, recTexShapes.y/texShapes.height); rlVertex2f(center.x, center.y); + rlTexCoord2f(recTexShapes.x/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); rlVertex2f(center.x + sinf(DEG2RAD*angle)*radius, center.y + cosf(DEG2RAD*angle)*radius); + rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength))*radius, center.y + cosf(DEG2RAD*(angle + stepLength))*radius); + rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, recTexShapes.y/texShapes.height); rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength*2))*radius, center.y + cosf(DEG2RAD*(angle + stepLength*2))*radius); angle += (stepLength*2); } @@ -779,49 +785,74 @@ void DrawRectangleRounded(Rectangle rec, float roundness, int segments, Color co if (segments%2) { rlColor4ub(color.r, color.g, color.b, color.a); + rlTexCoord2f(recTexShapes.x/texShapes.width, recTexShapes.y/texShapes.height); rlVertex2f(center.x, center.y); + rlTexCoord2f(recTexShapes.x/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); rlVertex2f(center.x + sinf(DEG2RAD*angle)*radius, center.y + cosf(DEG2RAD*angle)*radius); + rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength))*radius, center.y + cosf(DEG2RAD*(angle + stepLength))*radius); + rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, recTexShapes.y/texShapes.height); rlVertex2f(center.x, center.y); } } // [2] Upper Rectangle rlColor4ub(color.r, color.g, color.b, color.a); + rlTexCoord2f(recTexShapes.x/texShapes.width, recTexShapes.y/texShapes.height); rlVertex2f(point[0].x, point[0].y); + rlTexCoord2f(recTexShapes.x/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); rlVertex2f(point[8].x, point[8].y); + rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); rlVertex2f(point[9].x, point[9].y); + rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, recTexShapes.y/texShapes.height); rlVertex2f(point[1].x, point[1].y); // [4] Right Rectangle rlColor4ub(color.r, color.g, color.b, color.a); + rlTexCoord2f(recTexShapes.x/texShapes.width, recTexShapes.y/texShapes.height); rlVertex2f(point[2].x, point[2].y); + rlTexCoord2f(recTexShapes.x/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); rlVertex2f(point[9].x, point[9].y); + rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); rlVertex2f(point[10].x, point[10].y); + rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, recTexShapes.y/texShapes.height); rlVertex2f(point[3].x, point[3].y); // [6] Bottom Rectangle rlColor4ub(color.r, color.g, color.b, color.a); + rlTexCoord2f(recTexShapes.x/texShapes.width, recTexShapes.y/texShapes.height); rlVertex2f(point[11].x, point[11].y); + rlTexCoord2f(recTexShapes.x/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); rlVertex2f(point[5].x, point[5].y); + rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); rlVertex2f(point[4].x, point[4].y); + rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, recTexShapes.y/texShapes.height); rlVertex2f(point[10].x, point[10].y); // [8] Left Rectangle rlColor4ub(color.r, color.g, color.b, color.a); + rlTexCoord2f(recTexShapes.x/texShapes.width, recTexShapes.y/texShapes.height); rlVertex2f(point[7].x, point[7].y); + rlTexCoord2f(recTexShapes.x/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); rlVertex2f(point[6].x, point[6].y); + rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); rlVertex2f(point[11].x, point[11].y); + rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, recTexShapes.y/texShapes.height); rlVertex2f(point[8].x, point[8].y); // [9] Middle Rectangle rlColor4ub(color.r, color.g, color.b, color.a); + rlTexCoord2f(recTexShapes.x/texShapes.width, recTexShapes.y/texShapes.height); rlVertex2f(point[8].x, point[8].y); + rlTexCoord2f(recTexShapes.x/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); rlVertex2f(point[11].x, point[11].y); + rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); rlVertex2f(point[10].x, point[10].y); + rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, recTexShapes.y/texShapes.height); rlVertex2f(point[9].x, point[9].y); rlEnd(); + rlDisableTexture(); #else if (rlCheckBufferLimit(12*segments + 5*6)) rlglDraw(); // 4 corners with 3 vertices per segment + 5 rectangles with 6 vertices each @@ -960,7 +991,9 @@ void DrawRectangleRoundedLines(Rectangle rec, float roundness, int segments, int { #if defined(SUPPORT_QUADS_DRAW_MODE) if (rlCheckBufferLimit(4*4*segments + 4*4)) rlglDraw(); // 4 corners with 4 vertices for each segment + 4 rectangles with 4 vertices each - + + rlEnableTexture(GetShapesTexture().id); + rlBegin(RL_QUADS); // Draw all of the 4 corners first: Upper Left Corner, Upper Right Corner, Lower Right Corner, Lower Left Corner for (int k = 0; k < 4; ++k) // Hope the compiler is smart enough to unroll this loop @@ -970,9 +1003,13 @@ void DrawRectangleRoundedLines(Rectangle rec, float roundness, int segments, int for (int i = 0; i < segments; i++) { rlColor4ub(color.r, color.g, color.b, color.a); + rlTexCoord2f(recTexShapes.x/texShapes.width, recTexShapes.y/texShapes.height); rlVertex2f(center.x + sinf(DEG2RAD*angle)*innerRadius, center.y + cosf(DEG2RAD*angle)*innerRadius); + rlTexCoord2f(recTexShapes.x/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); rlVertex2f(center.x + sinf(DEG2RAD*angle)*outerRadius, center.y + cosf(DEG2RAD*angle)*outerRadius); + rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength))*outerRadius, center.y + cosf(DEG2RAD*(angle + stepLength))*outerRadius); + rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, recTexShapes.y/texShapes.height); rlVertex2f(center.x + sinf(DEG2RAD*(angle + stepLength))*innerRadius, center.y + cosf(DEG2RAD*(angle + stepLength))*innerRadius); angle += stepLength; @@ -981,33 +1018,50 @@ void DrawRectangleRoundedLines(Rectangle rec, float roundness, int segments, int // Upper rectangle rlColor4ub(color.r, color.g, color.b, color.a); + rlTexCoord2f(recTexShapes.x/texShapes.width, recTexShapes.y/texShapes.height); rlVertex2f(point[0].x, point[0].y); + rlTexCoord2f(recTexShapes.x/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); rlVertex2f(point[8].x, point[8].y); + rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); rlVertex2f(point[9].x, point[9].y); + rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, recTexShapes.y/texShapes.height); rlVertex2f(point[1].x, point[1].y); // Right rectangle rlColor4ub(color.r, color.g, color.b, color.a); + rlTexCoord2f(recTexShapes.x/texShapes.width, recTexShapes.y/texShapes.height); rlVertex2f(point[2].x, point[2].y); + rlTexCoord2f(recTexShapes.x/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); rlVertex2f(point[10].x, point[10].y); + rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); rlVertex2f(point[11].x, point[11].y); + rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, recTexShapes.y/texShapes.height); rlVertex2f(point[3].x, point[3].y); // Lower rectangle rlColor4ub(color.r, color.g, color.b, color.a); + rlTexCoord2f(recTexShapes.x/texShapes.width, recTexShapes.y/texShapes.height); rlVertex2f(point[13].x, point[13].y); + rlTexCoord2f(recTexShapes.x/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); rlVertex2f(point[5].x, point[5].y); + rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); rlVertex2f(point[4].x, point[4].y); + rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, recTexShapes.y/texShapes.height); rlVertex2f(point[12].x, point[12].y); // Left rectangle rlColor4ub(color.r, color.g, color.b, color.a); + rlTexCoord2f(recTexShapes.x/texShapes.width, recTexShapes.y/texShapes.height); rlVertex2f(point[15].x, point[15].y); + rlTexCoord2f(recTexShapes.x/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); rlVertex2f(point[7].x, point[7].y); + rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); rlVertex2f(point[6].x, point[6].y); + rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, recTexShapes.y/texShapes.height); rlVertex2f(point[14].x, point[14].y); rlEnd(); + rlDisableTexture(); #else if (rlCheckBufferLimit(4*6*segments + 4*6)) rlglDraw(); // 4 corners with 6(2*3) vertices for each segment + 4 rectangles with 6 vertices each -- cgit v1.2.3 From cc1dd6b410ca8c6ba2b9dd1a923c7740034cd1d9 Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 23 Apr 2019 23:27:08 +0200 Subject: Review camera module This module still requires further work but 3rd person camera is less broken now... --- src/camera.h | 129 +++++++++++++++++++++++++++-------------------------------- 1 file changed, 60 insertions(+), 69 deletions(-) (limited to 'src') diff --git a/src/camera.h b/src/camera.h index 2ed35f3b..e103b293 100644 --- a/src/camera.h +++ b/src/camera.h @@ -16,13 +16,13 @@ * functions must be redefined to manage inputs accordingly. * * CONTRIBUTORS: -* Marc Palau: Initial implementation (2014) * Ramon Santamaria: Supervision, review, update and maintenance +* Marc Palau: Initial implementation (2014) * * * LICENSE: zlib/libpng * -* Copyright (c) 2015-2017 Ramon Santamaria (@raysan5) +* Copyright (c) 2015-2019 Ramon Santamaria (@raysan5) * * 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. @@ -54,15 +54,6 @@ // NOTE: Below types are required for CAMERA_STANDALONE usage //---------------------------------------------------------------------------------- #if defined(CAMERA_STANDALONE) - // Camera modes - typedef enum { - CAMERA_CUSTOM = 0, - CAMERA_FREE, - CAMERA_ORBITAL, - CAMERA_FIRST_PERSON, - CAMERA_THIRD_PERSON - } CameraMode; - // Vector2 type typedef struct Vector2 { float x; @@ -77,12 +68,30 @@ } Vector3; // Camera type, defines a camera position/orientation in 3d space - typedef struct Camera { - Vector3 position; - Vector3 target; - Vector3 up; - float fovy; - } Camera; + typedef struct Camera3D { + Vector3 position; // Camera position + Vector3 target; // Camera target it looks-at + Vector3 up; // Camera up vector (rotation over its axis) + float fovy; // Camera field-of-view apperture in Y (degrees) in perspective, used as near plane width in orthographic + int type; // Camera type, defines projection type: CAMERA_PERSPECTIVE or CAMERA_ORTHOGRAPHIC + } Camera3D; + + typedef Camera3D Camera; // Camera type fallback, defaults to Camera3D + + // Camera system modes + typedef enum { + CAMERA_CUSTOM = 0, + CAMERA_FREE, + CAMERA_ORBITAL, + CAMERA_FIRST_PERSON, + CAMERA_THIRD_PERSON + } CameraMode; + + // Camera projection modes + typedef enum { + CAMERA_PERSPECTIVE = 0, + CAMERA_ORTHOGRAPHIC + } CameraType; #endif #ifdef __cplusplus @@ -103,7 +112,7 @@ void UpdateCamera(Camera *camera); // Update camera pos void SetCameraPanControl(int panKey); // Set camera pan key to combine with mouse movement (free camera) void SetCameraAltControl(int altKey); // Set camera alt key to combine with mouse movement (free camera) -void SetCameraSmoothZoomControl(int szKey); // Set camera smooth zoom key to combine with mouse (free camera) +void SetCameraSmoothZoomControl(int szoomKey); // Set camera smooth zoom key to combine with mouse (free camera) void SetCameraMoveControls(int frontKey, int backKey, int rightKey, int leftKey, int upKey, int downKey); // Set camera move controls (1st person and 3rd person cameras) @@ -124,16 +133,14 @@ void SetCameraMoveControls(int frontKey, int backKey, #if defined(CAMERA_IMPLEMENTATION) -#include // Required for: sqrt(), sin(), cos() +#include // Required for: sqrt(), sinf(), cosf() #ifndef PI #define PI 3.14159265358979323846 #endif - #ifndef DEG2RAD #define DEG2RAD (PI/180.0f) #endif - #ifndef RAD2DEG #define RAD2DEG (180.0f/PI) #endif @@ -193,8 +200,8 @@ typedef enum { //---------------------------------------------------------------------------------- // Global Variables Definition //---------------------------------------------------------------------------------- -static Vector2 cameraAngle = { 0.0f, 0.0f }; // TODO: Remove! Compute it in UpdateCamera() -static float cameraTargetDistance = 0.0f; // TODO: Remove! Compute it in UpdateCamera() +static Vector2 cameraAngle = { 0.0f, 0.0f }; // Camera angle in plane XZ +static float cameraTargetDistance = 0.0f; // Camera distance from position to target static float playerEyesPosition = 1.85f; // Default player eyes position from ground (in meters) static int cameraMoveControl[6] = { 'W', 'S', 'D', 'A', 'E', 'Q' }; @@ -227,9 +234,6 @@ static Vector2 GetMousePosition() { return (Vector2){ 0.0f, 0.0f }; } // Select camera mode (multiple camera modes available) void SetCameraMode(Camera camera, int mode) { - // TODO: cameraTargetDistance and cameraAngle should be - // calculated using camera parameters on UpdateCamera() - Vector3 v1 = camera.position; Vector3 v2 = camera.target; @@ -254,9 +258,8 @@ void SetCameraMode(Camera camera, int mode) playerEyesPosition = camera.position.y; // Lock cursor for first person and third person cameras - if ((mode == CAMERA_FIRST_PERSON) || - (mode == CAMERA_THIRD_PERSON)) DisableCursor(); - else EnableCursor(); + if ((mode == CAMERA_FIRST_PERSON) || (mode == CAMERA_THIRD_PERSON)) DisableCursor(); + else EnableCursor(); cameraMode = mode; } @@ -385,6 +388,11 @@ void UpdateCamera(Camera *camera) camera->target.z += ((mousePositionDelta.x*CAMERA_FREE_MOUSE_SENSITIVITY)*sinf(cameraAngle.x) + (mousePositionDelta.y*CAMERA_FREE_MOUSE_SENSITIVITY)*cosf(cameraAngle.x)*sinf(cameraAngle.y))*(cameraTargetDistance/CAMERA_FREE_PANNING_DIVIDER); } } + + // Update camera position with changes + camera->position.x = sinf(cameraAngle.x)*cameraTargetDistance*cosf(cameraAngle.y) + camera->target.x; + camera->position.y = ((cameraAngle.y <= 0.0f)? 1 : -1)*sinf(cameraAngle.y)*cameraTargetDistance*sinf(cameraAngle.y) + camera->target.y; + camera->position.z = cosf(cameraAngle.x)*cameraTargetDistance*cosf(cameraAngle.y) + camera->target.z; } break; case CAMERA_ORBITAL: @@ -395,6 +403,11 @@ void UpdateCamera(Camera *camera) // Camera distance clamp if (cameraTargetDistance < CAMERA_THIRD_PERSON_DISTANCE_CLAMP) cameraTargetDistance = CAMERA_THIRD_PERSON_DISTANCE_CLAMP; + // Update camera position with changes + camera->position.x = sinf(cameraAngle.x)*cameraTargetDistance*cosf(cameraAngle.y) + camera->target.x; + camera->position.y = ((cameraAngle.y <= 0.0f)? 1 : -1)*sinf(cameraAngle.y)*cameraTargetDistance*sinf(cameraAngle.y) + camera->target.y; + camera->position.z = cosf(cameraAngle.x)*cameraTargetDistance*cosf(cameraAngle.y) + camera->target.z; + } break; case CAMERA_FIRST_PERSON: case CAMERA_THIRD_PERSON: @@ -421,34 +434,17 @@ void UpdateCamera(Camera *camera) cameraAngle.x += (mousePositionDelta.x*-CAMERA_MOUSE_MOVE_SENSITIVITY); cameraAngle.y += (mousePositionDelta.y*-CAMERA_MOUSE_MOVE_SENSITIVITY); - if (cameraMode == CAMERA_THIRD_PERSON) - { - // Angle clamp - if (cameraAngle.y > CAMERA_THIRD_PERSON_MIN_CLAMP*DEG2RAD) cameraAngle.y = CAMERA_THIRD_PERSON_MIN_CLAMP*DEG2RAD; - else if (cameraAngle.y < CAMERA_THIRD_PERSON_MAX_CLAMP*DEG2RAD) cameraAngle.y = CAMERA_THIRD_PERSON_MAX_CLAMP*DEG2RAD; - - // Camera zoom - cameraTargetDistance -= (mouseWheelMove*CAMERA_MOUSE_SCROLL_SENSITIVITY); - - // Camera distance clamp - if (cameraTargetDistance < CAMERA_THIRD_PERSON_DISTANCE_CLAMP) cameraTargetDistance = CAMERA_THIRD_PERSON_DISTANCE_CLAMP; - - // Camera is always looking at player - camera->target.x = camera->position.x + CAMERA_THIRD_PERSON_OFFSET.x*cosf(cameraAngle.x) + CAMERA_THIRD_PERSON_OFFSET.z*sinf(cameraAngle.x); - camera->target.y = camera->position.y + CAMERA_THIRD_PERSON_OFFSET.y; - camera->target.z = camera->position.z + CAMERA_THIRD_PERSON_OFFSET.z*sinf(cameraAngle.x) - CAMERA_THIRD_PERSON_OFFSET.x*sinf(cameraAngle.x); - } - else // CAMERA_FIRST_PERSON + // Angle clamp + if (cameraAngle.y > CAMERA_FIRST_PERSON_MIN_CLAMP*DEG2RAD) cameraAngle.y = CAMERA_FIRST_PERSON_MIN_CLAMP*DEG2RAD; + else if (cameraAngle.y < CAMERA_FIRST_PERSON_MAX_CLAMP*DEG2RAD) cameraAngle.y = CAMERA_FIRST_PERSON_MAX_CLAMP*DEG2RAD; + + // Camera is always looking at player + camera->target.x = camera->position.x - sinf(cameraAngle.x)*CAMERA_FIRST_PERSON_FOCUS_DISTANCE; + camera->target.y = camera->position.y + sinf(cameraAngle.y)*CAMERA_FIRST_PERSON_FOCUS_DISTANCE; + camera->target.z = camera->position.z - cosf(cameraAngle.x)*CAMERA_FIRST_PERSON_FOCUS_DISTANCE; + + if (cameraMode == CAMERA_FIRST_PERSON) { - // Angle clamp - if (cameraAngle.y > CAMERA_FIRST_PERSON_MIN_CLAMP*DEG2RAD) cameraAngle.y = CAMERA_FIRST_PERSON_MIN_CLAMP*DEG2RAD; - else if (cameraAngle.y < CAMERA_FIRST_PERSON_MAX_CLAMP*DEG2RAD) cameraAngle.y = CAMERA_FIRST_PERSON_MAX_CLAMP*DEG2RAD; - - // Camera is always looking at player - camera->target.x = camera->position.x - sinf(cameraAngle.x)*CAMERA_FIRST_PERSON_FOCUS_DISTANCE; - camera->target.y = camera->position.y + sinf(cameraAngle.y)*CAMERA_FIRST_PERSON_FOCUS_DISTANCE; - camera->target.z = camera->position.z - cosf(cameraAngle.x)*CAMERA_FIRST_PERSON_FOCUS_DISTANCE; - if (isMoving) swingCounter++; // Camera position update @@ -458,21 +454,16 @@ void UpdateCamera(Camera *camera) camera->up.x = sinf(swingCounter/(CAMERA_FIRST_PERSON_STEP_TRIGONOMETRIC_DIVIDER*2))/CAMERA_FIRST_PERSON_WAVING_DIVIDER; camera->up.z = -sinf(swingCounter/(CAMERA_FIRST_PERSON_STEP_TRIGONOMETRIC_DIVIDER*2))/CAMERA_FIRST_PERSON_WAVING_DIVIDER; } + else if (cameraMode == CAMERA_THIRD_PERSON) + { + // Camera zoom + cameraTargetDistance -= (mouseWheelMove*CAMERA_MOUSE_SCROLL_SENSITIVITY); + if (cameraTargetDistance < CAMERA_THIRD_PERSON_DISTANCE_CLAMP) cameraTargetDistance = CAMERA_THIRD_PERSON_DISTANCE_CLAMP; + } + } break; default: break; } - - // Update camera position with changes - if ((cameraMode == CAMERA_FREE) || - (cameraMode == CAMERA_ORBITAL) || - (cameraMode == CAMERA_THIRD_PERSON)) - { - // TODO: It seems camera->position is not correctly updated or some rounding issue makes the camera move straight to camera->target... - camera->position.x = sinf(cameraAngle.x)*cameraTargetDistance*cosf(cameraAngle.y) + camera->target.x; - if (cameraAngle.y <= 0.0f) camera->position.y = sinf(cameraAngle.y)*cameraTargetDistance*sinf(cameraAngle.y) + camera->target.y; - else camera->position.y = -sinf(cameraAngle.y)*cameraTargetDistance*sinf(cameraAngle.y) + camera->target.y; - camera->position.z = cosf(cameraAngle.x)*cameraTargetDistance*cosf(cameraAngle.y) + camera->target.z; - } } // Set camera pan key to combine with mouse movement (free camera) @@ -482,7 +473,7 @@ void SetCameraPanControl(int panKey) { cameraPanControlKey = panKey; } void SetCameraAltControl(int altKey) { cameraAltControlKey = altKey; } // Set camera smooth zoom key to combine with mouse (free camera) -void SetCameraSmoothZoomControl(int szKey) { cameraSmoothZoomControlKey = szKey; } +void SetCameraSmoothZoomControl(int szoomKey) { cameraSmoothZoomControlKey = szoomKey; } // Set camera move controls (1st person and 3rd person cameras) void SetCameraMoveControls(int frontKey, int backKey, int rightKey, int leftKey, int upKey, int downKey) -- cgit v1.2.3 From 86f9ea6e7a0962f3a1a066ed2e7cf0acd2f7df98 Mon Sep 17 00:00:00 2001 From: Demizdor Date: Wed, 24 Apr 2019 22:08:57 +0300 Subject: Fixed selection in DrawTextRecEx() --- src/text.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/text.c b/src/text.c index 22bd7659..15b8d555 100644 --- a/src/text.c +++ b/src/text.c @@ -900,7 +900,7 @@ void DrawTextRecEx(Font font, const char *text, Rectangle rec, float fontSize, f int startLine = -1; // Index where to begin drawing (where a line begins) int endLine = -1; // Index where to stop drawing (where a line ends) - for (int i = 0; i < length; i++) + for (int i = 0, k = 0; i < length; i++, k++) { int glyphWidth = 0; int next = 1; @@ -979,7 +979,7 @@ void DrawTextRecEx(Font font, const char *text, Rectangle rec, float fontSize, f //draw selected bool isGlyphSelected = false; - if ((selectStart >= 0) && (i >= selectStart) && (i < (selectStart + selectLength))) + if ((selectStart >= 0) && (k >= selectStart) && (k < (selectStart + selectLength))) { Rectangle strec = {rec.x + textOffsetX-1, rec.y + textOffsetY, glyphWidth, (font.baseSize + font.baseSize/4)*scaleFactor }; DrawRectangleRec(strec, selectBack); -- cgit v1.2.3 From 04ed4dd40cd287435a466b73ec52a73f1321bce1 Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 25 Apr 2019 11:02:13 +0200 Subject: Renamed internal variable Probably required for HiDPI support --- src/core.c | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) (limited to 'src') diff --git a/src/core.c b/src/core.c index 5ec3b76a..4069f782 100644 --- a/src/core.c +++ b/src/core.c @@ -284,7 +284,7 @@ static int currentWidth, currentHeight; // Current render width and heig static int renderOffsetX = 0; // Offset X from render area (must be divided by 2) static int renderOffsetY = 0; // Offset Y from render area (must be divided by 2) static bool fullscreen = false; // Fullscreen mode (useful only for PLATFORM_DESKTOP) -static Matrix downscaleView; // Matrix to downscale view (in case screen size bigger than display size) +static Matrix screenScaling; // Matrix to scale screen #if defined(PLATFORM_RPI) static EGL_DISPMANX_WINDOW_T nativeWindow; // Native window (graphic device) @@ -1086,7 +1086,7 @@ void BeginDrawing(void) previousTime = currentTime; rlLoadIdentity(); // Reset current matrix (MODELVIEW) - rlMultMatrixf(MatrixToFloat(downscaleView)); // If downscale required, apply it here + rlMultMatrixf(MatrixToFloat(screenScaling)); // If downscale required, apply it here //rlTranslatef(0.375, 0.375, 0); // HACK to have 2D pixel-perfect drawing on OpenGL 1.1 // NOTE: Not required with OpenGL 3.3+ @@ -2307,8 +2307,8 @@ static bool InitGraphicsDevice(int width, int height) // NOTE: Framebuffer (render area - renderWidth, renderHeight) could include black bars... // ...in top-down or left-right to match display aspect ratio (no weird scalings) - // Downscale matrix is required in case desired screen area is bigger than display area - downscaleView = MatrixIdentity(); + // Screen scaling matrix is required in case desired screen area is different than display area + screenScaling = MatrixIdentity(); #if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB) glfwSetErrorCallback(ErrorCallback); @@ -2438,7 +2438,7 @@ static bool InitGraphicsDevice(int width, int height) // At this point we need to manage render size vs screen size // NOTE: This function uses and modifies global module variables: - // screenWidth/screenHeight - renderWidth/renderHeight - downscaleView + // screenWidth/screenHeight - renderWidth/renderHeight - screenScaling SetupFramebuffer(displayWidth, displayHeight); window = glfwCreateWindow(displayWidth, displayHeight, windowTitle, glfwGetPrimaryMonitor(), NULL); @@ -2779,7 +2779,7 @@ static bool InitGraphicsDevice(int width, int height) eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &displayFormat); // At this point we need to manage render size vs screen size - // NOTE: This function use and modify global module variables: screenWidth/screenHeight and renderWidth/renderHeight and downscaleView + // NOTE: This function use and modify global module variables: screenWidth/screenHeight and renderWidth/renderHeight and screenScaling SetupFramebuffer(displayWidth, displayHeight); ANativeWindow_setBuffersGeometry(androidApp->window, renderWidth, renderHeight, displayFormat); @@ -2792,7 +2792,7 @@ static bool InitGraphicsDevice(int width, int height) graphics_get_display_size(0, &displayWidth, &displayHeight); // At this point we need to manage render size vs screen size - // NOTE: This function use and modify global module variables: screenWidth/screenHeight and renderWidth/renderHeight and downscaleView + // NOTE: This function use and modify global module variables: screenWidth/screenHeight and renderWidth/renderHeight and screenScaling SetupFramebuffer(displayWidth, displayHeight); dstRect.x = 0; @@ -2921,10 +2921,9 @@ static void SetupFramebuffer(int width, int height) renderOffsetY = 0; } - // NOTE: downscale matrix required! + // Screen scaling required float scaleRatio = (float)renderWidth/(float)screenWidth; - - downscaleView = MatrixScale(scaleRatio, scaleRatio, scaleRatio); + screenScaling = MatrixScale(scaleRatio, scaleRatio, scaleRatio); // NOTE: We render to full display resolution! // We just need to calculate above parameters for downscale matrix and offsets -- cgit v1.2.3 From c76863b289fdd7d41bd074c11e9660851818caad Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 25 Apr 2019 11:39:45 +0200 Subject: Working on HiDPI support -WIP- Trying to define a global transformation matrix to scale all content for HiDPI. --- src/core.c | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/core.c b/src/core.c index 4069f782..8034b029 100644 --- a/src/core.c +++ b/src/core.c @@ -284,7 +284,7 @@ static int currentWidth, currentHeight; // Current render width and heig static int renderOffsetX = 0; // Offset X from render area (must be divided by 2) static int renderOffsetY = 0; // Offset Y from render area (must be divided by 2) static bool fullscreen = false; // Fullscreen mode (useful only for PLATFORM_DESKTOP) -static Matrix screenScaling; // Matrix to scale screen +static Matrix screenScaling; // Matrix to scale screen (framebuffer rendering) #if defined(PLATFORM_RPI) static EGL_DISPMANX_WINDOW_T nativeWindow; // Native window (graphic device) @@ -618,8 +618,6 @@ void InitWindow(int width, int height, const char *title) emscripten_set_touchend_callback("#canvas", NULL, 1, EmscriptenTouchCallback); emscripten_set_touchmove_callback("#canvas", NULL, 1, EmscriptenTouchCallback); emscripten_set_touchcancel_callback("#canvas", NULL, 1, EmscriptenTouchCallback); - //emscripten_set_touchstart_callback(0, NULL, 1, Emscripten_HandleTouch); - //emscripten_set_touchend_callback("#canvas", data, 0, Emscripten_HandleTouch); // Support gamepad events (not provided by GLFW3 on emscripten) emscripten_set_gamepadconnected_callback(NULL, 1, EmscriptenGamepadCallback); @@ -2357,8 +2355,8 @@ static bool InitGraphicsDevice(int width, int height) //glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API); // OpenGL API to use. Alternative: GLFW_OPENGL_ES_API //glfwWindowHint(GLFW_AUX_BUFFERS, 0); // Number of auxiliar buffers #if defined(PLATFORM_DESKTOP) - // TODO: If using external GLFW, it requires latest GLFW 3.3 for this functionality - //glfwWindowHint(GLFW_SCALE_TO_MONITOR, GLFW_TRUE); // Scale content area based on the monitor content scale where window is placed on + // NOTE: If using external GLFW, it requires latest GLFW 3.3 for this functionality + glfwWindowHint(GLFW_SCALE_TO_MONITOR, GLFW_TRUE); // Scale content area based on the monitor content scale where window is placed on #endif // Check some Window creation flags @@ -2462,6 +2460,12 @@ static bool InitGraphicsDevice(int width, int height) if (windowPosY < 0) windowPosY = 0; glfwSetWindowPos(window, windowPosX, windowPosY); + + // Get window HiDPI scaling factor + float scaleRatio = 0.0f; + glfwGetWindowContentScale(window, &scaleRatio, NULL); + scaleRatio = roundf(scaleRatio); + screenScaling = MatrixScale(scaleRatio, scaleRatio, scaleRatio); #endif renderWidth = screenWidth; renderHeight = screenHeight; @@ -2878,14 +2882,14 @@ static bool InitGraphicsDevice(int width, int height) // Set viewport parameters static void SetupViewport(void) { -#if defined(__APPLE__) +#if defined(PLATFORM_DESKTOP) // Get framebuffer size of current window // NOTE: Required to handle HighDPI display correctly on OSX because framebuffer // is automatically reasized to adapt to new DPI. // When OS does that, it can be detected using GLFW3 callback: glfwSetFramebufferSizeCallback() int fbWidth, fbHeight; glfwGetFramebufferSize(window, &fbWidth, &fbHeight); - rlViewport(renderOffsetX/2, renderOffsetY/2, fbWidth - renderOffsetX, fbHeight - renderOffsetY); + rlViewport(renderOffsetX/2, renderOffsetY/2, fbWidth - renderOffsetX, fbHeight - renderOffsetY); #else // Initialize screen viewport (area of the screen that you will actually draw to) // NOTE: Viewport must be recalculated if screen is resized -- cgit v1.2.3 From f37e55a77bd6177dbaea4d7f484961c09104e104 Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 25 Apr 2019 13:45:37 +0200 Subject: Reverted HiDPI changes, they break 2D mode on HiDPI :( --- src/core.c | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/core.c b/src/core.c index 8034b029..0d17fdad 100644 --- a/src/core.c +++ b/src/core.c @@ -1084,7 +1084,7 @@ void BeginDrawing(void) previousTime = currentTime; rlLoadIdentity(); // Reset current matrix (MODELVIEW) - rlMultMatrixf(MatrixToFloat(screenScaling)); // If downscale required, apply it here + rlMultMatrixf(MatrixToFloat(screenScaling)); // Apply screen scaling //rlTranslatef(0.375, 0.375, 0); // HACK to have 2D pixel-perfect drawing on OpenGL 1.1 // NOTE: Not required with OpenGL 3.3+ @@ -2465,7 +2465,7 @@ static bool InitGraphicsDevice(int width, int height) float scaleRatio = 0.0f; glfwGetWindowContentScale(window, &scaleRatio, NULL); scaleRatio = roundf(scaleRatio); - screenScaling = MatrixScale(scaleRatio, scaleRatio, scaleRatio); + //screenScaling = MatrixScale(scaleRatio, scaleRatio, scaleRatio); #endif renderWidth = screenWidth; renderHeight = screenHeight; @@ -2882,10 +2882,9 @@ static bool InitGraphicsDevice(int width, int height) // Set viewport parameters static void SetupViewport(void) { -#if defined(PLATFORM_DESKTOP) +#if defined(__APPLE__) // Get framebuffer size of current window - // NOTE: Required to handle HighDPI display correctly on OSX because framebuffer - // is automatically reasized to adapt to new DPI. + // NOTE: Required to handle HighDPI display correctly on OSX because framebuffer is automatically reasized to adapt to new DPI. // When OS does that, it can be detected using GLFW3 callback: glfwSetFramebufferSizeCallback() int fbWidth, fbHeight; glfwGetFramebufferSize(window, &fbWidth, &fbHeight); -- cgit v1.2.3 From 2de1f318212dbceb71db6be053be995208748f2a Mon Sep 17 00:00:00 2001 From: Reece Mackie <20544390+Rover656@users.noreply.github.com> Date: Sat, 27 Apr 2019 19:33:51 +0100 Subject: UWP Support Overhaul (#819) * Working build * Fix build again, stop deleting files * Hotfix crash, needs investigating * Remove VS2015.UWP, I cannot update the project * Lots of UWP work, added keyboard and mouse press support. Still need to finish scroll wheel, mouse position and cursor hiding, plus other stuff that I haven't seen yet. * Implemented a ton more things, added BaseApp.h to provide common code to UWP apps. * Remove constant window dimensions * Enable and Disable cursor support. * Actually use mouse delta * Gamepad Support * Cleaning and small tweaks * Restore original example. * Update comment * Use 'Messages' to handle the cursor functions so code is more portable. * Comment * Comment unused message fields and use vector for mouse pos instead. * Move messages to utils.h and use messages for everything. No more plat-specific code in raylib.h * Working build * Fix build again, stop deleting files * Hotfix crash, needs investigating * Remove VS2015.UWP, I cannot update the project * Lots of UWP work, added keyboard and mouse press support. Still need to finish scroll wheel, mouse position and cursor hiding, plus other stuff that I haven't seen yet. * Implemented a ton more things, added BaseApp.h to provide common code to UWP apps. * Remove constant window dimensions * Enable and Disable cursor support. * Actually use mouse delta * Gamepad Support * Cleaning and small tweaks * Restore original example. * Update comment * Use 'Messages' to handle the cursor functions so code is more portable. * Comment * Comment unused message fields and use vector for mouse pos instead. * Move messages to utils.h and use messages for everything. No more plat-specific code in raylib.h * Tested some desktop stuff and added projection matrix updates for window resizing. * Fixed big bad mouse bug * Fix alt buttons and add hack to combat flickery key presses (far from perfect) * Remove debug code * Final commit * Well, so I thought * Wow, i am bad * Remove packages folder * Remove useless include * Apply requested changes and fix linux build * Try to stop packages folder * Have we fixed the formatting properly? * Third time's the charm? * Where did this come from? * Re-fix * Autoformat is gonna kill * Fixed XBOX ONE Support * Fix tabs --- src/camera.h | 2 +- src/core.c | 260 ++++++++++++++++++++++++++++++++--- src/external/ANGLE/EGL/eglplatform.h | 5 + src/rlgl.h | 10 +- src/utils.c | 92 ++++++++++++- src/utils.h | 75 ++++++++++ 6 files changed, 419 insertions(+), 25 deletions(-) (limited to 'src') diff --git a/src/camera.h b/src/camera.h index e103b293..d80f8346 100644 --- a/src/camera.h +++ b/src/camera.h @@ -256,7 +256,7 @@ void SetCameraMode(Camera camera, int mode) //cameraAngle.y = -60.0f*DEG2RAD; // Camera angle in plane XY (0 aligned with X, move positive CW) playerEyesPosition = camera.position.y; - + // Lock cursor for first person and third person cameras if ((mode == CAMERA_FIRST_PERSON) || (mode == CAMERA_THIRD_PERSON)) DisableCursor(); else EnableCursor(); diff --git a/src/core.c b/src/core.c index 0d17fdad..db75979a 100644 --- a/src/core.c +++ b/src/core.c @@ -134,7 +134,7 @@ #include // Required for: tolower() [Used in IsFileExtension()] #include // Required for stat() [Used in GetLastWriteTime()] -#if defined(PLATFORM_DESKTOP) && defined(_WIN32) && (defined(_MSC_VER) || defined(__TINYC__)) +#if (defined(PLATFORM_DESKTOP) || defined(PLATFORM_UWP)) && defined(_WIN32) && (defined(_MSC_VER) || defined(__TINYC__)) #include "external/dirent.h" // Required for: DIR, opendir(), closedir() [Used in GetDirectoryFiles()] #else #include // Required for: DIR, opendir(), closedir() [Used in GetDirectoryFiles()] @@ -391,6 +391,7 @@ static int gamepadStream[MAX_GAMEPADS] = { -1 };// Gamepad device file descripto static pthread_t gamepadThreadId; // Gamepad reading thread id static char gamepadName[64]; // Gamepad name holder #endif + //----------------------------------------------------------------------------------- // Timming system variables @@ -401,6 +402,7 @@ static double updateTime = 0.0; // Time measure for frame update static double drawTime = 0.0; // Time measure for frame draw static double frameTime = 0.0; // Time measure for one frame static double targetTime = 0.0; // Desired time for one frame, if 0 not applied + //----------------------------------------------------------------------------------- // Config internal variables @@ -486,10 +488,6 @@ static void InitGamepad(void); // Init raw gamepad inpu static void *GamepadThread(void *arg); // Mouse reading thread #endif -#if defined(PLATFORM_UWP) -// TODO: Define functions required to manage inputs -#endif - #if defined(_WIN32) // NOTE: We include Sleep() function signature here to avoid windows.h inclusion void __stdcall Sleep(unsigned long msTimeout); // Required for Wait() @@ -810,6 +808,7 @@ void SetWindowIcon(Image image) // Set title for window (only PLATFORM_DESKTOP) void SetWindowTitle(const char *title) { + windowTitle = title; #if defined(PLATFORM_DESKTOP) glfwSetWindowTitle(window, title); #endif @@ -887,7 +886,7 @@ int GetScreenHeight(void) // Get native window handle void *GetWindowHandle(void) { -#if defined(_WIN32) +#if defined(PLATFORM_DESKTOP) && defined(_WIN32) // NOTE: Returned handle is: void *HWND (windows.h) return glfwGetWin32Window(window); #elif defined(__linux__) @@ -1026,6 +1025,11 @@ void ShowCursor(void) { #if defined(PLATFORM_DESKTOP) glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); +#endif +#if defined(PLATFORM_UWP) + UWPMessage* msg = CreateUWPMessage(); + msg->Type = ShowMouse; + SendMessageToUWP(msg); #endif cursorHidden = false; } @@ -1035,6 +1039,11 @@ void HideCursor(void) { #if defined(PLATFORM_DESKTOP) glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN); +#endif +#if defined(PLATFORM_UWP) + UWPMessage* msg = CreateUWPMessage(); + msg->Type = HideMouse; + SendMessageToUWP(msg); #endif cursorHidden = true; } @@ -1053,6 +1062,11 @@ void EnableCursor(void) #endif #if defined(PLATFORM_WEB) toggleCursorLock = true; +#endif +#if defined(PLATFORM_UWP) + UWPMessage* msg = CreateUWPMessage(); + msg->Type = LockMouse; + SendMessageToUWP(msg); #endif cursorHidden = false; } @@ -1065,6 +1079,11 @@ void DisableCursor(void) #endif #if defined(PLATFORM_WEB) toggleCursorLock = true; +#endif +#if defined(PLATFORM_UWP) + UWPMessage* msg = CreateUWPMessage(); + msg->Type = UnlockMouse; + SendMessageToUWP(msg); #endif cursorHidden = true; } @@ -1145,6 +1164,8 @@ void EndDrawing(void) frameTime += extraTime; } + + return; } // Initialize 2D mode with custom camera (2D) @@ -1421,6 +1442,11 @@ double GetTime(void) return (double)(time - baseTime)*1e-9; // Elapsed time since InitTimer() #endif + +#if defined(PLATFORM_UWP) + //Updated through messages + return currentTime; +#endif } // Returns hexadecimal value for a Color @@ -2209,6 +2235,13 @@ void SetMousePosition(int x, int y) // NOTE: emscripten not implemented glfwSetCursorPos(window, mousePosition.x, mousePosition.y); #endif +#if defined(PLATFORM_UWP) + UWPMessage* msg = CreateUWPMessage(); + msg->Type = SetMouseLocation; + msg->Vector0.x = mousePosition.x; + msg->Vector0.y = mousePosition.y; + SendMessageToUWP(msg); +#endif } // Set mouse offset @@ -2736,6 +2769,8 @@ static bool InitGraphicsDevice(int width, int height) eglQuerySurface(display, surface, EGL_WIDTH, &screenWidth); eglQuerySurface(display, surface, EGL_HEIGHT, &screenHeight); + //SetupFramebuffer(displayWidth, displayHeight); //Borked + #else // PLATFORM_ANDROID, PLATFORM_RPI EGLint numConfigs; @@ -2906,8 +2941,8 @@ static void SetupFramebuffer(int width, int height) TraceLog(LOG_WARNING, "DOWNSCALING: Required screen size (%ix%i) is bigger than display size (%ix%i)", screenWidth, screenHeight, displayWidth, displayHeight); // Downscaling to fit display with border-bars - float widthRatio = (float)displayWidth/(float)screenWidth; - float heightRatio = (float)displayHeight/(float)screenHeight; + float widthRatio = (float)displayWidth / (float)screenWidth; + float heightRatio = (float)displayHeight / (float)screenHeight; if (widthRatio <= heightRatio) { @@ -2925,7 +2960,7 @@ static void SetupFramebuffer(int width, int height) } // Screen scaling required - float scaleRatio = (float)renderWidth/(float)screenWidth; + float scaleRatio = (float)renderWidth / (float)screenWidth; screenScaling = MatrixScale(scaleRatio, scaleRatio, scaleRatio); // NOTE: We render to full display resolution! @@ -2941,13 +2976,13 @@ static void SetupFramebuffer(int width, int height) TraceLog(LOG_INFO, "UPSCALING: Required screen size: %i x %i -> Display size: %i x %i", screenWidth, screenHeight, displayWidth, displayHeight); // Upscaling to fit display with border-bars - float displayRatio = (float)displayWidth/(float)displayHeight; - float screenRatio = (float)screenWidth/(float)screenHeight; + float displayRatio = (float)displayWidth / (float)displayHeight; + float screenRatio = (float)screenWidth / (float)screenHeight; if (displayRatio <= screenRatio) { renderWidth = screenWidth; - renderHeight = (int)round((float)screenWidth/displayRatio); + renderHeight = (int)round((float)screenWidth / displayRatio); renderOffsetX = 0; renderOffsetY = (renderHeight - screenHeight); } @@ -2996,7 +3031,7 @@ static void InitTimer(void) // http://stackoverflow.com/questions/43057578/c-programming-win32-games-sleep-taking-longer-than-expected static void Wait(float ms) { -#if defined(SUPPORT_BUSY_WAIT_LOOP) +#if defined(SUPPORT_BUSY_WAIT_LOOP) && !defined(PLATFORM_UWP) double prevTime = GetTime(); double nextTime = 0.0; @@ -3029,7 +3064,7 @@ static bool GetKeyStatus(int key) // NOTE: Android supports up to 260 keys if (key < 0 || key > 260) return false; else return currentKeyState[key]; -#elif defined(PLATFORM_RPI) +#elif defined(PLATFORM_RPI) || defined(PLATFORM_UWP) // NOTE: Keys states are filled in PollInputEvents() if (key < 0 || key > 511) return false; else return currentKeyState[key]; @@ -3044,7 +3079,7 @@ static bool GetMouseButtonStatus(int button) #elif defined(PLATFORM_ANDROID) // TODO: Check for virtual mouse? return false; -#elif defined(PLATFORM_RPI) +#elif defined(PLATFORM_RPI) || defined(PLATFORM_UWP) // NOTE: Mouse buttons states are filled in PollInputEvents() return currentMouseState[button]; #endif @@ -3090,6 +3125,197 @@ static void PollInputEvents(void) } #endif +#if defined(PLATFORM_UWP) + + // Register previous keys states + for (int i = 0; i < 512; i++) previousKeyState[i] = currentKeyState[i]; + + for (int i = 0; i < MAX_GAMEPADS; i++) + { + if (gamepadReady[i]) + { + for (int k = 0; k < MAX_GAMEPAD_BUTTONS; k++) previousGamepadState[i][k] = currentGamepadState[i][k]; + } + } + + // Register previous mouse states + previousMouseWheelY = currentMouseWheelY; + currentMouseWheelY = 0; + for (int i = 0; i < 3; i++) + { + previousMouseState[i] = currentMouseState[i]; + + } + + // Loop over pending messages + while (HasMessageFromUWP()) + { + UWPMessage* msg = GetMessageFromUWP(); + + switch (msg->Type) + { + case RegisterKey: + { + //Convert from virtualKey + int actualKey = -1; + + switch (msg->Int0) + { + case 0x08: actualKey = KEY_BACKSPACE; break; + case 0x20: actualKey = KEY_SPACE; break; + case 0x1B: actualKey = KEY_ESCAPE; break; + case 0x0D: actualKey = KEY_ENTER; break; + case 0x2E: actualKey = KEY_DELETE; break; + case 0x27: actualKey = KEY_RIGHT; break; + case 0x25: actualKey = KEY_LEFT; break; + case 0x28: actualKey = KEY_DOWN; break; + case 0x26: actualKey = KEY_UP; break; + case 0x70: actualKey = KEY_F1; break; + case 0x71: actualKey = KEY_F2; break; + case 0x72: actualKey = KEY_F3; break; + case 0x73: actualKey = KEY_F4; break; + case 0x74: actualKey = KEY_F5; break; + case 0x75: actualKey = KEY_F6; break; + case 0x76: actualKey = KEY_F7; break; + case 0x77: actualKey = KEY_F8; break; + case 0x78: actualKey = KEY_F9; break; + case 0x79: actualKey = KEY_F10; break; + case 0x7A: actualKey = KEY_F11; break; + case 0x7B: actualKey = KEY_F12; break; + case 0xA0: actualKey = KEY_LEFT_SHIFT; break; + case 0xA2: actualKey = KEY_LEFT_CONTROL; break; + case 0xA4: actualKey = KEY_LEFT_ALT; break; + case 0xA1: actualKey = KEY_RIGHT_SHIFT; break; + case 0xA3: actualKey = KEY_RIGHT_CONTROL; break; + case 0xA5: actualKey = KEY_RIGHT_ALT; break; + case 0x30: actualKey = KEY_ZERO; break; + case 0x31: actualKey = KEY_ONE; break; + case 0x32: actualKey = KEY_TWO; break; + case 0x33: actualKey = KEY_THREE; break; + case 0x34: actualKey = KEY_FOUR; break; + case 0x35: actualKey = KEY_FIVE; break; + case 0x36: actualKey = KEY_SIX; break; + case 0x37: actualKey = KEY_SEVEN; break; + case 0x38: actualKey = KEY_EIGHT; break; + case 0x39: actualKey = KEY_NINE; break; + case 0x41: actualKey = KEY_A; break; + case 0x42: actualKey = KEY_B; break; + case 0x43: actualKey = KEY_C; break; + case 0x44: actualKey = KEY_D; break; + case 0x45: actualKey = KEY_E; break; + case 0x46: actualKey = KEY_F; break; + case 0x47: actualKey = KEY_G; break; + case 0x48: actualKey = KEY_H; break; + case 0x49: actualKey = KEY_I; break; + case 0x4A: actualKey = KEY_J; break; + case 0x4B: actualKey = KEY_K; break; + case 0x4C: actualKey = KEY_L; break; + case 0x4D: actualKey = KEY_M; break; + case 0x4E: actualKey = KEY_N; break; + case 0x4F: actualKey = KEY_O; break; + case 0x50: actualKey = KEY_P; break; + case 0x51: actualKey = KEY_Q; break; + case 0x52: actualKey = KEY_R; break; + case 0x53: actualKey = KEY_S; break; + case 0x54: actualKey = KEY_T; break; + case 0x55: actualKey = KEY_U; break; + case 0x56: actualKey = KEY_V; break; + case 0x57: actualKey = KEY_W; break; + case 0x58: actualKey = KEY_X; break; + case 0x59: actualKey = KEY_Y; break; + case 0x5A: actualKey = KEY_Z; break; + } + + if (actualKey > -1) + currentKeyState[actualKey] = msg->Char0; + break; + } + + case RegisterClick: + { + currentMouseState[msg->Int0] = msg->Char0; + break; + } + + case ScrollWheelUpdate: + { + currentMouseWheelY += msg->Int0; + break; + } + + case UpdateMouseLocation: + { + mousePosition = msg->Vector0; + break; + } + + case MarkGamepadActive: + { + if (msg->Int0 < MAX_GAMEPADS) + gamepadReady[msg->Int0] = msg->Bool0; + break; + } + + case MarkGamepadButton: + { + if (msg->Int0 < MAX_GAMEPADS && msg->Int1 < MAX_GAMEPAD_BUTTONS) + currentGamepadState[msg->Int0][msg->Int1] = msg->Char0; + break; + } + + case MarkGamepadAxis: + { + if (msg->Int0 < MAX_GAMEPADS && msg->Int1 < MAX_GAMEPAD_AXIS) + gamepadAxisState[msg->Int0][msg->Int1] = msg->Float0; + break; + } + + case SetDisplayDims: + { + displayWidth = msg->Vector0.x; + displayHeight = msg->Vector0.y; + break; + } + + case HandleResize: + { + eglQuerySurface(display, surface, EGL_WIDTH, &screenWidth); + eglQuerySurface(display, surface, EGL_HEIGHT, &screenHeight); + + // If window is resized, viewport and projection matrix needs to be re-calculated + rlViewport(0, 0, screenWidth, screenHeight); // Set viewport width and height + rlMatrixMode(RL_PROJECTION); // Switch to PROJECTION matrix + rlLoadIdentity(); // Reset current matrix (PROJECTION) + rlOrtho(0, screenWidth, screenHeight, 0, 0.0f, 1.0f); // Orthographic projection mode with top-left corner at (0,0) + rlMatrixMode(RL_MODELVIEW); // Switch back to MODELVIEW matrix + rlLoadIdentity(); // Reset current matrix (MODELVIEW) + rlClearScreenBuffers(); // Clear screen buffers (color and depth) + + // Window size must be updated to be used on 3D mode to get new aspect ratio (BeginMode3D()) + // NOTE: Be careful! GLFW3 will choose the closest fullscreen resolution supported by current monitor, + // for example, if reescaling back to 800x450 (desired), it could set 720x480 (closest fullscreen supported) + currentWidth = screenWidth; + currentHeight = screenHeight; + + // NOTE: Postprocessing texture is not scaled to new size + + windowResized = true; + break; + } + + case SetGameTime: + { + currentTime = msg->Double0; + break; + } + + } + + DeleteUWPMessage(msg); //Delete, we are done + } + +#endif + #if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB) // Mouse input polling double mouseX; @@ -4577,7 +4803,7 @@ static void *GamepadThread(void *arg) // Plays raylib logo appearing animation static void LogoAnimation(void) { -#if !defined(PLATFORM_WEB) +#if !defined(PLATFORM_WEB) && !defined(PLATFORM_UWP) int logoPositionX = screenWidth/2 - 128; int logoPositionY = screenHeight/2 - 128; @@ -4686,4 +4912,4 @@ static void LogoAnimation(void) #endif showLogo = false; // Prevent for repeating when reloading window (Android) -} +} \ No newline at end of file diff --git a/src/external/ANGLE/EGL/eglplatform.h b/src/external/ANGLE/EGL/eglplatform.h index eb3ea70c..7e542ff7 100644 --- a/src/external/ANGLE/EGL/eglplatform.h +++ b/src/external/ANGLE/EGL/eglplatform.h @@ -74,11 +74,16 @@ //#include // raylib edit!!! +#ifndef PLATFORM_UWP typedef void *PVOID; // PVOID is a pointer to any type. This type is declared in WinNT.h typedef PVOID HANDLE; // HANDLE is handle to an object. This type is declared in WinNT.h typedef HANDLE HWND; // HWND is a handle to a window. This type is declared in WinDef.h typedef HANDLE HDC; // HDC is a handle to a device context (DC). This type is declared in WinDef.h typedef HANDLE HBITMAP; // HBITMAP is a handle to a bitmap. This type is declared in WinDef.h +#else +//UWP Fix +#include "Windows.h" +#endif // HDC, HBITMAP and HWND are actually pointers to void. You can cast a long to a HWND like this: HWND h = (HWND)my_long_var; // but very careful of what information is stored in my_long_var. You have to make sure that you have a pointer in there. diff --git a/src/rlgl.h b/src/rlgl.h index 71a1dc4b..ae92f149 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -999,17 +999,17 @@ void rlMultMatrixf(float *matf) } // Multiply the current matrix by a perspective matrix generated by parameters -void rlFrustum(double left, double right, double bottom, double top, double near, double far) +void rlFrustum(double left, double right, double bottom, double top, double znear, double zfar) { - Matrix matPerps = MatrixFrustum(left, right, bottom, top, near, far); + Matrix matPerps = MatrixFrustum(left, right, bottom, top, znear, zfar); *currentMatrix = MatrixMultiply(*currentMatrix, matPerps); } // Multiply the current matrix by an orthographic matrix generated by parameters -void rlOrtho(double left, double right, double bottom, double top, double near, double far) +void rlOrtho(double left, double right, double bottom, double top, double znear, double zfar) { - Matrix matOrtho = MatrixOrtho(left, right, bottom, top, near, far); + Matrix matOrtho = MatrixOrtho(left, right, bottom, top, znear, zfar); *currentMatrix = MatrixMultiply(*currentMatrix, matOrtho); } @@ -1619,7 +1619,7 @@ void rlglInit(int width, int height) if (strcmp(extList[i], (const char *)"GL_EXT_debug_marker") == 0) debugMarkerSupported = true; } -#if defined(_WIN32) && defined(_MSC_VER) +#if defined(_WIN32) && defined(_MSC_VER) && !defined(PLATFORM_UWP) //is this a hotfix? I may need to find out why this is broken RL_FREE(extList); #endif diff --git a/src/utils.c b/src/utils.c index 3cff472b..c886d2a7 100644 --- a/src/utils.c +++ b/src/utils.c @@ -132,7 +132,7 @@ void TraceLog(int logType, const char *text, ...) #else char buffer[MAX_TRACELOG_BUFFER_SIZE] = { 0 }; - switch(logType) + switch (logType) { case LOG_TRACE: strcpy(buffer, "TRACE: "); break; case LOG_DEBUG: strcpy(buffer, "DEBUG: "); break; @@ -150,7 +150,7 @@ void TraceLog(int logType, const char *text, ...) va_end(args); - if (logType >= logTypeExit) exit(1); // If exit message, exit program + if (logType >= logTypeExit) exit(1); // If exit message, exit program #endif // SUPPORT_TRACELOG } @@ -202,3 +202,91 @@ static int android_close(void *cookie) return 0; } #endif + +#if defined(PLATFORM_UWP) + +#define MAX_MESSAGES 512 //If there are over 128 messages, I will cry... either way, this may be too much EDIT: Welp, 512 + +static int UWPOutMessageId = -1; //Stores the last index for the message +static UWPMessage* UWPOutMessages[MAX_MESSAGES]; //Messages out to UWP + +static int UWPInMessageId = -1; //Stores the last index for the message +static UWPMessage* UWPInMessages[MAX_MESSAGES]; //Messages in from UWP + +UWPMessage* CreateUWPMessage(void) +{ + UWPMessage* msg = (UWPMessage*)RL_MALLOC(sizeof(UWPMessage)); + msg->Type = None; + Vector2 v0 = {0, 0}; + msg->Vector0 = v0; + msg->Int0 = 0; + msg->Int1 = 0; + msg->Char0 = 0; + msg->Float0 = 0; + msg->Double0 = 0; + msg->Bool0 = false; + return msg; +} + +void DeleteUWPMessage(UWPMessage* msg) +{ + RL_FREE(msg); +} + +bool UWPHasMessages(void) +{ + return UWPOutMessageId > -1; +} + +UWPMessage* UWPGetMessage(void) +{ + if (UWPHasMessages()) + { + return UWPOutMessages[UWPOutMessageId--]; + } + + return NULL; +} + +void UWPSendMessage(UWPMessage* msg) +{ + if (UWPInMessageId + 1 < MAX_MESSAGES) + { + UWPInMessageId++; + UWPInMessages[UWPInMessageId] = msg; + } + else + { + TraceLog(LOG_WARNING, "[UWP Messaging] Not enough array space to register new UWP inbound Message."); + } +} + +void SendMessageToUWP(UWPMessage* msg) +{ + if (UWPOutMessageId + 1 < MAX_MESSAGES) + { + UWPOutMessageId++; + UWPOutMessages[UWPOutMessageId] = msg; + } + else + { + TraceLog(LOG_WARNING, "[UWP Messaging] Not enough array space to register new UWP outward Message."); + } +} + +bool HasMessageFromUWP(void) +{ + return UWPInMessageId > -1; +} + +UWPMessage* GetMessageFromUWP(void) +{ + if (HasMessageFromUWP()) + { + return UWPInMessages[UWPInMessageId--]; + } + + return NULL; +} + +#endif diff --git a/src/utils.h b/src/utils.h index d7ab8829..14e6bf70 100644 --- a/src/utils.h +++ b/src/utils.h @@ -59,6 +59,81 @@ void InitAssetManager(AAssetManager *manager); // Initialize asset manager from FILE *android_fopen(const char *fileName, const char *mode); // Replacement for fopen() #endif +#if defined(PLATFORM_UWP) + +// UWP Messages System + +typedef enum +{ + None = 0, + + //Send + ShowMouse, + HideMouse, + LockMouse, + UnlockMouse, + SetMouseLocation, //Vector0 (pos) + + //Recieve (Into C) + RegisterKey, //Int0 (key), Char0 (status) + RegisterClick, //Int0 (button), Char0 (status) + ScrollWheelUpdate, //Int0 (delta) + UpdateMouseLocation, //Vector0 (pos) + MarkGamepadActive, //Int0 (gamepad), Bool0 (active or not) + MarkGamepadButton, //Int0 (gamepad), Int1 (button), Char0 (status) + MarkGamepadAxis,//Int0 (gamepad), int1 (axis), Float0 (value) + SetDisplayDims, //Vector0 (display dimensions) + HandleResize, //Vector0 (new dimensions) - Onresized event + SetGameTime, //Int0 +} UWPMessageType; + +typedef struct UWPMessage +{ + //The message type + UWPMessageType Type; + + //Vector parameters + Vector2 Vector0; + + //Int parameters + int Int0; + int Int1; + + //Char parameters + char Char0; + + //Float parameters + float Float0; + + //Double parameters + double Double0; + + //Bool parameters + bool Bool0; + + //More parameters can be added and fed to functions +} UWPMessage; + +//Allocate UWP Message +RLAPI UWPMessage* CreateUWPMessage(void); + +//Free UWP Message +RLAPI void DeleteUWPMessage(UWPMessage* msg); + +//Get messages into C++ +RLAPI bool UWPHasMessages(void); +RLAPI UWPMessage* UWPGetMessage(void); +RLAPI void UWPSendMessage(UWPMessage* msg); + +//For C to call +#ifndef _cplusplus //Hide from C++ code +void SendMessageToUWP(UWPMessage* msg); +bool HasMessageFromUWP(void); +UWPMessage* GetMessageFromUWP(void); +#endif + +#endif + #ifdef __cplusplus } #endif -- cgit v1.2.3 From b911cefab3f39506e22d517088cc9869f363e897 Mon Sep 17 00:00:00 2001 From: Reece Mackie <20544390+Rover656@users.noreply.github.com> Date: Sat, 27 Apr 2019 20:49:33 +0100 Subject: First gamepad stuff --- src/core.c | 126 +++++++++++++++++++++++++++++++++++++++++++++++++---------- src/raylib.h | 51 ++++++++++++++++++++++++ 2 files changed, 157 insertions(+), 20 deletions(-) (limited to 'src') diff --git a/src/core.c b/src/core.c index 0d17fdad..448ad668 100644 --- a/src/core.c +++ b/src/core.c @@ -3050,6 +3050,86 @@ static bool GetMouseButtonStatus(int button) #endif } +static GamepadButton GetGamepadButton(int button) +{ + GamepadButton b = GAMEPAD_BUTTON_UNKNOWN; +#if defined(PLATFORM_DESKTOP) + switch (button) + { + case GLFW_GAMEPAD_BUTTON_Y: b = GAMEPAD_BUTTON_RIGHT_FACE_UP; break; + case GLFW_GAMEPAD_BUTTON_B: b = GAMEPAD_BUTTON_RIGHT_FACE_RIGHT; break; + case GLFW_GAMEPAD_BUTTON_A: b = GAMEPAD_BUTTON_RIGHT_FACE_DOWN; break; + case GLFW_GAMEPAD_BUTTON_X: b = GAMEPAD_BUTTON_RIGHT_FACE_LEFT; break; + case GLFW_GAMEPAD_BUTTON_LEFT_BUMPER: b = GAMEPAD_BUTTON_LEFT_TRIGGER_1; break; + case GLFW_GAMEPAD_BUTTON_RIGHT_BUMPER: b = GAMEPAD_BUTTON_RIGHT_TRIGGER_1; break; + case GLFW_GAMEPAD_BUTTON_BACK: b = GAMEPAD_BUTTON_MIDDLE_LEFT; break; + case GLFW_GAMEPAD_BUTTON_GUIDE: b = GAMEPAD_BUTTON_MIDDLE; break; + case GLFW_GAMEPAD_BUTTON_START: b = GAMEPAD_BUTTON_MIDDLE_RIGHT; break; + case GLFW_GAMEPAD_BUTTON_DPAD_UP: b = GAMEPAD_BUTTON_LEFT_FACE_UP; break; + case GLFW_GAMEPAD_BUTTON_DPAD_RIGHT: b = GAMEPAD_BUTTON_LEFT_FACE_RIGHT; break; + case GLFW_GAMEPAD_BUTTON_DPAD_DOWN: b = GAMEPAD_BUTTON_LEFT_FACE_DOWN; break; + case GLFW_GAMEPAD_BUTTON_DPAD_LEFT: b = GAMEPAD_BUTTON_LEFT_FACE_LEFT; break; + case GLFW_GAMEPAD_BUTTON_LEFT_THUMB: b = GAMEPAD_BUTTON_LEFT_THUMB; break; + case GLFW_GAMEPAD_BUTTON_RIGHT_THUMB: b = GAMEPAD_BUTTON_RIGHT_THUMB; break; + } +#endif + +#if defined(PLATFORM_WEB) + //TODO: TEST + //https://www.w3.org/TR/gamepad/#gamepad-interface + switch (button) + { + case 0: b = GAMEPAD_BUTTON_RIGHT_FACE_DOWN; break; + case 1: b = GAMEPAD_BUTTON_RIGHT_FACE_RIGHT; break; + case 2: b = GAMEPAD_BUTTON_RIGHT_FACE_LEFT; break; + case 3: b = GAMEPAD_BUTTON_RIGHT_FACE_UP; break; + case 4: b = GAMEPAD_BUTTON_LEFT_TRIGGER_1; break; + case 5: b = GAMEPAD_BUTTON_RIGHT_TRIGGER_1; break; + case 6: b = GAMEPAD_BUTTON_LEFT_TRIGGER_2; break; + case 7: b = GAMEPAD_BUTTON_RIGHT_TRIGGER_2; break; + case 8: b = GAMEPAD_BUTTON_MIDDLE_LEFT; break; + case 9: b = GAMEPAD_BUTTON_MIDDLE_RIGHT; break; + case 10: b = GAMEPAD_BUTTON_LEFT_THUMB; break; + case 11: b = GAMEPAD_BUTTON_RIGHT_THUMB; break; + case 12: b = GAMEPAD_BUTTON_LEFT_FACE_UP; break; + case 13: b = GAMEPAD_BUTTON_LEFT_FACE_DOWN; break; + case 14: b = GAMEPAD_BUTTON_LEFT_FACE_LEFT; break; + case 15: b = GAMEPAD_BUTTON_LEFT_FACE_RIGHT; break; + } +#endif + + return b; +} + +static GamepadAxis GetGamepadAxis(int axis) +{ + GamepadAxis a = GAMEPAD_AXIS_UNKNOWN; +#if defined(PLATFORM_DESKTOP) + switch(axis) + { + case GLFW_GAMEPAD_AXIS_LEFT_X: a = GAMEPAD_AXIS_LEFT_X; break; + case GLFW_GAMEPAD_AXIS_LEFT_Y: a = GAMEPAD_AXIS_LEFT_Y; break; + case GLFW_GAMEPAD_AXIS_RIGHT_X: a = GAMEPAD_AXIS_RIGHT_X; break; + case GLFW_GAMEPAD_AXIS_RIGHT_Y: a = GAMEPAD_AXIS_RIGHT_Y; break; + case GLFW_GAMEPAD_AXIS_LEFT_TRIGGER: a = GAMEPAD_AXIS_LEFT_TRIGGER; break; + case GLFW_GAMEPAD_AXIS_RIGHT_TRIGGER: a = GAMEPAD_AXIS_RIGHT_TRIGGER; break; + } +#endif + +#if defined(PLATFORM_WEB) + //TODO: TEST + switch(axis) + { + case 0: a = GAMEPAD_AXIS_LEFT_X; + case 1: a = GAMEPAD_AXIS_LEFT_Y; + case 2: a = GAMEPAD_AXIS_RIGHT_X; + case 3: a = GAMEPAD_AXIS_RIGHT_X; + } +#endif + + return a; +} + // Poll (store) all input events static void PollInputEvents(void) { @@ -3114,7 +3194,7 @@ static void PollInputEvents(void) #if defined(PLATFORM_DESKTOP) // Check if gamepads are ready - // NOTE: We do it here in case of disconection + // NOTE: We do it here in case of disconnection for (int i = 0; i < MAX_GAMEPADS; i++) { if (glfwJoystickPresent(i)) gamepadReady[i] = true; @@ -3131,33 +3211,37 @@ static void PollInputEvents(void) // Get current gamepad state // NOTE: There is no callback available, so we get it manually - const unsigned char *buttons; - int buttonsCount; - - buttons = glfwGetJoystickButtons(i, &buttonsCount); + //Get remapped buttons + GLFWgamepadstate state; + glfwGetGamepadState(i, &state); //This remapps all gamepads so they work the same + const unsigned char *buttons = state.buttons; - for (int k = 0; (buttons != NULL) && (k < buttonsCount) && (buttonsCount < MAX_GAMEPAD_BUTTONS); k++) + for (int k = 0; (buttons != NULL) && (k < GLFW_GAMEPAD_BUTTON_DPAD_LEFT + 1) && (k < MAX_GAMEPAD_BUTTONS); k++) { + const GamepadButton button = GetGamepadButton(k); + if (buttons[k] == GLFW_PRESS) { - currentGamepadState[i][k] = 1; - lastGamepadButtonPressed = k; + currentGamepadState[i][button] = 1; + lastGamepadButtonPressed = button; } - else currentGamepadState[i][k] = 0; + else currentGamepadState[i][button] = 0; } // Get current axis state - const float *axes; - int axisCount = 0; - - axes = glfwGetJoystickAxes(i, &axisCount); + const float *axes = state.axes; - for (int k = 0; (axes != NULL) && (k < axisCount) && (k < MAX_GAMEPAD_AXIS); k++) + for (int k = 0; (axes != NULL) && (k < GLFW_GAMEPAD_AXIS_LAST + 1) && (k < MAX_GAMEPAD_AXIS); k++) { - gamepadAxisState[i][k] = axes[k]; + const GamepadAxis axis = GetGamepadAxis(k); + gamepadAxisState[i][axis] = axes[k]; } - gamepadAxisCount = axisCount; + //Register buttons for 2nd triggers + currentGamepadState[i][GAMEPAD_BUTTON_LEFT_TRIGGER_2] = (char)(gamepadAxisState[i][GAMEPAD_AXIS_LEFT_TRIGGER] > 0.1); + currentGamepadState[i][GAMEPAD_BUTTON_RIGHT_TRIGGER_2] = (char)(gamepadAxisState[i][GAMEPAD_AXIS_RIGHT_TRIGGER] > 0.1); + + gamepadAxisCount = GLFW_GAMEPAD_AXIS_LAST; } } @@ -3191,12 +3275,13 @@ static void PollInputEvents(void) // Register buttons data for every connected gamepad for (int j = 0; (j < gamepadState.numButtons) && (j < MAX_GAMEPAD_BUTTONS); j++) { + const GamepadButton button = GetGamepadButton(j); if (gamepadState.digitalButton[j] == 1) { - currentGamepadState[i][j] = 1; - lastGamepadButtonPressed = j; + currentGamepadState[i][button] = 1; + lastGamepadButtonPressed = button; } - else currentGamepadState[i][j] = 0; + else currentGamepadState[i][button] = 0; //TraceLog(LOG_DEBUG, "Gamepad %d, button %d: Digital: %d, Analog: %g", gamepadState.index, j, gamepadState.digitalButton[j], gamepadState.analogButton[j]); } @@ -3204,7 +3289,8 @@ static void PollInputEvents(void) // Register axis data for every connected gamepad for (int j = 0; (j < gamepadState.numAxes) && (j < MAX_GAMEPAD_AXIS); j++) { - gamepadAxisState[i][j] = gamepadState.axis[j]; + const GamepadAxis axis = GetGamepadAxis(k); + gamepadAxisState[i][axis] = gamepadState.axis[j]; } gamepadAxisCount = gamepadState.numAxes; diff --git a/src/raylib.h b/src/raylib.h index 43260e06..9759000f 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -619,6 +619,57 @@ typedef enum { GAMEPAD_PLAYER4 = 3 } GamepadNumber; +// Gamepad Buttons +typedef enum +{ + //This is here just for error checking + GAMEPAD_BUTTON_UNKNOWN = 0, + + //This is normally ABXY/Circle, Triangle, Square, Cross. No support for 6 button controllers though.. + GAMEPAD_BUTTON_LEFT_FACE_UP, + GAMEPAD_BUTTON_LEFT_FACE_RIGHT, + GAMEPAD_BUTTON_LEFT_FACE_DOWN, + GAMEPAD_BUTTON_LEFT_FACE_LEFT, + + + //This is normally a DPAD + GAMEPAD_BUTTON_RIGHT_FACE_UP, + GAMEPAD_BUTTON_RIGHT_FACE_RIGHT, + GAMEPAD_BUTTON_RIGHT_FACE_DOWN, + GAMEPAD_BUTTON_RIGHT_FACE_LEFT, + + //Triggers + GAMEPAD_BUTTON_LEFT_TRIGGER_1, + GAMEPAD_BUTTON_LEFT_TRIGGER_2, + GAMEPAD_BUTTON_RIGHT_TRIGGER_1, + GAMEPAD_BUTTON_RIGHT_TRIGGER_2, + + //These are buttons in the center of the gamepad + GAMEPAD_BUTTON_MIDDLE_LEFT, //PS3 Select + GAMEPAD_BUTTON_MIDDLE, //PS Button/XBOX Button + GAMEPAD_BUTTON_MIDDLE_RIGHT, //PS3 Start + + //These are the joystick press in buttons + GAMEPAD_BUTTON_LEFT_THUMB, + GAMEPAD_BUTTON_RIGHT_THUMB +} GamepadButton; + +typedef enum +{ + GAMEPAD_AXIS_UNKNOWN = 0, + //Left stick + GAMEPAD_AXIS_LEFT_X, + GAMEPAD_AXIS_LEFT_Y, + + //Right stick + GAMEPAD_AXIS_RIGHT_X, + GAMEPAD_AXIS_RIGHT_Y, + + //Pressure levels + GAMEPAD_AXIS_LEFT_TRIGGER, // [1..-1] (pressure-level) + GAMEPAD_AXIS_RIGHT_TRIGGER // [1..-1] (pressure-level) +} GamepadAxis; + // PS3 USB Controller Buttons // TODO: Provide a generic way to list gamepad controls schemes, // defining specific controls schemes is not a good option -- cgit v1.2.3 From 56ded3259ded9c5fc8d5c7dff1a50044326f5ab5 Mon Sep 17 00:00:00 2001 From: Reece Mackie <20544390+Rover656@users.noreply.github.com> Date: Sat, 27 Apr 2019 21:36:57 +0100 Subject: More work, UWP now supports it and deleted old gamepads --- src/core.c | 38 +++++++++++++++++++++++++++++ src/raylib.h | 78 ------------------------------------------------------------ 2 files changed, 38 insertions(+), 78 deletions(-) (limited to 'src') diff --git a/src/core.c b/src/core.c index 7977d0ad..2aa22fa6 100644 --- a/src/core.c +++ b/src/core.c @@ -3095,20 +3095,50 @@ static GamepadButton GetGamepadButton(int button) case GLFW_GAMEPAD_BUTTON_B: b = GAMEPAD_BUTTON_RIGHT_FACE_RIGHT; break; case GLFW_GAMEPAD_BUTTON_A: b = GAMEPAD_BUTTON_RIGHT_FACE_DOWN; break; case GLFW_GAMEPAD_BUTTON_X: b = GAMEPAD_BUTTON_RIGHT_FACE_LEFT; break; + case GLFW_GAMEPAD_BUTTON_LEFT_BUMPER: b = GAMEPAD_BUTTON_LEFT_TRIGGER_1; break; case GLFW_GAMEPAD_BUTTON_RIGHT_BUMPER: b = GAMEPAD_BUTTON_RIGHT_TRIGGER_1; break; + case GLFW_GAMEPAD_BUTTON_BACK: b = GAMEPAD_BUTTON_MIDDLE_LEFT; break; case GLFW_GAMEPAD_BUTTON_GUIDE: b = GAMEPAD_BUTTON_MIDDLE; break; case GLFW_GAMEPAD_BUTTON_START: b = GAMEPAD_BUTTON_MIDDLE_RIGHT; break; + case GLFW_GAMEPAD_BUTTON_DPAD_UP: b = GAMEPAD_BUTTON_LEFT_FACE_UP; break; case GLFW_GAMEPAD_BUTTON_DPAD_RIGHT: b = GAMEPAD_BUTTON_LEFT_FACE_RIGHT; break; case GLFW_GAMEPAD_BUTTON_DPAD_DOWN: b = GAMEPAD_BUTTON_LEFT_FACE_DOWN; break; case GLFW_GAMEPAD_BUTTON_DPAD_LEFT: b = GAMEPAD_BUTTON_LEFT_FACE_LEFT; break; + case GLFW_GAMEPAD_BUTTON_LEFT_THUMB: b = GAMEPAD_BUTTON_LEFT_THUMB; break; case GLFW_GAMEPAD_BUTTON_RIGHT_THUMB: b = GAMEPAD_BUTTON_RIGHT_THUMB; break; } #endif +#if defined(PLATFORM_UWP) + /*switch(button) + { + case 4: b = GAMEPAD_BUTTON_RIGHT_FACE_DOWN; break; + case 8: b = GAMEPAD_BUTTON_RIGHT_FACE_RIGHT; break; + case 16: b = GAMEPAD_BUTTON_RIGHT_FACE_LEFT; break; + case 32: b = GAMEPAD_BUTTON_RIGHT_FACE_RIGHT; break; + + case 128: b = GAMEPAD_BUTTON_LEFT_FACE_DOWN; break; + case 256: b = GAMEPAD_BUTTON_LEFT_FACE_LEFT; break; + case 512: b = GAMEPAD_BUTTON_LEFT_FACE_RIGHT; break; + case 64: b = GAMEPAD_BUTTON_LEFT_FACE_UP; break; + + case 1024: b = GAMEPAD_BUTTON_LEFT_TRIGGER_1; break; + case 2048: b = GAMEPAD_BUTTON_RIGHT_TRIGGER_1; break; + + case 4096: b = GAMEPAD_BUTTON_LEFT_THUMB; break; + case 8192: b = GAMEPAD_BUTTON_RIGHT_THUMB; break; + + case 2: b = GAMEPAD_BUTTON_MIDDLE_LEFT; + case 1: b = GAMEPAD_BUTTON_MIDDLE_RIGHT; + }*/ + //Above might not be most efficient, so not doing it for now + b = button; +#endif + #if defined(PLATFORM_WEB) //TODO: TEST //https://www.w3.org/TR/gamepad/#gamepad-interface @@ -3151,6 +3181,10 @@ static GamepadAxis GetGamepadAxis(int axis) } #endif +#if defined(PLATFORM_UWP) + a = axis; //UWP will provide the correct axis +#endif + #if defined(PLATFORM_WEB) //TODO: TEST switch(axis) @@ -3347,6 +3381,10 @@ static void PollInputEvents(void) { if (msg->Int0 < MAX_GAMEPADS && msg->Int1 < MAX_GAMEPAD_AXIS) gamepadAxisState[msg->Int0][msg->Int1] = msg->Float0; + + //Register buttons for 2nd triggers + currentGamepadState[msg->Int0][GAMEPAD_BUTTON_LEFT_TRIGGER_2] = (char)(gamepadAxisState[msg->Int0][GAMEPAD_AXIS_LEFT_TRIGGER] > 0.1); + currentGamepadState[msg->Int0][GAMEPAD_BUTTON_RIGHT_TRIGGER_2] = (char)(gamepadAxisState[msg->Int0][GAMEPAD_AXIS_RIGHT_TRIGGER] > 0.1); break; } diff --git a/src/raylib.h b/src/raylib.h index 9759000f..1b4a5434 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -670,84 +670,6 @@ typedef enum GAMEPAD_AXIS_RIGHT_TRIGGER // [1..-1] (pressure-level) } GamepadAxis; -// PS3 USB Controller Buttons -// TODO: Provide a generic way to list gamepad controls schemes, -// defining specific controls schemes is not a good option -typedef enum { - GAMEPAD_PS3_BUTTON_TRIANGLE = 0, - GAMEPAD_PS3_BUTTON_CIRCLE = 1, - GAMEPAD_PS3_BUTTON_CROSS = 2, - GAMEPAD_PS3_BUTTON_SQUARE = 3, - GAMEPAD_PS3_BUTTON_L1 = 6, - GAMEPAD_PS3_BUTTON_R1 = 7, - GAMEPAD_PS3_BUTTON_L2 = 4, - GAMEPAD_PS3_BUTTON_R2 = 5, - GAMEPAD_PS3_BUTTON_START = 8, - GAMEPAD_PS3_BUTTON_SELECT = 9, - GAMEPAD_PS3_BUTTON_PS = 12, - GAMEPAD_PS3_BUTTON_UP = 24, - GAMEPAD_PS3_BUTTON_RIGHT = 25, - GAMEPAD_PS3_BUTTON_DOWN = 26, - GAMEPAD_PS3_BUTTON_LEFT = 27 -} GamepadPS3Button; - -// PS3 USB Controller Axis -typedef enum { - GAMEPAD_PS3_AXIS_LEFT_X = 0, - GAMEPAD_PS3_AXIS_LEFT_Y = 1, - GAMEPAD_PS3_AXIS_RIGHT_X = 2, - GAMEPAD_PS3_AXIS_RIGHT_Y = 5, - GAMEPAD_PS3_AXIS_L2 = 3, // [1..-1] (pressure-level) - GAMEPAD_PS3_AXIS_R2 = 4 // [1..-1] (pressure-level) -} GamepadPS3Axis; - -// Xbox360 USB Controller Buttons -typedef enum { - GAMEPAD_XBOX_BUTTON_A = 0, - GAMEPAD_XBOX_BUTTON_B = 1, - GAMEPAD_XBOX_BUTTON_X = 2, - GAMEPAD_XBOX_BUTTON_Y = 3, - GAMEPAD_XBOX_BUTTON_LB = 4, - GAMEPAD_XBOX_BUTTON_RB = 5, - GAMEPAD_XBOX_BUTTON_SELECT = 6, - GAMEPAD_XBOX_BUTTON_START = 7, - GAMEPAD_XBOX_BUTTON_HOME = 8, - GAMEPAD_XBOX_BUTTON_UP = 10, - GAMEPAD_XBOX_BUTTON_RIGHT = 11, - GAMEPAD_XBOX_BUTTON_DOWN = 12, - GAMEPAD_XBOX_BUTTON_LEFT = 13 -} GamepadXbox360Button; - -// Xbox360 USB Controller Axis, -// NOTE: For Raspberry Pi, axis must be reconfigured -typedef enum { - GAMEPAD_XBOX_AXIS_LEFT_X = 0, // [-1..1] (left->right) - GAMEPAD_XBOX_AXIS_LEFT_Y = 1, // [1..-1] (up->down) - GAMEPAD_XBOX_AXIS_RIGHT_X = 2, // [-1..1] (left->right) - GAMEPAD_XBOX_AXIS_RIGHT_Y = 3, // [1..-1] (up->down) - GAMEPAD_XBOX_AXIS_LT = 4, // [-1..1] (pressure-level) - GAMEPAD_XBOX_AXIS_RT = 5 // [-1..1] (pressure-level) -} GamepadXbox360Axis; - -// Android Gamepad Controller (SNES CLASSIC) -typedef enum { - GAMEPAD_ANDROID_DPAD_UP = 19, - GAMEPAD_ANDROID_DPAD_DOWN = 20, - GAMEPAD_ANDROID_DPAD_LEFT = 21, - GAMEPAD_ANDROID_DPAD_RIGHT = 22, - GAMEPAD_ANDROID_DPAD_CENTER = 23, - GAMEPAD_ANDROID_BUTTON_A = 96, - GAMEPAD_ANDROID_BUTTON_B = 97, - GAMEPAD_ANDROID_BUTTON_C = 98, - GAMEPAD_ANDROID_BUTTON_X = 99, - GAMEPAD_ANDROID_BUTTON_Y = 100, - GAMEPAD_ANDROID_BUTTON_Z = 101, - GAMEPAD_ANDROID_BUTTON_L1 = 102, - GAMEPAD_ANDROID_BUTTON_R1 = 103, - GAMEPAD_ANDROID_BUTTON_L2 = 104, - GAMEPAD_ANDROID_BUTTON_R2 = 105 -} GamepadAndroid; - // Shader location point type typedef enum { LOC_VERTEX_POSITION = 0, -- cgit v1.2.3 From c1f33eb817765ad801b2419d86457a6102b64032 Mon Sep 17 00:00:00 2001 From: Reece Mackie <20544390+Rover656@users.noreply.github.com> Date: Sat, 27 Apr 2019 21:43:32 +0100 Subject: Line cleaning --- src/raylib.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/raylib.h b/src/raylib.h index 1b4a5434..b8347ef4 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -631,7 +631,6 @@ typedef enum GAMEPAD_BUTTON_LEFT_FACE_DOWN, GAMEPAD_BUTTON_LEFT_FACE_LEFT, - //This is normally a DPAD GAMEPAD_BUTTON_RIGHT_FACE_UP, GAMEPAD_BUTTON_RIGHT_FACE_RIGHT, @@ -657,6 +656,7 @@ typedef enum typedef enum { GAMEPAD_AXIS_UNKNOWN = 0, + //Left stick GAMEPAD_AXIS_LEFT_X, GAMEPAD_AXIS_LEFT_Y, -- cgit v1.2.3 From e8c413b7cd1696c207d015bc3e4a00edf71300d2 Mon Sep 17 00:00:00 2001 From: raysan5 Date: Sat, 27 Apr 2019 22:47:03 +0200 Subject: Review UWP implementation Basically, formating review and some variables naming to follow raylib conventions. --- src/core.c | 329 ++++++++++++++++++++++++++---------------------------------- src/rlgl.h | 31 ++---- src/utils.c | 63 +++++------- src/utils.h | 94 +++++++---------- 4 files changed, 215 insertions(+), 302 deletions(-) (limited to 'src') diff --git a/src/core.c b/src/core.c index db75979a..2a8f2e3a 100644 --- a/src/core.c +++ b/src/core.c @@ -391,7 +391,6 @@ static int gamepadStream[MAX_GAMEPADS] = { -1 };// Gamepad device file descripto static pthread_t gamepadThreadId; // Gamepad reading thread id static char gamepadName[64]; // Gamepad name holder #endif - //----------------------------------------------------------------------------------- // Timming system variables @@ -402,7 +401,6 @@ static double updateTime = 0.0; // Time measure for frame update static double drawTime = 0.0; // Time measure for frame draw static double frameTime = 0.0; // Time measure for one frame static double targetTime = 0.0; // Desired time for one frame, if 0 not applied - //----------------------------------------------------------------------------------- // Config internal variables @@ -1027,8 +1025,8 @@ void ShowCursor(void) glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); #endif #if defined(PLATFORM_UWP) - UWPMessage* msg = CreateUWPMessage(); - msg->Type = ShowMouse; + UWPMessage *msg = CreateUWPMessage(); + msg->type = UWP_MSG_SHOW_MOUSE; SendMessageToUWP(msg); #endif cursorHidden = false; @@ -1041,8 +1039,8 @@ void HideCursor(void) glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN); #endif #if defined(PLATFORM_UWP) - UWPMessage* msg = CreateUWPMessage(); - msg->Type = HideMouse; + UWPMessage *msg = CreateUWPMessage(); + msg->type = UWP_MSG_HIDE_MOUSE; SendMessageToUWP(msg); #endif cursorHidden = true; @@ -1064,8 +1062,8 @@ void EnableCursor(void) toggleCursorLock = true; #endif #if defined(PLATFORM_UWP) - UWPMessage* msg = CreateUWPMessage(); - msg->Type = LockMouse; + UWPMessage *msg = CreateUWPMessage(); + msg->type = UWP_MSG_LOCK_MOUSE; SendMessageToUWP(msg); #endif cursorHidden = false; @@ -1081,8 +1079,8 @@ void DisableCursor(void) toggleCursorLock = true; #endif #if defined(PLATFORM_UWP) - UWPMessage* msg = CreateUWPMessage(); - msg->Type = UnlockMouse; + UWPMessage *msg = CreateUWPMessage(); + msg->type = UWP_MSG_UNLOCK_MOUSE; SendMessageToUWP(msg); #endif cursorHidden = true; @@ -1165,7 +1163,7 @@ void EndDrawing(void) frameTime += extraTime; } - return; + return; } // Initialize 2D mode with custom camera (2D) @@ -1444,8 +1442,8 @@ double GetTime(void) #endif #if defined(PLATFORM_UWP) - //Updated through messages - return currentTime; + // Updated through messages + return currentTime; #endif } @@ -2236,10 +2234,10 @@ void SetMousePosition(int x, int y) glfwSetCursorPos(window, mousePosition.x, mousePosition.y); #endif #if defined(PLATFORM_UWP) - UWPMessage* msg = CreateUWPMessage(); - msg->Type = SetMouseLocation; - msg->Vector0.x = mousePosition.x; - msg->Vector0.y = mousePosition.y; + UWPMessage *msg = CreateUWPMessage(); + msg->type = UWP_MSG_SET_MOUSE_LOCATION; + msg->paramVector0.x = mousePosition.x; + msg->paramVector0.y = mousePosition.y; SendMessageToUWP(msg); #endif } @@ -2711,8 +2709,6 @@ static bool InitGraphicsDevice(int width, int height) } } - //SetupFramebuffer(displayWidth, displayHeight); - EGLint numConfigs = 0; if ((eglChooseConfig(display, framebufferAttribs, &config, 1, &numConfigs) == EGL_FALSE) || (numConfigs == 0)) { @@ -2769,8 +2765,6 @@ static bool InitGraphicsDevice(int width, int height) eglQuerySurface(display, surface, EGL_WIDTH, &screenWidth); eglQuerySurface(display, surface, EGL_HEIGHT, &screenHeight); - //SetupFramebuffer(displayWidth, displayHeight); //Borked - #else // PLATFORM_ANDROID, PLATFORM_RPI EGLint numConfigs; @@ -2941,8 +2935,8 @@ static void SetupFramebuffer(int width, int height) TraceLog(LOG_WARNING, "DOWNSCALING: Required screen size (%ix%i) is bigger than display size (%ix%i)", screenWidth, screenHeight, displayWidth, displayHeight); // Downscaling to fit display with border-bars - float widthRatio = (float)displayWidth / (float)screenWidth; - float heightRatio = (float)displayHeight / (float)screenHeight; + float widthRatio = (float)displayWidth/(float)screenWidth; + float heightRatio = (float)displayHeight/(float)screenHeight; if (widthRatio <= heightRatio) { @@ -2960,7 +2954,7 @@ static void SetupFramebuffer(int width, int height) } // Screen scaling required - float scaleRatio = (float)renderWidth / (float)screenWidth; + float scaleRatio = (float)renderWidth/(float)screenWidth; screenScaling = MatrixScale(scaleRatio, scaleRatio, scaleRatio); // NOTE: We render to full display resolution! @@ -2976,13 +2970,13 @@ static void SetupFramebuffer(int width, int height) TraceLog(LOG_INFO, "UPSCALING: Required screen size: %i x %i -> Display size: %i x %i", screenWidth, screenHeight, displayWidth, displayHeight); // Upscaling to fit display with border-bars - float displayRatio = (float)displayWidth / (float)displayHeight; - float screenRatio = (float)screenWidth / (float)screenHeight; + float displayRatio = (float)displayWidth/(float)displayHeight; + float screenRatio = (float)screenWidth/(float)screenHeight; if (displayRatio <= screenRatio) { renderWidth = screenWidth; - renderHeight = (int)round((float)screenWidth / displayRatio); + renderHeight = (int)round((float)screenWidth/displayRatio); renderOffsetX = 0; renderOffsetY = (renderHeight - screenHeight); } @@ -3126,7 +3120,6 @@ static void PollInputEvents(void) #endif #if defined(PLATFORM_UWP) - // Register previous keys states for (int i = 0; i < 512; i++) previousKeyState[i] = currentKeyState[i]; @@ -3141,180 +3134,140 @@ static void PollInputEvents(void) // Register previous mouse states previousMouseWheelY = currentMouseWheelY; currentMouseWheelY = 0; - for (int i = 0; i < 3; i++) - { - previousMouseState[i] = currentMouseState[i]; - - } + for (int i = 0; i < 3; i++) previousMouseState[i] = currentMouseState[i]; // Loop over pending messages while (HasMessageFromUWP()) { - UWPMessage* msg = GetMessageFromUWP(); + UWPMessage *msg = GetMessageFromUWP(); - switch (msg->Type) - { - case RegisterKey: + switch (msg->type) { - //Convert from virtualKey - int actualKey = -1; - - switch (msg->Int0) + case UWP_MSG_REGISTER_KEY: { - case 0x08: actualKey = KEY_BACKSPACE; break; - case 0x20: actualKey = KEY_SPACE; break; - case 0x1B: actualKey = KEY_ESCAPE; break; - case 0x0D: actualKey = KEY_ENTER; break; - case 0x2E: actualKey = KEY_DELETE; break; - case 0x27: actualKey = KEY_RIGHT; break; - case 0x25: actualKey = KEY_LEFT; break; - case 0x28: actualKey = KEY_DOWN; break; - case 0x26: actualKey = KEY_UP; break; - case 0x70: actualKey = KEY_F1; break; - case 0x71: actualKey = KEY_F2; break; - case 0x72: actualKey = KEY_F3; break; - case 0x73: actualKey = KEY_F4; break; - case 0x74: actualKey = KEY_F5; break; - case 0x75: actualKey = KEY_F6; break; - case 0x76: actualKey = KEY_F7; break; - case 0x77: actualKey = KEY_F8; break; - case 0x78: actualKey = KEY_F9; break; - case 0x79: actualKey = KEY_F10; break; - case 0x7A: actualKey = KEY_F11; break; - case 0x7B: actualKey = KEY_F12; break; - case 0xA0: actualKey = KEY_LEFT_SHIFT; break; - case 0xA2: actualKey = KEY_LEFT_CONTROL; break; - case 0xA4: actualKey = KEY_LEFT_ALT; break; - case 0xA1: actualKey = KEY_RIGHT_SHIFT; break; - case 0xA3: actualKey = KEY_RIGHT_CONTROL; break; - case 0xA5: actualKey = KEY_RIGHT_ALT; break; - case 0x30: actualKey = KEY_ZERO; break; - case 0x31: actualKey = KEY_ONE; break; - case 0x32: actualKey = KEY_TWO; break; - case 0x33: actualKey = KEY_THREE; break; - case 0x34: actualKey = KEY_FOUR; break; - case 0x35: actualKey = KEY_FIVE; break; - case 0x36: actualKey = KEY_SIX; break; - case 0x37: actualKey = KEY_SEVEN; break; - case 0x38: actualKey = KEY_EIGHT; break; - case 0x39: actualKey = KEY_NINE; break; - case 0x41: actualKey = KEY_A; break; - case 0x42: actualKey = KEY_B; break; - case 0x43: actualKey = KEY_C; break; - case 0x44: actualKey = KEY_D; break; - case 0x45: actualKey = KEY_E; break; - case 0x46: actualKey = KEY_F; break; - case 0x47: actualKey = KEY_G; break; - case 0x48: actualKey = KEY_H; break; - case 0x49: actualKey = KEY_I; break; - case 0x4A: actualKey = KEY_J; break; - case 0x4B: actualKey = KEY_K; break; - case 0x4C: actualKey = KEY_L; break; - case 0x4D: actualKey = KEY_M; break; - case 0x4E: actualKey = KEY_N; break; - case 0x4F: actualKey = KEY_O; break; - case 0x50: actualKey = KEY_P; break; - case 0x51: actualKey = KEY_Q; break; - case 0x52: actualKey = KEY_R; break; - case 0x53: actualKey = KEY_S; break; - case 0x54: actualKey = KEY_T; break; - case 0x55: actualKey = KEY_U; break; - case 0x56: actualKey = KEY_V; break; - case 0x57: actualKey = KEY_W; break; - case 0x58: actualKey = KEY_X; break; - case 0x59: actualKey = KEY_Y; break; - case 0x5A: actualKey = KEY_Z; break; - } - - if (actualKey > -1) - currentKeyState[actualKey] = msg->Char0; - break; - } - - case RegisterClick: - { - currentMouseState[msg->Int0] = msg->Char0; - break; - } - - case ScrollWheelUpdate: - { - currentMouseWheelY += msg->Int0; - break; - } - - case UpdateMouseLocation: - { - mousePosition = msg->Vector0; - break; - } + // Convert from virtualKey + int actualKey = -1; - case MarkGamepadActive: - { - if (msg->Int0 < MAX_GAMEPADS) - gamepadReady[msg->Int0] = msg->Bool0; - break; - } - - case MarkGamepadButton: - { - if (msg->Int0 < MAX_GAMEPADS && msg->Int1 < MAX_GAMEPAD_BUTTONS) - currentGamepadState[msg->Int0][msg->Int1] = msg->Char0; - break; - } - - case MarkGamepadAxis: - { - if (msg->Int0 < MAX_GAMEPADS && msg->Int1 < MAX_GAMEPAD_AXIS) - gamepadAxisState[msg->Int0][msg->Int1] = msg->Float0; - break; - } - - case SetDisplayDims: - { - displayWidth = msg->Vector0.x; - displayHeight = msg->Vector0.y; - break; - } - - case HandleResize: - { - eglQuerySurface(display, surface, EGL_WIDTH, &screenWidth); - eglQuerySurface(display, surface, EGL_HEIGHT, &screenHeight); - - // If window is resized, viewport and projection matrix needs to be re-calculated - rlViewport(0, 0, screenWidth, screenHeight); // Set viewport width and height - rlMatrixMode(RL_PROJECTION); // Switch to PROJECTION matrix - rlLoadIdentity(); // Reset current matrix (PROJECTION) - rlOrtho(0, screenWidth, screenHeight, 0, 0.0f, 1.0f); // Orthographic projection mode with top-left corner at (0,0) - rlMatrixMode(RL_MODELVIEW); // Switch back to MODELVIEW matrix - rlLoadIdentity(); // Reset current matrix (MODELVIEW) - rlClearScreenBuffers(); // Clear screen buffers (color and depth) - - // Window size must be updated to be used on 3D mode to get new aspect ratio (BeginMode3D()) - // NOTE: Be careful! GLFW3 will choose the closest fullscreen resolution supported by current monitor, - // for example, if reescaling back to 800x450 (desired), it could set 720x480 (closest fullscreen supported) - currentWidth = screenWidth; - currentHeight = screenHeight; - - // NOTE: Postprocessing texture is not scaled to new size - - windowResized = true; - break; - } + switch (msg->paramInt0) + { + case 0x08: actualKey = KEY_BACKSPACE; break; + case 0x20: actualKey = KEY_SPACE; break; + case 0x1B: actualKey = KEY_ESCAPE; break; + case 0x0D: actualKey = KEY_ENTER; break; + case 0x2E: actualKey = KEY_DELETE; break; + case 0x27: actualKey = KEY_RIGHT; break; + case 0x25: actualKey = KEY_LEFT; break; + case 0x28: actualKey = KEY_DOWN; break; + case 0x26: actualKey = KEY_UP; break; + case 0x70: actualKey = KEY_F1; break; + case 0x71: actualKey = KEY_F2; break; + case 0x72: actualKey = KEY_F3; break; + case 0x73: actualKey = KEY_F4; break; + case 0x74: actualKey = KEY_F5; break; + case 0x75: actualKey = KEY_F6; break; + case 0x76: actualKey = KEY_F7; break; + case 0x77: actualKey = KEY_F8; break; + case 0x78: actualKey = KEY_F9; break; + case 0x79: actualKey = KEY_F10; break; + case 0x7A: actualKey = KEY_F11; break; + case 0x7B: actualKey = KEY_F12; break; + case 0xA0: actualKey = KEY_LEFT_SHIFT; break; + case 0xA2: actualKey = KEY_LEFT_CONTROL; break; + case 0xA4: actualKey = KEY_LEFT_ALT; break; + case 0xA1: actualKey = KEY_RIGHT_SHIFT; break; + case 0xA3: actualKey = KEY_RIGHT_CONTROL; break; + case 0xA5: actualKey = KEY_RIGHT_ALT; break; + case 0x30: actualKey = KEY_ZERO; break; + case 0x31: actualKey = KEY_ONE; break; + case 0x32: actualKey = KEY_TWO; break; + case 0x33: actualKey = KEY_THREE; break; + case 0x34: actualKey = KEY_FOUR; break; + case 0x35: actualKey = KEY_FIVE; break; + case 0x36: actualKey = KEY_SIX; break; + case 0x37: actualKey = KEY_SEVEN; break; + case 0x38: actualKey = KEY_EIGHT; break; + case 0x39: actualKey = KEY_NINE; break; + case 0x41: actualKey = KEY_A; break; + case 0x42: actualKey = KEY_B; break; + case 0x43: actualKey = KEY_C; break; + case 0x44: actualKey = KEY_D; break; + case 0x45: actualKey = KEY_E; break; + case 0x46: actualKey = KEY_F; break; + case 0x47: actualKey = KEY_G; break; + case 0x48: actualKey = KEY_H; break; + case 0x49: actualKey = KEY_I; break; + case 0x4A: actualKey = KEY_J; break; + case 0x4B: actualKey = KEY_K; break; + case 0x4C: actualKey = KEY_L; break; + case 0x4D: actualKey = KEY_M; break; + case 0x4E: actualKey = KEY_N; break; + case 0x4F: actualKey = KEY_O; break; + case 0x50: actualKey = KEY_P; break; + case 0x51: actualKey = KEY_Q; break; + case 0x52: actualKey = KEY_R; break; + case 0x53: actualKey = KEY_S; break; + case 0x54: actualKey = KEY_T; break; + case 0x55: actualKey = KEY_U; break; + case 0x56: actualKey = KEY_V; break; + case 0x57: actualKey = KEY_W; break; + case 0x58: actualKey = KEY_X; break; + case 0x59: actualKey = KEY_Y; break; + case 0x5A: actualKey = KEY_Z; break; + default: break; + } - case SetGameTime: - { - currentTime = msg->Double0; - break; - } + if (actualKey > -1) currentKeyState[actualKey] = msg->paramChar0; + } break; + case UWP_MSG_REGISTER_CLICK: currentMouseState[msg->paramInt0] = msg->paramChar0; break; + case UWP_MSG_SCROLL_WHEEL_UPDATE: currentMouseWheelY += msg->paramInt0; break; + case UWP_MSG_UPDATE_MOUSE_LOCATION: mousePosition = msg->paramVector0; break; + case UWP_MSG_SET_GAMEPAD_ACTIVE: if (msg->paramInt0 < MAX_GAMEPADS) gamepadReady[msg->paramInt0] = msg->paramBool0; break; + case UWP_MSG_SET_GAMEPAD_BUTTON: + { + if ((msg->paramInt0 < MAX_GAMEPADS) && (msg->paramInt1 < MAX_GAMEPAD_BUTTONS)) currentGamepadState[msg->paramInt0][msg->paramInt1] = msg->paramChar0; + } break; + case UWP_MSG_SET_GAMEPAD_AXIS: + { + if ((msg->paramInt0 < MAX_GAMEPADS) && (msg->paramInt1 < MAX_GAMEPAD_AXIS)) gamepadAxisState[msg->paramInt0][msg->paramInt1] = msg->paramFloat0; + } break; + case UWP_MSG_SET_DISPLAY_DIMS: + { + displayWidth = msg->paramVector0.x; + displayHeight = msg->paramVector0.y; + } break; + case UWP_MSG_HANDLE_RESIZE: + { + eglQuerySurface(display, surface, EGL_WIDTH, &screenWidth); + eglQuerySurface(display, surface, EGL_HEIGHT, &screenHeight); + + // If window is resized, viewport and projection matrix needs to be re-calculated + rlViewport(0, 0, screenWidth, screenHeight); // Set viewport width and height + rlMatrixMode(RL_PROJECTION); // Switch to PROJECTION matrix + rlLoadIdentity(); // Reset current matrix (PROJECTION) + rlOrtho(0, screenWidth, screenHeight, 0, 0.0f, 1.0f); // Orthographic projection mode with top-left corner at (0,0) + rlMatrixMode(RL_MODELVIEW); // Switch back to MODELVIEW matrix + rlLoadIdentity(); // Reset current matrix (MODELVIEW) + rlClearScreenBuffers(); // Clear screen buffers (color and depth) + + // Window size must be updated to be used on 3D mode to get new aspect ratio (BeginMode3D()) + // NOTE: Be careful! GLFW3 will choose the closest fullscreen resolution supported by current monitor, + // for example, if reescaling back to 800x450 (desired), it could set 720x480 (closest fullscreen supported) + currentWidth = screenWidth; + currentHeight = screenHeight; + + // NOTE: Postprocessing texture is not scaled to new size + + windowResized = true; + + } break; + case UWP_MSG_SET_GAME_TIME: currentTime = msg->paramDouble0; break; + default: break; } DeleteUWPMessage(msg); //Delete, we are done } - -#endif +#endif // defined(PLATFORM_UWP) #if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB) // Mouse input polling diff --git a/src/rlgl.h b/src/rlgl.h index ae92f149..1091f0d1 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -422,8 +422,8 @@ RLAPI void rlTranslatef(float x, float y, float z); // Multiply the current ma RLAPI void rlRotatef(float angleDeg, float x, float y, float z); // Multiply the current matrix by a rotation matrix RLAPI void rlScalef(float x, float y, float z); // Multiply the current matrix by a scaling matrix RLAPI void rlMultMatrixf(float *matf); // Multiply the current matrix by another matrix -RLAPI void rlFrustum(double left, double right, double bottom, double top, double near, double far); -RLAPI void rlOrtho(double left, double right, double bottom, double top, double near, double far); +RLAPI void rlFrustum(double left, double right, double bottom, double top, double znear, double zfar); +RLAPI void rlOrtho(double left, double right, double bottom, double top, double znear, double zfar); RLAPI void rlViewport(int x, int y, int width, int height); // Set the viewport area //------------------------------------------------------------------------------------ @@ -888,14 +888,14 @@ void rlMatrixMode(int mode) } } -void rlFrustum(double left, double right, double bottom, double top, double zNear, double zFar) +void rlFrustum(double left, double right, double bottom, double top, double znear, double zfar) { - glFrustum(left, right, bottom, top, zNear, zFar); + glFrustum(left, right, bottom, top, znear, zfar); } -void rlOrtho(double left, double right, double bottom, double top, double zNear, double zFar) +void rlOrtho(double left, double right, double bottom, double top, double znear, double zfar) { - glOrtho(left, right, bottom, top, zNear, zFar); + glOrtho(left, right, bottom, top, znear, zfar); } void rlPushMatrix(void) { glPushMatrix(); } @@ -1491,7 +1491,6 @@ void rlglInit(int width, int height) GLint numExt = 0; #if defined(GRAPHICS_API_OPENGL_33) - // NOTE: On OpenGL 3.3 VAO and NPOT are supported by default vaoSupported = true; @@ -1504,12 +1503,7 @@ void rlglInit(int width, int height) // NOTE: We don't need to check again supported extensions but we do (GLAD already dealt with that) glGetIntegerv(GL_NUM_EXTENSIONS, &numExt); -#if defined(_MSC_VER) const char **extList = RL_MALLOC(sizeof(const char *)*numExt); -#else - const char *extList[numExt]; -#endif - for (int i = 0; i < numExt; i++) extList[i] = (char *)glGetStringi(GL_EXTENSIONS, i); #elif defined(GRAPHICS_API_OPENGL_ES2) @@ -1523,10 +1517,10 @@ void rlglInit(int width, int height) // NOTE: String could be splitted using strtok() function (string.h) // NOTE: strtok() modifies the passed string, it can not be const - char *extList[512]; // Allocate 512 strings pointers (2 KB) + // Allocate 512 strings pointers (2 KB) + const char **extList = RL_MALLOC(sizeof(const char *)*512); extList[numExt] = strtok(extensionsDup, " "); - while (extList[numExt] != NULL) { numExt++; @@ -1619,9 +1613,7 @@ void rlglInit(int width, int height) if (strcmp(extList[i], (const char *)"GL_EXT_debug_marker") == 0) debugMarkerSupported = true; } -#if defined(_WIN32) && defined(_MSC_VER) && !defined(PLATFORM_UWP) //is this a hotfix? I may need to find out why this is broken RL_FREE(extList); -#endif #if defined(GRAPHICS_API_OPENGL_ES2) if (vaoSupported) TraceLog(LOG_INFO, "[EXTENSION] VAO extension detected, VAO functions initialized successfully"); @@ -1642,11 +1634,8 @@ void rlglInit(int width, int height) if (debugMarkerSupported) TraceLog(LOG_INFO, "[EXTENSION] Debug Marker supported"); - - // Initialize buffers, default shaders and default textures //---------------------------------------------------------- - // Init default white texture unsigned char pixels[4] = { 255, 255, 255, 255 }; // 1 pixel RGBA (4 bytes) defaultTextureId = rlLoadTexture(pixels, 1, 1, UNCOMPRESSED_R8G8B8A8, 1); @@ -4623,6 +4612,6 @@ int GetPixelDataSize(int width, int height, int format) return dataSize; } -#endif +#endif // RLGL_STANDALONE -#endif // RLGL_IMPLEMENTATION \ No newline at end of file +#endif // RLGL_IMPLEMENTATION \ No newline at end of file diff --git a/src/utils.c b/src/utils.c index c886d2a7..52fd0b45 100644 --- a/src/utils.c +++ b/src/utils.c @@ -205,73 +205,64 @@ static int android_close(void *cookie) #if defined(PLATFORM_UWP) -#define MAX_MESSAGES 512 //If there are over 128 messages, I will cry... either way, this may be too much EDIT: Welp, 512 +#define MAX_MESSAGES 512 // If there are over 128 messages, I will cry... either way, this may be too much EDIT: Welp, 512 -static int UWPOutMessageId = -1; //Stores the last index for the message -static UWPMessage* UWPOutMessages[MAX_MESSAGES]; //Messages out to UWP +static int UWPOutMessageId = -1; // Stores the last index for the message +static UWPMessage* UWPOutMessages[MAX_MESSAGES]; // Messages out to UWP -static int UWPInMessageId = -1; //Stores the last index for the message -static UWPMessage* UWPInMessages[MAX_MESSAGES]; //Messages in from UWP +static int UWPInMessageId = -1; // Stores the last index for the message +static UWPMessage* UWPInMessages[MAX_MESSAGES]; // Messages in from UWP UWPMessage* CreateUWPMessage(void) { - UWPMessage* msg = (UWPMessage*)RL_MALLOC(sizeof(UWPMessage)); - msg->Type = None; - Vector2 v0 = {0, 0}; - msg->Vector0 = v0; - msg->Int0 = 0; - msg->Int1 = 0; - msg->Char0 = 0; - msg->Float0 = 0; - msg->Double0 = 0; - msg->Bool0 = false; + UWPMessage *msg = (UWPMessage *)RL_MALLOC(sizeof(UWPMessage)); + msg->type = UWP_MSG_NONE; + Vector2 v0 = { 0, 0 }; + msg->paramVector0 = v0; + msg->paramInt0 = 0; + msg->paramInt1 = 0; + msg->paramChar0 = 0; + msg->paramFloat0 = 0; + msg->paramDouble0 = 0; + msg->paramBool0 = false; return msg; } -void DeleteUWPMessage(UWPMessage* msg) +void DeleteUWPMessage(UWPMessage *msg) { RL_FREE(msg); } bool UWPHasMessages(void) { - return UWPOutMessageId > -1; + return (UWPOutMessageId > -1); } -UWPMessage* UWPGetMessage(void) +UWPMessage *UWPGetMessage(void) { - if (UWPHasMessages()) - { - return UWPOutMessages[UWPOutMessageId--]; - } + if (UWPHasMessages()) return UWPOutMessages[UWPOutMessageId--]; return NULL; } -void UWPSendMessage(UWPMessage* msg) +void UWPSendMessage(UWPMessage *msg) { if (UWPInMessageId + 1 < MAX_MESSAGES) { UWPInMessageId++; UWPInMessages[UWPInMessageId] = msg; } - else - { - TraceLog(LOG_WARNING, "[UWP Messaging] Not enough array space to register new UWP inbound Message."); - } + else TraceLog(LOG_WARNING, "[UWP Messaging] Not enough array space to register new UWP inbound Message."); } -void SendMessageToUWP(UWPMessage* msg) +void SendMessageToUWP(UWPMessage *msg) { if (UWPOutMessageId + 1 < MAX_MESSAGES) { UWPOutMessageId++; UWPOutMessages[UWPOutMessageId] = msg; } - else - { - TraceLog(LOG_WARNING, "[UWP Messaging] Not enough array space to register new UWP outward Message."); - } + else TraceLog(LOG_WARNING, "[UWP Messaging] Not enough array space to register new UWP outward Message."); } bool HasMessageFromUWP(void) @@ -281,12 +272,8 @@ bool HasMessageFromUWP(void) UWPMessage* GetMessageFromUWP(void) { - if (HasMessageFromUWP()) - { - return UWPInMessages[UWPInMessageId--]; - } + if (HasMessageFromUWP()) return UWPInMessages[UWPInMessageId--]; return NULL; } - -#endif +#endif // defined(PLATFORM_UWP) diff --git a/src/utils.h b/src/utils.h index 14e6bf70..1611b02c 100644 --- a/src/utils.h +++ b/src/utils.h @@ -60,79 +60,63 @@ FILE *android_fopen(const char *fileName, const char *mode); // Replacement f #endif #if defined(PLATFORM_UWP) - // UWP Messages System - -typedef enum -{ - None = 0, - - //Send - ShowMouse, - HideMouse, - LockMouse, - UnlockMouse, - SetMouseLocation, //Vector0 (pos) - - //Recieve (Into C) - RegisterKey, //Int0 (key), Char0 (status) - RegisterClick, //Int0 (button), Char0 (status) - ScrollWheelUpdate, //Int0 (delta) - UpdateMouseLocation, //Vector0 (pos) - MarkGamepadActive, //Int0 (gamepad), Bool0 (active or not) - MarkGamepadButton, //Int0 (gamepad), Int1 (button), Char0 (status) - MarkGamepadAxis,//Int0 (gamepad), int1 (axis), Float0 (value) - SetDisplayDims, //Vector0 (display dimensions) - HandleResize, //Vector0 (new dimensions) - Onresized event - SetGameTime, //Int0 +typedef enum { + UWP_MSG_NONE = 0, + + // Send + UWP_MSG_SHOW_MOUSE, + UWP_MSG_HIDE_MOUSE, + UWP_MSG_LOCK_MOUSE, + UWP_MSG_UNLOCK_MOUSE, + UWP_MSG_SET_MOUSE_LOCATION, // paramVector0 (pos) + + // Receive (Into C) + UWP_MSG_REGISTER_KEY, // paramInt0 (key), paramChar0 (status) + UWP_MSG_REGISTER_CLICK, // paramInt0 (button), paramChar0 (status) + UWP_MSG_SCROLL_WHEEL_UPDATE, // paramInt0 (delta) + UWP_MSG_UPDATE_MOUSE_LOCATION, // paramVector0 (pos) + UWP_MSG_SET_GAMEPAD_ACTIVE, // paramInt0 (gamepad), paramBool0 (active or not) + UWP_MSG_SET_GAMEPAD_BUTTON, // paramInt0 (gamepad), paramInt1 (button), paramChar0 (status) + UWP_MSG_SET_GAMEPAD_AXIS, // paramInt0 (gamepad), int1 (axis), paramFloat0 (value) + UWP_MSG_SET_DISPLAY_DIMS, // paramVector0 (display dimensions) + UWP_MSG_HANDLE_RESIZE, // paramVector0 (new dimensions) - Onresized event + UWP_MSG_SET_GAME_TIME, // paramInt0 } UWPMessageType; -typedef struct UWPMessage -{ - //The message type - UWPMessageType Type; - - //Vector parameters - Vector2 Vector0; - - //Int parameters - int Int0; - int Int1; - - //Char parameters - char Char0; - - //Float parameters - float Float0; - - //Double parameters - double Double0; - - //Bool parameters - bool Bool0; - - //More parameters can be added and fed to functions +typedef struct UWPMessage { + UWPMessageType type; // Message type + + Vector2 paramVector0; // Vector parameters + int paramInt0; // Int parameter + int paramInt1; // Int parameter + char paramChar0; // Char parameters + float paramFloat0; // Float parameters + double paramDouble0; // Double parameters + bool paramBool0; // Bool parameters + + // More parameters can be added and fed to functions } UWPMessage; -//Allocate UWP Message +// Allocate UWP Message RLAPI UWPMessage* CreateUWPMessage(void); -//Free UWP Message +// Free UWP Message RLAPI void DeleteUWPMessage(UWPMessage* msg); -//Get messages into C++ +// Get messages into C++ RLAPI bool UWPHasMessages(void); RLAPI UWPMessage* UWPGetMessage(void); RLAPI void UWPSendMessage(UWPMessage* msg); -//For C to call -#ifndef _cplusplus //Hide from C++ code +// For C to call +#ifndef __cplusplus // Hide from C++ code void SendMessageToUWP(UWPMessage* msg); bool HasMessageFromUWP(void); UWPMessage* GetMessageFromUWP(void); #endif -#endif +#endif //defined(PLATFORM_UWP) #ifdef __cplusplus } -- cgit v1.2.3 From 604a8c0b78b6f51abcce61aa0c3db25412acafa7 Mon Sep 17 00:00:00 2001 From: raysan5 Date: Sun, 28 Apr 2019 14:45:46 +0200 Subject: WARNING: Functions renamed Two functions have been renamed for coherence; previous naming was confusing for several users: - DrawPolyEx() ---> DrawTriangleFan() - DrawPolyExLines() ---> DrawLineStrip() --- src/raylib.h | 4 +-- src/shapes.c | 99 ++++++++++++++++++++++++++++++------------------------------ 2 files changed, 52 insertions(+), 51 deletions(-) (limited to 'src') diff --git a/src/raylib.h b/src/raylib.h index 43260e06..c1cebdc8 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -1058,6 +1058,7 @@ RLAPI void DrawLine(int startPosX, int startPosY, int endPosX, int endPosY, Colo RLAPI void DrawLineV(Vector2 startPos, Vector2 endPos, Color color); // Draw a line (Vector version) RLAPI void DrawLineEx(Vector2 startPos, Vector2 endPos, float thick, Color color); // Draw a line defining thickness RLAPI void DrawLineBezier(Vector2 startPos, Vector2 endPos, float thick, Color color); // Draw a line using cubic-bezier curves in-out +RLAPI void DrawLineStrip(Vector2 *points, int numPoints, Color color); // Draw lines sequence RLAPI void DrawCircle(int centerX, int centerY, float radius, Color color); // Draw a color-filled circle RLAPI void DrawCircleSector(Vector2 center, float radius, int startAngle, int endAngle, int segments, Color color); // Draw a piece of a circle RLAPI void DrawCircleSectorLines(Vector2 center, float radius, int startAngle, int endAngle, int segments, Color color); // Draw circle sector outline @@ -1079,9 +1080,8 @@ RLAPI void DrawRectangleRounded(Rectangle rec, float roundness, int segments, Co RLAPI void DrawRectangleRoundedLines(Rectangle rec, float roundness, int segments, int lineThick, Color color); // Draw rectangle with rounded edges outline RLAPI void DrawTriangle(Vector2 v1, Vector2 v2, Vector2 v3, Color color); // Draw a color-filled triangle RLAPI void DrawTriangleLines(Vector2 v1, Vector2 v2, Vector2 v3, Color color); // Draw triangle outline +RLAPI void DrawTriangleFan(Vector2 *points, int numPoints, Color color); // Draw a triangle fan defined by points RLAPI void DrawPoly(Vector2 center, int sides, float radius, float rotation, Color color); // Draw a regular polygon (Vector version) -RLAPI void DrawPolyEx(Vector2 *points, int numPoints, Color color); // Draw a closed polygon defined by points -RLAPI void DrawPolyExLines(Vector2 *points, int numPoints, Color color); // Draw polygon lines RLAPI void SetShapesTexture(Texture2D texture, Rectangle source); // Define default texture used to draw shapes diff --git a/src/shapes.c b/src/shapes.c index ecef287c..93b332f5 100644 --- a/src/shapes.c +++ b/src/shapes.c @@ -176,6 +176,25 @@ void DrawLineBezier(Vector2 startPos, Vector2 endPos, float thick, Color color) } } +// Draw lines sequence +void DrawLineStrip(Vector2 *points, int pointsCount, Color color) +{ + if (pointsCount >= 2) + { + if (rlCheckBufferLimit(pointsCount)) rlglDraw(); + + rlBegin(RL_LINES); + rlColor4ub(color.r, color.g, color.b, color.a); + + for (int i = 0; i < pointsCount - 1; i++) + { + rlVertex2f(points[i].x, points[i].y); + rlVertex2f(points[i + 1].x, points[i + 1].y); + } + rlEnd(); + } +} + // Draw a color-filled circle void DrawCircle(int centerX, int centerY, float radius, Color color) { @@ -1208,6 +1227,37 @@ void DrawTriangleLines(Vector2 v1, Vector2 v2, Vector2 v3, Color color) rlEnd(); } +// Draw a triangle fan defined by points +// NOTE: First point provided is shared by all triangles +void DrawTriangleFan(Vector2 *points, int pointsCount, Color color) +{ + if (pointsCount >= 3) + { + if (rlCheckBufferLimit((pointsCount - 2)*4)) rlglDraw(); + + rlEnableTexture(GetShapesTexture().id); + rlBegin(RL_QUADS); + rlColor4ub(color.r, color.g, color.b, color.a); + + for (int i = 1; i < pointsCount - 1; i++) + { + rlTexCoord2f(recTexShapes.x/texShapes.width, recTexShapes.y/texShapes.height); + rlVertex2f(points[0].x, points[0].y); + + rlTexCoord2f(recTexShapes.x/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); + rlVertex2f(points[i].x, points[i].y); + + rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); + rlVertex2f(points[i + 1].x, points[i + 1].y); + + rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, recTexShapes.y/texShapes.height); + rlVertex2f(points[i + 1].x, points[i + 1].y); + } + rlEnd(); + rlDisableTexture(); + } +} + // Draw a regular polygon of n sides (Vector version) void DrawPoly(Vector2 center, int sides, float radius, float rotation, Color color) { @@ -1256,55 +1306,6 @@ void DrawPoly(Vector2 center, int sides, float radius, float rotation, Color col rlPopMatrix(); } -// Draw a closed polygon defined by points -void DrawPolyEx(Vector2 *points, int pointsCount, Color color) -{ - if (pointsCount >= 3) - { - if (rlCheckBufferLimit((pointsCount - 2)*4)) rlglDraw(); - - rlEnableTexture(GetShapesTexture().id); - rlBegin(RL_QUADS); - rlColor4ub(color.r, color.g, color.b, color.a); - - for (int i = 1; i < pointsCount - 1; i++) - { - rlTexCoord2f(recTexShapes.x/texShapes.width, recTexShapes.y/texShapes.height); - rlVertex2f(points[0].x, points[0].y); - - rlTexCoord2f(recTexShapes.x/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); - rlVertex2f(points[i].x, points[i].y); - - rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, (recTexShapes.y + recTexShapes.height)/texShapes.height); - rlVertex2f(points[i + 1].x, points[i + 1].y); - - rlTexCoord2f((recTexShapes.x + recTexShapes.width)/texShapes.width, recTexShapes.y/texShapes.height); - rlVertex2f(points[i + 1].x, points[i + 1].y); - } - rlEnd(); - rlDisableTexture(); - } -} - -// Draw polygon using lines -void DrawPolyExLines(Vector2 *points, int pointsCount, Color color) -{ - if (pointsCount >= 2) - { - if (rlCheckBufferLimit(pointsCount)) rlglDraw(); - - rlBegin(RL_LINES); - rlColor4ub(color.r, color.g, color.b, color.a); - - for (int i = 0; i < pointsCount - 1; i++) - { - rlVertex2f(points[i].x, points[i].y); - rlVertex2f(points[i + 1].x, points[i + 1].y); - } - rlEnd(); - } -} - // Define default texture used to draw shapes void SetShapesTexture(Texture2D texture, Rectangle source) { -- cgit v1.2.3 From 7c10f971c1f8edfc65b074aceec7c3a0696c9b87 Mon Sep 17 00:00:00 2001 From: raysan5 Date: Sun, 28 Apr 2019 16:03:59 +0200 Subject: Expose enable/disable backface culling Some tweaks on BeginVrDrawing() --- src/rlgl.h | 33 +++++++++++++++++++++------------ 1 file changed, 21 insertions(+), 12 deletions(-) (limited to 'src') diff --git a/src/rlgl.h b/src/rlgl.h index 1091f0d1..b067e5c7 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -451,6 +451,8 @@ RLAPI void rlEnableRenderTexture(unsigned int id); // Enable render t RLAPI void rlDisableRenderTexture(void); // Disable render texture (fbo), return to default framebuffer RLAPI void rlEnableDepthTest(void); // Enable depth test RLAPI void rlDisableDepthTest(void); // Disable depth test +RLAPI void rlEnableBackfaceCulling(void); // Enable backface culling +RLAPI void rlDisableBackfaceCulling(void); // Disable backface culling RLAPI void rlEnableWireMode(void); // Enable wire mode RLAPI void rlDisableWireMode(void); // Disable wire mode RLAPI void rlDeleteTextures(unsigned int id); // Delete OpenGL texture from GPU @@ -1345,6 +1347,18 @@ void rlDisableDepthTest(void) glDisable(GL_DEPTH_TEST); } +// Enable backface culling +void rlEnableBackfaceCulling(void) +{ + glEnable(GL_CULL_FACE); +} + +// Disable backface culling +void rlDisableBackfaceCulling(void) +{ + glDisable(GL_CULL_FACE); +} + // Enable wire mode void rlEnableWireMode(void) { @@ -3657,30 +3671,25 @@ void ToggleVrMode(void) #endif } -// Begin Oculus drawing configuration +// Begin VR drawing configuration void BeginVrDrawing(void) { #if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) if (vrSimulatorReady) { - // Setup framebuffer for stereo rendering - rlEnableRenderTexture(stereoFbo.id); - - // NOTE: If your application is configured to treat the texture as a linear format (e.g. GL_RGBA) - // and performs linear-to-gamma conversion in GLSL or does not care about gamma-correction, then: - // - Require OculusBuffer format to be OVR_FORMAT_R8G8B8A8_UNORM_SRGB - // - Do NOT enable GL_FRAMEBUFFER_SRGB - //glEnable(GL_FRAMEBUFFER_SRGB); + + rlEnableRenderTexture(stereoFbo.id); // Setup framebuffer for stereo rendering + //glEnable(GL_FRAMEBUFFER_SRGB); // Enable SRGB framebuffer (only if required) - //glViewport(0, 0, buffer.width, buffer.height); // Useful if rendering to separate framebuffers (every eye) - rlClearScreenBuffers(); // Clear current framebuffer(s) + //glViewport(0, 0, buffer.width, buffer.height); // Useful if rendering to separate framebuffers (every eye) + rlClearScreenBuffers(); // Clear current framebuffer vrStereoRender = true; } #endif } -// End Oculus drawing process (and desktop mirror) +// End VR drawing process (and desktop mirror) void EndVrDrawing(void) { #if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) -- cgit v1.2.3 From 40940f439860b3345198dc44cd493f0c0dc12f7c Mon Sep 17 00:00:00 2001 From: raysan5 Date: Sun, 28 Apr 2019 16:45:23 +0200 Subject: Some formatting review --- src/core.c | 67 ++++++++++++++++++++++++++++--------------------------------- src/rlgl.h | 16 +++++++-------- src/utils.c | 10 ++++----- 3 files changed, 44 insertions(+), 49 deletions(-) (limited to 'src') diff --git a/src/core.c b/src/core.c index 2a8f2e3a..1273a057 100644 --- a/src/core.c +++ b/src/core.c @@ -476,12 +476,13 @@ static EM_BOOL EmscriptenGamepadCallback(int eventType, const EmscriptenGamepadE #endif #if defined(PLATFORM_RPI) +static void InitEvdevInput(void); // Evdev inputs initialization +static void EventThreadSpawn(char *device); // Identifies a input device and spawns a thread to handle it if needed +static void *EventThread(void *arg); // Input device events reading thread + static void InitKeyboard(void); // Init raw keyboard system (standard input reading) static void ProcessKeyboard(void); // Process keyboard events static void RestoreKeyboard(void); // Restore keyboard system -static void InitEvdevInput(void); // Mouse initialization (including mouse thread) -static void EventThreadSpawn(char *device); // Identifies a input device and spawns a thread to handle it if needed -static void *EventThread(void *arg); // Input device events reading thread static void InitGamepad(void); // Init raw gamepad input static void *GamepadThread(void *arg); // Mouse reading thread #endif @@ -595,7 +596,7 @@ void InitWindow(int width, int height, const char *title) #if defined(PLATFORM_RPI) // Init raw input system - InitEvdevInput(); // Mouse init + InitEvdevInput(); // Evdev inputs initialization InitKeyboard(); // Keyboard init InitGamepad(); // Gamepad init #endif @@ -629,7 +630,7 @@ void InitWindow(int width, int height, const char *title) SetTargetFPS(60); LogoAnimation(); } -#endif // defined(PLATFORM_ANDROID) +#endif // PLATFORM_ANDROID } // Close window and unload OpenGL context @@ -2369,12 +2370,12 @@ static bool InitGraphicsDevice(int width, int height) // Screen size security check if (screenWidth <= 0) screenWidth = displayWidth; if (screenHeight <= 0) screenHeight = displayHeight; -#endif // defined(PLATFORM_DESKTOP) +#endif // PLATFORM_DESKTOP #if defined(PLATFORM_WEB) displayWidth = screenWidth; displayHeight = screenHeight; -#endif // defined(PLATFORM_WEB) +#endif // PLATFORM_WEB glfwDefaultWindowHints(); // Set default windows hints: //glfwWindowHint(GLFW_RED_BITS, 8); // Framebuffer red color component bits @@ -2552,7 +2553,7 @@ static bool InitGraphicsDevice(int width, int height) glfwSwapInterval(1); TraceLog(LOG_INFO, "Trying to enable VSYNC"); } -#endif // defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB) +#endif // PLATFORM_DESKTOP || PLATFORM_WEB #if defined(PLATFORM_ANDROID) || defined(PLATFORM_RPI) || defined(PLATFORM_UWP) fullscreen = true; @@ -2819,7 +2820,7 @@ static bool InitGraphicsDevice(int width, int height) //ANativeWindow_setBuffersGeometry(androidApp->window, 0, 0, displayFormat); // Force use of native display size surface = eglCreateWindowSurface(display, config, androidApp->window, NULL); -#endif // defined(PLATFORM_ANDROID) +#endif // PLATFORM_ANDROID #if defined(PLATFORM_RPI) graphics_get_display_size(0, &displayWidth, &displayHeight); @@ -2859,7 +2860,8 @@ static bool InitGraphicsDevice(int width, int height) surface = eglCreateWindowSurface(display, config, &nativeWindow, NULL); //--------------------------------------------------------------------------------- -#endif // defined(PLATFORM_RPI) +#endif // PLATFORM_RPI + // There must be at least one frame displayed before the buffers are swapped //eglSwapInterval(display, 1); @@ -2880,7 +2882,7 @@ static bool InitGraphicsDevice(int width, int height) TraceLog(LOG_INFO, "Screen size: %i x %i", screenWidth, screenHeight); TraceLog(LOG_INFO, "Viewport offsets: %i, %i", renderOffsetX, renderOffsetY); } -#endif // defined(PLATFORM_ANDROID) || defined(PLATFORM_RPI) +#endif // PLATFORM_ANDROID || PLATFORM_RPI renderWidth = screenWidth; renderHeight = screenHeight; @@ -3103,7 +3105,7 @@ static void PollInputEvents(void) for (int i = 0; i < 512; i++)previousKeyState[i] = currentKeyState[i]; // Grab a keypress from the evdev fifo if avalable - if(lastKeyPressedEvdev.Head != lastKeyPressedEvdev.Tail) + if (lastKeyPressedEvdev.Head != lastKeyPressedEvdev.Tail) { lastKeyPressed = lastKeyPressedEvdev.Contents[lastKeyPressedEvdev.Tail]; // Read the key from the buffer lastKeyPressedEvdev.Tail = (lastKeyPressedEvdev.Tail + 1) & 0x07; // Increment the tail pointer forwards and binary wraparound after 7 (fifo is 8 elements long) @@ -3267,7 +3269,7 @@ static void PollInputEvents(void) DeleteUWPMessage(msg); //Delete, we are done } -#endif // defined(PLATFORM_UWP) +#endif // PLATFORM_UWP #if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB) // Mouse input polling @@ -3414,12 +3416,11 @@ static void PollInputEvents(void) #endif #if defined(PLATFORM_RPI) - // NOTE: Mouse input events polling is done asynchonously in another pthread - EventThread() - // NOTE: Keyboard reading could be done using input_event(s) reading or just read from stdin, // we now use both methods inside here. 2nd method is still used for legacy purposes (Allows for input trough SSH console) ProcessKeyboard(); + // NOTE: Mouse input events polling is done asynchronously in another pthread - EventThread() // NOTE: Gamepad (Joystick) input events polling is done asynchonously in another pthread - GamepadThread() #endif } @@ -4244,6 +4245,7 @@ static void InitEvdevInput(void) // Open the linux directory of "/dev/input" directory = opendir(DEFAULT_EVDEV_PATH); + if (directory) { while ((entity = readdir(directory)) != NULL) @@ -4460,9 +4462,10 @@ static void EventThreadSpawn(char *device) static void *EventThread(void *arg) { // Scancode to keycode mapping for US keyboards - // TODO: Proabobly replace this with a keymap from the X11 to get the correct regional map for the keyboard (Currently non US keyboards will have the wrong mapping for some keys) + // TODO: Probably replace this with a keymap from the X11 to get the correct regional map for the keyboard: + // Currently non US keyboards will have the wrong mapping for some keys static const int keymap_US[] = - {0,256,49,50,51,52,53,54,55,56,57,48,45,61,259,258,81,87,69,82,84, + { 0,256,49,50,51,52,53,54,55,56,57,48,45,61,259,258,81,87,69,82,84, 89,85,73,79,80,91,93,257,341,65,83,68,70,71,72,74,75,76,59,39,96, 340,92,90,88,67,86,66,78,77,44,46,47,344,332,342,32,280,290,291, 292,293,294,295,296,297,298,299,282,281,327,328,329,333,324,325, @@ -4476,7 +4479,7 @@ static void *EventThread(void *arg) 192,193,194,0,0,0,0,0,200,201,202,203,204,205,206,207,208,209,210, 211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226, 227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242, - 243,244,245,246,247,248,0,0,0,0,0,0,0,}; + 243,244,245,246,247,248,0,0,0,0,0,0,0, }; struct input_event event; InputEventWorker *worker = (InputEventWorker *)arg; @@ -4515,10 +4518,7 @@ static void *EventThread(void *arg) #endif } - if (event.code == REL_WHEEL) - { - currentMouseWheelY += event.value; - } + if (event.code == REL_WHEEL) currentMouseWheelY += event.value; } // Absolute movement parsing @@ -4546,26 +4546,21 @@ static void *EventThread(void *arg) } // Multitouch movement - if (event.code == ABS_MT_SLOT) - { - worker->touchSlot = event.value; // Remeber the slot number for the folowing events - } + if (event.code == ABS_MT_SLOT) worker->touchSlot = event.value; // Remeber the slot number for the folowing events if (event.code == ABS_MT_POSITION_X) { - if (worker->touchSlot < MAX_TOUCH_POINTS) - touchPosition[worker->touchSlot].x = (event.value - worker->absRange.x)*screenWidth/worker->absRange.width; // Scale acording to absRange + if (worker->touchSlot < MAX_TOUCH_POINTS) touchPosition[worker->touchSlot].x = (event.value - worker->absRange.x)*screenWidth/worker->absRange.width; // Scale acording to absRange } if (event.code == ABS_MT_POSITION_Y) { - if (worker->touchSlot < MAX_TOUCH_POINTS) - touchPosition[worker->touchSlot].y = (event.value - worker->absRange.y)*screenHeight/worker->absRange.height; // Scale acording to absRange + if (worker->touchSlot < MAX_TOUCH_POINTS) touchPosition[worker->touchSlot].y = (event.value - worker->absRange.y)*screenHeight/worker->absRange.height; // Scale acording to absRange } if (event.code == ABS_MT_TRACKING_ID) { - if ( (event.value < 0) && (worker->touchSlot < MAX_TOUCH_POINTS) ) + if ((event.value < 0) && (worker->touchSlot < MAX_TOUCH_POINTS)) { // Touch has ended for this point touchPosition[worker->touchSlot].x = -1; @@ -4577,7 +4572,6 @@ static void *EventThread(void *arg) // Button parsing if (event.type == EV_KEY) { - // Mouse button parsing if ((event.code == BTN_TOUCH) || (event.code == BTN_LEFT)) { @@ -4595,25 +4589,26 @@ static void *EventThread(void *arg) if (event.code == BTN_MIDDLE) currentMouseStateEvdev[MOUSE_MIDDLE_BUTTON] = event.value; // Keyboard button parsing - if((event.code >= 1) && (event.code <= 255)) //Keyboard keys appear for codes 1 to 255 + if ((event.code >= 1) && (event.code <= 255)) //Keyboard keys appear for codes 1 to 255 { keycode = keymap_US[event.code & 0xFF]; // The code we get is a scancode so we look up the apropriate keycode + // Make sure we got a valid keycode - if((keycode > 0) && (keycode < sizeof(currentKeyState))) + if ((keycode > 0) && (keycode < sizeof(currentKeyState))) { // Store the key information for raylib to later use currentKeyStateEvdev[keycode] = event.value; - if(event.value > 0) + if (event.value > 0) { // Add the key int the fifo lastKeyPressedEvdev.Contents[lastKeyPressedEvdev.Head] = keycode; // Put the data at the front of the fifo snake lastKeyPressedEvdev.Head = (lastKeyPressedEvdev.Head + 1) & 0x07; // Increment the head pointer forwards and binary wraparound after 7 (fifo is 8 elements long) // TODO: This fifo is not fully threadsafe with multiple writers, so multiple keyboards hitting a key at the exact same time could miss a key (double write to head before it was incremented) } + TraceLog(LOG_DEBUG, "KEY%s ScanCode: %4i KeyCode: %4i",event.value == 0 ? "UP":"DOWN", event.code, keycode); } } - } // Screen confinement diff --git a/src/rlgl.h b/src/rlgl.h index b067e5c7..e98c6dc3 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -831,9 +831,9 @@ static RenderTexture2D stereoFbo; // VR stereo rendering framebuffer static bool vrSimulatorReady = false; // VR simulator ready flag static bool vrStereoRender = false; // VR stereo rendering enabled/disabled flag // NOTE: This flag is useful to render data over stereo image (i.e. FPS) -#endif // defined(SUPPORT_VR_SIMULATOR) +#endif // SUPPORT_VR_SIMULATOR -#endif // defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) +#endif // GRAPHICS_API_OPENGL_33 || GRAPHICS_API_OPENGL_ES2 static int blendMode = 0; // Track current blending mode @@ -864,7 +864,7 @@ static void GenDrawQuad(void); // Generate and draw quad static void SetStereoView(int eye, Matrix matProjection, Matrix matModelView); // Set internal projection and modelview matrix depending on eye #endif -#endif // defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) +#endif // GRAPHICS_API_OPENGL_33 || GRAPHICS_API_OPENGL_ES2 #if defined(GRAPHICS_API_OPENGL_11) static int GenerateMipmaps(unsigned char *data, int baseWidth, int baseHeight); @@ -1691,7 +1691,7 @@ void rlglInit(int width, int height) projection = MatrixIdentity(); modelview = MatrixIdentity(); currentMatrix = &modelview; -#endif // defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) +#endif // GRAPHICS_API_OPENGL_33 || GRAPHICS_API_OPENGL_ES2 // Initialize OpenGL default states //---------------------------------------------------------- @@ -1883,11 +1883,11 @@ unsigned int rlLoadTexture(void *data, int width, int height, int format, int mi return id; } #endif -#endif // defined(GRAPHICS_API_OPENGL_11) +#endif // GRAPHICS_API_OPENGL_11 glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - glGenTextures(1, &id); // Generate Pointer to the texture + glGenTextures(1, &id); // Generate texture id #if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) //glActiveTexture(GL_TEXTURE0); // If not defined, using GL_TEXTURE0 by default (shader texture) @@ -4428,9 +4428,9 @@ static void SetStereoView(int eye, Matrix matProjection, Matrix matModelView) SetMatrixModelview(eyeModelView); SetMatrixProjection(eyeProjection); } -#endif // defined(SUPPORT_VR_SIMULATOR) +#endif // SUPPORT_VR_SIMULATOR -#endif //defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) +#endif // GRAPHICS_API_OPENGL_33 || GRAPHICS_API_OPENGL_ES2 #if defined(GRAPHICS_API_OPENGL_11) // Mipmaps data is generated after image data diff --git a/src/utils.c b/src/utils.c index 52fd0b45..ee4be46d 100644 --- a/src/utils.c +++ b/src/utils.c @@ -34,7 +34,7 @@ // Check if config flags have been externally provided on compilation line #if !defined(EXTERNAL_CONFIG_FLAGS) - #include "config.h" // Defines module configuration flags + #include "config.h" // Defines module configuration flags #endif #include "utils.h" @@ -69,7 +69,7 @@ AAssetManager *assetManager; // Module specific Functions Declaration //---------------------------------------------------------------------------------- #if defined(PLATFORM_ANDROID) -/* This should be in , but Travis doesn't find it... */ +// This should be in , but Travis does not find it... FILE *funopen(const void *cookie, int (*readfn)(void *, char *, int), int (*writefn)(void *, const char *, int), fpos_t (*seekfn)(void *, fpos_t, int), int (*closefn)(void *)); @@ -173,7 +173,7 @@ FILE *android_fopen(const char *fileName, const char *mode) return funopen(asset, android_read, android_write, android_seek, android_close); } -#endif +#endif // PLATFORM_ANDROID //---------------------------------------------------------------------------------- // Module specific Functions Definition @@ -201,7 +201,7 @@ static int android_close(void *cookie) AAsset_close((AAsset *)cookie); return 0; } -#endif +#endif // PLATFORM_ANDROID #if defined(PLATFORM_UWP) @@ -276,4 +276,4 @@ UWPMessage* GetMessageFromUWP(void) return NULL; } -#endif // defined(PLATFORM_UWP) +#endif // PLATFORM_UWP -- cgit v1.2.3 From 7ca856f9b76e7e9eac49120d145f89c2fc639c38 Mon Sep 17 00:00:00 2001 From: Reece Mackie <20544390+Rover656@users.noreply.github.com> Date: Sun, 28 Apr 2019 15:59:39 +0100 Subject: Formatting changes --- src/core.c | 35 ++++++----------------------------- src/raylib.h | 19 ++++++++++--------- 2 files changed, 16 insertions(+), 38 deletions(-) (limited to 'src') diff --git a/src/core.c b/src/core.c index ec7586df..4bb1e76f 100644 --- a/src/core.c +++ b/src/core.c @@ -3110,34 +3110,11 @@ static GamepadButton GetGamepadButton(int button) #endif #if defined(PLATFORM_UWP) - /*switch(button) - { - case 4: b = GAMEPAD_BUTTON_RIGHT_FACE_DOWN; break; - case 8: b = GAMEPAD_BUTTON_RIGHT_FACE_RIGHT; break; - case 16: b = GAMEPAD_BUTTON_RIGHT_FACE_LEFT; break; - case 32: b = GAMEPAD_BUTTON_RIGHT_FACE_RIGHT; break; - - case 128: b = GAMEPAD_BUTTON_LEFT_FACE_DOWN; break; - case 256: b = GAMEPAD_BUTTON_LEFT_FACE_LEFT; break; - case 512: b = GAMEPAD_BUTTON_LEFT_FACE_RIGHT; break; - case 64: b = GAMEPAD_BUTTON_LEFT_FACE_UP; break; - - case 1024: b = GAMEPAD_BUTTON_LEFT_TRIGGER_1; break; - case 2048: b = GAMEPAD_BUTTON_RIGHT_TRIGGER_1; break; - - case 4096: b = GAMEPAD_BUTTON_LEFT_THUMB; break; - case 8192: b = GAMEPAD_BUTTON_RIGHT_THUMB; break; - - case 2: b = GAMEPAD_BUTTON_MIDDLE_LEFT; - case 1: b = GAMEPAD_BUTTON_MIDDLE_RIGHT; - }*/ - //Above might not be most efficient, so not doing it for now b = button; #endif #if defined(PLATFORM_WEB) - //TODO: TEST - //https://www.w3.org/TR/gamepad/#gamepad-interface + // https://www.w3.org/TR/gamepad/#gamepad-interface switch (button) { case 0: b = GAMEPAD_BUTTON_RIGHT_FACE_DOWN; break; @@ -3178,11 +3155,11 @@ static GamepadAxis GetGamepadAxis(int axis) #endif #if defined(PLATFORM_UWP) - a = axis; //UWP will provide the correct axis + a = axis; // UWP will provide the correct axis #endif #if defined(PLATFORM_WEB) - //TODO: TEST + // https://www.w3.org/TR/gamepad/#gamepad-interface switch(axis) { case 0: a = GAMEPAD_AXIS_LEFT_X; @@ -3430,9 +3407,9 @@ static void PollInputEvents(void) // Get current gamepad state // NOTE: There is no callback available, so we get it manually - //Get remapped buttons + // Get remapped buttons GLFWgamepadstate state; - glfwGetGamepadState(i, &state); //This remapps all gamepads so they work the same + glfwGetGamepadState(i, &state); // This remapps all gamepads so they have their buttons mapped like an xbox controller const unsigned char *buttons = state.buttons; for (int k = 0; (buttons != NULL) && (k < GLFW_GAMEPAD_BUTTON_DPAD_LEFT + 1) && (k < MAX_GAMEPAD_BUTTONS); k++) @@ -3456,7 +3433,7 @@ static void PollInputEvents(void) gamepadAxisState[i][axis] = axes[k]; } - //Register buttons for 2nd triggers + // Register buttons for 2nd triggers (because GLFW doesn't count these as buttons but rather axis) currentGamepadState[i][GAMEPAD_BUTTON_LEFT_TRIGGER_2] = (char)(gamepadAxisState[i][GAMEPAD_AXIS_LEFT_TRIGGER] > 0.1); currentGamepadState[i][GAMEPAD_BUTTON_RIGHT_TRIGGER_2] = (char)(gamepadAxisState[i][GAMEPAD_AXIS_RIGHT_TRIGGER] > 0.1); diff --git a/src/raylib.h b/src/raylib.h index cf8543a2..3fb4ee6d 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -622,50 +622,51 @@ typedef enum { // Gamepad Buttons typedef enum { - //This is here just for error checking + // This is here just for error checking GAMEPAD_BUTTON_UNKNOWN = 0, - //This is normally ABXY/Circle, Triangle, Square, Cross. No support for 6 button controllers though.. + // This is normally ABXY/Circle, Triangle, Square, Cross. No support for 6 button controllers though.. GAMEPAD_BUTTON_LEFT_FACE_UP, GAMEPAD_BUTTON_LEFT_FACE_RIGHT, GAMEPAD_BUTTON_LEFT_FACE_DOWN, GAMEPAD_BUTTON_LEFT_FACE_LEFT, - //This is normally a DPAD + // This is normally a DPAD GAMEPAD_BUTTON_RIGHT_FACE_UP, GAMEPAD_BUTTON_RIGHT_FACE_RIGHT, GAMEPAD_BUTTON_RIGHT_FACE_DOWN, GAMEPAD_BUTTON_RIGHT_FACE_LEFT, - //Triggers + // Triggers GAMEPAD_BUTTON_LEFT_TRIGGER_1, GAMEPAD_BUTTON_LEFT_TRIGGER_2, GAMEPAD_BUTTON_RIGHT_TRIGGER_1, GAMEPAD_BUTTON_RIGHT_TRIGGER_2, - //These are buttons in the center of the gamepad + // These are buttons in the center of the gamepad GAMEPAD_BUTTON_MIDDLE_LEFT, //PS3 Select GAMEPAD_BUTTON_MIDDLE, //PS Button/XBOX Button GAMEPAD_BUTTON_MIDDLE_RIGHT, //PS3 Start - //These are the joystick press in buttons + // These are the joystick press in buttons GAMEPAD_BUTTON_LEFT_THUMB, GAMEPAD_BUTTON_RIGHT_THUMB } GamepadButton; typedef enum { + // This is here just for error checking GAMEPAD_AXIS_UNKNOWN = 0, - //Left stick + // Left stick GAMEPAD_AXIS_LEFT_X, GAMEPAD_AXIS_LEFT_Y, - //Right stick + // Right stick GAMEPAD_AXIS_RIGHT_X, GAMEPAD_AXIS_RIGHT_Y, - //Pressure levels + // Pressure levels for the back triggers GAMEPAD_AXIS_LEFT_TRIGGER, // [1..-1] (pressure-level) GAMEPAD_AXIS_RIGHT_TRIGGER // [1..-1] (pressure-level) } GamepadAxis; -- cgit v1.2.3 From 3244ec2a1d151dfd84e6145a9e9b4ce744cbc23e Mon Sep 17 00:00:00 2001 From: Reece Mackie <20544390+Rover656@users.noreply.github.com> Date: Sun, 28 Apr 2019 16:03:23 +0100 Subject: Add another UWP comment for clarity --- src/core.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/core.c b/src/core.c index 4bb1e76f..5eed81c9 100644 --- a/src/core.c +++ b/src/core.c @@ -3110,7 +3110,7 @@ static GamepadButton GetGamepadButton(int button) #endif #if defined(PLATFORM_UWP) - b = button; + b = button; // UWP will provide the correct button #endif #if defined(PLATFORM_WEB) -- cgit v1.2.3 From d42965b0b02247f9b2581d3b7ba6e9ea47ddfcd6 Mon Sep 17 00:00:00 2001 From: Reece Mackie <20544390+Rover656@users.noreply.github.com> Date: Sun, 28 Apr 2019 16:05:45 +0100 Subject: Fix tabs --- src/core.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/core.c b/src/core.c index 5eed81c9..fb1f4f1a 100644 --- a/src/core.c +++ b/src/core.c @@ -3324,9 +3324,9 @@ static void PollInputEvents(void) { if ((msg->paramInt0 < MAX_GAMEPADS) && (msg->paramInt1 < MAX_GAMEPAD_AXIS)) gamepadAxisState[msg->paramInt0][msg->paramInt1] = msg->paramFloat0; - // Register buttons for 2nd triggers - currentGamepadState[msg->paramInt0][GAMEPAD_BUTTON_LEFT_TRIGGER_2] = (char)(gamepadAxisState[msg->paramInt0][GAMEPAD_AXIS_LEFT_TRIGGER] > 0.1); - currentGamepadState[msg->paramInt0][GAMEPAD_BUTTON_RIGHT_TRIGGER_2] = (char)(gamepadAxisState[msg->paramInt0][GAMEPAD_AXIS_RIGHT_TRIGGER] > 0.1); + // Register buttons for 2nd triggers + currentGamepadState[msg->paramInt0][GAMEPAD_BUTTON_LEFT_TRIGGER_2] = (char)(gamepadAxisState[msg->paramInt0][GAMEPAD_AXIS_LEFT_TRIGGER] > 0.1); + currentGamepadState[msg->paramInt0][GAMEPAD_BUTTON_RIGHT_TRIGGER_2] = (char)(gamepadAxisState[msg->paramInt0][GAMEPAD_AXIS_RIGHT_TRIGGER] > 0.1); } break; case UWP_MSG_SET_DISPLAY_DIMS: { -- cgit v1.2.3 From e69688437a33dbc15a2a7e143ad76e524184ff03 Mon Sep 17 00:00:00 2001 From: Reece Mackie <20544390+Rover656@users.noreply.github.com> Date: Sun, 28 Apr 2019 16:06:56 +0100 Subject: Why does visual studio keep using tabs!!! --- src/core.c | 114 ++++++++++++++++++++++++++++++------------------------------- 1 file changed, 57 insertions(+), 57 deletions(-) (limited to 'src') diff --git a/src/core.c b/src/core.c index fb1f4f1a..1dc27050 100644 --- a/src/core.c +++ b/src/core.c @@ -3083,93 +3083,93 @@ static bool GetMouseButtonStatus(int button) static GamepadButton GetGamepadButton(int button) { - GamepadButton b = GAMEPAD_BUTTON_UNKNOWN; + GamepadButton b = GAMEPAD_BUTTON_UNKNOWN; #if defined(PLATFORM_DESKTOP) switch (button) { - case GLFW_GAMEPAD_BUTTON_Y: b = GAMEPAD_BUTTON_RIGHT_FACE_UP; break; - case GLFW_GAMEPAD_BUTTON_B: b = GAMEPAD_BUTTON_RIGHT_FACE_RIGHT; break; - case GLFW_GAMEPAD_BUTTON_A: b = GAMEPAD_BUTTON_RIGHT_FACE_DOWN; break; - case GLFW_GAMEPAD_BUTTON_X: b = GAMEPAD_BUTTON_RIGHT_FACE_LEFT; break; + case GLFW_GAMEPAD_BUTTON_Y: b = GAMEPAD_BUTTON_RIGHT_FACE_UP; break; + case GLFW_GAMEPAD_BUTTON_B: b = GAMEPAD_BUTTON_RIGHT_FACE_RIGHT; break; + case GLFW_GAMEPAD_BUTTON_A: b = GAMEPAD_BUTTON_RIGHT_FACE_DOWN; break; + case GLFW_GAMEPAD_BUTTON_X: b = GAMEPAD_BUTTON_RIGHT_FACE_LEFT; break; - case GLFW_GAMEPAD_BUTTON_LEFT_BUMPER: b = GAMEPAD_BUTTON_LEFT_TRIGGER_1; break; - case GLFW_GAMEPAD_BUTTON_RIGHT_BUMPER: b = GAMEPAD_BUTTON_RIGHT_TRIGGER_1; break; + case GLFW_GAMEPAD_BUTTON_LEFT_BUMPER: b = GAMEPAD_BUTTON_LEFT_TRIGGER_1; break; + case GLFW_GAMEPAD_BUTTON_RIGHT_BUMPER: b = GAMEPAD_BUTTON_RIGHT_TRIGGER_1; break; - case GLFW_GAMEPAD_BUTTON_BACK: b = GAMEPAD_BUTTON_MIDDLE_LEFT; break; - case GLFW_GAMEPAD_BUTTON_GUIDE: b = GAMEPAD_BUTTON_MIDDLE; break; - case GLFW_GAMEPAD_BUTTON_START: b = GAMEPAD_BUTTON_MIDDLE_RIGHT; break; + case GLFW_GAMEPAD_BUTTON_BACK: b = GAMEPAD_BUTTON_MIDDLE_LEFT; break; + case GLFW_GAMEPAD_BUTTON_GUIDE: b = GAMEPAD_BUTTON_MIDDLE; break; + case GLFW_GAMEPAD_BUTTON_START: b = GAMEPAD_BUTTON_MIDDLE_RIGHT; break; - case GLFW_GAMEPAD_BUTTON_DPAD_UP: b = GAMEPAD_BUTTON_LEFT_FACE_UP; break; - case GLFW_GAMEPAD_BUTTON_DPAD_RIGHT: b = GAMEPAD_BUTTON_LEFT_FACE_RIGHT; break; - case GLFW_GAMEPAD_BUTTON_DPAD_DOWN: b = GAMEPAD_BUTTON_LEFT_FACE_DOWN; break; - case GLFW_GAMEPAD_BUTTON_DPAD_LEFT: b = GAMEPAD_BUTTON_LEFT_FACE_LEFT; break; + case GLFW_GAMEPAD_BUTTON_DPAD_UP: b = GAMEPAD_BUTTON_LEFT_FACE_UP; break; + case GLFW_GAMEPAD_BUTTON_DPAD_RIGHT: b = GAMEPAD_BUTTON_LEFT_FACE_RIGHT; break; + case GLFW_GAMEPAD_BUTTON_DPAD_DOWN: b = GAMEPAD_BUTTON_LEFT_FACE_DOWN; break; + case GLFW_GAMEPAD_BUTTON_DPAD_LEFT: b = GAMEPAD_BUTTON_LEFT_FACE_LEFT; break; - case GLFW_GAMEPAD_BUTTON_LEFT_THUMB: b = GAMEPAD_BUTTON_LEFT_THUMB; break; - case GLFW_GAMEPAD_BUTTON_RIGHT_THUMB: b = GAMEPAD_BUTTON_RIGHT_THUMB; break; + case GLFW_GAMEPAD_BUTTON_LEFT_THUMB: b = GAMEPAD_BUTTON_LEFT_THUMB; break; + case GLFW_GAMEPAD_BUTTON_RIGHT_THUMB: b = GAMEPAD_BUTTON_RIGHT_THUMB; break; } #endif #if defined(PLATFORM_UWP) - b = button; // UWP will provide the correct button + b = button; // UWP will provide the correct button #endif #if defined(PLATFORM_WEB) // https://www.w3.org/TR/gamepad/#gamepad-interface switch (button) { - case 0: b = GAMEPAD_BUTTON_RIGHT_FACE_DOWN; break; - case 1: b = GAMEPAD_BUTTON_RIGHT_FACE_RIGHT; break; - case 2: b = GAMEPAD_BUTTON_RIGHT_FACE_LEFT; break; - case 3: b = GAMEPAD_BUTTON_RIGHT_FACE_UP; break; - case 4: b = GAMEPAD_BUTTON_LEFT_TRIGGER_1; break; - case 5: b = GAMEPAD_BUTTON_RIGHT_TRIGGER_1; break; - case 6: b = GAMEPAD_BUTTON_LEFT_TRIGGER_2; break; - case 7: b = GAMEPAD_BUTTON_RIGHT_TRIGGER_2; break; - case 8: b = GAMEPAD_BUTTON_MIDDLE_LEFT; break; - case 9: b = GAMEPAD_BUTTON_MIDDLE_RIGHT; break; - case 10: b = GAMEPAD_BUTTON_LEFT_THUMB; break; - case 11: b = GAMEPAD_BUTTON_RIGHT_THUMB; break; - case 12: b = GAMEPAD_BUTTON_LEFT_FACE_UP; break; - case 13: b = GAMEPAD_BUTTON_LEFT_FACE_DOWN; break; - case 14: b = GAMEPAD_BUTTON_LEFT_FACE_LEFT; break; - case 15: b = GAMEPAD_BUTTON_LEFT_FACE_RIGHT; break; + case 0: b = GAMEPAD_BUTTON_RIGHT_FACE_DOWN; break; + case 1: b = GAMEPAD_BUTTON_RIGHT_FACE_RIGHT; break; + case 2: b = GAMEPAD_BUTTON_RIGHT_FACE_LEFT; break; + case 3: b = GAMEPAD_BUTTON_RIGHT_FACE_UP; break; + case 4: b = GAMEPAD_BUTTON_LEFT_TRIGGER_1; break; + case 5: b = GAMEPAD_BUTTON_RIGHT_TRIGGER_1; break; + case 6: b = GAMEPAD_BUTTON_LEFT_TRIGGER_2; break; + case 7: b = GAMEPAD_BUTTON_RIGHT_TRIGGER_2; break; + case 8: b = GAMEPAD_BUTTON_MIDDLE_LEFT; break; + case 9: b = GAMEPAD_BUTTON_MIDDLE_RIGHT; break; + case 10: b = GAMEPAD_BUTTON_LEFT_THUMB; break; + case 11: b = GAMEPAD_BUTTON_RIGHT_THUMB; break; + case 12: b = GAMEPAD_BUTTON_LEFT_FACE_UP; break; + case 13: b = GAMEPAD_BUTTON_LEFT_FACE_DOWN; break; + case 14: b = GAMEPAD_BUTTON_LEFT_FACE_LEFT; break; + case 15: b = GAMEPAD_BUTTON_LEFT_FACE_RIGHT; break; } #endif - return b; + return b; } static GamepadAxis GetGamepadAxis(int axis) { - GamepadAxis a = GAMEPAD_AXIS_UNKNOWN; + GamepadAxis a = GAMEPAD_AXIS_UNKNOWN; #if defined(PLATFORM_DESKTOP) switch(axis) { - case GLFW_GAMEPAD_AXIS_LEFT_X: a = GAMEPAD_AXIS_LEFT_X; break; - case GLFW_GAMEPAD_AXIS_LEFT_Y: a = GAMEPAD_AXIS_LEFT_Y; break; - case GLFW_GAMEPAD_AXIS_RIGHT_X: a = GAMEPAD_AXIS_RIGHT_X; break; - case GLFW_GAMEPAD_AXIS_RIGHT_Y: a = GAMEPAD_AXIS_RIGHT_Y; break; - case GLFW_GAMEPAD_AXIS_LEFT_TRIGGER: a = GAMEPAD_AXIS_LEFT_TRIGGER; break; - case GLFW_GAMEPAD_AXIS_RIGHT_TRIGGER: a = GAMEPAD_AXIS_RIGHT_TRIGGER; break; + case GLFW_GAMEPAD_AXIS_LEFT_X: a = GAMEPAD_AXIS_LEFT_X; break; + case GLFW_GAMEPAD_AXIS_LEFT_Y: a = GAMEPAD_AXIS_LEFT_Y; break; + case GLFW_GAMEPAD_AXIS_RIGHT_X: a = GAMEPAD_AXIS_RIGHT_X; break; + case GLFW_GAMEPAD_AXIS_RIGHT_Y: a = GAMEPAD_AXIS_RIGHT_Y; break; + case GLFW_GAMEPAD_AXIS_LEFT_TRIGGER: a = GAMEPAD_AXIS_LEFT_TRIGGER; break; + case GLFW_GAMEPAD_AXIS_RIGHT_TRIGGER: a = GAMEPAD_AXIS_RIGHT_TRIGGER; break; } #endif #if defined(PLATFORM_UWP) - a = axis; // UWP will provide the correct axis + a = axis; // UWP will provide the correct axis #endif #if defined(PLATFORM_WEB) - // https://www.w3.org/TR/gamepad/#gamepad-interface + // https://www.w3.org/TR/gamepad/#gamepad-interface switch(axis) { - case 0: a = GAMEPAD_AXIS_LEFT_X; - case 1: a = GAMEPAD_AXIS_LEFT_Y; - case 2: a = GAMEPAD_AXIS_RIGHT_X; - case 3: a = GAMEPAD_AXIS_RIGHT_X; + case 0: a = GAMEPAD_AXIS_LEFT_X; + case 1: a = GAMEPAD_AXIS_LEFT_Y; + case 2: a = GAMEPAD_AXIS_RIGHT_X; + case 3: a = GAMEPAD_AXIS_RIGHT_X; } #endif - return a; + return a; } // Poll (store) all input events @@ -3408,13 +3408,13 @@ static void PollInputEvents(void) // Get current gamepad state // NOTE: There is no callback available, so we get it manually // Get remapped buttons - GLFWgamepadstate state; - glfwGetGamepadState(i, &state); // This remapps all gamepads so they have their buttons mapped like an xbox controller - const unsigned char *buttons = state.buttons; + GLFWgamepadstate state; + glfwGetGamepadState(i, &state); // This remapps all gamepads so they have their buttons mapped like an xbox controller + const unsigned char *buttons = state.buttons; for (int k = 0; (buttons != NULL) && (k < GLFW_GAMEPAD_BUTTON_DPAD_LEFT + 1) && (k < MAX_GAMEPAD_BUTTONS); k++) { - const GamepadButton button = GetGamepadButton(k); + const GamepadButton button = GetGamepadButton(k); if (buttons[k] == GLFW_PRESS) { @@ -3429,13 +3429,13 @@ static void PollInputEvents(void) for (int k = 0; (axes != NULL) && (k < GLFW_GAMEPAD_AXIS_LAST + 1) && (k < MAX_GAMEPAD_AXIS); k++) { - const GamepadAxis axis = GetGamepadAxis(k); + const GamepadAxis axis = GetGamepadAxis(k); gamepadAxisState[i][axis] = axes[k]; } // Register buttons for 2nd triggers (because GLFW doesn't count these as buttons but rather axis) - currentGamepadState[i][GAMEPAD_BUTTON_LEFT_TRIGGER_2] = (char)(gamepadAxisState[i][GAMEPAD_AXIS_LEFT_TRIGGER] > 0.1); - currentGamepadState[i][GAMEPAD_BUTTON_RIGHT_TRIGGER_2] = (char)(gamepadAxisState[i][GAMEPAD_AXIS_RIGHT_TRIGGER] > 0.1); + currentGamepadState[i][GAMEPAD_BUTTON_LEFT_TRIGGER_2] = (char)(gamepadAxisState[i][GAMEPAD_AXIS_LEFT_TRIGGER] > 0.1); + currentGamepadState[i][GAMEPAD_BUTTON_RIGHT_TRIGGER_2] = (char)(gamepadAxisState[i][GAMEPAD_AXIS_RIGHT_TRIGGER] > 0.1); gamepadAxisCount = GLFW_GAMEPAD_AXIS_LAST; } @@ -3471,7 +3471,7 @@ static void PollInputEvents(void) // Register buttons data for every connected gamepad for (int j = 0; (j < gamepadState.numButtons) && (j < MAX_GAMEPAD_BUTTONS); j++) { - const GamepadButton button = GetGamepadButton(j); + const GamepadButton button = GetGamepadButton(j); if (gamepadState.digitalButton[j] == 1) { currentGamepadState[i][button] = 1; @@ -3485,7 +3485,7 @@ static void PollInputEvents(void) // Register axis data for every connected gamepad for (int j = 0; (j < gamepadState.numAxes) && (j < MAX_GAMEPAD_AXIS); j++) { - const GamepadAxis axis = GetGamepadAxis(k); + const GamepadAxis axis = GetGamepadAxis(k); gamepadAxisState[i][axis] = gamepadState.axis[j]; } -- cgit v1.2.3 From 86eba249708a0bcfee5ba665c1fbb1d2050113ec Mon Sep 17 00:00:00 2001 From: Reece Mackie <20544390+Rover656@users.noreply.github.com> Date: Sun, 28 Apr 2019 16:08:07 +0100 Subject: This is dumb... --- src/raylib.h | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) (limited to 'src') diff --git a/src/raylib.h b/src/raylib.h index 3fb4ee6d..dfbebf90 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -627,21 +627,21 @@ typedef enum // This is normally ABXY/Circle, Triangle, Square, Cross. No support for 6 button controllers though.. GAMEPAD_BUTTON_LEFT_FACE_UP, - GAMEPAD_BUTTON_LEFT_FACE_RIGHT, - GAMEPAD_BUTTON_LEFT_FACE_DOWN, + GAMEPAD_BUTTON_LEFT_FACE_RIGHT, + GAMEPAD_BUTTON_LEFT_FACE_DOWN, GAMEPAD_BUTTON_LEFT_FACE_LEFT, // This is normally a DPAD - GAMEPAD_BUTTON_RIGHT_FACE_UP, - GAMEPAD_BUTTON_RIGHT_FACE_RIGHT, - GAMEPAD_BUTTON_RIGHT_FACE_DOWN, - GAMEPAD_BUTTON_RIGHT_FACE_LEFT, + GAMEPAD_BUTTON_RIGHT_FACE_UP, + GAMEPAD_BUTTON_RIGHT_FACE_RIGHT, + GAMEPAD_BUTTON_RIGHT_FACE_DOWN, + GAMEPAD_BUTTON_RIGHT_FACE_LEFT, // Triggers GAMEPAD_BUTTON_LEFT_TRIGGER_1, GAMEPAD_BUTTON_LEFT_TRIGGER_2, - GAMEPAD_BUTTON_RIGHT_TRIGGER_1, - GAMEPAD_BUTTON_RIGHT_TRIGGER_2, + GAMEPAD_BUTTON_RIGHT_TRIGGER_1, + GAMEPAD_BUTTON_RIGHT_TRIGGER_2, // These are buttons in the center of the gamepad GAMEPAD_BUTTON_MIDDLE_LEFT, //PS3 Select @@ -650,25 +650,25 @@ typedef enum // These are the joystick press in buttons GAMEPAD_BUTTON_LEFT_THUMB, - GAMEPAD_BUTTON_RIGHT_THUMB + GAMEPAD_BUTTON_RIGHT_THUMB } GamepadButton; typedef enum { - // This is here just for error checking + // This is here just for error checking GAMEPAD_AXIS_UNKNOWN = 0, // Left stick - GAMEPAD_AXIS_LEFT_X, - GAMEPAD_AXIS_LEFT_Y, + GAMEPAD_AXIS_LEFT_X, + GAMEPAD_AXIS_LEFT_Y, // Right stick - GAMEPAD_AXIS_RIGHT_X, - GAMEPAD_AXIS_RIGHT_Y, + GAMEPAD_AXIS_RIGHT_X, + GAMEPAD_AXIS_RIGHT_Y, // Pressure levels for the back triggers - GAMEPAD_AXIS_LEFT_TRIGGER, // [1..-1] (pressure-level) - GAMEPAD_AXIS_RIGHT_TRIGGER // [1..-1] (pressure-level) + GAMEPAD_AXIS_LEFT_TRIGGER, // [1..-1] (pressure-level) + GAMEPAD_AXIS_RIGHT_TRIGGER // [1..-1] (pressure-level) } GamepadAxis; // Shader location point type -- cgit v1.2.3 From a51f3be38fe8dea4b3220e4071ebd826a2090c1c Mon Sep 17 00:00:00 2001 From: Reece Mackie <20544390+Rover656@users.noreply.github.com> Date: Sun, 28 Apr 2019 16:53:20 +0100 Subject: Fix web --- src/core.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/core.c b/src/core.c index 1dc27050..8bff8245 100644 --- a/src/core.c +++ b/src/core.c @@ -3485,7 +3485,7 @@ static void PollInputEvents(void) // Register axis data for every connected gamepad for (int j = 0; (j < gamepadState.numAxes) && (j < MAX_GAMEPAD_AXIS); j++) { - const GamepadAxis axis = GetGamepadAxis(k); + const GamepadAxis axis = GetGamepadAxis(j); gamepadAxisState[i][axis] = gamepadState.axis[j]; } -- cgit v1.2.3 From 100c82e369c3b40c2aafe4c1faddd6ee7d37ba6a Mon Sep 17 00:00:00 2001 From: raysan5 Date: Sun, 28 Apr 2019 18:23:21 +0200 Subject: Review formatting to follow raylib style --- src/core.c | 114 +++++++++++++++++++++++++++++++---------------------------- src/raylib.h | 19 +++++----- 2 files changed, 68 insertions(+), 65 deletions(-) (limited to 'src') diff --git a/src/core.c b/src/core.c index 8bff8245..f2978d77 100644 --- a/src/core.c +++ b/src/core.c @@ -445,6 +445,8 @@ static void Wait(float ms); // Wait for some millise static bool GetKeyStatus(int key); // Returns if a key has been pressed static bool GetMouseButtonStatus(int button); // Returns if a mouse button has been pressed +static int GetGamepadButton(int button); // Get gamepad button generic to all platforms +static int GetGamepadAxis(int axis); // Get gamepad axis generic to all platforms static void PollInputEvents(void); // Register user events static void LogoAnimation(void); // Plays raylib logo appearing animation @@ -3081,95 +3083,97 @@ static bool GetMouseButtonStatus(int button) #endif } -static GamepadButton GetGamepadButton(int button) +// Get gamepad button generic to all platforms +static int GetGamepadButton(int button) { - GamepadButton b = GAMEPAD_BUTTON_UNKNOWN; + int btn = GAMEPAD_BUTTON_UNKNOWN; #if defined(PLATFORM_DESKTOP) switch (button) { - case GLFW_GAMEPAD_BUTTON_Y: b = GAMEPAD_BUTTON_RIGHT_FACE_UP; break; - case GLFW_GAMEPAD_BUTTON_B: b = GAMEPAD_BUTTON_RIGHT_FACE_RIGHT; break; - case GLFW_GAMEPAD_BUTTON_A: b = GAMEPAD_BUTTON_RIGHT_FACE_DOWN; break; - case GLFW_GAMEPAD_BUTTON_X: b = GAMEPAD_BUTTON_RIGHT_FACE_LEFT; break; + case GLFW_GAMEPAD_BUTTON_Y: btn = GAMEPAD_BUTTON_RIGHT_FACE_UP; break; + case GLFW_GAMEPAD_BUTTON_B: btn = GAMEPAD_BUTTON_RIGHT_FACE_RIGHT; break; + case GLFW_GAMEPAD_BUTTON_A: btn = GAMEPAD_BUTTON_RIGHT_FACE_DOWN; break; + case GLFW_GAMEPAD_BUTTON_X: btn = GAMEPAD_BUTTON_RIGHT_FACE_LEFT; break; - case GLFW_GAMEPAD_BUTTON_LEFT_BUMPER: b = GAMEPAD_BUTTON_LEFT_TRIGGER_1; break; - case GLFW_GAMEPAD_BUTTON_RIGHT_BUMPER: b = GAMEPAD_BUTTON_RIGHT_TRIGGER_1; break; + case GLFW_GAMEPAD_BUTTON_LEFT_BUMPER: btn = GAMEPAD_BUTTON_LEFT_TRIGGER_1; break; + case GLFW_GAMEPAD_BUTTON_RIGHT_BUMPER: btn = GAMEPAD_BUTTON_RIGHT_TRIGGER_1; break; - case GLFW_GAMEPAD_BUTTON_BACK: b = GAMEPAD_BUTTON_MIDDLE_LEFT; break; - case GLFW_GAMEPAD_BUTTON_GUIDE: b = GAMEPAD_BUTTON_MIDDLE; break; - case GLFW_GAMEPAD_BUTTON_START: b = GAMEPAD_BUTTON_MIDDLE_RIGHT; break; + case GLFW_GAMEPAD_BUTTON_BACK: btn = GAMEPAD_BUTTON_MIDDLE_LEFT; break; + case GLFW_GAMEPAD_BUTTON_GUIDE: btn = GAMEPAD_BUTTON_MIDDLE; break; + case GLFW_GAMEPAD_BUTTON_START: btn = GAMEPAD_BUTTON_MIDDLE_RIGHT; break; - case GLFW_GAMEPAD_BUTTON_DPAD_UP: b = GAMEPAD_BUTTON_LEFT_FACE_UP; break; - case GLFW_GAMEPAD_BUTTON_DPAD_RIGHT: b = GAMEPAD_BUTTON_LEFT_FACE_RIGHT; break; - case GLFW_GAMEPAD_BUTTON_DPAD_DOWN: b = GAMEPAD_BUTTON_LEFT_FACE_DOWN; break; - case GLFW_GAMEPAD_BUTTON_DPAD_LEFT: b = GAMEPAD_BUTTON_LEFT_FACE_LEFT; break; + case GLFW_GAMEPAD_BUTTON_DPAD_UP: btn = GAMEPAD_BUTTON_LEFT_FACE_UP; break; + case GLFW_GAMEPAD_BUTTON_DPAD_RIGHT: btn = GAMEPAD_BUTTON_LEFT_FACE_RIGHT; break; + case GLFW_GAMEPAD_BUTTON_DPAD_DOWN: btn = GAMEPAD_BUTTON_LEFT_FACE_DOWN; break; + case GLFW_GAMEPAD_BUTTON_DPAD_LEFT: btn = GAMEPAD_BUTTON_LEFT_FACE_LEFT; break; - case GLFW_GAMEPAD_BUTTON_LEFT_THUMB: b = GAMEPAD_BUTTON_LEFT_THUMB; break; - case GLFW_GAMEPAD_BUTTON_RIGHT_THUMB: b = GAMEPAD_BUTTON_RIGHT_THUMB; break; + case GLFW_GAMEPAD_BUTTON_LEFT_THUMB: btn = GAMEPAD_BUTTON_LEFT_THUMB; break; + case GLFW_GAMEPAD_BUTTON_RIGHT_THUMB: btn = GAMEPAD_BUTTON_RIGHT_THUMB; break; } #endif #if defined(PLATFORM_UWP) - b = button; // UWP will provide the correct button + btn = button; // UWP will provide the correct button #endif #if defined(PLATFORM_WEB) - // https://www.w3.org/TR/gamepad/#gamepad-interface + // Gamepad Buttons reference: https://www.w3.org/TR/gamepad/#gamepad-interface switch (button) { - case 0: b = GAMEPAD_BUTTON_RIGHT_FACE_DOWN; break; - case 1: b = GAMEPAD_BUTTON_RIGHT_FACE_RIGHT; break; - case 2: b = GAMEPAD_BUTTON_RIGHT_FACE_LEFT; break; - case 3: b = GAMEPAD_BUTTON_RIGHT_FACE_UP; break; - case 4: b = GAMEPAD_BUTTON_LEFT_TRIGGER_1; break; - case 5: b = GAMEPAD_BUTTON_RIGHT_TRIGGER_1; break; - case 6: b = GAMEPAD_BUTTON_LEFT_TRIGGER_2; break; - case 7: b = GAMEPAD_BUTTON_RIGHT_TRIGGER_2; break; - case 8: b = GAMEPAD_BUTTON_MIDDLE_LEFT; break; - case 9: b = GAMEPAD_BUTTON_MIDDLE_RIGHT; break; - case 10: b = GAMEPAD_BUTTON_LEFT_THUMB; break; - case 11: b = GAMEPAD_BUTTON_RIGHT_THUMB; break; - case 12: b = GAMEPAD_BUTTON_LEFT_FACE_UP; break; - case 13: b = GAMEPAD_BUTTON_LEFT_FACE_DOWN; break; - case 14: b = GAMEPAD_BUTTON_LEFT_FACE_LEFT; break; - case 15: b = GAMEPAD_BUTTON_LEFT_FACE_RIGHT; break; + case 0: btn = GAMEPAD_BUTTON_RIGHT_FACE_DOWN; break; + case 1: btn = GAMEPAD_BUTTON_RIGHT_FACE_RIGHT; break; + case 2: btn = GAMEPAD_BUTTON_RIGHT_FACE_LEFT; break; + case 3: btn = GAMEPAD_BUTTON_RIGHT_FACE_UP; break; + case 4: btn = GAMEPAD_BUTTON_LEFT_TRIGGER_1; break; + case 5: btn = GAMEPAD_BUTTON_RIGHT_TRIGGER_1; break; + case 6: btn = GAMEPAD_BUTTON_LEFT_TRIGGER_2; break; + case 7: btn = GAMEPAD_BUTTON_RIGHT_TRIGGER_2; break; + case 8: btn = GAMEPAD_BUTTON_MIDDLE_LEFT; break; + case 9: btn = GAMEPAD_BUTTON_MIDDLE_RIGHT; break; + case 10: btn = GAMEPAD_BUTTON_LEFT_THUMB; break; + case 11: btn = GAMEPAD_BUTTON_RIGHT_THUMB; break; + case 12: btn = GAMEPAD_BUTTON_LEFT_FACE_UP; break; + case 13: btn = GAMEPAD_BUTTON_LEFT_FACE_DOWN; break; + case 14: btn = GAMEPAD_BUTTON_LEFT_FACE_LEFT; break; + case 15: btn = GAMEPAD_BUTTON_LEFT_FACE_RIGHT; break; } #endif - return b; + return btn; } -static GamepadAxis GetGamepadAxis(int axis) +// Get gamepad axis generic to all platforms +static int GetGamepadAxis(int axis) { - GamepadAxis a = GAMEPAD_AXIS_UNKNOWN; + int axs = GAMEPAD_AXIS_UNKNOWN; #if defined(PLATFORM_DESKTOP) - switch(axis) + switch (axis) { - case GLFW_GAMEPAD_AXIS_LEFT_X: a = GAMEPAD_AXIS_LEFT_X; break; - case GLFW_GAMEPAD_AXIS_LEFT_Y: a = GAMEPAD_AXIS_LEFT_Y; break; - case GLFW_GAMEPAD_AXIS_RIGHT_X: a = GAMEPAD_AXIS_RIGHT_X; break; - case GLFW_GAMEPAD_AXIS_RIGHT_Y: a = GAMEPAD_AXIS_RIGHT_Y; break; - case GLFW_GAMEPAD_AXIS_LEFT_TRIGGER: a = GAMEPAD_AXIS_LEFT_TRIGGER; break; - case GLFW_GAMEPAD_AXIS_RIGHT_TRIGGER: a = GAMEPAD_AXIS_RIGHT_TRIGGER; break; + case GLFW_GAMEPAD_AXIS_LEFT_X: axs = GAMEPAD_AXIS_LEFT_X; break; + case GLFW_GAMEPAD_AXIS_LEFT_Y: axs = GAMEPAD_AXIS_LEFT_Y; break; + case GLFW_GAMEPAD_AXIS_RIGHT_X: axs = GAMEPAD_AXIS_RIGHT_X; break; + case GLFW_GAMEPAD_AXIS_RIGHT_Y: axs = GAMEPAD_AXIS_RIGHT_Y; break; + case GLFW_GAMEPAD_AXIS_LEFT_TRIGGER: axs = GAMEPAD_AXIS_LEFT_TRIGGER; break; + case GLFW_GAMEPAD_AXIS_RIGHT_TRIGGER: axs = GAMEPAD_AXIS_RIGHT_TRIGGER; break; } #endif #if defined(PLATFORM_UWP) - a = axis; // UWP will provide the correct axis + axs = axis; // UWP will provide the correct axis #endif #if defined(PLATFORM_WEB) - // https://www.w3.org/TR/gamepad/#gamepad-interface - switch(axis) + // Gamepad axis reference:https://www.w3.org/TR/gamepad/#gamepad-interface + switch (axis) { - case 0: a = GAMEPAD_AXIS_LEFT_X; - case 1: a = GAMEPAD_AXIS_LEFT_Y; - case 2: a = GAMEPAD_AXIS_RIGHT_X; - case 3: a = GAMEPAD_AXIS_RIGHT_X; + case 0: axs = GAMEPAD_AXIS_LEFT_X; + case 1: axs = GAMEPAD_AXIS_LEFT_Y; + case 2: axs = GAMEPAD_AXIS_RIGHT_X; + case 3: axs = GAMEPAD_AXIS_RIGHT_X; } #endif - return a; + return axs; } // Poll (store) all input events @@ -3429,7 +3433,7 @@ static void PollInputEvents(void) for (int k = 0; (axes != NULL) && (k < GLFW_GAMEPAD_AXIS_LAST + 1) && (k < MAX_GAMEPAD_AXIS); k++) { - const GamepadAxis axis = GetGamepadAxis(k); + const int axis = GetGamepadAxis(k); gamepadAxisState[i][axis] = axes[k]; } @@ -3485,7 +3489,7 @@ static void PollInputEvents(void) // Register axis data for every connected gamepad for (int j = 0; (j < gamepadState.numAxes) && (j < MAX_GAMEPAD_AXIS); j++) { - const GamepadAxis axis = GetGamepadAxis(j); + const int axis = GetGamepadAxis(j); gamepadAxisState[i][axis] = gamepadState.axis[j]; } diff --git a/src/raylib.h b/src/raylib.h index dfbebf90..3bd64b3b 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -620,12 +620,12 @@ typedef enum { } GamepadNumber; // Gamepad Buttons -typedef enum -{ +typedef enum { // This is here just for error checking GAMEPAD_BUTTON_UNKNOWN = 0, - // This is normally ABXY/Circle, Triangle, Square, Cross. No support for 6 button controllers though.. + // This is normally [A,B,X,Y]/[Circle,Triangle,Square,Cross] + // No support for 6 button controllers though.. GAMEPAD_BUTTON_LEFT_FACE_UP, GAMEPAD_BUTTON_LEFT_FACE_RIGHT, GAMEPAD_BUTTON_LEFT_FACE_DOWN, @@ -644,17 +644,16 @@ typedef enum GAMEPAD_BUTTON_RIGHT_TRIGGER_2, // These are buttons in the center of the gamepad - GAMEPAD_BUTTON_MIDDLE_LEFT, //PS3 Select - GAMEPAD_BUTTON_MIDDLE, //PS Button/XBOX Button - GAMEPAD_BUTTON_MIDDLE_RIGHT, //PS3 Start + GAMEPAD_BUTTON_MIDDLE_LEFT, //PS3 Select + GAMEPAD_BUTTON_MIDDLE, //PS Button/XBOX Button + GAMEPAD_BUTTON_MIDDLE_RIGHT, //PS3 Start // These are the joystick press in buttons GAMEPAD_BUTTON_LEFT_THUMB, GAMEPAD_BUTTON_RIGHT_THUMB } GamepadButton; -typedef enum -{ +typedef enum { // This is here just for error checking GAMEPAD_AXIS_UNKNOWN = 0, @@ -667,8 +666,8 @@ typedef enum GAMEPAD_AXIS_RIGHT_Y, // Pressure levels for the back triggers - GAMEPAD_AXIS_LEFT_TRIGGER, // [1..-1] (pressure-level) - GAMEPAD_AXIS_RIGHT_TRIGGER // [1..-1] (pressure-level) + GAMEPAD_AXIS_LEFT_TRIGGER, // [1..-1] (pressure-level) + GAMEPAD_AXIS_RIGHT_TRIGGER // [1..-1] (pressure-level) } GamepadAxis; // Shader location point type -- cgit v1.2.3 From bb2841a26d2c118b2febfc02c6cab7f7b2791893 Mon Sep 17 00:00:00 2001 From: Ray Date: Wed, 1 May 2019 14:30:36 +0200 Subject: WARNING: Support high DPI displays This change could break things. So, I created SUPPORT_HIGH_DPI flag to enable it (disabled by default). Basically, it detects HighDPI display and scales all drawing (and mouse input) appropiately to match the equivalent "standardDPI" screen size on highDPI. It uses screenScaling matrix to do that. This scaling comes with some undesired effects, like aliasing on default font text (keep in mind that font is pixel-perfect, not intended for any non-rounded scale factor). The only solution for this aliasing would be some AA postpro filter or implementing the highDPI scaling in a different way: rendering to a texture and scaling it with FILTER_BILINEAR, check `core_window_scale_letterbox.c` example for reference. Use at your own risk. --- src/config.h | 2 + src/core.c | 132 ++++++++++++++++++++++++++--------------------------------- 2 files changed, 59 insertions(+), 75 deletions(-) (limited to 'src') diff --git a/src/config.h b/src/config.h index 2ea4b438..77e936bd 100644 --- a/src/config.h +++ b/src/config.h @@ -50,6 +50,8 @@ #define SUPPORT_SCREEN_CAPTURE 1 // Allow automatic gif recording of current screen pressing CTRL+F12, defined in KeyCallback() #define SUPPORT_GIF_RECORDING 1 +// Allow scale all the drawn content to match the high-DPI equivalent size (only PLATFORM_DESKTOP) +//#define SUPPORT_HIGH_DPI 1 //------------------------------------------------------------------------------------ diff --git a/src/core.c b/src/core.c index f2978d77..6dd423fa 100644 --- a/src/core.c +++ b/src/core.c @@ -59,6 +59,9 @@ * #define SUPPORT_GIF_RECORDING * Allow automatic gif recording of current screen pressing CTRL+F12, defined in KeyCallback() * +* #define SUPPORT_HIGH_DPI +* Allow scale all the drawn content to match the high-DPI equivalent size (only PLATFORM_DESKTOP) +* * DEPENDENCIES: * rglfw - Manage graphic device, OpenGL context and inputs on PLATFORM_DESKTOP (Windows, Linux, OSX. FreeBSD, OpenBSD, NetBSD, DragonFly) * raymath - 3D math functionality (Vector2, Vector3, Matrix, Quaternion) @@ -437,7 +440,7 @@ extern void UnloadDefaultFont(void); // [Module: text] Unloads default fo //---------------------------------------------------------------------------------- static bool InitGraphicsDevice(int width, int height); // Initialize graphics device static void SetupFramebuffer(int width, int height); // Setup main framebuffer -static void SetupViewport(void); // Set viewport parameters +static void SetupViewport(int width, int height); // Set viewport for a provided width and height static void SwapBuffers(void); // Copy back buffer to front buffers static void InitTimer(void); // Initialize timer @@ -1175,6 +1178,7 @@ void BeginMode2D(Camera2D camera) rlglDraw(); // Draw Buffers (Only OpenGL 3+ and ES2) rlLoadIdentity(); // Reset current matrix (MODELVIEW) + rlMultMatrixf(MatrixToFloat(screenScaling)); // Apply screen scaling if required // Camera rotation and scaling is always relative to target Matrix matOrigin = MatrixTranslate(-camera.target.x, -camera.target.y, 0.0f); @@ -1193,6 +1197,7 @@ void EndMode2D(void) rlglDraw(); // Draw Buffers (Only OpenGL 3+ and ES2) rlLoadIdentity(); // Reset current matrix (MODELVIEW) + rlMultMatrixf(MatrixToFloat(screenScaling)); // Apply screen scaling if required } // Initializes 3D mode with custom camera (3D) @@ -1246,6 +1251,8 @@ void EndMode3D(void) rlMatrixMode(RL_MODELVIEW); // Get back to modelview matrix rlLoadIdentity(); // Reset current matrix (MODELVIEW) + rlMultMatrixf(MatrixToFloat(screenScaling)); // Apply screen scaling if required + rlDisableDepthTest(); // Disable DEPTH_TEST for 2D } @@ -1284,22 +1291,8 @@ void EndTextureMode(void) rlDisableRenderTexture(); // Disable render target - // Set viewport to default framebuffer size (screen size) - SetupViewport(); - - rlMatrixMode(RL_PROJECTION); // Switch to PROJECTION matrix - rlLoadIdentity(); // Reset current matrix (PROJECTION) - - // Set orthographic projection to current framebuffer size - // NOTE: Configured top-left corner as (0, 0) - rlOrtho(0, GetScreenWidth(), GetScreenHeight(), 0, 0.0f, 1.0f); - - rlMatrixMode(RL_MODELVIEW); // Switch back to MODELVIEW matrix - rlLoadIdentity(); // Reset current matrix (MODELVIEW) - - // Reset current screen size - currentWidth = GetScreenWidth(); - currentHeight = GetScreenHeight(); + // Set viewport to default framebuffer size + SetupViewport(renderWidth, renderHeight); } // Returns a ray trace from mouse position @@ -2336,12 +2329,11 @@ static bool InitGraphicsDevice(int width, int height) currentWidth = width; currentHeight = height; + screenScaling = MatrixIdentity(); // No draw scaling required by default + // NOTE: Framebuffer (render area - renderWidth, renderHeight) could include black bars... // ...in top-down or left-right to match display aspect ratio (no weird scalings) - // Screen scaling matrix is required in case desired screen area is different than display area - screenScaling = MatrixIdentity(); - #if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB) glfwSetErrorCallback(ErrorCallback); @@ -2388,7 +2380,7 @@ static bool InitGraphicsDevice(int width, int height) //glfwWindowHint(GLFW_REFRESH_RATE, 0); // Refresh rate for fullscreen window //glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API); // OpenGL API to use. Alternative: GLFW_OPENGL_ES_API //glfwWindowHint(GLFW_AUX_BUFFERS, 0); // Number of auxiliar buffers -#if defined(PLATFORM_DESKTOP) +#if defined(PLATFORM_DESKTOP) && defined(SUPPORT_HIGH_DPI) // NOTE: If using external GLFW, it requires latest GLFW 3.3 for this functionality glfwWindowHint(GLFW_SCALE_TO_MONITOR, GLFW_TRUE); // Scale content area based on the monitor content scale where window is placed on #endif @@ -2468,9 +2460,11 @@ static bool InitGraphicsDevice(int width, int height) // framebuffer is rendered correctly but once displayed on a 16:9 monitor, it gets stretched // by the sides to fit all monitor space... - // At this point we need to manage render size vs screen size - // NOTE: This function uses and modifies global module variables: - // screenWidth/screenHeight - renderWidth/renderHeight - screenScaling + // Try to setup the most appropiate fullscreen framebuffer for the requested screenWidth/screenHeight + // It considers device display resolution mode and setups a framebuffer with black bars if required (render size/offset) + // Modified global variables: screenWidth/screenHeight - renderWidth/renderHeight - renderOffsetX/renderOffsetY - screenScaling + // TODO: It is a quite cumbersome solution to display size vs requested size, it should be reviewed or removed... + // HighDPI monitors are properly considered in a following similar function: SetupViewport() SetupFramebuffer(displayWidth, displayHeight); window = glfwCreateWindow(displayWidth, displayHeight, windowTitle, glfwGetPrimaryMonitor(), NULL); @@ -2494,12 +2488,6 @@ static bool InitGraphicsDevice(int width, int height) if (windowPosY < 0) windowPosY = 0; glfwSetWindowPos(window, windowPosX, windowPosY); - - // Get window HiDPI scaling factor - float scaleRatio = 0.0f; - glfwGetWindowContentScale(window, &scaleRatio, NULL); - scaleRatio = roundf(scaleRatio); - //screenScaling = MatrixScale(scaleRatio, scaleRatio, scaleRatio); #endif renderWidth = screenWidth; renderHeight = screenHeight; @@ -2886,23 +2874,23 @@ static bool InitGraphicsDevice(int width, int height) } #endif // PLATFORM_ANDROID || PLATFORM_RPI - renderWidth = screenWidth; - renderHeight = screenHeight; - // Initialize OpenGL context (states and resources) - // NOTE: screenWidth and screenHeight not used, just stored as globals + // NOTE: screenWidth and screenHeight not used, just stored as globals in rlgl rlglInit(screenWidth, screenHeight); - // Setup default viewport - SetupViewport(); + int fbWidth = renderWidth; + int fbHeight = renderHeight; - // Initialize internal projection and modelview matrices - // NOTE: Default to orthographic projection mode with top-left corner at (0,0) - rlMatrixMode(RL_PROJECTION); // Switch to PROJECTION matrix - rlLoadIdentity(); // Reset current matrix (PROJECTION) - rlOrtho(0, renderWidth - renderOffsetX, renderHeight - renderOffsetY, 0, 0.0f, 1.0f); - rlMatrixMode(RL_MODELVIEW); // Switch back to MODELVIEW matrix - rlLoadIdentity(); // Reset current matrix (MODELVIEW) +#if defined(PLATFORM_DESKTOP) && defined(SUPPORT_HIGH_DPI) + glfwGetFramebufferSize(window, &fbWidth, &fbHeight); + + // Screen scaling matrix is required in case desired screen area is different than display area + screenScaling = MatrixScale((float)fbWidth/screenWidth, (float)fbHeight/screenHeight, 1.0f); + SetMouseScale((float)screenWidth/fbWidth, (float)screenHeight/fbHeight); +#endif // PLATFORM_DESKTOP && SUPPORT_HIGH_DPI + + // Setup default viewport + SetupViewport(fbWidth, fbHeight); ClearBackground(RAYWHITE); // Default background color for raylib games :P @@ -2912,21 +2900,32 @@ static bool InitGraphicsDevice(int width, int height) return true; } -// Set viewport parameters -static void SetupViewport(void) +// Set viewport for a provided width and height +static void SetupViewport(int width, int height) { -#if defined(__APPLE__) - // Get framebuffer size of current window - // NOTE: Required to handle HighDPI display correctly on OSX because framebuffer is automatically reasized to adapt to new DPI. - // When OS does that, it can be detected using GLFW3 callback: glfwSetFramebufferSizeCallback() - int fbWidth, fbHeight; - glfwGetFramebufferSize(window, &fbWidth, &fbHeight); - rlViewport(renderOffsetX/2, renderOffsetY/2, fbWidth - renderOffsetX, fbHeight - renderOffsetY); -#else - // Initialize screen viewport (area of the screen that you will actually draw to) - // NOTE: Viewport must be recalculated if screen is resized + renderWidth = width; + renderHeight = height; + + // Set viewport width and height + // NOTE: We consider render size and offset in case black bars are required and + // render area does not match full display area (this situation is only applicable on fullscreen mode) rlViewport(renderOffsetX/2, renderOffsetY/2, renderWidth - renderOffsetX, renderHeight - renderOffsetY); -#endif + + rlMatrixMode(RL_PROJECTION); // Switch to PROJECTION matrix + rlLoadIdentity(); // Reset current matrix (PROJECTION) + + // Set orthographic projection to current framebuffer size + // NOTE: Configured top-left corner as (0, 0) + rlOrtho(0, renderWidth, renderHeight, 0, 0.0f, 1.0f); + + rlMatrixMode(RL_MODELVIEW); // Switch back to MODELVIEW matrix + rlLoadIdentity(); // Reset current matrix (MODELVIEW) + + // Window size must be updated to be used on 3D mode to get new aspect ratio (BeginMode3D()) + // NOTE: Be careful! GLFW3 will choose the closest fullscreen resolution supported by current monitor, + // for example, if reescaling back to 800x450 (desired), it could set 720x480 (closest fullscreen supported) + currentWidth = screenWidth; + currentHeight = screenHeight; } // Compute framebuffer size relative to screen size and display size @@ -2959,7 +2958,7 @@ static void SetupFramebuffer(int width, int height) // Screen scaling required float scaleRatio = (float)renderWidth/(float)screenWidth; - screenScaling = MatrixScale(scaleRatio, scaleRatio, scaleRatio); + screenScaling = MatrixScale(scaleRatio, scaleRatio, 1.0f); // NOTE: We render to full display resolution! // We just need to calculate above parameters for downscale matrix and offsets @@ -3705,24 +3704,7 @@ static void CursorEnterCallback(GLFWwindow *window, int enter) // NOTE: Window resizing not allowed by default static void WindowSizeCallback(GLFWwindow *window, int width, int height) { - // If window is resized, viewport and projection matrix needs to be re-calculated - rlViewport(0, 0, width, height); // Set viewport width and height - rlMatrixMode(RL_PROJECTION); // Switch to PROJECTION matrix - rlLoadIdentity(); // Reset current matrix (PROJECTION) - rlOrtho(0, width, height, 0, 0.0f, 1.0f); // Orthographic projection mode with top-left corner at (0,0) - rlMatrixMode(RL_MODELVIEW); // Switch back to MODELVIEW matrix - rlLoadIdentity(); // Reset current matrix (MODELVIEW) - rlClearScreenBuffers(); // Clear screen buffers (color and depth) - - // Window size must be updated to be used on 3D mode to get new aspect ratio (BeginMode3D()) - // NOTE: Be careful! GLFW3 will choose the closest fullscreen resolution supported by current monitor, - // for example, if reescaling back to 800x450 (desired), it could set 720x480 (closest fullscreen supported) - screenWidth = width; - screenHeight = height; - renderWidth = width; - renderHeight = height; - currentWidth = width; - currentHeight = height; + SetupViewport(width, height); // Reset viewport and projection matrix for new size // NOTE: Postprocessing texture is not scaled to new size -- cgit v1.2.3 From c9025ed205d9385b042070228a8fa0ff637b4aa4 Mon Sep 17 00:00:00 2001 From: Ray Date: Wed, 1 May 2019 16:15:33 +0200 Subject: Corrected issue with texture rendering Not sure if already corrected... --- src/core.c | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/core.c b/src/core.c index 6dd423fa..22c59a91 100644 --- a/src/core.c +++ b/src/core.c @@ -1293,6 +1293,10 @@ void EndTextureMode(void) // Set viewport to default framebuffer size SetupViewport(renderWidth, renderHeight); + + // Reset current screen size + currentWidth = GetScreenWidth(); + currentHeight = GetScreenHeight(); } // Returns a ray trace from mouse position @@ -2920,12 +2924,6 @@ static void SetupViewport(int width, int height) rlMatrixMode(RL_MODELVIEW); // Switch back to MODELVIEW matrix rlLoadIdentity(); // Reset current matrix (MODELVIEW) - - // Window size must be updated to be used on 3D mode to get new aspect ratio (BeginMode3D()) - // NOTE: Be careful! GLFW3 will choose the closest fullscreen resolution supported by current monitor, - // for example, if reescaling back to 800x450 (desired), it could set 720x480 (closest fullscreen supported) - currentWidth = screenWidth; - currentHeight = screenHeight; } // Compute framebuffer size relative to screen size and display size @@ -3706,6 +3704,12 @@ static void WindowSizeCallback(GLFWwindow *window, int width, int height) { SetupViewport(width, height); // Reset viewport and projection matrix for new size + // Set current screen size + screenWidth = width; + screenHeight = height; + currentWidth = width; + currentHeight = height; + // NOTE: Postprocessing texture is not scaled to new size windowResized = true; -- cgit v1.2.3 From 59c436c922b9f7fe9bfb0d595f17dee0330f289f Mon Sep 17 00:00:00 2001 From: Narice <31109099+Narice@users.noreply.github.com> Date: Wed, 1 May 2019 21:41:51 +0200 Subject: Defined PI (#822) PI is not always defined in math.h, thus it must be defined in this header --- src/easings.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/easings.h b/src/easings.h index 9ad27313..99685949 100644 --- a/src/easings.h +++ b/src/easings.h @@ -91,6 +91,7 @@ #endif #include // Required for: sin(), cos(), sqrt(), pow() +#define PI 3.14159265358979323846 //Required as PI is not always defined in math.h #ifdef __cplusplus extern "C" { // Prevents name mangling of functions @@ -250,4 +251,4 @@ EASEDEF float EaseElasticInOut(float t, float b, float c, float d) } #endif -#endif // EASINGS_H \ No newline at end of file +#endif // EASINGS_H -- cgit v1.2.3 From a54af067c2c2c5ef11c39fdf8f0b00e029e663d1 Mon Sep 17 00:00:00 2001 From: Narice <31109099+Narice@users.noreply.github.com> Date: Wed, 1 May 2019 22:03:32 +0200 Subject: Added guards to PI define Added guards to not redefine it if the user is using it with raylib.h also added an 'f' at the end of the define to keep compliant with raylib's PI define --- src/easings.h | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/easings.h b/src/easings.h index 99685949..810aeccb 100644 --- a/src/easings.h +++ b/src/easings.h @@ -91,7 +91,10 @@ #endif #include // Required for: sin(), cos(), sqrt(), pow() -#define PI 3.14159265358979323846 //Required as PI is not always defined in math.h + +#ifndef PI + #define PI 3.14159265358979323846f //Required as PI is not always defined in math.h +#endif #ifdef __cplusplus extern "C" { // Prevents name mangling of functions -- cgit v1.2.3 From fc56f8d9efa544c468df8df44d02a695d6a2e752 Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 2 May 2019 09:46:01 +0200 Subject: Work on touch_as_mouse input -WIP- --- src/core.c | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/core.c b/src/core.c index 22c59a91..18fbb181 100644 --- a/src/core.c +++ b/src/core.c @@ -47,6 +47,9 @@ * #define SUPPORT_MOUSE_GESTURES * Mouse gestures are directly mapped like touches and processed by gestures system. * +* #define SUPPORT_TOUCH_AS_MOUSE +* Touch input and mouse input are shared. Mouse functions also return touch information. +* * #define SUPPORT_BUSY_WAIT_LOOP * Use busy wait loop for timing sync, if not defined, a high-resolution timer is setup and used * @@ -2154,6 +2157,11 @@ bool IsMouseButtonPressed(int button) if ((currentMouseState[button] != previousMouseState[button]) && (currentMouseState[button] == 1)) pressed = true; #endif +#if defined(PLATFORM_WEB) + Vector2 pos = GetTouchPosition(0); + if ((pos.x > 0) && (pos.y > 0)) pressed = true; // There was a touch! +#endif + return pressed; } @@ -2218,11 +2226,21 @@ int GetMouseY(void) // Returns mouse position XY Vector2 GetMousePosition(void) { + Vector2 position = { 0.0f, 0.0f }; + #if defined(PLATFORM_ANDROID) - return GetTouchPosition(0); + position = GetTouchPosition(0); #else - return (Vector2){ (mousePosition.x + mouseOffset.x)*mouseScale.x, (mousePosition.y + mouseOffset.y)*mouseScale.y }; + position = (Vector2){ (mousePosition.x + mouseOffset.x)*mouseScale.x, (mousePosition.y + mouseOffset.y)*mouseScale.y }; #endif +#if defined(PLATFORM_WEB) + Vector2 pos = GetTouchPosition(0); + + // Touch position has priority over mouse position + if ((pos.x > 0) && (pos.y > 0)) position = pos; // There was a touch! +#endif + + return position; } // Set mouse position XY -- cgit v1.2.3 From 780cefc3b0a2f2115b235890db96028ff5e6fcf3 Mon Sep 17 00:00:00 2001 From: Shiqing Date: Fri, 3 May 2019 12:17:58 +0800 Subject: Add SUPPORT_HIGH_DPI to CMakeOptions.txt --- src/CMakeOptions.txt | 1 + src/config.h.in | 2 ++ 2 files changed, 3 insertions(+) (limited to 'src') diff --git a/src/CMakeOptions.txt b/src/CMakeOptions.txt index b69c443f..b5048b8a 100644 --- a/src/CMakeOptions.txt +++ b/src/CMakeOptions.txt @@ -31,6 +31,7 @@ option(SUPPORT_SCREEN_CAPTURE "Allow automatic screen capture of current screen option(SUPPORT_GIF_RECORDING "Allow automatic gif recording of current screen pressing CTRL+F12, defined in KeyCallback()" ON) option(SUPPORT_GESTURES_SYSTEM "Gestures module is included (gestures.h) to support gestures detection: tap, hold, swipe, drag" ON) option(SUPPORT_MOUSE_GESTURES "Mouse gestures are directly mapped like touches and processed by gestures system" ON) +option(SUPPORT_HIGH_DPI "Support high DPI displays" OFF) # rlgl.h option(SUPPORT_VR_SIMULATOR "Support VR simulation functionality (stereo rendering)" ON) diff --git a/src/config.h.in b/src/config.h.in index b1c524f7..b07b7e94 100644 --- a/src/config.h.in +++ b/src/config.h.in @@ -15,6 +15,8 @@ #cmakedefine SUPPORT_SCREEN_CAPTURE 1 /* Allow automatic gif recording of current screen pressing CTRL+F12, defined in KeyCallback() */ #cmakedefine SUPPORT_GIF_RECORDING 1 +/* Support high DPI displays */ +#cmakedefine SUPPORT_HIGH_DPI 1 // rlgl.h /* Support VR simulation functionality (stereo rendering) */ -- cgit v1.2.3 From f44888e466ad63eccec229bdcc091f8f7e2f629e Mon Sep 17 00:00:00 2001 From: Ray Date: Fri, 3 May 2019 09:45:16 +0200 Subject: Force HighDPI on macOS --- src/core.c | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src') diff --git a/src/core.c b/src/core.c index 18fbb181..a5e9bd9a 100644 --- a/src/core.c +++ b/src/core.c @@ -130,6 +130,10 @@ #include "external/rgif.h" // Support GIF recording #endif +#if defined(__APPLE__) + #define SUPPORT_HIGH_DPI // Force HighDPI support on macOS +#endif + #include // Standard input / output lib #include // Required for: malloc(), free(), rand(), atexit() #include // Required for: typedef unsigned long long int uint64_t, used by hi-res timer -- cgit v1.2.3 From c6b7f9c5b0ca62c7579da7c3da6614db2720264c Mon Sep 17 00:00:00 2001 From: Ray Date: Fri, 3 May 2019 15:55:24 +0200 Subject: Some minor comments --- src/core.c | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src') diff --git a/src/core.c b/src/core.c index a5e9bd9a..def60d68 100644 --- a/src/core.c +++ b/src/core.c @@ -64,6 +64,7 @@ * * #define SUPPORT_HIGH_DPI * Allow scale all the drawn content to match the high-DPI equivalent size (only PLATFORM_DESKTOP) +* NOTE: This flag is forced on macOS, since most displays are high-DPI * * DEPENDENCIES: * rglfw - Manage graphic device, OpenGL context and inputs on PLATFORM_DESKTOP (Windows, Linux, OSX. FreeBSD, OpenBSD, NetBSD, DragonFly) @@ -3046,6 +3047,7 @@ static void InitTimer(void) // NOTE: Sleep() granularity could be around 10 ms, it means, Sleep() could // take longer than expected... for that reason we use the busy wait loop // http://stackoverflow.com/questions/43057578/c-programming-win32-games-sleep-taking-longer-than-expected +// http://www.geisswerks.com/ryan/FAQS/timing.html --> All about timming on Win32! static void Wait(float ms) { #if defined(SUPPORT_BUSY_WAIT_LOOP) && !defined(PLATFORM_UWP) -- cgit v1.2.3 From 36d8a648f0cbc9bff9893b4e7612846097e76397 Mon Sep 17 00:00:00 2001 From: Ahmad Fatoum Date: Sat, 4 May 2019 22:19:09 +0200 Subject: external: glfw: reinstate export of GLFW_PKG_{DEPS,LIBS} We were doing this before, but it was deleted during the last GLFW update. Readd it to fix the associated macOS CI failure. Fixes: cd934c9f6 ("Update GLFW to 3.3.1") --- src/external/glfw/CMakeLists.txt | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/external/glfw/CMakeLists.txt b/src/external/glfw/CMakeLists.txt index 061618ee..a9ed8554 100644 --- a/src/external/glfw/CMakeLists.txt +++ b/src/external/glfw/CMakeLists.txt @@ -303,10 +303,12 @@ endif() # Export GLFW library dependencies #-------------------------------------------------------------------- foreach(arg ${glfw_PKG_DEPS}) - set(GLFW_PKG_DEPS "${GLFW_PKG_DEPS} ${arg}") + set(GLFW_PKG_DEPS "${GLFW_PKG_DEPS} ${arg}" CACHE INTERNAL + "GLFW pkg-config Requires.private") endforeach() foreach(arg ${glfw_PKG_LIBS}) - set(GLFW_PKG_LIBS "${GLFW_PKG_LIBS} ${arg}") + set(GLFW_PKG_LIBS "${GLFW_PKG_LIBS} ${arg}" CACHE INTERNAL + "GLFW pkg-config Libs.private") endforeach() #-------------------------------------------------------------------- -- cgit v1.2.3 From ae2e48c77fa7e340ff6faea9366f61186b50622d Mon Sep 17 00:00:00 2001 From: Ahmad Fatoum Date: Sat, 4 May 2019 22:48:25 +0200 Subject: CMake: don't use system GLFW headers if using built-in GLFW This fixes the current CI failure. --- src/CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 7b69e0f9..8ccdc932 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -37,6 +37,7 @@ if(NOT glfw3_FOUND AND NOT USE_EXTERNAL_GLFW STREQUAL "ON" AND "${PLATFORM}" MAT add_subdirectory(external/glfw) list(APPEND raylib_sources $) + include_directories(BEFORE SYSTEM external/glfw/include) else() MESSAGE(STATUS "Using external GLFW") set(GLFW_PKG_DEPS glfw3) -- cgit v1.2.3 From 80c8599e818fe765f6129bcdb2fda859c8f193cb Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 6 May 2019 10:07:06 +0200 Subject: Avoid warnings pre-evaluating values Variable operations inside the functions should be evaluated before the function operations. --- src/easings.h | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) (limited to 'src') diff --git a/src/easings.h b/src/easings.h index 810aeccb..892ce352 100644 --- a/src/easings.h +++ b/src/easings.h @@ -112,30 +112,30 @@ EASEDEF float EaseSineOut(float t, float b, float c, float d) { return (c*sin(t/ EASEDEF float EaseSineInOut(float t, float b, float c, float d) { return (-c/2*(cos(PI*t/d) - 1) + b); } // Circular Easing functions -EASEDEF float EaseCircIn(float t, float b, float c, float d) { return (-c*(sqrt(1 - (t/=d)*t) - 1) + b); } -EASEDEF float EaseCircOut(float t, float b, float c, float d) { return (c*sqrt(1 - (t=t/d-1)*t) + b); } +EASEDEF float EaseCircIn(float t, float b, float c, float d) { t /= d; return (-c*(sqrt(1 - t*t) - 1) + b); } +EASEDEF float EaseCircOut(float t, float b, float c, float d) { t = t/d - 1; return (c*sqrt(1 - t*t) + b); } EASEDEF float EaseCircInOut(float t, float b, float c, float d) { if ((t/=d/2) < 1) return (-c/2*(sqrt(1 - t*t) - 1) + b); - return (c/2*(sqrt(1 - t*(t-=2)) + 1) + b); + t -= 2; return (c/2*(sqrt(1 - t*t) + 1) + b); } // Cubic Easing functions -EASEDEF float EaseCubicIn(float t, float b, float c, float d) { return (c*(t/=d)*t*t + b); } -EASEDEF float EaseCubicOut(float t, float b, float c, float d) { return (c*((t=t/d-1)*t*t + 1) + b); } +EASEDEF float EaseCubicIn(float t, float b, float c, float d) { t /= d; return (c*t*t*t + b); } +EASEDEF float EaseCubicOut(float t, float b, float c, float d) { t = t/d-1; return (c*(t*t*t + 1) + b); } EASEDEF float EaseCubicInOut(float t, float b, float c, float d) { if ((t/=d/2) < 1) return (c/2*t*t*t + b); - return (c/2*((t-=2)*t*t + 2) + b); + t -= 2; return (c/2*(t*t*t + 2) + b); } // Quadratic Easing functions -EASEDEF float EaseQuadIn(float t, float b, float c, float d) { return (c*(t/=d)*t + b); } -EASEDEF float EaseQuadOut(float t, float b, float c, float d) { return (-c*(t/=d)*(t-2) + b); } +EASEDEF float EaseQuadIn(float t, float b, float c, float d) { t /= d; return (c*t*t + b); } +EASEDEF float EaseQuadOut(float t, float b, float c, float d) { t /= d; return (-c*t*(t - 2) + b); } EASEDEF float EaseQuadInOut(float t, float b, float c, float d) { if ((t/=d/2) < 1) return (((c/2)*(t*t)) + b); - return (-c/2*(((t-2)*(--t)) - 1) + b); + t--; return (-c/2*(((t - 2)*t) - 1) + b); } // Exponential Easing functions @@ -161,16 +161,22 @@ EASEDEF float EaseBackIn(float t, float b, float c, float d) EASEDEF float EaseBackOut(float t, float b, float c, float d) { float s = 1.70158f; - return (c*((t=t/d-1)*t*((s + 1)*t + s) + 1) + b); + t = t/d - 1; + return (c*(t*t*((s + 1)*t + s) + 1) + b); } EASEDEF float EaseBackInOut(float t, float b, float c, float d) { float s = 1.70158f; - if ((t/=d/2) < 1) return (c/2*(t*t*(((s*=(1.525f)) + 1)*t - s)) + b); + if ((t/=d/2) < 1) + { + s *= 1.525f; + return (c/2*(t*t*((s + 1)*t - s)) + b); + } float postFix = t-=2; - return (c/2*((postFix)*t*(((s*=(1.525f)) + 1)*t + s) + 2) + b); + s *= 1.525f; + return (c/2*((postFix)*t*((s + 1)*t + s) + 2) + b); } // Bounce Easing functions -- cgit v1.2.3 From 528e164ac5e1a4ecca404c7f54e98325a55b959f Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 6 May 2019 10:17:34 +0200 Subject: Corrected issue with wrong text measuring --- src/text.c | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/text.c b/src/text.c index 15b8d555..1050d12d 100644 --- a/src/text.c +++ b/src/text.c @@ -833,8 +833,8 @@ void DrawText(const char *text, int posX, int posY, int fontSize, Color color) void DrawTextEx(Font font, const char *text, Vector2 position, float fontSize, float spacing, Color tint) { int length = strlen(text); - int textOffsetX = 0; // Offset between characters int textOffsetY = 0; // Required for line break! + float textOffsetX = 0.0f; // Offset between characters float scaleFactor = 0.0f; int letter = 0; // Current character @@ -856,7 +856,7 @@ void DrawTextEx(Font font, const char *text, Vector2 position, float fontSize, f { // NOTE: Fixed line spacing of 1.5 lines textOffsetY += (int)((font.baseSize + font.baseSize/2)*scaleFactor); - textOffsetX = 0; + textOffsetX = 0.0f; } else { @@ -869,8 +869,8 @@ void DrawTextEx(Font font, const char *text, Vector2 position, float fontSize, f font.chars[index].rec.height*scaleFactor }, (Vector2){ 0, 0 }, 0.0f, tint); } - if (font.chars[index].advanceX == 0) textOffsetX += (int)(font.chars[index].rec.width*scaleFactor + spacing); - else textOffsetX += (int)(font.chars[index].advanceX*scaleFactor + spacing); + if (font.chars[index].advanceX == 0) textOffsetX += ((float)font.chars[index].rec.width*scaleFactor + spacing); + else textOffsetX += ((float)font.chars[index].advanceX*scaleFactor + spacing); } } } @@ -1053,6 +1053,7 @@ Vector2 MeasureTextEx(Font font, const char *text, float fontSize, float spacing int next = 1; letter = GetNextCodepoint(&text[i], &next); + // NOTE: normally we exit the decoding sequence as soon as a bad byte is found (and return 0x3f) // but we need to draw all of the bad bytes using the '?' symbol so to not skip any we set `next = 1` if(letter == 0x3f) next = 1; -- cgit v1.2.3 From afd90a5a5655724dc56466fa0c2d42c3f702d88a Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 7 May 2019 09:50:40 +0200 Subject: Add comment tweak --- src/core.c | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/core.c b/src/core.c index def60d68..1055b8a6 100644 --- a/src/core.c +++ b/src/core.c @@ -860,6 +860,7 @@ void SetWindowMinSize(int width, int height) } // Set window dimensions +// TODO: Issues on HighDPI scaling void SetWindowSize(int width, int height) { #if defined(PLATFORM_DESKTOP) -- cgit v1.2.3 From e0e2346c2266d8f8f09a2e1e68fffd61b49afa8d Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 7 May 2019 10:05:21 +0200 Subject: NO SUPPORT_BUSY_WAIT_LOOP by default --- src/Makefile | 4 ++-- src/config.h | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/Makefile b/src/Makefile index ea09aa9f..35a10bc7 100644 --- a/src/Makefile +++ b/src/Makefile @@ -437,7 +437,7 @@ else ifeq ($(RAYLIB_LIBTYPE),SHARED) ifeq ($(PLATFORM),PLATFORM_DESKTOP) ifeq ($(PLATFORM_OS),WINDOWS) - $(CC) -shared -o $(RAYLIB_RELEASE_PATH)/raylib.dll $(OBJS) -L$(RAYLIB_RELEASE_PATH) -static-libgcc -lopengl32 -lgdi32 -Wl,--out-implib,$(RAYLIB_RELEASE_PATH)/libraylibdll.a + $(CC) -shared -o $(RAYLIB_RELEASE_PATH)/raylib.dll $(OBJS) -L$(RAYLIB_RELEASE_PATH) -static-libgcc -lopengl32 -lgdi32 -lwinmm -Wl,--out-implib,$(RAYLIB_RELEASE_PATH)/libraylibdll.a @echo "raylib dynamic library (raylib.dll) and import library (libraylibdll.a) generated!" endif ifeq ($(PLATFORM_OS),LINUX) @@ -534,7 +534,7 @@ raygui.o : raygui.c raygui.h physac.o : physac.c physac.h @echo #define PHYSAC_IMPLEMENTATION > physac.c @echo #include "$(RAYLIB_MODULE_PHYSAC_PATH)/physac.h" > physac.c - $(CC) -c $< $(CFLAGS) $(INCLUDE_PATHS) -D$(PLATFORM) -DRAYGUI_IMPLEMENTATION + $(CC) -c $< $(CFLAGS) $(INCLUDE_PATHS) -D$(PLATFORM) -DPHYSAC_IMPLEMENTATION # Install generated and needed files to desired directories. diff --git a/src/config.h b/src/config.h index 77e936bd..ebe1a7da 100644 --- a/src/config.h +++ b/src/config.h @@ -43,7 +43,7 @@ // Mouse gestures are directly mapped like touches and processed by gestures system #define SUPPORT_MOUSE_GESTURES 1 // Use busy wait loop for timing sync, if not defined, a high-resolution timer is setup and used -#define SUPPORT_BUSY_WAIT_LOOP 1 +//#define SUPPORT_BUSY_WAIT_LOOP 1 // Wait for events passively (sleeping while no events) instead of polling them actively every frame //#define SUPPORT_EVENTS_WAITING 1 // Allow automatic screen capture of current screen pressing F12, defined in KeyCallback() -- cgit v1.2.3 From f6d1448da94e388a6d114023c12047d6e67ae615 Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 7 May 2019 15:15:23 +0200 Subject: Review CMake option flags --- src/CMakeOptions.txt | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) (limited to 'src') diff --git a/src/CMakeOptions.txt b/src/CMakeOptions.txt index b5048b8a..43b083e6 100644 --- a/src/CMakeOptions.txt +++ b/src/CMakeOptions.txt @@ -21,21 +21,19 @@ endif() option(INCLUDE_EVERYTHING "Include everything disabled by default (for CI usage" OFF) set(OFF ${INCLUDE_EVERYTHING} CACHE INTERNAL "Replace any OFF by default with \${OFF} to have it covered by this option") - # core.c -option(SUPPORT_BUSY_WAIT_LOOP "Use busy wait loop for timing sync instead of a high-resolution timer" ON) -option(SUPPORT_EVENTS_WAITING "Wait for events passively (sleeping while no events) instead of polling them actively every frame" OFF) option(SUPPORT_CAMERA_SYSTEM "Provide camera module (camera.h) with multiple predefined cameras: free, 1st/3rd person, orbital" ON) +option(SUPPORT_GESTURES_SYSTEM "Gestures module is included (gestures.h) to support gestures detection: tap, hold, swipe, drag" ON) +option(SUPPORT_MOUSE_GESTURES "Mouse gestures are directly mapped like touches and processed by gestures system" ON) option(SUPPORT_DEFAULT_FONT "Default font is loaded on window initialization to be available for the user to render simple text. If enabled, uses external module functions to load default raylib font (module: text)" ON) option(SUPPORT_SCREEN_CAPTURE "Allow automatic screen capture of current screen pressing F12, defined in KeyCallback()" ON) option(SUPPORT_GIF_RECORDING "Allow automatic gif recording of current screen pressing CTRL+F12, defined in KeyCallback()" ON) -option(SUPPORT_GESTURES_SYSTEM "Gestures module is included (gestures.h) to support gestures detection: tap, hold, swipe, drag" ON) -option(SUPPORT_MOUSE_GESTURES "Mouse gestures are directly mapped like touches and processed by gestures system" ON) +option(SUPPORT_BUSY_WAIT_LOOP "Use busy wait loop for timing sync instead of a high-resolution timer" OFF) +option(SUPPORT_EVENTS_WAITING "Wait for events passively (sleeping while no events) instead of polling them actively every frame" OFF) option(SUPPORT_HIGH_DPI "Support high DPI displays" OFF) # rlgl.h option(SUPPORT_VR_SIMULATOR "Support VR simulation functionality (stereo rendering)" ON) -option(SUPPORT_DISTORTION_SHADER "Include stereo rendering distortion shader (shader_distortion.h)" ON) # shapes.c option(SUPPORT_FONT_TEXTURE "Draw rectangle shapes using font texture white character instead of default white texture. Allows drawing rectangles and text with a single draw call, very useful for GUI systems!" ON) @@ -44,6 +42,7 @@ option(SUPPORT_QUADS_DRAW_MODE "Use QUADS instead of TRIANGLES for drawing when # textures.c option(SUPPORT_IMAGE_EXPORT "Support image exporting to file" ON) option(SUPPORT_IMAGE_GENERATION "Support procedural image generation functionality (gradient, spot, perlin-noise, cellular)" ON) +option(SUPPORT_IMAGE_MANIPULATION "Support multiple image editing functions to scale, adjust colors, flip, draw on images, crop... If not defined only three image editing functions supported: ImageFormat(), ImageAlphaMask(), ImageToPOT()" ON) option(SUPPORT_FILEFORMAT_PNG "Support loading PNG as textures" ON) option(SUPPORT_FILEFORMAT_DDS "Support loading DDS as textures" ON) option(SUPPORT_FILEFORMAT_HDR "Support loading HDR as textures" ON) @@ -57,26 +56,28 @@ option(SUPPORT_FILEFORMAT_PSD "Support loading PSD as textures" ${OFF}) option(SUPPORT_FILEFORMAT_PKM "Support loading PKM as textures" ${OFF}) option(SUPPORT_FILEFORMAT_PVR "Support loading PVR as textures" ${OFF}) +# text.c +option(SUPPORT_FILEFORMAT_FNT "Support loading fonts in FNT format" ON) +option(SUPPORT_FILEFORMAT_TTF "Support loading font in TTF/OTF format" ON) + # models.c +option(SUPPORT_MESH_GENERATION "Support procedural mesh generation functions, uses external par_shapes.h library. NOTE: Some generated meshes DO NOT include generated texture coordinates" ON) option(SUPPORT_FILEFORMAT_OBJ "Support loading OBJ file format" ON) option(SUPPORT_FILEFORMAT_MTL "Support loading MTL file format" ON) -option(SUPPORT_MESH_GENERATION "Support procedural mesh generation functions, uses external par_shapes.h library. NOTE: Some generated meshes DO NOT include generated texture coordinates" ON) +option(SUPPORT_FILEFORMAT_IQM "Support loading IQM file format" ON) +option(SUPPORT_FILEFORMAT_GLTF "Support loading GLTF file format" ON) # raudio.c option(SUPPORT_FILEFORMAT_WAV "Support loading WAV for sound" ON) option(SUPPORT_FILEFORMAT_OGG "Support loading OGG for sound" ON) option(SUPPORT_FILEFORMAT_XM "Support loading XM for sound" ON) option(SUPPORT_FILEFORMAT_MOD "Support loading MOD for sound" ON) +option(SUPPORT_FILEFORMAT_MP3 "Support loading MP3 for sound" ${ON}) option(SUPPORT_FILEFORMAT_FLAC "Support loading FLAC for sound" ${OFF}) # utils.c option(SUPPORT_TRACELOG "Show TraceLog() output messages. NOTE: By default LOG_DEBUG traces not shown" ON) -option(SUPPORT_FILEFORMAT_FNT "Support loading fonts in FNT format" ON) -option(SUPPORT_FILEFORMAT_TTF "Support loading font in TTF format" ON) - -option(SUPPORT_IMAGE_MANIPULATION "Support multiple image editing functions to scale, adjust colors, flip, draw on images, crop... If not defined only three image editing functions supported: ImageFormat(), ImageAlphaMask(), ImageToPOT()" ON) - if(NOT (STATIC OR SHARED)) message(FATAL_ERROR "Nothing to do if both -DSHARED=OFF and -DSTATIC=OFF...") endif() -- cgit v1.2.3 From 98243877739fa59ffd7e40cae20b57a13c2dbb93 Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 7 May 2019 15:16:14 +0200 Subject: Added resource file for raylib.dll Some minor tweaks --- src/Makefile | 1 + src/raylib.dll.rc | 27 +++++++++++++++++++++++++++ src/raylib.h | 5 +++-- src/raylib.rc | 2 +- 4 files changed, 32 insertions(+), 3 deletions(-) create mode 100644 src/raylib.dll.rc (limited to 'src') diff --git a/src/Makefile b/src/Makefile index 35a10bc7..c50d4279 100644 --- a/src/Makefile +++ b/src/Makefile @@ -437,6 +437,7 @@ else ifeq ($(RAYLIB_LIBTYPE),SHARED) ifeq ($(PLATFORM),PLATFORM_DESKTOP) ifeq ($(PLATFORM_OS),WINDOWS) + # TODO: Compile resource file raylib.dll.rc for linkage on raylib.dll generation $(CC) -shared -o $(RAYLIB_RELEASE_PATH)/raylib.dll $(OBJS) -L$(RAYLIB_RELEASE_PATH) -static-libgcc -lopengl32 -lgdi32 -lwinmm -Wl,--out-implib,$(RAYLIB_RELEASE_PATH)/libraylibdll.a @echo "raylib dynamic library (raylib.dll) and import library (libraylibdll.a) generated!" endif diff --git a/src/raylib.dll.rc b/src/raylib.dll.rc new file mode 100644 index 00000000..e5dca309 --- /dev/null +++ b/src/raylib.dll.rc @@ -0,0 +1,27 @@ +GLFW_ICON ICON "raylib.ico" + +1 VERSIONINFO +FILEVERSION 2,5,0,0 +PRODUCTVERSION 2,5,0,0 +BEGIN + BLOCK "StringFileInfo" + BEGIN + //BLOCK "080904E4" // English UK + BLOCK "040904E4" // English US + BEGIN + //VALUE "CompanyName", "raylib technologies" + VALUE "FileDescription", "raylib dynamic library (www.raylib.com)" + VALUE "FileVersion", "2.5.0" + VALUE "InternalName", "raylib_dll" + VALUE "LegalCopyright", "(c) 2019 Ramon Santamaria (@raysan5)" + //VALUE "OriginalFilename", "raylib.dll" + VALUE "ProductName", "raylib" + VALUE "ProductVersion", "2.5.0" + END + END + BLOCK "VarFileInfo" + BEGIN + //VALUE "Translation", 0x809, 1252 // English UK + VALUE "Translation", 0x409, 1252 // English US + END +END diff --git a/src/raylib.h b/src/raylib.h index 3bd64b3b..21202f18 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -1174,13 +1174,14 @@ RLAPI void DrawTextRecEx(Font font, const char *text, Rectangle rec, float fontS RLAPI int MeasureText(const char *text, int fontSize); // Measure string width for default font RLAPI Vector2 MeasureTextEx(Font font, const char *text, float fontSize, float spacing); // Measure string size for Font RLAPI int GetGlyphIndex(Font font, int character); // Get index position for a unicode character on font -RLAPI int GetNextCodepoint(const char* text, int* count); // Returns next codepoint in a UTF8 encoded `text` or 0x3f(`?`) on failure. `count` will hold the total number of bytes processed. +RLAPI int GetNextCodepoint(const char *text, int *count); // Returns next codepoint in a UTF8 encoded string + // NOTE: 0x3f(`?`) is returned on failure, `count` will hold the total number of bytes processed // Text strings management functions // NOTE: Some strings allocate memory internally for returned strings, just be careful! RLAPI bool TextIsEqual(const char *text1, const char *text2); // Check if two text string are equal RLAPI unsigned int TextLength(const char *text); // Get text length, checks for '\0' ending -RLAPI unsigned int TextCountCodepoints(const char *text); // Get total number of characters(codepoints) in a UTF8 encoded `text` until '\0' is found. +RLAPI unsigned int TextCountCodepoints(const char *text); // Get total number of characters (codepoints) in a UTF8 encoded string RLAPI const char *TextFormat(const char *text, ...); // Text formatting with variables (sprintf style) RLAPI const char *TextSubtext(const char *text, int position, int length); // Get a piece of a text string RLAPI const char *TextReplace(char *text, const char *replace, const char *by); // Replace text string (memory should be freed!) diff --git a/src/raylib.rc b/src/raylib.rc index c2fdfa46..4d204c65 100644 --- a/src/raylib.rc +++ b/src/raylib.rc @@ -10,7 +10,7 @@ BEGIN BLOCK "040904E4" // English US BEGIN //VALUE "CompanyName", "raylib technologies" - VALUE "FileDescription", "Created using raylib (www.raylib.com)" + VALUE "FileDescription", "raylib application (www.raylib.com)" VALUE "FileVersion", "2.5.0" VALUE "InternalName", "raylib app" VALUE "LegalCopyright", "(c) 2019 Ramon Santamaria (@raysan5)" -- cgit v1.2.3 From f6d1ffd4cd0291dc161ae38b0ac040afc6b41c90 Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 7 May 2019 15:23:56 +0200 Subject: Tweak ON flag --- src/CMakeOptions.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/CMakeOptions.txt b/src/CMakeOptions.txt index 43b083e6..5e1d9e47 100644 --- a/src/CMakeOptions.txt +++ b/src/CMakeOptions.txt @@ -72,7 +72,7 @@ option(SUPPORT_FILEFORMAT_WAV "Support loading WAV for sound" ON) option(SUPPORT_FILEFORMAT_OGG "Support loading OGG for sound" ON) option(SUPPORT_FILEFORMAT_XM "Support loading XM for sound" ON) option(SUPPORT_FILEFORMAT_MOD "Support loading MOD for sound" ON) -option(SUPPORT_FILEFORMAT_MP3 "Support loading MP3 for sound" ${ON}) +option(SUPPORT_FILEFORMAT_MP3 "Support loading MP3 for sound" ON) option(SUPPORT_FILEFORMAT_FLAC "Support loading FLAC for sound" ${OFF}) # utils.c -- cgit v1.2.3 From 4773de26a50c29ae918e306c9936ad9d4ebf80aa Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 7 May 2019 22:56:38 +0200 Subject: Added WinMM library Required for high resolution timer --- src/external/glfw/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/external/glfw/CMakeLists.txt b/src/external/glfw/CMakeLists.txt index a9ed8554..62906ee8 100644 --- a/src/external/glfw/CMakeLists.txt +++ b/src/external/glfw/CMakeLists.txt @@ -190,7 +190,7 @@ endif() #-------------------------------------------------------------------- if (_GLFW_WIN32) - list(APPEND glfw_PKG_LIBS "-lgdi32") + list(APPEND glfw_PKG_LIBS "-lgdi32 -lwinmm") if (GLFW_USE_HYBRID_HPG) set(_GLFW_USE_HYBRID_HPG 1) -- cgit v1.2.3 From 97c8a28aaac8d2ac8689d18a619d32107d6b96f7 Mon Sep 17 00:00:00 2001 From: Ray Date: Wed, 8 May 2019 18:33:09 +0200 Subject: Remove trail spaces --- src/core.c | 18 +++++++++--------- src/rlgl.h | 28 ++++++++++++++-------------- src/shapes.c | 8 ++++---- src/textures.c | 4 ++-- 4 files changed, 29 insertions(+), 29 deletions(-) (limited to 'src') diff --git a/src/core.c b/src/core.c index 1055b8a6..5b0ca86c 100644 --- a/src/core.c +++ b/src/core.c @@ -1302,7 +1302,7 @@ void EndTextureMode(void) // Set viewport to default framebuffer size SetupViewport(renderWidth, renderHeight); - + // Reset current screen size currentWidth = GetScreenWidth(); currentHeight = GetScreenHeight(); @@ -2241,7 +2241,7 @@ Vector2 GetMousePosition(void) #endif #if defined(PLATFORM_WEB) Vector2 pos = GetTouchPosition(0); - + // Touch position has priority over mouse position if ((pos.x > 0) && (pos.y > 0)) position = pos; // There was a touch! #endif @@ -2933,7 +2933,7 @@ static void SetupViewport(int width, int height) { renderWidth = width; renderHeight = height; - + // Set viewport width and height // NOTE: We consider render size and offset in case black bars are required and // render area does not match full display area (this situation is only applicable on fullscreen mode) @@ -2944,7 +2944,7 @@ static void SetupViewport(int width, int height) // Set orthographic projection to current framebuffer size // NOTE: Configured top-left corner as (0, 0) - rlOrtho(0, renderWidth, renderHeight, 0, 0.0f, 1.0f); + rlOrtho(0, renderWidth, renderHeight, 0, 0.0f, 1.0f); rlMatrixMode(RL_MODELVIEW); // Switch back to MODELVIEW matrix rlLoadIdentity(); // Reset current matrix (MODELVIEW) @@ -3382,7 +3382,7 @@ static void PollInputEvents(void) // NOTE: Postprocessing texture is not scaled to new size windowResized = true; - + } break; case UWP_MSG_SET_GAME_TIME: currentTime = msg->paramDouble0; break; default: break; @@ -3734,7 +3734,7 @@ static void WindowSizeCallback(GLFWwindow *window, int width, int height) screenHeight = height; currentWidth = width; currentHeight = height; - + // NOTE: Postprocessing texture is not scaled to new size windowResized = true; @@ -4361,7 +4361,7 @@ static void InitEvdevInput(void) // Open the linux directory of "/dev/input" directory = opendir(DEFAULT_EVDEV_PATH); - + if (directory) { while ((entity = readdir(directory)) != NULL) @@ -4708,7 +4708,7 @@ static void *EventThread(void *arg) if ((event.code >= 1) && (event.code <= 255)) //Keyboard keys appear for codes 1 to 255 { keycode = keymap_US[event.code & 0xFF]; // The code we get is a scancode so we look up the apropriate keycode - + // Make sure we got a valid keycode if ((keycode > 0) && (keycode < sizeof(currentKeyState))) { @@ -4721,7 +4721,7 @@ static void *EventThread(void *arg) lastKeyPressedEvdev.Head = (lastKeyPressedEvdev.Head + 1) & 0x07; // Increment the head pointer forwards and binary wraparound after 7 (fifo is 8 elements long) // TODO: This fifo is not fully threadsafe with multiple writers, so multiple keyboards hitting a key at the exact same time could miss a key (double write to head before it was incremented) } - + TraceLog(LOG_DEBUG, "KEY%s ScanCode: %4i KeyCode: %4i",event.value == 0 ? "UP":"DOWN", event.code, keycode); } } diff --git a/src/rlgl.h b/src/rlgl.h index e98c6dc3..d8db16ae 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -64,7 +64,7 @@ #if defined(RLGL_STANDALONE) #define RAYMATH_STANDALONE #define RAYMATH_HEADER_ONLY - + #if defined(_WIN32) && defined(BUILD_LIBTYPE_SHARED) #define RLAPI __declspec(dllexport) // We are building raylib as a Win32 shared library (.dll) #elif defined(_WIN32) && defined(USE_LIBTYPE_SHARED) @@ -72,7 +72,7 @@ #else #define RLAPI // We are building or using raylib as a static library (or Linux shared library) #endif - + // Allow custom memory allocators #ifndef RL_MALLOC #define RL_MALLOC(sz) malloc(sz) @@ -544,7 +544,7 @@ RLAPI void EndBlendMode(void); // End blending mode (re RLAPI void InitVrSimulator(void); // Init VR simulator for selected device parameters RLAPI void CloseVrSimulator(void); // Close VR simulator for current device RLAPI void UpdateVrTracking(Camera *camera); // Update VR tracking (position and orientation) and camera -RLAPI void SetVrConfiguration(VrDeviceInfo info, Shader distortion); // Set stereo rendering configuration parameters +RLAPI void SetVrConfiguration(VrDeviceInfo info, Shader distortion); // Set stereo rendering configuration parameters RLAPI bool IsVrSimulatorReady(void); // Detect if VR simulator is ready RLAPI void ToggleVrMode(void); // Enable/Disable VR experience RLAPI void BeginVrDrawing(void); // Begin VR simulator stereo rendering @@ -1567,11 +1567,11 @@ void rlglInit(int width, int height) glBindVertexArray = (PFNGLBINDVERTEXARRAYOESPROC)eglGetProcAddress("glBindVertexArrayOES"); glDeleteVertexArrays = (PFNGLDELETEVERTEXARRAYSOESPROC)eglGetProcAddress("glDeleteVertexArraysOES"); //glIsVertexArray = (PFNGLISVERTEXARRAYOESPROC)eglGetProcAddress("glIsVertexArrayOES"); // NOTE: Fails in WebGL, omitted - + if (glGenVertexArrays == NULL) printf("glGenVertexArrays is NULL.\n"); // WEB: ISSUE FOUND! ...but why? if (glBindVertexArray == NULL) printf("glBindVertexArray is NULL.\n"); // WEB: ISSUE FOUND! ...but why? } - + // TODO: HACK REVIEW! // For some reason on raylib 2.5, VAO usage breaks the build // error seems related to function pointers but I can not get detailed info... @@ -2488,19 +2488,19 @@ void rlLoadMesh(Mesh *mesh, bool dynamic) unsigned int rlLoadAttribBuffer(unsigned int vaoId, int shaderLoc, void *buffer, int size, bool dynamic) { unsigned int id = 0; - + #if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) int drawHint = GL_STATIC_DRAW; if (dynamic) drawHint = GL_DYNAMIC_DRAW; - + if (vaoSupported) glBindVertexArray(vaoId); - + glGenBuffers(1, &id); glBindBuffer(GL_ARRAY_BUFFER, id); glBufferData(GL_ARRAY_BUFFER, size, buffer, drawHint); glVertexAttribPointer(shaderLoc, 2, GL_FLOAT, 0, 0, 0); glEnableVertexAttribArray(shaderLoc); - + if (vaoSupported) glBindVertexArray(0); #endif @@ -3536,7 +3536,7 @@ void InitVrSimulator(void) // Initialize framebuffer and textures for stereo rendering // NOTE: Screen size should match HMD aspect ratio stereoFbo = rlLoadRenderTexture(screenWidth, screenHeight, UNCOMPRESSED_R8G8B8A8, 24, false); - + vrSimulatorReady = true; #else TraceLog(LOG_WARNING, "VR Simulator not supported on OpenGL 1.1"); @@ -3558,13 +3558,13 @@ void CloseVrSimulator(void) #endif } -// Set stereo rendering configuration parameters +// Set stereo rendering configuration parameters void SetVrConfiguration(VrDeviceInfo hmd, Shader distortion) { #if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) // Reset vrConfig for a new values assignment memset(&vrConfig, 0, sizeof(vrConfig)); - + // Assign distortion shader vrConfig.distortionShader = distortion; @@ -3620,7 +3620,7 @@ void SetVrConfiguration(VrDeviceInfo hmd, Shader distortion) // Compute eyes Viewports vrConfig.eyeViewportRight[2] = hmd.hResolution/2; vrConfig.eyeViewportRight[3] = hmd.vResolution; - + vrConfig.eyeViewportLeft[0] = hmd.hResolution/2; vrConfig.eyeViewportLeft[1] = 0; vrConfig.eyeViewportLeft[2] = hmd.hResolution/2; @@ -3677,7 +3677,7 @@ void BeginVrDrawing(void) #if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) if (vrSimulatorReady) { - + rlEnableRenderTexture(stereoFbo.id); // Setup framebuffer for stereo rendering //glEnable(GL_FRAMEBUFFER_SRGB); // Enable SRGB framebuffer (only if required) diff --git a/src/shapes.c b/src/shapes.c index 93b332f5..64beb8ca 100644 --- a/src/shapes.c +++ b/src/shapes.c @@ -777,9 +777,9 @@ void DrawRectangleRounded(Rectangle rec, float roundness, int segments, Color co #if defined(SUPPORT_QUADS_DRAW_MODE) if (rlCheckBufferLimit(16*segments/2 + 5*4)) rlglDraw(); - + rlEnableTexture(GetShapesTexture().id); - + rlBegin(RL_QUADS); // Draw all of the 4 corners: [1] Upper Left Corner, [3] Upper Right Corner, [5] Lower Right Corner, [7] Lower Left Corner for (int k = 0; k < 4; ++k) // Hope the compiler is smart enough to unroll this loop @@ -1010,9 +1010,9 @@ void DrawRectangleRoundedLines(Rectangle rec, float roundness, int segments, int { #if defined(SUPPORT_QUADS_DRAW_MODE) if (rlCheckBufferLimit(4*4*segments + 4*4)) rlglDraw(); // 4 corners with 4 vertices for each segment + 4 rectangles with 4 vertices each - + rlEnableTexture(GetShapesTexture().id); - + rlBegin(RL_QUADS); // Draw all of the 4 corners first: Upper Left Corner, Upper Right Corner, Lower Right Corner, Lower Left Corner for (int k = 0; k < 4; ++k) // Hope the compiler is smart enough to unroll this loop diff --git a/src/textures.c b/src/textures.c index eb743026..a405f78b 100644 --- a/src/textures.c +++ b/src/textures.c @@ -112,11 +112,11 @@ defined(SUPPORT_FILEFORMAT_GIF) || \ defined(SUPPORT_FILEFORMAT_PIC) || \ defined(SUPPORT_FILEFORMAT_HDR)) - + #define STBI_MALLOC RL_MALLOC #define STBI_FREE RL_FREE #define STBI_REALLOC(p,newsz) realloc(p,newsz) - + #define STB_IMAGE_IMPLEMENTATION #include "external/stb_image.h" // Required for: stbi_load_from_file() // NOTE: Used to read image data (multiple formats support) -- cgit v1.2.3 From d3dae384497f61ad7eb1d9578db8860e6e6336aa Mon Sep 17 00:00:00 2001 From: ProfJski <49599659+ProfJski@users.noreply.github.com> Date: Wed, 8 May 2019 13:54:12 -0400 Subject: Update CheckCollisionSpheres() to avoid sqrt Square root calls are computationally expensive. In this case, they can be avoided. Instead of checking distance Date: Wed, 8 May 2019 14:14:57 -0400 Subject: Update models.c --- src/models.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/models.c b/src/models.c index 9e534a7c..fc93c141 100644 --- a/src/models.c +++ b/src/models.c @@ -2472,7 +2472,7 @@ void DrawBoundingBox(BoundingBox box, Color color) // Detect collision between two spheres bool CheckCollisionSpheres(Vector3 centerA, float radiusA, Vector3 centerB, float radiusB) { - return Vector3DotProduct(Vector3Subtract(B,A),Vector3Subtract(B,A))<=(RadA+RadB)*(RadA+RadB); + return Vector3DotProduct(Vector3Subtract(centerB,centerA),Vector3Subtract(centerB,centerA))<=(radiusA+radiusB)*(radiusA+radiusB); } // Detect collision between two boxes -- cgit v1.2.3 From 46bac0ba2c4e00eae12c6070e2c028244be75c75 Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 9 May 2019 16:09:49 +0200 Subject: Add comment in CheckCollisionSpheres() --- src/models.c | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/models.c b/src/models.c index fc93c141..3f809f8d 100644 --- a/src/models.c +++ b/src/models.c @@ -2472,7 +2472,24 @@ void DrawBoundingBox(BoundingBox box, Color color) // Detect collision between two spheres bool CheckCollisionSpheres(Vector3 centerA, float radiusA, Vector3 centerB, float radiusB) { - return Vector3DotProduct(Vector3Subtract(centerB,centerA),Vector3Subtract(centerB,centerA))<=(radiusA+radiusB)*(radiusA+radiusB); + bool collision = false; + + // Simple way to check for collision, just checking distance between two points + // Unfortunately, sqrtf() is a costly operation, so we avoid it with following solution + /* + float dx = centerA.x - centerB.x; // X distance between centers + float dy = centerA.y - centerB.y; // Y distance between centers + float dz = centerA.z - centerB.z; // Y distance between centers + + float distance = sqrtf(dx*dx + dy*dy + dz*dz); // Distance between centers + + if (distance <= (radiusA + radiusB)) collision = true; + */ + + // Check for distances squared to avoid sqrtf() + collision = (Vector3DotProduct(Vector3Subtract(centerB, centerA), Vector3Subtract(centerB, centerA)) <= (radiusA + radiusB)*(radiusA + radiusB)); + + return collision; } // Detect collision between two boxes -- cgit v1.2.3 From a2ed65aa1461addee7093d92ca80615d607e926b Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 9 May 2019 16:10:55 +0200 Subject: Make code a bit clearer for beginners --- src/models.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/models.c b/src/models.c index 3f809f8d..6af33116 100644 --- a/src/models.c +++ b/src/models.c @@ -2487,7 +2487,7 @@ bool CheckCollisionSpheres(Vector3 centerA, float radiusA, Vector3 centerB, floa */ // Check for distances squared to avoid sqrtf() - collision = (Vector3DotProduct(Vector3Subtract(centerB, centerA), Vector3Subtract(centerB, centerA)) <= (radiusA + radiusB)*(radiusA + radiusB)); + if (Vector3DotProduct(Vector3Subtract(centerB, centerA), Vector3Subtract(centerB, centerA)) <= (radiusA + radiusB)*(radiusA + radiusB)) collision = true; return collision; } -- cgit v1.2.3 From 509d9411a1f4a608981a84e6d9b80b40e37b602e Mon Sep 17 00:00:00 2001 From: Demizdor Date: Fri, 10 May 2019 13:57:24 +0300 Subject: Fixed DrawTextRecEx() selection when wordwrap is ON --- src/text.c | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/text.c b/src/text.c index 1050d12d..db4e8f75 100644 --- a/src/text.c +++ b/src/text.c @@ -899,7 +899,7 @@ void DrawTextRecEx(Font font, const char *text, Rectangle rec, float fontSize, f int state = wordWrap? MEASURE_STATE : DRAW_STATE; int startLine = -1; // Index where to begin drawing (where a line begins) int endLine = -1; // Index where to stop drawing (where a line ends) - + int lastk = -1; // Holds last value of the character position for (int i = 0, k = 0; i < length; i++, k++) { int glyphWidth = 0; @@ -954,6 +954,11 @@ void DrawTextRecEx(Font font, const char *text, Rectangle rec, float fontSize, f textOffsetX = 0; i = startLine; glyphWidth = 0; + + // Save character position when we switch states + int tmp = lastk; + lastk = k - 1; + k = tmp; } } @@ -981,7 +986,7 @@ void DrawTextRecEx(Font font, const char *text, Rectangle rec, float fontSize, f bool isGlyphSelected = false; if ((selectStart >= 0) && (k >= selectStart) && (k < (selectStart + selectLength))) { - Rectangle strec = {rec.x + textOffsetX-1, rec.y + textOffsetY, glyphWidth, (font.baseSize + font.baseSize/4)*scaleFactor }; + Rectangle strec = {rec.x + textOffsetX-1, rec.y + textOffsetY, glyphWidth, font.baseSize*scaleFactor }; DrawRectangleRec(strec, selectBack); isGlyphSelected = true; } @@ -1005,6 +1010,7 @@ void DrawTextRecEx(Font font, const char *text, Rectangle rec, float fontSize, f startLine = endLine; endLine = -1; glyphWidth = 0; + k = lastk; state = !state; } } -- cgit v1.2.3 From 561c486ceb2d1563fbcd0bec60a1f1d9e94cb7c0 Mon Sep 17 00:00:00 2001 From: raysan5 Date: Fri, 10 May 2019 20:51:48 +0200 Subject: Add WinMM library for linkage Now it's required on Windows if not using a busy wait loop --- src/physac.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/physac.h b/src/physac.h index 038361a4..374aa4bc 100644 --- a/src/physac.h +++ b/src/physac.h @@ -43,7 +43,7 @@ * NOTE 2: Physac requires static C library linkage to avoid dependency on MinGW DLL (-static -lpthread) * * Use the following code to compile: -* gcc -o $(NAME_PART).exe $(FILE_NAME) -s -static -lraylib -lpthread -lopengl32 -lgdi32 -std=c99 +* gcc -o $(NAME_PART).exe $(FILE_NAME) -s -static -lraylib -lpthread -lopengl32 -lgdi32 -lwinmm -std=c99 * * VERY THANKS TO: * Ramon Santamaria (github: @raysan5) -- cgit v1.2.3 From d50aa32ec88cef70c5fb3182f3e1ff43b6ef4159 Mon Sep 17 00:00:00 2001 From: raysan5 Date: Sun, 12 May 2019 21:51:19 +0200 Subject: Update CMakeLists.txt --- src/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 8ccdc932..b6006c8b 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -46,7 +46,7 @@ endif() add_definitions("-DRAYLIB_CMAKE=1") if(USE_AUDIO) - MESSAGE(STATUS "Audio Backend: mini_al") + MESSAGE(STATUS "Audio Backend: miniaudio") set(sources ${raylib_sources}) else() MESSAGE(STATUS "Audio Backend: None (-DUSE_AUDIO=OFF)") -- cgit v1.2.3 From 3f7b14aeed8bd3b5abc0dd47532c266944d169b6 Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 14 May 2019 18:02:11 +0200 Subject: Corrected web issue --- src/rlgl.h | 14 +------------- 1 file changed, 1 insertion(+), 13 deletions(-) (limited to 'src') diff --git a/src/rlgl.h b/src/rlgl.h index d8db16ae..639a107e 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -1559,8 +1559,6 @@ void rlglInit(int width, int height) // NOTE: Only check on OpenGL ES, OpenGL 3.3 has VAO support as core feature if (strcmp(extList[i], (const char *)"GL_OES_vertex_array_object") == 0) { - vaoSupported = true; - // The extension is supported by our hardware and driver, try to get related functions pointers // NOTE: emscripten does not support VAOs natively, it uses emulation and it reduces overall performance... glGenVertexArrays = (PFNGLGENVERTEXARRAYSOESPROC)eglGetProcAddress("glGenVertexArraysOES"); @@ -1568,19 +1566,9 @@ void rlglInit(int width, int height) glDeleteVertexArrays = (PFNGLDELETEVERTEXARRAYSOESPROC)eglGetProcAddress("glDeleteVertexArraysOES"); //glIsVertexArray = (PFNGLISVERTEXARRAYOESPROC)eglGetProcAddress("glIsVertexArrayOES"); // NOTE: Fails in WebGL, omitted - if (glGenVertexArrays == NULL) printf("glGenVertexArrays is NULL.\n"); // WEB: ISSUE FOUND! ...but why? - if (glBindVertexArray == NULL) printf("glBindVertexArray is NULL.\n"); // WEB: ISSUE FOUND! ...but why? + if ((glGenVertexArrays != NULL) && (glBindVertexArray != NULL) && (glDeleteVertexArrays != NULL)) vaoSupported = true; } - // TODO: HACK REVIEW! - // For some reason on raylib 2.5, VAO usage breaks the build - // error seems related to function pointers but I can not get detailed info... - // Avoiding VAO usage is the only solution for now... :( - // Ref: https://emscripten.org/docs/porting/guidelines/function_pointer_issues.html - #if defined(PLATFORM_WEB) - vaoSupported = false; - #endif - // Check NPOT textures support // NOTE: Only check on OpenGL ES, OpenGL 3.3 has NPOT textures full support as core feature if (strcmp(extList[i], (const char *)"GL_OES_texture_npot") == 0) texNPOTSupported = true; -- cgit v1.2.3 From e8a376c80c61278bb003d4f96b01df2657dc61ec Mon Sep 17 00:00:00 2001 From: Ahmad Fatoum Date: Fri, 10 May 2019 08:16:39 +0200 Subject: CMake: add winmm.dll as Windows dependency Fixes: e0e2346c2266 ("NO SUPPORT_BUSY_WAIT_LOOP by default") --- src/CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index b6006c8b..a467899f 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -73,6 +73,7 @@ if(${PLATFORM} MATCHES "Desktop") endif() elseif(WIN32) add_definitions(-D_CRT_SECURE_NO_WARNINGS) + set(LIBS_PRIVATE ${LIBS_PRIVATE} winmm) else() find_library(pthread NAMES pthread) find_package(OpenGL QUIET) -- cgit v1.2.3 From 4d8b9e595a62e094b840a15efc1d7710128aa1f4 Mon Sep 17 00:00:00 2001 From: Ahmad Fatoum Date: Wed, 15 May 2019 08:14:24 +0200 Subject: external: glfw: Revert "Added WinMM library" This reverts commit 4773de26a50c29ae918e306c9936ad9d4ebf80aa. which adds -lwinmm at the wrong place. It should be in the raylib linker flags, not GLFW's. --- src/external/glfw/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/external/glfw/CMakeLists.txt b/src/external/glfw/CMakeLists.txt index 62906ee8..a9ed8554 100644 --- a/src/external/glfw/CMakeLists.txt +++ b/src/external/glfw/CMakeLists.txt @@ -190,7 +190,7 @@ endif() #-------------------------------------------------------------------- if (_GLFW_WIN32) - list(APPEND glfw_PKG_LIBS "-lgdi32 -lwinmm") + list(APPEND glfw_PKG_LIBS "-lgdi32") if (GLFW_USE_HYBRID_HPG) set(_GLFW_USE_HYBRID_HPG 1) -- cgit v1.2.3 From 0eece03205b04f57f3a93a61c70eb1d69ac32977 Mon Sep 17 00:00:00 2001 From: Ray Date: Wed, 15 May 2019 12:22:29 +0200 Subject: Corrected issue with texture flip X --- src/textures.c | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/textures.c b/src/textures.c index a405f78b..73deed22 100644 --- a/src/textures.c +++ b/src/textures.c @@ -2573,7 +2573,7 @@ void DrawTextureEx(Texture2D texture, Vector2 position, float rotation, float sc // Draw a part of a texture (defined by a rectangle) void DrawTextureRec(Texture2D texture, Rectangle sourceRec, Vector2 position, Color tint) { - Rectangle destRec = { position.x, position.y, sourceRec.width, (float)fabs(sourceRec.height) }; + Rectangle destRec = { position.x, position.y, (float)fabs(sourceRec.width), (float)fabs(sourceRec.height) }; Vector2 origin = { 0.0f, 0.0f }; DrawTexturePro(texture, sourceRec, destRec, origin, 0.0f, tint); @@ -2599,8 +2599,10 @@ void DrawTexturePro(Texture2D texture, Rectangle sourceRec, Rectangle destRec, V { float width = (float)texture.width; float height = (float)texture.height; - - if (sourceRec.width < 0) sourceRec.x -= sourceRec.width; + + bool flipX = false; + + if (sourceRec.width < 0) { flipX = true; sourceRec.width *= -1; } if (sourceRec.height < 0) sourceRec.y -= sourceRec.height; rlEnableTexture(texture.id); @@ -2615,19 +2617,23 @@ void DrawTexturePro(Texture2D texture, Rectangle sourceRec, Rectangle destRec, V rlNormal3f(0.0f, 0.0f, 1.0f); // Normal vector pointing towards viewer // Bottom-left corner for texture and quad - rlTexCoord2f(sourceRec.x/width, sourceRec.y/height); + if (flipX) rlTexCoord2f((sourceRec.x + sourceRec.width)/width, sourceRec.y/height); + else rlTexCoord2f(sourceRec.x/width, sourceRec.y/height); rlVertex2f(0.0f, 0.0f); // Bottom-right corner for texture and quad - rlTexCoord2f(sourceRec.x/width, (sourceRec.y + sourceRec.height)/height); + if (flipX) rlTexCoord2f((sourceRec.x + sourceRec.width)/width, (sourceRec.y + sourceRec.height)/height); + else rlTexCoord2f(sourceRec.x/width, (sourceRec.y + sourceRec.height)/height); rlVertex2f(0.0f, destRec.height); // Top-right corner for texture and quad - rlTexCoord2f((sourceRec.x + sourceRec.width)/width, (sourceRec.y + sourceRec.height)/height); + if (flipX) rlTexCoord2f(sourceRec.x/width, (sourceRec.y + sourceRec.height)/height); + else rlTexCoord2f((sourceRec.x + sourceRec.width)/width, (sourceRec.y + sourceRec.height)/height); rlVertex2f(destRec.width, destRec.height); // Top-left corner for texture and quad - rlTexCoord2f((sourceRec.x + sourceRec.width)/width, sourceRec.y/height); + if (flipX) rlTexCoord2f(sourceRec.x/width, sourceRec.y/height); + else rlTexCoord2f((sourceRec.x + sourceRec.width)/width, sourceRec.y/height); rlVertex2f(destRec.width, 0.0f); rlEnd(); rlPopMatrix(); -- cgit v1.2.3 From 5a1a0a34923fa8ecfcd5d45717b7db63f630b2a7 Mon Sep 17 00:00:00 2001 From: Ray Date: Wed, 15 May 2019 15:12:56 +0200 Subject: Corrected issue with multi-mesh obj models Note that all meshes are loaded as a single one at this moment, loading should be improved! --- src/models.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/models.c b/src/models.c index 6af33116..bd83e925 100644 --- a/src/models.c +++ b/src/models.c @@ -2769,7 +2769,9 @@ static Model LoadOBJ(const char *fileName) else TraceLog(LOG_INFO, "[%s] Model data loaded successfully: %i meshes / %i materials", fileName, meshCount, materialCount); // Init model meshes array - model.meshCount = meshCount; + // TODO: Support multiple meshes... in the meantime, only one mesh is returned + //model.meshCount = meshCount; + model.meshCount = 1; model.meshes = (Mesh *)RL_MALLOC(model.meshCount*sizeof(Mesh)); // Init model materials array -- cgit v1.2.3 From 579d9325510d80cd038c7b4e1965aaf88efea527 Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 16 May 2019 15:30:41 +0200 Subject: Update miniaudio to v0.9.4 --- src/external/miniaudio.h | 9111 ++++++++++++++++++++++++++-------------------- 1 file changed, 5169 insertions(+), 3942 deletions(-) (limited to 'src') diff --git a/src/external/miniaudio.h b/src/external/miniaudio.h index dae605f2..5db50a96 100644 --- a/src/external/miniaudio.h +++ b/src/external/miniaudio.h @@ -1,6 +1,6 @@ /* Audio playback and capture library. Choice of public domain or MIT-0. See license statements at the end of this file. -miniaudio (formerly mini_al) - v0.9.3 - 2019-04-19 +miniaudio (formerly mini_al) - v0.9.4 - 2019-05-06 David Reid - davidreidsoftware@gmail.com */ @@ -450,14 +450,14 @@ extern "C" { #if defined(_MSC_VER) #pragma warning(push) - #pragma warning(disable:4201) // nonstandard extension used: nameless struct/union - #pragma warning(disable:4324) // structure was padded due to alignment specifier + #pragma warning(disable:4201) /* nonstandard extension used: nameless struct/union */ + #pragma warning(disable:4324) /* structure was padded due to alignment specifier */ #else #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wpedantic" /* For ISO C99 doesn't support unnamed structs/unions [-Wpedantic] */ #endif -// Platform/backend detection. +/* Platform/backend detection. */ #ifdef _WIN32 #define MA_WIN32 #if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_PC_APP || WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP) @@ -467,7 +467,7 @@ extern "C" { #endif #else #define MA_POSIX - #include // Unfortunate #include, but needed for pthread_t, pthread_mutex_t and pthread_cond_t types. + #include /* Unfortunate #include, but needed for pthread_t, pthread_mutex_t and pthread_cond_t types. */ #ifdef __unix__ #define MA_UNIX @@ -555,7 +555,7 @@ typedef void (* ma_proc)(void); typedef ma_uint16 wchar_t; #endif -// Define NULL for some compilers. +/* Define NULL for some compilers. */ #ifndef NULL #define NULL 0 #endif @@ -571,18 +571,21 @@ typedef ma_uint16 wchar_t; #define MA_INLINE __forceinline #else #ifdef __GNUC__ -#define MA_INLINE inline __attribute__((always_inline)) +#define MA_INLINE __inline__ __attribute__((always_inline)) #else -#define MA_INLINE inline +#define MA_INLINE #endif #endif -#ifdef _MSC_VER -#define MA_ALIGN(alignment) __declspec(align(alignment)) +#if defined(_MSC_VER) + #if _MSC_VER >= 1400 + #define MA_ALIGN(alignment) __declspec(align(alignment)) + #endif #elif !defined(__DMC__) -#define MA_ALIGN(alignment) __attribute__((aligned(alignment))) -#else -#define MA_ALIGN(alignment) + #define MA_ALIGN(alignment) __attribute__((aligned(alignment))) +#endif +#ifndef MA_ALIGN + #define MA_ALIGN(alignment) #endif #ifdef _MSC_VER @@ -591,11 +594,11 @@ typedef ma_uint16 wchar_t; #define MA_ALIGNED_STRUCT(alignment) struct MA_ALIGN(alignment) #endif -// SIMD alignment in bytes. Currently set to 64 bytes in preparation for future AVX-512 optimizations. +/* SIMD alignment in bytes. Currently set to 64 bytes in preparation for future AVX-512 optimizations. */ #define MA_SIMD_ALIGNMENT 64 -// Logging levels +/* Logging levels */ #define MA_LOG_LEVEL_VERBOSE 4 #define MA_LOG_LEVEL_INFO 3 #define MA_LOG_LEVEL_WARNING 2 @@ -710,7 +713,7 @@ typedef int ma_result; #define MA_FAILED_TO_CREATE_THREAD -313 -// Standard sample rates. +/* Standard sample rates. */ #define MA_SAMPLE_RATE_8000 8000 #define MA_SAMPLE_RATE_11025 11025 #define MA_SAMPLE_RATE_16000 16000 @@ -726,7 +729,7 @@ typedef int ma_result; #define MA_SAMPLE_RATE_352800 352800 #define MA_SAMPLE_RATE_384000 384000 -#define MA_MIN_PCM_SAMPLE_SIZE_IN_BYTES 1 // For simplicity, miniaudio does not support PCM samples that are not byte aligned. +#define MA_MIN_PCM_SAMPLE_SIZE_IN_BYTES 1 /* For simplicity, miniaudio does not support PCM samples that are not byte aligned. */ #define MA_MAX_PCM_SAMPLE_SIZE_IN_BYTES 8 #define MA_MIN_CHANNELS 1 #define MA_MAX_CHANNELS 32 @@ -758,12 +761,14 @@ typedef enum typedef enum { - // I like to keep these explicitly defined because they're used as a key into a lookup table. When items are - // added to this, make sure there are no gaps and that they're added to the lookup table in ma_get_bytes_per_sample(). - ma_format_unknown = 0, // Mainly used for indicating an error, but also used as the default for the output format for decoders. + /* + I like to keep these explicitly defined because they're used as a key into a lookup table. When items are + added to this, make sure there are no gaps and that they're added to the lookup table in ma_get_bytes_per_sample(). + */ + ma_format_unknown = 0, /* Mainly used for indicating an error, but also used as the default for the output format for decoders. */ ma_format_u8 = 1, - ma_format_s16 = 2, // Seems to be the most widely supported format. - ma_format_s24 = 3, // Tightly packed. 3 bytes per sample. + ma_format_s16 = 2, /* Seems to be the most widely supported format. */ + ma_format_s24 = 3, /* Tightly packed. 3 bytes per sample. */ ma_format_s32 = 4, ma_format_f32 = 5, ma_format_count @@ -771,9 +776,9 @@ typedef enum typedef enum { - ma_channel_mix_mode_rectangular = 0, // Simple averaging based on the plane(s) the channel is sitting on. - ma_channel_mix_mode_simple, // Drop excess channels; zeroed out extra channels. - ma_channel_mix_mode_custom_weights, // Use custom weights specified in ma_channel_router_config. + ma_channel_mix_mode_rectangular = 0, /* Simple averaging based on the plane(s) the channel is sitting on. */ + ma_channel_mix_mode_simple, /* Drop excess channels; zeroed out extra channels. */ + ma_channel_mix_mode_custom_weights, /* Use custom weights specified in ma_channel_router_config. */ ma_channel_mix_mode_planar_blend = ma_channel_mix_mode_rectangular, ma_channel_mix_mode_default = ma_channel_mix_mode_planar_blend } ma_channel_mix_mode; @@ -782,12 +787,12 @@ typedef enum { ma_standard_channel_map_microsoft, ma_standard_channel_map_alsa, - ma_standard_channel_map_rfc3551, // Based off AIFF. + ma_standard_channel_map_rfc3551, /* Based off AIFF. */ ma_standard_channel_map_flac, ma_standard_channel_map_vorbis, - ma_standard_channel_map_sound4, // FreeBSD's sound(4). - ma_standard_channel_map_sndio, // www.sndio.org/tips.html - ma_standard_channel_map_webaudio = ma_standard_channel_map_flac, // https://webaudio.github.io/web-audio-api/#ChannelOrdering. Only 1, 2, 4 and 6 channels are defined, but can fill in the gaps with logical assumptions. + ma_standard_channel_map_sound4, /* FreeBSD's sound(4). */ + ma_standard_channel_map_sndio, /* www.sndio.org/tips.html */ + ma_standard_channel_map_webaudio = ma_standard_channel_map_flac, /* https://webaudio.github.io/web-audio-api/#ChannelOrdering. Only 1, 2, 4 and 6 channels are defined, but can fill in the gaps with logical assumptions. */ ma_standard_channel_map_default = ma_standard_channel_map_microsoft } ma_standard_channel_map; @@ -843,7 +848,7 @@ typedef struct ma_channel channelMapIn[MA_MAX_CHANNELS]; ma_channel channelMapOut[MA_MAX_CHANNELS]; ma_channel_mix_mode mixingMode; - float weights[MA_MAX_CHANNELS][MA_MAX_CHANNELS]; // [in][out]. Only used when mixingMode is set to ma_channel_mix_mode_custom_weights. + float weights[MA_MAX_CHANNELS][MA_MAX_CHANNELS]; /* [in][out]. Only used when mixingMode is set to ma_channel_mix_mode_custom_weights. */ ma_bool32 noSSE2 : 1; ma_bool32 noAVX2 : 1; ma_bool32 noAVX512 : 1; @@ -867,7 +872,7 @@ struct ma_channel_router typedef struct ma_src ma_src; -typedef ma_uint32 (* ma_src_read_deinterleaved_proc)(ma_src* pSRC, ma_uint32 frameCount, void** ppSamplesOut, void* pUserData); // Returns the number of frames that were read. +typedef ma_uint32 (* ma_src_read_deinterleaved_proc)(ma_src* pSRC, ma_uint32 frameCount, void** ppSamplesOut, void* pUserData); /* Returns the number of frames that were read. */ typedef enum { @@ -924,9 +929,9 @@ MA_ALIGNED_STRUCT(MA_SIMD_ALIGNMENT) ma_src { MA_ALIGN(MA_SIMD_ALIGNMENT) float input[MA_MAX_CHANNELS][MA_SRC_SINC_MAX_WINDOW_WIDTH*2 + MA_SRC_INPUT_BUFFER_SIZE_IN_SAMPLES]; float timeIn; - ma_uint32 inputFrameCount; // The number of frames sitting in the input buffer, not including the first half of the window. - ma_uint32 windowPosInSamples; // An offset of . - float table[MA_SRC_SINC_MAX_WINDOW_WIDTH*1 * MA_SRC_SINC_LOOKUP_TABLE_RESOLUTION]; // Precomputed lookup table. The +1 is used to avoid the need for an overflow check. + ma_uint32 inputFrameCount; /* The number of frames sitting in the input buffer, not including the first half of the window. */ + ma_uint32 windowPosInSamples; /* An offset of . */ + float table[MA_SRC_SINC_MAX_WINDOW_WIDTH*1 * MA_SRC_SINC_LOOKUP_TABLE_RESOLUTION]; /* Precomputed lookup table. The +1 is used to avoid the need for an overflow check. */ } sinc; }; @@ -955,7 +960,7 @@ typedef struct ma_dither_mode ditherMode; ma_src_algorithm srcAlgorithm; ma_bool32 allowDynamicSampleRate; - ma_bool32 neverConsumeEndOfInput : 1; // <-- For SRC. + ma_bool32 neverConsumeEndOfInput : 1; /* <-- For SRC. */ ma_bool32 noSSE2 : 1; ma_bool32 noAVX2 : 1; ma_bool32 noAVX512 : 1; @@ -972,387 +977,431 @@ MA_ALIGNED_STRUCT(MA_SIMD_ALIGNMENT) ma_pcm_converter { ma_pcm_converter_read_proc onRead; void* pUserData; - ma_format_converter formatConverterIn; // For converting data to f32 in preparation for further processing. - ma_format_converter formatConverterOut; // For converting data to the requested output format. Used as the final step in the processing pipeline. - ma_channel_router channelRouter; // For channel conversion. - ma_src src; // For sample rate conversion. - ma_bool32 isDynamicSampleRateAllowed : 1; // ma_pcm_converter_set_input_sample_rate() and ma_pcm_converter_set_output_sample_rate() will fail if this is set to false. + ma_format_converter formatConverterIn; /* For converting data to f32 in preparation for further processing. */ + ma_format_converter formatConverterOut; /* For converting data to the requested output format. Used as the final step in the processing pipeline. */ + ma_channel_router channelRouter; /* For channel conversion. */ + ma_src src; /* For sample rate conversion. */ + ma_bool32 isDynamicSampleRateAllowed : 1; /* ma_pcm_converter_set_input_sample_rate() and ma_pcm_converter_set_output_sample_rate() will fail if this is set to false. */ ma_bool32 isPreFormatConversionRequired : 1; ma_bool32 isPostFormatConversionRequired : 1; ma_bool32 isChannelRoutingRequired : 1; ma_bool32 isSRCRequired : 1; ma_bool32 isChannelRoutingAtStart : 1; - ma_bool32 isPassthrough : 1; // <-- Will be set to true when the DSP pipeline is an optimized passthrough. + ma_bool32 isPassthrough : 1; /* <-- Will be set to true when the DSP pipeline is an optimized passthrough. */ }; -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// DATA CONVERSION -// =============== -// -// This section contains the APIs for data conversion. You will find everything here for channel mapping, sample format conversion, resampling, etc. -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Channel Maps -// ============ -// -// Below is the channel map used by ma_standard_channel_map_default: -// -// |---------------|------------------------------| -// | Channel Count | Mapping | -// |---------------|------------------------------| -// | 1 (Mono) | 0: MA_CHANNEL_MONO | -// |---------------|------------------------------| -// | 2 (Stereo) | 0: MA_CHANNEL_FRONT_LEFT | -// | | 1: MA_CHANNEL_FRONT_RIGHT | -// |---------------|------------------------------| -// | 3 | 0: MA_CHANNEL_FRONT_LEFT | -// | | 1: MA_CHANNEL_FRONT_RIGHT | -// | | 2: MA_CHANNEL_FRONT_CENTER | -// |---------------|------------------------------| -// | 4 (Surround) | 0: MA_CHANNEL_FRONT_LEFT | -// | | 1: MA_CHANNEL_FRONT_RIGHT | -// | | 2: MA_CHANNEL_FRONT_CENTER | -// | | 3: MA_CHANNEL_BACK_CENTER | -// |---------------|------------------------------| -// | 5 | 0: MA_CHANNEL_FRONT_LEFT | -// | | 1: MA_CHANNEL_FRONT_RIGHT | -// | | 2: MA_CHANNEL_FRONT_CENTER | -// | | 3: MA_CHANNEL_BACK_LEFT | -// | | 4: MA_CHANNEL_BACK_RIGHT | -// |---------------|------------------------------| -// | 6 (5.1) | 0: MA_CHANNEL_FRONT_LEFT | -// | | 1: MA_CHANNEL_FRONT_RIGHT | -// | | 2: MA_CHANNEL_FRONT_CENTER | -// | | 3: MA_CHANNEL_LFE | -// | | 4: MA_CHANNEL_SIDE_LEFT | -// | | 5: MA_CHANNEL_SIDE_RIGHT | -// |---------------|------------------------------| -// | 7 | 0: MA_CHANNEL_FRONT_LEFT | -// | | 1: MA_CHANNEL_FRONT_RIGHT | -// | | 2: MA_CHANNEL_FRONT_CENTER | -// | | 3: MA_CHANNEL_LFE | -// | | 4: MA_CHANNEL_BACK_CENTER | -// | | 4: MA_CHANNEL_SIDE_LEFT | -// | | 5: MA_CHANNEL_SIDE_RIGHT | -// |---------------|------------------------------| -// | 8 (7.1) | 0: MA_CHANNEL_FRONT_LEFT | -// | | 1: MA_CHANNEL_FRONT_RIGHT | -// | | 2: MA_CHANNEL_FRONT_CENTER | -// | | 3: MA_CHANNEL_LFE | -// | | 4: MA_CHANNEL_BACK_LEFT | -// | | 5: MA_CHANNEL_BACK_RIGHT | -// | | 6: MA_CHANNEL_SIDE_LEFT | -// | | 7: MA_CHANNEL_SIDE_RIGHT | -// |---------------|------------------------------| -// | Other | All channels set to 0. This | -// | | is equivalent to the same | -// | | mapping as the device. | -// |---------------|------------------------------| -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -// Helper for retrieving a standard channel map. +/************************************************************************************************************************************************************ +************************************************************************************************************************************************************* + +DATA CONVERSION +=============== + +This section contains the APIs for data conversion. You will find everything here for channel mapping, sample format conversion, resampling, etc. + +************************************************************************************************************************************************************* +************************************************************************************************************************************************************/ + +/************************************************************************************************************************************************************ + +Channel Maps +============ + +Below is the channel map used by ma_standard_channel_map_default: + +|---------------|------------------------------| +| Channel Count | Mapping | +|---------------|------------------------------| +| 1 (Mono) | 0: MA_CHANNEL_MONO | +|---------------|------------------------------| +| 2 (Stereo) | 0: MA_CHANNEL_FRONT_LEFT | +| | 1: MA_CHANNEL_FRONT_RIGHT | +|---------------|------------------------------| +| 3 | 0: MA_CHANNEL_FRONT_LEFT | +| | 1: MA_CHANNEL_FRONT_RIGHT | +| | 2: MA_CHANNEL_FRONT_CENTER | +|---------------|------------------------------| +| 4 (Surround) | 0: MA_CHANNEL_FRONT_LEFT | +| | 1: MA_CHANNEL_FRONT_RIGHT | +| | 2: MA_CHANNEL_FRONT_CENTER | +| | 3: MA_CHANNEL_BACK_CENTER | +|---------------|------------------------------| +| 5 | 0: MA_CHANNEL_FRONT_LEFT | +| | 1: MA_CHANNEL_FRONT_RIGHT | +| | 2: MA_CHANNEL_FRONT_CENTER | +| | 3: MA_CHANNEL_BACK_LEFT | +| | 4: MA_CHANNEL_BACK_RIGHT | +|---------------|------------------------------| +| 6 (5.1) | 0: MA_CHANNEL_FRONT_LEFT | +| | 1: MA_CHANNEL_FRONT_RIGHT | +| | 2: MA_CHANNEL_FRONT_CENTER | +| | 3: MA_CHANNEL_LFE | +| | 4: MA_CHANNEL_SIDE_LEFT | +| | 5: MA_CHANNEL_SIDE_RIGHT | +|---------------|------------------------------| +| 7 | 0: MA_CHANNEL_FRONT_LEFT | +| | 1: MA_CHANNEL_FRONT_RIGHT | +| | 2: MA_CHANNEL_FRONT_CENTER | +| | 3: MA_CHANNEL_LFE | +| | 4: MA_CHANNEL_BACK_CENTER | +| | 4: MA_CHANNEL_SIDE_LEFT | +| | 5: MA_CHANNEL_SIDE_RIGHT | +|---------------|------------------------------| +| 8 (7.1) | 0: MA_CHANNEL_FRONT_LEFT | +| | 1: MA_CHANNEL_FRONT_RIGHT | +| | 2: MA_CHANNEL_FRONT_CENTER | +| | 3: MA_CHANNEL_LFE | +| | 4: MA_CHANNEL_BACK_LEFT | +| | 5: MA_CHANNEL_BACK_RIGHT | +| | 6: MA_CHANNEL_SIDE_LEFT | +| | 7: MA_CHANNEL_SIDE_RIGHT | +|---------------|------------------------------| +| Other | All channels set to 0. This | +| | is equivalent to the same | +| | mapping as the device. | +|---------------|------------------------------| + +************************************************************************************************************************************************************/ + +/* +Helper for retrieving a standard channel map. +*/ void ma_get_standard_channel_map(ma_standard_channel_map standardChannelMap, ma_uint32 channels, ma_channel channelMap[MA_MAX_CHANNELS]); -// Copies a channel map. +/* +Copies a channel map. +*/ void ma_channel_map_copy(ma_channel* pOut, const ma_channel* pIn, ma_uint32 channels); -// Determines whether or not a channel map is valid. -// -// A blank channel map is valid (all channels set to MA_CHANNEL_NONE). The way a blank channel map is handled is context specific, but -// is usually treated as a passthrough. -// -// Invalid channel maps: -// - A channel map with no channels -// - A channel map with more than one channel and a mono channel +/* +Determines whether or not a channel map is valid. + +A blank channel map is valid (all channels set to MA_CHANNEL_NONE). The way a blank channel map is handled is context specific, but +is usually treated as a passthrough. + +Invalid channel maps: + - A channel map with no channels + - A channel map with more than one channel and a mono channel +*/ ma_bool32 ma_channel_map_valid(ma_uint32 channels, const ma_channel channelMap[MA_MAX_CHANNELS]); -// Helper for comparing two channel maps for equality. -// -// This assumes the channel count is the same between the two. +/* +Helper for comparing two channel maps for equality. + +This assumes the channel count is the same between the two. +*/ ma_bool32 ma_channel_map_equal(ma_uint32 channels, const ma_channel channelMapA[MA_MAX_CHANNELS], const ma_channel channelMapB[MA_MAX_CHANNELS]); -// Helper for determining if a channel map is blank (all channels set to MA_CHANNEL_NONE). +/* +Helper for determining if a channel map is blank (all channels set to MA_CHANNEL_NONE). +*/ ma_bool32 ma_channel_map_blank(ma_uint32 channels, const ma_channel channelMap[MA_MAX_CHANNELS]); -// Helper for determining whether or not a channel is present in the given channel map. +/* +Helper for determining whether or not a channel is present in the given channel map. +*/ ma_bool32 ma_channel_map_contains_channel_position(ma_uint32 channels, const ma_channel channelMap[MA_MAX_CHANNELS], ma_channel channelPosition); -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Format Conversion -// ================= -// The format converter serves two purposes: -// 1) Conversion between data formats (u8 to f32, etc.) -// 2) Interleaving and deinterleaving -// -// When initializing a converter, you specify the input and output formats (u8, s16, etc.) and read callbacks. There are two read callbacks - one for -// interleaved input data (onRead) and another for deinterleaved input data (onReadDeinterleaved). You implement whichever is most convenient for you. You -// can implement both, but it's not recommended as it just introduces unnecessary complexity. -// -// To read data as interleaved samples, use ma_format_converter_read(). Otherwise use ma_format_converter_read_deinterleaved(). -// -// Dithering -// --------- -// The format converter also supports dithering. Dithering can be set using ditherMode variable in the config, like so. -// -// pConfig->ditherMode = ma_dither_mode_rectangle; -// -// The different dithering modes include the following, in order of efficiency: -// - None: ma_dither_mode_none -// - Rectangle: ma_dither_mode_rectangle -// - Triangle: ma_dither_mode_triangle -// -// Note that even if the dither mode is set to something other than ma_dither_mode_none, it will be ignored for conversions where dithering is not needed. -// Dithering is available for the following conversions: -// - s16 -> u8 -// - s24 -> u8 -// - s32 -> u8 -// - f32 -> u8 -// - s24 -> s16 -// - s32 -> s16 -// - f32 -> s16 -// -// Note that it is not an error to pass something other than ma_dither_mode_none for conversions where dither is not used. It will just be ignored. -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -// Initializes a format converter. +/************************************************************************************************************************************************************ + +Format Conversion +================= +The format converter serves two purposes: + 1) Conversion between data formats (u8 to f32, etc.) + 2) Interleaving and deinterleaving + +When initializing a converter, you specify the input and output formats (u8, s16, etc.) and read callbacks. There are two read callbacks - one for +interleaved input data (onRead) and another for deinterleaved input data (onReadDeinterleaved). You implement whichever is most convenient for you. You +can implement both, but it's not recommended as it just introduces unnecessary complexity. + +To read data as interleaved samples, use ma_format_converter_read(). Otherwise use ma_format_converter_read_deinterleaved(). + +Dithering +--------- +The format converter also supports dithering. Dithering can be set using ditherMode variable in the config, like so. + + pConfig->ditherMode = ma_dither_mode_rectangle; + +The different dithering modes include the following, in order of efficiency: + - None: ma_dither_mode_none + - Rectangle: ma_dither_mode_rectangle + - Triangle: ma_dither_mode_triangle + +Note that even if the dither mode is set to something other than ma_dither_mode_none, it will be ignored for conversions where dithering is not needed. +Dithering is available for the following conversions: + - s16 -> u8 + - s24 -> u8 + - s32 -> u8 + - f32 -> u8 + - s24 -> s16 + - s32 -> s16 + - f32 -> s16 + +Note that it is not an error to pass something other than ma_dither_mode_none for conversions where dither is not used. It will just be ignored. + +************************************************************************************************************************************************************/ + +/* +Initializes a format converter. +*/ ma_result ma_format_converter_init(const ma_format_converter_config* pConfig, ma_format_converter* pConverter); -// Reads data from the format converter as interleaved channels. +/* +Reads data from the format converter as interleaved channels. +*/ ma_uint64 ma_format_converter_read(ma_format_converter* pConverter, ma_uint64 frameCount, void* pFramesOut, void* pUserData); -// Reads data from the format converter as deinterleaved channels. +/* +Reads data from the format converter as deinterleaved channels. +*/ ma_uint64 ma_format_converter_read_deinterleaved(ma_format_converter* pConverter, ma_uint64 frameCount, void** ppSamplesOut, void* pUserData); - -// Helper for initializing a format converter config. +/* +Helper for initializing a format converter config. +*/ ma_format_converter_config ma_format_converter_config_init_new(void); ma_format_converter_config ma_format_converter_config_init(ma_format formatIn, ma_format formatOut, ma_uint32 channels, ma_format_converter_read_proc onRead, void* pUserData); ma_format_converter_config ma_format_converter_config_init_deinterleaved(ma_format formatIn, ma_format formatOut, ma_uint32 channels, ma_format_converter_read_deinterleaved_proc onReadDeinterleaved, void* pUserData); -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Channel Routing -// =============== -// There are two main things you can do with the channel router: -// 1) Rearrange channels -// 2) Convert from one channel count to another -// -// Channel Rearrangement -// --------------------- -// A simple example of channel rearrangement may be swapping the left and right channels in a stereo stream. To do this you just pass in the same channel -// count for both the input and output with channel maps that contain the same channels (in a different order). -// -// Channel Conversion -// ------------------ -// The channel router can also convert from one channel count to another, such as converting a 5.1 stream to stero. When changing the channel count, the -// router will first perform a 1:1 mapping of channel positions that are present in both the input and output channel maps. The second thing it will do -// is distribute the input mono channel (if any) across all output channels, excluding any None and LFE channels. If there is an output mono channel, all -// input channels will be averaged, excluding any None and LFE channels. -// -// The last case to consider is when a channel position in the input channel map is not present in the output channel map, and vice versa. In this case the -// channel router will perform a blend of other related channels to produce an audible channel. There are several blending modes. -// 1) Simple -// Unmatched channels are silenced. -// 2) Planar Blending -// Channels are blended based on a set of planes that each speaker emits audio from. -// -// Rectangular / Planar Blending -// ----------------------------- -// In this mode, channel positions are associated with a set of planes where the channel conceptually emits audio from. An example is the front/left speaker. -// This speaker is positioned to the front of the listener, so you can think of it as emitting audio from the front plane. It is also positioned to the left -// of the listener so you can think of it as also emitting audio from the left plane. Now consider the (unrealistic) situation where the input channel map -// contains only the front/left channel position, but the output channel map contains both the front/left and front/center channel. When deciding on the audio -// data to send to the front/center speaker (which has no 1:1 mapping with an input channel) we need to use some logic based on our available input channel -// positions. -// -// As mentioned earlier, our front/left speaker is, conceptually speaking, emitting audio from the front _and_ the left planes. Similarly, the front/center -// speaker is emitting audio from _only_ the front plane. What these two channels have in common is that they are both emitting audio from the front plane. -// Thus, it makes sense that the front/center speaker should receive some contribution from the front/left channel. How much contribution depends on their -// planar relationship (thus the name of this blending technique). -// -// Because the front/left channel is emitting audio from two planes (front and left), you can think of it as though it's willing to dedicate 50% of it's total -// volume to each of it's planes (a channel position emitting from 1 plane would be willing to given 100% of it's total volume to that plane, and a channel -// position emitting from 3 planes would be willing to given 33% of it's total volume to each plane). Similarly, the front/center speaker is emitting audio -// from only one plane so you can think of it as though it's willing to _take_ 100% of it's volume from front plane emissions. Now, since the front/left -// channel is willing to _give_ 50% of it's total volume to the front plane, and the front/center speaker is willing to _take_ 100% of it's total volume -// from the front, you can imagine that 50% of the front/left speaker will be given to the front/center speaker. -// -// Usage -// ----- -// To use the channel router you need to specify three things: -// 1) The input channel count and channel map -// 2) The output channel count and channel map -// 3) The mixing mode to use in the case where a 1:1 mapping is unavailable -// -// Note that input and output data is always deinterleaved 32-bit floating point. -// -// Initialize the channel router with ma_channel_router_init(). You will need to pass in a config object which specifies the input and output configuration, -// mixing mode and a callback for sending data to the router. This callback will be called when input data needs to be sent to the router for processing. Note -// that the mixing mode is only used when a 1:1 mapping is unavailable. This includes the custom weights mode. -// -// Read data from the channel router with ma_channel_router_read_deinterleaved(). Output data is always 32-bit floating point. -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -// Initializes a channel router where it is assumed that the input data is non-interleaved. +/************************************************************************************************************************************************************ + +Channel Routing +=============== +There are two main things you can do with the channel router: + 1) Rearrange channels + 2) Convert from one channel count to another + +Channel Rearrangement +--------------------- +A simple example of channel rearrangement may be swapping the left and right channels in a stereo stream. To do this you just pass in the same channel +count for both the input and output with channel maps that contain the same channels (in a different order). + +Channel Conversion +------------------ +The channel router can also convert from one channel count to another, such as converting a 5.1 stream to stero. When changing the channel count, the +router will first perform a 1:1 mapping of channel positions that are present in both the input and output channel maps. The second thing it will do +is distribute the input mono channel (if any) across all output channels, excluding any None and LFE channels. If there is an output mono channel, all +input channels will be averaged, excluding any None and LFE channels. + +The last case to consider is when a channel position in the input channel map is not present in the output channel map, and vice versa. In this case the +channel router will perform a blend of other related channels to produce an audible channel. There are several blending modes. + 1) Simple + Unmatched channels are silenced. + 2) Planar Blending + Channels are blended based on a set of planes that each speaker emits audio from. + +Rectangular / Planar Blending +----------------------------- +In this mode, channel positions are associated with a set of planes where the channel conceptually emits audio from. An example is the front/left speaker. +This speaker is positioned to the front of the listener, so you can think of it as emitting audio from the front plane. It is also positioned to the left +of the listener so you can think of it as also emitting audio from the left plane. Now consider the (unrealistic) situation where the input channel map +contains only the front/left channel position, but the output channel map contains both the front/left and front/center channel. When deciding on the audio +data to send to the front/center speaker (which has no 1:1 mapping with an input channel) we need to use some logic based on our available input channel +positions. + +As mentioned earlier, our front/left speaker is, conceptually speaking, emitting audio from the front _and_ the left planes. Similarly, the front/center +speaker is emitting audio from _only_ the front plane. What these two channels have in common is that they are both emitting audio from the front plane. +Thus, it makes sense that the front/center speaker should receive some contribution from the front/left channel. How much contribution depends on their +planar relationship (thus the name of this blending technique). + +Because the front/left channel is emitting audio from two planes (front and left), you can think of it as though it's willing to dedicate 50% of it's total +volume to each of it's planes (a channel position emitting from 1 plane would be willing to given 100% of it's total volume to that plane, and a channel +position emitting from 3 planes would be willing to given 33% of it's total volume to each plane). Similarly, the front/center speaker is emitting audio +from only one plane so you can think of it as though it's willing to _take_ 100% of it's volume from front plane emissions. Now, since the front/left +channel is willing to _give_ 50% of it's total volume to the front plane, and the front/center speaker is willing to _take_ 100% of it's total volume +from the front, you can imagine that 50% of the front/left speaker will be given to the front/center speaker. + +Usage +----- +To use the channel router you need to specify three things: + 1) The input channel count and channel map + 2) The output channel count and channel map + 3) The mixing mode to use in the case where a 1:1 mapping is unavailable + +Note that input and output data is always deinterleaved 32-bit floating point. + +Initialize the channel router with ma_channel_router_init(). You will need to pass in a config object which specifies the input and output configuration, +mixing mode and a callback for sending data to the router. This callback will be called when input data needs to be sent to the router for processing. Note +that the mixing mode is only used when a 1:1 mapping is unavailable. This includes the custom weights mode. + +Read data from the channel router with ma_channel_router_read_deinterleaved(). Output data is always 32-bit floating point. + +************************************************************************************************************************************************************/ + +/* +Initializes a channel router where it is assumed that the input data is non-interleaved. +*/ ma_result ma_channel_router_init(const ma_channel_router_config* pConfig, ma_channel_router* pRouter); -// Reads data from the channel router as deinterleaved channels. +/* +Reads data from the channel router as deinterleaved channels. +*/ ma_uint64 ma_channel_router_read_deinterleaved(ma_channel_router* pRouter, ma_uint64 frameCount, void** ppSamplesOut, void* pUserData); -// Helper for initializing a channel router config. +/* +Helper for initializing a channel router config. +*/ ma_channel_router_config ma_channel_router_config_init(ma_uint32 channelsIn, const ma_channel channelMapIn[MA_MAX_CHANNELS], ma_uint32 channelsOut, const ma_channel channelMapOut[MA_MAX_CHANNELS], ma_channel_mix_mode mixingMode, ma_channel_router_read_deinterleaved_proc onRead, void* pUserData); -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Sample Rate Conversion -// ====================== -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +/************************************************************************************************************************************************************ + +Sample Rate Conversion +====================== + +************************************************************************************************************************************************************/ -// Initializes a sample rate conversion object. +/* +Initializes a sample rate conversion object. +*/ ma_result ma_src_init(const ma_src_config* pConfig, ma_src* pSRC); -// Dynamically adjusts the sample rate. -// -// This is useful for dynamically adjust pitch. Keep in mind, however, that this will speed up or slow down the sound. If this -// is not acceptable you will need to use your own algorithm. +/* +Dynamically adjusts the sample rate. + +This is useful for dynamically adjust pitch. Keep in mind, however, that this will speed up or slow down the sound. If this +is not acceptable you will need to use your own algorithm. +*/ ma_result ma_src_set_sample_rate(ma_src* pSRC, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut); -// Reads a number of frames. -// -// Returns the number of frames actually read. -ma_uint64 ma_src_read_deinterleaved(ma_src* pSRC, ma_uint64 frameCount, void** ppSamplesOut, void* pUserData); +/* +Reads a number of frames. +Returns the number of frames actually read. +*/ +ma_uint64 ma_src_read_deinterleaved(ma_src* pSRC, ma_uint64 frameCount, void** ppSamplesOut, void* pUserData); -// Helper for creating a sample rate conversion config. +/* +Helper for creating a sample rate conversion config. +*/ ma_src_config ma_src_config_init_new(void); ma_src_config ma_src_config_init(ma_uint32 sampleRateIn, ma_uint32 sampleRateOut, ma_uint32 channels, ma_src_read_deinterleaved_proc onReadDeinterleaved, void* pUserData); -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Conversion -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +/************************************************************************************************************************************************************ + +Conversion -// Initializes a DSP object. +************************************************************************************************************************************************************/ + +/* +Initializes a DSP object. +*/ ma_result ma_pcm_converter_init(const ma_pcm_converter_config* pConfig, ma_pcm_converter* pDSP); -// Dynamically adjusts the input sample rate. -// -// This will fail is the DSP was not initialized with allowDynamicSampleRate. -// -// DEPRECATED. Use ma_pcm_converter_set_sample_rate() instead. +/* +Dynamically adjusts the input sample rate. + +This will fail is the DSP was not initialized with allowDynamicSampleRate. + +DEPRECATED. Use ma_pcm_converter_set_sample_rate() instead. +*/ ma_result ma_pcm_converter_set_input_sample_rate(ma_pcm_converter* pDSP, ma_uint32 sampleRateOut); -// Dynamically adjusts the output sample rate. -// -// This is useful for dynamically adjust pitch. Keep in mind, however, that this will speed up or slow down the sound. If this -// is not acceptable you will need to use your own algorithm. -// -// This will fail is the DSP was not initialized with allowDynamicSampleRate. -// -// DEPRECATED. Use ma_pcm_converter_set_sample_rate() instead. +/* +Dynamically adjusts the output sample rate. + +This is useful for dynamically adjust pitch. Keep in mind, however, that this will speed up or slow down the sound. If this +is not acceptable you will need to use your own algorithm. + +This will fail is the DSP was not initialized with allowDynamicSampleRate. + +DEPRECATED. Use ma_pcm_converter_set_sample_rate() instead. +*/ ma_result ma_pcm_converter_set_output_sample_rate(ma_pcm_converter* pDSP, ma_uint32 sampleRateOut); -// Dynamically adjusts the output sample rate. -// -// This is useful for dynamically adjust pitch. Keep in mind, however, that this will speed up or slow down the sound. If this -// is not acceptable you will need to use your own algorithm. -// -// This will fail is the DSP was not initialized with allowDynamicSampleRate. -ma_result ma_pcm_converter_set_sample_rate(ma_pcm_converter* pDSP, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut); +/* +Dynamically adjusts the output sample rate. +This is useful for dynamically adjust pitch. Keep in mind, however, that this will speed up or slow down the sound. If this +is not acceptable you will need to use your own algorithm. + +This will fail if the DSP was not initialized with allowDynamicSampleRate. +*/ +ma_result ma_pcm_converter_set_sample_rate(ma_pcm_converter* pDSP, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut); -// Reads a number of frames and runs them through the DSP processor. +/* +Reads a number of frames and runs them through the DSP processor. +*/ ma_uint64 ma_pcm_converter_read(ma_pcm_converter* pDSP, void* pFramesOut, ma_uint64 frameCount); -// Helper for initializing a ma_pcm_converter_config object. +/* +Helper for initializing a ma_pcm_converter_config object. +*/ ma_pcm_converter_config ma_pcm_converter_config_init_new(void); ma_pcm_converter_config ma_pcm_converter_config_init(ma_format formatIn, ma_uint32 channelsIn, ma_uint32 sampleRateIn, ma_format formatOut, ma_uint32 channelsOut, ma_uint32 sampleRateOut, ma_pcm_converter_read_proc onRead, void* pUserData); ma_pcm_converter_config ma_pcm_converter_config_init_ex(ma_format formatIn, ma_uint32 channelsIn, ma_uint32 sampleRateIn, ma_channel channelMapIn[MA_MAX_CHANNELS], ma_format formatOut, ma_uint32 channelsOut, ma_uint32 sampleRateOut, ma_channel channelMapOut[MA_MAX_CHANNELS], ma_pcm_converter_read_proc onRead, void* pUserData); +/* +High-level helper for doing a full format conversion in one go. Returns the number of output frames. Call this with pOut set to NULL to +determine the required size of the output buffer. + +A return value of 0 indicates an error. -// High-level helper for doing a full format conversion in one go. Returns the number of output frames. Call this with pOut set to NULL to -// determine the required size of the output buffer. -// -// A return value of 0 indicates an error. -// -// This function is useful for one-off bulk conversions, but if you're streaming data you should use the DSP APIs instead. +This function is useful for one-off bulk conversions, but if you're streaming data you should use the DSP APIs instead. +*/ ma_uint64 ma_convert_frames(void* pOut, ma_format formatOut, ma_uint32 channelsOut, ma_uint32 sampleRateOut, const void* pIn, ma_format formatIn, ma_uint32 channelsIn, ma_uint32 sampleRateIn, ma_uint64 frameCount); ma_uint64 ma_convert_frames_ex(void* pOut, ma_format formatOut, ma_uint32 channelsOut, ma_uint32 sampleRateOut, ma_channel channelMapOut[MA_MAX_CHANNELS], const void* pIn, ma_format formatIn, ma_uint32 channelsIn, ma_uint32 sampleRateIn, ma_channel channelMapIn[MA_MAX_CHANNELS], ma_uint64 frameCount); -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Ring Buffer -// =========== -// -// Features -// -------- -// - Lock free (assuming single producer, single consumer) -// - Support for interleaved and deinterleaved streams -// - Allows the caller to allocate their own block of memory -// -// Usage -// ----- -// - Call ma_rb_init() to initialize a simple buffer, with an optional pre-allocated buffer. If you pass in NULL -// for the pre-allocated buffer, it will be allocated for you and free()'d in ma_rb_uninit(). If you pass in -// your own pre-allocated buffer, free()-ing is left to you. -// -// - Call ma_rb_init_ex() if you need a deinterleaved buffer. The data for each sub-buffer is offset from each -// other based on the stride. Use ma_rb_get_subbuffer_stride(), ma_rb_get_subbuffer_offset() and -// ma_rb_get_subbuffer_ptr() to manage your sub-buffers. -// -// - Use ma_rb_acquire_read() and ma_rb_acquire_write() to retrieve a pointer to a section of the ring buffer. -// You specify the number of bytes you need, and on output it will set to what was actually acquired. If the -// read or write pointer is positioned such that the number of bytes requested will require a loop, it will be -// clamped to the end of the buffer. Therefore, the number of bytes you're given may be less than the number -// you requested. -// -// - After calling ma_rb_acquire_read/write(), you do your work on the buffer and then "commit" it with -// ma_rb_commit_read/write(). This is where the read/write pointers are updated. When you commit you need to -// pass in the buffer that was returned by the earlier call to ma_rb_acquire_read/write() and is only used -// for validation. The number of bytes passed to ma_rb_commit_read/write() is what's used to increment the -// pointers. -// -// - If you want to correct for drift between the write pointer and the read pointer you can use a combination -// of ma_rb_pointer_distance(), ma_rb_seek_read() and ma_rb_seek_write(). Note that you can only move the -// pointers forward, and you should only move the read pointer forward via the consumer thread, and the write -// pointer forward by the producer thread. If there is too much space between the pointers, move the read -// pointer forward. If there is too little space between the pointers, move the write pointer forward. -// -// -// Notes -// ----- -// - Thread safety depends on a single producer, single consumer model. Only one thread is allowed to write, and -// only one thread is allowed to read. The producer is the only one allowed to move the write pointer, and the -// consumer is the only one allowed to move the read pointer. -// - Operates on bytes. Use ma_pcm_rb to operate in terms of PCM frames. -// - Maximum buffer size in bytes is 0x7FFFFFFF-(MA_SIMD_ALIGNMENT-1) because of reasons. -// -// -// PCM Ring Buffer -// =============== -// This is the same as the regular ring buffer, except that it works on PCM frames instead of bytes. -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +/************************************************************************************************************************************************************ + +Ring Buffer +=========== + +Features +-------- +- Lock free (assuming single producer, single consumer) +- Support for interleaved and deinterleaved streams +- Allows the caller to allocate their own block of memory + +Usage +----- +- Call ma_rb_init() to initialize a simple buffer, with an optional pre-allocated buffer. If you pass in NULL + for the pre-allocated buffer, it will be allocated for you and free()'d in ma_rb_uninit(). If you pass in + your own pre-allocated buffer, free()-ing is left to you. + +- Call ma_rb_init_ex() if you need a deinterleaved buffer. The data for each sub-buffer is offset from each + other based on the stride. Use ma_rb_get_subbuffer_stride(), ma_rb_get_subbuffer_offset() and + ma_rb_get_subbuffer_ptr() to manage your sub-buffers. + +- Use ma_rb_acquire_read() and ma_rb_acquire_write() to retrieve a pointer to a section of the ring buffer. + You specify the number of bytes you need, and on output it will set to what was actually acquired. If the + read or write pointer is positioned such that the number of bytes requested will require a loop, it will be + clamped to the end of the buffer. Therefore, the number of bytes you're given may be less than the number + you requested. + +- After calling ma_rb_acquire_read/write(), you do your work on the buffer and then "commit" it with + ma_rb_commit_read/write(). This is where the read/write pointers are updated. When you commit you need to + pass in the buffer that was returned by the earlier call to ma_rb_acquire_read/write() and is only used + for validation. The number of bytes passed to ma_rb_commit_read/write() is what's used to increment the + pointers. + +- If you want to correct for drift between the write pointer and the read pointer you can use a combination + of ma_rb_pointer_distance(), ma_rb_seek_read() and ma_rb_seek_write(). Note that you can only move the + pointers forward, and you should only move the read pointer forward via the consumer thread, and the write + pointer forward by the producer thread. If there is too much space between the pointers, move the read + pointer forward. If there is too little space between the pointers, move the write pointer forward. + + +Notes +----- +- Thread safety depends on a single producer, single consumer model. Only one thread is allowed to write, and + only one thread is allowed to read. The producer is the only one allowed to move the write pointer, and the + consumer is the only one allowed to move the read pointer. +- Operates on bytes. Use ma_pcm_rb to operate in terms of PCM frames. +- Maximum buffer size in bytes is 0x7FFFFFFF-(MA_SIMD_ALIGNMENT-1) because of reasons. + + +PCM Ring Buffer +=============== +This is the same as the regular ring buffer, except that it works on PCM frames instead of bytes. + +************************************************************************************************************************************************************/ typedef struct { void* pBuffer; @@ -1404,51 +1453,69 @@ ma_uint32 ma_pcm_rb_get_subbuffer_offset(ma_pcm_rb* pRB, ma_uint32 subbufferInde void* ma_pcm_rb_get_subbuffer_ptr(ma_pcm_rb* pRB, ma_uint32 subbufferIndex, void* pBuffer); -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Miscellaneous Helpers -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +/************************************************************************************************************************************************************ + +Miscellaneous Helpers -// malloc(). Calls MA_MALLOC(). +************************************************************************************************************************************************************/ + +/* +malloc(). Calls MA_MALLOC(). +*/ void* ma_malloc(size_t sz); -// realloc(). Calls MA_REALLOC(). +/* +realloc(). Calls MA_REALLOC(). +*/ void* ma_realloc(void* p, size_t sz); -// free(). Calls MA_FREE(). +/* +free(). Calls MA_FREE(). +*/ void ma_free(void* p); -// Performs an aligned malloc, with the assumption that the alignment is a power of 2. +/* +Performs an aligned malloc, with the assumption that the alignment is a power of 2. +*/ void* ma_aligned_malloc(size_t sz, size_t alignment); -// Free's an aligned malloc'd buffer. +/* +Free's an aligned malloc'd buffer. +*/ void ma_aligned_free(void* p); -// Retrieves a friendly name for a format. +/* +Retrieves a friendly name for a format. +*/ const char* ma_get_format_name(ma_format format); -// Blends two frames in floating point format. +/* +Blends two frames in floating point format. +*/ void ma_blend_f32(float* pOut, float* pInA, float* pInB, float factor, ma_uint32 channels); -// Retrieves the size of a sample in bytes for the given format. -// -// This API is efficient and is implemented using a lookup table. -// -// Thread Safety: SAFE -// This is API is pure. +/* +Retrieves the size of a sample in bytes for the given format. + +This API is efficient and is implemented using a lookup table. + +Thread Safety: SAFE + This API is pure. +*/ ma_uint32 ma_get_bytes_per_sample(ma_format format); static MA_INLINE ma_uint32 ma_get_bytes_per_frame(ma_format format, ma_uint32 channels) { return ma_get_bytes_per_sample(format) * channels; } -// Converts a log level to a string. +/* +Converts a log level to a string. +*/ const char* ma_log_level_to_string(ma_uint32 logLevel); -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Format Conversion -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +/************************************************************************************************************************************************************ + +Format Conversion + +************************************************************************************************************************************************************/ void ma_pcm_u8_to_s16(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); void ma_pcm_u8_to_s24(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); void ma_pcm_u8_to_s32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); @@ -1471,36 +1538,40 @@ void ma_pcm_f32_to_s24(void* pOut, const void* pIn, ma_uint64 count, ma_dither_m void ma_pcm_f32_to_s32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode); void ma_pcm_convert(void* pOut, ma_format formatOut, const void* pIn, ma_format formatIn, ma_uint64 sampleCount, ma_dither_mode ditherMode); -// Deinterleaves an interleaved buffer. +/* +Deinterleaves an interleaved buffer. +*/ void ma_deinterleave_pcm_frames(ma_format format, ma_uint32 channels, ma_uint64 frameCount, const void* pInterleavedPCMFrames, void** ppDeinterleavedPCMFrames); -// Interleaves a group of deinterleaved buffers. +/* +Interleaves a group of deinterleaved buffers. +*/ void ma_interleave_pcm_frames(ma_format format, ma_uint32 channels, ma_uint64 frameCount, const void** ppDeinterleavedPCMFrames, void* pInterleavedPCMFrames); -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// DEVICE I/O -// ========== -// -// This section contains the APIs for device playback and capture. Here is where you'll find ma_device_init(), etc. -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +/************************************************************************************************************************************************************ +************************************************************************************************************************************************************* + +DEVICE I/O +========== + +This section contains the APIs for device playback and capture. Here is where you'll find ma_device_init(), etc. + +************************************************************************************************************************************************************* +************************************************************************************************************************************************************/ #ifndef MA_NO_DEVICE_IO -// Some backends are only supported on certain platforms. +/* Some backends are only supported on certain platforms. */ #if defined(MA_WIN32) #define MA_SUPPORT_WASAPI - #if defined(MA_WIN32_DESKTOP) // DirectSound and WinMM backends are only supported on desktop's. + #if defined(MA_WIN32_DESKTOP) /* DirectSound and WinMM backends are only supported on desktops. */ #define MA_SUPPORT_DSOUND #define MA_SUPPORT_WINMM - #define MA_SUPPORT_JACK // JACK is technically supported on Windows, but I don't know how many people use it in practice... + #define MA_SUPPORT_JACK /* JACK is technically supported on Windows, but I don't know how many people use it in practice... */ #endif #endif #if defined(MA_UNIX) #if defined(MA_LINUX) - #if !defined(MA_ANDROID) // ALSA is not supported on Android. + #if !defined(MA_ANDROID) /* ALSA is not supported on Android. */ #define MA_SUPPORT_ALSA #endif #endif @@ -1512,14 +1583,14 @@ void ma_interleave_pcm_frames(ma_format format, ma_uint32 channels, ma_uint64 fr #define MA_SUPPORT_AAUDIO #define MA_SUPPORT_OPENSL #endif - #if defined(__OpenBSD__) // <-- Change this to "#if defined(MA_BSD)" to enable sndio on all BSD flavors. - #define MA_SUPPORT_SNDIO // sndio is only supported on OpenBSD for now. May be expanded later if there's demand. + #if defined(__OpenBSD__) /* <-- Change this to "#if defined(MA_BSD)" to enable sndio on all BSD flavors. */ + #define MA_SUPPORT_SNDIO /* sndio is only supported on OpenBSD for now. May be expanded later if there's demand. */ #endif #if defined(__NetBSD__) || defined(__OpenBSD__) - #define MA_SUPPORT_AUDIO4 // Only support audio(4) on platforms with known support. + #define MA_SUPPORT_AUDIO4 /* Only support audio(4) on platforms with known support. */ #endif #if defined(__FreeBSD__) || defined(__DragonFly__) - #define MA_SUPPORT_OSS // Only support OSS on specific platforms with known support. + #define MA_SUPPORT_OSS /* Only support OSS on specific platforms with known support. */ #endif #endif #if defined(MA_APPLE) @@ -1529,7 +1600,7 @@ void ma_interleave_pcm_frames(ma_format format, ma_uint32 channels, ma_uint64 fr #define MA_SUPPORT_WEBAUDIO #endif -// Explicitly disable the Null backend for Emscripten because it uses a background thread which is not properly supported right now. +/* Explicitly disable the Null backend for Emscripten because it uses a background thread which is not properly supported right now. */ #if !defined(MA_EMSCRIPTEN) #define MA_SUPPORT_NULL #endif @@ -1579,7 +1650,7 @@ void ma_interleave_pcm_frames(ma_format format, ma_uint32 channels, ma_uint64 fr #endif #ifdef MA_SUPPORT_WASAPI -// We need a IMMNotificationClient object for WASAPI. +/* We need a IMMNotificationClient object for WASAPI. */ typedef struct { void* lpVtbl; @@ -1607,7 +1678,7 @@ typedef enum ma_backend_null /* <-- Must always be the last item. Lowest priority, and used as the terminator for backend enumeration. */ } ma_backend; -// Thread priorties should be ordered such that the default priority of the worker thread is 0. +/* Thread priorties should be ordered such that the default priority of the worker thread is 0. */ typedef enum { ma_thread_priority_idle = -5, @@ -1746,61 +1817,63 @@ typedef enum typedef union { #ifdef MA_SUPPORT_WASAPI - wchar_t wasapi[64]; // WASAPI uses a wchar_t string for identification. + wchar_t wasapi[64]; /* WASAPI uses a wchar_t string for identification. */ #endif #ifdef MA_SUPPORT_DSOUND - ma_uint8 dsound[16]; // DirectSound uses a GUID for identification. + ma_uint8 dsound[16]; /* DirectSound uses a GUID for identification. */ #endif #ifdef MA_SUPPORT_WINMM - /*UINT_PTR*/ ma_uint32 winmm; // When creating a device, WinMM expects a Win32 UINT_PTR for device identification. In practice it's actually just a UINT. + /*UINT_PTR*/ ma_uint32 winmm; /* When creating a device, WinMM expects a Win32 UINT_PTR for device identification. In practice it's actually just a UINT. */ #endif #ifdef MA_SUPPORT_ALSA - char alsa[256]; // ALSA uses a name string for identification. + char alsa[256]; /* ALSA uses a name string for identification. */ #endif #ifdef MA_SUPPORT_PULSEAUDIO - char pulse[256]; // PulseAudio uses a name string for identification. + char pulse[256]; /* PulseAudio uses a name string for identification. */ #endif #ifdef MA_SUPPORT_JACK - int jack; // JACK always uses default devices. + int jack; /* JACK always uses default devices. */ #endif #ifdef MA_SUPPORT_COREAUDIO - char coreaudio[256]; // Core Audio uses a string for identification. + char coreaudio[256]; /* Core Audio uses a string for identification. */ #endif #ifdef MA_SUPPORT_SNDIO - char sndio[256]; // "snd/0", etc. + char sndio[256]; /* "snd/0", etc. */ #endif #ifdef MA_SUPPORT_AUDIO4 - char audio4[256]; // "/dev/audio", etc. + char audio4[256]; /* "/dev/audio", etc. */ #endif #ifdef MA_SUPPORT_OSS - char oss[64]; // "dev/dsp0", etc. "dev/dsp" for the default device. + char oss[64]; /* "dev/dsp0", etc. "dev/dsp" for the default device. */ #endif #ifdef MA_SUPPORT_AAUDIO - ma_int32 aaudio; // AAudio uses a 32-bit integer for identification. + ma_int32 aaudio; /* AAudio uses a 32-bit integer for identification. */ #endif #ifdef MA_SUPPORT_OPENSL - ma_uint32 opensl; // OpenSL|ES uses a 32-bit unsigned integer for identification. + ma_uint32 opensl; /* OpenSL|ES uses a 32-bit unsigned integer for identification. */ #endif #ifdef MA_SUPPORT_WEBAUDIO - char webaudio[32]; // Web Audio always uses default devices for now, but if this changes it'll be a GUID. + char webaudio[32]; /* Web Audio always uses default devices for now, but if this changes it'll be a GUID. */ #endif #ifdef MA_SUPPORT_NULL - int nullbackend; // The null backend uses an integer for device IDs. + int nullbackend; /* The null backend uses an integer for device IDs. */ #endif } ma_device_id; typedef struct { - // Basic info. This is the only information guaranteed to be filled in during device enumeration. + /* Basic info. This is the only information guaranteed to be filled in during device enumeration. */ ma_device_id id; char name[256]; - // Detailed info. As much of this is filled as possible with ma_context_get_device_info(). Note that you are allowed to initialize - // a device with settings outside of this range, but it just means the data will be converted using miniaudio's data conversion - // pipeline before sending the data to/from the device. Most programs will need to not worry about these values, but it's provided - // here mainly for informational purposes or in the rare case that someone might find it useful. - // - // These will be set to 0 when returned by ma_context_enumerate_devices() or ma_context_get_devices(). + /* + Detailed info. As much of this is filled as possible with ma_context_get_device_info(). Note that you are allowed to initialize + a device with settings outside of this range, but it just means the data will be converted using miniaudio's data conversion + pipeline before sending the data to/from the device. Most programs will need to not worry about these values, but it's provided + here mainly for informational purposes or in the rare case that someone might find it useful. + + These will be set to 0 when returned by ma_context_enumerate_devices() or ma_context_get_devices(). + */ ma_uint32 formatCount; ma_format formats[ma_format_count]; ma_uint32 minChannels; @@ -1845,7 +1918,7 @@ typedef struct struct { - ma_bool32 noMMap; // Disables MMap mode. + ma_bool32 noMMap; /* Disables MMap mode. */ } alsa; struct { @@ -1868,7 +1941,7 @@ typedef struct { const char* pApplicationName; const char* pServerName; - ma_bool32 tryAutoSpawn; // Enables autospawning of the PulseAudio daemon if necessary. + ma_bool32 tryAutoSpawn; /* Enables autospawning of the PulseAudio daemon if necessary. */ } pulse; struct { @@ -1881,21 +1954,21 @@ typedef ma_bool32 (* ma_enum_devices_callback_proc)(ma_context* pContext, ma_dev struct ma_context { - ma_backend backend; // DirectSound, ALSA, etc. + ma_backend backend; /* DirectSound, ALSA, etc. */ ma_log_proc logCallback; ma_thread_priority threadPriority; void* pUserData; - ma_mutex deviceEnumLock; // Used to make ma_context_get_devices() thread safe. - ma_mutex deviceInfoLock; // Used to make ma_context_get_device_info() thread safe. - ma_uint32 deviceInfoCapacity; // Total capacity of pDeviceInfos. + ma_mutex deviceEnumLock; /* Used to make ma_context_get_devices() thread safe. */ + ma_mutex deviceInfoLock; /* Used to make ma_context_get_device_info() thread safe. */ + ma_uint32 deviceInfoCapacity; /* Total capacity of pDeviceInfos. */ ma_uint32 playbackDeviceInfoCount; ma_uint32 captureDeviceInfoCount; - ma_device_info* pDeviceInfos; // Playback devices first, then capture. - ma_bool32 isBackendAsynchronous : 1; // Set when the context is initialized. Set to 1 for asynchronous backends such as Core Audio and JACK. Do not modify. + ma_device_info* pDeviceInfos; /* Playback devices first, then capture. */ + ma_bool32 isBackendAsynchronous : 1; /* Set when the context is initialized. Set to 1 for asynchronous backends such as Core Audio and JACK. Do not modify. */ ma_result (* onUninit )(ma_context* pContext); ma_bool32 (* onDeviceIDEqual )(ma_context* pContext, const ma_device_id* pID0, const ma_device_id* pID1); - ma_result (* onEnumDevices )(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData); // Return false from the callback to stop enumeration. + ma_result (* onEnumDevices )(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData); /* Return false from the callback to stop enumeration. */ ma_result (* onGetDeviceInfo )(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_share_mode shareMode, ma_device_info* pDeviceInfo); ma_result (* onDeviceInit )(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice); void (* onDeviceUninit )(ma_device* pDevice); @@ -2101,7 +2174,7 @@ struct ma_context ma_proc AudioObjectSetPropertyData; ma_proc AudioObjectAddPropertyListener; - ma_handle hAudioUnit; // Could possibly be set to AudioToolbox on later versions of macOS. + ma_handle hAudioUnit; /* Could possibly be set to AudioToolbox on later versions of macOS. */ ma_proc AudioComponentFindNext; ma_proc AudioComponentInstanceDispose; ma_proc AudioComponentInstanceNew; @@ -2259,21 +2332,21 @@ MA_ALIGNED_STRUCT(MA_SIMD_ALIGNMENT) ma_device ma_uint32 state; ma_device_callback_proc onData; ma_stop_proc onStop; - void* pUserData; // Application defined data. + void* pUserData; /* Application defined data. */ ma_mutex lock; ma_event wakeupEvent; ma_event startEvent; ma_event stopEvent; ma_thread thread; - ma_result workResult; // This is set by the worker thread after it's finished doing a job. + ma_result workResult; /* This is set by the worker thread after it's finished doing a job. */ ma_bool32 usingDefaultSampleRate : 1; ma_bool32 usingDefaultBufferSize : 1; ma_bool32 usingDefaultPeriods : 1; - ma_bool32 isOwnerOfContext : 1; // When set to true, uninitializing the device will also uninitialize the context. Set to true when NULL is passed into ma_device_init(). + ma_bool32 isOwnerOfContext : 1; /* When set to true, uninitializing the device will also uninitialize the context. Set to true when NULL is passed into ma_device_init(). */ struct { - char name[256]; /* Maybe temporary. Likely to be replaced with a query API. */ - ma_share_mode shareMode; /* Set to whatever was passed in when the device was initialized. */ + char name[256]; /* Maybe temporary. Likely to be replaced with a query API. */ + ma_share_mode shareMode; /* Set to whatever was passed in when the device was initialized. */ ma_bool32 usingDefaultFormat : 1; ma_bool32 usingDefaultChannels : 1; ma_bool32 usingDefaultChannelMap : 1; @@ -2287,13 +2360,13 @@ MA_ALIGNED_STRUCT(MA_SIMD_ALIGNMENT) ma_device ma_uint32 internalBufferSizeInFrames; ma_uint32 internalPeriods; ma_pcm_converter converter; - ma_uint32 _dspFrameCount; // Internal use only. Used as the data source when reading from the device. - const ma_uint8* _dspFrames; // ^^^ AS ABOVE ^^^ + ma_uint32 _dspFrameCount; /* Internal use only. Used as the data source when reading from the device. */ + const ma_uint8* _dspFrames; /* ^^^ AS ABOVE ^^^ */ } playback; struct { - char name[256]; /* Maybe temporary. Likely to be replaced with a query API. */ - ma_share_mode shareMode; /* Set to whatever was passed in when the device was initialized. */ + char name[256]; /* Maybe temporary. Likely to be replaced with a query API. */ + ma_share_mode shareMode; /* Set to whatever was passed in when the device was initialized. */ ma_bool32 usingDefaultFormat : 1; ma_bool32 usingDefaultChannels : 1; ma_bool32 usingDefaultChannelMap : 1; @@ -2307,8 +2380,8 @@ MA_ALIGNED_STRUCT(MA_SIMD_ALIGNMENT) ma_device ma_uint32 internalBufferSizeInFrames; ma_uint32 internalPeriods; ma_pcm_converter converter; - ma_uint32 _dspFrameCount; // Internal use only. Used as the data source when reading from the device. - const ma_uint8* _dspFrames; // ^^^ AS ABOVE ^^^ + ma_uint32 _dspFrameCount; /* Internal use only. Used as the data source when reading from the device. */ + const ma_uint8* _dspFrames; /* ^^^ AS ABOVE ^^^ */ } capture; union @@ -2401,7 +2474,7 @@ MA_ALIGNED_STRUCT(MA_SIMD_ALIGNMENT) ma_device /*jack_client_t**/ ma_ptr pClient; /*jack_port_t**/ ma_ptr pPortsPlayback[MA_MAX_CHANNELS]; /*jack_port_t**/ ma_ptr pPortsCapture[MA_MAX_CHANNELS]; - float* pIntermediaryBufferPlayback; // Typed as a float because JACK is always floating point. + float* pIntermediaryBufferPlayback; /* Typed as a float because JACK is always floating point. */ float* pIntermediaryBufferCapture; ma_pcm_rb duplexRB; } jack; @@ -2413,7 +2486,7 @@ MA_ALIGNED_STRUCT(MA_SIMD_ALIGNMENT) ma_device ma_uint32 deviceObjectIDCapture; /*AudioUnit*/ ma_ptr audioUnitPlayback; /*AudioUnit*/ ma_ptr audioUnitCapture; - /*AudioBufferList**/ ma_ptr pAudioBufferList; // Only used for input devices. + /*AudioBufferList**/ ma_ptr pAudioBufferList; /* Only used for input devices. */ ma_event stopEvent; ma_uint32 originalBufferSizeInFrames; ma_uint32 originalBufferSizeInMilliseconds; @@ -2469,7 +2542,7 @@ MA_ALIGNED_STRUCT(MA_SIMD_ALIGNMENT) ma_device /*SLAndroidSimpleBufferQueueItf*/ ma_ptr pBufferQueueCapture; ma_uint32 currentBufferIndexPlayback; ma_uint32 currentBufferIndexCapture; - ma_uint8* pBufferPlayback; // This is malloc()'d and is used for storing audio data. Typed as ma_uint8 for easy offsetting. + ma_uint8* pBufferPlayback; /* This is malloc()'d and is used for storing audio data. Typed as ma_uint8 for easy offsetting. */ ma_uint8* pBufferCapture; ma_pcm_rb duplexRB; } opensl; @@ -2477,9 +2550,9 @@ MA_ALIGNED_STRUCT(MA_SIMD_ALIGNMENT) ma_device #ifdef MA_SUPPORT_WEBAUDIO struct { - int indexPlayback; /* We use a factory on the JavaScript side to manage devices and use an index for JS/C interop. */ + int indexPlayback; /* We use a factory on the JavaScript side to manage devices and use an index for JS/C interop. */ int indexCapture; - ma_pcm_rb duplexRB; /* In external capture format. */ + ma_pcm_rb duplexRB; /* In external capture format. */ } webaudio; #endif #ifdef MA_SUPPORT_NULL @@ -2507,358 +2580,407 @@ MA_ALIGNED_STRUCT(MA_SIMD_ALIGNMENT) ma_device #pragma GCC diagnostic pop /* For ISO C99 doesn't support unnamed structs/unions [-Wpedantic] */ #endif -// Initializes a context. -// -// The context is used for selecting and initializing the relevant backends. -// -// Note that the location of the context cannot change throughout it's lifetime. Consider allocating -// the ma_context object with malloc() if this is an issue. The reason for this is that a pointer -// to the context is stored in the ma_device structure. -// -// is used to allow the application to prioritize backends depending on it's specific -// requirements. This can be null in which case it uses the default priority, which is as follows: -// - WASAPI -// - DirectSound -// - WinMM -// - Core Audio (Apple) -// - sndio -// - audio(4) -// - OSS -// - PulseAudio -// - ALSA -// - JACK -// - AAudio -// - OpenSL|ES -// - Web Audio / Emscripten -// - Null -// -// is used to configure the context. Use the logCallback config to set a callback for whenever a -// log message is posted. The priority of the worker thread can be set with the threadPriority config. -// -// It is recommended that only a single context is active at any given time because it's a bulky data -// structure which performs run-time linking for the relevant backends every time it's initialized. -// -// Return Value: -// MA_SUCCESS if successful; any other error code otherwise. -// -// Thread Safety: UNSAFE +/* +Initializes a context. + +The context is used for selecting and initializing the relevant backends. + +Note that the location of the context cannot change throughout it's lifetime. Consider allocating +the ma_context object with malloc() if this is an issue. The reason for this is that a pointer +to the context is stored in the ma_device structure. + + is used to allow the application to prioritize backends depending on it's specific +requirements. This can be null in which case it uses the default priority, which is as follows: + - WASAPI + - DirectSound + - WinMM + - Core Audio (Apple) + - sndio + - audio(4) + - OSS + - PulseAudio + - ALSA + - JACK + - AAudio + - OpenSL|ES + - Web Audio / Emscripten + - Null + + is used to configure the context. Use the logCallback config to set a callback for whenever a +log message is posted. The priority of the worker thread can be set with the threadPriority config. + +It is recommended that only a single context is active at any given time because it's a bulky data +structure which performs run-time linking for the relevant backends every time it's initialized. + +Return Value: + MA_SUCCESS if successful; any other error code otherwise. + +Thread Safety: UNSAFE +*/ ma_result ma_context_init(const ma_backend backends[], ma_uint32 backendCount, const ma_context_config* pConfig, ma_context* pContext); -// Uninitializes a context. -// -// Results are undefined if you call this while any device created by this context is still active. -// -// Return Value: -// MA_SUCCESS if successful; any other error code otherwise. -// -// Thread Safety: UNSAFE +/* +Uninitializes a context. + +Results are undefined if you call this while any device created by this context is still active. + +Return Value: + MA_SUCCESS if successful; any other error code otherwise. + +Thread Safety: UNSAFE +*/ ma_result ma_context_uninit(ma_context* pContext); -// Enumerates over every device (both playback and capture). -// -// This is a lower-level enumeration function to the easier to use ma_context_get_devices(). Use -// ma_context_enumerate_devices() if you would rather not incur an internal heap allocation, or -// it simply suits your code better. -// -// Do _not_ assume the first enumerated device of a given type is the default device. -// -// Some backends and platforms may only support default playback and capture devices. -// -// Note that this only retrieves the ID and name/description of the device. The reason for only -// retrieving basic information is that it would otherwise require opening the backend device in -// order to probe it for more detailed information which can be inefficient. Consider using -// ma_context_get_device_info() for this, but don't call it from within the enumeration callback. -// -// In general, you should not do anything complicated from within the callback. In particular, do -// not try initializing a device from within the callback. -// -// Consider using ma_context_get_devices() for a simpler and safer API, albeit at the expense of -// an internal heap allocation. -// -// Returning false from the callback will stop enumeration. Returning true will continue enumeration. -// -// Return Value: -// MA_SUCCESS if successful; any other error code otherwise. -// -// Thread Safety: SAFE -// This is guarded using a simple mutex lock. +/* +Enumerates over every device (both playback and capture). + +This is a lower-level enumeration function to the easier to use ma_context_get_devices(). Use +ma_context_enumerate_devices() if you would rather not incur an internal heap allocation, or +it simply suits your code better. + +Do _not_ assume the first enumerated device of a given type is the default device. + +Some backends and platforms may only support default playback and capture devices. + +Note that this only retrieves the ID and name/description of the device. The reason for only +retrieving basic information is that it would otherwise require opening the backend device in +order to probe it for more detailed information which can be inefficient. Consider using +ma_context_get_device_info() for this, but don't call it from within the enumeration callback. + +In general, you should not do anything complicated from within the callback. In particular, do +not try initializing a device from within the callback. + +Consider using ma_context_get_devices() for a simpler and safer API, albeit at the expense of +an internal heap allocation. + +Returning false from the callback will stop enumeration. Returning true will continue enumeration. + +Return Value: + MA_SUCCESS if successful; any other error code otherwise. + +Thread Safety: SAFE + This is guarded using a simple mutex lock. +*/ ma_result ma_context_enumerate_devices(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData); -// Retrieves basic information about every active playback and/or capture device. -// -// You can pass in NULL for the playback or capture lists in which case they'll be ignored. -// -// It is _not_ safe to assume the first device in the list is the default device. -// -// The returned pointers will become invalid upon the next call this this function, or when the -// context is uninitialized. Do not free the returned pointers. -// -// This function follows the same enumeration rules as ma_context_enumerate_devices(). See -// documentation for ma_context_enumerate_devices() for more information. -// -// Return Value: -// MA_SUCCESS if successful; any other error code otherwise. -// -// Thread Safety: SAFE -// Since each call to this function invalidates the pointers from the previous call, you -// should not be calling this simultaneously across multiple threads. Instead, you need to -// make a copy of the returned data with your own higher level synchronization. +/* +Retrieves basic information about every active playback and/or capture device. + +You can pass in NULL for the playback or capture lists in which case they'll be ignored. + +It is _not_ safe to assume the first device in the list is the default device. + +The returned pointers will become invalid upon the next call this this function, or when the +context is uninitialized. Do not free the returned pointers. + +This function follows the same enumeration rules as ma_context_enumerate_devices(). See +documentation for ma_context_enumerate_devices() for more information. + +Return Value: + MA_SUCCESS if successful; any other error code otherwise. + +Thread Safety: SAFE + Since each call to this function invalidates the pointers from the previous call, you + should not be calling this simultaneously across multiple threads. Instead, you need to + make a copy of the returned data with your own higher level synchronization. +*/ ma_result ma_context_get_devices(ma_context* pContext, ma_device_info** ppPlaybackDeviceInfos, ma_uint32* pPlaybackDeviceCount, ma_device_info** ppCaptureDeviceInfos, ma_uint32* pCaptureDeviceCount); -// Retrieves information about a device with the given ID. -// -// Do _not_ call this from within the ma_context_enumerate_devices() callback. -// -// It's possible for a device to have different information and capabilities depending on wether or -// not it's opened in shared or exclusive mode. For example, in shared mode, WASAPI always uses -// floating point samples for mixing, but in exclusive mode it can be anything. Therefore, this -// function allows you to specify which share mode you want information for. Note that not all -// backends and devices support shared or exclusive mode, in which case this function will fail -// if the requested share mode is unsupported. -// -// This leaves pDeviceInfo unmodified in the result of an error. -// -// Return Value: -// MA_SUCCESS if successful; any other error code otherwise. -// -// Thread Safety: SAFE -// This is guarded using a simple mutex lock. +/* +Retrieves information about a device with the given ID. + +Do _not_ call this from within the ma_context_enumerate_devices() callback. + +It's possible for a device to have different information and capabilities depending on wether or +not it's opened in shared or exclusive mode. For example, in shared mode, WASAPI always uses +floating point samples for mixing, but in exclusive mode it can be anything. Therefore, this +function allows you to specify which share mode you want information for. Note that not all +backends and devices support shared or exclusive mode, in which case this function will fail +if the requested share mode is unsupported. + +This leaves pDeviceInfo unmodified in the result of an error. + +Return Value: + MA_SUCCESS if successful; any other error code otherwise. + +Thread Safety: SAFE + This is guarded using a simple mutex lock. +*/ ma_result ma_context_get_device_info(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_share_mode shareMode, ma_device_info* pDeviceInfo); -// Initializes a device. -// -// The context can be null in which case it uses the default. This is equivalent to passing in a -// context that was initialized like so: -// -// ma_context_init(NULL, 0, NULL, &context); -// -// Do not pass in null for the context if you are needing to open multiple devices. You can, -// however, use null when initializing the first device, and then use device.pContext for the -// initialization of other devices. -// -// The device's configuration is controlled with pConfig. This allows you to configure the sample -// format, channel count, sample rate, etc. Before calling ma_device_init(), you will need to -// initialize a ma_device_config object using ma_device_config_init(). You must set the callback in -// the device config. -// -// Passing in 0 to any property in pConfig will force the use of a default value. In the case of -// sample format, channel count, sample rate and channel map it will default to the values used by -// the backend's internal device. For the size of the buffer you can set bufferSizeInFrames or -// bufferSizeInMilliseconds (if both are set it will prioritize bufferSizeInFrames). If both are -// set to zero, it will default to MA_BASE_BUFFER_SIZE_IN_MILLISECONDS_LOW_LATENCY or -// MA_BASE_BUFFER_SIZE_IN_MILLISECONDS_CONSERVATIVE, depending on whether or not performanceProfile -// is set to ma_performance_profile_low_latency or ma_performance_profile_conservative. -// -// If you request exclusive mode and the backend does not support it an error will be returned. For -// robustness, you may want to first try initializing the device in exclusive mode, and then fall back -// to shared mode if required. Alternatively you can just request shared mode (the default if you -// leave it unset in the config) which is the most reliable option. Some backends do not have a -// practical way of choosing whether or not the device should be exclusive or not (ALSA, for example) -// in which case it just acts as a hint. Unless you have special requirements you should try avoiding -// exclusive mode as it's intrusive to the user. Starting with Windows 10, miniaudio will use low-latency -// shared mode where possible which may make exclusive mode unnecessary. -// -// When sending or receiving data to/from a device, miniaudio will internally perform a format -// conversion to convert between the format specified by pConfig and the format used internally by -// the backend. If you pass in NULL for pConfig or 0 for the sample format, channel count, -// sample rate _and_ channel map, data transmission will run on an optimized pass-through fast path. -// -// The buffer size should be treated as a hint. miniaudio will try it's best to use exactly what you -// ask for, but it may differ. You should not assume the number of frames specified in each call to -// the data callback is exactly what you originally specified. -// -// The property controls how frequently the background thread is woken to check for more -// data. It's tied to the buffer size, so as an example, if your buffer size is equivalent to 10 -// milliseconds and you have 2 periods, the CPU will wake up approximately every 5 milliseconds. -// -// When compiling for UWP you must ensure you call this function on the main UI thread because the -// operating system may need to present the user with a message asking for permissions. Please refer -// to the official documentation for ActivateAudioInterfaceAsync() for more information. -// -// ALSA Specific: When initializing the default device, requesting shared mode will try using the -// "dmix" device for playback and the "dsnoop" device for capture. If these fail it will try falling -// back to the "hw" device. -// -// Return Value: -// MA_SUCCESS if successful; any other error code otherwise. -// -// Thread Safety: UNSAFE -// It is not safe to call this function simultaneously for different devices because some backends -// depend on and mutate global state (such as OpenSL|ES). The same applies to calling this at the -// same time as ma_device_uninit(). +/* +Initializes a device. + +The context can be null in which case it uses the default. This is equivalent to passing in a +context that was initialized like so: + + ma_context_init(NULL, 0, NULL, &context); + +Do not pass in null for the context if you are needing to open multiple devices. You can, +however, use null when initializing the first device, and then use device.pContext for the +initialization of other devices. + +The device's configuration is controlled with pConfig. This allows you to configure the sample +format, channel count, sample rate, etc. Before calling ma_device_init(), you will need to +initialize a ma_device_config object using ma_device_config_init(). You must set the callback in +the device config. + +Passing in 0 to any property in pConfig will force the use of a default value. In the case of +sample format, channel count, sample rate and channel map it will default to the values used by +the backend's internal device. For the size of the buffer you can set bufferSizeInFrames or +bufferSizeInMilliseconds (if both are set it will prioritize bufferSizeInFrames). If both are +set to zero, it will default to MA_BASE_BUFFER_SIZE_IN_MILLISECONDS_LOW_LATENCY or +MA_BASE_BUFFER_SIZE_IN_MILLISECONDS_CONSERVATIVE, depending on whether or not performanceProfile +is set to ma_performance_profile_low_latency or ma_performance_profile_conservative. + +If you request exclusive mode and the backend does not support it an error will be returned. For +robustness, you may want to first try initializing the device in exclusive mode, and then fall back +to shared mode if required. Alternatively you can just request shared mode (the default if you +leave it unset in the config) which is the most reliable option. Some backends do not have a +practical way of choosing whether or not the device should be exclusive or not (ALSA, for example) +in which case it just acts as a hint. Unless you have special requirements you should try avoiding +exclusive mode as it's intrusive to the user. Starting with Windows 10, miniaudio will use low-latency +shared mode where possible which may make exclusive mode unnecessary. + +When sending or receiving data to/from a device, miniaudio will internally perform a format +conversion to convert between the format specified by pConfig and the format used internally by +the backend. If you pass in NULL for pConfig or 0 for the sample format, channel count, +sample rate _and_ channel map, data transmission will run on an optimized pass-through fast path. + +The buffer size should be treated as a hint. miniaudio will try it's best to use exactly what you +ask for, but it may differ. You should not assume the number of frames specified in each call to +the data callback is exactly what you originally specified. + +The property controls how frequently the background thread is woken to check for more +data. It's tied to the buffer size, so as an example, if your buffer size is equivalent to 10 +milliseconds and you have 2 periods, the CPU will wake up approximately every 5 milliseconds. + +When compiling for UWP you must ensure you call this function on the main UI thread because the +operating system may need to present the user with a message asking for permissions. Please refer +to the official documentation for ActivateAudioInterfaceAsync() for more information. + +ALSA Specific: When initializing the default device, requesting shared mode will try using the +"dmix" device for playback and the "dsnoop" device for capture. If these fail it will try falling +back to the "hw" device. + +Return Value: + MA_SUCCESS if successful; any other error code otherwise. + +Thread Safety: UNSAFE + It is not safe to call this function simultaneously for different devices because some backends + depend on and mutate global state (such as OpenSL|ES). The same applies to calling this at the + same time as ma_device_uninit(). +*/ ma_result ma_device_init(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice); -// Initializes a device without a context, with extra parameters for controlling the configuration -// of the internal self-managed context. -// -// See ma_device_init() and ma_context_init(). +/* +Initializes a device without a context, with extra parameters for controlling the configuration +of the internal self-managed context. + +See ma_device_init() and ma_context_init(). +*/ ma_result ma_device_init_ex(const ma_backend backends[], ma_uint32 backendCount, const ma_context_config* pContextConfig, const ma_device_config* pConfig, ma_device* pDevice); -// Uninitializes a device. -// -// This will explicitly stop the device. You do not need to call ma_device_stop() beforehand, but it's -// harmless if you do. -// -// Return Value: -// MA_SUCCESS if successful; any other error code otherwise. -// -// Thread Safety: UNSAFE -// As soon as this API is called the device should be considered undefined. All bets are off if you -// try using the device at the same time as uninitializing it. +/* +Uninitializes a device. + +This will explicitly stop the device. You do not need to call ma_device_stop() beforehand, but it's +harmless if you do. + +Return Value: + MA_SUCCESS if successful; any other error code otherwise. + +Thread Safety: UNSAFE + As soon as this API is called the device should be considered undefined. All bets are off if you + try using the device at the same time as uninitializing it. +*/ void ma_device_uninit(ma_device* pDevice); -// Sets the callback to use when the device has stopped, either explicitly or as a result of an error. -// -// Thread Safety: SAFE -// This API is implemented as a simple atomic assignment. +/* +Sets the callback to use when the device has stopped, either explicitly or as a result of an error. + +Thread Safety: SAFE + This API is implemented as a simple atomic assignment. +*/ void ma_device_set_stop_callback(ma_device* pDevice, ma_stop_proc proc); -// Activates the device. For playback devices this begins playback. For capture devices it begins -// recording. -// -// For a playback device, this will retrieve an initial chunk of audio data from the client before -// returning. The reason for this is to ensure there is valid audio data in the buffer, which needs -// to be done _before_ the device begins playback. -// -// This API waits until the backend device has been started for real by the worker thread. It also -// waits on a mutex for thread-safety. -// -// Return Value: -// MA_SUCCESS if successful; any other error code otherwise. -// -// Thread Safety: SAFE +/* +Activates the device. For playback devices this begins playback. For capture devices it begins +recording. + +For a playback device, this will retrieve an initial chunk of audio data from the client before +returning. The reason for this is to ensure there is valid audio data in the buffer, which needs +to be done _before_ the device begins playback. + +This API waits until the backend device has been started for real by the worker thread. It also +waits on a mutex for thread-safety. + +Return Value: + MA_SUCCESS if successful; any other error code otherwise. + +Thread Safety: SAFE +*/ ma_result ma_device_start(ma_device* pDevice); -// Puts the device to sleep, but does not uninitialize it. Use ma_device_start() to start it up again. -// -// This API needs to wait on the worker thread to stop the backend device properly before returning. It -// also waits on a mutex for thread-safety. In addition, some backends need to wait for the device to -// finish playback/recording of the current fragment which can take some time (usually proportionate to -// the buffer size that was specified at initialization time). -// -// This should not drop unprocessed samples. Backends are required to either pause the stream in-place -// or drain the buffer if pausing is not possible. The reason for this is that stopping the device and -// the resuming it with ma_device_start() (which you might do when your program loses focus) may result -// in a situation where those samples are never output to the speakers or received from the microphone -// which can in turn result in de-syncs. -// -// Return Value: -// MA_SUCCESS if successful; any other error code otherwise. -// -// Thread Safety: SAFE +/* +Puts the device to sleep, but does not uninitialize it. Use ma_device_start() to start it up again. + +This API needs to wait on the worker thread to stop the backend device properly before returning. It +also waits on a mutex for thread-safety. In addition, some backends need to wait for the device to +finish playback/recording of the current fragment which can take some time (usually proportionate to +the buffer size that was specified at initialization time). + +This should not drop unprocessed samples. Backends are required to either pause the stream in-place +or drain the buffer if pausing is not possible. The reason for this is that stopping the device and +the resuming it with ma_device_start() (which you might do when your program loses focus) may result +in a situation where those samples are never output to the speakers or received from the microphone +which can in turn result in de-syncs. + +Return Value: + MA_SUCCESS if successful; any other error code otherwise. + +Thread Safety: SAFE +*/ ma_result ma_device_stop(ma_device* pDevice); -// Determines whether or not the device is started. -// -// This is implemented as a simple accessor. -// -// Return Value: -// True if the device is started, false otherwise. -// -// Thread Safety: SAFE -// If another thread calls ma_device_start() or ma_device_stop() at this same time as this function -// is called, there's a very small chance the return value will be out of sync. +/* +Determines whether or not the device is started. + +This is implemented as a simple accessor. + +Return Value: + True if the device is started, false otherwise. + +Thread Safety: SAFE + If another thread calls ma_device_start() or ma_device_stop() at this same time as this function + is called, there's a very small chance the return value will be out of sync. +*/ ma_bool32 ma_device_is_started(ma_device* pDevice); -// Helper function for initializing a ma_context_config object. +/* +Helper function for initializing a ma_context_config object. +*/ ma_context_config ma_context_config_init(void); -// Initializes a device config. -// -// By default, the device config will use native device settings (format, channels, sample rate, etc.). Using native -// settings means you will get an optimized pass-through data transmission pipeline to and from the device, but you will -// need to do all format conversions manually. Normally you would want to use a known format that your program can handle -// natively, which you can do by specifying it after this function returns, like so: -// -// ma_device_config config = ma_device_config_init(ma_device_type_playback); -// config.callback = my_data_callback; -// config.pUserData = pMyUserData; -// config.format = ma_format_f32; -// config.channels = 2; -// config.sampleRate = 44100; -// -// In this case miniaudio will perform all of the necessary data conversion for you behind the scenes. -// -// Currently miniaudio only supports asynchronous, callback based data delivery which means you must specify callback. A -// pointer to user data can also be specified which is set in the pUserData member of the ma_device object. -// -// To specify a channel map you can use ma_get_standard_channel_map(): -// -// ma_get_standard_channel_map(ma_standard_channel_map_default, config.channels, config.channelMap); -// -// Alternatively you can set the channel map manually if you need something specific or something that isn't one of miniaudio's -// stock channel maps. -// -// By default the system's default device will be used. Set the pDeviceID member to a pointer to a ma_device_id object to -// use a specific device. You can enumerate over the devices with ma_context_enumerate_devices() or ma_context_get_devices() -// which will give you access to the device ID. Set pDeviceID to NULL to use the default device. -// -// The device type can be one of the ma_device_type's: -// ma_device_type_playback -// ma_device_type_capture -// ma_device_type_duplex -// -// Thread Safety: SAFE +/* +Initializes a device config. + +By default, the device config will use native device settings (format, channels, sample rate, etc.). Using native +settings means you will get an optimized pass-through data transmission pipeline to and from the device, but you will +need to do all format conversions manually. Normally you would want to use a known format that your program can handle +natively, which you can do by specifying it after this function returns, like so: + + ma_device_config config = ma_device_config_init(ma_device_type_playback); + config.callback = my_data_callback; + config.pUserData = pMyUserData; + config.format = ma_format_f32; + config.channels = 2; + config.sampleRate = 44100; + +In this case miniaudio will perform all of the necessary data conversion for you behind the scenes. + +Currently miniaudio only supports asynchronous, callback based data delivery which means you must specify callback. A +pointer to user data can also be specified which is set in the pUserData member of the ma_device object. + +To specify a channel map you can use ma_get_standard_channel_map(): + + ma_get_standard_channel_map(ma_standard_channel_map_default, config.channels, config.channelMap); + +Alternatively you can set the channel map manually if you need something specific or something that isn't one of miniaudio's +stock channel maps. + +By default the system's default device will be used. Set the pDeviceID member to a pointer to a ma_device_id object to +use a specific device. You can enumerate over the devices with ma_context_enumerate_devices() or ma_context_get_devices() +which will give you access to the device ID. Set pDeviceID to NULL to use the default device. + +The device type can be one of the ma_device_type's: + ma_device_type_playback + ma_device_type_capture + ma_device_type_duplex + +Thread Safety: SAFE +*/ ma_device_config ma_device_config_init(ma_device_type deviceType); -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Utiltities -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +/************************************************************************************************************************************************************ + +Utiltities + +************************************************************************************************************************************************************/ + +/* +Creates a mutex. -// Creates a mutex. -// -// A mutex must be created from a valid context. A mutex is initially unlocked. +A mutex must be created from a valid context. A mutex is initially unlocked. +*/ ma_result ma_mutex_init(ma_context* pContext, ma_mutex* pMutex); -// Deletes a mutex. +/* +Deletes a mutex. +*/ void ma_mutex_uninit(ma_mutex* pMutex); -// Locks a mutex with an infinite timeout. +/* +Locks a mutex with an infinite timeout. +*/ void ma_mutex_lock(ma_mutex* pMutex); -// Unlocks a mutex. +/* +Unlocks a mutex. +*/ void ma_mutex_unlock(ma_mutex* pMutex); -// Retrieves a friendly name for a backend. +/* +Retrieves a friendly name for a backend. +*/ const char* ma_get_backend_name(ma_backend backend); -// Adjust buffer size based on a scaling factor. -// -// This just multiplies the base size by the scaling factor, making sure it's a size of at least 1. +/* +Adjust buffer size based on a scaling factor. + +This just multiplies the base size by the scaling factor, making sure it's a size of at least 1. +*/ ma_uint32 ma_scale_buffer_size(ma_uint32 baseBufferSize, float scale); -// Calculates a buffer size in milliseconds from the specified number of frames and sample rate. +/* +Calculates a buffer size in milliseconds from the specified number of frames and sample rate. +*/ ma_uint32 ma_calculate_buffer_size_in_milliseconds_from_frames(ma_uint32 bufferSizeInFrames, ma_uint32 sampleRate); -// Calculates a buffer size in frames from the specified number of milliseconds and sample rate. +/* +Calculates a buffer size in frames from the specified number of milliseconds and sample rate. +*/ ma_uint32 ma_calculate_buffer_size_in_frames_from_milliseconds(ma_uint32 bufferSizeInMilliseconds, ma_uint32 sampleRate); -// Retrieves the default buffer size in milliseconds based on the specified performance profile. +/* +Retrieves the default buffer size in milliseconds based on the specified performance profile. +*/ ma_uint32 ma_get_default_buffer_size_in_milliseconds(ma_performance_profile performanceProfile); -// Calculates a buffer size in frames for the specified performance profile and scale factor. +/* +Calculates a buffer size in frames for the specified performance profile and scale factor. +*/ ma_uint32 ma_get_default_buffer_size_in_frames(ma_performance_profile performanceProfile, ma_uint32 sampleRate); - -// Copies silent frames into the given buffer. +/* +Copies silent frames into the given buffer. +*/ void ma_zero_pcm_frames(void* p, ma_uint32 frameCount, ma_format format, ma_uint32 channels); -#endif // MA_NO_DEVICE_IO +#endif /* MA_NO_DEVICE_IO */ -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Decoding -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -#ifndef MA_NO_DECODING +/************************************************************************************************************************************************************ + +Decoding + +************************************************************************************************************************************************************/ +#ifndef MA_NO_DECODING typedef struct ma_decoder ma_decoder; @@ -2868,16 +2990,16 @@ typedef enum ma_seek_origin_current } ma_seek_origin; -typedef size_t (* ma_decoder_read_proc) (ma_decoder* pDecoder, void* pBufferOut, size_t bytesToRead); // Returns the number of bytes read. +typedef size_t (* ma_decoder_read_proc) (ma_decoder* pDecoder, void* pBufferOut, size_t bytesToRead); /* Returns the number of bytes read. */ typedef ma_bool32 (* ma_decoder_seek_proc) (ma_decoder* pDecoder, int byteOffset, ma_seek_origin origin); typedef ma_result (* ma_decoder_seek_to_pcm_frame_proc)(ma_decoder* pDecoder, ma_uint64 frameIndex); typedef ma_result (* ma_decoder_uninit_proc) (ma_decoder* pDecoder); typedef struct { - ma_format format; // Set to 0 or ma_format_unknown to use the stream's internal format. - ma_uint32 channels; // Set to 0 to use the stream's internal channels. - ma_uint32 sampleRate; // Set to 0 to use the stream's internal sample rate. + ma_format format; /* Set to 0 or ma_format_unknown to use the stream's internal format. */ + ma_uint32 channels; /* Set to 0 to use the stream's internal channels. */ + ma_uint32 sampleRate; /* Set to 0 to use the stream's internal sample rate. */ ma_channel channelMap[MA_MAX_CHANNELS]; ma_channel_mix_mode channelMixMode; ma_dither_mode ditherMode; @@ -2902,16 +3024,16 @@ struct ma_decoder ma_uint32 outputChannels; ma_uint32 outputSampleRate; ma_channel outputChannelMap[MA_MAX_CHANNELS]; - ma_pcm_converter dsp; // <-- Format conversion is achieved by running frames through this. + ma_pcm_converter dsp; /* <-- Format conversion is achieved by running frames through this. */ ma_decoder_seek_to_pcm_frame_proc onSeekToPCMFrame; ma_decoder_uninit_proc onUninit; - void* pInternalDecoder; // <-- The drwav/drflac/stb_vorbis/etc. objects. + void* pInternalDecoder; /* <-- The drwav/drflac/stb_vorbis/etc. objects. */ struct { const ma_uint8* pData; size_t dataSize; size_t currentReadPos; - } memory; // Only used for decoders that were opened against a block of memory. + } memory; /* Only used for decoders that were opened against a block of memory. */ }; ma_decoder_config ma_decoder_config_init(ma_format outputFormat, ma_uint32 outputChannels, ma_uint32 outputSampleRate); @@ -2940,23 +3062,23 @@ ma_result ma_decoder_uninit(ma_decoder* pDecoder); ma_uint64 ma_decoder_read_pcm_frames(ma_decoder* pDecoder, void* pFramesOut, ma_uint64 frameCount); ma_result ma_decoder_seek_to_pcm_frame(ma_decoder* pDecoder, ma_uint64 frameIndex); - -// Helper for opening and decoding a file into a heap allocated block of memory. Free the returned pointer with ma_free(). On input, -// pConfig should be set to what you want. On output it will be set to what you got. +/* +Helper for opening and decoding a file into a heap allocated block of memory. Free the returned pointer with ma_free(). On input, +pConfig should be set to what you want. On output it will be set to what you got. +*/ #ifndef MA_NO_STDIO ma_result ma_decode_file(const char* pFilePath, ma_decoder_config* pConfig, ma_uint64* pFrameCountOut, void** ppDataOut); #endif ma_result ma_decode_memory(const void* pData, size_t dataSize, ma_decoder_config* pConfig, ma_uint64* pFrameCountOut, void** ppDataOut); -#endif // MA_NO_DECODING +#endif /* MA_NO_DECODING */ -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Generation -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +/************************************************************************************************************************************************************ +Generation + +************************************************************************************************************************************************************/ typedef struct { double amplitude; @@ -2972,32 +3094,34 @@ ma_uint64 ma_sine_wave_read_f32_ex(ma_sine_wave* pSineWave, ma_uint64 frameCount #ifdef __cplusplus } #endif -#endif //miniaudio_h +#endif /* miniaudio_h */ + -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// IMPLEMENTATION -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +/************************************************************************************************************************************************************ +************************************************************************************************************************************************************* + +IMPLEMENTATION + +************************************************************************************************************************************************************* +************************************************************************************************************************************************************/ #if defined(MINIAUDIO_IMPLEMENTATION) || defined(MA_IMPLEMENTATION) #include -#include // For INT_MAX -#include // sin(), etc. +#include /* For INT_MAX */ +#include /* sin(), etc. */ #if defined(MA_DEBUG_OUTPUT) -#include // for printf() for debug output +#include /* for printf() for debug output */ #endif #ifdef MA_WIN32 -// @raysan5: To avoid conflicting windows.h symbols with raylib, so flags are defined -// WARNING: Those flags avoid inclusion of some Win32 headers that could be required -// by user at some point and won't be included... -//------------------------------------------------------------------------------------- +/* + @raysan5: To avoid conflicting windows.h symbols with raylib, so flags are defined + WARNING: Those flags avoid inclusion of some Win32 headers that could be required + by user at some point and won't be included... +*/ -// If defined, the following flags inhibit definition of the indicated items. +/* If defined, the following flags inhibit definition of the indicated items.*/ #define NOGDICAPMASKS // CC_*, LC_*, PC_*, CP_*, TC_*, RC_ #define NOVIRTUALKEYCODES // VK_* #define NOWINMESSAGES // WM_*, EM_*, LB_*, CB_* @@ -3018,7 +3142,7 @@ ma_uint64 ma_sine_wave_read_f32_ex(ma_sine_wave* pSineWave, ma_uint64 frameCount #define NOGDI // All GDI defines and routines #define NOKERNEL // All KERNEL defines and routines #define NOUSER // All USER defines and routines -//#define NONLS // All NLS defines and routines +/*#define NONLS // All NLS defines and routines*/ #define NOMB // MB_* and MessageBox() #define NOMEMMGR // GMEM_*, LMEM_*, GHND, LHND, associated routines #define NOMETAFILE // typedef METAFILEPICT @@ -3038,12 +3162,12 @@ ma_uint64 ma_sine_wave_read_f32_ex(ma_sine_wave* pSineWave, ma_uint64 frameCount #define NODEFERWINDOWPOS // DeferWindowPos routines #define NOMCX // Modem Configuration Extensions -// Type required before windows.h inclusion +/* Type required before windows.h inclusion */ typedef struct tagMSG *LPMSG; #include -// Type required by some unused function... +/* Type required by some unused function... */ typedef struct tagBITMAPINFOHEADER { DWORD biSize; LONG biWidth; @@ -3062,19 +3186,18 @@ typedef struct tagBITMAPINFOHEADER { #include #include -// @raysan5: Some required types defined for MSVC/TinyC compiler +/* @raysan5: Some required types defined for MSVC/TinyC compiler */ #if defined(_MSC_VER) || defined(__TINYC__) #include "propidl.h" #endif -//---------------------------------------------------------------------------------- #else -#include // For malloc()/free() -#include // For memset() +#include /* For malloc()/free() */ +#include /* For memset() */ #endif #if defined(MA_APPLE) && (__MAC_OS_X_VERSION_MIN_REQUIRED < 101200) -#include // For mach_absolute_time() +#include /* For mach_absolute_time() */ #endif #ifdef MA_POSIX @@ -3117,7 +3240,7 @@ typedef struct tagBITMAPINFOHEADER { #endif #endif -// Architecture Detection +/* Architecture Detection */ #if defined(__x86_64__) || defined(_M_X64) #define MA_X64 #elif defined(__i386) || defined(_M_IX86) @@ -3126,35 +3249,35 @@ typedef struct tagBITMAPINFOHEADER { #define MA_ARM #endif -// Cannot currently support AVX-512 if AVX is disabled. +/* Cannot currently support AVX-512 if AVX is disabled. */ #if !defined(MA_NO_AVX512) && defined(MA_NO_AVX2) #define MA_NO_AVX512 #endif -// Intrinsics Support +/* Intrinsics Support */ #if defined(MA_X64) || defined(MA_X86) #if defined(_MSC_VER) && !defined(__clang__) - // MSVC. - #if !defined(MA_NO_SSE2) // Assume all MSVC compilers support SSE2 intrinsics. + /* MSVC. */ + #if _MSC_VER >= 1400 && !defined(MA_NO_SSE2) /* 2005 */ #define MA_SUPPORT_SSE2 #endif - //#if _MSC_VER >= 1600 && !defined(MA_NO_AVX) // 2010 - // #define MA_SUPPORT_AVX - //#endif - #if _MSC_VER >= 1700 && !defined(MA_NO_AVX2) // 2012 + /*#if _MSC_VER >= 1600 && !defined(MA_NO_AVX)*/ /* 2010 */ + /* #define MA_SUPPORT_AVX*/ + /*#endif*/ + #if _MSC_VER >= 1700 && !defined(MA_NO_AVX2) /* 2012 */ #define MA_SUPPORT_AVX2 #endif - #if _MSC_VER >= 1910 && !defined(MA_NO_AVX512) // 2017 + #if _MSC_VER >= 1910 && !defined(MA_NO_AVX512) /* 2017 */ #define MA_SUPPORT_AVX512 #endif #else - // Assume GNUC-style. + /* Assume GNUC-style. */ #if defined(__SSE2__) && !defined(MA_NO_SSE2) #define MA_SUPPORT_SSE2 #endif - //#if defined(__AVX__) && !defined(MA_NO_AVX) - // #define MA_SUPPORT_AVX - //#endif + /*#if defined(__AVX__) && !defined(MA_NO_AVX)*/ + /* #define MA_SUPPORT_AVX*/ + /*#endif*/ #if defined(__AVX2__) && !defined(MA_NO_AVX2) #define MA_SUPPORT_AVX2 #endif @@ -3163,14 +3286,14 @@ typedef struct tagBITMAPINFOHEADER { #endif #endif - // If at this point we still haven't determined compiler support for the intrinsics just fall back to __has_include. + /* If at this point we still haven't determined compiler support for the intrinsics just fall back to __has_include. */ #if !defined(__GNUC__) && !defined(__clang__) && defined(__has_include) #if !defined(MA_SUPPORT_SSE2) && !defined(MA_NO_SSE2) && __has_include() #define MA_SUPPORT_SSE2 #endif - //#if !defined(MA_SUPPORT_AVX) && !defined(MA_NO_AVX) && __has_include() - // #define MA_SUPPORT_AVX - //#endif + /*#if !defined(MA_SUPPORT_AVX) && !defined(MA_NO_AVX) && __has_include()*/ + /* #define MA_SUPPORT_AVX*/ + /*#endif*/ #if !defined(MA_SUPPORT_AVX2) && !defined(MA_NO_AVX2) && __has_include() #define MA_SUPPORT_AVX2 #endif @@ -3180,7 +3303,7 @@ typedef struct tagBITMAPINFOHEADER { #endif #if defined(MA_SUPPORT_AVX512) - #include // Not a mistake. Intentionally including instead of because otherwise the compiler will complain. + #include /* Not a mistake. Intentionally including instead of because otherwise the compiler will complain. */ #elif defined(MA_SUPPORT_AVX2) || defined(MA_SUPPORT_AVX) #include #elif defined(MA_SUPPORT_SSE2) @@ -3193,7 +3316,7 @@ typedef struct tagBITMAPINFOHEADER { #define MA_SUPPORT_NEON #endif - // Fall back to looking for the #include file. + /* Fall back to looking for the #include file. */ #if !defined(__GNUC__) && !defined(__clang__) && defined(__has_include) #if !defined(MA_SUPPORT_NEON) && !defined(MA_NO_NEON) && __has_include() #define MA_SUPPORT_NEON @@ -3207,7 +3330,7 @@ typedef struct tagBITMAPINFOHEADER { #if defined(_MSC_VER) #pragma warning(push) - #pragma warning(disable:4752) // found Intel(R) Advanced Vector Extensions; consider using /arch:AVX + #pragma warning(disable:4752) /* found Intel(R) Advanced Vector Extensions; consider using /arch:AVX */ #endif #if defined(MA_X64) || defined(MA_X86) @@ -3233,11 +3356,13 @@ typedef struct tagBITMAPINFOHEADER { #elif (defined(__GNUC__) || defined(__clang__)) && !defined(MA_ANDROID) static MA_INLINE void ma_cpuid(int info[4], int fid) { - // It looks like the -fPIC option uses the ebx register which GCC complains about. We can work around this by just using a different register, the - // specific register of which I'm letting the compiler decide on. The "k" prefix is used to specify a 32-bit register. The {...} syntax is for - // supporting different assembly dialects. - // - // What's basically happening is that we're saving and restoring the ebx register manually. + /* + It looks like the -fPIC option uses the ebx register which GCC complains about. We can work around this by just using a different register, the + specific register of which I'm letting the compiler decide on. The "k" prefix is used to specify a 32-bit register. The {...} syntax is for + supporting different assembly dialects. + + What's basically happening is that we're saving and restoring the ebx register manually. + */ #if defined(DRFLAC_X86) && defined(__PIC__) __asm__ __volatile__ ( "xchg{l} {%%}ebx, %k1;" @@ -3252,7 +3377,7 @@ typedef struct tagBITMAPINFOHEADER { #endif } - static MA_INLINE unsigned long long ma_xgetbv(int reg) + static MA_INLINE ma_uint64 ma_xgetbv(int reg) { unsigned int hi; unsigned int lo; @@ -3261,7 +3386,7 @@ typedef struct tagBITMAPINFOHEADER { "xgetbv" : "=a"(lo), "=d"(hi) : "c"(reg) ); - return ((unsigned long long)hi << 32ULL) | (unsigned long long)lo; + return ((ma_uint64)hi << 32) | (ma_uint64)lo; } #else #define MA_NO_CPUID @@ -3277,9 +3402,9 @@ static MA_INLINE ma_bool32 ma_has_sse2() #if defined(MA_SUPPORT_SSE2) #if (defined(MA_X64) || defined(MA_X86)) && !defined(MA_NO_SSE2) #if defined(MA_X64) - return MA_TRUE; // 64-bit targets always support SSE2. + return MA_TRUE; /* 64-bit targets always support SSE2. */ #elif (defined(_M_IX86_FP) && _M_IX86_FP == 2) || defined(__SSE2__) - return MA_TRUE; // If the compiler is allowed to freely generate SSE2 code we can assume support. + return MA_TRUE; /* If the compiler is allowed to freely generate SSE2 code we can assume support. */ #else #if defined(MA_NO_CPUID) return MA_FALSE; @@ -3290,10 +3415,10 @@ static MA_INLINE ma_bool32 ma_has_sse2() #endif #endif #else - return MA_FALSE; // SSE2 is only supported on x86 and x64 architectures. + return MA_FALSE; /* SSE2 is only supported on x86 and x64 architectures. */ #endif #else - return MA_FALSE; // No compiler support. + return MA_FALSE; /* No compiler support. */ #endif } @@ -3303,9 +3428,9 @@ static MA_INLINE ma_bool32 ma_has_avx() #if defined(MA_SUPPORT_AVX) #if (defined(MA_X64) || defined(MA_X86)) && !defined(MA_NO_AVX) #if defined(_AVX_) || defined(__AVX__) - return MA_TRUE; // If the compiler is allowed to freely generate AVX code we can assume support. + return MA_TRUE; /* If the compiler is allowed to freely generate AVX code we can assume support. */ #else - // AVX requires both CPU and OS support. + /* AVX requires both CPU and OS support. */ #if defined(MA_NO_CPUID) || defined(MA_NO_XGETBV) return MA_FALSE; #else @@ -3324,10 +3449,10 @@ static MA_INLINE ma_bool32 ma_has_avx() #endif #endif #else - return MA_FALSE; // AVX is only supported on x86 and x64 architectures. + return MA_FALSE; /* AVX is only supported on x86 and x64 architectures. */ #endif #else - return MA_FALSE; // No compiler support. + return MA_FALSE; /* No compiler support. */ #endif } #endif @@ -3337,9 +3462,9 @@ static MA_INLINE ma_bool32 ma_has_avx2() #if defined(MA_SUPPORT_AVX2) #if (defined(MA_X64) || defined(MA_X86)) && !defined(MA_NO_AVX2) #if defined(_AVX2_) || defined(__AVX2__) - return MA_TRUE; // If the compiler is allowed to freely generate AVX2 code we can assume support. + return MA_TRUE; /* If the compiler is allowed to freely generate AVX2 code we can assume support. */ #else - // AVX2 requires both CPU and OS support. + /* AVX2 requires both CPU and OS support. */ #if defined(MA_NO_CPUID) || defined(MA_NO_XGETBV) return MA_FALSE; #else @@ -3360,10 +3485,10 @@ static MA_INLINE ma_bool32 ma_has_avx2() #endif #endif #else - return MA_FALSE; // AVX2 is only supported on x86 and x64 architectures. + return MA_FALSE; /* AVX2 is only supported on x86 and x64 architectures. */ #endif #else - return MA_FALSE; // No compiler support. + return MA_FALSE; /* No compiler support. */ #endif } @@ -3372,9 +3497,9 @@ static MA_INLINE ma_bool32 ma_has_avx512f() #if defined(MA_SUPPORT_AVX512) #if (defined(MA_X64) || defined(MA_X86)) && !defined(MA_NO_AVX512) #if defined(__AVX512F__) - return MA_TRUE; // If the compiler is allowed to freely generate AVX-512F code we can assume support. + return MA_TRUE; /* If the compiler is allowed to freely generate AVX-512F code we can assume support. */ #else - // AVX-512 requires both CPU and OS support. + /* AVX-512 requires both CPU and OS support. */ #if defined(MA_NO_CPUID) || defined(MA_NO_XGETBV) return MA_FALSE; #else @@ -3395,10 +3520,10 @@ static MA_INLINE ma_bool32 ma_has_avx512f() #endif #endif #else - return MA_FALSE; // AVX-512F is only supported on x86 and x64 architectures. + return MA_FALSE; /* AVX-512F is only supported on x86 and x64 architectures. */ #endif #else - return MA_FALSE; // No compiler support. + return MA_FALSE; /* No compiler support. */ #endif } @@ -3407,16 +3532,16 @@ static MA_INLINE ma_bool32 ma_has_neon() #if defined(MA_SUPPORT_NEON) #if defined(MA_ARM) && !defined(MA_NO_NEON) #if (defined(__ARM_NEON) || defined(__aarch64__) || defined(_M_ARM64)) - return MA_TRUE; // If the compiler is allowed to freely generate NEON code we can assume support. + return MA_TRUE; /* If the compiler is allowed to freely generate NEON code we can assume support. */ #else - // TODO: Runtime check. + /* TODO: Runtime check. */ return MA_FALSE; #endif #else - return MA_FALSE; // NEON is only supported on ARM architectures. + return MA_FALSE; /* NEON is only supported on ARM architectures. */ #endif #else - return MA_FALSE; // No compiler support. + return MA_FALSE; /* No compiler support. */ #endif } @@ -3457,78 +3582,78 @@ static MA_INLINE ma_bool32 ma_is_big_endian() #endif -// The default format when ma_format_unknown (0) is requested when initializing a device. +/* The default format when ma_format_unknown (0) is requested when initializing a device. */ #ifndef MA_DEFAULT_FORMAT #define MA_DEFAULT_FORMAT ma_format_f32 #endif -// The default channel count to use when 0 is used when initializing a device. +/* The default channel count to use when 0 is used when initializing a device. */ #ifndef MA_DEFAULT_CHANNELS #define MA_DEFAULT_CHANNELS 2 #endif -// The default sample rate to use when 0 is used when initializing a device. +/* The default sample rate to use when 0 is used when initializing a device. */ #ifndef MA_DEFAULT_SAMPLE_RATE #define MA_DEFAULT_SAMPLE_RATE 48000 #endif -// Default periods when none is specified in ma_device_init(). More periods means more work on the CPU. +/* Default periods when none is specified in ma_device_init(). More periods means more work on the CPU. */ #ifndef MA_DEFAULT_PERIODS #define MA_DEFAULT_PERIODS 3 #endif -// The base buffer size in milliseconds for low latency mode. +/* The base buffer size in milliseconds for low latency mode. */ #ifndef MA_BASE_BUFFER_SIZE_IN_MILLISECONDS_LOW_LATENCY #define MA_BASE_BUFFER_SIZE_IN_MILLISECONDS_LOW_LATENCY (10*MA_DEFAULT_PERIODS) #endif -// The base buffer size in milliseconds for conservative mode. +/* The base buffer size in milliseconds for conservative mode. */ #ifndef MA_BASE_BUFFER_SIZE_IN_MILLISECONDS_CONSERVATIVE #define MA_BASE_BUFFER_SIZE_IN_MILLISECONDS_CONSERVATIVE (100*MA_DEFAULT_PERIODS) #endif -// Standard sample rates, in order of priority. +/* Standard sample rates, in order of priority. */ ma_uint32 g_maStandardSampleRatePriorities[] = { - MA_SAMPLE_RATE_48000, // Most common + MA_SAMPLE_RATE_48000, /* Most common */ MA_SAMPLE_RATE_44100, - MA_SAMPLE_RATE_32000, // Lows + MA_SAMPLE_RATE_32000, /* Lows */ MA_SAMPLE_RATE_24000, MA_SAMPLE_RATE_22050, - MA_SAMPLE_RATE_88200, // Highs + MA_SAMPLE_RATE_88200, /* Highs */ MA_SAMPLE_RATE_96000, MA_SAMPLE_RATE_176400, MA_SAMPLE_RATE_192000, - MA_SAMPLE_RATE_16000, // Extreme lows + MA_SAMPLE_RATE_16000, /* Extreme lows */ MA_SAMPLE_RATE_11025, MA_SAMPLE_RATE_8000, - MA_SAMPLE_RATE_352800, // Extreme highs + MA_SAMPLE_RATE_352800, /* Extreme highs */ MA_SAMPLE_RATE_384000 }; ma_format g_maFormatPriorities[] = { - ma_format_s16, // Most common + ma_format_s16, /* Most common */ ma_format_f32, - //ma_format_s24_32, // Clean alignment + /*ma_format_s24_32,*/ /* Clean alignment */ ma_format_s32, - ma_format_s24, // Unclean alignment + ma_format_s24, /* Unclean alignment */ - ma_format_u8 // Low quality + ma_format_u8 /* Low quality */ }; -/////////////////////////////////////////////////////////////////////////////// -// -// Standard Library Stuff -// -/////////////////////////////////////////////////////////////////////////////// +/****************************************************************************** + +Standard Library Stuff + +******************************************************************************/ #ifndef MA_MALLOC #ifdef MA_WIN32 #define MA_MALLOC(sz) HeapAlloc(GetProcessHeap(), 0, (sz)) @@ -3590,15 +3715,18 @@ ma_format g_maFormatPriorities[] = { #define ma_buffer_frame_capacity(buffer, channels, format) (sizeof(buffer) / ma_get_bytes_per_sample(format) / (channels)) +/* +Return Values: + 0: Success + 22: EINVAL + 34: ERANGE -// Return Values: -// 0: Success -// 22: EINVAL -// 34: ERANGE -// -// Not using symbolic constants for errors because I want to avoid #including errno.h +Not using symbolic constants for errors because I want to avoid #including errno.h +*/ int ma_strcpy_s(char* dst, size_t dstSizeInBytes, const char* src) { + size_t i; + if (dst == 0) { return 22; } @@ -3610,7 +3738,6 @@ int ma_strcpy_s(char* dst, size_t dstSizeInBytes, const char* src) return 22; } - size_t i; for (i = 0; i < dstSizeInBytes && src[i] != '\0'; ++i) { dst[i] = src[i]; } @@ -3626,6 +3753,9 @@ int ma_strcpy_s(char* dst, size_t dstSizeInBytes, const char* src) int ma_strncpy_s(char* dst, size_t dstSizeInBytes, const char* src, size_t count) { + size_t maxcount; + size_t i; + if (dst == 0) { return 22; } @@ -3637,12 +3767,11 @@ int ma_strncpy_s(char* dst, size_t dstSizeInBytes, const char* src, size_t count return 22; } - size_t maxcount = count; - if (count == ((size_t)-1) || count >= dstSizeInBytes) { // -1 = _TRUNCATE + maxcount = count; + if (count == ((size_t)-1) || count >= dstSizeInBytes) { /* -1 = _TRUNCATE */ maxcount = dstSizeInBytes - 1; } - size_t i; for (i = 0; i < maxcount && src[i] != '\0'; ++i) { dst[i] = src[i]; } @@ -3658,6 +3787,8 @@ int ma_strncpy_s(char* dst, size_t dstSizeInBytes, const char* src, size_t count int ma_strcat_s(char* dst, size_t dstSizeInBytes, const char* src) { + char* dstorig; + if (dst == 0) { return 22; } @@ -3669,7 +3800,7 @@ int ma_strcat_s(char* dst, size_t dstSizeInBytes, const char* src) return 22; } - char* dstorig = dst; + dstorig = dst; while (dstSizeInBytes > 0 && dst[0] != '\0') { dst += 1; @@ -3677,7 +3808,7 @@ int ma_strcat_s(char* dst, size_t dstSizeInBytes, const char* src) } if (dstSizeInBytes == 0) { - return 22; // Unterminated. + return 22; /* Unterminated. */ } @@ -3698,6 +3829,10 @@ int ma_strcat_s(char* dst, size_t dstSizeInBytes, const char* src) int ma_itoa_s(int value, char* dst, size_t dstSizeInBytes, int radix) { + int sign; + unsigned int valueU; + char* dstEnd; + if (dst == NULL || dstSizeInBytes == 0) { return 22; } @@ -3706,16 +3841,15 @@ int ma_itoa_s(int value, char* dst, size_t dstSizeInBytes, int radix) return 22; } - int sign = (value < 0 && radix == 10) ? -1 : 1; // The negative sign is only used when the base is 10. + sign = (value < 0 && radix == 10) ? -1 : 1; /* The negative sign is only used when the base is 10. */ - unsigned int valueU; if (value < 0) { valueU = -value; } else { valueU = value; } - char* dstEnd = dst; + dstEnd = dst; do { int remainder = valueU % radix; @@ -3732,7 +3866,7 @@ int ma_itoa_s(int value, char* dst, size_t dstSizeInBytes, int radix) if (dstSizeInBytes == 0) { dst[0] = '\0'; - return 22; // Ran out of room in the output buffer. + return 22; /* Ran out of room in the output buffer. */ } if (sign < 0) { @@ -3742,13 +3876,13 @@ int ma_itoa_s(int value, char* dst, size_t dstSizeInBytes, int radix) if (dstSizeInBytes == 0) { dst[0] = '\0'; - return 22; // Ran out of room in the output buffer. + return 22; /* Ran out of room in the output buffer. */ } *dstEnd = '\0'; - // At this point the string will be reversed. + /* At this point the string will be reversed. */ dstEnd -= 1; while (dst < dstEnd) { char temp = *dst; @@ -3766,8 +3900,7 @@ int ma_strcmp(const char* str1, const char* str2) { if (str1 == str2) return 0; - // These checks differ from the standard implementation. It's not important, but I prefer - // it just for sanity. + /* These checks differ from the standard implementation. It's not important, but I prefer it just for sanity. */ if (str1 == NULL) return -1; if (str2 == NULL) return 1; @@ -3800,7 +3933,7 @@ char* ma_copy_string(const char* src) } -// Thanks to good old Bit Twiddling Hacks for this one: http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 +/* Thanks to good old Bit Twiddling Hacks for this one: http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 */ static MA_INLINE unsigned int ma_next_power_of_2(unsigned int x) { x--; @@ -3846,7 +3979,7 @@ static MA_INLINE unsigned int ma_count_set_bits(unsigned int x) -// Clamps an f32 sample to -1..1 +/* Clamps an f32 sample to -1..1 */ static MA_INLINE float ma_clip_f32(float x) { if (x < -1) return -1; @@ -3863,7 +3996,7 @@ static MA_INLINE float ma_mix_f32_fast(float x, float y, float a) float r0 = (y - x); float r1 = r0*a; return x + r1; - //return x + (y - x)*a; + /*return x + (y - x)*a;*/ } #if defined(MA_SUPPORT_SSE2) @@ -3907,17 +4040,18 @@ static MA_INLINE float ma_scale_to_range_f32(float x, float lo, float hi) } +/* +Random Number Generation + +miniaudio uses the LCG random number generation algorithm. This is good enough for audio. -// Random Number Generation -// -// miniaudio uses the LCG random number generation algorithm. This is good enough for audio. -// -// Note that miniaudio's LCG implementation uses global state which is _not_ thread-local. When this is called across -// multiple threads, results will be unpredictable. However, it won't crash and results will still be random enough -// for miniaudio's purposes. -#define MA_LCG_M 4294967296 -#define MA_LCG_A 1103515245 -#define MA_LCG_C 12345 +Note that miniaudio's LCG implementation uses global state which is _not_ thread-local. When this is called across +multiple threads, results will be unpredictable. However, it won't crash and results will still be random enough +for miniaudio's purposes. +*/ +#define MA_LCG_M 2147483647 +#define MA_LCG_A 48271 +#define MA_LCG_C 0 static ma_int32 g_maLCG; void ma_seed(ma_int32 seed) @@ -3995,10 +4129,17 @@ static MA_INLINE ma_int32 ma_dither_s32(ma_dither_mode ditherMode, ma_int32 dith } -// Splits a buffer into parts of equal length and of the given alignment. The returned size of the split buffers will be a -// multiple of the alignment. The alignment must be a power of 2. +/* +Splits a buffer into parts of equal length and of the given alignment. The returned size of the split buffers will be a +multiple of the alignment. The alignment must be a power of 2. +*/ void ma_split_buffer(void* pBuffer, size_t bufferSize, size_t splitCount, size_t alignment, void** ppBuffersOut, size_t* pSplitSizeOut) { + ma_uintptr pBufferUnaligned; + ma_uintptr pBufferAligned; + size_t unalignedBytes; + size_t splitSize; + if (pSplitSizeOut) { *pSplitSizeOut = 0; } @@ -4011,18 +4152,19 @@ void ma_split_buffer(void* pBuffer, size_t bufferSize, size_t splitCount, size_t alignment = 1; } - ma_uintptr pBufferUnaligned = (ma_uintptr)pBuffer; - ma_uintptr pBufferAligned = (pBufferUnaligned + (alignment-1)) & ~(alignment-1); - size_t unalignedBytes = (size_t)(pBufferAligned - pBufferUnaligned); + pBufferUnaligned = (ma_uintptr)pBuffer; + pBufferAligned = (pBufferUnaligned + (alignment-1)) & ~(alignment-1); + unalignedBytes = (size_t)(pBufferAligned - pBufferUnaligned); - size_t splitSize = 0; + splitSize = 0; if (bufferSize >= unalignedBytes) { splitSize = (bufferSize - unalignedBytes) / splitCount; splitSize = splitSize & ~(alignment-1); } if (ppBuffersOut != NULL) { - for (size_t i = 0; i < splitCount; ++i) { + size_t i; + for (i = 0; i < splitCount; ++i) { ppBuffersOut[i] = (ma_uint8*)(pBufferAligned + (splitSize*i)); } } @@ -4033,11 +4175,11 @@ void ma_split_buffer(void* pBuffer, size_t bufferSize, size_t splitCount, size_t } -/////////////////////////////////////////////////////////////////////////////// -// -// Atomics -// -/////////////////////////////////////////////////////////////////////////////// +/****************************************************************************** + +Atomics + +******************************************************************************/ #if defined(_WIN32) && !defined(__GNUC__) #define ma_memory_barrier() MemoryBarrier() #define ma_atomic_exchange_32(a, b) InterlockedExchange((LONG*)a, (LONG)b) @@ -4060,9 +4202,10 @@ void ma_split_buffer(void* pBuffer, size_t bufferSize, size_t splitCount, size_t #endif -ma_uint32 ma_get_standard_sample_rate_priority_index(ma_uint32 sampleRate) // Lower = higher priority +ma_uint32 ma_get_standard_sample_rate_priority_index(ma_uint32 sampleRate) /* Lower = higher priority */ { - for (ma_uint32 i = 0; i < ma_countof(g_maStandardSampleRatePriorities); ++i) { + ma_uint32 i; + for (i = 0; i < ma_countof(g_maStandardSampleRatePriorities); ++i) { if (g_maStandardSampleRatePriorities[i] == sampleRate) { return i; } @@ -4073,13 +4216,12 @@ ma_uint32 ma_get_standard_sample_rate_priority_index(ma_uint32 sampleRate) // ma_uint64 ma_calculate_frame_count_after_src(ma_uint32 sampleRateOut, ma_uint32 sampleRateIn, ma_uint64 frameCountIn) { - double srcRatio = (double)sampleRateOut / sampleRateIn; - double frameCountOutF = frameCountIn * srcRatio; - - ma_uint64 frameCountOut = (ma_uint64)frameCountOutF; + double srcRatio = (double)sampleRateOut / sampleRateIn; + double frameCountOutF = (ma_int64)frameCountIn * srcRatio; /* Cast to int64 required for VC6. */ + ma_uint64 frameCountOut = (ma_uint64)frameCountOutF; - // If the output frame count is fractional, make sure we add an extra frame to ensure there's enough room for that last sample. - if ((frameCountOutF - frameCountOut) > 0.0) { + /* If the output frame count is fractional, make sure we add an extra frame to ensure there's enough room for that last sample. */ + if ((frameCountOutF - (ma_int64)frameCountOut) > 0.0) { frameCountOut += 1; } @@ -4087,39 +4229,43 @@ ma_uint64 ma_calculate_frame_count_after_src(ma_uint32 sampleRateOut, ma_uint32 } -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// DEVICE I/O -// ========== -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +/************************************************************************************************************************************************************ +************************************************************************************************************************************************************* + +DEVICE I/O +========== + +************************************************************************************************************************************************************* +************************************************************************************************************************************************************/ #ifndef MA_NO_DEVICE_IO -// Unfortunately using runtime linking for pthreads causes problems. This has occurred for me when testing on FreeBSD. When -// using runtime linking, deadlocks can occur (for me it happens when loading data from fread()). It turns out that doing -// compile-time linking fixes this. I'm not sure why this happens, but the safest way I can think of to fix this is to simply -// disable runtime linking by default. To enable runtime linking, #define this before the implementation of this file. I am -// not officially supporting this, but I'm leaving it here in case it's useful for somebody, somewhere. -//#define MA_USE_RUNTIME_LINKING_FOR_PTHREAD - -// Disable run-time linking on certain backends. +/* +Unfortunately using runtime linking for pthreads causes problems. This has occurred for me when testing on FreeBSD. When +using runtime linking, deadlocks can occur (for me it happens when loading data from fread()). It turns out that doing +compile-time linking fixes this. I'm not sure why this happens, but the safest way I can think of to fix this is to simply +disable runtime linking by default. To enable runtime linking, #define this before the implementation of this file. I am +not officially supporting this, but I'm leaving it here in case it's useful for somebody, somewhere. +*/ +/*#define MA_USE_RUNTIME_LINKING_FOR_PTHREAD*/ + +/* Disable run-time linking on certain backends. */ #ifndef MA_NO_RUNTIME_LINKING #if defined(MA_ANDROID) || defined(MA_EMSCRIPTEN) #define MA_NO_RUNTIME_LINKING #endif #endif -// Check if we have the necessary development packages for each backend at the top so we can use this to determine whether or not -// certain unused functions and variables can be excluded from the build to avoid warnings. +/* +Check if we have the necessary development packages for each backend at the top so we can use this to determine whether or not +certain unused functions and variables can be excluded from the build to avoid warnings. +*/ #ifdef MA_ENABLE_WASAPI - #define MA_HAS_WASAPI // Every compiler should support WASAPI + #define MA_HAS_WASAPI /* Every compiler should support WASAPI */ #endif #ifdef MA_ENABLE_DSOUND - #define MA_HAS_DSOUND // Every compiler should support DirectSound. + #define MA_HAS_DSOUND /* Every compiler should support DirectSound. */ #endif #ifdef MA_ENABLE_WINMM - #define MA_HAS_WINMM // Every compiler I'm aware of supports WinMM. + #define MA_HAS_WINMM /* Every compiler I'm aware of supports WinMM. */ #endif #ifdef MA_ENABLE_ALSA #define MA_HAS_ALSA @@ -4173,7 +4319,7 @@ ma_uint64 ma_calculate_frame_count_after_src(ma_uint32 sampleRateOut, ma_uint32 #define MA_HAS_WEBAUDIO #endif #ifdef MA_ENABLE_NULL - #define MA_HAS_NULL // Everything supports the null backend. + #define MA_HAS_NULL /* Everything supports the null backend. */ #endif const char* ma_get_backend_name(ma_backend backend) @@ -4220,7 +4366,7 @@ typedef int (WINAPI * MA_PFN_StringFromGUID2)(const GUID* const rguid, LPOLE typedef HWND (WINAPI * MA_PFN_GetForegroundWindow)(); typedef HWND (WINAPI * MA_PFN_GetDesktopWindow)(); -// Microsoft documents these APIs as returning LSTATUS, but the Win32 API shipping with some compilers do not define it. It's just a LONG. +/* Microsoft documents these APIs as returning LSTATUS, but the Win32 API shipping with some compilers do not define it. It's just a LONG. */ typedef LONG (WINAPI * MA_PFN_RegOpenKeyExA)(HKEY hKey, LPCSTR lpSubKey, DWORD ulOptions, REGSAM samDesired, PHKEY phkResult); typedef LONG (WINAPI * MA_PFN_RegCloseKey)(HKEY hKey); typedef LONG (WINAPI * MA_PFN_RegQueryValueExA)(HKEY hKey, LPCSTR lpValueName, LPDWORD lpReserved, LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData); @@ -4228,29 +4374,30 @@ typedef LONG (WINAPI * MA_PFN_RegQueryValueExA)(HKEY hKey, LPCSTR lpValueName, L #define MA_STATE_UNINITIALIZED 0 -#define MA_STATE_STOPPED 1 // The device's default state after initialization. -#define MA_STATE_STARTED 2 // The worker thread is in it's main loop waiting for the driver to request or deliver audio data. -#define MA_STATE_STARTING 3 // Transitioning from a stopped state to started. -#define MA_STATE_STOPPING 4 // Transitioning from a started state to stopped. +#define MA_STATE_STOPPED 1 /* The device's default state after initialization. */ +#define MA_STATE_STARTED 2 /* The worker thread is in it's main loop waiting for the driver to request or deliver audio data. */ +#define MA_STATE_STARTING 3 /* Transitioning from a stopped state to started. */ +#define MA_STATE_STOPPING 4 /* Transitioning from a started state to stopped. */ #define MA_DEFAULT_PLAYBACK_DEVICE_NAME "Default Playback Device" #define MA_DEFAULT_CAPTURE_DEVICE_NAME "Default Capture Device" -/////////////////////////////////////////////////////////////////////////////// -// -// Timing -// -/////////////////////////////////////////////////////////////////////////////// +/******************************************************************************* + +Timing + +*******************************************************************************/ #ifdef MA_WIN32 LARGE_INTEGER g_ma_TimerFrequency = {{0}}; void ma_timer_init(ma_timer* pTimer) { + LARGE_INTEGER counter; + if (g_ma_TimerFrequency.QuadPart == 0) { QueryPerformanceFrequency(&g_ma_TimerFrequency); } - LARGE_INTEGER counter; QueryPerformanceCounter(&counter); pTimer->counter = counter.QuadPart; } @@ -4310,11 +4457,14 @@ void ma_timer_init(ma_timer* pTimer) double ma_timer_get_time_in_seconds(ma_timer* pTimer) { + ma_uint64 newTimeCounter; + ma_uint64 oldTimeCounter; + struct timespec newTime; clock_gettime(MA_CLOCK_ID, &newTime); - ma_uint64 newTimeCounter = (newTime.tv_sec * 1000000000) + newTime.tv_nsec; - ma_uint64 oldTimeCounter = pTimer->counter; + newTimeCounter = (newTime.tv_sec * 1000000000) + newTime.tv_nsec; + oldTimeCounter = pTimer->counter; return (newTimeCounter - oldTimeCounter) / 1000000000.0; } @@ -4329,11 +4479,14 @@ void ma_timer_init(ma_timer* pTimer) double ma_timer_get_time_in_seconds(ma_timer* pTimer) { + ma_uint64 newTimeCounter; + ma_uint64 oldTimeCounter; + struct timeval newTime; gettimeofday(&newTime, NULL); - ma_uint64 newTimeCounter = (newTime.tv_sec * 1000000) + newTime.tv_usec; - ma_uint64 oldTimeCounter = pTimer->counter; + newTimeCounter = (newTime.tv_sec * 1000000) + newTime.tv_usec; + oldTimeCounter = pTimer->counter; return (newTimeCounter - oldTimeCounter) / 1000000.0; } @@ -4341,18 +4494,18 @@ double ma_timer_get_time_in_seconds(ma_timer* pTimer) #endif -/////////////////////////////////////////////////////////////////////////////// -// -// Dynamic Linking -// -/////////////////////////////////////////////////////////////////////////////// +/******************************************************************************* + +Dynamic Linking + +*******************************************************************************/ ma_handle ma_dlopen(const char* filename) { #ifdef _WIN32 #ifdef MA_WIN32_DESKTOP return (ma_handle)LoadLibraryA(filename); #else - // *sigh* It appears there is no ANSI version of LoadPackagedLibrary()... + /* *sigh* It appears there is no ANSI version of LoadPackagedLibrary()... */ WCHAR filenameW[4096]; if (MultiByteToWideChar(CP_UTF8, 0, filename, -1, filenameW, sizeof(filenameW)) == 0) { return NULL; @@ -4391,11 +4544,11 @@ ma_proc ma_dlsym(ma_handle handle, const char* symbol) } -/////////////////////////////////////////////////////////////////////////////// -// -// Threading -// -/////////////////////////////////////////////////////////////////////////////// +/******************************************************************************* + +Threading + +*******************************************************************************/ #ifdef MA_WIN32 int ma_thread_priority_to_win32(ma_thread_priority priority) { @@ -4510,12 +4663,13 @@ typedef int (* ma_pthread_attr_setschedpolicy_proc)(pthread_attr_t *attr, int po typedef int (* ma_pthread_attr_getschedparam_proc)(const pthread_attr_t *attr, struct sched_param *param); typedef int (* ma_pthread_attr_setschedparam_proc)(pthread_attr_t *attr, const struct sched_param *param); -ma_bool32 ma_thread_create__posix(ma_context* pContext, ma_thread* pThread, ma_thread_entry_proc entryProc, void* pData) +ma_result ma_thread_create__posix(ma_context* pContext, ma_thread* pThread, ma_thread_entry_proc entryProc, void* pData) { + int result; pthread_attr_t* pAttr = NULL; #if !defined(__EMSCRIPTEN__) - // Try setting the thread priority. It's not critical if anything fails here. + /* Try setting the thread priority. It's not critical if anything fails here. */ pthread_attr_t attr; if (((ma_pthread_attr_init_proc)pContext->posix.pthread_attr_init)(&attr) == 0) { int scheduler = -1; @@ -4540,7 +4694,7 @@ ma_bool32 ma_thread_create__posix(ma_context* pContext, ma_thread* pThread, ma_t if (scheduler != -1) { int priorityMin = sched_get_priority_min(scheduler); int priorityMax = sched_get_priority_max(scheduler); - int priorityStep = (priorityMax - priorityMin) / 7; // 7 = number of priorities supported by miniaudio. + int priorityStep = (priorityMax - priorityMin) / 7; /* 7 = number of priorities supported by miniaudio. */ struct sched_param sched; if (((ma_pthread_attr_getschedparam_proc)pContext->posix.pthread_attr_getschedparam)(&attr, &sched) == 0) { @@ -4549,7 +4703,7 @@ ma_bool32 ma_thread_create__posix(ma_context* pContext, ma_thread* pThread, ma_t } else if (pContext->threadPriority == ma_thread_priority_realtime) { sched.sched_priority = priorityMax; } else { - sched.sched_priority += ((int)pContext->threadPriority + 5) * priorityStep; // +5 because the lowest priority is -5. + sched.sched_priority += ((int)pContext->threadPriority + 5) * priorityStep; /* +5 because the lowest priority is -5. */ if (sched.sched_priority < priorityMin) { sched.sched_priority = priorityMin; } @@ -4568,7 +4722,7 @@ ma_bool32 ma_thread_create__posix(ma_context* pContext, ma_thread* pThread, ma_t } #endif - int result = ((ma_pthread_create_proc)pContext->posix.pthread_create)(&pThread->posix.thread, pAttr, entryProc, pData); + result = ((ma_pthread_create_proc)pContext->posix.pthread_create)(&pThread->posix.thread, pAttr, entryProc, pData); if (result != 0) { return MA_FAILED_TO_CREATE_THREAD; } @@ -4655,7 +4809,7 @@ ma_bool32 ma_event_wait__posix(ma_event* pEvent) while (pEvent->posix.value == 0) { ((ma_pthread_cond_wait_proc)pEvent->pContext->posix.pthread_cond_wait)(&pEvent->posix.condition, &pEvent->posix.mutex); } - pEvent->posix.value = 0; // Auto-reset. + pEvent->posix.value = 0; /* Auto-reset. */ } ((ma_pthread_mutex_unlock_proc)pEvent->pContext->posix.pthread_mutex_unlock)(&pEvent->posix.mutex); @@ -4677,7 +4831,9 @@ ma_bool32 ma_event_signal__posix(ma_event* pEvent) ma_result ma_thread_create(ma_context* pContext, ma_thread* pThread, ma_thread_entry_proc entryProc, void* pData) { - if (pContext == NULL || pThread == NULL || entryProc == NULL) return MA_FALSE; + if (pContext == NULL || pThread == NULL || entryProc == NULL) { + return MA_FALSE; + } pThread->pContext = pContext; @@ -4691,7 +4847,9 @@ ma_result ma_thread_create(ma_context* pContext, ma_thread* pThread, ma_thread_e void ma_thread_wait(ma_thread* pThread) { - if (pThread == NULL) return; + if (pThread == NULL) { + return; + } #ifdef MA_WIN32 ma_thread_wait__win32(pThread); @@ -4730,7 +4888,9 @@ ma_result ma_mutex_init(ma_context* pContext, ma_mutex* pMutex) void ma_mutex_uninit(ma_mutex* pMutex) { - if (pMutex == NULL || pMutex->pContext == NULL) return; + if (pMutex == NULL || pMutex->pContext == NULL) { + return; + } #ifdef MA_WIN32 ma_mutex_uninit__win32(pMutex); @@ -4742,7 +4902,9 @@ void ma_mutex_uninit(ma_mutex* pMutex) void ma_mutex_lock(ma_mutex* pMutex) { - if (pMutex == NULL || pMutex->pContext == NULL) return; + if (pMutex == NULL || pMutex->pContext == NULL) { + return; + } #ifdef MA_WIN32 ma_mutex_lock__win32(pMutex); @@ -4754,7 +4916,9 @@ void ma_mutex_lock(ma_mutex* pMutex) void ma_mutex_unlock(ma_mutex* pMutex) { - if (pMutex == NULL || pMutex->pContext == NULL) return; + if (pMutex == NULL || pMutex->pContext == NULL) { + return; +} #ifdef MA_WIN32 ma_mutex_unlock__win32(pMutex); @@ -4767,7 +4931,9 @@ void ma_mutex_unlock(ma_mutex* pMutex) ma_result ma_event_init(ma_context* pContext, ma_event* pEvent) { - if (pContext == NULL || pEvent == NULL) return MA_FALSE; + if (pContext == NULL || pEvent == NULL) { + return MA_FALSE; + } pEvent->pContext = pContext; @@ -4781,7 +4947,9 @@ ma_result ma_event_init(ma_context* pContext, ma_event* pEvent) void ma_event_uninit(ma_event* pEvent) { - if (pEvent == NULL || pEvent->pContext == NULL) return; + if (pEvent == NULL || pEvent->pContext == NULL) { + return; + } #ifdef MA_WIN32 ma_event_uninit__win32(pEvent); @@ -4793,7 +4961,9 @@ void ma_event_uninit(ma_event* pEvent) ma_bool32 ma_event_wait(ma_event* pEvent) { - if (pEvent == NULL || pEvent->pContext == NULL) return MA_FALSE; + if (pEvent == NULL || pEvent->pContext == NULL) { + return MA_FALSE; + } #ifdef MA_WIN32 return ma_event_wait__win32(pEvent); @@ -4805,7 +4975,9 @@ ma_bool32 ma_event_wait(ma_event* pEvent) ma_bool32 ma_event_signal(ma_event* pEvent) { - if (pEvent == NULL || pEvent->pContext == NULL) return MA_FALSE; + if (pEvent == NULL || pEvent->pContext == NULL) { + return MA_FALSE; + } #ifdef MA_WIN32 return ma_event_signal__win32(pEvent); @@ -4818,7 +4990,7 @@ ma_bool32 ma_event_signal(ma_event* pEvent) ma_uint32 ma_get_best_sample_rate_within_range(ma_uint32 sampleRateMin, ma_uint32 sampleRateMax) { - // Normalize the range in case we were given something stupid. + /* Normalize the range in case we were given something stupid. */ if (sampleRateMin < MA_MIN_SAMPLE_RATE) { sampleRateMin = MA_MIN_SAMPLE_RATE; } @@ -4832,7 +5004,8 @@ ma_uint32 ma_get_best_sample_rate_within_range(ma_uint32 sampleRateMin, ma_uint3 if (sampleRateMin == sampleRateMax) { return sampleRateMax; } else { - for (size_t iStandardRate = 0; iStandardRate < ma_countof(g_maStandardSampleRatePriorities); ++iStandardRate) { + size_t iStandardRate; + for (iStandardRate = 0; iStandardRate < ma_countof(g_maStandardSampleRatePriorities); ++iStandardRate) { ma_uint32 standardRate = g_maStandardSampleRatePriorities[iStandardRate]; if (standardRate >= sampleRateMin && standardRate <= sampleRateMax) { return standardRate; @@ -4840,7 +5013,7 @@ ma_uint32 ma_get_best_sample_rate_within_range(ma_uint32 sampleRateMin, ma_uint3 } } - // Should never get here. + /* Should never get here. */ ma_assert(MA_FALSE); return 0; } @@ -4849,11 +5022,12 @@ ma_uint32 ma_get_closest_standard_sample_rate(ma_uint32 sampleRateIn) { ma_uint32 closestRate = 0; ma_uint32 closestDiff = 0xFFFFFFFF; + size_t iStandardRate; - for (size_t iStandardRate = 0; iStandardRate < ma_countof(g_maStandardSampleRatePriorities); ++iStandardRate) { + for (iStandardRate = 0; iStandardRate < ma_countof(g_maStandardSampleRatePriorities); ++iStandardRate) { ma_uint32 standardRate = g_maStandardSampleRatePriorities[iStandardRate]; - ma_uint32 diff; + if (sampleRateIn > standardRate) { diff = sampleRateIn - standardRate; } else { @@ -4861,7 +5035,7 @@ ma_uint32 ma_get_closest_standard_sample_rate(ma_uint32 sampleRateIn) } if (diff == 0) { - return standardRate; // The input sample rate is a standard rate. + return standardRate; /* The input sample rate is a standard rate. */ } if (closestDiff > diff) { @@ -4900,12 +5074,15 @@ ma_uint32 ma_get_default_buffer_size_in_milliseconds(ma_performance_profile perf ma_uint32 ma_get_default_buffer_size_in_frames(ma_performance_profile performanceProfile, ma_uint32 sampleRate) { - ma_uint32 bufferSizeInMilliseconds = ma_get_default_buffer_size_in_milliseconds(performanceProfile); + ma_uint32 bufferSizeInMilliseconds; + ma_uint32 sampleRateMS; + + bufferSizeInMilliseconds = ma_get_default_buffer_size_in_milliseconds(performanceProfile); if (bufferSizeInMilliseconds == 0) { bufferSizeInMilliseconds = 1; } - ma_uint32 sampleRateMS = (sampleRate/1000); + sampleRateMS = (sampleRate/1000); if (sampleRateMS == 0) { sampleRateMS = 1; } @@ -4933,24 +5110,28 @@ const char* ma_log_level_to_string(ma_uint32 logLevel) case MA_LOG_LEVEL_INFO: return "INFO"; case MA_LOG_LEVEL_WARNING: return "WARNING"; case MA_LOG_LEVEL_ERROR: return "ERROR"; - default: return "ERROR"; + default: return "ERROR"; } } -// Posts a log message. +/* Posts a log message. */ void ma_log(ma_context* pContext, ma_device* pDevice, ma_uint32 logLevel, const char* message) { - if (pContext == NULL) return; + if (pContext == NULL) { + return; + } #if defined(MA_LOG_LEVEL) if (logLevel <= MA_LOG_LEVEL) { + ma_log_proc onLog; + #if defined(MA_DEBUG_OUTPUT) if (logLevel <= MA_LOG_LEVEL) { printf("%s: %s\n", ma_log_level_to_string(logLevel), message); } #endif - ma_log_proc onLog = pContext->logCallback; + onLog = pContext->logCallback; if (onLog) { onLog(pContext, pDevice, logLevel, message); } @@ -4958,10 +5139,10 @@ void ma_log(ma_context* pContext, ma_device* pDevice, ma_uint32 logLevel, const #endif } -// Posts an error. Throw a breakpoint in here if you're needing to debug. The return value is always "resultCode". +/* Posts an error. Throw a breakpoint in here if you're needing to debug. The return value is always "resultCode". */ ma_result ma_context_post_error(ma_context* pContext, ma_device* pDevice, ma_uint32 logLevel, const char* message, ma_result resultCode) { - // Derive the context from the device if necessary. + /* Derive the context from the device if necessary. */ if (pContext == NULL) { if (pDevice != NULL) { pContext = pDevice->pContext; @@ -4979,22 +5160,23 @@ ma_result ma_post_error(ma_device* pDevice, ma_uint32 logLevel, const char* mess -// The callback for reading from the client -> DSP -> device. +/* The callback for reading from the client -> DSP -> device. */ ma_uint32 ma_device__on_read_from_client(ma_pcm_converter* pDSP, void* pFramesOut, ma_uint32 frameCount, void* pUserData) { - (void)pDSP; - ma_device* pDevice = (ma_device*)pUserData; + ma_device_callback_proc onData; + ma_assert(pDevice != NULL); ma_zero_pcm_frames(pFramesOut, frameCount, pDevice->playback.format, pDevice->playback.channels); - ma_device_callback_proc onData = pDevice->onData; + onData = pDevice->onData; if (onData) { onData(pDevice, pFramesOut, NULL, frameCount); return frameCount; } + (void)pDSP; return 0; } @@ -5002,18 +5184,21 @@ ma_uint32 ma_device__on_read_from_client(ma_pcm_converter* pDSP, void* pFramesOu ma_uint32 ma_device__pcm_converter__on_read_from_buffer_capture(ma_pcm_converter* pConverter, void* pFramesOut, ma_uint32 frameCount, void* pUserData) { ma_device* pDevice = (ma_device*)pUserData; + ma_uint32 framesToRead; + ma_uint32 bytesToRead; + ma_assert(pDevice != NULL); if (pDevice->capture._dspFrameCount == 0) { - return 0; // Nothing left. + return 0; /* Nothing left. */ } - ma_uint32 framesToRead = frameCount; + framesToRead = frameCount; if (framesToRead > pDevice->capture._dspFrameCount) { framesToRead = pDevice->capture._dspFrameCount; } - ma_uint32 bytesToRead = framesToRead * ma_get_bytes_per_frame(pConverter->formatConverterIn.config.formatIn, pConverter->channelRouter.config.channelsIn); + bytesToRead = framesToRead * ma_get_bytes_per_frame(pConverter->formatConverterIn.config.formatIn, pConverter->channelRouter.config.channelsIn); ma_copy_memory(pFramesOut, pDevice->capture._dspFrames, bytesToRead); pDevice->capture._dspFrameCount -= framesToRead; pDevice->capture._dspFrames += bytesToRead; @@ -5024,18 +5209,21 @@ ma_uint32 ma_device__pcm_converter__on_read_from_buffer_capture(ma_pcm_converter ma_uint32 ma_device__pcm_converter__on_read_from_buffer_playback(ma_pcm_converter* pConverter, void* pFramesOut, ma_uint32 frameCount, void* pUserData) { ma_device* pDevice = (ma_device*)pUserData; + ma_uint32 framesToRead; + ma_uint32 bytesToRead; + ma_assert(pDevice != NULL); if (pDevice->playback._dspFrameCount == 0) { - return 0; // Nothing left. + return 0; /* Nothing left. */ } - ma_uint32 framesToRead = frameCount; + framesToRead = frameCount; if (framesToRead > pDevice->playback._dspFrameCount) { framesToRead = pDevice->playback._dspFrameCount; } - ma_uint32 bytesToRead = framesToRead * ma_get_bytes_per_frame(pConverter->formatConverterIn.config.formatIn, pConverter->channelRouter.config.channelsIn); + bytesToRead = framesToRead * ma_get_bytes_per_frame(pConverter->formatConverterIn.config.formatIn, pConverter->channelRouter.config.channelsIn); ma_copy_memory(pFramesOut, pDevice->playback._dspFrames, bytesToRead); pDevice->playback._dspFrameCount -= framesToRead; pDevice->playback._dspFrames += bytesToRead; @@ -5045,14 +5233,16 @@ ma_uint32 ma_device__pcm_converter__on_read_from_buffer_playback(ma_pcm_converte -// A helper function for reading sample data from the client. +/* A helper function for reading sample data from the client. */ static MA_INLINE void ma_device__read_frames_from_client(ma_device* pDevice, ma_uint32 frameCount, void* pSamples) { + ma_device_callback_proc onData; + ma_assert(pDevice != NULL); ma_assert(frameCount > 0); ma_assert(pSamples != NULL); - ma_device_callback_proc onData = pDevice->onData; + onData = pDevice->onData; if (onData) { if (pDevice->playback.converter.isPassthrough) { ma_zero_pcm_frames(pSamples, frameCount, pDevice->playback.format, pDevice->playback.channels); @@ -5063,23 +5253,27 @@ static MA_INLINE void ma_device__read_frames_from_client(ma_device* pDevice, ma_ } } -// A helper for sending sample data to the client. +/* A helper for sending sample data to the client. */ static MA_INLINE void ma_device__send_frames_to_client(ma_device* pDevice, ma_uint32 frameCount, const void* pSamples) { + ma_device_callback_proc onData; + ma_assert(pDevice != NULL); ma_assert(frameCount > 0); ma_assert(pSamples != NULL); - ma_device_callback_proc onData = pDevice->onData; + onData = pDevice->onData; if (onData) { if (pDevice->capture.converter.isPassthrough) { onData(pDevice, NULL, pSamples, frameCount); } else { + ma_uint8 chunkBuffer[4096]; + ma_uint32 chunkFrameCount; + pDevice->capture._dspFrameCount = frameCount; pDevice->capture._dspFrames = (const ma_uint8*)pSamples; - ma_uint8 chunkBuffer[4096]; - ma_uint32 chunkFrameCount = sizeof(chunkBuffer) / ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels); + chunkFrameCount = sizeof(chunkBuffer) / ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels); for (;;) { ma_uint32 framesJustRead = (ma_uint32)ma_pcm_converter_read(&pDevice->capture.converter, chunkBuffer, chunkFrameCount); @@ -5099,12 +5293,12 @@ static MA_INLINE void ma_device__send_frames_to_client(ma_device* pDevice, ma_ui static MA_INLINE ma_result ma_device__handle_duplex_callback_capture(ma_device* pDevice, ma_uint32 frameCount, const void* pFramesInInternalFormat, ma_pcm_rb* pRB) { + ma_result result; + ma_assert(pDevice != NULL); ma_assert(frameCount > 0); ma_assert(pFramesInInternalFormat != NULL); ma_assert(pRB != NULL); - - ma_result result; pDevice->capture._dspFrameCount = (ma_uint32)frameCount; pDevice->capture._dspFrames = (const ma_uint8*)pFramesInInternalFormat; @@ -5114,6 +5308,7 @@ static MA_INLINE ma_result ma_device__handle_duplex_callback_capture(ma_device* ma_uint32 framesProcessed; ma_uint32 framesToProcess = 256; void* pFramesInExternalFormat; + result = ma_pcm_rb_acquire_write(pRB, &framesToProcess, &pFramesInExternalFormat); if (result != MA_SUCCESS) { ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "Failed to acquire capture PCM frames from ring buffer.", result); @@ -5145,6 +5340,12 @@ static MA_INLINE ma_result ma_device__handle_duplex_callback_capture(ma_device* static MA_INLINE ma_result ma_device__handle_duplex_callback_playback(ma_device* pDevice, ma_uint32 frameCount, void* pFramesInInternalFormat, ma_pcm_rb* pRB) { + ma_result result; + ma_uint8 playbackFramesInExternalFormat[4096]; + ma_uint8 silentInputFrames[4096]; + ma_uint32 totalFramesToReadFromClient; + ma_uint32 totalFramesReadFromClient; + ma_assert(pDevice != NULL); ma_assert(frameCount > 0); ma_assert(pFramesInInternalFormat != NULL); @@ -5154,24 +5355,25 @@ static MA_INLINE ma_result ma_device__handle_duplex_callback_playback(ma_device* Sitting in the ring buffer should be captured data from the capture callback in external format. If there's not enough data in there for the whole frameCount frames we just use silence instead for the input data. */ - ma_result result; - ma_uint8 playbackFramesInExternalFormat[4096]; - ma_uint8 silentInputFrames[4096]; ma_zero_memory(silentInputFrames, sizeof(silentInputFrames)); /* We need to calculate how many output frames are required to be read from the client to completely fill frameCount internal frames. */ - ma_uint32 totalFramesToReadFromClient = (ma_uint32)ma_calculate_frame_count_after_src(pDevice->sampleRate, pDevice->playback.internalSampleRate, frameCount); // ma_pcm_converter_get_required_input_frame_count(&pDevice->playback.converter, (ma_uint32)frameCount); - ma_uint32 totalFramesReadFromClient = 0; + totalFramesToReadFromClient = (ma_uint32)ma_calculate_frame_count_after_src(pDevice->sampleRate, pDevice->playback.internalSampleRate, frameCount); /* ma_pcm_converter_get_required_input_frame_count(&pDevice->playback.converter, (ma_uint32)frameCount); */ + totalFramesReadFromClient = 0; while (totalFramesReadFromClient < totalFramesToReadFromClient && ma_device_is_started(pDevice)) { - ma_uint32 framesRemainingFromClient = (totalFramesToReadFromClient - totalFramesReadFromClient); - ma_uint32 framesToProcessFromClient = sizeof(playbackFramesInExternalFormat) / ma_get_bytes_per_frame(pDevice->playback.format, pDevice->playback.channels); + ma_uint32 framesRemainingFromClient; + ma_uint32 framesToProcessFromClient; + ma_uint32 inputFrameCount; + void* pInputFrames; + + framesRemainingFromClient = (totalFramesToReadFromClient - totalFramesReadFromClient); + framesToProcessFromClient = sizeof(playbackFramesInExternalFormat) / ma_get_bytes_per_frame(pDevice->playback.format, pDevice->playback.channels); if (framesToProcessFromClient > framesRemainingFromClient) { framesToProcessFromClient = framesRemainingFromClient; } /* We need to grab captured samples before firing the callback. If there's not enough input samples we just pass silence. */ - ma_uint32 inputFrameCount = framesToProcessFromClient; - void* pInputFrames; + inputFrameCount = framesToProcessFromClient; result = ma_pcm_rb_acquire_read(pRB, &inputFrameCount, &pInputFrames); if (result == MA_SUCCESS) { if (inputFrameCount > 0) { @@ -5210,13 +5412,13 @@ static MA_INLINE ma_result ma_device__handle_duplex_callback_playback(ma_device* return MA_SUCCESS; } -// A helper for changing the state of the device. +/* A helper for changing the state of the device. */ static MA_INLINE void ma_device__set_state(ma_device* pDevice, ma_uint32 newState) { ma_atomic_exchange_32(&pDevice->state, newState); } -// A helper for getting the state of the device. +/* A helper for getting the state of the device. */ static MA_INLINE ma_uint32 ma_device__get_state(ma_device* pDevice) { return pDevice->state; @@ -5232,8 +5434,8 @@ static MA_INLINE ma_bool32 ma_device__is_async(ma_device* pDevice) #ifdef MA_WIN32 GUID MA_GUID_KSDATAFORMAT_SUBTYPE_PCM = {0x00000001, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}}; GUID MA_GUID_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT = {0x00000003, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}}; - //GUID MA_GUID_KSDATAFORMAT_SUBTYPE_ALAW = {0x00000006, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}}; - //GUID MA_GUID_KSDATAFORMAT_SUBTYPE_MULAW = {0x00000007, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}}; + /*GUID MA_GUID_KSDATAFORMAT_SUBTYPE_ALAW = {0x00000006, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}};*/ + /*GUID MA_GUID_KSDATAFORMAT_SUBTYPE_MULAW = {0x00000007, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}};*/ #endif @@ -5280,11 +5482,16 @@ ma_bool32 ma_context__try_get_device_name_by_id__enum_callback(ma_context* pCont return !pData->foundDevice; } -// Generic function for retrieving the name of a device by it's ID. -// -// This function simply enumerates every device and then retrieves the name of the first device that has the same ID. +/* +Generic function for retrieving the name of a device by it's ID. + +This function simply enumerates every device and then retrieves the name of the first device that has the same ID. +*/ ma_result ma_context__try_get_device_name_by_id(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, char* pName, size_t nameBufferSize) { + ma_result result; + ma_context__try_get_device_name_by_id__enum_callback_data data; + ma_assert(pContext != NULL); ma_assert(pName != NULL); @@ -5292,13 +5499,12 @@ ma_result ma_context__try_get_device_name_by_id(ma_context* pContext, ma_device_ return MA_NO_DEVICE; } - ma_context__try_get_device_name_by_id__enum_callback_data data; data.deviceType = deviceType; data.pDeviceID = pDeviceID; data.pName = pName; data.nameBufferSize = nameBufferSize; data.foundDevice = MA_FALSE; - ma_result result = ma_context_enumerate_devices(pContext, ma_context__try_get_device_name_by_id__enum_callback, &data); + result = ma_context_enumerate_devices(pContext, ma_context__try_get_device_name_by_id__enum_callback, &data); if (result != MA_SUCCESS) { return result; } @@ -5311,25 +5517,27 @@ ma_result ma_context__try_get_device_name_by_id(ma_context* pContext, ma_device_ } -ma_uint32 ma_get_format_priority_index(ma_format format) // Lower = better. +ma_uint32 ma_get_format_priority_index(ma_format format) /* Lower = better. */ { - for (ma_uint32 i = 0; i < ma_countof(g_maFormatPriorities); ++i) { + ma_uint32 i; + for (i = 0; i < ma_countof(g_maFormatPriorities); ++i) { if (g_maFormatPriorities[i] == format) { return i; } } - // Getting here means the format could not be found or is equal to ma_format_unknown. + /* Getting here means the format could not be found or is equal to ma_format_unknown. */ return (ma_uint32)-1; } void ma_device__post_init_setup(ma_device* pDevice, ma_device_type deviceType); -/////////////////////////////////////////////////////////////////////////////// -// -// Null Backend -// -/////////////////////////////////////////////////////////////////////////////// + +/******************************************************************************* + +Null Backend + +*******************************************************************************/ #ifdef MA_HAS_NULL #define MA_DEVICE_OP_NONE__NULL 0 @@ -5439,12 +5647,12 @@ ma_bool32 ma_context_is_device_id_equal__null(ma_context* pContext, const ma_dev ma_result ma_context_enumerate_devices__null(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData) { + ma_bool32 cbResult = MA_TRUE; + ma_assert(pContext != NULL); ma_assert(callback != NULL); - ma_bool32 cbResult = MA_TRUE; - - // Playback. + /* Playback. */ if (cbResult) { ma_device_info deviceInfo; ma_zero_object(&deviceInfo); @@ -5452,7 +5660,7 @@ ma_result ma_context_enumerate_devices__null(ma_context* pContext, ma_enum_devic cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData); } - // Capture. + /* Capture. */ if (cbResult) { ma_device_info deviceInfo; ma_zero_object(&deviceInfo); @@ -5465,26 +5673,25 @@ ma_result ma_context_enumerate_devices__null(ma_context* pContext, ma_enum_devic ma_result ma_context_get_device_info__null(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_share_mode shareMode, ma_device_info* pDeviceInfo) { - ma_assert(pContext != NULL); + ma_uint32 iFormat; - (void)pContext; - (void)shareMode; + ma_assert(pContext != NULL); if (pDeviceID != NULL && pDeviceID->nullbackend != 0) { - return MA_NO_DEVICE; // Don't know the device. + return MA_NO_DEVICE; /* Don't know the device. */ } - // Name / Description + /* Name / Description */ if (deviceType == ma_device_type_playback) { ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), "NULL Playback Device", (size_t)-1); } else { ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), "NULL Capture Device", (size_t)-1); } - // Support everything on the null backend. - pDeviceInfo->formatCount = ma_format_count - 1; // Minus one because we don't want to include ma_format_unknown. - for (ma_uint32 iFormat = 0; iFormat < pDeviceInfo->formatCount; ++iFormat) { - pDeviceInfo->formats[iFormat] = (ma_format)(iFormat + 1); // +1 to skip over ma_format_unknown. + /* Support everything on the null backend. */ + pDeviceInfo->formatCount = ma_format_count - 1; /* Minus one because we don't want to include ma_format_unknown. */ + for (iFormat = 0; iFormat < pDeviceInfo->formatCount; ++iFormat) { + pDeviceInfo->formats[iFormat] = (ma_format)(iFormat + 1); /* +1 to skip over ma_format_unknown. */ } pDeviceInfo->minChannels = 1; @@ -5492,6 +5699,8 @@ ma_result ma_context_get_device_info__null(ma_context* pContext, ma_device_type pDeviceInfo->minSampleRate = MA_SAMPLE_RATE_8000; pDeviceInfo->maxSampleRate = MA_SAMPLE_RATE_384000; + (void)pContext; + (void)shareMode; return MA_SUCCESS; } @@ -5510,16 +5719,14 @@ void ma_device_uninit__null(ma_device* pDevice) ma_result ma_device_init__null(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice) { - (void)pContext; - (void)pConfig; - ma_result result; + ma_uint32 bufferSizeInFrames; ma_assert(pDevice != NULL); ma_zero_object(&pDevice->null_device); - ma_uint32 bufferSizeInFrames = pConfig->bufferSizeInFrames; + bufferSizeInFrames = pConfig->bufferSizeInFrames; if (bufferSizeInFrames == 0) { bufferSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(pConfig->bufferSizeInMilliseconds, pConfig->sampleRate); } @@ -5594,6 +5801,8 @@ ma_result ma_device_write__null(ma_device* pDevice, const void* pPCMFrames, ma_u /* Keep going until everything has been read. */ totalPCMFramesProcessed = 0; while (totalPCMFramesProcessed < frameCount) { + ma_uint64 targetFrame; + /* If there are any frames remaining in the current period, consume those first. */ if (pDevice->null_device.currentPeriodFramesRemainingPlayback > 0) { ma_uint32 framesRemaining = (frameCount - totalPCMFramesProcessed); @@ -5628,14 +5837,16 @@ ma_result ma_device_write__null(ma_device* pDevice, const void* pPCMFrames, ma_u } /* Getting here means we've still got more frames to consume, we but need to wait for it to become available. */ - ma_uint64 targetFrame = pDevice->null_device.lastProcessedFramePlayback; + targetFrame = pDevice->null_device.lastProcessedFramePlayback; for (;;) { + ma_uint64 currentFrame; + /* Stop waiting if the device has been stopped. */ if (!pDevice->null_device.isStarted) { break; } - ma_uint64 currentFrame = ma_device_get_total_run_time_in_frames__null(pDevice); + currentFrame = ma_device_get_total_run_time_in_frames__null(pDevice); if (currentFrame >= targetFrame) { break; } @@ -5667,6 +5878,8 @@ ma_result ma_device_read__null(ma_device* pDevice, void* pPCMFrames, ma_uint32 f /* Keep going until everything has been read. */ totalPCMFramesProcessed = 0; while (totalPCMFramesProcessed < frameCount) { + ma_uint64 targetFrame; + /* If there are any frames remaining in the current period, consume those first. */ if (pDevice->null_device.currentPeriodFramesRemainingCapture > 0) { ma_uint32 bpf = ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels); @@ -5695,14 +5908,16 @@ ma_result ma_device_read__null(ma_device* pDevice, void* pPCMFrames, ma_uint32 f } /* Getting here means we've still got more frames to consume, we but need to wait for it to become available. */ - ma_uint64 targetFrame = pDevice->null_device.lastProcessedFrameCapture + (pDevice->capture.internalBufferSizeInFrames / pDevice->capture.internalPeriods); + targetFrame = pDevice->null_device.lastProcessedFrameCapture + (pDevice->capture.internalBufferSizeInFrames / pDevice->capture.internalPeriods); for (;;) { + ma_uint64 currentFrame; + /* Stop waiting if the device has been stopped. */ if (!pDevice->null_device.isStarted) { break; } - ma_uint64 currentFrame = ma_device_get_total_run_time_in_frames__null(pDevice); + currentFrame = ma_device_get_total_run_time_in_frames__null(pDevice); if (currentFrame >= targetFrame) { break; } @@ -5750,11 +5965,11 @@ ma_result ma_context_init__null(const ma_context_config* pConfig, ma_context* pC #endif -/////////////////////////////////////////////////////////////////////////////// -// -// WIN32 COMMON -// -/////////////////////////////////////////////////////////////////////////////// +/******************************************************************************* + +WIN32 COMMON + +*******************************************************************************/ #if defined(MA_WIN32) #if defined(MA_WIN32_DESKTOP) #define ma_CoInitializeEx(pContext, pvReserved, dwCoInit) ((MA_PFN_CoInitializeEx)pContext->win32.CoInitializeEx)(pvReserved, dwCoInit) @@ -5810,8 +6025,10 @@ typedef size_t DWORD_PTR; #define SPEAKER_TOP_BACK_RIGHT 0x20000 #endif -// The SDK that comes with old versions of MSVC (VC6, for example) does not appear to define WAVEFORMATEXTENSIBLE. We -// define our own implementation in this case. +/* +The SDK that comes with old versions of MSVC (VC6, for example) does not appear to define WAVEFORMATEXTENSIBLE. We +define our own implementation in this case. +*/ #if (defined(_MSC_VER) && !defined(_WAVEFORMATEXTENSIBLE_)) || defined(__DMC__) typedef struct { @@ -5837,7 +6054,7 @@ typedef struct GUID MA_GUID_NULL = {0x00000000, 0x0000, 0x0000, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}; -// Converts an individual Win32-style channel identifier (SPEAKER_FRONT_LEFT, etc.) to miniaudio. +/* Converts an individual Win32-style channel identifier (SPEAKER_FRONT_LEFT, etc.) to miniaudio. */ ma_uint8 ma_channel_id_to_ma__win32(DWORD id) { switch (id) @@ -5864,7 +6081,7 @@ ma_uint8 ma_channel_id_to_ma__win32(DWORD id) } } -// Converts an individual miniaudio channel identifier (MA_CHANNEL_FRONT_LEFT, etc.) to Win32-style. +/* Converts an individual miniaudio channel identifier (MA_CHANNEL_FRONT_LEFT, etc.) to Win32-style. */ DWORD ma_channel_id_to_win32(DWORD id) { switch (id) @@ -5892,18 +6109,20 @@ DWORD ma_channel_id_to_win32(DWORD id) } } -// Converts a channel mapping to a Win32-style channel mask. +/* Converts a channel mapping to a Win32-style channel mask. */ DWORD ma_channel_map_to_channel_mask__win32(const ma_channel channelMap[MA_MAX_CHANNELS], ma_uint32 channels) { DWORD dwChannelMask = 0; - for (ma_uint32 iChannel = 0; iChannel < channels; ++iChannel) { + ma_uint32 iChannel; + + for (iChannel = 0; iChannel < channels; ++iChannel) { dwChannelMask |= ma_channel_id_to_win32(channelMap[iChannel]); } return dwChannelMask; } -// Converts a Win32-style channel mask to a miniaudio channel map. +/* Converts a Win32-style channel mask to a miniaudio channel map. */ void ma_channel_mask_to_channel_map__win32(DWORD dwChannelMask, ma_uint32 channels, ma_channel channelMap[MA_MAX_CHANNELS]) { if (channels == 1 && dwChannelMask == 0) { @@ -5915,12 +6134,14 @@ void ma_channel_mask_to_channel_map__win32(DWORD dwChannelMask, ma_uint32 channe if (channels == 1 && (dwChannelMask & SPEAKER_FRONT_CENTER) != 0) { channelMap[0] = MA_CHANNEL_MONO; } else { - // Just iterate over each bit. + /* Just iterate over each bit. */ ma_uint32 iChannel = 0; - for (ma_uint32 iBit = 0; iBit < 32; ++iBit) { + ma_uint32 iBit; + + for (iBit = 0; iBit < 32; ++iBit) { DWORD bitValue = (dwChannelMask & (1UL << iBit)); if (bitValue != 0) { - // The bit is set. + /* The bit is set. */ channelMap[iChannel] = ma_channel_id_to_ma__win32(bitValue); iChannel += 1; } @@ -5950,7 +6171,7 @@ ma_format ma_format_from_WAVEFORMATEX(const WAVEFORMATEX* pWF) } if (pWFEX->Samples.wValidBitsPerSample == 24) { if (pWFEX->Format.wBitsPerSample == 32) { - //return ma_format_s24_32; + /*return ma_format_s24_32;*/ } if (pWFEX->Format.wBitsPerSample == 24) { return ma_format_s24; @@ -5967,9 +6188,11 @@ ma_format ma_format_from_WAVEFORMATEX(const WAVEFORMATEX* pWF) if (pWFEX->Samples.wValidBitsPerSample == 32) { return ma_format_f32; } - //if (pWFEX->Samples.wValidBitsPerSample == 64) { - // return ma_format_f64; - //} + /* + if (pWFEX->Samples.wValidBitsPerSample == 64) { + return ma_format_f64; + } + */ } } else { if (pWF->wFormatTag == WAVE_FORMAT_PCM) { @@ -5991,7 +6214,7 @@ ma_format ma_format_from_WAVEFORMATEX(const WAVEFORMATEX* pWF) return ma_format_f32; } if (pWF->wBitsPerSample == 64) { - //return ma_format_f64; + /*return ma_format_f64;*/ } } } @@ -6001,30 +6224,31 @@ ma_format ma_format_from_WAVEFORMATEX(const WAVEFORMATEX* pWF) #endif -/////////////////////////////////////////////////////////////////////////////// -// -// WASAPI Backend -// -/////////////////////////////////////////////////////////////////////////////// +/******************************************************************************* + +WASAPI Backend + +*******************************************************************************/ #ifdef MA_HAS_WASAPI -//#if defined(_MSC_VER) -// #pragma warning(push) -// #pragma warning(disable:4091) // 'typedef ': ignored on left of '' when no variable is declared -//#endif -//#include -//#include -//#if defined(_MSC_VER) -// #pragma warning(pop) -//#endif - - -// Some compilers don't define VerifyVersionInfoW. Need to write this ourselves. -#if defined(__DMC__) -#define _WIN32_WINNT_VISTA 0x0600 -#define VER_MINORVERSION 0x01 -#define VER_MAJORVERSION 0x02 -#define VER_SERVICEPACKMAJOR 0x20 -#define VER_GREATER_EQUAL 0x03 +#if 0 +#if defined(_MSC_VER) + #pragma warning(push) + #pragma warning(disable:4091) /* 'typedef ': ignored on left of '' when no variable is declared */ +#endif +#include +#include +#if defined(_MSC_VER) + #pragma warning(pop) +#endif +#endif /* 0 */ + + +/* Some compilers don't define VerifyVersionInfoW. Need to write this ourselves. */ +#define MA_WIN32_WINNT_VISTA 0x0600 +#define MA_VER_MINORVERSION 0x01 +#define MA_VER_MAJORVERSION 0x02 +#define MA_VER_SERVICEPACKMAJOR 0x20 +#define MA_VER_GREATER_EQUAL 0x03 typedef struct { DWORD dwOSVersionInfoSize; @@ -6040,11 +6264,8 @@ typedef struct { BYTE wReserved; } ma_OSVERSIONINFOEXW; -BOOL WINAPI VerifyVersionInfoW(ma_OSVERSIONINFOEXW* lpVersionInfo, DWORD dwTypeMask, DWORDLONG dwlConditionMask); -ULONGLONG WINAPI VerSetConditionMask(ULONGLONG dwlConditionMask, DWORD dwTypeBitMask, BYTE dwConditionMask); -#else -typedef OSVERSIONINFOEXW ma_OSVERSIONINFOEXW; -#endif +typedef BOOL (WINAPI * ma_PFNVerifyVersionInfoW) (ma_OSVERSIONINFOEXW* lpVersionInfo, DWORD dwTypeMask, DWORDLONG dwlConditionMask); +typedef ULONGLONG (WINAPI * ma_PFNVerSetConditionMask)(ULONGLONG dwlConditionMask, DWORD dwTypeBitMask, BYTE dwConditionMask); #ifndef PROPERTYKEY_DEFINED @@ -6056,7 +6277,7 @@ typedef struct } PROPERTYKEY; #endif -// Some compilers don't define PropVariantInit(). We just do this ourselves since it's just a memset(). +/* Some compilers don't define PropVariantInit(). We just do this ourselves since it's just a memset(). */ static MA_INLINE void ma_PropVariantInit(PROPVARIANT* pProp) { ma_zero_object(pProp); @@ -6066,23 +6287,23 @@ static MA_INLINE void ma_PropVariantInit(PROPVARIANT* pProp) const PROPERTYKEY MA_PKEY_Device_FriendlyName = {{0xA45C254E, 0xDF1C, 0x4EFD, {0x80, 0x20, 0x67, 0xD1, 0x46, 0xA8, 0x50, 0xE0}}, 14}; const PROPERTYKEY MA_PKEY_AudioEngine_DeviceFormat = {{0xF19F064D, 0x82C, 0x4E27, {0xBC, 0x73, 0x68, 0x82, 0xA1, 0xBB, 0x8E, 0x4C}}, 0}; -const IID MA_IID_IUnknown = {0x00000000, 0x0000, 0x0000, {0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}}; // 00000000-0000-0000-C000-000000000046 -const IID MA_IID_IAgileObject = {0x94EA2B94, 0xE9CC, 0x49E0, {0xC0, 0xFF, 0xEE, 0x64, 0xCA, 0x8F, 0x5B, 0x90}}; // 94EA2B94-E9CC-49E0-C0FF-EE64CA8F5B90 +const IID MA_IID_IUnknown = {0x00000000, 0x0000, 0x0000, {0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}}; /* 00000000-0000-0000-C000-000000000046 */ +const IID MA_IID_IAgileObject = {0x94EA2B94, 0xE9CC, 0x49E0, {0xC0, 0xFF, 0xEE, 0x64, 0xCA, 0x8F, 0x5B, 0x90}}; /* 94EA2B94-E9CC-49E0-C0FF-EE64CA8F5B90 */ -const IID MA_IID_IAudioClient = {0x1CB9AD4C, 0xDBFA, 0x4C32, {0xB1, 0x78, 0xC2, 0xF5, 0x68, 0xA7, 0x03, 0xB2}}; // 1CB9AD4C-DBFA-4C32-B178-C2F568A703B2 = __uuidof(IAudioClient) -const IID MA_IID_IAudioClient2 = {0x726778CD, 0xF60A, 0x4EDA, {0x82, 0xDE, 0xE4, 0x76, 0x10, 0xCD, 0x78, 0xAA}}; // 726778CD-F60A-4EDA-82DE-E47610CD78AA = __uuidof(IAudioClient2) -const IID MA_IID_IAudioClient3 = {0x7ED4EE07, 0x8E67, 0x4CD4, {0x8C, 0x1A, 0x2B, 0x7A, 0x59, 0x87, 0xAD, 0x42}}; // 7ED4EE07-8E67-4CD4-8C1A-2B7A5987AD42 = __uuidof(IAudioClient3) -const IID MA_IID_IAudioRenderClient = {0xF294ACFC, 0x3146, 0x4483, {0xA7, 0xBF, 0xAD, 0xDC, 0xA7, 0xC2, 0x60, 0xE2}}; // F294ACFC-3146-4483-A7BF-ADDCA7C260E2 = __uuidof(IAudioRenderClient) -const IID MA_IID_IAudioCaptureClient = {0xC8ADBD64, 0xE71E, 0x48A0, {0xA4, 0xDE, 0x18, 0x5C, 0x39, 0x5C, 0xD3, 0x17}}; // C8ADBD64-E71E-48A0-A4DE-185C395CD317 = __uuidof(IAudioCaptureClient) -const IID MA_IID_IMMNotificationClient = {0x7991EEC9, 0x7E89, 0x4D85, {0x83, 0x90, 0x6C, 0x70, 0x3C, 0xEC, 0x60, 0xC0}}; // 7991EEC9-7E89-4D85-8390-6C703CEC60C0 = __uuidof(IMMNotificationClient) +const IID MA_IID_IAudioClient = {0x1CB9AD4C, 0xDBFA, 0x4C32, {0xB1, 0x78, 0xC2, 0xF5, 0x68, 0xA7, 0x03, 0xB2}}; /* 1CB9AD4C-DBFA-4C32-B178-C2F568A703B2 = __uuidof(IAudioClient) */ +const IID MA_IID_IAudioClient2 = {0x726778CD, 0xF60A, 0x4EDA, {0x82, 0xDE, 0xE4, 0x76, 0x10, 0xCD, 0x78, 0xAA}}; /* 726778CD-F60A-4EDA-82DE-E47610CD78AA = __uuidof(IAudioClient2) */ +const IID MA_IID_IAudioClient3 = {0x7ED4EE07, 0x8E67, 0x4CD4, {0x8C, 0x1A, 0x2B, 0x7A, 0x59, 0x87, 0xAD, 0x42}}; /* 7ED4EE07-8E67-4CD4-8C1A-2B7A5987AD42 = __uuidof(IAudioClient3) */ +const IID MA_IID_IAudioRenderClient = {0xF294ACFC, 0x3146, 0x4483, {0xA7, 0xBF, 0xAD, 0xDC, 0xA7, 0xC2, 0x60, 0xE2}}; /* F294ACFC-3146-4483-A7BF-ADDCA7C260E2 = __uuidof(IAudioRenderClient) */ +const IID MA_IID_IAudioCaptureClient = {0xC8ADBD64, 0xE71E, 0x48A0, {0xA4, 0xDE, 0x18, 0x5C, 0x39, 0x5C, 0xD3, 0x17}}; /* C8ADBD64-E71E-48A0-A4DE-185C395CD317 = __uuidof(IAudioCaptureClient) */ +const IID MA_IID_IMMNotificationClient = {0x7991EEC9, 0x7E89, 0x4D85, {0x83, 0x90, 0x6C, 0x70, 0x3C, 0xEC, 0x60, 0xC0}}; /* 7991EEC9-7E89-4D85-8390-6C703CEC60C0 = __uuidof(IMMNotificationClient) */ #ifndef MA_WIN32_DESKTOP -const IID MA_IID_DEVINTERFACE_AUDIO_RENDER = {0xE6327CAD, 0xDCEC, 0x4949, {0xAE, 0x8A, 0x99, 0x1E, 0x97, 0x6A, 0x79, 0xD2}}; // E6327CAD-DCEC-4949-AE8A-991E976A79D2 -const IID MA_IID_DEVINTERFACE_AUDIO_CAPTURE = {0x2EEF81BE, 0x33FA, 0x4800, {0x96, 0x70, 0x1C, 0xD4, 0x74, 0x97, 0x2C, 0x3F}}; // 2EEF81BE-33FA-4800-9670-1CD474972C3F -const IID MA_IID_IActivateAudioInterfaceCompletionHandler = {0x41D949AB, 0x9862, 0x444A, {0x80, 0xF6, 0xC2, 0x61, 0x33, 0x4D, 0xA5, 0xEB}}; // 41D949AB-9862-444A-80F6-C261334DA5EB +const IID MA_IID_DEVINTERFACE_AUDIO_RENDER = {0xE6327CAD, 0xDCEC, 0x4949, {0xAE, 0x8A, 0x99, 0x1E, 0x97, 0x6A, 0x79, 0xD2}}; /* E6327CAD-DCEC-4949-AE8A-991E976A79D2 */ +const IID MA_IID_DEVINTERFACE_AUDIO_CAPTURE = {0x2EEF81BE, 0x33FA, 0x4800, {0x96, 0x70, 0x1C, 0xD4, 0x74, 0x97, 0x2C, 0x3F}}; /* 2EEF81BE-33FA-4800-9670-1CD474972C3F */ +const IID MA_IID_IActivateAudioInterfaceCompletionHandler = {0x41D949AB, 0x9862, 0x444A, {0x80, 0xF6, 0xC2, 0x61, 0x33, 0x4D, 0xA5, 0xEB}}; /* 41D949AB-9862-444A-80F6-C261334DA5EB */ #endif -const IID MA_CLSID_MMDeviceEnumerator_Instance = {0xBCDE0395, 0xE52F, 0x467C, {0x8E, 0x3D, 0xC4, 0x57, 0x92, 0x91, 0x69, 0x2E}}; // BCDE0395-E52F-467C-8E3D-C4579291692E = __uuidof(MMDeviceEnumerator) -const IID MA_IID_IMMDeviceEnumerator_Instance = {0xA95664D2, 0x9614, 0x4F35, {0xA7, 0x46, 0xDE, 0x8D, 0xB6, 0x36, 0x17, 0xE6}}; // A95664D2-9614-4F35-A746-DE8DB63617E6 = __uuidof(IMMDeviceEnumerator) +const IID MA_CLSID_MMDeviceEnumerator_Instance = {0xBCDE0395, 0xE52F, 0x467C, {0x8E, 0x3D, 0xC4, 0x57, 0x92, 0x91, 0x69, 0x2E}}; /* BCDE0395-E52F-467C-8E3D-C4579291692E = __uuidof(MMDeviceEnumerator) */ +const IID MA_IID_IMMDeviceEnumerator_Instance = {0xA95664D2, 0x9614, 0x4F35, {0xA7, 0x46, 0xDE, 0x8D, 0xB6, 0x36, 0x17, 0xE6}}; /* A95664D2-9614-4F35-A746-DE8DB63617E6 = __uuidof(IMMDeviceEnumerator) */ #ifdef __cplusplus #define MA_CLSID_MMDeviceEnumerator MA_CLSID_MMDeviceEnumerator_Instance #define MA_IID_IMMDeviceEnumerator MA_IID_IMMDeviceEnumerator_Instance @@ -6125,7 +6346,7 @@ typedef ma_int64 MA_REFERENCE_TIME; #define MA_AUDCLNT_SESSIONFLAGS_DISPLAY_HIDE 0x20000000 #define MA_AUDCLNT_SESSIONFLAGS_DISPLAY_HIDEWHENEXPIRED 0x40000000 -// We only care about a few error codes. +/* We only care about a few error codes. */ #define MA_AUDCLNT_E_INVALID_DEVICE_PERIOD (-2004287456) #define MA_AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED (-2004287463) #define MA_AUDCLNT_S_BUFFER_EMPTY (143196161) @@ -6153,7 +6374,7 @@ typedef enum typedef enum { - MA_AudioCategory_Other = 0, // <-- miniaudio is only caring about Other. + MA_AudioCategory_Other = 0 /* <-- miniaudio is only caring about Other. */ } MA_AUDIO_STREAM_CATEGORY; typedef struct @@ -6163,10 +6384,10 @@ typedef struct MA_AUDIO_STREAM_CATEGORY eCategory; } ma_AudioClientProperties; -// IUnknown +/* IUnknown */ typedef struct { - // IUnknown + /* IUnknown */ HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IUnknown* pThis, const IID* const riid, void** ppObject); ULONG (STDMETHODCALLTYPE * AddRef) (ma_IUnknown* pThis); ULONG (STDMETHODCALLTYPE * Release) (ma_IUnknown* pThis); @@ -6180,15 +6401,15 @@ ULONG ma_IUnknown_AddRef(ma_IUnknown* pThis) ULONG ma_IUnknown_Release(ma_IUnknown* pThis) { return pThis->lpVtbl->Release(pThis); } #ifdef MA_WIN32_DESKTOP - // IMMNotificationClient + /* IMMNotificationClient */ typedef struct { - // IUnknown + /* IUnknown */ HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IMMNotificationClient* pThis, const IID* const riid, void** ppObject); ULONG (STDMETHODCALLTYPE * AddRef) (ma_IMMNotificationClient* pThis); ULONG (STDMETHODCALLTYPE * Release) (ma_IMMNotificationClient* pThis); - // IMMNotificationClient + /* IMMNotificationClient */ HRESULT (STDMETHODCALLTYPE * OnDeviceStateChanged) (ma_IMMNotificationClient* pThis, LPCWSTR pDeviceID, DWORD dwNewState); HRESULT (STDMETHODCALLTYPE * OnDeviceAdded) (ma_IMMNotificationClient* pThis, LPCWSTR pDeviceID); HRESULT (STDMETHODCALLTYPE * OnDeviceRemoved) (ma_IMMNotificationClient* pThis, LPCWSTR pDeviceID); @@ -6196,15 +6417,15 @@ ULONG ma_IUnknown_Release(ma_IUnknown* pThis) HRESULT (STDMETHODCALLTYPE * OnPropertyValueChanged)(ma_IMMNotificationClient* pThis, LPCWSTR pDeviceID, const PROPERTYKEY key); } ma_IMMNotificationClientVtbl; - // IMMDeviceEnumerator + /* IMMDeviceEnumerator */ typedef struct { - // IUnknown + /* IUnknown */ HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IMMDeviceEnumerator* pThis, const IID* const riid, void** ppObject); ULONG (STDMETHODCALLTYPE * AddRef) (ma_IMMDeviceEnumerator* pThis); ULONG (STDMETHODCALLTYPE * Release) (ma_IMMDeviceEnumerator* pThis); - // IMMDeviceEnumerator + /* IMMDeviceEnumerator */ HRESULT (STDMETHODCALLTYPE * EnumAudioEndpoints) (ma_IMMDeviceEnumerator* pThis, ma_EDataFlow dataFlow, DWORD dwStateMask, ma_IMMDeviceCollection** ppDevices); HRESULT (STDMETHODCALLTYPE * GetDefaultAudioEndpoint) (ma_IMMDeviceEnumerator* pThis, ma_EDataFlow dataFlow, ma_ERole role, ma_IMMDevice** ppEndpoint); HRESULT (STDMETHODCALLTYPE * GetDevice) (ma_IMMDeviceEnumerator* pThis, LPCWSTR pID, ma_IMMDevice** ppDevice); @@ -6225,15 +6446,15 @@ ULONG ma_IUnknown_Release(ma_IUnknown* pThis) HRESULT ma_IMMDeviceEnumerator_UnregisterEndpointNotificationCallback(ma_IMMDeviceEnumerator* pThis, ma_IMMNotificationClient* pClient) { return pThis->lpVtbl->UnregisterEndpointNotificationCallback(pThis, pClient); } - // IMMDeviceCollection + /* IMMDeviceCollection */ typedef struct { - // IUnknown + /* IUnknown */ HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IMMDeviceCollection* pThis, const IID* const riid, void** ppObject); ULONG (STDMETHODCALLTYPE * AddRef) (ma_IMMDeviceCollection* pThis); ULONG (STDMETHODCALLTYPE * Release) (ma_IMMDeviceCollection* pThis); - // IMMDeviceCollection + /* IMMDeviceCollection */ HRESULT (STDMETHODCALLTYPE * GetCount)(ma_IMMDeviceCollection* pThis, UINT* pDevices); HRESULT (STDMETHODCALLTYPE * Item) (ma_IMMDeviceCollection* pThis, UINT nDevice, ma_IMMDevice** ppDevice); } ma_IMMDeviceCollectionVtbl; @@ -6248,15 +6469,15 @@ ULONG ma_IUnknown_Release(ma_IUnknown* pThis) HRESULT ma_IMMDeviceCollection_Item(ma_IMMDeviceCollection* pThis, UINT nDevice, ma_IMMDevice** ppDevice) { return pThis->lpVtbl->Item(pThis, nDevice, ppDevice); } - // IMMDevice + /* IMMDevice */ typedef struct { - // IUnknown + /* IUnknown */ HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IMMDevice* pThis, const IID* const riid, void** ppObject); ULONG (STDMETHODCALLTYPE * AddRef) (ma_IMMDevice* pThis); ULONG (STDMETHODCALLTYPE * Release) (ma_IMMDevice* pThis); - // IMMDevice + /* IMMDevice */ HRESULT (STDMETHODCALLTYPE * Activate) (ma_IMMDevice* pThis, const IID* const iid, DWORD dwClsCtx, PROPVARIANT* pActivationParams, void** ppInterface); HRESULT (STDMETHODCALLTYPE * OpenPropertyStore)(ma_IMMDevice* pThis, DWORD stgmAccess, ma_IPropertyStore** ppProperties); HRESULT (STDMETHODCALLTYPE * GetId) (ma_IMMDevice* pThis, LPWSTR *pID); @@ -6274,15 +6495,15 @@ ULONG ma_IUnknown_Release(ma_IUnknown* pThis) HRESULT ma_IMMDevice_GetId(ma_IMMDevice* pThis, LPWSTR *pID) { return pThis->lpVtbl->GetId(pThis, pID); } HRESULT ma_IMMDevice_GetState(ma_IMMDevice* pThis, DWORD *pState) { return pThis->lpVtbl->GetState(pThis, pState); } #else - // IActivateAudioInterfaceAsyncOperation + /* IActivateAudioInterfaceAsyncOperation */ typedef struct { - // IUnknown + /* IUnknown */ HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IActivateAudioInterfaceAsyncOperation* pThis, const IID* const riid, void** ppObject); ULONG (STDMETHODCALLTYPE * AddRef) (ma_IActivateAudioInterfaceAsyncOperation* pThis); ULONG (STDMETHODCALLTYPE * Release) (ma_IActivateAudioInterfaceAsyncOperation* pThis); - // IActivateAudioInterfaceAsyncOperation + /* IActivateAudioInterfaceAsyncOperation */ HRESULT (STDMETHODCALLTYPE * GetActivateResult)(ma_IActivateAudioInterfaceAsyncOperation* pThis, HRESULT *pActivateResult, ma_IUnknown** ppActivatedInterface); } ma_IActivateAudioInterfaceAsyncOperationVtbl; struct ma_IActivateAudioInterfaceAsyncOperation @@ -6295,15 +6516,15 @@ ULONG ma_IUnknown_Release(ma_IUnknown* pThis) HRESULT ma_IActivateAudioInterfaceAsyncOperation_GetActivateResult(ma_IActivateAudioInterfaceAsyncOperation* pThis, HRESULT *pActivateResult, ma_IUnknown** ppActivatedInterface) { return pThis->lpVtbl->GetActivateResult(pThis, pActivateResult, ppActivatedInterface); } #endif -// IPropertyStore +/* IPropertyStore */ typedef struct { - // IUnknown + /* IUnknown */ HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IPropertyStore* pThis, const IID* const riid, void** ppObject); ULONG (STDMETHODCALLTYPE * AddRef) (ma_IPropertyStore* pThis); ULONG (STDMETHODCALLTYPE * Release) (ma_IPropertyStore* pThis); - // IPropertyStore + /* IPropertyStore */ HRESULT (STDMETHODCALLTYPE * GetCount)(ma_IPropertyStore* pThis, DWORD* pPropCount); HRESULT (STDMETHODCALLTYPE * GetAt) (ma_IPropertyStore* pThis, DWORD propIndex, PROPERTYKEY* pPropKey); HRESULT (STDMETHODCALLTYPE * GetValue)(ma_IPropertyStore* pThis, const PROPERTYKEY* const pKey, PROPVARIANT* pPropVar); @@ -6324,15 +6545,15 @@ HRESULT ma_IPropertyStore_SetValue(ma_IPropertyStore* pThis, const PROPERTYKEY* HRESULT ma_IPropertyStore_Commit(ma_IPropertyStore* pThis) { return pThis->lpVtbl->Commit(pThis); } -// IAudioClient +/* IAudioClient */ typedef struct { - // IUnknown + /* IUnknown */ HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IAudioClient* pThis, const IID* const riid, void** ppObject); ULONG (STDMETHODCALLTYPE * AddRef) (ma_IAudioClient* pThis); ULONG (STDMETHODCALLTYPE * Release) (ma_IAudioClient* pThis); - // IAudioClient + /* IAudioClient */ HRESULT (STDMETHODCALLTYPE * Initialize) (ma_IAudioClient* pThis, MA_AUDCLNT_SHAREMODE shareMode, DWORD streamFlags, MA_REFERENCE_TIME bufferDuration, MA_REFERENCE_TIME periodicity, const WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid); HRESULT (STDMETHODCALLTYPE * GetBufferSize) (ma_IAudioClient* pThis, ma_uint32* pNumBufferFrames); HRESULT (STDMETHODCALLTYPE * GetStreamLatency) (ma_IAudioClient* pThis, MA_REFERENCE_TIME* pLatency); @@ -6366,15 +6587,15 @@ HRESULT ma_IAudioClient_Reset(ma_IAudioClient* pThis) HRESULT ma_IAudioClient_SetEventHandle(ma_IAudioClient* pThis, HANDLE eventHandle) { return pThis->lpVtbl->SetEventHandle(pThis, eventHandle); } HRESULT ma_IAudioClient_GetService(ma_IAudioClient* pThis, const IID* const riid, void** pp) { return pThis->lpVtbl->GetService(pThis, riid, pp); } -// IAudioClient2 +/* IAudioClient2 */ typedef struct { - // IUnknown + /* IUnknown */ HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IAudioClient2* pThis, const IID* const riid, void** ppObject); ULONG (STDMETHODCALLTYPE * AddRef) (ma_IAudioClient2* pThis); ULONG (STDMETHODCALLTYPE * Release) (ma_IAudioClient2* pThis); - // IAudioClient + /* IAudioClient */ HRESULT (STDMETHODCALLTYPE * Initialize) (ma_IAudioClient2* pThis, MA_AUDCLNT_SHAREMODE shareMode, DWORD streamFlags, MA_REFERENCE_TIME bufferDuration, MA_REFERENCE_TIME periodicity, const WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid); HRESULT (STDMETHODCALLTYPE * GetBufferSize) (ma_IAudioClient2* pThis, ma_uint32* pNumBufferFrames); HRESULT (STDMETHODCALLTYPE * GetStreamLatency) (ma_IAudioClient2* pThis, MA_REFERENCE_TIME* pLatency); @@ -6388,7 +6609,7 @@ typedef struct HRESULT (STDMETHODCALLTYPE * SetEventHandle) (ma_IAudioClient2* pThis, HANDLE eventHandle); HRESULT (STDMETHODCALLTYPE * GetService) (ma_IAudioClient2* pThis, const IID* const riid, void** pp); - // IAudioClient2 + /* IAudioClient2 */ HRESULT (STDMETHODCALLTYPE * IsOffloadCapable) (ma_IAudioClient2* pThis, MA_AUDIO_STREAM_CATEGORY category, BOOL* pOffloadCapable); HRESULT (STDMETHODCALLTYPE * SetClientProperties)(ma_IAudioClient2* pThis, const ma_AudioClientProperties* pProperties); HRESULT (STDMETHODCALLTYPE * GetBufferSizeLimits)(ma_IAudioClient2* pThis, const WAVEFORMATEX* pFormat, BOOL eventDriven, MA_REFERENCE_TIME* pMinBufferDuration, MA_REFERENCE_TIME* pMaxBufferDuration); @@ -6417,15 +6638,15 @@ HRESULT ma_IAudioClient2_SetClientProperties(ma_IAudioClient2* pThis, const ma_A HRESULT ma_IAudioClient2_GetBufferSizeLimits(ma_IAudioClient2* pThis, const WAVEFORMATEX* pFormat, BOOL eventDriven, MA_REFERENCE_TIME* pMinBufferDuration, MA_REFERENCE_TIME* pMaxBufferDuration) { return pThis->lpVtbl->GetBufferSizeLimits(pThis, pFormat, eventDriven, pMinBufferDuration, pMaxBufferDuration); } -// IAudioClient3 +/* IAudioClient3 */ typedef struct { - // IUnknown + /* IUnknown */ HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IAudioClient3* pThis, const IID* const riid, void** ppObject); ULONG (STDMETHODCALLTYPE * AddRef) (ma_IAudioClient3* pThis); ULONG (STDMETHODCALLTYPE * Release) (ma_IAudioClient3* pThis); - // IAudioClient + /* IAudioClient */ HRESULT (STDMETHODCALLTYPE * Initialize) (ma_IAudioClient3* pThis, MA_AUDCLNT_SHAREMODE shareMode, DWORD streamFlags, MA_REFERENCE_TIME bufferDuration, MA_REFERENCE_TIME periodicity, const WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid); HRESULT (STDMETHODCALLTYPE * GetBufferSize) (ma_IAudioClient3* pThis, ma_uint32* pNumBufferFrames); HRESULT (STDMETHODCALLTYPE * GetStreamLatency) (ma_IAudioClient3* pThis, MA_REFERENCE_TIME* pLatency); @@ -6439,12 +6660,12 @@ typedef struct HRESULT (STDMETHODCALLTYPE * SetEventHandle) (ma_IAudioClient3* pThis, HANDLE eventHandle); HRESULT (STDMETHODCALLTYPE * GetService) (ma_IAudioClient3* pThis, const IID* const riid, void** pp); - // IAudioClient2 + /* IAudioClient2 */ HRESULT (STDMETHODCALLTYPE * IsOffloadCapable) (ma_IAudioClient3* pThis, MA_AUDIO_STREAM_CATEGORY category, BOOL* pOffloadCapable); HRESULT (STDMETHODCALLTYPE * SetClientProperties)(ma_IAudioClient3* pThis, const ma_AudioClientProperties* pProperties); HRESULT (STDMETHODCALLTYPE * GetBufferSizeLimits)(ma_IAudioClient3* pThis, const WAVEFORMATEX* pFormat, BOOL eventDriven, MA_REFERENCE_TIME* pMinBufferDuration, MA_REFERENCE_TIME* pMaxBufferDuration); - // IAudioClient3 + /* IAudioClient3 */ HRESULT (STDMETHODCALLTYPE * GetSharedModeEnginePeriod) (ma_IAudioClient3* pThis, const WAVEFORMATEX* pFormat, UINT32* pDefaultPeriodInFrames, UINT32* pFundamentalPeriodInFrames, UINT32* pMinPeriodInFrames, UINT32* pMaxPeriodInFrames); HRESULT (STDMETHODCALLTYPE * GetCurrentSharedModeEnginePeriod)(ma_IAudioClient3* pThis, WAVEFORMATEX** ppFormat, UINT32* pCurrentPeriodInFrames); HRESULT (STDMETHODCALLTYPE * InitializeSharedAudioStream) (ma_IAudioClient3* pThis, DWORD streamFlags, UINT32 periodInFrames, const WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid); @@ -6476,15 +6697,15 @@ HRESULT ma_IAudioClient3_GetCurrentSharedModeEnginePeriod(ma_IAudioClient3* pThi HRESULT ma_IAudioClient3_InitializeSharedAudioStream(ma_IAudioClient3* pThis, DWORD streamFlags, UINT32 periodInFrames, const WAVEFORMATEX* pFormat, const GUID* pAudioSessionGUID) { return pThis->lpVtbl->InitializeSharedAudioStream(pThis, streamFlags, periodInFrames, pFormat, pAudioSessionGUID); } -// IAudioRenderClient +/* IAudioRenderClient */ typedef struct { - // IUnknown + /* IUnknown */ HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IAudioRenderClient* pThis, const IID* const riid, void** ppObject); ULONG (STDMETHODCALLTYPE * AddRef) (ma_IAudioRenderClient* pThis); ULONG (STDMETHODCALLTYPE * Release) (ma_IAudioRenderClient* pThis); - // IAudioRenderClient + /* IAudioRenderClient */ HRESULT (STDMETHODCALLTYPE * GetBuffer) (ma_IAudioRenderClient* pThis, ma_uint32 numFramesRequested, BYTE** ppData); HRESULT (STDMETHODCALLTYPE * ReleaseBuffer)(ma_IAudioRenderClient* pThis, ma_uint32 numFramesWritten, DWORD dwFlags); } ma_IAudioRenderClientVtbl; @@ -6499,15 +6720,15 @@ HRESULT ma_IAudioRenderClient_GetBuffer(ma_IAudioRenderClient* pThis, ma_uint32 HRESULT ma_IAudioRenderClient_ReleaseBuffer(ma_IAudioRenderClient* pThis, ma_uint32 numFramesWritten, DWORD dwFlags) { return pThis->lpVtbl->ReleaseBuffer(pThis, numFramesWritten, dwFlags); } -// IAudioCaptureClient +/* IAudioCaptureClient */ typedef struct { - // IUnknown + /* IUnknown */ HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IAudioCaptureClient* pThis, const IID* const riid, void** ppObject); ULONG (STDMETHODCALLTYPE * AddRef) (ma_IAudioCaptureClient* pThis); ULONG (STDMETHODCALLTYPE * Release) (ma_IAudioCaptureClient* pThis); - // IAudioRenderClient + /* IAudioRenderClient */ HRESULT (STDMETHODCALLTYPE * GetBuffer) (ma_IAudioCaptureClient* pThis, BYTE** ppData, ma_uint32* pNumFramesToRead, DWORD* pFlags, ma_uint64* pDevicePosition, ma_uint64* pQPCPosition); HRESULT (STDMETHODCALLTYPE * ReleaseBuffer) (ma_IAudioCaptureClient* pThis, ma_uint32 numFramesRead); HRESULT (STDMETHODCALLTYPE * GetNextPacketSize)(ma_IAudioCaptureClient* pThis, ma_uint32* pNumFramesInNextPacket); @@ -6529,12 +6750,12 @@ typedef struct ma_completion_handler_uwp ma_completion_handler_uwp; typedef struct { - // IUnknown + /* IUnknown */ HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_completion_handler_uwp* pThis, const IID* const riid, void** ppObject); ULONG (STDMETHODCALLTYPE * AddRef) (ma_completion_handler_uwp* pThis); ULONG (STDMETHODCALLTYPE * Release) (ma_completion_handler_uwp* pThis); - // IActivateAudioInterfaceCompletionHandler + /* IActivateAudioInterfaceCompletionHandler */ HRESULT (STDMETHODCALLTYPE * ActivateCompleted)(ma_completion_handler_uwp* pThis, ma_IActivateAudioInterfaceAsyncOperation* pActivateOperation); } ma_completion_handler_uwp_vtbl; struct ma_completion_handler_uwp @@ -6546,14 +6767,16 @@ struct ma_completion_handler_uwp HRESULT STDMETHODCALLTYPE ma_completion_handler_uwp_QueryInterface(ma_completion_handler_uwp* pThis, const IID* const riid, void** ppObject) { - // We need to "implement" IAgileObject which is just an indicator that's used internally by WASAPI for some multithreading management. To - // "implement" this, we just make sure we return pThis when the IAgileObject is requested. + /* + We need to "implement" IAgileObject which is just an indicator that's used internally by WASAPI for some multithreading management. To + "implement" this, we just make sure we return pThis when the IAgileObject is requested. + */ if (!ma_is_guid_equal(riid, &MA_IID_IUnknown) && !ma_is_guid_equal(riid, &MA_IID_IActivateAudioInterfaceCompletionHandler) && !ma_is_guid_equal(riid, &MA_IID_IAgileObject)) { *ppObject = NULL; return E_NOINTERFACE; } - // Getting here means the IID is IUnknown or IMMNotificationClient. + /* Getting here means the IID is IUnknown or IMMNotificationClient. */ *ppObject = (void*)pThis; ((ma_completion_handler_uwp_vtbl*)pThis->lpVtbl)->AddRef(pThis); return S_OK; @@ -6568,7 +6791,7 @@ ULONG STDMETHODCALLTYPE ma_completion_handler_uwp_Release(ma_completion_handler_ { ma_uint32 newRefCount = ma_atomic_decrement_32(&pThis->counter); if (newRefCount == 0) { - return 0; // We don't free anything here because we never allocate the object on the heap. + return 0; /* We don't free anything here because we never allocate the object on the heap. */ } return (ULONG)newRefCount; @@ -6615,20 +6838,22 @@ void ma_completion_handler_uwp_wait(ma_completion_handler_uwp* pHandler) { WaitForSingleObject(pHandler->hEvent, INFINITE); } -#endif // !MA_WIN32_DESKTOP +#endif /* !MA_WIN32_DESKTOP */ -// We need a virtual table for our notification client object that's used for detecting changes to the default device. +/* We need a virtual table for our notification client object that's used for detecting changes to the default device. */ #ifdef MA_WIN32_DESKTOP HRESULT STDMETHODCALLTYPE ma_IMMNotificationClient_QueryInterface(ma_IMMNotificationClient* pThis, const IID* const riid, void** ppObject) { - // We care about two interfaces - IUnknown and IMMNotificationClient. If the requested IID is something else - // we just return E_NOINTERFACE. Otherwise we need to increment the reference counter and return S_OK. + /* + We care about two interfaces - IUnknown and IMMNotificationClient. If the requested IID is something else + we just return E_NOINTERFACE. Otherwise we need to increment the reference counter and return S_OK. + */ if (!ma_is_guid_equal(riid, &MA_IID_IUnknown) && !ma_is_guid_equal(riid, &MA_IID_IMMNotificationClient)) { *ppObject = NULL; return E_NOINTERFACE; } - // Getting here means the IID is IUnknown or IMMNotificationClient. + /* Getting here means the IID is IUnknown or IMMNotificationClient. */ *ppObject = (void*)pThis; ((ma_IMMNotificationClientVtbl*)pThis->lpVtbl)->AddRef(pThis); return S_OK; @@ -6643,7 +6868,7 @@ ULONG STDMETHODCALLTYPE ma_IMMNotificationClient_Release(ma_IMMNotificationClien { ma_uint32 newRefCount = ma_atomic_decrement_32(&pThis->counter); if (newRefCount == 0) { - return 0; // We don't free anything here because we never allocate the object on the heap. + return 0; /* We don't free anything here because we never allocate the object on the heap. */ } return (ULONG)newRefCount; @@ -6668,7 +6893,7 @@ HRESULT STDMETHODCALLTYPE ma_IMMNotificationClient_OnDeviceAdded(ma_IMMNotificat printf("IMMNotificationClient_OnDeviceAdded(pDeviceID=%S)\n", (pDeviceID != NULL) ? pDeviceID : L"(NULL)"); #endif - // We don't need to worry about this event for our purposes. + /* We don't need to worry about this event for our purposes. */ (void)pThis; (void)pDeviceID; return S_OK; @@ -6680,7 +6905,7 @@ HRESULT STDMETHODCALLTYPE ma_IMMNotificationClient_OnDeviceRemoved(ma_IMMNotific printf("IMMNotificationClient_OnDeviceRemoved(pDeviceID=%S)\n", (pDeviceID != NULL) ? pDeviceID : L"(NULL)"); #endif - // We don't need to worry about this event for our purposes. + /* We don't need to worry about this event for our purposes. */ (void)pThis; (void)pDeviceID; return S_OK; @@ -6692,27 +6917,31 @@ HRESULT STDMETHODCALLTYPE ma_IMMNotificationClient_OnDefaultDeviceChanged(ma_IMM printf("IMMNotificationClient_OnDefaultDeviceChanged(dataFlow=%d, role=%d, pDefaultDeviceID=%S)\n", dataFlow, role, (pDefaultDeviceID != NULL) ? pDefaultDeviceID : L"(NULL)"); #endif - // We only ever use the eConsole role in miniaudio. + /* We only ever use the eConsole role in miniaudio. */ if (role != ma_eConsole) { return S_OK; } - // We only care about devices with the same data flow and role as the current device. + /* We only care about devices with the same data flow and role as the current device. */ if ((pThis->pDevice->type == ma_device_type_playback && dataFlow != ma_eRender) || (pThis->pDevice->type == ma_device_type_capture && dataFlow != ma_eCapture)) { return S_OK; } - // Not currently supporting automatic stream routing in exclusive mode. This is not working correctly on my machine due to - // AUDCLNT_E_DEVICE_IN_USE errors when reinitializing the device. If this is a bug in miniaudio, we can try re-enabling this once - // it's fixed. + /* + Not currently supporting automatic stream routing in exclusive mode. This is not working correctly on my machine due to + AUDCLNT_E_DEVICE_IN_USE errors when reinitializing the device. If this is a bug in miniaudio, we can try re-enabling this once + it's fixed. + */ if ((dataFlow == ma_eRender && pThis->pDevice->playback.shareMode == ma_share_mode_exclusive) || (dataFlow == ma_eCapture && pThis->pDevice->capture.shareMode == ma_share_mode_exclusive)) { return S_OK; } - // We don't change the device here - we change it in the worker thread to keep synchronization simple. To do this I'm just setting a flag to - // indicate that the default device has changed. + /* + We don't change the device here - we change it in the worker thread to keep synchronization simple. To do this I'm just setting a flag to + indicate that the default device has changed. + */ if (dataFlow == ma_eRender) { ma_atomic_exchange_32(&pThis->pDevice->wasapi.hasDefaultPlaybackDeviceChanged, MA_TRUE); } @@ -6746,7 +6975,7 @@ static ma_IMMNotificationClientVtbl g_maNotificationCientVtbl = { ma_IMMNotificationClient_OnDefaultDeviceChanged, ma_IMMNotificationClient_OnPropertyValueChanged }; -#endif // MA_WIN32_DESKTOP +#endif /* MA_WIN32_DESKTOP */ #ifdef MA_WIN32_DESKTOP typedef ma_IMMDevice ma_WASAPIDeviceInterface; @@ -6784,9 +7013,9 @@ ma_result ma_context_get_device_info_from_IAudioClient__wasapi(ma_context* pCont ma_assert(pAudioClient != NULL); ma_assert(pInfo != NULL); - // We use a different technique to retrieve the device information depending on whether or not we are using shared or exclusive mode. + /* We use a different technique to retrieve the device information depending on whether or not we are using shared or exclusive mode. */ if (shareMode == ma_share_mode_shared) { - // Shared Mode. We use GetMixFormat() here. + /* Shared Mode. We use GetMixFormat() here. */ WAVEFORMATEX* pWF = NULL; HRESULT hr = ma_IAudioClient_GetMixFormat((ma_IAudioClient*)pAudioClient, (WAVEFORMATEX**)&pWF); if (SUCCEEDED(hr)) { @@ -6796,10 +7025,12 @@ ma_result ma_context_get_device_info_from_IAudioClient__wasapi(ma_context* pCont return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to retrieve mix format for device info retrieval.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); } } else { - // Exlcusive Mode. We repeatedly call IsFormatSupported() here. This is not currently support on UWP. + /* Exlcusive Mode. We repeatedly call IsFormatSupported() here. This is not currently support on UWP. */ #ifdef MA_WIN32_DESKTOP - // The first thing to do is get the format from PKEY_AudioEngine_DeviceFormat. This should give us a channel count we assume is - // correct which will simplify our searching. + /* + The first thing to do is get the format from PKEY_AudioEngine_DeviceFormat. This should give us a channel count we assume is + correct which will simplify our searching. + */ ma_IPropertyStore *pProperties; HRESULT hr = ma_IMMDevice_OpenPropertyStore((ma_IMMDevice*)pMMDevice, STGM_READ, &pProperties); if (SUCCEEDED(hr)) { @@ -6811,38 +7042,44 @@ ma_result ma_context_get_device_info_from_IAudioClient__wasapi(ma_context* pCont WAVEFORMATEX* pWF = (WAVEFORMATEX*)var.blob.pBlobData; ma_set_device_info_from_WAVEFORMATEX(pWF, pInfo); - // In my testing, the format returned by PKEY_AudioEngine_DeviceFormat is suitable for exclusive mode so we check this format - // first. If this fails, fall back to a search. + /* + In my testing, the format returned by PKEY_AudioEngine_DeviceFormat is suitable for exclusive mode so we check this format + first. If this fails, fall back to a search. + */ hr = ma_IAudioClient_IsFormatSupported((ma_IAudioClient*)pAudioClient, MA_AUDCLNT_SHAREMODE_EXCLUSIVE, pWF, NULL); ma_PropVariantClear(pContext, &var); if (FAILED(hr)) { - // The format returned by PKEY_AudioEngine_DeviceFormat is not supported, so fall back to a search. We assume the channel - // count returned by MA_PKEY_AudioEngine_DeviceFormat is valid and correct. For simplicity we're only returning one format. + /* + The format returned by PKEY_AudioEngine_DeviceFormat is not supported, so fall back to a search. We assume the channel + count returned by MA_PKEY_AudioEngine_DeviceFormat is valid and correct. For simplicity we're only returning one format. + */ ma_uint32 channels = pInfo->minChannels; - ma_format formatsToSearch[] = { ma_format_s16, ma_format_s24, - //ma_format_s24_32, + /*ma_format_s24_32,*/ ma_format_f32, ma_format_s32, ma_format_u8 }; - ma_channel defaultChannelMap[MA_MAX_CHANNELS]; + WAVEFORMATEXTENSIBLE wf; + ma_bool32 found; + ma_uint32 iFormat; + ma_get_standard_channel_map(ma_standard_channel_map_microsoft, channels, defaultChannelMap); - WAVEFORMATEXTENSIBLE wf; ma_zero_object(&wf); wf.Format.cbSize = sizeof(wf); wf.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE; wf.Format.nChannels = (WORD)channels; wf.dwChannelMask = ma_channel_map_to_channel_mask__win32(defaultChannelMap, channels); - ma_bool32 found = MA_FALSE; - for (ma_uint32 iFormat = 0; iFormat < ma_countof(formatsToSearch); ++iFormat) { + found = MA_FALSE; + for (iFormat = 0; iFormat < ma_countof(formatsToSearch); ++iFormat) { ma_format format = formatsToSearch[iFormat]; + ma_uint32 iSampleRate; wf.Format.wBitsPerSample = (WORD)ma_get_bytes_per_sample(format)*8; wf.Format.nBlockAlign = (wf.Format.nChannels * wf.Format.wBitsPerSample) / 8; @@ -6854,7 +7091,7 @@ ma_result ma_context_get_device_info_from_IAudioClient__wasapi(ma_context* pCont wf.SubFormat = MA_GUID_KSDATAFORMAT_SUBTYPE_PCM; } - for (ma_uint32 iSampleRate = 0; iSampleRate < ma_countof(g_maStandardSampleRatePriorities); ++iSampleRate) { + for (iSampleRate = 0; iSampleRate < ma_countof(g_maStandardSampleRatePriorities); ++iSampleRate) { wf.Format.nSamplesPerSec = g_maStandardSampleRatePriorities[iSampleRate]; hr = ma_IAudioClient_IsFormatSupported((ma_IAudioClient*)pAudioClient, MA_AUDCLNT_SHAREMODE_EXCLUSIVE, (WAVEFORMATEX*)&wf, NULL); @@ -6885,7 +7122,7 @@ ma_result ma_context_get_device_info_from_IAudioClient__wasapi(ma_context* pCont return MA_SUCCESS; #else - // Exclusive mode not fully supported in UWP right now. + /* Exclusive mode not fully supported in UWP right now. */ return MA_ERROR; #endif } @@ -6894,11 +7131,13 @@ ma_result ma_context_get_device_info_from_IAudioClient__wasapi(ma_context* pCont #ifdef MA_WIN32_DESKTOP ma_result ma_context_get_MMDevice__wasapi(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_IMMDevice** ppMMDevice) { + ma_IMMDeviceEnumerator* pDeviceEnumerator; + HRESULT hr; + ma_assert(pContext != NULL); ma_assert(ppMMDevice != NULL); - ma_IMMDeviceEnumerator* pDeviceEnumerator; - HRESULT hr = ma_CoCreateInstance(pContext, MA_CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, MA_IID_IMMDeviceEnumerator, (void**)&pDeviceEnumerator); + hr = ma_CoCreateInstance(pContext, MA_CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, MA_IID_IMMDeviceEnumerator, (void**)&pDeviceEnumerator); if (FAILED(hr)) { return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create IMMDeviceEnumerator.", MA_FAILED_TO_INIT_BACKEND); } @@ -6919,18 +7158,20 @@ ma_result ma_context_get_MMDevice__wasapi(ma_context* pContext, ma_device_type d ma_result ma_context_get_device_info_from_MMDevice__wasapi(ma_context* pContext, ma_IMMDevice* pMMDevice, ma_share_mode shareMode, ma_bool32 onlySimpleInfo, ma_device_info* pInfo) { + LPWSTR id; + HRESULT hr; + ma_assert(pContext != NULL); ma_assert(pMMDevice != NULL); ma_assert(pInfo != NULL); - // ID. - LPWSTR id; - HRESULT hr = ma_IMMDevice_GetId(pMMDevice, &id); + /* ID. */ + hr = ma_IMMDevice_GetId(pMMDevice, &id); if (SUCCEEDED(hr)) { size_t idlen = wcslen(id); if (idlen+1 > ma_countof(pInfo->id.wasapi)) { ma_CoTaskMemFree(pContext, id); - ma_assert(MA_FALSE); // NOTE: If this is triggered, please report it. It means the format of the ID must haved change and is too long to fit in our fixed sized buffer. + ma_assert(MA_FALSE); /* NOTE: If this is triggered, please report it. It means the format of the ID must haved change and is too long to fit in our fixed sized buffer. */ return MA_ERROR; } @@ -6946,7 +7187,7 @@ ma_result ma_context_get_device_info_from_MMDevice__wasapi(ma_context* pContext, if (SUCCEEDED(hr)) { PROPVARIANT var; - // Description / Friendly Name + /* Description / Friendly Name */ ma_PropVariantInit(&var); hr = ma_IPropertyStore_GetValue(pProperties, &MA_PKEY_Device_FriendlyName, &var); if (SUCCEEDED(hr)) { @@ -6958,7 +7199,7 @@ ma_result ma_context_get_device_info_from_MMDevice__wasapi(ma_context* pContext, } } - // Format + /* Format */ if (!onlySimpleInfo) { ma_IAudioClient* pAudioClient; hr = ma_IMMDevice_Activate(pMMDevice, &MA_IID_IAudioClient, CLSCTX_ALL, NULL, (void**)&pAudioClient); @@ -6977,23 +7218,27 @@ ma_result ma_context_get_device_info_from_MMDevice__wasapi(ma_context* pContext, ma_result ma_context_enumerate_device_collection__wasapi(ma_context* pContext, ma_IMMDeviceCollection* pDeviceCollection, ma_device_type deviceType, ma_enum_devices_callback_proc callback, void* pUserData) { + UINT deviceCount; + HRESULT hr; + ma_uint32 iDevice; + ma_assert(pContext != NULL); ma_assert(callback != NULL); - UINT deviceCount; - HRESULT hr = ma_IMMDeviceCollection_GetCount(pDeviceCollection, &deviceCount); + hr = ma_IMMDeviceCollection_GetCount(pDeviceCollection, &deviceCount); if (FAILED(hr)) { return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to get playback device count.", MA_NO_DEVICE); } - for (ma_uint32 iDevice = 0; iDevice < deviceCount; ++iDevice) { + for (iDevice = 0; iDevice < deviceCount; ++iDevice) { ma_device_info deviceInfo; + ma_IMMDevice* pMMDevice; + ma_zero_object(&deviceInfo); - ma_IMMDevice* pMMDevice; hr = ma_IMMDeviceCollection_Item(pDeviceCollection, iDevice, &pMMDevice); if (SUCCEEDED(hr)) { - ma_result result = ma_context_get_device_info_from_MMDevice__wasapi(pContext, pMMDevice, ma_share_mode_shared, MA_TRUE, &deviceInfo); // MA_TRUE = onlySimpleInfo. + ma_result result = ma_context_get_device_info_from_MMDevice__wasapi(pContext, pMMDevice, ma_share_mode_shared, MA_TRUE, &deviceInfo); /* MA_TRUE = onlySimpleInfo. */ ma_IMMDevice_Release(pMMDevice); if (result == MA_SUCCESS) { @@ -7034,13 +7279,18 @@ ma_result ma_context_get_IAudioClient_Desktop__wasapi(ma_context* pContext, ma_d #else ma_result ma_context_get_IAudioClient_UWP__wasapi(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_IAudioClient** ppAudioClient, ma_IUnknown** ppActivatedInterface) { - ma_assert(pContext != NULL); - ma_assert(ppAudioClient != NULL); - ma_IActivateAudioInterfaceAsyncOperation *pAsyncOp = NULL; ma_completion_handler_uwp completionHandler; - IID iid; + LPOLESTR iidStr; + HRESULT hr; + ma_result result; + HRESULT activateResult; + ma_IUnknown* pActivatedInterface; + + ma_assert(pContext != NULL); + ma_assert(ppAudioClient != NULL); + if (pDeviceID != NULL) { ma_copy_memory(&iid, pDeviceID->wasapi, sizeof(iid)); } else { @@ -7051,17 +7301,16 @@ ma_result ma_context_get_IAudioClient_UWP__wasapi(ma_context* pContext, ma_devic } } - LPOLESTR iidStr; #if defined(__cplusplus) - HRESULT hr = StringFromIID(iid, &iidStr); + hr = StringFromIID(iid, &iidStr); #else - HRESULT hr = StringFromIID(&iid, &iidStr); + hr = StringFromIID(&iid, &iidStr); #endif if (FAILED(hr)) { return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to convert device IID to string for ActivateAudioInterfaceAsync(). Out of memory.", MA_OUT_OF_MEMORY); } - ma_result result = ma_completion_handler_uwp_init(&completionHandler); + result = ma_completion_handler_uwp_init(&completionHandler); if (result != MA_SUCCESS) { ma_CoTaskMemFree(pContext, iidStr); return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create event for waiting for ActivateAudioInterfaceAsync().", MA_FAILED_TO_OPEN_BACKEND_DEVICE); @@ -7080,12 +7329,10 @@ ma_result ma_context_get_IAudioClient_UWP__wasapi(ma_context* pContext, ma_devic ma_CoTaskMemFree(pContext, iidStr); - // Wait for the async operation for finish. + /* Wait for the async operation for finish. */ ma_completion_handler_uwp_wait(&completionHandler); ma_completion_handler_uwp_uninit(&completionHandler); - HRESULT activateResult; - ma_IUnknown* pActivatedInterface; hr = ma_IActivateAudioInterfaceAsyncOperation_GetActivateResult(pAsyncOp, &activateResult, &pActivatedInterface); ma_IActivateAudioInterfaceAsyncOperation_Release(pAsyncOp); @@ -7093,7 +7340,7 @@ ma_result ma_context_get_IAudioClient_UWP__wasapi(ma_context* pContext, ma_devic return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to activate device.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); } - // Here is where we grab the IAudioClient interface. + /* Here is where we grab the IAudioClient interface. */ hr = ma_IUnknown_QueryInterface(pActivatedInterface, &MA_IID_IAudioClient, (void**)ppAudioClient); if (FAILED(hr)) { return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to query IAudioClient interface.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); @@ -7121,28 +7368,26 @@ ma_result ma_context_get_IAudioClient__wasapi(ma_context* pContext, ma_device_ty ma_result ma_context_enumerate_devices__wasapi(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData) { - ma_assert(pContext != NULL); - ma_assert(callback != NULL); - - // Different enumeration for desktop and UWP. + /* Different enumeration for desktop and UWP. */ #ifdef MA_WIN32_DESKTOP - // Desktop + /* Desktop */ + HRESULT hr; ma_IMMDeviceEnumerator* pDeviceEnumerator; - HRESULT hr = ma_CoCreateInstance(pContext, MA_CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, MA_IID_IMMDeviceEnumerator, (void**)&pDeviceEnumerator); + ma_IMMDeviceCollection* pDeviceCollection; + + hr = ma_CoCreateInstance(pContext, MA_CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, MA_IID_IMMDeviceEnumerator, (void**)&pDeviceEnumerator); if (FAILED(hr)) { return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create device enumerator.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); } - ma_IMMDeviceCollection* pDeviceCollection; - - // Playback. + /* Playback. */ hr = ma_IMMDeviceEnumerator_EnumAudioEndpoints(pDeviceEnumerator, ma_eRender, MA_MM_DEVICE_STATE_ACTIVE, &pDeviceCollection); if (SUCCEEDED(hr)) { ma_context_enumerate_device_collection__wasapi(pContext, pDeviceCollection, ma_device_type_playback, callback, pUserData); ma_IMMDeviceCollection_Release(pDeviceCollection); } - // Capture. + /* Capture. */ hr = ma_IMMDeviceEnumerator_EnumAudioEndpoints(pDeviceEnumerator, ma_eCapture, MA_MM_DEVICE_STATE_ACTIVE, &pDeviceCollection); if (SUCCEEDED(hr)) { ma_context_enumerate_device_collection__wasapi(pContext, pDeviceCollection, ma_device_type_capture, callback, pUserData); @@ -7151,16 +7396,18 @@ ma_result ma_context_enumerate_devices__wasapi(ma_context* pContext, ma_enum_dev ma_IMMDeviceEnumerator_Release(pDeviceEnumerator); #else - // UWP - // - // The MMDevice API is only supported on desktop applications. For now, while I'm still figuring out how to properly enumerate - // over devices without using MMDevice, I'm restricting devices to defaults. - // - // Hint: DeviceInformation::FindAllAsync() with DeviceClass.AudioCapture/AudioRender. https://blogs.windows.com/buildingapps/2014/05/15/real-time-audio-in-windows-store-and-windows-phone-apps/ + /* + UWP + + The MMDevice API is only supported on desktop applications. For now, while I'm still figuring out how to properly enumerate + over devices without using MMDevice, I'm restricting devices to defaults. + + Hint: DeviceInformation::FindAllAsync() with DeviceClass.AudioCapture/AudioRender. https://blogs.windows.com/buildingapps/2014/05/15/real-time-audio-in-windows-store-and-windows-phone-apps/ + */ if (callback) { ma_bool32 cbResult = MA_TRUE; - // Playback. + /* Playback. */ if (cbResult) { ma_device_info deviceInfo; ma_zero_object(&deviceInfo); @@ -7168,7 +7415,7 @@ ma_result ma_context_enumerate_devices__wasapi(ma_context* pContext, ma_enum_dev cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData); } - // Capture. + /* Capture. */ if (cbResult) { ma_device_info deviceInfo; ma_zero_object(&deviceInfo); @@ -7185,30 +7432,34 @@ ma_result ma_context_get_device_info__wasapi(ma_context* pContext, ma_device_typ { #ifdef MA_WIN32_DESKTOP ma_IMMDevice* pMMDevice = NULL; - ma_result result = ma_context_get_MMDevice__wasapi(pContext, deviceType, pDeviceID, &pMMDevice); + ma_result result; + + result = ma_context_get_MMDevice__wasapi(pContext, deviceType, pDeviceID, &pMMDevice); if (result != MA_SUCCESS) { return result; } - result = ma_context_get_device_info_from_MMDevice__wasapi(pContext, pMMDevice, shareMode, MA_FALSE, pDeviceInfo); // MA_FALSE = !onlySimpleInfo. + result = ma_context_get_device_info_from_MMDevice__wasapi(pContext, pMMDevice, shareMode, MA_FALSE, pDeviceInfo); /* MA_FALSE = !onlySimpleInfo. */ ma_IMMDevice_Release(pMMDevice); return result; #else - // UWP currently only uses default devices. + ma_IAudioClient* pAudioClient; + ma_result result; + + /* UWP currently only uses default devices. */ if (deviceType == ma_device_type_playback) { ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); } else { ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); } - // Not currently supporting exclusive mode on UWP. + /* Not currently supporting exclusive mode on UWP. */ if (shareMode == ma_share_mode_exclusive) { return MA_ERROR; } - ma_IAudioClient* pAudioClient; - ma_result result = ma_context_get_IAudioClient_UWP__wasapi(pContext, deviceType, pDeviceID, &pAudioClient, NULL); + result = ma_context_get_IAudioClient_UWP__wasapi(pContext, deviceType, pDeviceID, &pAudioClient, NULL); if (result != MA_SUCCESS) { return result; } @@ -7256,7 +7507,7 @@ void ma_device_uninit__wasapi(ma_device* pDevice) typedef struct { - // Input. + /* Input. */ ma_format formatIn; ma_uint32 channelsIn; ma_uint32 sampleRateIn; @@ -7270,7 +7521,7 @@ typedef struct ma_bool32 usingDefaultChannelMap; ma_share_mode shareMode; - // Output. + /* Output. */ ma_IAudioClient* pAudioClient; ma_IAudioRenderClient* pRenderClient; ma_IAudioCaptureClient* pCaptureClient; @@ -7286,7 +7537,15 @@ typedef struct ma_result ma_device_init_internal__wasapi(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_init_internal_data__wasapi* pData) { - (void)pContext; + HRESULT hr; + ma_result result = MA_SUCCESS; + const char* errorMsg = ""; + MA_AUDCLNT_SHAREMODE shareMode = MA_AUDCLNT_SHAREMODE_SHARED; + MA_REFERENCE_TIME bufferDurationInMicroseconds; + ma_bool32 wasInitializedUsingIAudioClient3 = MA_FALSE; + WAVEFORMATEXTENSIBLE wf; + ma_WASAPIDeviceInterface* pDeviceInterface = NULL; + ma_IAudioClient2* pAudioClient2; ma_assert(pContext != NULL); ma_assert(pData != NULL); @@ -7299,16 +7558,6 @@ ma_result ma_device_init_internal__wasapi(ma_context* pContext, ma_device_type d pData->pAudioClient = NULL; pData->pRenderClient = NULL; pData->pCaptureClient = NULL; - - - HRESULT hr; - ma_result result = MA_SUCCESS; - const char* errorMsg = ""; - MA_AUDCLNT_SHAREMODE shareMode = MA_AUDCLNT_SHAREMODE_SHARED; - MA_REFERENCE_TIME bufferDurationInMicroseconds; - ma_bool32 wasInitializedUsingIAudioClient3 = MA_FALSE; - WAVEFORMATEXTENSIBLE wf; - ma_WASAPIDeviceInterface* pDeviceInterface = NULL; result = ma_context_get_IAudioClient__wasapi(pContext, deviceType, pDeviceID, &pData->pAudioClient, &pDeviceInterface); if (result != MA_SUCCESS) { @@ -7316,8 +7565,7 @@ ma_result ma_device_init_internal__wasapi(ma_context* pContext, ma_device_type d } - // Try enabling hardware offloading. - ma_IAudioClient2* pAudioClient2; + /* Try enabling hardware offloading. */ hr = ma_IAudioClient_QueryInterface(pData->pAudioClient, &MA_IID_IAudioClient2, (void**)&pAudioClient2); if (SUCCEEDED(hr)) { BOOL isHardwareOffloadingSupported = 0; @@ -7333,11 +7581,11 @@ ma_result ma_device_init_internal__wasapi(ma_context* pContext, ma_device_type d } - // Here is where we try to determine the best format to use with the device. If the client if wanting exclusive mode, first try finding the best format for that. If this fails, fall back to shared mode. + /* Here is where we try to determine the best format to use with the device. If the client if wanting exclusive mode, first try finding the best format for that. If this fails, fall back to shared mode. */ result = MA_FORMAT_NOT_SUPPORTED; if (pData->shareMode == ma_share_mode_exclusive) { #ifdef MA_WIN32_DESKTOP - // In exclusive mode on desktop we always use the backend's native format. + /* In exclusive mode on desktop we always use the backend's native format. */ ma_IPropertyStore* pStore = NULL; hr = ma_IMMDevice_OpenPropertyStore(pDeviceInterface, STGM_READ, &pStore); if (SUCCEEDED(hr)) { @@ -7357,11 +7605,13 @@ ma_result ma_device_init_internal__wasapi(ma_context* pContext, ma_device_type d ma_IPropertyStore_Release(pStore); } #else - // I do not know how to query the device's native format on UWP so for now I'm just disabling support for - // exclusive mode. The alternative is to enumerate over different formats and check IsFormatSupported() - // until you find one that works. - // - // TODO: Add support for exclusive mode to UWP. + /* + I do not know how to query the device's native format on UWP so for now I'm just disabling support for + exclusive mode. The alternative is to enumerate over different formats and check IsFormatSupported() + until you find one that works. + + TODO: Add support for exclusive mode to UWP. + */ hr = S_FALSE; #endif @@ -7372,7 +7622,7 @@ ma_result ma_device_init_internal__wasapi(ma_context* pContext, ma_device_type d result = MA_SHARE_MODE_NOT_SUPPORTED; } } else { - // In shared mode we are always using the format reported by the operating system. + /* In shared mode we are always using the format reported by the operating system. */ WAVEFORMATEXTENSIBLE* pNativeFormat = NULL; hr = ma_IAudioClient_GetMixFormat((ma_IAudioClient*)pData->pAudioClient, (WAVEFORMATEX**)&pNativeFormat); if (hr != S_OK) { @@ -7387,7 +7637,7 @@ ma_result ma_device_init_internal__wasapi(ma_context* pContext, ma_device_type d shareMode = MA_AUDCLNT_SHAREMODE_SHARED; } - // Return an error if we still haven't found a format. + /* Return an error if we still haven't found a format. */ if (result != MA_SUCCESS) { errorMsg = "[WASAPI] Failed to find best device mix format."; goto done; @@ -7397,10 +7647,10 @@ ma_result ma_device_init_internal__wasapi(ma_context* pContext, ma_device_type d pData->channelsOut = wf.Format.nChannels; pData->sampleRateOut = wf.Format.nSamplesPerSec; - // Get the internal channel map based on the channel mask. + /* Get the internal channel map based on the channel mask. */ ma_channel_mask_to_channel_map__win32(wf.dwChannelMask, pData->channelsOut, pData->channelMapOut); - // If we're using a default buffer size we need to calculate it based on the efficiency of the system. + /* If we're using a default buffer size we need to calculate it based on the efficiency of the system. */ pData->periodsOut = pData->periodsIn; pData->bufferSizeInFramesOut = pData->bufferSizeInFramesIn; if (pData->bufferSizeInFramesOut == 0) { @@ -7410,12 +7660,14 @@ ma_result ma_device_init_internal__wasapi(ma_context* pContext, ma_device_type d bufferDurationInMicroseconds = ((ma_uint64)pData->bufferSizeInFramesOut * 1000 * 1000) / pData->sampleRateOut; - // Slightly different initialization for shared and exclusive modes. We try exclusive mode first, and if it fails, fall back to shared mode. + /* Slightly different initialization for shared and exclusive modes. We try exclusive mode first, and if it fails, fall back to shared mode. */ if (shareMode == MA_AUDCLNT_SHAREMODE_EXCLUSIVE) { MA_REFERENCE_TIME bufferDuration = (bufferDurationInMicroseconds / pData->periodsOut) * 10; - // If the periodicy is too small, Initialize() will fail with AUDCLNT_E_INVALID_DEVICE_PERIOD. In this case we should just keep increasing - // it and trying it again. + /* + If the periodicy is too small, Initialize() will fail with AUDCLNT_E_INVALID_DEVICE_PERIOD. In this case we should just keep increasing + it and trying it again. + */ hr = E_FAIL; for (;;) { hr = ma_IAudioClient_Initialize((ma_IAudioClient*)pData->pAudioClient, shareMode, MA_AUDCLNT_STREAMFLAGS_EVENTCALLBACK, bufferDuration, bufferDuration, (WAVEFORMATEX*)&wf, NULL); @@ -7423,7 +7675,7 @@ ma_result ma_device_init_internal__wasapi(ma_context* pContext, ma_device_type d if (bufferDuration > 500*10000) { break; } else { - if (bufferDuration == 0) { // <-- Just a sanity check to prevent an infinit loop. Should never happen, but it makes me feel better. + if (bufferDuration == 0) { /* <-- Just a sanity check to prevent an infinit loop. Should never happen, but it makes me feel better. */ break; } @@ -7441,7 +7693,7 @@ ma_result ma_device_init_internal__wasapi(ma_context* pContext, ma_device_type d if (SUCCEEDED(hr)) { bufferDuration = (MA_REFERENCE_TIME)((10000.0 * 1000 / wf.Format.nSamplesPerSec * bufferSizeInFrames) + 0.5); - // Unfortunately we need to release and re-acquire the audio client according to MSDN. Seems silly - why not just call IAudioClient_Initialize() again?! + /* Unfortunately we need to release and re-acquire the audio client according to MSDN. Seems silly - why not just call IAudioClient_Initialize() again?! */ ma_IAudioClient_Release((ma_IAudioClient*)pData->pAudioClient); #ifdef MA_WIN32_DESKTOP @@ -7507,7 +7759,7 @@ ma_result ma_device_init_internal__wasapi(ma_context* pContext, ma_device_type d } #endif - // If we don't have an IAudioClient3 then we need to use the normal initialization routine. + /* If we don't have an IAudioClient3 then we need to use the normal initialization routine. */ if (!wasInitializedUsingIAudioClient3) { MA_REFERENCE_TIME bufferDuration = bufferDurationInMicroseconds*10; hr = ma_IAudioClient_Initialize((ma_IAudioClient*)pData->pAudioClient, shareMode, MA_AUDCLNT_STREAMFLAGS_EVENTCALLBACK, bufferDuration, 0, (WAVEFORMATEX*)&wf, NULL); @@ -7547,25 +7799,27 @@ ma_result ma_device_init_internal__wasapi(ma_context* pContext, ma_device_type d } - // Grab the name of the device. + /* Grab the name of the device. */ #ifdef MA_WIN32_DESKTOP - ma_IPropertyStore *pProperties; - hr = ma_IMMDevice_OpenPropertyStore(pDeviceInterface, STGM_READ, &pProperties); - if (SUCCEEDED(hr)) { - PROPVARIANT varName; - ma_PropVariantInit(&varName); - hr = ma_IPropertyStore_GetValue(pProperties, &MA_PKEY_Device_FriendlyName, &varName); + { + ma_IPropertyStore *pProperties; + hr = ma_IMMDevice_OpenPropertyStore(pDeviceInterface, STGM_READ, &pProperties); if (SUCCEEDED(hr)) { - WideCharToMultiByte(CP_UTF8, 0, varName.pwszVal, -1, pData->deviceName, sizeof(pData->deviceName), 0, FALSE); - ma_PropVariantClear(pContext, &varName); - } + PROPVARIANT varName; + ma_PropVariantInit(&varName); + hr = ma_IPropertyStore_GetValue(pProperties, &MA_PKEY_Device_FriendlyName, &varName); + if (SUCCEEDED(hr)) { + WideCharToMultiByte(CP_UTF8, 0, varName.pwszVal, -1, pData->deviceName, sizeof(pData->deviceName), 0, FALSE); + ma_PropVariantClear(pContext, &varName); + } - ma_IPropertyStore_Release(pProperties); + ma_IPropertyStore_Release(pProperties); + } } #endif done: - // Clean up. + /* Clean up. */ #ifdef MA_WIN32_DESKTOP if (pDeviceInterface != NULL) { ma_IMMDevice_Release(pDeviceInterface); @@ -7598,14 +7852,16 @@ done: ma_result ma_device_reinit__wasapi(ma_device* pDevice, ma_device_type deviceType) { + ma_device_init_internal_data__wasapi data; + ma_result result; + ma_assert(pDevice != NULL); - // We only re-initialize the playback or capture device. Never a full-duplex device. + /* We only re-initialize the playback or capture device. Never a full-duplex device. */ if (deviceType == ma_device_type_duplex) { return MA_INVALID_ARGS; } - ma_device_init_internal_data__wasapi data; if (deviceType == ma_device_type_capture) { data.formatIn = pDevice->capture.format; data.channelsIn = pDevice->capture.channels; @@ -7629,12 +7885,12 @@ ma_result ma_device_reinit__wasapi(ma_device* pDevice, ma_device_type deviceType data.bufferSizeInFramesIn = pDevice->wasapi.originalBufferSizeInFrames; data.bufferSizeInMillisecondsIn = pDevice->wasapi.originalBufferSizeInMilliseconds; data.periodsIn = pDevice->wasapi.originalPeriods; - ma_result result = ma_device_init_internal__wasapi(pDevice->pContext, deviceType, NULL, &data); + result = ma_device_init_internal__wasapi(pDevice->pContext, deviceType, NULL, &data); if (result != MA_SUCCESS) { return result; } - // At this point we have some new objects ready to go. We need to uninitialize the previous ones and then set the new ones. + /* At this point we have some new objects ready to go. We need to uninitialize the previous ones and then set the new ones. */ if (deviceType == ma_device_type_capture) { if (pDevice->wasapi.pCaptureClient) { ma_IAudioCaptureClient_Release((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient); @@ -7862,27 +8118,30 @@ ma_result ma_device_init__wasapi(ma_context* pContext, const ma_device_config* p ma_IAudioClient_GetBufferSize((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback, &pDevice->wasapi.actualBufferSizeInFramesPlayback); } - - // We need to get notifications of when the default device changes. We do this through a device enumerator by - // registering a IMMNotificationClient with it. We only care about this if it's the default device. + /* + We need to get notifications of when the default device changes. We do this through a device enumerator by + registering a IMMNotificationClient with it. We only care about this if it's the default device. + */ #ifdef MA_WIN32_DESKTOP - ma_IMMDeviceEnumerator* pDeviceEnumerator; - HRESULT hr = ma_CoCreateInstance(pContext, MA_CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, MA_IID_IMMDeviceEnumerator, (void**)&pDeviceEnumerator); - if (FAILED(hr)) { - ma_device_uninit__wasapi(pDevice); - return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create device enumerator.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); - } + { + ma_IMMDeviceEnumerator* pDeviceEnumerator; + HRESULT hr = ma_CoCreateInstance(pContext, MA_CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, MA_IID_IMMDeviceEnumerator, (void**)&pDeviceEnumerator); + if (FAILED(hr)) { + ma_device_uninit__wasapi(pDevice); + return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create device enumerator.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); + } - pDevice->wasapi.notificationClient.lpVtbl = (void*)&g_maNotificationCientVtbl; - pDevice->wasapi.notificationClient.counter = 1; - pDevice->wasapi.notificationClient.pDevice = pDevice; + pDevice->wasapi.notificationClient.lpVtbl = (void*)&g_maNotificationCientVtbl; + pDevice->wasapi.notificationClient.counter = 1; + pDevice->wasapi.notificationClient.pDevice = pDevice; - hr = pDeviceEnumerator->lpVtbl->RegisterEndpointNotificationCallback(pDeviceEnumerator, &pDevice->wasapi.notificationClient); - if (SUCCEEDED(hr)) { - pDevice->wasapi.pDeviceEnumerator = (ma_ptr)pDeviceEnumerator; - } else { - // Not the end of the world if we fail to register the notification callback. We just won't support automatic stream routing. - ma_IMMDeviceEnumerator_Release(pDeviceEnumerator); + hr = pDeviceEnumerator->lpVtbl->RegisterEndpointNotificationCallback(pDeviceEnumerator, &pDevice->wasapi.notificationClient); + if (SUCCEEDED(hr)) { + pDevice->wasapi.pDeviceEnumerator = (ma_ptr)pDeviceEnumerator; + } else { + /* Not the end of the world if we fail to register the notification callback. We just won't support automatic stream routing. */ + ma_IMMDeviceEnumerator_Release(pDeviceEnumerator); + } } #endif @@ -7894,6 +8153,10 @@ ma_result ma_device_init__wasapi(ma_context* pContext, const ma_device_config* p ma_result ma_device__get_available_frames__wasapi(ma_device* pDevice, ma_IAudioClient* pAudioClient, ma_uint32* pFrameCount) { + ma_uint32 paddingFramesCount; + HRESULT hr; + ma_share_mode shareMode; + ma_assert(pDevice != NULL); ma_assert(pFrameCount != NULL); @@ -7903,14 +8166,13 @@ ma_result ma_device__get_available_frames__wasapi(ma_device* pDevice, ma_IAudioC return MA_INVALID_OPERATION; } - ma_uint32 paddingFramesCount; - HRESULT hr = ma_IAudioClient_GetCurrentPadding(pAudioClient, &paddingFramesCount); + hr = ma_IAudioClient_GetCurrentPadding(pAudioClient, &paddingFramesCount); if (FAILED(hr)) { return MA_DEVICE_UNAVAILABLE; } - // Slightly different rules for exclusive and shared modes. - ma_share_mode shareMode = ((ma_ptr)pAudioClient == pDevice->wasapi.pAudioClientPlayback) ? pDevice->playback.shareMode : pDevice->capture.shareMode; + /* Slightly different rules for exclusive and shared modes. */ + shareMode = ((ma_ptr)pAudioClient == pDevice->wasapi.pAudioClientPlayback) ? pDevice->playback.shareMode : pDevice->capture.shareMode; if (shareMode == ma_share_mode_exclusive) { *pFrameCount = paddingFramesCount; } else { @@ -7941,6 +8203,8 @@ ma_bool32 ma_device_is_reroute_required__wasapi(ma_device* pDevice, ma_device_ty ma_result ma_device_reroute__wasapi(ma_device* pDevice, ma_device_type deviceType) { + ma_result result; + if (deviceType == ma_device_type_duplex) { return MA_INVALID_ARGS; } @@ -7957,7 +8221,7 @@ ma_result ma_device_reroute__wasapi(ma_device* pDevice, ma_device_type deviceTyp printf("=== CHANGING DEVICE ===\n"); #endif - ma_result result = ma_device_reinit__wasapi(pDevice, deviceType); + result = ma_device_reinit__wasapi(pDevice, deviceType); if (result != MA_SUCCESS) { return result; } @@ -8037,7 +8301,7 @@ ma_result ma_device_main_loop__wasapi(ma_device* pDevice) return result; } - //printf("TRACE 1: framesAvailablePlayback=%d\n", framesAvailablePlayback); + /*printf("TRACE 1: framesAvailablePlayback=%d\n", framesAvailablePlayback);*/ /* In exclusive mode, the frame count needs to exactly match the value returned by GetCurrentPadding(). */ @@ -8087,7 +8351,7 @@ ma_result ma_device_main_loop__wasapi(ma_device* pDevice) break; } - //printf("TRACE 2: framesAvailableCapture=%d\n", framesAvailableCapture); + /*printf("TRACE 2: framesAvailableCapture=%d\n", framesAvailableCapture);*/ /* Wait for more if nothing is available. */ if (framesAvailableCapture == 0) { @@ -8232,7 +8496,7 @@ ma_result ma_device_main_loop__wasapi(ma_device* pDevice) break; } - //printf("TRACE: Released capture buffer\n"); + /*printf("TRACE: Released capture buffer\n");*/ pMappedBufferCapture = NULL; mappedBufferFramesRemainingCapture = 0; @@ -8255,7 +8519,7 @@ ma_result ma_device_main_loop__wasapi(ma_device* pDevice) break; } - //printf("TRACE: Released playback buffer\n"); + /*printf("TRACE: Released playback buffer\n");*/ framesWrittenToPlaybackDevice += mappedBufferSizeInFramesPlayback; pMappedBufferPlayback = NULL; @@ -8476,26 +8740,50 @@ ma_result ma_context_uninit__wasapi(ma_context* pContext) ma_result ma_context_init__wasapi(const ma_context_config* pConfig, ma_context* pContext) { + ma_result result = MA_SUCCESS; + ma_assert(pContext != NULL); (void)pContext; (void)pConfig; - ma_result result = MA_SUCCESS; - #ifdef MA_WIN32_DESKTOP - // WASAPI is only supported in Vista SP1 and newer. The reason for SP1 and not the base version of Vista is that event-driven - // exclusive mode does not work until SP1. - ma_OSVERSIONINFOEXW osvi; - ma_zero_object(&osvi); - osvi.dwOSVersionInfoSize = sizeof(osvi); - osvi.dwMajorVersion = HIBYTE(_WIN32_WINNT_VISTA); - osvi.dwMinorVersion = LOBYTE(_WIN32_WINNT_VISTA); - osvi.wServicePackMajor = 1; - if (VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR, VerSetConditionMask(VerSetConditionMask(VerSetConditionMask(0, VER_MAJORVERSION, VER_GREATER_EQUAL), VER_MINORVERSION, VER_GREATER_EQUAL), VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL))) { - result = MA_SUCCESS; - } else { - result = MA_NO_BACKEND; + /* + WASAPI is only supported in Vista SP1 and newer. The reason for SP1 and not the base version of Vista is that event-driven + exclusive mode does not work until SP1. + + Unfortunately older compilers don't define these functions so we need to dynamically load them in order to avoid a lin error. + */ + { + ma_OSVERSIONINFOEXW osvi; + ma_handle kernel32DLL; + ma_PFNVerifyVersionInfoW _VerifyVersionInfoW; + ma_PFNVerSetConditionMask _VerSetConditionMask; + + kernel32DLL = ma_dlopen("kernel32.dll"); + if (kernel32DLL == NULL) { + return MA_NO_BACKEND; + } + + _VerifyVersionInfoW = (ma_PFNVerifyVersionInfoW)ma_dlsym(kernel32DLL, "VerifyVersionInfoW"); + _VerSetConditionMask = (ma_PFNVerSetConditionMask)ma_dlsym(kernel32DLL, "VerSetConditionMask"); + if (_VerifyVersionInfoW == NULL || _VerSetConditionMask == NULL) { + ma_dlclose(kernel32DLL); + return MA_NO_BACKEND; + } + + ma_zero_object(&osvi); + osvi.dwOSVersionInfoSize = sizeof(osvi); + osvi.dwMajorVersion = HIBYTE(MA_WIN32_WINNT_VISTA); + osvi.dwMinorVersion = LOBYTE(MA_WIN32_WINNT_VISTA); + osvi.wServicePackMajor = 1; + if (_VerifyVersionInfoW(&osvi, MA_VER_MAJORVERSION | MA_VER_MINORVERSION | MA_VER_SERVICEPACKMAJOR, _VerSetConditionMask(_VerSetConditionMask(_VerSetConditionMask(0, MA_VER_MAJORVERSION, MA_VER_GREATER_EQUAL), MA_VER_MINORVERSION, MA_VER_GREATER_EQUAL), MA_VER_SERVICEPACKMAJOR, MA_VER_GREATER_EQUAL))) { + result = MA_SUCCESS; + } else { + result = MA_NO_BACKEND; + } + + ma_dlclose(kernel32DLL); } #endif @@ -8519,17 +8807,17 @@ ma_result ma_context_init__wasapi(const ma_context_config* pConfig, ma_context* } #endif -/////////////////////////////////////////////////////////////////////////////// -// -// DirectSound Backend -// -/////////////////////////////////////////////////////////////////////////////// +/****************************************************************************** + +DirectSound Backend + +******************************************************************************/ #ifdef MA_HAS_DSOUND -//#include +/*#include */ GUID MA_GUID_IID_DirectSoundNotify = {0xb0210783, 0x89cd, 0x11d0, {0xaf, 0x08, 0x00, 0xa0, 0xc9, 0x25, 0xcd, 0x16}}; -// miniaudio only uses priority or exclusive modes. +/* miniaudio only uses priority or exclusive modes. */ #define MA_DSSCL_NORMAL 1 #define MA_DSSCL_PRIORITY 2 #define MA_DSSCL_EXCLUSIVE 3 @@ -8591,7 +8879,7 @@ typedef struct DWORD dwReserved; WAVEFORMATEX* lpwfxFormat; DWORD dwFXCount; - void* lpDSCFXDesc; // <-- miniaudio doesn't use this, so set to void*. + void* lpDSCFXDesc; /* <-- miniaudio doesn't use this, so set to void*. */ } MA_DSCBUFFERDESC; typedef struct @@ -8660,20 +8948,22 @@ typedef struct ma_IDirectSoundCaptureBuffer ma_IDirectSoundCaptureBuffer; typedef struct ma_IDirectSoundNotify ma_IDirectSoundNotify; -// COM objects. The way these work is that you have a vtable (a list of function pointers, kind of -// like how C++ works internally), and then you have a structure with a single member, which is a -// pointer to the vtable. The vtable is where the methods of the object are defined. Methods need -// to be in a specific order, and parent classes need to have their methods declared first. +/* +COM objects. The way these work is that you have a vtable (a list of function pointers, kind of +like how C++ works internally), and then you have a structure with a single member, which is a +pointer to the vtable. The vtable is where the methods of the object are defined. Methods need +to be in a specific order, and parent classes need to have their methods declared first. +*/ -// IDirectSound +/* IDirectSound */ typedef struct { - // IUnknown + /* IUnknown */ HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IDirectSound* pThis, const IID* const riid, void** ppObject); ULONG (STDMETHODCALLTYPE * AddRef) (ma_IDirectSound* pThis); ULONG (STDMETHODCALLTYPE * Release) (ma_IDirectSound* pThis); - // IDirectSound + /* IDirectSound */ HRESULT (STDMETHODCALLTYPE * CreateSoundBuffer) (ma_IDirectSound* pThis, const MA_DSBUFFERDESC* pDSBufferDesc, ma_IDirectSoundBuffer** ppDSBuffer, void* pUnkOuter); HRESULT (STDMETHODCALLTYPE * GetCaps) (ma_IDirectSound* pThis, MA_DSCAPS* pDSCaps); HRESULT (STDMETHODCALLTYPE * DuplicateSoundBuffer)(ma_IDirectSound* pThis, ma_IDirectSoundBuffer* pDSBufferOriginal, ma_IDirectSoundBuffer** ppDSBufferDuplicate); @@ -8700,15 +8990,15 @@ HRESULT ma_IDirectSound_SetSpeakerConfig(ma_IDirectSound* pThis, DWORD dwSpeaker HRESULT ma_IDirectSound_Initialize(ma_IDirectSound* pThis, const GUID* pGuidDevice) { return pThis->lpVtbl->Initialize(pThis, pGuidDevice); } -// IDirectSoundBuffer +/* IDirectSoundBuffer */ typedef struct { - // IUnknown + /* IUnknown */ HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IDirectSoundBuffer* pThis, const IID* const riid, void** ppObject); ULONG (STDMETHODCALLTYPE * AddRef) (ma_IDirectSoundBuffer* pThis); ULONG (STDMETHODCALLTYPE * Release) (ma_IDirectSoundBuffer* pThis); - // IDirectSoundBuffer + /* IDirectSoundBuffer */ HRESULT (STDMETHODCALLTYPE * GetCaps) (ma_IDirectSoundBuffer* pThis, MA_DSBCAPS* pDSBufferCaps); HRESULT (STDMETHODCALLTYPE * GetCurrentPosition)(ma_IDirectSoundBuffer* pThis, DWORD* pCurrentPlayCursor, DWORD* pCurrentWriteCursor); HRESULT (STDMETHODCALLTYPE * GetFormat) (ma_IDirectSoundBuffer* pThis, WAVEFORMATEX* pFormat, DWORD dwSizeAllocated, DWORD* pSizeWritten); @@ -8755,15 +9045,15 @@ HRESULT ma_IDirectSoundBuffer_Unlock(ma_IDirectSoundBuffer* pThis, void* pAudioP HRESULT ma_IDirectSoundBuffer_Restore(ma_IDirectSoundBuffer* pThis) { return pThis->lpVtbl->Restore(pThis); } -// IDirectSoundCapture +/* IDirectSoundCapture */ typedef struct { - // IUnknown + /* IUnknown */ HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IDirectSoundCapture* pThis, const IID* const riid, void** ppObject); ULONG (STDMETHODCALLTYPE * AddRef) (ma_IDirectSoundCapture* pThis); ULONG (STDMETHODCALLTYPE * Release) (ma_IDirectSoundCapture* pThis); - // IDirectSoundCapture + /* IDirectSoundCapture */ HRESULT (STDMETHODCALLTYPE * CreateCaptureBuffer)(ma_IDirectSoundCapture* pThis, const MA_DSCBUFFERDESC* pDSCBufferDesc, ma_IDirectSoundCaptureBuffer** ppDSCBuffer, void* pUnkOuter); HRESULT (STDMETHODCALLTYPE * GetCaps) (ma_IDirectSoundCapture* pThis, MA_DSCCAPS* pDSCCaps); HRESULT (STDMETHODCALLTYPE * Initialize) (ma_IDirectSoundCapture* pThis, const GUID* pGuidDevice); @@ -8780,15 +9070,15 @@ HRESULT ma_IDirectSoundCapture_GetCaps (ma_IDirectSoundCapture* pThis HRESULT ma_IDirectSoundCapture_Initialize (ma_IDirectSoundCapture* pThis, const GUID* pGuidDevice) { return pThis->lpVtbl->Initialize(pThis, pGuidDevice); } -// IDirectSoundCaptureBuffer +/* IDirectSoundCaptureBuffer */ typedef struct { - // IUnknown + /* IUnknown */ HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IDirectSoundCaptureBuffer* pThis, const IID* const riid, void** ppObject); ULONG (STDMETHODCALLTYPE * AddRef) (ma_IDirectSoundCaptureBuffer* pThis); ULONG (STDMETHODCALLTYPE * Release) (ma_IDirectSoundCaptureBuffer* pThis); - // IDirectSoundCaptureBuffer + /* IDirectSoundCaptureBuffer */ HRESULT (STDMETHODCALLTYPE * GetCaps) (ma_IDirectSoundCaptureBuffer* pThis, MA_DSCBCAPS* pDSCBCaps); HRESULT (STDMETHODCALLTYPE * GetCurrentPosition)(ma_IDirectSoundCaptureBuffer* pThis, DWORD* pCapturePosition, DWORD* pReadPosition); HRESULT (STDMETHODCALLTYPE * GetFormat) (ma_IDirectSoundCaptureBuffer* pThis, WAVEFORMATEX* pFormat, DWORD dwSizeAllocated, DWORD* pSizeWritten); @@ -8817,15 +9107,15 @@ HRESULT ma_IDirectSoundCaptureBuffer_Stop(ma_IDirectSoundCaptureBuffer* pThis) HRESULT ma_IDirectSoundCaptureBuffer_Unlock(ma_IDirectSoundCaptureBuffer* pThis, void* pAudioPtr1, DWORD dwAudioBytes1, void* pAudioPtr2, DWORD dwAudioBytes2) { return pThis->lpVtbl->Unlock(pThis, pAudioPtr1, dwAudioBytes1, pAudioPtr2, dwAudioBytes2); } -// IDirectSoundNotify +/* IDirectSoundNotify */ typedef struct { - // IUnknown + /* IUnknown */ HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IDirectSoundNotify* pThis, const IID* const riid, void** ppObject); ULONG (STDMETHODCALLTYPE * AddRef) (ma_IDirectSoundNotify* pThis); ULONG (STDMETHODCALLTYPE * Release) (ma_IDirectSoundNotify* pThis); - // IDirectSoundNotify + /* IDirectSoundNotify */ HRESULT (STDMETHODCALLTYPE * SetNotificationPositions)(ma_IDirectSoundNotify* pThis, DWORD dwPositionNotifies, const MA_DSBPOSITIONNOTIFY* pPositionNotifies); } ma_IDirectSoundNotifyVtbl; struct ma_IDirectSoundNotify @@ -8845,22 +9135,29 @@ typedef HRESULT (WINAPI * ma_DirectSoundCaptureCreateProc) (const GUID* pcG typedef HRESULT (WINAPI * ma_DirectSoundCaptureEnumerateAProc)(ma_DSEnumCallbackAProc pDSEnumCallback, LPVOID pContext); -// Retrieves the channel count and channel map for the given speaker configuration. If the speaker configuration is unknown, -// the channel count and channel map will be left unmodified. +/* +Retrieves the channel count and channel map for the given speaker configuration. If the speaker configuration is unknown, +the channel count and channel map will be left unmodified. +*/ void ma_get_channels_from_speaker_config__dsound(DWORD speakerConfig, WORD* pChannelsOut, DWORD* pChannelMapOut) { - WORD channels = 0; + WORD channels; + DWORD channelMap; + + channels = 0; if (pChannelsOut != NULL) { channels = *pChannelsOut; } - DWORD channelMap = 0; + channelMap = 0; if (pChannelMapOut != NULL) { channelMap = *pChannelMapOut; } - // The speaker configuration is a combination of speaker config and speaker geometry. The lower 8 bits is what we care about. The upper - // 16 bits is for the geometry. + /* + The speaker configuration is a combination of speaker config and speaker geometry. The lower 8 bits is what we care about. The upper + 16 bits is for the geometry. + */ switch ((BYTE)(speakerConfig)) { case 1 /*DSSPEAKER_HEADPHONE*/: channels = 2; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break; case 2 /*DSSPEAKER_MONO*/: channels = 1; channelMap = SPEAKER_FRONT_CENTER; break; @@ -8886,18 +9183,21 @@ void ma_get_channels_from_speaker_config__dsound(DWORD speakerConfig, WORD* pCha ma_result ma_context_create_IDirectSound__dsound(ma_context* pContext, ma_share_mode shareMode, const ma_device_id* pDeviceID, ma_IDirectSound** ppDirectSound) { + ma_IDirectSound* pDirectSound; + HWND hWnd; + ma_assert(pContext != NULL); ma_assert(ppDirectSound != NULL); *ppDirectSound = NULL; - ma_IDirectSound* pDirectSound = NULL; + pDirectSound = NULL; if (FAILED(((ma_DirectSoundCreateProc)pContext->dsound.DirectSoundCreate)((pDeviceID == NULL) ? NULL : (const GUID*)pDeviceID->dsound, &pDirectSound, NULL))) { return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[DirectSound] DirectSoundCreate() failed for playback device.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); } - // The cooperative level must be set before doing anything else. - HWND hWnd = ((MA_PFN_GetForegroundWindow)pContext->win32.GetForegroundWindow)(); + /* The cooperative level must be set before doing anything else. */ + hWnd = ((MA_PFN_GetForegroundWindow)pContext->win32.GetForegroundWindow)(); if (hWnd == NULL) { hWnd = ((MA_PFN_GetDesktopWindow)pContext->win32.GetDesktopWindow)(); } @@ -8911,6 +9211,8 @@ ma_result ma_context_create_IDirectSound__dsound(ma_context* pContext, ma_share_ ma_result ma_context_create_IDirectSoundCapture__dsound(ma_context* pContext, ma_share_mode shareMode, const ma_device_id* pDeviceID, ma_IDirectSoundCapture** ppDirectSoundCapture) { + ma_IDirectSoundCapture* pDirectSoundCapture; + ma_assert(pContext != NULL); ma_assert(ppDirectSoundCapture != NULL); @@ -8920,7 +9222,7 @@ ma_result ma_context_create_IDirectSoundCapture__dsound(ma_context* pContext, ma } *ppDirectSoundCapture = NULL; - ma_IDirectSoundCapture* pDirectSoundCapture = NULL; + pDirectSoundCapture = NULL; if (FAILED(((ma_DirectSoundCaptureCreateProc)pContext->dsound.DirectSoundCaptureCreate)((pDeviceID == NULL) ? NULL : (const GUID*)pDeviceID->dsound, &pDirectSoundCapture, NULL))) { return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[DirectSound] DirectSoundCaptureCreate() failed for capture device.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); @@ -8932,6 +9234,10 @@ ma_result ma_context_create_IDirectSoundCapture__dsound(ma_context* pContext, ma ma_result ma_context_get_format_info_for_IDirectSoundCapture__dsound(ma_context* pContext, ma_IDirectSoundCapture* pDirectSoundCapture, WORD* pChannels, WORD* pBitsPerSample, DWORD* pSampleRate) { + MA_DSCCAPS caps; + WORD bitsPerSample; + DWORD sampleRate; + ma_assert(pContext != NULL); ma_assert(pDirectSoundCapture != NULL); @@ -8945,7 +9251,6 @@ ma_result ma_context_get_format_info_for_IDirectSoundCapture__dsound(ma_context* *pSampleRate = 0; } - MA_DSCCAPS caps; ma_zero_object(&caps); caps.dwSize = sizeof(caps); if (FAILED(ma_IDirectSoundCapture_GetCaps(pDirectSoundCapture, &caps))) { @@ -8956,10 +9261,9 @@ ma_result ma_context_get_format_info_for_IDirectSoundCapture__dsound(ma_context* *pChannels = (WORD)caps.dwChannels; } - // The device can support multiple formats. We just go through the different formats in order of priority and - // pick the first one. This the same type of system as the WinMM backend. - WORD bitsPerSample = 16; - DWORD sampleRate = 48000; + /* The device can support multiple formats. We just go through the different formats in order of priority and pick the first one. This the same type of system as the WinMM backend. */ + bitsPerSample = 16; + sampleRate = 48000; if (caps.dwChannels == 1) { if ((caps.dwFormats & WAVE_FORMAT_48M16) != 0) { @@ -8985,7 +9289,7 @@ ma_result ma_context_get_format_info_for_IDirectSoundCapture__dsound(ma_context* } else if ((caps.dwFormats & WAVE_FORMAT_96M08) != 0) { sampleRate = 96000; } else { - bitsPerSample = 16; // Didn't find it. Just fall back to 16-bit. + bitsPerSample = 16; /* Didn't find it. Just fall back to 16-bit. */ } } } else if (caps.dwChannels == 2) { @@ -9012,7 +9316,7 @@ ma_result ma_context_get_format_info_for_IDirectSoundCapture__dsound(ma_context* } else if ((caps.dwFormats & WAVE_FORMAT_96S08) != 0) { sampleRate = 96000; } else { - bitsPerSample = 16; // Didn't find it. Just fall back to 16-bit. + bitsPerSample = 16; /* Didn't find it. Just fall back to 16-bit. */ } } } @@ -9049,52 +9353,53 @@ typedef struct BOOL CALLBACK ma_context_enumerate_devices_callback__dsound(LPGUID lpGuid, LPCSTR lpcstrDescription, LPCSTR lpcstrModule, LPVOID lpContext) { - (void)lpcstrModule; - ma_context_enumerate_devices_callback_data__dsound* pData = (ma_context_enumerate_devices_callback_data__dsound*)lpContext; - ma_assert(pData != NULL); + ma_device_info deviceInfo; - ma_device_info deviceInfo; ma_zero_object(&deviceInfo); - // ID. + /* ID. */ if (lpGuid != NULL) { ma_copy_memory(deviceInfo.id.dsound, lpGuid, 16); } else { ma_zero_memory(deviceInfo.id.dsound, 16); } - // Name / Description + /* Name / Description */ ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), lpcstrDescription, (size_t)-1); - // Call the callback function, but make sure we stop enumerating if the callee requested so. + /* Call the callback function, but make sure we stop enumerating if the callee requested so. */ + ma_assert(pData != NULL); pData->terminated = !pData->callback(pData->pContext, pData->deviceType, &deviceInfo, pData->pUserData); if (pData->terminated) { - return FALSE; // Stop enumeration. + return FALSE; /* Stop enumeration. */ } else { - return TRUE; // Continue enumeration. + return TRUE; /* Continue enumeration. */ } + + (void)lpcstrModule; } ma_result ma_context_enumerate_devices__dsound(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData) { + ma_context_enumerate_devices_callback_data__dsound data; + ma_assert(pContext != NULL); ma_assert(callback != NULL); - ma_context_enumerate_devices_callback_data__dsound data; data.pContext = pContext; data.callback = callback; data.pUserData = pUserData; data.terminated = MA_FALSE; - // Playback. + /* Playback. */ if (!data.terminated) { data.deviceType = ma_device_type_playback; ((ma_DirectSoundEnumerateAProc)pContext->dsound.DirectSoundEnumerateA)(ma_context_enumerate_devices_callback__dsound, &data); } - // Capture. + /* Capture. */ if (!data.terminated) { data.deviceType = ma_device_type_capture; ((ma_DirectSoundCaptureEnumerateAProc)pContext->dsound.DirectSoundCaptureEnumerateA)(ma_context_enumerate_devices_callback__dsound, &data); @@ -9113,27 +9418,26 @@ typedef struct BOOL CALLBACK ma_context_get_device_info_callback__dsound(LPGUID lpGuid, LPCSTR lpcstrDescription, LPCSTR lpcstrModule, LPVOID lpContext) { - (void)lpcstrModule; - ma_context_get_device_info_callback_data__dsound* pData = (ma_context_get_device_info_callback_data__dsound*)lpContext; ma_assert(pData != NULL); if ((pData->pDeviceID == NULL || ma_is_guid_equal(pData->pDeviceID->dsound, &MA_GUID_NULL)) && (lpGuid == NULL || ma_is_guid_equal(lpGuid, &MA_GUID_NULL))) { - // Default device. + /* Default device. */ ma_strncpy_s(pData->pDeviceInfo->name, sizeof(pData->pDeviceInfo->name), lpcstrDescription, (size_t)-1); pData->found = MA_TRUE; - return FALSE; // Stop enumeration. + return FALSE; /* Stop enumeration. */ } else { - // Not the default device. + /* Not the default device. */ if (lpGuid != NULL) { if (memcmp(pData->pDeviceID->dsound, lpGuid, sizeof(pData->pDeviceID->dsound)) == 0) { ma_strncpy_s(pData->pDeviceInfo->name, sizeof(pData->pDeviceInfo->name), lpcstrDescription, (size_t)-1); pData->found = MA_TRUE; - return FALSE; // Stop enumeration. + return FALSE; /* Stop enumeration. */ } } } + (void)lpcstrModule; return TRUE; } @@ -9145,11 +9449,12 @@ ma_result ma_context_get_device_info__dsound(ma_context* pContext, ma_device_typ } if (pDeviceID != NULL) { - // ID. + ma_context_get_device_info_callback_data__dsound data; + + /* ID. */ ma_copy_memory(pDeviceInfo->id.dsound, pDeviceID->dsound, 16); - // Name / Description. This is retrieved by enumerating over each device until we find that one that matches the input ID. - ma_context_get_device_info_callback_data__dsound data; + /* Name / Description. This is retrieved by enumerating over each device until we find that one that matches the input ID. */ data.pDeviceID = pDeviceID; data.pDeviceInfo = pDeviceInfo; data.found = MA_FALSE; @@ -9163,12 +9468,12 @@ ma_result ma_context_get_device_info__dsound(ma_context* pContext, ma_device_typ return MA_NO_DEVICE; } } else { - // I don't think there's a way to get the name of the default device with DirectSound. In this case we just need to use defaults. + /* I don't think there's a way to get the name of the default device with DirectSound. In this case we just need to use defaults. */ - // ID + /* ID */ ma_zero_memory(pDeviceInfo->id.dsound, 16); - // Name / Description/ + /* Name / Description */ if (deviceType == ma_device_type_playback) { ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); } else { @@ -9176,16 +9481,19 @@ ma_result ma_context_get_device_info__dsound(ma_context* pContext, ma_device_typ } } - // Retrieving detailed information is slightly different depending on the device type. + /* Retrieving detailed information is slightly different depending on the device type. */ if (deviceType == ma_device_type_playback) { - // Playback. + /* Playback. */ ma_IDirectSound* pDirectSound; - ma_result result = ma_context_create_IDirectSound__dsound(pContext, shareMode, pDeviceID, &pDirectSound); + ma_result result; + MA_DSCAPS caps; + ma_uint32 iFormat; + + result = ma_context_create_IDirectSound__dsound(pContext, shareMode, pDeviceID, &pDirectSound); if (result != MA_SUCCESS) { return result; } - MA_DSCAPS caps; ma_zero_object(&caps); caps.dwSize = sizeof(caps); if (FAILED(ma_IDirectSound_GetCaps(pDirectSound, &caps))) { @@ -9193,10 +9501,10 @@ ma_result ma_context_get_device_info__dsound(ma_context* pContext, ma_device_typ } if ((caps.dwFlags & MA_DSCAPS_PRIMARYSTEREO) != 0) { - // It supports at least stereo, but could support more. + /* It supports at least stereo, but could support more. */ WORD channels = 2; - // Look at the speaker configuration to get a better idea on the channel count. + /* Look at the speaker configuration to get a better idea on the channel count. */ DWORD speakerConfig; if (SUCCEEDED(ma_IDirectSound_GetSpeakerConfig(pDirectSound, &speakerConfig))) { ma_get_channels_from_speaker_config__dsound(speakerConfig, &channels, NULL); @@ -9205,18 +9513,20 @@ ma_result ma_context_get_device_info__dsound(ma_context* pContext, ma_device_typ pDeviceInfo->minChannels = channels; pDeviceInfo->maxChannels = channels; } else { - // It does not support stereo, which means we are stuck with mono. + /* It does not support stereo, which means we are stuck with mono. */ pDeviceInfo->minChannels = 1; pDeviceInfo->maxChannels = 1; } - // Sample rate. + /* Sample rate. */ if ((caps.dwFlags & MA_DSCAPS_CONTINUOUSRATE) != 0) { pDeviceInfo->minSampleRate = caps.dwMinSecondarySampleRate; pDeviceInfo->maxSampleRate = caps.dwMaxSecondarySampleRate; - // On my machine the min and max sample rates can return 100 and 200000 respectively. I'd rather these be within - // the range of our standard sample rates so I'm clamping. + /* + On my machine the min and max sample rates can return 100 and 200000 respectively. I'd rather these be within + the range of our standard sample rates so I'm clamping. + */ if (caps.dwMinSecondarySampleRate < MA_MIN_SAMPLE_RATE && caps.dwMaxSecondarySampleRate >= MA_MIN_SAMPLE_RATE) { pDeviceInfo->minSampleRate = MA_MIN_SAMPLE_RATE; } @@ -9224,31 +9534,35 @@ ma_result ma_context_get_device_info__dsound(ma_context* pContext, ma_device_typ pDeviceInfo->maxSampleRate = MA_MAX_SAMPLE_RATE; } } else { - // Only supports a single sample rate. Set both min an max to the same thing. Do not clamp within the standard rates. + /* Only supports a single sample rate. Set both min an max to the same thing. Do not clamp within the standard rates. */ pDeviceInfo->minSampleRate = caps.dwMaxSecondarySampleRate; pDeviceInfo->maxSampleRate = caps.dwMaxSecondarySampleRate; } - // DirectSound can support all formats. - pDeviceInfo->formatCount = ma_format_count - 1; // Minus one because we don't want to include ma_format_unknown. - for (ma_uint32 iFormat = 0; iFormat < pDeviceInfo->formatCount; ++iFormat) { - pDeviceInfo->formats[iFormat] = (ma_format)(iFormat + 1); // +1 to skip over ma_format_unknown. + /* DirectSound can support all formats. */ + pDeviceInfo->formatCount = ma_format_count - 1; /* Minus one because we don't want to include ma_format_unknown. */ + for (iFormat = 0; iFormat < pDeviceInfo->formatCount; ++iFormat) { + pDeviceInfo->formats[iFormat] = (ma_format)(iFormat + 1); /* +1 to skip over ma_format_unknown. */ } ma_IDirectSound_Release(pDirectSound); } else { - // Capture. This is a little different to playback due to the say the supported formats are reported. Technically capture - // devices can support a number of different formats, but for simplicity and consistency with ma_device_init() I'm just - // reporting the best format. + /* + Capture. This is a little different to playback due to the say the supported formats are reported. Technically capture + devices can support a number of different formats, but for simplicity and consistency with ma_device_init() I'm just + reporting the best format. + */ ma_IDirectSoundCapture* pDirectSoundCapture; - ma_result result = ma_context_create_IDirectSoundCapture__dsound(pContext, shareMode, pDeviceID, &pDirectSoundCapture); + ma_result result; + WORD channels; + WORD bitsPerSample; + DWORD sampleRate; + + result = ma_context_create_IDirectSoundCapture__dsound(pContext, shareMode, pDeviceID, &pDirectSoundCapture); if (result != MA_SUCCESS) { return result; } - WORD channels; - WORD bitsPerSample; - DWORD sampleRate; result = ma_context_get_format_info_for_IDirectSoundCapture__dsound(pContext, pDirectSoundCapture, &channels, &bitsPerSample, &sampleRate); if (result != MA_SUCCESS) { ma_IDirectSoundCapture_Release(pDirectSoundCapture); @@ -9289,8 +9603,6 @@ typedef struct BOOL CALLBACK ma_enum_devices_callback__dsound(LPGUID lpGuid, LPCSTR lpcstrDescription, LPCSTR lpcstrModule, LPVOID lpContext) { - (void)lpcstrModule; - ma_device_enum_data__dsound* pData = (ma_device_enum_data__dsound*)lpContext; ma_assert(pData != NULL); @@ -9313,6 +9625,7 @@ BOOL CALLBACK ma_enum_devices_callback__dsound(LPGUID lpGuid, LPCSTR lpcstrDescr pData->deviceCount += 1; } + (void)lpcstrModule; return TRUE; } @@ -9341,12 +9654,13 @@ void ma_device_uninit__dsound(ma_device* pDevice) ma_result ma_config_to_WAVEFORMATEXTENSIBLE(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, const ma_channel* pChannelMap, WAVEFORMATEXTENSIBLE* pWF) { GUID subformat; + switch (format) { case ma_format_u8: case ma_format_s16: case ma_format_s24: - //case ma_format_s24_32: + /*case ma_format_s24_32:*/ case ma_format_s32: { subformat = MA_GUID_KSDATAFORMAT_SUBTYPE_PCM; @@ -9379,13 +9693,12 @@ ma_result ma_config_to_WAVEFORMATEXTENSIBLE(ma_format format, ma_uint32 channels ma_result ma_device_init__dsound(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice) { ma_result result; - - (void)pContext; + ma_uint32 bufferSizeInMilliseconds; ma_assert(pDevice != NULL); ma_zero_object(&pDevice->dsound); - ma_uint32 bufferSizeInMilliseconds = pConfig->bufferSizeInMilliseconds; + bufferSizeInMilliseconds = pConfig->bufferSizeInMilliseconds; if (bufferSizeInMilliseconds == 0) { bufferSizeInMilliseconds = ma_calculate_buffer_size_in_milliseconds_from_frames(pConfig->bufferSizeInFrames, pConfig->sampleRate); } @@ -9404,11 +9717,18 @@ ma_result ma_device_init__dsound(ma_context* pContext, const ma_device_config* p bufferSizeInMilliseconds = pConfig->periods * 20; } - // Unfortunately DirectSound uses different APIs and data structures for playback and catpure devices. We need to initialize - // the capture device first because we'll want to match it's buffer size and period count on the playback side if we're using - // full-duplex mode. + /* + Unfortunately DirectSound uses different APIs and data structures for playback and catpure devices. We need to initialize + the capture device first because we'll want to match it's buffer size and period count on the playback side if we're using + full-duplex mode. + */ if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) { WAVEFORMATEXTENSIBLE wf; + MA_DSCBUFFERDESC descDS; + ma_uint32 bufferSizeInFrames; + char rawdata[1024]; /* <-- Ugly hack to avoid a malloc() due to a crappy DirectSound API. */ + WAVEFORMATEXTENSIBLE* pActualFormat; + result = ma_config_to_WAVEFORMATEXTENSIBLE(pConfig->capture.format, pConfig->capture.channels, pConfig->sampleRate, pConfig->capture.channelMap, &wf); if (result != MA_SUCCESS) { return result; @@ -9432,9 +9752,8 @@ ma_result ma_device_init__dsound(ma_context* pContext, const ma_device_config* p wf.SubFormat = MA_GUID_KSDATAFORMAT_SUBTYPE_PCM; /* The size of the buffer must be a clean multiple of the period count. */ - ma_uint32 bufferSizeInFrames = (ma_calculate_buffer_size_in_frames_from_milliseconds(bufferSizeInMilliseconds, wf.Format.nSamplesPerSec) / pConfig->periods) * pConfig->periods; + bufferSizeInFrames = (ma_calculate_buffer_size_in_frames_from_milliseconds(bufferSizeInMilliseconds, wf.Format.nSamplesPerSec) / pConfig->periods) * pConfig->periods; - MA_DSCBUFFERDESC descDS; ma_zero_object(&descDS); descDS.dwSize = sizeof(descDS); descDS.dwFlags = 0; @@ -9445,9 +9764,8 @@ ma_result ma_device_init__dsound(ma_context* pContext, const ma_device_config* p return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundCapture_CreateCaptureBuffer() failed for capture device.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); } - // Get the _actual_ properties of the buffer. - char rawdata[1024]; - WAVEFORMATEXTENSIBLE* pActualFormat = (WAVEFORMATEXTENSIBLE*)rawdata; + /* Get the _actual_ properties of the buffer. */ + pActualFormat = (WAVEFORMATEXTENSIBLE*)rawdata; if (FAILED(ma_IDirectSoundCaptureBuffer_GetFormat((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, (WAVEFORMATEX*)pActualFormat, sizeof(rawdata), NULL))) { ma_device_uninit__dsound(pDevice); return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to retrieve the actual format of the capture device's buffer.", MA_FORMAT_NOT_SUPPORTED); @@ -9457,7 +9775,7 @@ ma_result ma_device_init__dsound(ma_context* pContext, const ma_device_config* p pDevice->capture.internalChannels = pActualFormat->Format.nChannels; pDevice->capture.internalSampleRate = pActualFormat->Format.nSamplesPerSec; - // Get the internal channel map based on the channel mask. + /* Get the internal channel map based on the channel mask. */ if (pActualFormat->Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) { ma_channel_mask_to_channel_map__win32(pActualFormat->dwChannelMask, pDevice->capture.internalChannels, pDevice->capture.internalChannelMap); } else { @@ -9485,6 +9803,13 @@ ma_result ma_device_init__dsound(ma_context* pContext, const ma_device_config* p if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) { WAVEFORMATEXTENSIBLE wf; + MA_DSBUFFERDESC descDSPrimary; + MA_DSCAPS caps; + char rawdata[1024]; /* <-- Ugly hack to avoid a malloc() due to a crappy DirectSound API. */ + WAVEFORMATEXTENSIBLE* pActualFormat; + ma_uint32 bufferSizeInFrames; + MA_DSBUFFERDESC descDS; + result = ma_config_to_WAVEFORMATEXTENSIBLE(pConfig->playback.format, pConfig->playback.channels, pConfig->sampleRate, pConfig->playback.channelMap, &wf); if (result != MA_SUCCESS) { return result; @@ -9496,7 +9821,6 @@ ma_result ma_device_init__dsound(ma_context* pContext, const ma_device_config* p return result; } - MA_DSBUFFERDESC descDSPrimary; ma_zero_object(&descDSPrimary); descDSPrimary.dwSize = sizeof(MA_DSBUFFERDESC); descDSPrimary.dwFlags = MA_DSBCAPS_PRIMARYBUFFER | MA_DSBCAPS_CTRLVOLUME; @@ -9506,8 +9830,7 @@ ma_result ma_device_init__dsound(ma_context* pContext, const ma_device_config* p } - // We may want to make some adjustments to the format if we are using defaults. - MA_DSCAPS caps; + /* We may want to make some adjustments to the format if we are using defaults. */ ma_zero_object(&caps); caps.dwSize = sizeof(caps); if (FAILED(ma_IDirectSound_GetCaps((ma_IDirectSound*)pDevice->dsound.pPlayback, &caps))) { @@ -9517,22 +9840,23 @@ ma_result ma_device_init__dsound(ma_context* pContext, const ma_device_config* p if (pDevice->playback.usingDefaultChannels) { if ((caps.dwFlags & MA_DSCAPS_PRIMARYSTEREO) != 0) { - // It supports at least stereo, but could support more. + DWORD speakerConfig; + + /* It supports at least stereo, but could support more. */ wf.Format.nChannels = 2; - // Look at the speaker configuration to get a better idea on the channel count. - DWORD speakerConfig; + /* Look at the speaker configuration to get a better idea on the channel count. */ if (SUCCEEDED(ma_IDirectSound_GetSpeakerConfig((ma_IDirectSound*)pDevice->dsound.pPlayback, &speakerConfig))) { ma_get_channels_from_speaker_config__dsound(speakerConfig, &wf.Format.nChannels, &wf.dwChannelMask); } } else { - // It does not support stereo, which means we are stuck with mono. + /* It does not support stereo, which means we are stuck with mono. */ wf.Format.nChannels = 1; } } if (pDevice->usingDefaultSampleRate) { - // We base the sample rate on the values returned by GetCaps(). + /* We base the sample rate on the values returned by GetCaps(). */ if ((caps.dwFlags & MA_DSCAPS_CONTINUOUSRATE) != 0) { wf.Format.nSamplesPerSec = ma_get_best_sample_rate_within_range(caps.dwMinSecondarySampleRate, caps.dwMaxSecondarySampleRate); } else { @@ -9543,19 +9867,20 @@ ma_result ma_device_init__dsound(ma_context* pContext, const ma_device_config* p wf.Format.nBlockAlign = (wf.Format.nChannels * wf.Format.wBitsPerSample) / 8; wf.Format.nAvgBytesPerSec = wf.Format.nBlockAlign * wf.Format.nSamplesPerSec; - // From MSDN: - // - // The method succeeds even if the hardware does not support the requested format; DirectSound sets the buffer to the closest - // supported format. To determine whether this has happened, an application can call the GetFormat method for the primary buffer - // and compare the result with the format that was requested with the SetFormat method. + /* + From MSDN: + + The method succeeds even if the hardware does not support the requested format; DirectSound sets the buffer to the closest + supported format. To determine whether this has happened, an application can call the GetFormat method for the primary buffer + and compare the result with the format that was requested with the SetFormat method. + */ if (FAILED(ma_IDirectSoundBuffer_SetFormat((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackPrimaryBuffer, (WAVEFORMATEX*)&wf))) { ma_device_uninit__dsound(pDevice); return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to set format of playback device's primary buffer.", MA_FORMAT_NOT_SUPPORTED); } - // Get the _actual_ properties of the buffer. - char rawdata[1024]; - WAVEFORMATEXTENSIBLE* pActualFormat = (WAVEFORMATEXTENSIBLE*)rawdata; + /* Get the _actual_ properties of the buffer. */ + pActualFormat = (WAVEFORMATEXTENSIBLE*)rawdata; if (FAILED(ma_IDirectSoundBuffer_GetFormat((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackPrimaryBuffer, (WAVEFORMATEX*)pActualFormat, sizeof(rawdata), NULL))) { ma_device_uninit__dsound(pDevice); return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to retrieve the actual format of the playback device's primary buffer.", MA_FORMAT_NOT_SUPPORTED); @@ -9565,7 +9890,7 @@ ma_result ma_device_init__dsound(ma_context* pContext, const ma_device_config* p pDevice->playback.internalChannels = pActualFormat->Format.nChannels; pDevice->playback.internalSampleRate = pActualFormat->Format.nSamplesPerSec; - // Get the internal channel map based on the channel mask. + /* Get the internal channel map based on the channel mask. */ if (pActualFormat->Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) { ma_channel_mask_to_channel_map__win32(pActualFormat->dwChannelMask, pDevice->playback.internalChannels, pDevice->playback.internalChannelMap); } else { @@ -9573,22 +9898,23 @@ ma_result ma_device_init__dsound(ma_context* pContext, const ma_device_config* p } /* The size of the buffer must be a clean multiple of the period count. */ - ma_uint32 bufferSizeInFrames = (ma_calculate_buffer_size_in_frames_from_milliseconds(bufferSizeInMilliseconds, pDevice->playback.internalSampleRate) / pConfig->periods) * pConfig->periods; - - // Meaning of dwFlags (from MSDN): - // - // DSBCAPS_CTRLPOSITIONNOTIFY - // The buffer has position notification capability. - // - // DSBCAPS_GLOBALFOCUS - // With this flag set, an application using DirectSound can continue to play its buffers if the user switches focus to - // another application, even if the new application uses DirectSound. - // - // DSBCAPS_GETCURRENTPOSITION2 - // In the first version of DirectSound, the play cursor was significantly ahead of the actual playing sound on emulated - // sound cards; it was directly behind the write cursor. Now, if the DSBCAPS_GETCURRENTPOSITION2 flag is specified, the - // application can get a more accurate play cursor. - MA_DSBUFFERDESC descDS; + bufferSizeInFrames = (ma_calculate_buffer_size_in_frames_from_milliseconds(bufferSizeInMilliseconds, pDevice->playback.internalSampleRate) / pConfig->periods) * pConfig->periods; + + /* + Meaning of dwFlags (from MSDN): + + DSBCAPS_CTRLPOSITIONNOTIFY + The buffer has position notification capability. + + DSBCAPS_GLOBALFOCUS + With this flag set, an application using DirectSound can continue to play its buffers if the user switches focus to + another application, even if the new application uses DirectSound. + + DSBCAPS_GETCURRENTPOSITION2 + In the first version of DirectSound, the play cursor was significantly ahead of the actual playing sound on emulated + sound cards; it was directly behind the write cursor. Now, if the DSBCAPS_GETCURRENTPOSITION2 flag is specified, the + application can get a more accurate play cursor. + */ ma_zero_object(&descDS); descDS.dwSize = sizeof(descDS); descDS.dwFlags = MA_DSBCAPS_CTRLPOSITIONNOTIFY | MA_DSBCAPS_GLOBALFOCUS | MA_DSBCAPS_GETCURRENTPOSITION2; @@ -9604,6 +9930,7 @@ ma_result ma_device_init__dsound(ma_context* pContext, const ma_device_config* p pDevice->playback.internalPeriods = pConfig->periods; } + (void)pContext; return MA_SUCCESS; } @@ -9756,7 +10083,7 @@ ma_result ma_device_main_loop__dsound(ma_device* pDevice) } #ifdef MA_DEBUG_OUTPUT - //printf("[DirectSound] (Duplex/Playback) physicalPlayCursorInBytes=%d, availableBytesPlayback=%d\n", physicalPlayCursorInBytes, availableBytesPlayback); + /*printf("[DirectSound] (Duplex/Playback) physicalPlayCursorInBytes=%d, availableBytesPlayback=%d\n", physicalPlayCursorInBytes, availableBytesPlayback);*/ #endif /* If there's no room available for writing we need to wait for more. */ @@ -9900,8 +10227,8 @@ ma_result ma_device_main_loop__dsound(ma_device* pDevice) } #ifdef MA_DEBUG_OUTPUT - //printf("[DirectSound] (Capture) physicalCaptureCursorInBytes=%d, physicalReadCursorInBytes=%d\n", physicalCaptureCursorInBytes, physicalReadCursorInBytes); - //printf("[DirectSound] (Capture) lockOffsetInBytesCapture=%d, lockSizeInBytesCapture=%d\n", lockOffsetInBytesCapture, lockSizeInBytesCapture); + /*printf("[DirectSound] (Capture) physicalCaptureCursorInBytes=%d, physicalReadCursorInBytes=%d\n", physicalCaptureCursorInBytes, physicalReadCursorInBytes);*/ + /*printf("[DirectSound] (Capture) lockOffsetInBytesCapture=%d, lockSizeInBytesCapture=%d\n", lockOffsetInBytesCapture, lockSizeInBytesCapture);*/ #endif if (lockSizeInBytesCapture < (pDevice->capture.internalBufferSizeInFrames/pDevice->capture.internalPeriods)) { @@ -9976,7 +10303,7 @@ ma_result ma_device_main_loop__dsound(ma_device* pDevice) } #ifdef MA_DEBUG_OUTPUT - //printf("[DirectSound] (Playback) physicalPlayCursorInBytes=%d, availableBytesPlayback=%d\n", physicalPlayCursorInBytes, availableBytesPlayback); + /*printf("[DirectSound] (Playback) physicalPlayCursorInBytes=%d, availableBytesPlayback=%d\n", physicalPlayCursorInBytes, availableBytesPlayback);*/ #endif /* If there's no room available for writing we need to wait for more. */ @@ -10148,16 +10475,18 @@ ma_result ma_context_init__dsound(const ma_context_config* pConfig, ma_context* -/////////////////////////////////////////////////////////////////////////////// -// -// WinMM Backend -// -/////////////////////////////////////////////////////////////////////////////// +/****************************************************************************** + +WinMM Backend + +******************************************************************************/ #ifdef MA_HAS_WINMM -// Some older compilers don't have WAVEOUTCAPS2A and WAVEINCAPS2A, so we'll need to write this ourselves. These structures -// are exactly the same as the older ones but they have a few GUIDs for manufacturer/product/name identification. I'm keeping -// the names the same as the Win32 library for consistency, but namespaced to avoid naming conflicts with the Win32 version. +/* +Some older compilers don't have WAVEOUTCAPS2A and WAVEINCAPS2A, so we'll need to write this ourselves. These structures +are exactly the same as the older ones but they have a few GUIDs for manufacturer/product/name identification. I'm keeping +the names the same as the Win32 library for consistency, but namespaced to avoid naming conflicts with the Win32 version. +*/ typedef struct { WORD wMid; @@ -10221,11 +10550,13 @@ ma_result ma_result_from_MMRESULT(MMRESULT resultMM) char* ma_find_last_character(char* str, char ch) { + char* last; + if (str == NULL) { return NULL; } - char* last = NULL; + last = NULL; while (*str != '\0') { if (*str == ch) { last = str; @@ -10238,8 +10569,10 @@ char* ma_find_last_character(char* str, char ch) } -// Our own "WAVECAPS" structure that contains generic information shared between WAVEOUTCAPS2 and WAVEINCAPS2 so -// we can do things generically and typesafely. Names are being kept the same for consistency. +/* +Our own "WAVECAPS" structure that contains generic information shared between WAVEOUTCAPS2 and WAVEINCAPS2 so +we can do things generically and typesafely. Names are being kept the same for consistency. +*/ typedef struct { CHAR szPname[MAXPNAMELEN]; @@ -10250,6 +10583,9 @@ typedef struct ma_result ma_get_best_info_from_formats_flags__winmm(DWORD dwFormats, WORD channels, WORD* pBitsPerSample, DWORD* pSampleRate) { + WORD bitsPerSample = 0; + DWORD sampleRate = 0; + if (pBitsPerSample) { *pBitsPerSample = 0; } @@ -10257,9 +10593,6 @@ ma_result ma_get_best_info_from_formats_flags__winmm(DWORD dwFormats, WORD chann *pSampleRate = 0; } - WORD bitsPerSample = 0; - DWORD sampleRate = 0; - if (channels == 1) { bitsPerSample = 16; if ((dwFormats & WAVE_FORMAT_48M16) != 0) { @@ -10406,47 +10739,55 @@ ma_result ma_formats_flags_to_WAVEFORMATEX__winmm(DWORD dwFormats, WORD channels ma_result ma_context_get_device_info_from_WAVECAPS(ma_context* pContext, MA_WAVECAPSA* pCaps, ma_device_info* pDeviceInfo) { + WORD bitsPerSample; + DWORD sampleRate; + ma_result result; + ma_assert(pContext != NULL); ma_assert(pCaps != NULL); ma_assert(pDeviceInfo != NULL); - // Name / Description - // - // Unfortunately the name specified in WAVE(OUT/IN)CAPS2 is limited to 31 characters. This results in an unprofessional looking - // situation where the names of the devices are truncated. To help work around this, we need to look at the name GUID and try - // looking in the registry for the full name. If we can't find it there, we need to just fall back to the default name. + /* + Name / Description + + Unfortunately the name specified in WAVE(OUT/IN)CAPS2 is limited to 31 characters. This results in an unprofessional looking + situation where the names of the devices are truncated. To help work around this, we need to look at the name GUID and try + looking in the registry for the full name. If we can't find it there, we need to just fall back to the default name. + */ - // Set the default to begin with. + /* Set the default to begin with. */ ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), pCaps->szPname, (size_t)-1); - // Now try the registry. There's a few things to consider here: - // - The name GUID can be null, in which we case we just need to stick to the original 31 characters. - // - If the name GUID is not present in the registry we'll also need to stick to the original 31 characters. - // - I like consistency, so I want the returned device names to be consistent with those returned by WASAPI and DirectSound. The - // problem, however is that WASAPI and DirectSound use " ()" format (such as "Speakers (High Definition Audio)"), - // but WinMM does not specificy the component name. From my admittedly limited testing, I've notice the component name seems to - // usually fit within the 31 characters of the fixed sized buffer, so what I'm going to do is parse that string for the component - // name, and then concatenate the name from the registry. + /* + Now try the registry. There's a few things to consider here: + - The name GUID can be null, in which we case we just need to stick to the original 31 characters. + - If the name GUID is not present in the registry we'll also need to stick to the original 31 characters. + - I like consistency, so I want the returned device names to be consistent with those returned by WASAPI and DirectSound. The + problem, however is that WASAPI and DirectSound use " ()" format (such as "Speakers (High Definition Audio)"), + but WinMM does not specificy the component name. From my admittedly limited testing, I've notice the component name seems to + usually fit within the 31 characters of the fixed sized buffer, so what I'm going to do is parse that string for the component + name, and then concatenate the name from the registry. + */ if (!ma_is_guid_equal(&pCaps->NameGuid, &MA_GUID_NULL)) { wchar_t guidStrW[256]; if (((MA_PFN_StringFromGUID2)pContext->win32.StringFromGUID2)(&pCaps->NameGuid, guidStrW, ma_countof(guidStrW)) > 0) { char guidStr[256]; + char keyStr[1024]; + HKEY hKey; + WideCharToMultiByte(CP_UTF8, 0, guidStrW, -1, guidStr, sizeof(guidStr), 0, FALSE); - char keyStr[1024]; ma_strcpy_s(keyStr, sizeof(keyStr), "SYSTEM\\CurrentControlSet\\Control\\MediaCategories\\"); ma_strcat_s(keyStr, sizeof(keyStr), guidStr); - HKEY hKey; - LONG result = ((MA_PFN_RegOpenKeyExA)pContext->win32.RegOpenKeyExA)(HKEY_LOCAL_MACHINE, keyStr, 0, KEY_READ, &hKey); - if (result == ERROR_SUCCESS) { + if (((MA_PFN_RegOpenKeyExA)pContext->win32.RegOpenKeyExA)(HKEY_LOCAL_MACHINE, keyStr, 0, KEY_READ, &hKey) == ERROR_SUCCESS) { BYTE nameFromReg[512]; DWORD nameFromRegSize = sizeof(nameFromReg); result = ((MA_PFN_RegQueryValueExA)pContext->win32.RegQueryValueExA)(hKey, "Name", 0, NULL, (LPBYTE)nameFromReg, (LPDWORD)&nameFromRegSize); ((MA_PFN_RegCloseKey)pContext->win32.RegCloseKey)(hKey); if (result == ERROR_SUCCESS) { - // We have the value from the registry, so now we need to construct the name string. + /* We have the value from the registry, so now we need to construct the name string. */ char name[1024]; if (ma_strcpy_s(name, sizeof(name), pDeviceInfo->name) == 0) { char* nameBeg = ma_find_last_character(name, '('); @@ -10454,7 +10795,7 @@ ma_result ma_context_get_device_info_from_WAVECAPS(ma_context* pContext, MA_WAVE size_t leadingLen = (nameBeg - name); ma_strncpy_s(nameBeg + 1, sizeof(name) - leadingLen, (const char*)nameFromReg, (size_t)-1); - // The closing ")", if it can fit. + /* The closing ")", if it can fit. */ if (leadingLen + nameFromRegSize < sizeof(name)-1) { ma_strcat_s(name, sizeof(name), ")"); } @@ -10467,10 +10808,8 @@ ma_result ma_context_get_device_info_from_WAVECAPS(ma_context* pContext, MA_WAVE } } - - WORD bitsPerSample; - DWORD sampleRate; - ma_result result = ma_get_best_info_from_formats_flags__winmm(pCaps->dwFormats, pCaps->wChannels, &bitsPerSample, &sampleRate); + + result = ma_get_best_info_from_formats_flags__winmm(pCaps->dwFormats, pCaps->wChannels, &bitsPerSample, &sampleRate); if (result != MA_SUCCESS) { return result; } @@ -10497,11 +10836,12 @@ ma_result ma_context_get_device_info_from_WAVECAPS(ma_context* pContext, MA_WAVE ma_result ma_context_get_device_info_from_WAVEOUTCAPS2(ma_context* pContext, MA_WAVEOUTCAPS2A* pCaps, ma_device_info* pDeviceInfo) { + MA_WAVECAPSA caps; + ma_assert(pContext != NULL); ma_assert(pCaps != NULL); ma_assert(pDeviceInfo != NULL); - MA_WAVECAPSA caps; ma_copy_memory(caps.szPname, pCaps->szPname, sizeof(caps.szPname)); caps.dwFormats = pCaps->dwFormats; caps.wChannels = pCaps->wChannels; @@ -10511,11 +10851,12 @@ ma_result ma_context_get_device_info_from_WAVEOUTCAPS2(ma_context* pContext, MA_ ma_result ma_context_get_device_info_from_WAVEINCAPS2(ma_context* pContext, MA_WAVEINCAPS2A* pCaps, ma_device_info* pDeviceInfo) { + MA_WAVECAPSA caps; + ma_assert(pContext != NULL); ma_assert(pCaps != NULL); ma_assert(pDeviceInfo != NULL); - MA_WAVECAPSA caps; ma_copy_memory(caps.szPname, pCaps->szPname, sizeof(caps.szPname)); caps.dwFormats = pCaps->dwFormats; caps.wChannels = pCaps->wChannels; @@ -10536,44 +10877,57 @@ ma_bool32 ma_context_is_device_id_equal__winmm(ma_context* pContext, const ma_de ma_result ma_context_enumerate_devices__winmm(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData) { + UINT playbackDeviceCount; + UINT captureDeviceCount; + UINT iPlaybackDevice; + UINT iCaptureDevice; + ma_assert(pContext != NULL); ma_assert(callback != NULL); - // Playback. - UINT playbackDeviceCount = ((MA_PFN_waveOutGetNumDevs)pContext->winmm.waveOutGetNumDevs)(); - for (UINT iPlaybackDevice = 0; iPlaybackDevice < playbackDeviceCount; ++iPlaybackDevice) { + /* Playback. */ + playbackDeviceCount = ((MA_PFN_waveOutGetNumDevs)pContext->winmm.waveOutGetNumDevs)(); + for (iPlaybackDevice = 0; iPlaybackDevice < playbackDeviceCount; ++iPlaybackDevice) { + MMRESULT result; MA_WAVEOUTCAPS2A caps; + ma_zero_object(&caps); - MMRESULT result = ((MA_PFN_waveOutGetDevCapsA)pContext->winmm.waveOutGetDevCapsA)(iPlaybackDevice, (WAVEOUTCAPSA*)&caps, sizeof(caps)); + + result = ((MA_PFN_waveOutGetDevCapsA)pContext->winmm.waveOutGetDevCapsA)(iPlaybackDevice, (WAVEOUTCAPSA*)&caps, sizeof(caps)); if (result == MMSYSERR_NOERROR) { ma_device_info deviceInfo; + ma_zero_object(&deviceInfo); deviceInfo.id.winmm = iPlaybackDevice; if (ma_context_get_device_info_from_WAVEOUTCAPS2(pContext, &caps, &deviceInfo) == MA_SUCCESS) { ma_bool32 cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData); if (cbResult == MA_FALSE) { - return MA_SUCCESS; // Enumeration was stopped. + return MA_SUCCESS; /* Enumeration was stopped. */ } } } } - // Capture. - UINT captureDeviceCount = ((MA_PFN_waveInGetNumDevs)pContext->winmm.waveInGetNumDevs)(); - for (UINT iCaptureDevice = 0; iCaptureDevice < captureDeviceCount; ++iCaptureDevice) { + /* Capture. */ + captureDeviceCount = ((MA_PFN_waveInGetNumDevs)pContext->winmm.waveInGetNumDevs)(); + for (iCaptureDevice = 0; iCaptureDevice < captureDeviceCount; ++iCaptureDevice) { + MMRESULT result; MA_WAVEINCAPS2A caps; + ma_zero_object(&caps); - MMRESULT result = ((MA_PFN_waveInGetDevCapsA)pContext->winmm.waveInGetDevCapsA)(iCaptureDevice, (WAVEINCAPSA*)&caps, sizeof(caps)); + + result = ((MA_PFN_waveInGetDevCapsA)pContext->winmm.waveInGetDevCapsA)(iCaptureDevice, (WAVEINCAPSA*)&caps, sizeof(caps)); if (result == MMSYSERR_NOERROR) { ma_device_info deviceInfo; + ma_zero_object(&deviceInfo); deviceInfo.id.winmm = iCaptureDevice; if (ma_context_get_device_info_from_WAVEINCAPS2(pContext, &caps, &deviceInfo) == MA_SUCCESS) { ma_bool32 cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData); if (cbResult == MA_FALSE) { - return MA_SUCCESS; // Enumeration was stopped. + return MA_SUCCESS; /* Enumeration was stopped. */ } } } @@ -10584,13 +10938,15 @@ ma_result ma_context_enumerate_devices__winmm(ma_context* pContext, ma_enum_devi ma_result ma_context_get_device_info__winmm(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_share_mode shareMode, ma_device_info* pDeviceInfo) { + UINT winMMDeviceID; + ma_assert(pContext != NULL); if (shareMode == ma_share_mode_exclusive) { return MA_SHARE_MODE_NOT_SUPPORTED; } - UINT winMMDeviceID = 0; + winMMDeviceID = 0; if (pDeviceID != NULL) { winMMDeviceID = (UINT)pDeviceID->winmm; } @@ -10598,16 +10954,22 @@ ma_result ma_context_get_device_info__winmm(ma_context* pContext, ma_device_type pDeviceInfo->id.winmm = winMMDeviceID; if (deviceType == ma_device_type_playback) { + MMRESULT result; MA_WAVEOUTCAPS2A caps; + ma_zero_object(&caps); - MMRESULT result = ((MA_PFN_waveOutGetDevCapsA)pContext->winmm.waveOutGetDevCapsA)(winMMDeviceID, (WAVEOUTCAPSA*)&caps, sizeof(caps)); + + result = ((MA_PFN_waveOutGetDevCapsA)pContext->winmm.waveOutGetDevCapsA)(winMMDeviceID, (WAVEOUTCAPSA*)&caps, sizeof(caps)); if (result == MMSYSERR_NOERROR) { return ma_context_get_device_info_from_WAVEOUTCAPS2(pContext, &caps, pDeviceInfo); } } else { + MMRESULT result; MA_WAVEINCAPS2A caps; + ma_zero_object(&caps); - MMRESULT result = ((MA_PFN_waveInGetDevCapsA)pContext->winmm.waveInGetDevCapsA)(winMMDeviceID, (WAVEINCAPSA*)&caps, sizeof(caps)); + + result = ((MA_PFN_waveInGetDevCapsA)pContext->winmm.waveInGetDevCapsA)(winMMDeviceID, (WAVEINCAPSA*)&caps, sizeof(caps)); if (result == MMSYSERR_NOERROR) { return ma_context_get_device_info_from_WAVEINCAPS2(pContext, &caps, pDeviceInfo); } @@ -10634,7 +10996,7 @@ void ma_device_uninit__winmm(ma_device* pDevice) ma_free(pDevice->winmm._pHeapData); - ma_zero_object(&pDevice->winmm); // Safety. + ma_zero_object(&pDevice->winmm); /* Safety. */ } ma_result ma_device_init__winmm(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice) @@ -10645,6 +11007,7 @@ ma_result ma_device_init__winmm(ma_context* pContext, const ma_device_config* pC ma_uint32 heapSize; UINT winMMDeviceIDPlayback = 0; UINT winMMDeviceIDCapture = 0; + ma_uint32 bufferSizeInMilliseconds; ma_assert(pDevice != NULL); ma_zero_object(&pDevice->winmm); @@ -10655,7 +11018,7 @@ ma_result ma_device_init__winmm(ma_context* pContext, const ma_device_config* pC return MA_SHARE_MODE_NOT_SUPPORTED; } - ma_uint32 bufferSizeInMilliseconds = pConfig->bufferSizeInMilliseconds; + bufferSizeInMilliseconds = pConfig->bufferSizeInMilliseconds; if (bufferSizeInMilliseconds == 0) { bufferSizeInMilliseconds = ma_calculate_buffer_size_in_milliseconds_from_frames(pConfig->bufferSizeInFrames, pConfig->sampleRate); } @@ -10677,20 +11040,20 @@ ma_result ma_device_init__winmm(ma_context* pContext, const ma_device_config* pC winMMDeviceIDCapture = (UINT)pConfig->capture.pDeviceID->winmm; } - // The capture device needs to be initialized first. + /* The capture device needs to be initialized first. */ if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) { WAVEINCAPSA caps; WAVEFORMATEX wf; MMRESULT resultMM; - // We use an event to know when a new fragment needs to be enqueued. + /* We use an event to know when a new fragment needs to be enqueued. */ pDevice->winmm.hEventCapture = (ma_handle)CreateEvent(NULL, TRUE, TRUE, NULL); if (pDevice->winmm.hEventCapture == NULL) { errorMsg = "[WinMM] Failed to create event for fragment enqueing for the capture device.", errorCode = MA_FAILED_TO_CREATE_EVENT; goto on_error; } - // The format should be based on the device's actual format. + /* The format should be based on the device's actual format. */ if (((MA_PFN_waveInGetDevCapsA)pContext->winmm.waveInGetDevCapsA)(winMMDeviceIDCapture, &caps, sizeof(caps)) != MMSYSERR_NOERROR) { errorMsg = "[WinMM] Failed to retrieve internal device caps.", errorCode = MA_FORMAT_NOT_SUPPORTED; goto on_error; @@ -10721,14 +11084,14 @@ ma_result ma_device_init__winmm(ma_context* pContext, const ma_device_config* pC WAVEFORMATEX wf; MMRESULT resultMM; - // We use an event to know when a new fragment needs to be enqueued. + /* We use an event to know when a new fragment needs to be enqueued. */ pDevice->winmm.hEventPlayback = (ma_handle)CreateEvent(NULL, TRUE, TRUE, NULL); if (pDevice->winmm.hEventPlayback == NULL) { errorMsg = "[WinMM] Failed to create event for fragment enqueing for the playback device.", errorCode = MA_FAILED_TO_CREATE_EVENT; goto on_error; } - // The format should be based on the device's actual format. + /* The format should be based on the device's actual format. */ if (((MA_PFN_waveOutGetDevCapsA)pContext->winmm.waveOutGetDevCapsA)(winMMDeviceIDPlayback, &caps, sizeof(caps)) != MMSYSERR_NOERROR) { errorMsg = "[WinMM] Failed to retrieve internal device caps.", errorCode = MA_FORMAT_NOT_SUPPORTED; goto on_error; @@ -10754,9 +11117,11 @@ ma_result ma_device_init__winmm(ma_context* pContext, const ma_device_config* pC pDevice->playback.internalBufferSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(bufferSizeInMilliseconds, pDevice->playback.internalSampleRate); } - // The heap allocated data is allocated like so: - // - // [Capture WAVEHDRs][Playback WAVEHDRs][Capture Intermediary Buffer][Playback Intermediary Buffer] + /* + The heap allocated data is allocated like so: + + [Capture WAVEHDRs][Playback WAVEHDRs][Capture Intermediary Buffer][Playback Intermediary Buffer] + */ heapSize = 0; if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) { heapSize += sizeof(WAVEHDR)*pDevice->capture.internalPeriods + (pDevice->capture.internalBufferSizeInFrames*ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels)); @@ -10774,6 +11139,8 @@ ma_result ma_device_init__winmm(ma_context* pContext, const ma_device_config* pC ma_zero_memory(pDevice->winmm._pHeapData, heapSize); if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) { + ma_uint32 iPeriod; + if (pConfig->deviceType == ma_device_type_capture) { pDevice->winmm.pWAVEHDRCapture = pDevice->winmm._pHeapData; pDevice->winmm.pIntermediaryBufferCapture = pDevice->winmm._pHeapData + (sizeof(WAVEHDR)*(pDevice->capture.internalPeriods)); @@ -10783,7 +11150,7 @@ ma_result ma_device_init__winmm(ma_context* pContext, const ma_device_config* pC } /* Prepare headers. */ - for (ma_uint32 iPeriod = 0; iPeriod < pDevice->capture.internalPeriods; ++iPeriod) { + for (iPeriod = 0; iPeriod < pDevice->capture.internalPeriods; ++iPeriod) { ma_uint32 fragmentSizeInBytes = ma_get_fragment_size_in_bytes(pDevice->capture.internalBufferSizeInFrames, pDevice->capture.internalPeriods, pDevice->capture.internalFormat, pDevice->capture.internalChannels); ((WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod].lpData = (LPSTR)(pDevice->winmm.pIntermediaryBufferCapture + (fragmentSizeInBytes*iPeriod)); @@ -10800,6 +11167,8 @@ ma_result ma_device_init__winmm(ma_context* pContext, const ma_device_config* pC } } if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) { + ma_uint32 iPeriod; + if (pConfig->deviceType == ma_device_type_playback) { pDevice->winmm.pWAVEHDRPlayback = pDevice->winmm._pHeapData; pDevice->winmm.pIntermediaryBufferPlayback = pDevice->winmm._pHeapData + (sizeof(WAVEHDR)*pDevice->playback.internalPeriods); @@ -10809,7 +11178,7 @@ ma_result ma_device_init__winmm(ma_context* pContext, const ma_device_config* pC } /* Prepare headers. */ - for (ma_uint32 iPeriod = 0; iPeriod < pDevice->playback.internalPeriods; ++iPeriod) { + for (iPeriod = 0; iPeriod < pDevice->playback.internalPeriods; ++iPeriod) { ma_uint32 fragmentSizeInBytes = ma_get_fragment_size_in_bytes(pDevice->playback.internalBufferSizeInFrames, pDevice->playback.internalPeriods, pDevice->playback.internalFormat, pDevice->playback.internalChannels); ((WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod].lpData = (LPSTR)(pDevice->winmm.pIntermediaryBufferPlayback + (fragmentSizeInBytes*iPeriod)); @@ -10831,7 +11200,8 @@ ma_result ma_device_init__winmm(ma_context* pContext, const ma_device_config* pC on_error: if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { if (pDevice->winmm.pWAVEHDRCapture != NULL) { - for (ma_uint32 iPeriod = 0; iPeriod < pDevice->capture.internalPeriods; ++iPeriod) { + ma_uint32 iPeriod; + for (iPeriod = 0; iPeriod < pDevice->capture.internalPeriods; ++iPeriod) { ((MA_PFN_waveInUnprepareHeader)pContext->winmm.waveInUnprepareHeader)((HWAVEIN)pDevice->winmm.hDeviceCapture, &((WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod], sizeof(WAVEHDR)); } } @@ -10841,7 +11211,8 @@ on_error: if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { if (pDevice->winmm.pWAVEHDRCapture != NULL) { - for (ma_uint32 iPeriod = 0; iPeriod < pDevice->playback.internalPeriods; ++iPeriod) { + ma_uint32 iPeriod; + for (iPeriod = 0; iPeriod < pDevice->playback.internalPeriods; ++iPeriod) { ((MA_PFN_waveOutUnprepareHeader)pContext->winmm.waveOutUnprepareHeader)((HWAVEOUT)pDevice->winmm.hDevicePlayback, &((WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod], sizeof(WAVEHDR)); } } @@ -10855,6 +11226,8 @@ on_error: ma_result ma_device_stop__winmm(ma_device* pDevice) { + MMRESULT resultMM; + ma_assert(pDevice != NULL); if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { @@ -10862,7 +11235,7 @@ ma_result ma_device_stop__winmm(ma_device* pDevice) return MA_INVALID_ARGS; } - MMRESULT resultMM = ((MA_PFN_waveInReset)pDevice->pContext->winmm.waveInReset)((HWAVEIN)pDevice->winmm.hDeviceCapture); + resultMM = ((MA_PFN_waveInReset)pDevice->pContext->winmm.waveInReset)((HWAVEIN)pDevice->winmm.hDeviceCapture); if (resultMM != MMSYSERR_NOERROR) { ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WinMM] WARNING: Failed to reset capture device.", ma_result_from_MMRESULT(resultMM)); } @@ -10873,7 +11246,7 @@ ma_result ma_device_stop__winmm(ma_device* pDevice) return MA_INVALID_ARGS; } - MMRESULT resultMM = ((MA_PFN_waveOutReset)pDevice->pContext->winmm.waveOutReset)((HWAVEOUT)pDevice->winmm.hDevicePlayback); + resultMM = ((MA_PFN_waveOutReset)pDevice->pContext->winmm.waveOutReset)((HWAVEOUT)pDevice->winmm.hDevicePlayback); if (resultMM != MMSYSERR_NOERROR) { ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WinMM] WARNING: Failed to reset playback device.", ma_result_from_MMRESULT(resultMM)); } @@ -10888,11 +11261,13 @@ ma_result ma_device_write__winmm(ma_device* pDevice, const void* pPCMFrames, ma_ ma_result result = MA_SUCCESS; MMRESULT resultMM; ma_uint32 totalFramesWritten; - WAVEHDR* pWAVEHDR = (WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback; + WAVEHDR* pWAVEHDR; ma_assert(pDevice != NULL); ma_assert(pPCMFrames != NULL); + pWAVEHDR = (WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback; + /* Keep processing as much data as possible. */ totalFramesWritten = 0; while (totalFramesWritten < frameCount) { @@ -10968,21 +11343,25 @@ ma_result ma_device_write__winmm(ma_device* pDevice, const void* pPCMFrames, ma_ ma_result ma_device_read__winmm(ma_device* pDevice, void* pPCMFrames, ma_uint32 frameCount) { - ma_assert(pDevice != NULL); - ma_assert(pPCMFrames != NULL); - ma_result result = MA_SUCCESS; MMRESULT resultMM; ma_uint32 totalFramesRead; - WAVEHDR* pWAVEHDR = (WAVEHDR*)pDevice->winmm.pWAVEHDRCapture; + WAVEHDR* pWAVEHDR; + + ma_assert(pDevice != NULL); + ma_assert(pPCMFrames != NULL); + + pWAVEHDR = (WAVEHDR*)pDevice->winmm.pWAVEHDRCapture; /* We want to start the device immediately. */ if (!pDevice->winmm.isStarted) { + ma_uint32 iPeriod; + /* Make sure the event is reset to a non-signaled state to ensure we don't prematurely return from WaitForSingleObject(). */ ResetEvent((HANDLE)pDevice->winmm.hEventCapture); /* To start the device we attach all of the buffers and then start it. As the buffers are filled with data we will get notifications. */ - for (ma_uint32 iPeriod = 0; iPeriod < pDevice->capture.internalPeriods; ++iPeriod) { + for (iPeriod = 0; iPeriod < pDevice->capture.internalPeriods; ++iPeriod) { resultMM = ((MA_PFN_waveInAddBuffer)pDevice->pContext->winmm.waveInAddBuffer)((HWAVEIN)pDevice->winmm.hDeviceCapture, &((LPWAVEHDR)pDevice->winmm.pWAVEHDRCapture)[iPeriod], sizeof(WAVEHDR)); if (resultMM != MMSYSERR_NOERROR) { return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[WinMM] Failed to attach input buffers to capture device in preparation for capture.", ma_result_from_MMRESULT(resultMM)); @@ -11126,11 +11505,11 @@ ma_result ma_context_init__winmm(const ma_context_config* pConfig, ma_context* p -/////////////////////////////////////////////////////////////////////////////// -// -// ALSA Backend -// -/////////////////////////////////////////////////////////////////////////////// +/****************************************************************************** + +ALSA Backend + +******************************************************************************/ #ifdef MA_HAS_ALSA #ifdef MA_NO_RUNTIME_LINKING @@ -11148,11 +11527,11 @@ typedef snd_pcm_info_t ma_snd_pcm_info_t; typedef snd_pcm_channel_area_t ma_snd_pcm_channel_area_t; typedef snd_pcm_chmap_t ma_snd_pcm_chmap_t; -// snd_pcm_stream_t +/* snd_pcm_stream_t */ #define MA_SND_PCM_STREAM_PLAYBACK SND_PCM_STREAM_PLAYBACK #define MA_SND_PCM_STREAM_CAPTURE SND_PCM_STREAM_CAPTURE -// snd_pcm_format_t +/* snd_pcm_format_t */ #define MA_SND_PCM_FORMAT_UNKNOWN SND_PCM_FORMAT_UNKNOWN #define MA_SND_PCM_FORMAT_U8 SND_PCM_FORMAT_U8 #define MA_SND_PCM_FORMAT_S16_LE SND_PCM_FORMAT_S16_LE @@ -11170,14 +11549,14 @@ typedef snd_pcm_chmap_t ma_snd_pcm_chmap_t; #define MA_SND_PCM_FORMAT_S24_3LE SND_PCM_FORMAT_S24_3LE #define MA_SND_PCM_FORMAT_S24_3BE SND_PCM_FORMAT_S24_3BE -// ma_snd_pcm_access_t +/* ma_snd_pcm_access_t */ #define MA_SND_PCM_ACCESS_MMAP_INTERLEAVED SND_PCM_ACCESS_MMAP_INTERLEAVED #define MA_SND_PCM_ACCESS_MMAP_NONINTERLEAVED SND_PCM_ACCESS_MMAP_NONINTERLEAVED #define MA_SND_PCM_ACCESS_MMAP_COMPLEX SND_PCM_ACCESS_MMAP_COMPLEX #define MA_SND_PCM_ACCESS_RW_INTERLEAVED SND_PCM_ACCESS_RW_INTERLEAVED #define MA_SND_PCM_ACCESS_RW_NONINTERLEAVED SND_PCM_ACCESS_RW_NONINTERLEAVED -// Channel positions. +/* Channel positions. */ #define MA_SND_CHMAP_UNKNOWN SND_CHMAP_UNKNOWN #define MA_SND_CHMAP_NA SND_CHMAP_NA #define MA_SND_CHMAP_MONO SND_CHMAP_MONO @@ -11216,12 +11595,12 @@ typedef snd_pcm_chmap_t ma_snd_pcm_chmap_t; #define MA_SND_CHMAP_BLC SND_CHMAP_BLC #define MA_SND_CHMAP_BRC SND_CHMAP_BRC -// Open mode flags. +/* Open mode flags. */ #define MA_SND_PCM_NO_AUTO_RESAMPLE SND_PCM_NO_AUTO_RESAMPLE #define MA_SND_PCM_NO_AUTO_CHANNELS SND_PCM_NO_AUTO_CHANNELS #define MA_SND_PCM_NO_AUTO_FORMAT SND_PCM_NO_AUTO_FORMAT #else -#include // For EPIPE, etc. +#include /* For EPIPE, etc. */ typedef unsigned long ma_snd_pcm_uframes_t; typedef long ma_snd_pcm_sframes_t; typedef int ma_snd_pcm_stream_t; @@ -11244,7 +11623,7 @@ typedef struct unsigned int pos[1]; } ma_snd_pcm_chmap_t; -// snd_pcm_state_t +/* snd_pcm_state_t */ #define MA_SND_PCM_STATE_OPEN 0 #define MA_SND_PCM_STATE_SETUP 1 #define MA_SND_PCM_STATE_PREPARED 2 @@ -11255,11 +11634,11 @@ typedef struct #define MA_SND_PCM_STATE_SUSPENDED 7 #define MA_SND_PCM_STATE_DISCONNECTED 8 -// snd_pcm_stream_t +/* snd_pcm_stream_t */ #define MA_SND_PCM_STREAM_PLAYBACK 0 #define MA_SND_PCM_STREAM_CAPTURE 1 -// snd_pcm_format_t +/* snd_pcm_format_t */ #define MA_SND_PCM_FORMAT_UNKNOWN -1 #define MA_SND_PCM_FORMAT_U8 1 #define MA_SND_PCM_FORMAT_S16_LE 2 @@ -11277,14 +11656,14 @@ typedef struct #define MA_SND_PCM_FORMAT_S24_3LE 32 #define MA_SND_PCM_FORMAT_S24_3BE 33 -// snd_pcm_access_t +/* snd_pcm_access_t */ #define MA_SND_PCM_ACCESS_MMAP_INTERLEAVED 0 #define MA_SND_PCM_ACCESS_MMAP_NONINTERLEAVED 1 #define MA_SND_PCM_ACCESS_MMAP_COMPLEX 2 #define MA_SND_PCM_ACCESS_RW_INTERLEAVED 3 #define MA_SND_PCM_ACCESS_RW_NONINTERLEAVED 4 -// Channel positions. +/* Channel positions. */ #define MA_SND_CHMAP_UNKNOWN 0 #define MA_SND_CHMAP_NA 1 #define MA_SND_CHMAP_MONO 2 @@ -11323,7 +11702,7 @@ typedef struct #define MA_SND_CHMAP_BLC 35 #define MA_SND_CHMAP_BRC 36 -// Open mode flags. +/* Open mode flags. */ #define MA_SND_PCM_NO_AUTO_RESAMPLE 0x00010000 #define MA_SND_PCM_NO_AUTO_CHANNELS 0x00020000 #define MA_SND_PCM_NO_AUTO_FORMAT 0x00040000 @@ -11385,7 +11764,7 @@ typedef size_t (* ma_snd_pcm_info_sizeof_proc) ( typedef const char* (* ma_snd_pcm_info_get_name_proc) (const ma_snd_pcm_info_t* info); typedef int (* ma_snd_config_update_free_global_proc) (); -// This array specifies each of the common devices that can be used for both playback and capture. +/* This array specifies each of the common devices that can be used for both playback and capture. */ const char* g_maCommonDeviceNamesALSA[] = { "default", "null", @@ -11393,19 +11772,21 @@ const char* g_maCommonDeviceNamesALSA[] = { "jack" }; -// This array allows us to blacklist specific playback devices. +/* This array allows us to blacklist specific playback devices. */ const char* g_maBlacklistedPlaybackDeviceNamesALSA[] = { "" }; -// This array allows us to blacklist specific capture devices. +/* This array allows us to blacklist specific capture devices. */ const char* g_maBlacklistedCaptureDeviceNamesALSA[] = { "" }; -// This array allows miniaudio to control device-specific default buffer sizes. This uses a scaling factor. Order is important. If -// any part of the string is present in the device's name, the associated scale will be used. +/* +This array allows miniaudio to control device-specific default buffer sizes. This uses a scaling factor. Order is important. If +any part of the string is present in the device's name, the associated scale will be used. +*/ static struct { const char* name; @@ -11417,11 +11798,13 @@ static struct float ma_find_default_buffer_size_scale__alsa(const char* deviceName) { + size_t i; + if (deviceName == NULL) { return 1; } - for (size_t i = 0; i < ma_countof(g_maDefaultBufferSizeScalesALSA); ++i) { + for (i = 0; i < ma_countof(g_maDefaultBufferSizeScalesALSA); ++i) { if (strstr(g_maDefaultBufferSizeScalesALSA[i].name, deviceName) != NULL) { return g_maDefaultBufferSizeScalesALSA[i].scale; } @@ -11433,12 +11816,12 @@ float ma_find_default_buffer_size_scale__alsa(const char* deviceName) ma_snd_pcm_format_t ma_convert_ma_format_to_alsa_format(ma_format format) { ma_snd_pcm_format_t ALSAFormats[] = { - MA_SND_PCM_FORMAT_UNKNOWN, // ma_format_unknown - MA_SND_PCM_FORMAT_U8, // ma_format_u8 - MA_SND_PCM_FORMAT_S16_LE, // ma_format_s16 - MA_SND_PCM_FORMAT_S24_3LE, // ma_format_s24 - MA_SND_PCM_FORMAT_S32_LE, // ma_format_s32 - MA_SND_PCM_FORMAT_FLOAT_LE // ma_format_f32 + MA_SND_PCM_FORMAT_UNKNOWN, /* ma_format_unknown */ + MA_SND_PCM_FORMAT_U8, /* ma_format_u8 */ + MA_SND_PCM_FORMAT_S16_LE, /* ma_format_s16 */ + MA_SND_PCM_FORMAT_S24_3LE, /* ma_format_s24 */ + MA_SND_PCM_FORMAT_S32_LE, /* ma_format_s32 */ + MA_SND_PCM_FORMAT_FLOAT_LE /* ma_format_f32 */ }; if (ma_is_big_endian()) { @@ -11450,11 +11833,10 @@ ma_snd_pcm_format_t ma_convert_ma_format_to_alsa_format(ma_format format) ALSAFormats[5] = MA_SND_PCM_FORMAT_FLOAT_BE; } - return ALSAFormats[format]; } -ma_format ma_convert_alsa_format_to_ma_format(ma_snd_pcm_format_t formatALSA) +ma_format ma_format_from_alsa(ma_snd_pcm_format_t formatALSA) { if (ma_is_little_endian()) { switch (formatALSA) { @@ -11474,7 +11856,7 @@ ma_format ma_convert_alsa_format_to_ma_format(ma_snd_pcm_format_t formatALSA) } } - // Endian agnostic. + /* Endian agnostic. */ switch (formatALSA) { case MA_SND_PCM_FORMAT_U8: return ma_format_u8; default: return ma_format_unknown; @@ -11519,7 +11901,8 @@ ma_channel ma_convert_alsa_channel_position_to_ma_channel(unsigned int alsaChann ma_bool32 ma_is_common_device_name__alsa(const char* name) { - for (size_t iName = 0; iName < ma_countof(g_maCommonDeviceNamesALSA); ++iName) { + size_t iName; + for (iName = 0; iName < ma_countof(g_maCommonDeviceNamesALSA); ++iName) { if (ma_strcmp(name, g_maCommonDeviceNamesALSA[iName]) == 0) { return MA_TRUE; } @@ -11531,7 +11914,8 @@ ma_bool32 ma_is_common_device_name__alsa(const char* name) ma_bool32 ma_is_playback_device_blacklisted__alsa(const char* name) { - for (size_t iName = 0; iName < ma_countof(g_maBlacklistedPlaybackDeviceNamesALSA); ++iName) { + size_t iName; + for (iName = 0; iName < ma_countof(g_maBlacklistedPlaybackDeviceNamesALSA); ++iName) { if (ma_strcmp(name, g_maBlacklistedPlaybackDeviceNamesALSA[iName]) == 0) { return MA_TRUE; } @@ -11542,7 +11926,8 @@ ma_bool32 ma_is_playback_device_blacklisted__alsa(const char* name) ma_bool32 ma_is_capture_device_blacklisted__alsa(const char* name) { - for (size_t iName = 0; iName < ma_countof(g_maBlacklistedCaptureDeviceNamesALSA); ++iName) { + size_t iName; + for (iName = 0; iName < ma_countof(g_maBlacklistedCaptureDeviceNamesALSA); ++iName) { if (ma_strcmp(name, g_maBlacklistedCaptureDeviceNamesALSA[iName]) == 0) { return MA_TRUE; } @@ -11578,15 +11963,18 @@ const char* ma_find_char(const char* str, char c, int* index) i += 1; } - // Should never get here, but treat it as though the character was not found to make me feel - // better inside. + /* Should never get here, but treat it as though the character was not found to make me feel better inside. */ if (index) *index = -1; return NULL; } ma_bool32 ma_is_device_name_in_hw_format__alsa(const char* hwid) { - // This function is just checking whether or not hwid is in "hw:%d,%d" format. + /* This function is just checking whether or not hwid is in "hw:%d,%d" format. */ + + int commaPos; + const char* dev; + int i; if (hwid == NULL) { return MA_FALSE; @@ -11598,23 +11986,22 @@ ma_bool32 ma_is_device_name_in_hw_format__alsa(const char* hwid) hwid += 3; - int commaPos; - const char* dev = ma_find_char(hwid, ',', &commaPos); + dev = ma_find_char(hwid, ',', &commaPos); if (dev == NULL) { return MA_FALSE; } else { - dev += 1; // Skip past the ",". + dev += 1; /* Skip past the ",". */ } - // Check if the part between the ":" and the "," contains only numbers. If not, return false. - for (int i = 0; i < commaPos; ++i) { + /* Check if the part between the ":" and the "," contains only numbers. If not, return false. */ + for (i = 0; i < commaPos; ++i) { if (hwid[i] < '0' || hwid[i] > '9') { return MA_FALSE; } } - // Check if everything after the "," is numeric. If not, return false. - int i = 0; + /* Check if everything after the "," is numeric. If not, return false. */ + i = 0; while (dev[i] != '\0') { if (dev[i] < '0' || dev[i] > '9') { return MA_FALSE; @@ -11625,49 +12012,56 @@ ma_bool32 ma_is_device_name_in_hw_format__alsa(const char* hwid) return MA_TRUE; } -int ma_convert_device_name_to_hw_format__alsa(ma_context* pContext, char* dst, size_t dstSize, const char* src) // Returns 0 on success, non-0 on error. +int ma_convert_device_name_to_hw_format__alsa(ma_context* pContext, char* dst, size_t dstSize, const char* src) /* Returns 0 on success, non-0 on error. */ { - // src should look something like this: "hw:CARD=I82801AAICH,DEV=0" + /* src should look something like this: "hw:CARD=I82801AAICH,DEV=0" */ + + int colonPos; + int commaPos; + char card[256]; + const char* dev; + int cardIndex; - if (dst == NULL) return -1; - if (dstSize < 7) return -1; // Absolute minimum size of the output buffer is 7 bytes. + if (dst == NULL) { + return -1; + } + if (dstSize < 7) { + return -1; /* Absolute minimum size of the output buffer is 7 bytes. */ + } - *dst = '\0'; // Safety. - if (src == NULL) return -1; + *dst = '\0'; /* Safety. */ + if (src == NULL) { + return -1; + } - // If the input name is already in "hw:%d,%d" format, just return that verbatim. + /* If the input name is already in "hw:%d,%d" format, just return that verbatim. */ if (ma_is_device_name_in_hw_format__alsa(src)) { return ma_strcpy_s(dst, dstSize, src); } - - int colonPos; src = ma_find_char(src, ':', &colonPos); if (src == NULL) { - return -1; // Couldn't find a colon + return -1; /* Couldn't find a colon */ } - char card[256]; - - int commaPos; - const char* dev = ma_find_char(src, ',', &commaPos); + dev = ma_find_char(src, ',', &commaPos); if (dev == NULL) { dev = "0"; - ma_strncpy_s(card, sizeof(card), src+6, (size_t)-1); // +6 = ":CARD=" + ma_strncpy_s(card, sizeof(card), src+6, (size_t)-1); /* +6 = ":CARD=" */ } else { - dev = dev + 5; // +5 = ",DEV=" - ma_strncpy_s(card, sizeof(card), src+6, commaPos-6); // +6 = ":CARD=" + dev = dev + 5; /* +5 = ",DEV=" */ + ma_strncpy_s(card, sizeof(card), src+6, commaPos-6); /* +6 = ":CARD=" */ } - int cardIndex = ((ma_snd_card_get_index_proc)pContext->alsa.snd_card_get_index)(card); + cardIndex = ((ma_snd_card_get_index_proc)pContext->alsa.snd_card_get_index)(card); if (cardIndex < 0) { - return -2; // Failed to retrieve the card index. + return -2; /* Failed to retrieve the card index. */ } - //printf("TESTING: CARD=%s,DEV=%s\n", card, dev); + /*printf("TESTING: CARD=%s,DEV=%s\n", card, dev); */ - // Construction. + /* Construction. */ dst[0] = 'h'; dst[1] = 'w'; dst[2] = ':'; if (ma_itoa_s(cardIndex, dst+3, dstSize-3, 10) != 0) { return -3; @@ -11684,9 +12078,11 @@ int ma_convert_device_name_to_hw_format__alsa(ma_context* pContext, char* dst, s ma_bool32 ma_does_id_exist_in_list__alsa(ma_device_id* pUniqueIDs, ma_uint32 count, const char* pHWID) { + ma_uint32 i; + ma_assert(pHWID != NULL); - for (ma_uint32 i = 0; i < count; ++i) { + for (i = 0; i < count; ++i) { if (ma_strcmp(pUniqueIDs[i].alsa, pHWID) == 0) { return MA_TRUE; } @@ -11698,19 +12094,27 @@ ma_bool32 ma_does_id_exist_in_list__alsa(ma_device_id* pUniqueIDs, ma_uint32 cou ma_result ma_context_open_pcm__alsa(ma_context* pContext, ma_share_mode shareMode, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_snd_pcm_t** ppPCM) { + ma_snd_pcm_t* pPCM; + ma_snd_pcm_stream_t stream; + int openMode; + ma_assert(pContext != NULL); ma_assert(ppPCM != NULL); *ppPCM = NULL; + pPCM = NULL; - ma_snd_pcm_t* pPCM = NULL; - - ma_snd_pcm_stream_t stream = (deviceType == ma_device_type_playback) ? MA_SND_PCM_STREAM_PLAYBACK : MA_SND_PCM_STREAM_CAPTURE; - int openMode = MA_SND_PCM_NO_AUTO_RESAMPLE | MA_SND_PCM_NO_AUTO_CHANNELS | MA_SND_PCM_NO_AUTO_FORMAT; + stream = (deviceType == ma_device_type_playback) ? MA_SND_PCM_STREAM_PLAYBACK : MA_SND_PCM_STREAM_CAPTURE; + openMode = MA_SND_PCM_NO_AUTO_RESAMPLE | MA_SND_PCM_NO_AUTO_CHANNELS | MA_SND_PCM_NO_AUTO_FORMAT; if (pDeviceID == NULL) { - // We're opening the default device. I don't know if trying anything other than "default" is necessary, but it makes - // me feel better to try as hard as we can get to get _something_ working. + ma_bool32 isDeviceOpen; + size_t i; + + /* + We're opening the default device. I don't know if trying anything other than "default" is necessary, but it makes + me feel better to try as hard as we can get to get _something_ working. + */ const char* defaultDeviceNames[] = { "default", NULL, @@ -11740,8 +12144,8 @@ ma_result ma_context_open_pcm__alsa(ma_context* pContext, ma_share_mode shareMod defaultDeviceNames[6] = "hw:0,0"; } - ma_bool32 isDeviceOpen = MA_FALSE; - for (size_t i = 0; i < ma_countof(defaultDeviceNames); ++i) { // TODO: i = 1 is temporary for testing purposes. Needs to be i = 0. + isDeviceOpen = MA_FALSE; + for (i = 0; i < ma_countof(defaultDeviceNames); ++i) { if (defaultDeviceNames[i] != NULL && defaultDeviceNames[i][0] != '\0') { if (((ma_snd_pcm_open_proc)pContext->alsa.snd_pcm_open)(&pPCM, defaultDeviceNames[i], stream, openMode) == 0) { isDeviceOpen = MA_TRUE; @@ -11754,28 +12158,31 @@ ma_result ma_context_open_pcm__alsa(ma_context* pContext, ma_share_mode shareMod return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[ALSA] snd_pcm_open() failed when trying to open an appropriate default device.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); } } else { - // We're trying to open a specific device. There's a few things to consider here: - // - // miniaudio recongnizes a special format of device id that excludes the "hw", "dmix", etc. prefix. It looks like this: ":0,0", ":0,1", etc. When - // an ID of this format is specified, it indicates to miniaudio that it can try different combinations of plugins ("hw", "dmix", etc.) until it - // finds an appropriate one that works. This comes in very handy when trying to open a device in shared mode ("dmix"), vs exclusive mode ("hw"). + /* + We're trying to open a specific device. There's a few things to consider here: + + miniaudio recongnizes a special format of device id that excludes the "hw", "dmix", etc. prefix. It looks like this: ":0,0", ":0,1", etc. When + an ID of this format is specified, it indicates to miniaudio that it can try different combinations of plugins ("hw", "dmix", etc.) until it + finds an appropriate one that works. This comes in very handy when trying to open a device in shared mode ("dmix"), vs exclusive mode ("hw"). + */ - // May end up needing to make small adjustments to the ID, so make a copy. + /* May end up needing to make small adjustments to the ID, so make a copy. */ ma_device_id deviceID = *pDeviceID; - ma_bool32 isDeviceOpen = MA_FALSE; + if (deviceID.alsa[0] != ':') { - // The ID is not in ":0,0" format. Use the ID exactly as-is. + /* The ID is not in ":0,0" format. Use the ID exactly as-is. */ if (((ma_snd_pcm_open_proc)pContext->alsa.snd_pcm_open)(&pPCM, deviceID.alsa, stream, openMode) == 0) { isDeviceOpen = MA_TRUE; } } else { - // The ID is in ":0,0" format. Try different plugins depending on the shared mode. + char hwid[256]; + + /* The ID is in ":0,0" format. Try different plugins depending on the shared mode. */ if (deviceID.alsa[1] == '\0') { - deviceID.alsa[0] = '\0'; // An ID of ":" should be converted to "". + deviceID.alsa[0] = '\0'; /* An ID of ":" should be converted to "". */ } - char hwid[256]; if (shareMode == ma_share_mode_shared) { if (deviceType == ma_device_type_playback) { ma_strcpy_s(hwid, sizeof(hwid), "dmix"); @@ -11790,7 +12197,7 @@ ma_result ma_context_open_pcm__alsa(ma_context* pContext, ma_share_mode shareMod } } - // If at this point we still don't have an open device it means we're either preferencing exclusive mode or opening with "dmix"/"dsnoop" failed. + /* If at this point we still don't have an open device it means we're either preferencing exclusive mode or opening with "dmix"/"dsnoop" failed. */ if (!isDeviceOpen) { ma_strcpy_s(hwid, sizeof(hwid), "hw"); if (ma_strcat_s(hwid, sizeof(hwid), deviceID.alsa) == 0) { @@ -11823,29 +12230,32 @@ ma_bool32 ma_context_is_device_id_equal__alsa(ma_context* pContext, const ma_dev ma_result ma_context_enumerate_devices__alsa(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData) { + ma_bool32 cbResult = MA_TRUE; + char** ppDeviceHints; + ma_device_id* pUniqueIDs = NULL; + ma_uint32 uniqueIDCount = 0; + char** ppNextDeviceHint; + ma_assert(pContext != NULL); ma_assert(callback != NULL); - ma_bool32 cbResult = MA_TRUE; - ma_mutex_lock(&pContext->alsa.internalDeviceEnumLock); - char** ppDeviceHints; if (((ma_snd_device_name_hint_proc)pContext->alsa.snd_device_name_hint)(-1, "pcm", (void***)&ppDeviceHints) < 0) { ma_mutex_unlock(&pContext->alsa.internalDeviceEnumLock); return MA_NO_BACKEND; } - ma_device_id* pUniqueIDs = NULL; - ma_uint32 uniqueIDCount = 0; - - char** ppNextDeviceHint = ppDeviceHints; + ppNextDeviceHint = ppDeviceHints; while (*ppNextDeviceHint != NULL) { char* NAME = ((ma_snd_device_name_get_hint_proc)pContext->alsa.snd_device_name_get_hint)(*ppNextDeviceHint, "NAME"); char* DESC = ((ma_snd_device_name_get_hint_proc)pContext->alsa.snd_device_name_get_hint)(*ppNextDeviceHint, "DESC"); char* IOID = ((ma_snd_device_name_get_hint_proc)pContext->alsa.snd_device_name_get_hint)(*ppNextDeviceHint, "IOID"); - ma_device_type deviceType = ma_device_type_playback; + ma_bool32 stopEnumeration = MA_FALSE; + char hwid[sizeof(pUniqueIDs->alsa)]; + ma_device_info deviceInfo; + if ((IOID == NULL || ma_strcmp(IOID, "Output") == 0)) { deviceType = ma_device_type_playback; } @@ -11853,44 +12263,34 @@ ma_result ma_context_enumerate_devices__alsa(ma_context* pContext, ma_enum_devic deviceType = ma_device_type_capture; } - ma_bool32 stopEnumeration = MA_FALSE; -#if 0 - printf("NAME: %s\n", NAME); - printf("DESC: %s\n", DESC); - printf("IOID: %s\n", IOID); - - char hwid2[256]; - ma_convert_device_name_to_hw_format__alsa(pContext, hwid2, sizeof(hwid2), NAME); - printf("DEVICE ID: %s\n\n", hwid2); -#endif - - char hwid[sizeof(pUniqueIDs->alsa)]; if (NAME != NULL) { if (pContext->alsa.useVerboseDeviceEnumeration) { - // Verbose mode. Use the name exactly as-is. + /* Verbose mode. Use the name exactly as-is. */ ma_strncpy_s(hwid, sizeof(hwid), NAME, (size_t)-1); } else { - // Simplified mode. Use ":%d,%d" format. + /* Simplified mode. Use ":%d,%d" format. */ if (ma_convert_device_name_to_hw_format__alsa(pContext, hwid, sizeof(hwid), NAME) == 0) { - // At this point, hwid looks like "hw:0,0". In simplified enumeration mode, we actually want to strip off the - // plugin name so it looks like ":0,0". The reason for this is that this special format is detected at device - // initialization time and is used as an indicator to try and use the most appropriate plugin depending on the - // device type and sharing mode. + /* + At this point, hwid looks like "hw:0,0". In simplified enumeration mode, we actually want to strip off the + plugin name so it looks like ":0,0". The reason for this is that this special format is detected at device + initialization time and is used as an indicator to try and use the most appropriate plugin depending on the + device type and sharing mode. + */ char* dst = hwid; char* src = hwid+2; while ((*dst++ = *src++)); } else { - // Conversion to "hw:%d,%d" failed. Just use the name as-is. + /* Conversion to "hw:%d,%d" failed. Just use the name as-is. */ ma_strncpy_s(hwid, sizeof(hwid), NAME, (size_t)-1); } if (ma_does_id_exist_in_list__alsa(pUniqueIDs, uniqueIDCount, hwid)) { - goto next_device; // The device has already been enumerated. Move on to the next one. + goto next_device; /* The device has already been enumerated. Move on to the next one. */ } else { - // The device has not yet been enumerated. Make sure it's added to our list so that it's not enumerated again. + /* The device has not yet been enumerated. Make sure it's added to our list so that it's not enumerated again. */ ma_device_id* pNewUniqueIDs = (ma_device_id*)ma_realloc(pUniqueIDs, sizeof(*pUniqueIDs) * (uniqueIDCount + 1)); if (pNewUniqueIDs == NULL) { - goto next_device; // Failed to allocate memory. + goto next_device; /* Failed to allocate memory. */ } pUniqueIDs = pNewUniqueIDs; @@ -11902,37 +12302,38 @@ ma_result ma_context_enumerate_devices__alsa(ma_context* pContext, ma_enum_devic ma_zero_memory(hwid, sizeof(hwid)); } - ma_device_info deviceInfo; ma_zero_object(&deviceInfo); ma_strncpy_s(deviceInfo.id.alsa, sizeof(deviceInfo.id.alsa), hwid, (size_t)-1); - // DESC is the friendly name. We treat this slightly differently depending on whether or not we are using verbose - // device enumeration. In verbose mode we want to take the entire description so that the end-user can distinguish - // between the subdevices of each card/dev pair. In simplified mode, however, we only want the first part of the - // description. - // - // The value in DESC seems to be split into two lines, with the first line being the name of the device and the - // second line being a description of the device. I don't like having the description be across two lines because - // it makes formatting ugly and annoying. I'm therefore deciding to put it all on a single line with the second line - // being put into parentheses. In simplified mode I'm just stripping the second line entirely. + /* + DESC is the friendly name. We treat this slightly differently depending on whether or not we are using verbose + device enumeration. In verbose mode we want to take the entire description so that the end-user can distinguish + between the subdevices of each card/dev pair. In simplified mode, however, we only want the first part of the + description. + + The value in DESC seems to be split into two lines, with the first line being the name of the device and the + second line being a description of the device. I don't like having the description be across two lines because + it makes formatting ugly and annoying. I'm therefore deciding to put it all on a single line with the second line + being put into parentheses. In simplified mode I'm just stripping the second line entirely. + */ if (DESC != NULL) { int lfPos; const char* line2 = ma_find_char(DESC, '\n', &lfPos); if (line2 != NULL) { - line2 += 1; // Skip past the new-line character. + line2 += 1; /* Skip past the new-line character. */ if (pContext->alsa.useVerboseDeviceEnumeration) { - // Verbose mode. Put the second line in brackets. + /* Verbose mode. Put the second line in brackets. */ ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), DESC, lfPos); ma_strcat_s (deviceInfo.name, sizeof(deviceInfo.name), " ("); ma_strcat_s (deviceInfo.name, sizeof(deviceInfo.name), line2); ma_strcat_s (deviceInfo.name, sizeof(deviceInfo.name), ")"); } else { - // Simplified mode. Strip the second line entirely. + /* Simplified mode. Strip the second line entirely. */ ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), DESC, lfPos); } } else { - // There's no second line. Just copy the whole description. + /* There's no second line. Just copy the whole description. */ ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), DESC, (size_t)-1); } } @@ -11941,8 +12342,10 @@ ma_result ma_context_enumerate_devices__alsa(ma_context* pContext, ma_enum_devic cbResult = callback(pContext, deviceType, &deviceInfo, pUserData); } - // Some devices are both playback and capture, but they are only enumerated by ALSA once. We need to fire the callback - // again for the other device type in this case. We do this for known devices. + /* + Some devices are both playback and capture, but they are only enumerated by ALSA once. We need to fire the callback + again for the other device type in this case. We do this for known devices. + */ if (cbResult) { if (ma_is_common_device_name__alsa(NAME)) { if (deviceType == ma_device_type_playback) { @@ -11967,7 +12370,7 @@ ma_result ma_context_enumerate_devices__alsa(ma_context* pContext, ma_enum_devic free(IOID); ppNextDeviceHint += 1; - // We need to stop enumeration if the callback returned false. + /* We need to stop enumeration if the callback returned false. */ if (stopEnumeration) { break; } @@ -12006,22 +12409,28 @@ ma_bool32 ma_context_get_device_info_enum_callback__alsa(ma_context* pContext, m } } - // Keep enumerating until we have found the device. + /* Keep enumerating until we have found the device. */ return !pData->foundDevice; } ma_result ma_context_get_device_info__alsa(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_share_mode shareMode, ma_device_info* pDeviceInfo) { + ma_context_get_device_info_enum_callback_data__alsa data; + ma_result result; + ma_snd_pcm_t* pPCM; + ma_snd_pcm_hw_params_t* pHWParams; + ma_snd_pcm_format_mask_t* pFormatMask; + int sampleRateDir = 0; + ma_assert(pContext != NULL); - // We just enumerate to find basic information about the device. - ma_context_get_device_info_enum_callback_data__alsa data; + /* We just enumerate to find basic information about the device. */ data.deviceType = deviceType; data.pDeviceID = pDeviceID; data.shareMode = shareMode; data.pDeviceInfo = pDeviceInfo; data.foundDevice = MA_FALSE; - ma_result result = ma_context_enumerate_devices__alsa(pContext, ma_context_get_device_info_enum_callback__alsa, &data); + result = ma_context_enumerate_devices__alsa(pContext, ma_context_get_device_info_enum_callback__alsa, &data); if (result != MA_SUCCESS) { return result; } @@ -12030,16 +12439,14 @@ ma_result ma_context_get_device_info__alsa(ma_context* pContext, ma_device_type return MA_NO_DEVICE; } - - // For detailed info we need to open the device. - ma_snd_pcm_t* pPCM; + /* For detailed info we need to open the device. */ result = ma_context_open_pcm__alsa(pContext, shareMode, deviceType, pDeviceID, &pPCM); if (result != MA_SUCCESS) { return result; } - // We need to initialize a HW parameters object in order to know what formats are supported. - ma_snd_pcm_hw_params_t* pHWParams = (ma_snd_pcm_hw_params_t*)calloc(1, ((ma_snd_pcm_hw_params_sizeof_proc)pContext->alsa.snd_pcm_hw_params_sizeof)()); + /* We need to initialize a HW parameters object in order to know what formats are supported. */ + pHWParams = (ma_snd_pcm_hw_params_t*)calloc(1, ((ma_snd_pcm_hw_params_sizeof_proc)pContext->alsa.snd_pcm_hw_params_sizeof)()); if (pHWParams == NULL) { return MA_OUT_OF_MEMORY; } @@ -12048,15 +12455,13 @@ ma_result ma_context_get_device_info__alsa(ma_context* pContext, ma_device_type return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to initialize hardware parameters. snd_pcm_hw_params_any() failed.", MA_FAILED_TO_CONFIGURE_BACKEND_DEVICE); } - int sampleRateDir = 0; - ((ma_snd_pcm_hw_params_get_channels_min_proc)pContext->alsa.snd_pcm_hw_params_get_channels_min)(pHWParams, &pDeviceInfo->minChannels); ((ma_snd_pcm_hw_params_get_channels_max_proc)pContext->alsa.snd_pcm_hw_params_get_channels_max)(pHWParams, &pDeviceInfo->maxChannels); ((ma_snd_pcm_hw_params_get_rate_min_proc)pContext->alsa.snd_pcm_hw_params_get_rate_min)(pHWParams, &pDeviceInfo->minSampleRate, &sampleRateDir); ((ma_snd_pcm_hw_params_get_rate_max_proc)pContext->alsa.snd_pcm_hw_params_get_rate_max)(pHWParams, &pDeviceInfo->maxSampleRate, &sampleRateDir); - // Formats. - ma_snd_pcm_format_mask_t* pFormatMask = (ma_snd_pcm_format_mask_t*)calloc(1, ((ma_snd_pcm_format_mask_sizeof_proc)pContext->alsa.snd_pcm_format_mask_sizeof)()); + /* Formats. */ + pFormatMask = (ma_snd_pcm_format_mask_t*)calloc(1, ((ma_snd_pcm_format_mask_sizeof_proc)pContext->alsa.snd_pcm_format_mask_sizeof)()); if (pFormatMask == NULL) { return MA_OUT_OF_MEMORY; } @@ -12089,17 +12494,19 @@ ma_result ma_context_get_device_info__alsa(ma_context* pContext, ma_device_type #if 0 -// Waits for a number of frames to become available for either capture or playback. The return -// value is the number of frames available. -// -// This will return early if the main loop is broken with ma_device__break_main_loop(). +/* +Waits for a number of frames to become available for either capture or playback. The return +value is the number of frames available. + +This will return early if the main loop is broken with ma_device__break_main_loop(). +*/ ma_uint32 ma_device__wait_for_frames__alsa(ma_device* pDevice, ma_bool32* pRequiresRestart) { ma_assert(pDevice != NULL); if (pRequiresRestart) *pRequiresRestart = MA_FALSE; - // I want it so that this function returns the period size in frames. We just wait until that number of frames are available and then return. + /* I want it so that this function returns the period size in frames. We just wait until that number of frames are available and then return. */ ma_uint32 periodSizeInFrames = pDevice->bufferSizeInFrames / pDevice->periods; while (!pDevice->alsa.breakFromMainLoop) { ma_snd_pcm_sframes_t framesAvailable = ((ma_snd_pcm_avail_update_proc)pDevice->pContext->alsa.snd_pcm_avail_update)((ma_snd_pcm_t*)pDevice->alsa.pPCM); @@ -12109,12 +12516,12 @@ ma_uint32 ma_device__wait_for_frames__alsa(ma_device* pDevice, ma_bool32* pRequi return 0; } - // A device recovery means a restart for mmap mode. + /* A device recovery means a restart for mmap mode. */ if (pRequiresRestart) { *pRequiresRestart = MA_TRUE; } - // Try again, but if it fails this time just return an error. + /* Try again, but if it fails this time just return an error. */ framesAvailable = ((ma_snd_pcm_avail_update_proc)pDevice->pContext->alsa.snd_pcm_avail_update)((ma_snd_pcm_t*)pDevice->alsa.pPCM); if (framesAvailable < 0) { return 0; @@ -12127,7 +12534,7 @@ ma_uint32 ma_device__wait_for_frames__alsa(ma_device* pDevice, ma_bool32* pRequi } if (framesAvailable < periodSizeInFrames) { - // Less than a whole period is available so keep waiting. + /* Less than a whole period is available so keep waiting. */ int waitResult = ((ma_snd_pcm_wait_proc)pDevice->pContext->alsa.snd_pcm_wait)((ma_snd_pcm_t*)pDevice->alsa.pPCM, -1); if (waitResult < 0) { if (waitResult == -EPIPE) { @@ -12135,7 +12542,7 @@ ma_uint32 ma_device__wait_for_frames__alsa(ma_device* pDevice, ma_bool32* pRequi return 0; } - // A device recovery means a restart for mmap mode. + /* A device recovery means a restart for mmap mode. */ if (pRequiresRestart) { *pRequiresRestart = MA_TRUE; } @@ -12144,7 +12551,7 @@ ma_uint32 ma_device__wait_for_frames__alsa(ma_device* pDevice, ma_bool32* pRequi } } - // We'll get here if the loop was terminated. Just return whatever's available. + /* We'll get here if the loop was terminated. Just return whatever's available. */ ma_snd_pcm_sframes_t framesAvailable = ((ma_snd_pcm_avail_update_proc)pDevice->pContext->alsa.snd_pcm_avail_update)((ma_snd_pcm_t*)pDevice->alsa.pPCM); if (framesAvailable < 0) { return 0; @@ -12164,14 +12571,14 @@ ma_bool32 ma_device_read_from_client_and_write__alsa(ma_device* pDevice) } if (pDevice->alsa.isUsingMMap) { - // mmap. + /* mmap. */ ma_bool32 requiresRestart; ma_uint32 framesAvailable = ma_device__wait_for_frames__alsa(pDevice, &requiresRestart); if (framesAvailable == 0) { return MA_FALSE; } - // Don't bother asking the client for more audio data if we're just stopping the device anyway. + /* Don't bother asking the client for more audio data if we're just stopping the device anyway. */ if (pDevice->alsa.breakFromMainLoop) { return MA_FALSE; } @@ -12209,14 +12616,14 @@ ma_bool32 ma_device_read_from_client_and_write__alsa(ma_device* pDevice) } } } else { - // readi/writei. + /* readi/writei. */ while (!pDevice->alsa.breakFromMainLoop) { ma_uint32 framesAvailable = ma_device__wait_for_frames__alsa(pDevice, NULL); if (framesAvailable == 0) { continue; } - // Don't bother asking the client for more audio data if we're just stopping the device anyway. + /* Don't bother asking the client for more audio data if we're just stopping the device anyway. */ if (pDevice->alsa.breakFromMainLoop) { return MA_FALSE; } @@ -12226,9 +12633,9 @@ ma_bool32 ma_device_read_from_client_and_write__alsa(ma_device* pDevice) ma_snd_pcm_sframes_t framesWritten = ((ma_snd_pcm_writei_proc)pDevice->pContext->alsa.snd_pcm_writei)((ma_snd_pcm_t*)pDevice->alsa.pPCM, pDevice->alsa.pIntermediaryBuffer, framesAvailable); if (framesWritten < 0) { if (framesWritten == -EAGAIN) { - continue; // Just keep trying... + continue; /* Just keep trying... */ } else if (framesWritten == -EPIPE) { - // Underrun. Just recover and try writing again. + /* Underrun. Just recover and try writing again. */ if (((ma_snd_pcm_recover_proc)pDevice->pContext->alsa.snd_pcm_recover)((ma_snd_pcm_t*)pDevice->alsa.pPCM, framesWritten, MA_TRUE) < 0) { ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to recover device after underrun.", MA_FAILED_TO_START_BACKEND_DEVICE); return MA_FALSE; @@ -12240,13 +12647,13 @@ ma_bool32 ma_device_read_from_client_and_write__alsa(ma_device* pDevice) return MA_FALSE; } - break; // Success. + break; /* Success. */ } else { ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] snd_pcm_writei() failed when writing initial data.", MA_FAILED_TO_SEND_DATA_TO_DEVICE); return MA_FALSE; } } else { - break; // Success. + break; /* Success. */ } } } @@ -12267,7 +12674,7 @@ ma_bool32 ma_device_read_and_send_to_client__alsa(ma_device* pDevice) ma_uint32 framesToSend = 0; void* pBuffer = NULL; if (pDevice->alsa.pIntermediaryBuffer == NULL) { - // mmap. + /* mmap. */ ma_bool32 requiresRestart; ma_uint32 framesAvailable = ma_device__wait_for_frames__alsa(pDevice, &requiresRestart); if (framesAvailable == 0) { @@ -12307,7 +12714,7 @@ ma_bool32 ma_device_read_and_send_to_client__alsa(ma_device* pDevice) } } } else { - // readi/writei. + /* readi/writei. */ ma_snd_pcm_sframes_t framesRead = 0; while (!pDevice->alsa.breakFromMainLoop) { ma_uint32 framesAvailable = ma_device__wait_for_frames__alsa(pDevice, NULL); @@ -12318,9 +12725,9 @@ ma_bool32 ma_device_read_and_send_to_client__alsa(ma_device* pDevice) framesRead = ((ma_snd_pcm_readi_proc)pDevice->pContext->alsa.snd_pcm_readi)((ma_snd_pcm_t*)pDevice->alsa.pPCM, pDevice->alsa.pIntermediaryBuffer, framesAvailable); if (framesRead < 0) { if (framesRead == -EAGAIN) { - continue; // Just keep trying... + continue; /* Just keep trying... */ } else if (framesRead == -EPIPE) { - // Overrun. Just recover and try reading again. + /* Overrun. Just recover and try reading again. */ if (((ma_snd_pcm_recover_proc)pDevice->pContext->alsa.snd_pcm_recover)((ma_snd_pcm_t*)pDevice->alsa.pPCM, framesRead, MA_TRUE) < 0) { ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to recover device after overrun.", MA_FAILED_TO_START_BACKEND_DEVICE); return MA_FALSE; @@ -12332,12 +12739,12 @@ ma_bool32 ma_device_read_and_send_to_client__alsa(ma_device* pDevice) return MA_FALSE; } - break; // Success. + break; /* Success. */ } else { return MA_FALSE; } } else { - break; // Success. + break; /* Success. */ } } @@ -12351,7 +12758,7 @@ ma_bool32 ma_device_read_and_send_to_client__alsa(ma_device* pDevice) return MA_TRUE; } -#endif +#endif /* 0 */ void ma_device_uninit__alsa(ma_device* pDevice) { @@ -12383,6 +12790,7 @@ ma_result ma_device_init_by_type__alsa(ma_context* pContext, const ma_device_con ma_snd_pcm_hw_params_t* pHWParams; ma_snd_pcm_sw_params_t* pSWParams; ma_snd_pcm_uframes_t bufferBoundary; + float bufferSizeScaleFactor; ma_assert(pContext != NULL); ma_assert(pConfig != NULL); @@ -12399,7 +12807,7 @@ ma_result ma_device_init_by_type__alsa(ma_context* pContext, const ma_device_con } /* If using the default buffer size we may want to apply some device-specific scaling for known devices that have peculiar latency characteristics */ - float bufferSizeScaleFactor = 1; + bufferSizeScaleFactor = 1; if (pDevice->usingDefaultBufferSize) { ma_snd_pcm_info_t* pInfo = (ma_snd_pcm_info_t*)calloc(1, ((ma_snd_pcm_info_sizeof_proc)pContext->alsa.snd_pcm_info_sizeof)()); if (pInfo == NULL) { @@ -12512,6 +12920,8 @@ ma_result ma_device_init_by_type__alsa(ma_context* pContext, const ma_device_con supported, and if so, use that one. If it's not supported, we just run though a list of formats and try to find the best one. */ if (!((ma_snd_pcm_format_mask_test_proc)pContext->alsa.snd_pcm_format_mask_test)(pFormatMask, formatALSA)) { + size_t i; + /* The requested format is not supported so now try running through the list of formats and return the best one. */ ma_snd_pcm_format_t preferredFormatsALSA[] = { MA_SND_PCM_FORMAT_S16_LE, /* ma_format_s16 */ @@ -12530,7 +12940,7 @@ ma_result ma_device_init_by_type__alsa(ma_context* pContext, const ma_device_con } formatALSA = MA_SND_PCM_FORMAT_UNKNOWN; - for (size_t i = 0; i < (sizeof(preferredFormatsALSA) / sizeof(preferredFormatsALSA[0])); ++i) { + for (i = 0; i < (sizeof(preferredFormatsALSA) / sizeof(preferredFormatsALSA[0])); ++i) { if (((ma_snd_pcm_format_mask_test_proc)pContext->alsa.snd_pcm_format_mask_test)(pFormatMask, preferredFormatsALSA[i])) { formatALSA = preferredFormatsALSA[i]; break; @@ -12553,7 +12963,7 @@ ma_result ma_device_init_by_type__alsa(ma_context* pContext, const ma_device_con return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Format not supported. snd_pcm_hw_params_set_format() failed.", MA_FORMAT_NOT_SUPPORTED); } - internalFormat = ma_convert_alsa_format_to_ma_format(formatALSA); + internalFormat = ma_format_from_alsa(formatALSA); if (internalFormat == ma_format_unknown) { ma_free(pHWParams); ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM); @@ -12673,7 +13083,7 @@ ma_result ma_device_init_by_type__alsa(ma_context* pContext, const ma_device_con bufferBoundary = internalBufferSizeInFrames; } - //printf("TRACE: bufferBoundary=%ld\n", bufferBoundary); + /*printf("TRACE: bufferBoundary=%ld\n", bufferBoundary);*/ if (deviceType == ma_device_type_playback && !isUsingMMap) { /* Only playback devices in writei/readi mode need a start threshold. */ /* @@ -12706,13 +13116,17 @@ ma_result ma_device_init_by_type__alsa(ma_context* pContext, const ma_device_con { ma_snd_pcm_chmap_t* pChmap = ((ma_snd_pcm_get_chmap_proc)pContext->alsa.snd_pcm_get_chmap)(pPCM); if (pChmap != NULL) { + ma_uint32 iChannel; + /* There are cases where the returned channel map can have a different channel count than was returned by snd_pcm_hw_params_set_channels_near(). */ if (pChmap->channels >= internalChannels) { /* Drop excess channels. */ - for (ma_uint32 iChannel = 0; iChannel < internalChannels; ++iChannel) { + for (iChannel = 0; iChannel < internalChannels; ++iChannel) { internalChannelMap[iChannel] = ma_convert_alsa_channel_position_to_ma_channel(pChmap->pos[iChannel]); } } else { + ma_uint32 i; + /* Excess channels use defaults. Do an initial fill with defaults, overwrite the first pChmap->channels, validate to ensure there are no duplicate channels. If validation fails, fall back to defaults. @@ -12723,13 +13137,14 @@ ma_result ma_device_init_by_type__alsa(ma_context* pContext, const ma_device_con ma_get_standard_channel_map(ma_standard_channel_map_alsa, internalChannels, internalChannelMap); /* Overwrite first pChmap->channels channels. */ - for (ma_uint32 iChannel = 0; iChannel < pChmap->channels; ++iChannel) { + for (iChannel = 0; iChannel < pChmap->channels; ++iChannel) { internalChannelMap[iChannel] = ma_convert_alsa_channel_position_to_ma_channel(pChmap->pos[iChannel]); } /* Validate. */ - for (ma_uint32 i = 0; i < internalChannels && isValid; ++i) { - for (ma_uint32 j = i+1; j < internalChannels; ++j) { + for (i = 0; i < internalChannels && isValid; ++i) { + ma_uint32 j; + for (j = i+1; j < internalChannels; ++j) { if (internalChannelMap[i] == internalChannelMap[j]) { isValid = MA_FALSE; break; @@ -12810,19 +13225,21 @@ ma_result ma_device_start__alsa(ma_device* pDevice) { ma_assert(pDevice != NULL); - // Prepare the device first... + /* Prepare the device first... */ if (((ma_snd_pcm_prepare_proc)pDevice->pContext->alsa.snd_pcm_prepare)((ma_snd_pcm_t*)pDevice->alsa.pPCM) < 0) { return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to prepare device.", MA_FAILED_TO_START_BACKEND_DEVICE); } - // ... and then grab an initial chunk from the client. After this is done, the device should - // automatically start playing, since that's how we configured the software parameters. + /* + ... and then grab an initial chunk from the client. After this is done, the device should + automatically start playing, since that's how we configured the software parameters. + */ if (pDevice->type == ma_device_type_playback) { if (!ma_device_read_from_client_and_write__alsa(pDevice)) { return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to write initial chunk of data to the playback device.", MA_FAILED_TO_SEND_DATA_TO_DEVICE); } - // mmap mode requires an explicit start. + /* mmap mode requires an explicit start. */ if (pDevice->alsa.isUsingMMap) { if (((ma_snd_pcm_start_proc)pDevice->pContext->alsa.snd_pcm_start)((ma_snd_pcm_t*)pDevice->alsa.pPCM) < 0) { return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[ALSA] Failed to start capture device.", MA_FAILED_TO_START_BACKEND_DEVICE); @@ -12836,7 +13253,7 @@ ma_result ma_device_start__alsa(ma_device* pDevice) return MA_SUCCESS; } -#endif +#endif /* 0 */ ma_result ma_device_stop__alsa(ma_device* pDevice) { @@ -12863,22 +13280,22 @@ ma_result ma_device_write__alsa(ma_device* pDevice, const void* pPCMFrames, ma_u ma_assert(pDevice != NULL); ma_assert(pPCMFrames != NULL); - //printf("TRACE: Enter write()\n"); + /*printf("TRACE: Enter write()\n");*/ totalPCMFramesProcessed = 0; while (totalPCMFramesProcessed < frameCount) { const void* pSrc = ma_offset_ptr(pPCMFrames, totalPCMFramesProcessed * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels)); ma_uint32 framesRemaining = (frameCount - totalPCMFramesProcessed); - //printf("TRACE: Writing %d frames (frameCount=%d)\n", framesRemaining, frameCount); + /*printf("TRACE: Writing %d frames (frameCount=%d)\n", framesRemaining, frameCount);*/ resultALSA = ((ma_snd_pcm_writei_proc)pDevice->pContext->alsa.snd_pcm_writei)((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback, pSrc, framesRemaining); if (resultALSA < 0) { if (resultALSA == -EAGAIN) { - //printf("TRACE: EGAIN (write)\n"); + /*printf("TRACE: EGAIN (write)\n");*/ continue; /* Try again. */ } else if (resultALSA == -EPIPE) { - //printf("TRACE: EPIPE (write)\n"); + /*printf("TRACE: EPIPE (write)\n");*/ /* Underrun. Recover and try again. If this fails we need to return an error. */ if (((ma_snd_pcm_recover_proc)pDevice->pContext->alsa.snd_pcm_recover)((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback, resultALSA, MA_TRUE) < 0) { /* MA_TRUE=silent (don't print anything on error). */ @@ -12929,15 +13346,15 @@ ma_result ma_device_read__alsa(ma_device* pDevice, void* pPCMFrames, ma_uint32 f void* pDst = ma_offset_ptr(pPCMFrames, totalPCMFramesProcessed * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels)); ma_uint32 framesRemaining = (frameCount - totalPCMFramesProcessed); - //printf("TRACE: snd_pcm_readi(framesRemaining=%d)\n", framesRemaining); + /*printf("TRACE: snd_pcm_readi(framesRemaining=%d)\n", framesRemaining);*/ resultALSA = ((ma_snd_pcm_readi_proc)pDevice->pContext->alsa.snd_pcm_readi)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture, pDst, framesRemaining); if (resultALSA < 0) { if (resultALSA == -EAGAIN) { - //printf("TRACE: EGAIN (read)\n"); + /*printf("TRACE: EGAIN (read)\n");*/ continue; } else if (resultALSA == -EPIPE) { - //printf("TRACE: EPIPE (read)\n"); + /*printf("TRACE: EPIPE (read)\n");*/ /* Overrun. Recover and try again. If this fails we need to return an error. */ if (((ma_snd_pcm_recover_proc)pDevice->pContext->alsa.snd_pcm_recover)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture, resultALSA, MA_TRUE) < 0) { @@ -12976,25 +13393,25 @@ ma_result ma_device_main_loop__alsa(ma_device* pDevice) pDevice->alsa.breakFromMainLoop = MA_FALSE; if (pDevice->type == ma_device_type_playback) { - // Playback. Read from client, write to device. + /* Playback. Read from client, write to device. */ while (!pDevice->alsa.breakFromMainLoop && ma_device_read_from_client_and_write__alsa(pDevice)) { } } else { - // Capture. Read from device, write to client. + /* Capture. Read from device, write to client. */ while (!pDevice->alsa.breakFromMainLoop && ma_device_read_and_send_to_client__alsa(pDevice)) { } } return MA_SUCCESS; } -#endif +#endif /* 0 */ ma_result ma_context_uninit__alsa(ma_context* pContext) { ma_assert(pContext != NULL); ma_assert(pContext->backend == ma_backend_alsa); - // Clean up memory for memory leak checkers. + /* Clean up memory for memory leak checkers. */ ((ma_snd_config_update_free_global_proc)pContext->alsa.snd_config_update_free_global)(); #ifndef MA_NO_RUNTIME_LINKING @@ -13008,15 +13425,14 @@ ma_result ma_context_uninit__alsa(ma_context* pContext) ma_result ma_context_init__alsa(const ma_context_config* pConfig, ma_context* pContext) { - ma_assert(pContext != NULL); - #ifndef MA_NO_RUNTIME_LINKING const char* libasoundNames[] = { "libasound.so.2", "libasound.so" }; + size_t i; - for (size_t i = 0; i < ma_countof(libasoundNames); ++i) { + for (i = 0; i < ma_countof(libasoundNames); ++i) { pContext->alsa.asoundSO = ma_dlopen(libasoundNames[i]); if (pContext->alsa.asoundSO != NULL) { break; @@ -13086,7 +13502,7 @@ ma_result ma_context_init__alsa(const ma_context_config* pConfig, ma_context* pC pContext->alsa.snd_pcm_info_get_name = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_pcm_info_get_name"); pContext->alsa.snd_config_update_free_global = (ma_proc)ma_dlsym(pContext->alsa.asoundSO, "snd_config_update_free_global"); #else - // The system below is just for type safety. + /* The system below is just for type safety. */ ma_snd_pcm_open_proc _snd_pcm_open = snd_pcm_open; ma_snd_pcm_close_proc _snd_pcm_close = snd_pcm_close; ma_snd_pcm_hw_params_sizeof_proc _snd_pcm_hw_params_sizeof = snd_pcm_hw_params_sizeof; @@ -13217,22 +13633,23 @@ ma_result ma_context_init__alsa(const ma_context_config* pConfig, ma_context* pC return MA_SUCCESS; } -#endif // ALSA +#endif /* ALSA */ + + +/****************************************************************************** +PulseAudio Backend -/////////////////////////////////////////////////////////////////////////////// -// -// PulseAudio Backend -// -/////////////////////////////////////////////////////////////////////////////// +******************************************************************************/ #ifdef MA_HAS_PULSEAUDIO +/* +It is assumed pulseaudio.h is available when compile-time linking is being used. We use this for type safety when using +compile time linking (we don't have this luxury when using runtime linking without headers). -// It is assumed pulseaudio.h is available when compile-time linking is being used. We use this for type safety when using -// compile time linking (we don't have this luxury when using runtime linking without headers). -// -// When using compile time linking, each of our ma_* equivalents should use the sames types as defined by the header. The -// reason for this is that it allow us to take advantage of proper type safety. +When using compile time linking, each of our ma_* equivalents should use the sames types as defined by the header. The +reason for this is that it allow us to take advantage of proper type safety. +*/ #ifdef MA_NO_RUNTIME_LINKING #include @@ -13800,7 +14217,7 @@ ma_pa_sample_format_t ma_format_to_pulse(ma_format format) } } - // Endian agnostic. + /* Endian agnostic. */ switch (format) { case ma_format_u8: return MA_PA_SAMPLE_U8; default: return MA_PA_SAMPLE_INVALID; @@ -13828,7 +14245,7 @@ ma_format ma_format_from_pulse(ma_pa_sample_format_t format) } } - // Endian agnostic. + /* Endian agnostic. */ switch (format) { case MA_PA_SAMPLE_U8: return ma_format_u8; default: return ma_format_unknown; @@ -13984,91 +14401,96 @@ typedef struct void ma_context_enumerate_devices_sink_callback__pulse(ma_pa_context* pPulseContext, const ma_pa_sink_info* pSinkInfo, int endOfList, void* pUserData) { - (void)pPulseContext; - ma_context_enumerate_devices_callback_data__pulse* pData = (ma_context_enumerate_devices_callback_data__pulse*)pUserData; + ma_device_info deviceInfo; + ma_assert(pData != NULL); if (endOfList || pData->isTerminated) { return; } - ma_device_info deviceInfo; ma_zero_object(&deviceInfo); - // The name from PulseAudio is the ID for miniaudio. + /* The name from PulseAudio is the ID for miniaudio. */ if (pSinkInfo->name != NULL) { ma_strncpy_s(deviceInfo.id.pulse, sizeof(deviceInfo.id.pulse), pSinkInfo->name, (size_t)-1); } - // The description from PulseAudio is the name for miniaudio. + /* The description from PulseAudio is the name for miniaudio. */ if (pSinkInfo->description != NULL) { ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), pSinkInfo->description, (size_t)-1); } pData->isTerminated = !pData->callback(pData->pContext, ma_device_type_playback, &deviceInfo, pData->pUserData); + + (void)pPulseContext; /* Unused. */ } void ma_context_enumerate_devices_source_callback__pulse(ma_pa_context* pPulseContext, const ma_pa_source_info* pSinkInfo, int endOfList, void* pUserData) { - (void)pPulseContext; - ma_context_enumerate_devices_callback_data__pulse* pData = (ma_context_enumerate_devices_callback_data__pulse*)pUserData; + ma_device_info deviceInfo; + ma_assert(pData != NULL); if (endOfList || pData->isTerminated) { return; } - ma_device_info deviceInfo; ma_zero_object(&deviceInfo); - // The name from PulseAudio is the ID for miniaudio. + /* The name from PulseAudio is the ID for miniaudio. */ if (pSinkInfo->name != NULL) { ma_strncpy_s(deviceInfo.id.pulse, sizeof(deviceInfo.id.pulse), pSinkInfo->name, (size_t)-1); } - // The description from PulseAudio is the name for miniaudio. + /* The description from PulseAudio is the name for miniaudio. */ if (pSinkInfo->description != NULL) { ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), pSinkInfo->description, (size_t)-1); } pData->isTerminated = !pData->callback(pData->pContext, ma_device_type_capture, &deviceInfo, pData->pUserData); + + (void)pPulseContext; /* Unused. */ } ma_result ma_context_enumerate_devices__pulse(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData) { + ma_result result = MA_SUCCESS; + ma_context_enumerate_devices_callback_data__pulse callbackData; + ma_pa_operation* pOP = NULL; + ma_pa_mainloop* pMainLoop; + ma_pa_mainloop_api* pAPI; + ma_pa_context* pPulseContext; + int error; + ma_assert(pContext != NULL); ma_assert(callback != NULL); - ma_result result = MA_SUCCESS; - - ma_context_enumerate_devices_callback_data__pulse callbackData; callbackData.pContext = pContext; callbackData.callback = callback; callbackData.pUserData = pUserData; callbackData.isTerminated = MA_FALSE; - ma_pa_operation* pOP = NULL; - - ma_pa_mainloop* pMainLoop = ((ma_pa_mainloop_new_proc)pContext->pulse.pa_mainloop_new)(); + pMainLoop = ((ma_pa_mainloop_new_proc)pContext->pulse.pa_mainloop_new)(); if (pMainLoop == NULL) { return MA_FAILED_TO_INIT_BACKEND; } - ma_pa_mainloop_api* pAPI = ((ma_pa_mainloop_get_api_proc)pContext->pulse.pa_mainloop_get_api)(pMainLoop); + pAPI = ((ma_pa_mainloop_get_api_proc)pContext->pulse.pa_mainloop_get_api)(pMainLoop); if (pAPI == NULL) { ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); return MA_FAILED_TO_INIT_BACKEND; } - ma_pa_context* pPulseContext = ((ma_pa_context_new_proc)pContext->pulse.pa_context_new)(pAPI, pContext->pulse.pApplicationName); + pPulseContext = ((ma_pa_context_new_proc)pContext->pulse.pa_context_new)(pAPI, pContext->pulse.pApplicationName); if (pPulseContext == NULL) { ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); return MA_FAILED_TO_INIT_BACKEND; } - int error = ((ma_pa_context_connect_proc)pContext->pulse.pa_context_connect)(pPulseContext, pContext->pulse.pServerName, (pContext->pulse.tryAutoSpawn) ? 0 : MA_PA_CONTEXT_NOAUTOSPAWN, NULL); + error = ((ma_pa_context_connect_proc)pContext->pulse.pa_context_connect)(pPulseContext, pContext->pulse.pServerName, (pContext->pulse.tryAutoSpawn) ? 0 : MA_PA_CONTEXT_NOAUTOSPAWN, NULL); if (error != MA_PA_OK) { ((ma_pa_context_unref_proc)pContext->pulse.pa_context_unref)(pPulseContext); ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); @@ -14101,7 +14523,7 @@ ma_result ma_context_enumerate_devices__pulse(ma_context* pContext, ma_enum_devi } - // Playback. + /* Playback. */ if (!callbackData.isTerminated) { pOP = ((ma_pa_context_get_sink_info_list_proc)pContext->pulse.pa_context_get_sink_info_list)(pPulseContext, ma_context_enumerate_devices_sink_callback__pulse, &callbackData); if (pOP == NULL) { @@ -14117,7 +14539,7 @@ ma_result ma_context_enumerate_devices__pulse(ma_context* pContext, ma_enum_devi } - // Capture. + /* Capture. */ if (!callbackData.isTerminated) { pOP = ((ma_pa_context_get_source_info_list_proc)pContext->pulse.pa_context_get_source_info_list)(pPulseContext, ma_context_enumerate_devices_source_callback__pulse, &callbackData); if (pOP == NULL) { @@ -14148,13 +14570,12 @@ typedef struct void ma_context_get_device_info_sink_callback__pulse(ma_pa_context* pPulseContext, const ma_pa_sink_info* pInfo, int endOfList, void* pUserData) { - (void)pPulseContext; + ma_context_get_device_info_callback_data__pulse* pData = (ma_context_get_device_info_callback_data__pulse*)pUserData; if (endOfList > 0) { return; } - ma_context_get_device_info_callback_data__pulse* pData = (ma_context_get_device_info_callback_data__pulse*)pUserData; ma_assert(pData != NULL); pData->foundDevice = MA_TRUE; @@ -14172,17 +14593,18 @@ void ma_context_get_device_info_sink_callback__pulse(ma_pa_context* pPulseContex pData->pDeviceInfo->maxSampleRate = pInfo->sample_spec.rate; pData->pDeviceInfo->formatCount = 1; pData->pDeviceInfo->formats[0] = ma_format_from_pulse(pInfo->sample_spec.format); + + (void)pPulseContext; /* Unused. */ } void ma_context_get_device_info_source_callback__pulse(ma_pa_context* pPulseContext, const ma_pa_source_info* pInfo, int endOfList, void* pUserData) { - (void)pPulseContext; + ma_context_get_device_info_callback_data__pulse* pData = (ma_context_get_device_info_callback_data__pulse*)pUserData; if (endOfList > 0) { return; } - ma_context_get_device_info_callback_data__pulse* pData = (ma_context_get_device_info_callback_data__pulse*)pUserData; ma_assert(pData != NULL); pData->foundDevice = MA_TRUE; @@ -14200,10 +14622,20 @@ void ma_context_get_device_info_source_callback__pulse(ma_pa_context* pPulseCont pData->pDeviceInfo->maxSampleRate = pInfo->sample_spec.rate; pData->pDeviceInfo->formatCount = 1; pData->pDeviceInfo->formats[0] = ma_format_from_pulse(pInfo->sample_spec.format); + + (void)pPulseContext; /* Unused. */ } ma_result ma_context_get_device_info__pulse(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_share_mode shareMode, ma_device_info* pDeviceInfo) { + ma_result result = MA_SUCCESS; + ma_context_get_device_info_callback_data__pulse callbackData; + ma_pa_operation* pOP = NULL; + ma_pa_mainloop* pMainLoop; + ma_pa_mainloop_api* pAPI; + ma_pa_context* pPulseContext; + int error; + ma_assert(pContext != NULL); /* No exclusive mode with the PulseAudio backend. */ @@ -14211,32 +14643,27 @@ ma_result ma_context_get_device_info__pulse(ma_context* pContext, ma_device_type return MA_SHARE_MODE_NOT_SUPPORTED; } - ma_result result = MA_SUCCESS; - - ma_context_get_device_info_callback_data__pulse callbackData; callbackData.pDeviceInfo = pDeviceInfo; callbackData.foundDevice = MA_FALSE; - ma_pa_operation* pOP = NULL; - - ma_pa_mainloop* pMainLoop = ((ma_pa_mainloop_new_proc)pContext->pulse.pa_mainloop_new)(); + pMainLoop = ((ma_pa_mainloop_new_proc)pContext->pulse.pa_mainloop_new)(); if (pMainLoop == NULL) { return MA_FAILED_TO_INIT_BACKEND; } - ma_pa_mainloop_api* pAPI = ((ma_pa_mainloop_get_api_proc)pContext->pulse.pa_mainloop_get_api)(pMainLoop); + pAPI = ((ma_pa_mainloop_get_api_proc)pContext->pulse.pa_mainloop_get_api)(pMainLoop); if (pAPI == NULL) { ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); return MA_FAILED_TO_INIT_BACKEND; } - ma_pa_context* pPulseContext = ((ma_pa_context_new_proc)pContext->pulse.pa_context_new)(pAPI, pContext->pulse.pApplicationName); + pPulseContext = ((ma_pa_context_new_proc)pContext->pulse.pa_context_new)(pAPI, pContext->pulse.pApplicationName); if (pPulseContext == NULL) { ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); return MA_FAILED_TO_INIT_BACKEND; } - int error = ((ma_pa_context_connect_proc)pContext->pulse.pa_context_connect)(pPulseContext, pContext->pulse.pServerName, 0, NULL); + error = ((ma_pa_context_connect_proc)pContext->pulse.pa_context_connect)(pPulseContext, pContext->pulse.pServerName, 0, NULL); if (error != MA_PA_OK) { ((ma_pa_context_unref_proc)pContext->pulse.pa_context_unref)(pPulseContext); ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); @@ -14298,10 +14725,13 @@ done: void ma_pulse_device_state_callback(ma_pa_context* pPulseContext, void* pUserData) { - ma_device* pDevice = (ma_device*)pUserData; + ma_device* pDevice; + ma_context* pContext; + + pDevice = (ma_device*)pUserData; ma_assert(pDevice != NULL); - ma_context* pContext = pDevice->pContext; + pContext = pDevice->pContext; ma_assert(pContext != NULL); pDevice->pulse.pulseContextState = ((ma_pa_context_get_state_proc)pContext->pulse.pa_context_get_state)(pPulseContext); @@ -14309,65 +14739,75 @@ void ma_pulse_device_state_callback(ma_pa_context* pPulseContext, void* pUserDat void ma_device_sink_info_callback(ma_pa_context* pPulseContext, const ma_pa_sink_info* pInfo, int endOfList, void* pUserData) { - (void)pPulseContext; + ma_pa_sink_info* pInfoOut; if (endOfList > 0) { return; } - ma_pa_sink_info* pInfoOut = (ma_pa_sink_info*)pUserData; + pInfoOut = (ma_pa_sink_info*)pUserData; ma_assert(pInfoOut != NULL); *pInfoOut = *pInfo; + + (void)pPulseContext; /* Unused. */ } void ma_device_source_info_callback(ma_pa_context* pPulseContext, const ma_pa_source_info* pInfo, int endOfList, void* pUserData) { - (void)pPulseContext; + ma_pa_source_info* pInfoOut; if (endOfList > 0) { return; } - ma_pa_source_info* pInfoOut = (ma_pa_source_info*)pUserData; + pInfoOut = (ma_pa_source_info*)pUserData; ma_assert(pInfoOut != NULL); *pInfoOut = *pInfo; + + (void)pPulseContext; /* Unused. */ } void ma_device_sink_name_callback(ma_pa_context* pPulseContext, const ma_pa_sink_info* pInfo, int endOfList, void* pUserData) { - (void)pPulseContext; + ma_device* pDevice; if (endOfList > 0) { return; } - ma_device* pDevice = (ma_device*)pUserData; + pDevice = (ma_device*)pUserData; ma_assert(pDevice != NULL); ma_strncpy_s(pDevice->playback.name, sizeof(pDevice->playback.name), pInfo->description, (size_t)-1); + + (void)pPulseContext; /* Unused. */ } void ma_device_source_name_callback(ma_pa_context* pPulseContext, const ma_pa_source_info* pInfo, int endOfList, void* pUserData) { - (void)pPulseContext; + ma_device* pDevice; if (endOfList > 0) { return; } - ma_device* pDevice = (ma_device*)pUserData; + pDevice = (ma_device*)pUserData; ma_assert(pDevice != NULL); ma_strncpy_s(pDevice->capture.name, sizeof(pDevice->capture.name), pInfo->description, (size_t)-1); + + (void)pPulseContext; /* Unused. */ } void ma_device_uninit__pulse(ma_device* pDevice) { + ma_context* pContext; + ma_assert(pDevice != NULL); - ma_context* pContext = pDevice->pContext; + pContext = pDevice->pContext; ma_assert(pContext != NULL); if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { @@ -14399,13 +14839,13 @@ ma_pa_buffer_attr ma_device__pa_buffer_attr_new(ma_uint32 bufferSizeInFrames, ma ma_pa_stream* ma_device__pa_stream_new__pulse(ma_device* pDevice, const char* pStreamName, const ma_pa_sample_spec* ss, const ma_pa_channel_map* cmap) { static int g_StreamCounter = 0; - char actualStreamName[256]; + if (pStreamName != NULL) { ma_strncpy_s(actualStreamName, sizeof(actualStreamName), pStreamName, (size_t)-1); } else { ma_strcpy_s(actualStreamName, sizeof(actualStreamName), "miniaudio:"); - ma_itoa_s(g_StreamCounter, actualStreamName + 8, sizeof(actualStreamName)-8, 10); // 8 = strlen("miniaudio:") + ma_itoa_s(g_StreamCounter, actualStreamName + 8, sizeof(actualStreamName)-8, 10); /* 8 = strlen("miniaudio:") */ } g_StreamCounter += 1; @@ -14414,15 +14854,25 @@ ma_pa_stream* ma_device__pa_stream_new__pulse(ma_device* pDevice, const char* pS ma_result ma_device_init__pulse(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice) { - (void)pContext; - - ma_assert(pDevice != NULL); - ma_zero_object(&pDevice->pulse); - ma_result result = MA_SUCCESS; int error = 0; const char* devPlayback = NULL; const char* devCapture = NULL; + ma_uint32 bufferSizeInMilliseconds; + ma_pa_sink_info sinkInfo; + ma_pa_source_info sourceInfo; + ma_pa_operation* pOP = NULL; + ma_pa_sample_spec ss; + ma_pa_channel_map cmap; + ma_pa_buffer_attr attr; + const ma_pa_sample_spec* pActualSS = NULL; + const ma_pa_channel_map* pActualCMap = NULL; + const ma_pa_buffer_attr* pActualAttr = NULL; + ma_uint32 iChannel; + ma_pa_stream_flags_t streamFlags; + + ma_assert(pDevice != NULL); + ma_zero_object(&pDevice->pulse); /* No exclusive mode with the PulseAudio backend. */ if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pConfig->playback.shareMode == ma_share_mode_exclusive) || @@ -14437,25 +14887,11 @@ ma_result ma_device_init__pulse(ma_context* pContext, const ma_device_config* pC devCapture = pConfig->capture.pDeviceID->pulse; } - ma_uint32 bufferSizeInMilliseconds = pConfig->bufferSizeInMilliseconds; + bufferSizeInMilliseconds = pConfig->bufferSizeInMilliseconds; if (bufferSizeInMilliseconds == 0) { bufferSizeInMilliseconds = ma_calculate_buffer_size_in_milliseconds_from_frames(pConfig->bufferSizeInFrames, pConfig->sampleRate); } - ma_pa_sink_info sinkInfo; - ma_pa_source_info sourceInfo; - ma_pa_operation* pOP = NULL; - - ma_pa_sample_spec ss; - ma_pa_channel_map cmap; - ma_pa_buffer_attr attr; - - const ma_pa_sample_spec* pActualSS = NULL; - const ma_pa_channel_map* pActualCMap = NULL; - const ma_pa_buffer_attr* pActualAttr = NULL; - - - pDevice->pulse.pMainLoop = ((ma_pa_mainloop_new_proc)pContext->pulse.pa_mainloop_new)(); if (pDevice->pulse.pMainLoop == NULL) { result = ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to create main loop for device.", MA_FAILED_TO_INIT_BACKEND); @@ -14484,7 +14920,7 @@ ma_result ma_device_init__pulse(ma_context* pContext, const ma_device_config* pC pDevice->pulse.pulseContextState = MA_PA_CONTEXT_UNCONNECTED; ((ma_pa_context_set_state_callback_proc)pContext->pulse.pa_context_set_state_callback)((ma_pa_context*)pDevice->pulse.pPulseContext, ma_pulse_device_state_callback, pDevice); - // Wait for PulseAudio to get itself ready before returning. + /* Wait for PulseAudio to get itself ready before returning. */ for (;;) { if (pDevice->pulse.pulseContextState == MA_PA_CONTEXT_READY) { break; @@ -14530,7 +14966,7 @@ ma_result ma_device_init__pulse(ma_context* pContext, const ma_device_config* pC goto on_error3; } - ma_pa_stream_flags_t streamFlags = MA_PA_STREAM_START_CORKED | MA_PA_STREAM_FIX_FORMAT | MA_PA_STREAM_FIX_RATE | MA_PA_STREAM_FIX_CHANNELS; + streamFlags = MA_PA_STREAM_START_CORKED | MA_PA_STREAM_FIX_FORMAT | MA_PA_STREAM_FIX_RATE | MA_PA_STREAM_FIX_CHANNELS; if (devCapture != NULL) { streamFlags |= MA_PA_STREAM_DONT_MOVE; } @@ -14575,7 +15011,7 @@ ma_result ma_device_init__pulse(ma_context* pContext, const ma_device_config* pC if (pActualCMap != NULL) { cmap = *pActualCMap; } - for (ma_uint32 iChannel = 0; iChannel < pDevice->capture.internalChannels; ++iChannel) { + for (iChannel = 0; iChannel < pDevice->capture.internalChannels; ++iChannel) { pDevice->capture.internalChannelMap[iChannel] = ma_channel_position_from_pulse(cmap.map[iChannel]); } @@ -14628,7 +15064,7 @@ ma_result ma_device_init__pulse(ma_context* pContext, const ma_device_config* pC goto on_error3; } - ma_pa_stream_flags_t streamFlags = MA_PA_STREAM_START_CORKED | MA_PA_STREAM_FIX_FORMAT | MA_PA_STREAM_FIX_RATE | MA_PA_STREAM_FIX_CHANNELS; + streamFlags = MA_PA_STREAM_START_CORKED | MA_PA_STREAM_FIX_FORMAT | MA_PA_STREAM_FIX_RATE | MA_PA_STREAM_FIX_CHANNELS; if (devPlayback != NULL) { streamFlags |= MA_PA_STREAM_DONT_MOVE; } @@ -14673,7 +15109,7 @@ ma_result ma_device_init__pulse(ma_context* pContext, const ma_device_config* pC if (pActualCMap != NULL) { cmap = *pActualCMap; } - for (ma_uint32 iChannel = 0; iChannel < pDevice->playback.internalChannels; ++iChannel) { + for (iChannel = 0; iChannel < pDevice->playback.internalChannels; ++iChannel) { pDevice->playback.internalChannelMap[iChannel] = ma_channel_position_from_pulse(cmap.map[iChannel]); } @@ -14728,35 +15164,38 @@ on_error0: void ma_pulse_operation_complete_callback(ma_pa_stream* pStream, int success, void* pUserData) { - (void)pStream; - ma_bool32* pIsSuccessful = (ma_bool32*)pUserData; ma_assert(pIsSuccessful != NULL); *pIsSuccessful = (ma_bool32)success; + + (void)pStream; /* Unused. */ } ma_result ma_device__cork_stream__pulse(ma_device* pDevice, ma_device_type deviceType, int cork) { ma_context* pContext = pDevice->pContext; - ma_assert(pContext != NULL); + ma_bool32 wasSuccessful; + ma_pa_stream* pStream; + ma_pa_operation* pOP; + ma_result result; /* This should not be called with a duplex device type. */ if (deviceType == ma_device_type_duplex) { return MA_INVALID_ARGS; } - ma_bool32 wasSuccessful = MA_FALSE; + wasSuccessful = MA_FALSE; - ma_pa_stream* pStream = (ma_pa_stream*)((deviceType == ma_device_type_capture) ? pDevice->pulse.pStreamCapture : pDevice->pulse.pStreamPlayback); + pStream = (ma_pa_stream*)((deviceType == ma_device_type_capture) ? pDevice->pulse.pStreamCapture : pDevice->pulse.pStreamPlayback); ma_assert(pStream != NULL); - ma_pa_operation* pOP = ((ma_pa_stream_cork_proc)pContext->pulse.pa_stream_cork)(pStream, cork, ma_pulse_operation_complete_callback, &wasSuccessful); + pOP = ((ma_pa_stream_cork_proc)pContext->pulse.pa_stream_cork)(pStream, cork, ma_pulse_operation_complete_callback, &wasSuccessful); if (pOP == NULL) { return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to cork PulseAudio stream.", (cork == 0) ? MA_FAILED_TO_START_BACKEND_DEVICE : MA_FAILED_TO_STOP_BACKEND_DEVICE); } - ma_result result = ma_device__wait_for_operation__pulse(pDevice, pOP); + result = ma_device__wait_for_operation__pulse(pDevice, pOP); ((ma_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP); if (result != MA_SUCCESS) { @@ -14808,6 +15247,8 @@ ma_result ma_device_stop__pulse(ma_device* pDevice) ma_result ma_device_write__pulse(ma_device* pDevice, const void* pPCMFrames, ma_uint32 frameCount) { + ma_uint32 totalFramesWritten; + ma_assert(pDevice != NULL); ma_assert(pPCMFrames != NULL); ma_assert(frameCount > 0); @@ -14820,14 +15261,10 @@ ma_result ma_device_write__pulse(ma_device* pDevice, const void* pPCMFrames, ma_ } } - ma_uint32 totalFramesWritten = 0; + totalFramesWritten = 0; while (totalFramesWritten < frameCount) { - //printf("TRACE: Outer loop.\n"); - /* Place the data into the mapped buffer if we have one. */ if (pDevice->pulse.pMappedBufferPlayback != NULL && pDevice->pulse.mappedBufferFramesRemainingPlayback > 0) { - //printf("TRACE: Copying data.\n"); - ma_uint32 bpf = ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels); ma_uint32 mappedBufferFramesConsumed = pDevice->pulse.mappedBufferFramesCapacityPlayback - pDevice->pulse.mappedBufferFramesRemainingPlayback; @@ -14846,7 +15283,6 @@ ma_result ma_device_write__pulse(ma_device* pDevice, const void* pPCMFrames, ma_ */ if (pDevice->pulse.mappedBufferFramesCapacityPlayback > 0 && pDevice->pulse.mappedBufferFramesRemainingPlayback == 0) { size_t nbytes = pDevice->pulse.mappedBufferFramesCapacityPlayback * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels); - //printf("TRACE: Submitting data. %d\n", nbytes); int error = ((ma_pa_stream_write_proc)pDevice->pContext->pulse.pa_stream_write)((ma_pa_stream*)pDevice->pulse.pStreamPlayback, pDevice->pulse.pMappedBufferPlayback, nbytes, NULL, 0, MA_PA_SEEK_RELATIVE); if (error < 0) { @@ -14865,21 +15301,17 @@ ma_result ma_device_write__pulse(ma_device* pDevice, const void* pPCMFrames, ma_ /* Getting here means we need to map a new buffer. If we don't have enough space we need to wait for more. */ for (;;) { - //printf("TRACE: Inner loop.\n"); + size_t writableSizeInBytes; /* If the device has been corked, don't try to continue. */ if (((ma_pa_stream_is_corked_proc)pDevice->pContext->pulse.pa_stream_is_corked)((ma_pa_stream*)pDevice->pulse.pStreamPlayback)) { break; } - size_t writableSizeInBytes = ((ma_pa_stream_writable_size_proc)pDevice->pContext->pulse.pa_stream_writable_size)((ma_pa_stream*)pDevice->pulse.pStreamPlayback); + writableSizeInBytes = ((ma_pa_stream_writable_size_proc)pDevice->pContext->pulse.pa_stream_writable_size)((ma_pa_stream*)pDevice->pulse.pStreamPlayback); if (writableSizeInBytes != (size_t)-1) { - //size_t periodSizeInBytes = (pDevice->playback.internalBufferSizeInFrames / pDevice->playback.internalPeriods) * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels); + /*size_t periodSizeInBytes = (pDevice->playback.internalBufferSizeInFrames / pDevice->playback.internalPeriods) * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);*/ if (writableSizeInBytes > 0) { - #if defined(MA_DEBUG_OUTPUT) - //printf("TRACE: Data available: %ld\n", writableSizeInBytes); - #endif - /* Data is avaialable. */ size_t bytesToMap = writableSizeInBytes; int error = ((ma_pa_stream_begin_write_proc)pDevice->pContext->pulse.pa_stream_begin_write)((ma_pa_stream*)pDevice->pulse.pStreamPlayback, &pDevice->pulse.pMappedBufferPlayback, &bytesToMap); @@ -14893,10 +15325,6 @@ ma_result ma_device_write__pulse(ma_device* pDevice, const void* pPCMFrames, ma_ break; } else { /* No data available. Need to wait for more. */ - #if defined(MA_DEBUG_OUTPUT) - //printf("TRACE: Playback: pa_mainloop_iterate(). writableSizeInBytes=%ld, periodSizeInBytes=%ld\n", writableSizeInBytes, periodSizeInBytes); - #endif - int error = ((ma_pa_mainloop_iterate_proc)pDevice->pContext->pulse.pa_mainloop_iterate)((ma_pa_mainloop*)pDevice->pulse.pMainLoop, 1, NULL); if (error < 0) { return ma_result_from_pulse(error); @@ -14915,6 +15343,8 @@ ma_result ma_device_write__pulse(ma_device* pDevice, const void* pPCMFrames, ma_ ma_result ma_device_read__pulse(ma_device* pDevice, void* pPCMFrames, ma_uint32 frameCount) { + ma_uint32 totalFramesRead; + ma_assert(pDevice != NULL); ma_assert(pPCMFrames != NULL); ma_assert(frameCount > 0); @@ -14927,7 +15357,7 @@ ma_result ma_device_read__pulse(ma_device* pDevice, void* pPCMFrames, ma_uint32 } } - ma_uint32 totalFramesRead = 0; + totalFramesRead = 0; while (totalFramesRead < frameCount) { if (ma_device__get_state(pDevice) != MA_STATE_STARTED) { break; @@ -14961,8 +15391,6 @@ ma_result ma_device_read__pulse(ma_device* pDevice, void* pPCMFrames, ma_uint32 mapping another chunk. If this fails we need to wait for data to become available. */ if (pDevice->pulse.mappedBufferFramesCapacityCapture > 0 && pDevice->pulse.mappedBufferFramesRemainingCapture == 0) { - //printf("TRACE: Dropping fragment. %d\n", nbytes); - int error = ((ma_pa_stream_drop_proc)pDevice->pContext->pulse.pa_stream_drop)((ma_pa_stream*)pDevice->pulse.pStreamCapture); if (error != 0) { return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to drop fragment.", ma_result_from_pulse(error)); @@ -14980,7 +15408,7 @@ ma_result ma_device_read__pulse(ma_device* pDevice, void* pPCMFrames, ma_uint32 /* Getting here means we need to map a new buffer. If we don't have enough data we wait for more. */ for (;;) { - //printf("TRACE: Inner loop.\n"); + size_t readableSizeInBytes; if (ma_device__get_state(pDevice) != MA_STATE_STARTED) { break; @@ -14991,9 +15419,9 @@ ma_result ma_device_read__pulse(ma_device* pDevice, void* pPCMFrames, ma_uint32 break; } - size_t readableSizeInBytes = ((ma_pa_stream_readable_size_proc)pDevice->pContext->pulse.pa_stream_readable_size)((ma_pa_stream*)pDevice->pulse.pStreamCapture); + readableSizeInBytes = ((ma_pa_stream_readable_size_proc)pDevice->pContext->pulse.pa_stream_readable_size)((ma_pa_stream*)pDevice->pulse.pStreamCapture); if (readableSizeInBytes != (size_t)-1) { - //size_t periodSizeInBytes = (pDevice->capture.internalBufferSizeInFrames / pDevice->capture.internalPeriods) * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels); + /*size_t periodSizeInBytes = (pDevice->capture.internalBufferSizeInFrames / pDevice->capture.internalPeriods) * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);*/ if (readableSizeInBytes > 0) { /* Data is avaialable. */ size_t bytesMapped = (size_t)-1; @@ -15002,10 +15430,6 @@ ma_result ma_device_read__pulse(ma_device* pDevice, void* pPCMFrames, ma_uint32 return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to peek capture buffer.", ma_result_from_pulse(error)); } - #if defined(MA_DEBUG_OUTPUT) - //printf("TRACE: Data available: bytesMapped=%ld, readableSizeInBytes=%ld.\n", bytesMapped, readableSizeInBytes); - #endif - if (pDevice->pulse.pMappedBufferCapture == NULL && bytesMapped == 0) { /* Nothing available. This shouldn't happen because we checked earlier with pa_stream_readable_size(). I'm going to throw an error in this case. */ return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[PulseAudio] Nothing available after peeking capture buffer.", MA_ERROR); @@ -15017,13 +15441,10 @@ ma_result ma_device_read__pulse(ma_device* pDevice, void* pPCMFrames, ma_uint32 break; } else { /* No data available. Need to wait for more. */ - #if defined(MA_DEBUG_OUTPUT) - //printf("TRACE: Capture: pa_mainloop_iterate(). readableSizeInBytes=%ld\n", readableSizeInBytes); - #endif /* I have had reports of a deadlock in this part of the code. I have reproduced this when using the "Built-in Audio Analogue Stereo" device without - an actual microphone connected. I'm experimenting here by not blocking in pa_mainloop_iterate() and instead sleep for a bit when there are not + an actual microphone connected. I'm experimenting here by not blocking in pa_mainloop_iterate() and instead sleep for a bit when there are no dispatches. */ int error = ((ma_pa_mainloop_iterate_proc)pDevice->pContext->pulse.pa_mainloop_iterate)((ma_pa_mainloop*)pDevice->pulse.pMainLoop, 0, NULL); @@ -15068,16 +15489,14 @@ ma_result ma_context_uninit__pulse(ma_context* pContext) ma_result ma_context_init__pulse(const ma_context_config* pConfig, ma_context* pContext) { - ma_assert(pContext != NULL); - #ifndef MA_NO_RUNTIME_LINKING - // libpulse.so const char* libpulseNames[] = { "libpulse.so", "libpulse.so.0" }; + size_t i; - for (size_t i = 0; i < ma_countof(libpulseNames); ++i) { + for (i = 0; i < ma_countof(libpulseNames); ++i) { pContext->pulse.pulseSO = ma_dlopen(libpulseNames[i]); if (pContext->pulse.pulseSO != NULL) { break; @@ -15133,7 +15552,7 @@ ma_result ma_context_init__pulse(const ma_context_config* pConfig, ma_context* p pContext->pulse.pa_stream_writable_size = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_stream_writable_size"); pContext->pulse.pa_stream_readable_size = (ma_proc)ma_dlsym(pContext->pulse.pulseSO, "pa_stream_readable_size"); #else - // This strange assignment system is just for type safety. + /* This strange assignment system is just for type safety. */ ma_pa_mainloop_new_proc _pa_mainloop_new = pa_mainloop_new; ma_pa_mainloop_free_proc _pa_mainloop_free = pa_mainloop_free; ma_pa_mainloop_get_api_proc _pa_mainloop_get_api = pa_mainloop_get_api; @@ -15244,56 +15663,78 @@ ma_result ma_context_init__pulse(const ma_context_config* pConfig, ma_context* p } pContext->pulse.tryAutoSpawn = pConfig->pulse.tryAutoSpawn; - // Although we have found the libpulse library, it doesn't necessarily mean PulseAudio is useable. We need to initialize - // and connect a dummy PulseAudio context to test PulseAudio's usability. - ma_pa_mainloop* pMainLoop = ((ma_pa_mainloop_new_proc)pContext->pulse.pa_mainloop_new)(); - if (pMainLoop == NULL) { - ma_free(pContext->pulse.pServerName); - ma_free(pContext->pulse.pApplicationName); - return MA_NO_BACKEND; - } + /* + Although we have found the libpulse library, it doesn't necessarily mean PulseAudio is useable. We need to initialize + and connect a dummy PulseAudio context to test PulseAudio's usability. + */ + { + ma_pa_mainloop* pMainLoop; + ma_pa_mainloop_api* pAPI; + ma_pa_context* pPulseContext; + int error; + + pMainLoop = ((ma_pa_mainloop_new_proc)pContext->pulse.pa_mainloop_new)(); + if (pMainLoop == NULL) { + ma_free(pContext->pulse.pServerName); + ma_free(pContext->pulse.pApplicationName); + #ifndef MA_NO_RUNTIME_LINKING + ma_dlclose(pContext->pulse.pulseSO); + #endif + return MA_NO_BACKEND; + } - ma_pa_mainloop_api* pAPI = ((ma_pa_mainloop_get_api_proc)pContext->pulse.pa_mainloop_get_api)(pMainLoop); - if (pAPI == NULL) { - ma_free(pContext->pulse.pServerName); - ma_free(pContext->pulse.pApplicationName); - ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); - return MA_NO_BACKEND; - } + pAPI = ((ma_pa_mainloop_get_api_proc)pContext->pulse.pa_mainloop_get_api)(pMainLoop); + if (pAPI == NULL) { + ma_free(pContext->pulse.pServerName); + ma_free(pContext->pulse.pApplicationName); + ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); + #ifndef MA_NO_RUNTIME_LINKING + ma_dlclose(pContext->pulse.pulseSO); + #endif + return MA_NO_BACKEND; + } - ma_pa_context* pPulseContext = ((ma_pa_context_new_proc)pContext->pulse.pa_context_new)(pAPI, pContext->pulse.pApplicationName); - if (pPulseContext == NULL) { - ma_free(pContext->pulse.pServerName); - ma_free(pContext->pulse.pApplicationName); - ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); - return MA_NO_BACKEND; - } + pPulseContext = ((ma_pa_context_new_proc)pContext->pulse.pa_context_new)(pAPI, pContext->pulse.pApplicationName); + if (pPulseContext == NULL) { + ma_free(pContext->pulse.pServerName); + ma_free(pContext->pulse.pApplicationName); + ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); + #ifndef MA_NO_RUNTIME_LINKING + ma_dlclose(pContext->pulse.pulseSO); + #endif + return MA_NO_BACKEND; + } - int error = ((ma_pa_context_connect_proc)pContext->pulse.pa_context_connect)(pPulseContext, pContext->pulse.pServerName, 0, NULL); - if (error != MA_PA_OK) { - ma_free(pContext->pulse.pServerName); - ma_free(pContext->pulse.pApplicationName); + error = ((ma_pa_context_connect_proc)pContext->pulse.pa_context_connect)(pPulseContext, pContext->pulse.pServerName, 0, NULL); + if (error != MA_PA_OK) { + ma_free(pContext->pulse.pServerName); + ma_free(pContext->pulse.pApplicationName); + ((ma_pa_context_unref_proc)pContext->pulse.pa_context_unref)(pPulseContext); + ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); + #ifndef MA_NO_RUNTIME_LINKING + ma_dlclose(pContext->pulse.pulseSO); + #endif + return MA_NO_BACKEND; + } + + ((ma_pa_context_disconnect_proc)pContext->pulse.pa_context_disconnect)(pPulseContext); ((ma_pa_context_unref_proc)pContext->pulse.pa_context_unref)(pPulseContext); ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); - return MA_NO_BACKEND; } - ((ma_pa_context_disconnect_proc)pContext->pulse.pa_context_disconnect)(pPulseContext); - ((ma_pa_context_unref_proc)pContext->pulse.pa_context_unref)(pPulseContext); - ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)(pMainLoop); return MA_SUCCESS; } #endif -/////////////////////////////////////////////////////////////////////////////// -// -// JACK Backend -// -/////////////////////////////////////////////////////////////////////////////// +/****************************************************************************** + +JACK Backend + +******************************************************************************/ #ifdef MA_HAS_JACK -// It is assumed jack.h is available when compile-time linking is being used. +/* It is assumed jack.h is available when compile-time linking is being used. */ #ifdef MA_NO_RUNTIME_LINKING #include @@ -15345,6 +15786,11 @@ typedef void (* ma_jack_free_proc) (void* ptr); ma_result ma_context_open_client__jack(ma_context* pContext, ma_jack_client_t** ppClient) { + size_t maxClientNameSize; + char clientName[256]; + ma_jack_status_t status; + ma_jack_client_t* pClient; + ma_assert(pContext != NULL); ma_assert(ppClient != NULL); @@ -15352,13 +15798,10 @@ ma_result ma_context_open_client__jack(ma_context* pContext, ma_jack_client_t** *ppClient = NULL; } - size_t maxClientNameSize = ((ma_jack_client_name_size_proc)pContext->jack.jack_client_name_size)(); // Includes null terminator. - - char clientName[256]; + maxClientNameSize = ((ma_jack_client_name_size_proc)pContext->jack.jack_client_name_size)(); /* Includes null terminator. */ ma_strncpy_s(clientName, ma_min(sizeof(clientName), maxClientNameSize), (pContext->jack.pClientName != NULL) ? pContext->jack.pClientName : "miniaudio", (size_t)-1); - ma_jack_status_t status; - ma_jack_client_t* pClient = ((ma_jack_client_open_proc)pContext->jack.jack_client_open)(clientName, (pContext->jack.tryStartServer) ? 0 : ma_JackNoStartServer, &status, NULL); + pClient = ((ma_jack_client_open_proc)pContext->jack.jack_client_open)(clientName, (pContext->jack.tryStartServer) ? 0 : ma_JackNoStartServer, &status, NULL); if (pClient == NULL) { return MA_FAILED_TO_OPEN_BACKEND_DEVICE; } @@ -15382,12 +15825,12 @@ ma_bool32 ma_context_is_device_id_equal__jack(ma_context* pContext, const ma_dev ma_result ma_context_enumerate_devices__jack(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData) { + ma_bool32 cbResult = MA_TRUE; + ma_assert(pContext != NULL); ma_assert(callback != NULL); - ma_bool32 cbResult = MA_TRUE; - - // Playback. + /* Playback. */ if (cbResult) { ma_device_info deviceInfo; ma_zero_object(&deviceInfo); @@ -15395,7 +15838,7 @@ ma_result ma_context_enumerate_devices__jack(ma_context* pContext, ma_enum_devic cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData); } - // Capture. + /* Capture. */ if (cbResult) { ma_device_info deviceInfo; ma_zero_object(&deviceInfo); @@ -15408,9 +15851,11 @@ ma_result ma_context_enumerate_devices__jack(ma_context* pContext, ma_enum_devic ma_result ma_context_get_device_info__jack(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_share_mode shareMode, ma_device_info* pDeviceInfo) { - ma_assert(pContext != NULL); + ma_jack_client_t* pClient; + ma_result result; + const char** ppPorts; - (void)pContext; + ma_assert(pContext != NULL); /* No exclusive mode with the JACK backend. */ if (shareMode == ma_share_mode_exclusive) { @@ -15418,23 +15863,22 @@ ma_result ma_context_get_device_info__jack(ma_context* pContext, ma_device_type } if (pDeviceID != NULL && pDeviceID->jack != 0) { - return MA_NO_DEVICE; // Don't know the device. + return MA_NO_DEVICE; /* Don't know the device. */ } - // Name / Description + /* Name / Description */ if (deviceType == ma_device_type_playback) { ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); } else { ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); } - // Jack only supports f32 and has a specific channel count and sample rate. + /* Jack only supports f32 and has a specific channel count and sample rate. */ pDeviceInfo->formatCount = 1; pDeviceInfo->formats[0] = ma_format_f32; - // The channel count and sample rate can only be determined by opening the device. - ma_jack_client_t* pClient; - ma_result result = ma_context_open_client__jack(pContext, &pClient); + /* The channel count and sample rate can only be determined by opening the device. */ + result = ma_context_open_client__jack(pContext, &pClient); if (result != MA_SUCCESS) { return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[JACK] Failed to open client.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); } @@ -15445,7 +15889,7 @@ ma_result ma_context_get_device_info__jack(ma_context* pContext, ma_device_type pDeviceInfo->minChannels = 0; pDeviceInfo->maxChannels = 0; - const char** ppPorts = ((ma_jack_get_ports_proc)pContext->jack.jack_get_ports)((ma_jack_client_t*)pClient, NULL, NULL, ma_JackPortIsPhysical | ((deviceType == ma_device_type_playback) ? ma_JackPortIsInput : ma_JackPortIsOutput)); + ppPorts = ((ma_jack_get_ports_proc)pContext->jack.jack_get_ports)((ma_jack_client_t*)pClient, NULL, NULL, ma_JackPortIsPhysical | ((deviceType == ma_device_type_playback) ? ma_JackPortIsInput : ma_JackPortIsOutput)); if (ppPorts == NULL) { ((ma_jack_client_close_proc)pContext->jack.jack_client_close)((ma_jack_client_t*)pClient); return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[JACK] Failed to query physical ports.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); @@ -15459,15 +15903,18 @@ ma_result ma_context_get_device_info__jack(ma_context* pContext, ma_device_type ((ma_jack_free_proc)pContext->jack.jack_free)((void*)ppPorts); ((ma_jack_client_close_proc)pContext->jack.jack_client_close)((ma_jack_client_t*)pClient); + (void)pContext; return MA_SUCCESS; } void ma_device_uninit__jack(ma_device* pDevice) { + ma_context* pContext; + ma_assert(pDevice != NULL); - ma_context* pContext = pDevice->pContext; + pContext = pDevice->pContext; ma_assert(pContext != NULL); if (pDevice->jack.pClient != NULL) { @@ -15489,7 +15936,7 @@ void ma_device_uninit__jack(ma_device* pDevice) void ma_device__jack_shutdown_callback(void* pUserData) { - // JACK died. Stop the device. + /* JACK died. Stop the device. */ ma_device* pDevice = (ma_device*)pUserData; ma_assert(pDevice != NULL); @@ -15526,19 +15973,24 @@ int ma_device__jack_buffer_size_callback(ma_jack_nframes_t frameCount, void* pUs int ma_device__jack_process_callback(ma_jack_nframes_t frameCount, void* pUserData) { - ma_device* pDevice = (ma_device*)pUserData; + ma_device* pDevice; + ma_context* pContext; + ma_uint32 iChannel; + + pDevice = (ma_device*)pUserData; ma_assert(pDevice != NULL); - ma_context* pContext = pDevice->pContext; + pContext = pDevice->pContext; ma_assert(pContext != NULL); if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { - // Channels need to be interleaved. - for (ma_uint32 iChannel = 0; iChannel < pDevice->capture.internalChannels; ++iChannel) { + /* Channels need to be interleaved. */ + for (iChannel = 0; iChannel < pDevice->capture.internalChannels; ++iChannel) { const float* pSrc = (const float*)((ma_jack_port_get_buffer_proc)pContext->jack.jack_port_get_buffer)((ma_jack_port_t*)pDevice->jack.pPortsCapture[iChannel], frameCount); if (pSrc != NULL) { float* pDst = pDevice->jack.pIntermediaryBufferCapture + iChannel; - for (ma_jack_nframes_t iFrame = 0; iFrame < frameCount; ++iFrame) { + ma_jack_nframes_t iFrame; + for (iFrame = 0; iFrame < frameCount; ++iFrame) { *pDst = *pSrc; pDst += pDevice->capture.internalChannels; @@ -15561,12 +16013,13 @@ int ma_device__jack_process_callback(ma_jack_nframes_t frameCount, void* pUserDa ma_device__read_frames_from_client(pDevice, frameCount, pDevice->jack.pIntermediaryBufferPlayback); } - // Channels need to be deinterleaved. - for (ma_uint32 iChannel = 0; iChannel < pDevice->playback.internalChannels; ++iChannel) { + /* Channels need to be deinterleaved. */ + for (iChannel = 0; iChannel < pDevice->playback.internalChannels; ++iChannel) { float* pDst = (float*)((ma_jack_port_get_buffer_proc)pContext->jack.jack_port_get_buffer)((ma_jack_port_t*)pDevice->jack.pPortsPlayback[iChannel], frameCount); if (pDst != NULL) { const float* pSrc = pDevice->jack.pIntermediaryBufferPlayback + iChannel; - for (ma_jack_nframes_t iFrame = 0; iFrame < frameCount; ++iFrame) { + ma_jack_nframes_t iFrame; + for (iFrame = 0; iFrame < frameCount; ++iFrame) { *pDst = *pSrc; pDst += 1; @@ -15581,12 +16034,14 @@ int ma_device__jack_process_callback(ma_jack_nframes_t frameCount, void* pUserDa ma_result ma_device_init__jack(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice) { + ma_result result; + ma_uint32 periods; + ma_uint32 bufferSizeInFrames; + ma_assert(pContext != NULL); ma_assert(pConfig != NULL); ma_assert(pDevice != NULL); - (void)pContext; - /* Only supporting default devices with JACK. */ if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pConfig->playback.pDeviceID != NULL && pConfig->playback.pDeviceID->jack != 0) || ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pConfig->capture.pDeviceID != NULL && pConfig->capture.pDeviceID->jack != 0)) { @@ -15600,7 +16055,7 @@ ma_result ma_device_init__jack(ma_context* pContext, const ma_device_config* pCo } /* Open the client. */ - ma_result result = ma_context_open_client__jack(pContext, (ma_jack_client_t**)&pDevice->jack.pClient); + result = ma_context_open_client__jack(pContext, (ma_jack_client_t**)&pDevice->jack.pClient); if (result != MA_SUCCESS) { return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[JACK] Failed to open client.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); } @@ -15617,8 +16072,8 @@ ma_result ma_device_init__jack(ma_context* pContext, const ma_device_config* pCo /* The buffer size in frames can change. */ - ma_uint32 periods = 2; - ma_uint32 bufferSizeInFrames = ((ma_jack_get_buffer_size_proc)pContext->jack.jack_get_buffer_size)((ma_jack_client_t*)pDevice->jack.pClient) * periods; + periods = 2; + bufferSizeInFrames = ((ma_jack_get_buffer_size_proc)pContext->jack.jack_get_buffer_size)((ma_jack_client_t*)pDevice->jack.pClient) * periods; if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) { const char** ppPorts; @@ -15636,7 +16091,7 @@ ma_result ma_device_init__jack(ma_context* pContext, const ma_device_config* pCo while (ppPorts[pDevice->capture.internalChannels] != NULL) { char name[64]; ma_strcpy_s(name, sizeof(name), "capture"); - ma_itoa_s((int)pDevice->capture.internalChannels, name+7, sizeof(name)-7, 10); // 7 = length of "capture" + ma_itoa_s((int)pDevice->capture.internalChannels, name+7, sizeof(name)-7, 10); /* 7 = length of "capture" */ pDevice->jack.pPortsCapture[pDevice->capture.internalChannels] = ((ma_jack_port_register_proc)pContext->jack.jack_port_register)((ma_jack_client_t*)pDevice->jack.pClient, name, MA_JACK_DEFAULT_AUDIO_TYPE, ma_JackPortIsInput, 0); if (pDevice->jack.pPortsCapture[pDevice->capture.internalChannels] == NULL) { @@ -15676,7 +16131,7 @@ ma_result ma_device_init__jack(ma_context* pContext, const ma_device_config* pCo while (ppPorts[pDevice->playback.internalChannels] != NULL) { char name[64]; ma_strcpy_s(name, sizeof(name), "playback"); - ma_itoa_s((int)pDevice->playback.internalChannels, name+8, sizeof(name)-8, 10); // 8 = length of "playback" + ma_itoa_s((int)pDevice->playback.internalChannels, name+8, sizeof(name)-8, 10); /* 8 = length of "playback" */ pDevice->jack.pPortsPlayback[pDevice->playback.internalChannels] = ((ma_jack_port_register_proc)pContext->jack.jack_port_register)((ma_jack_client_t*)pDevice->jack.pClient, name, MA_JACK_DEFAULT_AUDIO_TYPE, ma_JackPortIsOutput, 0); if (pDevice->jack.pPortsPlayback[pDevice->playback.internalChannels] == NULL) { @@ -15715,12 +16170,11 @@ ma_result ma_device_init__jack(ma_context* pContext, const ma_device_config* pCo ma_result ma_device_start__jack(ma_device* pDevice) { - ma_assert(pDevice != NULL); - ma_context* pContext = pDevice->pContext; - ma_assert(pContext != NULL); + int resultJACK; + size_t i; - int resultJACK = ((ma_jack_activate_proc)pContext->jack.jack_activate)((ma_jack_client_t*)pDevice->jack.pClient); + resultJACK = ((ma_jack_activate_proc)pContext->jack.jack_activate)((ma_jack_client_t*)pDevice->jack.pClient); if (resultJACK != 0) { return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[JACK] Failed to activate the JACK client.", MA_FAILED_TO_START_BACKEND_DEVICE); } @@ -15732,7 +16186,7 @@ ma_result ma_device_start__jack(ma_device* pDevice) return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[JACK] Failed to retrieve physical ports.", MA_ERROR); } - for (size_t i = 0; ppServerPorts[i] != NULL; ++i) { + for (i = 0; ppServerPorts[i] != NULL; ++i) { const char* pServerPort = ppServerPorts[i]; const char* pClientPort = ((ma_jack_port_name_proc)pContext->jack.jack_port_name)((ma_jack_port_t*)pDevice->jack.pPortsCapture[i]); @@ -15754,7 +16208,7 @@ ma_result ma_device_start__jack(ma_device* pDevice) return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[JACK] Failed to retrieve physical ports.", MA_ERROR); } - for (size_t i = 0; ppServerPorts[i] != NULL; ++i) { + for (i = 0; ppServerPorts[i] != NULL; ++i) { const char* pServerPort = ppServerPorts[i]; const char* pClientPort = ((ma_jack_port_name_proc)pContext->jack.jack_port_name)((ma_jack_port_t*)pDevice->jack.pPortsPlayback[i]); @@ -15774,16 +16228,14 @@ ma_result ma_device_start__jack(ma_device* pDevice) ma_result ma_device_stop__jack(ma_device* pDevice) { - ma_assert(pDevice != NULL); - ma_context* pContext = pDevice->pContext; - ma_assert(pContext != NULL); + ma_stop_proc onStop; if (((ma_jack_deactivate_proc)pContext->jack.jack_deactivate)((ma_jack_client_t*)pDevice->jack.pClient) != 0) { return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[JACK] An error occurred when deactivating the JACK client.", MA_ERROR); } - ma_stop_proc onStop = pDevice->onStop; + onStop = pDevice->onStop; if (onStop) { onStop(pDevice); } @@ -15809,10 +16261,7 @@ ma_result ma_context_uninit__jack(ma_context* pContext) ma_result ma_context_init__jack(const ma_context_config* pConfig, ma_context* pContext) { - ma_assert(pContext != NULL); - #ifndef MA_NO_RUNTIME_LINKING - // libjack.so const char* libjackNames[] = { #ifdef MA_WIN32 "libjack.dll" @@ -15821,8 +16270,9 @@ ma_result ma_context_init__jack(const ma_context_config* pConfig, ma_context* pC "libjack.so.0" #endif }; + size_t i; - for (size_t i = 0; i < ma_countof(libjackNames); ++i) { + for (i = 0; i < ma_countof(libjackNames); ++i) { pContext->jack.jackSO = ma_dlopen(libjackNames[i]); if (pContext->jack.jackSO != NULL) { break; @@ -15850,8 +16300,10 @@ ma_result ma_context_init__jack(const ma_context_config* pConfig, ma_context* pC pContext->jack.jack_port_get_buffer = (ma_proc)ma_dlsym(pContext->jack.jackSO, "jack_port_get_buffer"); pContext->jack.jack_free = (ma_proc)ma_dlsym(pContext->jack.jackSO, "jack_free"); #else - // This strange assignment system is here just to ensure type safety of miniaudio's function pointer - // types. If anything differs slightly the compiler should throw a warning. + /* + This strange assignment system is here just to ensure type safety of miniaudio's function pointer + types. If anything differs slightly the compiler should throw a warning. + */ ma_jack_client_open_proc _jack_client_open = jack_client_open; ma_jack_client_close_proc _jack_client_close = jack_client_close; ma_jack_client_name_size_proc _jack_client_name_size = jack_client_name_size; @@ -15903,27 +16355,35 @@ ma_result ma_context_init__jack(const ma_context_config* pConfig, ma_context* pC } pContext->jack.tryStartServer = pConfig->jack.tryStartServer; - // Getting here means the JACK library is installed, but it doesn't necessarily mean it's usable. We need to quickly test this by connecting - // a temporary client. - ma_jack_client_t* pDummyClient; - ma_result result = ma_context_open_client__jack(pContext, &pDummyClient); - if (result != MA_SUCCESS) { - ma_free(pContext->jack.pClientName); - return MA_NO_BACKEND; - } + /* + Getting here means the JACK library is installed, but it doesn't necessarily mean it's usable. We need to quickly test this by connecting + a temporary client. + */ + { + ma_jack_client_t* pDummyClient; + ma_result result = ma_context_open_client__jack(pContext, &pDummyClient); + if (result != MA_SUCCESS) { + ma_free(pContext->jack.pClientName); + #ifndef MA_NO_RUNTIME_LINKING + ma_dlclose(pContext->jack.jackSO); + #endif + return MA_NO_BACKEND; + } + + ((ma_jack_client_close_proc)pContext->jack.jack_client_close)((ma_jack_client_t*)pDummyClient); + } - ((ma_jack_client_close_proc)pContext->jack.jack_client_close)((ma_jack_client_t*)pDummyClient); return MA_SUCCESS; } -#endif // JACK +#endif /* JACK */ + +/****************************************************************************** -/////////////////////////////////////////////////////////////////////////////// -// -// Core Audio Backend -// -/////////////////////////////////////////////////////////////////////////////// +Core Audio Backend + +******************************************************************************/ #ifdef MA_HAS_COREAUDIO #include @@ -15941,10 +16401,10 @@ ma_result ma_context_init__jack(const ma_context_config* pConfig, ma_context* pC #include -// CoreFoundation +/* CoreFoundation */ typedef Boolean (* ma_CFStringGetCString_proc)(CFStringRef theString, char* buffer, CFIndex bufferSize, CFStringEncoding encoding); -// CoreAudio +/* CoreAudio */ #if defined(MA_APPLE_DESKTOP) typedef OSStatus (* ma_AudioObjectGetPropertyData_proc)(AudioObjectID inObjectID, const AudioObjectPropertyAddress* inAddress, UInt32 inQualifierDataSize, const void* inQualifierData, UInt32* ioDataSize, void* outData); typedef OSStatus (* ma_AudioObjectGetPropertyDataSize_proc)(AudioObjectID inObjectID, const AudioObjectPropertyAddress* inAddress, UInt32 inQualifierDataSize, const void* inQualifierData, UInt32* outDataSize); @@ -15952,7 +16412,7 @@ typedef OSStatus (* ma_AudioObjectSetPropertyData_proc)(AudioObjectID inObjectID typedef OSStatus (* ma_AudioObjectAddPropertyListener_proc)(AudioObjectID inObjectID, const AudioObjectPropertyAddress* inAddress, AudioObjectPropertyListenerProc inListener, void* inClientData); #endif -// AudioToolbox +/* AudioToolbox */ typedef AudioComponent (* ma_AudioComponentFindNext_proc)(AudioComponent inComponent, const AudioComponentDescription* inDesc); typedef OSStatus (* ma_AudioComponentInstanceDispose_proc)(AudioComponentInstance inInstance); typedef OSStatus (* ma_AudioComponentInstanceNew_proc)(AudioComponent inComponent, AudioComponentInstance* outInstance); @@ -15971,37 +16431,38 @@ typedef OSStatus (* ma_AudioUnitRender_proc)(AudioUnit inUnit, AudioUnitRenderAc ma_result ma_device_reinit_internal__coreaudio(ma_device* pDevice, ma_device_type deviceType, ma_bool32 disposePreviousAudioUnit); - -// Core Audio -// -// So far, Core Audio has been the worst backend to work with due to being both unintuitive and having almost no documentation -// apart from comments in the headers (which admittedly are quite good). For my own purposes, and for anybody out there whose -// needing to figure out how this darn thing works, I'm going to outline a few things here. -// -// Since miniaudio is a fairly low-level API, one of the things it needs is control over specific devices, and it needs to be -// able to identify whether or not it can be used as playback and/or capture. The AudioObject API is the only one I've seen -// that supports this level of detail. There was some public domain sample code I stumbled across that used the AudioComponent -// and AudioUnit APIs, but I couldn't see anything that gave low-level control over device selection and capabilities (the -// distinction between playback and capture in particular). Therefore, miniaudio is using the AudioObject API. -// -// Most (all?) functions in the AudioObject API take a AudioObjectID as it's input. This is the device identifier. When -// retrieving global information, such as the device list, you use kAudioObjectSystemObject. When retrieving device-specific -// data, you pass in the ID for that device. In order to retrieve device-specific IDs you need to enumerate over each of the -// devices. This is done using the AudioObjectGetPropertyDataSize() and AudioObjectGetPropertyData() APIs which seem to be -// the central APIs for retrieving information about the system and specific devices. -// -// To use the AudioObjectGetPropertyData() API you need to use the notion of a property address. A property address is a -// structure with three variables and is used to identify which property you are getting or setting. The first is the "selector" -// which is basically the specific property that you're wanting to retrieve or set. The second is the "scope", which is -// typically set to kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyScopeInput for input-specific properties and -// kAudioObjectPropertyScopeOutput for output-specific properties. The last is the "element" which is always set to -// kAudioObjectPropertyElementMaster in miniaudio's case. I don't know of any cases where this would be set to anything different. -// -// Back to the earlier issue of device retrieval, you first use the AudioObjectGetPropertyDataSize() API to retrieve the size -// of the raw data which is just a list of AudioDeviceID's. You use the kAudioObjectSystemObject AudioObjectID, and a property -// address with the kAudioHardwarePropertyDevices selector and the kAudioObjectPropertyScopeGlobal scope. Once you have the -// size, allocate a block of memory of that size and then call AudioObjectGetPropertyData(). The data is just a list of -// AudioDeviceID's so just do "dataSize/sizeof(AudioDeviceID)" to know the device count. +/* +Core Audio + +So far, Core Audio has been the worst backend to work with due to being both unintuitive and having almost no documentation +apart from comments in the headers (which admittedly are quite good). For my own purposes, and for anybody out there whose +needing to figure out how this darn thing works, I'm going to outline a few things here. + +Since miniaudio is a fairly low-level API, one of the things it needs is control over specific devices, and it needs to be +able to identify whether or not it can be used as playback and/or capture. The AudioObject API is the only one I've seen +that supports this level of detail. There was some public domain sample code I stumbled across that used the AudioComponent +and AudioUnit APIs, but I couldn't see anything that gave low-level control over device selection and capabilities (the +distinction between playback and capture in particular). Therefore, miniaudio is using the AudioObject API. + +Most (all?) functions in the AudioObject API take a AudioObjectID as it's input. This is the device identifier. When +retrieving global information, such as the device list, you use kAudioObjectSystemObject. When retrieving device-specific +data, you pass in the ID for that device. In order to retrieve device-specific IDs you need to enumerate over each of the +devices. This is done using the AudioObjectGetPropertyDataSize() and AudioObjectGetPropertyData() APIs which seem to be +the central APIs for retrieving information about the system and specific devices. + +To use the AudioObjectGetPropertyData() API you need to use the notion of a property address. A property address is a +structure with three variables and is used to identify which property you are getting or setting. The first is the "selector" +which is basically the specific property that you're wanting to retrieve or set. The second is the "scope", which is +typically set to kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyScopeInput for input-specific properties and +kAudioObjectPropertyScopeOutput for output-specific properties. The last is the "element" which is always set to +kAudioObjectPropertyElementMaster in miniaudio's case. I don't know of any cases where this would be set to anything different. + +Back to the earlier issue of device retrieval, you first use the AudioObjectGetPropertyDataSize() API to retrieve the size +of the raw data which is just a list of AudioDeviceID's. You use the kAudioObjectSystemObject AudioObjectID, and a property +address with the kAudioHardwarePropertyDevices selector and the kAudioObjectPropertyScopeGlobal scope. Once you have the +size, allocate a block of memory of that size and then call AudioObjectGetPropertyData(). The data is just a list of +AudioDeviceID's so just do "dataSize/sizeof(AudioDeviceID)" to know the device count. +*/ ma_result ma_result_from_OSStatus(OSStatus status) { @@ -16122,7 +16583,7 @@ ma_channel ma_channel_from_AudioChannelLabel(AudioChannelLabel label) case kAudioChannelLabel_Discrete_15: return MA_CHANNEL_AUX_15; case kAudioChannelLabel_Discrete_65535: return MA_CHANNEL_NONE; - #if 0 // Introduced in a later version of macOS. + #if 0 /* Introduced in a later version of macOS. */ case kAudioChannelLabel_HOA_ACN: return MA_CHANNEL_NONE; case kAudioChannelLabel_HOA_ACN_0: return MA_CHANNEL_AUX_0; case kAudioChannelLabel_HOA_ACN_1: return MA_CHANNEL_AUX_1; @@ -16152,27 +16613,27 @@ ma_result ma_format_from_AudioStreamBasicDescription(const AudioStreamBasicDescr ma_assert(pDescription != NULL); ma_assert(pFormatOut != NULL); - *pFormatOut = ma_format_unknown; // Safety. + *pFormatOut = ma_format_unknown; /* Safety. */ - // There's a few things miniaudio doesn't support. + /* There's a few things miniaudio doesn't support. */ if (pDescription->mFormatID != kAudioFormatLinearPCM) { return MA_FORMAT_NOT_SUPPORTED; } - // We don't support any non-packed formats that are aligned high. + /* We don't support any non-packed formats that are aligned high. */ if ((pDescription->mFormatFlags & kLinearPCMFormatFlagIsAlignedHigh) != 0) { return MA_FORMAT_NOT_SUPPORTED; } - // Only supporting native-endian. + /* Only supporting native-endian. */ if ((ma_is_little_endian() && (pDescription->mFormatFlags & kAudioFormatFlagIsBigEndian) != 0) || (ma_is_big_endian() && (pDescription->mFormatFlags & kAudioFormatFlagIsBigEndian) == 0)) { return MA_FORMAT_NOT_SUPPORTED; } - // We are not currently supporting non-interleaved formats (this will be added in a future version of miniaudio). - //if ((pDescription->mFormatFlags & kAudioFormatFlagIsNonInterleaved) != 0) { - // return MA_FORMAT_NOT_SUPPORTED; - //} + /* We are not currently supporting non-interleaved formats (this will be added in a future version of miniaudio). */ + /*if ((pDescription->mFormatFlags & kAudioFormatFlagIsNonInterleaved) != 0) { + return MA_FORMAT_NOT_SUPPORTED; + }*/ if ((pDescription->mFormatFlags & kLinearPCMFormatFlagIsFloat) != 0) { if (pDescription->mBitsPerChannel == 32) { @@ -16190,9 +16651,9 @@ ma_result ma_format_from_AudioStreamBasicDescription(const AudioStreamBasicDescr return MA_SUCCESS; } else { if (pDescription->mBytesPerFrame/pDescription->mChannelsPerFrame == sizeof(ma_int32)) { - // TODO: Implement ma_format_s24_32. - //*pFormatOut = ma_format_s24_32; - //return MA_SUCCESS; + /* TODO: Implement ma_format_s24_32. */ + /**pFormatOut = ma_format_s24_32;*/ + /*return MA_SUCCESS;*/ return MA_FORMAT_NOT_SUPPORTED; } } @@ -16208,7 +16669,7 @@ ma_result ma_format_from_AudioStreamBasicDescription(const AudioStreamBasicDescr } } - // Getting here means the format is not supported. + /* Getting here means the format is not supported. */ return MA_FORMAT_NOT_SUPPORTED; } @@ -16217,16 +16678,18 @@ ma_result ma_get_channel_map_from_AudioChannelLayout(AudioChannelLayout* pChanne ma_assert(pChannelLayout != NULL); if (pChannelLayout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelDescriptions) { - for (UInt32 iChannel = 0; iChannel < pChannelLayout->mNumberChannelDescriptions; ++iChannel) { + UInt32 iChannel; + for (iChannel = 0; iChannel < pChannelLayout->mNumberChannelDescriptions; ++iChannel) { channelMap[iChannel] = ma_channel_from_AudioChannelLabel(pChannelLayout->mChannelDescriptions[iChannel].mChannelLabel); } } else #if 0 if (pChannelLayout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelBitmap) { - // This is the same kind of system that's used by Windows audio APIs. + /* This is the same kind of system that's used by Windows audio APIs. */ UInt32 iChannel = 0; + UInt32 iBit; AudioChannelBitmap bitmap = pChannelLayout->mChannelBitmap; - for (UInt32 iBit = 0; iBit < 32; ++iBit) { + for (iBit = 0; iBit < 32; ++iBit) { AudioChannelBitmap bit = bitmap & (1 << iBit); if (bit != 0) { channelMap[iChannel++] = ma_channel_from_AudioChannelBit(bit); @@ -16235,8 +16698,10 @@ ma_result ma_get_channel_map_from_AudioChannelLayout(AudioChannelLayout* pChanne } else #endif { - // Need to use the tag to determine the channel map. For now I'm just assuming a default channel map, but later on this should - // be updated to determine the mapping based on the tag. + /* + Need to use the tag to determine the channel map. For now I'm just assuming a default channel map, but later on this should + be updated to determine the mapping based on the tag. + */ UInt32 channelCount = AudioChannelLayoutTag_GetNumberOfChannels(pChannelLayout->mChannelLayoutTag); switch (pChannelLayout->mChannelLayoutTag) { @@ -16256,15 +16721,15 @@ ma_result ma_get_channel_map_from_AudioChannelLayout(AudioChannelLayout* pChanne { channelMap[7] = MA_CHANNEL_SIDE_RIGHT; channelMap[6] = MA_CHANNEL_SIDE_LEFT; - } // Intentional fallthrough. + } /* Intentional fallthrough. */ case kAudioChannelLayoutTag_Hexagonal: { channelMap[5] = MA_CHANNEL_BACK_CENTER; - } // Intentional fallthrough. + } /* Intentional fallthrough. */ case kAudioChannelLayoutTag_Pentagonal: { channelMap[4] = MA_CHANNEL_FRONT_CENTER; - } // Intentional fallghrough. + } /* Intentional fallghrough. */ case kAudioChannelLayoutTag_Quadraphonic: { channelMap[3] = MA_CHANNEL_BACK_RIGHT; @@ -16273,7 +16738,7 @@ ma_result ma_get_channel_map_from_AudioChannelLayout(AudioChannelLayout* pChanne channelMap[0] = MA_CHANNEL_LEFT; } break; - // TODO: Add support for more tags here. + /* TODO: Add support for more tags here. */ default: { @@ -16287,29 +16752,31 @@ ma_result ma_get_channel_map_from_AudioChannelLayout(AudioChannelLayout* pChanne #if defined(MA_APPLE_DESKTOP) -ma_result ma_get_device_object_ids__coreaudio(ma_context* pContext, UInt32* pDeviceCount, AudioObjectID** ppDeviceObjectIDs) // NOTE: Free the returned buffer with ma_free(). +ma_result ma_get_device_object_ids__coreaudio(ma_context* pContext, UInt32* pDeviceCount, AudioObjectID** ppDeviceObjectIDs) /* NOTE: Free the returned buffer with ma_free(). */ { + AudioObjectPropertyAddress propAddressDevices; + UInt32 deviceObjectsDataSize; + OSStatus status; + AudioObjectID* pDeviceObjectIDs; + ma_assert(pContext != NULL); ma_assert(pDeviceCount != NULL); ma_assert(ppDeviceObjectIDs != NULL); - (void)pContext; - // Safety. + /* Safety. */ *pDeviceCount = 0; *ppDeviceObjectIDs = NULL; - AudioObjectPropertyAddress propAddressDevices; propAddressDevices.mSelector = kAudioHardwarePropertyDevices; propAddressDevices.mScope = kAudioObjectPropertyScopeGlobal; propAddressDevices.mElement = kAudioObjectPropertyElementMaster; - UInt32 deviceObjectsDataSize; - OSStatus status = ((ma_AudioObjectGetPropertyDataSize_proc)pContext->coreaudio.AudioObjectGetPropertyDataSize)(kAudioObjectSystemObject, &propAddressDevices, 0, NULL, &deviceObjectsDataSize); + status = ((ma_AudioObjectGetPropertyDataSize_proc)pContext->coreaudio.AudioObjectGetPropertyDataSize)(kAudioObjectSystemObject, &propAddressDevices, 0, NULL, &deviceObjectsDataSize); if (status != noErr) { return ma_result_from_OSStatus(status); } - AudioObjectID* pDeviceObjectIDs = (AudioObjectID*)ma_malloc(deviceObjectsDataSize); + pDeviceObjectIDs = (AudioObjectID*)ma_malloc(deviceObjectsDataSize); if (pDeviceObjectIDs == NULL) { return MA_OUT_OF_MEMORY; } @@ -16322,20 +16789,25 @@ ma_result ma_get_device_object_ids__coreaudio(ma_context* pContext, UInt32* pDev *pDeviceCount = deviceObjectsDataSize / sizeof(AudioObjectID); *ppDeviceObjectIDs = pDeviceObjectIDs; + + (void)pContext; /* Unused. */ return MA_SUCCESS; } ma_result ma_get_AudioObject_uid_as_CFStringRef(ma_context* pContext, AudioObjectID objectID, CFStringRef* pUID) { + AudioObjectPropertyAddress propAddress; + UInt32 dataSize; + OSStatus status; + ma_assert(pContext != NULL); - AudioObjectPropertyAddress propAddress; propAddress.mSelector = kAudioDevicePropertyDeviceUID; propAddress.mScope = kAudioObjectPropertyScopeGlobal; propAddress.mElement = kAudioObjectPropertyElementMaster; - UInt32 dataSize = sizeof(*pUID); - OSStatus status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(objectID, &propAddress, 0, NULL, &dataSize, pUID); + dataSize = sizeof(*pUID); + status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(objectID, &propAddress, 0, NULL, &dataSize, pUID); if (status != noErr) { return ma_result_from_OSStatus(status); } @@ -16345,10 +16817,12 @@ ma_result ma_get_AudioObject_uid_as_CFStringRef(ma_context* pContext, AudioObjec ma_result ma_get_AudioObject_uid(ma_context* pContext, AudioObjectID objectID, size_t bufferSize, char* bufferOut) { + CFStringRef uid; + ma_result result; + ma_assert(pContext != NULL); - CFStringRef uid; - ma_result result = ma_get_AudioObject_uid_as_CFStringRef(pContext, objectID, &uid); + result = ma_get_AudioObject_uid_as_CFStringRef(pContext, objectID, &uid); if (result != MA_SUCCESS) { return result; } @@ -16362,16 +16836,19 @@ ma_result ma_get_AudioObject_uid(ma_context* pContext, AudioObjectID objectID, s ma_result ma_get_AudioObject_name(ma_context* pContext, AudioObjectID objectID, size_t bufferSize, char* bufferOut) { + AudioObjectPropertyAddress propAddress; + CFStringRef deviceName = NULL; + UInt32 dataSize; + OSStatus status; + ma_assert(pContext != NULL); - AudioObjectPropertyAddress propAddress; propAddress.mSelector = kAudioDevicePropertyDeviceNameCFString; propAddress.mScope = kAudioObjectPropertyScopeGlobal; propAddress.mElement = kAudioObjectPropertyElementMaster; - CFStringRef deviceName = NULL; - UInt32 dataSize = sizeof(deviceName); - OSStatus status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(objectID, &propAddress, 0, NULL, &dataSize, &deviceName); + dataSize = sizeof(deviceName); + status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(objectID, &propAddress, 0, NULL, &dataSize, &deviceName); if (status != noErr) { return ma_result_from_OSStatus(status); } @@ -16385,24 +16862,27 @@ ma_result ma_get_AudioObject_name(ma_context* pContext, AudioObjectID objectID, ma_bool32 ma_does_AudioObject_support_scope(ma_context* pContext, AudioObjectID deviceObjectID, AudioObjectPropertyScope scope) { + AudioObjectPropertyAddress propAddress; + UInt32 dataSize; + OSStatus status; + AudioBufferList* pBufferList; + ma_bool32 isSupported; + ma_assert(pContext != NULL); - // To know whether or not a device is an input device we need ot look at the stream configuration. If it has an output channel it's a - // playback device. - AudioObjectPropertyAddress propAddress; + /* To know whether or not a device is an input device we need ot look at the stream configuration. If it has an output channel it's a playback device. */ propAddress.mSelector = kAudioDevicePropertyStreamConfiguration; propAddress.mScope = scope; propAddress.mElement = kAudioObjectPropertyElementMaster; - UInt32 dataSize; - OSStatus status = ((ma_AudioObjectGetPropertyDataSize_proc)pContext->coreaudio.AudioObjectGetPropertyDataSize)(deviceObjectID, &propAddress, 0, NULL, &dataSize); + status = ((ma_AudioObjectGetPropertyDataSize_proc)pContext->coreaudio.AudioObjectGetPropertyDataSize)(deviceObjectID, &propAddress, 0, NULL, &dataSize); if (status != noErr) { return MA_FALSE; } - AudioBufferList* pBufferList = (AudioBufferList*)ma_malloc(dataSize); + pBufferList = (AudioBufferList*)ma_malloc(dataSize); if (pBufferList == NULL) { - return MA_FALSE; // Out of memory. + return MA_FALSE; /* Out of memory. */ } status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(deviceObjectID, &propAddress, 0, NULL, &dataSize, pBufferList); @@ -16411,7 +16891,7 @@ ma_bool32 ma_does_AudioObject_support_scope(ma_context* pContext, AudioObjectID return MA_FALSE; } - ma_bool32 isSupported = MA_FALSE; + isSupported = MA_FALSE; if (pBufferList->mNumberBuffers > 0) { isSupported = MA_TRUE; } @@ -16431,26 +16911,31 @@ ma_bool32 ma_does_AudioObject_support_capture(ma_context* pContext, AudioObjectI } -ma_result ma_get_AudioObject_stream_descriptions(ma_context* pContext, AudioObjectID deviceObjectID, ma_device_type deviceType, UInt32* pDescriptionCount, AudioStreamRangedDescription** ppDescriptions) // NOTE: Free the returned pointer with ma_free(). +ma_result ma_get_AudioObject_stream_descriptions(ma_context* pContext, AudioObjectID deviceObjectID, ma_device_type deviceType, UInt32* pDescriptionCount, AudioStreamRangedDescription** ppDescriptions) /* NOTE: Free the returned pointer with ma_free(). */ { + AudioObjectPropertyAddress propAddress; + UInt32 dataSize; + OSStatus status; + AudioStreamRangedDescription* pDescriptions; + ma_assert(pContext != NULL); ma_assert(pDescriptionCount != NULL); ma_assert(ppDescriptions != NULL); - // TODO: Experiment with kAudioStreamPropertyAvailablePhysicalFormats instead of (or in addition to) kAudioStreamPropertyAvailableVirtualFormats. My - // MacBook Pro uses s24/32 format, however, which miniaudio does not currently support. - AudioObjectPropertyAddress propAddress; - propAddress.mSelector = kAudioStreamPropertyAvailableVirtualFormats; //kAudioStreamPropertyAvailablePhysicalFormats; + /* + TODO: Experiment with kAudioStreamPropertyAvailablePhysicalFormats instead of (or in addition to) kAudioStreamPropertyAvailableVirtualFormats. My + MacBook Pro uses s24/32 format, however, which miniaudio does not currently support. + */ + propAddress.mSelector = kAudioStreamPropertyAvailableVirtualFormats; /*kAudioStreamPropertyAvailablePhysicalFormats;*/ propAddress.mScope = (deviceType == ma_device_type_playback) ? kAudioObjectPropertyScopeOutput : kAudioObjectPropertyScopeInput; propAddress.mElement = kAudioObjectPropertyElementMaster; - UInt32 dataSize; - OSStatus status = ((ma_AudioObjectGetPropertyDataSize_proc)pContext->coreaudio.AudioObjectGetPropertyDataSize)(deviceObjectID, &propAddress, 0, NULL, &dataSize); + status = ((ma_AudioObjectGetPropertyDataSize_proc)pContext->coreaudio.AudioObjectGetPropertyDataSize)(deviceObjectID, &propAddress, 0, NULL, &dataSize); if (status != noErr) { return ma_result_from_OSStatus(status); } - AudioStreamRangedDescription* pDescriptions = (AudioStreamRangedDescription*)ma_malloc(dataSize); + pDescriptions = (AudioStreamRangedDescription*)ma_malloc(dataSize); if (pDescriptions == NULL) { return MA_OUT_OF_MEMORY; } @@ -16467,25 +16952,28 @@ ma_result ma_get_AudioObject_stream_descriptions(ma_context* pContext, AudioObje } -ma_result ma_get_AudioObject_channel_layout(ma_context* pContext, AudioObjectID deviceObjectID, ma_device_type deviceType, AudioChannelLayout** ppChannelLayout) // NOTE: Free the returned pointer with ma_free(). +ma_result ma_get_AudioObject_channel_layout(ma_context* pContext, AudioObjectID deviceObjectID, ma_device_type deviceType, AudioChannelLayout** ppChannelLayout) /* NOTE: Free the returned pointer with ma_free(). */ { + AudioObjectPropertyAddress propAddress; + UInt32 dataSize; + OSStatus status; + AudioChannelLayout* pChannelLayout; + ma_assert(pContext != NULL); ma_assert(ppChannelLayout != NULL); - *ppChannelLayout = NULL; // Safety. + *ppChannelLayout = NULL; /* Safety. */ - AudioObjectPropertyAddress propAddress; propAddress.mSelector = kAudioDevicePropertyPreferredChannelLayout; propAddress.mScope = (deviceType == ma_device_type_playback) ? kAudioObjectPropertyScopeOutput : kAudioObjectPropertyScopeInput; propAddress.mElement = kAudioObjectPropertyElementMaster; - UInt32 dataSize; - OSStatus status = ((ma_AudioObjectGetPropertyDataSize_proc)pContext->coreaudio.AudioObjectGetPropertyDataSize)(deviceObjectID, &propAddress, 0, NULL, &dataSize); + status = ((ma_AudioObjectGetPropertyDataSize_proc)pContext->coreaudio.AudioObjectGetPropertyDataSize)(deviceObjectID, &propAddress, 0, NULL, &dataSize); if (status != noErr) { return ma_result_from_OSStatus(status); } - AudioChannelLayout* pChannelLayout = (AudioChannelLayout*)ma_malloc(dataSize); + pChannelLayout = (AudioChannelLayout*)ma_malloc(dataSize); if (pChannelLayout == NULL) { return MA_OUT_OF_MEMORY; } @@ -16502,13 +16990,15 @@ ma_result ma_get_AudioObject_channel_layout(ma_context* pContext, AudioObjectID ma_result ma_get_AudioObject_channel_count(ma_context* pContext, AudioObjectID deviceObjectID, ma_device_type deviceType, ma_uint32* pChannelCount) { + AudioChannelLayout* pChannelLayout; + ma_result result; + ma_assert(pContext != NULL); ma_assert(pChannelCount != NULL); - *pChannelCount = 0; // Safety. + *pChannelCount = 0; /* Safety. */ - AudioChannelLayout* pChannelLayout; - ma_result result = ma_get_AudioObject_channel_layout(pContext, deviceObjectID, deviceType, &pChannelLayout); + result = ma_get_AudioObject_channel_layout(pContext, deviceObjectID, deviceType, &pChannelLayout); if (result != MA_SUCCESS) { return result; } @@ -16527,12 +17017,14 @@ ma_result ma_get_AudioObject_channel_count(ma_context* pContext, AudioObjectID d ma_result ma_get_AudioObject_channel_map(ma_context* pContext, AudioObjectID deviceObjectID, ma_device_type deviceType, ma_channel channelMap[MA_MAX_CHANNELS]) { + AudioChannelLayout* pChannelLayout; + ma_result result; + ma_assert(pContext != NULL); - AudioChannelLayout* pChannelLayout; - ma_result result = ma_get_AudioObject_channel_layout(pContext, deviceObjectID, deviceType, &pChannelLayout); + result = ma_get_AudioObject_channel_layout(pContext, deviceObjectID, deviceType, &pChannelLayout); if (result != MA_SUCCESS) { - return result; // Rather than always failing here, would it be more robust to simply assume a default? + return result; /* Rather than always failing here, would it be more robust to simply assume a default? */ } result = ma_get_channel_map_from_AudioChannelLayout(pChannelLayout, channelMap); @@ -16545,28 +17037,31 @@ ma_result ma_get_AudioObject_channel_map(ma_context* pContext, AudioObjectID dev return result; } -ma_result ma_get_AudioObject_sample_rates(ma_context* pContext, AudioObjectID deviceObjectID, ma_device_type deviceType, UInt32* pSampleRateRangesCount, AudioValueRange** ppSampleRateRanges) // NOTE: Free the returned pointer with ma_free(). +ma_result ma_get_AudioObject_sample_rates(ma_context* pContext, AudioObjectID deviceObjectID, ma_device_type deviceType, UInt32* pSampleRateRangesCount, AudioValueRange** ppSampleRateRanges) /* NOTE: Free the returned pointer with ma_free(). */ { + AudioObjectPropertyAddress propAddress; + UInt32 dataSize; + OSStatus status; + AudioValueRange* pSampleRateRanges; + ma_assert(pContext != NULL); ma_assert(pSampleRateRangesCount != NULL); ma_assert(ppSampleRateRanges != NULL); - // Safety. + /* Safety. */ *pSampleRateRangesCount = 0; *ppSampleRateRanges = NULL; - AudioObjectPropertyAddress propAddress; propAddress.mSelector = kAudioDevicePropertyAvailableNominalSampleRates; propAddress.mScope = (deviceType == ma_device_type_playback) ? kAudioObjectPropertyScopeOutput : kAudioObjectPropertyScopeInput; propAddress.mElement = kAudioObjectPropertyElementMaster; - UInt32 dataSize; - OSStatus status = ((ma_AudioObjectGetPropertyDataSize_proc)pContext->coreaudio.AudioObjectGetPropertyDataSize)(deviceObjectID, &propAddress, 0, NULL, &dataSize); + status = ((ma_AudioObjectGetPropertyDataSize_proc)pContext->coreaudio.AudioObjectGetPropertyDataSize)(deviceObjectID, &propAddress, 0, NULL, &dataSize); if (status != noErr) { return ma_result_from_OSStatus(status); } - AudioValueRange* pSampleRateRanges = (AudioValueRange*)ma_malloc(dataSize); + pSampleRateRanges = (AudioValueRange*)ma_malloc(dataSize); if (pSampleRateRanges == NULL) { return MA_OUT_OF_MEMORY; } @@ -16584,28 +17079,32 @@ ma_result ma_get_AudioObject_sample_rates(ma_context* pContext, AudioObjectID de ma_result ma_get_AudioObject_get_closest_sample_rate(ma_context* pContext, AudioObjectID deviceObjectID, ma_device_type deviceType, ma_uint32 sampleRateIn, ma_uint32* pSampleRateOut) { + UInt32 sampleRateRangeCount; + AudioValueRange* pSampleRateRanges; + ma_result result; + ma_assert(pContext != NULL); ma_assert(pSampleRateOut != NULL); - *pSampleRateOut = 0; // Safety. + *pSampleRateOut = 0; /* Safety. */ - UInt32 sampleRateRangeCount; - AudioValueRange* pSampleRateRanges; - ma_result result = ma_get_AudioObject_sample_rates(pContext, deviceObjectID, deviceType, &sampleRateRangeCount, &pSampleRateRanges); + result = ma_get_AudioObject_sample_rates(pContext, deviceObjectID, deviceType, &sampleRateRangeCount, &pSampleRateRanges); if (result != MA_SUCCESS) { return result; } if (sampleRateRangeCount == 0) { ma_free(pSampleRateRanges); - return MA_ERROR; // Should never hit this case should we? + return MA_ERROR; /* Should never hit this case should we? */ } if (sampleRateIn == 0) { - // Search in order of miniaudio's preferred priority. - for (UInt32 iMALSampleRate = 0; iMALSampleRate < ma_countof(g_maStandardSampleRatePriorities); ++iMALSampleRate) { + /* Search in order of miniaudio's preferred priority. */ + UInt32 iMALSampleRate; + for (iMALSampleRate = 0; iMALSampleRate < ma_countof(g_maStandardSampleRatePriorities); ++iMALSampleRate) { ma_uint32 malSampleRate = g_maStandardSampleRatePriorities[iMALSampleRate]; - for (UInt32 iCASampleRate = 0; iCASampleRate < sampleRateRangeCount; ++iCASampleRate) { + UInt32 iCASampleRate; + for (iCASampleRate = 0; iCASampleRate < sampleRateRangeCount; ++iCASampleRate) { AudioValueRange caSampleRate = pSampleRateRanges[iCASampleRate]; if (caSampleRate.mMinimum <= malSampleRate && caSampleRate.mMaximum >= malSampleRate) { *pSampleRateOut = malSampleRate; @@ -16615,18 +17114,21 @@ ma_result ma_get_AudioObject_get_closest_sample_rate(ma_context* pContext, Audio } } - // If we get here it means none of miniaudio's standard sample rates matched any of the supported sample rates from the device. In this - // case we just fall back to the first one reported by Core Audio. + /* + If we get here it means none of miniaudio's standard sample rates matched any of the supported sample rates from the device. In this + case we just fall back to the first one reported by Core Audio. + */ ma_assert(sampleRateRangeCount > 0); *pSampleRateOut = pSampleRateRanges[0].mMinimum; ma_free(pSampleRateRanges); return MA_SUCCESS; } else { - // Find the closest match to this sample rate. + /* Find the closest match to this sample rate. */ UInt32 currentAbsoluteDifference = INT32_MAX; UInt32 iCurrentClosestRange = (UInt32)-1; - for (UInt32 iRange = 0; iRange < sampleRateRangeCount; ++iRange) { + UInt32 iRange; + for (iRange = 0; iRange < sampleRateRangeCount; ++iRange) { if (pSampleRateRanges[iRange].mMinimum <= sampleRateIn && pSampleRateRanges[iRange].mMaximum >= sampleRateIn) { *pSampleRateOut = sampleRateIn; ma_free(pSampleRateRanges); @@ -16653,32 +17155,35 @@ ma_result ma_get_AudioObject_get_closest_sample_rate(ma_context* pContext, Audio return MA_SUCCESS; } - // Should never get here, but it would mean we weren't able to find any suitable sample rates. - //ma_free(pSampleRateRanges); - //return MA_ERROR; + /* Should never get here, but it would mean we weren't able to find any suitable sample rates. */ + /*ma_free(pSampleRateRanges);*/ + /*return MA_ERROR;*/ } ma_result ma_get_AudioObject_closest_buffer_size_in_frames(ma_context* pContext, AudioObjectID deviceObjectID, ma_device_type deviceType, ma_uint32 bufferSizeInFramesIn, ma_uint32* pBufferSizeInFramesOut) { + AudioObjectPropertyAddress propAddress; + AudioValueRange bufferSizeRange; + UInt32 dataSize; + OSStatus status; + ma_assert(pContext != NULL); ma_assert(pBufferSizeInFramesOut != NULL); - *pBufferSizeInFramesOut = 0; // Safety. + *pBufferSizeInFramesOut = 0; /* Safety. */ - AudioObjectPropertyAddress propAddress; propAddress.mSelector = kAudioDevicePropertyBufferFrameSizeRange; propAddress.mScope = (deviceType == ma_device_type_playback) ? kAudioObjectPropertyScopeOutput : kAudioObjectPropertyScopeInput; propAddress.mElement = kAudioObjectPropertyElementMaster; - AudioValueRange bufferSizeRange; - UInt32 dataSize = sizeof(bufferSizeRange); - OSStatus status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(deviceObjectID, &propAddress, 0, NULL, &dataSize, &bufferSizeRange); + dataSize = sizeof(bufferSizeRange); + status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(deviceObjectID, &propAddress, 0, NULL, &dataSize, &bufferSizeRange); if (status != noErr) { return ma_result_from_OSStatus(status); } - // This is just a clamp. + /* This is just a clamp. */ if (bufferSizeInFramesIn < bufferSizeRange.mMinimum) { *pBufferSizeInFramesOut = (ma_uint32)bufferSizeRange.mMinimum; } else if (bufferSizeInFramesIn > bufferSizeRange.mMaximum) { @@ -16692,25 +17197,29 @@ ma_result ma_get_AudioObject_closest_buffer_size_in_frames(ma_context* pContext, ma_result ma_set_AudioObject_buffer_size_in_frames(ma_context* pContext, AudioObjectID deviceObjectID, ma_device_type deviceType, ma_uint32* pBufferSizeInOut) { + ma_result result; + ma_uint32 chosenBufferSizeInFrames; + AudioObjectPropertyAddress propAddress; + UInt32 dataSize; + OSStatus status; + ma_assert(pContext != NULL); - ma_uint32 chosenBufferSizeInFrames; - ma_result result = ma_get_AudioObject_closest_buffer_size_in_frames(pContext, deviceObjectID, deviceType, *pBufferSizeInOut, &chosenBufferSizeInFrames); + result = ma_get_AudioObject_closest_buffer_size_in_frames(pContext, deviceObjectID, deviceType, *pBufferSizeInOut, &chosenBufferSizeInFrames); if (result != MA_SUCCESS) { return result; } - // Try setting the size of the buffer... If this fails we just use whatever is currently set. - AudioObjectPropertyAddress propAddress; + /* Try setting the size of the buffer... If this fails we just use whatever is currently set. */ propAddress.mSelector = kAudioDevicePropertyBufferFrameSize; propAddress.mScope = (deviceType == ma_device_type_playback) ? kAudioObjectPropertyScopeOutput : kAudioObjectPropertyScopeInput; propAddress.mElement = kAudioObjectPropertyElementMaster; ((ma_AudioObjectSetPropertyData_proc)pContext->coreaudio.AudioObjectSetPropertyData)(deviceObjectID, &propAddress, 0, NULL, sizeof(chosenBufferSizeInFrames), &chosenBufferSizeInFrames); - // Get the actual size of the buffer. - UInt32 dataSize = sizeof(*pBufferSizeInOut); - OSStatus status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(deviceObjectID, &propAddress, 0, NULL, &dataSize, &chosenBufferSizeInFrames); + /* Get the actual size of the buffer. */ + dataSize = sizeof(*pBufferSizeInOut); + status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(deviceObjectID, &propAddress, 0, NULL, &dataSize, &chosenBufferSizeInFrames); if (status != noErr) { return ma_result_from_OSStatus(status); } @@ -16725,12 +17234,16 @@ ma_result ma_find_AudioObjectID(ma_context* pContext, ma_device_type deviceType, ma_assert(pContext != NULL); ma_assert(pDeviceObjectID != NULL); - // Safety. + /* Safety. */ *pDeviceObjectID = 0; if (pDeviceID == NULL) { - // Default device. + /* Default device. */ AudioObjectPropertyAddress propAddressDefaultDevice; + UInt32 defaultDeviceObjectIDSize = sizeof(AudioObjectID); + AudioObjectID defaultDeviceObjectID; + OSStatus status; + propAddressDefaultDevice.mScope = kAudioObjectPropertyScopeGlobal; propAddressDefaultDevice.mElement = kAudioObjectPropertyElementMaster; if (deviceType == ma_device_type_playback) { @@ -16739,23 +17252,25 @@ ma_result ma_find_AudioObjectID(ma_context* pContext, ma_device_type deviceType, propAddressDefaultDevice.mSelector = kAudioHardwarePropertyDefaultInputDevice; } - UInt32 defaultDeviceObjectIDSize = sizeof(AudioObjectID); - AudioObjectID defaultDeviceObjectID; - OSStatus status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(kAudioObjectSystemObject, &propAddressDefaultDevice, 0, NULL, &defaultDeviceObjectIDSize, &defaultDeviceObjectID); + defaultDeviceObjectIDSize = sizeof(AudioObjectID); + status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(kAudioObjectSystemObject, &propAddressDefaultDevice, 0, NULL, &defaultDeviceObjectIDSize, &defaultDeviceObjectID); if (status == noErr) { *pDeviceObjectID = defaultDeviceObjectID; return MA_SUCCESS; } } else { - // Explicit device. + /* Explicit device. */ UInt32 deviceCount; AudioObjectID* pDeviceObjectIDs; - ma_result result = ma_get_device_object_ids__coreaudio(pContext, &deviceCount, &pDeviceObjectIDs); + ma_result result; + UInt32 iDevice; + + result = ma_get_device_object_ids__coreaudio(pContext, &deviceCount, &pDeviceObjectIDs); if (result != MA_SUCCESS) { return result; } - for (UInt32 iDevice = 0; iDevice < deviceCount; ++iDevice) { + for (iDevice = 0; iDevice < deviceCount; ++iDevice) { AudioObjectID deviceObjectID = pDeviceObjectIDs[iDevice]; char uid[256]; @@ -16781,7 +17296,7 @@ ma_result ma_find_AudioObjectID(ma_context* pContext, ma_device_type deviceType, } } - // If we get here it means we couldn't find the device. + /* If we get here it means we couldn't find the device. */ return MA_NO_DEVICE; } @@ -16790,20 +17305,32 @@ ma_result ma_find_best_format__coreaudio(ma_context* pContext, AudioObjectID dev { UInt32 deviceFormatDescriptionCount; AudioStreamRangedDescription* pDeviceFormatDescriptions; - ma_result result = ma_get_AudioObject_stream_descriptions(pContext, deviceObjectID, deviceType, &deviceFormatDescriptionCount, &pDeviceFormatDescriptions); + ma_result result; + ma_uint32 desiredSampleRate; + ma_uint32 desiredChannelCount; + ma_format desiredFormat; + AudioStreamBasicDescription bestDeviceFormatSoFar; + ma_bool32 hasSupportedFormat; + UInt32 iFormat; + + result = ma_get_AudioObject_stream_descriptions(pContext, deviceObjectID, deviceType, &deviceFormatDescriptionCount, &pDeviceFormatDescriptions); if (result != MA_SUCCESS) { return result; } - ma_uint32 desiredSampleRate = sampleRate; + desiredSampleRate = sampleRate; if (usingDefaultSampleRate) { - // When using the device's default sample rate, we get the highest priority standard rate supported by the device. Otherwise - // we just use the pre-set rate. - for (ma_uint32 iStandardRate = 0; iStandardRate < ma_countof(g_maStandardSampleRatePriorities); ++iStandardRate) { + /* + When using the device's default sample rate, we get the highest priority standard rate supported by the device. Otherwise + we just use the pre-set rate. + */ + ma_uint32 iStandardRate; + for (iStandardRate = 0; iStandardRate < ma_countof(g_maStandardSampleRatePriorities); ++iStandardRate) { ma_uint32 standardRate = g_maStandardSampleRatePriorities[iStandardRate]; - ma_bool32 foundRate = MA_FALSE; - for (UInt32 iDeviceRate = 0; iDeviceRate < deviceFormatDescriptionCount; ++iDeviceRate) { + UInt32 iDeviceRate; + + for (iDeviceRate = 0; iDeviceRate < deviceFormatDescriptionCount; ++iDeviceRate) { ma_uint32 deviceRate = (ma_uint32)pDeviceFormatDescriptions[iDeviceRate].mFormat.mSampleRate; if (deviceRate == standardRate) { @@ -16819,23 +17346,24 @@ ma_result ma_find_best_format__coreaudio(ma_context* pContext, AudioObjectID dev } } - ma_uint32 desiredChannelCount = channels; + desiredChannelCount = channels; if (usingDefaultChannels) { - ma_get_AudioObject_channel_count(pContext, deviceObjectID, deviceType, &desiredChannelCount); // <-- Not critical if this fails. + ma_get_AudioObject_channel_count(pContext, deviceObjectID, deviceType, &desiredChannelCount); /* <-- Not critical if this fails. */ } - ma_format desiredFormat = format; + desiredFormat = format; if (usingDefaultFormat) { desiredFormat = g_maFormatPriorities[0]; } - // If we get here it means we don't have an exact match to what the client is asking for. We'll need to find the closest one. The next - // loop will check for formats that have the same sample rate to what we're asking for. If there is, we prefer that one in all cases. - AudioStreamBasicDescription bestDeviceFormatSoFar; + /* + If we get here it means we don't have an exact match to what the client is asking for. We'll need to find the closest one. The next + loop will check for formats that have the same sample rate to what we're asking for. If there is, we prefer that one in all cases. + */ ma_zero_object(&bestDeviceFormatSoFar); - ma_bool32 hasSupportedFormat = MA_FALSE; - for (UInt32 iFormat = 0; iFormat < deviceFormatDescriptionCount; ++iFormat) { + hasSupportedFormat = MA_FALSE; + for (iFormat = 0; iFormat < deviceFormatDescriptionCount; ++iFormat) { ma_format format; ma_result formatResult = ma_format_from_AudioStreamBasicDescription(&pDeviceFormatDescriptions[iFormat].mFormat, &format); if (formatResult == MA_SUCCESS && format != ma_format_unknown) { @@ -16850,102 +17378,114 @@ ma_result ma_find_best_format__coreaudio(ma_context* pContext, AudioObjectID dev } - for (UInt32 iFormat = 0; iFormat < deviceFormatDescriptionCount; ++iFormat) { + for (iFormat = 0; iFormat < deviceFormatDescriptionCount; ++iFormat) { AudioStreamBasicDescription thisDeviceFormat = pDeviceFormatDescriptions[iFormat].mFormat; - - // If the format is not supported by miniaudio we need to skip this one entirely. ma_format thisSampleFormat; - ma_result formatResult = ma_format_from_AudioStreamBasicDescription(&pDeviceFormatDescriptions[iFormat].mFormat, &thisSampleFormat); + ma_result formatResult; + ma_format bestSampleFormatSoFar; + + /* If the format is not supported by miniaudio we need to skip this one entirely. */ + formatResult = ma_format_from_AudioStreamBasicDescription(&pDeviceFormatDescriptions[iFormat].mFormat, &thisSampleFormat); if (formatResult != MA_SUCCESS || thisSampleFormat == ma_format_unknown) { - continue; // The format is not supported by miniaudio. Skip. + continue; /* The format is not supported by miniaudio. Skip. */ } - ma_format bestSampleFormatSoFar; ma_format_from_AudioStreamBasicDescription(&bestDeviceFormatSoFar, &bestSampleFormatSoFar); - - // Getting here means the format is supported by miniaudio which makes this format a candidate. + /* Getting here means the format is supported by miniaudio which makes this format a candidate. */ if (thisDeviceFormat.mSampleRate != desiredSampleRate) { - // The sample rate does not match, but this format could still be usable, although it's a very low priority. If the best format - // so far has an equal sample rate we can just ignore this one. + /* + The sample rate does not match, but this format could still be usable, although it's a very low priority. If the best format + so far has an equal sample rate we can just ignore this one. + */ if (bestDeviceFormatSoFar.mSampleRate == desiredSampleRate) { - continue; // The best sample rate so far has the same sample rate as what we requested which means it's still the best so far. Skip this format. + continue; /* The best sample rate so far has the same sample rate as what we requested which means it's still the best so far. Skip this format. */ } else { - // In this case, neither the best format so far nor this one have the same sample rate. Check the channel count next. + /* In this case, neither the best format so far nor this one have the same sample rate. Check the channel count next. */ if (thisDeviceFormat.mChannelsPerFrame != desiredChannelCount) { - // This format has a different sample rate _and_ a different channel count. + /* This format has a different sample rate _and_ a different channel count. */ if (bestDeviceFormatSoFar.mChannelsPerFrame == desiredChannelCount) { - continue; // No change to the best format. + continue; /* No change to the best format. */ } else { - // Both this format and the best so far have different sample rates and different channel counts. Whichever has the - // best format is the new best. + /* + Both this format and the best so far have different sample rates and different channel counts. Whichever has the + best format is the new best. + */ if (ma_get_format_priority_index(thisSampleFormat) < ma_get_format_priority_index(bestSampleFormatSoFar)) { bestDeviceFormatSoFar = thisDeviceFormat; continue; } else { - continue; // No change to the best format. + continue; /* No change to the best format. */ } } } else { - // This format has a different sample rate but the desired channel count. + /* This format has a different sample rate but the desired channel count. */ if (bestDeviceFormatSoFar.mChannelsPerFrame == desiredChannelCount) { - // Both this format and the best so far have the desired channel count. Whichever has the best format is the new best. + /* Both this format and the best so far have the desired channel count. Whichever has the best format is the new best. */ if (ma_get_format_priority_index(thisSampleFormat) < ma_get_format_priority_index(bestSampleFormatSoFar)) { bestDeviceFormatSoFar = thisDeviceFormat; continue; } else { - continue; // No change to the best format for now. + continue; /* No change to the best format for now. */ } } else { - // This format has the desired channel count, but the best so far does not. We have a new best. + /* This format has the desired channel count, but the best so far does not. We have a new best. */ bestDeviceFormatSoFar = thisDeviceFormat; continue; } } } } else { - // The sample rates match which makes this format a very high priority contender. If the best format so far has a different - // sample rate it needs to be replaced with this one. + /* + The sample rates match which makes this format a very high priority contender. If the best format so far has a different + sample rate it needs to be replaced with this one. + */ if (bestDeviceFormatSoFar.mSampleRate != desiredSampleRate) { bestDeviceFormatSoFar = thisDeviceFormat; continue; } else { - // In this case both this format and the best format so far have the same sample rate. Check the channel count next. + /* In this case both this format and the best format so far have the same sample rate. Check the channel count next. */ if (thisDeviceFormat.mChannelsPerFrame == desiredChannelCount) { - // In this case this format has the same channel count as what the client is requesting. If the best format so far has - // a different count, this one becomes the new best. + /* + In this case this format has the same channel count as what the client is requesting. If the best format so far has + a different count, this one becomes the new best. + */ if (bestDeviceFormatSoFar.mChannelsPerFrame != desiredChannelCount) { bestDeviceFormatSoFar = thisDeviceFormat; continue; } else { - // In this case both this format and the best so far have the ideal sample rate and channel count. Check the format. + /* In this case both this format and the best so far have the ideal sample rate and channel count. Check the format. */ if (thisSampleFormat == desiredFormat) { bestDeviceFormatSoFar = thisDeviceFormat; - break; // Found the exact match. + break; /* Found the exact match. */ } else { - // The formats are different. The new best format is the one with the highest priority format according to miniaudio. + /* The formats are different. The new best format is the one with the highest priority format according to miniaudio. */ if (ma_get_format_priority_index(thisSampleFormat) < ma_get_format_priority_index(bestSampleFormatSoFar)) { bestDeviceFormatSoFar = thisDeviceFormat; continue; } else { - continue; // No change to the best format for now. + continue; /* No change to the best format for now. */ } } } } else { - // In this case the channel count is different to what the client has requested. If the best so far has the same channel - // count as the requested count then it remains the best. + /* + In this case the channel count is different to what the client has requested. If the best so far has the same channel + count as the requested count then it remains the best. + */ if (bestDeviceFormatSoFar.mChannelsPerFrame == desiredChannelCount) { continue; } else { - // This is the case where both have the same sample rate (good) but different channel counts. Right now both have about - // the same priority, but we need to compare the format now. + /* + This is the case where both have the same sample rate (good) but different channel counts. Right now both have about + the same priority, but we need to compare the format now. + */ if (thisSampleFormat == bestSampleFormatSoFar) { if (ma_get_format_priority_index(thisSampleFormat) < ma_get_format_priority_index(bestSampleFormatSoFar)) { bestDeviceFormatSoFar = thisDeviceFormat; continue; } else { - continue; // No change to the best format for now. + continue; /* No change to the best format for now. */ } } } @@ -16961,10 +17501,15 @@ ma_result ma_find_best_format__coreaudio(ma_context* pContext, AudioObjectID dev ma_result ma_get_AudioUnit_channel_map(ma_context* pContext, AudioUnit audioUnit, ma_device_type deviceType, ma_channel channelMap[MA_MAX_CHANNELS]) { - ma_assert(pContext != NULL); - AudioUnitScope deviceScope; AudioUnitElement deviceBus; + UInt32 channelLayoutSize; + OSStatus status; + AudioChannelLayout* pChannelLayout; + ma_result result; + + ma_assert(pContext != NULL); + if (deviceType == ma_device_type_playback) { deviceScope = kAudioUnitScope_Output; deviceBus = MA_COREAUDIO_OUTPUT_BUS; @@ -16973,13 +17518,12 @@ ma_result ma_get_AudioUnit_channel_map(ma_context* pContext, AudioUnit audioUnit deviceBus = MA_COREAUDIO_INPUT_BUS; } - UInt32 channelLayoutSize; - OSStatus status = ((ma_AudioUnitGetPropertyInfo_proc)pContext->coreaudio.AudioUnitGetPropertyInfo)(audioUnit, kAudioUnitProperty_AudioChannelLayout, deviceScope, deviceBus, &channelLayoutSize, NULL); + status = ((ma_AudioUnitGetPropertyInfo_proc)pContext->coreaudio.AudioUnitGetPropertyInfo)(audioUnit, kAudioUnitProperty_AudioChannelLayout, deviceScope, deviceBus, &channelLayoutSize, NULL); if (status != noErr) { return ma_result_from_OSStatus(status); } - AudioChannelLayout* pChannelLayout = (AudioChannelLayout*)ma_malloc(channelLayoutSize); + pChannelLayout = (AudioChannelLayout*)ma_malloc(channelLayoutSize); if (pChannelLayout == NULL) { return MA_OUT_OF_MEMORY; } @@ -16990,7 +17534,7 @@ ma_result ma_get_AudioUnit_channel_map(ma_context* pContext, AudioUnit audioUnit return ma_result_from_OSStatus(status); } - ma_result result = ma_get_channel_map_from_AudioChannelLayout(pChannelLayout, channelMap); + result = ma_get_channel_map_from_AudioChannelLayout(pChannelLayout, channelMap); if (result != MA_SUCCESS) { ma_free(pChannelLayout); return result; @@ -17012,21 +17556,21 @@ ma_bool32 ma_context_is_device_id_equal__coreaudio(ma_context* pContext, const m ma_result ma_context_enumerate_devices__coreaudio(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData) { - ma_assert(pContext != NULL); - ma_assert(callback != NULL); - #if defined(MA_APPLE_DESKTOP) UInt32 deviceCount; AudioObjectID* pDeviceObjectIDs; - ma_result result = ma_get_device_object_ids__coreaudio(pContext, &deviceCount, &pDeviceObjectIDs); + ma_result result; + UInt32 iDevice; + + result = ma_get_device_object_ids__coreaudio(pContext, &deviceCount, &pDeviceObjectIDs); if (result != MA_SUCCESS) { return result; } - for (UInt32 iDevice = 0; iDevice < deviceCount; ++iDevice) { + for (iDevice = 0; iDevice < deviceCount; ++iDevice) { AudioObjectID deviceObjectID = pDeviceObjectIDs[iDevice]; - ma_device_info info; + ma_zero_object(&info); if (ma_get_AudioObject_uid(pContext, deviceObjectID, sizeof(info.id.coreaudio), info.id.coreaudio) != MA_SUCCESS) { continue; @@ -17049,7 +17593,7 @@ ma_result ma_context_enumerate_devices__coreaudio(ma_context* pContext, ma_enum_ ma_free(pDeviceObjectIDs); #else - // Only supporting default devices on non-Desktop platforms. + /* Only supporting default devices on non-Desktop platforms. */ ma_device_info info; ma_zero_object(&info); @@ -17070,8 +17614,9 @@ ma_result ma_context_enumerate_devices__coreaudio(ma_context* pContext, ma_enum_ ma_result ma_context_get_device_info__coreaudio(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_share_mode shareMode, ma_device_info* pDeviceInfo) { + ma_result result; + ma_assert(pContext != NULL); - (void)pDeviceInfo; /* No exclusive mode with the Core Audio backend for now. */ if (shareMode == ma_share_mode_exclusive) { @@ -17079,151 +17624,169 @@ ma_result ma_context_get_device_info__coreaudio(ma_context* pContext, ma_device_ } #if defined(MA_APPLE_DESKTOP) - // Desktop - // ======= - AudioObjectID deviceObjectID; - ma_result result = ma_find_AudioObjectID(pContext, deviceType, pDeviceID, &deviceObjectID); - if (result != MA_SUCCESS) { - return result; - } - - result = ma_get_AudioObject_uid(pContext, deviceObjectID, sizeof(pDeviceInfo->id.coreaudio), pDeviceInfo->id.coreaudio); - if (result != MA_SUCCESS) { - return result; - } + /* Desktop */ + { + AudioObjectID deviceObjectID; + UInt32 streamDescriptionCount; + AudioStreamRangedDescription* pStreamDescriptions; + UInt32 iStreamDescription; + UInt32 sampleRateRangeCount; + AudioValueRange* pSampleRateRanges; + + result = ma_find_AudioObjectID(pContext, deviceType, pDeviceID, &deviceObjectID); + if (result != MA_SUCCESS) { + return result; + } - result = ma_get_AudioObject_name(pContext, deviceObjectID, sizeof(pDeviceInfo->name), pDeviceInfo->name); - if (result != MA_SUCCESS) { - return result; - } + result = ma_get_AudioObject_uid(pContext, deviceObjectID, sizeof(pDeviceInfo->id.coreaudio), pDeviceInfo->id.coreaudio); + if (result != MA_SUCCESS) { + return result; + } - // Formats. - UInt32 streamDescriptionCount; - AudioStreamRangedDescription* pStreamDescriptions; - result = ma_get_AudioObject_stream_descriptions(pContext, deviceObjectID, deviceType, &streamDescriptionCount, &pStreamDescriptions); - if (result != MA_SUCCESS) { - return result; - } + result = ma_get_AudioObject_name(pContext, deviceObjectID, sizeof(pDeviceInfo->name), pDeviceInfo->name); + if (result != MA_SUCCESS) { + return result; + } - for (UInt32 iStreamDescription = 0; iStreamDescription < streamDescriptionCount; ++iStreamDescription) { - ma_format format; - result = ma_format_from_AudioStreamBasicDescription(&pStreamDescriptions[iStreamDescription].mFormat, &format); + /* Formats. */ + result = ma_get_AudioObject_stream_descriptions(pContext, deviceObjectID, deviceType, &streamDescriptionCount, &pStreamDescriptions); if (result != MA_SUCCESS) { - continue; + return result; } + + for (iStreamDescription = 0; iStreamDescription < streamDescriptionCount; ++iStreamDescription) { + ma_format format; + ma_bool32 formatExists = MA_FALSE; + ma_uint32 iOutputFormat; + + result = ma_format_from_AudioStreamBasicDescription(&pStreamDescriptions[iStreamDescription].mFormat, &format); + if (result != MA_SUCCESS) { + continue; + } - ma_assert(format != ma_format_unknown); + ma_assert(format != ma_format_unknown); - // Make sure the format isn't already in the output list. - ma_bool32 exists = MA_FALSE; - for (ma_uint32 iOutputFormat = 0; iOutputFormat < pDeviceInfo->formatCount; ++iOutputFormat) { - if (pDeviceInfo->formats[iOutputFormat] == format) { - exists = MA_TRUE; - break; + /* Make sure the format isn't already in the output list. */ + for (iOutputFormat = 0; iOutputFormat < pDeviceInfo->formatCount; ++iOutputFormat) { + if (pDeviceInfo->formats[iOutputFormat] == format) { + formatExists = MA_TRUE; + break; + } } - } - if (!exists) { - pDeviceInfo->formats[pDeviceInfo->formatCount++] = format; + if (!formatExists) { + pDeviceInfo->formats[pDeviceInfo->formatCount++] = format; + } } - } - ma_free(pStreamDescriptions); + ma_free(pStreamDescriptions); - // Channels. - result = ma_get_AudioObject_channel_count(pContext, deviceObjectID, deviceType, &pDeviceInfo->minChannels); - if (result != MA_SUCCESS) { - return result; - } - pDeviceInfo->maxChannels = pDeviceInfo->minChannels; + /* Channels. */ + result = ma_get_AudioObject_channel_count(pContext, deviceObjectID, deviceType, &pDeviceInfo->minChannels); + if (result != MA_SUCCESS) { + return result; + } + pDeviceInfo->maxChannels = pDeviceInfo->minChannels; - // Sample rates. - UInt32 sampleRateRangeCount; - AudioValueRange* pSampleRateRanges; - result = ma_get_AudioObject_sample_rates(pContext, deviceObjectID, deviceType, &sampleRateRangeCount, &pSampleRateRanges); - if (result != MA_SUCCESS) { - return result; - } + /* Sample rates. */ + result = ma_get_AudioObject_sample_rates(pContext, deviceObjectID, deviceType, &sampleRateRangeCount, &pSampleRateRanges); + if (result != MA_SUCCESS) { + return result; + } - if (sampleRateRangeCount > 0) { - pDeviceInfo->minSampleRate = UINT32_MAX; - pDeviceInfo->maxSampleRate = 0; - for (UInt32 iSampleRate = 0; iSampleRate < sampleRateRangeCount; ++iSampleRate) { - if (pDeviceInfo->minSampleRate > pSampleRateRanges[iSampleRate].mMinimum) { - pDeviceInfo->minSampleRate = pSampleRateRanges[iSampleRate].mMinimum; - } - if (pDeviceInfo->maxSampleRate < pSampleRateRanges[iSampleRate].mMaximum) { - pDeviceInfo->maxSampleRate = pSampleRateRanges[iSampleRate].mMaximum; + if (sampleRateRangeCount > 0) { + UInt32 iSampleRate; + pDeviceInfo->minSampleRate = UINT32_MAX; + pDeviceInfo->maxSampleRate = 0; + for (iSampleRate = 0; iSampleRate < sampleRateRangeCount; ++iSampleRate) { + if (pDeviceInfo->minSampleRate > pSampleRateRanges[iSampleRate].mMinimum) { + pDeviceInfo->minSampleRate = pSampleRateRanges[iSampleRate].mMinimum; + } + if (pDeviceInfo->maxSampleRate < pSampleRateRanges[iSampleRate].mMaximum) { + pDeviceInfo->maxSampleRate = pSampleRateRanges[iSampleRate].mMaximum; + } } } } #else - // Mobile - // ====== - if (deviceType == ma_device_type_playback) { - ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); - } else { - ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); - } + /* Mobile */ + { + AudioComponentDescription desc; + AudioComponent component; + AudioUnit audioUnit; + OSStatus status; + AudioUnitScope formatScope; + AudioUnitElement formatElement; + AudioStreamBasicDescription bestFormat; + UInt32 propSize; + + if (deviceType == ma_device_type_playback) { + ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); + } else { + ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); + } - // Retrieving device information is more annoying on mobile than desktop. For simplicity I'm locking this down to whatever format is - // reported on a temporary I/O unit. The problem, however, is that this doesn't return a value for the sample rate which we need to - // retrieve from the AVAudioSession shared instance. - AudioComponentDescription desc; - desc.componentType = kAudioUnitType_Output; - desc.componentSubType = kAudioUnitSubType_RemoteIO; - desc.componentManufacturer = kAudioUnitManufacturer_Apple; - desc.componentFlags = 0; - desc.componentFlagsMask = 0; + /* + Retrieving device information is more annoying on mobile than desktop. For simplicity I'm locking this down to whatever format is + reported on a temporary I/O unit. The problem, however, is that this doesn't return a value for the sample rate which we need to + retrieve from the AVAudioSession shared instance. + */ + desc.componentType = kAudioUnitType_Output; + desc.componentSubType = kAudioUnitSubType_RemoteIO; + desc.componentManufacturer = kAudioUnitManufacturer_Apple; + desc.componentFlags = 0; + desc.componentFlagsMask = 0; - AudioComponent component = ((ma_AudioComponentFindNext_proc)pContext->coreaudio.AudioComponentFindNext)(NULL, &desc); - if (component == NULL) { - return MA_FAILED_TO_INIT_BACKEND; - } + component = ((ma_AudioComponentFindNext_proc)pContext->coreaudio.AudioComponentFindNext)(NULL, &desc); + if (component == NULL) { + return MA_FAILED_TO_INIT_BACKEND; + } - AudioUnit audioUnit; - OSStatus status = ((ma_AudioComponentInstanceNew_proc)pContext->coreaudio.AudioComponentInstanceNew)(component, &audioUnit); - if (status != noErr) { - return ma_result_from_OSStatus(status); - } + status = ((ma_AudioComponentInstanceNew_proc)pContext->coreaudio.AudioComponentInstanceNew)(component, &audioUnit); + if (status != noErr) { + return ma_result_from_OSStatus(status); + } - AudioUnitScope formatScope = (deviceType == ma_device_type_playback) ? kAudioUnitScope_Input : kAudioUnitScope_Output; - AudioUnitElement formatElement = (deviceType == ma_device_type_playback) ? MA_COREAUDIO_OUTPUT_BUS : MA_COREAUDIO_INPUT_BUS; + formatScope = (deviceType == ma_device_type_playback) ? kAudioUnitScope_Input : kAudioUnitScope_Output; + formatElement = (deviceType == ma_device_type_playback) ? MA_COREAUDIO_OUTPUT_BUS : MA_COREAUDIO_INPUT_BUS; - AudioStreamBasicDescription bestFormat; - UInt32 propSize = sizeof(bestFormat); - status = ((ma_AudioUnitGetProperty_proc)pContext->coreaudio.AudioUnitGetProperty)(audioUnit, kAudioUnitProperty_StreamFormat, formatScope, formatElement, &bestFormat, &propSize); - if (status != noErr) { - ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(audioUnit); - return ma_result_from_OSStatus(status); - } + propSize = sizeof(bestFormat); + status = ((ma_AudioUnitGetProperty_proc)pContext->coreaudio.AudioUnitGetProperty)(audioUnit, kAudioUnitProperty_StreamFormat, formatScope, formatElement, &bestFormat, &propSize); + if (status != noErr) { + ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(audioUnit); + return ma_result_from_OSStatus(status); + } - ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(audioUnit); - audioUnit = NULL; + ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(audioUnit); + audioUnit = NULL; - pDeviceInfo->minChannels = bestFormat.mChannelsPerFrame; - pDeviceInfo->maxChannels = bestFormat.mChannelsPerFrame; + pDeviceInfo->minChannels = bestFormat.mChannelsPerFrame; + pDeviceInfo->maxChannels = bestFormat.mChannelsPerFrame; - pDeviceInfo->formatCount = 1; - ma_result result = ma_format_from_AudioStreamBasicDescription(&bestFormat, &pDeviceInfo->formats[0]); - if (result != MA_SUCCESS) { - return result; - } + pDeviceInfo->formatCount = 1; + result = ma_format_from_AudioStreamBasicDescription(&bestFormat, &pDeviceInfo->formats[0]); + if (result != MA_SUCCESS) { + return result; + } - // It looks like Apple are wanting to push the whole AVAudioSession thing. Thus, we need to use that to determine device settings. To do - // this we just get the shared instance and inspect. - @autoreleasepool { - AVAudioSession* pAudioSession = [AVAudioSession sharedInstance]; - ma_assert(pAudioSession != NULL); + /* + It looks like Apple are wanting to push the whole AVAudioSession thing. Thus, we need to use that to determine device settings. To do + this we just get the shared instance and inspect. + */ + @autoreleasepool { + AVAudioSession* pAudioSession = [AVAudioSession sharedInstance]; + ma_assert(pAudioSession != NULL); - pDeviceInfo->minSampleRate = (ma_uint32)pAudioSession.sampleRate; - pDeviceInfo->maxSampleRate = pDeviceInfo->minSampleRate; + pDeviceInfo->minSampleRate = (ma_uint32)pAudioSession.sampleRate; + pDeviceInfo->maxSampleRate = pDeviceInfo->minSampleRate; + } } #endif + (void)pDeviceInfo; /* Unused. */ return MA_SUCCESS; } @@ -17252,27 +17815,25 @@ void ma_device_uninit__coreaudio(ma_device* pDevice) OSStatus ma_on_output__coreaudio(void* pUserData, AudioUnitRenderActionFlags* pActionFlags, const AudioTimeStamp* pTimeStamp, UInt32 busNumber, UInt32 frameCount, AudioBufferList* pBufferList) { - (void)pActionFlags; - (void)pTimeStamp; - (void)busNumber; - ma_device* pDevice = (ma_device*)pUserData; + ma_stream_layout layout; + ma_assert(pDevice != NULL); #if defined(MA_DEBUG_OUTPUT) printf("INFO: Output Callback: busNumber=%d, frameCount=%d, mNumberBuffers=%d\n", busNumber, frameCount, pBufferList->mNumberBuffers); #endif - // We need to check whether or not we are outputting interleaved or non-interleaved samples. The - // way we do this is slightly different for each type. - ma_stream_layout layout = ma_stream_layout_interleaved; + /* We need to check whether or not we are outputting interleaved or non-interleaved samples. The way we do this is slightly different for each type. */ + layout = ma_stream_layout_interleaved; if (pBufferList->mBuffers[0].mNumberChannels != pDevice->playback.internalChannels) { layout = ma_stream_layout_deinterleaved; } if (layout == ma_stream_layout_interleaved) { - // For now we can assume everything is interleaved. - for (UInt32 iBuffer = 0; iBuffer < pBufferList->mNumberBuffers; ++iBuffer) { + /* For now we can assume everything is interleaved. */ + UInt32 iBuffer; + for (iBuffer = 0; iBuffer < pBufferList->mNumberBuffers; ++iBuffer) { if (pBufferList->mBuffers[iBuffer].mNumberChannels == pDevice->playback.internalChannels) { ma_uint32 frameCountForThisBuffer = pBufferList->mBuffers[iBuffer].mDataByteSize / ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels); if (frameCountForThisBuffer > 0) { @@ -17287,9 +17848,11 @@ OSStatus ma_on_output__coreaudio(void* pUserData, AudioUnitRenderActionFlags* pA printf(" frameCount=%d, mNumberChannels=%d, mDataByteSize=%d\n", frameCount, pBufferList->mBuffers[iBuffer].mNumberChannels, pBufferList->mBuffers[iBuffer].mDataByteSize); #endif } else { - // This case is where the number of channels in the output buffer do not match our internal channels. It could mean that it's - // not interleaved, in which case we can't handle right now since miniaudio does not yet support non-interleaved streams. We just - // output silence here. + /* + This case is where the number of channels in the output buffer do not match our internal channels. It could mean that it's + not interleaved, in which case we can't handle right now since miniaudio does not yet support non-interleaved streams. We just + output silence here. + */ ma_zero_memory(pBufferList->mBuffers[iBuffer].mData, pBufferList->mBuffers[iBuffer].mDataByteSize); #if defined(MA_DEBUG_OUTPUT) @@ -17298,14 +17861,16 @@ OSStatus ma_on_output__coreaudio(void* pUserData, AudioUnitRenderActionFlags* pA } } } else { - // This is the deinterleaved case. We need to update each buffer in groups of internalChannels. This - // assumes each buffer is the same size. + /* This is the deinterleaved case. We need to update each buffer in groups of internalChannels. This assumes each buffer is the same size. */ ma_uint8 tempBuffer[4096]; - for (UInt32 iBuffer = 0; iBuffer < pBufferList->mNumberBuffers; iBuffer += pDevice->playback.internalChannels) { + UInt32 iBuffer; + for (iBuffer = 0; iBuffer < pBufferList->mNumberBuffers; iBuffer += pDevice->playback.internalChannels) { ma_uint32 frameCountPerBuffer = pBufferList->mBuffers[iBuffer].mDataByteSize / ma_get_bytes_per_sample(pDevice->playback.internalFormat); - ma_uint32 framesRemaining = frameCountPerBuffer; + while (framesRemaining > 0) { + void* ppDeinterleavedBuffers[MA_MAX_CHANNELS]; + ma_uint32 iChannel; ma_uint32 framesToRead = sizeof(tempBuffer) / ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels); if (framesToRead > framesRemaining) { framesToRead = framesRemaining; @@ -17317,8 +17882,7 @@ OSStatus ma_on_output__coreaudio(void* pUserData, AudioUnitRenderActionFlags* pA ma_device__read_frames_from_client(pDevice, framesToRead, tempBuffer); } - void* ppDeinterleavedBuffers[MA_MAX_CHANNELS]; - for (ma_uint32 iChannel = 0; iChannel < pDevice->playback.internalChannels; ++iChannel) { + for (iChannel = 0; iChannel < pDevice->playback.internalChannels; ++iChannel) { ppDeinterleavedBuffers[iChannel] = (void*)ma_offset_ptr(pBufferList->mBuffers[iBuffer].mData, (frameCountPerBuffer - framesRemaining) * ma_get_bytes_per_sample(pDevice->playback.internalFormat)); } @@ -17329,26 +17893,27 @@ OSStatus ma_on_output__coreaudio(void* pUserData, AudioUnitRenderActionFlags* pA } } + (void)pActionFlags; + (void)pTimeStamp; + (void)busNumber; + return noErr; } OSStatus ma_on_input__coreaudio(void* pUserData, AudioUnitRenderActionFlags* pActionFlags, const AudioTimeStamp* pTimeStamp, UInt32 busNumber, UInt32 frameCount, AudioBufferList* pUnusedBufferList) { - (void)pActionFlags; - (void)pTimeStamp; - (void)busNumber; - (void)frameCount; - (void)pUnusedBufferList; - ma_device* pDevice = (ma_device*)pUserData; + AudioBufferList* pRenderedBufferList; + ma_stream_layout layout; + OSStatus status; + ma_assert(pDevice != NULL); - AudioBufferList* pRenderedBufferList = (AudioBufferList*)pDevice->coreaudio.pAudioBufferList; + pRenderedBufferList = (AudioBufferList*)pDevice->coreaudio.pAudioBufferList; ma_assert(pRenderedBufferList); - // We need to check whether or not we are outputting interleaved or non-interleaved samples. The - // way we do this is slightly different for each type. - ma_stream_layout layout = ma_stream_layout_interleaved; + /* We need to check whether or not we are outputting interleaved or non-interleaved samples. The way we do this is slightly different for each type. */ + layout = ma_stream_layout_interleaved; if (pRenderedBufferList->mBuffers[0].mNumberChannels != pDevice->capture.internalChannels) { layout = ma_stream_layout_deinterleaved; } @@ -17357,7 +17922,7 @@ OSStatus ma_on_input__coreaudio(void* pUserData, AudioUnitRenderActionFlags* pAc printf("INFO: Input Callback: busNumber=%d, frameCount=%d, mNumberBuffers=%d\n", busNumber, frameCount, pRenderedBufferList->mNumberBuffers); #endif - OSStatus status = ((ma_AudioUnitRender_proc)pDevice->pContext->coreaudio.AudioUnitRender)((AudioUnit)pDevice->coreaudio.audioUnitCapture, pActionFlags, pTimeStamp, busNumber, frameCount, pRenderedBufferList); + status = ((ma_AudioUnitRender_proc)pDevice->pContext->coreaudio.AudioUnitRender)((AudioUnit)pDevice->coreaudio.audioUnitCapture, pActionFlags, pTimeStamp, busNumber, frameCount, pRenderedBufferList); if (status != noErr) { #if defined(MA_DEBUG_OUTPUT) printf(" ERROR: AudioUnitRender() failed with %d\n", status); @@ -17366,7 +17931,8 @@ OSStatus ma_on_input__coreaudio(void* pUserData, AudioUnitRenderActionFlags* pAc } if (layout == ma_stream_layout_interleaved) { - for (UInt32 iBuffer = 0; iBuffer < pRenderedBufferList->mNumberBuffers; ++iBuffer) { + UInt32 iBuffer; + for (iBuffer = 0; iBuffer < pRenderedBufferList->mNumberBuffers; ++iBuffer) { if (pRenderedBufferList->mBuffers[iBuffer].mNumberChannels == pDevice->capture.internalChannels) { if (pDevice->type == ma_device_type_duplex) { ma_device__handle_duplex_callback_capture(pDevice, frameCount, pRenderedBufferList->mBuffers[iBuffer].mData, &pDevice->coreaudio.duplexRB); @@ -17377,13 +17943,16 @@ OSStatus ma_on_input__coreaudio(void* pUserData, AudioUnitRenderActionFlags* pAc printf(" mDataByteSize=%d\n", pRenderedBufferList->mBuffers[iBuffer].mDataByteSize); #endif } else { - // This case is where the number of channels in the output buffer do not match our internal channels. It could mean that it's - // not interleaved, in which case we can't handle right now since miniaudio does not yet support non-interleaved streams. - + /* + This case is where the number of channels in the output buffer do not match our internal channels. It could mean that it's + not interleaved, in which case we can't handle right now since miniaudio does not yet support non-interleaved streams. + */ ma_uint8 silentBuffer[4096]; + ma_uint32 framesRemaining; + ma_zero_memory(silentBuffer, sizeof(silentBuffer)); - ma_uint32 framesRemaining = frameCount; + framesRemaining = frameCount; while (framesRemaining > 0) { ma_uint32 framesToSend = sizeof(silentBuffer) / ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels); if (framesToSend > framesRemaining) { @@ -17405,19 +17974,20 @@ OSStatus ma_on_input__coreaudio(void* pUserData, AudioUnitRenderActionFlags* pAc } } } else { - // This is the deinterleaved case. We need to interleave the audio data before sending it to the client. This - // assumes each buffer is the same size. + /* This is the deinterleaved case. We need to interleave the audio data before sending it to the client. This assumes each buffer is the same size. */ ma_uint8 tempBuffer[4096]; - for (UInt32 iBuffer = 0; iBuffer < pRenderedBufferList->mNumberBuffers; iBuffer += pDevice->capture.internalChannels) { + UInt32 iBuffer; + for (iBuffer = 0; iBuffer < pRenderedBufferList->mNumberBuffers; iBuffer += pDevice->capture.internalChannels) { ma_uint32 framesRemaining = frameCount; while (framesRemaining > 0) { + void* ppDeinterleavedBuffers[MA_MAX_CHANNELS]; + ma_uint32 iChannel; ma_uint32 framesToSend = sizeof(tempBuffer) / ma_get_bytes_per_sample(pDevice->capture.internalFormat); if (framesToSend > framesRemaining) { framesToSend = framesRemaining; } - void* ppDeinterleavedBuffers[MA_MAX_CHANNELS]; - for (ma_uint32 iChannel = 0; iChannel < pDevice->capture.internalChannels; ++iChannel) { + for (iChannel = 0; iChannel < pDevice->capture.internalChannels; ++iChannel) { ppDeinterleavedBuffers[iChannel] = (void*)ma_offset_ptr(pRenderedBufferList->mBuffers[iBuffer].mData, (frameCount - framesRemaining) * ma_get_bytes_per_sample(pDevice->capture.internalFormat)); } @@ -17434,20 +18004,26 @@ OSStatus ma_on_input__coreaudio(void* pUserData, AudioUnitRenderActionFlags* pAc } } + (void)pActionFlags; + (void)pTimeStamp; + (void)busNumber; + (void)frameCount; + (void)pUnusedBufferList; + return noErr; } void on_start_stop__coreaudio(void* pUserData, AudioUnit audioUnit, AudioUnitPropertyID propertyID, AudioUnitScope scope, AudioUnitElement element) { - (void)propertyID; - ma_device* pDevice = (ma_device*)pUserData; ma_assert(pDevice != NULL); - // There's been a report of a deadlock here when triggered by ma_device_uninit(). It looks like - // AudioUnitGetProprty (called below) and AudioComponentInstanceDispose (called in ma_device_uninit) - // can try waiting on the same lock. I'm going to try working around this by not calling any Core - // Audio APIs in the callback when the device has been stopped or uninitialized. + /* + There's been a report of a deadlock here when triggered by ma_device_uninit(). It looks like + AudioUnitGetProprty (called below) and AudioComponentInstanceDispose (called in ma_device_uninit) + can try waiting on the same lock. I'm going to try working around this by not calling any Core + Audio APIs in the callback when the device has been stopped or uninitialized. + */ if (ma_device__get_state(pDevice) == MA_STATE_UNINITIALIZED || ma_device__get_state(pDevice) == MA_STATE_STOPPING || ma_device__get_state(pDevice) == MA_STATE_STOPPED) { ma_stop_proc onStop = pDevice->onStop; if (onStop) { @@ -17460,66 +18036,76 @@ void on_start_stop__coreaudio(void* pUserData, AudioUnit audioUnit, AudioUnitPro UInt32 isRunningSize = sizeof(isRunning); OSStatus status = ((ma_AudioUnitGetProperty_proc)pDevice->pContext->coreaudio.AudioUnitGetProperty)(audioUnit, kAudioOutputUnitProperty_IsRunning, scope, element, &isRunning, &isRunningSize); if (status != noErr) { - return; // Don't really know what to do in this case... just ignore it, I suppose... + return; /* Don't really know what to do in this case... just ignore it, I suppose... */ } if (!isRunning) { - // The stop event is a bit annoying in Core Audio because it will be called when we automatically switch the default device. Some scenarios to consider: - // - // 1) When the device is unplugged, this will be called _before_ the default device change notification. - // 2) When the device is changed via the default device change notification, this will be called _after_ the switch. - // - // For case #1, we just check if there's a new default device available. If so, we just ignore the stop event. For case #2 we check a flag. + ma_stop_proc onStop; + + /* + The stop event is a bit annoying in Core Audio because it will be called when we automatically switch the default device. Some scenarios to consider: + + 1) When the device is unplugged, this will be called _before_ the default device change notification. + 2) When the device is changed via the default device change notification, this will be called _after_ the switch. + + For case #1, we just check if there's a new default device available. If so, we just ignore the stop event. For case #2 we check a flag. + */ if (((audioUnit == pDevice->coreaudio.audioUnitPlayback) && pDevice->coreaudio.isDefaultPlaybackDevice) || ((audioUnit == pDevice->coreaudio.audioUnitCapture) && pDevice->coreaudio.isDefaultCaptureDevice)) { - // It looks like the device is switching through an external event, such as the user unplugging the device or changing the default device - // via the operating system's sound settings. If we're re-initializing the device, we just terminate because we want the stopping of the - // device to be seamless to the client (we don't want them receiving the onStop event and thinking that the device has stopped when it - // hasn't!). + /* + It looks like the device is switching through an external event, such as the user unplugging the device or changing the default device + via the operating system's sound settings. If we're re-initializing the device, we just terminate because we want the stopping of the + device to be seamless to the client (we don't want them receiving the onStop event and thinking that the device has stopped when it + hasn't!). + */ if (((audioUnit == pDevice->coreaudio.audioUnitPlayback) && pDevice->coreaudio.isSwitchingPlaybackDevice) || ((audioUnit == pDevice->coreaudio.audioUnitCapture) && pDevice->coreaudio.isSwitchingCaptureDevice)) { return; } - // Getting here means the device is not reinitializing which means it may have been unplugged. From what I can see, it looks like Core Audio - // will try switching to the new default device seamlessly. We need to somehow find a way to determine whether or not Core Audio will most - // likely be successful in switching to the new device. - // - // TODO: Try to predict if Core Audio will switch devices. If not, the onStop callback needs to be posted. + /* + Getting here means the device is not reinitializing which means it may have been unplugged. From what I can see, it looks like Core Audio + will try switching to the new default device seamlessly. We need to somehow find a way to determine whether or not Core Audio will most + likely be successful in switching to the new device. + + TODO: Try to predict if Core Audio will switch devices. If not, the onStop callback needs to be posted. + */ return; } - // Getting here means we need to stop the device. - ma_stop_proc onStop = pDevice->onStop; + /* Getting here means we need to stop the device. */ + onStop = pDevice->onStop; if (onStop) { onStop(pDevice); } } } + + (void)propertyID; /* Unused. */ } #if defined(MA_APPLE_DESKTOP) OSStatus ma_default_device_changed__coreaudio(AudioObjectID objectID, UInt32 addressCount, const AudioObjectPropertyAddress* pAddresses, void* pUserData) { - (void)objectID; - ma_device* pDevice = (ma_device*)pUserData; ma_assert(pDevice != NULL); - // Not sure if I really need to check this, but it makes me feel better. + /* Not sure if I really need to check this, but it makes me feel better. */ if (addressCount == 0) { return noErr; } if (pAddresses[0].mSelector == kAudioHardwarePropertyDefaultOutputDevice) { + ma_result reinitResult; + pDevice->coreaudio.isSwitchingPlaybackDevice = MA_TRUE; - ma_result reinitResult = ma_device_reinit_internal__coreaudio(pDevice, ma_device_type_playback, MA_TRUE); + reinitResult = ma_device_reinit_internal__coreaudio(pDevice, ma_device_type_playback, MA_TRUE); pDevice->coreaudio.isSwitchingPlaybackDevice = MA_FALSE; if (reinitResult == MA_SUCCESS) { ma_device__post_init_setup(pDevice, ma_device_type_playback); - // Restart the device if required. If this fails we need to stop the device entirely. + /* Restart the device if required. If this fails we need to stop the device entirely. */ if (ma_device__get_state(pDevice) == MA_STATE_STARTED) { OSStatus status = ((ma_AudioOutputUnitStart_proc)pDevice->pContext->coreaudio.AudioOutputUnitStart)((AudioUnit)pDevice->coreaudio.audioUnitPlayback); if (status != noErr) { @@ -17533,14 +18119,16 @@ OSStatus ma_default_device_changed__coreaudio(AudioObjectID objectID, UInt32 add } if (pAddresses[0].mSelector == kAudioHardwarePropertyDefaultInputDevice) { + ma_result reinitResult; + pDevice->coreaudio.isSwitchingPlaybackDevice = MA_TRUE; - ma_result reinitResult = ma_device_reinit_internal__coreaudio(pDevice, ma_device_type_capture, MA_TRUE); + reinitResult = ma_device_reinit_internal__coreaudio(pDevice, ma_device_type_capture, MA_TRUE); pDevice->coreaudio.isSwitchingPlaybackDevice = MA_FALSE; if (reinitResult == MA_SUCCESS) { ma_device__post_init_setup(pDevice, ma_device_type_capture); - // Restart the device if required. If this fails we need to stop the device entirely. + /* Restart the device if required. If this fails we need to stop the device entirely. */ if (ma_device__get_state(pDevice) == MA_STATE_STARTED) { OSStatus status = ((ma_AudioOutputUnitStart_proc)pDevice->pContext->coreaudio.AudioOutputUnitStart)((AudioUnit)pDevice->coreaudio.audioUnitCapture); if (status != noErr) { @@ -17553,13 +18141,14 @@ OSStatus ma_default_device_changed__coreaudio(AudioObjectID objectID, UInt32 add } } + (void)objectID; /* Unused. */ return noErr; } #endif typedef struct { - // Input. + /* Input. */ ma_format formatIn; ma_uint32 channelsIn; ma_uint32 sampleRateIn; @@ -17574,13 +18163,13 @@ typedef struct ma_share_mode shareMode; ma_bool32 registerStopEvent; - // Output. + /* Output. */ #if defined(MA_APPLE_DESKTOP) AudioObjectID deviceObjectID; #endif AudioComponent component; AudioUnit audioUnit; - AudioBufferList* pAudioBufferList; // Only used for input devices. + AudioBufferList* pAudioBufferList; /* Only used for input devices. */ ma_format formatOut; ma_uint32 channelsOut; ma_uint32 sampleRateOut; @@ -17592,6 +18181,16 @@ typedef struct ma_result ma_device_init_internal__coreaudio(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_init_internal_data__coreaudio* pData, void* pDevice_DoNotReference) /* <-- pDevice is typed as void* intentionally so as to avoid accidentally referencing it. */ { + ma_result result; + OSStatus status; + UInt32 enableIOFlag; + AudioStreamBasicDescription bestFormat; + ma_uint32 actualBufferSizeInFrames; + AURenderCallbackStruct callbackInfo; +#if defined(MA_APPLE_DESKTOP) + AudioObjectID deviceObjectID; +#endif + /* This API should only be used for a single device type: playback or capture. No full-duplex mode. */ if (deviceType == ma_device_type_duplex) { return MA_INVALID_ARGS; @@ -17607,10 +18206,7 @@ ma_result ma_device_init_internal__coreaudio(ma_context* pContext, ma_device_typ pData->audioUnit = NULL; pData->pAudioBufferList = NULL; - ma_result result; - #if defined(MA_APPLE_DESKTOP) - AudioObjectID deviceObjectID; result = ma_find_AudioObjectID(pContext, deviceType, pDeviceID, &deviceObjectID); if (result != MA_SUCCESS) { return result; @@ -17619,7 +18215,7 @@ ma_result ma_device_init_internal__coreaudio(ma_context* pContext, ma_device_typ pData->deviceObjectID = deviceObjectID; #endif - // Core audio doesn't really use the notion of a period so we can leave this unmodified, but not too over the top. + /* Core audio doesn't really use the notion of a period so we can leave this unmodified, but not too over the top. */ pData->periodsOut = pData->periodsIn; if (pData->periodsOut < 1) { pData->periodsOut = 1; @@ -17629,15 +18225,15 @@ ma_result ma_device_init_internal__coreaudio(ma_context* pContext, ma_device_typ } - // Audio unit. - OSStatus status = ((ma_AudioComponentInstanceNew_proc)pContext->coreaudio.AudioComponentInstanceNew)((AudioComponent)pContext->coreaudio.component, (AudioUnit*)&pData->audioUnit); + /* Audio unit. */ + status = ((ma_AudioComponentInstanceNew_proc)pContext->coreaudio.AudioComponentInstanceNew)((AudioComponent)pContext->coreaudio.component, (AudioUnit*)&pData->audioUnit); if (status != noErr) { return ma_result_from_OSStatus(status); } - // The input/output buses need to be explicitly enabled and disabled. We set the flag based on the output unit first, then we just swap it for input. - UInt32 enableIOFlag = 1; + /* The input/output buses need to be explicitly enabled and disabled. We set the flag based on the output unit first, then we just swap it for input. */ + enableIOFlag = 1; if (deviceType == ma_device_type_capture) { enableIOFlag = 0; } @@ -17656,7 +18252,7 @@ ma_result ma_device_init_internal__coreaudio(ma_context* pContext, ma_device_typ } - // Set the device to use with this audio unit. This is only used on desktop since we are using defaults on mobile. + /* Set the device to use with this audio unit. This is only used on desktop since we are using defaults on mobile. */ #if defined(MA_APPLE_DESKTOP) status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, (deviceType == ma_device_type_playback) ? MA_COREAUDIO_OUTPUT_BUS : MA_COREAUDIO_INPUT_BUS, &deviceObjectID, sizeof(AudioDeviceID)); if (status != noErr) { @@ -17665,31 +18261,34 @@ ma_result ma_device_init_internal__coreaudio(ma_context* pContext, ma_device_typ } #endif - // Format. This is the hardest part of initialization because there's a few variables to take into account. - // 1) The format must be supported by the device. - // 2) The format must be supported miniaudio. - // 3) There's a priority that miniaudio prefers. - // - // Ideally we would like to use a format that's as close to the hardware as possible so we can get as close to a passthrough as possible. The - // most important property is the sample rate. miniaudio can do format conversion for any sample rate and channel count, but cannot do the same - // for the sample data format. If the sample data format is not supported by miniaudio it must be ignored completely. - // - // On mobile platforms this is a bit different. We just force the use of whatever the audio unit's current format is set to. - AudioStreamBasicDescription bestFormat; + /* + Format. This is the hardest part of initialization because there's a few variables to take into account. + 1) The format must be supported by the device. + 2) The format must be supported miniaudio. + 3) There's a priority that miniaudio prefers. + + Ideally we would like to use a format that's as close to the hardware as possible so we can get as close to a passthrough as possible. The + most important property is the sample rate. miniaudio can do format conversion for any sample rate and channel count, but cannot do the same + for the sample data format. If the sample data format is not supported by miniaudio it must be ignored completely. + + On mobile platforms this is a bit different. We just force the use of whatever the audio unit's current format is set to. + */ { AudioUnitScope formatScope = (deviceType == ma_device_type_playback) ? kAudioUnitScope_Input : kAudioUnitScope_Output; AudioUnitElement formatElement = (deviceType == ma_device_type_playback) ? MA_COREAUDIO_OUTPUT_BUS : MA_COREAUDIO_INPUT_BUS; - + #if defined(MA_APPLE_DESKTOP) + AudioStreamBasicDescription origFormat; + UInt32 origFormatSize; + result = ma_find_best_format__coreaudio(pContext, deviceObjectID, deviceType, pData->formatIn, pData->channelsIn, pData->sampleRateIn, pData->usingDefaultFormat, pData->usingDefaultChannels, pData->usingDefaultSampleRate, &bestFormat); if (result != MA_SUCCESS) { ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit); return result; } - // From what I can see, Apple's documentation implies that we should keep the sample rate consistent. - AudioStreamBasicDescription origFormat; - UInt32 origFormatSize = sizeof(origFormat); + /* From what I can see, Apple's documentation implies that we should keep the sample rate consistent. */ + origFormatSize = sizeof(origFormat); if (deviceType == ma_device_type_playback) { status = ((ma_AudioUnitGetProperty_proc)pContext->coreaudio.AudioUnitGetProperty)(pData->audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, MA_COREAUDIO_OUTPUT_BUS, &origFormat, &origFormatSize); } else { @@ -17705,7 +18304,7 @@ ma_result ma_device_init_internal__coreaudio(ma_context* pContext, ma_device_typ status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioUnitProperty_StreamFormat, formatScope, formatElement, &bestFormat, sizeof(bestFormat)); if (status != noErr) { - // We failed to set the format, so fall back to the current format of the audio unit. + /* We failed to set the format, so fall back to the current format of the audio unit. */ bestFormat = origFormat; } #else @@ -17716,10 +18315,12 @@ ma_result ma_device_init_internal__coreaudio(ma_context* pContext, ma_device_typ return ma_result_from_OSStatus(status); } - // Sample rate is a little different here because for some reason kAudioUnitProperty_StreamFormat returns 0... Oh well. We need to instead try - // setting the sample rate to what the user has requested and then just see the results of it. Need to use some Objective-C here for this since - // it depends on Apple's AVAudioSession API. To do this we just get the shared AVAudioSession instance and then set it. Note that from what I - // can tell, it looks like the sample rate is shared between playback and capture for everything. + /* + Sample rate is a little different here because for some reason kAudioUnitProperty_StreamFormat returns 0... Oh well. We need to instead try + setting the sample rate to what the user has requested and then just see the results of it. Need to use some Objective-C here for this since + it depends on Apple's AVAudioSession API. To do this we just get the shared AVAudioSession instance and then set it. Note that from what I + can tell, it looks like the sample rate is shared between playback and capture for everything. + */ @autoreleasepool { AVAudioSession* pAudioSession = [AVAudioSession sharedInstance]; ma_assert(pAudioSession != NULL); @@ -17750,34 +18351,35 @@ ma_result ma_device_init_internal__coreaudio(ma_context* pContext, ma_device_typ pData->sampleRateOut = bestFormat.mSampleRate; } - - // Internal channel map. This is weird in my testing. If I use the AudioObject to get the - // channel map, the channel descriptions are set to "Unknown" for some reason. To work around - // this it looks like retrieving it from the AudioUnit will work. However, and this is where - // it gets weird, it doesn't seem to work with capture devices, nor at all on iOS... Therefore - // I'm going to fall back to a default assumption in these cases. + /* + Internal channel map. This is weird in my testing. If I use the AudioObject to get the + channel map, the channel descriptions are set to "Unknown" for some reason. To work around + this it looks like retrieving it from the AudioUnit will work. However, and this is where + it gets weird, it doesn't seem to work with capture devices, nor at all on iOS... Therefore + I'm going to fall back to a default assumption in these cases. + */ #if defined(MA_APPLE_DESKTOP) result = ma_get_AudioUnit_channel_map(pContext, pData->audioUnit, deviceType, pData->channelMapOut); if (result != MA_SUCCESS) { #if 0 - // Try falling back to the channel map from the AudioObject. + /* Try falling back to the channel map from the AudioObject. */ result = ma_get_AudioObject_channel_map(pContext, deviceObjectID, deviceType, pData->channelMapOut); if (result != MA_SUCCESS) { return result; } #else - // Fall back to default assumptions. + /* Fall back to default assumptions. */ ma_get_standard_channel_map(ma_standard_channel_map_default, pData->channelsOut, pData->channelMapOut); #endif } #else - // TODO: Figure out how to get the channel map using AVAudioSession. + /* TODO: Figure out how to get the channel map using AVAudioSession. */ ma_get_standard_channel_map(ma_standard_channel_map_default, pData->channelsOut, pData->channelMapOut); #endif - - // Buffer size. Not allowing this to be configurable on iOS. - ma_uint32 actualBufferSizeInFrames = pData->bufferSizeInFramesIn; + + /* Buffer size. Not allowing this to be configurable on iOS. */ + actualBufferSizeInFrames = pData->bufferSizeInFramesIn; #if defined(MA_APPLE_DESKTOP) if (actualBufferSizeInFrames == 0) { @@ -17797,13 +18399,14 @@ ma_result ma_device_init_internal__coreaudio(ma_context* pContext, ma_device_typ #endif + /* + During testing I discovered that the buffer size can be too big. You'll get an error like this: - // During testing I discovered that the buffer size can be too big. You'll get an error like this: - // - // kAudioUnitErr_TooManyFramesToProcess : inFramesToProcess=4096, mMaxFramesPerSlice=512 - // - // Note how inFramesToProcess is smaller than mMaxFramesPerSlice. To fix, we need to set kAudioUnitProperty_MaximumFramesPerSlice to that - // of the size of our buffer, or do it the other way around and set our buffer size to the kAudioUnitProperty_MaximumFramesPerSlice. + kAudioUnitErr_TooManyFramesToProcess : inFramesToProcess=4096, mMaxFramesPerSlice=512 + + Note how inFramesToProcess is smaller than mMaxFramesPerSlice. To fix, we need to set kAudioUnitProperty_MaximumFramesPerSlice to that + of the size of our buffer, or do it the other way around and set our buffer size to the kAudioUnitProperty_MaximumFramesPerSlice. + */ { /*AudioUnitScope propScope = (deviceType == ma_device_type_playback) ? kAudioUnitScope_Input : kAudioUnitScope_Output; AudioUnitElement propBus = (deviceType == ma_device_type_playback) ? MA_COREAUDIO_OUTPUT_BUS : MA_COREAUDIO_INPUT_BUS; @@ -17821,22 +18424,24 @@ ma_result ma_device_init_internal__coreaudio(ma_context* pContext, ma_device_typ } } - // We need a buffer list if this is an input device. We render into this in the input callback. + /* We need a buffer list if this is an input device. We render into this in the input callback. */ if (deviceType == ma_device_type_capture) { ma_bool32 isInterleaved = (bestFormat.mFormatFlags & kAudioFormatFlagIsNonInterleaved) == 0; - - size_t allocationSize = sizeof(AudioBufferList) - sizeof(AudioBuffer); // Subtract sizeof(AudioBuffer) because that part is dynamically sized. + size_t allocationSize; + AudioBufferList* pBufferList; + + allocationSize = sizeof(AudioBufferList) - sizeof(AudioBuffer); /* Subtract sizeof(AudioBuffer) because that part is dynamically sized. */ if (isInterleaved) { - // Interleaved case. This is the simple case because we just have one buffer. + /* Interleaved case. This is the simple case because we just have one buffer. */ allocationSize += sizeof(AudioBuffer) * 1; allocationSize += actualBufferSizeInFrames * ma_get_bytes_per_frame(pData->formatOut, pData->channelsOut); } else { - // Non-interleaved case. This is the more complex case because there's more than one buffer. + /* Non-interleaved case. This is the more complex case because there's more than one buffer. */ allocationSize += sizeof(AudioBuffer) * pData->channelsOut; allocationSize += actualBufferSizeInFrames * ma_get_bytes_per_sample(pData->formatOut) * pData->channelsOut; } - AudioBufferList* pBufferList = (AudioBufferList*)ma_malloc(allocationSize); + pBufferList = (AudioBufferList*)ma_malloc(allocationSize); if (pBufferList == NULL) { ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit); return MA_OUT_OF_MEMORY; @@ -17848,8 +18453,9 @@ ma_result ma_device_init_internal__coreaudio(ma_context* pContext, ma_device_typ pBufferList->mBuffers[0].mDataByteSize = actualBufferSizeInFrames * ma_get_bytes_per_frame(pData->formatOut, pData->channelsOut); pBufferList->mBuffers[0].mData = (ma_uint8*)pBufferList + sizeof(AudioBufferList); } else { + ma_uint32 iBuffer; pBufferList->mNumberBuffers = pData->channelsOut; - for (ma_uint32 iBuffer = 0; iBuffer < pBufferList->mNumberBuffers; ++iBuffer) { + for (iBuffer = 0; iBuffer < pBufferList->mNumberBuffers; ++iBuffer) { pBufferList->mBuffers[iBuffer].mNumberChannels = 1; pBufferList->mBuffers[iBuffer].mDataByteSize = actualBufferSizeInFrames * ma_get_bytes_per_sample(pData->formatOut); pBufferList->mBuffers[iBuffer].mData = (ma_uint8*)pBufferList + ((sizeof(AudioBufferList) - sizeof(AudioBuffer)) + (sizeof(AudioBuffer) * pData->channelsOut)) + (actualBufferSizeInFrames * ma_get_bytes_per_sample(pData->formatOut) * iBuffer); @@ -17859,8 +18465,7 @@ ma_result ma_device_init_internal__coreaudio(ma_context* pContext, ma_device_typ pData->pAudioBufferList = pBufferList; } - // Callbacks. - AURenderCallbackStruct callbackInfo; + /* Callbacks. */ callbackInfo.inputProcRefCon = pDevice_DoNotReference; if (deviceType == ma_device_type_playback) { callbackInfo.inputProc = ma_on_output__coreaudio; @@ -17878,7 +18483,7 @@ ma_result ma_device_init_internal__coreaudio(ma_context* pContext, ma_device_typ } } - // We need to listen for stop events. + /* We need to listen for stop events. */ if (pData->registerStopEvent) { status = ((ma_AudioUnitAddPropertyListener_proc)pContext->coreaudio.AudioUnitAddPropertyListener)(pData->audioUnit, kAudioOutputUnitProperty_IsRunning, on_start_stop__coreaudio, pDevice_DoNotReference); if (status != noErr) { @@ -17887,7 +18492,7 @@ ma_result ma_device_init_internal__coreaudio(ma_context* pContext, ma_device_typ } } - // Initialize the audio unit. + /* Initialize the audio unit. */ status = ((ma_AudioUnitInitialize_proc)pContext->coreaudio.AudioUnitInitialize)(pData->audioUnit); if (status != noErr) { ma_free(pData->pAudioBufferList); @@ -17896,7 +18501,7 @@ ma_result ma_device_init_internal__coreaudio(ma_context* pContext, ma_device_typ return ma_result_from_OSStatus(status); } - // Grab the name. + /* Grab the name. */ #if defined(MA_APPLE_DESKTOP) ma_get_AudioObject_name(pContext, deviceObjectID, sizeof(pData->deviceName), pData->deviceName); #else @@ -17912,12 +18517,14 @@ ma_result ma_device_init_internal__coreaudio(ma_context* pContext, ma_device_typ ma_result ma_device_reinit_internal__coreaudio(ma_device* pDevice, ma_device_type deviceType, ma_bool32 disposePreviousAudioUnit) { + ma_device_init_internal_data__coreaudio data; + ma_result result; + /* This should only be called for playback or capture, not duplex. */ if (deviceType == ma_device_type_duplex) { return MA_INVALID_ARGS; } - ma_device_init_internal_data__coreaudio data; if (deviceType == ma_device_type_capture) { data.formatIn = pDevice->capture.format; data.channelsIn = pDevice->capture.channels; @@ -17970,7 +18577,7 @@ ma_result ma_device_reinit_internal__coreaudio(ma_device* pDevice, ma_device_typ data.bufferSizeInMillisecondsIn = pDevice->coreaudio.originalBufferSizeInMilliseconds; data.periodsIn = pDevice->coreaudio.originalPeriods; - ma_result result = ma_device_init_internal__coreaudio(pDevice->pContext, deviceType, NULL, &data, (void*)pDevice); + result = ma_device_init_internal__coreaudio(pDevice->pContext, deviceType, NULL, &data, (void*)pDevice); if (result != MA_SUCCESS) { return result; } @@ -17981,7 +18588,7 @@ ma_result ma_device_reinit_internal__coreaudio(ma_device* pDevice, ma_device_typ ma_result ma_device_init__coreaudio(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice) { - (void)pConfig; + ma_result result; ma_assert(pContext != NULL); ma_assert(pConfig != NULL); @@ -18009,7 +18616,7 @@ ma_result ma_device_init__coreaudio(ma_context* pContext, const ma_device_config data.bufferSizeInMillisecondsIn = pConfig->bufferSizeInMilliseconds; data.registerStopEvent = MA_TRUE; - ma_result result = ma_device_init_internal__coreaudio(pDevice->pContext, ma_device_type_capture, pConfig->capture.pDeviceID, &data, (void*)pDevice); + result = ma_device_init_internal__coreaudio(pDevice->pContext, ma_device_type_capture, pConfig->capture.pDeviceID, &data, (void*)pDevice); if (result != MA_SUCCESS) { return result; } @@ -18028,10 +18635,12 @@ ma_result ma_device_init__coreaudio(ma_context* pContext, const ma_device_config pDevice->capture.internalBufferSizeInFrames = data.bufferSizeInFramesOut; pDevice->capture.internalPeriods = data.periodsOut; - // TODO: This needs to be made global. + /* TODO: This needs to be made global. */ #if defined(MA_APPLE_DESKTOP) - // If we are using the default device we'll need to listen for changes to the system's default device so we can seemlessly - // switch the device in the background. + /* + If we are using the default device we'll need to listen for changes to the system's default device so we can seemlessly + switch the device in the background. + */ if (pConfig->capture.pDeviceID == NULL) { AudioObjectPropertyAddress propAddress; propAddress.mSelector = kAudioHardwarePropertyDefaultInputDevice; @@ -18067,7 +18676,7 @@ ma_result ma_device_init__coreaudio(ma_context* pContext, const ma_device_config data.registerStopEvent = MA_TRUE; } - ma_result result = ma_device_init_internal__coreaudio(pDevice->pContext, ma_device_type_playback, pConfig->playback.pDeviceID, &data, (void*)pDevice); + result = ma_device_init_internal__coreaudio(pDevice->pContext, ma_device_type_playback, pConfig->playback.pDeviceID, &data, (void*)pDevice); if (result != MA_SUCCESS) { if (pConfig->deviceType == ma_device_type_duplex) { ((ma_AudioComponentInstanceDispose_proc)pDevice->pContext->coreaudio.AudioComponentInstanceDispose)((AudioUnit)pDevice->coreaudio.audioUnitCapture); @@ -18091,10 +18700,12 @@ ma_result ma_device_init__coreaudio(ma_context* pContext, const ma_device_config pDevice->playback.internalBufferSizeInFrames = data.bufferSizeInFramesOut; pDevice->playback.internalPeriods = data.periodsOut; - // TODO: This needs to be made global. + /* TODO: This needs to be made global. */ #if defined(MA_APPLE_DESKTOP) - // If we are using the default device we'll need to listen for changes to the system's default device so we can seemlessly - // switch the device in the background. + /* + If we are using the default device we'll need to listen for changes to the system's default device so we can seemlessly + switch the device in the background. + */ if (pConfig->playback.pDeviceID == NULL) { AudioObjectPropertyAddress propAddress; propAddress.mSelector = kAudioHardwarePropertyDefaultOutputDevice; @@ -18204,8 +18815,7 @@ ma_result ma_context_init__coreaudio(const ma_context_config* pConfig, ma_contex [pAudioSession setCategory: AVAudioSessionCategoryPlayAndRecord error:nil]; - // By default we want miniaudio to use the speakers instead of the receiver. In the future this may - // be customizable. + /* By default we want miniaudio to use the speakers instead of the receiver. In the future this may be customizable. */ ma_bool32 useSpeakers = MA_TRUE; if (useSpeakers) { [pAudioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil]; @@ -18233,11 +18843,12 @@ ma_result ma_context_init__coreaudio(const ma_context_config* pConfig, ma_contex pContext->coreaudio.AudioObjectSetPropertyData = ma_dlsym(pContext->coreaudio.hCoreAudio, "AudioObjectSetPropertyData"); pContext->coreaudio.AudioObjectAddPropertyListener = ma_dlsym(pContext->coreaudio.hCoreAudio, "AudioObjectAddPropertyListener"); - - // It looks like Apple has moved some APIs from AudioUnit into AudioToolbox on more recent versions of macOS. They are still - // defined in AudioUnit, but just in case they decide to remove them from there entirely I'm going to implement a fallback. - // The way it'll work is that it'll first try AudioUnit, and if the required symbols are not present there we'll fall back to - // AudioToolbox. + /* + It looks like Apple has moved some APIs from AudioUnit into AudioToolbox on more recent versions of macOS. They are still + defined in AudioUnit, but just in case they decide to remove them from there entirely I'm going to implement a fallback. + The way it'll work is that it'll first try AudioUnit, and if the required symbols are not present there we'll fall back to + AudioToolbox. + */ pContext->coreaudio.hAudioUnit = ma_dlopen("AudioUnit.framework/AudioUnit"); if (pContext->coreaudio.hAudioUnit == NULL) { ma_dlclose(pContext->coreaudio.hCoreAudio); @@ -18246,7 +18857,7 @@ ma_result ma_context_init__coreaudio(const ma_context_config* pConfig, ma_contex } if (ma_dlsym(pContext->coreaudio.hAudioUnit, "AudioComponentFindNext") == NULL) { - // Couldn't find the required symbols in AudioUnit, so fall back to AudioToolbox. + /* Couldn't find the required symbols in AudioUnit, so fall back to AudioToolbox. */ ma_dlclose(pContext->coreaudio.hAudioUnit); pContext->coreaudio.hAudioUnit = ma_dlopen("AudioToolbox.framework/AudioToolbox"); if (pContext->coreaudio.hAudioUnit == NULL) { @@ -18301,54 +18912,59 @@ ma_result ma_context_init__coreaudio(const ma_context_config* pConfig, ma_contex pContext->onDeviceStart = ma_device_start__coreaudio; pContext->onDeviceStop = ma_device_stop__coreaudio; - // Audio component. - AudioComponentDescription desc; - desc.componentType = kAudioUnitType_Output; -#if defined(MA_APPLE_DESKTOP) - desc.componentSubType = kAudioUnitSubType_HALOutput; -#else - desc.componentSubType = kAudioUnitSubType_RemoteIO; -#endif - desc.componentManufacturer = kAudioUnitManufacturer_Apple; - desc.componentFlags = 0; - desc.componentFlagsMask = 0; - - pContext->coreaudio.component = ((ma_AudioComponentFindNext_proc)pContext->coreaudio.AudioComponentFindNext)(NULL, &desc); - if (pContext->coreaudio.component == NULL) { -#if !defined(MA_NO_RUNTIME_LINKING) && !defined(MA_APPLE_MOBILE) - ma_dlclose(pContext->coreaudio.hAudioUnit); - ma_dlclose(pContext->coreaudio.hCoreAudio); - ma_dlclose(pContext->coreaudio.hCoreFoundation); -#endif - return MA_FAILED_TO_INIT_BACKEND; + /* Audio component. */ + { + AudioComponentDescription desc; + desc.componentType = kAudioUnitType_Output; + #if defined(MA_APPLE_DESKTOP) + desc.componentSubType = kAudioUnitSubType_HALOutput; + #else + desc.componentSubType = kAudioUnitSubType_RemoteIO; + #endif + desc.componentManufacturer = kAudioUnitManufacturer_Apple; + desc.componentFlags = 0; + desc.componentFlagsMask = 0; + + pContext->coreaudio.component = ((ma_AudioComponentFindNext_proc)pContext->coreaudio.AudioComponentFindNext)(NULL, &desc); + if (pContext->coreaudio.component == NULL) { + #if !defined(MA_NO_RUNTIME_LINKING) && !defined(MA_APPLE_MOBILE) + ma_dlclose(pContext->coreaudio.hAudioUnit); + ma_dlclose(pContext->coreaudio.hCoreAudio); + ma_dlclose(pContext->coreaudio.hCoreFoundation); + #endif + return MA_FAILED_TO_INIT_BACKEND; + } } return MA_SUCCESS; } -#endif // Core Audio +#endif /* Core Audio */ + + +/****************************************************************************** +sndio Backend -/////////////////////////////////////////////////////////////////////////////// -// -// sndio Backend -// -/////////////////////////////////////////////////////////////////////////////// +******************************************************************************/ #ifdef MA_HAS_SNDIO #include #include -// Only supporting OpenBSD. This did not work very well at all on FreeBSD when I tried it. Not sure if this is due -// to miniaudio's implementation or if it's some kind of system configuration issue, but basically the default device -// just doesn't emit any sound, or at times you'll hear tiny pieces. I will consider enabling this when there's -// demand for it or if I can get it tested and debugged more thoroughly. - -//#if defined(__NetBSD__) || defined(__OpenBSD__) -//#include -//#endif -//#if defined(__FreeBSD__) || defined(__DragonFly__) -//#include -//#endif +/* +Only supporting OpenBSD. This did not work very well at all on FreeBSD when I tried it. Not sure if this is due +to miniaudio's implementation or if it's some kind of system configuration issue, but basically the default device +just doesn't emit any sound, or at times you'll hear tiny pieces. I will consider enabling this when there's +demand for it or if I can get it tested and debugged more thoroughly. +*/ +#if 0 +#if defined(__NetBSD__) || defined(__OpenBSD__) +#include +#endif +#if defined(__FreeBSD__) || defined(__DragonFly__) +#include +#endif +#endif #define MA_SIO_DEVANY "default" #define MA_SIO_PLAY 1 @@ -18358,7 +18974,7 @@ ma_result ma_context_init__coreaudio(const ma_context_config* pConfig, ma_contex #define MA_SIO_NRATE 16 #define MA_SIO_NCONF 4 -struct ma_sio_hdl; // <-- Opaque +struct ma_sio_hdl; /* <-- Opaque */ struct ma_sio_par { @@ -18419,7 +19035,7 @@ typedef int (* ma_sio_initpar_proc)(struct ma_sio_par*); ma_format ma_format_from_sio_enc__sndio(unsigned int bits, unsigned int bps, unsigned int sig, unsigned int le, unsigned int msb) { - // We only support native-endian right now. + /* We only support native-endian right now. */ if ((ma_is_little_endian() && le == 0) || (ma_is_big_endian() && le == 1)) { return ma_format_unknown; } @@ -18434,7 +19050,7 @@ ma_format ma_format_from_sio_enc__sndio(unsigned int bits, unsigned int bps, uns return ma_format_s24; } if (bits == 24 && bps == 4 && sig == 1 && msb == 0) { - //return ma_format_s24_32; + /*return ma_format_s24_32;*/ } if (bits == 32 && bps == 4 && sig == 1) { return ma_format_s32; @@ -18445,29 +19061,40 @@ ma_format ma_format_from_sio_enc__sndio(unsigned int bits, unsigned int bps, uns ma_format ma_find_best_format_from_sio_cap__sndio(struct ma_sio_cap* caps) { + ma_format bestFormat; + unsigned int iConfig; + ma_assert(caps != NULL); - ma_format bestFormat = ma_format_unknown; - for (unsigned int iConfig = 0; iConfig < caps->nconf; iConfig += 1) { - for (unsigned int iEncoding = 0; iEncoding < MA_SIO_NENC; iEncoding += 1) { + bestFormat = ma_format_unknown; + for (iConfig = 0; iConfig < caps->nconf; iConfig += 1) { + unsigned int iEncoding; + for (iEncoding = 0; iEncoding < MA_SIO_NENC; iEncoding += 1) { + unsigned int bits; + unsigned int bps; + unsigned int sig; + unsigned int le; + unsigned int msb; + ma_format format; + if ((caps->confs[iConfig].enc & (1UL << iEncoding)) == 0) { continue; } - unsigned int bits = caps->enc[iEncoding].bits; - unsigned int bps = caps->enc[iEncoding].bps; - unsigned int sig = caps->enc[iEncoding].sig; - unsigned int le = caps->enc[iEncoding].le; - unsigned int msb = caps->enc[iEncoding].msb; - ma_format format = ma_format_from_sio_enc__sndio(bits, bps, sig, le, msb); + bits = caps->enc[iEncoding].bits; + bps = caps->enc[iEncoding].bps; + sig = caps->enc[iEncoding].sig; + le = caps->enc[iEncoding].le; + msb = caps->enc[iEncoding].msb; + format = ma_format_from_sio_enc__sndio(bits, bps, sig, le, msb); if (format == ma_format_unknown) { - continue; // Format not supported. + continue; /* Format not supported. */ } if (bestFormat == ma_format_unknown) { bestFormat = format; } else { - if (ma_get_format_priority_index(bestFormat) > ma_get_format_priority_index(format)) { // <-- Lower = better. + if (ma_get_format_priority_index(bestFormat) > ma_get_format_priority_index(format)) { /* <-- Lower = better. */ bestFormat = format; } } @@ -18479,31 +19106,45 @@ ma_format ma_find_best_format_from_sio_cap__sndio(struct ma_sio_cap* caps) ma_uint32 ma_find_best_channels_from_sio_cap__sndio(struct ma_sio_cap* caps, ma_device_type deviceType, ma_format requiredFormat) { + ma_uint32 maxChannels; + unsigned int iConfig; + ma_assert(caps != NULL); ma_assert(requiredFormat != ma_format_unknown); - // Just pick whatever configuration has the most channels. - ma_uint32 maxChannels = 0; - for (unsigned int iConfig = 0; iConfig < caps->nconf; iConfig += 1) { - // The encoding should be of requiredFormat. - for (unsigned int iEncoding = 0; iEncoding < MA_SIO_NENC; iEncoding += 1) { + /* Just pick whatever configuration has the most channels. */ + maxChannels = 0; + for (iConfig = 0; iConfig < caps->nconf; iConfig += 1) { + /* The encoding should be of requiredFormat. */ + unsigned int iEncoding; + for (iEncoding = 0; iEncoding < MA_SIO_NENC; iEncoding += 1) { + unsigned int iChannel; + unsigned int bits; + unsigned int bps; + unsigned int sig; + unsigned int le; + unsigned int msb; + ma_format format; + if ((caps->confs[iConfig].enc & (1UL << iEncoding)) == 0) { continue; } - unsigned int bits = caps->enc[iEncoding].bits; - unsigned int bps = caps->enc[iEncoding].bps; - unsigned int sig = caps->enc[iEncoding].sig; - unsigned int le = caps->enc[iEncoding].le; - unsigned int msb = caps->enc[iEncoding].msb; - ma_format format = ma_format_from_sio_enc__sndio(bits, bps, sig, le, msb); + bits = caps->enc[iEncoding].bits; + bps = caps->enc[iEncoding].bps; + sig = caps->enc[iEncoding].sig; + le = caps->enc[iEncoding].le; + msb = caps->enc[iEncoding].msb; + format = ma_format_from_sio_enc__sndio(bits, bps, sig, le, msb); if (format != requiredFormat) { continue; } - // Getting here means the format is supported. Iterate over each channel count and grab the biggest one. - for (unsigned int iChannel = 0; iChannel < MA_SIO_NCHAN; iChannel += 1) { + /* Getting here means the format is supported. Iterate over each channel count and grab the biggest one. */ + for (iChannel = 0; iChannel < MA_SIO_NCHAN; iChannel += 1) { unsigned int chan = 0; + unsigned int channels; + if (deviceType == ma_device_type_playback) { chan = caps->confs[iConfig].pchan; } else { @@ -18514,7 +19155,6 @@ ma_uint32 ma_find_best_channels_from_sio_cap__sndio(struct ma_sio_cap* caps, ma_ continue; } - unsigned int channels; if (deviceType == ma_device_type_playback) { channels = caps->pchan[iChannel]; } else { @@ -18533,34 +19173,50 @@ ma_uint32 ma_find_best_channels_from_sio_cap__sndio(struct ma_sio_cap* caps, ma_ ma_uint32 ma_find_best_sample_rate_from_sio_cap__sndio(struct ma_sio_cap* caps, ma_device_type deviceType, ma_format requiredFormat, ma_uint32 requiredChannels) { + ma_uint32 firstSampleRate; + ma_uint32 bestSampleRate; + unsigned int iConfig; + ma_assert(caps != NULL); ma_assert(requiredFormat != ma_format_unknown); ma_assert(requiredChannels > 0); ma_assert(requiredChannels <= MA_MAX_CHANNELS); - ma_uint32 firstSampleRate = 0; // <-- If the device does not support a standard rate we'll fall back to the first one that's found. - - ma_uint32 bestSampleRate = 0; - for (unsigned int iConfig = 0; iConfig < caps->nconf; iConfig += 1) { - // The encoding should be of requiredFormat. - for (unsigned int iEncoding = 0; iEncoding < MA_SIO_NENC; iEncoding += 1) { + firstSampleRate = 0; /* <-- If the device does not support a standard rate we'll fall back to the first one that's found. */ + bestSampleRate = 0; + + for (iConfig = 0; iConfig < caps->nconf; iConfig += 1) { + /* The encoding should be of requiredFormat. */ + unsigned int iEncoding; + for (iEncoding = 0; iEncoding < MA_SIO_NENC; iEncoding += 1) { + unsigned int iChannel; + unsigned int bits; + unsigned int bps; + unsigned int sig; + unsigned int le; + unsigned int msb; + ma_format format; + if ((caps->confs[iConfig].enc & (1UL << iEncoding)) == 0) { continue; } - unsigned int bits = caps->enc[iEncoding].bits; - unsigned int bps = caps->enc[iEncoding].bps; - unsigned int sig = caps->enc[iEncoding].sig; - unsigned int le = caps->enc[iEncoding].le; - unsigned int msb = caps->enc[iEncoding].msb; - ma_format format = ma_format_from_sio_enc__sndio(bits, bps, sig, le, msb); + bits = caps->enc[iEncoding].bits; + bps = caps->enc[iEncoding].bps; + sig = caps->enc[iEncoding].sig; + le = caps->enc[iEncoding].le; + msb = caps->enc[iEncoding].msb; + format = ma_format_from_sio_enc__sndio(bits, bps, sig, le, msb); if (format != requiredFormat) { continue; } - // Getting here means the format is supported. Iterate over each channel count and grab the biggest one. - for (unsigned int iChannel = 0; iChannel < MA_SIO_NCHAN; iChannel += 1) { + /* Getting here means the format is supported. Iterate over each channel count and grab the biggest one. */ + for (iChannel = 0; iChannel < MA_SIO_NCHAN; iChannel += 1) { unsigned int chan = 0; + unsigned int channels; + unsigned int iRate; + if (deviceType == ma_device_type_playback) { chan = caps->confs[iConfig].pchan; } else { @@ -18571,7 +19227,6 @@ ma_uint32 ma_find_best_sample_rate_from_sio_cap__sndio(struct ma_sio_cap* caps, continue; } - unsigned int channels; if (deviceType == ma_device_type_playback) { channels = caps->pchan[iChannel]; } else { @@ -18582,21 +19237,22 @@ ma_uint32 ma_find_best_sample_rate_from_sio_cap__sndio(struct ma_sio_cap* caps, continue; } - // Getting here means we have found a compatible encoding/channel pair. - for (unsigned int iRate = 0; iRate < MA_SIO_NRATE; iRate += 1) { + /* Getting here means we have found a compatible encoding/channel pair. */ + for (iRate = 0; iRate < MA_SIO_NRATE; iRate += 1) { ma_uint32 rate = (ma_uint32)caps->rate[iRate]; + ma_uint32 ratePriority; if (firstSampleRate == 0) { firstSampleRate = rate; } - // Disregard this rate if it's not a standard one. - ma_uint32 ratePriority = ma_get_standard_sample_rate_priority_index(rate); + /* Disregard this rate if it's not a standard one. */ + ratePriority = ma_get_standard_sample_rate_priority_index(rate); if (ratePriority == (ma_uint32)-1) { continue; } - if (ma_get_standard_sample_rate_priority_index(bestSampleRate) > ratePriority) { // Lower = better. + if (ma_get_standard_sample_rate_priority_index(bestSampleRate) > ratePriority) { /* Lower = better. */ bestSampleRate = rate; } } @@ -18604,7 +19260,7 @@ ma_uint32 ma_find_best_sample_rate_from_sio_cap__sndio(struct ma_sio_cap* caps, } } - // If a standard sample rate was not found just fall back to the first one that was iterated. + /* If a standard sample rate was not found just fall back to the first one that was iterated. */ if (bestSampleRate == 0) { bestSampleRate = firstSampleRate; } @@ -18625,19 +19281,19 @@ ma_bool32 ma_context_is_device_id_equal__sndio(ma_context* pContext, const ma_de ma_result ma_context_enumerate_devices__sndio(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData) { + ma_bool32 isTerminating = MA_FALSE; + struct ma_sio_hdl* handle; + ma_assert(pContext != NULL); ma_assert(callback != NULL); - // sndio doesn't seem to have a good device enumeration API, so I'm therefore only enumerating - // over default devices for now. - ma_bool32 isTerminating = MA_FALSE; - struct ma_sio_hdl* handle; + /* sndio doesn't seem to have a good device enumeration API, so I'm therefore only enumerating over default devices for now. */ - // Playback. + /* Playback. */ if (!isTerminating) { handle = ((ma_sio_open_proc)pContext->sndio.sio_open)(MA_SIO_DEVANY, MA_SIO_PLAY, 0); if (handle != NULL) { - // Supports playback. + /* Supports playback. */ ma_device_info deviceInfo; ma_zero_object(&deviceInfo); ma_strcpy_s(deviceInfo.id.sndio, sizeof(deviceInfo.id.sndio), MA_SIO_DEVANY); @@ -18649,11 +19305,11 @@ ma_result ma_context_enumerate_devices__sndio(ma_context* pContext, ma_enum_devi } } - // Capture. + /* Capture. */ if (!isTerminating) { handle = ((ma_sio_open_proc)pContext->sndio.sio_open)(MA_SIO_DEVANY, MA_SIO_REC, 0); if (handle != NULL) { - // Supports capture. + /* Supports capture. */ ma_device_info deviceInfo; ma_zero_object(&deviceInfo); ma_strcpy_s(deviceInfo.id.sndio, sizeof(deviceInfo.id.sndio), "default"); @@ -18670,11 +19326,15 @@ ma_result ma_context_enumerate_devices__sndio(ma_context* pContext, ma_enum_devi ma_result ma_context_get_device_info__sndio(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_share_mode shareMode, ma_device_info* pDeviceInfo) { + char devid[256]; + struct ma_sio_hdl* handle; + struct ma_sio_cap caps; + unsigned int iConfig; + ma_assert(pContext != NULL); (void)shareMode; - // We need to open the device before we can get information about it. - char devid[256]; + /* We need to open the device before we can get information about it. */ if (pDeviceID == NULL) { ma_strcpy_s(devid, sizeof(devid), MA_SIO_DEVANY); ma_strcpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), (deviceType == ma_device_type_playback) ? MA_DEFAULT_PLAYBACK_DEVICE_NAME : MA_DEFAULT_CAPTURE_DEVICE_NAME); @@ -18683,37 +19343,50 @@ ma_result ma_context_get_device_info__sndio(ma_context* pContext, ma_device_type ma_strcpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), devid); } - struct ma_sio_hdl* handle = ((ma_sio_open_proc)pContext->sndio.sio_open)(devid, (deviceType == ma_device_type_playback) ? MA_SIO_PLAY : MA_SIO_REC, 0); + handle = ((ma_sio_open_proc)pContext->sndio.sio_open)(devid, (deviceType == ma_device_type_playback) ? MA_SIO_PLAY : MA_SIO_REC, 0); if (handle == NULL) { return MA_NO_DEVICE; } - struct ma_sio_cap caps; if (((ma_sio_getcap_proc)pContext->sndio.sio_getcap)(handle, &caps) == 0) { return MA_ERROR; } - for (unsigned int iConfig = 0; iConfig < caps.nconf; iConfig += 1) { - // The main thing we care about is that the encoding is supported by miniaudio. If it is, we want to give - // preference to some formats over others. - for (unsigned int iEncoding = 0; iEncoding < MA_SIO_NENC; iEncoding += 1) { + for (iConfig = 0; iConfig < caps.nconf; iConfig += 1) { + /* + The main thing we care about is that the encoding is supported by miniaudio. If it is, we want to give + preference to some formats over others. + */ + unsigned int iEncoding; + unsigned int iChannel; + unsigned int iRate; + + for (iEncoding = 0; iEncoding < MA_SIO_NENC; iEncoding += 1) { + unsigned int bits; + unsigned int bps; + unsigned int sig; + unsigned int le; + unsigned int msb; + ma_format format; + ma_bool32 formatExists = MA_FALSE; + ma_uint32 iExistingFormat; + if ((caps.confs[iConfig].enc & (1UL << iEncoding)) == 0) { continue; } - unsigned int bits = caps.enc[iEncoding].bits; - unsigned int bps = caps.enc[iEncoding].bps; - unsigned int sig = caps.enc[iEncoding].sig; - unsigned int le = caps.enc[iEncoding].le; - unsigned int msb = caps.enc[iEncoding].msb; - ma_format format = ma_format_from_sio_enc__sndio(bits, bps, sig, le, msb); + bits = caps.enc[iEncoding].bits; + bps = caps.enc[iEncoding].bps; + sig = caps.enc[iEncoding].sig; + le = caps.enc[iEncoding].le; + msb = caps.enc[iEncoding].msb; + format = ma_format_from_sio_enc__sndio(bits, bps, sig, le, msb); if (format == ma_format_unknown) { - continue; // Format not supported. + continue; /* Format not supported. */ } - // Add this format if it doesn't already exist. - ma_bool32 formatExists = MA_FALSE; - for (ma_uint32 iExistingFormat = 0; iExistingFormat < pDeviceInfo->formatCount; iExistingFormat += 1) { + /* Add this format if it doesn't already exist. */ + for (iExistingFormat = 0; iExistingFormat < pDeviceInfo->formatCount; iExistingFormat += 1) { if (pDeviceInfo->formats[iExistingFormat] == format) { formatExists = MA_TRUE; break; @@ -18725,9 +19398,11 @@ ma_result ma_context_get_device_info__sndio(ma_context* pContext, ma_device_type } } - // Channels. - for (unsigned int iChannel = 0; iChannel < MA_SIO_NCHAN; iChannel += 1) { + /* Channels. */ + for (iChannel = 0; iChannel < MA_SIO_NCHAN; iChannel += 1) { unsigned int chan = 0; + unsigned int channels; + if (deviceType == ma_device_type_playback) { chan = caps.confs[iConfig].pchan; } else { @@ -18738,7 +19413,6 @@ ma_result ma_context_get_device_info__sndio(ma_context* pContext, ma_device_type continue; } - unsigned int channels; if (deviceType == ma_device_type_playback) { channels = caps.pchan[iChannel]; } else { @@ -18753,8 +19427,8 @@ ma_result ma_context_get_device_info__sndio(ma_context* pContext, ma_device_type } } - // Sample rates. - for (unsigned int iRate = 0; iRate < MA_SIO_NRATE; iRate += 1) { + /* Sample rates. */ + for (iRate = 0; iRate < MA_SIO_NRATE; iRate += 1) { if ((caps.confs[iConfig].rate & (1UL << iRate)) != 0) { unsigned int rate = caps.rate[iRate]; if (pDeviceInfo->minSampleRate > rate) { @@ -19053,17 +19727,13 @@ ma_result ma_context_uninit__sndio(ma_context* pContext) ma_result ma_context_init__sndio(const ma_context_config* pConfig, ma_context* pContext) { - ma_assert(pContext != NULL); - - (void)pConfig; - #ifndef MA_NO_RUNTIME_LINKING - // libpulse.so const char* libsndioNames[] = { "libsndio.so" }; + size_t i; - for (size_t i = 0; i < ma_countof(libsndioNames); ++i) { + for (i = 0; i < ma_countof(libsndioNames); ++i) { pContext->sndio.sndioSO = ma_dlopen(libsndioNames[i]); if (pContext->sndio.sndioSO != NULL) { break; @@ -19108,17 +19778,18 @@ ma_result ma_context_init__sndio(const ma_context_config* pConfig, ma_context* p pContext->onDeviceWrite = ma_device_write__sndio; pContext->onDeviceRead = ma_device_read__sndio; + (void)pConfig; return MA_SUCCESS; } -#endif // sndio +#endif /* sndio */ -/////////////////////////////////////////////////////////////////////////////// -// -// audio(4) Backend -// -/////////////////////////////////////////////////////////////////////////////// +/****************************************************************************** + +audio(4) Backend + +******************************************************************************/ #ifdef MA_HAS_AUDIO4 #include #include @@ -19137,11 +19808,13 @@ ma_result ma_context_init__sndio(const ma_context_config* pConfig, ma_context* p void ma_construct_device_id__audio4(char* id, size_t idSize, const char* base, int deviceIndex) { + size_t baseLen; + ma_assert(id != NULL); ma_assert(idSize > 0); ma_assert(deviceIndex >= 0); - size_t baseLen = strlen(base); + baseLen = strlen(base); ma_assert(idSize > baseLen); ma_strcpy_s(id, idSize, base); @@ -19150,23 +19823,27 @@ void ma_construct_device_id__audio4(char* id, size_t idSize, const char* base, i ma_result ma_extract_device_index_from_id__audio4(const char* id, const char* base, int* pIndexOut) { + size_t idLen; + size_t baseLen; + const char* deviceIndexStr; + ma_assert(id != NULL); ma_assert(base != NULL); ma_assert(pIndexOut != NULL); - size_t idLen = strlen(id); - size_t baseLen = strlen(base); + idLen = strlen(id); + baseLen = strlen(base); if (idLen <= baseLen) { - return MA_ERROR; // Doesn't look like the id starts with the base. + return MA_ERROR; /* Doesn't look like the id starts with the base. */ } if (strncmp(id, base, baseLen) != 0) { - return MA_ERROR; // ID does not begin with base. + return MA_ERROR; /* ID does not begin with base. */ } - const char* deviceIndexStr = id + baseLen; + deviceIndexStr = id + baseLen; if (deviceIndexStr[0] == '\0') { - return MA_ERROR; // No index specified in the ID. + return MA_ERROR; /* No index specified in the ID. */ } if (pIndexOut) { @@ -19211,7 +19888,7 @@ ma_format ma_format_from_encoding__audio4(unsigned int encoding, unsigned int pr } } - return ma_format_unknown; // Encoding not supported. + return ma_format_unknown; /* Encoding not supported. */ } void ma_encoding_from_format__audio4(ma_format format, unsigned int* pEncoding, unsigned int* pPrecision) @@ -19270,13 +19947,22 @@ ma_format ma_format_from_swpar__audio4(struct audio_swpar* par) return ma_format_f32; } - // Format not supported. + /* Format not supported. */ return ma_format_unknown; } #endif ma_result ma_context_get_device_info_from_fd__audio4(ma_context* pContext, ma_device_type deviceType, int fd, ma_device_info* pInfoOut) { + audio_device_t fdDevice; +#if !defined(MA_AUDIO4_USE_NEW_API) + int counter = 0; + audio_info_t fdInfo; +#else + struct audio_swpar fdPar; + ma_format format; +#endif + ma_assert(pContext != NULL); ma_assert(fd >= 0); ma_assert(pInfoOut != NULL); @@ -19284,26 +19970,26 @@ ma_result ma_context_get_device_info_from_fd__audio4(ma_context* pContext, ma_de (void)pContext; (void)deviceType; - audio_device_t fdDevice; if (ioctl(fd, AUDIO_GETDEV, &fdDevice) < 0) { - return MA_ERROR; // Failed to retrieve device info. + return MA_ERROR; /* Failed to retrieve device info. */ } - // Name. + /* Name. */ ma_strcpy_s(pInfoOut->name, sizeof(pInfoOut->name), fdDevice.name); #if !defined(MA_AUDIO4_USE_NEW_API) - // Supported formats. We get this by looking at the encodings. - int counter = 0; + /* Supported formats. We get this by looking at the encodings. */ for (;;) { audio_encoding_t encoding; + ma_format format; + ma_zero_object(&encoding); encoding.index = counter; if (ioctl(fd, AUDIO_GETENC, &encoding) < 0) { break; } - ma_format format = ma_format_from_encoding__audio4(encoding.encoding, encoding.precision); + format = ma_format_from_encoding__audio4(encoding.encoding, encoding.precision); if (format != ma_format_unknown) { pInfoOut->formats[pInfoOut->formatCount++] = format; } @@ -19311,7 +19997,6 @@ ma_result ma_context_get_device_info_from_fd__audio4(ma_context* pContext, ma_de counter += 1; } - audio_info_t fdInfo; if (ioctl(fd, AUDIO_GETINFO, &fdInfo) < 0) { return MA_ERROR; } @@ -19328,12 +20013,11 @@ ma_result ma_context_get_device_info_from_fd__audio4(ma_context* pContext, ma_de pInfoOut->maxSampleRate = fdInfo.record.sample_rate; } #else - struct audio_swpar fdPar; if (ioctl(fd, AUDIO_GETPAR, &fdPar) < 0) { return MA_ERROR; } - ma_format format = ma_format_from_swpar__audio4(&fdPar); + format = ma_format_from_swpar__audio4(&fdPar); if (format == ma_format_unknown) { return MA_FORMAT_NOT_SUPPORTED; } @@ -19356,32 +20040,36 @@ ma_result ma_context_get_device_info_from_fd__audio4(ma_context* pContext, ma_de ma_result ma_context_enumerate_devices__audio4(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData) { + const int maxDevices = 64; + char devpath[256]; + int iDevice; + ma_assert(pContext != NULL); ma_assert(callback != NULL); - const int maxDevices = 64; - - // Every device will be named "/dev/audioN", with a "/dev/audioctlN" equivalent. We use the "/dev/audioctlN" - // version here since we can open it even when another process has control of the "/dev/audioN" device. - char devpath[256]; - for (int iDevice = 0; iDevice < maxDevices; ++iDevice) { + /* + Every device will be named "/dev/audioN", with a "/dev/audioctlN" equivalent. We use the "/dev/audioctlN" + version here since we can open it even when another process has control of the "/dev/audioN" device. + */ + for (iDevice = 0; iDevice < maxDevices; ++iDevice) { + struct stat st; + int fd; + ma_bool32 isTerminating = MA_FALSE; + ma_strcpy_s(devpath, sizeof(devpath), "/dev/audioctl"); ma_itoa_s(iDevice, devpath+strlen(devpath), sizeof(devpath)-strlen(devpath), 10); - struct stat st; if (stat(devpath, &st) < 0) { break; } - // The device exists, but we need to check if it's usable as playback and/or capture. - int fd; - ma_bool32 isTerminating = MA_FALSE; + /* The device exists, but we need to check if it's usable as playback and/or capture. */ - // Playback. + /* Playback. */ if (!isTerminating) { fd = open(devpath, O_RDONLY, 0); if (fd >= 0) { - // Supports playback. + /* Supports playback. */ ma_device_info deviceInfo; ma_zero_object(&deviceInfo); ma_construct_device_id__audio4(deviceInfo.id.audio4, sizeof(deviceInfo.id.audio4), "/dev/audio", iDevice); @@ -19393,11 +20081,11 @@ ma_result ma_context_enumerate_devices__audio4(ma_context* pContext, ma_enum_dev } } - // Capture. + /* Capture. */ if (!isTerminating) { fd = open(devpath, O_WRONLY, 0); if (fd >= 0) { - // Supports capture. + /* Supports capture. */ ma_device_info deviceInfo; ma_zero_object(&deviceInfo); ma_construct_device_id__audio4(deviceInfo.id.audio4, sizeof(deviceInfo.id.audio4), "/dev/audio", iDevice); @@ -19419,20 +20107,24 @@ ma_result ma_context_enumerate_devices__audio4(ma_context* pContext, ma_enum_dev ma_result ma_context_get_device_info__audio4(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_share_mode shareMode, ma_device_info* pDeviceInfo) { - ma_assert(pContext != NULL); - (void)shareMode; - - // We need to open the "/dev/audioctlN" device to get the info. To do this we need to extract the number - // from the device ID which will be in "/dev/audioN" format. int fd = -1; int deviceIndex = -1; char ctlid[256]; + ma_result result; + + ma_assert(pContext != NULL); + (void)shareMode; + + /* + We need to open the "/dev/audioctlN" device to get the info. To do this we need to extract the number + from the device ID which will be in "/dev/audioN" format. + */ if (pDeviceID == NULL) { - // Default device. + /* Default device. */ ma_strcpy_s(ctlid, sizeof(ctlid), "/dev/audioctl"); } else { - // Specific device. We need to convert from "/dev/audioN" to "/dev/audioctlN". - ma_result result = ma_extract_device_index_from_id__audio4(pDeviceID->audio4, "/dev/audio", &deviceIndex); + /* Specific device. We need to convert from "/dev/audioN" to "/dev/audioctlN". */ + result = ma_extract_device_index_from_id__audio4(pDeviceID->audio4, "/dev/audio", &deviceIndex); if (result != MA_SUCCESS) { return result; } @@ -19451,7 +20143,7 @@ ma_result ma_context_get_device_info__audio4(ma_context* pContext, ma_device_typ ma_construct_device_id__audio4(pDeviceInfo->id.audio4, sizeof(pDeviceInfo->id.audio4), "/dev/audio", deviceIndex); } - ma_result result = ma_context_get_device_info_from_fd__audio4(pContext, deviceType, fd, pDeviceInfo); + result = ma_context_get_device_info_from_fd__audio4(pContext, deviceType, fd, pDeviceInfo); close(fd); return result; @@ -19506,7 +20198,8 @@ ma_result ma_device_init_fd__audio4(ma_context* pContext, const ma_device_config if ((deviceType == ma_device_type_capture && pConfig->capture.pDeviceID == NULL) || (deviceType == ma_device_type_playback && pConfig->playback.pDeviceID == NULL)) { /* Default device. */ - for (size_t iDevice = 0; iDevice < ma_countof(pDefaultDeviceNames); ++iDevice) { + size_t iDevice; + for (iDevice = 0; iDevice < ma_countof(pDefaultDeviceNames); ++iDevice) { fd = open(pDefaultDeviceNames[iDevice], fdFlags, 0); if (fd != -1) { break; @@ -19681,9 +20374,11 @@ ma_result ma_device_init__audio4(ma_context* pContext, const ma_device_config* p pDevice->audio4.fdCapture = -1; pDevice->audio4.fdPlayback = -1; - // The version of the operating system dictates whether or not the device is exclusive or shared. NetBSD - // introduced in-kernel mixing which means it's shared. All other BSD flavours are exclusive as far as - // I'm aware. + /* + The version of the operating system dictates whether or not the device is exclusive or shared. NetBSD + introduced in-kernel mixing which means it's shared. All other BSD flavours are exclusive as far as + I'm aware. + */ #if defined(__NetBSD_Version__) && __NetBSD_Version__ >= 800000000 /* NetBSD 8.0+ */ if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pConfig->playback.shareMode == ma_share_mode_exclusive) || @@ -19826,11 +20521,11 @@ ma_result ma_context_init__audio4(const ma_context_config* pConfig, ma_context* #endif /* audio4 */ -/////////////////////////////////////////////////////////////////////////////// -// -// OSS Backend -// -/////////////////////////////////////////////////////////////////////////////// +/****************************************************************************** + +OSS Backend + +******************************************************************************/ #ifdef MA_HAS_OSS #include #include @@ -19843,7 +20538,7 @@ ma_result ma_context_init__audio4(const ma_context_config* pConfig, ma_context* int ma_open_temp_device__oss() { - // The OSS sample code uses "/dev/mixer" as the device for getting system properties so I'm going to do the same. + /* The OSS sample code uses "/dev/mixer" as the device for getting system properties so I'm going to do the same. */ int fd = open("/dev/mixer", O_RDONLY, 0); if (fd >= 0) { return fd; @@ -19854,6 +20549,9 @@ int ma_open_temp_device__oss() ma_result ma_context_open_device__oss(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_share_mode shareMode, int* pfd) { + const char* deviceName; + int flags; + ma_assert(pContext != NULL); ma_assert(pfd != NULL); (void)pContext; @@ -19865,12 +20563,12 @@ ma_result ma_context_open_device__oss(ma_context* pContext, ma_device_type devic return MA_INVALID_ARGS; } - const char* deviceName = "/dev/dsp"; + deviceName = "/dev/dsp"; if (pDeviceID != NULL) { deviceName = pDeviceID->oss; } - int flags = (deviceType == ma_device_type_playback) ? O_WRONLY : O_RDONLY; + flags = (deviceType == ma_device_type_playback) ? O_WRONLY : O_RDONLY; if (shareMode == ma_share_mode_exclusive) { flags |= O_EXCL; } @@ -19895,40 +20593,47 @@ ma_bool32 ma_context_is_device_id_equal__oss(ma_context* pContext, const ma_devi ma_result ma_context_enumerate_devices__oss(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData) { + int fd; + oss_sysinfo si; + int result; + ma_assert(pContext != NULL); ma_assert(callback != NULL); - int fd = ma_open_temp_device__oss(); + fd = ma_open_temp_device__oss(); if (fd == -1) { return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[OSS] Failed to open a temporary device for retrieving system information used for device enumeration.", MA_NO_BACKEND); } - oss_sysinfo si; - int result = ioctl(fd, SNDCTL_SYSINFO, &si); + result = ioctl(fd, SNDCTL_SYSINFO, &si); if (result != -1) { - for (int iAudioDevice = 0; iAudioDevice < si.numaudios; ++iAudioDevice) { + int iAudioDevice; + for (iAudioDevice = 0; iAudioDevice < si.numaudios; ++iAudioDevice) { oss_audioinfo ai; ai.dev = iAudioDevice; result = ioctl(fd, SNDCTL_AUDIOINFO, &ai); if (result != -1) { - if (ai.devnode[0] != '\0') { // <-- Can be blank, according to documentation. + if (ai.devnode[0] != '\0') { /* <-- Can be blank, according to documentation. */ ma_device_info deviceInfo; + ma_bool32 isTerminating = MA_FALSE; + ma_zero_object(&deviceInfo); - // ID + /* ID */ ma_strncpy_s(deviceInfo.id.oss, sizeof(deviceInfo.id.oss), ai.devnode, (size_t)-1); - // The human readable device name should be in the "ai.handle" variable, but it can - // sometimes be empty in which case we just fall back to "ai.name" which is less user - // friendly, but usually has a value. + /* + The human readable device name should be in the "ai.handle" variable, but it can + sometimes be empty in which case we just fall back to "ai.name" which is less user + friendly, but usually has a value. + */ if (ai.handle[0] != '\0') { ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), ai.handle, (size_t)-1); } else { ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), ai.name, (size_t)-1); } - // The device can be both playback and capture. - ma_bool32 isTerminating = MA_FALSE; + /* The device can be both playback and capture. */ if (!isTerminating && (ai.caps & PCM_CAP_OUTPUT) != 0) { isTerminating = !callback(pContext, ma_device_type_playback, &deviceInfo, pUserData); } @@ -19953,10 +20658,15 @@ ma_result ma_context_enumerate_devices__oss(ma_context* pContext, ma_enum_device ma_result ma_context_get_device_info__oss(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_share_mode shareMode, ma_device_info* pDeviceInfo) { + ma_bool32 foundDevice; + int fdTemp; + oss_sysinfo si; + int result; + ma_assert(pContext != NULL); (void)shareMode; - // Handle the default device a little differently. + /* Handle the default device a little differently. */ if (pDeviceID == NULL) { if (deviceType == ma_device_type_playback) { ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); @@ -19968,32 +20678,36 @@ ma_result ma_context_get_device_info__oss(ma_context* pContext, ma_device_type d } - // If we get here it means we are _not_ using the default device. - ma_bool32 foundDevice = MA_FALSE; + /* If we get here it means we are _not_ using the default device. */ + foundDevice = MA_FALSE; - int fdTemp = ma_open_temp_device__oss(); + fdTemp = ma_open_temp_device__oss(); if (fdTemp == -1) { return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[OSS] Failed to open a temporary device for retrieving system information used for device enumeration.", MA_NO_BACKEND); } - oss_sysinfo si; - int result = ioctl(fdTemp, SNDCTL_SYSINFO, &si); + result = ioctl(fdTemp, SNDCTL_SYSINFO, &si); if (result != -1) { - for (int iAudioDevice = 0; iAudioDevice < si.numaudios; ++iAudioDevice) { + int iAudioDevice; + for (iAudioDevice = 0; iAudioDevice < si.numaudios; ++iAudioDevice) { oss_audioinfo ai; ai.dev = iAudioDevice; result = ioctl(fdTemp, SNDCTL_AUDIOINFO, &ai); if (result != -1) { if (ma_strcmp(ai.devnode, pDeviceID->oss) == 0) { - // It has the same name, so now just confirm the type. + /* It has the same name, so now just confirm the type. */ if ((deviceType == ma_device_type_playback && ((ai.caps & PCM_CAP_OUTPUT) != 0)) || (deviceType == ma_device_type_capture && ((ai.caps & PCM_CAP_INPUT) != 0))) { - // ID + unsigned int formatMask; + + /* ID */ ma_strncpy_s(pDeviceInfo->id.oss, sizeof(pDeviceInfo->id.oss), ai.devnode, (size_t)-1); - // The human readable device name should be in the "ai.handle" variable, but it can - // sometimes be empty in which case we just fall back to "ai.name" which is less user - // friendly, but usually has a value. + /* + The human readable device name should be in the "ai.handle" variable, but it can + sometimes be empty in which case we just fall back to "ai.name" which is less user + friendly, but usually has a value. + */ if (ai.handle[0] != '\0') { ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), ai.handle, (size_t)-1); } else { @@ -20006,7 +20720,6 @@ ma_result ma_context_get_device_info__oss(ma_context* pContext, ma_device_type d pDeviceInfo->maxSampleRate = ai.max_rate; pDeviceInfo->formatCount = 0; - unsigned int formatMask; if (deviceType == ma_device_type_playback) { formatMask = ai.oformats; } else { @@ -20041,7 +20754,6 @@ ma_result ma_context_get_device_info__oss(ma_context* pContext, ma_device_type d return MA_NO_DEVICE; } - return MA_SUCCESS; } @@ -20320,19 +21032,23 @@ ma_result ma_context_uninit__oss(ma_context* pContext) ma_result ma_context_init__oss(const ma_context_config* pConfig, ma_context* pContext) { + int fd; + int ossVersion; + int result; + ma_assert(pContext != NULL); (void)pConfig; /* Try opening a temporary device first so we can get version information. This is closed at the end. */ - int fd = ma_open_temp_device__oss(); + fd = ma_open_temp_device__oss(); if (fd == -1) { return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[OSS] Failed to open temporary device for retrieving system properties.", MA_NO_BACKEND); /* Looks liks OSS isn't installed, or there are no available devices. */ } /* Grab the OSS version. */ - int ossVersion = 0; - int result = ioctl(fd, OSS_GETVERSION, &ossVersion); + ossVersion = 0; + result = ioctl(fd, OSS_GETVERSION, &ossVersion); if (result == -1) { close(fd); return ma_context_post_error(pContext, NULL, MA_LOG_LEVEL_ERROR, "[OSS] Failed to retrieve OSS version.", MA_NO_BACKEND); @@ -20358,13 +21074,13 @@ ma_result ma_context_init__oss(const ma_context_config* pConfig, ma_context* pCo #endif /* OSS */ -/////////////////////////////////////////////////////////////////////////////// -// -// AAudio Backend -// -/////////////////////////////////////////////////////////////////////////////// +/****************************************************************************** + +AAudio Backend + +******************************************************************************/ #ifdef MA_HAS_AAUDIO -//#include +/*#include */ #define MA_AAUDIO_UNSPECIFIED 0 @@ -20424,26 +21140,26 @@ typedef ma_aaudio_data_callback_result_t (*ma_AAudioStream_dataCallback)(ma_AAud typedef ma_aaudio_result_t (* MA_PFN_AAudio_createStreamBuilder) (ma_AAudioStreamBuilder** ppBuilder); typedef ma_aaudio_result_t (* MA_PFN_AAudioStreamBuilder_delete) (ma_AAudioStreamBuilder* pBuilder); -typedef void (* MA_PFN_AAudioStreamBuilder_setDeviceId) (ma_AAudioStreamBuilder* pBuilder, int32_t deviceId); -typedef void (* MA_PFN_AAudioStreamBuilder_setDirection) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_direction_t direction); -typedef void (* MA_PFN_AAudioStreamBuilder_setSharingMode) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_sharing_mode_t sharingMode); -typedef void (* MA_PFN_AAudioStreamBuilder_setFormat) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_format_t format); -typedef void (* MA_PFN_AAudioStreamBuilder_setChannelCount) (ma_AAudioStreamBuilder* pBuilder, int32_t channelCount); -typedef void (* MA_PFN_AAudioStreamBuilder_setSampleRate) (ma_AAudioStreamBuilder* pBuilder, int32_t sampleRate); -typedef void (* MA_PFN_AAudioStreamBuilder_setBufferCapacityInFrames)(ma_AAudioStreamBuilder* pBuilder, int32_t numFrames); -typedef void (* MA_PFN_AAudioStreamBuilder_setFramesPerDataCallback) (ma_AAudioStreamBuilder* pBuilder, int32_t numFrames); -typedef void (* MA_PFN_AAudioStreamBuilder_setDataCallback) (ma_AAudioStreamBuilder* pBuilder, ma_AAudioStream_dataCallback callback, void* pUserData); -typedef void (* MA_PFN_AAudioStreamBuilder_setPerformanceMode) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_performance_mode_t mode); +typedef void (* MA_PFN_AAudioStreamBuilder_setDeviceId) (ma_AAudioStreamBuilder* pBuilder, int32_t deviceId); +typedef void (* MA_PFN_AAudioStreamBuilder_setDirection) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_direction_t direction); +typedef void (* MA_PFN_AAudioStreamBuilder_setSharingMode) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_sharing_mode_t sharingMode); +typedef void (* MA_PFN_AAudioStreamBuilder_setFormat) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_format_t format); +typedef void (* MA_PFN_AAudioStreamBuilder_setChannelCount) (ma_AAudioStreamBuilder* pBuilder, int32_t channelCount); +typedef void (* MA_PFN_AAudioStreamBuilder_setSampleRate) (ma_AAudioStreamBuilder* pBuilder, int32_t sampleRate); +typedef void (* MA_PFN_AAudioStreamBuilder_setBufferCapacityInFrames)(ma_AAudioStreamBuilder* pBuilder, int32_t numFrames); +typedef void (* MA_PFN_AAudioStreamBuilder_setFramesPerDataCallback) (ma_AAudioStreamBuilder* pBuilder, int32_t numFrames); +typedef void (* MA_PFN_AAudioStreamBuilder_setDataCallback) (ma_AAudioStreamBuilder* pBuilder, ma_AAudioStream_dataCallback callback, void* pUserData); +typedef void (* MA_PFN_AAudioStreamBuilder_setPerformanceMode) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_performance_mode_t mode); typedef ma_aaudio_result_t (* MA_PFN_AAudioStreamBuilder_openStream) (ma_AAudioStreamBuilder* pBuilder, ma_AAudioStream** ppStream); typedef ma_aaudio_result_t (* MA_PFN_AAudioStream_close) (ma_AAudioStream* pStream); typedef ma_aaudio_stream_state_t (* MA_PFN_AAudioStream_getState) (ma_AAudioStream* pStream); typedef ma_aaudio_result_t (* MA_PFN_AAudioStream_waitForStateChange) (ma_AAudioStream* pStream, ma_aaudio_stream_state_t inputState, ma_aaudio_stream_state_t* pNextState, int64_t timeoutInNanoseconds); typedef ma_aaudio_format_t (* MA_PFN_AAudioStream_getFormat) (ma_AAudioStream* pStream); -typedef int32_t (* MA_PFN_AAudioStream_getChannelCount) (ma_AAudioStream* pStream); -typedef int32_t (* MA_PFN_AAudioStream_getSampleRate) (ma_AAudioStream* pStream); -typedef int32_t (* MA_PFN_AAudioStream_getBufferCapacityInFrames) (ma_AAudioStream* pStream); -typedef int32_t (* MA_PFN_AAudioStream_getFramesPerDataCallback) (ma_AAudioStream* pStream); -typedef int32_t (* MA_PFN_AAudioStream_getFramesPerBurst) (ma_AAudioStream* pStream); +typedef int32_t (* MA_PFN_AAudioStream_getChannelCount) (ma_AAudioStream* pStream); +typedef int32_t (* MA_PFN_AAudioStream_getSampleRate) (ma_AAudioStream* pStream); +typedef int32_t (* MA_PFN_AAudioStream_getBufferCapacityInFrames) (ma_AAudioStream* pStream); +typedef int32_t (* MA_PFN_AAudioStream_getFramesPerDataCallback) (ma_AAudioStream* pStream); +typedef int32_t (* MA_PFN_AAudioStream_getFramesPerBurst) (ma_AAudioStream* pStream); typedef ma_aaudio_result_t (* MA_PFN_AAudioStream_requestStart) (ma_AAudioStream* pStream); typedef ma_aaudio_result_t (* MA_PFN_AAudioStream_requestStop) (ma_AAudioStream* pStream); @@ -20510,6 +21226,8 @@ ma_result ma_open_stream__aaudio(ma_context* pContext, ma_device_type deviceType ((MA_PFN_AAudioStreamBuilder_setSharingMode)pContext->aaudio.AAudioStreamBuilder_setSharingMode)(pBuilder, (shareMode == ma_share_mode_shared) ? MA_AAUDIO_SHARING_MODE_SHARED : MA_AAUDIO_SHARING_MODE_EXCLUSIVE); if (pConfig != NULL) { + ma_uint32 bufferCapacityInFrames; + if (pDevice == NULL || !pDevice->usingDefaultSampleRate) { ((MA_PFN_AAudioStreamBuilder_setSampleRate)pContext->aaudio.AAudioStreamBuilder_setSampleRate)(pBuilder, pConfig->sampleRate); } @@ -20530,7 +21248,7 @@ ma_result ma_open_stream__aaudio(ma_context* pContext, ma_device_type deviceType } } - ma_uint32 bufferCapacityInFrames = pConfig->bufferSizeInFrames; + bufferCapacityInFrames = pConfig->bufferSizeInFrames; if (bufferCapacityInFrames == 0) { bufferCapacityInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(pConfig->bufferSizeInMilliseconds, pConfig->sampleRate); } @@ -20723,6 +21441,8 @@ ma_result ma_device_init__aaudio(ma_context* pContext, const ma_device_config* p /* We first need to try opening the stream. */ if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) { + int32_t framesPerPeriod; + result = ma_open_stream__aaudio(pContext, ma_device_type_capture, pConfig->capture.pDeviceID, pConfig->capture.shareMode, pConfig, pDevice, (ma_AAudioStream**)&pDevice->aaudio.pStreamCapture); if (result != MA_SUCCESS) { return result; /* Failed to open the AAudio stream. */ @@ -20734,9 +21454,11 @@ ma_result ma_device_init__aaudio(ma_context* pContext, const ma_device_config* p ma_get_standard_channel_map(ma_standard_channel_map_default, pDevice->capture.internalChannels, pDevice->capture.internalChannelMap); /* <-- Cannot find info on channel order, so assuming a default. */ pDevice->capture.internalBufferSizeInFrames = ((MA_PFN_AAudioStream_getBufferCapacityInFrames)pContext->aaudio.AAudioStream_getBufferCapacityInFrames)((ma_AAudioStream*)pDevice->aaudio.pStreamCapture); - /* TODO: When synchronous reading and writing is supported, use AAudioStream_getFramesPerBurst() instead of AAudioStream_getFramesPerDataCallback(). Keep - * using AAudioStream_getFramesPerDataCallback() for asynchronous mode, though. */ - int32_t framesPerPeriod = ((MA_PFN_AAudioStream_getFramesPerDataCallback)pContext->aaudio.AAudioStream_getFramesPerDataCallback)((ma_AAudioStream*)pDevice->aaudio.pStreamCapture); + /* + TODO: When synchronous reading and writing is supported, use AAudioStream_getFramesPerBurst() instead of AAudioStream_getFramesPerDataCallback(). Keep + using AAudioStream_getFramesPerDataCallback() for asynchronous mode, though. + */ + framesPerPeriod = ((MA_PFN_AAudioStream_getFramesPerDataCallback)pContext->aaudio.AAudioStream_getFramesPerDataCallback)((ma_AAudioStream*)pDevice->aaudio.pStreamCapture); if (framesPerPeriod > 0) { pDevice->capture.internalPeriods = 1; } else { @@ -20745,6 +21467,8 @@ ma_result ma_device_init__aaudio(ma_context* pContext, const ma_device_config* p } if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) { + int32_t framesPerPeriod; + result = ma_open_stream__aaudio(pContext, ma_device_type_playback, pConfig->playback.pDeviceID, pConfig->playback.shareMode, pConfig, pDevice, (ma_AAudioStream**)&pDevice->aaudio.pStreamPlayback); if (result != MA_SUCCESS) { return result; /* Failed to open the AAudio stream. */ @@ -20756,7 +21480,7 @@ ma_result ma_device_init__aaudio(ma_context* pContext, const ma_device_config* p ma_get_standard_channel_map(ma_standard_channel_map_default, pDevice->playback.internalChannels, pDevice->playback.internalChannelMap); /* <-- Cannot find info on channel order, so assuming a default. */ pDevice->playback.internalBufferSizeInFrames = ((MA_PFN_AAudioStream_getBufferCapacityInFrames)pContext->aaudio.AAudioStream_getBufferCapacityInFrames)((ma_AAudioStream*)pDevice->aaudio.pStreamPlayback); - int32_t framesPerPeriod = ((MA_PFN_AAudioStream_getFramesPerDataCallback)pContext->aaudio.AAudioStream_getFramesPerDataCallback)((ma_AAudioStream*)pDevice->aaudio.pStreamPlayback); + framesPerPeriod = ((MA_PFN_AAudioStream_getFramesPerDataCallback)pContext->aaudio.AAudioStream_getFramesPerDataCallback)((ma_AAudioStream*)pDevice->aaudio.pStreamPlayback); if (framesPerPeriod > 0) { pDevice->playback.internalPeriods = 1; } else { @@ -20784,6 +21508,7 @@ ma_result ma_device_init__aaudio(ma_context* pContext, const ma_device_config* p ma_result ma_device_start_stream__aaudio(ma_device* pDevice, ma_AAudioStream* pStream) { ma_aaudio_result_t resultAA; + ma_aaudio_stream_state_t currentState; ma_assert(pDevice != NULL); @@ -20795,7 +21520,7 @@ ma_result ma_device_start_stream__aaudio(ma_device* pDevice, ma_AAudioStream* pS /* Do we actually need to wait for the device to transition into it's started state? */ /* The device should be in either a starting or started state. If it's not set to started we need to wait for it to transition. It should go from starting to started. */ - ma_aaudio_stream_state_t currentState = ((MA_PFN_AAudioStream_getState)pDevice->pContext->aaudio.AAudioStream_getState)(pStream); + currentState = ((MA_PFN_AAudioStream_getState)pDevice->pContext->aaudio.AAudioStream_getState)(pStream); if (currentState != MA_AAUDIO_STREAM_STATE_STARTED) { ma_result result; @@ -20815,6 +21540,7 @@ ma_result ma_device_start_stream__aaudio(ma_device* pDevice, ma_AAudioStream* pS ma_result ma_device_stop_stream__aaudio(ma_device* pDevice, ma_AAudioStream* pStream) { ma_aaudio_result_t resultAA; + ma_aaudio_stream_state_t currentState; ma_assert(pDevice != NULL); @@ -20824,7 +21550,7 @@ ma_result ma_device_stop_stream__aaudio(ma_device* pDevice, ma_AAudioStream* pSt } /* The device should be in either a stopping or stopped state. If it's not set to started we need to wait for it to transition. It should go from stopping to stopped. */ - ma_aaudio_stream_state_t currentState = ((MA_PFN_AAudioStream_getState)pDevice->pContext->aaudio.AAudioStream_getState)(pStream); + currentState = ((MA_PFN_AAudioStream_getState)pDevice->pContext->aaudio.AAudioStream_getState)(pStream); if (currentState != MA_AAUDIO_STREAM_STATE_STOPPED) { ma_result result; @@ -20867,6 +21593,8 @@ ma_result ma_device_start__aaudio(ma_device* pDevice) ma_result ma_device_stop__aaudio(ma_device* pDevice) { + ma_stop_proc onStop; + ma_assert(pDevice != NULL); if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { @@ -20883,7 +21611,7 @@ ma_result ma_device_stop__aaudio(ma_device* pDevice) } } - ma_stop_proc onStop = pDevice->onStop; + onStop = pDevice->onStop; if (onStop) { onStop(pDevice); } @@ -20905,15 +21633,12 @@ ma_result ma_context_uninit__aaudio(ma_context* pContext) ma_result ma_context_init__aaudio(const ma_context_config* pConfig, ma_context* pContext) { - ma_assert(pContext != NULL); - - (void)pConfig; - const char* libNames[] = { "libaaudio.so" }; + size_t i; - for (size_t i = 0; i < ma_countof(libNames); ++i) { + for (i = 0; i < ma_countof(libNames); ++i) { pContext->aaudio.hAAudio = ma_dlopen(libNames[i]); if (pContext->aaudio.hAAudio != NULL) { break; @@ -20960,23 +21685,24 @@ ma_result ma_context_init__aaudio(const ma_context_config* pConfig, ma_context* pContext->onDeviceStart = ma_device_start__aaudio; pContext->onDeviceStop = ma_device_stop__aaudio; + (void)pConfig; return MA_SUCCESS; } -#endif // AAudio +#endif /* AAudio */ + + +/****************************************************************************** +OpenSL|ES Backend -/////////////////////////////////////////////////////////////////////////////// -// -// OpenSL|ES Backend -// -/////////////////////////////////////////////////////////////////////////////// +******************************************************************************/ #ifdef MA_HAS_OPENSL #include #ifdef MA_ANDROID #include #endif -// OpenSL|ES has one-per-application objects :( +/* OpenSL|ES has one-per-application objects :( */ SLObjectItf g_maEngineObjectSL = NULL; SLEngineItf g_maEngineSL = NULL; ma_uint32 g_maOpenSLInitCounter = 0; @@ -20992,7 +21718,7 @@ ma_uint32 g_maOpenSLInitCounter = 0; #define MA_OPENSL_BUFFERQUEUE(p) (*((SLBufferQueueItf)(p))) #endif -// Converts an individual OpenSL-style channel identifier (SL_SPEAKER_FRONT_LEFT, etc.) to miniaudio. +/* Converts an individual OpenSL-style channel identifier (SL_SPEAKER_FRONT_LEFT, etc.) to miniaudio. */ ma_uint8 ma_channel_id_to_ma__opensl(SLuint32 id) { switch (id) @@ -21019,7 +21745,7 @@ ma_uint8 ma_channel_id_to_ma__opensl(SLuint32 id) } } -// Converts an individual miniaudio channel identifier (MA_CHANNEL_FRONT_LEFT, etc.) to OpenSL-style. +/* Converts an individual miniaudio channel identifier (MA_CHANNEL_FRONT_LEFT, etc.) to OpenSL-style. */ SLuint32 ma_channel_id_to_opensl(ma_uint8 id) { switch (id) @@ -21047,18 +21773,19 @@ SLuint32 ma_channel_id_to_opensl(ma_uint8 id) } } -// Converts a channel mapping to an OpenSL-style channel mask. +/* Converts a channel mapping to an OpenSL-style channel mask. */ SLuint32 ma_channel_map_to_channel_mask__opensl(const ma_channel channelMap[MA_MAX_CHANNELS], ma_uint32 channels) { SLuint32 channelMask = 0; - for (ma_uint32 iChannel = 0; iChannel < channels; ++iChannel) { + ma_uint32 iChannel; + for (iChannel = 0; iChannel < channels; ++iChannel) { channelMask |= ma_channel_id_to_opensl(channelMap[iChannel]); } return channelMask; } -// Converts an OpenSL-style channel mask to a miniaudio channel map. +/* Converts an OpenSL-style channel mask to a miniaudio channel map. */ void ma_channel_mask_to_channel_map__opensl(SLuint32 channelMask, ma_uint32 channels, ma_channel channelMap[MA_MAX_CHANNELS]) { if (channels == 1 && channelMask == 0) { @@ -21070,12 +21797,13 @@ void ma_channel_mask_to_channel_map__opensl(SLuint32 channelMask, ma_uint32 chan if (channels == 1 && (channelMask & SL_SPEAKER_FRONT_CENTER) != 0) { channelMap[0] = MA_CHANNEL_MONO; } else { - // Just iterate over each bit. + /* Just iterate over each bit. */ ma_uint32 iChannel = 0; - for (ma_uint32 iBit = 0; iBit < 32; ++iBit) { + ma_uint32 iBit; + for (iBit = 0; iBit < 32; ++iBit) { SLuint32 bitValue = (channelMask & (1UL << iBit)); if (bitValue != 0) { - // The bit is set. + /* The bit is set. */ channelMap[iChannel] = ma_channel_id_to_ma__opensl(bitValue); iChannel += 1; } @@ -21114,7 +21842,7 @@ SLuint32 ma_round_to_standard_sample_rate__opensl(SLuint32 samplesPerSec) return SL_SAMPLINGRATE_48; } - // Android doesn't support more than 48000. + /* Android doesn't support more than 48000. */ #ifndef MA_ANDROID if (samplesPerSec <= SL_SAMPLINGRATE_64) { return SL_SAMPLINGRATE_64; @@ -21146,6 +21874,8 @@ ma_bool32 ma_context_is_device_id_equal__opensl(ma_context* pContext, const ma_d ma_result ma_context_enumerate_devices__opensl(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData) { + ma_bool32 cbResult; + ma_assert(pContext != NULL); ma_assert(callback != NULL); @@ -21154,9 +21884,11 @@ ma_result ma_context_enumerate_devices__opensl(ma_context* pContext, ma_enum_dev return MA_INVALID_OPERATION; } - // TODO: Test Me. - // - // This is currently untested, so for now we are just returning default devices. + /* + TODO: Test Me. + + This is currently untested, so for now we are just returning default devices. + */ #if 0 && !defined(MA_ANDROID) ma_bool32 isTerminated = MA_FALSE; @@ -21166,11 +21898,11 @@ ma_result ma_context_enumerate_devices__opensl(ma_context* pContext, ma_enum_dev SLAudioIODeviceCapabilitiesItf deviceCaps; SLresult resultSL = (*g_maEngineObjectSL)->GetInterface(g_maEngineObjectSL, SL_IID_AUDIOIODEVICECAPABILITIES, &deviceCaps); if (resultSL != SL_RESULT_SUCCESS) { - // The interface may not be supported so just report a default device. + /* The interface may not be supported so just report a default device. */ goto return_default_device; } - // Playback + /* Playback */ if (!isTerminated) { resultSL = (*deviceCaps)->GetAvailableAudioOutputs(deviceCaps, &deviceCount, pDeviceIDs); if (resultSL != SL_RESULT_SUCCESS) { @@ -21196,7 +21928,7 @@ ma_result ma_context_enumerate_devices__opensl(ma_context* pContext, ma_enum_dev } } - // Capture + /* Capture */ if (!isTerminated) { resultSL = (*deviceCaps)->GetAvailableAudioInputs(deviceCaps, &deviceCount, pDeviceIDs); if (resultSL != SL_RESULT_SUCCESS) { @@ -21228,9 +21960,9 @@ ma_result ma_context_enumerate_devices__opensl(ma_context* pContext, ma_enum_dev #endif return_default_device:; - ma_bool32 cbResult = MA_TRUE; + cbResult = MA_TRUE; - // Playback. + /* Playback. */ if (cbResult) { ma_device_info deviceInfo; ma_zero_object(&deviceInfo); @@ -21238,7 +21970,7 @@ return_default_device:; cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData); } - // Capture. + /* Capture. */ if (cbResult) { ma_device_info deviceInfo; ma_zero_object(&deviceInfo); @@ -21263,14 +21995,16 @@ ma_result ma_context_get_device_info__opensl(ma_context* pContext, ma_device_typ return MA_SHARE_MODE_NOT_SUPPORTED; } - // TODO: Test Me. - // - // This is currently untested, so for now we are just returning default devices. + /* + TODO: Test Me. + + This is currently untested, so for now we are just returning default devices. + */ #if 0 && !defined(MA_ANDROID) SLAudioIODeviceCapabilitiesItf deviceCaps; SLresult resultSL = (*g_maEngineObjectSL)->GetInterface(g_maEngineObjectSL, SL_IID_AUDIOIODEVICECAPABILITIES, &deviceCaps); if (resultSL != SL_RESULT_SUCCESS) { - // The interface may not be supported so just report a default device. + /* The interface may not be supported so just report a default device. */ goto return_default_device; } @@ -21301,11 +22035,11 @@ return_default_device: if (pDeviceID != NULL) { if ((deviceType == ma_device_type_playback && pDeviceID->opensl != SL_DEFAULTDEVICEID_AUDIOOUTPUT) || (deviceType == ma_device_type_capture && pDeviceID->opensl != SL_DEFAULTDEVICEID_AUDIOINPUT)) { - return MA_NO_DEVICE; // Don't know the device. + return MA_NO_DEVICE; /* Don't know the device. */ } } - // Name / Description + /* Name / Description */ if (deviceType == ma_device_type_playback) { ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); } else { @@ -21317,9 +22051,11 @@ return_default_device: return_detailed_info: - // For now we're just outputting a set of values that are supported by the API but not necessarily supported - // by the device natively. Later on we should work on this so that it more closely reflects the device's - // actual native format. + /* + For now we're just outputting a set of values that are supported by the API but not necessarily supported + by the device natively. Later on we should work on this so that it more closely reflects the device's + actual native format. + */ pDeviceInfo->minChannels = 1; pDeviceInfo->maxChannels = 2; pDeviceInfo->minSampleRate = 8000; @@ -21337,25 +22073,31 @@ return_detailed_info: #ifdef MA_ANDROID -//void ma_buffer_queue_callback_capture__opensl_android(SLAndroidSimpleBufferQueueItf pBufferQueue, SLuint32 eventFlags, const void* pBuffer, SLuint32 bufferSize, SLuint32 dataUsed, void* pContext) +/*void ma_buffer_queue_callback_capture__opensl_android(SLAndroidSimpleBufferQueueItf pBufferQueue, SLuint32 eventFlags, const void* pBuffer, SLuint32 bufferSize, SLuint32 dataUsed, void* pContext)*/ void ma_buffer_queue_callback_capture__opensl_android(SLAndroidSimpleBufferQueueItf pBufferQueue, void* pUserData) { ma_device* pDevice = (ma_device*)pUserData; + size_t periodSizeInBytes; + ma_uint8* pBuffer; + SLresult resultSL; + ma_assert(pDevice != NULL); (void)pBufferQueue; - // For now, don't do anything unless the buffer was fully processed. From what I can tell, it looks like - // OpenSL|ES 1.1 improves on buffer queues to the point that we could much more intelligently handle this, - // but unfortunately it looks like Android is only supporting OpenSL|ES 1.0.1 for now :( + /* + For now, don't do anything unless the buffer was fully processed. From what I can tell, it looks like + OpenSL|ES 1.1 improves on buffer queues to the point that we could much more intelligently handle this, + but unfortunately it looks like Android is only supporting OpenSL|ES 1.0.1 for now :( + */ /* Don't do anything if the device is not started. */ if (pDevice->state != MA_STATE_STARTED) { return; } - size_t periodSizeInBytes = (pDevice->capture.internalBufferSizeInFrames / pDevice->capture.internalPeriods) * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels); - ma_uint8* pBuffer = pDevice->opensl.pBufferCapture + (pDevice->opensl.currentBufferIndexCapture * periodSizeInBytes); + periodSizeInBytes = (pDevice->capture.internalBufferSizeInFrames / pDevice->capture.internalPeriods) * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels); + pBuffer = pDevice->opensl.pBufferCapture + (pDevice->opensl.currentBufferIndexCapture * periodSizeInBytes); if (pDevice->type == ma_device_type_duplex) { ma_device__handle_duplex_callback_capture(pDevice, (pDevice->capture.internalBufferSizeInFrames / pDevice->capture.internalPeriods), pBuffer, &pDevice->opensl.duplexRB); @@ -21363,7 +22105,7 @@ void ma_buffer_queue_callback_capture__opensl_android(SLAndroidSimpleBufferQueue ma_device__send_frames_to_client(pDevice, (pDevice->capture.internalBufferSizeInFrames / pDevice->capture.internalPeriods), pBuffer); } - SLresult resultSL = MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueueCapture)->Enqueue((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueueCapture, pBuffer, periodSizeInBytes); + resultSL = MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueueCapture)->Enqueue((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueueCapture, pBuffer, periodSizeInBytes); if (resultSL != SL_RESULT_SUCCESS) { return; } @@ -21374,6 +22116,10 @@ void ma_buffer_queue_callback_capture__opensl_android(SLAndroidSimpleBufferQueue void ma_buffer_queue_callback_playback__opensl_android(SLAndroidSimpleBufferQueueItf pBufferQueue, void* pUserData) { ma_device* pDevice = (ma_device*)pUserData; + size_t periodSizeInBytes; + ma_uint8* pBuffer; + SLresult resultSL; + ma_assert(pDevice != NULL); (void)pBufferQueue; @@ -21383,8 +22129,8 @@ void ma_buffer_queue_callback_playback__opensl_android(SLAndroidSimpleBufferQueu return; } - size_t periodSizeInBytes = (pDevice->playback.internalBufferSizeInFrames / pDevice->playback.internalPeriods) * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels); - ma_uint8* pBuffer = pDevice->opensl.pBufferPlayback + (pDevice->opensl.currentBufferIndexPlayback * periodSizeInBytes); + periodSizeInBytes = (pDevice->playback.internalBufferSizeInFrames / pDevice->playback.internalPeriods) * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels); + pBuffer = pDevice->opensl.pBufferPlayback + (pDevice->opensl.currentBufferIndexPlayback * periodSizeInBytes); if (pDevice->type == ma_device_type_duplex) { ma_device__handle_duplex_callback_playback(pDevice, (pDevice->playback.internalBufferSizeInFrames / pDevice->playback.internalPeriods), pBuffer, &pDevice->opensl.duplexRB); @@ -21392,7 +22138,7 @@ void ma_buffer_queue_callback_playback__opensl_android(SLAndroidSimpleBufferQueu ma_device__read_frames_from_client(pDevice, (pDevice->playback.internalBufferSizeInFrames / pDevice->playback.internalPeriods), pBuffer); } - SLresult resultSL = MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueuePlayback)->Enqueue((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueuePlayback, pBuffer, periodSizeInBytes); + resultSL = MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueuePlayback)->Enqueue((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueuePlayback, pBuffer, periodSizeInBytes); if (resultSL != SL_RESULT_SUCCESS) { return; } @@ -21530,6 +22276,15 @@ ma_result ma_deconstruct_SLDataFormat_PCM__opensl(ma_SLDataFormat_PCM* pDataForm ma_result ma_device_init__opensl(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice) { +#ifdef MA_ANDROID + SLDataLocator_AndroidSimpleBufferQueue queue; + SLresult resultSL; + ma_uint32 bufferSizeInFrames; + size_t bufferSizeInBytes; + const SLInterfaceID itfIDs1[] = {SL_IID_ANDROIDSIMPLEBUFFERQUEUE}; + const SLboolean itfIDsRequired1[] = {SL_BOOLEAN_TRUE}; +#endif + (void)pContext; ma_assert(g_maOpenSLInitCounter > 0); /* <-- If you trigger this it means you've either not initialized the context, or you've uninitialized it and then attempted to initialize a new device. */ @@ -21542,10 +22297,7 @@ ma_result ma_device_init__opensl(ma_context* pContext, const ma_device_config* p been able to test with and I currently depend on Android-specific extensions (simple buffer queues). */ -#ifndef MA_ANDROID - return MA_NO_BACKEND; -#endif - +#ifdef MA_ANDROID /* No exclusive mode with OpenSL|ES. */ if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pConfig->playback.shareMode == ma_share_mode_exclusive) || ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pConfig->capture.shareMode == ma_share_mode_exclusive)) { @@ -21556,32 +22308,30 @@ ma_result ma_device_init__opensl(ma_context* pContext, const ma_device_config* p ma_assert(pDevice != NULL); ma_zero_object(&pDevice->opensl); - SLDataLocator_AndroidSimpleBufferQueue queue; queue.locatorType = SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE; queue.numBuffers = pConfig->periods; if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) { ma_SLDataFormat_PCM pcm; + SLDataLocator_IODevice locatorDevice; + SLDataSource source; + SLDataSink sink; + ma_SLDataFormat_PCM_init__opensl(pConfig->capture.format, pConfig->capture.channels, pConfig->sampleRate, pConfig->capture.channelMap, &pcm); - SLDataLocator_IODevice locatorDevice; locatorDevice.locatorType = SL_DATALOCATOR_IODEVICE; locatorDevice.deviceType = SL_IODEVICE_AUDIOINPUT; locatorDevice.deviceID = (pConfig->capture.pDeviceID == NULL) ? SL_DEFAULTDEVICEID_AUDIOINPUT : pConfig->capture.pDeviceID->opensl; locatorDevice.device = NULL; - SLDataSource source; source.pLocator = &locatorDevice; source.pFormat = NULL; - SLDataSink sink; sink.pLocator = &queue; sink.pFormat = (SLDataFormat_PCM*)&pcm; - const SLInterfaceID itfIDs1[] = {SL_IID_ANDROIDSIMPLEBUFFERQUEUE}; - const SLboolean itfIDsRequired1[] = {SL_BOOLEAN_TRUE}; - SLresult resultSL = (*g_maEngineSL)->CreateAudioRecorder(g_maEngineSL, (SLObjectItf*)&pDevice->opensl.pAudioRecorderObj, &source, &sink, 1, itfIDs1, itfIDsRequired1); + resultSL = (*g_maEngineSL)->CreateAudioRecorder(g_maEngineSL, (SLObjectItf*)&pDevice->opensl.pAudioRecorderObj, &source, &sink, 1, itfIDs1, itfIDsRequired1); if (resultSL == SL_RESULT_CONTENT_UNSUPPORTED) { /* Unsupported format. Fall back to something safer and try again. If this fails, just abort. */ pcm.formatType = SL_DATAFORMAT_PCM; @@ -21622,7 +22372,7 @@ ma_result ma_device_init__opensl(ma_context* pContext, const ma_device_config* p ma_deconstruct_SLDataFormat_PCM__opensl(&pcm, &pDevice->capture.internalFormat, &pDevice->capture.internalChannels, &pDevice->capture.internalSampleRate, pDevice->capture.internalChannelMap); /* Buffer. */ - ma_uint32 bufferSizeInFrames = pConfig->bufferSizeInFrames; + bufferSizeInFrames = pConfig->bufferSizeInFrames; if (bufferSizeInFrames == 0) { bufferSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(pConfig->bufferSizeInMilliseconds, pDevice->capture.internalSampleRate); } @@ -21630,7 +22380,7 @@ ma_result ma_device_init__opensl(ma_context* pContext, const ma_device_config* p pDevice->capture.internalBufferSizeInFrames = (bufferSizeInFrames / pDevice->capture.internalPeriods) * pDevice->capture.internalPeriods; pDevice->opensl.currentBufferIndexCapture = 0; - size_t bufferSizeInBytes = pDevice->capture.internalBufferSizeInFrames * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels); + bufferSizeInBytes = pDevice->capture.internalBufferSizeInFrames * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels); pDevice->opensl.pBufferCapture = (ma_uint8*)ma_malloc(bufferSizeInBytes); if (pDevice->opensl.pBufferCapture == NULL) { ma_device_uninit__opensl(pDevice); @@ -21641,9 +22391,13 @@ ma_result ma_device_init__opensl(ma_context* pContext, const ma_device_config* p if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) { ma_SLDataFormat_PCM pcm; + SLDataSource source; + SLDataLocator_OutputMix outmixLocator; + SLDataSink sink; + ma_SLDataFormat_PCM_init__opensl(pConfig->playback.format, pConfig->playback.channels, pConfig->sampleRate, pConfig->playback.channelMap, &pcm); - SLresult resultSL = (*g_maEngineSL)->CreateOutputMix(g_maEngineSL, (SLObjectItf*)&pDevice->opensl.pOutputMixObj, 0, NULL, NULL); + resultSL = (*g_maEngineSL)->CreateOutputMix(g_maEngineSL, (SLObjectItf*)&pDevice->opensl.pOutputMixObj, 0, NULL, NULL); if (resultSL != SL_RESULT_SUCCESS) { ma_device_uninit__opensl(pDevice); return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to create output mix.", MA_FAILED_TO_OPEN_BACKEND_DEVICE); @@ -21664,21 +22418,16 @@ ma_result ma_device_init__opensl(ma_context* pContext, const ma_device_config* p SLuint32 deviceID_OpenSL = pConfig->playback.pDeviceID->opensl; MA_OPENSL_OUTPUTMIX(pDevice->opensl.pOutputMix)->ReRoute((SLOutputMixItf)pDevice->opensl.pOutputMix, 1, &deviceID_OpenSL); } - - SLDataSource source; + source.pLocator = &queue; source.pFormat = (SLDataFormat_PCM*)&pcm; - SLDataLocator_OutputMix outmixLocator; outmixLocator.locatorType = SL_DATALOCATOR_OUTPUTMIX; outmixLocator.outputMix = (SLObjectItf)pDevice->opensl.pOutputMixObj; - SLDataSink sink; sink.pLocator = &outmixLocator; sink.pFormat = NULL; - const SLInterfaceID itfIDs1[] = {SL_IID_ANDROIDSIMPLEBUFFERQUEUE}; - const SLboolean itfIDsRequired1[] = {SL_BOOLEAN_TRUE}; resultSL = (*g_maEngineSL)->CreateAudioPlayer(g_maEngineSL, (SLObjectItf*)&pDevice->opensl.pAudioPlayerObj, &source, &sink, 1, itfIDs1, itfIDsRequired1); if (resultSL == SL_RESULT_CONTENT_UNSUPPORTED) { /* Unsupported format. Fall back to something safer and try again. If this fails, just abort. */ @@ -21720,7 +22469,7 @@ ma_result ma_device_init__opensl(ma_context* pContext, const ma_device_config* p ma_deconstruct_SLDataFormat_PCM__opensl(&pcm, &pDevice->playback.internalFormat, &pDevice->playback.internalChannels, &pDevice->playback.internalSampleRate, pDevice->playback.internalChannelMap); /* Buffer. */ - ma_uint32 bufferSizeInFrames = pConfig->bufferSizeInFrames; + bufferSizeInFrames = pConfig->bufferSizeInFrames; if (bufferSizeInFrames == 0) { bufferSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(pConfig->bufferSizeInMilliseconds, pDevice->playback.internalSampleRate); } @@ -21728,7 +22477,7 @@ ma_result ma_device_init__opensl(ma_context* pContext, const ma_device_config* p pDevice->playback.internalBufferSizeInFrames = (bufferSizeInFrames / pDevice->playback.internalPeriods) * pDevice->playback.internalPeriods; pDevice->opensl.currentBufferIndexPlayback = 0; - size_t bufferSizeInBytes = pDevice->playback.internalBufferSizeInFrames * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels); + bufferSizeInBytes = pDevice->playback.internalBufferSizeInFrames * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels); pDevice->opensl.pBufferPlayback = (ma_uint8*)ma_malloc(bufferSizeInBytes); if (pDevice->opensl.pBufferPlayback == NULL) { ma_device_uninit__opensl(pDevice); @@ -21747,10 +22496,17 @@ ma_result ma_device_init__opensl(ma_context* pContext, const ma_device_config* p } return MA_SUCCESS; +#else + return MA_NO_BACKEND; /* Non-Android implementations are not supported. */ +#endif } ma_result ma_device_start__opensl(ma_device* pDevice) { + SLresult resultSL; + size_t periodSizeInBytes; + ma_uint32 iPeriod; + ma_assert(pDevice != NULL); ma_assert(g_maOpenSLInitCounter > 0); /* <-- If you trigger this it means you've either not initialized the context, or you've uninitialized it and then attempted to start the device. */ @@ -21759,13 +22515,13 @@ ma_result ma_device_start__opensl(ma_device* pDevice) } if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { - SLresult resultSL = MA_OPENSL_RECORD(pDevice->opensl.pAudioRecorder)->SetRecordState((SLRecordItf)pDevice->opensl.pAudioRecorder, SL_RECORDSTATE_RECORDING); + resultSL = MA_OPENSL_RECORD(pDevice->opensl.pAudioRecorder)->SetRecordState((SLRecordItf)pDevice->opensl.pAudioRecorder, SL_RECORDSTATE_RECORDING); if (resultSL != SL_RESULT_SUCCESS) { return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to start internal capture device.", MA_FAILED_TO_START_BACKEND_DEVICE); } - size_t periodSizeInBytes = (pDevice->capture.internalBufferSizeInFrames / pDevice->capture.internalPeriods) * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels); - for (ma_uint32 iPeriod = 0; iPeriod < pDevice->capture.internalPeriods; ++iPeriod) { + periodSizeInBytes = (pDevice->capture.internalBufferSizeInFrames / pDevice->capture.internalPeriods) * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels); + for (iPeriod = 0; iPeriod < pDevice->capture.internalPeriods; ++iPeriod) { resultSL = MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueuePlayback)->Enqueue((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueueCapture, pDevice->opensl.pBufferCapture + (periodSizeInBytes * iPeriod), periodSizeInBytes); if (resultSL != SL_RESULT_SUCCESS) { MA_OPENSL_RECORD(pDevice->opensl.pAudioRecorder)->SetRecordState((SLRecordItf)pDevice->opensl.pAudioRecorder, SL_RECORDSTATE_STOPPED); @@ -21775,7 +22531,7 @@ ma_result ma_device_start__opensl(ma_device* pDevice) } if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { - SLresult resultSL = MA_OPENSL_PLAY(pDevice->opensl.pAudioPlayer)->SetPlayState((SLPlayItf)pDevice->opensl.pAudioPlayer, SL_PLAYSTATE_PLAYING); + resultSL = MA_OPENSL_PLAY(pDevice->opensl.pAudioPlayer)->SetPlayState((SLPlayItf)pDevice->opensl.pAudioPlayer, SL_PLAYSTATE_PLAYING); if (resultSL != SL_RESULT_SUCCESS) { return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to start internal playback device.", MA_FAILED_TO_START_BACKEND_DEVICE); } @@ -21787,8 +22543,8 @@ ma_result ma_device_start__opensl(ma_device* pDevice) ma_device__read_frames_from_client(pDevice, pDevice->playback.internalBufferSizeInFrames, pDevice->opensl.pBufferPlayback); } - size_t periodSizeInBytes = (pDevice->playback.internalBufferSizeInFrames / pDevice->playback.internalPeriods) * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels); - for (ma_uint32 iPeriod = 0; iPeriod < pDevice->playback.internalPeriods; ++iPeriod) { + periodSizeInBytes = (pDevice->playback.internalBufferSizeInFrames / pDevice->playback.internalPeriods) * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels); + for (iPeriod = 0; iPeriod < pDevice->playback.internalPeriods; ++iPeriod) { resultSL = MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueuePlayback)->Enqueue((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueuePlayback, pDevice->opensl.pBufferPlayback + (periodSizeInBytes * iPeriod), periodSizeInBytes); if (resultSL != SL_RESULT_SUCCESS) { MA_OPENSL_PLAY(pDevice->opensl.pAudioPlayer)->SetPlayState((SLPlayItf)pDevice->opensl.pAudioPlayer, SL_PLAYSTATE_STOPPED); @@ -21802,6 +22558,9 @@ ma_result ma_device_start__opensl(ma_device* pDevice) ma_result ma_device_stop__opensl(ma_device* pDevice) { + SLresult resultSL; + ma_stop_proc onStop; + ma_assert(pDevice != NULL); ma_assert(g_maOpenSLInitCounter > 0); /* <-- If you trigger this it means you've either not initialized the context, or you've uninitialized it before stopping/uninitializing the device. */ @@ -21812,7 +22571,7 @@ ma_result ma_device_stop__opensl(ma_device* pDevice) /* TODO: Wait until all buffers have been processed. Hint: Maybe SLAndroidSimpleBufferQueue::GetState() could be used in a loop? */ if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { - SLresult resultSL = MA_OPENSL_RECORD(pDevice->opensl.pAudioRecorder)->SetRecordState((SLRecordItf)pDevice->opensl.pAudioRecorder, SL_RECORDSTATE_STOPPED); + resultSL = MA_OPENSL_RECORD(pDevice->opensl.pAudioRecorder)->SetRecordState((SLRecordItf)pDevice->opensl.pAudioRecorder, SL_RECORDSTATE_STOPPED); if (resultSL != SL_RESULT_SUCCESS) { return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to stop internal capture device.", MA_FAILED_TO_STOP_BACKEND_DEVICE); } @@ -21821,7 +22580,7 @@ ma_result ma_device_stop__opensl(ma_device* pDevice) } if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) { - SLresult resultSL = MA_OPENSL_PLAY(pDevice->opensl.pAudioPlayer)->SetPlayState((SLPlayItf)pDevice->opensl.pAudioPlayer, SL_PLAYSTATE_STOPPED); + resultSL = MA_OPENSL_PLAY(pDevice->opensl.pAudioPlayer)->SetPlayState((SLPlayItf)pDevice->opensl.pAudioPlayer, SL_PLAYSTATE_STOPPED); if (resultSL != SL_RESULT_SUCCESS) { return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to stop internal playback device.", MA_FAILED_TO_STOP_BACKEND_DEVICE); } @@ -21830,7 +22589,7 @@ ma_result ma_device_stop__opensl(ma_device* pDevice) } /* Make sure the client is aware that the device has stopped. There may be an OpenSL|ES callback for this, but I haven't found it. */ - ma_stop_proc onStop = pDevice->onStop; + onStop = pDevice->onStop; if (onStop) { onStop(pDevice); } @@ -21895,11 +22654,11 @@ ma_result ma_context_init__opensl(const ma_context_config* pConfig, ma_context* #endif /* OpenSL|ES */ -/////////////////////////////////////////////////////////////////////////////// -// -// Web Audio Backend -// -/////////////////////////////////////////////////////////////////////////////// +/****************************************************************************** + +Web Audio Backend + +******************************************************************************/ #ifdef MA_HAS_WEBAUDIO #include @@ -21946,13 +22705,14 @@ ma_bool32 ma_context_is_device_id_equal__webaudio(ma_context* pContext, const ma ma_result ma_context_enumerate_devices__webaudio(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData) { + ma_bool32 cbResult = MA_TRUE; + ma_assert(pContext != NULL); ma_assert(callback != NULL); - // Only supporting default devices for now. - ma_bool32 cbResult = MA_TRUE; + /* Only supporting default devices for now. */ - // Playback. + /* Playback. */ if (cbResult) { ma_device_info deviceInfo; ma_zero_object(&deviceInfo); @@ -21960,7 +22720,7 @@ ma_result ma_context_enumerate_devices__webaudio(ma_context* pContext, ma_enum_d cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData); } - // Capture. + /* Capture. */ if (cbResult) { if (ma_is_capture_supported__webaudio()) { ma_device_info deviceInfo; @@ -22395,12 +23155,12 @@ ma_result ma_context_uninit__webaudio(ma_context* pContext) ma_result ma_context_init__webaudio(const ma_context_config* pConfig, ma_context* pContext) { + int resultFromJS; + ma_assert(pContext != NULL); - - (void)pConfig; /* Here is where our global JavaScript object is initialized. */ - int resultFromJS = EM_ASM_INT({ + resultFromJS = EM_ASM_INT({ if ((window.AudioContext || window.webkitAudioContext) === undefined) { return 0; /* Web Audio not supported. */ } @@ -22469,23 +23229,27 @@ ma_result ma_context_init__webaudio(const ma_context_config* pConfig, ma_context pContext->onDeviceStart = ma_device_start__webaudio; pContext->onDeviceStop = ma_device_stop__webaudio; + (void)pConfig; /* Unused. */ return MA_SUCCESS; } -#endif // Web Audio +#endif /* Web Audio */ ma_bool32 ma__is_channel_map_valid(const ma_channel* channelMap, ma_uint32 channels) { - // A blank channel map should be allowed, in which case it should use an appropriate default which will depend on context. + /* A blank channel map should be allowed, in which case it should use an appropriate default which will depend on context. */ if (channelMap[0] != MA_CHANNEL_NONE) { + ma_uint32 iChannel; + if (channels == 0) { - return MA_FALSE; // No channels. + return MA_FALSE; /* No channels. */ } - // A channel cannot be present in the channel map more than once. - for (ma_uint32 iChannel = 0; iChannel < channels; ++iChannel) { - for (ma_uint32 jChannel = iChannel + 1; jChannel < channels; ++jChannel) { + /* A channel cannot be present in the channel map more than once. */ + for (iChannel = 0; iChannel < channels; ++iChannel) { + ma_uint32 jChannel; + for (jChannel = iChannel + 1; jChannel < channels; ++jChannel) { if (channelMap[iChannel] == channelMap[jChannel]) { return MA_FALSE; } @@ -22595,28 +23359,34 @@ ma_thread_result MA_THREADCALL ma_worker_thread(void* pData) ma_CoInitializeEx(pDevice->pContext, NULL, MA_COINIT_VALUE); #endif - // When the device is being initialized it's initial state is set to MA_STATE_UNINITIALIZED. Before returning from - // ma_device_init(), the state needs to be set to something valid. In miniaudio the device's default state immediately - // after initialization is stopped, so therefore we need to mark the device as such. miniaudio will wait on the worker - // thread to signal an event to know when the worker thread is ready for action. + /* + When the device is being initialized it's initial state is set to MA_STATE_UNINITIALIZED. Before returning from + ma_device_init(), the state needs to be set to something valid. In miniaudio the device's default state immediately + after initialization is stopped, so therefore we need to mark the device as such. miniaudio will wait on the worker + thread to signal an event to know when the worker thread is ready for action. + */ ma_device__set_state(pDevice, MA_STATE_STOPPED); ma_event_signal(&pDevice->stopEvent); for (;;) { /* <-- This loop just keeps the thread alive. The main audio loop is inside. */ - // We wait on an event to know when something has requested that the device be started and the main loop entered. + ma_stop_proc onStop; + + /* We wait on an event to know when something has requested that the device be started and the main loop entered. */ ma_event_wait(&pDevice->wakeupEvent); - // Default result code. + /* Default result code. */ pDevice->workResult = MA_SUCCESS; - // If the reason for the wake up is that we are terminating, just break from the loop. + /* If the reason for the wake up is that we are terminating, just break from the loop. */ if (ma_device__get_state(pDevice) == MA_STATE_UNINITIALIZED) { break; } - // Getting to this point means the device is wanting to get started. The function that has requested that the device - // be started will be waiting on an event (pDevice->startEvent) which means we need to make sure we signal the event - // in both the success and error case. It's important that the state of the device is set _before_ signaling the event. + /* + Getting to this point means the device is wanting to get started. The function that has requested that the device + be started will be waiting on an event (pDevice->startEvent) which means we need to make sure we signal the event + in both the success and error case. It's important that the state of the device is set _before_ signaling the event. + */ ma_assert(ma_device__get_state(pDevice) == MA_STATE_STARTING); /* Make sure the state is set appropriately. */ @@ -22626,6 +23396,8 @@ ma_thread_result MA_THREADCALL ma_worker_thread(void* pData) if (pDevice->pContext->onDeviceMainLoop != NULL) { pDevice->pContext->onDeviceMainLoop(pDevice); } else { + ma_uint32 periodSizeInFrames; + /* When a device is using miniaudio's generic worker thread they must implement onDeviceRead or onDeviceWrite, depending on the device type. */ ma_assert( (pDevice->type == ma_device_type_playback && pDevice->pContext->onDeviceWrite != NULL) || @@ -22633,7 +23405,6 @@ ma_thread_result MA_THREADCALL ma_worker_thread(void* pData) (pDevice->type == ma_device_type_duplex && pDevice->pContext->onDeviceWrite != NULL && pDevice->pContext->onDeviceRead != NULL) ); - ma_uint32 periodSizeInFrames; if (pDevice->type == ma_device_type_capture) { ma_assert(pDevice->capture.internalBufferSizeInFrames >= pDevice->capture.internalPeriods); periodSizeInFrames = pDevice->capture.internalBufferSizeInFrames / pDevice->capture.internalPeriods; @@ -22666,6 +23437,7 @@ ma_thread_result MA_THREADCALL ma_worker_thread(void* pData) ma_uint32 captureDeviceDataCapInFrames = sizeof(captureDeviceData) / ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels); while (totalFramesProcessed < periodSizeInFrames) { + ma_device_callback_proc onData; ma_uint32 framesRemaining = periodSizeInFrames - totalFramesProcessed; ma_uint32 framesToProcess = framesRemaining; if (framesToProcess > captureDeviceDataCapInFrames) { @@ -22677,15 +23449,15 @@ ma_thread_result MA_THREADCALL ma_worker_thread(void* pData) break; } - ma_device_callback_proc onData = pDevice->onData; + onData = pDevice->onData; if (onData != NULL) { pDevice->capture._dspFrameCount = framesToProcess; pDevice->capture._dspFrames = captureDeviceData; /* We need to process every input frame. */ for (;;) { - ma_uint8 capturedData[4096]; // In capture.format/channels format - ma_uint8 playbackData[4096]; // In playback.format/channels format + ma_uint8 capturedData[4096]; /* In capture.format/channels format */ + ma_uint8 playbackData[4096]; /* In playback.format/channels format */ ma_uint32 capturedDataCapInFrames = sizeof(capturedData) / ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels); ma_uint32 playbackDataCapInFrames = sizeof(playbackData) / ma_get_bytes_per_frame(pDevice->playback.format, pDevice->playback.channels); @@ -22768,33 +23540,36 @@ ma_thread_result MA_THREADCALL ma_worker_thread(void* pData) } } - - // Getting here means we have broken from the main loop which happens the application has requested that device be stopped. Note that this - // may have actually already happened above if the device was lost and miniaudio has attempted to re-initialize the device. In this case we - // don't want to be doing this a second time. + /* + Getting here means we have broken from the main loop which happens the application has requested that device be stopped. Note that this + may have actually already happened above if the device was lost and miniaudio has attempted to re-initialize the device. In this case we + don't want to be doing this a second time. + */ if (ma_device__get_state(pDevice) != MA_STATE_UNINITIALIZED) { if (pDevice->pContext->onDeviceStop) { pDevice->pContext->onDeviceStop(pDevice); } } - // After the device has stopped, make sure an event is posted. - ma_stop_proc onStop = pDevice->onStop; + /* After the device has stopped, make sure an event is posted. */ + onStop = pDevice->onStop; if (onStop) { onStop(pDevice); } - // A function somewhere is waiting for the device to have stopped for real so we need to signal an event to allow it to continue. Note that - // it's possible that the device has been uninitialized which means we need to _not_ change the status to stopped. We cannot go from an - // uninitialized state to stopped state. + /* + A function somewhere is waiting for the device to have stopped for real so we need to signal an event to allow it to continue. Note that + it's possible that the device has been uninitialized which means we need to _not_ change the status to stopped. We cannot go from an + uninitialized state to stopped state. + */ if (ma_device__get_state(pDevice) != MA_STATE_UNINITIALIZED) { ma_device__set_state(pDevice, MA_STATE_STOPPED); ma_event_signal(&pDevice->stopEvent); } } - // Make sure we aren't continuously waiting on a stop event. - ma_event_signal(&pDevice->stopEvent); // <-- Is this still needed? + /* Make sure we aren't continuously waiting on a stop event. */ + ma_event_signal(&pDevice->stopEvent); /* <-- Is this still needed? */ #ifdef MA_WIN32 ma_CoUninitialize(pDevice->pContext); @@ -22804,10 +23579,13 @@ ma_thread_result MA_THREADCALL ma_worker_thread(void* pData) } -// Helper for determining whether or not the given device is initialized. +/* Helper for determining whether or not the given device is initialized. */ ma_bool32 ma_device__is_initialized(ma_device* pDevice) { - if (pDevice == NULL) return MA_FALSE; + if (pDevice == NULL) { + return MA_FALSE; + } + return ma_device__get_state(pDevice) != MA_STATE_UNINITIALIZED; } @@ -22826,7 +23604,7 @@ ma_result ma_context_uninit_backend_apis__win32(ma_context* pContext) ma_result ma_context_init_backend_apis__win32(ma_context* pContext) { #ifdef MA_WIN32_DESKTOP - // Ole32.dll + /* Ole32.dll */ pContext->win32.hOle32DLL = ma_dlopen("ole32.dll"); if (pContext->win32.hOle32DLL == NULL) { return MA_FAILED_TO_INIT_BACKEND; @@ -22840,7 +23618,7 @@ ma_result ma_context_init_backend_apis__win32(ma_context* pContext) pContext->win32.StringFromGUID2 = (ma_proc)ma_dlsym(pContext->win32.hOle32DLL, "StringFromGUID2"); - // User32.dll + /* User32.dll */ pContext->win32.hUser32DLL = ma_dlopen("user32.dll"); if (pContext->win32.hUser32DLL == NULL) { return MA_FAILED_TO_INIT_BACKEND; @@ -22850,7 +23628,7 @@ ma_result ma_context_init_backend_apis__win32(ma_context* pContext) pContext->win32.GetDesktopWindow = (ma_proc)ma_dlsym(pContext->win32.hUser32DLL, "GetDesktopWindow"); - // Advapi32.dll + /* Advapi32.dll */ pContext->win32.hAdvapi32DLL = ma_dlopen("advapi32.dll"); if (pContext->win32.hAdvapi32DLL == NULL) { return MA_FAILED_TO_INIT_BACKEND; @@ -22878,15 +23656,16 @@ ma_result ma_context_uninit_backend_apis__nix(ma_context* pContext) ma_result ma_context_init_backend_apis__nix(ma_context* pContext) { - // pthread + /* pthread */ #if defined(MA_USE_RUNTIME_LINKING_FOR_PTHREAD) && !defined(MA_NO_RUNTIME_LINKING) const char* libpthreadFileNames[] = { "libpthread.so", "libpthread.so.0", "libpthread.dylib" }; + size_t i; - for (size_t i = 0; i < sizeof(libpthreadFileNames) / sizeof(libpthreadFileNames[0]); ++i) { + for (i = 0; i < sizeof(libpthreadFileNames) / sizeof(libpthreadFileNames[0]); ++i) { pContext->posix.pthreadSO = ma_dlopen(libpthreadFileNames[i]); if (pContext->posix.pthreadSO != NULL) { break; @@ -22968,14 +23747,20 @@ ma_bool32 ma_context_is_backend_asynchronous(ma_context* pContext) ma_result ma_context_init(const ma_backend backends[], ma_uint32 backendCount, const ma_context_config* pConfig, ma_context* pContext) { + ma_result result; + ma_context_config config; + ma_backend defaultBackends[ma_backend_null+1]; + ma_uint32 iBackend; + ma_backend* pBackendsToIterate; + ma_uint32 backendsToIterateCount; + if (pContext == NULL) { return MA_INVALID_ARGS; } ma_zero_object(pContext); - // Always make sure the config is set first to ensure properties are available as soon as possible. - ma_context_config config; + /* Always make sure the config is set first to ensure properties are available as soon as possible. */ if (pConfig != NULL) { config = *pConfig; } else { @@ -22986,19 +23771,18 @@ ma_result ma_context_init(const ma_backend backends[], ma_uint32 backendCount, c pContext->threadPriority = config.threadPriority; pContext->pUserData = config.pUserData; - // Backend APIs need to be initialized first. This is where external libraries will be loaded and linked. - ma_result result = ma_context_init_backend_apis(pContext); + /* Backend APIs need to be initialized first. This is where external libraries will be loaded and linked. */ + result = ma_context_init_backend_apis(pContext); if (result != MA_SUCCESS) { return result; } - ma_backend defaultBackends[ma_backend_null+1]; - for (int i = 0; i <= ma_backend_null; ++i) { - defaultBackends[i] = (ma_backend)i; + for (iBackend = 0; iBackend <= ma_backend_null; ++iBackend) { + defaultBackends[iBackend] = (ma_backend)iBackend; } - ma_backend* pBackendsToIterate = (ma_backend*)backends; - ma_uint32 backendsToIterateCount = backendCount; + pBackendsToIterate = (ma_backend*)backends; + backendsToIterateCount = backendCount; if (pBackendsToIterate == NULL) { pBackendsToIterate = (ma_backend*)defaultBackends; backendsToIterateCount = ma_countof(defaultBackends); @@ -23006,7 +23790,7 @@ ma_result ma_context_init(const ma_backend backends[], ma_uint32 backendCount, c ma_assert(pBackendsToIterate != NULL); - for (ma_uint32 iBackend = 0; iBackend < backendsToIterateCount; ++iBackend) { + for (iBackend = 0; iBackend < backendsToIterateCount; ++iBackend) { ma_backend backend = pBackendsToIterate[iBackend]; result = MA_NO_BACKEND; @@ -23099,7 +23883,7 @@ ma_result ma_context_init(const ma_backend backends[], ma_uint32 backendCount, c default: break; } - // If this iteration was successful, return. + /* If this iteration was successful, return. */ if (result == MA_SUCCESS) { result = ma_mutex_init(pContext, &pContext->deviceEnumLock); if (result != MA_SUCCESS) { @@ -23123,8 +23907,8 @@ ma_result ma_context_init(const ma_backend backends[], ma_uint32 backendCount, c } } - // If we get here it means an error occurred. - ma_zero_object(pContext); // Safety. + /* If we get here it means an error occurred. */ + ma_zero_object(pContext); /* Safety. */ return MA_NO_BACKEND; } @@ -23136,10 +23920,10 @@ ma_result ma_context_uninit(ma_context* pContext) pContext->onUninit(pContext); - ma_context_uninit_backend_apis(pContext); ma_mutex_uninit(&pContext->deviceEnumLock); ma_mutex_uninit(&pContext->deviceInfoLock); ma_free(pContext->pDeviceInfos); + ma_context_uninit_backend_apis(pContext); return MA_SUCCESS; } @@ -23147,11 +23931,12 @@ ma_result ma_context_uninit(ma_context* pContext) ma_result ma_context_enumerate_devices(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData) { + ma_result result; + if (pContext == NULL || pContext->onEnumDevices == NULL || callback == NULL) { return MA_INVALID_ARGS; } - ma_result result; ma_mutex_lock(&pContext->deviceEnumLock); { result = pContext->onEnumDevices(pContext, callback, pUserData); @@ -23164,13 +23949,15 @@ ma_result ma_context_enumerate_devices(ma_context* pContext, ma_enum_devices_cal ma_bool32 ma_context_get_devices__enum_callback(ma_context* pContext, ma_device_type deviceType, const ma_device_info* pInfo, void* pUserData) { - (void)pUserData; - - // We need to insert the device info into our main internal buffer. Where it goes depends on the device type. If it's a capture device - // it's just appended to the end. If it's a playback device it's inserted just before the first capture device. + /* + We need to insert the device info into our main internal buffer. Where it goes depends on the device type. If it's a capture device + it's just appended to the end. If it's a playback device it's inserted just before the first capture device. + */ - // First make sure we have room. Since the number of devices we add to the list is usually relatively small I've decided to use a - // simple fixed size increment for buffer expansion. + /* + First make sure we have room. Since the number of devices we add to the list is usually relatively small I've decided to use a + simple fixed size increment for buffer expansion. + */ const ma_uint32 bufferExpansionCount = 2; const ma_uint32 totalDeviceInfoCount = pContext->playbackDeviceInfoCount + pContext->captureDeviceInfoCount; @@ -23178,7 +23965,7 @@ ma_bool32 ma_context_get_devices__enum_callback(ma_context* pContext, ma_device_ ma_uint32 newCapacity = totalDeviceInfoCount + bufferExpansionCount; ma_device_info* pNewInfos = (ma_device_info*)ma_realloc(pContext->pDeviceInfos, sizeof(*pContext->pDeviceInfos)*newCapacity); if (pNewInfos == NULL) { - return MA_FALSE; // Out of memory. + return MA_FALSE; /* Out of memory. */ } pContext->pDeviceInfos = pNewInfos; @@ -23186,29 +23973,33 @@ ma_bool32 ma_context_get_devices__enum_callback(ma_context* pContext, ma_device_ } if (deviceType == ma_device_type_playback) { - // Playback. Insert just before the first capture device. + /* Playback. Insert just before the first capture device. */ - // The first thing to do is move all of the capture devices down a slot. + /* The first thing to do is move all of the capture devices down a slot. */ ma_uint32 iFirstCaptureDevice = pContext->playbackDeviceInfoCount; - for (size_t iCaptureDevice = totalDeviceInfoCount; iCaptureDevice > iFirstCaptureDevice; --iCaptureDevice) { + size_t iCaptureDevice; + for (iCaptureDevice = totalDeviceInfoCount; iCaptureDevice > iFirstCaptureDevice; --iCaptureDevice) { pContext->pDeviceInfos[iCaptureDevice] = pContext->pDeviceInfos[iCaptureDevice-1]; } - // Now just insert where the first capture device was before moving it down a slot. + /* Now just insert where the first capture device was before moving it down a slot. */ pContext->pDeviceInfos[iFirstCaptureDevice] = *pInfo; pContext->playbackDeviceInfoCount += 1; } else { - // Capture. Insert at the end. + /* Capture. Insert at the end. */ pContext->pDeviceInfos[totalDeviceInfoCount] = *pInfo; pContext->captureDeviceInfoCount += 1; } + (void)pUserData; return MA_TRUE; } ma_result ma_context_get_devices(ma_context* pContext, ma_device_info** ppPlaybackDeviceInfos, ma_uint32* pPlaybackDeviceCount, ma_device_info** ppCaptureDeviceInfos, ma_uint32* pCaptureDeviceCount) { - // Safety. + ma_result result; + + /* Safety. */ if (ppPlaybackDeviceInfos != NULL) *ppPlaybackDeviceInfos = NULL; if (pPlaybackDeviceCount != NULL) *pPlaybackDeviceCount = 0; if (ppCaptureDeviceInfos != NULL) *ppCaptureDeviceInfos = NULL; @@ -23218,18 +24009,17 @@ ma_result ma_context_get_devices(ma_context* pContext, ma_device_info** ppPlayba return MA_INVALID_ARGS; } - // Note that we don't use ma_context_enumerate_devices() here because we want to do locking at a higher level. - ma_result result; + /* Note that we don't use ma_context_enumerate_devices() here because we want to do locking at a higher level. */ ma_mutex_lock(&pContext->deviceEnumLock); { - // Reset everything first. + /* Reset everything first. */ pContext->playbackDeviceInfoCount = 0; pContext->captureDeviceInfoCount = 0; - // Now enumerate over available devices. + /* Now enumerate over available devices. */ result = pContext->onEnumDevices(pContext, ma_context_get_devices__enum_callback, NULL); if (result == MA_SUCCESS) { - // Playback devices. + /* Playback devices. */ if (ppPlaybackDeviceInfos != NULL) { *ppPlaybackDeviceInfos = pContext->pDeviceInfos; } @@ -23237,9 +24027,9 @@ ma_result ma_context_get_devices(ma_context* pContext, ma_device_info** ppPlayba *pPlaybackDeviceCount = pContext->playbackDeviceInfoCount; } - // Capture devices. + /* Capture devices. */ if (ppCaptureDeviceInfos != NULL) { - *ppCaptureDeviceInfos = pContext->pDeviceInfos + pContext->playbackDeviceInfoCount; // Capture devices come after playback devices. + *ppCaptureDeviceInfos = pContext->pDeviceInfos + pContext->playbackDeviceInfoCount; /* Capture devices come after playback devices. */ } if (pCaptureDeviceCount != NULL) { *pCaptureDeviceCount = pContext->captureDeviceInfoCount; @@ -23253,20 +24043,21 @@ ma_result ma_context_get_devices(ma_context* pContext, ma_device_info** ppPlayba ma_result ma_context_get_device_info(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_share_mode shareMode, ma_device_info* pDeviceInfo) { - // NOTE: Do not clear pDeviceInfo on entry. The reason is the pDeviceID may actually point to pDeviceInfo->id which will break things. + ma_device_info deviceInfo; + + /* NOTE: Do not clear pDeviceInfo on entry. The reason is the pDeviceID may actually point to pDeviceInfo->id which will break things. */ if (pContext == NULL || pDeviceInfo == NULL) { return MA_INVALID_ARGS; } - ma_device_info deviceInfo; ma_zero_object(&deviceInfo); - // Help the backend out by copying over the device ID if we have one. + /* Help the backend out by copying over the device ID if we have one. */ if (pDeviceID != NULL) { ma_copy_memory(&deviceInfo.id, pDeviceID, sizeof(*pDeviceID)); } - // The backend may have an optimized device info retrieval function. If so, try that first. + /* The backend may have an optimized device info retrieval function. If so, try that first. */ if (pContext->onGetDeviceInfo != NULL) { ma_result result; ma_mutex_lock(&pContext->deviceInfoLock); @@ -23275,7 +24066,7 @@ ma_result ma_context_get_device_info(ma_context* pContext, ma_device_type device } ma_mutex_unlock(&pContext->deviceInfoLock); - // Clamp ranges. + /* Clamp ranges. */ deviceInfo.minChannels = ma_max(deviceInfo.minChannels, MA_MIN_CHANNELS); deviceInfo.maxChannels = ma_min(deviceInfo.maxChannels, MA_MAX_CHANNELS); deviceInfo.minSampleRate = ma_max(deviceInfo.minSampleRate, MA_MIN_SAMPLE_RATE); @@ -23285,13 +24076,16 @@ ma_result ma_context_get_device_info(ma_context* pContext, ma_device_type device return result; } - // Getting here means onGetDeviceInfo has not been set. + /* Getting here means onGetDeviceInfo has not been set. */ return MA_ERROR; } ma_result ma_device_init(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice) { + ma_result result; + ma_device_config config; + if (pContext == NULL) { return ma_device_init_ex(NULL, 0, NULL, pConfig, pDevice); } @@ -23303,7 +24097,7 @@ ma_result ma_device_init(ma_context* pContext, const ma_device_config* pConfig, } /* We need to make a copy of the config so we can set default values if they were left unset in the input config. */ - ma_device_config config = *pConfig; + config = *pConfig; /* Basic config validation. */ if (config.deviceType != ma_device_type_playback && config.deviceType != ma_device_type_capture && config.deviceType != ma_device_type_duplex) { @@ -23332,7 +24126,7 @@ ma_result ma_device_init(ma_context* pContext, const ma_device_config* pConfig, ma_zero_object(pDevice); pDevice->pContext = pContext; - // Set the user data and log callback ASAP to ensure it is available for the entire initialization process. + /* Set the user data and log callback ASAP to ensure it is available for the entire initialization process. */ pDevice->pUserData = config.pUserData; pDevice->onData = config.dataCallback; pDevice->onStop = config.stopCallback; @@ -23343,8 +24137,10 @@ ma_result ma_device_init(ma_context* pContext, const ma_device_config* pConfig, } } - // When passing in 0 for the format/channels/rate/chmap it means the device will be using whatever is chosen by the backend. If everything is set - // to defaults it means the format conversion pipeline will run on a fast path where data transfer is just passed straight through to the backend. + /* + When passing in 0 for the format/channels/rate/chmap it means the device will be using whatever is chosen by the backend. If everything is set + to defaults it means the format conversion pipeline will run on a fast path where data transfer is just passed straight through to the backend. + */ if (config.sampleRate == 0) { config.sampleRate = MA_DEFAULT_SAMPLE_RATE; pDevice->usingDefaultSampleRate = MA_TRUE; @@ -23375,13 +24171,13 @@ ma_result ma_device_init(ma_context* pContext, const ma_device_config* pConfig, } - // Default buffer size. + /* Default buffer size. */ if (config.bufferSizeInMilliseconds == 0 && config.bufferSizeInFrames == 0) { config.bufferSizeInMilliseconds = (config.performanceProfile == ma_performance_profile_low_latency) ? MA_BASE_BUFFER_SIZE_IN_MILLISECONDS_LOW_LATENCY : MA_BASE_BUFFER_SIZE_IN_MILLISECONDS_CONSERVATIVE; pDevice->usingDefaultBufferSize = MA_TRUE; } - // Default periods. + /* Default periods. */ if (config.periods == 0) { config.periods = MA_DEFAULT_PERIODS; pDevice->usingDefaultPeriods = MA_TRUE; @@ -23410,7 +24206,7 @@ ma_result ma_device_init(ma_context* pContext, const ma_device_config* pConfig, ma_channel_map_copy(pDevice->playback.channelMap, config.playback.channelMap, config.playback.channels); - // The internal format, channel count and sample rate can be modified by the backend. + /* The internal format, channel count and sample rate can be modified by the backend. */ pDevice->capture.internalFormat = pDevice->capture.format; pDevice->capture.internalChannels = pDevice->capture.channels; pDevice->capture.internalSampleRate = pDevice->sampleRate; @@ -23426,11 +24222,13 @@ ma_result ma_device_init(ma_context* pContext, const ma_device_config* pConfig, return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "Failed to create mutex.", MA_FAILED_TO_CREATE_MUTEX); } - // When the device is started, the worker thread is the one that does the actual startup of the backend device. We - // use a semaphore to wait for the background thread to finish the work. The same applies for stopping the device. - // - // Each of these semaphores is released internally by the worker thread when the work is completed. The start - // semaphore is also used to wake up the worker thread. + /* + When the device is started, the worker thread is the one that does the actual startup of the backend device. We + use a semaphore to wait for the background thread to finish the work. The same applies for stopping the device. + + Each of these semaphores is released internally by the worker thread when the work is completed. The start + semaphore is also used to wake up the worker thread. + */ if (ma_event_init(pContext, &pDevice->wakeupEvent) != MA_SUCCESS) { ma_mutex_uninit(&pDevice->lock); return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "Failed to create worker thread wakeup event.", MA_FAILED_TO_CREATE_EVENT); @@ -23448,15 +24246,15 @@ ma_result ma_device_init(ma_context* pContext, const ma_device_config* pConfig, } - ma_result result = pContext->onDeviceInit(pContext, &config, pDevice); + result = pContext->onDeviceInit(pContext, &config, pDevice); if (result != MA_SUCCESS) { - return MA_NO_BACKEND; // The error message will have been posted with ma_post_error() by the source of the error so don't bother calling it here. + return MA_NO_BACKEND; /* The error message will have been posted with ma_post_error() by the source of the error so don't bother calling it here. */ } ma_device__post_init_setup(pDevice, pConfig->deviceType); - // If the backend did not fill out a name for the device, try a generic method. + /* If the backend did not fill out a name for the device, try a generic method. */ if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) { if (pDevice->capture.name[0] == '\0') { if (ma_context__try_get_device_name_by_id(pContext, ma_device_type_capture, config.capture.pDeviceID, pDevice->capture.name, sizeof(pDevice->capture.name)) != MA_SUCCESS) { @@ -23473,15 +24271,15 @@ ma_result ma_device_init(ma_context* pContext, const ma_device_config* pConfig, } - // Some backends don't require the worker thread. + /* Some backends don't require the worker thread. */ if (!ma_context_is_backend_asynchronous(pContext)) { - // The worker thread. + /* The worker thread. */ if (ma_thread_create(pContext, &pDevice->thread, ma_worker_thread, pDevice) != MA_SUCCESS) { ma_device_uninit(pDevice); return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "Failed to create worker thread.", MA_FAILED_TO_CREATE_THREAD); } - // Wait for the worker thread to put the device into it's stopped state for real. + /* Wait for the worker thread to put the device into it's stopped state for real. */ ma_event_wait(&pDevice->stopEvent); } else { ma_device__set_state(pDevice, MA_STATE_STOPPED); @@ -23527,37 +24325,43 @@ ma_result ma_device_init(ma_context* pContext, const ma_device_config* pConfig, ma_result ma_device_init_ex(const ma_backend backends[], ma_uint32 backendCount, const ma_context_config* pContextConfig, const ma_device_config* pConfig, ma_device* pDevice) { + ma_result result; + ma_context* pContext; + ma_backend defaultBackends[ma_backend_null+1]; + ma_uint32 iBackend; + ma_backend* pBackendsToIterate; + ma_uint32 backendsToIterateCount; + if (pConfig == NULL) { return MA_INVALID_ARGS; } - ma_context* pContext = (ma_context*)ma_malloc(sizeof(*pContext)); + pContext = (ma_context*)ma_malloc(sizeof(*pContext)); if (pContext == NULL) { return MA_OUT_OF_MEMORY; } - ma_backend defaultBackends[ma_backend_null+1]; - for (int i = 0; i <= ma_backend_null; ++i) { - defaultBackends[i] = (ma_backend)i; + for (iBackend = 0; iBackend <= ma_backend_null; ++iBackend) { + defaultBackends[iBackend] = (ma_backend)iBackend; } - ma_backend* pBackendsToIterate = (ma_backend*)backends; - ma_uint32 backendsToIterateCount = backendCount; + pBackendsToIterate = (ma_backend*)backends; + backendsToIterateCount = backendCount; if (pBackendsToIterate == NULL) { pBackendsToIterate = (ma_backend*)defaultBackends; backendsToIterateCount = ma_countof(defaultBackends); } - ma_result result = MA_NO_BACKEND; + result = MA_NO_BACKEND; - for (ma_uint32 iBackend = 0; iBackend < backendsToIterateCount; ++iBackend) { + for (iBackend = 0; iBackend < backendsToIterateCount; ++iBackend) { result = ma_context_init(&pBackendsToIterate[iBackend], 1, pContextConfig, pContext); if (result == MA_SUCCESS) { result = ma_device_init(pContext, pConfig, pDevice); if (result == MA_SUCCESS) { - break; // Success. + break; /* Success. */ } else { - ma_context_uninit(pContext); // Failure. + ma_context_uninit(pContext); /* Failure. */ } } } @@ -23577,16 +24381,15 @@ void ma_device_uninit(ma_device* pDevice) return; } - // Make sure the device is stopped first. The backends will probably handle this naturally, - // but I like to do it explicitly for my own sanity. + /* Make sure the device is stopped first. The backends will probably handle this naturally, but I like to do it explicitly for my own sanity. */ if (ma_device_is_started(pDevice)) { ma_device_stop(pDevice); } - // Putting the device into an uninitialized state will make the worker thread return. + /* Putting the device into an uninitialized state will make the worker thread return. */ ma_device__set_state(pDevice, MA_STATE_UNINITIALIZED); - // Wake up the worker thread and wait for it to properly terminate. + /* Wake up the worker thread and wait for it to properly terminate. */ if (!ma_context_is_backend_asynchronous(pDevice->pContext)) { ma_event_signal(&pDevice->wakeupEvent); ma_thread_wait(&pDevice->thread); @@ -23609,12 +24412,17 @@ void ma_device_uninit(ma_device* pDevice) void ma_device_set_stop_callback(ma_device* pDevice, ma_stop_proc proc) { - if (pDevice == NULL) return; + if (pDevice == NULL) { + return; + } + ma_atomic_exchange_ptr(&pDevice->onStop, proc); } ma_result ma_device_start(ma_device* pDevice) { + ma_result result; + if (pDevice == NULL) { return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "ma_device_start() called with invalid arguments (pDevice == NULL).", MA_INVALID_ARGS); } @@ -23632,27 +24440,31 @@ ma_result ma_device_start(ma_device* pDevice) return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "ma_device_start() called in synchronous mode. This should only be used in asynchronous/callback mode.", MA_DEVICE_NOT_INITIALIZED); } - ma_result result = MA_ERROR; + result = MA_ERROR; ma_mutex_lock(&pDevice->lock); { - // Starting and stopping are wrapped in a mutex which means we can assert that the device is in a stopped or paused state. + /* Starting and stopping are wrapped in a mutex which means we can assert that the device is in a stopped or paused state. */ ma_assert(ma_device__get_state(pDevice) == MA_STATE_STOPPED); ma_device__set_state(pDevice, MA_STATE_STARTING); - // Asynchronous backends need to be handled differently. + /* Asynchronous backends need to be handled differently. */ if (ma_context_is_backend_asynchronous(pDevice->pContext)) { result = pDevice->pContext->onDeviceStart(pDevice); if (result == MA_SUCCESS) { ma_device__set_state(pDevice, MA_STATE_STARTED); } } else { - // Synchronous backends are started by signaling an event that's being waited on in the worker thread. We first wake up the - // thread and then wait for the start event. + /* + Synchronous backends are started by signaling an event that's being waited on in the worker thread. We first wake up the + thread and then wait for the start event. + */ ma_event_signal(&pDevice->wakeupEvent); - // Wait for the worker thread to finish starting the device. Note that the worker thread will be the one - // who puts the device into the started state. Don't call ma_device__set_state() here. + /* + Wait for the worker thread to finish starting the device. Note that the worker thread will be the one who puts the device + into the started state. Don't call ma_device__set_state() here. + */ ma_event_wait(&pDevice->startEvent); result = pDevice->workResult; } @@ -23664,6 +24476,8 @@ ma_result ma_device_start(ma_device* pDevice) ma_result ma_device_stop(ma_device* pDevice) { + ma_result result; + if (pDevice == NULL) { return ma_post_error(pDevice, MA_LOG_LEVEL_ERROR, "ma_device_stop() called with invalid arguments (pDevice == NULL).", MA_INVALID_ARGS); } @@ -23682,17 +24496,17 @@ ma_result ma_device_stop(ma_device* pDevice) } } - ma_result result = MA_ERROR; + result = MA_ERROR; ma_mutex_lock(&pDevice->lock); { - // Starting and stopping are wrapped in a mutex which means we can assert that the device is in a started or paused state. + /* Starting and stopping are wrapped in a mutex which means we can assert that the device is in a started or paused state. */ ma_assert(ma_device__get_state(pDevice) == MA_STATE_STARTED); ma_device__set_state(pDevice, MA_STATE_STOPPING); - // There's no need to wake up the thread like we do when starting. + /* There's no need to wake up the thread like we do when starting. */ - // Asynchronous backends need to be handled differently. + /* Asynchronous backends need to be handled differently. */ if (ma_context_is_backend_asynchronous(pDevice->pContext)) { if (pDevice->pContext->onDeviceStop) { result = pDevice->pContext->onDeviceStop(pDevice); @@ -23702,10 +24516,12 @@ ma_result ma_device_stop(ma_device* pDevice) ma_device__set_state(pDevice, MA_STATE_STOPPED); } else { - // Synchronous backends. + /* Synchronous backends. */ - // We need to wait for the worker thread to become available for work before returning. Note that the worker thread will be - // the one who puts the device into the stopped state. Don't call ma_device__set_state() here. + /* + We need to wait for the worker thread to become available for work before returning. Note that the worker thread will be + the one who puts the device into the stopped state. Don't call ma_device__set_state() here. + */ ma_event_wait(&pDevice->stopEvent); result = MA_SUCCESS; } @@ -23717,7 +24533,10 @@ ma_result ma_device_stop(ma_device* pDevice) ma_bool32 ma_device_is_started(ma_device* pDevice) { - if (pDevice == NULL) return MA_FALSE; + if (pDevice == NULL) { + return MA_FALSE; + } + return ma_device__get_state(pDevice) == MA_STATE_STARTED; } @@ -23738,12 +24557,12 @@ ma_device_config ma_device_config_init(ma_device_type deviceType) return config; } -#endif // MA_NO_DEVICE_IO +#endif /* MA_NO_DEVICE_IO */ void ma_get_standard_channel_map_microsoft(ma_uint32 channels, ma_channel channelMap[MA_MAX_CHANNELS]) { - // Based off the speaker configurations mentioned here: https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/ksmedia/ns-ksmedia-ksaudio_channel_config + /* Based off the speaker configurations mentioned here: https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/ksmedia/ns-ksmedia-ksaudio_channel_config */ switch (channels) { case 1: @@ -23757,7 +24576,7 @@ void ma_get_standard_channel_map_microsoft(ma_uint32 channels, ma_channel channe channelMap[1] = MA_CHANNEL_FRONT_RIGHT; } break; - case 3: // Not defined, but best guess. + case 3: /* Not defined, but best guess. */ { channelMap[0] = MA_CHANNEL_FRONT_LEFT; channelMap[1] = MA_CHANNEL_FRONT_RIGHT; @@ -23767,14 +24586,13 @@ void ma_get_standard_channel_map_microsoft(ma_uint32 channels, ma_channel channe case 4: { #ifndef MA_USE_QUAD_MICROSOFT_CHANNEL_MAP - // Surround. Using the Surround profile has the advantage of the 3rd channel (MA_CHANNEL_FRONT_CENTER) mapping nicely - // with higher channel counts. + /* Surround. Using the Surround profile has the advantage of the 3rd channel (MA_CHANNEL_FRONT_CENTER) mapping nicely with higher channel counts. */ channelMap[0] = MA_CHANNEL_FRONT_LEFT; channelMap[1] = MA_CHANNEL_FRONT_RIGHT; channelMap[2] = MA_CHANNEL_FRONT_CENTER; channelMap[3] = MA_CHANNEL_BACK_CENTER; #else - // Quad. + /* Quad. */ channelMap[0] = MA_CHANNEL_FRONT_LEFT; channelMap[1] = MA_CHANNEL_FRONT_RIGHT; channelMap[2] = MA_CHANNEL_BACK_LEFT; @@ -23782,7 +24600,7 @@ void ma_get_standard_channel_map_microsoft(ma_uint32 channels, ma_channel channe #endif } break; - case 5: // Not defined, but best guess. + case 5: /* Not defined, but best guess. */ { channelMap[0] = MA_CHANNEL_FRONT_LEFT; channelMap[1] = MA_CHANNEL_FRONT_RIGHT; @@ -23801,7 +24619,7 @@ void ma_get_standard_channel_map_microsoft(ma_uint32 channels, ma_channel channe channelMap[5] = MA_CHANNEL_SIDE_RIGHT; } break; - case 7: // Not defined, but best guess. + case 7: /* Not defined, but best guess. */ { channelMap[0] = MA_CHANNEL_FRONT_LEFT; channelMap[1] = MA_CHANNEL_FRONT_RIGHT; @@ -23826,9 +24644,10 @@ void ma_get_standard_channel_map_microsoft(ma_uint32 channels, ma_channel channe } break; } - // Remainder. + /* Remainder. */ if (channels > 8) { - for (ma_uint32 iChannel = 8; iChannel < MA_MAX_CHANNELS; ++iChannel) { + ma_uint32 iChannel; + for (iChannel = 8; iChannel < MA_MAX_CHANNELS; ++iChannel) { channelMap[iChannel] = (ma_channel)(MA_CHANNEL_AUX_0 + (iChannel-8)); } } @@ -23908,9 +24727,10 @@ void ma_get_standard_channel_map_alsa(ma_uint32 channels, ma_channel channelMap[ } break; } - // Remainder. + /* Remainder. */ if (channels > 8) { - for (ma_uint32 iChannel = 8; iChannel < MA_MAX_CHANNELS; ++iChannel) { + ma_uint32 iChannel; + for (iChannel = 8; iChannel < MA_MAX_CHANNELS; ++iChannel) { channelMap[iChannel] = (ma_channel)(MA_CHANNEL_AUX_0 + (iChannel-8)); } } @@ -23966,9 +24786,10 @@ void ma_get_standard_channel_map_rfc3551(ma_uint32 channels, ma_channel channelM } break; } - // Remainder. + /* Remainder. */ if (channels > 8) { - for (ma_uint32 iChannel = 6; iChannel < MA_MAX_CHANNELS; ++iChannel) { + ma_uint32 iChannel; + for (iChannel = 6; iChannel < MA_MAX_CHANNELS; ++iChannel) { channelMap[iChannel] = (ma_channel)(MA_CHANNEL_AUX_0 + (iChannel-6)); } } @@ -24048,9 +24869,10 @@ void ma_get_standard_channel_map_flac(ma_uint32 channels, ma_channel channelMap[ } break; } - // Remainder. + /* Remainder. */ if (channels > 8) { - for (ma_uint32 iChannel = 8; iChannel < MA_MAX_CHANNELS; ++iChannel) { + ma_uint32 iChannel; + for (iChannel = 8; iChannel < MA_MAX_CHANNELS; ++iChannel) { channelMap[iChannel] = (ma_channel)(MA_CHANNEL_AUX_0 + (iChannel-8)); } } @@ -24058,8 +24880,7 @@ void ma_get_standard_channel_map_flac(ma_uint32 channels, ma_channel channelMap[ void ma_get_standard_channel_map_vorbis(ma_uint32 channels, ma_channel channelMap[MA_MAX_CHANNELS]) { - // In Vorbis' type 0 channel mapping, the first two channels are not always the standard left/right - it - // will have the center speaker where the right usually goes. Why?! + /* In Vorbis' type 0 channel mapping, the first two channels are not always the standard left/right - it will have the center speaker where the right usually goes. Why?! */ switch (channels) { case 1: @@ -24132,9 +24953,10 @@ void ma_get_standard_channel_map_vorbis(ma_uint32 channels, ma_channel channelMa } break; } - // Remainder. + /* Remainder. */ if (channels > 8) { - for (ma_uint32 iChannel = 8; iChannel < MA_MAX_CHANNELS; ++iChannel) { + ma_uint32 iChannel; + for (iChannel = 8; iChannel < MA_MAX_CHANNELS; ++iChannel) { channelMap[iChannel] = (ma_channel)(MA_CHANNEL_AUX_0 + (iChannel-8)); } } @@ -24214,9 +25036,10 @@ void ma_get_standard_channel_map_sound4(ma_uint32 channels, ma_channel channelMa } break; } - // Remainder. + /* Remainder. */ if (channels > 8) { - for (ma_uint32 iChannel = 8; iChannel < MA_MAX_CHANNELS; ++iChannel) { + ma_uint32 iChannel; + for (iChannel = 8; iChannel < MA_MAX_CHANNELS; ++iChannel) { channelMap[iChannel] = (ma_channel)(MA_CHANNEL_AUX_0 + (iChannel-8)); } } @@ -24273,9 +25096,10 @@ void ma_get_standard_channel_map_sndio(ma_uint32 channels, ma_channel channelMap } break; } - // Remainder. + /* Remainder. */ if (channels > 6) { - for (ma_uint32 iChannel = 6; iChannel < MA_MAX_CHANNELS; ++iChannel) { + ma_uint32 iChannel; + for (iChannel = 6; iChannel < MA_MAX_CHANNELS; ++iChannel) { channelMap[iChannel] = (ma_channel)(MA_CHANNEL_AUX_0 + (iChannel-6)); } } @@ -24336,14 +25160,15 @@ ma_bool32 ma_channel_map_valid(ma_uint32 channels, const ma_channel channelMap[M return MA_FALSE; } - // A channel count of 0 is invalid. + /* A channel count of 0 is invalid. */ if (channels == 0) { return MA_FALSE; } - // It does not make sense to have a mono channel when there is more than 1 channel. + /* It does not make sense to have a mono channel when there is more than 1 channel. */ if (channels > 1) { - for (ma_uint32 iChannel = 0; iChannel < channels; ++iChannel) { + ma_uint32 iChannel; + for (iChannel = 0; iChannel < channels; ++iChannel) { if (channelMap[iChannel] == MA_CHANNEL_MONO) { return MA_FALSE; } @@ -24355,6 +25180,8 @@ ma_bool32 ma_channel_map_valid(ma_uint32 channels, const ma_channel channelMap[M ma_bool32 ma_channel_map_equal(ma_uint32 channels, const ma_channel channelMapA[MA_MAX_CHANNELS], const ma_channel channelMapB[MA_MAX_CHANNELS]) { + ma_uint32 iChannel; + if (channelMapA == channelMapB) { return MA_FALSE; } @@ -24363,7 +25190,7 @@ ma_bool32 ma_channel_map_equal(ma_uint32 channels, const ma_channel channelMapA[ return MA_FALSE; } - for (ma_uint32 iChannel = 0; iChannel < channels; ++iChannel) { + for (iChannel = 0; iChannel < channels; ++iChannel) { if (channelMapA[iChannel] != channelMapB[iChannel]) { return MA_FALSE; } @@ -24374,7 +25201,9 @@ ma_bool32 ma_channel_map_equal(ma_uint32 channels, const ma_channel channelMapA[ ma_bool32 ma_channel_map_blank(ma_uint32 channels, const ma_channel channelMap[MA_MAX_CHANNELS]) { - for (ma_uint32 iChannel = 0; iChannel < channels; ++iChannel) { + ma_uint32 iChannel; + + for (iChannel = 0; iChannel < channels; ++iChannel) { if (channelMap[iChannel] != MA_CHANNEL_NONE) { return MA_FALSE; } @@ -24385,7 +25214,8 @@ ma_bool32 ma_channel_map_blank(ma_uint32 channels, const ma_channel channelMap[M ma_bool32 ma_channel_map_contains_channel_position(ma_uint32 channels, const ma_channel channelMap[MA_MAX_CHANNELS], ma_channel channelPosition) { - for (ma_uint32 iChannel = 0; iChannel < channels; ++iChannel) { + ma_uint32 iChannel; + for (iChannel = 0; iChannel < channels; ++iChannel) { if (channelMap[iChannel] == channelPosition) { return MA_TRUE; } @@ -24397,15 +25227,11 @@ ma_bool32 ma_channel_map_contains_channel_position(ma_uint32 channels, const ma_ -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Format Conversion. -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +/************************************************************************************************************************************************************** -//#define MA_USE_REFERENCE_CONVERSION_APIS 1 -//#define MA_USE_SSE +Format Conversion. +**************************************************************************************************************************************************************/ void ma_copy_memory_64(void* dst, const void* src, ma_uint64 sizeInBytes) { #if 0xFFFFFFFFFFFFFFFF <= MA_SIZE_MAX @@ -24417,7 +25243,7 @@ void ma_copy_memory_64(void* dst, const void* src, ma_uint64 sizeInBytes) bytesToCopyNow = MA_SIZE_MAX; } - ma_copy_memory(dst, src, (size_t)bytesToCopyNow); // Safe cast to size_t. + ma_copy_memory(dst, src, (size_t)bytesToCopyNow); /* Safe cast to size_t. */ sizeInBytes -= bytesToCopyNow; dst = ( void*)(( ma_uint8*)dst + bytesToCopyNow); @@ -24437,7 +25263,7 @@ void ma_zero_memory_64(void* dst, ma_uint64 sizeInBytes) bytesToZeroNow = MA_SIZE_MAX; } - ma_zero_memory(dst, (size_t)bytesToZeroNow); // Safe cast to size_t. + ma_zero_memory(dst, (size_t)bytesToZeroNow); /* Safe cast to size_t. */ sizeInBytes -= bytesToZeroNow; dst = (void*)((ma_uint8*)dst + bytesToZeroNow); @@ -24446,7 +25272,7 @@ void ma_zero_memory_64(void* dst, ma_uint64 sizeInBytes) } -// u8 +/* u8 */ void ma_pcm_u8_to_u8(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) { (void)ditherMode; @@ -24455,9 +25281,7 @@ void ma_pcm_u8_to_u8(void* dst, const void* src, ma_uint64 count, ma_dither_mode void ma_pcm_u8_to_s16__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) -{ - (void)ditherMode; - +{ ma_int16* dst_s16 = (ma_int16*)dst; const ma_uint8* src_u8 = (const ma_uint8*)src; @@ -24468,6 +25292,8 @@ void ma_pcm_u8_to_s16__reference(void* dst, const void* src, ma_uint64 count, ma x = x << 8; dst_s16[i] = x; } + + (void)ditherMode; } void ma_pcm_u8_to_s16__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) @@ -24512,8 +25338,6 @@ void ma_pcm_u8_to_s16(void* dst, const void* src, ma_uint64 count, ma_dither_mod void ma_pcm_u8_to_s24__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) { - (void)ditherMode; - ma_uint8* dst_s24 = (ma_uint8*)dst; const ma_uint8* src_u8 = (const ma_uint8*)src; @@ -24526,6 +25350,8 @@ void ma_pcm_u8_to_s24__reference(void* dst, const void* src, ma_uint64 count, ma dst_s24[i*3+1] = 0; dst_s24[i*3+2] = (ma_uint8)((ma_int8)x); } + + (void)ditherMode; } void ma_pcm_u8_to_s24__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) @@ -24570,8 +25396,6 @@ void ma_pcm_u8_to_s24(void* dst, const void* src, ma_uint64 count, ma_dither_mod void ma_pcm_u8_to_s32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) { - (void)ditherMode; - ma_int32* dst_s32 = (ma_int32*)dst; const ma_uint8* src_u8 = (const ma_uint8*)src; @@ -24582,6 +25406,8 @@ void ma_pcm_u8_to_s32__reference(void* dst, const void* src, ma_uint64 count, ma x = x << 24; dst_s32[i] = x; } + + (void)ditherMode; } void ma_pcm_u8_to_s32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) @@ -24626,19 +25452,19 @@ void ma_pcm_u8_to_s32(void* dst, const void* src, ma_uint64 count, ma_dither_mod void ma_pcm_u8_to_f32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) { - (void)ditherMode; - float* dst_f32 = (float*)dst; const ma_uint8* src_u8 = (const ma_uint8*)src; ma_uint64 i; for (i = 0; i < count; i += 1) { float x = (float)src_u8[i]; - x = x * 0.00784313725490196078f; // 0..255 to 0..2 - x = x - 1; // 0..2 to -1..1 + x = x * 0.00784313725490196078f; /* 0..255 to 0..2 */ + x = x - 1; /* 0..2 to -1..1 */ dst_f32[i] = x; } + + (void)ditherMode; } void ma_pcm_u8_to_f32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) @@ -24759,7 +25585,7 @@ void ma_pcm_deinterleave_u8(void** dst, const void* src, ma_uint64 frameCount, m } -// s16 +/* s16 */ void ma_pcm_s16_to_u8__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) { ma_uint8* dst_u8 = (ma_uint8*)dst; @@ -24778,7 +25604,7 @@ void ma_pcm_s16_to_u8__reference(void* dst, const void* src, ma_uint64 count, ma for (i = 0; i < count; i += 1) { ma_int16 x = src_s16[i]; - // Dither. Don't overflow. + /* Dither. Don't overflow. */ ma_int32 dither = ma_dither_s32(ditherMode, -0x80, 0x7F); if ((x + dither) <= 0x7FFF) { x = (ma_int16)(x + dither); @@ -24842,8 +25668,6 @@ void ma_pcm_s16_to_s16(void* dst, const void* src, ma_uint64 count, ma_dither_mo void ma_pcm_s16_to_s24__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) { - (void)ditherMode; - ma_uint8* dst_s24 = (ma_uint8*)dst; const ma_int16* src_s16 = (const ma_int16*)src; @@ -24853,6 +25677,8 @@ void ma_pcm_s16_to_s24__reference(void* dst, const void* src, ma_uint64 count, m dst_s24[i*3+1] = (ma_uint8)(src_s16[i] & 0xFF); dst_s24[i*3+2] = (ma_uint8)(src_s16[i] >> 8); } + + (void)ditherMode; } void ma_pcm_s16_to_s24__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) @@ -24897,8 +25723,6 @@ void ma_pcm_s16_to_s24(void* dst, const void* src, ma_uint64 count, ma_dither_mo void ma_pcm_s16_to_s32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) { - (void)ditherMode; - ma_int32* dst_s32 = (ma_int32*)dst; const ma_int16* src_s16 = (const ma_int16*)src; @@ -24906,6 +25730,8 @@ void ma_pcm_s16_to_s32__reference(void* dst, const void* src, ma_uint64 count, m for (i = 0; i < count; i += 1) { dst_s32[i] = src_s16[i] << 16; } + + (void)ditherMode; } void ma_pcm_s16_to_s32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) @@ -24950,8 +25776,6 @@ void ma_pcm_s16_to_s32(void* dst, const void* src, ma_uint64 count, ma_dither_mo void ma_pcm_s16_to_f32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) { - (void)ditherMode; - float* dst_f32 = (float*)dst; const ma_int16* src_s16 = (const ma_int16*)src; @@ -24960,17 +25784,19 @@ void ma_pcm_s16_to_f32__reference(void* dst, const void* src, ma_uint64 count, m float x = (float)src_s16[i]; #if 0 - // The accurate way. - x = x + 32768.0f; // -32768..32767 to 0..65535 - x = x * 0.00003051804379339284f; // 0..65536 to 0..2 - x = x - 1; // 0..2 to -1..1 + /* The accurate way. */ + x = x + 32768.0f; /* -32768..32767 to 0..65535 */ + x = x * 0.00003051804379339284f; /* 0..65536 to 0..2 */ + x = x - 1; /* 0..2 to -1..1 */ #else - // The fast way. - x = x * 0.000030517578125f; // -32768..32767 to -1..0.999969482421875 + /* The fast way. */ + x = x * 0.000030517578125f; /* -32768..32767 to -1..0.999969482421875 */ #endif dst_f32[i] = x; } + + (void)ditherMode; } void ma_pcm_s16_to_f32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) @@ -25071,7 +25897,7 @@ void ma_pcm_deinterleave_s16(void** dst, const void* src, ma_uint64 frameCount, } -// s24 +/* s24 */ void ma_pcm_s24_to_u8__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) { ma_uint8* dst_u8 = (ma_uint8*)dst; @@ -25088,7 +25914,7 @@ void ma_pcm_s24_to_u8__reference(void* dst, const void* src, ma_uint64 count, ma for (i = 0; i < count; i += 1) { ma_int32 x = (ma_int32)(((ma_uint32)(src_s24[i*3+0]) << 8) | ((ma_uint32)(src_s24[i*3+1]) << 16) | ((ma_uint32)(src_s24[i*3+2])) << 24); - // Dither. Don't overflow. + /* Dither. Don't overflow. */ ma_int32 dither = ma_dither_s32(ditherMode, -0x800000, 0x7FFFFF); if ((ma_int64)x + dither <= 0x7FFFFFFF) { x = x + dither; @@ -25160,7 +25986,7 @@ void ma_pcm_s24_to_s16__reference(void* dst, const void* src, ma_uint64 count, m for (i = 0; i < count; i += 1) { ma_int32 x = (ma_int32)(((ma_uint32)(src_s24[i*3+0]) << 8) | ((ma_uint32)(src_s24[i*3+1]) << 16) | ((ma_uint32)(src_s24[i*3+2])) << 24); - // Dither. Don't overflow. + /* Dither. Don't overflow. */ ma_int32 dither = ma_dither_s32(ditherMode, -0x8000, 0x7FFF); if ((ma_int64)x + dither <= 0x7FFFFFFF) { x = x + dither; @@ -25224,8 +26050,6 @@ void ma_pcm_s24_to_s24(void* dst, const void* src, ma_uint64 count, ma_dither_mo void ma_pcm_s24_to_s32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) { - (void)ditherMode; - ma_int32* dst_s32 = (ma_int32*)dst; const ma_uint8* src_s24 = (const ma_uint8*)src; @@ -25233,6 +26057,8 @@ void ma_pcm_s24_to_s32__reference(void* dst, const void* src, ma_uint64 count, m for (i = 0; i < count; i += 1) { dst_s32[i] = (ma_int32)(((ma_uint32)(src_s24[i*3+0]) << 8) | ((ma_uint32)(src_s24[i*3+1]) << 16) | ((ma_uint32)(src_s24[i*3+2])) << 24); } + + (void)ditherMode; } void ma_pcm_s24_to_s32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) @@ -25277,8 +26103,6 @@ void ma_pcm_s24_to_s32(void* dst, const void* src, ma_uint64 count, ma_dither_mo void ma_pcm_s24_to_f32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) { - (void)ditherMode; - float* dst_f32 = (float*)dst; const ma_uint8* src_s24 = (const ma_uint8*)src; @@ -25287,17 +26111,19 @@ void ma_pcm_s24_to_f32__reference(void* dst, const void* src, ma_uint64 count, m float x = (float)(((ma_int32)(((ma_uint32)(src_s24[i*3+0]) << 8) | ((ma_uint32)(src_s24[i*3+1]) << 16) | ((ma_uint32)(src_s24[i*3+2])) << 24)) >> 8); #if 0 - // The accurate way. - x = x + 8388608.0f; // -8388608..8388607 to 0..16777215 - x = x * 0.00000011920929665621f; // 0..16777215 to 0..2 - x = x - 1; // 0..2 to -1..1 + /* The accurate way. */ + x = x + 8388608.0f; /* -8388608..8388607 to 0..16777215 */ + x = x * 0.00000011920929665621f; /* 0..16777215 to 0..2 */ + x = x - 1; /* 0..2 to -1..1 */ #else - // The fast way. - x = x * 0.00000011920928955078125f; // -8388608..8388607 to -1..0.999969482421875 + /* The fast way. */ + x = x * 0.00000011920928955078125f; /* -8388608..8388607 to -1..0.999969482421875 */ #endif dst_f32[i] = x; } + + (void)ditherMode; } void ma_pcm_s24_to_f32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) @@ -25403,7 +26229,7 @@ void ma_pcm_deinterleave_s24(void** dst, const void* src, ma_uint64 frameCount, -// s32 +/* s32 */ void ma_pcm_s32_to_u8__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) { ma_uint8* dst_u8 = (ma_uint8*)dst; @@ -25422,7 +26248,7 @@ void ma_pcm_s32_to_u8__reference(void* dst, const void* src, ma_uint64 count, ma for (i = 0; i < count; i += 1) { ma_int32 x = src_s32[i]; - // Dither. Don't overflow. + /* Dither. Don't overflow. */ ma_int32 dither = ma_dither_s32(ditherMode, -0x800000, 0x7FFFFF); if ((ma_int64)x + dither <= 0x7FFFFFFF) { x = x + dither; @@ -25494,7 +26320,7 @@ void ma_pcm_s32_to_s16__reference(void* dst, const void* src, ma_uint64 count, m for (i = 0; i < count; i += 1) { ma_int32 x = src_s32[i]; - // Dither. Don't overflow. + /* Dither. Don't overflow. */ ma_int32 dither = ma_dither_s32(ditherMode, -0x8000, 0x7FFF); if ((ma_int64)x + dither <= 0x7FFFFFFF) { x = x + dither; @@ -25550,8 +26376,6 @@ void ma_pcm_s32_to_s16(void* dst, const void* src, ma_uint64 count, ma_dither_mo void ma_pcm_s32_to_s24__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) { - (void)ditherMode; // No dithering for s32 -> s24. - ma_uint8* dst_s24 = (ma_uint8*)dst; const ma_int32* src_s32 = (const ma_int32*)src; @@ -25562,6 +26386,8 @@ void ma_pcm_s32_to_s24__reference(void* dst, const void* src, ma_uint64 count, m dst_s24[i*3+1] = (ma_uint8)((x & 0x00FF0000) >> 16); dst_s24[i*3+2] = (ma_uint8)((x & 0xFF000000) >> 24); } + + (void)ditherMode; /* No dithering for s32 -> s24. */ } void ma_pcm_s32_to_s24__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) @@ -25614,8 +26440,6 @@ void ma_pcm_s32_to_s32(void* dst, const void* src, ma_uint64 count, ma_dither_mo void ma_pcm_s32_to_f32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) { - (void)ditherMode; // No dithering for s32 -> f32. - float* dst_f32 = (float*)dst; const ma_int32* src_s32 = (const ma_int32*)src; @@ -25633,6 +26457,8 @@ void ma_pcm_s32_to_f32__reference(void* dst, const void* src, ma_uint64 count, m dst_f32[i] = (float)x; } + + (void)ditherMode; /* No dithering for s32 -> f32. */ } void ma_pcm_s32_to_f32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) @@ -25733,9 +26559,11 @@ void ma_pcm_deinterleave_s32(void** dst, const void* src, ma_uint64 frameCount, } -// f32 +/* f32 */ void ma_pcm_f32_to_u8__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) { + ma_uint64 i; + ma_uint8* dst_u8 = (ma_uint8*)dst; const float* src_f32 = (const float*)src; @@ -25746,13 +26574,12 @@ void ma_pcm_f32_to_u8__reference(void* dst, const void* src, ma_uint64 count, ma ditherMax = 1.0f / 127; } - ma_uint64 i; for (i = 0; i < count; i += 1) { float x = src_f32[i]; x = x + ma_dither_f32(ditherMode, ditherMin, ditherMax); - x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); // clip - x = x + 1; // -1..1 to 0..2 - x = x * 127.5f; // 0..2 to 0..255 + x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); /* clip */ + x = x + 1; /* -1..1 to 0..2 */ + x = x * 127.5f; /* 0..2 to 0..255 */ dst_u8[i] = (ma_uint8)x; } @@ -25800,6 +26627,8 @@ void ma_pcm_f32_to_u8(void* dst, const void* src, ma_uint64 count, ma_dither_mod void ma_pcm_f32_to_s16__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) { + ma_uint64 i; + ma_int16* dst_s16 = (ma_int16*)dst; const float* src_f32 = (const float*)src; @@ -25810,20 +26639,19 @@ void ma_pcm_f32_to_s16__reference(void* dst, const void* src, ma_uint64 count, m ditherMax = 1.0f / 32767; } - ma_uint64 i; for (i = 0; i < count; i += 1) { float x = src_f32[i]; x = x + ma_dither_f32(ditherMode, ditherMin, ditherMax); - x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); // clip + x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); /* clip */ #if 0 - // The accurate way. - x = x + 1; // -1..1 to 0..2 - x = x * 32767.5f; // 0..2 to 0..65535 - x = x - 32768.0f; // 0...65535 to -32768..32767 + /* The accurate way. */ + x = x + 1; /* -1..1 to 0..2 */ + x = x * 32767.5f; /* 0..2 to 0..65535 */ + x = x - 32768.0f; /* 0...65535 to -32768..32767 */ #else - // The fast way. - x = x * 32767.0f; // -1..1 to -32767..32767 + /* The fast way. */ + x = x * 32767.0f; /* -1..1 to -32767..32767 */ #endif dst_s16[i] = (ma_int16)x; @@ -25832,6 +26660,10 @@ void ma_pcm_f32_to_s16__reference(void* dst, const void* src, ma_uint64 count, m void ma_pcm_f32_to_s16__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) { + ma_uint64 i; + ma_uint64 i4; + ma_uint64 count4; + ma_int16* dst_s16 = (ma_int16*)dst; const float* src_f32 = (const float*)src; @@ -25842,11 +26674,10 @@ void ma_pcm_f32_to_s16__optimized(void* dst, const void* src, ma_uint64 count, m ditherMax = 1.0f / 32767; } - ma_uint64 i = 0; - - // Unrolled. - ma_uint64 count4 = count >> 2; - for (ma_uint64 i4 = 0; i4 < count4; i4 += 1) { + /* Unrolled. */ + i = 0; + count4 = count >> 2; + for (i4 = 0; i4 < count4; i4 += 1) { float d0 = ma_dither_f32(ditherMode, ditherMin, ditherMax); float d1 = ma_dither_f32(ditherMode, ditherMin, ditherMax); float d2 = ma_dither_f32(ditherMode, ditherMin, ditherMax); @@ -25880,12 +26711,12 @@ void ma_pcm_f32_to_s16__optimized(void* dst, const void* src, ma_uint64 count, m i += 4; } - // Leftover. + /* Leftover. */ for (; i < count; i += 1) { float x = src_f32[i]; x = x + ma_dither_f32(ditherMode, ditherMin, ditherMax); - x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); // clip - x = x * 32767.0f; // -1..1 to -32767..32767 + x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); /* clip */ + x = x * 32767.0f; /* -1..1 to -32767..32767 */ dst_s16[i] = (ma_int16)x; } @@ -25894,29 +26725,40 @@ void ma_pcm_f32_to_s16__optimized(void* dst, const void* src, ma_uint64 count, m #if defined(MA_SUPPORT_SSE2) void ma_pcm_f32_to_s16__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) { - // Both the input and output buffers need to be aligned to 16 bytes. + ma_uint64 i; + ma_uint64 i8; + ma_uint64 count8; + ma_int16* dst_s16; + const float* src_f32; + float ditherMin; + float ditherMax; + + /* Both the input and output buffers need to be aligned to 16 bytes. */ if ((((ma_uintptr)dst & 15) != 0) || (((ma_uintptr)src & 15) != 0)) { ma_pcm_f32_to_s16__optimized(dst, src, count, ditherMode); return; } - ma_int16* dst_s16 = (ma_int16*)dst; - const float* src_f32 = (const float*)src; + dst_s16 = (ma_int16*)dst; + src_f32 = (const float*)src; - float ditherMin = 0; - float ditherMax = 0; + ditherMin = 0; + ditherMax = 0; if (ditherMode != ma_dither_mode_none) { ditherMin = 1.0f / -32768; ditherMax = 1.0f / 32767; } - ma_uint64 i = 0; + i = 0; - // SSE2. SSE allows us to output 8 s16's at a time which means our loop is unrolled 8 times. - ma_uint64 count8 = count >> 3; - for (ma_uint64 i8 = 0; i8 < count8; i8 += 1) { + /* SSE2. SSE allows us to output 8 s16's at a time which means our loop is unrolled 8 times. */ + count8 = count >> 3; + for (i8 = 0; i8 < count8; i8 += 1) { __m128 d0; __m128 d1; + __m128 x0; + __m128 x1; + if (ditherMode == ma_dither_mode_none) { d0 = _mm_set1_ps(0); d1 = _mm_set1_ps(0); @@ -25948,8 +26790,8 @@ void ma_pcm_f32_to_s16__sse2(void* dst, const void* src, ma_uint64 count, ma_dit ); } - __m128 x0 = *((__m128*)(src_f32 + i) + 0); - __m128 x1 = *((__m128*)(src_f32 + i) + 1); + x0 = *((__m128*)(src_f32 + i) + 0); + x1 = *((__m128*)(src_f32 + i) + 1); x0 = _mm_add_ps(x0, d0); x1 = _mm_add_ps(x1, d1); @@ -25963,12 +26805,12 @@ void ma_pcm_f32_to_s16__sse2(void* dst, const void* src, ma_uint64 count, ma_dit } - // Leftover. + /* Leftover. */ for (; i < count; i += 1) { float x = src_f32[i]; x = x + ma_dither_f32(ditherMode, ditherMin, ditherMax); - x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); // clip - x = x * 32767.0f; // -1..1 to -32767..32767 + x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); /* clip */ + x = x * 32767.0f; /* -1..1 to -32767..32767 */ dst_s16[i] = (ma_int16)x; } @@ -25977,29 +26819,45 @@ void ma_pcm_f32_to_s16__sse2(void* dst, const void* src, ma_uint64 count, ma_dit #if defined(MA_SUPPORT_AVX2) void ma_pcm_f32_to_s16__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) { - // Both the input and output buffers need to be aligned to 32 bytes. + ma_uint64 i; + ma_uint64 i16; + ma_uint64 count16; + ma_int16* dst_s16; + const float* src_f32; + float ditherMin; + float ditherMax; + + /* Both the input and output buffers need to be aligned to 32 bytes. */ if ((((ma_uintptr)dst & 31) != 0) || (((ma_uintptr)src & 31) != 0)) { ma_pcm_f32_to_s16__optimized(dst, src, count, ditherMode); return; } - ma_int16* dst_s16 = (ma_int16*)dst; - const float* src_f32 = (const float*)src; + dst_s16 = (ma_int16*)dst; + src_f32 = (const float*)src; - float ditherMin = 0; - float ditherMax = 0; + ditherMin = 0; + ditherMax = 0; if (ditherMode != ma_dither_mode_none) { ditherMin = 1.0f / -32768; ditherMax = 1.0f / 32767; } - ma_uint64 i = 0; + i = 0; - // AVX2. AVX2 allows us to output 16 s16's at a time which means our loop is unrolled 16 times. - ma_uint64 count16 = count >> 4; - for (ma_uint64 i16 = 0; i16 < count16; i16 += 1) { + /* AVX2. AVX2 allows us to output 16 s16's at a time which means our loop is unrolled 16 times. */ + count16 = count >> 4; + for (i16 = 0; i16 < count16; i16 += 1) { __m256 d0; __m256 d1; + __m256 x0; + __m256 x1; + __m256i i0; + __m256i i1; + __m256i p0; + __m256i p1; + __m256i r; + if (ditherMode == ma_dither_mode_none) { d0 = _mm256_set1_ps(0); d1 = _mm256_set1_ps(0); @@ -26047,8 +26905,8 @@ void ma_pcm_f32_to_s16__avx2(void* dst, const void* src, ma_uint64 count, ma_dit ); } - __m256 x0 = *((__m256*)(src_f32 + i) + 0); - __m256 x1 = *((__m256*)(src_f32 + i) + 1); + x0 = *((__m256*)(src_f32 + i) + 0); + x1 = *((__m256*)(src_f32 + i) + 1); x0 = _mm256_add_ps(x0, d0); x1 = _mm256_add_ps(x1, d1); @@ -26056,12 +26914,12 @@ void ma_pcm_f32_to_s16__avx2(void* dst, const void* src, ma_uint64 count, ma_dit x0 = _mm256_mul_ps(x0, _mm256_set1_ps(32767.0f)); x1 = _mm256_mul_ps(x1, _mm256_set1_ps(32767.0f)); - // Computing the final result is a little more complicated for AVX2 than SSE2. - __m256i i0 = _mm256_cvttps_epi32(x0); - __m256i i1 = _mm256_cvttps_epi32(x1); - __m256i p0 = _mm256_permute2x128_si256(i0, i1, 0 | 32); - __m256i p1 = _mm256_permute2x128_si256(i0, i1, 1 | 48); - __m256i r = _mm256_packs_epi32(p0, p1); + /* Computing the final result is a little more complicated for AVX2 than SSE2. */ + i0 = _mm256_cvttps_epi32(x0); + i1 = _mm256_cvttps_epi32(x1); + p0 = _mm256_permute2x128_si256(i0, i1, 0 | 32); + p1 = _mm256_permute2x128_si256(i0, i1, 1 | 48); + r = _mm256_packs_epi32(p0, p1); _mm256_stream_si256(((__m256i*)(dst_s16 + i)), r); @@ -26069,12 +26927,12 @@ void ma_pcm_f32_to_s16__avx2(void* dst, const void* src, ma_uint64 count, ma_dit } - // Leftover. + /* Leftover. */ for (; i < count; i += 1) { float x = src_f32[i]; x = x + ma_dither_f32(ditherMode, ditherMin, ditherMax); - x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); // clip - x = x * 32767.0f; // -1..1 to -32767..32767 + x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); /* clip */ + x = x * 32767.0f; /* -1..1 to -32767..32767 */ dst_s16[i] = (ma_int16)x; } @@ -26083,36 +26941,49 @@ void ma_pcm_f32_to_s16__avx2(void* dst, const void* src, ma_uint64 count, ma_dit #if defined(MA_SUPPORT_AVX512) void ma_pcm_f32_to_s16__avx512(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) { - // TODO: Convert this from AVX to AVX-512. + /* TODO: Convert this from AVX to AVX-512. */ ma_pcm_f32_to_s16__avx2(dst, src, count, ditherMode); } #endif #if defined(MA_SUPPORT_NEON) void ma_pcm_f32_to_s16__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) { - // Both the input and output buffers need to be aligned to 16 bytes. + ma_uint64 i; + ma_uint64 i8; + ma_uint64 count8; + ma_int16* dst_s16; + const float* src_f32; + float ditherMin; + float ditherMax; + + /* Both the input and output buffers need to be aligned to 16 bytes. */ if ((((ma_uintptr)dst & 15) != 0) || (((ma_uintptr)src & 15) != 0)) { ma_pcm_f32_to_s16__optimized(dst, src, count, ditherMode); return; } - ma_int16* dst_s16 = (ma_int16*)dst; - const float* src_f32 = (const float*)src; + dst_s16 = (ma_int16*)dst; + src_f32 = (const float*)src; - float ditherMin = 0; - float ditherMax = 0; + ditherMin = 0; + ditherMax = 0; if (ditherMode != ma_dither_mode_none) { ditherMin = 1.0f / -32768; ditherMax = 1.0f / 32767; } - ma_uint64 i = 0; + i = 0; - // NEON. NEON allows us to output 8 s16's at a time which means our loop is unrolled 8 times. - ma_uint64 count8 = count >> 3; - for (ma_uint64 i8 = 0; i8 < count8; i8 += 1) { + /* NEON. NEON allows us to output 8 s16's at a time which means our loop is unrolled 8 times. */ + count8 = count >> 3; + for (i8 = 0; i8 < count8; i8 += 1) { float32x4_t d0; float32x4_t d1; + float32x4_t x0; + float32x4_t x1; + int32x4_t i0; + int32x4_t i1; + if (ditherMode == ma_dither_mode_none) { d0 = vmovq_n_f32(0); d1 = vmovq_n_f32(0); @@ -26146,8 +27017,8 @@ void ma_pcm_f32_to_s16__neon(void* dst, const void* src, ma_uint64 count, ma_dit d1 = vld1q_f32(d1v); } - float32x4_t x0 = *((float32x4_t*)(src_f32 + i) + 0); - float32x4_t x1 = *((float32x4_t*)(src_f32 + i) + 1); + x0 = *((float32x4_t*)(src_f32 + i) + 0); + x1 = *((float32x4_t*)(src_f32 + i) + 1); x0 = vaddq_f32(x0, d0); x1 = vaddq_f32(x1, d1); @@ -26155,20 +27026,20 @@ void ma_pcm_f32_to_s16__neon(void* dst, const void* src, ma_uint64 count, ma_dit x0 = vmulq_n_f32(x0, 32767.0f); x1 = vmulq_n_f32(x1, 32767.0f); - int32x4_t i0 = vcvtq_s32_f32(x0); - int32x4_t i1 = vcvtq_s32_f32(x1); + i0 = vcvtq_s32_f32(x0); + i1 = vcvtq_s32_f32(x1); *((int16x8_t*)(dst_s16 + i)) = vcombine_s16(vqmovn_s32(i0), vqmovn_s32(i1)); i += 8; } - // Leftover. + /* Leftover. */ for (; i < count; i += 1) { float x = src_f32[i]; x = x + ma_dither_f32(ditherMode, ditherMin, ditherMax); - x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); // clip - x = x * 32767.0f; // -1..1 to -32767..32767 + x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); /* clip */ + x = x * 32767.0f; /* -1..1 to -32767..32767 */ dst_s16[i] = (ma_int16)x; } @@ -26187,31 +27058,32 @@ void ma_pcm_f32_to_s16(void* dst, const void* src, ma_uint64 count, ma_dither_mo void ma_pcm_f32_to_s24__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) { - (void)ditherMode; // No dithering for f32 -> s24. - ma_uint8* dst_s24 = (ma_uint8*)dst; const float* src_f32 = (const float*)src; ma_uint64 i; for (i = 0; i < count; i += 1) { + ma_int32 r; float x = src_f32[i]; - x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); // clip + x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); /* clip */ #if 0 - // The accurate way. - x = x + 1; // -1..1 to 0..2 - x = x * 8388607.5f; // 0..2 to 0..16777215 - x = x - 8388608.0f; // 0..16777215 to -8388608..8388607 + /* The accurate way. */ + x = x + 1; /* -1..1 to 0..2 */ + x = x * 8388607.5f; /* 0..2 to 0..16777215 */ + x = x - 8388608.0f; /* 0..16777215 to -8388608..8388607 */ #else - // The fast way. - x = x * 8388607.0f; // -1..1 to -8388607..8388607 + /* The fast way. */ + x = x * 8388607.0f; /* -1..1 to -8388607..8388607 */ #endif - ma_int32 r = (ma_int32)x; + r = (ma_int32)x; dst_s24[(i*3)+0] = (ma_uint8)((r & 0x0000FF) >> 0); dst_s24[(i*3)+1] = (ma_uint8)((r & 0x00FF00) >> 8); dst_s24[(i*3)+2] = (ma_uint8)((r & 0xFF0000) >> 16); } + + (void)ditherMode; /* No dithering for f32 -> s24. */ } void ma_pcm_f32_to_s24__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) @@ -26256,28 +27128,28 @@ void ma_pcm_f32_to_s24(void* dst, const void* src, ma_uint64 count, ma_dither_mo void ma_pcm_f32_to_s32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) { - (void)ditherMode; // No dithering for f32 -> s32. - ma_int32* dst_s32 = (ma_int32*)dst; const float* src_f32 = (const float*)src; ma_uint32 i; for (i = 0; i < count; i += 1) { double x = src_f32[i]; - x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); // clip + x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); /* clip */ #if 0 - // The accurate way. - x = x + 1; // -1..1 to 0..2 - x = x * 2147483647.5; // 0..2 to 0..4294967295 - x = x - 2147483648.0; // 0...4294967295 to -2147483648..2147483647 + /* The accurate way. */ + x = x + 1; /* -1..1 to 0..2 */ + x = x * 2147483647.5; /* 0..2 to 0..4294967295 */ + x = x - 2147483648.0; /* 0...4294967295 to -2147483648..2147483647 */ #else - // The fast way. - x = x * 2147483647.0; // -1..1 to -2147483647..2147483647 + /* The fast way. */ + x = x * 2147483647.0; /* -1..1 to -2147483647..2147483647 */ #endif dst_s32[i] = (ma_int32)x; } + + (void)ditherMode; /* No dithering for f32 -> s32. */ } void ma_pcm_f32_to_s32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode) @@ -26827,7 +27699,7 @@ ma_result ma_format_converter_init(const ma_format_converter_config* pConfig, ma pConverter->config = *pConfig; - // SIMD + /* SIMD */ pConverter->useSSE2 = ma_has_sse2() && !pConfig->noSSE2; pConverter->useAVX2 = ma_has_avx2() && !pConfig->noAVX2; pConverter->useAVX512 = ma_has_avx512f() && !pConfig->noAVX512; @@ -26892,29 +27764,36 @@ ma_result ma_format_converter_init(const ma_format_converter_config* pConfig, ma ma_uint64 ma_format_converter_read(ma_format_converter* pConverter, ma_uint64 frameCount, void* pFramesOut, void* pUserData) { + ma_uint64 totalFramesRead; + ma_uint32 sampleSizeIn; + ma_uint32 sampleSizeOut; + ma_uint32 frameSizeOut; + ma_uint8* pNextFramesOut; + if (pConverter == NULL || pFramesOut == NULL) { return 0; } - ma_uint64 totalFramesRead = 0; - ma_uint32 sampleSizeIn = ma_get_bytes_per_sample(pConverter->config.formatIn); - ma_uint32 sampleSizeOut = ma_get_bytes_per_sample(pConverter->config.formatOut); - //ma_uint32 frameSizeIn = sampleSizeIn * pConverter->config.channels; - ma_uint32 frameSizeOut = sampleSizeOut * pConverter->config.channels; - ma_uint8* pNextFramesOut = (ma_uint8*)pFramesOut; + totalFramesRead = 0; + sampleSizeIn = ma_get_bytes_per_sample(pConverter->config.formatIn); + sampleSizeOut = ma_get_bytes_per_sample(pConverter->config.formatOut); + /*frameSizeIn = sampleSizeIn * pConverter->config.channels;*/ + frameSizeOut = sampleSizeOut * pConverter->config.channels; + pNextFramesOut = (ma_uint8*)pFramesOut; if (pConverter->config.onRead != NULL) { - // Input data is interleaved. + /* Input data is interleaved. */ if (pConverter->config.formatIn == pConverter->config.formatOut) { - // Pass through. + /* Pass through. */ while (totalFramesRead < frameCount) { + ma_uint32 framesJustRead; ma_uint64 framesRemaining = (frameCount - totalFramesRead); ma_uint64 framesToReadRightNow = framesRemaining; if (framesToReadRightNow > 0xFFFFFFFF) { framesToReadRightNow = 0xFFFFFFFF; } - ma_uint32 framesJustRead = (ma_uint32)pConverter->config.onRead(pConverter, (ma_uint32)framesToReadRightNow, pNextFramesOut, pUserData); + framesJustRead = (ma_uint32)pConverter->config.onRead(pConverter, (ma_uint32)framesToReadRightNow, pNextFramesOut, pUserData); if (framesJustRead == 0) { break; } @@ -26927,20 +27806,23 @@ ma_uint64 ma_format_converter_read(ma_format_converter* pConverter, ma_uint64 fr } } } else { - // Conversion required. + /* Conversion required. */ + ma_uint32 maxFramesToReadAtATime; + MA_ALIGN(MA_SIMD_ALIGNMENT) ma_uint8 temp[MA_MAX_CHANNELS * MA_MAX_PCM_SAMPLE_SIZE_IN_BYTES * 128]; ma_assert(sizeof(temp) <= 0xFFFFFFFF); - ma_uint32 maxFramesToReadAtATime = sizeof(temp) / sampleSizeIn / pConverter->config.channels; + maxFramesToReadAtATime = sizeof(temp) / sampleSizeIn / pConverter->config.channels; while (totalFramesRead < frameCount) { + ma_uint32 framesJustRead; ma_uint64 framesRemaining = (frameCount - totalFramesRead); ma_uint64 framesToReadRightNow = framesRemaining; if (framesToReadRightNow > maxFramesToReadAtATime) { framesToReadRightNow = maxFramesToReadAtATime; } - ma_uint32 framesJustRead = (ma_uint32)pConverter->config.onRead(pConverter, (ma_uint32)framesToReadRightNow, temp, pUserData); + framesJustRead = (ma_uint32)pConverter->config.onRead(pConverter, (ma_uint32)framesToReadRightNow, temp, pUserData); if (framesJustRead == 0) { break; } @@ -26956,37 +27838,40 @@ ma_uint64 ma_format_converter_read(ma_format_converter* pConverter, ma_uint64 fr } } } else { - // Input data is deinterleaved. If a conversion is required we need to do an intermediary step. - MA_ALIGN(MA_SIMD_ALIGNMENT) ma_uint8 tempSamplesOfOutFormat[MA_MAX_CHANNELS * MA_MAX_PCM_SAMPLE_SIZE_IN_BYTES * 128]; - ma_assert(sizeof(tempSamplesOfOutFormat) <= 0xFFFFFFFFF); - + /* Input data is deinterleaved. If a conversion is required we need to do an intermediary step. */ void* ppTempSamplesOfOutFormat[MA_MAX_CHANNELS]; size_t splitBufferSizeOut; + ma_uint32 maxFramesToReadAtATime; + + MA_ALIGN(MA_SIMD_ALIGNMENT) ma_uint8 tempSamplesOfOutFormat[MA_MAX_CHANNELS * MA_MAX_PCM_SAMPLE_SIZE_IN_BYTES * 128]; + ma_assert(sizeof(tempSamplesOfOutFormat) <= 0xFFFFFFFF); + ma_split_buffer(tempSamplesOfOutFormat, sizeof(tempSamplesOfOutFormat), pConverter->config.channels, MA_SIMD_ALIGNMENT, (void**)&ppTempSamplesOfOutFormat, &splitBufferSizeOut); - ma_uint32 maxFramesToReadAtATime = (ma_uint32)(splitBufferSizeOut / sampleSizeIn); + maxFramesToReadAtATime = (ma_uint32)(splitBufferSizeOut / sampleSizeIn); while (totalFramesRead < frameCount) { + ma_uint32 framesJustRead; ma_uint64 framesRemaining = (frameCount - totalFramesRead); ma_uint64 framesToReadRightNow = framesRemaining; if (framesToReadRightNow > maxFramesToReadAtATime) { framesToReadRightNow = maxFramesToReadAtATime; } - ma_uint32 framesJustRead = 0; - if (pConverter->config.formatIn == pConverter->config.formatOut) { - // Only interleaving. + /* Only interleaving. */ framesJustRead = (ma_uint32)pConverter->config.onReadDeinterleaved(pConverter, (ma_uint32)framesToReadRightNow, ppTempSamplesOfOutFormat, pUserData); if (framesJustRead == 0) { break; } } else { - // Interleaving + Conversion. Convert first, then interleave. - MA_ALIGN(MA_SIMD_ALIGNMENT) ma_uint8 tempSamplesOfInFormat[MA_MAX_CHANNELS * MA_MAX_PCM_SAMPLE_SIZE_IN_BYTES * 128]; - + /* Interleaving + Conversion. Convert first, then interleave. */ void* ppTempSamplesOfInFormat[MA_MAX_CHANNELS]; size_t splitBufferSizeIn; + ma_uint32 iChannel; + + MA_ALIGN(MA_SIMD_ALIGNMENT) ma_uint8 tempSamplesOfInFormat[MA_MAX_CHANNELS * MA_MAX_PCM_SAMPLE_SIZE_IN_BYTES * 128]; + ma_split_buffer(tempSamplesOfInFormat, sizeof(tempSamplesOfInFormat), pConverter->config.channels, MA_SIMD_ALIGNMENT, (void**)&ppTempSamplesOfInFormat, &splitBufferSizeIn); if (framesToReadRightNow > (splitBufferSizeIn / sampleSizeIn)) { @@ -26998,7 +27883,7 @@ ma_uint64 ma_format_converter_read(ma_format_converter* pConverter, ma_uint64 fr break; } - for (ma_uint32 iChannel = 0; iChannel < pConverter->config.channels; iChannel += 1) { + for (iChannel = 0; iChannel < pConverter->config.channels; iChannel += 1) { pConverter->onConvertPCM(ppTempSamplesOfOutFormat[iChannel], ppTempSamplesOfInFormat[iChannel], framesJustRead, pConverter->config.ditherMode); } } @@ -27019,41 +27904,47 @@ ma_uint64 ma_format_converter_read(ma_format_converter* pConverter, ma_uint64 fr ma_uint64 ma_format_converter_read_deinterleaved(ma_format_converter* pConverter, ma_uint64 frameCount, void** ppSamplesOut, void* pUserData) { + ma_uint64 totalFramesRead; + ma_uint32 sampleSizeIn; + ma_uint32 sampleSizeOut; + ma_uint8* ppNextSamplesOut[MA_MAX_CHANNELS]; + if (pConverter == NULL || ppSamplesOut == NULL) { return 0; } - ma_uint64 totalFramesRead = 0; - ma_uint32 sampleSizeIn = ma_get_bytes_per_sample(pConverter->config.formatIn); - ma_uint32 sampleSizeOut = ma_get_bytes_per_sample(pConverter->config.formatOut); + totalFramesRead = 0; + sampleSizeIn = ma_get_bytes_per_sample(pConverter->config.formatIn); + sampleSizeOut = ma_get_bytes_per_sample(pConverter->config.formatOut); - ma_uint8* ppNextSamplesOut[MA_MAX_CHANNELS]; ma_copy_memory(ppNextSamplesOut, ppSamplesOut, sizeof(void*) * pConverter->config.channels); if (pConverter->config.onRead != NULL) { - // Input data is interleaved. + /* Input data is interleaved. */ + ma_uint32 maxFramesToReadAtATime; + MA_ALIGN(MA_SIMD_ALIGNMENT) ma_uint8 tempSamplesOfOutFormat[MA_MAX_CHANNELS * MA_MAX_PCM_SAMPLE_SIZE_IN_BYTES * 128]; ma_assert(sizeof(tempSamplesOfOutFormat) <= 0xFFFFFFFF); - ma_uint32 maxFramesToReadAtATime = sizeof(tempSamplesOfOutFormat) / sampleSizeIn / pConverter->config.channels; + maxFramesToReadAtATime = sizeof(tempSamplesOfOutFormat) / sampleSizeIn / pConverter->config.channels; while (totalFramesRead < frameCount) { + ma_uint32 iChannel; + ma_uint32 framesJustRead; ma_uint64 framesRemaining = (frameCount - totalFramesRead); ma_uint64 framesToReadRightNow = framesRemaining; if (framesToReadRightNow > maxFramesToReadAtATime) { framesToReadRightNow = maxFramesToReadAtATime; } - ma_uint32 framesJustRead = 0; - if (pConverter->config.formatIn == pConverter->config.formatOut) { - // Only de-interleaving. + /* Only de-interleaving. */ framesJustRead = (ma_uint32)pConverter->config.onRead(pConverter, (ma_uint32)framesToReadRightNow, tempSamplesOfOutFormat, pUserData); if (framesJustRead == 0) { break; } } else { - // De-interleaving + Conversion. Convert first, then de-interleave. + /* De-interleaving + Conversion. Convert first, then de-interleave. */ MA_ALIGN(MA_SIMD_ALIGNMENT) ma_uint8 tempSamplesOfInFormat[sizeof(tempSamplesOfOutFormat)]; framesJustRead = (ma_uint32)pConverter->config.onRead(pConverter, (ma_uint32)framesToReadRightNow, tempSamplesOfInFormat, pUserData); @@ -27067,7 +27958,7 @@ ma_uint64 ma_format_converter_read_deinterleaved(ma_format_converter* pConverter pConverter->onDeinterleavePCM((void**)ppNextSamplesOut, tempSamplesOfOutFormat, framesJustRead, pConverter->config.channels); totalFramesRead += framesJustRead; - for (ma_uint32 iChannel = 0; iChannel < pConverter->config.channels; ++iChannel) { + for (iChannel = 0; iChannel < pConverter->config.channels; ++iChannel) { ppNextSamplesOut[iChannel] += framesJustRead * sampleSizeOut; } @@ -27076,23 +27967,25 @@ ma_uint64 ma_format_converter_read_deinterleaved(ma_format_converter* pConverter } } } else { - // Input data is deinterleaved. + /* Input data is deinterleaved. */ if (pConverter->config.formatIn == pConverter->config.formatOut) { - // Pass through. + /* Pass through. */ while (totalFramesRead < frameCount) { + ma_uint32 iChannel; + ma_uint32 framesJustRead; ma_uint64 framesRemaining = (frameCount - totalFramesRead); ma_uint64 framesToReadRightNow = framesRemaining; if (framesToReadRightNow > 0xFFFFFFFF) { framesToReadRightNow = 0xFFFFFFFF; } - ma_uint32 framesJustRead = (ma_uint32)pConverter->config.onReadDeinterleaved(pConverter, (ma_uint32)framesToReadRightNow, (void**)ppNextSamplesOut, pUserData); + framesJustRead = (ma_uint32)pConverter->config.onReadDeinterleaved(pConverter, (ma_uint32)framesToReadRightNow, (void**)ppNextSamplesOut, pUserData); if (framesJustRead == 0) { break; } totalFramesRead += framesJustRead; - for (ma_uint32 iChannel = 0; iChannel < pConverter->config.channels; ++iChannel) { + for (iChannel = 0; iChannel < pConverter->config.channels; ++iChannel) { ppNextSamplesOut[iChannel] += framesJustRead * sampleSizeOut; } @@ -27101,29 +27994,33 @@ ma_uint64 ma_format_converter_read_deinterleaved(ma_format_converter* pConverter } } } else { - // Conversion required. + /* Conversion required. */ + void* ppTemp[MA_MAX_CHANNELS]; + size_t splitBufferSize; + ma_uint32 maxFramesToReadAtATime; + MA_ALIGN(MA_SIMD_ALIGNMENT) ma_uint8 temp[MA_MAX_CHANNELS][MA_MAX_PCM_SAMPLE_SIZE_IN_BYTES * 128]; ma_assert(sizeof(temp) <= 0xFFFFFFFF); - void* ppTemp[MA_MAX_CHANNELS]; - size_t splitBufferSize; ma_split_buffer(temp, sizeof(temp), pConverter->config.channels, MA_SIMD_ALIGNMENT, (void**)&ppTemp, &splitBufferSize); - ma_uint32 maxFramesToReadAtATime = (ma_uint32)(splitBufferSize / sampleSizeIn); + maxFramesToReadAtATime = (ma_uint32)(splitBufferSize / sampleSizeIn); while (totalFramesRead < frameCount) { + ma_uint32 iChannel; + ma_uint32 framesJustRead; ma_uint64 framesRemaining = (frameCount - totalFramesRead); ma_uint64 framesToReadRightNow = framesRemaining; if (framesToReadRightNow > maxFramesToReadAtATime) { framesToReadRightNow = maxFramesToReadAtATime; } - ma_uint32 framesJustRead = (ma_uint32)pConverter->config.onReadDeinterleaved(pConverter, (ma_uint32)framesToReadRightNow, ppTemp, pUserData); + framesJustRead = (ma_uint32)pConverter->config.onReadDeinterleaved(pConverter, (ma_uint32)framesToReadRightNow, ppTemp, pUserData); if (framesJustRead == 0) { break; } - for (ma_uint32 iChannel = 0; iChannel < pConverter->config.channels; iChannel += 1) { + for (iChannel = 0; iChannel < pConverter->config.channels; iChannel += 1) { pConverter->onConvertPCM(ppNextSamplesOut[iChannel], ppTemp[iChannel], framesJustRead, pConverter->config.ditherMode); ppNextSamplesOut[iChannel] += framesJustRead * sampleSizeOut; } @@ -27172,15 +28069,17 @@ ma_format_converter_config ma_format_converter_config_init_deinterleaved(ma_form -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Channel Routing -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +/************************************************************************************************************************************************************** + +Channel Routing -// -X = Left, +X = Right -// -Y = Bottom, +Y = Top -// -Z = Front, +Z = Back +**************************************************************************************************************************************************************/ + +/* +-X = Left, +X = Right +-Y = Bottom, +Y = Top +-Z = Front, +Z = Back +*/ typedef struct { float x; @@ -27275,90 +28174,92 @@ static MA_INLINE float ma_vec3_distance(ma_vec3 a, ma_vec3 b) #define MA_PLANE_TOP 5 float g_maChannelPlaneRatios[MA_CHANNEL_POSITION_COUNT][6] = { - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_NONE - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_MONO - { 0.5f, 0.0f, 0.5f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_FRONT_LEFT - { 0.0f, 0.5f, 0.5f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_FRONT_RIGHT - { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_FRONT_CENTER - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_LFE - { 0.5f, 0.0f, 0.0f, 0.5f, 0.0f, 0.0f}, // MA_CHANNEL_BACK_LEFT - { 0.0f, 0.5f, 0.0f, 0.5f, 0.0f, 0.0f}, // MA_CHANNEL_BACK_RIGHT - { 0.25f, 0.0f, 0.75f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_FRONT_LEFT_CENTER - { 0.0f, 0.25f, 0.75f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_FRONT_RIGHT_CENTER - { 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f}, // MA_CHANNEL_BACK_CENTER - { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_SIDE_LEFT - { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_SIDE_RIGHT - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f}, // MA_CHANNEL_TOP_CENTER - { 0.33f, 0.0f, 0.33f, 0.0f, 0.0f, 0.34f}, // MA_CHANNEL_TOP_FRONT_LEFT - { 0.0f, 0.0f, 0.5f, 0.0f, 0.0f, 0.5f}, // MA_CHANNEL_TOP_FRONT_CENTER - { 0.0f, 0.33f, 0.33f, 0.0f, 0.0f, 0.34f}, // MA_CHANNEL_TOP_FRONT_RIGHT - { 0.33f, 0.0f, 0.0f, 0.33f, 0.0f, 0.34f}, // MA_CHANNEL_TOP_BACK_LEFT - { 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, 0.5f}, // MA_CHANNEL_TOP_BACK_CENTER - { 0.0f, 0.33f, 0.0f, 0.33f, 0.0f, 0.34f}, // MA_CHANNEL_TOP_BACK_RIGHT - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_0 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_1 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_2 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_3 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_4 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_5 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_6 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_7 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_8 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_9 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_10 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_11 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_12 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_13 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_14 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_15 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_16 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_17 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_18 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_19 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_20 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_21 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_22 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_23 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_24 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_25 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_26 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_27 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_28 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_29 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_30 - { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // MA_CHANNEL_AUX_31 + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_NONE */ + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_MONO */ + { 0.5f, 0.0f, 0.5f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_FRONT_LEFT */ + { 0.0f, 0.5f, 0.5f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_FRONT_RIGHT */ + { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_FRONT_CENTER */ + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_LFE */ + { 0.5f, 0.0f, 0.0f, 0.5f, 0.0f, 0.0f}, /* MA_CHANNEL_BACK_LEFT */ + { 0.0f, 0.5f, 0.0f, 0.5f, 0.0f, 0.0f}, /* MA_CHANNEL_BACK_RIGHT */ + { 0.25f, 0.0f, 0.75f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_FRONT_LEFT_CENTER */ + { 0.0f, 0.25f, 0.75f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_FRONT_RIGHT_CENTER */ + { 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f}, /* MA_CHANNEL_BACK_CENTER */ + { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_SIDE_LEFT */ + { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_SIDE_RIGHT */ + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f}, /* MA_CHANNEL_TOP_CENTER */ + { 0.33f, 0.0f, 0.33f, 0.0f, 0.0f, 0.34f}, /* MA_CHANNEL_TOP_FRONT_LEFT */ + { 0.0f, 0.0f, 0.5f, 0.0f, 0.0f, 0.5f}, /* MA_CHANNEL_TOP_FRONT_CENTER */ + { 0.0f, 0.33f, 0.33f, 0.0f, 0.0f, 0.34f}, /* MA_CHANNEL_TOP_FRONT_RIGHT */ + { 0.33f, 0.0f, 0.0f, 0.33f, 0.0f, 0.34f}, /* MA_CHANNEL_TOP_BACK_LEFT */ + { 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, 0.5f}, /* MA_CHANNEL_TOP_BACK_CENTER */ + { 0.0f, 0.33f, 0.0f, 0.33f, 0.0f, 0.34f}, /* MA_CHANNEL_TOP_BACK_RIGHT */ + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_0 */ + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_1 */ + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_2 */ + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_3 */ + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_4 */ + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_5 */ + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_6 */ + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_7 */ + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_8 */ + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_9 */ + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_10 */ + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_11 */ + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_12 */ + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_13 */ + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_14 */ + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_15 */ + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_16 */ + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_17 */ + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_18 */ + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_19 */ + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_20 */ + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_21 */ + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_22 */ + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_23 */ + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_24 */ + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_25 */ + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_26 */ + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_27 */ + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_28 */ + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_29 */ + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_30 */ + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_31 */ }; float ma_calculate_channel_position_planar_weight(ma_channel channelPositionA, ma_channel channelPositionB) { - // Imagine the following simplified example: You have a single input speaker which is the front/left speaker which you want to convert to - // the following output configuration: - // - // - front/left - // - side/left - // - back/left - // - // The front/left output is easy - it the same speaker position so it receives the full contribution of the front/left input. The amount - // of contribution to apply to the side/left and back/left speakers, however, is a bit more complicated. - // - // Imagine the front/left speaker as emitting audio from two planes - the front plane and the left plane. You can think of the front/left - // speaker emitting half of it's total volume from the front, and the other half from the left. Since part of it's volume is being emitted - // from the left side, and the side/left and back/left channels also emit audio from the left plane, one would expect that they would - // receive some amount of contribution from front/left speaker. The amount of contribution depends on how many planes are shared between - // the two speakers. Note that in the examples below I've added a top/front/left speaker as an example just to show how the math works - // across 3 spatial dimensions. - // - // The first thing to do is figure out how each speaker's volume is spread over each of plane: - // - front/left: 2 planes (front and left) = 1/2 = half it's total volume on each plane - // - side/left: 1 plane (left only) = 1/1 = entire volume from left plane - // - back/left: 2 planes (back and left) = 1/2 = half it's total volume on each plane - // - top/front/left: 3 planes (top, front and left) = 1/3 = one third it's total volume on each plane - // - // The amount of volume each channel contributes to each of it's planes is what controls how much it is willing to given and take to other - // channels on the same plane. The volume that is willing to the given by one channel is multiplied by the volume that is willing to be - // taken by the other to produce the final contribution. - - // Contribution = Sum(Volume to Give * Volume to Take) + /* + Imagine the following simplified example: You have a single input speaker which is the front/left speaker which you want to convert to + the following output configuration: + + - front/left + - side/left + - back/left + + The front/left output is easy - it the same speaker position so it receives the full contribution of the front/left input. The amount + of contribution to apply to the side/left and back/left speakers, however, is a bit more complicated. + + Imagine the front/left speaker as emitting audio from two planes - the front plane and the left plane. You can think of the front/left + speaker emitting half of it's total volume from the front, and the other half from the left. Since part of it's volume is being emitted + from the left side, and the side/left and back/left channels also emit audio from the left plane, one would expect that they would + receive some amount of contribution from front/left speaker. The amount of contribution depends on how many planes are shared between + the two speakers. Note that in the examples below I've added a top/front/left speaker as an example just to show how the math works + across 3 spatial dimensions. + + The first thing to do is figure out how each speaker's volume is spread over each of plane: + - front/left: 2 planes (front and left) = 1/2 = half it's total volume on each plane + - side/left: 1 plane (left only) = 1/1 = entire volume from left plane + - back/left: 2 planes (back and left) = 1/2 = half it's total volume on each plane + - top/front/left: 3 planes (top, front and left) = 1/3 = one third it's total volume on each plane + + The amount of volume each channel contributes to each of it's planes is what controls how much it is willing to given and take to other + channels on the same plane. The volume that is willing to the given by one channel is multiplied by the volume that is willing to be + taken by the other to produce the final contribution. + */ + + /* Contribution = Sum(Volume to Give * Volume to Take) */ float contribution = g_maChannelPlaneRatios[channelPositionA][0] * g_maChannelPlaneRatios[channelPositionB][0] + g_maChannelPlaneRatios[channelPositionA][1] * g_maChannelPlaneRatios[channelPositionB][1] + @@ -27380,6 +28281,8 @@ float ma_channel_router__calculate_input_channel_planar_weight(const ma_channel_ ma_bool32 ma_channel_router__is_spatial_channel_position(const ma_channel_router* pRouter, ma_channel channelPosition) { + int i; + ma_assert(pRouter != NULL); (void)pRouter; @@ -27387,7 +28290,7 @@ ma_bool32 ma_channel_router__is_spatial_channel_position(const ma_channel_router return MA_FALSE; } - for (int i = 0; i < 6; ++i) { + for (i = 0; i < 6; ++i) { if (g_maChannelPlaneRatios[channelPosition][i] != 0) { return MA_TRUE; } @@ -27398,6 +28301,9 @@ ma_bool32 ma_channel_router__is_spatial_channel_position(const ma_channel_router ma_result ma_channel_router_init(const ma_channel_router_config* pConfig, ma_channel_router* pRouter) { + ma_uint32 iChannelIn; + ma_uint32 iChannelOut; + if (pRouter == NULL) { return MA_INVALID_ARGS; } @@ -27412,21 +28318,21 @@ ma_result ma_channel_router_init(const ma_channel_router_config* pConfig, ma_cha } if (!ma_channel_map_valid(pConfig->channelsIn, pConfig->channelMapIn)) { - return MA_INVALID_ARGS; // Invalid input channel map. + return MA_INVALID_ARGS; /* Invalid input channel map. */ } if (!ma_channel_map_valid(pConfig->channelsOut, pConfig->channelMapOut)) { - return MA_INVALID_ARGS; // Invalid output channel map. + return MA_INVALID_ARGS; /* Invalid output channel map. */ } pRouter->config = *pConfig; - // SIMD + /* SIMD */ pRouter->useSSE2 = ma_has_sse2() && !pConfig->noSSE2; pRouter->useAVX2 = ma_has_avx2() && !pConfig->noAVX2; pRouter->useAVX512 = ma_has_avx512f() && !pConfig->noAVX512; pRouter->useNEON = ma_has_neon() && !pConfig->noNEON; - // If the input and output channels and channel maps are the same we should use a passthrough. + /* If the input and output channels and channel maps are the same we should use a passthrough. */ if (pRouter->config.channelsIn == pRouter->config.channelsOut) { if (ma_channel_map_equal(pRouter->config.channelsIn, pRouter->config.channelMapIn, pRouter->config.channelMapOut)) { pRouter->isPassthrough = MA_TRUE; @@ -27436,18 +28342,20 @@ ma_result ma_channel_router_init(const ma_channel_router_config* pConfig, ma_cha } } - // Here is where we do a bit of pre-processing to know how each channel should be combined to make up the output. Rules: - // - // 1) If it's a passthrough, do nothing - it's just a simple memcpy(). - // 2) If the channel counts are the same and every channel position in the input map is present in the output map, use a - // simple shuffle. An example might be different 5.1 channel layouts. - // 3) Otherwise channels are blended based on spatial locality. + /* + Here is where we do a bit of pre-processing to know how each channel should be combined to make up the output. Rules: + + 1) If it's a passthrough, do nothing - it's just a simple memcpy(). + 2) If the channel counts are the same and every channel position in the input map is present in the output map, use a + simple shuffle. An example might be different 5.1 channel layouts. + 3) Otherwise channels are blended based on spatial locality. + */ if (!pRouter->isPassthrough) { if (pRouter->config.channelsIn == pRouter->config.channelsOut) { ma_bool32 areAllChannelPositionsPresent = MA_TRUE; - for (ma_uint32 iChannelIn = 0; iChannelIn < pRouter->config.channelsIn; ++iChannelIn) { + for (iChannelIn = 0; iChannelIn < pRouter->config.channelsIn; ++iChannelIn) { ma_bool32 isInputChannelPositionInOutput = MA_FALSE; - for (ma_uint32 iChannelOut = 0; iChannelOut < pRouter->config.channelsOut; ++iChannelOut) { + for (iChannelOut = 0; iChannelOut < pRouter->config.channelsOut; ++iChannelOut) { if (pRouter->config.channelMapIn[iChannelIn] == pRouter->config.channelMapOut[iChannelOut]) { isInputChannelPositionInOutput = MA_TRUE; break; @@ -27463,10 +28371,12 @@ ma_result ma_channel_router_init(const ma_channel_router_config* pConfig, ma_cha if (areAllChannelPositionsPresent) { pRouter->isSimpleShuffle = MA_TRUE; - // All the router will be doing is rearranging channels which means all we need to do is use a shuffling table which is just - // a mapping between the index of the input channel to the index of the output channel. - for (ma_uint32 iChannelIn = 0; iChannelIn < pRouter->config.channelsIn; ++iChannelIn) { - for (ma_uint32 iChannelOut = 0; iChannelOut < pRouter->config.channelsOut; ++iChannelOut) { + /* + All the router will be doing is rearranging channels which means all we need to do is use a shuffling table which is just + a mapping between the index of the input channel to the index of the output channel. + */ + for (iChannelIn = 0; iChannelIn < pRouter->config.channelsIn; ++iChannelIn) { + for (iChannelOut = 0; iChannelOut < pRouter->config.channelsOut; ++iChannelOut) { if (pRouter->config.channelMapIn[iChannelIn] == pRouter->config.channelMapOut[iChannelOut]) { pRouter->shuffleTable[iChannelIn] = (ma_uint8)iChannelOut; break; @@ -27478,18 +28388,20 @@ ma_result ma_channel_router_init(const ma_channel_router_config* pConfig, ma_cha } - // Here is where weights are calculated. Note that we calculate the weights at all times, even when using a passthrough and simple - // shuffling. We use different algorithms for calculating weights depending on our mixing mode. - // - // In simple mode we don't do any blending (except for converting between mono, which is done in a later step). Instead we just - // map 1:1 matching channels. In this mode, if no channels in the input channel map correspond to anything in the output channel - // map, nothing will be heard! + /* + Here is where weights are calculated. Note that we calculate the weights at all times, even when using a passthrough and simple + shuffling. We use different algorithms for calculating weights depending on our mixing mode. + + In simple mode we don't do any blending (except for converting between mono, which is done in a later step). Instead we just + map 1:1 matching channels. In this mode, if no channels in the input channel map correspond to anything in the output channel + map, nothing will be heard! + */ - // In all cases we need to make sure all channels that are present in both channel maps have a 1:1 mapping. - for (ma_uint32 iChannelIn = 0; iChannelIn < pRouter->config.channelsIn; ++iChannelIn) { + /* In all cases we need to make sure all channels that are present in both channel maps have a 1:1 mapping. */ + for (iChannelIn = 0; iChannelIn < pRouter->config.channelsIn; ++iChannelIn) { ma_channel channelPosIn = pRouter->config.channelMapIn[iChannelIn]; - for (ma_uint32 iChannelOut = 0; iChannelOut < pRouter->config.channelsOut; ++iChannelOut) { + for (iChannelOut = 0; iChannelOut < pRouter->config.channelsOut; ++iChannelOut) { ma_channel channelPosOut = pRouter->config.channelMapOut[iChannelOut]; if (channelPosIn == channelPosOut) { @@ -27498,13 +28410,15 @@ ma_result ma_channel_router_init(const ma_channel_router_config* pConfig, ma_cha } } - // The mono channel is accumulated on all other channels, except LFE. Make sure in this loop we exclude output mono channels since - // they were handled in the pass above. - for (ma_uint32 iChannelIn = 0; iChannelIn < pRouter->config.channelsIn; ++iChannelIn) { + /* + The mono channel is accumulated on all other channels, except LFE. Make sure in this loop we exclude output mono channels since + they were handled in the pass above. + */ + for (iChannelIn = 0; iChannelIn < pRouter->config.channelsIn; ++iChannelIn) { ma_channel channelPosIn = pRouter->config.channelMapIn[iChannelIn]; if (channelPosIn == MA_CHANNEL_MONO) { - for (ma_uint32 iChannelOut = 0; iChannelOut < pRouter->config.channelsOut; ++iChannelOut) { + for (iChannelOut = 0; iChannelOut < pRouter->config.channelsOut; ++iChannelOut) { ma_channel channelPosOut = pRouter->config.channelMapOut[iChannelOut]; if (channelPosOut != MA_CHANNEL_NONE && channelPosOut != MA_CHANNEL_MONO && channelPosOut != MA_CHANNEL_LFE) { @@ -27514,10 +28428,10 @@ ma_result ma_channel_router_init(const ma_channel_router_config* pConfig, ma_cha } } - // The output mono channel is the average of all non-none, non-mono and non-lfe input channels. + /* The output mono channel is the average of all non-none, non-mono and non-lfe input channels. */ { ma_uint32 len = 0; - for (ma_uint32 iChannelIn = 0; iChannelIn < pRouter->config.channelsIn; ++iChannelIn) { + for (iChannelIn = 0; iChannelIn < pRouter->config.channelsIn; ++iChannelIn) { ma_channel channelPosIn = pRouter->config.channelMapIn[iChannelIn]; if (channelPosIn != MA_CHANNEL_NONE && channelPosIn != MA_CHANNEL_MONO && channelPosIn != MA_CHANNEL_LFE) { @@ -27528,11 +28442,11 @@ ma_result ma_channel_router_init(const ma_channel_router_config* pConfig, ma_cha if (len > 0) { float monoWeight = 1.0f / len; - for (ma_uint32 iChannelOut = 0; iChannelOut < pRouter->config.channelsOut; ++iChannelOut) { + for (iChannelOut = 0; iChannelOut < pRouter->config.channelsOut; ++iChannelOut) { ma_channel channelPosOut = pRouter->config.channelMapOut[iChannelOut]; if (channelPosOut == MA_CHANNEL_MONO) { - for (ma_uint32 iChannelIn = 0; iChannelIn < pRouter->config.channelsIn; ++iChannelIn) { + for (iChannelIn = 0; iChannelIn < pRouter->config.channelsIn; ++iChannelIn) { ma_channel channelPosIn = pRouter->config.channelMapIn[iChannelIn]; if (channelPosIn != MA_CHANNEL_NONE && channelPosIn != MA_CHANNEL_MONO && channelPosIn != MA_CHANNEL_LFE) { @@ -27545,18 +28459,18 @@ ma_result ma_channel_router_init(const ma_channel_router_config* pConfig, ma_cha } - // Input and output channels that are not present on the other side need to be blended in based on spatial locality. + /* Input and output channels that are not present on the other side need to be blended in based on spatial locality. */ switch (pRouter->config.mixingMode) { case ma_channel_mix_mode_rectangular: { - // Unmapped input channels. - for (ma_uint32 iChannelIn = 0; iChannelIn < pRouter->config.channelsIn; ++iChannelIn) { + /* Unmapped input channels. */ + for (iChannelIn = 0; iChannelIn < pRouter->config.channelsIn; ++iChannelIn) { ma_channel channelPosIn = pRouter->config.channelMapIn[iChannelIn]; if (ma_channel_router__is_spatial_channel_position(pRouter, channelPosIn)) { if (!ma_channel_map_contains_channel_position(pRouter->config.channelsOut, pRouter->config.channelMapOut, channelPosIn)) { - for (ma_uint32 iChannelOut = 0; iChannelOut < pRouter->config.channelsOut; ++iChannelOut) { + for (iChannelOut = 0; iChannelOut < pRouter->config.channelsOut; ++iChannelOut) { ma_channel channelPosOut = pRouter->config.channelMapOut[iChannelOut]; if (ma_channel_router__is_spatial_channel_position(pRouter, channelPosOut)) { @@ -27565,7 +28479,7 @@ ma_result ma_channel_router_init(const ma_channel_router_config* pConfig, ma_cha weight = ma_channel_router__calculate_input_channel_planar_weight(pRouter, channelPosIn, channelPosOut); } - // Only apply the weight if we haven't already got some contribution from the respective channels. + /* Only apply the weight if we haven't already got some contribution from the respective channels. */ if (pRouter->config.weights[iChannelIn][iChannelOut] == 0) { pRouter->config.weights[iChannelIn][iChannelOut] = weight; } @@ -27575,13 +28489,13 @@ ma_result ma_channel_router_init(const ma_channel_router_config* pConfig, ma_cha } } - // Unmapped output channels. - for (ma_uint32 iChannelOut = 0; iChannelOut < pRouter->config.channelsOut; ++iChannelOut) { + /* Unmapped output channels. */ + for (iChannelOut = 0; iChannelOut < pRouter->config.channelsOut; ++iChannelOut) { ma_channel channelPosOut = pRouter->config.channelMapOut[iChannelOut]; if (ma_channel_router__is_spatial_channel_position(pRouter, channelPosOut)) { if (!ma_channel_map_contains_channel_position(pRouter->config.channelsIn, pRouter->config.channelMapIn, channelPosOut)) { - for (ma_uint32 iChannelIn = 0; iChannelIn < pRouter->config.channelsIn; ++iChannelIn) { + for (iChannelIn = 0; iChannelIn < pRouter->config.channelsIn; ++iChannelIn) { ma_channel channelPosIn = pRouter->config.channelMapIn[iChannelIn]; if (ma_channel_router__is_spatial_channel_position(pRouter, channelPosIn)) { @@ -27590,7 +28504,7 @@ ma_result ma_channel_router_init(const ma_channel_router_config* pConfig, ma_cha weight = ma_channel_router__calculate_input_channel_planar_weight(pRouter, channelPosIn, channelPosOut); } - // Only apply the weight if we haven't already got some contribution from the respective channels. + /* Only apply the weight if we haven't already got some contribution from the respective channels. */ if (pRouter->config.weights[iChannelIn][iChannelOut] == 0) { pRouter->config.weights[iChannelIn][iChannelOut] = weight; } @@ -27634,34 +28548,38 @@ static MA_INLINE ma_bool32 ma_channel_router__can_use_neon(ma_channel_router* pR void ma_channel_router__do_routing(ma_channel_router* pRouter, ma_uint64 frameCount, float** ppSamplesOut, const float** ppSamplesIn) { + ma_uint32 iChannelIn; + ma_uint32 iChannelOut; + ma_assert(pRouter != NULL); ma_assert(pRouter->isPassthrough == MA_FALSE); if (pRouter->isSimpleShuffle) { - // A shuffle is just a re-arrangement of channels and does not require any arithmetic. + /* A shuffle is just a re-arrangement of channels and does not require any arithmetic. */ ma_assert(pRouter->config.channelsIn == pRouter->config.channelsOut); - for (ma_uint32 iChannelIn = 0; iChannelIn < pRouter->config.channelsIn; ++iChannelIn) { - ma_uint32 iChannelOut = pRouter->shuffleTable[iChannelIn]; + for (iChannelIn = 0; iChannelIn < pRouter->config.channelsIn; ++iChannelIn) { + iChannelOut = pRouter->shuffleTable[iChannelIn]; ma_copy_memory_64(ppSamplesOut[iChannelOut], ppSamplesIn[iChannelIn], frameCount * sizeof(float)); } } else { - // This is the more complicated case. Each of the output channels is accumulated with 0 or more input channels. + /* This is the more complicated case. Each of the output channels is accumulated with 0 or more input channels. */ - // Clear. - for (ma_uint32 iChannelOut = 0; iChannelOut < pRouter->config.channelsOut; ++iChannelOut) { + /* Clear. */ + for (iChannelOut = 0; iChannelOut < pRouter->config.channelsOut; ++iChannelOut) { ma_zero_memory_64(ppSamplesOut[iChannelOut], frameCount * sizeof(float)); } - // Accumulate. - for (ma_uint32 iChannelIn = 0; iChannelIn < pRouter->config.channelsIn; ++iChannelIn) { - for (ma_uint32 iChannelOut = 0; iChannelOut < pRouter->config.channelsOut; ++iChannelOut) { + /* Accumulate. */ + for (iChannelIn = 0; iChannelIn < pRouter->config.channelsIn; ++iChannelIn) { + for (iChannelOut = 0; iChannelOut < pRouter->config.channelsOut; ++iChannelOut) { ma_uint64 iFrame = 0; #if defined(MA_SUPPORT_NEON) if (ma_channel_router__can_use_neon(pRouter, ppSamplesOut[iChannelOut], ppSamplesIn[iChannelIn])) { float32x4_t weight = vmovq_n_f32(pRouter->config.weights[iChannelIn][iChannelOut]); - ma_uint64 frameCount4 = frameCount/4; - for (ma_uint64 iFrame4 = 0; iFrame4 < frameCount4; iFrame4 += 1) { + ma_uint64 iFrame4; + + for (iFrame4 = 0; iFrame4 < frameCount4; iFrame4 += 1) { float32x4_t* pO = (float32x4_t*)ppSamplesOut[iChannelOut] + iFrame4; float32x4_t* pI = (float32x4_t*)ppSamplesIn [iChannelIn ] + iFrame4; *pO = vaddq_f32(*pO, vmulq_f32(*pI, weight)); @@ -27674,9 +28592,10 @@ void ma_channel_router__do_routing(ma_channel_router* pRouter, ma_uint64 frameCo #if defined(MA_SUPPORT_AVX512) if (ma_channel_router__can_use_avx512(pRouter, ppSamplesOut[iChannelOut], ppSamplesIn[iChannelIn])) { __m512 weight = _mm512_set1_ps(pRouter->config.weights[iChannelIn][iChannelOut]); - ma_uint64 frameCount16 = frameCount/16; - for (ma_uint64 iFrame16 = 0; iFrame16 < frameCount16; iFrame16 += 1) { + ma_uint64 iFrame16; + + for (iFrame16 = 0; iFrame16 < frameCount16; iFrame16 += 1) { __m512* pO = (__m512*)ppSamplesOut[iChannelOut] + iFrame16; __m512* pI = (__m512*)ppSamplesIn [iChannelIn ] + iFrame16; *pO = _mm512_add_ps(*pO, _mm512_mul_ps(*pI, weight)); @@ -27689,9 +28608,10 @@ void ma_channel_router__do_routing(ma_channel_router* pRouter, ma_uint64 frameCo #if defined(MA_SUPPORT_AVX2) if (ma_channel_router__can_use_avx2(pRouter, ppSamplesOut[iChannelOut], ppSamplesIn[iChannelIn])) { __m256 weight = _mm256_set1_ps(pRouter->config.weights[iChannelIn][iChannelOut]); - ma_uint64 frameCount8 = frameCount/8; - for (ma_uint64 iFrame8 = 0; iFrame8 < frameCount8; iFrame8 += 1) { + ma_uint64 iFrame8; + + for (iFrame8 = 0; iFrame8 < frameCount8; iFrame8 += 1) { __m256* pO = (__m256*)ppSamplesOut[iChannelOut] + iFrame8; __m256* pI = (__m256*)ppSamplesIn [iChannelIn ] + iFrame8; *pO = _mm256_add_ps(*pO, _mm256_mul_ps(*pI, weight)); @@ -27704,9 +28624,10 @@ void ma_channel_router__do_routing(ma_channel_router* pRouter, ma_uint64 frameCo #if defined(MA_SUPPORT_SSE2) if (ma_channel_router__can_use_sse2(pRouter, ppSamplesOut[iChannelOut], ppSamplesIn[iChannelIn])) { __m128 weight = _mm_set1_ps(pRouter->config.weights[iChannelIn][iChannelOut]); - ma_uint64 frameCount4 = frameCount/4; - for (ma_uint64 iFrame4 = 0; iFrame4 < frameCount4; iFrame4 += 1) { + ma_uint64 iFrame4; + + for (iFrame4 = 0; iFrame4 < frameCount4; iFrame4 += 1) { __m128* pO = (__m128*)ppSamplesOut[iChannelOut] + iFrame4; __m128* pI = (__m128*)ppSamplesIn [iChannelIn ] + iFrame4; *pO = _mm_add_ps(*pO, _mm_mul_ps(*pI, weight)); @@ -27715,14 +28636,15 @@ void ma_channel_router__do_routing(ma_channel_router* pRouter, ma_uint64 frameCo iFrame += frameCount4*4; } else #endif - { // Reference. + { /* Reference. */ float weight0 = pRouter->config.weights[iChannelIn][iChannelOut]; float weight1 = pRouter->config.weights[iChannelIn][iChannelOut]; float weight2 = pRouter->config.weights[iChannelIn][iChannelOut]; float weight3 = pRouter->config.weights[iChannelIn][iChannelOut]; - ma_uint64 frameCount4 = frameCount/4; - for (ma_uint64 iFrame4 = 0; iFrame4 < frameCount4; iFrame4 += 1) { + ma_uint64 iFrame4; + + for (iFrame4 = 0; iFrame4 < frameCount4; iFrame4 += 1) { ppSamplesOut[iChannelOut][iFrame+0] += ppSamplesIn[iChannelIn][iFrame+0] * weight0; ppSamplesOut[iChannelOut][iFrame+1] += ppSamplesIn[iChannelIn][iFrame+1] * weight1; ppSamplesOut[iChannelOut][iFrame+2] += ppSamplesIn[iChannelIn][iFrame+2] * weight2; @@ -27731,7 +28653,7 @@ void ma_channel_router__do_routing(ma_channel_router* pRouter, ma_uint64 frameCo } } - // Leftover. + /* Leftover. */ for (; iFrame < frameCount; ++iFrame) { ppSamplesOut[iChannelOut][iFrame] += ppSamplesIn[iChannelIn][iFrame] * pRouter->config.weights[iChannelIn][iChannelOut]; } @@ -27746,94 +28668,110 @@ ma_uint64 ma_channel_router_read_deinterleaved(ma_channel_router* pRouter, ma_ui return 0; } - // Fast path for a passthrough. + /* Fast path for a passthrough. */ if (pRouter->isPassthrough) { if (frameCount <= 0xFFFFFFFF) { return (ma_uint32)pRouter->config.onReadDeinterleaved(pRouter, (ma_uint32)frameCount, ppSamplesOut, pUserData); } else { float* ppNextSamplesOut[MA_MAX_CHANNELS]; + ma_uint64 totalFramesRead; + ma_copy_memory(ppNextSamplesOut, ppSamplesOut, sizeof(float*) * pRouter->config.channelsOut); - ma_uint64 totalFramesRead = 0; + totalFramesRead = 0; while (totalFramesRead < frameCount) { + ma_uint32 iChannel; + ma_uint32 framesJustRead; ma_uint64 framesRemaining = (frameCount - totalFramesRead); ma_uint64 framesToReadRightNow = framesRemaining; if (framesToReadRightNow > 0xFFFFFFFF) { framesToReadRightNow = 0xFFFFFFFF; } - ma_uint32 framesJustRead = (ma_uint32)pRouter->config.onReadDeinterleaved(pRouter, (ma_uint32)framesToReadRightNow, (void**)ppNextSamplesOut, pUserData); + framesJustRead = (ma_uint32)pRouter->config.onReadDeinterleaved(pRouter, (ma_uint32)framesToReadRightNow, (void**)ppNextSamplesOut, pUserData); if (framesJustRead == 0) { break; } totalFramesRead += framesJustRead; - for (ma_uint32 iChannel = 0; iChannel < pRouter->config.channelsOut; ++iChannel) { - ppNextSamplesOut[iChannel] += framesJustRead; - } if (framesJustRead < framesToReadRightNow) { break; } + + for (iChannel = 0; iChannel < pRouter->config.channelsOut; ++iChannel) { + ppNextSamplesOut[iChannel] += framesJustRead; + } } + + return totalFramesRead; } } - // Slower path for a non-passthrough. - float* ppNextSamplesOut[MA_MAX_CHANNELS]; - ma_copy_memory(ppNextSamplesOut, ppSamplesOut, sizeof(float*) * pRouter->config.channelsOut); - - MA_ALIGN(MA_SIMD_ALIGNMENT) float temp[MA_MAX_CHANNELS * 256]; - ma_assert(sizeof(temp) <= 0xFFFFFFFF); + /* Slower path for a non-passthrough. */ + { + float* ppNextSamplesOut[MA_MAX_CHANNELS]; + float* ppTemp[MA_MAX_CHANNELS]; + size_t maxBytesToReadPerFrameEachIteration; + size_t maxFramesToReadEachIteration; + ma_uint64 totalFramesRead; + MA_ALIGN(MA_SIMD_ALIGNMENT) float temp[MA_MAX_CHANNELS * 256]; + + ma_assert(sizeof(temp) <= 0xFFFFFFFF); + ma_copy_memory(ppNextSamplesOut, ppSamplesOut, sizeof(float*) * pRouter->config.channelsOut); + + + ma_split_buffer(temp, sizeof(temp), pRouter->config.channelsIn, MA_SIMD_ALIGNMENT, (void**)&ppTemp, &maxBytesToReadPerFrameEachIteration); - float* ppTemp[MA_MAX_CHANNELS]; - size_t maxBytesToReadPerFrameEachIteration; - ma_split_buffer(temp, sizeof(temp), pRouter->config.channelsIn, MA_SIMD_ALIGNMENT, (void**)&ppTemp, &maxBytesToReadPerFrameEachIteration); + maxFramesToReadEachIteration = maxBytesToReadPerFrameEachIteration/sizeof(float); - size_t maxFramesToReadEachIteration = maxBytesToReadPerFrameEachIteration/sizeof(float); + totalFramesRead = 0; + while (totalFramesRead < frameCount) { + ma_uint32 iChannel; + ma_uint32 framesJustRead; + ma_uint64 framesRemaining = (frameCount - totalFramesRead); + ma_uint64 framesToReadRightNow = framesRemaining; + if (framesToReadRightNow > maxFramesToReadEachIteration) { + framesToReadRightNow = maxFramesToReadEachIteration; + } - ma_uint64 totalFramesRead = 0; - while (totalFramesRead < frameCount) { - ma_uint64 framesRemaining = (frameCount - totalFramesRead); - ma_uint64 framesToReadRightNow = framesRemaining; - if (framesToReadRightNow > maxFramesToReadEachIteration) { - framesToReadRightNow = maxFramesToReadEachIteration; - } + framesJustRead = pRouter->config.onReadDeinterleaved(pRouter, (ma_uint32)framesToReadRightNow, (void**)ppTemp, pUserData); + if (framesJustRead == 0) { + break; + } - ma_uint32 framesJustRead = pRouter->config.onReadDeinterleaved(pRouter, (ma_uint32)framesToReadRightNow, (void**)ppTemp, pUserData); - if (framesJustRead == 0) { - break; - } + ma_channel_router__do_routing(pRouter, framesJustRead, (float**)ppNextSamplesOut, (const float**)ppTemp); /* <-- Real work is done here. */ - ma_channel_router__do_routing(pRouter, framesJustRead, (float**)ppNextSamplesOut, (const float**)ppTemp); // <-- Real work is done here. + totalFramesRead += framesJustRead; + if (totalFramesRead < frameCount) { + for (iChannel = 0; iChannel < pRouter->config.channelsIn; iChannel += 1) { + ppNextSamplesOut[iChannel] += framesJustRead; + } + } - totalFramesRead += framesJustRead; - if (totalFramesRead < frameCount) { - for (ma_uint32 iChannel = 0; iChannel < pRouter->config.channelsIn; iChannel += 1) { - ppNextSamplesOut[iChannel] += framesJustRead; + if (framesJustRead < framesToReadRightNow) { + break; } } - if (framesJustRead < framesToReadRightNow) { - break; - } + return totalFramesRead; } - - return totalFramesRead; } ma_channel_router_config ma_channel_router_config_init(ma_uint32 channelsIn, const ma_channel channelMapIn[MA_MAX_CHANNELS], ma_uint32 channelsOut, const ma_channel channelMapOut[MA_MAX_CHANNELS], ma_channel_mix_mode mixingMode, ma_channel_router_read_deinterleaved_proc onRead, void* pUserData) { ma_channel_router_config config; + ma_uint32 iChannel; + ma_zero_object(&config); config.channelsIn = channelsIn; - for (ma_uint32 iChannel = 0; iChannel < channelsIn; ++iChannel) { + for (iChannel = 0; iChannel < channelsIn; ++iChannel) { config.channelMapIn[iChannel] = channelMapIn[iChannel]; } config.channelsOut = channelsOut; - for (ma_uint32 iChannel = 0; iChannel < channelsOut; ++iChannel) { + for (iChannel = 0; iChannel < channelsOut; ++iChannel) { config.channelMapOut[iChannel] = channelMapOut[iChannel]; } @@ -27846,12 +28784,11 @@ ma_channel_router_config ma_channel_router_config_init(ma_uint32 channelsIn, con -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// SRC -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +/************************************************************************************************************************************************************** + +SRC +**************************************************************************************************************************************************************/ #define ma_floorf(x) ((float)floor((double)(x))) #define ma_sinf(x) ((float)sin((double)(x))) #define ma_cosf(x) ((float)cos((double)(x))) @@ -27874,10 +28811,12 @@ ma_uint64 ma_src_read_deinterleaved__sinc(ma_src* pSRC, ma_uint64 frameCount, vo void ma_src__build_sinc_table__sinc(ma_src* pSRC) { + ma_uint32 i; + ma_assert(pSRC != NULL); pSRC->sinc.table[0] = 1.0f; - for (ma_uint32 i = 1; i < ma_countof(pSRC->sinc.table); i += 1) { + for (i = 1; i < ma_countof(pSRC->sinc.table); i += 1) { double x = i*MA_PI_D / MA_SRC_SINC_LOOKUP_TABLE_RESOLUTION; pSRC->sinc.table[i] = (float)(sin(x)/x); } @@ -27885,15 +28824,17 @@ void ma_src__build_sinc_table__sinc(ma_src* pSRC) void ma_src__build_sinc_table__rectangular(ma_src* pSRC) { - // This is the same as the base sinc table. + /* This is the same as the base sinc table. */ ma_src__build_sinc_table__sinc(pSRC); } void ma_src__build_sinc_table__hann(ma_src* pSRC) { + ma_uint32 i; + ma_src__build_sinc_table__sinc(pSRC); - for (ma_uint32 i = 0; i < ma_countof(pSRC->sinc.table); i += 1) { + for (i = 0; i < ma_countof(pSRC->sinc.table); i += 1) { double x = pSRC->sinc.table[i]; double N = MA_SRC_SINC_MAX_WINDOW_WIDTH*2; double n = ((double)(i) / MA_SRC_SINC_LOOKUP_TABLE_RESOLUTION) + MA_SRC_SINC_MAX_WINDOW_WIDTH; @@ -27920,14 +28861,14 @@ ma_result ma_src_init(const ma_src_config* pConfig, ma_src* pSRC) pSRC->config = *pConfig; - // SIMD + /* SIMD */ pSRC->useSSE2 = ma_has_sse2() && !pConfig->noSSE2; pSRC->useAVX2 = ma_has_avx2() && !pConfig->noAVX2; pSRC->useAVX512 = ma_has_avx512f() && !pConfig->noAVX512; pSRC->useNEON = ma_has_neon() && !pConfig->noNEON; if (pSRC->config.algorithm == ma_src_algorithm_sinc) { - // Make sure the window width within bounds. + /* Make sure the window width within bounds. */ if (pSRC->config.sinc.windowWidth == 0) { pSRC->config.sinc.windowWidth = MA_SRC_SINC_DEFAULT_WINDOW_WIDTH; } @@ -27938,11 +28879,11 @@ ma_result ma_src_init(const ma_src_config* pConfig, ma_src* pSRC) pSRC->config.sinc.windowWidth = MA_SRC_SINC_MAX_WINDOW_WIDTH; } - // Set up the lookup table. + /* Set up the lookup table. */ switch (pSRC->config.sinc.windowFunction) { case ma_src_sinc_window_function_hann: ma_src__build_sinc_table__hann(pSRC); break; case ma_src_sinc_window_function_rectangular: ma_src__build_sinc_table__rectangular(pSRC); break; - default: return MA_INVALID_ARGS; // <-- Hitting this means the window function is unknown to miniaudio. + default: return MA_INVALID_ARGS; /* <-- Hitting this means the window function is unknown to miniaudio. */ } } @@ -27955,7 +28896,7 @@ ma_result ma_src_set_sample_rate(ma_src* pSRC, ma_uint32 sampleRateIn, ma_uint32 return MA_INVALID_ARGS; } - // Must have a sample rate of > 0. + /* Must have a sample rate of > 0. */ if (sampleRateIn == 0 || sampleRateOut == 0) { return MA_INVALID_ARGS; } @@ -27968,13 +28909,15 @@ ma_result ma_src_set_sample_rate(ma_src* pSRC, ma_uint32 sampleRateIn, ma_uint32 ma_uint64 ma_src_read_deinterleaved(ma_src* pSRC, ma_uint64 frameCount, void** ppSamplesOut, void* pUserData) { + ma_src_algorithm algorithm; + if (pSRC == NULL || frameCount == 0 || ppSamplesOut == NULL) { return 0; } - ma_src_algorithm algorithm = pSRC->config.algorithm; + algorithm = pSRC->config.algorithm; - // Can use a function pointer for this. + /* Can use a function pointer for this. */ switch (algorithm) { case ma_src_algorithm_none: return ma_src_read_deinterleaved__passthrough(pSRC, frameCount, ppSamplesOut, pUserData); case ma_src_algorithm_linear: return ma_src_read_deinterleaved__linear( pSRC, frameCount, ppSamplesOut, pUserData); @@ -27982,7 +28925,7 @@ ma_uint64 ma_src_read_deinterleaved(ma_src* pSRC, ma_uint64 frameCount, void** p default: break; } - // Should never get here. + /* Should never get here. */ return 0; } @@ -27991,26 +28934,30 @@ ma_uint64 ma_src_read_deinterleaved__passthrough(ma_src* pSRC, ma_uint64 frameCo if (frameCount <= 0xFFFFFFFF) { return pSRC->config.onReadDeinterleaved(pSRC, (ma_uint32)frameCount, ppSamplesOut, pUserData); } else { + ma_uint32 iChannel; + ma_uint64 totalFramesRead; float* ppNextSamplesOut[MA_MAX_CHANNELS]; - for (ma_uint32 iChannel = 0; iChannel < pSRC->config.channels; ++iChannel) { + + for (iChannel = 0; iChannel < pSRC->config.channels; ++iChannel) { ppNextSamplesOut[iChannel] = (float*)ppSamplesOut[iChannel]; } - ma_uint64 totalFramesRead = 0; + totalFramesRead = 0; while (totalFramesRead < frameCount) { + ma_uint32 framesJustRead; ma_uint64 framesRemaining = frameCount - totalFramesRead; ma_uint64 framesToReadRightNow = framesRemaining; if (framesToReadRightNow > 0xFFFFFFFF) { framesToReadRightNow = 0xFFFFFFFF; } - ma_uint32 framesJustRead = (ma_uint32)pSRC->config.onReadDeinterleaved(pSRC, (ma_uint32)framesToReadRightNow, (void**)ppNextSamplesOut, pUserData); + framesJustRead = (ma_uint32)pSRC->config.onReadDeinterleaved(pSRC, (ma_uint32)framesToReadRightNow, (void**)ppNextSamplesOut, pUserData); if (framesJustRead == 0) { break; } totalFramesRead += framesJustRead; - for (ma_uint32 iChannel = 0; iChannel < pSRC->config.channels; ++iChannel) { + for (iChannel = 0; iChannel < pSRC->config.channels; ++iChannel) { ppNextSamplesOut[iChannel] += framesJustRead; } @@ -28025,65 +28972,77 @@ ma_uint64 ma_src_read_deinterleaved__passthrough(ma_src* pSRC, ma_uint64 frameCo ma_uint64 ma_src_read_deinterleaved__linear(ma_src* pSRC, ma_uint64 frameCount, void** ppSamplesOut, void* pUserData) { + float* ppNextSamplesOut[MA_MAX_CHANNELS]; + float factor; + ma_uint32 maxFrameCountPerChunkIn; + ma_uint64 totalFramesRead; + ma_assert(pSRC != NULL); ma_assert(frameCount > 0); ma_assert(ppSamplesOut != NULL); - - float* ppNextSamplesOut[MA_MAX_CHANNELS]; + ma_copy_memory(ppNextSamplesOut, ppSamplesOut, sizeof(void*) * pSRC->config.channels); + factor = (float)pSRC->config.sampleRateIn / pSRC->config.sampleRateOut; + maxFrameCountPerChunkIn = ma_countof(pSRC->linear.input[0]); - float factor = (float)pSRC->config.sampleRateIn / pSRC->config.sampleRateOut; - - ma_uint32 maxFrameCountPerChunkIn = ma_countof(pSRC->linear.input[0]); - - ma_uint64 totalFramesRead = 0; + totalFramesRead = 0; while (totalFramesRead < frameCount) { + ma_uint32 iChannel; + float tBeg; + float tEnd; + float tAvailable; + float tNext; + float* ppSamplesFromClient[MA_MAX_CHANNELS]; + ma_uint32 iNextFrame; + ma_uint32 maxOutputFramesToRead; + ma_uint32 maxOutputFramesToRead4; + ma_uint32 framesToReadFromClient; + ma_uint32 framesReadFromClient; ma_uint64 framesRemaining = frameCount - totalFramesRead; ma_uint64 framesToRead = framesRemaining; if (framesToRead > 16384) { - framesToRead = 16384; // <-- Keep this small because we're using 32-bit floats for calculating sample positions and I don't want to run out of precision with huge sample counts. + framesToRead = 16384; /* <-- Keep this small because we're using 32-bit floats for calculating sample positions and I don't want to run out of precision with huge sample counts. */ } - // Read Input Data - // =============== - float tBeg = pSRC->linear.timeIn; - float tEnd = tBeg + (framesToRead*factor); + /* Read Input Data */ + tBeg = pSRC->linear.timeIn; + tEnd = tBeg + ((ma_int64)framesToRead*factor); /* Cast to int64 required for VC6. */ - ma_uint32 framesToReadFromClient = (ma_uint32)(tEnd) + 1 + 1; // +1 to make tEnd 1-based and +1 because we always need to an extra sample for interpolation. + framesToReadFromClient = (ma_uint32)(tEnd) + 1 + 1; /* +1 to make tEnd 1-based and +1 because we always need to an extra sample for interpolation. */ if (framesToReadFromClient >= maxFrameCountPerChunkIn) { framesToReadFromClient = maxFrameCountPerChunkIn; } - float* ppSamplesFromClient[MA_MAX_CHANNELS]; - for (ma_uint32 iChannel = 0; iChannel < pSRC->config.channels; ++iChannel) { + for (iChannel = 0; iChannel < pSRC->config.channels; ++iChannel) { ppSamplesFromClient[iChannel] = pSRC->linear.input[iChannel] + pSRC->linear.leftoverFrames; } - ma_uint32 framesReadFromClient = 0; + framesReadFromClient = 0; if (framesToReadFromClient > pSRC->linear.leftoverFrames) { framesReadFromClient = (ma_uint32)pSRC->config.onReadDeinterleaved(pSRC, (ma_uint32)framesToReadFromClient - pSRC->linear.leftoverFrames, (void**)ppSamplesFromClient, pUserData); } - framesReadFromClient += pSRC->linear.leftoverFrames; // <-- You can sort of think of it as though we've re-read the leftover samples from the client. + framesReadFromClient += pSRC->linear.leftoverFrames; /* <-- You can sort of think of it as though we've re-read the leftover samples from the client. */ if (framesReadFromClient < 2) { break; } - for (ma_uint32 iChannel = 0; iChannel < pSRC->config.channels; ++iChannel) { + for (iChannel = 0; iChannel < pSRC->config.channels; ++iChannel) { ppSamplesFromClient[iChannel] = pSRC->linear.input[iChannel]; } - // Write Output Data - // ================= + /* Write Output Data */ - // At this point we have a bunch of frames that the client has given to us for processing. From this we can determine the maximum number of output frames - // that can be processed from this input. We want to output as many samples as possible from our input data. - float tAvailable = framesReadFromClient - tBeg - 1; // Subtract 1 because the last input sample is needed for interpolation and cannot be included in the output sample count calculation. + /* + At this point we have a bunch of frames that the client has given to us for processing. From this we can determine the maximum number of output frames + that can be processed from this input. We want to output as many samples as possible from our input data. + */ + tAvailable = framesReadFromClient - tBeg - 1; /* Subtract 1 because the last input sample is needed for interpolation and cannot be included in the output sample count calculation. */ - ma_uint32 maxOutputFramesToRead = (ma_uint32)(tAvailable / factor); + maxOutputFramesToRead = (ma_uint32)(tAvailable / factor); if (maxOutputFramesToRead == 0) { maxOutputFramesToRead = 1; } @@ -28091,15 +29050,17 @@ ma_uint64 ma_src_read_deinterleaved__linear(ma_src* pSRC, ma_uint64 frameCount, maxOutputFramesToRead = (ma_uint32)framesToRead; } - // Output frames are always read in groups of 4 because I'm planning on using this as a reference for some SIMD-y stuff later. - ma_uint32 maxOutputFramesToRead4 = maxOutputFramesToRead/4; - for (ma_uint32 iChannel = 0; iChannel < pSRC->config.channels; ++iChannel) { + /* Output frames are always read in groups of 4 because I'm planning on using this as a reference for some SIMD-y stuff later. */ + maxOutputFramesToRead4 = maxOutputFramesToRead/4; + for (iChannel = 0; iChannel < pSRC->config.channels; ++iChannel) { + ma_uint32 iFrameOut; float t0 = pSRC->linear.timeIn + factor*0; float t1 = pSRC->linear.timeIn + factor*1; float t2 = pSRC->linear.timeIn + factor*2; float t3 = pSRC->linear.timeIn + factor*3; - - for (ma_uint32 iFrameOut = 0; iFrameOut < maxOutputFramesToRead4; iFrameOut += 1) { + float t; + + for (iFrameOut = 0; iFrameOut < maxOutputFramesToRead4; iFrameOut += 1) { float iPrevSample0 = (float)floor(t0); float iPrevSample1 = (float)floor(t1); float iPrevSample2 = (float)floor(t2); @@ -28136,17 +29097,19 @@ ma_uint64 ma_src_read_deinterleaved__linear(ma_src* pSRC, ma_uint64 frameCount, t3 += factor*4; } - float t = pSRC->linear.timeIn + (factor*maxOutputFramesToRead4*4); - for (ma_uint32 iFrameOut = (maxOutputFramesToRead4*4); iFrameOut < maxOutputFramesToRead; iFrameOut += 1) { + t = pSRC->linear.timeIn + (factor*maxOutputFramesToRead4*4); + for (iFrameOut = (maxOutputFramesToRead4*4); iFrameOut < maxOutputFramesToRead; iFrameOut += 1) { float iPrevSample = (float)floor(t); float iNextSample = iPrevSample + 1; float alpha = t - iPrevSample; + float prevSample; + float nextSample; ma_assert(iPrevSample < ma_countof(pSRC->linear.input[iChannel])); ma_assert(iNextSample < ma_countof(pSRC->linear.input[iChannel])); - float prevSample = ppSamplesFromClient[iChannel][(ma_uint32)iPrevSample]; - float nextSample = ppSamplesFromClient[iChannel][(ma_uint32)iNextSample]; + prevSample = ppSamplesFromClient[iChannel][(ma_uint32)iPrevSample]; + nextSample = ppSamplesFromClient[iChannel][(ma_uint32)iNextSample]; ppNextSamplesOut[iChannel][iFrameOut] = ma_mix_f32_fast(prevSample, nextSample, alpha); @@ -28159,26 +29122,26 @@ ma_uint64 ma_src_read_deinterleaved__linear(ma_src* pSRC, ma_uint64 frameCount, totalFramesRead += maxOutputFramesToRead; - // Residual - // ======== - float tNext = pSRC->linear.timeIn + (maxOutputFramesToRead*factor); + /* Residual */ + tNext = pSRC->linear.timeIn + (maxOutputFramesToRead*factor); pSRC->linear.timeIn = tNext; ma_assert(tNext <= framesReadFromClient+1); - ma_uint32 iNextFrame = (ma_uint32)floor(tNext); + iNextFrame = (ma_uint32)floor(tNext); pSRC->linear.leftoverFrames = framesReadFromClient - iNextFrame; pSRC->linear.timeIn = tNext - iNextFrame; - for (ma_uint32 iChannel = 0; iChannel < pSRC->config.channels; ++iChannel) { - for (ma_uint32 iFrame = 0; iFrame < pSRC->linear.leftoverFrames; ++iFrame) { + for (iChannel = 0; iChannel < pSRC->config.channels; ++iChannel) { + ma_uint32 iFrame; + for (iFrame = 0; iFrame < pSRC->linear.leftoverFrames; ++iFrame) { float sample = ppSamplesFromClient[iChannel][framesReadFromClient-pSRC->linear.leftoverFrames + iFrame]; ppSamplesFromClient[iChannel][iFrame] = sample; } } - // Exit the loop if we've found everything from the client. + /* Exit the loop if we've found everything from the client. */ if (framesReadFromClient < framesToReadFromClient) { break; } @@ -28209,37 +29172,37 @@ ma_src_config ma_src_config_init(ma_uint32 sampleRateIn, ma_uint32 sampleRateOut } -/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Sinc Sample Rate Conversion -// =========================== -// -// The sinc SRC algorithm uses a windowed sinc to perform interpolation of samples. Currently, miniaudio's implementation supports rectangular and Hann window -// methods. -// -// Whenever an output sample is being computed, it looks at a sub-section of the input samples. I've called this sub-section in the code below the "window", -// which I realize is a bit ambigous with the mathematical "window", but it works for me when I need to conceptualize things in my head. The window is made up -// of two halves. The first half contains past input samples (initialized to zero), and the second half contains future input samples. As time moves forward -// and input samples are consumed, the window moves forward. The larger the window, the better the quality at the expense of slower processing. The window is -// limited the range [MA_SRC_SINC_MIN_WINDOW_WIDTH, MA_SRC_SINC_MAX_WINDOW_WIDTH] and defaults to MA_SRC_SINC_DEFAULT_WINDOW_WIDTH. -// -// Input samples are cached for efficiency (to prevent frequently requesting tiny numbers of samples from the client). When the window gets to the end of the -// cache, it's moved back to the start, and more samples are read from the client. If the client has no more data to give, the cache is filled with zeros and -// the last of the input samples will be consumed. Once the last of the input samples have been consumed, no more samples will be output. -// -// -// When reading output samples, we always first read whatever is already in the input cache. Only when the cache has been fully consumed do we read more data -// from the client. -// -// To access samples in the input buffer you do so relative to the window. When the window itself is at position 0, the first item in the buffer is accessed -// with "windowPos + windowWidth". Generally, to access any sample relative to the window you do "windowPos + windowWidth + sampleIndexRelativeToWindow". -// -/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -// Comment this to disable interpolation of table lookups. Less accurate, but faster. +/************************************************************************************************************************************************************** + +Sinc Sample Rate Conversion +=========================== + +The sinc SRC algorithm uses a windowed sinc to perform interpolation of samples. Currently, miniaudio's implementation supports rectangular and Hann window +methods. + +Whenever an output sample is being computed, it looks at a sub-section of the input samples. I've called this sub-section in the code below the "window", +which I realize is a bit ambigous with the mathematical "window", but it works for me when I need to conceptualize things in my head. The window is made up +of two halves. The first half contains past input samples (initialized to zero), and the second half contains future input samples. As time moves forward +and input samples are consumed, the window moves forward. The larger the window, the better the quality at the expense of slower processing. The window is +limited the range [MA_SRC_SINC_MIN_WINDOW_WIDTH, MA_SRC_SINC_MAX_WINDOW_WIDTH] and defaults to MA_SRC_SINC_DEFAULT_WINDOW_WIDTH. + +Input samples are cached for efficiency (to prevent frequently requesting tiny numbers of samples from the client). When the window gets to the end of the +cache, it's moved back to the start, and more samples are read from the client. If the client has no more data to give, the cache is filled with zeros and +the last of the input samples will be consumed. Once the last of the input samples have been consumed, no more samples will be output. + + +When reading output samples, we always first read whatever is already in the input cache. Only when the cache has been fully consumed do we read more data +from the client. + +To access samples in the input buffer you do so relative to the window. When the window itself is at position 0, the first item in the buffer is accessed +with "windowPos + windowWidth". Generally, to access any sample relative to the window you do "windowPos + windowWidth + sampleIndexRelativeToWindow". + +**************************************************************************************************************************************************************/ + +/* Comment this to disable interpolation of table lookups. Less accurate, but faster. */ #define MA_USE_SINC_TABLE_INTERPOLATION -// Retrieves a sample from the input buffer's window. Values >= 0 retrieve future samples. Negative values return past samples. +/* Retrieves a sample from the input buffer's window. Values >= 0 retrieve future samples. Negative values return past samples. */ static MA_INLINE float ma_src_sinc__get_input_sample_from_window(const ma_src* pSRC, ma_uint32 channel, ma_uint32 windowPosInSamples, ma_int32 sampleIndex) { ma_assert(pSRC != NULL); @@ -28247,7 +29210,7 @@ static MA_INLINE float ma_src_sinc__get_input_sample_from_window(const ma_src* p ma_assert(sampleIndex >= -(ma_int32)pSRC->config.sinc.windowWidth); ma_assert(sampleIndex < (ma_int32)pSRC->config.sinc.windowWidth); - // The window should always be contained within the input cache. + /* The window should always be contained within the input cache. */ ma_assert(windowPosInSamples < ma_countof(pSRC->sinc.input[0]) - pSRC->config.sinc.windowWidth); return pSRC->sinc.input[channel][windowPosInSamples + pSRC->config.sinc.windowWidth + sampleIndex]; @@ -28255,19 +29218,20 @@ static MA_INLINE float ma_src_sinc__get_input_sample_from_window(const ma_src* p static MA_INLINE float ma_src_sinc__interpolation_factor(const ma_src* pSRC, float x) { - ma_assert(pSRC != NULL); + float xabs; + ma_int32 ixabs; - float xabs = (float)fabs(x); - //if (xabs >= MA_SRC_SINC_MAX_WINDOW_WIDTH /*pSRC->config.sinc.windowWidth*/) { - // xabs = 1; // <-- A non-zero integer will always return 0. - //} + ma_assert(pSRC != NULL); - xabs = xabs * MA_SRC_SINC_LOOKUP_TABLE_RESOLUTION; - ma_int32 ixabs = (ma_int32)xabs; + xabs = (float)fabs(x); + xabs = xabs * MA_SRC_SINC_LOOKUP_TABLE_RESOLUTION; + ixabs = (ma_int32)xabs; #if defined(MA_USE_SINC_TABLE_INTERPOLATION) - float a = xabs - ixabs; - return ma_mix_f32_fast(pSRC->sinc.table[ixabs], pSRC->sinc.table[ixabs+1], a); + { + float a = xabs - ixabs; + return ma_mix_f32_fast(pSRC->sinc.table[ixabs], pSRC->sinc.table[ixabs+1], a); + } #else return pSRC->sinc.table[ixabs]; #endif @@ -28286,37 +29250,38 @@ static MA_INLINE __m128 ma_truncf_sse2(__m128 x) static MA_INLINE __m128 ma_src_sinc__interpolation_factor__sse2(const ma_src* pSRC, __m128 x) { - //__m128 windowWidth128 = _mm_set1_ps(MA_SRC_SINC_MAX_WINDOW_WIDTH); - __m128 resolution128 = _mm_set1_ps(MA_SRC_SINC_LOOKUP_TABLE_RESOLUTION); - //__m128 one = _mm_set1_ps(1); + __m128 resolution128; + __m128 xabs; + __m128i ixabs; + __m128 lo; + __m128 hi; + __m128 a; + __m128 r; + int* ixabsv; - __m128 xabs = ma_fabsf_sse2(x); + resolution128 = _mm_set1_ps(MA_SRC_SINC_LOOKUP_TABLE_RESOLUTION); + xabs = ma_fabsf_sse2(x); + xabs = _mm_mul_ps(xabs, resolution128); + ixabs = _mm_cvttps_epi32(xabs); - // if (MA_SRC_SINC_MAX_WINDOW_WIDTH <= xabs) xabs = 1 else xabs = xabs; - //__m128 xcmp = _mm_cmp_ps(windowWidth128, xabs, 2); // 2 = Less than or equal = _mm_cmple_ps. - //xabs = _mm_or_ps(_mm_and_ps(one, xcmp), _mm_andnot_ps(xcmp, xabs)); // xabs = (xcmp) ? 1 : xabs; - - xabs = _mm_mul_ps(xabs, resolution128); - __m128i ixabs = _mm_cvttps_epi32(xabs); - - int* ixabsv = (int*)&ixabs; + ixabsv = (int*)&ixabs; - __m128 lo = _mm_set_ps( + lo = _mm_set_ps( pSRC->sinc.table[ixabsv[3]], pSRC->sinc.table[ixabsv[2]], pSRC->sinc.table[ixabsv[1]], pSRC->sinc.table[ixabsv[0]] ); - __m128 hi = _mm_set_ps( + hi = _mm_set_ps( pSRC->sinc.table[ixabsv[3]+1], pSRC->sinc.table[ixabsv[2]+1], pSRC->sinc.table[ixabsv[1]+1], pSRC->sinc.table[ixabsv[0]+1] ); - __m128 a = _mm_sub_ps(xabs, _mm_cvtepi32_ps(ixabs)); - __m128 r = ma_mix_f32_fast__sse2(lo, hi, a); + a = _mm_sub_ps(xabs, _mm_cvtepi32_ps(ixabs)); + r = ma_mix_f32_fast__sse2(lo, hi, a); return r; } @@ -28331,16 +29296,9 @@ static MA_INLINE __m256 ma_fabsf_avx2(__m256 x) #if 0 static MA_INLINE __m256 ma_src_sinc__interpolation_factor__avx2(const ma_src* pSRC, __m256 x) { - //__m256 windowWidth256 = _mm256_set1_ps(MA_SRC_SINC_MAX_WINDOW_WIDTH); __m256 resolution256 = _mm256_set1_ps(MA_SRC_SINC_LOOKUP_TABLE_RESOLUTION); - //__m256 one = _mm256_set1_ps(1); - __m256 xabs = ma_fabsf_avx2(x); - // if (MA_SRC_SINC_MAX_WINDOW_WIDTH <= xabs) xabs = 1 else xabs = xabs; - //__m256 xcmp = _mm256_cmp_ps(windowWidth256, xabs, 2); // 2 = Less than or equal = _mm_cmple_ps. - //xabs = _mm256_or_ps(_mm256_and_ps(one, xcmp), _mm256_andnot_ps(xcmp, xabs)); // xabs = (xcmp) ? 1 : xabs; - xabs = _mm256_mul_ps(xabs, resolution256); __m256i ixabs = _mm256_cvttps_epi32(xabs); @@ -28387,27 +29345,32 @@ static MA_INLINE float32x4_t ma_fabsf_neon(float32x4_t x) static MA_INLINE float32x4_t ma_src_sinc__interpolation_factor__neon(const ma_src* pSRC, float32x4_t x) { - float32x4_t xabs = ma_fabsf_neon(x); - xabs = vmulq_n_f32(xabs, MA_SRC_SINC_LOOKUP_TABLE_RESOLUTION); + float32x4_t xabs; + int32x4_t ixabs; + float32x4_t a + float32x4_t r + int* ixabsv; + float lo[4]; + float hi[4]; - int32x4_t ixabs = vcvtq_s32_f32(xabs); + xabs = ma_fabsf_neon(x); + xabs = vmulq_n_f32(xabs, MA_SRC_SINC_LOOKUP_TABLE_RESOLUTION); + ixabs = vcvtq_s32_f32(xabs); + + ixabsv = (int*)&ixabs; - int* ixabsv = (int*)&ixabs; - - float lo[4]; lo[0] = pSRC->sinc.table[ixabsv[0]]; lo[1] = pSRC->sinc.table[ixabsv[1]]; lo[2] = pSRC->sinc.table[ixabsv[2]]; lo[3] = pSRC->sinc.table[ixabsv[3]]; - float hi[4]; hi[0] = pSRC->sinc.table[ixabsv[0]+1]; hi[1] = pSRC->sinc.table[ixabsv[1]+1]; hi[2] = pSRC->sinc.table[ixabsv[2]+1]; hi[3] = pSRC->sinc.table[ixabsv[3]+1]; - float32x4_t a = vsubq_f32(xabs, vcvtq_f32_s32(ixabs)); - float32x4_t r = ma_mix_f32_fast__neon(vld1q_f32(lo), vld1q_f32(hi), a); + a = vsubq_f32(xabs, vcvtq_f32_s32(ixabs)); + r = ma_mix_f32_fast__neon(vld1q_f32(lo), vld1q_f32(hi), a); return r; } @@ -28415,19 +29378,35 @@ static MA_INLINE float32x4_t ma_src_sinc__interpolation_factor__neon(const ma_sr ma_uint64 ma_src_read_deinterleaved__sinc(ma_src* pSRC, ma_uint64 frameCount, void** ppSamplesOut, void* pUserData) { + float factor; + float inverseFactor; + ma_int32 windowWidth; + ma_int32 windowWidth2; + ma_int32 windowWidthSIMD; + ma_int32 windowWidthSIMD2; + float* ppNextSamplesOut[MA_MAX_CHANNELS]; + float _windowSamplesUnaligned[MA_SRC_SINC_MAX_WINDOW_WIDTH*2 + MA_SIMD_ALIGNMENT]; + float* windowSamples; + float _iWindowFUnaligned[MA_SRC_SINC_MAX_WINDOW_WIDTH*2 + MA_SIMD_ALIGNMENT]; + float* iWindowF; + ma_int32 i; + ma_uint64 totalOutputFramesRead; + ma_assert(pSRC != NULL); ma_assert(frameCount > 0); ma_assert(ppSamplesOut != NULL); - float factor = (float)pSRC->config.sampleRateIn / pSRC->config.sampleRateOut; - float inverseFactor = 1/factor; + factor = (float)pSRC->config.sampleRateIn / pSRC->config.sampleRateOut; + inverseFactor = 1/factor; - ma_int32 windowWidth = (ma_int32)pSRC->config.sinc.windowWidth; - ma_int32 windowWidth2 = windowWidth*2; + windowWidth = (ma_int32)pSRC->config.sinc.windowWidth; + windowWidth2 = windowWidth*2; - // There are cases where it's actually more efficient to increase the window width so that it's aligned with the respective - // SIMD pipeline being used. - ma_int32 windowWidthSIMD = windowWidth; + /* + There are cases where it's actually more efficient to increase the window width so that it's aligned with the respective + SIMD pipeline being used. + */ + windowWidthSIMD = windowWidth; if (pSRC->useNEON) { windowWidthSIMD = (windowWidthSIMD + 1) & ~(1); } else if (pSRC->useAVX512) { @@ -28438,33 +29417,43 @@ ma_uint64 ma_src_read_deinterleaved__sinc(ma_src* pSRC, ma_uint64 frameCount, vo windowWidthSIMD = (windowWidthSIMD + 1) & ~(1); } - ma_int32 windowWidthSIMD2 = windowWidthSIMD*2; - (void)windowWidthSIMD2; // <-- Silence a warning when SIMD is disabled. + windowWidthSIMD2 = windowWidthSIMD*2; + (void)windowWidthSIMD2; /* <-- Silence a warning when SIMD is disabled. */ - float* ppNextSamplesOut[MA_MAX_CHANNELS]; ma_copy_memory(ppNextSamplesOut, ppSamplesOut, sizeof(void*) * pSRC->config.channels); - float _windowSamplesUnaligned[MA_SRC_SINC_MAX_WINDOW_WIDTH*2 + MA_SIMD_ALIGNMENT]; - float* windowSamples = (float*)(((ma_uintptr)_windowSamplesUnaligned + MA_SIMD_ALIGNMENT-1) & ~(MA_SIMD_ALIGNMENT-1)); + windowSamples = (float*)(((ma_uintptr)_windowSamplesUnaligned + MA_SIMD_ALIGNMENT-1) & ~(MA_SIMD_ALIGNMENT-1)); ma_zero_memory(windowSamples, MA_SRC_SINC_MAX_WINDOW_WIDTH*2 * sizeof(float)); - float _iWindowFUnaligned[MA_SRC_SINC_MAX_WINDOW_WIDTH*2 + MA_SIMD_ALIGNMENT]; - float* iWindowF = (float*)(((ma_uintptr)_iWindowFUnaligned + MA_SIMD_ALIGNMENT-1) & ~(MA_SIMD_ALIGNMENT-1)); + iWindowF = (float*)(((ma_uintptr)_iWindowFUnaligned + MA_SIMD_ALIGNMENT-1) & ~(MA_SIMD_ALIGNMENT-1)); ma_zero_memory(iWindowF, MA_SRC_SINC_MAX_WINDOW_WIDTH*2 * sizeof(float)); - for (ma_int32 i = 0; i < windowWidth2; ++i) { + + for (i = 0; i < windowWidth2; ++i) { iWindowF[i] = (float)(i - windowWidth); } - ma_uint64 totalOutputFramesRead = 0; + totalOutputFramesRead = 0; while (totalOutputFramesRead < frameCount) { - // The maximum number of frames we can read this iteration depends on how many input samples we have available to us. This is the number - // of input samples between the end of the window and the end of the cache. - ma_uint32 maxInputSamplesAvailableInCache = ma_countof(pSRC->sinc.input[0]) - (pSRC->config.sinc.windowWidth*2) - pSRC->sinc.windowPosInSamples; + ma_uint32 maxInputSamplesAvailableInCache; + float timeInBeg; + float timeInEnd; + ma_uint64 maxOutputFramesToRead; + ma_uint64 outputFramesRemaining; + ma_uint64 outputFramesToRead; + ma_uint32 iChannel; + ma_uint32 prevWindowPosInSamples; + ma_uint32 availableOutputFrames; + + /* + The maximum number of frames we can read this iteration depends on how many input samples we have available to us. This is the number + of input samples between the end of the window and the end of the cache. + */ + maxInputSamplesAvailableInCache = ma_countof(pSRC->sinc.input[0]) - (pSRC->config.sinc.windowWidth*2) - pSRC->sinc.windowPosInSamples; if (maxInputSamplesAvailableInCache > pSRC->sinc.inputFrameCount) { maxInputSamplesAvailableInCache = pSRC->sinc.inputFrameCount; } - // Never consume the tail end of the input data if requested. + /* Never consume the tail end of the input data if requested. */ if (pSRC->config.neverConsumeEndOfInput) { if (maxInputSamplesAvailableInCache >= pSRC->config.sinc.windowWidth) { maxInputSamplesAvailableInCache -= pSRC->config.sinc.windowWidth; @@ -28473,33 +29462,34 @@ ma_uint64 ma_src_read_deinterleaved__sinc(ma_src* pSRC, ma_uint64 frameCount, vo } } - float timeInBeg = pSRC->sinc.timeIn; - float timeInEnd = (float)(pSRC->sinc.windowPosInSamples + maxInputSamplesAvailableInCache); + timeInBeg = pSRC->sinc.timeIn; + timeInEnd = (float)(pSRC->sinc.windowPosInSamples + maxInputSamplesAvailableInCache); ma_assert(timeInBeg >= 0); ma_assert(timeInBeg <= timeInEnd); - ma_uint64 maxOutputFramesToRead = (ma_uint64)(((timeInEnd - timeInBeg) * inverseFactor)); + maxOutputFramesToRead = (ma_uint64)(((timeInEnd - timeInBeg) * inverseFactor)); - ma_uint64 outputFramesRemaining = frameCount - totalOutputFramesRead; - ma_uint64 outputFramesToRead = outputFramesRemaining; + outputFramesRemaining = frameCount - totalOutputFramesRead; + outputFramesToRead = outputFramesRemaining; if (outputFramesToRead > maxOutputFramesToRead) { outputFramesToRead = maxOutputFramesToRead; } - for (ma_uint32 iChannel = 0; iChannel < pSRC->config.channels; iChannel += 1) { - // Do SRC. + for (iChannel = 0; iChannel < pSRC->config.channels; iChannel += 1) { + /* Do SRC. */ float timeIn = timeInBeg; - for (ma_uint32 iSample = 0; iSample < outputFramesToRead; iSample += 1) { - float sampleOut = 0; - float iTimeInF = ma_floorf(timeIn); + ma_uint32 iSample; + for (iSample = 0; iSample < outputFramesToRead; iSample += 1) { + float sampleOut = 0; + float iTimeInF = ma_floorf(timeIn); ma_uint32 iTimeIn = (ma_uint32)iTimeInF; - ma_int32 iWindow = 0; + float tScalar; - // Pre-load the window samples into an aligned buffer to begin with. Need to put these into an aligned buffer to make SIMD easier. - windowSamples[0] = 0; // <-- The first sample is always zero. - for (ma_int32 i = 1; i < windowWidth2; ++i) { + /* Pre-load the window samples into an aligned buffer to begin with. Need to put these into an aligned buffer to make SIMD easier. */ + windowSamples[0] = 0; /* <-- The first sample is always zero. */ + for (i = 1; i < windowWidth2; ++i) { windowSamples[i] = pSRC->sinc.input[iChannel][iTimeIn + i]; } @@ -28507,13 +29497,19 @@ ma_uint64 ma_src_read_deinterleaved__sinc(ma_src* pSRC, ma_uint64 frameCount, vo if (pSRC->useAVX2 || pSRC->useAVX512) { __m256i ixabs[MA_SRC_SINC_MAX_WINDOW_WIDTH*2/8]; __m256 a[MA_SRC_SINC_MAX_WINDOW_WIDTH*2/8]; - __m256 resolution256 = _mm256_set1_ps(MA_SRC_SINC_LOOKUP_TABLE_RESOLUTION); + __m256 resolution256; + __m256 t; + __m256 r; + ma_int32 windowWidth8; + ma_int32 iWindow8; + + resolution256 = _mm256_set1_ps(MA_SRC_SINC_LOOKUP_TABLE_RESOLUTION); - __m256 t = _mm256_set1_ps((timeIn - iTimeInF)); - __m256 r = _mm256_set1_ps(0); + t = _mm256_set1_ps((timeIn - iTimeInF)); + r = _mm256_set1_ps(0); - ma_int32 windowWidth8 = windowWidthSIMD2 >> 3; - for (ma_int32 iWindow8 = 0; iWindow8 < windowWidth8; iWindow8 += 1) { + windowWidth8 = windowWidthSIMD2 >> 3; + for (iWindow8 = 0; iWindow8 < windowWidth8; iWindow8 += 1) { __m256 w = *((__m256*)iWindowF + iWindow8); __m256 xabs = _mm256_sub_ps(t, w); @@ -28524,7 +29520,7 @@ ma_uint64 ma_src_read_deinterleaved__sinc(ma_src* pSRC, ma_uint64 frameCount, vo a[iWindow8] = _mm256_sub_ps(xabs, _mm256_cvtepi32_ps(ixabs[iWindow8])); } - for (ma_int32 iWindow8 = 0; iWindow8 < windowWidth8; iWindow8 += 1) { + for (iWindow8 = 0; iWindow8 < windowWidth8; iWindow8 += 1) { int* ixabsv = (int*)&ixabs[iWindow8]; __m256 lo = _mm256_set_ps( @@ -28553,7 +29549,7 @@ ma_uint64 ma_src_read_deinterleaved__sinc(ma_src* pSRC, ma_uint64 frameCount, vo r = _mm256_add_ps(r, _mm256_mul_ps(s, ma_mix_f32_fast__avx2(lo, hi, a[iWindow8]))); } - // Horizontal add. + /* Horizontal add. */ __m256 x = _mm256_hadd_ps(r, _mm256_permute2f128_ps(r, r, 1)); x = _mm256_hadd_ps(x, x); x = _mm256_hadd_ps(x, x); @@ -28569,7 +29565,8 @@ ma_uint64 ma_src_read_deinterleaved__sinc(ma_src* pSRC, ma_uint64 frameCount, vo __m128 r = _mm_set1_ps(0); ma_int32 windowWidth4 = windowWidthSIMD2 >> 2; - for (ma_int32 iWindow4 = 0; iWindow4 < windowWidth4; iWindow4 += 1) { + ma_int32 iWindow4; + for (iWindow4 = 0; iWindow4 < windowWidth4; iWindow4 += 1) { __m128* s = (__m128*)windowSamples + iWindow4; __m128* w = (__m128*)iWindowF + iWindow4; @@ -28592,7 +29589,8 @@ ma_uint64 ma_src_read_deinterleaved__sinc(ma_src* pSRC, ma_uint64 frameCount, vo float32x4_t r = vmovq_n_f32(0); ma_int32 windowWidth4 = windowWidthSIMD2 >> 2; - for (ma_int32 iWindow4 = 0; iWindow4 < windowWidth4; iWindow4 += 1) { + ma_int32 iWindow4; + for (iWindow4 = 0; iWindow4 < windowWidth4; iWindow4 += 1) { float32x4_t* s = (float32x4_t*)windowSamples + iWindow4; float32x4_t* w = (float32x4_t*)iWindowF + iWindow4; @@ -28610,16 +29608,16 @@ ma_uint64 ma_src_read_deinterleaved__sinc(ma_src* pSRC, ma_uint64 frameCount, vo else #endif { - iWindow += 1; // The first one is a dummy for SIMD alignment purposes. Skip it. + iWindow += 1; /* The first one is a dummy for SIMD alignment purposes. Skip it. */ } - // Non-SIMD/Reference implementation. - float t = (timeIn - iTimeIn); + /* Non-SIMD/Reference implementation. */ + tScalar = (timeIn - iTimeIn); for (; iWindow < windowWidth2; iWindow += 1) { float s = windowSamples[iWindow]; float w = iWindowF[iWindow]; - float a = ma_src_sinc__interpolation_factor(pSRC, (t - w)); + float a = ma_src_sinc__interpolation_factor(pSRC, (tScalar - w)); float r = s * a; sampleOut += r; @@ -28635,14 +29633,14 @@ ma_uint64 ma_src_read_deinterleaved__sinc(ma_src* pSRC, ma_uint64 frameCount, vo totalOutputFramesRead += outputFramesToRead; - ma_uint32 prevWindowPosInSamples = pSRC->sinc.windowPosInSamples; + prevWindowPosInSamples = pSRC->sinc.windowPosInSamples; - pSRC->sinc.timeIn += (outputFramesToRead * factor); + pSRC->sinc.timeIn += ((ma_int64)outputFramesToRead * factor); /* Cast to int64 required for VC6. */ pSRC->sinc.windowPosInSamples = (ma_uint32)pSRC->sinc.timeIn; pSRC->sinc.inputFrameCount -= pSRC->sinc.windowPosInSamples - prevWindowPosInSamples; - // If the window has reached a point where we cannot read a whole output sample it needs to be moved back to the start. - ma_uint32 availableOutputFrames = (ma_uint32)((timeInEnd - pSRC->sinc.timeIn) * inverseFactor); + /* If the window has reached a point where we cannot read a whole output sample it needs to be moved back to the start. */ + availableOutputFrames = (ma_uint32)((timeInEnd - pSRC->sinc.timeIn) * inverseFactor); if (availableOutputFrames == 0) { size_t samplesToMove = ma_countof(pSRC->sinc.input[0]) - pSRC->sinc.windowPosInSamples; @@ -28650,32 +29648,38 @@ ma_uint64 ma_src_read_deinterleaved__sinc(ma_src* pSRC, ma_uint64 frameCount, vo pSRC->sinc.timeIn -= ma_floorf(pSRC->sinc.timeIn); pSRC->sinc.windowPosInSamples = 0; - // Move everything from the end of the cache up to the front. - for (ma_uint32 iChannel = 0; iChannel < pSRC->config.channels; iChannel += 1) { + /* Move everything from the end of the cache up to the front. */ + for (iChannel = 0; iChannel < pSRC->config.channels; iChannel += 1) { memmove(pSRC->sinc.input[iChannel], pSRC->sinc.input[iChannel] + ma_countof(pSRC->sinc.input[iChannel]) - samplesToMove, samplesToMove * sizeof(*pSRC->sinc.input[iChannel])); } } - // Read more data from the client if required. + /* Read more data from the client if required. */ if (pSRC->isEndOfInputLoaded) { pSRC->isEndOfInputLoaded = MA_FALSE; break; } - // Everything beyond this point is reloading. If we're at the end of the input data we do _not_ want to try reading any more in this function call. If the - // caller wants to keep trying, they can reload their internal data sources and call this function again. We should never be + /* + Everything beyond this point is reloading. If we're at the end of the input data we do _not_ want to try reading any more in this function call. If the + caller wants to keep trying, they can reload their internal data sources and call this function again. We should never be + */ ma_assert(pSRC->isEndOfInputLoaded == MA_FALSE); if (pSRC->sinc.inputFrameCount <= pSRC->config.sinc.windowWidth || availableOutputFrames == 0) { float* ppInputDst[MA_MAX_CHANNELS] = {0}; - for (ma_uint32 iChannel = 0; iChannel < pSRC->config.channels; iChannel += 1) { + ma_uint32 framesToReadFromClient; + ma_uint32 framesReadFromClient; + ma_uint32 leftoverFrames; + + for (iChannel = 0; iChannel < pSRC->config.channels; iChannel += 1) { ppInputDst[iChannel] = pSRC->sinc.input[iChannel] + pSRC->config.sinc.windowWidth + pSRC->sinc.inputFrameCount; } - // Now read data from the client. - ma_uint32 framesToReadFromClient = ma_countof(pSRC->sinc.input[0]) - (pSRC->config.sinc.windowWidth + pSRC->sinc.inputFrameCount); + /* Now read data from the client. */ + framesToReadFromClient = ma_countof(pSRC->sinc.input[0]) - (pSRC->config.sinc.windowWidth + pSRC->sinc.inputFrameCount); - ma_uint32 framesReadFromClient = 0; + framesReadFromClient = 0; if (framesToReadFromClient > 0) { framesReadFromClient = pSRC->config.onReadDeinterleaved(pSRC, framesToReadFromClient, (void**)ppInputDst, pUserData); } @@ -28689,8 +29693,7 @@ ma_uint64 ma_src_read_deinterleaved__sinc(ma_src* pSRC, ma_uint64 frameCount, vo if (framesReadFromClient != 0) { pSRC->sinc.inputFrameCount += framesReadFromClient; } else { - // We couldn't get anything more from the client. If no more output samples can be computed from the available input samples - // we need to return. + /* We couldn't get anything more from the client. If no more output samples can be computed from the available input samples we need to return. */ if (pSRC->config.neverConsumeEndOfInput) { if ((pSRC->sinc.inputFrameCount * inverseFactor) <= pSRC->config.sinc.windowWidth) { break; @@ -28702,10 +29705,10 @@ ma_uint64 ma_src_read_deinterleaved__sinc(ma_src* pSRC, ma_uint64 frameCount, vo } } - // Anything left over in the cache must be set to zero. - ma_uint32 leftoverFrames = ma_countof(pSRC->sinc.input[0]) - (pSRC->config.sinc.windowWidth + pSRC->sinc.inputFrameCount); + /* Anything left over in the cache must be set to zero. */ + leftoverFrames = ma_countof(pSRC->sinc.input[0]) - (pSRC->config.sinc.windowWidth + pSRC->sinc.inputFrameCount); if (leftoverFrames > 0) { - for (ma_uint32 iChannel = 0; iChannel < pSRC->config.channels; iChannel += 1) { + for (iChannel = 0; iChannel < pSRC->config.channels; iChannel += 1) { ma_zero_memory(pSRC->sinc.input[iChannel] + pSRC->config.sinc.windowWidth + pSRC->sinc.inputFrameCount, leftoverFrames * sizeof(float)); } } @@ -28717,13 +29720,11 @@ ma_uint64 ma_src_read_deinterleaved__sinc(ma_src* pSRC, ma_uint64 frameCount, vo -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// FORMAT CONVERSION -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +/************************************************************************************************************************************************************** + +Format Conversion + +**************************************************************************************************************************************************************/ void ma_pcm_convert(void* pOut, ma_format formatOut, const void* pIn, ma_format formatIn, ma_uint64 sampleCount, ma_dither_mode ditherMode) { if (formatOut == formatIn) { @@ -28800,16 +29801,18 @@ void ma_pcm_convert(void* pOut, ma_format formatOut, const void* pIn, ma_format void ma_deinterleave_pcm_frames(ma_format format, ma_uint32 channels, ma_uint64 frameCount, const void* pInterleavedPCMFrames, void** ppDeinterleavedPCMFrames) { if (pInterleavedPCMFrames == NULL || ppDeinterleavedPCMFrames == NULL) { - return; // Invalid args. + return; /* Invalid args. */ } - // For efficiency we do this per format. + /* For efficiency we do this per format. */ switch (format) { case ma_format_s16: { const ma_int16* pSrcS16 = (const ma_int16*)pInterleavedPCMFrames; - for (ma_uint64 iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) { - for (ma_uint32 iChannel = 0; iChannel < channels; ++iChannel) { + ma_uint64 iPCMFrame; + for (iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) { + ma_uint32 iChannel; + for (iChannel = 0; iChannel < channels; ++iChannel) { ma_int16* pDstS16 = (ma_int16*)ppDeinterleavedPCMFrames[iChannel]; pDstS16[iPCMFrame] = pSrcS16[iPCMFrame*channels+iChannel]; } @@ -28819,8 +29822,10 @@ void ma_deinterleave_pcm_frames(ma_format format, ma_uint32 channels, ma_uint64 case ma_format_f32: { const float* pSrcF32 = (const float*)pInterleavedPCMFrames; - for (ma_uint64 iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) { - for (ma_uint32 iChannel = 0; iChannel < channels; ++iChannel) { + ma_uint64 iPCMFrame; + for (iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) { + ma_uint32 iChannel; + for (iChannel = 0; iChannel < channels; ++iChannel) { float* pDstF32 = (float*)ppDeinterleavedPCMFrames[iChannel]; pDstF32[iPCMFrame] = pSrcF32[iPCMFrame*channels+iChannel]; } @@ -28830,9 +29835,10 @@ void ma_deinterleave_pcm_frames(ma_format format, ma_uint32 channels, ma_uint64 default: { ma_uint32 sampleSizeInBytes = ma_get_bytes_per_sample(format); - - for (ma_uint64 iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) { - for (ma_uint32 iChannel = 0; iChannel < channels; ++iChannel) { + ma_uint64 iPCMFrame; + for (iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) { + ma_uint32 iChannel; + for (iChannel = 0; iChannel < channels; ++iChannel) { void* pDst = ma_offset_ptr(ppDeinterleavedPCMFrames[iChannel], iPCMFrame*sampleSizeInBytes); const void* pSrc = ma_offset_ptr(pInterleavedPCMFrames, (iPCMFrame*channels+iChannel)*sampleSizeInBytes); memcpy(pDst, pSrc, sampleSizeInBytes); @@ -28849,8 +29855,10 @@ void ma_interleave_pcm_frames(ma_format format, ma_uint32 channels, ma_uint64 fr case ma_format_s16: { ma_int16* pDstS16 = (ma_int16*)pInterleavedPCMFrames; - for (ma_uint64 iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) { - for (ma_uint32 iChannel = 0; iChannel < channels; ++iChannel) { + ma_uint64 iPCMFrame; + for (iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) { + ma_uint32 iChannel; + for (iChannel = 0; iChannel < channels; ++iChannel) { const ma_int16* pSrcS16 = (const ma_int16*)ppDeinterleavedPCMFrames[iChannel]; pDstS16[iPCMFrame*channels+iChannel] = pSrcS16[iPCMFrame]; } @@ -28860,8 +29868,10 @@ void ma_interleave_pcm_frames(ma_format format, ma_uint32 channels, ma_uint64 fr case ma_format_f32: { float* pDstF32 = (float*)pInterleavedPCMFrames; - for (ma_uint64 iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) { - for (ma_uint32 iChannel = 0; iChannel < channels; ++iChannel) { + ma_uint64 iPCMFrame; + for (iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) { + ma_uint32 iChannel; + for (iChannel = 0; iChannel < channels; ++iChannel) { const float* pSrcF32 = (const float*)ppDeinterleavedPCMFrames[iChannel]; pDstF32[iPCMFrame*channels+iChannel] = pSrcF32[iPCMFrame]; } @@ -28871,9 +29881,10 @@ void ma_interleave_pcm_frames(ma_format format, ma_uint32 channels, ma_uint64 fr default: { ma_uint32 sampleSizeInBytes = ma_get_bytes_per_sample(format); - - for (ma_uint64 iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) { - for (ma_uint32 iChannel = 0; iChannel < channels; ++iChannel) { + ma_uint64 iPCMFrame; + for (iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) { + ma_uint32 iChannel; + for (iChannel = 0; iChannel < channels; ++iChannel) { void* pDst = ma_offset_ptr(pInterleavedPCMFrames, (iPCMFrame*channels+iChannel)*sampleSizeInBytes); const void* pSrc = ma_offset_ptr(ppDeinterleavedPCMFrames[iChannel], iPCMFrame*sampleSizeInBytes); memcpy(pDst, pSrc, sampleSizeInBytes); @@ -28893,12 +29904,15 @@ typedef struct ma_uint32 ma_pcm_converter__pre_format_converter_on_read(ma_format_converter* pConverter, ma_uint32 frameCount, void* pFramesOut, void* pUserData) { + ma_pcm_converter_callback_data* pData; + ma_pcm_converter* pDSP; + (void)pConverter; - ma_pcm_converter_callback_data* pData = (ma_pcm_converter_callback_data*)pUserData; + pData = (ma_pcm_converter_callback_data*)pUserData; ma_assert(pData != NULL); - ma_pcm_converter* pDSP = pData->pDSP; + pDSP = pData->pDSP; ma_assert(pDSP != NULL); return pDSP->onRead(pDSP, pFramesOut, frameCount, pData->pUserDataForClient); @@ -28906,15 +29920,18 @@ ma_uint32 ma_pcm_converter__pre_format_converter_on_read(ma_format_converter* pC ma_uint32 ma_pcm_converter__post_format_converter_on_read(ma_format_converter* pConverter, ma_uint32 frameCount, void* pFramesOut, void* pUserData) { + ma_pcm_converter_callback_data* pData; + ma_pcm_converter* pDSP; + (void)pConverter; - ma_pcm_converter_callback_data* pData = (ma_pcm_converter_callback_data*)pUserData; + pData = (ma_pcm_converter_callback_data*)pUserData; ma_assert(pData != NULL); - ma_pcm_converter* pDSP = pData->pDSP; + pDSP = pData->pDSP; ma_assert(pDSP != NULL); - // When this version of this callback is used it means we're reading directly from the client. + /* When this version of this callback is used it means we're reading directly from the client. */ ma_assert(pDSP->isPreFormatConversionRequired == MA_FALSE); ma_assert(pDSP->isChannelRoutingRequired == MA_FALSE); ma_assert(pDSP->isSRCRequired == MA_FALSE); @@ -28924,12 +29941,15 @@ ma_uint32 ma_pcm_converter__post_format_converter_on_read(ma_format_converter* p ma_uint32 ma_pcm_converter__post_format_converter_on_read_deinterleaved(ma_format_converter* pConverter, ma_uint32 frameCount, void** ppSamplesOut, void* pUserData) { + ma_pcm_converter_callback_data* pData; + ma_pcm_converter* pDSP; + (void)pConverter; - ma_pcm_converter_callback_data* pData = (ma_pcm_converter_callback_data*)pUserData; + pData = (ma_pcm_converter_callback_data*)pUserData; ma_assert(pData != NULL); - ma_pcm_converter* pDSP = pData->pDSP; + pDSP = pData->pDSP; ma_assert(pDSP != NULL); if (!pDSP->isChannelRoutingAtStart) { @@ -28945,15 +29965,18 @@ ma_uint32 ma_pcm_converter__post_format_converter_on_read_deinterleaved(ma_forma ma_uint32 ma_pcm_converter__src_on_read_deinterleaved(ma_src* pSRC, ma_uint32 frameCount, void** ppSamplesOut, void* pUserData) { + ma_pcm_converter_callback_data* pData; + ma_pcm_converter* pDSP; + (void)pSRC; - ma_pcm_converter_callback_data* pData = (ma_pcm_converter_callback_data*)pUserData; + pData = (ma_pcm_converter_callback_data*)pUserData; ma_assert(pData != NULL); - ma_pcm_converter* pDSP = pData->pDSP; + pDSP = pData->pDSP; ma_assert(pDSP != NULL); - // If the channel routing stage is at the front we need to read from that. Otherwise we read from the pre format converter. + /* If the channel routing stage is at the front we need to read from that. Otherwise we read from the pre format converter. */ if (pDSP->isChannelRoutingAtStart) { return (ma_uint32)ma_channel_router_read_deinterleaved(&pDSP->channelRouter, frameCount, ppSamplesOut, pUserData); } else { @@ -28963,15 +29986,18 @@ ma_uint32 ma_pcm_converter__src_on_read_deinterleaved(ma_src* pSRC, ma_uint32 fr ma_uint32 ma_pcm_converter__channel_router_on_read_deinterleaved(ma_channel_router* pRouter, ma_uint32 frameCount, void** ppSamplesOut, void* pUserData) { + ma_pcm_converter_callback_data* pData; + ma_pcm_converter* pDSP; + (void)pRouter; - ma_pcm_converter_callback_data* pData = (ma_pcm_converter_callback_data*)pUserData; + pData = (ma_pcm_converter_callback_data*)pUserData; ma_assert(pData != NULL); - ma_pcm_converter* pDSP = pData->pDSP; + pDSP = pData->pDSP; ma_assert(pDSP != NULL); - // If the channel routing stage is at the front of the pipeline we read from the pre format converter. Otherwise we read from the sample rate converter. + /* If the channel routing stage is at the front of the pipeline we read from the pre format converter. Otherwise we read from the sample rate converter. */ if (pDSP->isChannelRoutingAtStart) { return (ma_uint32)ma_format_converter_read_deinterleaved(&pDSP->formatConverterIn, frameCount, ppSamplesOut, pUserData); } else { @@ -28985,6 +30011,8 @@ ma_uint32 ma_pcm_converter__channel_router_on_read_deinterleaved(ma_channel_rout ma_result ma_pcm_converter_init(const ma_pcm_converter_config* pConfig, ma_pcm_converter* pDSP) { + ma_result result; + if (pDSP == NULL) { return MA_INVALID_ARGS; } @@ -28994,60 +30022,61 @@ ma_result ma_pcm_converter_init(const ma_pcm_converter_config* pConfig, ma_pcm_c pDSP->pUserData = pConfig->pUserData; pDSP->isDynamicSampleRateAllowed = pConfig->allowDynamicSampleRate; + /* + In general, this is the pipeline used for data conversion. Note that this can actually change which is explained later. + + Pre Format Conversion -> Sample Rate Conversion -> Channel Routing -> Post Format Conversion + + Pre Format Conversion + --------------------- + This is where the sample data is converted to a format that's usable by the later stages in the pipeline. Input data + is converted to deinterleaved floating-point. + + Channel Routing + --------------- + Channel routing is where stereo is converted to 5.1, mono is converted to stereo, etc. This stage depends on the + pre format conversion stage. + + Sample Rate Conversion + ---------------------- + Sample rate conversion depends on the pre format conversion stage and as the name implies performs sample rate conversion. + + Post Format Conversion + ---------------------- + This stage is where our deinterleaved floating-point data from the previous stages are converted to the requested output + format. + + + Optimizations + ------------- + Sometimes the conversion pipeline is rearranged for efficiency. The first obvious optimization is to eliminate unnecessary + stages in the pipeline. When no channel routing nor sample rate conversion is necessary, the entire pipeline is optimized + down to just this: + + Post Format Conversion + + When sample rate conversion is not unnecessary: + + Pre Format Conversion -> Channel Routing -> Post Format Conversion + + When channel routing is unnecessary: + + Pre Format Conversion -> Sample Rate Conversion -> Post Format Conversion + + A slightly less obvious optimization is used depending on whether or not we are increasing or decreasing the number of + channels. Because everything in the pipeline works on a per-channel basis, the efficiency of the pipeline is directly + proportionate to the number of channels that need to be processed. Therefore, it's can be more efficient to move the + channel conversion stage to an earlier or later stage. When the channel count is being reduced, we move the channel + conversion stage to the start of the pipeline so that later stages can work on a smaller number of channels at a time. + Otherwise, we move the channel conversion stage to the end of the pipeline. When reducing the channel count, the pipeline + will look like this: + + Pre Format Conversion -> Channel Routing -> Sample Rate Conversion -> Post Format Conversion + + Notice how the Channel Routing and Sample Rate Conversion stages are swapped so that the SRC stage has less data to process. + */ - // In general, this is the pipeline used for data conversion. Note that this can actually change which is explained later. - // - // Pre Format Conversion -> Sample Rate Conversion -> Channel Routing -> Post Format Conversion - // - // Pre Format Conversion - // --------------------- - // This is where the sample data is converted to a format that's usable by the later stages in the pipeline. Input data - // is converted to deinterleaved floating-point. - // - // Channel Routing - // --------------- - // Channel routing is where stereo is converted to 5.1, mono is converted to stereo, etc. This stage depends on the - // pre format conversion stage. - // - // Sample Rate Conversion - // ---------------------- - // Sample rate conversion depends on the pre format conversion stage and as the name implies performs sample rate conversion. - // - // Post Format Conversion - // ---------------------- - // This stage is where our deinterleaved floating-point data from the previous stages are converted to the requested output - // format. - // - // - // Optimizations - // ------------- - // Sometimes the conversion pipeline is rearranged for efficiency. The first obvious optimization is to eliminate unnecessary - // stages in the pipeline. When no channel routing nor sample rate conversion is necessary, the entire pipeline is optimized - // down to just this: - // - // Post Format Conversion - // - // When sample rate conversion is not unnecessary: - // - // Pre Format Conversion -> Channel Routing -> Post Format Conversion - // - // When channel routing is unnecessary: - // - // Pre Format Conversion -> Sample Rate Conversion -> Post Format Conversion - // - // A slightly less obvious optimization is used depending on whether or not we are increasing or decreasing the number of - // channels. Because everything in the pipeline works on a per-channel basis, the efficiency of the pipeline is directly - // proportionate to the number of channels that need to be processed. Therefore, it's can be more efficient to move the - // channel conversion stage to an earlier or later stage. When the channel count is being reduced, we move the channel - // conversion stage to the start of the pipeline so that later stages can work on a smaller number of channels at a time. - // Otherwise, we move the channel conversion stage to the end of the pipeline. When reducing the channel count, the pipeline - // will look like this: - // - // Pre Format Conversion -> Channel Routing -> Sample Rate Conversion -> Post Format Conversion - // - // Notice how the Channel Routing and Sample Rate Conversion stages are swapped so that the SRC stage has less data to process. - - // First we need to determine what's required and what's not. + /* First we need to determine what's required and what's not. */ if (pConfig->sampleRateIn != pConfig->sampleRateOut || pConfig->allowDynamicSampleRate) { pDSP->isSRCRequired = MA_TRUE; } @@ -29055,9 +30084,9 @@ ma_result ma_pcm_converter_init(const ma_pcm_converter_config* pConfig, ma_pcm_c pDSP->isChannelRoutingRequired = MA_TRUE; } - // If neither a sample rate conversion nor channel conversion is necessary we can skip the pre format conversion. + /* If neither a sample rate conversion nor channel conversion is necessary we can skip the pre format conversion. */ if (!pDSP->isSRCRequired && !pDSP->isChannelRoutingRequired) { - // We don't need a pre format conversion stage, but we may still need a post format conversion stage. + /* We don't need a pre format conversion stage, but we may still need a post format conversion stage. */ if (pConfig->formatIn != pConfig->formatOut) { pDSP->isPostFormatConversionRequired = MA_TRUE; } @@ -29066,22 +30095,24 @@ ma_result ma_pcm_converter_init(const ma_pcm_converter_config* pConfig, ma_pcm_c pDSP->isPostFormatConversionRequired = MA_TRUE; } - // Use a passthrough if none of the stages are being used. + /* Use a passthrough if none of the stages are being used. */ if (!pDSP->isPreFormatConversionRequired && !pDSP->isPostFormatConversionRequired && !pDSP->isChannelRoutingRequired && !pDSP->isSRCRequired) { pDSP->isPassthrough = MA_TRUE; } - // Move the channel conversion stage to the start of the pipeline if we are reducing the channel count. + /* Move the channel conversion stage to the start of the pipeline if we are reducing the channel count. */ if (pConfig->channelsOut < pConfig->channelsIn) { pDSP->isChannelRoutingAtStart = MA_TRUE; } - // We always initialize every stage of the pipeline regardless of whether or not the stage is used because it simplifies - // a few things when it comes to dynamically changing properties post-initialization. - ma_result result = MA_SUCCESS; + /* + We always initialize every stage of the pipeline regardless of whether or not the stage is used because it simplifies + a few things when it comes to dynamically changing properties post-initialization. + */ + result = MA_SUCCESS; - // Pre format conversion. + /* Pre format conversion. */ { ma_format_converter_config preFormatConverterConfig = ma_format_converter_config_init( pConfig->formatIn, @@ -29102,8 +30133,10 @@ ma_result ma_pcm_converter_init(const ma_pcm_converter_config* pConfig, ma_pcm_c } } - // Post format conversion. The exact configuration for this depends on whether or not we are reading data directly from the client - // or from an earlier stage in the pipeline. + /* + Post format conversion. The exact configuration for this depends on whether or not we are reading data directly from the client + or from an earlier stage in the pipeline. + */ { ma_format_converter_config postFormatConverterConfig = ma_format_converter_config_init_new(); postFormatConverterConfig.formatIn = pConfig->formatIn; @@ -29127,7 +30160,7 @@ ma_result ma_pcm_converter_init(const ma_pcm_converter_config* pConfig, ma_pcm_c } } - // SRC + /* SRC */ { ma_src_config srcConfig = ma_src_config_init( pConfig->sampleRateIn, @@ -29150,7 +30183,7 @@ ma_result ma_pcm_converter_init(const ma_pcm_converter_config* pConfig, ma_pcm_c } } - // Channel conversion + /* Channel conversion */ { ma_channel_router_config routerConfig = ma_channel_router_config_init( pConfig->channelsIn, @@ -29177,7 +30210,7 @@ ma_result ma_pcm_converter_init(const ma_pcm_converter_config* pConfig, ma_pcm_c ma_result ma_pcm_converter_refresh_sample_rate(ma_pcm_converter* pDSP) { - // The SRC stage will already have been initialized so we can just set it there. + /* The SRC stage will already have been initialized so we can just set it there. */ ma_src_set_sample_rate(&pDSP->src, pDSP->src.config.sampleRateIn, pDSP->src.config.sampleRateOut); return MA_SUCCESS; } @@ -29188,12 +30221,12 @@ ma_result ma_pcm_converter_set_input_sample_rate(ma_pcm_converter* pDSP, ma_uint return MA_INVALID_ARGS; } - // Must have a sample rate of > 0. + /* Must have a sample rate of > 0. */ if (sampleRateIn == 0) { return MA_INVALID_ARGS; } - // Must have been initialized with allowDynamicSampleRate. + /* Must have been initialized with allowDynamicSampleRate. */ if (!pDSP->isDynamicSampleRateAllowed) { return MA_INVALID_OPERATION; } @@ -29208,12 +30241,12 @@ ma_result ma_pcm_converter_set_output_sample_rate(ma_pcm_converter* pDSP, ma_uin return MA_INVALID_ARGS; } - // Must have a sample rate of > 0. + /* Must have a sample rate of > 0. */ if (sampleRateOut == 0) { return MA_INVALID_ARGS; } - // Must have been initialized with allowDynamicSampleRate. + /* Must have been initialized with allowDynamicSampleRate. */ if (!pDSP->isDynamicSampleRateAllowed) { return MA_INVALID_OPERATION; } @@ -29228,12 +30261,12 @@ ma_result ma_pcm_converter_set_sample_rate(ma_pcm_converter* pDSP, ma_uint32 sam return MA_INVALID_ARGS; } - // Must have a sample rate of > 0. + /* Must have a sample rate of > 0. */ if (sampleRateIn == 0 || sampleRateOut == 0) { return MA_INVALID_ARGS; } - // Must have been initialized with allowDynamicSampleRate. + /* Must have been initialized with allowDynamicSampleRate. */ if (!pDSP->isDynamicSampleRateAllowed) { return MA_INVALID_OPERATION; } @@ -29246,11 +30279,13 @@ ma_result ma_pcm_converter_set_sample_rate(ma_pcm_converter* pDSP, ma_uint32 sam ma_uint64 ma_pcm_converter_read(ma_pcm_converter* pDSP, void* pFramesOut, ma_uint64 frameCount) { + ma_pcm_converter_callback_data data; + if (pDSP == NULL || pFramesOut == NULL) { return 0; } - // Fast path. + /* Fast path. */ if (pDSP->isPassthrough) { if (frameCount <= 0xFFFFFFFF) { return (ma_uint32)pDSP->onRead(pDSP, pFramesOut, (ma_uint32)frameCount, pDSP->pUserData); @@ -29259,13 +30294,14 @@ ma_uint64 ma_pcm_converter_read(ma_pcm_converter* pDSP, void* pFramesOut, ma_uin ma_uint64 totalFramesRead = 0; while (totalFramesRead < frameCount) { + ma_uint32 framesRead; ma_uint64 framesRemaining = (frameCount - totalFramesRead); ma_uint64 framesToReadRightNow = framesRemaining; if (framesToReadRightNow > 0xFFFFFFFF) { framesToReadRightNow = 0xFFFFFFFF; } - ma_uint32 framesRead = pDSP->onRead(pDSP, pNextFramesOut, (ma_uint32)framesToReadRightNow, pDSP->pUserData); + framesRead = pDSP->onRead(pDSP, pNextFramesOut, (ma_uint32)framesToReadRightNow, pDSP->pUserData); if (framesRead == 0) { break; } @@ -29278,10 +30314,9 @@ ma_uint64 ma_pcm_converter_read(ma_pcm_converter* pDSP, void* pFramesOut, ma_uin } } - // Slower path. The real work is done here. To do this all we need to do is read from the last stage in the pipeline. + /* Slower path. The real work is done here. To do this all we need to do is read from the last stage in the pipeline. */ ma_assert(pDSP->isPostFormatConversionRequired == MA_TRUE); - ma_pcm_converter_callback_data data; data.pDSP = pDSP; data.pUserDataForClient = pDSP->pUserData; return ma_format_converter_read(&pDSP->formatConverterOut, frameCount, pFramesOut, &data); @@ -29295,24 +30330,29 @@ typedef struct ma_uint32 channelsIn; ma_uint64 totalFrameCount; ma_uint64 iNextFrame; - ma_bool32 isFeedingZeros; // When set to true, feeds the DSP zero samples. + ma_bool32 isFeedingZeros; /* When set to true, feeds the DSP zero samples. */ } ma_convert_frames__data; ma_uint32 ma_convert_frames__on_read(ma_pcm_converter* pDSP, void* pFramesOut, ma_uint32 frameCount, void* pUserData) { + ma_convert_frames__data* pData; + ma_uint32 framesToRead; + ma_uint64 framesRemaining; + ma_uint32 frameSizeInBytes; + (void)pDSP; - ma_convert_frames__data* pData = (ma_convert_frames__data*)pUserData; + pData = (ma_convert_frames__data*)pUserData; ma_assert(pData != NULL); ma_assert(pData->totalFrameCount >= pData->iNextFrame); - ma_uint32 framesToRead = frameCount; - ma_uint64 framesRemaining = (pData->totalFrameCount - pData->iNextFrame); + framesToRead = frameCount; + framesRemaining = (pData->totalFrameCount - pData->iNextFrame); if (framesToRead > framesRemaining) { framesToRead = (ma_uint32)framesRemaining; } - ma_uint32 frameSizeInBytes = ma_get_bytes_per_frame(pData->formatIn, pData->channelsIn); + frameSizeInBytes = ma_get_bytes_per_frame(pData->formatIn, pData->channelsIn); if (!pData->isFeedingZeros) { ma_copy_memory(pFramesOut, (const ma_uint8*)pData->pDataIn + (frameSizeInBytes * pData->iNextFrame), frameSizeInBytes * framesToRead); @@ -29364,9 +30404,9 @@ ma_pcm_converter_config ma_pcm_converter_config_init_ex(ma_format formatIn, ma_u ma_uint64 ma_convert_frames(void* pOut, ma_format formatOut, ma_uint32 channelsOut, ma_uint32 sampleRateOut, const void* pIn, ma_format formatIn, ma_uint32 channelsIn, ma_uint32 sampleRateIn, ma_uint64 frameCount) { ma_channel channelMapOut[MA_MAX_CHANNELS]; - ma_get_standard_channel_map(ma_standard_channel_map_default, channelsOut, channelMapOut); - ma_channel channelMapIn[MA_MAX_CHANNELS]; + + ma_get_standard_channel_map(ma_standard_channel_map_default, channelsOut, channelMapOut); ma_get_standard_channel_map(ma_standard_channel_map_default, channelsIn, channelMapIn); return ma_convert_frames_ex(pOut, formatOut, channelsOut, sampleRateOut, channelMapOut, pIn, formatIn, channelsIn, sampleRateIn, channelMapIn, frameCount); @@ -29374,16 +30414,21 @@ ma_uint64 ma_convert_frames(void* pOut, ma_format formatOut, ma_uint32 channelsO ma_uint64 ma_convert_frames_ex(void* pOut, ma_format formatOut, ma_uint32 channelsOut, ma_uint32 sampleRateOut, ma_channel channelMapOut[MA_MAX_CHANNELS], const void* pIn, ma_format formatIn, ma_uint32 channelsIn, ma_uint32 sampleRateIn, ma_channel channelMapIn[MA_MAX_CHANNELS], ma_uint64 frameCount) { + ma_uint64 frameCountOut; + ma_convert_frames__data data; + ma_pcm_converter_config converterConfig; + ma_pcm_converter converter; + ma_uint64 totalFramesRead; + if (frameCount == 0) { return 0; } - ma_uint64 frameCountOut = ma_calculate_frame_count_after_src(sampleRateOut, sampleRateIn, frameCount); + frameCountOut = ma_calculate_frame_count_after_src(sampleRateOut, sampleRateIn, frameCount); if (pOut == NULL) { return frameCountOut; } - ma_convert_frames__data data; data.pDataIn = pIn; data.formatIn = formatIn; data.channelsIn = channelsIn; @@ -29391,51 +30436,54 @@ ma_uint64 ma_convert_frames_ex(void* pOut, ma_format formatOut, ma_uint32 channe data.iNextFrame = 0; data.isFeedingZeros = MA_FALSE; - ma_pcm_converter_config config; - ma_zero_object(&config); + ma_zero_object(&converterConfig); - config.formatIn = formatIn; - config.channelsIn = channelsIn; - config.sampleRateIn = sampleRateIn; + converterConfig.formatIn = formatIn; + converterConfig.channelsIn = channelsIn; + converterConfig.sampleRateIn = sampleRateIn; if (channelMapIn != NULL) { - ma_channel_map_copy(config.channelMapIn, channelMapIn, channelsIn); + ma_channel_map_copy(converterConfig.channelMapIn, channelMapIn, channelsIn); } else { - ma_get_standard_channel_map(ma_standard_channel_map_default, config.channelsIn, config.channelMapIn); + ma_get_standard_channel_map(ma_standard_channel_map_default, converterConfig.channelsIn, converterConfig.channelMapIn); } - config.formatOut = formatOut; - config.channelsOut = channelsOut; - config.sampleRateOut = sampleRateOut; + converterConfig.formatOut = formatOut; + converterConfig.channelsOut = channelsOut; + converterConfig.sampleRateOut = sampleRateOut; if (channelMapOut != NULL) { - ma_channel_map_copy(config.channelMapOut, channelMapOut, channelsOut); + ma_channel_map_copy(converterConfig.channelMapOut, channelMapOut, channelsOut); } else { - ma_get_standard_channel_map(ma_standard_channel_map_default, config.channelsOut, config.channelMapOut); + ma_get_standard_channel_map(ma_standard_channel_map_default, converterConfig.channelsOut, converterConfig.channelMapOut); } - config.onRead = ma_convert_frames__on_read; - config.pUserData = &data; + converterConfig.onRead = ma_convert_frames__on_read; + converterConfig.pUserData = &data; - ma_pcm_converter dsp; - if (ma_pcm_converter_init(&config, &dsp) != MA_SUCCESS) { + if (ma_pcm_converter_init(&converterConfig, &converter) != MA_SUCCESS) { return 0; } - // Always output our computed frame count. There is a chance the sample rate conversion routine may not output the last sample - // due to precision issues with 32-bit floats, in which case we should feed the DSP zero samples so it can generate that last - // frame. - ma_uint64 totalFramesRead = ma_pcm_converter_read(&dsp, pOut, frameCountOut); + /* + Always output our computed frame count. There is a chance the sample rate conversion routine may not output the last sample + due to precision issues with 32-bit floats, in which case we should feed the DSP zero samples so it can generate that last + frame. + */ + totalFramesRead = ma_pcm_converter_read(&converter, pOut, frameCountOut); if (totalFramesRead < frameCountOut) { ma_uint32 bpf = ma_get_bytes_per_frame(formatIn, channelsIn); data.isFeedingZeros = MA_TRUE; - data.totalFrameCount = 0xFFFFFFFFFFFFFFFF; + data.totalFrameCount = ((ma_uint64)0xFFFFFFFF << 32) | 0xFFFFFFFF; /* C89 does not support 64-bit constants so need to instead construct it like this. Annoying... */ /*data.totalFrameCount = 0xFFFFFFFFFFFFFFFF;*/ data.pDataIn = NULL; while (totalFramesRead < frameCountOut) { - ma_uint64 framesToRead = (frameCountOut - totalFramesRead); + ma_uint64 framesToRead; + ma_uint64 framesJustRead; + + framesToRead = (frameCountOut - totalFramesRead); ma_assert(framesToRead > 0); - ma_uint64 framesJustRead = ma_pcm_converter_read(&dsp, ma_offset_ptr(pOut, totalFramesRead * bpf), framesToRead); + framesJustRead = ma_pcm_converter_read(&converter, ma_offset_ptr(pOut, totalFramesRead * bpf), framesToRead); totalFramesRead += framesJustRead; if (framesJustRead < framesToRead) { @@ -29443,7 +30491,7 @@ ma_uint64 ma_convert_frames_ex(void* pOut, ma_format formatOut, ma_uint32 channe } } - // At this point we should have output every sample, but just to be super duper sure, just fill the rest with zeros. + /* At this point we should have output every sample, but just to be super duper sure, just fill the rest with zeros. */ if (totalFramesRead < frameCountOut) { ma_zero_memory_64(ma_offset_ptr(pOut, totalFramesRead * bpf), ((frameCountOut - totalFramesRead) * bpf)); totalFramesRead = frameCountOut; @@ -29455,13 +30503,11 @@ ma_uint64 ma_convert_frames_ex(void* pOut, ma_format formatOut, ma_uint32 channe } -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Ring Buffer -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +/************************************************************************************************************************************************************** + +Ring Buffer + +**************************************************************************************************************************************************************/ MA_INLINE ma_uint32 ma_rb__extract_offset_in_bytes(ma_uint32 encodedOffset) { return encodedOffset & 0x7FFFFFFF; @@ -29501,6 +30547,8 @@ MA_INLINE void ma_rb__deconstruct_offset(ma_uint32 encodedOffset, ma_uint32* pOf ma_result ma_rb_init_ex(size_t subbufferSizeInBytes, size_t subbufferCount, size_t subbufferStrideInBytes, void* pOptionalPreallocatedBuffer, ma_rb* pRB) { + const ma_uint32 maxSubBufferSize = 0x7FFFFFFF - (MA_SIMD_ALIGNMENT-1); + if (pRB == NULL) { return MA_INVALID_ARGS; } @@ -29509,9 +30557,8 @@ ma_result ma_rb_init_ex(size_t subbufferSizeInBytes, size_t subbufferCount, size return MA_INVALID_ARGS; } - const ma_uint32 maxSubBufferSize = 0x7FFFFFFF - (MA_SIMD_ALIGNMENT-1); if (subbufferSizeInBytes > maxSubBufferSize) { - return MA_INVALID_ARGS; // Maximum buffer size is ~2GB. The most significant bit is a flag for use internally. + return MA_INVALID_ARGS; /* Maximum buffer size is ~2GB. The most significant bit is a flag for use internally. */ } @@ -29523,11 +30570,15 @@ ma_result ma_rb_init_ex(size_t subbufferSizeInBytes, size_t subbufferCount, size pRB->subbufferStrideInBytes = (ma_uint32)subbufferStrideInBytes; pRB->pBuffer = pOptionalPreallocatedBuffer; } else { - // Here is where we allocate our own buffer. We always want to align this to MA_SIMD_ALIGNMENT for future SIMD optimization opportunity. To do this - // we need to make sure the stride is a multiple of MA_SIMD_ALIGNMENT. + size_t bufferSizeInBytes; + + /* + Here is where we allocate our own buffer. We always want to align this to MA_SIMD_ALIGNMENT for future SIMD optimization opportunity. To do this + we need to make sure the stride is a multiple of MA_SIMD_ALIGNMENT. + */ pRB->subbufferStrideInBytes = (pRB->subbufferSizeInBytes + (MA_SIMD_ALIGNMENT-1)) & ~MA_SIMD_ALIGNMENT; - size_t bufferSizeInBytes = (size_t)pRB->subbufferCount*pRB->subbufferStrideInBytes; + bufferSizeInBytes = (size_t)pRB->subbufferCount*pRB->subbufferStrideInBytes; pRB->pBuffer = ma_aligned_malloc(bufferSizeInBytes, MA_SIMD_ALIGNMENT); if (pRB->pBuffer == NULL) { return MA_OUT_OF_MEMORY; @@ -29558,31 +30609,37 @@ void ma_rb_uninit(ma_rb* pRB) ma_result ma_rb_acquire_read(ma_rb* pRB, size_t* pSizeInBytes, void** ppBufferOut) { + ma_uint32 writeOffset; + ma_uint32 writeOffsetInBytes; + ma_uint32 writeOffsetLoopFlag; + ma_uint32 readOffset; + ma_uint32 readOffsetInBytes; + ma_uint32 readOffsetLoopFlag; + size_t bytesAvailable; + size_t bytesRequested; + if (pRB == NULL || pSizeInBytes == NULL || ppBufferOut == NULL) { return MA_INVALID_ARGS; } - // The returned buffer should never move ahead of the write pointer. - ma_uint32 writeOffset = pRB->encodedWriteOffset; - ma_uint32 writeOffsetInBytes; - ma_uint32 writeOffsetLoopFlag; + /* The returned buffer should never move ahead of the write pointer. */ + writeOffset = pRB->encodedWriteOffset; ma_rb__deconstruct_offset(writeOffset, &writeOffsetInBytes, &writeOffsetLoopFlag); - ma_uint32 readOffset = pRB->encodedReadOffset; - ma_uint32 readOffsetInBytes; - ma_uint32 readOffsetLoopFlag; + readOffset = pRB->encodedReadOffset; ma_rb__deconstruct_offset(readOffset, &readOffsetInBytes, &readOffsetLoopFlag); - // The number of bytes available depends on whether or not the read and write pointers are on the same loop iteration. If so, we - // can only read up to the write pointer. If not, we can only read up to the end of the buffer. - size_t bytesAvailable; + /* + The number of bytes available depends on whether or not the read and write pointers are on the same loop iteration. If so, we + can only read up to the write pointer. If not, we can only read up to the end of the buffer. + */ if (readOffsetLoopFlag == writeOffsetLoopFlag) { bytesAvailable = writeOffsetInBytes - readOffsetInBytes; } else { bytesAvailable = pRB->subbufferSizeInBytes - readOffsetInBytes; } - size_t bytesRequested = *pSizeInBytes; + bytesRequested = *pSizeInBytes; if (bytesRequested > bytesAvailable) { bytesRequested = bytesAvailable; } @@ -29595,28 +30652,32 @@ ma_result ma_rb_acquire_read(ma_rb* pRB, size_t* pSizeInBytes, void** ppBufferOu ma_result ma_rb_commit_read(ma_rb* pRB, size_t sizeInBytes, void* pBufferOut) { + ma_uint32 readOffset; + ma_uint32 readOffsetInBytes; + ma_uint32 readOffsetLoopFlag; + ma_uint32 newReadOffsetInBytes; + ma_uint32 newReadOffsetLoopFlag; + if (pRB == NULL) { return MA_INVALID_ARGS; } - // Validate the buffer. + /* Validate the buffer. */ if (pBufferOut != ma_rb__get_read_ptr(pRB)) { return MA_INVALID_ARGS; } - ma_uint32 readOffset = pRB->encodedReadOffset; - ma_uint32 readOffsetInBytes; - ma_uint32 readOffsetLoopFlag; + readOffset = pRB->encodedReadOffset; ma_rb__deconstruct_offset(readOffset, &readOffsetInBytes, &readOffsetLoopFlag); - // Check that sizeInBytes is correct. It should never go beyond the end of the buffer. - ma_uint32 newReadOffsetInBytes = (ma_uint32)(readOffsetInBytes + sizeInBytes); + /* Check that sizeInBytes is correct. It should never go beyond the end of the buffer. */ + newReadOffsetInBytes = (ma_uint32)(readOffsetInBytes + sizeInBytes); if (newReadOffsetInBytes > pRB->subbufferSizeInBytes) { - return MA_INVALID_ARGS; // <-- sizeInBytes will cause the read offset to overflow. + return MA_INVALID_ARGS; /* <-- sizeInBytes will cause the read offset to overflow. */ } - // Move the read pointer back to the start if necessary. - ma_uint32 newReadOffsetLoopFlag = readOffsetLoopFlag; + /* Move the read pointer back to the start if necessary. */ + newReadOffsetLoopFlag = readOffsetLoopFlag; if (newReadOffsetInBytes == pRB->subbufferSizeInBytes) { newReadOffsetInBytes = 0; newReadOffsetLoopFlag ^= 0x80000000; @@ -29628,32 +30689,38 @@ ma_result ma_rb_commit_read(ma_rb* pRB, size_t sizeInBytes, void* pBufferOut) ma_result ma_rb_acquire_write(ma_rb* pRB, size_t* pSizeInBytes, void** ppBufferOut) { + ma_uint32 readOffset; + ma_uint32 readOffsetInBytes; + ma_uint32 readOffsetLoopFlag; + ma_uint32 writeOffset; + ma_uint32 writeOffsetInBytes; + ma_uint32 writeOffsetLoopFlag; + size_t bytesAvailable; + size_t bytesRequested; + if (pRB == NULL || pSizeInBytes == NULL || ppBufferOut == NULL) { return MA_INVALID_ARGS; } - // The returned buffer should never overtake the read buffer. - ma_uint32 readOffset = pRB->encodedReadOffset; - ma_uint32 readOffsetInBytes; - ma_uint32 readOffsetLoopFlag; + /* The returned buffer should never overtake the read buffer. */ + readOffset = pRB->encodedReadOffset; ma_rb__deconstruct_offset(readOffset, &readOffsetInBytes, &readOffsetLoopFlag); - ma_uint32 writeOffset = pRB->encodedWriteOffset; - ma_uint32 writeOffsetInBytes; - ma_uint32 writeOffsetLoopFlag; + writeOffset = pRB->encodedWriteOffset; ma_rb__deconstruct_offset(writeOffset, &writeOffsetInBytes, &writeOffsetLoopFlag); - // In the case of writing, if the write pointer and the read pointer are on the same loop iteration we can only - // write up to the end of the buffer. Otherwise we can only write up to the read pointer. The write pointer should - // never overtake the read pointer. - size_t bytesAvailable; + /* + In the case of writing, if the write pointer and the read pointer are on the same loop iteration we can only + write up to the end of the buffer. Otherwise we can only write up to the read pointer. The write pointer should + never overtake the read pointer. + */ if (writeOffsetLoopFlag == readOffsetLoopFlag) { bytesAvailable = pRB->subbufferSizeInBytes - writeOffsetInBytes; } else { bytesAvailable = readOffsetInBytes - writeOffsetInBytes; } - size_t bytesRequested = *pSizeInBytes; + bytesRequested = *pSizeInBytes; if (bytesRequested > bytesAvailable) { bytesRequested = bytesAvailable; } @@ -29661,7 +30728,7 @@ ma_result ma_rb_acquire_write(ma_rb* pRB, size_t* pSizeInBytes, void** ppBufferO *pSizeInBytes = bytesRequested; *ppBufferOut = ma_rb__get_write_ptr(pRB); - // Clear the buffer if desired. + /* Clear the buffer if desired. */ if (pRB->clearOnWriteAcquire) { ma_zero_memory(*ppBufferOut, *pSizeInBytes); } @@ -29671,28 +30738,32 @@ ma_result ma_rb_acquire_write(ma_rb* pRB, size_t* pSizeInBytes, void** ppBufferO ma_result ma_rb_commit_write(ma_rb* pRB, size_t sizeInBytes, void* pBufferOut) { + ma_uint32 writeOffset; + ma_uint32 writeOffsetInBytes; + ma_uint32 writeOffsetLoopFlag; + ma_uint32 newWriteOffsetInBytes; + ma_uint32 newWriteOffsetLoopFlag; + if (pRB == NULL) { return MA_INVALID_ARGS; } - // Validate the buffer. + /* Validate the buffer. */ if (pBufferOut != ma_rb__get_write_ptr(pRB)) { return MA_INVALID_ARGS; } - ma_uint32 writeOffset = pRB->encodedWriteOffset; - ma_uint32 writeOffsetInBytes; - ma_uint32 writeOffsetLoopFlag; + writeOffset = pRB->encodedWriteOffset; ma_rb__deconstruct_offset(writeOffset, &writeOffsetInBytes, &writeOffsetLoopFlag); - // Check that sizeInBytes is correct. It should never go beyond the end of the buffer. - ma_uint32 newWriteOffsetInBytes = (ma_uint32)(writeOffsetInBytes + sizeInBytes); + /* Check that sizeInBytes is correct. It should never go beyond the end of the buffer. */ + newWriteOffsetInBytes = (ma_uint32)(writeOffsetInBytes + sizeInBytes); if (newWriteOffsetInBytes > pRB->subbufferSizeInBytes) { - return MA_INVALID_ARGS; // <-- sizeInBytes will cause the read offset to overflow. + return MA_INVALID_ARGS; /* <-- sizeInBytes will cause the read offset to overflow. */ } - // Move the read pointer back to the start if necessary. - ma_uint32 newWriteOffsetLoopFlag = writeOffsetLoopFlag; + /* Move the read pointer back to the start if necessary. */ + newWriteOffsetLoopFlag = writeOffsetLoopFlag; if (newWriteOffsetInBytes == pRB->subbufferSizeInBytes) { newWriteOffsetInBytes = 0; newWriteOffsetLoopFlag ^= 0x80000000; @@ -29704,24 +30775,29 @@ ma_result ma_rb_commit_write(ma_rb* pRB, size_t sizeInBytes, void* pBufferOut) ma_result ma_rb_seek_read(ma_rb* pRB, size_t offsetInBytes) { + ma_uint32 readOffset; + ma_uint32 readOffsetInBytes; + ma_uint32 readOffsetLoopFlag; + ma_uint32 writeOffset; + ma_uint32 writeOffsetInBytes; + ma_uint32 writeOffsetLoopFlag; + ma_uint32 newReadOffsetInBytes; + ma_uint32 newReadOffsetLoopFlag; + if (pRB == NULL || offsetInBytes > pRB->subbufferSizeInBytes) { return MA_INVALID_ARGS; } - ma_uint32 readOffset = pRB->encodedReadOffset; - ma_uint32 readOffsetInBytes; - ma_uint32 readOffsetLoopFlag; + readOffset = pRB->encodedReadOffset; ma_rb__deconstruct_offset(readOffset, &readOffsetInBytes, &readOffsetLoopFlag); - ma_uint32 writeOffset = pRB->encodedWriteOffset; - ma_uint32 writeOffsetInBytes; - ma_uint32 writeOffsetLoopFlag; + writeOffset = pRB->encodedWriteOffset; ma_rb__deconstruct_offset(writeOffset, &writeOffsetInBytes, &writeOffsetLoopFlag); - ma_uint32 newReadOffsetInBytes = readOffsetInBytes; - ma_uint32 newReadOffsetLoopFlag = readOffsetLoopFlag; + newReadOffsetInBytes = readOffsetInBytes; + newReadOffsetLoopFlag = readOffsetLoopFlag; - // We cannot go past the write buffer. + /* We cannot go past the write buffer. */ if (readOffsetLoopFlag == writeOffsetLoopFlag) { if ((readOffsetInBytes + offsetInBytes) > writeOffsetInBytes) { newReadOffsetInBytes = writeOffsetInBytes; @@ -29729,7 +30805,7 @@ ma_result ma_rb_seek_read(ma_rb* pRB, size_t offsetInBytes) newReadOffsetInBytes = (ma_uint32)(readOffsetInBytes + offsetInBytes); } } else { - // May end up looping. + /* May end up looping. */ if ((readOffsetInBytes + offsetInBytes) >= pRB->subbufferSizeInBytes) { newReadOffsetInBytes = (ma_uint32)(readOffsetInBytes + offsetInBytes) - pRB->subbufferSizeInBytes; newReadOffsetLoopFlag ^= 0x80000000; /* <-- Looped. */ @@ -29744,26 +30820,31 @@ ma_result ma_rb_seek_read(ma_rb* pRB, size_t offsetInBytes) ma_result ma_rb_seek_write(ma_rb* pRB, size_t offsetInBytes) { + ma_uint32 readOffset; + ma_uint32 readOffsetInBytes; + ma_uint32 readOffsetLoopFlag; + ma_uint32 writeOffset; + ma_uint32 writeOffsetInBytes; + ma_uint32 writeOffsetLoopFlag; + ma_uint32 newWriteOffsetInBytes; + ma_uint32 newWriteOffsetLoopFlag; + if (pRB == NULL) { return MA_INVALID_ARGS; } - ma_uint32 readOffset = pRB->encodedReadOffset; - ma_uint32 readOffsetInBytes; - ma_uint32 readOffsetLoopFlag; + readOffset = pRB->encodedReadOffset; ma_rb__deconstruct_offset(readOffset, &readOffsetInBytes, &readOffsetLoopFlag); - ma_uint32 writeOffset = pRB->encodedWriteOffset; - ma_uint32 writeOffsetInBytes; - ma_uint32 writeOffsetLoopFlag; + writeOffset = pRB->encodedWriteOffset; ma_rb__deconstruct_offset(writeOffset, &writeOffsetInBytes, &writeOffsetLoopFlag); - ma_uint32 newWriteOffsetInBytes = writeOffsetInBytes; - ma_uint32 newWriteOffsetLoopFlag = writeOffsetLoopFlag; + newWriteOffsetInBytes = writeOffsetInBytes; + newWriteOffsetLoopFlag = writeOffsetLoopFlag; - // We cannot go past the write buffer. + /* We cannot go past the write buffer. */ if (readOffsetLoopFlag == writeOffsetLoopFlag) { - // May end up looping. + /* May end up looping. */ if ((writeOffsetInBytes + offsetInBytes) >= pRB->subbufferSizeInBytes) { newWriteOffsetInBytes = (ma_uint32)(writeOffsetInBytes + offsetInBytes) - pRB->subbufferSizeInBytes; newWriteOffsetLoopFlag ^= 0x80000000; /* <-- Looped. */ @@ -29784,18 +30865,21 @@ ma_result ma_rb_seek_write(ma_rb* pRB, size_t offsetInBytes) ma_int32 ma_rb_pointer_distance(ma_rb* pRB) { + ma_uint32 readOffset; + ma_uint32 readOffsetInBytes; + ma_uint32 readOffsetLoopFlag; + ma_uint32 writeOffset; + ma_uint32 writeOffsetInBytes; + ma_uint32 writeOffsetLoopFlag; + if (pRB == NULL) { return 0; } - ma_uint32 readOffset = pRB->encodedReadOffset; - ma_uint32 readOffsetInBytes; - ma_uint32 readOffsetLoopFlag; + readOffset = pRB->encodedReadOffset; ma_rb__deconstruct_offset(readOffset, &readOffsetInBytes, &readOffsetLoopFlag); - ma_uint32 writeOffset = pRB->encodedWriteOffset; - ma_uint32 writeOffsetInBytes; - ma_uint32 writeOffsetLoopFlag; + writeOffset = pRB->encodedWriteOffset; ma_rb__deconstruct_offset(writeOffset, &writeOffsetInBytes, &writeOffsetLoopFlag); if (readOffsetLoopFlag == writeOffsetLoopFlag) { @@ -29855,18 +30939,21 @@ static MA_INLINE ma_uint32 ma_pcm_rb_get_bpf(ma_pcm_rb* pRB) ma_result ma_pcm_rb_init_ex(ma_format format, ma_uint32 channels, ma_uint32 subbufferSizeInFrames, ma_uint32 subbufferCount, ma_uint32 subbufferStrideInFrames, void* pOptionalPreallocatedBuffer, ma_pcm_rb* pRB) { + ma_uint32 bpf; + ma_result result; + if (pRB == NULL) { return MA_INVALID_ARGS; } ma_zero_object(pRB); - ma_uint32 bpf = ma_get_bytes_per_frame(format, channels); + bpf = ma_get_bytes_per_frame(format, channels); if (bpf == 0) { return MA_INVALID_ARGS; } - ma_result result = ma_rb_init_ex(subbufferSizeInFrames*bpf, subbufferCount, subbufferStrideInFrames*bpf, pOptionalPreallocatedBuffer, &pRB->rb); + result = ma_rb_init_ex(subbufferSizeInFrames*bpf, subbufferCount, subbufferStrideInFrames*bpf, pOptionalPreallocatedBuffer, &pRB->rb); if (result != MA_SUCCESS) { return result; } @@ -30014,14 +31101,11 @@ void* ma_pcm_rb_get_subbuffer_ptr(ma_pcm_rb* pRB, ma_uint32 subbufferIndex, void -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Miscellaneous Helpers -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +/************************************************************************************************************************************************************** + +Miscellaneous Helpers +**************************************************************************************************************************************************************/ void* ma_malloc(size_t sz) { return MA_MALLOC(sz); @@ -30039,18 +31123,22 @@ void ma_free(void* p) void* ma_aligned_malloc(size_t sz, size_t alignment) { + size_t extraBytes; + void* pUnaligned; + void* pAligned; + if (alignment == 0) { return 0; } - size_t extraBytes = alignment-1 + sizeof(void*); + extraBytes = alignment-1 + sizeof(void*); - void* pUnaligned = ma_malloc(sz + extraBytes); + pUnaligned = ma_malloc(sz + extraBytes); if (pUnaligned == NULL) { return NULL; } - void* pAligned = (void*)(((ma_uintptr)pUnaligned + extraBytes) & ~((ma_uintptr)(alignment-1))); + pAligned = (void*)(((ma_uintptr)pUnaligned + extraBytes) & ~((ma_uintptr)(alignment-1))); ((void**)pAligned)[-1] = pUnaligned; return pAligned; @@ -30077,7 +31165,8 @@ const char* ma_get_format_name(ma_format format) void ma_blend_f32(float* pOut, float* pInA, float* pInB, float factor, ma_uint32 channels) { - for (ma_uint32 i = 0; i < channels; ++i) { + ma_uint32 i; + for (i = 0; i < channels; ++i) { pOut[i] = ma_mix_f32(pInA[i], pInB[i], factor); } } @@ -30086,32 +31175,32 @@ void ma_blend_f32(float* pOut, float* pInA, float* pInB, float factor, ma_uint32 ma_uint32 ma_get_bytes_per_sample(ma_format format) { ma_uint32 sizes[] = { - 0, // unknown - 1, // u8 - 2, // s16 - 3, // s24 - 4, // s32 - 4, // f32 + 0, /* unknown */ + 1, /* u8 */ + 2, /* s16 */ + 3, /* s24 */ + 4, /* s32 */ + 4, /* f32 */ }; return sizes[format]; } -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// DECODING -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +/************************************************************************************************************************************************************** + +Decoding + +**************************************************************************************************************************************************************/ #ifndef MA_NO_DECODING size_t ma_decoder_read_bytes(ma_decoder* pDecoder, void* pBufferOut, size_t bytesToRead) { + size_t bytesRead; + ma_assert(pDecoder != NULL); ma_assert(pBufferOut != NULL); - size_t bytesRead = pDecoder->onRead(pDecoder, pBufferOut, bytesToRead); + bytesRead = pDecoder->onRead(pDecoder, pBufferOut, bytesToRead); pDecoder->readPointer += bytesRead; return bytesRead; @@ -30119,9 +31208,11 @@ size_t ma_decoder_read_bytes(ma_decoder* pDecoder, void* pBufferOut, size_t byte ma_bool32 ma_decoder_seek_bytes(ma_decoder* pDecoder, int byteOffset, ma_seek_origin origin) { + ma_bool32 wasSuccessful; + ma_assert(pDecoder != NULL); - ma_bool32 wasSuccessful = pDecoder->onSeek(pDecoder, byteOffset, origin); + wasSuccessful = pDecoder->onSeek(pDecoder, byteOffset, origin); if (wasSuccessful) { if (origin == ma_seek_origin_start) { pDecoder->readPointer = (ma_uint64)byteOffset; @@ -30194,9 +31285,11 @@ ma_decoder_config ma_decoder_config_init_copy(const ma_decoder_config* pConfig) ma_result ma_decoder__init_dsp(ma_decoder* pDecoder, const ma_decoder_config* pConfig, ma_pcm_converter_read_proc onRead) { + ma_pcm_converter_config dspConfig; + ma_assert(pDecoder != NULL); - // Output format. + /* Output format. */ if (pConfig->format == ma_format_unknown) { pDecoder->outputFormat = pDecoder->internalFormat; } else { @@ -30222,8 +31315,8 @@ ma_result ma_decoder__init_dsp(ma_decoder* pDecoder, const ma_decoder_config* pC } - // DSP. - ma_pcm_converter_config dspConfig = ma_pcm_converter_config_init_ex( + /* DSP. */ + dspConfig = ma_pcm_converter_config_init_ex( pDecoder->internalFormat, pDecoder->internalChannels, pDecoder->internalSampleRate, pDecoder->internalChannelMap, pDecoder->outputFormat, pDecoder->outputChannels, pDecoder->outputSampleRate, pDecoder->outputChannelMap, onRead, pDecoder); @@ -30235,7 +31328,7 @@ ma_result ma_decoder__init_dsp(ma_decoder* pDecoder, const ma_decoder_config* pC return ma_pcm_converter_init(&dspConfig, &pDecoder->dsp); } -// WAV +/* WAV */ #ifdef dr_wav_h #define MA_HAS_WAV @@ -30257,12 +31350,15 @@ drwav_bool32 ma_decoder_internal_on_seek__wav(void* pUserData, int offset, drwav ma_uint32 ma_decoder_internal_on_read_pcm_frames__wav(ma_pcm_converter* pDSP, void* pSamplesOut, ma_uint32 frameCount, void* pUserData) { + ma_decoder* pDecoder; + drwav* pWav; + (void)pDSP; - ma_decoder* pDecoder = (ma_decoder*)pUserData; + pDecoder = (ma_decoder*)pUserData; ma_assert(pDecoder != NULL); - drwav* pWav = (drwav*)pDecoder->pInternalDecoder; + pWav = (drwav*)pDecoder->pInternalDecoder; ma_assert(pWav != NULL); switch (pDecoder->internalFormat) { @@ -30272,17 +31368,20 @@ ma_uint32 ma_decoder_internal_on_read_pcm_frames__wav(ma_pcm_converter* pDSP, vo default: break; } - // Should never get here. If we do, it means the internal format was not set correctly at initialization time. + /* Should never get here. If we do, it means the internal format was not set correctly at initialization time. */ ma_assert(MA_FALSE); return 0; } ma_result ma_decoder_internal_on_seek_to_pcm_frame__wav(ma_decoder* pDecoder, ma_uint64 frameIndex) { - drwav* pWav = (drwav*)pDecoder->pInternalDecoder; + drwav* pWav; + drwav_bool32 result; + + pWav = (drwav*)pDecoder->pInternalDecoder; ma_assert(pWav != NULL); - drwav_bool32 result = drwav_seek_to_pcm_frame(pWav, frameIndex); + result = drwav_seek_to_pcm_frame(pWav, frameIndex); if (result) { return MA_SUCCESS; } else { @@ -30298,21 +31397,24 @@ ma_result ma_decoder_internal_on_uninit__wav(ma_decoder* pDecoder) ma_result ma_decoder_init_wav__internal(const ma_decoder_config* pConfig, ma_decoder* pDecoder) { + drwav* pWav; + ma_result result; + ma_assert(pConfig != NULL); ma_assert(pDecoder != NULL); - // Try opening the decoder first. - drwav* pWav = drwav_open(ma_decoder_internal_on_read__wav, ma_decoder_internal_on_seek__wav, pDecoder); + /* Try opening the decoder first. */ + pWav = drwav_open(ma_decoder_internal_on_read__wav, ma_decoder_internal_on_seek__wav, pDecoder); if (pWav == NULL) { return MA_ERROR; } - // If we get here it means we successfully initialized the WAV decoder. We can now initialize the rest of the ma_decoder. + /* If we get here it means we successfully initialized the WAV decoder. We can now initialize the rest of the ma_decoder. */ pDecoder->onSeekToPCMFrame = ma_decoder_internal_on_seek_to_pcm_frame__wav; pDecoder->onUninit = ma_decoder_internal_on_uninit__wav; pDecoder->pInternalDecoder = pWav; - // Try to be as optimal as possible for the internal format. If miniaudio does not support a format we will fall back to f32. + /* Try to be as optimal as possible for the internal format. If miniaudio does not support a format we will fall back to f32. */ pDecoder->internalFormat = ma_format_unknown; switch (pWav->translatedFormatTag) { case DR_WAVE_FORMAT_PCM: @@ -30350,7 +31452,7 @@ ma_result ma_decoder_init_wav__internal(const ma_decoder_config* pConfig, ma_dec pDecoder->internalSampleRate = pWav->sampleRate; ma_get_standard_channel_map(ma_standard_channel_map_microsoft, pDecoder->internalChannels, pDecoder->internalChannelMap); - ma_result result = ma_decoder__init_dsp(pDecoder, pConfig, ma_decoder_internal_on_read_pcm_frames__wav); + result = ma_decoder__init_dsp(pDecoder, pConfig, ma_decoder_internal_on_read_pcm_frames__wav); if (result != MA_SUCCESS) { drwav_close(pWav); return result; @@ -30360,7 +31462,7 @@ ma_result ma_decoder_init_wav__internal(const ma_decoder_config* pConfig, ma_dec } #endif -// FLAC +/* FLAC */ #ifdef dr_flac_h #define MA_HAS_FLAC @@ -30382,12 +31484,15 @@ drflac_bool32 ma_decoder_internal_on_seek__flac(void* pUserData, int offset, drf ma_uint32 ma_decoder_internal_on_read_pcm_frames__flac(ma_pcm_converter* pDSP, void* pSamplesOut, ma_uint32 frameCount, void* pUserData) { + ma_decoder* pDecoder; + drflac* pFlac; + (void)pDSP; - ma_decoder* pDecoder = (ma_decoder*)pUserData; + pDecoder = (ma_decoder*)pUserData; ma_assert(pDecoder != NULL); - drflac* pFlac = (drflac*)pDecoder->pInternalDecoder; + pFlac = (drflac*)pDecoder->pInternalDecoder; ma_assert(pFlac != NULL); switch (pDecoder->internalFormat) { @@ -30397,17 +31502,20 @@ ma_uint32 ma_decoder_internal_on_read_pcm_frames__flac(ma_pcm_converter* pDSP, v default: break; } - // Should never get here. If we do, it means the internal format was not set correctly at initialization time. + /* Should never get here. If we do, it means the internal format was not set correctly at initialization time. */ ma_assert(MA_FALSE); return 0; } ma_result ma_decoder_internal_on_seek_to_pcm_frame__flac(ma_decoder* pDecoder, ma_uint64 frameIndex) { - drflac* pFlac = (drflac*)pDecoder->pInternalDecoder; + drflac* pFlac; + drflac_bool32 result; + + pFlac = (drflac*)pDecoder->pInternalDecoder; ma_assert(pFlac != NULL); - drflac_bool32 result = drflac_seek_to_pcm_frame(pFlac, frameIndex); + result = drflac_seek_to_pcm_frame(pFlac, frameIndex); if (result) { return MA_SUCCESS; } else { @@ -30423,22 +31531,27 @@ ma_result ma_decoder_internal_on_uninit__flac(ma_decoder* pDecoder) ma_result ma_decoder_init_flac__internal(const ma_decoder_config* pConfig, ma_decoder* pDecoder) { + drflac* pFlac; + ma_result result; + ma_assert(pConfig != NULL); ma_assert(pDecoder != NULL); - // Try opening the decoder first. - drflac* pFlac = drflac_open(ma_decoder_internal_on_read__flac, ma_decoder_internal_on_seek__flac, pDecoder); + /* Try opening the decoder first. */ + pFlac = drflac_open(ma_decoder_internal_on_read__flac, ma_decoder_internal_on_seek__flac, pDecoder); if (pFlac == NULL) { return MA_ERROR; } - // If we get here it means we successfully initialized the FLAC decoder. We can now initialize the rest of the ma_decoder. + /* If we get here it means we successfully initialized the FLAC decoder. We can now initialize the rest of the ma_decoder. */ pDecoder->onSeekToPCMFrame = ma_decoder_internal_on_seek_to_pcm_frame__flac; pDecoder->onUninit = ma_decoder_internal_on_uninit__flac; pDecoder->pInternalDecoder = pFlac; - // dr_flac supports reading as s32, s16 and f32. Try to do a one-to-one mapping if possible, but fall back to s32 if not. s32 is the "native" FLAC format - // since it's the only one that's truly lossless. + /* + dr_flac supports reading as s32, s16 and f32. Try to do a one-to-one mapping if possible, but fall back to s32 if not. s32 is the "native" FLAC format + since it's the only one that's truly lossless. + */ pDecoder->internalFormat = ma_format_s32; if (pConfig->format == ma_format_s16) { pDecoder->internalFormat = ma_format_s16; @@ -30450,7 +31563,7 @@ ma_result ma_decoder_init_flac__internal(const ma_decoder_config* pConfig, ma_de pDecoder->internalSampleRate = pFlac->sampleRate; ma_get_standard_channel_map(ma_standard_channel_map_flac, pDecoder->internalChannels, pDecoder->internalChannelMap); - ma_result result = ma_decoder__init_dsp(pDecoder, pConfig, ma_decoder_internal_on_read_pcm_frames__flac); + result = ma_decoder__init_dsp(pDecoder, pConfig, ma_decoder_internal_on_read_pcm_frames__flac); if (result != MA_SUCCESS) { drflac_close(pFlac); return result; @@ -30460,11 +31573,11 @@ ma_result ma_decoder_init_flac__internal(const ma_decoder_config* pConfig, ma_de } #endif -// Vorbis +/* Vorbis */ #ifdef STB_VORBIS_INCLUDE_STB_VORBIS_H #define MA_HAS_VORBIS -// The size in bytes of each chunk of data to read from the Vorbis stream. +/* The size in bytes of each chunk of data to read from the Vorbis stream. */ #define MA_VORBIS_DATA_CHUNK_SIZE 4096 typedef struct @@ -30473,23 +31586,27 @@ typedef struct ma_uint8* pData; size_t dataSize; size_t dataCapacity; - ma_uint32 framesConsumed; // The number of frames consumed in ppPacketData. - ma_uint32 framesRemaining; // The number of frames remaining in ppPacketData. + ma_uint32 framesConsumed; /* The number of frames consumed in ppPacketData. */ + ma_uint32 framesRemaining; /* The number of frames remaining in ppPacketData. */ float** ppPacketData; } ma_vorbis_decoder; ma_uint32 ma_vorbis_decoder_read_pcm_frames(ma_vorbis_decoder* pVorbis, ma_decoder* pDecoder, void* pSamplesOut, ma_uint32 frameCount) { + float* pSamplesOutF; + ma_uint32 totalFramesRead; + ma_assert(pVorbis != NULL); ma_assert(pDecoder != NULL); - float* pSamplesOutF = (float*)pSamplesOut; + pSamplesOutF = (float*)pSamplesOut; - ma_uint32 totalFramesRead = 0; + totalFramesRead = 0; while (frameCount > 0) { - // Read from the in-memory buffer first. + /* Read from the in-memory buffer first. */ while (pVorbis->framesRemaining > 0 && frameCount > 0) { - for (ma_uint32 iChannel = 0; iChannel < pDecoder->internalChannels; ++iChannel) { + ma_uint32 iChannel; + for (iChannel = 0; iChannel < pDecoder->internalChannels; ++iChannel) { pSamplesOutF[0] = pVorbis->ppPacketData[iChannel][pVorbis->framesConsumed]; pSamplesOutF += 1; } @@ -30506,18 +31623,22 @@ ma_uint32 ma_vorbis_decoder_read_pcm_frames(ma_vorbis_decoder* pVorbis, ma_decod ma_assert(pVorbis->framesRemaining == 0); - // We've run out of cached frames, so decode the next packet and continue iteration. + /* We've run out of cached frames, so decode the next packet and continue iteration. */ do { + int samplesRead; + int consumedDataSize; + if (pVorbis->dataSize > INT_MAX) { - break; // Too big. + break; /* Too big. */ } - int samplesRead = 0; - int consumedDataSize = stb_vorbis_decode_frame_pushdata(pVorbis->pInternalVorbis, pVorbis->pData, (int)pVorbis->dataSize, NULL, (float***)&pVorbis->ppPacketData, &samplesRead); + samplesRead = 0; + consumedDataSize = stb_vorbis_decode_frame_pushdata(pVorbis->pInternalVorbis, pVorbis->pData, (int)pVorbis->dataSize, NULL, (float***)&pVorbis->ppPacketData, &samplesRead); if (consumedDataSize != 0) { size_t leftoverDataSize = (pVorbis->dataSize - (size_t)consumedDataSize); - for (size_t i = 0; i < leftoverDataSize; ++i) { + size_t i; + for (i = 0; i < leftoverDataSize; ++i) { pVorbis->pData[i] = pVorbis->pData[i + consumedDataSize]; } @@ -30526,22 +31647,26 @@ ma_uint32 ma_vorbis_decoder_read_pcm_frames(ma_vorbis_decoder* pVorbis, ma_decod pVorbis->framesRemaining = samplesRead; break; } else { - // Need more data. If there's any room in the existing buffer allocation fill that first. Otherwise expand. + /* Need more data. If there's any room in the existing buffer allocation fill that first. Otherwise expand. */ + size_t bytesRead; if (pVorbis->dataCapacity == pVorbis->dataSize) { - // No room. Expand. - pVorbis->dataCapacity += MA_VORBIS_DATA_CHUNK_SIZE; - ma_uint8* pNewData = (ma_uint8*)ma_realloc(pVorbis->pData, pVorbis->dataCapacity); + /* No room. Expand. */ + size_t newCap = pVorbis->dataCapacity + MA_VORBIS_DATA_CHUNK_SIZE; + ma_uint8* pNewData; + + pNewData = (ma_uint8*)ma_realloc(pVorbis->pData, newCap); if (pNewData == NULL) { - return totalFramesRead; // Out of memory. + return totalFramesRead; /* Out of memory. */ } pVorbis->pData = pNewData; + pVorbis->dataCapacity = newCap; } - // Fill in a chunk. - size_t bytesRead = ma_decoder_read_bytes(pDecoder, pVorbis->pData + pVorbis->dataSize, (pVorbis->dataCapacity - pVorbis->dataSize)); + /* Fill in a chunk. */ + bytesRead = ma_decoder_read_bytes(pDecoder, pVorbis->pData + pVorbis->dataSize, (pVorbis->dataCapacity - pVorbis->dataSize)); if (bytesRead == 0) { - return totalFramesRead; // Error reading more data. + return totalFramesRead; /* Error reading more data. */ } pVorbis->dataSize += bytesRead; @@ -30554,12 +31679,16 @@ ma_uint32 ma_vorbis_decoder_read_pcm_frames(ma_vorbis_decoder* pVorbis, ma_decod ma_result ma_vorbis_decoder_seek_to_pcm_frame(ma_vorbis_decoder* pVorbis, ma_decoder* pDecoder, ma_uint64 frameIndex) { + float buffer[4096]; + ma_assert(pVorbis != NULL); ma_assert(pDecoder != NULL); - // This is terribly inefficient because stb_vorbis does not have a good seeking solution with it's push API. Currently this just performs - // a full decode right from the start of the stream. Later on I'll need to write a layer that goes through all of the Ogg pages until we - // find the one containing the sample we need. Then we know exactly where to seek for stb_vorbis. + /* + This is terribly inefficient because stb_vorbis does not have a good seeking solution with it's push API. Currently this just performs + a full decode right from the start of the stream. Later on I'll need to write a layer that goes through all of the Ogg pages until we + find the one containing the sample we need. Then we know exactly where to seek for stb_vorbis. + */ if (!ma_decoder_seek_bytes(pDecoder, 0, ma_seek_origin_start)) { return MA_ERROR; } @@ -30569,14 +31698,14 @@ ma_result ma_vorbis_decoder_seek_to_pcm_frame(ma_vorbis_decoder* pVorbis, ma_dec pVorbis->framesRemaining = 0; pVorbis->dataSize = 0; - float buffer[4096]; while (frameIndex > 0) { + ma_uint32 framesRead; ma_uint32 framesToRead = ma_countof(buffer)/pDecoder->internalChannels; if (framesToRead > frameIndex) { framesToRead = (ma_uint32)frameIndex; } - ma_uint32 framesRead = ma_vorbis_decoder_read_pcm_frames(pVorbis, pDecoder, buffer, framesToRead); + framesRead = ma_vorbis_decoder_read_pcm_frames(pVorbis, pDecoder, buffer, framesToRead); if (framesRead == 0) { return MA_ERROR; } @@ -30590,8 +31719,6 @@ ma_result ma_vorbis_decoder_seek_to_pcm_frame(ma_vorbis_decoder* pVorbis, ma_dec ma_result ma_decoder_internal_on_seek_to_pcm_frame__vorbis(ma_decoder* pDecoder, ma_uint64 frameIndex) { - ma_assert(pDecoder != NULL); - ma_vorbis_decoder* pVorbis = (ma_vorbis_decoder*)pDecoder->pInternalDecoder; ma_assert(pVorbis != NULL); @@ -30612,13 +31739,16 @@ ma_result ma_decoder_internal_on_uninit__vorbis(ma_decoder* pDecoder) ma_uint32 ma_decoder_internal_on_read_pcm_frames__vorbis(ma_pcm_converter* pDSP, void* pSamplesOut, ma_uint32 frameCount, void* pUserData) { + ma_decoder* pDecoder; + ma_vorbis_decoder* pVorbis; + (void)pDSP; - ma_decoder* pDecoder = (ma_decoder*)pUserData; + pDecoder = (ma_decoder*)pUserData; ma_assert(pDecoder != NULL); ma_assert(pDecoder->internalFormat == ma_format_f32); - ma_vorbis_decoder* pVorbis = (ma_vorbis_decoder*)pDecoder->pInternalDecoder; + pVorbis = (ma_vorbis_decoder*)pDecoder->pInternalDecoder; ma_assert(pVorbis != NULL); return ma_vorbis_decoder_read_pcm_frames(pVorbis, pDecoder, pSamplesOut, frameCount); @@ -30626,20 +31756,29 @@ ma_uint32 ma_decoder_internal_on_read_pcm_frames__vorbis(ma_pcm_converter* pDSP, ma_result ma_decoder_init_vorbis__internal(const ma_decoder_config* pConfig, ma_decoder* pDecoder) { - ma_assert(pConfig != NULL); - ma_assert(pDecoder != NULL); - + ma_result result; stb_vorbis* pInternalVorbis = NULL; - - // We grow the buffer in chunks. size_t dataSize = 0; size_t dataCapacity = 0; ma_uint8* pData = NULL; + stb_vorbis_info vorbisInfo; + size_t vorbisDataSize; + ma_vorbis_decoder* pVorbis; + + ma_assert(pConfig != NULL); + ma_assert(pDecoder != NULL); + + /* We grow the buffer in chunks. */ do { - // Allocate memory for a new chunk. + /* Allocate memory for a new chunk. */ + ma_uint8* pNewData; + size_t bytesRead; + int vorbisError = 0; + int consumedDataSize = 0; + dataCapacity += MA_VORBIS_DATA_CHUNK_SIZE; - ma_uint8* pNewData = (ma_uint8*)ma_realloc(pData, dataCapacity); + pNewData = (ma_uint8*)ma_realloc(pData, dataCapacity); if (pNewData == NULL) { ma_free(pData); return MA_OUT_OF_MEMORY; @@ -30647,52 +31786,53 @@ ma_result ma_decoder_init_vorbis__internal(const ma_decoder_config* pConfig, ma_ pData = pNewData; - // Fill in a chunk. - size_t bytesRead = ma_decoder_read_bytes(pDecoder, pData + dataSize, (dataCapacity - dataSize)); + /* Fill in a chunk. */ + bytesRead = ma_decoder_read_bytes(pDecoder, pData + dataSize, (dataCapacity - dataSize)); if (bytesRead == 0) { return MA_ERROR; } dataSize += bytesRead; if (dataSize > INT_MAX) { - return MA_ERROR; // Too big. + return MA_ERROR; /* Too big. */ } - int vorbisError = 0; - int consumedDataSize = 0; pInternalVorbis = stb_vorbis_open_pushdata(pData, (int)dataSize, &consumedDataSize, &vorbisError, NULL); if (pInternalVorbis != NULL) { - // If we get here it means we were able to open the stb_vorbis decoder. There may be some leftover bytes in our buffer, so - // we need to move those bytes down to the front of the buffer since they'll be needed for future decoding. + /* + If we get here it means we were able to open the stb_vorbis decoder. There may be some leftover bytes in our buffer, so + we need to move those bytes down to the front of the buffer since they'll be needed for future decoding. + */ size_t leftoverDataSize = (dataSize - (size_t)consumedDataSize); - for (size_t i = 0; i < leftoverDataSize; ++i) { + size_t i; + for (i = 0; i < leftoverDataSize; ++i) { pData[i] = pData[i + consumedDataSize]; } dataSize = leftoverDataSize; - break; // Success. + break; /* Success. */ } else { if (vorbisError == VORBIS_need_more_data) { continue; } else { - return MA_ERROR; // Failed to open the stb_vorbis decoder. + return MA_ERROR; /* Failed to open the stb_vorbis decoder. */ } } } while (MA_TRUE); - // If we get here it means we successfully opened the Vorbis decoder. - stb_vorbis_info vorbisInfo = stb_vorbis_get_info(pInternalVorbis); + /* If we get here it means we successfully opened the Vorbis decoder. */ + vorbisInfo = stb_vorbis_get_info(pInternalVorbis); - // Don't allow more than MA_MAX_CHANNELS channels. + /* Don't allow more than MA_MAX_CHANNELS channels. */ if (vorbisInfo.channels > MA_MAX_CHANNELS) { stb_vorbis_close(pInternalVorbis); ma_free(pData); - return MA_ERROR; // Too many channels. + return MA_ERROR; /* Too many channels. */ } - size_t vorbisDataSize = sizeof(ma_vorbis_decoder) + sizeof(float)*vorbisInfo.max_frame_size; - ma_vorbis_decoder* pVorbis = (ma_vorbis_decoder*)ma_malloc(vorbisDataSize); + vorbisDataSize = sizeof(ma_vorbis_decoder) + sizeof(float)*vorbisInfo.max_frame_size; + pVorbis = (ma_vorbis_decoder*)ma_malloc(vorbisDataSize); if (pVorbis == NULL) { stb_vorbis_close(pInternalVorbis); ma_free(pData); @@ -30709,13 +31849,13 @@ ma_result ma_decoder_init_vorbis__internal(const ma_decoder_config* pConfig, ma_ pDecoder->onUninit = ma_decoder_internal_on_uninit__vorbis; pDecoder->pInternalDecoder = pVorbis; - // The internal format is always f32. + /* The internal format is always f32. */ pDecoder->internalFormat = ma_format_f32; pDecoder->internalChannels = vorbisInfo.channels; pDecoder->internalSampleRate = vorbisInfo.sample_rate; ma_get_standard_channel_map(ma_standard_channel_map_vorbis, pDecoder->internalChannels, pDecoder->internalChannelMap); - ma_result result = ma_decoder__init_dsp(pDecoder, pConfig, ma_decoder_internal_on_read_pcm_frames__vorbis); + result = ma_decoder__init_dsp(pDecoder, pConfig, ma_decoder_internal_on_read_pcm_frames__vorbis); if (result != MA_SUCCESS) { stb_vorbis_close(pVorbis->pInternalVorbis); ma_free(pVorbis->pData); @@ -30727,7 +31867,7 @@ ma_result ma_decoder_init_vorbis__internal(const ma_decoder_config* pConfig, ma_ } #endif -// MP3 +/* MP3 */ #ifdef dr_mp3_h #define MA_HAS_MP3 @@ -30749,13 +31889,16 @@ drmp3_bool32 ma_decoder_internal_on_seek__mp3(void* pUserData, int offset, drmp3 ma_uint32 ma_decoder_internal_on_read_pcm_frames__mp3(ma_pcm_converter* pDSP, void* pSamplesOut, ma_uint32 frameCount, void* pUserData) { + ma_decoder* pDecoder; + drmp3* pMP3; + (void)pDSP; - ma_decoder* pDecoder = (ma_decoder*)pUserData; + pDecoder = (ma_decoder*)pUserData; ma_assert(pDecoder != NULL); ma_assert(pDecoder->internalFormat == ma_format_f32); - drmp3* pMP3 = (drmp3*)pDecoder->pInternalDecoder; + pMP3 = (drmp3*)pDecoder->pInternalDecoder; ma_assert(pMP3 != NULL); return (ma_uint32)drmp3_read_pcm_frames_f32(pMP3, frameCount, (float*)pSamplesOut); @@ -30763,10 +31906,13 @@ ma_uint32 ma_decoder_internal_on_read_pcm_frames__mp3(ma_pcm_converter* pDSP, vo ma_result ma_decoder_internal_on_seek_to_pcm_frame__mp3(ma_decoder* pDecoder, ma_uint64 frameIndex) { - drmp3* pMP3 = (drmp3*)pDecoder->pInternalDecoder; + drmp3* pMP3; + drmp3_bool32 result; + + pMP3 = (drmp3*)pDecoder->pInternalDecoder; ma_assert(pMP3 != NULL); - drmp3_bool32 result = drmp3_seek_to_pcm_frame(pMP3, frameIndex); + result = drmp3_seek_to_pcm_frame(pMP3, frameIndex); if (result) { return MA_SUCCESS; } else { @@ -30783,24 +31929,29 @@ ma_result ma_decoder_internal_on_uninit__mp3(ma_decoder* pDecoder) ma_result ma_decoder_init_mp3__internal(const ma_decoder_config* pConfig, ma_decoder* pDecoder) { + drmp3* pMP3; + drmp3_config mp3Config; + ma_result result; + ma_assert(pConfig != NULL); ma_assert(pDecoder != NULL); - drmp3* pMP3 = (drmp3*)ma_malloc(sizeof(*pMP3)); + pMP3 = (drmp3*)ma_malloc(sizeof(*pMP3)); if (pMP3 == NULL) { return MA_OUT_OF_MEMORY; } - // Try opening the decoder first. MP3 can have variable sample rates (it's per frame/packet). We therefore need - // to use some smarts to determine the most appropriate internal sample rate. These are the rules we're going - // to use: - // - // Sample Rates - // 1) If an output sample rate is specified in pConfig we just use that. Otherwise; - // 2) Fall back to 44100. - // - // The internal channel count is always stereo, and the internal format is always f32. - drmp3_config mp3Config; + /* + Try opening the decoder first. MP3 can have variable sample rates (it's per frame/packet). We therefore need + to use some smarts to determine the most appropriate internal sample rate. These are the rules we're going + to use: + + Sample Rates + 1) If an output sample rate is specified in pConfig we just use that. Otherwise; + 2) Fall back to 44100. + + The internal channel count is always stereo, and the internal format is always f32. + */ ma_zero_object(&mp3Config); mp3Config.outputChannels = 2; mp3Config.outputSampleRate = (pConfig->sampleRate != 0) ? pConfig->sampleRate : 44100; @@ -30808,18 +31959,18 @@ ma_result ma_decoder_init_mp3__internal(const ma_decoder_config* pConfig, ma_dec return MA_ERROR; } - // If we get here it means we successfully initialized the MP3 decoder. We can now initialize the rest of the ma_decoder. + /* If we get here it means we successfully initialized the MP3 decoder. We can now initialize the rest of the ma_decoder. */ pDecoder->onSeekToPCMFrame = ma_decoder_internal_on_seek_to_pcm_frame__mp3; pDecoder->onUninit = ma_decoder_internal_on_uninit__mp3; pDecoder->pInternalDecoder = pMP3; - // Internal format. + /* Internal format. */ pDecoder->internalFormat = ma_format_f32; pDecoder->internalChannels = pMP3->channels; pDecoder->internalSampleRate = pMP3->sampleRate; ma_get_standard_channel_map(ma_standard_channel_map_default, pDecoder->internalChannels, pDecoder->internalChannelMap); - ma_result result = ma_decoder__init_dsp(pDecoder, pConfig, ma_decoder_internal_on_read_pcm_frames__mp3); + result = ma_decoder__init_dsp(pDecoder, pConfig, ma_decoder_internal_on_read_pcm_frames__mp3); if (result != MA_SUCCESS) { ma_free(pMP3); return result; @@ -30829,36 +31980,40 @@ ma_result ma_decoder_init_mp3__internal(const ma_decoder_config* pConfig, ma_dec } #endif -// Raw +/* Raw */ ma_uint32 ma_decoder_internal_on_read_pcm_frames__raw(ma_pcm_converter* pDSP, void* pSamplesOut, ma_uint32 frameCount, void* pUserData) { + ma_decoder* pDecoder; + ma_uint32 bpf; + (void)pDSP; - ma_decoder* pDecoder = (ma_decoder*)pUserData; + pDecoder = (ma_decoder*)pUserData; ma_assert(pDecoder != NULL); - // For raw decoding we just read directly from the decoder's callbacks. - ma_uint32 bpf = ma_get_bytes_per_frame(pDecoder->internalFormat, pDecoder->internalChannels); + /* For raw decoding we just read directly from the decoder's callbacks. */ + bpf = ma_get_bytes_per_frame(pDecoder->internalFormat, pDecoder->internalChannels); return (ma_uint32)ma_decoder_read_bytes(pDecoder, pSamplesOut, frameCount * bpf) / bpf; } ma_result ma_decoder_internal_on_seek_to_pcm_frame__raw(ma_decoder* pDecoder, ma_uint64 frameIndex) { + ma_bool32 result = MA_FALSE; + ma_uint64 totalBytesToSeek; + ma_assert(pDecoder != NULL); if (pDecoder->onSeek == NULL) { return MA_ERROR; } - ma_bool32 result = MA_FALSE; - - // The callback uses a 32 bit integer whereas we use a 64 bit unsigned integer. We just need to continuously seek until we're at the correct position. - ma_uint64 totalBytesToSeek = frameIndex * ma_get_bytes_per_frame(pDecoder->internalFormat, pDecoder->internalChannels); + /* The callback uses a 32 bit integer whereas we use a 64 bit unsigned integer. We just need to continuously seek until we're at the correct position. */ + totalBytesToSeek = frameIndex * ma_get_bytes_per_frame(pDecoder->internalFormat, pDecoder->internalChannels); if (totalBytesToSeek < 0x7FFFFFFF) { - // Simple case. + /* Simple case. */ result = ma_decoder_seek_bytes(pDecoder, (int)(frameIndex * ma_get_bytes_per_frame(pDecoder->internalFormat, pDecoder->internalChannels)), ma_seek_origin_start); } else { - // Complex case. Start by doing a seek relative to the start. Then keep looping using offset seeking. + /* Complex case. Start by doing a seek relative to the start. Then keep looping using offset seeking. */ result = ma_decoder_seek_bytes(pDecoder, 0x7FFFFFFF, ma_seek_origin_start); if (result == MA_TRUE) { totalBytesToSeek -= 0x7FFFFFFF; @@ -30894,6 +32049,8 @@ ma_result ma_decoder_internal_on_uninit__raw(ma_decoder* pDecoder) ma_result ma_decoder_init_raw__internal(const ma_decoder_config* pConfigIn, const ma_decoder_config* pConfigOut, ma_decoder* pDecoder) { + ma_result result; + ma_assert(pConfigIn != NULL); ma_assert(pConfigOut != NULL); ma_assert(pDecoder != NULL); @@ -30901,13 +32058,13 @@ ma_result ma_decoder_init_raw__internal(const ma_decoder_config* pConfigIn, cons pDecoder->onSeekToPCMFrame = ma_decoder_internal_on_seek_to_pcm_frame__raw; pDecoder->onUninit = ma_decoder_internal_on_uninit__raw; - // Internal format. + /* Internal format. */ pDecoder->internalFormat = pConfigIn->format; pDecoder->internalChannels = pConfigIn->channels; pDecoder->internalSampleRate = pConfigIn->sampleRate; ma_channel_map_copy(pDecoder->internalChannelMap, pConfigIn->channelMap, pConfigIn->channels); - ma_result result = ma_decoder__init_dsp(pDecoder, pConfigOut, ma_decoder_internal_on_read_pcm_frames__raw); + result = ma_decoder__init_dsp(pDecoder, pConfigOut, ma_decoder_internal_on_read_pcm_frames__raw); if (result != MA_SUCCESS) { return result; } @@ -30939,9 +32096,12 @@ ma_result ma_decoder__preinit(ma_decoder_read_proc onRead, ma_decoder_seek_proc ma_result ma_decoder_init_wav(ma_decoder_read_proc onRead, ma_decoder_seek_proc onSeek, void* pUserData, const ma_decoder_config* pConfig, ma_decoder* pDecoder) { - ma_decoder_config config = ma_decoder_config_init_copy(pConfig); + ma_decoder_config config; + ma_result result; - ma_result result = ma_decoder__preinit(onRead, onSeek, pUserData, &config, pDecoder); + config = ma_decoder_config_init_copy(pConfig); + + result = ma_decoder__preinit(onRead, onSeek, pUserData, &config, pDecoder); if (result != MA_SUCCESS) { return result; } @@ -30955,9 +32115,12 @@ ma_result ma_decoder_init_wav(ma_decoder_read_proc onRead, ma_decoder_seek_proc ma_result ma_decoder_init_flac(ma_decoder_read_proc onRead, ma_decoder_seek_proc onSeek, void* pUserData, const ma_decoder_config* pConfig, ma_decoder* pDecoder) { - ma_decoder_config config = ma_decoder_config_init_copy(pConfig); + ma_decoder_config config; + ma_result result; + + config = ma_decoder_config_init_copy(pConfig); - ma_result result = ma_decoder__preinit(onRead, onSeek, pUserData, &config, pDecoder); + result = ma_decoder__preinit(onRead, onSeek, pUserData, &config, pDecoder); if (result != MA_SUCCESS) { return result; } @@ -30971,9 +32134,12 @@ ma_result ma_decoder_init_flac(ma_decoder_read_proc onRead, ma_decoder_seek_proc ma_result ma_decoder_init_vorbis(ma_decoder_read_proc onRead, ma_decoder_seek_proc onSeek, void* pUserData, const ma_decoder_config* pConfig, ma_decoder* pDecoder) { - ma_decoder_config config = ma_decoder_config_init_copy(pConfig); + ma_decoder_config config; + ma_result result; - ma_result result = ma_decoder__preinit(onRead, onSeek, pUserData, &config, pDecoder); + config = ma_decoder_config_init_copy(pConfig); + + result = ma_decoder__preinit(onRead, onSeek, pUserData, &config, pDecoder); if (result != MA_SUCCESS) { return result; } @@ -30987,9 +32153,12 @@ ma_result ma_decoder_init_vorbis(ma_decoder_read_proc onRead, ma_decoder_seek_pr ma_result ma_decoder_init_mp3(ma_decoder_read_proc onRead, ma_decoder_seek_proc onSeek, void* pUserData, const ma_decoder_config* pConfig, ma_decoder* pDecoder) { - ma_decoder_config config = ma_decoder_config_init_copy(pConfig); + ma_decoder_config config; + ma_result result; + + config = ma_decoder_config_init_copy(pConfig); - ma_result result = ma_decoder__preinit(onRead, onSeek, pUserData, &config, pDecoder); + result = ma_decoder__preinit(onRead, onSeek, pUserData, &config, pDecoder); if (result != MA_SUCCESS) { return result; } @@ -31003,9 +32172,12 @@ ma_result ma_decoder_init_mp3(ma_decoder_read_proc onRead, ma_decoder_seek_proc ma_result ma_decoder_init_raw(ma_decoder_read_proc onRead, ma_decoder_seek_proc onSeek, void* pUserData, const ma_decoder_config* pConfigIn, const ma_decoder_config* pConfigOut, ma_decoder* pDecoder) { - ma_decoder_config config = ma_decoder_config_init_copy(pConfigOut); + ma_decoder_config config; + ma_result result; - ma_result result = ma_decoder__preinit(onRead, onSeek, pUserData, &config, pDecoder); + config = ma_decoder_config_init_copy(pConfigOut); + + result = ma_decoder__preinit(onRead, onSeek, pUserData, &config, pDecoder); if (result != MA_SUCCESS) { return result; } @@ -31015,18 +32187,19 @@ ma_result ma_decoder_init_raw(ma_decoder_read_proc onRead, ma_decoder_seek_proc ma_result ma_decoder_init__internal(ma_decoder_read_proc onRead, ma_decoder_seek_proc onSeek, void* pUserData, const ma_decoder_config* pConfig, ma_decoder* pDecoder) { + ma_result result = MA_NO_BACKEND; + ma_assert(pConfig != NULL); ma_assert(pDecoder != NULL); - // Silence some warnings in the case that we don't have any decoder backends enabled. + /* Silence some warnings in the case that we don't have any decoder backends enabled. */ (void)onRead; (void)onSeek; (void)pUserData; (void)pConfig; (void)pDecoder; - // We use trial and error to open a decoder. - ma_result result = MA_NO_BACKEND; + /* We use trial and error to open a decoder. */ #ifdef MA_HAS_WAV if (result != MA_SUCCESS) { @@ -31070,9 +32243,12 @@ ma_result ma_decoder_init__internal(ma_decoder_read_proc onRead, ma_decoder_seek ma_result ma_decoder_init(ma_decoder_read_proc onRead, ma_decoder_seek_proc onSeek, void* pUserData, const ma_decoder_config* pConfig, ma_decoder* pDecoder) { - ma_decoder_config config = ma_decoder_config_init_copy(pConfig); + ma_decoder_config config; + ma_result result; - ma_result result = ma_decoder__preinit(onRead, onSeek, pUserData, &config, pDecoder); + config = ma_decoder_config_init_copy(pConfig); + + result = ma_decoder__preinit(onRead, onSeek, pUserData, &config, pDecoder); if (result != MA_SUCCESS) { return result; } @@ -31083,9 +32259,11 @@ ma_result ma_decoder_init(ma_decoder_read_proc onRead, ma_decoder_seek_proc onSe size_t ma_decoder__on_read_memory(ma_decoder* pDecoder, void* pBufferOut, size_t bytesToRead) { + size_t bytesRemaining; + ma_assert(pDecoder->memory.dataSize >= pDecoder->memory.currentReadPos); - size_t bytesRemaining = pDecoder->memory.dataSize - pDecoder->memory.currentReadPos; + bytesRemaining = pDecoder->memory.dataSize - pDecoder->memory.currentReadPos; if (bytesToRead > bytesRemaining) { bytesToRead = bytesRemaining; } @@ -31103,21 +32281,21 @@ ma_bool32 ma_decoder__on_seek_memory(ma_decoder* pDecoder, int byteOffset, ma_se if (origin == ma_seek_origin_current) { if (byteOffset > 0) { if (pDecoder->memory.currentReadPos + byteOffset > pDecoder->memory.dataSize) { - byteOffset = (int)(pDecoder->memory.dataSize - pDecoder->memory.currentReadPos); // Trying to seek too far forward. + byteOffset = (int)(pDecoder->memory.dataSize - pDecoder->memory.currentReadPos); /* Trying to seek too far forward. */ } } else { if (pDecoder->memory.currentReadPos < (size_t)-byteOffset) { - byteOffset = -(int)pDecoder->memory.currentReadPos; // Trying to seek too far backwards. + byteOffset = -(int)pDecoder->memory.currentReadPos; /* Trying to seek too far backwards. */ } } - // This will never underflow thanks to the clamps above. + /* This will never underflow thanks to the clamps above. */ pDecoder->memory.currentReadPos += byteOffset; } else { if ((ma_uint32)byteOffset <= pDecoder->memory.dataSize) { pDecoder->memory.currentReadPos = byteOffset; } else { - pDecoder->memory.currentReadPos = pDecoder->memory.dataSize; // Trying to seek too far forward. + pDecoder->memory.currentReadPos = pDecoder->memory.dataSize; /* Trying to seek too far forward. */ } } @@ -31145,9 +32323,12 @@ ma_result ma_decoder__preinit_memory(const void* pData, size_t dataSize, const m ma_result ma_decoder_init_memory(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder) { - ma_decoder_config config = ma_decoder_config_init_copy(pConfig); // Make sure the config is not NULL. + ma_decoder_config config; + ma_result result; - ma_result result = ma_decoder__preinit_memory(pData, dataSize, &config, pDecoder); + config = ma_decoder_config_init_copy(pConfig); /* Make sure the config is not NULL. */ + + result = ma_decoder__preinit_memory(pData, dataSize, &config, pDecoder); if (result != MA_SUCCESS) { return result; } @@ -31157,9 +32338,12 @@ ma_result ma_decoder_init_memory(const void* pData, size_t dataSize, const ma_de ma_result ma_decoder_init_memory_wav(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder) { - ma_decoder_config config = ma_decoder_config_init_copy(pConfig); // Make sure the config is not NULL. + ma_decoder_config config; + ma_result result; + + config = ma_decoder_config_init_copy(pConfig); /* Make sure the config is not NULL. */ - ma_result result = ma_decoder__preinit_memory(pData, dataSize, &config, pDecoder); + result = ma_decoder__preinit_memory(pData, dataSize, &config, pDecoder); if (result != MA_SUCCESS) { return result; } @@ -31173,9 +32357,12 @@ ma_result ma_decoder_init_memory_wav(const void* pData, size_t dataSize, const m ma_result ma_decoder_init_memory_flac(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder) { - ma_decoder_config config = ma_decoder_config_init_copy(pConfig); // Make sure the config is not NULL. + ma_decoder_config config; + ma_result result; - ma_result result = ma_decoder__preinit_memory(pData, dataSize, &config, pDecoder); + config = ma_decoder_config_init_copy(pConfig); /* Make sure the config is not NULL. */ + + result = ma_decoder__preinit_memory(pData, dataSize, &config, pDecoder); if (result != MA_SUCCESS) { return result; } @@ -31189,9 +32376,12 @@ ma_result ma_decoder_init_memory_flac(const void* pData, size_t dataSize, const ma_result ma_decoder_init_memory_vorbis(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder) { - ma_decoder_config config = ma_decoder_config_init_copy(pConfig); // Make sure the config is not NULL. + ma_decoder_config config; + ma_result result; + + config = ma_decoder_config_init_copy(pConfig); /* Make sure the config is not NULL. */ - ma_result result = ma_decoder__preinit_memory(pData, dataSize, &config, pDecoder); + result = ma_decoder__preinit_memory(pData, dataSize, &config, pDecoder); if (result != MA_SUCCESS) { return result; } @@ -31205,9 +32395,12 @@ ma_result ma_decoder_init_memory_vorbis(const void* pData, size_t dataSize, cons ma_result ma_decoder_init_memory_mp3(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder) { - ma_decoder_config config = ma_decoder_config_init_copy(pConfig); // Make sure the config is not NULL. + ma_decoder_config config; + ma_result result; - ma_result result = ma_decoder__preinit_memory(pData, dataSize, &config, pDecoder); + config = ma_decoder_config_init_copy(pConfig); /* Make sure the config is not NULL. */ + + result = ma_decoder__preinit_memory(pData, dataSize, &config, pDecoder); if (result != MA_SUCCESS) { return result; } @@ -31221,9 +32414,12 @@ ma_result ma_decoder_init_memory_mp3(const void* pData, size_t dataSize, const m ma_result ma_decoder_init_memory_raw(const void* pData, size_t dataSize, const ma_decoder_config* pConfigIn, const ma_decoder_config* pConfigOut, ma_decoder* pDecoder) { - ma_decoder_config config = ma_decoder_config_init_copy(pConfigOut); // Make sure the config is not NULL. + ma_decoder_config config; + ma_result result; + + config = ma_decoder_config_init_copy(pConfigOut); /* Make sure the config is not NULL. */ - ma_result result = ma_decoder__preinit_memory(pData, dataSize, &config, pDecoder); + result = ma_decoder__preinit_memory(pData, dataSize, &config, pDecoder); if (result != MA_SUCCESS) { return result; } @@ -31234,18 +32430,20 @@ ma_result ma_decoder_init_memory_raw(const void* pData, size_t dataSize, const m #ifndef MA_NO_STDIO #include #if !defined(_MSC_VER) && !defined(__DMC__) -#include // For strcasecmp(). +#include /* For strcasecmp(). */ #endif const char* ma_path_file_name(const char* path) { + const char* fileName; + if (path == NULL) { return NULL; } - const char* fileName = path; + fileName = path; - // We just loop through the path until we find the last slash. + /* We just loop through the path until we find the last slash. */ while (path[0] != '\0') { if (path[0] == '/' || path[0] == '\\') { fileName = path; @@ -31254,7 +32452,7 @@ const char* ma_path_file_name(const char* path) path += 1; } - // At this point the file name is sitting on a slash, so just move forward. + /* At this point the file name is sitting on a slash, so just move forward. */ while (fileName[0] != '\0' && (fileName[0] == '/' || fileName[0] == '\\')) { fileName += 1; } @@ -31264,14 +32462,17 @@ const char* ma_path_file_name(const char* path) const char* ma_path_extension(const char* path) { + const char* extension; + const char* lastOccurance; + if (path == NULL) { path = ""; } - const char* extension = ma_path_file_name(path); - const char* lastOccurance = NULL; + extension = ma_path_file_name(path); + lastOccurance = NULL; - // Just find the last '.' and return. + /* Just find the last '.' and return. */ while (extension[0] != '\0') { if (extension[0] == '.') { extension += 1; @@ -31286,12 +32487,15 @@ const char* ma_path_extension(const char* path) ma_bool32 ma_path_extension_equal(const char* path, const char* extension) { + const char* ext1; + const char* ext2; + if (path == NULL || extension == NULL) { return MA_FALSE; } - const char* ext1 = extension; - const char* ext2 = ma_path_extension(path); + ext1 = extension; + ext2 = ma_path_extension(path); #if defined(_MSC_VER) || defined(__DMC__) return _stricmp(ext1, ext2) == 0; @@ -31312,6 +32516,8 @@ ma_bool32 ma_decoder__on_seek_stdio(ma_decoder* pDecoder, int byteOffset, ma_see ma_result ma_decoder__preinit_file(const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder) { + FILE* pFile; + if (pDecoder == NULL) { return MA_INVALID_ARGS; } @@ -31322,7 +32528,6 @@ ma_result ma_decoder__preinit_file(const char* pFilePath, const ma_decoder_confi return MA_INVALID_ARGS; } - FILE* pFile; #if defined(_MSC_VER) && _MSC_VER >= 1400 if (fopen_s(&pFile, pFilePath, "rb") != 0) { return MA_ERROR; @@ -31334,7 +32539,7 @@ ma_result ma_decoder__preinit_file(const char* pFilePath, const ma_decoder_confi } #endif - // We need to manually set the user data so the calls to ma_decoder__on_seek_stdio() succeed. + /* We need to manually set the user data so the calls to ma_decoder__on_seek_stdio() succeed. */ pDecoder->pUserData = pFile; (void)pConfig; @@ -31343,12 +32548,12 @@ ma_result ma_decoder__preinit_file(const char* pFilePath, const ma_decoder_confi ma_result ma_decoder_init_file(const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder) { - ma_result result = ma_decoder__preinit_file(pFilePath, pConfig, pDecoder); // This sets pDecoder->pUserData to a FILE*. + ma_result result = ma_decoder__preinit_file(pFilePath, pConfig, pDecoder); /* This sets pDecoder->pUserData to a FILE*. */ if (result != MA_SUCCESS) { return result; } - // WAV + /* WAV */ if (ma_path_extension_equal(pFilePath, "wav")) { result = ma_decoder_init_wav(ma_decoder__on_read_stdio, ma_decoder__on_seek_stdio, pDecoder->pUserData, pConfig, pDecoder); if (result == MA_SUCCESS) { @@ -31358,7 +32563,7 @@ ma_result ma_decoder_init_file(const char* pFilePath, const ma_decoder_config* p ma_decoder__on_seek_stdio(pDecoder, 0, ma_seek_origin_start); } - // FLAC + /* FLAC */ if (ma_path_extension_equal(pFilePath, "flac")) { result = ma_decoder_init_flac(ma_decoder__on_read_stdio, ma_decoder__on_seek_stdio, pDecoder->pUserData, pConfig, pDecoder); if (result == MA_SUCCESS) { @@ -31368,7 +32573,7 @@ ma_result ma_decoder_init_file(const char* pFilePath, const ma_decoder_config* p ma_decoder__on_seek_stdio(pDecoder, 0, ma_seek_origin_start); } - // MP3 + /* MP3 */ if (ma_path_extension_equal(pFilePath, "mp3")) { result = ma_decoder_init_mp3(ma_decoder__on_read_stdio, ma_decoder__on_seek_stdio, pDecoder->pUserData, pConfig, pDecoder); if (result == MA_SUCCESS) { @@ -31378,7 +32583,7 @@ ma_result ma_decoder_init_file(const char* pFilePath, const ma_decoder_config* p ma_decoder__on_seek_stdio(pDecoder, 0, ma_seek_origin_start); } - // Trial and error. + /* Trial and error. */ return ma_decoder_init(ma_decoder__on_read_stdio, ma_decoder__on_seek_stdio, pDecoder->pUserData, pConfig, pDecoder); } @@ -31434,7 +32639,7 @@ ma_result ma_decoder_uninit(ma_decoder* pDecoder) } #ifndef MA_NO_STDIO - // If we have a file handle, close it. + /* If we have a file handle, close it. */ if (pDecoder->onRead == ma_decoder__on_read_stdio) { fclose((FILE*)pDecoder->pUserData); } @@ -31445,37 +32650,50 @@ ma_result ma_decoder_uninit(ma_decoder* pDecoder) ma_uint64 ma_decoder_read_pcm_frames(ma_decoder* pDecoder, void* pFramesOut, ma_uint64 frameCount) { - if (pDecoder == NULL) return 0; + if (pDecoder == NULL) { + return 0; + } return ma_pcm_converter_read(&pDecoder->dsp, pFramesOut, frameCount); } ma_result ma_decoder_seek_to_pcm_frame(ma_decoder* pDecoder, ma_uint64 frameIndex) { - if (pDecoder == NULL) return 0; + if (pDecoder == NULL) { + return 0; + } if (pDecoder->onSeekToPCMFrame) { return pDecoder->onSeekToPCMFrame(pDecoder, frameIndex); } - // Should never get here, but if we do it means onSeekToPCMFrame was not set by the backend. + /* Should never get here, but if we do it means onSeekToPCMFrame was not set by the backend. */ return MA_INVALID_ARGS; } ma_result ma_decoder__full_decode_and_uninit(ma_decoder* pDecoder, ma_decoder_config* pConfigOut, ma_uint64* pFrameCountOut, void** ppPCMFramesOut) { + ma_uint64 totalFrameCount; + ma_uint64 bpf; + ma_uint64 dataCapInFrames; + void* pPCMFramesOut; + ma_assert(pDecoder != NULL); - ma_uint64 totalFrameCount = 0; - ma_uint64 bpf = ma_get_bytes_per_frame(pDecoder->outputFormat, pDecoder->outputChannels); + totalFrameCount = 0; + bpf = ma_get_bytes_per_frame(pDecoder->outputFormat, pDecoder->outputChannels); - // The frame count is unknown until we try reading. Thus, we just run in a loop. - ma_uint64 dataCapInFrames = 0; - void* pPCMFramesOut = NULL; + /* The frame count is unknown until we try reading. Thus, we just run in a loop. */ + dataCapInFrames = 0; + pPCMFramesOut = NULL; for (;;) { - // Make room if there's not enough. + ma_uint64 frameCountToTryReading; + ma_uint64 framesJustRead; + + /* Make room if there's not enough. */ if (totalFrameCount == dataCapInFrames) { + void* pNewPCMFramesOut; ma_uint64 newDataCapInFrames = dataCapInFrames*2; if (newDataCapInFrames == 0) { newDataCapInFrames = 4096; @@ -31487,7 +32705,7 @@ ma_result ma_decoder__full_decode_and_uninit(ma_decoder* pDecoder, ma_decoder_co } - void* pNewPCMFramesOut = (void*)ma_realloc(pPCMFramesOut, (size_t)(newDataCapInFrames * bpf)); + pNewPCMFramesOut = (void*)ma_realloc(pPCMFramesOut, (size_t)(newDataCapInFrames * bpf)); if (pNewPCMFramesOut == NULL) { ma_free(pPCMFramesOut); return MA_OUT_OF_MEMORY; @@ -31497,10 +32715,10 @@ ma_result ma_decoder__full_decode_and_uninit(ma_decoder* pDecoder, ma_decoder_co pPCMFramesOut = pNewPCMFramesOut; } - ma_uint64 frameCountToTryReading = dataCapInFrames - totalFrameCount; + frameCountToTryReading = dataCapInFrames - totalFrameCount; ma_assert(frameCountToTryReading > 0); - ma_uint64 framesJustRead = ma_decoder_read_pcm_frames(pDecoder, (ma_uint8*)pPCMFramesOut + (totalFrameCount * bpf), frameCountToTryReading); + framesJustRead = ma_decoder_read_pcm_frames(pDecoder, (ma_uint8*)pPCMFramesOut + (totalFrameCount * bpf), frameCountToTryReading); totalFrameCount += framesJustRead; if (framesJustRead < frameCountToTryReading) { @@ -31533,6 +32751,10 @@ ma_result ma_decoder__full_decode_and_uninit(ma_decoder* pDecoder, ma_decoder_co #ifndef MA_NO_STDIO ma_result ma_decode_file(const char* pFilePath, ma_decoder_config* pConfig, ma_uint64* pFrameCountOut, void** ppPCMFramesOut) { + ma_decoder_config config; + ma_decoder decoder; + ma_result result; + if (pFrameCountOut != NULL) { *pFrameCountOut = 0; } @@ -31544,10 +32766,9 @@ ma_result ma_decode_file(const char* pFilePath, ma_decoder_config* pConfig, ma_u return MA_INVALID_ARGS; } - ma_decoder_config config = ma_decoder_config_init_copy(pConfig); + config = ma_decoder_config_init_copy(pConfig); - ma_decoder decoder; - ma_result result = ma_decoder_init_file(pFilePath, &config, &decoder); + result = ma_decoder_init_file(pFilePath, &config, &decoder); if (result != MA_SUCCESS) { return result; } @@ -31558,6 +32779,10 @@ ma_result ma_decode_file(const char* pFilePath, ma_decoder_config* pConfig, ma_u ma_result ma_decode_memory(const void* pData, size_t dataSize, ma_decoder_config* pConfig, ma_uint64* pFrameCountOut, void** ppPCMFramesOut) { + ma_decoder_config config; + ma_decoder decoder; + ma_result result; + if (pFrameCountOut != NULL) { *pFrameCountOut = 0; } @@ -31569,10 +32794,9 @@ ma_result ma_decode_memory(const void* pData, size_t dataSize, ma_decoder_config return MA_INVALID_ARGS; } - ma_decoder_config config = ma_decoder_config_init_copy(pConfig); + config = ma_decoder_config_init_copy(pConfig); - ma_decoder decoder; - ma_result result = ma_decoder_init_memory(pData, dataSize, &config, &decoder); + result = ma_decoder_init_memory(pData, dataSize, &config, &decoder); if (result != MA_SUCCESS) { return result; } @@ -31580,19 +32804,16 @@ ma_result ma_decode_memory(const void* pData, size_t dataSize, ma_decoder_config return ma_decoder__full_decode_and_uninit(&decoder, pConfig, pFrameCountOut, ppPCMFramesOut); } -#endif // MA_NO_DECODING +#endif /* MA_NO_DECODING */ + +/************************************************************************************************************************************************************** -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// GENERATION -// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +Generation +**************************************************************************************************************************************************************/ ma_result ma_sine_wave_init(double amplitude, double periodsPerSecond, ma_uint32 sampleRate, ma_sine_wave* pSineWave) { if (pSineWave == NULL) { @@ -31631,22 +32852,25 @@ ma_uint64 ma_sine_wave_read_f32_ex(ma_sine_wave* pSineWave, ma_uint64 frameCount } if (ppFrames != NULL) { - for (ma_uint64 iFrame = 0; iFrame < frameCount; iFrame += 1) { + ma_uint64 iFrame; + for (iFrame = 0; iFrame < frameCount; iFrame += 1) { + ma_uint32 iChannel; + float s = (float)(sin(pSineWave->time * pSineWave->periodsPerSecond) * pSineWave->amplitude); pSineWave->time += pSineWave->delta; if (layout == ma_stream_layout_interleaved) { - for (ma_uint32 iChannel = 0; iChannel < channels; iChannel += 1) { + for (iChannel = 0; iChannel < channels; iChannel += 1) { ppFrames[0][iFrame*channels + iChannel] = s; } } else { - for (ma_uint32 iChannel = 0; iChannel < channels; iChannel += 1) { + for (iChannel = 0; iChannel < channels; iChannel += 1) { ppFrames[iChannel][iFrame] = s; } } } } else { - pSineWave->time += pSineWave->delta * frameCount; + pSineWave->time += pSineWave->delta * (ma_int64)frameCount; /* Cast to int64 required for VC6. */ } return frameCount; @@ -31689,6 +32913,9 @@ Device /* REVISION HISTORY ================ +v0.9.4 - 2019-05-06 + - Add support for C89. With this change, miniaudio should compile clean with GCC/Clang with "-std=c89 -ansi -pedantic" and + Microsoft compilers back to VC6. Other compilers should also work, but have not been tested. v0.9.3 - 2019-04-19 - Fix compiler errors on GCC when compiling with -std=c99. -- cgit v1.2.3 From 25ac9bfb280e13cc5f9f5824407eb21ca7fcbdd2 Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 16 May 2019 15:31:33 +0200 Subject: Update dr_flac, dr_mp3, dr_wav to latest version --- src/external/dr_flac.h | 6490 +++++++++++++++++++++++++++++++++++------------- src/external/dr_mp3.h | 1839 ++++++++++---- src/external/dr_wav.h | 3253 ++++++++++++++++-------- 3 files changed, 8237 insertions(+), 3345 deletions(-) (limited to 'src') diff --git a/src/external/dr_flac.h b/src/external/dr_flac.h index c836847e..13f42b2a 100644 --- a/src/external/dr_flac.h +++ b/src/external/dr_flac.h @@ -1,119 +1,118 @@ -// FLAC audio decoder. Public domain. See "unlicense" statement at the end of this file. -// dr_flac - v0.9.7 - 2018-07-05 -// -// David Reid - mackron@gmail.com - -// USAGE -// -// dr_flac is a single-file library. To use it, do something like the following in one .c file. -// #define DR_FLAC_IMPLEMENTATION -// #include "dr_flac.h" -// -// You can then #include this file in other parts of the program as you would with any other header file. To decode audio data, -// do something like the following: -// -// drflac* pFlac = drflac_open_file("MySong.flac"); -// if (pFlac == NULL) { -// // Failed to open FLAC file -// } -// -// drflac_int32* pSamples = malloc(pFlac->totalSampleCount * sizeof(drflac_int32)); -// drflac_uint64 numberOfInterleavedSamplesActuallyRead = drflac_read_s32(pFlac, pFlac->totalSampleCount, pSamples); -// -// The drflac object represents the decoder. It is a transparent type so all the information you need, such as the number of -// channels and the bits per sample, should be directly accessible - just make sure you don't change their values. Samples are -// always output as interleaved signed 32-bit PCM. In the example above a native FLAC stream was opened, however dr_flac has -// seamless support for Ogg encapsulated FLAC streams as well. -// -// You do not need to decode the entire stream in one go - you just specify how many samples you'd like at any given time and -// the decoder will give you as many samples as it can, up to the amount requested. Later on when you need the next batch of -// samples, just call it again. Example: -// -// while (drflac_read_s32(pFlac, chunkSize, pChunkSamples) > 0) { -// do_something(); -// } -// -// You can seek to a specific sample with drflac_seek_to_sample(). The given sample is based on interleaving. So for example, -// if you were to seek to the sample at index 0 in a stereo stream, you'll be seeking to the first sample of the left channel. -// The sample at index 1 will be the first sample of the right channel. The sample at index 2 will be the second sample of the -// left channel, etc. -// -// -// If you just want to quickly decode an entire FLAC file in one go you can do something like this: -// -// unsigned int channels; -// unsigned int sampleRate; -// drflac_uint64 totalSampleCount; -// drflac_int32* pSampleData = drflac_open_and_decode_file_s32("MySong.flac", &channels, &sampleRate, &totalSampleCount); -// if (pSampleData == NULL) { -// // Failed to open and decode FLAC file. -// } -// -// ... -// -// drflac_free(pSampleData); -// -// -// You can read samples as signed 16-bit integer and 32-bit floating-point PCM with the *_s16() and *_f32() family of APIs -// respectively, but note that these should be considered lossy. -// -// -// If you need access to metadata (album art, etc.), use drflac_open_with_metadata(), drflac_open_file_with_metdata() or -// drflac_open_memory_with_metadata(). The rationale for keeping these APIs separate is that they're slightly slower than the -// normal versions and also just a little bit harder to use. -// -// dr_flac reports metadata to the application through the use of a callback, and every metadata block is reported before -// drflac_open_with_metdata() returns. -// -// -// The main opening APIs (drflac_open(), etc.) will fail if the header is not present. The presents a problem in certain -// scenarios such as broadcast style streams like internet radio where the header may not be present because the user has -// started playback mid-stream. To handle this, use the relaxed APIs: drflac_open_relaxed() and drflac_open_with_metadata_relaxed(). -// -// It is not recommended to use these APIs for file based streams because a missing header would usually indicate a -// corrupted or perverse file. In addition, these APIs can take a long time to initialize because they may need to spend -// a lot of time finding the first frame. -// -// -// -// OPTIONS -// #define these options before including this file. -// -// #define DR_FLAC_NO_STDIO -// Disable drflac_open_file(). -// -// #define DR_FLAC_NO_OGG -// Disables support for Ogg/FLAC streams. -// -// #define DR_FLAC_NO_WIN32_IO -// In the Win32 build, dr_flac uses the Win32 IO APIs for drflac_open_file() by default. This setting will make it use the -// standard FILE APIs instead. Ignored when DR_FLAC_NO_STDIO is #defined. (The rationale for this configuration is that -// there's a bug in one compiler's Win32 implementation of the FILE APIs which is not present in the Win32 IO APIs.) -// -// #define DR_FLAC_BUFFER_SIZE -// Defines the size of the internal buffer to store data from onRead(). This buffer is used to reduce the number of calls -// back to the client for more data. Larger values means more memory, but better performance. My tests show diminishing -// returns after about 4KB (which is the default). Consider reducing this if you have a very efficient implementation of -// onRead(), or increase it if it's very inefficient. Must be a multiple of 8. -// -// #define DR_FLAC_NO_CRC -// Disables CRC checks. This will offer a performance boost when CRC is unnecessary. -// -// #define DR_FLAC_NO_SIMD -// Disables SIMD optimizations (SSE on x86/x64 architectures). Use this if you are having compatibility issues with your -// compiler. -// -// -// -// QUICK NOTES -// - dr_flac does not currently support changing the sample rate nor channel count mid stream. -// - Audio data is output as signed 32-bit PCM, regardless of the bits per sample the FLAC stream is encoded as. -// - This has not been tested on big-endian architectures. -// - Rice codes in unencoded binary form (see https://xiph.org/flac/format.html#rice_partition) has not been tested. If anybody -// knows where I can find some test files for this, let me know. -// - dr_flac is not thread-safe, but its APIs can be called from any thread so long as you do your own synchronization. -// - When using Ogg encapsulation, a corrupted metadata block will result in drflac_open_with_metadata() and drflac_open() -// returning inconsistent samples. +/* +FLAC audio decoder. Choice of public domain or MIT-0. See license statements at the end of this file. +dr_flac - v0.11.7 - 2019-05-06 + +David Reid - mackron@gmail.com +*/ + +/* +USAGE +===== +dr_flac is a single-file library. To use it, do something like the following in one .c file. + #define DR_FLAC_IMPLEMENTATION + #include "dr_flac.h" + +You can then #include this file in other parts of the program as you would with any other header file. To decode audio data, +do something like the following: + + drflac* pFlac = drflac_open_file("MySong.flac"); + if (pFlac == NULL) { + // Failed to open FLAC file + } + + drflac_int32* pSamples = malloc(pFlac->totalPCMFrameCount * pFlac->channels * sizeof(drflac_int32)); + drflac_uint64 numberOfInterleavedSamplesActuallyRead = drflac_read_pcm_frames_s32(pFlac, pFlac->totalPCMFrameCount, pSamples); + +The drflac object represents the decoder. It is a transparent type so all the information you need, such as the number of +channels and the bits per sample, should be directly accessible - just make sure you don't change their values. Samples are +always output as interleaved signed 32-bit PCM. In the example above a native FLAC stream was opened, however dr_flac has +seamless support for Ogg encapsulated FLAC streams as well. + +You do not need to decode the entire stream in one go - you just specify how many samples you'd like at any given time and +the decoder will give you as many samples as it can, up to the amount requested. Later on when you need the next batch of +samples, just call it again. Example: + + while (drflac_read_pcm_frames_s32(pFlac, chunkSizeInPCMFrames, pChunkSamples) > 0) { + do_something(); + } + +You can seek to a specific sample with drflac_seek_to_sample(). The given sample is based on interleaving. So for example, +if you were to seek to the sample at index 0 in a stereo stream, you'll be seeking to the first sample of the left channel. +The sample at index 1 will be the first sample of the right channel. The sample at index 2 will be the second sample of the +left channel, etc. + + +If you just want to quickly decode an entire FLAC file in one go you can do something like this: + + unsigned int channels; + unsigned int sampleRate; + drflac_uint64 totalPCMFrameCount; + drflac_int32* pSampleData = drflac_open_file_and_read_pcm_frames_s32("MySong.flac", &channels, &sampleRate, &totalPCMFrameCount); + if (pSampleData == NULL) { + // Failed to open and decode FLAC file. + } + + ... + + drflac_free(pSampleData); + + +You can read samples as signed 16-bit integer and 32-bit floating-point PCM with the *_s16() and *_f32() family of APIs +respectively, but note that these should be considered lossy. + + +If you need access to metadata (album art, etc.), use drflac_open_with_metadata(), drflac_open_file_with_metdata() or +drflac_open_memory_with_metadata(). The rationale for keeping these APIs separate is that they're slightly slower than the +normal versions and also just a little bit harder to use. + +dr_flac reports metadata to the application through the use of a callback, and every metadata block is reported before +drflac_open_with_metdata() returns. + + +The main opening APIs (drflac_open(), etc.) will fail if the header is not present. The presents a problem in certain +scenarios such as broadcast style streams like internet radio where the header may not be present because the user has +started playback mid-stream. To handle this, use the relaxed APIs: drflac_open_relaxed() and drflac_open_with_metadata_relaxed(). + +It is not recommended to use these APIs for file based streams because a missing header would usually indicate a +corrupted or perverse file. In addition, these APIs can take a long time to initialize because they may need to spend +a lot of time finding the first frame. + + + +OPTIONS +======= +#define these options before including this file. + +#define DR_FLAC_NO_STDIO + Disable drflac_open_file() and family. + +#define DR_FLAC_NO_OGG + Disables support for Ogg/FLAC streams. + +#define DR_FLAC_BUFFER_SIZE + Defines the size of the internal buffer to store data from onRead(). This buffer is used to reduce the number of calls + back to the client for more data. Larger values means more memory, but better performance. My tests show diminishing + returns after about 4KB (which is the default). Consider reducing this if you have a very efficient implementation of + onRead(), or increase it if it's very inefficient. Must be a multiple of 8. + +#define DR_FLAC_NO_CRC + Disables CRC checks. This will offer a performance boost when CRC is unnecessary. + +#define DR_FLAC_NO_SIMD + Disables SIMD optimizations (SSE on x86/x64 architectures). Use this if you are having compatibility issues with your + compiler. + + + +QUICK NOTES +=========== +- dr_flac does not currently support changing the sample rate nor channel count mid stream. +- Audio data is output as signed 32-bit PCM, regardless of the bits per sample the FLAC stream is encoded as. +- This has not been tested on big-endian architectures. +- dr_flac is not thread-safe, but its APIs can be called from any thread so long as you do your own synchronization. +- When using Ogg encapsulation, a corrupted metadata block will result in drflac_open_with_metadata() and drflac_open() + returning inconsistent samples. +*/ #ifndef dr_flac_h #define dr_flac_h @@ -145,9 +144,25 @@ typedef drflac_uint32 drflac_bool32; #define DRFLAC_TRUE 1 #define DRFLAC_FALSE 0 -// As data is read from the client it is placed into an internal buffer for fast access. This controls the -// size of that buffer. Larger values means more speed, but also more memory. In my testing there is diminishing -// returns after about 4KB, but you can fiddle with this to suit your own needs. Must be a multiple of 8. +#if defined(_MSC_VER) && _MSC_VER >= 1700 /* Visual Studio 2012 */ + #define DRFLAC_DEPRECATED __declspec(deprecated) +#elif (defined(__GNUC__) && __GNUC__ >= 4) /* GCC 4 */ + #define DRFLAC_DEPRECATED __attribute__((deprecated)) +#elif defined(__has_feature) /* Clang */ + #if defined(__has_feature(attribute_deprecated)) + #define DRFLAC_DEPRECATED __attribute__((deprecated)) + #else + #define DRFLAC_DEPRECATED + #endif +#else + #define DRFLAC_DEPRECATED +#endif + +/* +As data is read from the client it is placed into an internal buffer for fast access. This controls the +size of that buffer. Larger values means more speed, but also more memory. In my testing there is diminishing +returns after about 4KB, but you can fiddle with this to suit your own needs. Must be a multiple of 8. +*/ #ifndef DR_FLAC_BUFFER_SIZE #define DR_FLAC_BUFFER_SIZE 4096 #endif @@ -156,24 +171,18 @@ typedef drflac_uint32 drflac_bool32; extern "C" { #endif -// Check if we can enable 64-bit optimizations. -#if defined(_WIN64) +/* Check if we can enable 64-bit optimizations. */ +#if defined(_WIN64) || defined(_LP64) || defined(__LP64__) #define DRFLAC_64BIT #endif -#if defined(__GNUC__) -#if defined(__x86_64__) || defined(__ppc64__) -#define DRFLAC_64BIT -#endif -#endif - #ifdef DRFLAC_64BIT typedef drflac_uint64 drflac_cache_t; #else typedef drflac_uint32 drflac_cache_t; #endif -// The various metadata block types. +/* The various metadata block types. */ #define DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO 0 #define DRFLAC_METADATA_BLOCK_TYPE_PADDING 1 #define DRFLAC_METADATA_BLOCK_TYPE_APPLICATION 2 @@ -183,7 +192,7 @@ typedef drflac_uint32 drflac_cache_t; #define DRFLAC_METADATA_BLOCK_TYPE_PICTURE 6 #define DRFLAC_METADATA_BLOCK_TYPE_INVALID 127 -// The various picture types specified in the PICTURE block. +/* The various picture types specified in the PICTURE block. */ #define DRFLAC_PICTURE_TYPE_OTHER 0 #define DRFLAC_PICTURE_TYPE_FILE_ICON 1 #define DRFLAC_PICTURE_TYPE_OTHER_FILE_ICON 2 @@ -219,12 +228,12 @@ typedef enum drflac_seek_origin_current } drflac_seek_origin; -// Packing is important on this structure because we map this directly to the raw data within the SEEKTABLE metadata block. +/* Packing is important on this structure because we map this directly to the raw data within the SEEKTABLE metadata block. */ #pragma pack(2) typedef struct { drflac_uint64 firstSample; - drflac_uint64 frameOffset; // The offset from the first byte of the header of the first frame. + drflac_uint64 frameOffset; /* The offset from the first byte of the header of the first frame. */ drflac_uint16 sampleCount; } drflac_seekpoint; #pragma pack() @@ -244,15 +253,17 @@ typedef struct typedef struct { - // The metadata type. Use this to know how to interpret the data below. + /* The metadata type. Use this to know how to interpret the data below. */ drflac_uint32 type; - // A pointer to the raw data. This points to a temporary buffer so don't hold on to it. It's best to - // not modify the contents of this buffer. Use the structures below for more meaningful and structured - // information about the metadata. It's possible for this to be null. + /* + A pointer to the raw data. This points to a temporary buffer so don't hold on to it. It's best to + not modify the contents of this buffer. Use the structures below for more meaningful and structured + information about the metadata. It's possible for this to be null. + */ const void* pRawData; - // The size in bytes of the block and the buffer pointed to by pRawData if it's non-NULL. + /* The size in bytes of the block and the buffer pointed to by pRawData if it's non-NULL. */ drflac_uint32 rawDataSize; union @@ -282,7 +293,7 @@ typedef struct drflac_uint32 vendorLength; const char* vendor; drflac_uint32 commentCount; - const char* comments; + const void* pComments; } vorbis_comment; struct @@ -291,7 +302,7 @@ typedef struct drflac_uint64 leadInSampleCount; drflac_bool32 isCD; drflac_uint8 trackCount; - const drflac_uint8* pTrackData; + const void* pTrackData; } cuesheet; struct @@ -312,40 +323,46 @@ typedef struct } drflac_metadata; -// Callback for when data needs to be read from the client. -// -// pUserData [in] The user data that was passed to drflac_open() and family. -// pBufferOut [out] The output buffer. -// bytesToRead [in] The number of bytes to read. -// -// Returns the number of bytes actually read. -// -// A return value of less than bytesToRead indicates the end of the stream. Do _not_ return from this callback until -// either the entire bytesToRead is filled or you have reached the end of the stream. +/* +Callback for when data needs to be read from the client. + +pUserData [in] The user data that was passed to drflac_open() and family. +pBufferOut [out] The output buffer. +bytesToRead [in] The number of bytes to read. + +Returns the number of bytes actually read. + +A return value of less than bytesToRead indicates the end of the stream. Do _not_ return from this callback until +either the entire bytesToRead is filled or you have reached the end of the stream. +*/ typedef size_t (* drflac_read_proc)(void* pUserData, void* pBufferOut, size_t bytesToRead); -// Callback for when data needs to be seeked. -// -// pUserData [in] The user data that was passed to drflac_open() and family. -// offset [in] The number of bytes to move, relative to the origin. Will never be negative. -// origin [in] The origin of the seek - the current position or the start of the stream. -// -// Returns whether or not the seek was successful. -// -// The offset will never be negative. Whether or not it is relative to the beginning or current position is determined -// by the "origin" parameter which will be either drflac_seek_origin_start or drflac_seek_origin_current. +/* +Callback for when data needs to be seeked. + +pUserData [in] The user data that was passed to drflac_open() and family. +offset [in] The number of bytes to move, relative to the origin. Will never be negative. +origin [in] The origin of the seek - the current position or the start of the stream. + +Returns whether or not the seek was successful. + +The offset will never be negative. Whether or not it is relative to the beginning or current position is determined +by the "origin" parameter which will be either drflac_seek_origin_start or drflac_seek_origin_current. +*/ typedef drflac_bool32 (* drflac_seek_proc)(void* pUserData, int offset, drflac_seek_origin origin); -// Callback for when a metadata block is read. -// -// pUserData [in] The user data that was passed to drflac_open() and family. -// pMetadata [in] A pointer to a structure containing the data of the metadata block. -// -// Use pMetadata->type to determine which metadata block is being handled and how to read the data. +/* +Callback for when a metadata block is read. + +pUserData [in] The user data that was passed to drflac_open() and family. +pMetadata [in] A pointer to a structure containing the data of the metadata block. + +Use pMetadata->type to determine which metadata block is being handled and how to read the data. +*/ typedef void (* drflac_meta_proc)(void* pUserData, drflac_metadata* pMetadata); -// Structure for internal use. Only used for decoders opened with drflac_open_memory. +/* Structure for internal use. Only used for decoders opened with drflac_open_memory. */ typedef struct { const drflac_uint8* data; @@ -353,420 +370,588 @@ typedef struct size_t currentReadPos; } drflac__memory_stream; -// Structure for internal use. Used for bit streaming. +/* Structure for internal use. Used for bit streaming. */ typedef struct { - // The function to call when more data needs to be read. + /* The function to call when more data needs to be read. */ drflac_read_proc onRead; - // The function to call when the current read position needs to be moved. + /* The function to call when the current read position needs to be moved. */ drflac_seek_proc onSeek; - // The user data to pass around to onRead and onSeek. + /* The user data to pass around to onRead and onSeek. */ void* pUserData; - // The number of unaligned bytes in the L2 cache. This will always be 0 until the end of the stream is hit. At the end of the - // stream there will be a number of bytes that don't cleanly fit in an L1 cache line, so we use this variable to know whether - // or not the bistreamer needs to run on a slower path to read those last bytes. This will never be more than sizeof(drflac_cache_t). + /* + The number of unaligned bytes in the L2 cache. This will always be 0 until the end of the stream is hit. At the end of the + stream there will be a number of bytes that don't cleanly fit in an L1 cache line, so we use this variable to know whether + or not the bistreamer needs to run on a slower path to read those last bytes. This will never be more than sizeof(drflac_cache_t). + */ size_t unalignedByteCount; - // The content of the unaligned bytes. + /* The content of the unaligned bytes. */ drflac_cache_t unalignedCache; - // The index of the next valid cache line in the "L2" cache. + /* The index of the next valid cache line in the "L2" cache. */ drflac_uint32 nextL2Line; - // The number of bits that have been consumed by the cache. This is used to determine how many valid bits are remaining. + /* The number of bits that have been consumed by the cache. This is used to determine how many valid bits are remaining. */ drflac_uint32 consumedBits; - // The cached data which was most recently read from the client. There are two levels of cache. Data flows as such: - // Client -> L2 -> L1. The L2 -> L1 movement is aligned and runs on a fast path in just a few instructions. + /* + The cached data which was most recently read from the client. There are two levels of cache. Data flows as such: + Client -> L2 -> L1. The L2 -> L1 movement is aligned and runs on a fast path in just a few instructions. + */ drflac_cache_t cacheL2[DR_FLAC_BUFFER_SIZE/sizeof(drflac_cache_t)]; drflac_cache_t cache; - // CRC-16. This is updated whenever bits are read from the bit stream. Manually set this to 0 to reset the CRC. For FLAC, this - // is reset to 0 at the beginning of each frame. + /* + CRC-16. This is updated whenever bits are read from the bit stream. Manually set this to 0 to reset the CRC. For FLAC, this + is reset to 0 at the beginning of each frame. + */ drflac_uint16 crc16; - drflac_cache_t crc16Cache; // A cache for optimizing CRC calculations. This is filled when when the L1 cache is reloaded. - drflac_uint32 crc16CacheIgnoredBytes; // The number of bytes to ignore when updating the CRC-16 from the CRC-16 cache. + drflac_cache_t crc16Cache; /* A cache for optimizing CRC calculations. This is filled when when the L1 cache is reloaded. */ + drflac_uint32 crc16CacheIgnoredBytes; /* The number of bytes to ignore when updating the CRC-16 from the CRC-16 cache. */ } drflac_bs; typedef struct { - // The type of the subframe: SUBFRAME_CONSTANT, SUBFRAME_VERBATIM, SUBFRAME_FIXED or SUBFRAME_LPC. + /* The type of the subframe: SUBFRAME_CONSTANT, SUBFRAME_VERBATIM, SUBFRAME_FIXED or SUBFRAME_LPC. */ drflac_uint8 subframeType; - // The number of wasted bits per sample as specified by the sub-frame header. + /* The number of wasted bits per sample as specified by the sub-frame header. */ drflac_uint8 wastedBitsPerSample; - // The order to use for the prediction stage for SUBFRAME_FIXED and SUBFRAME_LPC. + /* The order to use for the prediction stage for SUBFRAME_FIXED and SUBFRAME_LPC. */ drflac_uint8 lpcOrder; - // The number of bits per sample for this subframe. This is not always equal to the current frame's bit per sample because - // an extra bit is required for side channels when interchannel decorrelation is being used. + /* + The number of bits per sample for this subframe. This is not always equal to the current frame's bit per sample because + an extra bit is required for side channels when interchannel decorrelation is being used. + */ drflac_uint32 bitsPerSample; - // A pointer to the buffer containing the decoded samples in the subframe. This pointer is an offset from drflac::pExtraData. Note that - // it's a signed 32-bit integer for each value. + /* + A pointer to the buffer containing the decoded samples in the subframe. This pointer is an offset from drflac::pExtraData. Note that + it's a signed 32-bit integer for each value. + */ drflac_int32* pDecodedSamples; } drflac_subframe; typedef struct { - // If the stream uses variable block sizes, this will be set to the index of the first sample. If fixed block sizes are used, this will - // always be set to 0. + /* + If the stream uses variable block sizes, this will be set to the index of the first sample. If fixed block sizes are used, this will + always be set to 0. + */ drflac_uint64 sampleNumber; - // If the stream uses fixed block sizes, this will be set to the frame number. If variable block sizes are used, this will always be 0. + /* If the stream uses fixed block sizes, this will be set to the frame number. If variable block sizes are used, this will always be 0. */ drflac_uint32 frameNumber; - // The sample rate of this frame. + /* The sample rate of this frame. */ drflac_uint32 sampleRate; - // The number of samples in each sub-frame within this frame. + /* The number of samples in each sub-frame within this frame. */ drflac_uint16 blockSize; - // The channel assignment of this frame. This is not always set to the channel count. If interchannel decorrelation is being used this - // will be set to DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE, DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE or DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE. + /* + The channel assignment of this frame. This is not always set to the channel count. If interchannel decorrelation is being used this + will be set to DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE, DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE or DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE. + */ drflac_uint8 channelAssignment; - // The number of bits per sample within this frame. + /* The number of bits per sample within this frame. */ drflac_uint8 bitsPerSample; - // The frame's CRC. + /* The frame's CRC. */ drflac_uint8 crc8; } drflac_frame_header; typedef struct { - // The header. + /* The header. */ drflac_frame_header header; - // The number of samples left to be read in this frame. This is initially set to the block size multiplied by the channel count. As samples - // are read, this will be decremented. When it reaches 0, the decoder will see this frame as fully consumed and load the next frame. + /* + The number of samples left to be read in this frame. This is initially set to the block size multiplied by the channel count. As samples + are read, this will be decremented. When it reaches 0, the decoder will see this frame as fully consumed and load the next frame. + */ drflac_uint32 samplesRemaining; - // The list of sub-frames within the frame. There is one sub-frame for each channel, and there's a maximum of 8 channels. + /* The list of sub-frames within the frame. There is one sub-frame for each channel, and there's a maximum of 8 channels. */ drflac_subframe subframes[8]; } drflac_frame; typedef struct { - // The function to call when a metadata block is read. + /* The function to call when a metadata block is read. */ drflac_meta_proc onMeta; - // The user data posted to the metadata callback function. + /* The user data posted to the metadata callback function. */ void* pUserDataMD; - // The sample rate. Will be set to something like 44100. + /* The sample rate. Will be set to something like 44100. */ drflac_uint32 sampleRate; - // The number of channels. This will be set to 1 for monaural streams, 2 for stereo, etc. Maximum 8. This is set based on the - // value specified in the STREAMINFO block. + /* + The number of channels. This will be set to 1 for monaural streams, 2 for stereo, etc. Maximum 8. This is set based on the + value specified in the STREAMINFO block. + */ drflac_uint8 channels; - // The bits per sample. Will be set to something like 16, 24, etc. + /* The bits per sample. Will be set to something like 16, 24, etc. */ drflac_uint8 bitsPerSample; - // The maximum block size, in samples. This number represents the number of samples in each channel (not combined). + /* The maximum block size, in samples. This number represents the number of samples in each channel (not combined). */ drflac_uint16 maxBlockSize; - // The total number of samples making up the stream. This includes every channel. For example, if the stream has 2 channels, - // with each channel having a total of 4096, this value will be set to 2*4096 = 8192. Can be 0 in which case it's still a - // valid stream, but just means the total sample count is unknown. Likely the case with streams like internet radio. + /* + The total number of samples making up the stream. This includes every channel. For example, if the stream has 2 channels, + with each channel having a total of 4096, this value will be set to 2*4096 = 8192. Can be 0 in which case it's still a + valid stream, but just means the total sample count is unknown. Likely the case with streams like internet radio. + */ drflac_uint64 totalSampleCount; + drflac_uint64 totalPCMFrameCount; /* <-- Equal to totalSampleCount / channels. */ - // The container type. This is set based on whether or not the decoder was opened from a native or Ogg stream. + /* The container type. This is set based on whether or not the decoder was opened from a native or Ogg stream. */ drflac_container container; - // The number of seekpoints in the seektable. + /* The number of seekpoints in the seektable. */ drflac_uint32 seekpointCount; - // Information about the frame the decoder is currently sitting on. + /* Information about the frame the decoder is currently sitting on. */ drflac_frame currentFrame; - // The index of the sample the decoder is currently sitting on. This is only used for seeking. + /* The index of the sample the decoder is currently sitting on. This is only used for seeking. */ drflac_uint64 currentSample; - // The position of the first frame in the stream. This is only ever used for seeking. + /* The position of the first frame in the stream. This is only ever used for seeking. */ drflac_uint64 firstFramePos; - // A hack to avoid a malloc() when opening a decoder with drflac_open_memory(). + /* A hack to avoid a malloc() when opening a decoder with drflac_open_memory(). */ drflac__memory_stream memoryStream; - // A pointer to the decoded sample data. This is an offset of pExtraData. + /* A pointer to the decoded sample data. This is an offset of pExtraData. */ drflac_int32* pDecodedSamples; - // A pointer to the seek table. This is an offset of pExtraData, or NULL if there is no seek table. + /* A pointer to the seek table. This is an offset of pExtraData, or NULL if there is no seek table. */ drflac_seekpoint* pSeekpoints; - // Internal use only. Only used with Ogg containers. Points to a drflac_oggbs object. This is an offset of pExtraData. + /* Internal use only. Only used with Ogg containers. Points to a drflac_oggbs object. This is an offset of pExtraData. */ void* _oggbs; - // The bit streamer. The raw FLAC data is fed through this object. + /* The bit streamer. The raw FLAC data is fed through this object. */ drflac_bs bs; - // Variable length extra data. We attach this to the end of the object so we can avoid unnecessary mallocs. + /* Variable length extra data. We attach this to the end of the object so we can avoid unnecessary mallocs. */ drflac_uint8 pExtraData[1]; } drflac; -// Opens a FLAC decoder. -// -// onRead [in] The function to call when data needs to be read from the client. -// onSeek [in] The function to call when the read position of the client data needs to move. -// pUserData [in, optional] A pointer to application defined data that will be passed to onRead and onSeek. -// -// Returns a pointer to an object representing the decoder. -// -// Close the decoder with drflac_close(). -// -// This function will automatically detect whether or not you are attempting to open a native or Ogg encapsulated -// FLAC, both of which should work seamlessly without any manual intervention. Ogg encapsulation also works with -// multiplexed streams which basically means it can play FLAC encoded audio tracks in videos. -// -// This is the lowest level function for opening a FLAC stream. You can also use drflac_open_file() and drflac_open_memory() -// to open the stream from a file or from a block of memory respectively. -// -// The STREAMINFO block must be present for this to succeed. Use drflac_open_relaxed() to open a FLAC stream where -// the header may not be present. -// -// See also: drflac_open_file(), drflac_open_memory(), drflac_open_with_metadata(), drflac_close() +/* +Opens a FLAC decoder. + +onRead [in] The function to call when data needs to be read from the client. +onSeek [in] The function to call when the read position of the client data needs to move. +pUserData [in, optional] A pointer to application defined data that will be passed to onRead and onSeek. + +Returns a pointer to an object representing the decoder. + +Close the decoder with drflac_close(). + +This function will automatically detect whether or not you are attempting to open a native or Ogg encapsulated +FLAC, both of which should work seamlessly without any manual intervention. Ogg encapsulation also works with +multiplexed streams which basically means it can play FLAC encoded audio tracks in videos. + +This is the lowest level function for opening a FLAC stream. You can also use drflac_open_file() and drflac_open_memory() +to open the stream from a file or from a block of memory respectively. + +The STREAMINFO block must be present for this to succeed. Use drflac_open_relaxed() to open a FLAC stream where +the header may not be present. + +See also: drflac_open_file(), drflac_open_memory(), drflac_open_with_metadata(), drflac_close() +*/ drflac* drflac_open(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData); -// The same as drflac_open(), except attempts to open the stream even when a header block is not present. -// -// Because the header is not necessarily available, the caller must explicitly define the container (Native or Ogg). Do -// not set this to drflac_container_unknown - that is for internal use only. -// -// Opening in relaxed mode will continue reading data from onRead until it finds a valid frame. If a frame is never -// found it will continue forever. To abort, force your onRead callback to return 0, which dr_flac will use as an -// indicator that the end of the stream was found. +/* +The same as drflac_open(), except attempts to open the stream even when a header block is not present. + +Because the header is not necessarily available, the caller must explicitly define the container (Native or Ogg). Do +not set this to drflac_container_unknown - that is for internal use only. + +Opening in relaxed mode will continue reading data from onRead until it finds a valid frame. If a frame is never +found it will continue forever. To abort, force your onRead callback to return 0, which dr_flac will use as an +indicator that the end of the stream was found. +*/ drflac* drflac_open_relaxed(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_container container, void* pUserData); -// Opens a FLAC decoder and notifies the caller of the metadata chunks (album art, etc.). -// -// onRead [in] The function to call when data needs to be read from the client. -// onSeek [in] The function to call when the read position of the client data needs to move. -// onMeta [in] The function to call for every metadata block. -// pUserData [in, optional] A pointer to application defined data that will be passed to onRead, onSeek and onMeta. -// -// Returns a pointer to an object representing the decoder. -// -// Close the decoder with drflac_close(). -// -// This is slower than drflac_open(), so avoid this one if you don't need metadata. Internally, this will do a DRFLAC_MALLOC() -// and DRFLAC_FREE() for every metadata block except for STREAMINFO and PADDING blocks. -// -// The caller is notified of the metadata via the onMeta callback. All metadata blocks will be handled before the function -// returns. -// -// The STREAMINFO block must be present for this to succeed. Use drflac_open_with_metadata_relaxed() to open a FLAC -// stream where the header may not be present. -// -// Note that this will behave inconsistently with drflac_open() if the stream is an Ogg encapsulated stream and a metadata -// block is corrupted. This is due to the way the Ogg stream recovers from corrupted pages. When drflac_open_with_metadata() -// is being used, the open routine will try to read the contents of the metadata block, whereas drflac_open() will simply -// seek past it (for the sake of efficiency). This inconsistency can result in different samples being returned depending on -// whether or not the stream is being opened with metadata. -// -// See also: drflac_open_file_with_metadata(), drflac_open_memory_with_metadata(), drflac_open(), drflac_close() +/* +Opens a FLAC decoder and notifies the caller of the metadata chunks (album art, etc.). + +onRead [in] The function to call when data needs to be read from the client. +onSeek [in] The function to call when the read position of the client data needs to move. +onMeta [in] The function to call for every metadata block. +pUserData [in, optional] A pointer to application defined data that will be passed to onRead, onSeek and onMeta. + +Returns a pointer to an object representing the decoder. + +Close the decoder with drflac_close(). + +This is slower than drflac_open(), so avoid this one if you don't need metadata. Internally, this will do a DRFLAC_MALLOC() +and DRFLAC_FREE() for every metadata block except for STREAMINFO and PADDING blocks. + +The caller is notified of the metadata via the onMeta callback. All metadata blocks will be handled before the function +returns. + +The STREAMINFO block must be present for this to succeed. Use drflac_open_with_metadata_relaxed() to open a FLAC +stream where the header may not be present. + +Note that this will behave inconsistently with drflac_open() if the stream is an Ogg encapsulated stream and a metadata +block is corrupted. This is due to the way the Ogg stream recovers from corrupted pages. When drflac_open_with_metadata() +is being used, the open routine will try to read the contents of the metadata block, whereas drflac_open() will simply +seek past it (for the sake of efficiency). This inconsistency can result in different samples being returned depending on +whether or not the stream is being opened with metadata. + +See also: drflac_open_file_with_metadata(), drflac_open_memory_with_metadata(), drflac_open(), drflac_close() +*/ drflac* drflac_open_with_metadata(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, void* pUserData); -// The same as drflac_open_with_metadata(), except attempts to open the stream even when a header block is not present. -// -// See also: drflac_open_with_metadata(), drflac_open_relaxed() +/* +The same as drflac_open_with_metadata(), except attempts to open the stream even when a header block is not present. + +See also: drflac_open_with_metadata(), drflac_open_relaxed() +*/ drflac* drflac_open_with_metadata_relaxed(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, drflac_container container, void* pUserData); -// Closes the given FLAC decoder. -// -// pFlac [in] The decoder to close. -// -// This will destroy the decoder object. +/* +Closes the given FLAC decoder. + +pFlac [in] The decoder to close. + +This will destroy the decoder object. +*/ void drflac_close(drflac* pFlac); -// Reads sample data from the given FLAC decoder, output as interleaved signed 32-bit PCM. -// -// pFlac [in] The decoder. -// samplesToRead [in] The number of samples to read. -// pBufferOut [out, optional] A pointer to the buffer that will receive the decoded samples. -// -// Returns the number of samples actually read. -// -// pBufferOut can be null, in which case the call will act as a seek, and the return value will be the number of samples -// seeked. -drflac_uint64 drflac_read_s32(drflac* pFlac, drflac_uint64 samplesToRead, drflac_int32* pBufferOut); - -// Same as drflac_read_s32(), except outputs samples as 16-bit integer PCM rather than 32-bit. -// -// pFlac [in] The decoder. -// samplesToRead [in] The number of samples to read. -// pBufferOut [out, optional] A pointer to the buffer that will receive the decoded samples. -// -// Returns the number of samples actually read. -// -// pBufferOut can be null, in which case the call will act as a seek, and the return value will be the number of samples -// seeked. -// -// Note that this is lossy for streams where the bits per sample is larger than 16. -drflac_uint64 drflac_read_s16(drflac* pFlac, drflac_uint64 samplesToRead, drflac_int16* pBufferOut); - -// Same as drflac_read_s32(), except outputs samples as 32-bit floating-point PCM. -// -// pFlac [in] The decoder. -// samplesToRead [in] The number of samples to read. -// pBufferOut [out, optional] A pointer to the buffer that will receive the decoded samples. -// -// Returns the number of samples actually read. -// -// pBufferOut can be null, in which case the call will act as a seek, and the return value will be the number of samples -// seeked. -// -// Note that this should be considered lossy due to the nature of floating point numbers not being able to exactly -// represent every possible number. -drflac_uint64 drflac_read_f32(drflac* pFlac, drflac_uint64 samplesToRead, float* pBufferOut); - -// Seeks to the sample at the given index. -// -// pFlac [in] The decoder. -// sampleIndex [in] The index of the sample to seek to. See notes below. -// -// Returns DRFLAC_TRUE if successful; DRFLAC_FALSE otherwise. -// -// The sample index is based on interleaving. In a stereo stream, for example, the sample at index 0 is the first sample -// in the left channel; the sample at index 1 is the first sample on the right channel, and so on. -// -// When seeking, you will likely want to ensure it's rounded to a multiple of the channel count. You can do this with -// something like drflac_seek_to_sample(pFlac, (mySampleIndex + (mySampleIndex % pFlac->channels))) -drflac_bool32 drflac_seek_to_sample(drflac* pFlac, drflac_uint64 sampleIndex); +/* +Reads sample data from the given FLAC decoder, output as interleaved signed 32-bit PCM. + +pFlac [in] The decoder. +framesToRead [in] The number of PCM frames to read. +pBufferOut [out, optional] A pointer to the buffer that will receive the decoded samples. + +Returns the number of PCM frames actually read. + +pBufferOut can be null, in which case the call will act as a seek, and the return value will be the number of frames +seeked. +*/ +drflac_uint64 drflac_read_pcm_frames_s32(drflac* pFlac, drflac_uint64 framesToRead, drflac_int32* pBufferOut); + +/* +Same as drflac_read_pcm_frames_s32(), except outputs samples as 16-bit integer PCM rather than 32-bit. + +Note that this is lossy for streams where the bits per sample is larger than 16. +*/ +drflac_uint64 drflac_read_pcm_frames_s16(drflac* pFlac, drflac_uint64 framesToRead, drflac_int16* pBufferOut); + +/* +Same as drflac_read_pcm_frames_s32(), except outputs samples as 32-bit floating-point PCM. + +Note that this should be considered lossy due to the nature of floating point numbers not being able to exactly +represent every possible number. +*/ +drflac_uint64 drflac_read_pcm_frames_f32(drflac* pFlac, drflac_uint64 framesToRead, float* pBufferOut); + +/* +Seeks to the PCM frame at the given index. + +pFlac [in] The decoder. +pcmFrameIndex [in] The index of the PCM frame to seek to. See notes below. + +Returns DRFLAC_TRUE if successful; DRFLAC_FALSE otherwise. +*/ +drflac_bool32 drflac_seek_to_pcm_frame(drflac* pFlac, drflac_uint64 pcmFrameIndex); #ifndef DR_FLAC_NO_STDIO -// Opens a FLAC decoder from the file at the given path. -// -// filename [in] The path of the file to open, either absolute or relative to the current directory. -// -// Returns a pointer to an object representing the decoder. -// -// Close the decoder with drflac_close(). -// -// This will hold a handle to the file until the decoder is closed with drflac_close(). Some platforms will restrict the -// number of files a process can have open at any given time, so keep this mind if you have many decoders open at the -// same time. -// -// See also: drflac_open(), drflac_open_file_with_metadata(), drflac_close() +/* +Opens a FLAC decoder from the file at the given path. + +filename [in] The path of the file to open, either absolute or relative to the current directory. + +Returns a pointer to an object representing the decoder. + +Close the decoder with drflac_close(). + +This will hold a handle to the file until the decoder is closed with drflac_close(). Some platforms will restrict the +number of files a process can have open at any given time, so keep this mind if you have many decoders open at the +same time. + +See also: drflac_open(), drflac_open_file_with_metadata(), drflac_close() +*/ drflac* drflac_open_file(const char* filename); -// Opens a FLAC decoder from the file at the given path and notifies the caller of the metadata chunks (album art, etc.) -// -// Look at the documentation for drflac_open_with_metadata() for more information on how metadata is handled. +/* +Opens a FLAC decoder from the file at the given path and notifies the caller of the metadata chunks (album art, etc.) + +Look at the documentation for drflac_open_with_metadata() for more information on how metadata is handled. +*/ drflac* drflac_open_file_with_metadata(const char* filename, drflac_meta_proc onMeta, void* pUserData); #endif -// Opens a FLAC decoder from a pre-allocated block of memory -// -// This does not create a copy of the data. It is up to the application to ensure the buffer remains valid for -// the lifetime of the decoder. +/* +Opens a FLAC decoder from a pre-allocated block of memory + +This does not create a copy of the data. It is up to the application to ensure the buffer remains valid for +the lifetime of the decoder. +*/ drflac* drflac_open_memory(const void* data, size_t dataSize); -// Opens a FLAC decoder from a pre-allocated block of memory and notifies the caller of the metadata chunks (album art, etc.) -// -// Look at the documentation for drflac_open_with_metadata() for more information on how metadata is handled. +/* +Opens a FLAC decoder from a pre-allocated block of memory and notifies the caller of the metadata chunks (album art, etc.) + +Look at the documentation for drflac_open_with_metadata() for more information on how metadata is handled. +*/ drflac* drflac_open_memory_with_metadata(const void* data, size_t dataSize, drflac_meta_proc onMeta, void* pUserData); -//// High Level APIs //// +/* High Level APIs */ + +/* +Opens a FLAC stream from the given callbacks and fully decodes it in a single operation. The return value is a +pointer to the sample data as interleaved signed 32-bit PCM. The returned data must be freed with DRFLAC_FREE(). + +Sometimes a FLAC file won't keep track of the total sample count. In this situation the function will continuously +read samples into a dynamically sized buffer on the heap until no samples are left. -// Opens a FLAC stream from the given callbacks and fully decodes it in a single operation. The return value is a -// pointer to the sample data as interleaved signed 32-bit PCM. The returned data must be freed with DRFLAC_FREE(). -// -// Sometimes a FLAC file won't keep track of the total sample count. In this situation the function will continuously -// read samples into a dynamically sized buffer on the heap until no samples are left. -// -// Do not call this function on a broadcast type of stream (like internet radio streams and whatnot). -drflac_int32* drflac_open_and_decode_s32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount); +Do not call this function on a broadcast type of stream (like internet radio streams and whatnot). +*/ +drflac_int32* drflac_open_and_read_pcm_frames_s32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount); -// Same as drflac_open_and_decode_s32(), except returns signed 16-bit integer samples. -drflac_int16* drflac_open_and_decode_s16(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount); +/* Same as drflac_open_and_read_pcm_frames_s32(), except returns signed 16-bit integer samples. */ +drflac_int16* drflac_open_and_read_pcm_frames_s16(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount); -// Same as drflac_open_and_decode_s32(), except returns 32-bit floating-point samples. -float* drflac_open_and_decode_f32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount); +/* Same as drflac_open_and_read_pcm_frames_s32(), except returns 32-bit floating-point samples. */ +float* drflac_open_and_read_pcm_frames_f32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount); #ifndef DR_FLAC_NO_STDIO -// Same as drflac_open_and_decode_s32() except opens the decoder from a file. -drflac_int32* drflac_open_and_decode_file_s32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount); +/* Same as drflac_open_and_read_pcm_frames_s32() except opens the decoder from a file. */ +drflac_int32* drflac_open_file_and_read_pcm_frames_s32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount); -// Same as drflac_open_and_decode_file_s32(), except returns signed 16-bit integer samples. -drflac_int16* drflac_open_and_decode_file_s16(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount); +/* Same as drflac_open_file_and_read_pcm_frames_s32(), except returns signed 16-bit integer samples. */ +drflac_int16* drflac_open_file_and_read_pcm_frames_s16(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount); -// Same as drflac_open_and_decode_file_f32(), except returns 32-bit floating-point samples. -float* drflac_open_and_decode_file_f32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount); +/* Same as drflac_open_file_and_read_pcm_frames_s32(), except returns 32-bit floating-point samples. */ +float* drflac_open_file_and_read_pcm_frames_f32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount); #endif -// Same as drflac_open_and_decode_s32() except opens the decoder from a block of memory. -drflac_int32* drflac_open_and_decode_memory_s32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount); +/* Same as drflac_open_and_read_pcm_frames_s32() except opens the decoder from a block of memory. */ +drflac_int32* drflac_open_memory_and_read_pcm_frames_s32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount); -// Same as drflac_open_and_decode_memory_s32(), except returns signed 16-bit integer samples. -drflac_int16* drflac_open_and_decode_memory_s16(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount); +/* Same as drflac_open_memory_and_read_pcm_frames_s32(), except returns signed 16-bit integer samples. */ +drflac_int16* drflac_open_memory_and_read_pcm_frames_s16(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount); -// Same as drflac_open_and_decode_memory_s32(), except returns 32-bit floating-point samples. -float* drflac_open_and_decode_memory_f32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount); +/* Same as drflac_open_memory_and_read_pcm_frames_s32(), except returns 32-bit floating-point samples. */ +float* drflac_open_memory_and_read_pcm_frames_f32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount); -// Frees memory that was allocated internally by dr_flac. +/* Frees memory that was allocated internally by dr_flac. */ void drflac_free(void* p); -// Structure representing an iterator for vorbis comments in a VORBIS_COMMENT metadata block. +/* Structure representing an iterator for vorbis comments in a VORBIS_COMMENT metadata block. */ typedef struct { drflac_uint32 countRemaining; const char* pRunningData; } drflac_vorbis_comment_iterator; -// Initializes a vorbis comment iterator. This can be used for iterating over the vorbis comments in a VORBIS_COMMENT -// metadata block. -void drflac_init_vorbis_comment_iterator(drflac_vorbis_comment_iterator* pIter, drflac_uint32 commentCount, const char* pComments); +/* +Initializes a vorbis comment iterator. This can be used for iterating over the vorbis comments in a VORBIS_COMMENT +metadata block. +*/ +void drflac_init_vorbis_comment_iterator(drflac_vorbis_comment_iterator* pIter, drflac_uint32 commentCount, const void* pComments); -// Goes to the next vorbis comment in the given iterator. If null is returned it means there are no more comments. The -// returned string is NOT null terminated. +/* +Goes to the next vorbis comment in the given iterator. If null is returned it means there are no more comments. The +returned string is NOT null terminated. +*/ const char* drflac_next_vorbis_comment(drflac_vorbis_comment_iterator* pIter, drflac_uint32* pCommentLengthOut); +/* Structure representing an iterator for cuesheet tracks in a CUESHEET metadata block. */ +typedef struct +{ + drflac_uint32 countRemaining; + const char* pRunningData; +} drflac_cuesheet_track_iterator; + +/* Packing is important on this structure because we map this directly to the raw data within the CUESHEET metadata block. */ +#pragma pack(4) +typedef struct +{ + drflac_uint64 offset; + drflac_uint8 index; + drflac_uint8 reserved[3]; +} drflac_cuesheet_track_index; +#pragma pack() + +typedef struct +{ + drflac_uint64 offset; + drflac_uint8 trackNumber; + char ISRC[12]; + drflac_bool8 isAudio; + drflac_bool8 preEmphasis; + drflac_uint8 indexCount; + const drflac_cuesheet_track_index* pIndexPoints; +} drflac_cuesheet_track; + +/* +Initializes a cuesheet track iterator. This can be used for iterating over the cuesheet tracks in a CUESHEET metadata +block. +*/ +void drflac_init_cuesheet_track_iterator(drflac_cuesheet_track_iterator* pIter, drflac_uint32 trackCount, const void* pTrackData); + +/* Goes to the next cuesheet track in the given iterator. If DRFLAC_FALSE is returned it means there are no more comments. */ +drflac_bool32 drflac_next_cuesheet_track(drflac_cuesheet_track_iterator* pIter, drflac_cuesheet_track* pCuesheetTrack); + + +/* Deprecated APIs */ +DRFLAC_DEPRECATED drflac_uint64 drflac_read_s32(drflac* pFlac, drflac_uint64 samplesToRead, drflac_int32* pBufferOut); /* Use drflac_read_pcm_frames_s32() instead. */ +DRFLAC_DEPRECATED drflac_uint64 drflac_read_s16(drflac* pFlac, drflac_uint64 samplesToRead, drflac_int16* pBufferOut); /* Use drflac_read_pcm_frames_s16() instead. */ +DRFLAC_DEPRECATED drflac_uint64 drflac_read_f32(drflac* pFlac, drflac_uint64 samplesToRead, float* pBufferOut); /* Use drflac_read_pcm_frames_f32() instead. */ +DRFLAC_DEPRECATED drflac_bool32 drflac_seek_to_sample(drflac* pFlac, drflac_uint64 sampleIndex); /* Use drflac_seek_to_pcm_frame() instead. */ +DRFLAC_DEPRECATED drflac_int32* drflac_open_and_decode_s32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount); /* Use drflac_open_and_read_pcm_frames_s32(). */ +DRFLAC_DEPRECATED drflac_int16* drflac_open_and_decode_s16(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount); /* Use drflac_open_and_read_pcm_frames_s16(). */ +DRFLAC_DEPRECATED float* drflac_open_and_decode_f32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount); /* Use drflac_open_and_read_pcm_frames_f32(). */ +DRFLAC_DEPRECATED drflac_int32* drflac_open_and_decode_file_s32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount); /* Use drflac_open_file_and_read_pcm_frames_s32(). */ +DRFLAC_DEPRECATED drflac_int16* drflac_open_and_decode_file_s16(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount); /* Use drflac_open_file_and_read_pcm_frames_s16(). */ +DRFLAC_DEPRECATED float* drflac_open_and_decode_file_f32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount); /* Use drflac_open_file_and_read_pcm_frames_f32(). */ +DRFLAC_DEPRECATED drflac_int32* drflac_open_and_decode_memory_s32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount); /* Use drflac_open_memory_and_read_pcm_frames_s32(). */ +DRFLAC_DEPRECATED drflac_int16* drflac_open_and_decode_memory_s16(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount); /* Use drflac_open_memory_and_read_pcm_frames_s16(). */ +DRFLAC_DEPRECATED float* drflac_open_and_decode_memory_f32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount); /* Use drflac_open_memory_and_read_pcm_frames_f32(). */ #ifdef __cplusplus } #endif -#endif //dr_flac_h +#endif /* dr_flac_h */ + +/************************************************************************************************************************************************************ + ************************************************************************************************************************************************************ -/////////////////////////////////////////////////////////////////////////////// -// -// IMPLEMENTATION -// -/////////////////////////////////////////////////////////////////////////////// + IMPLEMENTATION + + ************************************************************************************************************************************************************ + ************************************************************************************************************************************************************/ #ifdef DR_FLAC_IMPLEMENTATION + +/* Disable some annoying warnings. */ +#if defined(__GNUC__) + #pragma GCC diagnostic push + #if __GNUC__ >= 7 + #pragma GCC diagnostic ignored "-Wimplicit-fallthrough" + #endif +#endif + +#ifdef __linux__ + #ifndef _BSD_SOURCE + #define _BSD_SOURCE + #endif + #ifndef __USE_BSD + #define __USE_BSD + #endif + #include +#endif + #include #include -// CPU architecture. +#ifdef _MSC_VER +#define DRFLAC_INLINE __forceinline +#else +#ifdef __GNUC__ +#define DRFLAC_INLINE __inline__ __attribute__((always_inline)) +#else +#define DRFLAC_INLINE +#endif +#endif + +/* CPU architecture. */ #if defined(__x86_64__) || defined(_M_X64) -#define DRFLAC_X64 + #define DRFLAC_X64 #elif defined(__i386) || defined(_M_IX86) -#define DRFLAC_X86 + #define DRFLAC_X86 #elif defined(__arm__) || defined(_M_ARM) -#define DRFLAC_ARM + #define DRFLAC_ARM +#endif + +/* Intrinsics Support */ +#if !defined(DR_FLAC_NO_SIMD) + #if defined(DRFLAC_X64) || defined(DRFLAC_X86) + #if defined(_MSC_VER) && !defined(__clang__) + /* MSVC. */ + #if _MSC_VER >= 1400 && !defined(DRFLAC_NO_SSE2) /* 2005 */ + #define DRFLAC_SUPPORT_SSE2 + #endif + #if _MSC_VER >= 1600 && !defined(DRFLAC_NO_SSE41) /* 2010 */ + #define DRFLAC_SUPPORT_SSE41 + #endif + #else + /* Assume GNUC-style. */ + #if defined(__SSE2__) && !defined(DRFLAC_NO_SSE2) + #define DRFLAC_SUPPORT_SSE2 + #endif + #if defined(__SSE4_1__) && !defined(DRFLAC_NO_SSE41) + #define DRFLAC_SUPPORT_SSE41 + #endif + #endif + + /* If at this point we still haven't determined compiler support for the intrinsics just fall back to __has_include. */ + #if !defined(__GNUC__) && !defined(__clang__) && defined(__has_include) + #if !defined(DRFLAC_SUPPORT_SSE2) && !defined(DRFLAC_NO_SSE2) && __has_include() + #define DRFLAC_SUPPORT_SSE2 + #endif + #if !defined(DRFLAC_SUPPORT_SSE41) && !defined(DRFLAC_NO_SSE41) && __has_include() + #define DRFLAC_SUPPORT_SSE41 + #endif + #endif + + #if defined(DRFLAC_SUPPORT_SSE41) + #include + #elif defined(DRFLAC_SUPPORT_SSE2) + #include + #endif + #endif + + #if defined(DRFLAC_ARM) + #if !defined(DRFLAC_NO_NEON) && (defined(__ARM_NEON) || defined(__aarch64__) || defined(_M_ARM64)) + #define DRFLAC_SUPPORT_NEON + #endif + + /* Fall back to looking for the #include file. */ + #if !defined(__GNUC__) && !defined(__clang__) && defined(__has_include) + #if !defined(DRFLAC_SUPPORT_NEON) && !defined(DRFLAC_NO_NEON) && __has_include() + #define DRFLAC_SUPPORT_NEON + #endif + #endif + + #if defined(DRFLAC_SUPPORT_NEON) + #include + #endif + #endif #endif -// Compile-time CPU feature support. +/* Compile-time CPU feature support. */ #if !defined(DR_FLAC_NO_SIMD) && (defined(DRFLAC_X86) || defined(DRFLAC_X64)) #if defined(_MSC_VER) && !defined(__clang__) #if _MSC_VER >= 1400 @@ -776,52 +961,127 @@ const char* drflac_next_vorbis_comment(drflac_vorbis_comment_iterator* pIter, dr __cpuid(info, fid); } #else - #define DRFLAC_NO_CPUID + #define DRFLAC_NO_CPUID #endif #else #if defined(__GNUC__) || defined(__clang__) static void drflac__cpuid(int info[4], int fid) { - __asm__ __volatile__ ( - "cpuid" : "=a"(info[0]), "=b"(info[1]), "=c"(info[2]), "=d"(info[3]) : "a"(fid), "c"(0) - ); + /* + It looks like the -fPIC option uses the ebx register which GCC complains about. We can work around this by just using a different register, the + specific register of which I'm letting the compiler decide on. The "k" prefix is used to specify a 32-bit register. The {...} syntax is for + supporting different assembly dialects. + + What's basically happening is that we're saving and restoring the ebx register manually. + */ + #if defined(DRFLAC_X86) && defined(__PIC__) + __asm__ __volatile__ ( + "xchg{l} {%%}ebx, %k1;" + "cpuid;" + "xchg{l} {%%}ebx, %k1;" + : "=a"(info[0]), "=&r"(info[1]), "=c"(info[2]), "=d"(info[3]) : "a"(fid), "c"(0) + ); + #else + __asm__ __volatile__ ( + "cpuid" : "=a"(info[0]), "=b"(info[1]), "=c"(info[2]), "=d"(info[3]) : "a"(fid), "c"(0) + ); + #endif } #else - #define DRFLAC_NO_CPUID + #define DRFLAC_NO_CPUID #endif #endif #else -#define DRFLAC_NO_CPUID + #define DRFLAC_NO_CPUID #endif +static DRFLAC_INLINE drflac_bool32 drflac_has_sse2() +{ +#if defined(DRFLAC_SUPPORT_SSE2) + #if (defined(DRFLAC_X64) || defined(DRFLAC_X86)) && !defined(DRFLAC_NO_SSE2) + #if defined(DRFLAC_X64) + return DRFLAC_TRUE; /* 64-bit targets always support SSE2. */ + #elif (defined(_M_IX86_FP) && _M_IX86_FP == 2) || defined(__SSE2__) + return DRFLAC_TRUE; /* If the compiler is allowed to freely generate SSE2 code we can assume support. */ + #else + #if defined(DRFLAC_NO_CPUID) + return DRFLAC_FALSE; + #else + int info[4]; + drflac_cpuid(info, 1); + return (info[3] & (1 << 26)) != 0; + #endif + #endif + #else + return DRFLAC_FALSE; /* SSE2 is only supported on x86 and x64 architectures. */ + #endif +#else + return DRFLAC_FALSE; /* No compiler support. */ +#endif +} -#ifdef __linux__ -#define _BSD_SOURCE -#include +static DRFLAC_INLINE drflac_bool32 drflac_has_sse41() +{ +#if defined(DRFLAC_SUPPORT_SSE41) + #if (defined(DRFLAC_X64) || defined(DRFLAC_X86)) && !defined(DRFLAC_NO_SSE41) + #if defined(DRFLAC_X64) + return DRFLAC_TRUE; /* 64-bit targets always support SSE4.1. */ + #elif (defined(_M_IX86_FP) && _M_IX86_FP == 2) || defined(__SSE4_1__) + return DRFLAC_TRUE; /* If the compiler is allowed to freely generate SSE41 code we can assume support. */ + #else + #if defined(DRFLAC_NO_CPUID) + return DRFLAC_FALSE; + #else + int info[4]; + drflac_cpuid(info, 1); + return (info[2] & (1 << 19)) != 0; + #endif + #endif + #else + return DRFLAC_FALSE; /* SSE41 is only supported on x86 and x64 architectures. */ + #endif +#else + return DRFLAC_FALSE; /* No compiler support. */ #endif +} + #if defined(_MSC_VER) && _MSC_VER >= 1500 && (defined(DRFLAC_X86) || defined(DRFLAC_X64)) -#define DRFLAC_HAS_LZCNT_INTRINSIC + #define DRFLAC_HAS_LZCNT_INTRINSIC #elif (defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7))) -#define DRFLAC_HAS_LZCNT_INTRINSIC + #define DRFLAC_HAS_LZCNT_INTRINSIC #elif defined(__clang__) #if __has_builtin(__builtin_clzll) || __has_builtin(__builtin_clzl) - #define DRFLAC_HAS_LZCNT_INTRINSIC + #define DRFLAC_HAS_LZCNT_INTRINSIC #endif #endif #if defined(_MSC_VER) && _MSC_VER >= 1300 -#define DRFLAC_HAS_BYTESWAP_INTRINSIC -#elif defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) -#define DRFLAC_HAS_BYTESWAP_INTRINSIC + #define DRFLAC_HAS_BYTESWAP16_INTRINSIC + #define DRFLAC_HAS_BYTESWAP32_INTRINSIC + #define DRFLAC_HAS_BYTESWAP64_INTRINSIC #elif defined(__clang__) - #if __has_builtin(__builtin_bswap16) && __has_builtin(__builtin_bswap32) && __has_builtin(__builtin_bswap64) - #define DRFLAC_HAS_BYTESWAP_INTRINSIC + #if __has_builtin(__builtin_bswap16) + #define DRFLAC_HAS_BYTESWAP16_INTRINSIC + #endif + #if __has_builtin(__builtin_bswap32) + #define DRFLAC_HAS_BYTESWAP32_INTRINSIC + #endif + #if __has_builtin(__builtin_bswap64) + #define DRFLAC_HAS_BYTESWAP64_INTRINSIC + #endif +#elif defined(__GNUC__) + #if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) + #define DRFLAC_HAS_BYTESWAP32_INTRINSIC + #define DRFLAC_HAS_BYTESWAP64_INTRINSIC + #endif + #if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)) + #define DRFLAC_HAS_BYTESWAP16_INTRINSIC #endif #endif -// Standard library stuff. +/* Standard library stuff. */ #ifndef DRFLAC_ASSERT #include #define DRFLAC_ASSERT(expression) assert(expression) @@ -842,21 +1102,11 @@ const char* drflac_next_vorbis_comment(drflac_vorbis_comment_iterator* pIter, dr #define DRFLAC_ZERO_MEMORY(p, sz) memset((p), 0, (sz)) #endif -#define DRFLAC_MAX_SIMD_VECTOR_SIZE 64 // 64 for AVX-512 in the future. - -#ifdef _MSC_VER -#define DRFLAC_INLINE __forceinline -#else -#ifdef __GNUC__ -#define DRFLAC_INLINE inline __attribute__((always_inline)) -#else -#define DRFLAC_INLINE inline -#endif -#endif +#define DRFLAC_MAX_SIMD_VECTOR_SIZE 64 /* 64 for AVX-512 in the future. */ typedef drflac_int32 drflac_result; #define DRFLAC_SUCCESS 0 -#define DRFLAC_ERROR -1 // A generic error. +#define DRFLAC_ERROR -1 /* A generic error. */ #define DRFLAC_INVALID_ARGS -2 #define DRFLAC_END_OF_STREAM -128 #define DRFLAC_CRC_MISMATCH -129 @@ -875,6 +1125,12 @@ typedef drflac_int32 drflac_result; #define DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE 9 #define DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE 10 +/* +Keeps track of the number of leading samples for each sub-frame. This is required because the SSE pipeline will occasionally +reference excess prior samples. +*/ +#define DRFLAC_LEADING_SAMPLES 32 + #define drflac_align(x, a) ((((x) + (a) - 1) / (a)) * (a)) #define drflac_assert DRFLAC_ASSERT @@ -882,30 +1138,35 @@ typedef drflac_int32 drflac_result; #define drflac_zero_memory DRFLAC_ZERO_MEMORY -// CPU caps. +/* CPU caps. */ static drflac_bool32 drflac__gIsLZCNTSupported = DRFLAC_FALSE; #ifndef DRFLAC_NO_CPUID -static drflac_bool32 drflac__gIsSSE42Supported = DRFLAC_FALSE; +static drflac_bool32 drflac__gIsSSE2Supported = DRFLAC_FALSE; +static drflac_bool32 drflac__gIsSSE41Supported = DRFLAC_FALSE; static void drflac__init_cpu_caps() { int info[4] = {0}; - // LZCNT + /* LZCNT */ drflac__cpuid(info, 0x80000001); - drflac__gIsLZCNTSupported = (info[2] & (1 << 5)) != 0; + drflac__gIsLZCNTSupported = (info[2] & (1 << 5)) != 0; - // SSE4.2 - drflac__cpuid(info, 1); - drflac__gIsSSE42Supported = (info[2] & (1 << 19)) != 0; + /* SSE2 */ + drflac__gIsSSE2Supported = drflac_has_sse2(); + + /* SSE4.1 */ + drflac__gIsSSE41Supported = drflac_has_sse41(); } #endif -//// Endian Management //// +/* Endian Management */ static DRFLAC_INLINE drflac_bool32 drflac__is_little_endian() { #if defined(DRFLAC_X86) || defined(DRFLAC_X64) return DRFLAC_TRUE; +#elif defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && __BYTE_ORDER == __LITTLE_ENDIAN + return DRFLAC_TRUE; #else int n = 1; return (*(char*)&n) == 1; @@ -914,7 +1175,7 @@ static DRFLAC_INLINE drflac_bool32 drflac__is_little_endian() static DRFLAC_INLINE drflac_uint16 drflac__swap_endian_uint16(drflac_uint16 n) { -#ifdef DRFLAC_HAS_BYTESWAP_INTRINSIC +#ifdef DRFLAC_HAS_BYTESWAP16_INTRINSIC #if defined(_MSC_VER) return _byteswap_ushort(n); #elif defined(__GNUC__) || defined(__clang__) @@ -930,7 +1191,7 @@ static DRFLAC_INLINE drflac_uint16 drflac__swap_endian_uint16(drflac_uint16 n) static DRFLAC_INLINE drflac_uint32 drflac__swap_endian_uint32(drflac_uint32 n) { -#ifdef DRFLAC_HAS_BYTESWAP_INTRINSIC +#ifdef DRFLAC_HAS_BYTESWAP32_INTRINSIC #if defined(_MSC_VER) return _byteswap_ulong(n); #elif defined(__GNUC__) || defined(__clang__) @@ -948,7 +1209,7 @@ static DRFLAC_INLINE drflac_uint32 drflac__swap_endian_uint32(drflac_uint32 n) static DRFLAC_INLINE drflac_uint64 drflac__swap_endian_uint64(drflac_uint64 n) { -#ifdef DRFLAC_HAS_BYTESWAP_INTRINSIC +#ifdef DRFLAC_HAS_BYTESWAP64_INTRINSIC #if defined(_MSC_VER) return _byteswap_uint64(n); #elif defined(__GNUC__) || defined(__clang__) @@ -971,55 +1232,39 @@ static DRFLAC_INLINE drflac_uint64 drflac__swap_endian_uint64(drflac_uint64 n) static DRFLAC_INLINE drflac_uint16 drflac__be2host_16(drflac_uint16 n) { -#ifdef __linux__ - return be16toh(n); -#else if (drflac__is_little_endian()) { return drflac__swap_endian_uint16(n); } return n; -#endif } static DRFLAC_INLINE drflac_uint32 drflac__be2host_32(drflac_uint32 n) { -#ifdef __linux__ - return be32toh(n); -#else if (drflac__is_little_endian()) { return drflac__swap_endian_uint32(n); } return n; -#endif } static DRFLAC_INLINE drflac_uint64 drflac__be2host_64(drflac_uint64 n) { -#ifdef __linux__ - return be64toh(n); -#else if (drflac__is_little_endian()) { return drflac__swap_endian_uint64(n); } return n; -#endif } static DRFLAC_INLINE drflac_uint32 drflac__le2host_32(drflac_uint32 n) { -#ifdef __linux__ - return le32toh(n); -#else if (!drflac__is_little_endian()) { return drflac__swap_endian_uint32(n); } return n; -#endif } @@ -1036,7 +1281,7 @@ static DRFLAC_INLINE drflac_uint32 drflac__unsynchsafe_32(drflac_uint32 n) -// The CRC code below is based on this document: http://zlib.net/crc_v3.txt +/* The CRC code below is based on this document: http://zlib.net/crc_v3.txt */ static drflac_uint8 drflac__crc8_table[] = { 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15, 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D, 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65, 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D, @@ -1098,8 +1343,6 @@ static DRFLAC_INLINE drflac_uint8 drflac_crc8_byte(drflac_uint8 crc, drflac_uint static DRFLAC_INLINE drflac_uint8 drflac_crc8(drflac_uint8 crc, drflac_uint32 data, drflac_uint32 count) { - drflac_assert(count <= 32); - #ifdef DR_FLAC_NO_CRC (void)crc; (void)data; @@ -1107,7 +1350,7 @@ static DRFLAC_INLINE drflac_uint8 drflac_crc8(drflac_uint8 crc, drflac_uint32 da return 0; #else #if 0 - // REFERENCE (use of this implementation requires an explicit flush by doing "drflac_crc8(crc, 0, 8);") + /* REFERENCE (use of this implementation requires an explicit flush by doing "drflac_crc8(crc, 0, 8);") */ drflac_uint8 p = 0x07; for (int i = count-1; i >= 0; --i) { drflac_uint8 bit = (data & (1 << i)) >> i; @@ -1119,13 +1362,19 @@ static DRFLAC_INLINE drflac_uint8 drflac_crc8(drflac_uint8 crc, drflac_uint32 da } return crc; #else - drflac_uint32 wholeBytes = count >> 3; - drflac_uint32 leftoverBits = count - (wholeBytes*8); + drflac_uint32 wholeBytes; + drflac_uint32 leftoverBits; + drflac_uint64 leftoverDataMask; static drflac_uint64 leftoverDataMaskTable[8] = { 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F }; - drflac_uint64 leftoverDataMask = leftoverDataMaskTable[leftoverBits]; + + drflac_assert(count <= 32); + + wholeBytes = count >> 3; + leftoverBits = count - (wholeBytes*8); + leftoverDataMask = leftoverDataMaskTable[leftoverBits]; switch (wholeBytes) { case 4: crc = drflac_crc8_byte(crc, (drflac_uint8)((data & (0xFF000000UL << leftoverBits)) >> (24 + leftoverBits))); @@ -1165,8 +1414,6 @@ static DRFLAC_INLINE drflac_uint16 drflac_crc16_bytes(drflac_uint16 crc, drflac_ static DRFLAC_INLINE drflac_uint16 drflac_crc16__32bit(drflac_uint16 crc, drflac_uint32 data, drflac_uint32 count) { - drflac_assert(count <= 64); - #ifdef DR_FLAC_NO_CRC (void)crc; (void)data; @@ -1174,7 +1421,7 @@ static DRFLAC_INLINE drflac_uint16 drflac_crc16__32bit(drflac_uint16 crc, drflac return 0; #else #if 0 - // REFERENCE (use of this implementation requires an explicit flush by doing "drflac_crc16(crc, 0, 16);") + /* REFERENCE (use of this implementation requires an explicit flush by doing "drflac_crc16(crc, 0, 16);") */ drflac_uint16 p = 0x8005; for (int i = count-1; i >= 0; --i) { drflac_uint16 bit = (data & (1ULL << i)) >> i; @@ -1187,13 +1434,19 @@ static DRFLAC_INLINE drflac_uint16 drflac_crc16__32bit(drflac_uint16 crc, drflac return crc; #else - drflac_uint32 wholeBytes = count >> 3; - drflac_uint32 leftoverBits = count - (wholeBytes*8); + drflac_uint32 wholeBytes; + drflac_uint32 leftoverBits; + drflac_uint64 leftoverDataMask; static drflac_uint64 leftoverDataMaskTable[8] = { 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F }; - drflac_uint64 leftoverDataMask = leftoverDataMaskTable[leftoverBits]; + + drflac_assert(count <= 64); + + wholeBytes = count >> 3; + leftoverBits = count - (wholeBytes*8); + leftoverDataMask = leftoverDataMaskTable[leftoverBits]; switch (wholeBytes) { default: @@ -1210,32 +1463,36 @@ static DRFLAC_INLINE drflac_uint16 drflac_crc16__32bit(drflac_uint16 crc, drflac static DRFLAC_INLINE drflac_uint16 drflac_crc16__64bit(drflac_uint16 crc, drflac_uint64 data, drflac_uint32 count) { - drflac_assert(count <= 64); - #ifdef DR_FLAC_NO_CRC (void)crc; (void)data; (void)count; return 0; #else - drflac_uint32 wholeBytes = count >> 3; - drflac_uint32 leftoverBits = count - (wholeBytes*8); + drflac_uint32 wholeBytes; + drflac_uint32 leftoverBits; + drflac_uint64 leftoverDataMask; static drflac_uint64 leftoverDataMaskTable[8] = { 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F }; - drflac_uint64 leftoverDataMask = leftoverDataMaskTable[leftoverBits]; + + drflac_assert(count <= 64); + + wholeBytes = count >> 3; + leftoverBits = count - (wholeBytes*8); + leftoverDataMask = leftoverDataMaskTable[leftoverBits]; switch (wholeBytes) { default: - case 8: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & ((drflac_uint64)0xFF00000000000000 << leftoverBits)) >> (56 + leftoverBits))); - case 7: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & ((drflac_uint64)0x00FF000000000000 << leftoverBits)) >> (48 + leftoverBits))); - case 6: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & ((drflac_uint64)0x0000FF0000000000 << leftoverBits)) >> (40 + leftoverBits))); - case 5: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & ((drflac_uint64)0x000000FF00000000 << leftoverBits)) >> (32 + leftoverBits))); - case 4: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & ((drflac_uint64)0x00000000FF000000 << leftoverBits)) >> (24 + leftoverBits))); - case 3: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & ((drflac_uint64)0x0000000000FF0000 << leftoverBits)) >> (16 + leftoverBits))); - case 2: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & ((drflac_uint64)0x000000000000FF00 << leftoverBits)) >> ( 8 + leftoverBits))); - case 1: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & ((drflac_uint64)0x00000000000000FF << leftoverBits)) >> ( 0 + leftoverBits))); + case 8: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0xFF000000 << 32) << leftoverBits)) >> (56 + leftoverBits))); /* Weird "<< 32" bitshift is required for C89 because it doesn't support 64-bit constants. Should be optimized out by a good compiler. */ + case 7: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x00FF0000 << 32) << leftoverBits)) >> (48 + leftoverBits))); + case 6: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x0000FF00 << 32) << leftoverBits)) >> (40 + leftoverBits))); + case 5: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x000000FF << 32) << leftoverBits)) >> (32 + leftoverBits))); + case 4: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0xFF000000 ) << leftoverBits)) >> (24 + leftoverBits))); + case 3: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x00FF0000 ) << leftoverBits)) >> (16 + leftoverBits))); + case 2: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x0000FF00 ) << leftoverBits)) >> ( 8 + leftoverBits))); + case 1: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x000000FF ) << leftoverBits)) >> ( 0 + leftoverBits))); case 0: if (leftoverBits > 0) crc = (crc << leftoverBits) ^ drflac__crc16_table[(crc >> (16 - leftoverBits)) ^ (data & leftoverDataMask)]; } return crc; @@ -1259,27 +1516,26 @@ static DRFLAC_INLINE drflac_uint16 drflac_crc16(drflac_uint16 crc, drflac_cache_ #define drflac__be2host__cache_line drflac__be2host_32 #endif -// BIT READING ATTEMPT #2 -// -// This uses a 32- or 64-bit bit-shifted cache - as bits are read, the cache is shifted such that the first valid bit is sitting -// on the most significant bit. It uses the notion of an L1 and L2 cache (borrowed from CPU architecture), where the L1 cache -// is a 32- or 64-bit unsigned integer (depending on whether or not a 32- or 64-bit build is being compiled) and the L2 is an -// array of "cache lines", with each cache line being the same size as the L1. The L2 is a buffer of about 4KB and is where data -// from onRead() is read into. -#define DRFLAC_CACHE_L1_SIZE_BYTES(bs) (sizeof((bs)->cache)) -#define DRFLAC_CACHE_L1_SIZE_BITS(bs) (sizeof((bs)->cache)*8) -#define DRFLAC_CACHE_L1_BITS_REMAINING(bs) (DRFLAC_CACHE_L1_SIZE_BITS(bs) - ((bs)->consumedBits)) -#ifdef DRFLAC_64BIT -#define DRFLAC_CACHE_L1_SELECTION_MASK(_bitCount) (~(((drflac_uint64)-1LL) >> (_bitCount))) -#else -#define DRFLAC_CACHE_L1_SELECTION_MASK(_bitCount) (~(((drflac_uint32)-1) >> (_bitCount))) -#endif -#define DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, _bitCount) (DRFLAC_CACHE_L1_SIZE_BITS(bs) - (_bitCount)) -#define DRFLAC_CACHE_L1_SELECT(bs, _bitCount) (((bs)->cache) & DRFLAC_CACHE_L1_SELECTION_MASK(_bitCount)) -#define DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, _bitCount) (DRFLAC_CACHE_L1_SELECT((bs), _bitCount) >> DRFLAC_CACHE_L1_SELECTION_SHIFT((bs), _bitCount)) -#define DRFLAC_CACHE_L2_SIZE_BYTES(bs) (sizeof((bs)->cacheL2)) -#define DRFLAC_CACHE_L2_LINE_COUNT(bs) (DRFLAC_CACHE_L2_SIZE_BYTES(bs) / sizeof((bs)->cacheL2[0])) -#define DRFLAC_CACHE_L2_LINES_REMAINING(bs) (DRFLAC_CACHE_L2_LINE_COUNT(bs) - (bs)->nextL2Line) +/* +BIT READING ATTEMPT #2 + +This uses a 32- or 64-bit bit-shifted cache - as bits are read, the cache is shifted such that the first valid bit is sitting +on the most significant bit. It uses the notion of an L1 and L2 cache (borrowed from CPU architecture), where the L1 cache +is a 32- or 64-bit unsigned integer (depending on whether or not a 32- or 64-bit build is being compiled) and the L2 is an +array of "cache lines", with each cache line being the same size as the L1. The L2 is a buffer of about 4KB and is where data +from onRead() is read into. +*/ +#define DRFLAC_CACHE_L1_SIZE_BYTES(bs) (sizeof((bs)->cache)) +#define DRFLAC_CACHE_L1_SIZE_BITS(bs) (sizeof((bs)->cache)*8) +#define DRFLAC_CACHE_L1_BITS_REMAINING(bs) (DRFLAC_CACHE_L1_SIZE_BITS(bs) - (bs)->consumedBits) +#define DRFLAC_CACHE_L1_SELECTION_MASK(_bitCount) (~((~(drflac_cache_t)0) >> (_bitCount))) +#define DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, _bitCount) (DRFLAC_CACHE_L1_SIZE_BITS(bs) - (_bitCount)) +#define DRFLAC_CACHE_L1_SELECT(bs, _bitCount) (((bs)->cache) & DRFLAC_CACHE_L1_SELECTION_MASK(_bitCount)) +#define DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, _bitCount) (DRFLAC_CACHE_L1_SELECT((bs), (_bitCount)) >> DRFLAC_CACHE_L1_SELECTION_SHIFT((bs), (_bitCount))) +#define DRFLAC_CACHE_L1_SELECT_AND_SHIFT_SAFE(bs, _bitCount)(DRFLAC_CACHE_L1_SELECT((bs), (_bitCount)) >> (DRFLAC_CACHE_L1_SELECTION_SHIFT((bs), (_bitCount)) & (DRFLAC_CACHE_L1_SIZE_BITS(bs)-1))) +#define DRFLAC_CACHE_L2_SIZE_BYTES(bs) (sizeof((bs)->cacheL2)) +#define DRFLAC_CACHE_L2_LINE_COUNT(bs) (DRFLAC_CACHE_L2_SIZE_BYTES(bs) / sizeof((bs)->cacheL2[0])) +#define DRFLAC_CACHE_L2_LINES_REMAINING(bs) (DRFLAC_CACHE_L2_LINE_COUNT(bs) - (bs)->nextL2Line) #ifndef DR_FLAC_NO_CRC @@ -1297,19 +1553,23 @@ static DRFLAC_INLINE void drflac__update_crc16(drflac_bs* bs) static DRFLAC_INLINE drflac_uint16 drflac__flush_crc16(drflac_bs* bs) { - // We should never be flushing in a situation where we are not aligned on a byte boundary. + /* We should never be flushing in a situation where we are not aligned on a byte boundary. */ drflac_assert((DRFLAC_CACHE_L1_BITS_REMAINING(bs) & 7) == 0); - // The bits that were read from the L1 cache need to be accumulated. The number of bytes needing to be accumulated is determined - // by the number of bits that have been consumed. + /* + The bits that were read from the L1 cache need to be accumulated. The number of bytes needing to be accumulated is determined + by the number of bits that have been consumed. + */ if (DRFLAC_CACHE_L1_BITS_REMAINING(bs) == 0) { drflac__update_crc16(bs); } else { - // We only accumulate the consumed bits. + /* We only accumulate the consumed bits. */ bs->crc16 = drflac_crc16_bytes(bs->crc16, bs->crc16Cache >> DRFLAC_CACHE_L1_BITS_REMAINING(bs), (bs->consumedBits >> 3) - bs->crc16CacheIgnoredBytes); - // The bits that we just accumulated should never be accumulated again. We need to keep track of how many bytes were accumulated - // so we can handle that later. + /* + The bits that we just accumulated should never be accumulated again. We need to keep track of how many bytes were accumulated + so we can handle that later. + */ bs->crc16CacheIgnoredBytes = bs->consumedBits >> 3; } @@ -1319,19 +1579,24 @@ static DRFLAC_INLINE drflac_uint16 drflac__flush_crc16(drflac_bs* bs) static DRFLAC_INLINE drflac_bool32 drflac__reload_l1_cache_from_l2(drflac_bs* bs) { - // Fast path. Try loading straight from L2. + size_t bytesRead; + size_t alignedL1LineCount; + + /* Fast path. Try loading straight from L2. */ if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) { bs->cache = bs->cacheL2[bs->nextL2Line++]; return DRFLAC_TRUE; } - // If we get here it means we've run out of data in the L2 cache. We'll need to fetch more from the client, if there's - // any left. + /* + If we get here it means we've run out of data in the L2 cache. We'll need to fetch more from the client, if there's + any left. + */ if (bs->unalignedByteCount > 0) { - return DRFLAC_FALSE; // If we have any unaligned bytes it means there's no more aligned bytes left in the client. + return DRFLAC_FALSE; /* If we have any unaligned bytes it means there's no more aligned bytes left in the client. */ } - size_t bytesRead = bs->onRead(bs->pUserData, bs->cacheL2, DRFLAC_CACHE_L2_SIZE_BYTES(bs)); + bytesRead = bs->onRead(bs->pUserData, bs->cacheL2, DRFLAC_CACHE_L2_SIZE_BYTES(bs)); bs->nextL2Line = 0; if (bytesRead == DRFLAC_CACHE_L2_SIZE_BYTES(bs)) { @@ -1340,13 +1605,15 @@ static DRFLAC_INLINE drflac_bool32 drflac__reload_l1_cache_from_l2(drflac_bs* bs } - // If we get here it means we were unable to retrieve enough data to fill the entire L2 cache. It probably - // means we've just reached the end of the file. We need to move the valid data down to the end of the buffer - // and adjust the index of the next line accordingly. Also keep in mind that the L2 cache must be aligned to - // the size of the L1 so we'll need to seek backwards by any misaligned bytes. - size_t alignedL1LineCount = bytesRead / DRFLAC_CACHE_L1_SIZE_BYTES(bs); + /* + If we get here it means we were unable to retrieve enough data to fill the entire L2 cache. It probably + means we've just reached the end of the file. We need to move the valid data down to the end of the buffer + and adjust the index of the next line accordingly. Also keep in mind that the L2 cache must be aligned to + the size of the L1 so we'll need to seek backwards by any misaligned bytes. + */ + alignedL1LineCount = bytesRead / DRFLAC_CACHE_L1_SIZE_BYTES(bs); - // We need to keep track of any unaligned bytes for later use. + /* We need to keep track of any unaligned bytes for later use. */ bs->unalignedByteCount = bytesRead - (alignedL1LineCount * DRFLAC_CACHE_L1_SIZE_BYTES(bs)); if (bs->unalignedByteCount > 0) { bs->unalignedCache = bs->cacheL2[alignedL1LineCount]; @@ -1354,7 +1621,8 @@ static DRFLAC_INLINE drflac_bool32 drflac__reload_l1_cache_from_l2(drflac_bs* bs if (alignedL1LineCount > 0) { size_t offset = DRFLAC_CACHE_L2_LINE_COUNT(bs) - alignedL1LineCount; - for (size_t i = alignedL1LineCount; i > 0; --i) { + size_t i; + for (i = alignedL1LineCount; i > 0; --i) { bs->cacheL2[i-1 + offset] = bs->cacheL2[i-1]; } @@ -1362,7 +1630,7 @@ static DRFLAC_INLINE drflac_bool32 drflac__reload_l1_cache_from_l2(drflac_bs* bs bs->cache = bs->cacheL2[bs->nextL2Line++]; return DRFLAC_TRUE; } else { - // If we get into this branch it means we weren't able to load any L1-aligned data. + /* If we get into this branch it means we weren't able to load any L1-aligned data. */ bs->nextL2Line = DRFLAC_CACHE_L2_LINE_COUNT(bs); return DRFLAC_FALSE; } @@ -1370,11 +1638,13 @@ static DRFLAC_INLINE drflac_bool32 drflac__reload_l1_cache_from_l2(drflac_bs* bs static drflac_bool32 drflac__reload_cache(drflac_bs* bs) { + size_t bytesRead; + #ifndef DR_FLAC_NO_CRC drflac__update_crc16(bs); #endif - // Fast path. Try just moving the next value in the L2 cache to the L1 cache. + /* Fast path. Try just moving the next value in the L2 cache to the L1 cache. */ if (drflac__reload_l1_cache_from_l2(bs)) { bs->cache = drflac__be2host__cache_line(bs->cache); bs->consumedBits = 0; @@ -1384,13 +1654,16 @@ static drflac_bool32 drflac__reload_cache(drflac_bs* bs) return DRFLAC_TRUE; } - // Slow path. + /* Slow path. */ - // If we get here it means we have failed to load the L1 cache from the L2. Likely we've just reached the end of the stream and the last - // few bytes did not meet the alignment requirements for the L2 cache. In this case we need to fall back to a slower path and read the - // data from the unaligned cache. - size_t bytesRead = bs->unalignedByteCount; + /* + If we get here it means we have failed to load the L1 cache from the L2. Likely we've just reached the end of the stream and the last + few bytes did not meet the alignment requirements for the L2 cache. In this case we need to fall back to a slower path and read the + data from the unaligned cache. + */ + bytesRead = bs->unalignedByteCount; if (bytesRead == 0) { + bs->consumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs); /* <-- The stream has been exhausted, so marked the bits as consumed. */ return DRFLAC_FALSE; } @@ -1398,8 +1671,8 @@ static drflac_bool32 drflac__reload_cache(drflac_bs* bs) bs->consumedBits = (drflac_uint32)(DRFLAC_CACHE_L1_SIZE_BYTES(bs) - bytesRead) * 8; bs->cache = drflac__be2host__cache_line(bs->unalignedCache); - bs->cache &= DRFLAC_CACHE_L1_SELECTION_MASK(DRFLAC_CACHE_L1_SIZE_BITS(bs) - bs->consumedBits); // <-- Make sure the consumed bits are always set to zero. Other parts of the library depend on this property. - bs->unalignedByteCount = 0; // <-- At this point the unaligned bytes have been moved into the cache and we thus have no more unaligned bytes. + bs->cache &= DRFLAC_CACHE_L1_SELECTION_MASK(DRFLAC_CACHE_L1_BITS_REMAINING(bs)); /* <-- Make sure the consumed bits are always set to zero. Other parts of the library depend on this property. */ + bs->unalignedByteCount = 0; /* <-- At this point the unaligned bytes have been moved into the cache and we thus have no more unaligned bytes. */ #ifndef DR_FLAC_NO_CRC bs->crc16Cache = bs->cache >> bs->consumedBits; @@ -1410,10 +1683,10 @@ static drflac_bool32 drflac__reload_cache(drflac_bs* bs) static void drflac__reset_cache(drflac_bs* bs) { - bs->nextL2Line = DRFLAC_CACHE_L2_LINE_COUNT(bs); // <-- This clears the L2 cache. - bs->consumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs); // <-- This clears the L1 cache. + bs->nextL2Line = DRFLAC_CACHE_L2_LINE_COUNT(bs); /* <-- This clears the L2 cache. */ + bs->consumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs); /* <-- This clears the L1 cache. */ bs->cache = 0; - bs->unalignedByteCount = 0; // <-- This clears the trailing unaligned bytes. + bs->unalignedByteCount = 0; /* <-- This clears the trailing unaligned bytes. */ bs->unalignedCache = 0; #ifndef DR_FLAC_NO_CRC @@ -1437,18 +1710,31 @@ static DRFLAC_INLINE drflac_bool32 drflac__read_uint32(drflac_bs* bs, unsigned i } if (bitCount <= DRFLAC_CACHE_L1_BITS_REMAINING(bs)) { + /* + If we want to load all 32-bits from a 32-bit cache we need to do it slightly differently because we can't do + a 32-bit shift on a 32-bit integer. This will never be the case on 64-bit caches, so we can have a slightly + more optimal solution for this. + */ +#ifdef DRFLAC_64BIT + *pResultOut = (drflac_uint32)DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCount); + bs->consumedBits += bitCount; + bs->cache <<= bitCount; +#else if (bitCount < DRFLAC_CACHE_L1_SIZE_BITS(bs)) { *pResultOut = (drflac_uint32)DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCount); bs->consumedBits += bitCount; bs->cache <<= bitCount; } else { + /* Cannot shift by 32-bits, so need to do it differently. */ *pResultOut = (drflac_uint32)bs->cache; bs->consumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs); bs->cache = 0; } +#endif + return DRFLAC_TRUE; } else { - // It straddles the cached data. It will never cover more than the next chunk. We just read the number in two parts and combine them. + /* It straddles the cached data. It will never cover more than the next chunk. We just read the number in two parts and combine them. */ drflac_uint32 bitCountHi = DRFLAC_CACHE_L1_BITS_REMAINING(bs); drflac_uint32 bitCountLo = bitCount - bitCountHi; drflac_uint32 resultHi = (drflac_uint32)DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCountHi); @@ -1466,17 +1752,19 @@ static DRFLAC_INLINE drflac_bool32 drflac__read_uint32(drflac_bs* bs, unsigned i static drflac_bool32 drflac__read_int32(drflac_bs* bs, unsigned int bitCount, drflac_int32* pResult) { + drflac_uint32 result; + drflac_uint32 signbit; + drflac_assert(bs != NULL); drflac_assert(pResult != NULL); drflac_assert(bitCount > 0); drflac_assert(bitCount <= 32); - drflac_uint32 result; if (!drflac__read_uint32(bs, bitCount, &result)) { return DRFLAC_FALSE; } - drflac_uint32 signbit = ((result >> (bitCount-1)) & 0x01); + signbit = ((result >> (bitCount-1)) & 0x01); result |= (~signbit + 1) << bitCount; *pResult = (drflac_int32)result; @@ -1486,15 +1774,16 @@ static drflac_bool32 drflac__read_int32(drflac_bs* bs, unsigned int bitCount, dr #ifdef DRFLAC_64BIT static drflac_bool32 drflac__read_uint64(drflac_bs* bs, unsigned int bitCount, drflac_uint64* pResultOut) { + drflac_uint32 resultHi; + drflac_uint32 resultLo; + drflac_assert(bitCount <= 64); drflac_assert(bitCount > 32); - drflac_uint32 resultHi; if (!drflac__read_uint32(bs, bitCount - 32, &resultHi)) { return DRFLAC_FALSE; } - drflac_uint32 resultLo; if (!drflac__read_uint32(bs, 32, &resultLo)) { return DRFLAC_FALSE; } @@ -1504,18 +1793,20 @@ static drflac_bool32 drflac__read_uint64(drflac_bs* bs, unsigned int bitCount, d } #endif -// Function below is unused, but leaving it here in case I need to quickly add it again. +/* Function below is unused, but leaving it here in case I need to quickly add it again. */ #if 0 static drflac_bool32 drflac__read_int64(drflac_bs* bs, unsigned int bitCount, drflac_int64* pResultOut) { + drflac_uint64 result; + drflac_uint64 signbit; + drflac_assert(bitCount <= 64); - drflac_uint64 result; if (!drflac__read_uint64(bs, bitCount, &result)) { return DRFLAC_FALSE; } - drflac_uint64 signbit = ((result >> (bitCount-1)) & 0x01); + signbit = ((result >> (bitCount-1)) & 0x01); result |= (~signbit + 1) << bitCount; *pResultOut = (drflac_int64)result; @@ -1525,12 +1816,13 @@ static drflac_bool32 drflac__read_int64(drflac_bs* bs, unsigned int bitCount, dr static drflac_bool32 drflac__read_uint16(drflac_bs* bs, unsigned int bitCount, drflac_uint16* pResult) { + drflac_uint32 result; + drflac_assert(bs != NULL); drflac_assert(pResult != NULL); drflac_assert(bitCount > 0); drflac_assert(bitCount <= 16); - drflac_uint32 result; if (!drflac__read_uint32(bs, bitCount, &result)) { return DRFLAC_FALSE; } @@ -1542,12 +1834,13 @@ static drflac_bool32 drflac__read_uint16(drflac_bs* bs, unsigned int bitCount, d #if 0 static drflac_bool32 drflac__read_int16(drflac_bs* bs, unsigned int bitCount, drflac_int16* pResult) { + drflac_int32 result; + drflac_assert(bs != NULL); drflac_assert(pResult != NULL); drflac_assert(bitCount > 0); drflac_assert(bitCount <= 16); - drflac_int32 result; if (!drflac__read_int32(bs, bitCount, &result)) { return DRFLAC_FALSE; } @@ -1559,12 +1852,13 @@ static drflac_bool32 drflac__read_int16(drflac_bs* bs, unsigned int bitCount, dr static drflac_bool32 drflac__read_uint8(drflac_bs* bs, unsigned int bitCount, drflac_uint8* pResult) { + drflac_uint32 result; + drflac_assert(bs != NULL); drflac_assert(pResult != NULL); drflac_assert(bitCount > 0); drflac_assert(bitCount <= 8); - drflac_uint32 result; if (!drflac__read_uint32(bs, bitCount, &result)) { return DRFLAC_FALSE; } @@ -1575,12 +1869,13 @@ static drflac_bool32 drflac__read_uint8(drflac_bs* bs, unsigned int bitCount, dr static drflac_bool32 drflac__read_int8(drflac_bs* bs, unsigned int bitCount, drflac_int8* pResult) { + drflac_int32 result; + drflac_assert(bs != NULL); drflac_assert(pResult != NULL); drflac_assert(bitCount > 0); drflac_assert(bitCount <= 8); - drflac_int32 result; if (!drflac__read_int32(bs, bitCount, &result)) { return DRFLAC_FALSE; } @@ -1597,12 +1892,12 @@ static drflac_bool32 drflac__seek_bits(drflac_bs* bs, size_t bitsToSeek) bs->cache <<= bitsToSeek; return DRFLAC_TRUE; } else { - // It straddles the cached data. This function isn't called too frequently so I'm favouring simplicity here. + /* It straddles the cached data. This function isn't called too frequently so I'm favouring simplicity here. */ bitsToSeek -= DRFLAC_CACHE_L1_BITS_REMAINING(bs); bs->consumedBits += DRFLAC_CACHE_L1_BITS_REMAINING(bs); bs->cache = 0; - // Simple case. Seek in groups of the same number as bits that fit within a cache line. + /* Simple case. Seek in groups of the same number as bits that fit within a cache line. */ #ifdef DRFLAC_64BIT while (bitsToSeek >= DRFLAC_CACHE_L1_SIZE_BITS(bs)) { drflac_uint64 bin; @@ -1621,7 +1916,7 @@ static drflac_bool32 drflac__seek_bits(drflac_bs* bs, size_t bitsToSeek) } #endif - // Whole leftover bytes. + /* Whole leftover bytes. */ while (bitsToSeek >= 8) { drflac_uint8 bin; if (!drflac__read_uint8(bs, 8, &bin)) { @@ -1630,13 +1925,13 @@ static drflac_bool32 drflac__seek_bits(drflac_bs* bs, size_t bitsToSeek) bitsToSeek -= 8; } - // Leftover bits. + /* Leftover bits. */ if (bitsToSeek > 0) { drflac_uint8 bin; if (!drflac__read_uint8(bs, (drflac_uint32)bitsToSeek, &bin)) { return DRFLAC_FALSE; } - bitsToSeek = 0; // <-- Necessary for the assert below. + bitsToSeek = 0; /* <-- Necessary for the assert below. */ } drflac_assert(bitsToSeek == 0); @@ -1645,23 +1940,26 @@ static drflac_bool32 drflac__seek_bits(drflac_bs* bs, size_t bitsToSeek) } -// This function moves the bit streamer to the first bit after the sync code (bit 15 of the of the frame header). It will also update the CRC-16. +/* This function moves the bit streamer to the first bit after the sync code (bit 15 of the of the frame header). It will also update the CRC-16. */ static drflac_bool32 drflac__find_and_seek_to_next_sync_code(drflac_bs* bs) { drflac_assert(bs != NULL); - // The sync code is always aligned to 8 bits. This is convenient for us because it means we can do byte-aligned movements. The first - // thing to do is align to the next byte. + /* + The sync code is always aligned to 8 bits. This is convenient for us because it means we can do byte-aligned movements. The first + thing to do is align to the next byte. + */ if (!drflac__seek_bits(bs, DRFLAC_CACHE_L1_BITS_REMAINING(bs) & 7)) { return DRFLAC_FALSE; } for (;;) { + drflac_uint8 hi; + #ifndef DR_FLAC_NO_CRC drflac__reset_crc16(bs); #endif - drflac_uint8 hi; if (!drflac__read_uint8(bs, 8, &hi)) { return DRFLAC_FALSE; } @@ -1682,8 +1980,8 @@ static drflac_bool32 drflac__find_and_seek_to_next_sync_code(drflac_bs* bs) } } - // Should never get here. - //return DRFLAC_FALSE; + /* Should never get here. */ + /*return DRFLAC_FALSE;*/ } @@ -1696,6 +1994,7 @@ static drflac_bool32 drflac__find_and_seek_to_next_sync_code(drflac_bs* bs) static DRFLAC_INLINE drflac_uint32 drflac__clz_software(drflac_cache_t x) { + drflac_uint32 n; static drflac_uint32 clz_table_4[] = { 0, 4, @@ -1704,13 +2003,17 @@ static DRFLAC_INLINE drflac_uint32 drflac__clz_software(drflac_cache_t x) 1, 1, 1, 1, 1, 1, 1, 1 }; - drflac_uint32 n = clz_table_4[x >> (sizeof(x)*8 - 4)]; + if (x == 0) { + return sizeof(x)*8; + } + + n = clz_table_4[x >> (sizeof(x)*8 - 4)]; if (n == 0) { #ifdef DRFLAC_64BIT - if ((x & 0xFFFFFFFF00000000ULL) == 0) { n = 32; x <<= 32; } - if ((x & 0xFFFF000000000000ULL) == 0) { n += 16; x <<= 16; } - if ((x & 0xFF00000000000000ULL) == 0) { n += 8; x <<= 8; } - if ((x & 0xF000000000000000ULL) == 0) { n += 4; x <<= 4; } + if ((x & ((drflac_uint64)0xFFFFFFFF << 32)) == 0) { n = 32; x <<= 32; } + if ((x & ((drflac_uint64)0xFFFF0000 << 32)) == 0) { n += 16; x <<= 16; } + if ((x & ((drflac_uint64)0xFF000000 << 32)) == 0) { n += 8; x <<= 8; } + if ((x & ((drflac_uint64)0xF0000000 << 32)) == 0) { n += 4; x <<= 4; } #else if ((x & 0xFFFF0000) == 0) { n = 16; x <<= 16; } if ((x & 0xFF000000) == 0) { n += 8; x <<= 8; } @@ -1725,7 +2028,7 @@ static DRFLAC_INLINE drflac_uint32 drflac__clz_software(drflac_cache_t x) #ifdef DRFLAC_IMPLEMENT_CLZ_LZCNT static DRFLAC_INLINE drflac_bool32 drflac__is_lzcnt_supported() { - // If the compiler itself does not support the intrinsic then we'll need to return false. + /* If the compiler itself does not support the intrinsic then we'll need to return false. */ #ifdef DRFLAC_HAS_LZCNT_INTRINSIC return drflac__gIsLZCNTSupported; #else @@ -1743,13 +2046,16 @@ static DRFLAC_INLINE drflac_uint32 drflac__clz_lzcnt(drflac_cache_t x) #endif #else #if defined(__GNUC__) || defined(__clang__) + if (x == 0) { + return sizeof(x)*8; + } #ifdef DRFLAC_64BIT - return (drflac_uint32)__builtin_clzll((unsigned long long)x); + return (drflac_uint32)__builtin_clzll((drflac_uint64)x); #else - return (drflac_uint32)__builtin_clzl((unsigned long)x); + return (drflac_uint32)__builtin_clzl((drflac_uint32)x); #endif #else - // Unsupported compiler. + /* Unsupported compiler. */ #error "This compiler does not support the lzcnt intrinsic." #endif #endif @@ -1757,9 +2063,16 @@ static DRFLAC_INLINE drflac_uint32 drflac__clz_lzcnt(drflac_cache_t x) #endif #ifdef DRFLAC_IMPLEMENT_CLZ_MSVC +#include /* For BitScanReverse(). */ + static DRFLAC_INLINE drflac_uint32 drflac__clz_msvc(drflac_cache_t x) { drflac_uint32 n; + + if (x == 0) { + return sizeof(x)*8; + } + #ifdef DRFLAC_64BIT _BitScanReverse64((unsigned long*)&n, x); #else @@ -1771,25 +2084,26 @@ static DRFLAC_INLINE drflac_uint32 drflac__clz_msvc(drflac_cache_t x) static DRFLAC_INLINE drflac_uint32 drflac__clz(drflac_cache_t x) { - // This function assumes at least one bit is set. Checking for 0 needs to be done at a higher level, outside this function. #ifdef DRFLAC_IMPLEMENT_CLZ_LZCNT if (drflac__is_lzcnt_supported()) { return drflac__clz_lzcnt(x); } else #endif { - #ifdef DRFLAC_IMPLEMENT_CLZ_MSVC +#ifdef DRFLAC_IMPLEMENT_CLZ_MSVC return drflac__clz_msvc(x); - #else +#else return drflac__clz_software(x); - #endif +#endif } } -static inline drflac_bool32 drflac__seek_past_next_set_bit(drflac_bs* bs, unsigned int* pOffsetOut) +static DRFLAC_INLINE drflac_bool32 drflac__seek_past_next_set_bit(drflac_bs* bs, unsigned int* pOffsetOut) { drflac_uint32 zeroCounter = 0; + drflac_uint32 setBitOffsetPlus1; + while (bs->cache == 0) { zeroCounter += (drflac_uint32)DRFLAC_CACHE_L1_BITS_REMAINING(bs); if (!drflac__reload_cache(bs)) { @@ -1797,7 +2111,7 @@ static inline drflac_bool32 drflac__seek_past_next_set_bit(drflac_bs* bs, unsign } } - drflac_uint32 setBitOffsetPlus1 = drflac__clz(bs->cache); + setBitOffsetPlus1 = drflac__clz(bs->cache); setBitOffsetPlus1 += 1; bs->consumedBits += setBitOffsetPlus1; @@ -1814,9 +2128,11 @@ static drflac_bool32 drflac__seek_to_byte(drflac_bs* bs, drflac_uint64 offsetFro drflac_assert(bs != NULL); drflac_assert(offsetFromStart > 0); - // Seeking from the start is not quite as trivial as it sounds because the onSeek callback takes a signed 32-bit integer (which - // is intentional because it simplifies the implementation of the onSeek callbacks), however offsetFromStart is unsigned 64-bit. - // To resolve we just need to do an initial seek from the start, and then a series of offset seeks to make up the remainder. + /* + Seeking from the start is not quite as trivial as it sounds because the onSeek callback takes a signed 32-bit integer (which + is intentional because it simplifies the implementation of the onSeek callbacks), however offsetFromStart is unsigned 64-bit. + To resolve we just need to do an initial seek from the start, and then a series of offset seeks to make up the remainder. + */ if (offsetFromStart > 0x7FFFFFFF) { drflac_uint64 bytesRemaining = offsetFromStart; if (!bs->onSeek(bs->pUserData, 0x7FFFFFFF, drflac_seek_origin_start)) { @@ -1842,7 +2158,7 @@ static drflac_bool32 drflac__seek_to_byte(drflac_bs* bs, drflac_uint64 offsetFro } } - // The cache should be reset to force a reload of fresh data from the client. + /* The cache should be reset to force a reload of fresh data from the client. */ drflac__reset_cache(bs); return DRFLAC_TRUE; } @@ -1850,12 +2166,18 @@ static drflac_bool32 drflac__seek_to_byte(drflac_bs* bs, drflac_uint64 offsetFro static drflac_result drflac__read_utf8_coded_number(drflac_bs* bs, drflac_uint64* pNumberOut, drflac_uint8* pCRCOut) { + drflac_uint8 crc; + drflac_uint64 result; + unsigned char utf8[7] = {0}; + int byteCount; + int i; + drflac_assert(bs != NULL); drflac_assert(pNumberOut != NULL); + drflac_assert(pCRCOut != NULL); - drflac_uint8 crc = *pCRCOut; + crc = *pCRCOut; - unsigned char utf8[7] = {0}; if (!drflac__read_uint8(bs, 8, utf8)) { *pNumberOut = 0; return DRFLAC_END_OF_STREAM; @@ -1868,7 +2190,7 @@ static drflac_result drflac__read_utf8_coded_number(drflac_bs* bs, drflac_uint64 return DRFLAC_SUCCESS; } - int byteCount = 1; + byteCount = 1; if ((utf8[0] & 0xE0) == 0xC0) { byteCount = 2; } else if ((utf8[0] & 0xF0) == 0xE0) { @@ -1883,14 +2205,14 @@ static drflac_result drflac__read_utf8_coded_number(drflac_bs* bs, drflac_uint64 byteCount = 7; } else { *pNumberOut = 0; - return DRFLAC_CRC_MISMATCH; // Bad UTF-8 encoding. + return DRFLAC_CRC_MISMATCH; /* Bad UTF-8 encoding. */ } - // Read extra bytes. + /* Read extra bytes. */ drflac_assert(byteCount > 1); - drflac_uint64 result = (drflac_uint64)(utf8[0] & (0xFF >> (byteCount + 1))); - for (int i = 1; i < byteCount; ++i) { + result = (drflac_uint64)(utf8[0] & (0xFF >> (byteCount + 1))); + for (i = 1; i < byteCount; ++i) { if (!drflac__read_uint8(bs, 8, utf8 + i)) { *pNumberOut = 0; return DRFLAC_END_OF_STREAM; @@ -1907,20 +2229,21 @@ static drflac_result drflac__read_utf8_coded_number(drflac_bs* bs, drflac_uint64 +/* +The next two functions are responsible for calculating the prediction. -// The next two functions are responsible for calculating the prediction. -// -// When the bits per sample is >16 we need to use 64-bit integer arithmetic because otherwise we'll run out of precision. It's -// safe to assume this will be slower on 32-bit platforms so we use a more optimal solution when the bits per sample is <=16. +When the bits per sample is >16 we need to use 64-bit integer arithmetic because otherwise we'll run out of precision. It's +safe to assume this will be slower on 32-bit platforms so we use a more optimal solution when the bits per sample is <=16. +*/ static DRFLAC_INLINE drflac_int32 drflac__calculate_prediction_32(drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pDecodedSamples) { - drflac_assert(order <= 32); + drflac_int32 prediction = 0; - // 32-bit version. + drflac_assert(order <= 32); - // VC++ optimizes this to a single jmp. I've not yet verified this for other compilers. - drflac_int32 prediction = 0; + /* 32-bit version. */ + /* VC++ optimizes this to a single jmp. I've not yet verified this for other compilers. */ switch (order) { case 32: prediction += coefficients[31] * pDecodedSamples[-32]; @@ -1962,13 +2285,14 @@ static DRFLAC_INLINE drflac_int32 drflac__calculate_prediction_32(drflac_uint32 static DRFLAC_INLINE drflac_int32 drflac__calculate_prediction_64(drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pDecodedSamples) { + drflac_int64 prediction; + drflac_assert(order <= 32); - // 64-bit version. + /* 64-bit version. */ - // This method is faster on the 32-bit build when compiling with VC++. See note below. + /* This method is faster on the 32-bit build when compiling with VC++. See note below. */ #ifndef DRFLAC_64BIT - drflac_int64 prediction; if (order == 8) { prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1]; @@ -2085,18 +2409,21 @@ static DRFLAC_INLINE drflac_int32 drflac__calculate_prediction_64(drflac_uint32 } else { + int j; + prediction = 0; - for (int j = 0; j < (int)order; ++j) { + for (j = 0; j < (int)order; ++j) { prediction += coefficients[j] * (drflac_int64)pDecodedSamples[-j-1]; } } #endif - // VC++ optimizes this to a single jmp instruction, but only the 64-bit build. The 32-bit build generates less efficient code for some - // reason. The ugly version above is faster so we'll just switch between the two depending on the target platform. + /* + VC++ optimizes this to a single jmp instruction, but only the 64-bit build. The 32-bit build generates less efficient code for some + reason. The ugly version above is faster so we'll just switch between the two depending on the target platform. + */ #ifdef DRFLAC_64BIT - drflac_int64 prediction = 0; - + prediction = 0; switch (order) { case 32: prediction += coefficients[31] * (drflac_int64)pDecodedSamples[-32]; @@ -2137,16 +2464,451 @@ static DRFLAC_INLINE drflac_int32 drflac__calculate_prediction_64(drflac_uint32 return (drflac_int32)(prediction >> shift); } +static DRFLAC_INLINE void drflac__calculate_prediction_64_x4(drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, const drflac_uint32 riceParamParts[4], drflac_int32* pDecodedSamples) +{ + drflac_int64 prediction0 = 0; + drflac_int64 prediction1 = 0; + drflac_int64 prediction2 = 0; + drflac_int64 prediction3 = 0; + + drflac_assert(order <= 32); + + switch (order) + { + case 32: + prediction0 += coefficients[31] * (drflac_int64)pDecodedSamples[-32]; + prediction1 += coefficients[31] * (drflac_int64)pDecodedSamples[-31]; + prediction2 += coefficients[31] * (drflac_int64)pDecodedSamples[-30]; + prediction3 += coefficients[31] * (drflac_int64)pDecodedSamples[-29]; + case 31: + prediction0 += coefficients[30] * (drflac_int64)pDecodedSamples[-31]; + prediction1 += coefficients[30] * (drflac_int64)pDecodedSamples[-30]; + prediction2 += coefficients[30] * (drflac_int64)pDecodedSamples[-29]; + prediction3 += coefficients[30] * (drflac_int64)pDecodedSamples[-28]; + case 30: + prediction0 += coefficients[29] * (drflac_int64)pDecodedSamples[-30]; + prediction1 += coefficients[29] * (drflac_int64)pDecodedSamples[-29]; + prediction2 += coefficients[29] * (drflac_int64)pDecodedSamples[-28]; + prediction3 += coefficients[29] * (drflac_int64)pDecodedSamples[-27]; + case 29: + prediction0 += coefficients[28] * (drflac_int64)pDecodedSamples[-29]; + prediction1 += coefficients[28] * (drflac_int64)pDecodedSamples[-28]; + prediction2 += coefficients[28] * (drflac_int64)pDecodedSamples[-27]; + prediction3 += coefficients[28] * (drflac_int64)pDecodedSamples[-26]; + case 28: + prediction0 += coefficients[27] * (drflac_int64)pDecodedSamples[-28]; + prediction1 += coefficients[27] * (drflac_int64)pDecodedSamples[-27]; + prediction2 += coefficients[27] * (drflac_int64)pDecodedSamples[-26]; + prediction3 += coefficients[27] * (drflac_int64)pDecodedSamples[-25]; + case 27: + prediction0 += coefficients[26] * (drflac_int64)pDecodedSamples[-27]; + prediction1 += coefficients[26] * (drflac_int64)pDecodedSamples[-26]; + prediction2 += coefficients[26] * (drflac_int64)pDecodedSamples[-25]; + prediction3 += coefficients[26] * (drflac_int64)pDecodedSamples[-24]; + case 26: + prediction0 += coefficients[25] * (drflac_int64)pDecodedSamples[-26]; + prediction1 += coefficients[25] * (drflac_int64)pDecodedSamples[-25]; + prediction2 += coefficients[25] * (drflac_int64)pDecodedSamples[-24]; + prediction3 += coefficients[25] * (drflac_int64)pDecodedSamples[-23]; + case 25: + prediction0 += coefficients[24] * (drflac_int64)pDecodedSamples[-25]; + prediction1 += coefficients[24] * (drflac_int64)pDecodedSamples[-24]; + prediction2 += coefficients[24] * (drflac_int64)pDecodedSamples[-23]; + prediction3 += coefficients[24] * (drflac_int64)pDecodedSamples[-22]; + case 24: + prediction0 += coefficients[23] * (drflac_int64)pDecodedSamples[-24]; + prediction1 += coefficients[23] * (drflac_int64)pDecodedSamples[-23]; + prediction2 += coefficients[23] * (drflac_int64)pDecodedSamples[-22]; + prediction3 += coefficients[23] * (drflac_int64)pDecodedSamples[-21]; + case 23: + prediction0 += coefficients[22] * (drflac_int64)pDecodedSamples[-23]; + prediction1 += coefficients[22] * (drflac_int64)pDecodedSamples[-22]; + prediction2 += coefficients[22] * (drflac_int64)pDecodedSamples[-21]; + prediction3 += coefficients[22] * (drflac_int64)pDecodedSamples[-20]; + case 22: + prediction0 += coefficients[21] * (drflac_int64)pDecodedSamples[-22]; + prediction1 += coefficients[21] * (drflac_int64)pDecodedSamples[-21]; + prediction2 += coefficients[21] * (drflac_int64)pDecodedSamples[-20]; + prediction3 += coefficients[21] * (drflac_int64)pDecodedSamples[-19]; + case 21: + prediction0 += coefficients[20] * (drflac_int64)pDecodedSamples[-21]; + prediction1 += coefficients[20] * (drflac_int64)pDecodedSamples[-20]; + prediction2 += coefficients[20] * (drflac_int64)pDecodedSamples[-19]; + prediction3 += coefficients[20] * (drflac_int64)pDecodedSamples[-18]; + case 20: + prediction0 += coefficients[19] * (drflac_int64)pDecodedSamples[-20]; + prediction1 += coefficients[19] * (drflac_int64)pDecodedSamples[-19]; + prediction2 += coefficients[19] * (drflac_int64)pDecodedSamples[-18]; + prediction3 += coefficients[19] * (drflac_int64)pDecodedSamples[-17]; + case 19: + prediction0 += coefficients[18] * (drflac_int64)pDecodedSamples[-19]; + prediction1 += coefficients[18] * (drflac_int64)pDecodedSamples[-18]; + prediction2 += coefficients[18] * (drflac_int64)pDecodedSamples[-17]; + prediction3 += coefficients[18] * (drflac_int64)pDecodedSamples[-16]; + case 18: + prediction0 += coefficients[17] * (drflac_int64)pDecodedSamples[-18]; + prediction1 += coefficients[17] * (drflac_int64)pDecodedSamples[-17]; + prediction2 += coefficients[17] * (drflac_int64)pDecodedSamples[-16]; + prediction3 += coefficients[17] * (drflac_int64)pDecodedSamples[-15]; + case 17: + prediction0 += coefficients[16] * (drflac_int64)pDecodedSamples[-17]; + prediction1 += coefficients[16] * (drflac_int64)pDecodedSamples[-16]; + prediction2 += coefficients[16] * (drflac_int64)pDecodedSamples[-15]; + prediction3 += coefficients[16] * (drflac_int64)pDecodedSamples[-14]; + + case 16: + prediction0 += coefficients[15] * (drflac_int64)pDecodedSamples[-16]; + prediction1 += coefficients[15] * (drflac_int64)pDecodedSamples[-15]; + prediction2 += coefficients[15] * (drflac_int64)pDecodedSamples[-14]; + prediction3 += coefficients[15] * (drflac_int64)pDecodedSamples[-13]; + case 15: + prediction0 += coefficients[14] * (drflac_int64)pDecodedSamples[-15]; + prediction1 += coefficients[14] * (drflac_int64)pDecodedSamples[-14]; + prediction2 += coefficients[14] * (drflac_int64)pDecodedSamples[-13]; + prediction3 += coefficients[14] * (drflac_int64)pDecodedSamples[-12]; + case 14: + prediction0 += coefficients[13] * (drflac_int64)pDecodedSamples[-14]; + prediction1 += coefficients[13] * (drflac_int64)pDecodedSamples[-13]; + prediction2 += coefficients[13] * (drflac_int64)pDecodedSamples[-12]; + prediction3 += coefficients[13] * (drflac_int64)pDecodedSamples[-11]; + case 13: + prediction0 += coefficients[12] * (drflac_int64)pDecodedSamples[-13]; + prediction1 += coefficients[12] * (drflac_int64)pDecodedSamples[-12]; + prediction2 += coefficients[12] * (drflac_int64)pDecodedSamples[-11]; + prediction3 += coefficients[12] * (drflac_int64)pDecodedSamples[-10]; + case 12: + prediction0 += coefficients[11] * (drflac_int64)pDecodedSamples[-12]; + prediction1 += coefficients[11] * (drflac_int64)pDecodedSamples[-11]; + prediction2 += coefficients[11] * (drflac_int64)pDecodedSamples[-10]; + prediction3 += coefficients[11] * (drflac_int64)pDecodedSamples[- 9]; + case 11: + prediction0 += coefficients[10] * (drflac_int64)pDecodedSamples[-11]; + prediction1 += coefficients[10] * (drflac_int64)pDecodedSamples[-10]; + prediction2 += coefficients[10] * (drflac_int64)pDecodedSamples[- 9]; + prediction3 += coefficients[10] * (drflac_int64)pDecodedSamples[- 8]; + case 10: + prediction0 += coefficients[9] * (drflac_int64)pDecodedSamples[-10]; + prediction1 += coefficients[9] * (drflac_int64)pDecodedSamples[- 9]; + prediction2 += coefficients[9] * (drflac_int64)pDecodedSamples[- 8]; + prediction3 += coefficients[9] * (drflac_int64)pDecodedSamples[- 7]; + case 9: + prediction0 += coefficients[8] * (drflac_int64)pDecodedSamples[- 9]; + prediction1 += coefficients[8] * (drflac_int64)pDecodedSamples[- 8]; + prediction2 += coefficients[8] * (drflac_int64)pDecodedSamples[- 7]; + prediction3 += coefficients[8] * (drflac_int64)pDecodedSamples[- 6]; + case 8: + prediction0 += coefficients[7] * (drflac_int64)pDecodedSamples[- 8]; + prediction1 += coefficients[7] * (drflac_int64)pDecodedSamples[- 7]; + prediction2 += coefficients[7] * (drflac_int64)pDecodedSamples[- 6]; + prediction3 += coefficients[7] * (drflac_int64)pDecodedSamples[- 5]; + case 7: + prediction0 += coefficients[6] * (drflac_int64)pDecodedSamples[- 7]; + prediction1 += coefficients[6] * (drflac_int64)pDecodedSamples[- 6]; + prediction2 += coefficients[6] * (drflac_int64)pDecodedSamples[- 5]; + prediction3 += coefficients[6] * (drflac_int64)pDecodedSamples[- 4]; + case 6: + prediction0 += coefficients[5] * (drflac_int64)pDecodedSamples[- 6]; + prediction1 += coefficients[5] * (drflac_int64)pDecodedSamples[- 5]; + prediction2 += coefficients[5] * (drflac_int64)pDecodedSamples[- 4]; + prediction3 += coefficients[5] * (drflac_int64)pDecodedSamples[- 3]; + case 5: + prediction0 += coefficients[4] * (drflac_int64)pDecodedSamples[- 5]; + prediction1 += coefficients[4] * (drflac_int64)pDecodedSamples[- 4]; + prediction2 += coefficients[4] * (drflac_int64)pDecodedSamples[- 3]; + prediction3 += coefficients[4] * (drflac_int64)pDecodedSamples[- 2]; + case 4: + prediction0 += coefficients[3] * (drflac_int64)pDecodedSamples[- 4]; + prediction1 += coefficients[3] * (drflac_int64)pDecodedSamples[- 3]; + prediction2 += coefficients[3] * (drflac_int64)pDecodedSamples[- 2]; + prediction3 += coefficients[3] * (drflac_int64)pDecodedSamples[- 1]; + order = 3; + } + + switch (order) + { + case 3: prediction0 += coefficients[ 2] * (drflac_int64)pDecodedSamples[- 3]; + case 2: prediction0 += coefficients[ 1] * (drflac_int64)pDecodedSamples[- 2]; + case 1: prediction0 += coefficients[ 0] * (drflac_int64)pDecodedSamples[- 1]; + } + pDecodedSamples[0] = riceParamParts[0] + (drflac_int32)(prediction0 >> shift); + + switch (order) + { + case 3: prediction1 += coefficients[ 2] * (drflac_int64)pDecodedSamples[- 2]; + case 2: prediction1 += coefficients[ 1] * (drflac_int64)pDecodedSamples[- 1]; + case 1: prediction1 += coefficients[ 0] * (drflac_int64)pDecodedSamples[ 0]; + } + pDecodedSamples[1] = riceParamParts[1] + (drflac_int32)(prediction1 >> shift); + + switch (order) + { + case 3: prediction2 += coefficients[ 2] * (drflac_int64)pDecodedSamples[- 1]; + case 2: prediction2 += coefficients[ 1] * (drflac_int64)pDecodedSamples[ 0]; + case 1: prediction2 += coefficients[ 0] * (drflac_int64)pDecodedSamples[ 1]; + } + pDecodedSamples[2] = riceParamParts[2] + (drflac_int32)(prediction2 >> shift); + + switch (order) + { + case 3: prediction3 += coefficients[ 2] * (drflac_int64)pDecodedSamples[ 0]; + case 2: prediction3 += coefficients[ 1] * (drflac_int64)pDecodedSamples[ 1]; + case 1: prediction3 += coefficients[ 0] * (drflac_int64)pDecodedSamples[ 2]; + } + pDecodedSamples[3] = riceParamParts[3] + (drflac_int32)(prediction3 >> shift); +} + +#if defined(DRFLAC_SUPPORT_SSE41) +static DRFLAC_INLINE drflac_int32 drflac__calculate_prediction_64__sse41(drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pDecodedSamples) +{ + __m128i prediction = _mm_setzero_si128(); + + drflac_assert(order <= 32); + + switch (order) + { + case 32: + case 31: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[31], 0, coefficients[30]), _mm_set_epi32(0, pDecodedSamples[-32], 0, pDecodedSamples[-31]))); + case 30: + case 29: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[29], 0, coefficients[28]), _mm_set_epi32(0, pDecodedSamples[-30], 0, pDecodedSamples[-29]))); + case 28: + case 27: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[27], 0, coefficients[26]), _mm_set_epi32(0, pDecodedSamples[-28], 0, pDecodedSamples[-27]))); + case 26: + case 25: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[25], 0, coefficients[24]), _mm_set_epi32(0, pDecodedSamples[-26], 0, pDecodedSamples[-25]))); + case 24: + case 23: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[23], 0, coefficients[22]), _mm_set_epi32(0, pDecodedSamples[-24], 0, pDecodedSamples[-23]))); + case 22: + case 21: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[21], 0, coefficients[20]), _mm_set_epi32(0, pDecodedSamples[-22], 0, pDecodedSamples[-21]))); + case 20: + case 19: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[19], 0, coefficients[18]), _mm_set_epi32(0, pDecodedSamples[-20], 0, pDecodedSamples[-19]))); + case 18: + case 17: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[17], 0, coefficients[16]), _mm_set_epi32(0, pDecodedSamples[-18], 0, pDecodedSamples[-17]))); + case 16: + case 15: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[15], 0, coefficients[14]), _mm_set_epi32(0, pDecodedSamples[-16], 0, pDecodedSamples[-15]))); + case 14: + case 13: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[13], 0, coefficients[12]), _mm_set_epi32(0, pDecodedSamples[-14], 0, pDecodedSamples[-13]))); + case 12: + case 11: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[11], 0, coefficients[10]), _mm_set_epi32(0, pDecodedSamples[-12], 0, pDecodedSamples[-11]))); + case 10: + case 9: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[ 9], 0, coefficients[ 8]), _mm_set_epi32(0, pDecodedSamples[-10], 0, pDecodedSamples[- 9]))); + case 8: + case 7: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[ 7], 0, coefficients[ 6]), _mm_set_epi32(0, pDecodedSamples[- 8], 0, pDecodedSamples[- 7]))); + case 6: + case 5: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[ 5], 0, coefficients[ 4]), _mm_set_epi32(0, pDecodedSamples[- 6], 0, pDecodedSamples[- 5]))); + case 4: + case 3: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[ 3], 0, coefficients[ 2]), _mm_set_epi32(0, pDecodedSamples[- 4], 0, pDecodedSamples[- 3]))); + case 2: + case 1: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[ 1], 0, coefficients[ 0]), _mm_set_epi32(0, pDecodedSamples[- 2], 0, pDecodedSamples[- 1]))); + } + + return (drflac_int32)(( + ((drflac_uint64*)&prediction)[0] + + ((drflac_uint64*)&prediction)[1]) >> shift); +} + +static DRFLAC_INLINE void drflac__calculate_prediction_64_x2__sse41(drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, const drflac_uint32 riceParamParts[4], drflac_int32* pDecodedSamples) +{ + __m128i prediction = _mm_setzero_si128(); + drflac_int64 predictions[2] = {0, 0}; + + drflac_assert(order <= 32); + + switch (order) + { + case 32: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[31], 0, coefficients[31]), _mm_set_epi32(0, pDecodedSamples[-31], 0, pDecodedSamples[-32]))); + case 31: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[30], 0, coefficients[30]), _mm_set_epi32(0, pDecodedSamples[-30], 0, pDecodedSamples[-31]))); + case 30: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[29], 0, coefficients[29]), _mm_set_epi32(0, pDecodedSamples[-29], 0, pDecodedSamples[-30]))); + case 29: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[28], 0, coefficients[28]), _mm_set_epi32(0, pDecodedSamples[-28], 0, pDecodedSamples[-29]))); + case 28: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[27], 0, coefficients[27]), _mm_set_epi32(0, pDecodedSamples[-27], 0, pDecodedSamples[-28]))); + case 27: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[26], 0, coefficients[26]), _mm_set_epi32(0, pDecodedSamples[-26], 0, pDecodedSamples[-27]))); + case 26: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[25], 0, coefficients[25]), _mm_set_epi32(0, pDecodedSamples[-25], 0, pDecodedSamples[-26]))); + case 25: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[24], 0, coefficients[24]), _mm_set_epi32(0, pDecodedSamples[-24], 0, pDecodedSamples[-25]))); + case 24: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[23], 0, coefficients[23]), _mm_set_epi32(0, pDecodedSamples[-23], 0, pDecodedSamples[-24]))); + case 23: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[22], 0, coefficients[22]), _mm_set_epi32(0, pDecodedSamples[-22], 0, pDecodedSamples[-23]))); + case 22: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[21], 0, coefficients[21]), _mm_set_epi32(0, pDecodedSamples[-21], 0, pDecodedSamples[-22]))); + case 21: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[20], 0, coefficients[20]), _mm_set_epi32(0, pDecodedSamples[-20], 0, pDecodedSamples[-21]))); + case 20: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[19], 0, coefficients[19]), _mm_set_epi32(0, pDecodedSamples[-19], 0, pDecodedSamples[-20]))); + case 19: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[18], 0, coefficients[18]), _mm_set_epi32(0, pDecodedSamples[-18], 0, pDecodedSamples[-19]))); + case 18: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[17], 0, coefficients[17]), _mm_set_epi32(0, pDecodedSamples[-17], 0, pDecodedSamples[-18]))); + case 17: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[16], 0, coefficients[16]), _mm_set_epi32(0, pDecodedSamples[-16], 0, pDecodedSamples[-17]))); + case 16: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[15], 0, coefficients[15]), _mm_set_epi32(0, pDecodedSamples[-15], 0, pDecodedSamples[-16]))); + case 15: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[14], 0, coefficients[14]), _mm_set_epi32(0, pDecodedSamples[-14], 0, pDecodedSamples[-15]))); + case 14: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[13], 0, coefficients[13]), _mm_set_epi32(0, pDecodedSamples[-13], 0, pDecodedSamples[-14]))); + case 13: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[12], 0, coefficients[12]), _mm_set_epi32(0, pDecodedSamples[-12], 0, pDecodedSamples[-13]))); + case 12: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[11], 0, coefficients[11]), _mm_set_epi32(0, pDecodedSamples[-11], 0, pDecodedSamples[-12]))); + case 11: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[10], 0, coefficients[10]), _mm_set_epi32(0, pDecodedSamples[-10], 0, pDecodedSamples[-11]))); + case 10: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[ 9], 0, coefficients[ 9]), _mm_set_epi32(0, pDecodedSamples[- 9], 0, pDecodedSamples[-10]))); + case 9: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[ 8], 0, coefficients[ 8]), _mm_set_epi32(0, pDecodedSamples[- 8], 0, pDecodedSamples[- 9]))); + case 8: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[ 7], 0, coefficients[ 7]), _mm_set_epi32(0, pDecodedSamples[- 7], 0, pDecodedSamples[- 8]))); + case 7: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[ 6], 0, coefficients[ 6]), _mm_set_epi32(0, pDecodedSamples[- 6], 0, pDecodedSamples[- 7]))); + case 6: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[ 5], 0, coefficients[ 5]), _mm_set_epi32(0, pDecodedSamples[- 5], 0, pDecodedSamples[- 6]))); + case 5: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[ 4], 0, coefficients[ 4]), _mm_set_epi32(0, pDecodedSamples[- 4], 0, pDecodedSamples[- 5]))); + case 4: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[ 3], 0, coefficients[ 3]), _mm_set_epi32(0, pDecodedSamples[- 3], 0, pDecodedSamples[- 4]))); + case 3: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[ 2], 0, coefficients[ 2]), _mm_set_epi32(0, pDecodedSamples[- 2], 0, pDecodedSamples[- 3]))); + case 2: prediction = _mm_add_epi64(prediction, _mm_mul_epi32(_mm_set_epi32(0, coefficients[ 1], 0, coefficients[ 1]), _mm_set_epi32(0, pDecodedSamples[- 1], 0, pDecodedSamples[- 2]))); + order = 1; + } + + _mm_storeu_si128((__m128i*)predictions, prediction); + + switch (order) + { + case 1: predictions[0] += coefficients[ 0] * (drflac_int64)pDecodedSamples[- 1]; + } + pDecodedSamples[0] = riceParamParts[0] + (drflac_int32)(predictions[0] >> shift); + + switch (order) + { + case 1: predictions[1] += coefficients[ 0] * (drflac_int64)pDecodedSamples[ 0]; + } + pDecodedSamples[1] = riceParamParts[1] + (drflac_int32)(predictions[1] >> shift); +} + + +static DRFLAC_INLINE __m128i drflac__mm_not_si128(__m128i a) +{ + return _mm_xor_si128(a, _mm_cmpeq_epi32(_mm_setzero_si128(), _mm_setzero_si128())); +} + +static DRFLAC_INLINE __m128i drflac__mm_slide1_epi32(__m128i a, __m128i b) +{ + /* a3a2a1a0/b3b2b1b0 -> a2a1a0b3 */ + + /* Result = a2a1a0b3 */ + __m128i b3a3b2a2 = _mm_unpackhi_epi32(a, b); + __m128i a2b3a2b3 = _mm_shuffle_epi32(b3a3b2a2, _MM_SHUFFLE(0, 3, 0, 3)); + __m128i a1a2a0b3 = _mm_unpacklo_epi32(a2b3a2b3, a); + __m128i a2a1a0b3 = _mm_shuffle_epi32(a1a2a0b3, _MM_SHUFFLE(2, 3, 1, 0)); + return a2a1a0b3; +} + +static DRFLAC_INLINE __m128i drflac__mm_slide2_epi32(__m128i a, __m128i b) +{ + /* Result = a1a0b3b2 */ + __m128i b1b0b3b2 = _mm_shuffle_epi32(b, _MM_SHUFFLE(1, 0, 3, 2)); + __m128i a1b3a0b2 = _mm_unpacklo_epi32(b1b0b3b2, a); + __m128i a1a0b3b2 = _mm_shuffle_epi32(a1b3a0b2, _MM_SHUFFLE(3, 1, 2, 0)); + return a1a0b3b2; +} + +static DRFLAC_INLINE __m128i drflac__mm_slide3_epi32(__m128i a, __m128i b) +{ + /* Result = a0b3b2b1 */ + __m128i b1a1b0a0 = _mm_unpacklo_epi32(a, b); + __m128i a0b1a0b1 = _mm_shuffle_epi32(b1a1b0a0, _MM_SHUFFLE(0, 3, 0, 3)); + __m128i b3a0b2b1 = _mm_unpackhi_epi32(a0b1a0b1, b); + __m128i a0b3b2b1 = _mm_shuffle_epi32(b3a0b2b1, _MM_SHUFFLE(2, 3, 1, 0)); + return a0b3b2b1; +} + +static DRFLAC_INLINE void drflac__calculate_prediction_32_x4__sse41(drflac_uint32 order, drflac_int32 shift, const __m128i* coefficients128, const __m128i riceParamParts128, drflac_int32* pDecodedSamples) +{ + drflac_assert(order <= 32); + + /* I don't think this is as efficient as it could be. More work needs to be done on this. */ + if (order > 0) { + drflac_int32 predictions[4]; + drflac_uint32 riceParamParts[4]; + + __m128i s_09_10_11_12 = _mm_loadu_si128((const __m128i*)(pDecodedSamples - 12)); + __m128i s_05_06_07_08 = _mm_loadu_si128((const __m128i*)(pDecodedSamples - 8)); + __m128i s_01_02_03_04 = _mm_loadu_si128((const __m128i*)(pDecodedSamples - 4)); + + __m128i prediction = _mm_setzero_si128(); + + /* + The idea with this switch is to do do a single jump based on the value of "order". In my test library, "order" is never larger than 12, so + I have decided to do a less optimal, but simpler solution in the order > 12 case. + */ + switch (order) + { + case 32: prediction = _mm_add_epi32(prediction, _mm_mullo_epi32(coefficients128[31], _mm_loadu_si128((const __m128i*)(pDecodedSamples - 32)))); + case 31: prediction = _mm_add_epi32(prediction, _mm_mullo_epi32(coefficients128[30], _mm_loadu_si128((const __m128i*)(pDecodedSamples - 31)))); + case 30: prediction = _mm_add_epi32(prediction, _mm_mullo_epi32(coefficients128[29], _mm_loadu_si128((const __m128i*)(pDecodedSamples - 30)))); + case 29: prediction = _mm_add_epi32(prediction, _mm_mullo_epi32(coefficients128[28], _mm_loadu_si128((const __m128i*)(pDecodedSamples - 29)))); + case 28: prediction = _mm_add_epi32(prediction, _mm_mullo_epi32(coefficients128[27], _mm_loadu_si128((const __m128i*)(pDecodedSamples - 28)))); + case 27: prediction = _mm_add_epi32(prediction, _mm_mullo_epi32(coefficients128[26], _mm_loadu_si128((const __m128i*)(pDecodedSamples - 27)))); + case 26: prediction = _mm_add_epi32(prediction, _mm_mullo_epi32(coefficients128[25], _mm_loadu_si128((const __m128i*)(pDecodedSamples - 26)))); + case 25: prediction = _mm_add_epi32(prediction, _mm_mullo_epi32(coefficients128[24], _mm_loadu_si128((const __m128i*)(pDecodedSamples - 25)))); + case 24: prediction = _mm_add_epi32(prediction, _mm_mullo_epi32(coefficients128[23], _mm_loadu_si128((const __m128i*)(pDecodedSamples - 24)))); + case 23: prediction = _mm_add_epi32(prediction, _mm_mullo_epi32(coefficients128[22], _mm_loadu_si128((const __m128i*)(pDecodedSamples - 23)))); + case 22: prediction = _mm_add_epi32(prediction, _mm_mullo_epi32(coefficients128[21], _mm_loadu_si128((const __m128i*)(pDecodedSamples - 22)))); + case 21: prediction = _mm_add_epi32(prediction, _mm_mullo_epi32(coefficients128[20], _mm_loadu_si128((const __m128i*)(pDecodedSamples - 21)))); + case 20: prediction = _mm_add_epi32(prediction, _mm_mullo_epi32(coefficients128[19], _mm_loadu_si128((const __m128i*)(pDecodedSamples - 20)))); + case 19: prediction = _mm_add_epi32(prediction, _mm_mullo_epi32(coefficients128[18], _mm_loadu_si128((const __m128i*)(pDecodedSamples - 19)))); + case 18: prediction = _mm_add_epi32(prediction, _mm_mullo_epi32(coefficients128[17], _mm_loadu_si128((const __m128i*)(pDecodedSamples - 18)))); + case 17: prediction = _mm_add_epi32(prediction, _mm_mullo_epi32(coefficients128[16], _mm_loadu_si128((const __m128i*)(pDecodedSamples - 17)))); + case 16: prediction = _mm_add_epi32(prediction, _mm_mullo_epi32(coefficients128[15], _mm_loadu_si128((const __m128i*)(pDecodedSamples - 16)))); + case 15: prediction = _mm_add_epi32(prediction, _mm_mullo_epi32(coefficients128[14], _mm_loadu_si128((const __m128i*)(pDecodedSamples - 15)))); + case 14: prediction = _mm_add_epi32(prediction, _mm_mullo_epi32(coefficients128[13], _mm_loadu_si128((const __m128i*)(pDecodedSamples - 14)))); + case 13: prediction = _mm_add_epi32(prediction, _mm_mullo_epi32(coefficients128[12], _mm_loadu_si128((const __m128i*)(pDecodedSamples - 13)))); + + case 12: prediction = _mm_add_epi32(prediction, _mm_mullo_epi32(coefficients128[11], s_09_10_11_12)); + case 11: prediction = _mm_add_epi32(prediction, _mm_mullo_epi32(coefficients128[10], drflac__mm_slide3_epi32(s_05_06_07_08, s_09_10_11_12))); + case 10: prediction = _mm_add_epi32(prediction, _mm_mullo_epi32(coefficients128[ 9], drflac__mm_slide2_epi32(s_05_06_07_08, s_09_10_11_12))); + case 9: prediction = _mm_add_epi32(prediction, _mm_mullo_epi32(coefficients128[ 8], drflac__mm_slide1_epi32(s_05_06_07_08, s_09_10_11_12))); + case 8: prediction = _mm_add_epi32(prediction, _mm_mullo_epi32(coefficients128[ 7], s_05_06_07_08)); + case 7: prediction = _mm_add_epi32(prediction, _mm_mullo_epi32(coefficients128[ 6], drflac__mm_slide3_epi32(s_01_02_03_04, s_05_06_07_08))); + case 6: prediction = _mm_add_epi32(prediction, _mm_mullo_epi32(coefficients128[ 5], drflac__mm_slide2_epi32(s_01_02_03_04, s_05_06_07_08))); + case 5: prediction = _mm_add_epi32(prediction, _mm_mullo_epi32(coefficients128[ 4], drflac__mm_slide1_epi32(s_01_02_03_04, s_05_06_07_08))); + case 4: prediction = _mm_add_epi32(prediction, _mm_mullo_epi32(coefficients128[ 3], s_01_02_03_04)); order = 3; /* <-- Don't forget to set order to 3 here! */ + case 3: prediction = _mm_add_epi32(prediction, _mm_mullo_epi32(coefficients128[ 2], drflac__mm_slide3_epi32(_mm_setzero_si128(), s_01_02_03_04))); + case 2: prediction = _mm_add_epi32(prediction, _mm_mullo_epi32(coefficients128[ 1], drflac__mm_slide2_epi32(_mm_setzero_si128(), s_01_02_03_04))); + case 1: prediction = _mm_add_epi32(prediction, _mm_mullo_epi32(coefficients128[ 0], drflac__mm_slide1_epi32(_mm_setzero_si128(), s_01_02_03_04))); + } + + _mm_storeu_si128((__m128i*)predictions, prediction); + _mm_storeu_si128((__m128i*)riceParamParts, riceParamParts128); + + predictions[0] = riceParamParts[0] + (predictions[0] >> shift); + + switch (order) + { + case 3: predictions[3] += ((const drflac_int32*)&coefficients128[ 2])[0] * predictions[ 0]; + case 2: predictions[2] += ((const drflac_int32*)&coefficients128[ 1])[0] * predictions[ 0]; + case 1: predictions[1] += ((const drflac_int32*)&coefficients128[ 0])[0] * predictions[ 0]; + } + predictions[1] = riceParamParts[1] + (predictions[1] >> shift); + + switch (order) + { + case 3: + case 2: predictions[3] += ((const drflac_int32*)&coefficients128[ 1])[0] * predictions[ 1]; + case 1: predictions[2] += ((const drflac_int32*)&coefficients128[ 0])[0] * predictions[ 1]; + } + predictions[2] = riceParamParts[2] + (predictions[2] >> shift); + + switch (order) + { + case 3: + case 2: + case 1: predictions[3] += ((const drflac_int32*)&coefficients128[ 0])[0] * predictions[ 2]; + } + predictions[3] = riceParamParts[3] + (predictions[3] >> shift); + + pDecodedSamples[0] = predictions[0]; + pDecodedSamples[1] = predictions[1]; + pDecodedSamples[2] = predictions[2]; + pDecodedSamples[3] = predictions[3]; + } else { + _mm_storeu_si128((__m128i*)pDecodedSamples, riceParamParts128); + } +} +#endif + #if 0 -// Reference implementation for reading and decoding samples with residual. This is intentionally left unoptimized for the -// sake of readability and should only be used as a reference. +/* +Reference implementation for reading and decoding samples with residual. This is intentionally left unoptimized for the +sake of readability and should only be used as a reference. +*/ static drflac_bool32 drflac__decode_samples_with_residual__rice__reference(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pSamplesOut) { + drflac_uint32 i; + drflac_assert(bs != NULL); drflac_assert(count > 0); drflac_assert(pSamplesOut != NULL); - for (drflac_uint32 i = 0; i < count; ++i) { + for (i = 0; i < count; ++i) { drflac_uint32 zeroCounter = 0; for (;;) { drflac_uint8 bit; @@ -2193,6 +2955,8 @@ static drflac_bool32 drflac__decode_samples_with_residual__rice__reference(drfla static drflac_bool32 drflac__read_rice_parts__reference(drflac_bs* bs, drflac_uint8 riceParam, drflac_uint32* pZeroCounterOut, drflac_uint32* pRiceParamPartOut) { drflac_uint32 zeroCounter = 0; + drflac_uint32 decodedRice; + for (;;) { drflac_uint8 bit; if (!drflac__read_uint8(bs, 1, &bit)) { @@ -2206,7 +2970,6 @@ static drflac_bool32 drflac__read_rice_parts__reference(drflac_bs* bs, drflac_ui } } - drflac_uint32 decodedRice; if (riceParam > 0) { if (!drflac__read_uint32(bs, riceParam, &decodedRice)) { return DRFLAC_FALSE; @@ -2221,13 +2984,20 @@ static drflac_bool32 drflac__read_rice_parts__reference(drflac_bs* bs, drflac_ui } #endif +#if 0 static DRFLAC_INLINE drflac_bool32 drflac__read_rice_parts(drflac_bs* bs, drflac_uint8 riceParam, drflac_uint32* pZeroCounterOut, drflac_uint32* pRiceParamPartOut) { - drflac_cache_t riceParamMask = DRFLAC_CACHE_L1_SELECTION_MASK(riceParam); - drflac_cache_t resultHiShift = DRFLAC_CACHE_L1_SIZE_BITS(bs) - riceParam; + drflac_cache_t riceParamMask; + drflac_uint32 zeroCounter; + drflac_uint32 setBitOffsetPlus1; + drflac_uint32 riceParamPart; + drflac_uint32 riceLength; + drflac_assert(riceParam > 0); /* <-- riceParam should never be 0. drflac__read_rice_parts__param_equals_zero() should be used instead for this case. */ - drflac_uint32 zeroCounter = 0; + riceParamMask = DRFLAC_CACHE_L1_SELECTION_MASK(riceParam); + + zeroCounter = 0; while (bs->cache == 0) { zeroCounter += (drflac_uint32)DRFLAC_CACHE_L1_BITS_REMAINING(bs); if (!drflac__reload_cache(bs)) { @@ -2235,172 +3005,725 @@ static DRFLAC_INLINE drflac_bool32 drflac__read_rice_parts(drflac_bs* bs, drflac } } - drflac_uint32 setBitOffsetPlus1 = drflac__clz(bs->cache); + setBitOffsetPlus1 = drflac__clz(bs->cache); zeroCounter += setBitOffsetPlus1; setBitOffsetPlus1 += 1; - - drflac_uint32 riceParamPart; - drflac_uint32 riceLength = setBitOffsetPlus1 + riceParam; + riceLength = setBitOffsetPlus1 + riceParam; if (riceLength < DRFLAC_CACHE_L1_BITS_REMAINING(bs)) { - riceParamPart = (drflac_uint32)((bs->cache & (riceParamMask >> setBitOffsetPlus1)) >> (DRFLAC_CACHE_L1_SIZE_BITS(bs) - riceLength)); + riceParamPart = (drflac_uint32)((bs->cache & (riceParamMask >> setBitOffsetPlus1)) >> DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, riceLength)); bs->consumedBits += riceLength; bs->cache <<= riceLength; } else { + drflac_uint32 bitCountLo; + drflac_cache_t resultHi; + bs->consumedBits += riceLength; - if (setBitOffsetPlus1 < DRFLAC_CACHE_L1_SIZE_BITS(bs)) { - bs->cache <<= setBitOffsetPlus1; - } + bs->cache <<= setBitOffsetPlus1 & (DRFLAC_CACHE_L1_SIZE_BITS(bs)-1); /* <-- Equivalent to "if (setBitOffsetPlus1 < DRFLAC_CACHE_L1_SIZE_BITS(bs)) { bs->cache <<= setBitOffsetPlus1; }" */ - // It straddles the cached data. It will never cover more than the next chunk. We just read the number in two parts and combine them. - drflac_uint32 bitCountLo = bs->consumedBits - DRFLAC_CACHE_L1_SIZE_BITS(bs); - drflac_cache_t resultHi = bs->cache & riceParamMask; // <-- This mask is OK because all bits after the first bits are always zero. + /* It straddles the cached data. It will never cover more than the next chunk. We just read the number in two parts and combine them. */ + bitCountLo = bs->consumedBits - DRFLAC_CACHE_L1_SIZE_BITS(bs); + resultHi = DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, riceParam); /* <-- Use DRFLAC_CACHE_L1_SELECT_AND_SHIFT_SAFE() if ever this function allows riceParam=0. */ if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) { - #ifndef DR_FLAC_NO_CRC +#ifndef DR_FLAC_NO_CRC drflac__update_crc16(bs); - #endif +#endif bs->cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]); bs->consumedBits = 0; - #ifndef DR_FLAC_NO_CRC +#ifndef DR_FLAC_NO_CRC bs->crc16Cache = bs->cache; - #endif +#endif } else { - // Slow path. We need to fetch more data from the client. + /* Slow path. We need to fetch more data from the client. */ if (!drflac__reload_cache(bs)) { return DRFLAC_FALSE; } } - riceParamPart = (drflac_uint32)((resultHi >> resultHiShift) | DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCountLo)); + riceParamPart = (drflac_uint32)(resultHi | DRFLAC_CACHE_L1_SELECT_AND_SHIFT_SAFE(bs, bitCountLo)); bs->consumedBits += bitCountLo; bs->cache <<= bitCountLo; } - *pZeroCounterOut = zeroCounter; - *pRiceParamPartOut = riceParamPart; + pZeroCounterOut[0] = zeroCounter; + pRiceParamPartOut[0] = riceParamPart; + return DRFLAC_TRUE; } +#endif +static DRFLAC_INLINE drflac_bool32 drflac__read_rice_parts_x1(drflac_bs* bs, drflac_uint8 riceParam, drflac_uint32* pZeroCounterOut, drflac_uint32* pRiceParamPartOut) +{ + drflac_uint32 riceParamPlus1 = riceParam + 1; + /*drflac_cache_t riceParamPlus1Mask = DRFLAC_CACHE_L1_SELECTION_MASK(riceParamPlus1);*/ + drflac_uint32 riceParamPlus1Shift = DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, riceParamPlus1); + drflac_uint32 riceParamPlus1MaxConsumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs) - riceParamPlus1; + + /* + The idea here is to use local variables for the cache in an attempt to encourage the compiler to store them in registers. I have + no idea how this will work in practice... + */ + drflac_cache_t bs_cache = bs->cache; + drflac_uint32 bs_consumedBits = bs->consumedBits; + + /* The first thing to do is find the first unset bit. Most likely a bit will be set in the current cache line. */ + drflac_uint32 lzcount = drflac__clz(bs_cache); + if (lzcount < sizeof(bs_cache)*8) { + pZeroCounterOut[0] = lzcount; + + /* + It is most likely that the riceParam part (which comes after the zero counter) is also on this cache line. When extracting + this, we include the set bit from the unary coded part because it simplifies cache management. This bit will be handled + outside of this function at a higher level. + */ + extract_rice_param_part: + bs_cache <<= lzcount; + bs_consumedBits += lzcount; + + if (bs_consumedBits <= riceParamPlus1MaxConsumedBits) { + /* Getting here means the rice parameter part is wholly contained within the current cache line. */ + pRiceParamPartOut[0] = (drflac_uint32)(bs_cache >> riceParamPlus1Shift); + bs_cache <<= riceParamPlus1; + bs_consumedBits += riceParamPlus1; + } else { + drflac_uint32 riceParamPartHi; + drflac_uint32 riceParamPartLo; + drflac_uint32 riceParamPartLoBitCount; + + /* + Getting here means the rice parameter part straddles the cache line. We need to read from the tail of the current cache + line, reload the cache, and then combine it with the head of the next cache line. + */ + + /* Grab the high part of the rice parameter part. */ + riceParamPartHi = (drflac_uint32)(bs_cache >> riceParamPlus1Shift); + + /* Before reloading the cache we need to grab the size in bits of the low part. */ + riceParamPartLoBitCount = bs_consumedBits - riceParamPlus1MaxConsumedBits; + drflac_assert(riceParamPartLoBitCount > 0 && riceParamPartLoBitCount < 32); + + /* Now reload the cache. */ + if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) { + #ifndef DR_FLAC_NO_CRC + drflac__update_crc16(bs); + #endif + bs_cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]); + bs_consumedBits = riceParamPartLoBitCount; + #ifndef DR_FLAC_NO_CRC + bs->crc16Cache = bs_cache; + #endif + } else { + /* Slow path. We need to fetch more data from the client. */ + if (!drflac__reload_cache(bs)) { + return DRFLAC_FALSE; + } -static drflac_bool32 drflac__decode_samples_with_residual__rice__simple(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pSamplesOut) -{ - drflac_assert(bs != NULL); - drflac_assert(count > 0); - drflac_assert(pSamplesOut != NULL); + bs_cache = bs->cache; + bs_consumedBits = bs->consumedBits + riceParamPartLoBitCount; + } - static drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF}; + /* We should now have enough information to construct the rice parameter part. */ + riceParamPartLo = (drflac_uint32)(bs_cache >> (DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, riceParamPartLoBitCount))); + pRiceParamPartOut[0] = riceParamPartHi | riceParamPartLo; - drflac_uint32 zeroCountPart0; - drflac_uint32 zeroCountPart1; - drflac_uint32 zeroCountPart2; - drflac_uint32 zeroCountPart3; - drflac_uint32 riceParamPart0; - drflac_uint32 riceParamPart1; - drflac_uint32 riceParamPart2; - drflac_uint32 riceParamPart3; - drflac_uint32 i4 = 0; - drflac_uint32 count4 = count >> 2; - while (i4 < count4) { - // Rice extraction. - if (!drflac__read_rice_parts(bs, riceParam, &zeroCountPart0, &riceParamPart0) || - !drflac__read_rice_parts(bs, riceParam, &zeroCountPart1, &riceParamPart1) || - !drflac__read_rice_parts(bs, riceParam, &zeroCountPart2, &riceParamPart2) || - !drflac__read_rice_parts(bs, riceParam, &zeroCountPart3, &riceParamPart3)) { - return DRFLAC_FALSE; + bs_cache <<= riceParamPartLoBitCount; } + } else { + /* + Getting here means there are no bits set on the cache line. This is a less optimal case because we just wasted a call + to drflac__clz() and we need to reload the cache. + */ + drflac_uint32 zeroCounter = (drflac_uint32)(DRFLAC_CACHE_L1_SIZE_BITS(bs) - bs_consumedBits); + for (;;) { + if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) { + #ifndef DR_FLAC_NO_CRC + drflac__update_crc16(bs); + #endif + bs_cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]); + bs_consumedBits = 0; + #ifndef DR_FLAC_NO_CRC + bs->crc16Cache = bs_cache; + #endif + } else { + /* Slow path. We need to fetch more data from the client. */ + if (!drflac__reload_cache(bs)) { + return DRFLAC_FALSE; + } - riceParamPart0 |= (zeroCountPart0 << riceParam); - riceParamPart1 |= (zeroCountPart1 << riceParam); - riceParamPart2 |= (zeroCountPart2 << riceParam); - riceParamPart3 |= (zeroCountPart3 << riceParam); + bs_cache = bs->cache; + bs_consumedBits = bs->consumedBits; + } - riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01]; - riceParamPart1 = (riceParamPart1 >> 1) ^ t[riceParamPart1 & 0x01]; - riceParamPart2 = (riceParamPart2 >> 1) ^ t[riceParamPart2 & 0x01]; - riceParamPart3 = (riceParamPart3 >> 1) ^ t[riceParamPart3 & 0x01]; + lzcount = drflac__clz(bs_cache); + zeroCounter += lzcount; - if (bitsPerSample > 16) { - pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_64(order, shift, coefficients, pSamplesOut + 0); - pSamplesOut[1] = riceParamPart1 + drflac__calculate_prediction_64(order, shift, coefficients, pSamplesOut + 1); - pSamplesOut[2] = riceParamPart2 + drflac__calculate_prediction_64(order, shift, coefficients, pSamplesOut + 2); - pSamplesOut[3] = riceParamPart3 + drflac__calculate_prediction_64(order, shift, coefficients, pSamplesOut + 3); - } else { - pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_32(order, shift, coefficients, pSamplesOut + 0); - pSamplesOut[1] = riceParamPart1 + drflac__calculate_prediction_32(order, shift, coefficients, pSamplesOut + 1); - pSamplesOut[2] = riceParamPart2 + drflac__calculate_prediction_32(order, shift, coefficients, pSamplesOut + 2); - pSamplesOut[3] = riceParamPart3 + drflac__calculate_prediction_32(order, shift, coefficients, pSamplesOut + 3); + if (lzcount < sizeof(bs_cache)*8) { + break; + } } - i4 += 1; - pSamplesOut += 4; + pZeroCounterOut[0] = zeroCounter; + goto extract_rice_param_part; } - drflac_uint32 i = i4 << 2; - while (i < count) { - // Rice extraction. - if (!drflac__read_rice_parts(bs, riceParam, &zeroCountPart0, &riceParamPart0)) { - return DRFLAC_FALSE; - } + /* Make sure the cache is restored at the end of it all. */ + bs->cache = bs_cache; + bs->consumedBits = bs_consumedBits; - // Rice reconstruction. - riceParamPart0 |= (zeroCountPart0 << riceParam); - riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01]; - //riceParamPart0 = (riceParamPart0 >> 1) ^ (~(riceParamPart0 & 0x01) + 1); + return DRFLAC_TRUE; +} - // Sample reconstruction. - if (bitsPerSample > 16) { - pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_64(order, shift, coefficients, pSamplesOut + 0); - } else { - pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_32(order, shift, coefficients, pSamplesOut + 0); - } +static DRFLAC_INLINE drflac_bool32 drflac__read_rice_parts_x4(drflac_bs* bs, drflac_uint8 riceParam, drflac_uint32* pZeroCounterOut, drflac_uint32* pRiceParamPartOut) +{ + drflac_uint32 riceParamPlus1 = riceParam + 1; + /*drflac_cache_t riceParamPlus1Mask = DRFLAC_CACHE_L1_SELECTION_MASK(riceParamPlus1);*/ + drflac_uint32 riceParamPlus1Shift = DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, riceParamPlus1); + drflac_uint32 riceParamPlus1MaxConsumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs) - riceParamPlus1; + + /* + The idea here is to use local variables for the cache in an attempt to encourage the compiler to store them in registers. I have + no idea how this will work in practice... + */ + drflac_cache_t bs_cache = bs->cache; + drflac_uint32 bs_consumedBits = bs->consumedBits; + + /* + What this is doing is trying to efficiently extract 4 rice parts at a time, the idea being that we can exploit certain properties + to our advantage to make things more efficient. + */ + int i; + for (i = 0; i < 4; ++i) { + /* The first thing to do is find the first unset bit. Most likely a bit will be set in the current cache line. */ + drflac_uint32 lzcount = drflac__clz(bs_cache); + if (lzcount < sizeof(bs_cache)*8) { + pZeroCounterOut[i] = lzcount; + + /* + It is most likely that the riceParam part (which comes after the zero counter) is also on this cache line. When extracting + this, we include the set bit from the unary coded part because it simplifies cache management. This bit will be handled + outside of this function at a higher level. + */ + extract_rice_param_part: + bs_cache <<= lzcount; + bs_consumedBits += lzcount; + + if (bs_consumedBits <= riceParamPlus1MaxConsumedBits) { + /* Getting here means the rice parameter part is wholly contained within the current cache line. */ + pRiceParamPartOut[i] = (drflac_uint32)(bs_cache >> riceParamPlus1Shift); + bs_cache <<= riceParamPlus1; + bs_consumedBits += riceParamPlus1; + } else { + drflac_uint32 riceParamPartHi; + drflac_uint32 riceParamPartLo; + drflac_uint32 riceParamPartLoBitCount; + + /* + Getting here means the rice parameter part straddles the cache line. We need to read from the tail of the current cache + line, reload the cache, and then combine it with the head of the next cache line. + */ + + /* Grab the high part of the rice parameter part. */ + riceParamPartHi = (drflac_uint32)(bs_cache >> riceParamPlus1Shift); + + /* Before reloading the cache we need to grab the size in bits of the low part. */ + riceParamPartLoBitCount = bs_consumedBits - riceParamPlus1MaxConsumedBits; + + /* Now reload the cache. */ + if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) { + #ifndef DR_FLAC_NO_CRC + drflac__update_crc16(bs); + #endif + bs_cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]); + bs_consumedBits = riceParamPartLoBitCount; + #ifndef DR_FLAC_NO_CRC + bs->crc16Cache = bs_cache; + #endif + } else { + /* Slow path. We need to fetch more data from the client. */ + if (!drflac__reload_cache(bs)) { + return DRFLAC_FALSE; + } - i += 1; - pSamplesOut += 1; - } + bs_cache = bs->cache; + bs_consumedBits = bs->consumedBits + riceParamPartLoBitCount; + } - return DRFLAC_TRUE; -} + /* We should now have enough information to construct the rice parameter part. */ + riceParamPartLo = (drflac_uint32)(bs_cache >> (DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, riceParamPartLoBitCount))); + pRiceParamPartOut[i] = riceParamPartHi | riceParamPartLo; -static drflac_bool32 drflac__decode_samples_with_residual__rice(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pSamplesOut) -{ -#if 0 - return drflac__decode_samples_with_residual__rice__reference(bs, bitsPerSample, count, riceParam, order, shift, coefficients, pSamplesOut); -#else - return drflac__decode_samples_with_residual__rice__simple(bs, bitsPerSample, count, riceParam, order, shift, coefficients, pSamplesOut); -#endif -} + bs_cache <<= riceParamPartLoBitCount; + } + } else { + /* + Getting here means there are no bits set on the cache line. This is a less optimal case because we just wasted a call + to drflac__clz() and we need to reload the cache. + */ + drflac_uint32 zeroCounter = (drflac_uint32)(DRFLAC_CACHE_L1_SIZE_BITS(bs) - bs_consumedBits); + for (;;) { + if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) { + #ifndef DR_FLAC_NO_CRC + drflac__update_crc16(bs); + #endif + bs_cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]); + bs_consumedBits = 0; + #ifndef DR_FLAC_NO_CRC + bs->crc16Cache = bs_cache; + #endif + } else { + /* Slow path. We need to fetch more data from the client. */ + if (!drflac__reload_cache(bs)) { + return DRFLAC_FALSE; + } -// Reads and seeks past a string of residual values as Rice codes. The decoder should be sitting on the first bit of the Rice codes. -static drflac_bool32 drflac__read_and_seek_residual__rice(drflac_bs* bs, drflac_uint32 count, drflac_uint8 riceParam) -{ - drflac_assert(bs != NULL); - drflac_assert(count > 0); + bs_cache = bs->cache; + bs_consumedBits = bs->consumedBits; + } - for (drflac_uint32 i = 0; i < count; ++i) { - drflac_uint32 zeroCountPart; - drflac_uint32 riceParamPart; - if (!drflac__read_rice_parts(bs, riceParam, &zeroCountPart, &riceParamPart)) { - return DRFLAC_FALSE; + lzcount = drflac__clz(bs_cache); + zeroCounter += lzcount; + + if (lzcount < sizeof(bs_cache)*8) { + break; + } + } + + pZeroCounterOut[i] = zeroCounter; + goto extract_rice_param_part; } } + /* Make sure the cache is restored at the end of it all. */ + bs->cache = bs_cache; + bs->consumedBits = bs_consumedBits; + return DRFLAC_TRUE; } -static drflac_bool32 drflac__decode_samples_with_residual__unencoded(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 unencodedBitsPerSample, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pSamplesOut) -{ +static DRFLAC_INLINE drflac_bool32 drflac__seek_rice_parts(drflac_bs* bs, drflac_uint8 riceParam) +{ + drflac_uint32 riceParamPlus1 = riceParam + 1; + drflac_uint32 riceParamPlus1MaxConsumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs) - riceParamPlus1; + + /* + The idea here is to use local variables for the cache in an attempt to encourage the compiler to store them in registers. I have + no idea how this will work in practice... + */ + drflac_cache_t bs_cache = bs->cache; + drflac_uint32 bs_consumedBits = bs->consumedBits; + + /* The first thing to do is find the first unset bit. Most likely a bit will be set in the current cache line. */ + drflac_uint32 lzcount = drflac__clz(bs_cache); + if (lzcount < sizeof(bs_cache)*8) { + /* + It is most likely that the riceParam part (which comes after the zero counter) is also on this cache line. When extracting + this, we include the set bit from the unary coded part because it simplifies cache management. This bit will be handled + outside of this function at a higher level. + */ + extract_rice_param_part: + bs_cache <<= lzcount; + bs_consumedBits += lzcount; + + if (bs_consumedBits <= riceParamPlus1MaxConsumedBits) { + /* Getting here means the rice parameter part is wholly contained within the current cache line. */ + bs_cache <<= riceParamPlus1; + bs_consumedBits += riceParamPlus1; + } else { + /* + Getting here means the rice parameter part straddles the cache line. We need to read from the tail of the current cache + line, reload the cache, and then combine it with the head of the next cache line. + */ + + /* Before reloading the cache we need to grab the size in bits of the low part. */ + drflac_uint32 riceParamPartLoBitCount = bs_consumedBits - riceParamPlus1MaxConsumedBits; + drflac_assert(riceParamPartLoBitCount > 0 && riceParamPartLoBitCount < 32); + + /* Now reload the cache. */ + if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) { + #ifndef DR_FLAC_NO_CRC + drflac__update_crc16(bs); + #endif + bs_cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]); + bs_consumedBits = riceParamPartLoBitCount; + #ifndef DR_FLAC_NO_CRC + bs->crc16Cache = bs_cache; + #endif + } else { + /* Slow path. We need to fetch more data from the client. */ + if (!drflac__reload_cache(bs)) { + return DRFLAC_FALSE; + } + + bs_cache = bs->cache; + bs_consumedBits = bs->consumedBits + riceParamPartLoBitCount; + } + + bs_cache <<= riceParamPartLoBitCount; + } + } else { + /* + Getting here means there are no bits set on the cache line. This is a less optimal case because we just wasted a call + to drflac__clz() and we need to reload the cache. + */ + for (;;) { + if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) { + #ifndef DR_FLAC_NO_CRC + drflac__update_crc16(bs); + #endif + bs_cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]); + bs_consumedBits = 0; + #ifndef DR_FLAC_NO_CRC + bs->crc16Cache = bs_cache; + #endif + } else { + /* Slow path. We need to fetch more data from the client. */ + if (!drflac__reload_cache(bs)) { + return DRFLAC_FALSE; + } + + bs_cache = bs->cache; + bs_consumedBits = bs->consumedBits; + } + + lzcount = drflac__clz(bs_cache); + if (lzcount < sizeof(bs_cache)*8) { + break; + } + } + + goto extract_rice_param_part; + } + + /* Make sure the cache is restored at the end of it all. */ + bs->cache = bs_cache; + bs->consumedBits = bs_consumedBits; + + return DRFLAC_TRUE; +} + + +static drflac_bool32 drflac__decode_samples_with_residual__rice__scalar(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pSamplesOut) +{ + drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF}; + drflac_uint32 zeroCountPart0; + drflac_uint32 zeroCountPart1; + drflac_uint32 zeroCountPart2; + drflac_uint32 zeroCountPart3; + drflac_uint32 riceParamPart0; + drflac_uint32 riceParamPart1; + drflac_uint32 riceParamPart2; + drflac_uint32 riceParamPart3; + drflac_uint32 riceParamMask; + const drflac_int32* pSamplesOutEnd; + drflac_uint32 i; + + drflac_assert(bs != NULL); + drflac_assert(count > 0); + drflac_assert(pSamplesOut != NULL); + + riceParamMask = ~((~0UL) << riceParam); + pSamplesOutEnd = pSamplesOut + ((count >> 2) << 2); + + if (bitsPerSample >= 24) { + while (pSamplesOut < pSamplesOutEnd) { + /* + Rice extraction. It's faster to do this one at a time against local variables than it is to use the x4 version + against an array. Not sure why, but perhaps it's making more efficient use of registers? + */ + if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0) || + !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart1, &riceParamPart1) || + !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart2, &riceParamPart2) || + !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart3, &riceParamPart3)) { + return DRFLAC_FALSE; + } + + riceParamPart0 &= riceParamMask; + riceParamPart1 &= riceParamMask; + riceParamPart2 &= riceParamMask; + riceParamPart3 &= riceParamMask; + + riceParamPart0 |= (zeroCountPart0 << riceParam); + riceParamPart1 |= (zeroCountPart1 << riceParam); + riceParamPart2 |= (zeroCountPart2 << riceParam); + riceParamPart3 |= (zeroCountPart3 << riceParam); + + riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01]; + riceParamPart1 = (riceParamPart1 >> 1) ^ t[riceParamPart1 & 0x01]; + riceParamPart2 = (riceParamPart2 >> 1) ^ t[riceParamPart2 & 0x01]; + riceParamPart3 = (riceParamPart3 >> 1) ^ t[riceParamPart3 & 0x01]; + + pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_64(order, shift, coefficients, pSamplesOut + 0); + pSamplesOut[1] = riceParamPart1 + drflac__calculate_prediction_64(order, shift, coefficients, pSamplesOut + 1); + pSamplesOut[2] = riceParamPart2 + drflac__calculate_prediction_64(order, shift, coefficients, pSamplesOut + 2); + pSamplesOut[3] = riceParamPart3 + drflac__calculate_prediction_64(order, shift, coefficients, pSamplesOut + 3); + + pSamplesOut += 4; + } + } else { + while (pSamplesOut < pSamplesOutEnd) { + if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0) || + !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart1, &riceParamPart1) || + !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart2, &riceParamPart2) || + !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart3, &riceParamPart3)) { + return DRFLAC_FALSE; + } + + riceParamPart0 &= riceParamMask; + riceParamPart1 &= riceParamMask; + riceParamPart2 &= riceParamMask; + riceParamPart3 &= riceParamMask; + + riceParamPart0 |= (zeroCountPart0 << riceParam); + riceParamPart1 |= (zeroCountPart1 << riceParam); + riceParamPart2 |= (zeroCountPart2 << riceParam); + riceParamPart3 |= (zeroCountPart3 << riceParam); + + riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01]; + riceParamPart1 = (riceParamPart1 >> 1) ^ t[riceParamPart1 & 0x01]; + riceParamPart2 = (riceParamPart2 >> 1) ^ t[riceParamPart2 & 0x01]; + riceParamPart3 = (riceParamPart3 >> 1) ^ t[riceParamPart3 & 0x01]; + + pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_32(order, shift, coefficients, pSamplesOut + 0); + pSamplesOut[1] = riceParamPart1 + drflac__calculate_prediction_32(order, shift, coefficients, pSamplesOut + 1); + pSamplesOut[2] = riceParamPart2 + drflac__calculate_prediction_32(order, shift, coefficients, pSamplesOut + 2); + pSamplesOut[3] = riceParamPart3 + drflac__calculate_prediction_32(order, shift, coefficients, pSamplesOut + 3); + + pSamplesOut += 4; + } + } + + i = ((count >> 2) << 2); + while (i < count) { + /* Rice extraction. */ + if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0)) { + return DRFLAC_FALSE; + } + + /* Rice reconstruction. */ + riceParamPart0 &= riceParamMask; + riceParamPart0 |= (zeroCountPart0 << riceParam); + riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01]; + /*riceParamPart0 = (riceParamPart0 >> 1) ^ (~(riceParamPart0 & 0x01) + 1);*/ + + /* Sample reconstruction. */ + if (bitsPerSample >= 24) { + pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_64(order, shift, coefficients, pSamplesOut + 0); + } else { + pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_32(order, shift, coefficients, pSamplesOut + 0); + } + + i += 1; + pSamplesOut += 1; + } + + return DRFLAC_TRUE; +} + +#if defined(DRFLAC_SUPPORT_SSE41) +static drflac_bool32 drflac__decode_samples_with_residual__rice__sse41(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pSamplesOut) +{ + static drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF}; + + /*drflac_uint32 zeroCountParts[4];*/ + /*drflac_uint32 riceParamParts[4];*/ + + drflac_uint32 zeroCountParts0; + drflac_uint32 zeroCountParts1; + drflac_uint32 zeroCountParts2; + drflac_uint32 zeroCountParts3; + drflac_uint32 riceParamParts0; + drflac_uint32 riceParamParts1; + drflac_uint32 riceParamParts2; + drflac_uint32 riceParamParts3; + drflac_uint32 riceParamMask; + const drflac_int32* pSamplesOutEnd; + __m128i riceParamMask128; + __m128i one; + drflac_uint32 i; + drflac_assert(bs != NULL); drflac_assert(count > 0); - drflac_assert(unencodedBitsPerSample > 0 && unencodedBitsPerSample <= 32); drflac_assert(pSamplesOut != NULL); - for (unsigned int i = 0; i < count; ++i) { - if (!drflac__read_int32(bs, unencodedBitsPerSample, pSamplesOut + i)) { + riceParamMask = ~((~0UL) << riceParam); + riceParamMask128 = _mm_set1_epi32(riceParamMask); + one = _mm_set1_epi32(0x01); + + pSamplesOutEnd = pSamplesOut + ((count >> 2) << 2); + + if (bitsPerSample >= 24) { + while (pSamplesOut < pSamplesOutEnd) { + __m128i zeroCountPart128; + __m128i riceParamPart128; + drflac_uint32 riceParamParts[4]; + + /* Rice extraction. */ + if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0) || + !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts1, &riceParamParts1) || + !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts2, &riceParamParts2) || + !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts3, &riceParamParts3)) { + return DRFLAC_FALSE; + } + + zeroCountPart128 = _mm_set_epi32(zeroCountParts3, zeroCountParts2, zeroCountParts1, zeroCountParts0); + riceParamPart128 = _mm_set_epi32(riceParamParts3, riceParamParts2, riceParamParts1, riceParamParts0); + + riceParamPart128 = _mm_and_si128(riceParamPart128, riceParamMask128); + riceParamPart128 = _mm_or_si128(riceParamPart128, _mm_slli_epi32(zeroCountPart128, riceParam)); + riceParamPart128 = _mm_xor_si128(_mm_srli_epi32(riceParamPart128, 1), _mm_mullo_epi32(_mm_and_si128(riceParamPart128, one), _mm_set1_epi32(0xFFFFFFFF))); /* <-- Only supported from SSE4.1 */ + /*riceParamPart128 = _mm_xor_si128(_mm_srli_epi32(riceParamPart128, 1), _mm_add_epi32(drflac__mm_not_si128(_mm_and_si128(riceParamPart128, one)), one));*/ /* <-- SSE2 compatible */ + + _mm_storeu_si128((__m128i*)riceParamParts, riceParamPart128); + + #if defined(DRFLAC_64BIT) + /* The scalar implementation seems to be faster on 64-bit in my testing. */ + drflac__calculate_prediction_64_x4(order, shift, coefficients, riceParamParts, pSamplesOut); + #else + pSamplesOut[0] = riceParamParts[0] + drflac__calculate_prediction_64__sse41(order, shift, coefficients, pSamplesOut + 0); + pSamplesOut[1] = riceParamParts[1] + drflac__calculate_prediction_64__sse41(order, shift, coefficients, pSamplesOut + 1); + pSamplesOut[2] = riceParamParts[2] + drflac__calculate_prediction_64__sse41(order, shift, coefficients, pSamplesOut + 2); + pSamplesOut[3] = riceParamParts[3] + drflac__calculate_prediction_64__sse41(order, shift, coefficients, pSamplesOut + 3); + #endif + + pSamplesOut += 4; + } + } else { + drflac_int32 coefficientsUnaligned[32*4 + 4] = {0}; + drflac_int32* coefficients128 = (drflac_int32*)(((size_t)coefficientsUnaligned + 15) & ~15); + + for (i = 0; i < order; ++i) { + coefficients128[i*4+0] = coefficients[i]; + coefficients128[i*4+1] = coefficients[i]; + coefficients128[i*4+2] = coefficients[i]; + coefficients128[i*4+3] = coefficients[i]; + } + + while (pSamplesOut < pSamplesOutEnd) { + __m128i zeroCountPart128; + __m128i riceParamPart128; + /*drflac_int32 riceParamParts[4];*/ + + /* Rice extraction. */ +#if 1 + if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0) || + !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts1, &riceParamParts1) || + !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts2, &riceParamParts2) || + !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts3, &riceParamParts3)) { + return DRFLAC_FALSE; + } + + zeroCountPart128 = _mm_set_epi32(zeroCountParts3, zeroCountParts2, zeroCountParts1, zeroCountParts0); + riceParamPart128 = _mm_set_epi32(riceParamParts3, riceParamParts2, riceParamParts1, riceParamParts0); +#else + if (!drflac__read_rice_parts_x4(bs, riceParam, zeroCountParts, riceParamParts)) { + return DRFLAC_FALSE; + } + + zeroCountPart128 = _mm_set_epi32(zeroCountParts[3], zeroCountParts[2], zeroCountParts[1], zeroCountParts[0]); + riceParamPart128 = _mm_set_epi32(riceParamParts[3], riceParamParts[2], riceParamParts[1], riceParamParts[0]); +#endif + + riceParamPart128 = _mm_and_si128(riceParamPart128, riceParamMask128); + riceParamPart128 = _mm_or_si128(riceParamPart128, _mm_slli_epi32(zeroCountPart128, riceParam)); + riceParamPart128 = _mm_xor_si128(_mm_srli_epi32(riceParamPart128, 1), _mm_mullo_epi32(_mm_and_si128(riceParamPart128, one), _mm_set1_epi32(0xFFFFFFFF))); + +#if 1 + drflac__calculate_prediction_32_x4__sse41(order, shift, (const __m128i*)coefficients128, riceParamPart128, pSamplesOut); +#else + _mm_storeu_si128((__m128i*)riceParamParts, riceParamPart128); + + pSamplesOut[0] = riceParamParts[0] + drflac__calculate_prediction_32(order, shift, coefficients, pSamplesOut + 0); + pSamplesOut[1] = riceParamParts[1] + drflac__calculate_prediction_32(order, shift, coefficients, pSamplesOut + 1); + pSamplesOut[2] = riceParamParts[2] + drflac__calculate_prediction_32(order, shift, coefficients, pSamplesOut + 2); + pSamplesOut[3] = riceParamParts[3] + drflac__calculate_prediction_32(order, shift, coefficients, pSamplesOut + 3); +#endif + + pSamplesOut += 4; + } + } + + + i = ((count >> 2) << 2); + while (i < count) { + /* Rice extraction. */ + if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0)) { + return DRFLAC_FALSE; + } + + /* Rice reconstruction. */ + riceParamParts0 &= riceParamMask; + riceParamParts0 |= (zeroCountParts0 << riceParam); + riceParamParts0 = (riceParamParts0 >> 1) ^ t[riceParamParts0 & 0x01]; + + /* Sample reconstruction. */ + if (bitsPerSample >= 24) { + pSamplesOut[0] = riceParamParts0 + drflac__calculate_prediction_64(order, shift, coefficients, pSamplesOut + 0); + } else { + pSamplesOut[0] = riceParamParts0 + drflac__calculate_prediction_32(order, shift, coefficients, pSamplesOut + 0); + } + + i += 1; + pSamplesOut += 1; + } + + return DRFLAC_TRUE; +} +#endif + +static drflac_bool32 drflac__decode_samples_with_residual__rice(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pSamplesOut) +{ +#if defined(DRFLAC_SUPPORT_SSE41) + if (drflac__gIsSSE41Supported) { + return drflac__decode_samples_with_residual__rice__sse41(bs, bitsPerSample, count, riceParam, order, shift, coefficients, pSamplesOut); + } else +#endif + { + /* Scalar fallback. */ + #if 0 + return drflac__decode_samples_with_residual__rice__reference(bs, bitsPerSample, count, riceParam, order, shift, coefficients, pSamplesOut); + #else + return drflac__decode_samples_with_residual__rice__scalar(bs, bitsPerSample, count, riceParam, order, shift, coefficients, pSamplesOut); + #endif + } +} + +/* Reads and seeks past a string of residual values as Rice codes. The decoder should be sitting on the first bit of the Rice codes. */ +static drflac_bool32 drflac__read_and_seek_residual__rice(drflac_bs* bs, drflac_uint32 count, drflac_uint8 riceParam) +{ + drflac_uint32 i; + + drflac_assert(bs != NULL); + drflac_assert(count > 0); + + for (i = 0; i < count; ++i) { + if (!drflac__seek_rice_parts(bs, riceParam)) { return DRFLAC_FALSE; } + } + + return DRFLAC_TRUE; +} + +static drflac_bool32 drflac__decode_samples_with_residual__unencoded(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 unencodedBitsPerSample, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pSamplesOut) +{ + drflac_uint32 i; + + drflac_assert(bs != NULL); + drflac_assert(count > 0); + drflac_assert(unencodedBitsPerSample <= 31); /* <-- unencodedBitsPerSample is a 5 bit number, so cannot exceed 31. */ + drflac_assert(pSamplesOut != NULL); + + for (i = 0; i < count; ++i) { + if (unencodedBitsPerSample > 0) { + if (!drflac__read_int32(bs, unencodedBitsPerSample, pSamplesOut + i)) { + return DRFLAC_FALSE; + } + } else { + pSamplesOut[i] = 0; + } if (bitsPerSample > 16) { pSamplesOut[i] += drflac__calculate_prediction_64(order, shift, coefficients, pSamplesOut + i); @@ -2413,60 +3736,66 @@ static drflac_bool32 drflac__decode_samples_with_residual__unencoded(drflac_bs* } -// Reads and decodes the residual for the sub-frame the decoder is currently sitting on. This function should be called -// when the decoder is sitting at the very start of the RESIDUAL block. The first residuals will be ignored. The -// and parameters are used to determine how many residual values need to be decoded. +/* +Reads and decodes the residual for the sub-frame the decoder is currently sitting on. This function should be called +when the decoder is sitting at the very start of the RESIDUAL block. The first residuals will be ignored. The + and parameters are used to determine how many residual values need to be decoded. +*/ static drflac_bool32 drflac__decode_samples_with_residual(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 blockSize, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pDecodedSamples) { + drflac_uint8 residualMethod; + drflac_uint8 partitionOrder; + drflac_uint32 samplesInPartition; + drflac_uint32 partitionsRemaining; + drflac_assert(bs != NULL); drflac_assert(blockSize != 0); - drflac_assert(pDecodedSamples != NULL); // <-- Should we allow NULL, in which case we just seek past the residual rather than do a full decode? + drflac_assert(pDecodedSamples != NULL); /* <-- Should we allow NULL, in which case we just seek past the residual rather than do a full decode? */ - drflac_uint8 residualMethod; if (!drflac__read_uint8(bs, 2, &residualMethod)) { return DRFLAC_FALSE; } if (residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE && residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) { - return DRFLAC_FALSE; // Unknown or unsupported residual coding method. + return DRFLAC_FALSE; /* Unknown or unsupported residual coding method. */ } - // Ignore the first values. + /* Ignore the first values. */ pDecodedSamples += order; - - drflac_uint8 partitionOrder; if (!drflac__read_uint8(bs, 4, &partitionOrder)) { return DRFLAC_FALSE; } - // From the FLAC spec: - // The Rice partition order in a Rice-coded residual section must be less than or equal to 8. + /* + From the FLAC spec: + The Rice partition order in a Rice-coded residual section must be less than or equal to 8. + */ if (partitionOrder > 8) { return DRFLAC_FALSE; } - // Validation check. + /* Validation check. */ if ((blockSize / (1 << partitionOrder)) <= order) { return DRFLAC_FALSE; } - drflac_uint32 samplesInPartition = (blockSize / (1 << partitionOrder)) - order; - drflac_uint32 partitionsRemaining = (1 << partitionOrder); + samplesInPartition = (blockSize / (1 << partitionOrder)) - order; + partitionsRemaining = (1 << partitionOrder); for (;;) { drflac_uint8 riceParam = 0; if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE) { if (!drflac__read_uint8(bs, 4, &riceParam)) { return DRFLAC_FALSE; } - if (riceParam == 16) { + if (riceParam == 15) { riceParam = 0xFF; } } else if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) { if (!drflac__read_uint8(bs, 5, &riceParam)) { return DRFLAC_FALSE; } - if (riceParam == 32) { + if (riceParam == 31) { riceParam = 0xFF; } } @@ -2488,7 +3817,6 @@ static drflac_bool32 drflac__decode_samples_with_residual(drflac_bs* bs, drflac_ pDecodedSamples += samplesInPartition; - if (partitionsRemaining == 1) { break; } @@ -2503,30 +3831,48 @@ static drflac_bool32 drflac__decode_samples_with_residual(drflac_bs* bs, drflac_ return DRFLAC_TRUE; } -// Reads and seeks past the residual for the sub-frame the decoder is currently sitting on. This function should be called -// when the decoder is sitting at the very start of the RESIDUAL block. The first residuals will be set to 0. The -// and parameters are used to determine how many residual values need to be decoded. +/* +Reads and seeks past the residual for the sub-frame the decoder is currently sitting on. This function should be called +when the decoder is sitting at the very start of the RESIDUAL block. The first residuals will be set to 0. The + and parameters are used to determine how many residual values need to be decoded. +*/ static drflac_bool32 drflac__read_and_seek_residual(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 order) { + drflac_uint8 residualMethod; + drflac_uint8 partitionOrder; + drflac_uint32 samplesInPartition; + drflac_uint32 partitionsRemaining; + drflac_assert(bs != NULL); drflac_assert(blockSize != 0); - drflac_uint8 residualMethod; if (!drflac__read_uint8(bs, 2, &residualMethod)) { return DRFLAC_FALSE; } if (residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE && residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) { - return DRFLAC_FALSE; // Unknown or unsupported residual coding method. + return DRFLAC_FALSE; /* Unknown or unsupported residual coding method. */ } - drflac_uint8 partitionOrder; if (!drflac__read_uint8(bs, 4, &partitionOrder)) { return DRFLAC_FALSE; } - drflac_uint32 samplesInPartition = (blockSize / (1 << partitionOrder)) - order; - drflac_uint32 partitionsRemaining = (1 << partitionOrder); + /* + From the FLAC spec: + The Rice partition order in a Rice-coded residual section must be less than or equal to 8. + */ + if (partitionOrder > 8) { + return DRFLAC_FALSE; + } + + /* Validation check. */ + if ((blockSize / (1 << partitionOrder)) <= order) { + return DRFLAC_FALSE; + } + + samplesInPartition = (blockSize / (1 << partitionOrder)) - order; + partitionsRemaining = (1 << partitionOrder); for (;;) { drflac_uint8 riceParam = 0; @@ -2534,14 +3880,14 @@ static drflac_bool32 drflac__read_and_seek_residual(drflac_bs* bs, drflac_uint32 if (!drflac__read_uint8(bs, 4, &riceParam)) { return DRFLAC_FALSE; } - if (riceParam == 16) { + if (riceParam == 15) { riceParam = 0xFF; } } else if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) { if (!drflac__read_uint8(bs, 5, &riceParam)) { return DRFLAC_FALSE; } - if (riceParam == 32) { + if (riceParam == 31) { riceParam = 0xFF; } } @@ -2576,15 +3922,19 @@ static drflac_bool32 drflac__read_and_seek_residual(drflac_bs* bs, drflac_uint32 static drflac_bool32 drflac__decode_samples__constant(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 bitsPerSample, drflac_int32* pDecodedSamples) { - // Only a single sample needs to be decoded here. + drflac_uint32 i; + + /* Only a single sample needs to be decoded here. */ drflac_int32 sample; if (!drflac__read_int32(bs, bitsPerSample, &sample)) { return DRFLAC_FALSE; } - // We don't really need to expand this, but it does simplify the process of reading samples. If this becomes a performance issue (unlikely) - // we'll want to look at a more efficient way. - for (drflac_uint32 i = 0; i < blockSize; ++i) { + /* + We don't really need to expand this, but it does simplify the process of reading samples. If this becomes a performance issue (unlikely) + we'll want to look at a more efficient way. + */ + for (i = 0; i < blockSize; ++i) { pDecodedSamples[i] = sample; } @@ -2593,7 +3943,9 @@ static drflac_bool32 drflac__decode_samples__constant(drflac_bs* bs, drflac_uint static drflac_bool32 drflac__decode_samples__verbatim(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 bitsPerSample, drflac_int32* pDecodedSamples) { - for (drflac_uint32 i = 0; i < blockSize; ++i) { + drflac_uint32 i; + + for (i = 0; i < blockSize; ++i) { drflac_int32 sample; if (!drflac__read_int32(bs, bitsPerSample, &sample)) { return DRFLAC_FALSE; @@ -2607,7 +3959,9 @@ static drflac_bool32 drflac__decode_samples__verbatim(drflac_bs* bs, drflac_uint static drflac_bool32 drflac__decode_samples__fixed(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 bitsPerSample, drflac_uint8 lpcOrder, drflac_int32* pDecodedSamples) { - drflac_int32 lpcCoefficientsTable[5][4] = { + drflac_uint32 i; + + static drflac_int32 lpcCoefficientsTable[5][4] = { {0, 0, 0, 0}, {1, 0, 0, 0}, {2, -1, 0, 0}, @@ -2615,8 +3969,8 @@ static drflac_bool32 drflac__decode_samples__fixed(drflac_bs* bs, drflac_uint32 {4, -6, 4, -1} }; - // Warm up samples and coefficients. - for (drflac_uint32 i = 0; i < lpcOrder; ++i) { + /* Warm up samples and coefficients. */ + for (i = 0; i < lpcOrder; ++i) { drflac_int32 sample; if (!drflac__read_int32(bs, bitsPerSample, &sample)) { return DRFLAC_FALSE; @@ -2625,7 +3979,6 @@ static drflac_bool32 drflac__decode_samples__fixed(drflac_bs* bs, drflac_uint32 pDecodedSamples[i] = sample; } - if (!drflac__decode_samples_with_residual(bs, bitsPerSample, blockSize, lpcOrder, 0, lpcCoefficientsTable[lpcOrder], pDecodedSamples)) { return DRFLAC_FALSE; } @@ -2636,8 +3989,11 @@ static drflac_bool32 drflac__decode_samples__fixed(drflac_bs* bs, drflac_uint32 static drflac_bool32 drflac__decode_samples__lpc(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 bitsPerSample, drflac_uint8 lpcOrder, drflac_int32* pDecodedSamples) { drflac_uint8 i; + drflac_uint8 lpcPrecision; + drflac_int8 lpcShift; + drflac_int32 coefficients[32]; - // Warm up samples. + /* Warm up samples. */ for (i = 0; i < lpcOrder; ++i) { drflac_int32 sample; if (!drflac__read_int32(bs, bitsPerSample, &sample)) { @@ -2647,23 +4003,19 @@ static drflac_bool32 drflac__decode_samples__lpc(drflac_bs* bs, drflac_uint32 bl pDecodedSamples[i] = sample; } - drflac_uint8 lpcPrecision; if (!drflac__read_uint8(bs, 4, &lpcPrecision)) { return DRFLAC_FALSE; } if (lpcPrecision == 15) { - return DRFLAC_FALSE; // Invalid. + return DRFLAC_FALSE; /* Invalid. */ } lpcPrecision += 1; - - drflac_int8 lpcShift; if (!drflac__read_int8(bs, 5, &lpcShift)) { return DRFLAC_FALSE; } - - drflac_int32 coefficients[32]; + drflac_zero_memory(coefficients, sizeof(coefficients)); for (i = 0; i < lpcOrder; ++i) { if (!drflac__read_int32(bs, lpcPrecision, coefficients + i)) { return DRFLAC_FALSE; @@ -2678,71 +4030,82 @@ static drflac_bool32 drflac__decode_samples__lpc(drflac_bs* bs, drflac_uint32 bl } -static drflac_bool32 drflac__read_next_frame_header(drflac_bs* bs, drflac_uint8 streaminfoBitsPerSample, drflac_frame_header* header) +static drflac_bool32 drflac__read_next_flac_frame_header(drflac_bs* bs, drflac_uint8 streaminfoBitsPerSample, drflac_frame_header* header) { + const drflac_uint32 sampleRateTable[12] = {0, 88200, 176400, 192000, 8000, 16000, 22050, 24000, 32000, 44100, 48000, 96000}; + const drflac_uint8 bitsPerSampleTable[8] = {0, 8, 12, (drflac_uint8)-1, 16, 20, 24, (drflac_uint8)-1}; /* -1 = reserved. */ + drflac_assert(bs != NULL); drflac_assert(header != NULL); - const drflac_uint32 sampleRateTable[12] = {0, 88200, 176400, 192000, 8000, 16000, 22050, 24000, 32000, 44100, 48000, 96000}; - const drflac_uint8 bitsPerSampleTable[8] = {0, 8, 12, (drflac_uint8)-1, 16, 20, 24, (drflac_uint8)-1}; // -1 = reserved. - - // Keep looping until we find a valid sync code. + /* Keep looping until we find a valid sync code. */ for (;;) { + drflac_uint8 crc8 = 0xCE; /* 0xCE = drflac_crc8(0, 0x3FFE, 14); */ + drflac_uint8 reserved = 0; + drflac_uint8 blockingStrategy = 0; + drflac_uint8 blockSize = 0; + drflac_uint8 sampleRate = 0; + drflac_uint8 channelAssignment = 0; + drflac_uint8 bitsPerSample = 0; + drflac_bool32 isVariableBlockSize; + if (!drflac__find_and_seek_to_next_sync_code(bs)) { return DRFLAC_FALSE; } - drflac_uint8 crc8 = 0xCE; // 0xCE = drflac_crc8(0, 0x3FFE, 14); - - drflac_uint8 reserved = 0; if (!drflac__read_uint8(bs, 1, &reserved)) { return DRFLAC_FALSE; } + if (reserved == 1) { + continue; + } crc8 = drflac_crc8(crc8, reserved, 1); - - drflac_uint8 blockingStrategy = 0; if (!drflac__read_uint8(bs, 1, &blockingStrategy)) { return DRFLAC_FALSE; } crc8 = drflac_crc8(crc8, blockingStrategy, 1); - - drflac_uint8 blockSize = 0; if (!drflac__read_uint8(bs, 4, &blockSize)) { return DRFLAC_FALSE; } + if (blockSize == 0) { + continue; + } crc8 = drflac_crc8(crc8, blockSize, 4); - - drflac_uint8 sampleRate = 0; if (!drflac__read_uint8(bs, 4, &sampleRate)) { return DRFLAC_FALSE; } crc8 = drflac_crc8(crc8, sampleRate, 4); - - drflac_uint8 channelAssignment = 0; if (!drflac__read_uint8(bs, 4, &channelAssignment)) { return DRFLAC_FALSE; } + if (channelAssignment > 10) { + continue; + } crc8 = drflac_crc8(crc8, channelAssignment, 4); - - drflac_uint8 bitsPerSample = 0; if (!drflac__read_uint8(bs, 3, &bitsPerSample)) { return DRFLAC_FALSE; } + if (bitsPerSample == 3 || bitsPerSample == 7) { + continue; + } crc8 = drflac_crc8(crc8, bitsPerSample, 3); if (!drflac__read_uint8(bs, 1, &reserved)) { return DRFLAC_FALSE; } + if (reserved == 1) { + continue; + } crc8 = drflac_crc8(crc8, reserved, 1); - drflac_bool32 isVariableBlockSize = blockingStrategy == 1; + isVariableBlockSize = blockingStrategy == 1; if (isVariableBlockSize) { drflac_uint64 sampleNumber; drflac_result result = drflac__read_utf8_coded_number(bs, &sampleNumber, &crc8); @@ -2765,7 +4128,7 @@ static drflac_bool32 drflac__read_next_frame_header(drflac_bs* bs, drflac_uint8 continue; } } - header->frameNumber = (drflac_uint32)frameNumber; // <-- Safe cast. + header->frameNumber = (drflac_uint32)frameNumber; /* <-- Safe cast. */ header->sampleNumber = 0; } @@ -2811,7 +4174,7 @@ static drflac_bool32 drflac__read_next_frame_header(drflac_bs* bs, drflac_uint8 crc8 = drflac_crc8(crc8, header->sampleRate, 16); header->sampleRate *= 10; } else { - continue; // Invalid. Assume an invalid block. + continue; /* Invalid. Assume an invalid block. */ } @@ -2826,11 +4189,11 @@ static drflac_bool32 drflac__read_next_frame_header(drflac_bs* bs, drflac_uint8 return DRFLAC_FALSE; } - #ifndef DR_FLAC_NO_CRC +#ifndef DR_FLAC_NO_CRC if (header->crc8 != crc8) { - continue; // CRC mismatch. Loop back to the top and find the next sync code. + continue; /* CRC mismatch. Loop back to the top and find the next sync code. */ } - #endif +#endif return DRFLAC_TRUE; } } @@ -2838,16 +4201,18 @@ static drflac_bool32 drflac__read_next_frame_header(drflac_bs* bs, drflac_uint8 static drflac_bool32 drflac__read_subframe_header(drflac_bs* bs, drflac_subframe* pSubframe) { drflac_uint8 header; + int type; + if (!drflac__read_uint8(bs, 8, &header)) { return DRFLAC_FALSE; } - // First bit should always be 0. + /* First bit should always be 0. */ if ((header & 0x80) != 0) { return DRFLAC_FALSE; } - int type = (header & 0x7E) >> 1; + type = (header & 0x7E) >> 1; if (type == 0) { pSubframe->subframeType = DRFLAC_SUBFRAME_CONSTANT; } else if (type == 1) { @@ -2872,7 +4237,7 @@ static drflac_bool32 drflac__read_subframe_header(drflac_bs* bs, drflac_subframe return DRFLAC_FALSE; } - // Wasted bits per sample. + /* Wasted bits per sample. */ pSubframe->wastedBitsPerSample = 0; if ((header & 0x01) == 1) { unsigned int wastedBitsPerSample; @@ -2887,15 +4252,17 @@ static drflac_bool32 drflac__read_subframe_header(drflac_bs* bs, drflac_subframe static drflac_bool32 drflac__decode_subframe(drflac_bs* bs, drflac_frame* frame, int subframeIndex, drflac_int32* pDecodedSamplesOut) { + drflac_subframe* pSubframe; + drflac_assert(bs != NULL); drflac_assert(frame != NULL); - drflac_subframe* pSubframe = frame->subframes + subframeIndex; + pSubframe = frame->subframes + subframeIndex; if (!drflac__read_subframe_header(bs, pSubframe)) { return DRFLAC_FALSE; } - // Side channels require an extra bit per sample. Took a while to figure that one out... + /* Side channels require an extra bit per sample. Took a while to figure that one out... */ pSubframe->bitsPerSample = frame->header.bitsPerSample; if ((frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE || frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE) && subframeIndex == 1) { pSubframe->bitsPerSample += 1; @@ -2903,7 +4270,10 @@ static drflac_bool32 drflac__decode_subframe(drflac_bs* bs, drflac_frame* frame, pSubframe->bitsPerSample += 1; } - // Need to handle wasted bits per sample. + /* Need to handle wasted bits per sample. */ + if (pSubframe->wastedBitsPerSample >= pSubframe->bitsPerSample) { + return DRFLAC_FALSE; + } pSubframe->bitsPerSample -= pSubframe->wastedBitsPerSample; pSubframe->pDecodedSamples = pDecodedSamplesOut; @@ -2937,15 +4307,17 @@ static drflac_bool32 drflac__decode_subframe(drflac_bs* bs, drflac_frame* frame, static drflac_bool32 drflac__seek_subframe(drflac_bs* bs, drflac_frame* frame, int subframeIndex) { + drflac_subframe* pSubframe; + drflac_assert(bs != NULL); drflac_assert(frame != NULL); - drflac_subframe* pSubframe = frame->subframes + subframeIndex; + pSubframe = frame->subframes + subframeIndex; if (!drflac__read_subframe_header(bs, pSubframe)) { return DRFLAC_FALSE; } - // Side channels require an extra bit per sample. Took a while to figure that one out... + /* Side channels require an extra bit per sample. Took a while to figure that one out... */ pSubframe->bitsPerSample = frame->header.bitsPerSample; if ((frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE || frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE) && subframeIndex == 1) { pSubframe->bitsPerSample += 1; @@ -2953,7 +4325,10 @@ static drflac_bool32 drflac__seek_subframe(drflac_bs* bs, drflac_frame* frame, i pSubframe->bitsPerSample += 1; } - // Need to handle wasted bits per sample. + /* Need to handle wasted bits per sample. */ + if (pSubframe->wastedBitsPerSample >= pSubframe->bitsPerSample) { + return DRFLAC_FALSE; + } pSubframe->bitsPerSample -= pSubframe->wastedBitsPerSample; pSubframe->pDecodedSamples = NULL; @@ -2988,22 +4363,23 @@ static drflac_bool32 drflac__seek_subframe(drflac_bs* bs, drflac_frame* frame, i case DRFLAC_SUBFRAME_LPC: { + unsigned char lpcPrecision; + unsigned int bitsToSeek = pSubframe->lpcOrder * pSubframe->bitsPerSample; if (!drflac__seek_bits(bs, bitsToSeek)) { return DRFLAC_FALSE; } - unsigned char lpcPrecision; if (!drflac__read_uint8(bs, 4, &lpcPrecision)) { return DRFLAC_FALSE; } if (lpcPrecision == 15) { - return DRFLAC_FALSE; // Invalid. + return DRFLAC_FALSE; /* Invalid. */ } lpcPrecision += 1; - bitsToSeek = (pSubframe->lpcOrder * lpcPrecision) + 5; // +5 for shift. + bitsToSeek = (pSubframe->lpcOrder * lpcPrecision) + 5; /* +5 for shift. */ if (!drflac__seek_bits(bs, bitsToSeek)) { return DRFLAC_FALSE; } @@ -3022,35 +4398,43 @@ static drflac_bool32 drflac__seek_subframe(drflac_bs* bs, drflac_frame* frame, i static DRFLAC_INLINE drflac_uint8 drflac__get_channel_count_from_channel_assignment(drflac_int8 channelAssignment) { - drflac_assert(channelAssignment <= 10); - drflac_uint8 lookup[] = {1, 2, 3, 4, 5, 6, 7, 8, 2, 2, 2}; + + drflac_assert(channelAssignment <= 10); return lookup[channelAssignment]; } -static drflac_result drflac__decode_frame(drflac* pFlac) +static drflac_result drflac__decode_flac_frame(drflac* pFlac) { - // This function should be called while the stream is sitting on the first byte after the frame header. + int channelCount; + int i; + drflac_uint8 paddingSizeInBits; + drflac_uint16 desiredCRC16; +#ifndef DR_FLAC_NO_CRC + drflac_uint16 actualCRC16; +#endif + + /* This function should be called while the stream is sitting on the first byte after the frame header. */ drflac_zero_memory(pFlac->currentFrame.subframes, sizeof(pFlac->currentFrame.subframes)); - // The frame block size must never be larger than the maximum block size defined by the FLAC stream. + /* The frame block size must never be larger than the maximum block size defined by the FLAC stream. */ if (pFlac->currentFrame.header.blockSize > pFlac->maxBlockSize) { return DRFLAC_ERROR; } - // The number of channels in the frame must match the channel count from the STREAMINFO block. - int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFrame.header.channelAssignment); + /* The number of channels in the frame must match the channel count from the STREAMINFO block. */ + channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFrame.header.channelAssignment); if (channelCount != (int)pFlac->channels) { return DRFLAC_ERROR; } - for (int i = 0; i < channelCount; ++i) { - if (!drflac__decode_subframe(&pFlac->bs, &pFlac->currentFrame, i, pFlac->pDecodedSamples + (pFlac->currentFrame.header.blockSize * i))) { + for (i = 0; i < channelCount; ++i) { + if (!drflac__decode_subframe(&pFlac->bs, &pFlac->currentFrame, i, pFlac->pDecodedSamples + ((pFlac->currentFrame.header.blockSize+DRFLAC_LEADING_SAMPLES) * i) + DRFLAC_LEADING_SAMPLES)) { return DRFLAC_ERROR; } } - drflac_uint8 paddingSizeInBits = DRFLAC_CACHE_L1_BITS_REMAINING(&pFlac->bs) & 7; + paddingSizeInBits = DRFLAC_CACHE_L1_BITS_REMAINING(&pFlac->bs) & 7; if (paddingSizeInBits > 0) { drflac_uint8 padding = 0; if (!drflac__read_uint8(&pFlac->bs, paddingSizeInBits, &padding)) { @@ -3059,16 +4443,15 @@ static drflac_result drflac__decode_frame(drflac* pFlac) } #ifndef DR_FLAC_NO_CRC - drflac_uint16 actualCRC16 = drflac__flush_crc16(&pFlac->bs); + actualCRC16 = drflac__flush_crc16(&pFlac->bs); #endif - drflac_uint16 desiredCRC16; if (!drflac__read_uint16(&pFlac->bs, 16, &desiredCRC16)) { return DRFLAC_END_OF_STREAM; } #ifndef DR_FLAC_NO_CRC if (actualCRC16 != desiredCRC16) { - return DRFLAC_CRC_MISMATCH; // CRC mismatch. + return DRFLAC_CRC_MISMATCH; /* CRC mismatch. */ } #endif @@ -3077,51 +4460,59 @@ static drflac_result drflac__decode_frame(drflac* pFlac) return DRFLAC_SUCCESS; } -static drflac_result drflac__seek_frame(drflac* pFlac) +static drflac_result drflac__seek_flac_frame(drflac* pFlac) { - int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFrame.header.channelAssignment); - for (int i = 0; i < channelCount; ++i) { + int channelCount; + int i; + drflac_uint16 desiredCRC16; +#ifndef DR_FLAC_NO_CRC + drflac_uint16 actualCRC16; +#endif + + channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFrame.header.channelAssignment); + for (i = 0; i < channelCount; ++i) { if (!drflac__seek_subframe(&pFlac->bs, &pFlac->currentFrame, i)) { return DRFLAC_ERROR; } } - // Padding. + /* Padding. */ if (!drflac__seek_bits(&pFlac->bs, DRFLAC_CACHE_L1_BITS_REMAINING(&pFlac->bs) & 7)) { return DRFLAC_ERROR; } - // CRC. + /* CRC. */ #ifndef DR_FLAC_NO_CRC - drflac_uint16 actualCRC16 = drflac__flush_crc16(&pFlac->bs); + actualCRC16 = drflac__flush_crc16(&pFlac->bs); #endif - drflac_uint16 desiredCRC16; if (!drflac__read_uint16(&pFlac->bs, 16, &desiredCRC16)) { return DRFLAC_END_OF_STREAM; } #ifndef DR_FLAC_NO_CRC if (actualCRC16 != desiredCRC16) { - return DRFLAC_CRC_MISMATCH; // CRC mismatch. + return DRFLAC_CRC_MISMATCH; /* CRC mismatch. */ } #endif return DRFLAC_SUCCESS; } -static drflac_bool32 drflac__read_and_decode_next_frame(drflac* pFlac) +static drflac_bool32 drflac__read_and_decode_next_flac_frame(drflac* pFlac) { drflac_assert(pFlac != NULL); for (;;) { - if (!drflac__read_next_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFrame.header)) { + drflac_result result; + + if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFrame.header)) { return DRFLAC_FALSE; } - drflac_result result = drflac__decode_frame(pFlac); + result = drflac__decode_flac_frame(pFlac); if (result != DRFLAC_SUCCESS) { if (result == DRFLAC_CRC_MISMATCH) { - continue; // CRC mismatch. Skip to the next frame. + continue; /* CRC mismatch. Skip to the next frame. */ } else { return DRFLAC_FALSE; } @@ -3134,29 +4525,67 @@ static drflac_bool32 drflac__read_and_decode_next_frame(drflac* pFlac) static void drflac__get_current_frame_sample_range(drflac* pFlac, drflac_uint64* pFirstSampleInFrameOut, drflac_uint64* pLastSampleInFrameOut) { + unsigned int channelCount; + drflac_uint64 firstSampleInFrame; + drflac_uint64 lastSampleInFrame; + drflac_assert(pFlac != NULL); - unsigned int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFrame.header.channelAssignment); + channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFrame.header.channelAssignment); - drflac_uint64 firstSampleInFrame = pFlac->currentFrame.header.sampleNumber; + firstSampleInFrame = pFlac->currentFrame.header.sampleNumber*channelCount; if (firstSampleInFrame == 0) { firstSampleInFrame = pFlac->currentFrame.header.frameNumber * pFlac->maxBlockSize*channelCount; } - drflac_uint64 lastSampleInFrame = firstSampleInFrame + (pFlac->currentFrame.header.blockSize*channelCount); + lastSampleInFrame = firstSampleInFrame + (pFlac->currentFrame.header.blockSize*channelCount); if (lastSampleInFrame > 0) { - lastSampleInFrame -= 1; // Needs to be zero based. + lastSampleInFrame -= 1; /* Needs to be zero based. */ + } + + if (pFirstSampleInFrameOut) { + *pFirstSampleInFrameOut = firstSampleInFrame; + } + if (pLastSampleInFrameOut) { + *pLastSampleInFrameOut = lastSampleInFrame; + } +} + +/* This function will be replacing drflac__get_current_frame_sample_range(), but it's not currently used so I have commented it out to silence a compiler warning. */ +#if 0 +static void drflac__get_pcm_frame_range_of_current_flac_frame(drflac* pFlac, drflac_uint64* pFirstPCMFrame, drflac_uint64* pLastPCMFrame) +{ + drflac_uint64 firstPCMFrame; + drflac_uint64 lastPCMFrame; + + drflac_assert(pFlac != NULL); + + firstPCMFrame = pFlac->currentFrame.header.sampleNumber; + if (firstPCMFrame == 0) { + firstPCMFrame = pFlac->currentFrame.header.frameNumber * pFlac->maxBlockSize; + } + + lastPCMFrame = firstPCMFrame + (pFlac->currentFrame.header.blockSize); + if (lastPCMFrame > 0) { + lastPCMFrame -= 1; /* Needs to be zero based. */ } - if (pFirstSampleInFrameOut) *pFirstSampleInFrameOut = firstSampleInFrame; - if (pLastSampleInFrameOut) *pLastSampleInFrameOut = lastSampleInFrame; + if (pFirstPCMFrame) { + *pFirstPCMFrame = firstPCMFrame; + } + if (pLastPCMFrame) { + *pLastPCMFrame = lastPCMFrame; + } } +#endif static drflac_bool32 drflac__seek_to_first_frame(drflac* pFlac) { + drflac_bool32 result; + drflac_assert(pFlac != NULL); - drflac_bool32 result = drflac__seek_to_byte(&pFlac->bs, pFlac->firstFramePos); + result = drflac__seek_to_byte(&pFlac->bs, pFlac->firstFramePos); drflac_zero_memory(&pFlac->currentFrame, sizeof(pFlac->currentFrame)); pFlac->currentSample = 0; @@ -3164,94 +4593,134 @@ static drflac_bool32 drflac__seek_to_first_frame(drflac* pFlac) return result; } -static DRFLAC_INLINE drflac_result drflac__seek_to_next_frame(drflac* pFlac) +static DRFLAC_INLINE drflac_result drflac__seek_to_next_flac_frame(drflac* pFlac) { - // This function should only ever be called while the decoder is sitting on the first byte past the FRAME_HEADER section. + /* This function should only ever be called while the decoder is sitting on the first byte past the FRAME_HEADER section. */ drflac_assert(pFlac != NULL); - return drflac__seek_frame(pFlac); + return drflac__seek_flac_frame(pFlac); } -static drflac_bool32 drflac__seek_to_sample__brute_force(drflac* pFlac, drflac_uint64 sampleIndex) +drflac_uint64 drflac__seek_forward_by_samples(drflac* pFlac, drflac_uint64 samplesToRead) { - drflac_assert(pFlac != NULL); + drflac_uint64 samplesRead = 0; + while (samplesToRead > 0) { + if (pFlac->currentFrame.samplesRemaining == 0) { + if (!drflac__read_and_decode_next_flac_frame(pFlac)) { + break; /* Couldn't read the next frame, so just break from the loop and return. */ + } + } else { + if (pFlac->currentFrame.samplesRemaining > samplesToRead) { + samplesRead += samplesToRead; + pFlac->currentFrame.samplesRemaining -= (drflac_uint32)samplesToRead; /* <-- Safe cast. Will always be < currentFrame.samplesRemaining < 65536. */ + samplesToRead = 0; + } else { + samplesRead += pFlac->currentFrame.samplesRemaining; + samplesToRead -= pFlac->currentFrame.samplesRemaining; + pFlac->currentFrame.samplesRemaining = 0; + } + } + } - drflac_bool32 isMidFrame = DRFLAC_FALSE; + pFlac->currentSample += samplesRead; + return samplesRead; +} + +drflac_uint64 drflac__seek_forward_by_pcm_frames(drflac* pFlac, drflac_uint64 pcmFramesToSeek) +{ + return drflac__seek_forward_by_samples(pFlac, pcmFramesToSeek*pFlac->channels); +} - // If we are seeking forward we start from the current position. Otherwise we need to start all the way from the start of the file. +static drflac_bool32 drflac__seek_to_sample__brute_force(drflac* pFlac, drflac_uint64 sampleIndex) +{ + drflac_bool32 isMidFrame = DRFLAC_FALSE; drflac_uint64 runningSampleCount; + + drflac_assert(pFlac != NULL); + + /* If we are seeking forward we start from the current position. Otherwise we need to start all the way from the start of the file. */ if (sampleIndex >= pFlac->currentSample) { - // Seeking forward. Need to seek from the current position. + /* Seeking forward. Need to seek from the current position. */ runningSampleCount = pFlac->currentSample; - // The frame header for the first frame may not yet have been read. We need to do that if necessary. + /* The frame header for the first frame may not yet have been read. We need to do that if necessary. */ if (pFlac->currentSample == 0 && pFlac->currentFrame.samplesRemaining == 0) { - if (!drflac__read_next_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFrame.header)) { + if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFrame.header)) { return DRFLAC_FALSE; } } else { isMidFrame = DRFLAC_TRUE; } } else { - // Seeking backwards. Need to seek from the start of the file. + /* Seeking backwards. Need to seek from the start of the file. */ runningSampleCount = 0; - // Move back to the start. + /* Move back to the start. */ if (!drflac__seek_to_first_frame(pFlac)) { return DRFLAC_FALSE; } - // Decode the first frame in preparation for sample-exact seeking below. - if (!drflac__read_next_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFrame.header)) { + /* Decode the first frame in preparation for sample-exact seeking below. */ + if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFrame.header)) { return DRFLAC_FALSE; } } - // We need to as quickly as possible find the frame that contains the target sample. To do this, we iterate over each frame and inspect its - // header. If based on the header we can determine that the frame contains the sample, we do a full decode of that frame. + /* + We need to as quickly as possible find the frame that contains the target sample. To do this, we iterate over each frame and inspect its + header. If based on the header we can determine that the frame contains the sample, we do a full decode of that frame. + */ for (;;) { + drflac_uint64 sampleCountInThisFrame; drflac_uint64 firstSampleInFrame = 0; drflac_uint64 lastSampleInFrame = 0; + drflac__get_current_frame_sample_range(pFlac, &firstSampleInFrame, &lastSampleInFrame); - drflac_uint64 sampleCountInThisFrame = (lastSampleInFrame - firstSampleInFrame) + 1; + sampleCountInThisFrame = (lastSampleInFrame - firstSampleInFrame) + 1; if (sampleIndex < (runningSampleCount + sampleCountInThisFrame)) { - // The sample should be in this frame. We need to fully decode it, however if it's an invalid frame (a CRC mismatch), we need to pretend - // it never existed and keep iterating. + /* + The sample should be in this frame. We need to fully decode it, however if it's an invalid frame (a CRC mismatch), we need to pretend + it never existed and keep iterating. + */ drflac_uint64 samplesToDecode = sampleIndex - runningSampleCount; if (!isMidFrame) { - drflac_result result = drflac__decode_frame(pFlac); + drflac_result result = drflac__decode_flac_frame(pFlac); if (result == DRFLAC_SUCCESS) { - // The frame is valid. We just need to skip over some samples to ensure it's sample-exact. - return drflac_read_s32(pFlac, samplesToDecode, NULL) == samplesToDecode; // <-- If this fails, something bad has happened (it should never fail). + /* The frame is valid. We just need to skip over some samples to ensure it's sample-exact. */ + return drflac__seek_forward_by_samples(pFlac, samplesToDecode) == samplesToDecode; /* <-- If this fails, something bad has happened (it should never fail). */ } else { if (result == DRFLAC_CRC_MISMATCH) { - goto next_iteration; // CRC mismatch. Pretend this frame never existed. + goto next_iteration; /* CRC mismatch. Pretend this frame never existed. */ } else { return DRFLAC_FALSE; } } } else { - // We started seeking mid-frame which means we need to skip the frame decoding part. - return drflac_read_s32(pFlac, samplesToDecode, NULL) == samplesToDecode; + /* We started seeking mid-frame which means we need to skip the frame decoding part. */ + return drflac__seek_forward_by_samples(pFlac, samplesToDecode) == samplesToDecode; } } else { - // It's not in this frame. We need to seek past the frame, but check if there was a CRC mismatch. If so, we pretend this - // frame never existed and leave the running sample count untouched. + /* + It's not in this frame. We need to seek past the frame, but check if there was a CRC mismatch. If so, we pretend this + frame never existed and leave the running sample count untouched. + */ if (!isMidFrame) { - drflac_result result = drflac__seek_to_next_frame(pFlac); + drflac_result result = drflac__seek_to_next_flac_frame(pFlac); if (result == DRFLAC_SUCCESS) { runningSampleCount += sampleCountInThisFrame; } else { if (result == DRFLAC_CRC_MISMATCH) { - goto next_iteration; // CRC mismatch. Pretend this frame never existed. + goto next_iteration; /* CRC mismatch. Pretend this frame never existed. */ } else { return DRFLAC_FALSE; } } } else { - // We started seeking mid-frame which means we need to seek by reading to the end of the frame instead of with - // drflac__seek_to_next_frame() which only works if the decoder is sitting on the byte just after the frame header. + /* + We started seeking mid-frame which means we need to seek by reading to the end of the frame instead of with + drflac__seek_to_next_flac_frame() which only works if the decoder is sitting on the byte just after the frame header. + */ runningSampleCount += pFlac->currentFrame.samplesRemaining; pFlac->currentFrame.samplesRemaining = 0; isMidFrame = DRFLAC_FALSE; @@ -3259,8 +4728,8 @@ static drflac_bool32 drflac__seek_to_sample__brute_force(drflac* pFlac, drflac_u } next_iteration: - // Grab the next frame in preparation for the next iteration. - if (!drflac__read_next_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFrame.header)) { + /* Grab the next frame in preparation for the next iteration. */ + if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFrame.header)) { return DRFLAC_FALSE; } } @@ -3269,15 +4738,18 @@ static drflac_bool32 drflac__seek_to_sample__brute_force(drflac* pFlac, drflac_u static drflac_bool32 drflac__seek_to_sample__seek_table(drflac* pFlac, drflac_uint64 sampleIndex) { + drflac_uint32 iClosestSeekpoint = 0; + drflac_bool32 isMidFrame = DRFLAC_FALSE; + drflac_uint64 runningSampleCount; + drflac_uint32 iSeekpoint; + drflac_assert(pFlac != NULL); if (pFlac->pSeekpoints == NULL || pFlac->seekpointCount == 0) { return DRFLAC_FALSE; } - - drflac_uint32 iClosestSeekpoint = 0; - for (drflac_uint32 iSeekpoint = 0; iSeekpoint < pFlac->seekpointCount; ++iSeekpoint) { + for (iSeekpoint = 0; iSeekpoint < pFlac->seekpointCount; ++iSeekpoint) { if (pFlac->pSeekpoints[iSeekpoint].firstSample*pFlac->channels >= sampleIndex) { break; } @@ -3285,82 +4757,87 @@ static drflac_bool32 drflac__seek_to_sample__seek_table(drflac* pFlac, drflac_ui iClosestSeekpoint = iSeekpoint; } - - drflac_bool32 isMidFrame = DRFLAC_FALSE; - - // At this point we should have found the seekpoint closest to our sample. If we are seeking forward and the closest seekpoint is _before_ the current sample, we - // just seek forward from where we are. Otherwise we start seeking from the seekpoint's first sample. - drflac_uint64 runningSampleCount; + /* + At this point we should have found the seekpoint closest to our sample. If we are seeking forward and the closest seekpoint is _before_ the current sample, we + just seek forward from where we are. Otherwise we start seeking from the seekpoint's first sample. + */ if ((sampleIndex >= pFlac->currentSample) && (pFlac->pSeekpoints[iClosestSeekpoint].firstSample*pFlac->channels <= pFlac->currentSample)) { - // Optimized case. Just seek forward from where we are. + /* Optimized case. Just seek forward from where we are. */ runningSampleCount = pFlac->currentSample; - // The frame header for the first frame may not yet have been read. We need to do that if necessary. + /* The frame header for the first frame may not yet have been read. We need to do that if necessary. */ if (pFlac->currentSample == 0 && pFlac->currentFrame.samplesRemaining == 0) { - if (!drflac__read_next_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFrame.header)) { + if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFrame.header)) { return DRFLAC_FALSE; } } else { isMidFrame = DRFLAC_TRUE; } } else { - // Slower case. Seek to the start of the seekpoint and then seek forward from there. + /* Slower case. Seek to the start of the seekpoint and then seek forward from there. */ runningSampleCount = pFlac->pSeekpoints[iClosestSeekpoint].firstSample*pFlac->channels; if (!drflac__seek_to_byte(&pFlac->bs, pFlac->firstFramePos + pFlac->pSeekpoints[iClosestSeekpoint].frameOffset)) { return DRFLAC_FALSE; } - // Grab the frame the seekpoint is sitting on in preparation for the sample-exact seeking below. - if (!drflac__read_next_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFrame.header)) { + /* Grab the frame the seekpoint is sitting on in preparation for the sample-exact seeking below. */ + if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFrame.header)) { return DRFLAC_FALSE; } } for (;;) { + drflac_uint64 sampleCountInThisFrame; drflac_uint64 firstSampleInFrame = 0; drflac_uint64 lastSampleInFrame = 0; drflac__get_current_frame_sample_range(pFlac, &firstSampleInFrame, &lastSampleInFrame); - drflac_uint64 sampleCountInThisFrame = (lastSampleInFrame - firstSampleInFrame) + 1; + sampleCountInThisFrame = (lastSampleInFrame - firstSampleInFrame) + 1; if (sampleIndex < (runningSampleCount + sampleCountInThisFrame)) { - // The sample should be in this frame. We need to fully decode it, but if it's an invalid frame (a CRC mismatch) we need to pretend - // it never existed and keep iterating. + /* + The sample should be in this frame. We need to fully decode it, but if it's an invalid frame (a CRC mismatch) we need to pretend + it never existed and keep iterating. + */ drflac_uint64 samplesToDecode = sampleIndex - runningSampleCount; if (!isMidFrame) { - drflac_result result = drflac__decode_frame(pFlac); + drflac_result result = drflac__decode_flac_frame(pFlac); if (result == DRFLAC_SUCCESS) { - // The frame is valid. We just need to skip over some samples to ensure it's sample-exact. - return drflac_read_s32(pFlac, samplesToDecode, NULL) == samplesToDecode; // <-- If this fails, something bad has happened (it should never fail). + /* The frame is valid. We just need to skip over some samples to ensure it's sample-exact. */ + return drflac__seek_forward_by_samples(pFlac, samplesToDecode) == samplesToDecode; /* <-- If this fails, something bad has happened (it should never fail). */ } else { if (result == DRFLAC_CRC_MISMATCH) { - goto next_iteration; // CRC mismatch. Pretend this frame never existed. + goto next_iteration; /* CRC mismatch. Pretend this frame never existed. */ } else { return DRFLAC_FALSE; } } } else { - // We started seeking mid-frame which means we need to skip the frame decoding part. - return drflac_read_s32(pFlac, samplesToDecode, NULL) == samplesToDecode; + /* We started seeking mid-frame which means we need to skip the frame decoding part. */ + return drflac__seek_forward_by_samples(pFlac, samplesToDecode) == samplesToDecode; } } else { - // It's not in this frame. We need to seek past the frame, but check if there was a CRC mismatch. If so, we pretend this - // frame never existed and leave the running sample count untouched. + /* + It's not in this frame. We need to seek past the frame, but check if there was a CRC mismatch. If so, we pretend this + frame never existed and leave the running sample count untouched. + */ if (!isMidFrame) { - drflac_result result = drflac__seek_to_next_frame(pFlac); + drflac_result result = drflac__seek_to_next_flac_frame(pFlac); if (result == DRFLAC_SUCCESS) { runningSampleCount += sampleCountInThisFrame; } else { if (result == DRFLAC_CRC_MISMATCH) { - goto next_iteration; // CRC mismatch. Pretend this frame never existed. + goto next_iteration; /* CRC mismatch. Pretend this frame never existed. */ } else { return DRFLAC_FALSE; } } } else { - // We started seeking mid-frame which means we need to seek by reading to the end of the frame instead of with - // drflac__seek_to_next_frame() which only works if the decoder is sitting on the byte just after the frame header. + /* + We started seeking mid-frame which means we need to seek by reading to the end of the frame instead of with + drflac__seek_to_next_flac_frame() which only works if the decoder is sitting on the byte just after the frame header. + */ runningSampleCount += pFlac->currentFrame.samplesRemaining; pFlac->currentFrame.samplesRemaining = 0; isMidFrame = DRFLAC_FALSE; @@ -3368,8 +4845,8 @@ static drflac_bool32 drflac__seek_to_sample__seek_table(drflac* pFlac, drflac_ui } next_iteration: - // Grab the next frame in preparation for the next iteration. - if (!drflac__read_next_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFrame.header)) { + /* Grab the next frame in preparation for the next iteration. */ + if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFrame.header)) { return DRFLAC_FALSE; } } @@ -3379,8 +4856,8 @@ static drflac_bool32 drflac__seek_to_sample__seek_table(drflac* pFlac, drflac_ui #ifndef DR_FLAC_NO_OGG typedef struct { - drflac_uint8 capturePattern[4]; // Should be "OggS" - drflac_uint8 structureVersion; // Always 0. + drflac_uint8 capturePattern[4]; /* Should be "OggS" */ + drflac_uint8 structureVersion; /* Always 0. */ drflac_uint8 headerType; drflac_uint64 granulePosition; drflac_uint32 serialNumber; @@ -3407,8 +4884,8 @@ typedef struct drflac_uint64 runningFilePos; drflac_bool32 hasStreamInfoBlock; drflac_bool32 hasMetadataBlocks; - drflac_bs bs; // <-- A bit streamer is required for loading data during initialization. - drflac_frame_header firstFrameHeader; // <-- The header of the first frame that was read during relaxed initalization. Only set if there is no STREAMINFO block. + drflac_bs bs; /* <-- A bit streamer is required for loading data during initialization. */ + drflac_frame_header firstFrameHeader; /* <-- The header of the first frame that was read during relaxed initalization. Only set if there is no STREAMINFO block. */ #ifndef DR_FLAC_NO_OGG drflac_uint32 oggSerial; @@ -3438,26 +4915,27 @@ static DRFLAC_INLINE drflac_bool32 drflac__read_and_decode_block_header(drflac_r drflac_bool32 drflac__read_streaminfo(drflac_read_proc onRead, void* pUserData, drflac_streaminfo* pStreamInfo) { - // min/max block size. drflac_uint32 blockSizes; + drflac_uint64 frameSizes = 0; + drflac_uint64 importantProps; + drflac_uint8 md5[16]; + + /* min/max block size. */ if (onRead(pUserData, &blockSizes, 4) != 4) { return DRFLAC_FALSE; } - // min/max frame size. - drflac_uint64 frameSizes = 0; + /* min/max frame size. */ if (onRead(pUserData, &frameSizes, 6) != 6) { return DRFLAC_FALSE; } - // Sample rate, channels, bits per sample and total sample count. - drflac_uint64 importantProps; + /* Sample rate, channels, bits per sample and total sample count. */ if (onRead(pUserData, &importantProps, 8) != 8) { return DRFLAC_FALSE; } - // MD5 - drflac_uint8 md5[16]; + /* MD5 */ if (onRead(pUserData, md5, sizeof(md5)) != sizeof(md5)) { return DRFLAC_FALSE; } @@ -3467,13 +4945,13 @@ drflac_bool32 drflac__read_streaminfo(drflac_read_proc onRead, void* pUserData, importantProps = drflac__be2host_64(importantProps); pStreamInfo->minBlockSize = (blockSizes & 0xFFFF0000) >> 16; - pStreamInfo->maxBlockSize = blockSizes & 0x0000FFFF; - pStreamInfo->minFrameSize = (drflac_uint32)((frameSizes & (drflac_uint64)0xFFFFFF0000000000) >> 40); - pStreamInfo->maxFrameSize = (drflac_uint32)((frameSizes & (drflac_uint64)0x000000FFFFFF0000) >> 16); - pStreamInfo->sampleRate = (drflac_uint32)((importantProps & (drflac_uint64)0xFFFFF00000000000) >> 44); - pStreamInfo->channels = (drflac_uint8 )((importantProps & (drflac_uint64)0x00000E0000000000) >> 41) + 1; - pStreamInfo->bitsPerSample = (drflac_uint8 )((importantProps & (drflac_uint64)0x000001F000000000) >> 36) + 1; - pStreamInfo->totalSampleCount = (importantProps & (drflac_uint64)0x0000000FFFFFFFFF) * pStreamInfo->channels; + pStreamInfo->maxBlockSize = (blockSizes & 0x0000FFFF); + pStreamInfo->minFrameSize = (drflac_uint32)((frameSizes & (((drflac_uint64)0x00FFFFFF << 16) << 24)) >> 40); + pStreamInfo->maxFrameSize = (drflac_uint32)((frameSizes & (((drflac_uint64)0x00FFFFFF << 16) << 0)) >> 16); + pStreamInfo->sampleRate = (drflac_uint32)((importantProps & (((drflac_uint64)0x000FFFFF << 16) << 28)) >> 44); + pStreamInfo->channels = (drflac_uint8 )((importantProps & (((drflac_uint64)0x0000000E << 16) << 24)) >> 41) + 1; + pStreamInfo->bitsPerSample = (drflac_uint8 )((importantProps & (((drflac_uint64)0x0000001F << 16) << 20)) >> 36) + 1; + pStreamInfo->totalSampleCount = ((importantProps & ((((drflac_uint64)0x0000000F << 16) << 16) | 0xFFFFFFFF))) * pStreamInfo->channels; drflac_copy_memory(pStreamInfo->md5, md5, sizeof(md5)); return DRFLAC_TRUE; @@ -3481,13 +4959,16 @@ drflac_bool32 drflac__read_streaminfo(drflac_read_proc onRead, void* pUserData, drflac_bool32 drflac__read_and_decode_metadata(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, void* pUserData, void* pUserDataMD, drflac_uint64* pFirstFramePos, drflac_uint64* pSeektablePos, drflac_uint32* pSeektableSize) { - // We want to keep track of the byte position in the stream of the seektable. At the time of calling this function we know that - // we'll be sitting on byte 42. + /* + We want to keep track of the byte position in the stream of the seektable. At the time of calling this function we know that + we'll be sitting on byte 42. + */ drflac_uint64 runningFilePos = 42; drflac_uint64 seektablePos = 0; drflac_uint32 seektableSize = 0; for (;;) { + drflac_metadata metadata; drflac_uint8 isLastBlock = 0; drflac_uint8 blockType; drflac_uint32 blockSize; @@ -3496,8 +4977,6 @@ drflac_bool32 drflac__read_and_decode_metadata(drflac_read_proc onRead, drflac_s } runningFilePos += 4; - - drflac_metadata metadata; metadata.type = blockType; metadata.pRawData = NULL; metadata.rawDataSize = 0; @@ -3506,6 +4985,10 @@ drflac_bool32 drflac__read_and_decode_metadata(drflac_read_proc onRead, drflac_s { case DRFLAC_METADATA_BLOCK_TYPE_APPLICATION: { + if (blockSize < 4) { + return DRFLAC_FALSE; + } + if (onMeta) { void* pRawData = DRFLAC_MALLOC(blockSize); if (pRawData == NULL) { @@ -3534,7 +5017,10 @@ drflac_bool32 drflac__read_and_decode_metadata(drflac_read_proc onRead, drflac_s seektableSize = blockSize; if (onMeta) { - void* pRawData = DRFLAC_MALLOC(blockSize); + drflac_uint32 iSeekpoint; + void* pRawData; + + pRawData = DRFLAC_MALLOC(blockSize); if (pRawData == NULL) { return DRFLAC_FALSE; } @@ -3549,8 +5035,8 @@ drflac_bool32 drflac__read_and_decode_metadata(drflac_read_proc onRead, drflac_s metadata.data.seektable.seekpointCount = blockSize/sizeof(drflac_seekpoint); metadata.data.seektable.pSeekpoints = (const drflac_seekpoint*)pRawData; - // Endian swap. - for (drflac_uint32 iSeekpoint = 0; iSeekpoint < metadata.data.seektable.seekpointCount; ++iSeekpoint) { + /* Endian swap. */ + for (iSeekpoint = 0; iSeekpoint < metadata.data.seektable.seekpointCount; ++iSeekpoint) { drflac_seekpoint* pSeekpoint = (drflac_seekpoint*)pRawData + iSeekpoint; pSeekpoint->firstSample = drflac__be2host_64(pSeekpoint->firstSample); pSeekpoint->frameOffset = drflac__be2host_64(pSeekpoint->frameOffset); @@ -3565,8 +5051,17 @@ drflac_bool32 drflac__read_and_decode_metadata(drflac_read_proc onRead, drflac_s case DRFLAC_METADATA_BLOCK_TYPE_VORBIS_COMMENT: { + if (blockSize < 8) { + return DRFLAC_FALSE; + } + if (onMeta) { - void* pRawData = DRFLAC_MALLOC(blockSize); + void* pRawData; + const char* pRunningData; + const char* pRunningDataEnd; + drflac_uint32 i; + + pRawData = DRFLAC_MALLOC(blockSize); if (pRawData == NULL) { return DRFLAC_FALSE; } @@ -3579,11 +5074,43 @@ drflac_bool32 drflac__read_and_decode_metadata(drflac_read_proc onRead, drflac_s metadata.pRawData = pRawData; metadata.rawDataSize = blockSize; - const char* pRunningData = (const char*)pRawData; - metadata.data.vorbis_comment.vendorLength = drflac__le2host_32(*(drflac_uint32*)pRunningData); pRunningData += 4; - metadata.data.vorbis_comment.vendor = pRunningData; pRunningData += metadata.data.vorbis_comment.vendorLength; - metadata.data.vorbis_comment.commentCount = drflac__le2host_32(*(drflac_uint32*)pRunningData); pRunningData += 4; - metadata.data.vorbis_comment.comments = pRunningData; + pRunningData = (const char*)pRawData; + pRunningDataEnd = (const char*)pRawData + blockSize; + + metadata.data.vorbis_comment.vendorLength = drflac__le2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4; + + /* Need space for the rest of the block */ + if ((pRunningDataEnd - pRunningData) - 4 < (drflac_int64)metadata.data.vorbis_comment.vendorLength) { /* <-- Note the order of operations to avoid overflow to a valid value */ + DRFLAC_FREE(pRawData); + return DRFLAC_FALSE; + } + metadata.data.vorbis_comment.vendor = pRunningData; pRunningData += metadata.data.vorbis_comment.vendorLength; + metadata.data.vorbis_comment.commentCount = drflac__le2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4; + + /* Need space for 'commentCount' comments after the block, which at minimum is a drflac_uint32 per comment */ + if ((pRunningDataEnd - pRunningData) / sizeof(drflac_uint32) < metadata.data.vorbis_comment.commentCount) { /* <-- Note the order of operations to avoid overflow to a valid value */ + DRFLAC_FREE(pRawData); + return DRFLAC_FALSE; + } + metadata.data.vorbis_comment.pComments = pRunningData; + + /* Check that the comments section is valid before passing it to the callback */ + for (i = 0; i < metadata.data.vorbis_comment.commentCount; ++i) { + drflac_uint32 commentLength; + + if (pRunningDataEnd - pRunningData < 4) { + DRFLAC_FREE(pRawData); + return DRFLAC_FALSE; + } + + commentLength = drflac__le2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4; + if (pRunningDataEnd - pRunningData < (drflac_int64)commentLength) { /* <-- Note the order of operations to avoid overflow to a valid value */ + DRFLAC_FREE(pRawData); + return DRFLAC_FALSE; + } + pRunningData += commentLength; + } + onMeta(pUserDataMD, &metadata); DRFLAC_FREE(pRawData); @@ -3592,8 +5119,18 @@ drflac_bool32 drflac__read_and_decode_metadata(drflac_read_proc onRead, drflac_s case DRFLAC_METADATA_BLOCK_TYPE_CUESHEET: { + if (blockSize < 396) { + return DRFLAC_FALSE; + } + if (onMeta) { - void* pRawData = DRFLAC_MALLOC(blockSize); + void* pRawData; + const char* pRunningData; + const char* pRunningDataEnd; + drflac_uint8 iTrack; + drflac_uint8 iIndex; + + pRawData = DRFLAC_MALLOC(blockSize); if (pRawData == NULL) { return DRFLAC_FALSE; } @@ -3606,12 +5143,42 @@ drflac_bool32 drflac__read_and_decode_metadata(drflac_read_proc onRead, drflac_s metadata.pRawData = pRawData; metadata.rawDataSize = blockSize; - const char* pRunningData = (const char*)pRawData; - drflac_copy_memory(metadata.data.cuesheet.catalog, pRunningData, 128); pRunningData += 128; - metadata.data.cuesheet.leadInSampleCount = drflac__be2host_64(*(drflac_uint64*)pRunningData); pRunningData += 4; - metadata.data.cuesheet.isCD = ((pRunningData[0] & 0x80) >> 7) != 0; pRunningData += 259; - metadata.data.cuesheet.trackCount = pRunningData[0]; pRunningData += 1; - metadata.data.cuesheet.pTrackData = (const drflac_uint8*)pRunningData; + pRunningData = (const char*)pRawData; + pRunningDataEnd = (const char*)pRawData + blockSize; + + drflac_copy_memory(metadata.data.cuesheet.catalog, pRunningData, 128); pRunningData += 128; + metadata.data.cuesheet.leadInSampleCount = drflac__be2host_64(*(const drflac_uint64*)pRunningData); pRunningData += 8; + metadata.data.cuesheet.isCD = (pRunningData[0] & 0x80) != 0; pRunningData += 259; + metadata.data.cuesheet.trackCount = pRunningData[0]; pRunningData += 1; + metadata.data.cuesheet.pTrackData = pRunningData; + + /* Check that the cuesheet tracks are valid before passing it to the callback */ + for (iTrack = 0; iTrack < metadata.data.cuesheet.trackCount; ++iTrack) { + drflac_uint8 indexCount; + drflac_uint32 indexPointSize; + + if (pRunningDataEnd - pRunningData < 36) { + DRFLAC_FREE(pRawData); + return DRFLAC_FALSE; + } + + /* Skip to the index point count */ + pRunningData += 35; + indexCount = pRunningData[0]; pRunningData += 1; + indexPointSize = indexCount * sizeof(drflac_cuesheet_track_index); + if (pRunningDataEnd - pRunningData < (drflac_int64)indexPointSize) { + DRFLAC_FREE(pRawData); + return DRFLAC_FALSE; + } + + /* Endian swap. */ + for (iIndex = 0; iIndex < indexCount; ++iIndex) { + drflac_cuesheet_track_index* pTrack = (drflac_cuesheet_track_index*)pRunningData; + pRunningData += sizeof(drflac_cuesheet_track_index); + pTrack->offset = drflac__be2host_64(pTrack->offset); + } + } + onMeta(pUserDataMD, &metadata); DRFLAC_FREE(pRawData); @@ -3620,8 +5187,16 @@ drflac_bool32 drflac__read_and_decode_metadata(drflac_read_proc onRead, drflac_s case DRFLAC_METADATA_BLOCK_TYPE_PICTURE: { + if (blockSize < 32) { + return DRFLAC_FALSE; + } + if (onMeta) { - void* pRawData = DRFLAC_MALLOC(blockSize); + void* pRawData; + const char* pRunningData; + const char* pRunningDataEnd; + + pRawData = DRFLAC_MALLOC(blockSize); if (pRawData == NULL) { return DRFLAC_FALSE; } @@ -3634,18 +5209,39 @@ drflac_bool32 drflac__read_and_decode_metadata(drflac_read_proc onRead, drflac_s metadata.pRawData = pRawData; metadata.rawDataSize = blockSize; - const char* pRunningData = (const char*)pRawData; - metadata.data.picture.type = drflac__be2host_32(*(drflac_uint32*)pRunningData); pRunningData += 4; - metadata.data.picture.mimeLength = drflac__be2host_32(*(drflac_uint32*)pRunningData); pRunningData += 4; - metadata.data.picture.mime = pRunningData; pRunningData += metadata.data.picture.mimeLength; - metadata.data.picture.descriptionLength = drflac__be2host_32(*(drflac_uint32*)pRunningData); pRunningData += 4; - metadata.data.picture.description = pRunningData; - metadata.data.picture.width = drflac__be2host_32(*(drflac_uint32*)pRunningData); pRunningData += 4; - metadata.data.picture.height = drflac__be2host_32(*(drflac_uint32*)pRunningData); pRunningData += 4; - metadata.data.picture.colorDepth = drflac__be2host_32(*(drflac_uint32*)pRunningData); pRunningData += 4; - metadata.data.picture.indexColorCount = drflac__be2host_32(*(drflac_uint32*)pRunningData); pRunningData += 4; - metadata.data.picture.pictureDataSize = drflac__be2host_32(*(drflac_uint32*)pRunningData); pRunningData += 4; - metadata.data.picture.pPictureData = (const drflac_uint8*)pRunningData; + pRunningData = (const char*)pRawData; + pRunningDataEnd = (const char*)pRawData + blockSize; + + metadata.data.picture.type = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4; + metadata.data.picture.mimeLength = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4; + + /* Need space for the rest of the block */ + if ((pRunningDataEnd - pRunningData) - 24 < (drflac_int64)metadata.data.picture.mimeLength) { /* <-- Note the order of operations to avoid overflow to a valid value */ + DRFLAC_FREE(pRawData); + return DRFLAC_FALSE; + } + metadata.data.picture.mime = pRunningData; pRunningData += metadata.data.picture.mimeLength; + metadata.data.picture.descriptionLength = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4; + + /* Need space for the rest of the block */ + if ((pRunningDataEnd - pRunningData) - 20 < (drflac_int64)metadata.data.picture.descriptionLength) { /* <-- Note the order of operations to avoid overflow to a valid value */ + DRFLAC_FREE(pRawData); + return DRFLAC_FALSE; + } + metadata.data.picture.description = pRunningData; pRunningData += metadata.data.picture.descriptionLength; + metadata.data.picture.width = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4; + metadata.data.picture.height = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4; + metadata.data.picture.colorDepth = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4; + metadata.data.picture.indexColorCount = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4; + metadata.data.picture.pictureDataSize = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4; + metadata.data.picture.pPictureData = (const drflac_uint8*)pRunningData; + + /* Need space for the picture after the block */ + if (pRunningDataEnd - pRunningData < (drflac_int64)metadata.data.picture.pictureDataSize) { /* <-- Note the order of operations to avoid overflow to a valid value */ + DRFLAC_FREE(pRawData); + return DRFLAC_FALSE; + } + onMeta(pUserDataMD, &metadata); DRFLAC_FREE(pRawData); @@ -3657,9 +5253,9 @@ drflac_bool32 drflac__read_and_decode_metadata(drflac_read_proc onRead, drflac_s if (onMeta) { metadata.data.padding.unused = 0; - // Padding doesn't have anything meaningful in it, so just skip over it, but make sure the caller is aware of it by firing the callback. + /* Padding doesn't have anything meaningful in it, so just skip over it, but make sure the caller is aware of it by firing the callback. */ if (!onSeek(pUserData, blockSize, drflac_seek_origin_current)) { - isLastBlock = DRFLAC_TRUE; // An error occurred while seeking. Attempt to recover by treating this as the last block which will in turn terminate the loop. + isLastBlock = DRFLAC_TRUE; /* An error occurred while seeking. Attempt to recover by treating this as the last block which will in turn terminate the loop. */ } else { onMeta(pUserDataMD, &metadata); } @@ -3668,18 +5264,20 @@ drflac_bool32 drflac__read_and_decode_metadata(drflac_read_proc onRead, drflac_s case DRFLAC_METADATA_BLOCK_TYPE_INVALID: { - // Invalid chunk. Just skip over this one. + /* Invalid chunk. Just skip over this one. */ if (onMeta) { if (!onSeek(pUserData, blockSize, drflac_seek_origin_current)) { - isLastBlock = DRFLAC_TRUE; // An error occurred while seeking. Attempt to recover by treating this as the last block which will in turn terminate the loop. + isLastBlock = DRFLAC_TRUE; /* An error occurred while seeking. Attempt to recover by treating this as the last block which will in turn terminate the loop. */ } } } break; default: { - // It's an unknown chunk, but not necessarily invalid. There's a chance more metadata blocks might be defined later on, so we - // can at the very least report the chunk to the application and let it look at the raw data. + /* + It's an unknown chunk, but not necessarily invalid. There's a chance more metadata blocks might be defined later on, so we + can at the very least report the chunk to the application and let it look at the raw data. + */ if (onMeta) { void* pRawData = DRFLAC_MALLOC(blockSize); if (pRawData == NULL) { @@ -3700,7 +5298,7 @@ drflac_bool32 drflac__read_and_decode_metadata(drflac_read_proc onRead, drflac_s } break; } - // If we're not handling metadata, just skip over the block. If we are, it will have been handled earlier in the switch statement above. + /* If we're not handling metadata, just skip over the block. If we are, it will have been handled earlier in the switch statement above. */ if (onMeta == NULL && blockSize > 0) { if (!onSeek(pUserData, blockSize, drflac_seek_origin_current)) { isLastBlock = DRFLAC_TRUE; @@ -3722,42 +5320,45 @@ drflac_bool32 drflac__read_and_decode_metadata(drflac_read_proc onRead, drflac_s drflac_bool32 drflac__init_private__native(drflac_init_info* pInit, drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, void* pUserData, void* pUserDataMD, drflac_bool32 relaxed) { - (void)onSeek; - - // Pre: The bit stream should be sitting just past the 4-byte id header. + /* Pre Condition: The bit stream should be sitting just past the 4-byte id header. */ - pInit->container = drflac_container_native; - - // The first metadata block should be the STREAMINFO block. drflac_uint8 isLastBlock; drflac_uint8 blockType; drflac_uint32 blockSize; + + (void)onSeek; + + pInit->container = drflac_container_native; + + /* The first metadata block should be the STREAMINFO block. */ if (!drflac__read_and_decode_block_header(onRead, pUserData, &isLastBlock, &blockType, &blockSize)) { return DRFLAC_FALSE; } if (blockType != DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO || blockSize != 34) { if (!relaxed) { - // We're opening in strict mode and the first block is not the STREAMINFO block. Error. + /* We're opening in strict mode and the first block is not the STREAMINFO block. Error. */ return DRFLAC_FALSE; } else { - // Relaxed mode. To open from here we need to just find the first frame and set the sample rate, etc. to whatever is defined - // for that frame. + /* + Relaxed mode. To open from here we need to just find the first frame and set the sample rate, etc. to whatever is defined + for that frame. + */ pInit->hasStreamInfoBlock = DRFLAC_FALSE; pInit->hasMetadataBlocks = DRFLAC_FALSE; - if (!drflac__read_next_frame_header(&pInit->bs, 0, &pInit->firstFrameHeader)) { - return DRFLAC_FALSE; // Couldn't find a frame. + if (!drflac__read_next_flac_frame_header(&pInit->bs, 0, &pInit->firstFrameHeader)) { + return DRFLAC_FALSE; /* Couldn't find a frame. */ } if (pInit->firstFrameHeader.bitsPerSample == 0) { - return DRFLAC_FALSE; // Failed to initialize because the first frame depends on the STREAMINFO block, which does not exist. + return DRFLAC_FALSE; /* Failed to initialize because the first frame depends on the STREAMINFO block, which does not exist. */ } pInit->sampleRate = pInit->firstFrameHeader.sampleRate; pInit->channels = drflac__get_channel_count_from_channel_assignment(pInit->firstFrameHeader.channelAssignment); pInit->bitsPerSample = pInit->firstFrameHeader.bitsPerSample; - pInit->maxBlockSize = 65535; // <-- See notes here: https://xiph.org/flac/format.html#metadata_block_streaminfo + pInit->maxBlockSize = 65535; /* <-- See notes here: https://xiph.org/flac/format.html#metadata_block_streaminfo */ return DRFLAC_TRUE; } } else { @@ -3771,8 +5372,8 @@ drflac_bool32 drflac__init_private__native(drflac_init_info* pInit, drflac_read_ pInit->channels = streaminfo.channels; pInit->bitsPerSample = streaminfo.bitsPerSample; pInit->totalSampleCount = streaminfo.totalSampleCount; - pInit->maxBlockSize = streaminfo.maxBlockSize; // Don't care about the min block size - only the max (used for determining the size of the memory allocation). - pInit->hasMetadataBlocks = !isLastBlock; + pInit->maxBlockSize = streaminfo.maxBlockSize; /* Don't care about the min block size - only the max (used for determining the size of the memory allocation). */ + pInit->hasMetadataBlocks = !isLastBlock; if (onMeta) { drflac_metadata metadata; @@ -3789,7 +5390,7 @@ drflac_bool32 drflac__init_private__native(drflac_init_info* pInit, drflac_read_ #ifndef DR_FLAC_NO_OGG #define DRFLAC_OGG_MAX_PAGE_SIZE 65307 -#define DRFLAC_OGG_CAPTURE_PATTERN_CRC32 1605413199 // CRC-32 of "OggS". +#define DRFLAC_OGG_CAPTURE_PATTERN_CRC32 1605413199 /* CRC-32 of "OggS". */ typedef enum { @@ -3797,7 +5398,7 @@ typedef enum drflac_ogg_fail_on_crc_mismatch } drflac_ogg_crc_mismatch_recovery; - +#ifndef DR_FLAC_NO_CRC static drflac_uint32 drflac__crc32_table[] = { 0x00000000L, 0x04C11DB7L, 0x09823B6EL, 0x0D4326D9L, 0x130476DCL, 0x17C56B6BL, 0x1A864DB2L, 0x1E475005L, @@ -3864,6 +5465,7 @@ static drflac_uint32 drflac__crc32_table[] = { 0xAFB010B1L, 0xAB710D06L, 0xA6322BDFL, 0xA2F33668L, 0xBCB4666DL, 0xB8757BDAL, 0xB5365D03L, 0xB1F740B4L }; +#endif static DRFLAC_INLINE drflac_uint32 drflac_crc32_byte(drflac_uint32 crc32, drflac_uint8 data) { @@ -3895,8 +5497,9 @@ static DRFLAC_INLINE drflac_uint32 drflac_crc32_uint64(drflac_uint32 crc32, drfl static DRFLAC_INLINE drflac_uint32 drflac_crc32_buffer(drflac_uint32 crc32, drflac_uint8* pData, drflac_uint32 dataSize) { - // This can be optimized. - for (drflac_uint32 i = 0; i < dataSize; ++i) { + /* This can be optimized. */ + drflac_uint32 i; + for (i = 0; i < dataSize; ++i) { crc32 = drflac_crc32_byte(crc32, pData[i]); } return crc32; @@ -3916,7 +5519,9 @@ static DRFLAC_INLINE drflac_uint32 drflac_ogg__get_page_header_size(drflac_ogg_p static DRFLAC_INLINE drflac_uint32 drflac_ogg__get_page_body_size(drflac_ogg_page_header* pHeader) { drflac_uint32 pageBodySize = 0; - for (int i = 0; i < pHeader->segmentCount; ++i) { + int i; + + for (i = 0; i < pHeader->segmentCount; ++i) { pageBodySize += pHeader->segmentTable[i]; } @@ -3925,9 +5530,11 @@ static DRFLAC_INLINE drflac_uint32 drflac_ogg__get_page_body_size(drflac_ogg_pag drflac_result drflac_ogg__read_page_header_after_capture_pattern(drflac_read_proc onRead, void* pUserData, drflac_ogg_page_header* pHeader, drflac_uint32* pBytesRead, drflac_uint32* pCRC32) { + drflac_uint8 data[23]; + drflac_uint32 i; + drflac_assert(*pCRC32 == DRFLAC_OGG_CAPTURE_PATTERN_CRC32); - drflac_uint8 data[23]; if (onRead(pUserData, data, 23) != 23) { return DRFLAC_END_OF_STREAM; } @@ -3941,13 +5548,12 @@ drflac_result drflac_ogg__read_page_header_after_capture_pattern(drflac_read_pro drflac_copy_memory(&pHeader->checksum, &data[18], 4); pHeader->segmentCount = data[22]; - // Calculate the CRC. Note that for the calculation the checksum part of the page needs to be set to 0. + /* Calculate the CRC. Note that for the calculation the checksum part of the page needs to be set to 0. */ data[18] = 0; data[19] = 0; data[20] = 0; data[21] = 0; - drflac_uint32 i; for (i = 0; i < 23; ++i) { *pCRC32 = drflac_crc32_byte(*pCRC32, data[i]); } @@ -3967,20 +5573,23 @@ drflac_result drflac_ogg__read_page_header_after_capture_pattern(drflac_read_pro drflac_result drflac_ogg__read_page_header(drflac_read_proc onRead, void* pUserData, drflac_ogg_page_header* pHeader, drflac_uint32* pBytesRead, drflac_uint32* pCRC32) { + drflac_uint8 id[4]; + *pBytesRead = 0; - drflac_uint8 id[4]; if (onRead(pUserData, id, 4) != 4) { return DRFLAC_END_OF_STREAM; } *pBytesRead += 4; - // We need to read byte-by-byte until we find the OggS capture pattern. + /* We need to read byte-by-byte until we find the OggS capture pattern. */ for (;;) { if (drflac_ogg__is_capture_pattern(id)) { + drflac_result result; + *pCRC32 = DRFLAC_OGG_CAPTURE_PATTERN_CRC32; - drflac_result result = drflac_ogg__read_page_header_after_capture_pattern(onRead, pUserData, pHeader, pBytesRead, pCRC32); + result = drflac_ogg__read_page_header_after_capture_pattern(onRead, pUserData, pHeader, pBytesRead, pCRC32); if (result == DRFLAC_SUCCESS) { return DRFLAC_SUCCESS; } else { @@ -3991,7 +5600,7 @@ drflac_result drflac_ogg__read_page_header(drflac_read_proc onRead, void* pUserD } } } else { - // The first 4 bytes did not equal the capture pattern. Read the next byte and try again. + /* The first 4 bytes did not equal the capture pattern. Read the next byte and try again. */ id[0] = id[1]; id[1] = id[2]; id[2] = id[3]; @@ -4004,25 +5613,27 @@ drflac_result drflac_ogg__read_page_header(drflac_read_proc onRead, void* pUserD } -// The main part of the Ogg encapsulation is the conversion from the physical Ogg bitstream to the native FLAC bitstream. It works -// in three general stages: Ogg Physical Bitstream -> Ogg/FLAC Logical Bitstream -> FLAC Native Bitstream. dr_flac is designed -// in such a way that the core sections assume everything is delivered in native format. Therefore, for each encapsulation type -// dr_flac is supporting there needs to be a layer sitting on top of the onRead and onSeek callbacks that ensures the bits read from -// the physical Ogg bitstream are converted and delivered in native FLAC format. +/* +The main part of the Ogg encapsulation is the conversion from the physical Ogg bitstream to the native FLAC bitstream. It works +in three general stages: Ogg Physical Bitstream -> Ogg/FLAC Logical Bitstream -> FLAC Native Bitstream. dr_flac is designed +in such a way that the core sections assume everything is delivered in native format. Therefore, for each encapsulation type +dr_flac is supporting there needs to be a layer sitting on top of the onRead and onSeek callbacks that ensures the bits read from +the physical Ogg bitstream are converted and delivered in native FLAC format. +*/ typedef struct { - drflac_read_proc onRead; // The original onRead callback from drflac_open() and family. - drflac_seek_proc onSeek; // The original onSeek callback from drflac_open() and family. - void* pUserData; // The user data passed on onRead and onSeek. This is the user data that was passed on drflac_open() and family. - drflac_uint64 currentBytePos; // The position of the byte we are sitting on in the physical byte stream. Used for efficient seeking. - drflac_uint64 firstBytePos; // The position of the first byte in the physical bitstream. Points to the start of the "OggS" identifier of the FLAC bos page. - drflac_uint32 serialNumber; // The serial number of the FLAC audio pages. This is determined by the initial header page that was read during initialization. - drflac_ogg_page_header bosPageHeader; // Used for seeking. + drflac_read_proc onRead; /* The original onRead callback from drflac_open() and family. */ + drflac_seek_proc onSeek; /* The original onSeek callback from drflac_open() and family. */ + void* pUserData; /* The user data passed on onRead and onSeek. This is the user data that was passed on drflac_open() and family. */ + drflac_uint64 currentBytePos; /* The position of the byte we are sitting on in the physical byte stream. Used for efficient seeking. */ + drflac_uint64 firstBytePos; /* The position of the first byte in the physical bitstream. Points to the start of the "OggS" identifier of the FLAC bos page. */ + drflac_uint32 serialNumber; /* The serial number of the FLAC audio pages. This is determined by the initial header page that was read during initialization. */ + drflac_ogg_page_header bosPageHeader; /* Used for seeking. */ drflac_ogg_page_header currentPageHeader; drflac_uint32 bytesRemainingInPage; drflac_uint32 pageDataSize; drflac_uint8 pageData[DRFLAC_OGG_MAX_PAGE_SIZE]; -} drflac_oggbs; // oggbs = Ogg Bitstream +} drflac_oggbs; /* oggbs = Ogg Bitstream */ static size_t drflac_oggbs__read_physical(drflac_oggbs* oggbs, void* bufferOut, size_t bytesToRead) { @@ -4059,7 +5670,7 @@ static drflac_bool32 drflac_oggbs__seek_physical(drflac_oggbs* oggbs, drflac_uin offset -= 0x7FFFFFFF; } - if (!oggbs->onSeek(oggbs->pUserData, (int)offset, drflac_seek_origin_current)) { // <-- Safe cast thanks to the loop above. + if (!oggbs->onSeek(oggbs->pUserData, (int)offset, drflac_seek_origin_current)) { /* <-- Safe cast thanks to the loop above. */ return DRFLAC_FALSE; } oggbs->currentBytePos += offset; @@ -4074,18 +5685,23 @@ static drflac_bool32 drflac_oggbs__goto_next_page(drflac_oggbs* oggbs, drflac_og for (;;) { drflac_uint32 crc32 = 0; drflac_uint32 bytesRead; + drflac_uint32 pageBodySize; +#ifndef DR_FLAC_NO_CRC + drflac_uint32 actualCRC32; +#endif + if (drflac_ogg__read_page_header(oggbs->onRead, oggbs->pUserData, &header, &bytesRead, &crc32) != DRFLAC_SUCCESS) { return DRFLAC_FALSE; } oggbs->currentBytePos += bytesRead; - drflac_uint32 pageBodySize = drflac_ogg__get_page_body_size(&header); + pageBodySize = drflac_ogg__get_page_body_size(&header); if (pageBodySize > DRFLAC_OGG_MAX_PAGE_SIZE) { - continue; // Invalid page size. Assume it's corrupted and just move to the next page. + continue; /* Invalid page size. Assume it's corrupted and just move to the next page. */ } if (header.serialNumber != oggbs->serialNumber) { - // It's not a FLAC page. Skip it. + /* It's not a FLAC page. Skip it. */ if (pageBodySize > 0 && !drflac_oggbs__seek_physical(oggbs, pageBodySize, drflac_seek_origin_current)) { return DRFLAC_FALSE; } @@ -4093,27 +5709,29 @@ static drflac_bool32 drflac_oggbs__goto_next_page(drflac_oggbs* oggbs, drflac_og } - // We need to read the entire page and then do a CRC check on it. If there's a CRC mismatch we need to skip this page. + /* We need to read the entire page and then do a CRC check on it. If there's a CRC mismatch we need to skip this page. */ if (drflac_oggbs__read_physical(oggbs, oggbs->pageData, pageBodySize) != pageBodySize) { return DRFLAC_FALSE; } oggbs->pageDataSize = pageBodySize; #ifndef DR_FLAC_NO_CRC - drflac_uint32 actualCRC32 = drflac_crc32_buffer(crc32, oggbs->pageData, oggbs->pageDataSize); + actualCRC32 = drflac_crc32_buffer(crc32, oggbs->pageData, oggbs->pageDataSize); if (actualCRC32 != header.checksum) { if (recoveryMethod == drflac_ogg_recover_on_crc_mismatch) { - continue; // CRC mismatch. Skip this page. + continue; /* CRC mismatch. Skip this page. */ } else { - // Even though we are failing on a CRC mismatch, we still want our stream to be in a good state. Therefore we - // go to the next valid page to ensure we're in a good state, but return false to let the caller know that the - // seek did not fully complete. + /* + Even though we are failing on a CRC mismatch, we still want our stream to be in a good state. Therefore we + go to the next valid page to ensure we're in a good state, but return false to let the caller know that the + seek did not fully complete. + */ drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch); return DRFLAC_FALSE; } } #else - (void)recoveryMethod; // <-- Silence a warning. + (void)recoveryMethod; /* <-- Silence a warning. */ #endif oggbs->currentPageHeader = header; @@ -4122,7 +5740,7 @@ static drflac_bool32 drflac_oggbs__goto_next_page(drflac_oggbs* oggbs, drflac_og } } -// Function below is unused at the moment, but I might be re-adding it later. +/* Function below is unused at the moment, but I might be re-adding it later. */ #if 0 static drflac_uint8 drflac_oggbs__get_current_segment_index(drflac_oggbs* oggbs, drflac_uint8* pBytesRemainingInSeg) { @@ -4145,7 +5763,7 @@ static drflac_uint8 drflac_oggbs__get_current_segment_index(drflac_oggbs* oggbs, static drflac_bool32 drflac_oggbs__seek_to_next_packet(drflac_oggbs* oggbs) { - // The current packet ends when we get to the segment with a lacing value of < 255 which is not at the end of a page. + /* The current packet ends when we get to the segment with a lacing value of < 255 which is not at the end of a page. */ for (;;) { drflac_bool32 atEndOfPage = DRFLAC_FALSE; @@ -4166,24 +5784,28 @@ static drflac_bool32 drflac_oggbs__seek_to_next_packet(drflac_oggbs* oggbs) bytesToEndOfPacketOrPage += segmentSize; } - // At this point we will have found either the packet or the end of the page. If were at the end of the page we'll - // want to load the next page and keep searching for the end of the packet. + /* + At this point we will have found either the packet or the end of the page. If were at the end of the page we'll + want to load the next page and keep searching for the end of the packet. + */ drflac_oggbs__seek_physical(oggbs, bytesToEndOfPacketOrPage, drflac_seek_origin_current); oggbs->bytesRemainingInPage -= bytesToEndOfPacketOrPage; if (atEndOfPage) { - // We're potentially at the next packet, but we need to check the next page first to be sure because the packet may - // straddle pages. + /* + We're potentially at the next packet, but we need to check the next page first to be sure because the packet may + straddle pages. + */ if (!drflac_oggbs__goto_next_page(oggbs)) { return DRFLAC_FALSE; } - // If it's a fresh packet it most likely means we're at the next packet. + /* If it's a fresh packet it most likely means we're at the next packet. */ if ((oggbs->currentPageHeader.headerType & 0x01) == 0) { return DRFLAC_TRUE; } } else { - // We're at the next packet. + /* We're at the next packet. */ return DRFLAC_TRUE; } } @@ -4191,9 +5813,9 @@ static drflac_bool32 drflac_oggbs__seek_to_next_packet(drflac_oggbs* oggbs) static drflac_bool32 drflac_oggbs__seek_to_next_frame(drflac_oggbs* oggbs) { - // The bitstream should be sitting on the first byte just after the header of the frame. + /* The bitstream should be sitting on the first byte just after the header of the frame. */ - // What we're actually doing here is seeking to the start of the next packet. + /* What we're actually doing here is seeking to the start of the next packet. */ return drflac_oggbs__seek_to_next_packet(oggbs); } #endif @@ -4201,12 +5823,13 @@ static drflac_bool32 drflac_oggbs__seek_to_next_frame(drflac_oggbs* oggbs) static size_t drflac__on_read_ogg(void* pUserData, void* bufferOut, size_t bytesToRead) { drflac_oggbs* oggbs = (drflac_oggbs*)pUserData; - drflac_assert(oggbs != NULL); - drflac_uint8* pRunningBufferOut = (drflac_uint8*)bufferOut; - - // Reading is done page-by-page. If we've run out of bytes in the page we need to move to the next one. size_t bytesRead = 0; + + drflac_assert(oggbs != NULL); + drflac_assert(pRunningBufferOut != NULL); + + /* Reading is done page-by-page. If we've run out of bytes in the page we need to move to the next one. */ while (bytesRead < bytesToRead) { size_t bytesRemainingToRead = bytesToRead - bytesRead; @@ -4217,7 +5840,7 @@ static size_t drflac__on_read_ogg(void* pUserData, void* bufferOut, size_t bytes break; } - // If we get here it means some of the requested data is contained in the next pages. + /* If we get here it means some of the requested data is contained in the next pages. */ if (oggbs->bytesRemainingInPage > 0) { drflac_copy_memory(pRunningBufferOut, oggbs->pageData + (oggbs->pageDataSize - oggbs->bytesRemainingInPage), oggbs->bytesRemainingInPage); bytesRead += oggbs->bytesRemainingInPage; @@ -4227,7 +5850,7 @@ static size_t drflac__on_read_ogg(void* pUserData, void* bufferOut, size_t bytes drflac_assert(bytesRemainingToRead > 0); if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch)) { - break; // Failed to go to the next page. Might have simply hit the end of the stream. + break; /* Failed to go to the next page. Might have simply hit the end of the stream. */ } } @@ -4237,10 +5860,12 @@ static size_t drflac__on_read_ogg(void* pUserData, void* bufferOut, size_t bytes static drflac_bool32 drflac__on_seek_ogg(void* pUserData, int offset, drflac_seek_origin origin) { drflac_oggbs* oggbs = (drflac_oggbs*)pUserData; + int bytesSeeked = 0; + drflac_assert(oggbs != NULL); - drflac_assert(offset > 0 || (offset == 0 && origin == drflac_seek_origin_start)); + drflac_assert(offset >= 0); /* <-- Never seek backwards. */ - // Seeking is always forward which makes things a lot simpler. + /* Seeking is always forward which makes things a lot simpler. */ if (origin == drflac_seek_origin_start) { if (!drflac_oggbs__seek_physical(oggbs, (int)oggbs->firstBytePos, drflac_seek_origin_start)) { return DRFLAC_FALSE; @@ -4253,10 +5878,8 @@ static drflac_bool32 drflac__on_seek_ogg(void* pUserData, int offset, drflac_see return drflac__on_seek_ogg(pUserData, offset, drflac_seek_origin_current); } - drflac_assert(origin == drflac_seek_origin_current); - int bytesSeeked = 0; while (bytesSeeked < offset) { int bytesRemainingToSeek = offset - bytesSeeked; drflac_assert(bytesRemainingToSeek >= 0); @@ -4267,7 +5890,7 @@ static drflac_bool32 drflac__on_seek_ogg(void* pUserData, int offset, drflac_see break; } - // If we get here it means some of the requested data is contained in the next pages. + /* If we get here it means some of the requested data is contained in the next pages. */ if (oggbs->bytesRemainingInPage > 0) { bytesSeeked += (int)oggbs->bytesRemainingInPage; oggbs->bytesRemainingInPage = 0; @@ -4275,7 +5898,7 @@ static drflac_bool32 drflac__on_seek_ogg(void* pUserData, int offset, drflac_see drflac_assert(bytesRemainingToSeek > 0); if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_fail_on_crc_mismatch)) { - // Failed to go to the next page. We either hit the end of the stream or had a CRC mismatch. + /* Failed to go to the next page. We either hit the end of the stream or had a CRC mismatch. */ return DRFLAC_FALSE; } } @@ -4286,38 +5909,45 @@ static drflac_bool32 drflac__on_seek_ogg(void* pUserData, int offset, drflac_see drflac_bool32 drflac_ogg__seek_to_sample(drflac* pFlac, drflac_uint64 sampleIndex) { drflac_oggbs* oggbs = (drflac_oggbs*)pFlac->_oggbs; + drflac_uint64 originalBytePos; + drflac_uint64 runningGranulePosition; + drflac_uint64 runningFrameBytePos; + drflac_uint64 runningSampleCount; + + drflac_assert(oggbs != NULL); - drflac_uint64 originalBytePos = oggbs->currentBytePos; // For recovery. + originalBytePos = oggbs->currentBytePos; /* For recovery. */ - // First seek to the first frame. + /* First seek to the first frame. */ if (!drflac__seek_to_byte(&pFlac->bs, pFlac->firstFramePos)) { return DRFLAC_FALSE; } oggbs->bytesRemainingInPage = 0; - drflac_uint64 runningGranulePosition = 0; - drflac_uint64 runningFrameBytePos = oggbs->currentBytePos; // <-- Points to the OggS identifier. + runningGranulePosition = 0; + runningFrameBytePos = oggbs->currentBytePos; /* <-- Points to the OggS identifier. */ for (;;) { if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch)) { drflac_oggbs__seek_physical(oggbs, originalBytePos, drflac_seek_origin_start); - return DRFLAC_FALSE; // Never did find that sample... + return DRFLAC_FALSE; /* Never did find that sample... */ } runningFrameBytePos = oggbs->currentBytePos - drflac_ogg__get_page_header_size(&oggbs->currentPageHeader) - oggbs->pageDataSize; if (oggbs->currentPageHeader.granulePosition*pFlac->channels >= sampleIndex) { - break; // The sample is somewhere in the previous page. + break; /* The sample is somewhere in the previous page. */ } - - // At this point we know the sample is not in the previous page. It could possibly be in this page. For simplicity we - // disregard any pages that do not begin a fresh packet. - if ((oggbs->currentPageHeader.headerType & 0x01) == 0) { // <-- Is it a fresh page? + /* + At this point we know the sample is not in the previous page. It could possibly be in this page. For simplicity we + disregard any pages that do not begin a fresh packet. + */ + if ((oggbs->currentPageHeader.headerType & 0x01) == 0) { /* <-- Is it a fresh page? */ if (oggbs->currentPageHeader.segmentTable[0] >= 2) { drflac_uint8 firstBytesInPage[2]; firstBytesInPage[0] = oggbs->pageData[0]; firstBytesInPage[1] = oggbs->pageData[1]; - if ((firstBytesInPage[0] == 0xFF) && (firstBytesInPage[1] & 0xFC) == 0xF8) { // <-- Does the page begin with a frame's sync code? + if ((firstBytesInPage[0] == 0xFF) && (firstBytesInPage[1] & 0xFC) == 0xF8) { /* <-- Does the page begin with a frame's sync code? */ runningGranulePosition = oggbs->currentPageHeader.granulePosition*pFlac->channels; } @@ -4326,11 +5956,12 @@ drflac_bool32 drflac_ogg__seek_to_sample(drflac* pFlac, drflac_uint64 sampleInde } } - - // We found the page that that is closest to the sample, so now we need to find it. The first thing to do is seek to the - // start of that page. In the loop above we checked that it was a fresh page which means this page is also the start of - // a new frame. This property means that after we've seeked to the page we can immediately start looping over frames until - // we find the one containing the target sample. + /* + We found the page that that is closest to the sample, so now we need to find it. The first thing to do is seek to the + start of that page. In the loop above we checked that it was a fresh page which means this page is also the start of + a new frame. This property means that after we've seeked to the page we can immediately start looping over frames until + we find the one containing the target sample. + */ if (!drflac_oggbs__seek_physical(oggbs, runningFrameBytePos, drflac_seek_origin_start)) { return DRFLAC_FALSE; } @@ -4338,66 +5969,75 @@ drflac_bool32 drflac_ogg__seek_to_sample(drflac* pFlac, drflac_uint64 sampleInde return DRFLAC_FALSE; } - - // At this point we'll be sitting on the first byte of the frame header of the first frame in the page. We just keep - // looping over these frames until we find the one containing the sample we're after. - drflac_uint64 runningSampleCount = runningGranulePosition; + /* + At this point we'll be sitting on the first byte of the frame header of the first frame in the page. We just keep + looping over these frames until we find the one containing the sample we're after. + */ + runningSampleCount = runningGranulePosition; for (;;) { - // There are two ways to find the sample and seek past irrelevant frames: - // 1) Use the native FLAC decoder. - // 2) Use Ogg's framing system. - // - // Both of these options have their own pros and cons. Using the native FLAC decoder is slower because it needs to - // do a full decode of the frame. Using Ogg's framing system is faster, but more complicated and involves some code - // duplication for the decoding of frame headers. - // - // Another thing to consider is that using the Ogg framing system will perform direct seeking of the physical Ogg - // bitstream. This is important to consider because it means we cannot read data from the drflac_bs object using the - // standard drflac__*() APIs because that will read in extra data for its own internal caching which in turn breaks - // the positioning of the read pointer of the physical Ogg bitstream. Therefore, anything that would normally be read - // using the native FLAC decoding APIs, such as drflac__read_next_frame_header(), need to be re-implemented so as to - // avoid the use of the drflac_bs object. - // - // Considering these issues, I have decided to use the slower native FLAC decoding method for the following reasons: - // 1) Seeking is already partially accelerated using Ogg's paging system in the code block above. - // 2) Seeking in an Ogg encapsulated FLAC stream is probably quite uncommon. - // 3) Simplicity. - if (!drflac__read_next_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFrame.header)) { + /* + There are two ways to find the sample and seek past irrelevant frames: + 1) Use the native FLAC decoder. + 2) Use Ogg's framing system. + + Both of these options have their own pros and cons. Using the native FLAC decoder is slower because it needs to + do a full decode of the frame. Using Ogg's framing system is faster, but more complicated and involves some code + duplication for the decoding of frame headers. + + Another thing to consider is that using the Ogg framing system will perform direct seeking of the physical Ogg + bitstream. This is important to consider because it means we cannot read data from the drflac_bs object using the + standard drflac__*() APIs because that will read in extra data for its own internal caching which in turn breaks + the positioning of the read pointer of the physical Ogg bitstream. Therefore, anything that would normally be read + using the native FLAC decoding APIs, such as drflac__read_next_flac_frame_header(), need to be re-implemented so as to + avoid the use of the drflac_bs object. + + Considering these issues, I have decided to use the slower native FLAC decoding method for the following reasons: + 1) Seeking is already partially accelerated using Ogg's paging system in the code block above. + 2) Seeking in an Ogg encapsulated FLAC stream is probably quite uncommon. + 3) Simplicity. + */ + drflac_uint64 firstSampleInFrame = 0; + drflac_uint64 lastSampleInFrame = 0; + drflac_uint64 sampleCountInThisFrame; + + if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFrame.header)) { return DRFLAC_FALSE; } - drflac_uint64 firstSampleInFrame = 0; - drflac_uint64 lastSampleInFrame = 0; drflac__get_current_frame_sample_range(pFlac, &firstSampleInFrame, &lastSampleInFrame); - drflac_uint64 sampleCountInThisFrame = (lastSampleInFrame - firstSampleInFrame) + 1; + sampleCountInThisFrame = (lastSampleInFrame - firstSampleInFrame) + 1; if (sampleIndex < (runningSampleCount + sampleCountInThisFrame)) { - // The sample should be in this frame. We need to fully decode it, however if it's an invalid frame (a CRC mismatch), we need to pretend - // it never existed and keep iterating. - drflac_result result = drflac__decode_frame(pFlac); + /* + The sample should be in this frame. We need to fully decode it, however if it's an invalid frame (a CRC mismatch), we need to pretend + it never existed and keep iterating. + */ + drflac_result result = drflac__decode_flac_frame(pFlac); if (result == DRFLAC_SUCCESS) { - // The frame is valid. We just need to skip over some samples to ensure it's sample-exact. - drflac_uint64 samplesToDecode = (size_t)(sampleIndex - runningSampleCount); // <-- Safe cast because the maximum number of samples in a frame is 65535. + /* The frame is valid. We just need to skip over some samples to ensure it's sample-exact. */ + drflac_uint64 samplesToDecode = (size_t)(sampleIndex - runningSampleCount); /* <-- Safe cast because the maximum number of samples in a frame is 65535. */ if (samplesToDecode == 0) { return DRFLAC_TRUE; } - return drflac_read_s32(pFlac, samplesToDecode, NULL) != 0; // <-- If this fails, something bad has happened (it should never fail). + return drflac__seek_forward_by_samples(pFlac, samplesToDecode) == samplesToDecode; /* <-- If this fails, something bad has happened (it should never fail). */ } else { if (result == DRFLAC_CRC_MISMATCH) { - continue; // CRC mismatch. Pretend this frame never existed. + continue; /* CRC mismatch. Pretend this frame never existed. */ } else { return DRFLAC_FALSE; } } } else { - // It's not in this frame. We need to seek past the frame, but check if there was a CRC mismatch. If so, we pretend this - // frame never existed and leave the running sample count untouched. - drflac_result result = drflac__seek_to_next_frame(pFlac); + /* + It's not in this frame. We need to seek past the frame, but check if there was a CRC mismatch. If so, we pretend this + frame never existed and leave the running sample count untouched. + */ + drflac_result result = drflac__seek_to_next_flac_frame(pFlac); if (result == DRFLAC_SUCCESS) { runningSampleCount += sampleCountInThisFrame; } else { if (result == DRFLAC_CRC_MISMATCH) { - continue; // CRC mismatch. Pretend this frame never existed. + continue; /* CRC mismatch. Pretend this frame never existed. */ } else { return DRFLAC_FALSE; } @@ -4409,45 +6049,48 @@ drflac_bool32 drflac_ogg__seek_to_sample(drflac* pFlac, drflac_uint64 sampleInde drflac_bool32 drflac__init_private__ogg(drflac_init_info* pInit, drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, void* pUserData, void* pUserDataMD, drflac_bool32 relaxed) { - // Pre: The bit stream should be sitting just past the 4-byte OggS capture pattern. + drflac_ogg_page_header header; + drflac_uint32 crc32 = DRFLAC_OGG_CAPTURE_PATTERN_CRC32; + drflac_uint32 bytesRead = 0; + + /* Pre Condition: The bit stream should be sitting just past the 4-byte OggS capture pattern. */ (void)relaxed; pInit->container = drflac_container_ogg; pInit->oggFirstBytePos = 0; - // We'll get here if the first 4 bytes of the stream were the OggS capture pattern, however it doesn't necessarily mean the - // stream includes FLAC encoded audio. To check for this we need to scan the beginning-of-stream page markers and check if - // any match the FLAC specification. Important to keep in mind that the stream may be multiplexed. - drflac_ogg_page_header header; - - drflac_uint32 crc32 = DRFLAC_OGG_CAPTURE_PATTERN_CRC32; - drflac_uint32 bytesRead = 0; + /* + We'll get here if the first 4 bytes of the stream were the OggS capture pattern, however it doesn't necessarily mean the + stream includes FLAC encoded audio. To check for this we need to scan the beginning-of-stream page markers and check if + any match the FLAC specification. Important to keep in mind that the stream may be multiplexed. + */ if (drflac_ogg__read_page_header_after_capture_pattern(onRead, pUserData, &header, &bytesRead, &crc32) != DRFLAC_SUCCESS) { return DRFLAC_FALSE; } pInit->runningFilePos += bytesRead; for (;;) { - // Break if we're past the beginning of stream page. + int pageBodySize; + + /* Break if we're past the beginning of stream page. */ if ((header.headerType & 0x02) == 0) { return DRFLAC_FALSE; } - - // Check if it's a FLAC header. - int pageBodySize = drflac_ogg__get_page_body_size(&header); - if (pageBodySize == 51) { // 51 = the lacing value of the FLAC header packet. - // It could be a FLAC page... + /* Check if it's a FLAC header. */ + pageBodySize = drflac_ogg__get_page_body_size(&header); + if (pageBodySize == 51) { /* 51 = the lacing value of the FLAC header packet. */ + /* It could be a FLAC page... */ drflac_uint32 bytesRemainingInPage = pageBodySize; - drflac_uint8 packetType; + if (onRead(pUserData, &packetType, 1) != 1) { return DRFLAC_FALSE; } bytesRemainingInPage -= 1; if (packetType == 0x7F) { - // Increasingly more likely to be a FLAC page... + /* Increasingly more likely to be a FLAC page... */ drflac_uint8 sig[4]; if (onRead(pUserData, sig, 4) != 4) { return DRFLAC_FALSE; @@ -4455,29 +6098,32 @@ drflac_bool32 drflac__init_private__ogg(drflac_init_info* pInit, drflac_read_pro bytesRemainingInPage -= 4; if (sig[0] == 'F' && sig[1] == 'L' && sig[2] == 'A' && sig[3] == 'C') { - // Almost certainly a FLAC page... + /* Almost certainly a FLAC page... */ drflac_uint8 mappingVersion[2]; if (onRead(pUserData, mappingVersion, 2) != 2) { return DRFLAC_FALSE; } if (mappingVersion[0] != 1) { - return DRFLAC_FALSE; // Only supporting version 1.x of the Ogg mapping. + return DRFLAC_FALSE; /* Only supporting version 1.x of the Ogg mapping. */ } - // The next 2 bytes are the non-audio packets, not including this one. We don't care about this because we're going to - // be handling it in a generic way based on the serial number and packet types. + /* + The next 2 bytes are the non-audio packets, not including this one. We don't care about this because we're going to + be handling it in a generic way based on the serial number and packet types. + */ if (!onSeek(pUserData, 2, drflac_seek_origin_current)) { return DRFLAC_FALSE; } - // Expecting the native FLAC signature "fLaC". + /* Expecting the native FLAC signature "fLaC". */ if (onRead(pUserData, sig, 4) != 4) { return DRFLAC_FALSE; } if (sig[0] == 'f' && sig[1] == 'L' && sig[2] == 'a' && sig[3] == 'C') { - // The remaining data in the page should be the STREAMINFO block. + /* The remaining data in the page should be the STREAMINFO block. */ + drflac_streaminfo streaminfo; drflac_uint8 isLastBlock; drflac_uint8 blockType; drflac_uint32 blockSize; @@ -4486,12 +6132,11 @@ drflac_bool32 drflac__init_private__ogg(drflac_init_info* pInit, drflac_read_pro } if (blockType != DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO || blockSize != 34) { - return DRFLAC_FALSE; // Invalid block type. First block must be the STREAMINFO block. + return DRFLAC_FALSE; /* Invalid block type. First block must be the STREAMINFO block. */ } - drflac_streaminfo streaminfo; if (drflac__read_streaminfo(onRead, pUserData, &streaminfo)) { - // Success! + /* Success! */ pInit->hasStreamInfoBlock = DRFLAC_TRUE; pInit->sampleRate = streaminfo.sampleRate; pInit->channels = streaminfo.channels; @@ -4510,26 +6155,26 @@ drflac_bool32 drflac__init_private__ogg(drflac_init_info* pInit, drflac_read_pro } pInit->runningFilePos += pageBodySize; - pInit->oggFirstBytePos = pInit->runningFilePos - 79; // Subtracting 79 will place us right on top of the "OggS" identifier of the FLAC bos page. + pInit->oggFirstBytePos = pInit->runningFilePos - 79; /* Subtracting 79 will place us right on top of the "OggS" identifier of the FLAC bos page. */ pInit->oggSerial = header.serialNumber; pInit->oggBosHeader = header; break; } else { - // Failed to read STREAMINFO block. Aww, so close... + /* Failed to read STREAMINFO block. Aww, so close... */ return DRFLAC_FALSE; } } else { - // Invalid file. + /* Invalid file. */ return DRFLAC_FALSE; } } else { - // Not a FLAC header. Skip it. + /* Not a FLAC header. Skip it. */ if (!onSeek(pUserData, bytesRemainingInPage, drflac_seek_origin_current)) { return DRFLAC_FALSE; } } } else { - // Not a FLAC header. Seek past the entire page and move on to the next. + /* Not a FLAC header. Seek past the entire page and move on to the next. */ if (!onSeek(pUserData, bytesRemainingInPage, drflac_seek_origin_current)) { return DRFLAC_FALSE; } @@ -4543,24 +6188,28 @@ drflac_bool32 drflac__init_private__ogg(drflac_init_info* pInit, drflac_read_pro pInit->runningFilePos += pageBodySize; - // Read the header of the next page. + /* Read the header of the next page. */ if (drflac_ogg__read_page_header(onRead, pUserData, &header, &bytesRead, &crc32) != DRFLAC_SUCCESS) { return DRFLAC_FALSE; } pInit->runningFilePos += bytesRead; } - - // If we get here it means we found a FLAC audio stream. We should be sitting on the first byte of the header of the next page. The next - // packets in the FLAC logical stream contain the metadata. The only thing left to do in the initialization phase for Ogg is to create the - // Ogg bistream object. - pInit->hasMetadataBlocks = DRFLAC_TRUE; // <-- Always have at least VORBIS_COMMENT metadata block. + /* + If we get here it means we found a FLAC audio stream. We should be sitting on the first byte of the header of the next page. The next + packets in the FLAC logical stream contain the metadata. The only thing left to do in the initialization phase for Ogg is to create the + Ogg bistream object. + */ + pInit->hasMetadataBlocks = DRFLAC_TRUE; /* <-- Always have at least VORBIS_COMMENT metadata block. */ return DRFLAC_TRUE; } #endif drflac_bool32 drflac__init_private(drflac_init_info* pInit, drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, drflac_container container, void* pUserData, void* pUserDataMD) { + drflac_bool32 relaxed; + drflac_uint8 id[4]; + if (pInit == NULL || onRead == NULL || onSeek == NULL) { return DRFLAC_FALSE; } @@ -4579,27 +6228,28 @@ drflac_bool32 drflac__init_private(drflac_init_info* pInit, drflac_read_proc onR drflac__reset_cache(&pInit->bs); - // If the container is explicitly defined then we can try opening in relaxed mode. - drflac_bool32 relaxed = container != drflac_container_unknown; - - drflac_uint8 id[4]; + /* If the container is explicitly defined then we can try opening in relaxed mode. */ + relaxed = container != drflac_container_unknown; - // Skip over any ID3 tags. + /* Skip over any ID3 tags. */ for (;;) { if (onRead(pUserData, id, 4) != 4) { - return DRFLAC_FALSE; // Ran out of data. + return DRFLAC_FALSE; /* Ran out of data. */ } pInit->runningFilePos += 4; if (id[0] == 'I' && id[1] == 'D' && id[2] == '3') { drflac_uint8 header[6]; + drflac_uint8 flags; + drflac_uint32 headerSize; + if (onRead(pUserData, header, 6) != 6) { - return DRFLAC_FALSE; // Ran out of data. + return DRFLAC_FALSE; /* Ran out of data. */ } pInit->runningFilePos += 6; - drflac_uint8 flags = header[1]; - drflac_uint32 headerSize; + flags = header[1]; + drflac_copy_memory(&headerSize, header+2, 4); headerSize = drflac__unsynchsafe_32(drflac__be2host_32(headerSize)); if (flags & 0x10) { @@ -4607,7 +6257,7 @@ drflac_bool32 drflac__init_private(drflac_init_info* pInit, drflac_read_proc onR } if (!onSeek(pUserData, headerSize, drflac_seek_origin_current)) { - return DRFLAC_FALSE; // Failed to seek past the tag. + return DRFLAC_FALSE; /* Failed to seek past the tag. */ } pInit->runningFilePos += headerSize; } else { @@ -4624,7 +6274,7 @@ drflac_bool32 drflac__init_private(drflac_init_info* pInit, drflac_read_proc onR } #endif - // If we get here it means we likely don't have a header. Try opening in relaxed mode, if applicable. + /* If we get here it means we likely don't have a header. Try opening in relaxed mode, if applicable. */ if (relaxed) { if (container == drflac_container_native) { return drflac__init_private__native(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed); @@ -4636,7 +6286,7 @@ drflac_bool32 drflac__init_private(drflac_init_info* pInit, drflac_read_proc onR #endif } - // Unsupported container. + /* Unsupported container. */ return DRFLAC_FALSE; } @@ -4646,61 +6296,76 @@ void drflac__init_from_info(drflac* pFlac, drflac_init_info* pInit) drflac_assert(pInit != NULL); drflac_zero_memory(pFlac, sizeof(*pFlac)); - pFlac->bs = pInit->bs; - pFlac->onMeta = pInit->onMeta; - pFlac->pUserDataMD = pInit->pUserDataMD; - pFlac->maxBlockSize = pInit->maxBlockSize; - pFlac->sampleRate = pInit->sampleRate; - pFlac->channels = (drflac_uint8)pInit->channels; - pFlac->bitsPerSample = (drflac_uint8)pInit->bitsPerSample; - pFlac->totalSampleCount = pInit->totalSampleCount; - pFlac->container = pInit->container; + pFlac->bs = pInit->bs; + pFlac->onMeta = pInit->onMeta; + pFlac->pUserDataMD = pInit->pUserDataMD; + pFlac->maxBlockSize = pInit->maxBlockSize; + pFlac->sampleRate = pInit->sampleRate; + pFlac->channels = (drflac_uint8)pInit->channels; + pFlac->bitsPerSample = (drflac_uint8)pInit->bitsPerSample; + pFlac->totalSampleCount = pInit->totalSampleCount; + pFlac->totalPCMFrameCount = pInit->totalSampleCount / pFlac->channels; + pFlac->container = pInit->container; } drflac* drflac_open_with_metadata_private(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, drflac_container container, void* pUserData, void* pUserDataMD) { + drflac_init_info init; + drflac_uint32 allocationSize; + drflac_uint32 wholeSIMDVectorCountPerChannel; + drflac_uint32 decodedSamplesAllocationSize; +#ifndef DR_FLAC_NO_OGG + drflac_uint32 oggbsAllocationSize; + drflac_oggbs oggbs; +#endif + drflac_uint64 firstFramePos; + drflac_uint64 seektablePos; + drflac_uint32 seektableSize; + drflac* pFlac; + #ifndef DRFLAC_NO_CPUID - // CPU support first. + /* CPU support first. */ drflac__init_cpu_caps(); #endif - drflac_init_info init; if (!drflac__init_private(&init, onRead, onSeek, onMeta, container, pUserData, pUserDataMD)) { return NULL; } - // The size of the allocation for the drflac object needs to be large enough to fit the following: - // 1) The main members of the drflac structure - // 2) A block of memory large enough to store the decoded samples of the largest frame in the stream - // 3) If the container is Ogg, a drflac_oggbs object - // - // The complicated part of the allocation is making sure there's enough room the decoded samples, taking into consideration - // the different SIMD instruction sets. - drflac_uint32 allocationSize = sizeof(drflac); - - // The allocation size for decoded frames depends on the number of 32-bit integers that fit inside the largest SIMD vector - // we are supporting. - drflac_uint32 wholeSIMDVectorCountPerChannel; - if ((init.maxBlockSize % (DRFLAC_MAX_SIMD_VECTOR_SIZE / sizeof(drflac_int32))) == 0) { - wholeSIMDVectorCountPerChannel = (init.maxBlockSize / (DRFLAC_MAX_SIMD_VECTOR_SIZE / sizeof(drflac_int32))); + /* + The size of the allocation for the drflac object needs to be large enough to fit the following: + 1) The main members of the drflac structure + 2) A block of memory large enough to store the decoded samples of the largest frame in the stream + 3) If the container is Ogg, a drflac_oggbs object + + The complicated part of the allocation is making sure there's enough room the decoded samples, taking into consideration + the different SIMD instruction sets. + */ + allocationSize = sizeof(drflac); + + /* + The allocation size for decoded frames depends on the number of 32-bit integers that fit inside the largest SIMD vector + we are supporting. + */ + if (((init.maxBlockSize+DRFLAC_LEADING_SAMPLES) % (DRFLAC_MAX_SIMD_VECTOR_SIZE / sizeof(drflac_int32))) == 0) { + wholeSIMDVectorCountPerChannel = ((init.maxBlockSize+DRFLAC_LEADING_SAMPLES) / (DRFLAC_MAX_SIMD_VECTOR_SIZE / sizeof(drflac_int32))); } else { - wholeSIMDVectorCountPerChannel = (init.maxBlockSize / (DRFLAC_MAX_SIMD_VECTOR_SIZE / sizeof(drflac_int32))) + 1; + wholeSIMDVectorCountPerChannel = ((init.maxBlockSize+DRFLAC_LEADING_SAMPLES) / (DRFLAC_MAX_SIMD_VECTOR_SIZE / sizeof(drflac_int32))) + 1; } - drflac_uint32 decodedSamplesAllocationSize = wholeSIMDVectorCountPerChannel * DRFLAC_MAX_SIMD_VECTOR_SIZE * init.channels; + decodedSamplesAllocationSize = wholeSIMDVectorCountPerChannel * DRFLAC_MAX_SIMD_VECTOR_SIZE * init.channels; allocationSize += decodedSamplesAllocationSize; - allocationSize += DRFLAC_MAX_SIMD_VECTOR_SIZE; // Allocate extra bytes to ensure we have enough for alignment. + allocationSize += DRFLAC_MAX_SIMD_VECTOR_SIZE; /* Allocate extra bytes to ensure we have enough for alignment. */ #ifndef DR_FLAC_NO_OGG - // There's additional data required for Ogg streams. - drflac_uint32 oggbsAllocationSize = 0; + /* There's additional data required for Ogg streams. */ + oggbsAllocationSize = 0; if (init.container == drflac_container_ogg) { oggbsAllocationSize = sizeof(drflac_oggbs); allocationSize += oggbsAllocationSize; } - drflac_oggbs oggbs; drflac_zero_memory(&oggbs, sizeof(oggbs)); if (init.container == drflac_container_ogg) { oggbs.onRead = onRead; @@ -4714,12 +6379,14 @@ drflac* drflac_open_with_metadata_private(drflac_read_proc onRead, drflac_seek_p } #endif - // This part is a bit awkward. We need to load the seektable so that it can be referenced in-memory, but I want the drflac object to - // consist of only a single heap allocation. To this, the size of the seek table needs to be known, which we determine when reading - // and decoding the metadata. - drflac_uint64 firstFramePos = 42; // <-- We know we are at byte 42 at this point. - drflac_uint64 seektablePos = 0; - drflac_uint32 seektableSize = 0; + /* + This part is a bit awkward. We need to load the seektable so that it can be referenced in-memory, but I want the drflac object to + consist of only a single heap allocation. To this, the size of the seek table needs to be known, which we determine when reading + and decoding the metadata. + */ + firstFramePos = 42; /* <-- We know we are at byte 42 at this point. */ + seektablePos = 0; + seektableSize = 0; if (init.hasMetadataBlocks) { drflac_read_proc onReadOverride = onRead; drflac_seek_proc onSeekOverride = onSeek; @@ -4741,7 +6408,7 @@ drflac* drflac_open_with_metadata_private(drflac_read_proc onRead, drflac_seek_p } - drflac* pFlac = (drflac*)DRFLAC_MALLOC(allocationSize); + pFlac = (drflac*)DRFLAC_MALLOC(allocationSize); drflac__init_from_info(pFlac, &init); pFlac->pDecodedSamples = (drflac_int32*)drflac_align((size_t)pFlac->pExtraData, DRFLAC_MAX_SIMD_VECTOR_SIZE); @@ -4750,7 +6417,7 @@ drflac* drflac_open_with_metadata_private(drflac_read_proc onRead, drflac_seek_p drflac_oggbs* pInternalOggbs = (drflac_oggbs*)((drflac_uint8*)pFlac->pDecodedSamples + decodedSamplesAllocationSize + seektableSize); *pInternalOggbs = oggbs; - // The Ogg bistream needs to be layered on top of the original bitstream. + /* The Ogg bistream needs to be layered on top of the original bitstream. */ pFlac->bs.onRead = drflac__on_read_ogg; pFlac->bs.onSeek = drflac__on_seek_ogg; pFlac->bs.pUserData = (void*)pInternalOggbs; @@ -4760,7 +6427,7 @@ drflac* drflac_open_with_metadata_private(drflac_read_proc onRead, drflac_seek_p pFlac->firstFramePos = firstFramePos; - // NOTE: Seektables are not currently compatible with Ogg encapsulation (Ogg has its own accelerated seeking system). I may change this later, so I'm leaving this here for now. + /* NOTE: Seektables are not currently compatible with Ogg encapsulation (Ogg has its own accelerated seeking system). I may change this later, so I'm leaving this here for now. */ #ifndef DR_FLAC_NO_OGG if (init.container == drflac_container_ogg) { @@ -4770,32 +6437,34 @@ drflac* drflac_open_with_metadata_private(drflac_read_proc onRead, drflac_seek_p else #endif { - // If we have a seektable we need to load it now, making sure we move back to where we were previously. + /* If we have a seektable we need to load it now, making sure we move back to where we were previously. */ if (seektablePos != 0) { pFlac->seekpointCount = seektableSize / sizeof(*pFlac->pSeekpoints); pFlac->pSeekpoints = (drflac_seekpoint*)((drflac_uint8*)pFlac->pDecodedSamples + decodedSamplesAllocationSize); - // Seek to the seektable, then just read directly into our seektable buffer. + /* Seek to the seektable, then just read directly into our seektable buffer. */ if (pFlac->bs.onSeek(pFlac->bs.pUserData, (int)seektablePos, drflac_seek_origin_start)) { if (pFlac->bs.onRead(pFlac->bs.pUserData, pFlac->pSeekpoints, seektableSize) == seektableSize) { - // Endian swap. - for (drflac_uint32 iSeekpoint = 0; iSeekpoint < pFlac->seekpointCount; ++iSeekpoint) { + /* Endian swap. */ + drflac_uint32 iSeekpoint; + for (iSeekpoint = 0; iSeekpoint < pFlac->seekpointCount; ++iSeekpoint) { pFlac->pSeekpoints[iSeekpoint].firstSample = drflac__be2host_64(pFlac->pSeekpoints[iSeekpoint].firstSample); pFlac->pSeekpoints[iSeekpoint].frameOffset = drflac__be2host_64(pFlac->pSeekpoints[iSeekpoint].frameOffset); pFlac->pSeekpoints[iSeekpoint].sampleCount = drflac__be2host_16(pFlac->pSeekpoints[iSeekpoint].sampleCount); } } else { - // Failed to read the seektable. Pretend we don't have one. + /* Failed to read the seektable. Pretend we don't have one. */ pFlac->pSeekpoints = NULL; pFlac->seekpointCount = 0; } - // We need to seek back to where we were. If this fails it's a critical error. + /* We need to seek back to where we were. If this fails it's a critical error. */ if (!pFlac->bs.onSeek(pFlac->bs.pUserData, (int)pFlac->firstFramePos, drflac_seek_origin_start)) { + DRFLAC_FREE(pFlac); return NULL; } } else { - // Failed to seek to the seektable. Ominous sign, but for now we can just pretend we don't have one. + /* Failed to seek to the seektable. Ominous sign, but for now we can just pretend we don't have one. */ pFlac->pSeekpoints = NULL; pFlac->seekpointCount = 0; } @@ -4803,19 +6472,20 @@ drflac* drflac_open_with_metadata_private(drflac_read_proc onRead, drflac_seek_p } - - // If we get here, but don't have a STREAMINFO block, it means we've opened the stream in relaxed mode and need to decode - // the first frame. + /* + If we get here, but don't have a STREAMINFO block, it means we've opened the stream in relaxed mode and need to decode + the first frame. + */ if (!init.hasStreamInfoBlock) { pFlac->currentFrame.header = init.firstFrameHeader; do { - drflac_result result = drflac__decode_frame(pFlac); + drflac_result result = drflac__decode_flac_frame(pFlac); if (result == DRFLAC_SUCCESS) { break; } else { if (result == DRFLAC_CRC_MISMATCH) { - if (!drflac__read_next_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFrame.header)) { + if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFrame.header)) { DRFLAC_FREE(pFlac); return NULL; } @@ -4834,9 +6504,6 @@ drflac* drflac_open_with_metadata_private(drflac_read_proc onRead, drflac_seek_p #ifndef DR_FLAC_NO_STDIO -typedef void* drflac_file; - -#if defined(DR_FLAC_NO_WIN32_IO) || !defined(_WIN32) #include static size_t drflac__on_read_stdio(void* pUserData, void* bufferOut, size_t bytesToRead) @@ -4846,15 +6513,15 @@ static size_t drflac__on_read_stdio(void* pUserData, void* bufferOut, size_t byt static drflac_bool32 drflac__on_seek_stdio(void* pUserData, int offset, drflac_seek_origin origin) { - drflac_assert(offset > 0 || (offset == 0 && origin == drflac_seek_origin_start)); + drflac_assert(offset >= 0); /* <-- Never seek backwards. */ return fseek((FILE*)pUserData, offset, (origin == drflac_seek_origin_current) ? SEEK_CUR : SEEK_SET) == 0; } -static drflac_file drflac__open_file_handle(const char* filename) +static FILE* drflac__fopen(const char* filename) { FILE* pFile; -#ifdef _MSC_VER +#if defined(_MSC_VER) && _MSC_VER >= 1400 if (fopen_s(&pFile, filename, "rb") != 0) { return NULL; } @@ -4865,65 +6532,23 @@ static drflac_file drflac__open_file_handle(const char* filename) } #endif - return (drflac_file)pFile; -} - -static void drflac__close_file_handle(drflac_file file) -{ - fclose((FILE*)file); + return pFile; } -#else -#include -// This doesn't seem to be defined for VC6. -#ifndef INVALID_SET_FILE_POINTER -#define INVALID_SET_FILE_POINTER ((DWORD)-1) -#endif -static size_t drflac__on_read_stdio(void* pUserData, void* bufferOut, size_t bytesToRead) +drflac* drflac_open_file(const char* filename) { - drflac_assert(bytesToRead < 0xFFFFFFFF); // dr_flac will never request huge amounts of data at a time. This is a safe assertion. - - DWORD bytesRead; - ReadFile((HANDLE)pUserData, bufferOut, (DWORD)bytesToRead, &bytesRead, NULL); + drflac* pFlac; + FILE* pFile; - return (size_t)bytesRead; -} + pFile = drflac__fopen(filename); + if (pFile == NULL) { + return NULL; + } -static drflac_bool32 drflac__on_seek_stdio(void* pUserData, int offset, drflac_seek_origin origin) -{ - drflac_assert(offset > 0 || (offset == 0 && origin == drflac_seek_origin_start)); - - return SetFilePointer((HANDLE)pUserData, offset, NULL, (origin == drflac_seek_origin_current) ? FILE_CURRENT : FILE_BEGIN) != INVALID_SET_FILE_POINTER; -} - -static drflac_file drflac__open_file_handle(const char* filename) -{ - HANDLE hFile = CreateFileA(filename, FILE_GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); - if (hFile == INVALID_HANDLE_VALUE) { - return NULL; - } - - return (drflac_file)hFile; -} - -static void drflac__close_file_handle(drflac_file file) -{ - CloseHandle((HANDLE)file); -} -#endif - - -drflac* drflac_open_file(const char* filename) -{ - drflac_file file = drflac__open_file_handle(filename); - if (file == NULL) { - return NULL; - } - - drflac* pFlac = drflac_open(drflac__on_read_stdio, drflac__on_seek_stdio, (void*)file); + pFlac = drflac_open(drflac__on_read_stdio, drflac__on_seek_stdio, (void*)pFile); if (pFlac == NULL) { - drflac__close_file_handle(file); + fclose(pFile); return NULL; } @@ -4932,28 +6557,33 @@ drflac* drflac_open_file(const char* filename) drflac* drflac_open_file_with_metadata(const char* filename, drflac_meta_proc onMeta, void* pUserData) { - drflac_file file = drflac__open_file_handle(filename); - if (file == NULL) { + drflac* pFlac; + FILE* pFile; + + pFile = drflac__fopen(filename); + if (pFile == NULL) { return NULL; } - drflac* pFlac = drflac_open_with_metadata_private(drflac__on_read_stdio, drflac__on_seek_stdio, onMeta, drflac_container_unknown, (void*)file, pUserData); + pFlac = drflac_open_with_metadata_private(drflac__on_read_stdio, drflac__on_seek_stdio, onMeta, drflac_container_unknown, (void*)pFile, pUserData); if (pFlac == NULL) { - drflac__close_file_handle(file); + fclose(pFile); return pFlac; } return pFlac; } -#endif //DR_FLAC_NO_STDIO +#endif /* DR_FLAC_NO_STDIO */ static size_t drflac__on_read_memory(void* pUserData, void* bufferOut, size_t bytesToRead) { drflac__memory_stream* memoryStream = (drflac__memory_stream*)pUserData; + size_t bytesRemaining; + drflac_assert(memoryStream != NULL); drflac_assert(memoryStream->dataSize >= memoryStream->currentReadPos); - size_t bytesRemaining = memoryStream->dataSize - memoryStream->currentReadPos; + bytesRemaining = memoryStream->dataSize - memoryStream->currentReadPos; if (bytesToRead > bytesRemaining) { bytesToRead = bytesRemaining; } @@ -4969,21 +6599,25 @@ static size_t drflac__on_read_memory(void* pUserData, void* bufferOut, size_t by static drflac_bool32 drflac__on_seek_memory(void* pUserData, int offset, drflac_seek_origin origin) { drflac__memory_stream* memoryStream = (drflac__memory_stream*)pUserData; + drflac_assert(memoryStream != NULL); - drflac_assert(offset > 0 || (offset == 0 && origin == drflac_seek_origin_start)); - drflac_assert(offset <= (drflac_int64)memoryStream->dataSize); + drflac_assert(offset >= 0); /* <-- Never seek backwards. */ + + if (offset > (drflac_int64)memoryStream->dataSize) { + return DRFLAC_FALSE; + } if (origin == drflac_seek_origin_current) { if (memoryStream->currentReadPos + offset <= memoryStream->dataSize) { memoryStream->currentReadPos += offset; } else { - memoryStream->currentReadPos = memoryStream->dataSize; // Trying to seek too far forward. + return DRFLAC_FALSE; /* Trying to seek too far forward. */ } } else { if ((drflac_uint32)offset <= memoryStream->dataSize) { memoryStream->currentReadPos = offset; } else { - memoryStream->currentReadPos = memoryStream->dataSize; // Trying to seek too far forward. + return DRFLAC_FALSE; /* Trying to seek too far forward. */ } } @@ -4993,17 +6627,19 @@ static drflac_bool32 drflac__on_seek_memory(void* pUserData, int offset, drflac_ drflac* drflac_open_memory(const void* data, size_t dataSize) { drflac__memory_stream memoryStream; + drflac* pFlac; + memoryStream.data = (const unsigned char*)data; memoryStream.dataSize = dataSize; memoryStream.currentReadPos = 0; - drflac* pFlac = drflac_open(drflac__on_read_memory, drflac__on_seek_memory, &memoryStream); + pFlac = drflac_open(drflac__on_read_memory, drflac__on_seek_memory, &memoryStream); if (pFlac == NULL) { return NULL; } pFlac->memoryStream = memoryStream; - // This is an awful hack... + /* This is an awful hack... */ #ifndef DR_FLAC_NO_OGG if (pFlac->container == drflac_container_ogg) { @@ -5022,17 +6658,19 @@ drflac* drflac_open_memory(const void* data, size_t dataSize) drflac* drflac_open_memory_with_metadata(const void* data, size_t dataSize, drflac_meta_proc onMeta, void* pUserData) { drflac__memory_stream memoryStream; + drflac* pFlac; + memoryStream.data = (const unsigned char*)data; memoryStream.dataSize = dataSize; memoryStream.currentReadPos = 0; - drflac* pFlac = drflac_open_with_metadata_private(drflac__on_read_memory, drflac__on_seek_memory, onMeta, drflac_container_unknown, &memoryStream, pUserData); + pFlac = drflac_open_with_metadata_private(drflac__on_read_memory, drflac__on_seek_memory, onMeta, drflac_container_unknown, &memoryStream, pUserData); if (pFlac == NULL) { return NULL; } pFlac->memoryStream = memoryStream; - // This is an awful hack... + /* This is an awful hack... */ #ifndef DR_FLAC_NO_OGG if (pFlac->container == drflac_container_ogg) { @@ -5075,19 +6713,22 @@ void drflac_close(drflac* pFlac) } #ifndef DR_FLAC_NO_STDIO - // If we opened the file with drflac_open_file() we will want to close the file handle. We can know whether or not drflac_open_file() - // was used by looking at the callbacks. + /* + If we opened the file with drflac_open_file() we will want to close the file handle. We can know whether or not drflac_open_file() + was used by looking at the callbacks. + */ if (pFlac->bs.onRead == drflac__on_read_stdio) { - drflac__close_file_handle((drflac_file)pFlac->bs.pUserData); + fclose((FILE*)pFlac->bs.pUserData); } #ifndef DR_FLAC_NO_OGG - // Need to clean up Ogg streams a bit differently due to the way the bit streaming is chained. + /* Need to clean up Ogg streams a bit differently due to the way the bit streaming is chained. */ if (pFlac->container == drflac_container_ogg) { - drflac_assert(pFlac->bs.onRead == drflac__on_read_ogg); drflac_oggbs* oggbs = (drflac_oggbs*)pFlac->_oggbs; + drflac_assert(pFlac->bs.onRead == drflac__on_read_ogg); + if (oggbs->onRead == drflac__on_read_stdio) { - drflac__close_file_handle((drflac_file)oggbs->pUserData); + fclose((FILE*)oggbs->pUserData); } } #endif @@ -5099,30 +6740,29 @@ void drflac_close(drflac* pFlac) drflac_uint64 drflac__read_s32__misaligned(drflac* pFlac, drflac_uint64 samplesToRead, drflac_int32* bufferOut) { unsigned int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFrame.header.channelAssignment); + drflac_uint64 samplesRead; - // We should never be calling this when the number of samples to read is >= the sample count. + /* We should never be calling this when the number of samples to read is >= the sample count. */ drflac_assert(samplesToRead < channelCount); drflac_assert(pFlac->currentFrame.samplesRemaining > 0 && samplesToRead <= pFlac->currentFrame.samplesRemaining); - - drflac_uint64 samplesRead = 0; + samplesRead = 0; while (samplesToRead > 0) { drflac_uint64 totalSamplesInFrame = pFlac->currentFrame.header.blockSize * channelCount; drflac_uint64 samplesReadFromFrameSoFar = totalSamplesInFrame - pFlac->currentFrame.samplesRemaining; drflac_uint64 channelIndex = samplesReadFromFrameSoFar % channelCount; - drflac_uint64 nextSampleInFrame = samplesReadFromFrameSoFar / channelCount; - int decodedSample = 0; + switch (pFlac->currentFrame.header.channelAssignment) { case DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE: { if (channelIndex == 0) { - decodedSample = pFlac->currentFrame.subframes[channelIndex].pDecodedSamples[nextSampleInFrame]; + decodedSample = pFlac->currentFrame.subframes[channelIndex + 0].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex + 0].wastedBitsPerSample; } else { - int side = pFlac->currentFrame.subframes[channelIndex + 0].pDecodedSamples[nextSampleInFrame]; - int left = pFlac->currentFrame.subframes[channelIndex - 1].pDecodedSamples[nextSampleInFrame]; + int side = pFlac->currentFrame.subframes[channelIndex + 0].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex + 0].wastedBitsPerSample; + int left = pFlac->currentFrame.subframes[channelIndex - 1].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex - 1].wastedBitsPerSample; decodedSample = left - side; } } break; @@ -5130,11 +6770,11 @@ drflac_uint64 drflac__read_s32__misaligned(drflac* pFlac, drflac_uint64 samplesT case DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE: { if (channelIndex == 0) { - int side = pFlac->currentFrame.subframes[channelIndex + 0].pDecodedSamples[nextSampleInFrame]; - int right = pFlac->currentFrame.subframes[channelIndex + 1].pDecodedSamples[nextSampleInFrame]; + int side = pFlac->currentFrame.subframes[channelIndex + 0].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex + 0].wastedBitsPerSample; + int right = pFlac->currentFrame.subframes[channelIndex + 1].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex + 1].wastedBitsPerSample; decodedSample = side + right; } else { - decodedSample = pFlac->currentFrame.subframes[channelIndex].pDecodedSamples[nextSampleInFrame]; + decodedSample = pFlac->currentFrame.subframes[channelIndex + 0].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex + 0].wastedBitsPerSample; } } break; @@ -5143,14 +6783,14 @@ drflac_uint64 drflac__read_s32__misaligned(drflac* pFlac, drflac_uint64 samplesT int mid; int side; if (channelIndex == 0) { - mid = pFlac->currentFrame.subframes[channelIndex + 0].pDecodedSamples[nextSampleInFrame]; - side = pFlac->currentFrame.subframes[channelIndex + 1].pDecodedSamples[nextSampleInFrame]; + mid = pFlac->currentFrame.subframes[channelIndex + 0].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex + 0].wastedBitsPerSample; + side = pFlac->currentFrame.subframes[channelIndex + 1].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex + 1].wastedBitsPerSample; mid = (((unsigned int)mid) << 1) | (side & 0x01); decodedSample = (mid + side) >> 1; } else { - mid = pFlac->currentFrame.subframes[channelIndex - 1].pDecodedSamples[nextSampleInFrame]; - side = pFlac->currentFrame.subframes[channelIndex + 0].pDecodedSamples[nextSampleInFrame]; + mid = pFlac->currentFrame.subframes[channelIndex - 1].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex - 1].wastedBitsPerSample; + side = pFlac->currentFrame.subframes[channelIndex + 0].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex + 0].wastedBitsPerSample; mid = (((unsigned int)mid) << 1) | (side & 0x01); decodedSample = (mid - side) >> 1; @@ -5160,12 +6800,11 @@ drflac_uint64 drflac__read_s32__misaligned(drflac* pFlac, drflac_uint64 samplesT case DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT: default: { - decodedSample = pFlac->currentFrame.subframes[channelIndex].pDecodedSamples[nextSampleInFrame]; + decodedSample = pFlac->currentFrame.subframes[channelIndex + 0].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex + 0].wastedBitsPerSample; } break; } - - decodedSample <<= ((32 - pFlac->bitsPerSample) + pFlac->currentFrame.subframes[channelIndex].wastedBitsPerSample); + decodedSample <<= (32 - pFlac->bitsPerSample); if (bufferOut) { *bufferOut++ = decodedSample; @@ -5179,34 +6818,11 @@ drflac_uint64 drflac__read_s32__misaligned(drflac* pFlac, drflac_uint64 samplesT return samplesRead; } -drflac_uint64 drflac__seek_forward_by_samples(drflac* pFlac, drflac_uint64 samplesToRead) -{ - drflac_uint64 samplesRead = 0; - while (samplesToRead > 0) { - if (pFlac->currentFrame.samplesRemaining == 0) { - if (!drflac__read_and_decode_next_frame(pFlac)) { - break; // Couldn't read the next frame, so just break from the loop and return. - } - } else { - if (pFlac->currentFrame.samplesRemaining > samplesToRead) { - samplesRead += samplesToRead; - pFlac->currentFrame.samplesRemaining -= (drflac_uint32)samplesToRead; // <-- Safe cast. Will always be < currentFrame.samplesRemaining < 65536. - samplesToRead = 0; - } else { - samplesRead += pFlac->currentFrame.samplesRemaining; - samplesToRead -= pFlac->currentFrame.samplesRemaining; - pFlac->currentFrame.samplesRemaining = 0; - } - } - } - - pFlac->currentSample += samplesRead; - return samplesRead; -} - drflac_uint64 drflac_read_s32(drflac* pFlac, drflac_uint64 samplesToRead, drflac_int32* bufferOut) { - // Note that is allowed to be null, in which case this will act like a seek. + drflac_uint64 samplesRead; + + /* Note that is allowed to be null, in which case this will act like a seek. */ if (pFlac == NULL || samplesToRead == 0) { return 0; } @@ -5215,22 +6831,24 @@ drflac_uint64 drflac_read_s32(drflac* pFlac, drflac_uint64 samplesToRead, drflac return drflac__seek_forward_by_samples(pFlac, samplesToRead); } - - drflac_uint64 samplesRead = 0; + samplesRead = 0; while (samplesToRead > 0) { - // If we've run out of samples in this frame, go to the next. + /* If we've run out of samples in this frame, go to the next. */ if (pFlac->currentFrame.samplesRemaining == 0) { - if (!drflac__read_and_decode_next_frame(pFlac)) { - break; // Couldn't read the next frame, so just break from the loop and return. + if (!drflac__read_and_decode_next_flac_frame(pFlac)) { + break; /* Couldn't read the next frame, so just break from the loop and return. */ } } else { - // Here is where we grab the samples and interleave them. - + /* Here is where we grab the samples and interleave them. */ unsigned int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFrame.header.channelAssignment); drflac_uint64 totalSamplesInFrame = pFlac->currentFrame.header.blockSize * channelCount; drflac_uint64 samplesReadFromFrameSoFar = totalSamplesInFrame - pFlac->currentFrame.samplesRemaining; - drflac_uint64 misalignedSampleCount = samplesReadFromFrameSoFar % channelCount; + drflac_uint64 alignedSampleCountPerChannel; + drflac_uint64 firstAlignedSampleInFrame; + unsigned int unusedBitsPerSample; + drflac_uint64 alignedSamplesRead; + if (misalignedSampleCount > 0) { drflac_uint64 misalignedSamplesRead = drflac__read_s32__misaligned(pFlac, misalignedSampleCount, bufferOut); samplesRead += misalignedSamplesRead; @@ -5241,79 +6859,87 @@ drflac_uint64 drflac_read_s32(drflac* pFlac, drflac_uint64 samplesToRead, drflac } - drflac_uint64 alignedSampleCountPerChannel = samplesToRead / channelCount; + alignedSampleCountPerChannel = samplesToRead / channelCount; if (alignedSampleCountPerChannel > pFlac->currentFrame.samplesRemaining / channelCount) { alignedSampleCountPerChannel = pFlac->currentFrame.samplesRemaining / channelCount; } - drflac_uint64 firstAlignedSampleInFrame = samplesReadFromFrameSoFar / channelCount; - unsigned int unusedBitsPerSample = 32 - pFlac->bitsPerSample; + firstAlignedSampleInFrame = samplesReadFromFrameSoFar / channelCount; + unusedBitsPerSample = 32 - pFlac->bitsPerSample; switch (pFlac->currentFrame.header.channelAssignment) { case DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE: { + drflac_uint64 i; const drflac_int32* pDecodedSamples0 = pFlac->currentFrame.subframes[0].pDecodedSamples + firstAlignedSampleInFrame; const drflac_int32* pDecodedSamples1 = pFlac->currentFrame.subframes[1].pDecodedSamples + firstAlignedSampleInFrame; - for (drflac_uint64 i = 0; i < alignedSampleCountPerChannel; ++i) { - int left = pDecodedSamples0[i]; - int side = pDecodedSamples1[i]; + for (i = 0; i < alignedSampleCountPerChannel; ++i) { + int left = pDecodedSamples0[i] << (unusedBitsPerSample + pFlac->currentFrame.subframes[0].wastedBitsPerSample); + int side = pDecodedSamples1[i] << (unusedBitsPerSample + pFlac->currentFrame.subframes[1].wastedBitsPerSample); int right = left - side; - bufferOut[i*2+0] = left << (unusedBitsPerSample + pFlac->currentFrame.subframes[0].wastedBitsPerSample); - bufferOut[i*2+1] = right << (unusedBitsPerSample + pFlac->currentFrame.subframes[1].wastedBitsPerSample); + bufferOut[i*2+0] = left; + bufferOut[i*2+1] = right; } } break; case DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE: { + drflac_uint64 i; const drflac_int32* pDecodedSamples0 = pFlac->currentFrame.subframes[0].pDecodedSamples + firstAlignedSampleInFrame; const drflac_int32* pDecodedSamples1 = pFlac->currentFrame.subframes[1].pDecodedSamples + firstAlignedSampleInFrame; - for (drflac_uint64 i = 0; i < alignedSampleCountPerChannel; ++i) { - int side = pDecodedSamples0[i]; - int right = pDecodedSamples1[i]; + for (i = 0; i < alignedSampleCountPerChannel; ++i) { + int side = pDecodedSamples0[i] << (unusedBitsPerSample + pFlac->currentFrame.subframes[0].wastedBitsPerSample); + int right = pDecodedSamples1[i] << (unusedBitsPerSample + pFlac->currentFrame.subframes[1].wastedBitsPerSample); int left = right + side; - bufferOut[i*2+0] = left << (unusedBitsPerSample + pFlac->currentFrame.subframes[0].wastedBitsPerSample); - bufferOut[i*2+1] = right << (unusedBitsPerSample + pFlac->currentFrame.subframes[1].wastedBitsPerSample); + bufferOut[i*2+0] = left; + bufferOut[i*2+1] = right; } } break; case DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE: { + drflac_uint64 i; const drflac_int32* pDecodedSamples0 = pFlac->currentFrame.subframes[0].pDecodedSamples + firstAlignedSampleInFrame; const drflac_int32* pDecodedSamples1 = pFlac->currentFrame.subframes[1].pDecodedSamples + firstAlignedSampleInFrame; - for (drflac_uint64 i = 0; i < alignedSampleCountPerChannel; ++i) { - int side = pDecodedSamples1[i]; - int mid = (((drflac_uint32)pDecodedSamples0[i]) << 1) | (side & 0x01); + for (i = 0; i < alignedSampleCountPerChannel; ++i) { + int mid = pDecodedSamples0[i] << pFlac->currentFrame.subframes[0].wastedBitsPerSample; + int side = pDecodedSamples1[i] << pFlac->currentFrame.subframes[1].wastedBitsPerSample; + + mid = (((drflac_uint32)mid) << 1) | (side & 0x01); - bufferOut[i*2+0] = ((mid + side) >> 1) << (unusedBitsPerSample + pFlac->currentFrame.subframes[0].wastedBitsPerSample); - bufferOut[i*2+1] = ((mid - side) >> 1) << (unusedBitsPerSample + pFlac->currentFrame.subframes[1].wastedBitsPerSample); + bufferOut[i*2+0] = ((mid + side) >> 1) << (unusedBitsPerSample); + bufferOut[i*2+1] = ((mid - side) >> 1) << (unusedBitsPerSample); } } break; case DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT: default: { - if (pFlac->currentFrame.header.channelAssignment == 1) // 1 = Stereo + if (pFlac->currentFrame.header.channelAssignment == 1) /* 1 = Stereo */ { - // Stereo optimized inner loop unroll. + /* Stereo optimized inner loop unroll. */ + drflac_uint64 i; const drflac_int32* pDecodedSamples0 = pFlac->currentFrame.subframes[0].pDecodedSamples + firstAlignedSampleInFrame; const drflac_int32* pDecodedSamples1 = pFlac->currentFrame.subframes[1].pDecodedSamples + firstAlignedSampleInFrame; - for (drflac_uint64 i = 0; i < alignedSampleCountPerChannel; ++i) { + for (i = 0; i < alignedSampleCountPerChannel; ++i) { bufferOut[i*2+0] = pDecodedSamples0[i] << (unusedBitsPerSample + pFlac->currentFrame.subframes[0].wastedBitsPerSample); bufferOut[i*2+1] = pDecodedSamples1[i] << (unusedBitsPerSample + pFlac->currentFrame.subframes[1].wastedBitsPerSample); } } else { - // Generic interleaving. - for (drflac_uint64 i = 0; i < alignedSampleCountPerChannel; ++i) { - for (unsigned int j = 0; j < channelCount; ++j) { + /* Generic interleaving. */ + drflac_uint64 i; + for (i = 0; i < alignedSampleCountPerChannel; ++i) { + unsigned int j; + for (j = 0; j < channelCount; ++j) { bufferOut[(i*channelCount)+j] = (pFlac->currentFrame.subframes[j].pDecodedSamples[firstAlignedSampleInFrame + i]) << (unusedBitsPerSample + pFlac->currentFrame.subframes[j].wastedBitsPerSample); } } @@ -5321,7 +6947,7 @@ drflac_uint64 drflac_read_s32(drflac* pFlac, drflac_uint64 samplesToRead, drflac } break; } - drflac_uint64 alignedSamplesRead = alignedSampleCountPerChannel * channelCount; + alignedSamplesRead = alignedSampleCountPerChannel * channelCount; samplesRead += alignedSamplesRead; samplesReadFromFrameSoFar += alignedSamplesRead; bufferOut += alignedSamplesRead; @@ -5330,7 +6956,7 @@ drflac_uint64 drflac_read_s32(drflac* pFlac, drflac_uint64 samplesToRead, drflac pFlac->currentFrame.samplesRemaining -= (unsigned int)alignedSamplesRead; - // At this point we may still have some excess samples left to read. + /* At this point we may still have some excess samples left to read. */ if (samplesToRead > 0 && pFlac->currentFrame.samplesRemaining > 0) { drflac_uint64 excessSamplesRead = 0; if (samplesToRead < pFlac->currentFrame.samplesRemaining) { @@ -5351,20 +6977,47 @@ drflac_uint64 drflac_read_s32(drflac* pFlac, drflac_uint64 samplesToRead, drflac return samplesRead; } +drflac_uint64 drflac_read_pcm_frames_s32(drflac* pFlac, drflac_uint64 framesToRead, drflac_int32* pBufferOut) +{ +#if defined(_MSC_VER) && !defined(__clang__) + #pragma warning(push) + #pragma warning(disable:4996) /* was declared deprecated */ +#elif defined(__GNUC__) || defined(__clang__) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + return drflac_read_s32(pFlac, framesToRead*pFlac->channels, pBufferOut) / pFlac->channels; +#if defined(_MSC_VER) && !defined(__clang__) + #pragma warning(pop) +#elif defined(__GNUC__) || defined(__clang__) + #pragma GCC diagnostic pop +#endif +} + + drflac_uint64 drflac_read_s16(drflac* pFlac, drflac_uint64 samplesToRead, drflac_int16* pBufferOut) { - // This reads samples in 2 passes and can probably be optimized. + /* This reads samples in 2 passes and can probably be optimized. */ drflac_uint64 totalSamplesRead = 0; +#if defined(_MSC_VER) && !defined(__clang__) + #pragma warning(push) + #pragma warning(disable:4996) /* was declared deprecated */ +#elif defined(__GNUC__) || defined(__clang__) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + while (samplesToRead > 0) { + drflac_uint64 i; drflac_int32 samples32[4096]; drflac_uint64 samplesJustRead = drflac_read_s32(pFlac, (samplesToRead > 4096) ? 4096 : samplesToRead, samples32); if (samplesJustRead == 0) { - break; // Reached the end. + break; /* Reached the end. */ } - // s32 -> s16 - for (drflac_uint64 i = 0; i < samplesJustRead; ++i) { + /* s32 -> s16 */ + for (i = 0; i < samplesJustRead; ++i) { pBufferOut[i] = (drflac_int16)(samples32[i] >> 16); } @@ -5373,23 +7026,69 @@ drflac_uint64 drflac_read_s16(drflac* pFlac, drflac_uint64 samplesToRead, drflac pBufferOut += samplesJustRead; } +#if defined(_MSC_VER) && !defined(__clang__) + #pragma warning(pop) +#elif defined(__GNUC__) || defined(__clang__) + #pragma GCC diagnostic pop +#endif + return totalSamplesRead; } +drflac_uint64 drflac_read_pcm_frames_s16(drflac* pFlac, drflac_uint64 framesToRead, drflac_int16* pBufferOut) +{ + /* This reads samples in 2 passes and can probably be optimized. */ + drflac_uint64 totalPCMFramesRead = 0; + + while (framesToRead > 0) { + drflac_uint64 iFrame; + drflac_int32 samples32[4096]; + drflac_uint64 framesJustRead = drflac_read_pcm_frames_s32(pFlac, (framesToRead > 4096/pFlac->channels) ? 4096/pFlac->channels : framesToRead, samples32); + if (framesJustRead == 0) { + break; /* Reached the end. */ + } + + /* s32 -> s16 */ + for (iFrame = 0; iFrame < framesJustRead; ++iFrame) { + drflac_uint32 iChannel; + for (iChannel = 0; iChannel < pFlac->channels; ++iChannel) { + drflac_uint64 iSample = iFrame*pFlac->channels + iChannel; + pBufferOut[iSample] = (drflac_int16)(samples32[iSample] >> 16); + } + } + + totalPCMFramesRead += framesJustRead; + framesToRead -= framesJustRead; + pBufferOut += framesJustRead * pFlac->channels; + } + + return totalPCMFramesRead; +} + + drflac_uint64 drflac_read_f32(drflac* pFlac, drflac_uint64 samplesToRead, float* pBufferOut) { - // This reads samples in 2 passes and can probably be optimized. + /* This reads samples in 2 passes and can probably be optimized. */ drflac_uint64 totalSamplesRead = 0; +#if defined(_MSC_VER) && !defined(__clang__) + #pragma warning(push) + #pragma warning(disable:4996) /* was declared deprecated */ +#elif defined(__GNUC__) || defined(__clang__) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + while (samplesToRead > 0) { + drflac_uint64 i; drflac_int32 samples32[4096]; drflac_uint64 samplesJustRead = drflac_read_s32(pFlac, (samplesToRead > 4096) ? 4096 : samplesToRead, samples32); if (samplesJustRead == 0) { - break; // Reached the end. + break; /* Reached the end. */ } - // s32 -> f32 - for (drflac_uint64 i = 0; i < samplesJustRead; ++i) { + /* s32 -> f32 */ + for (i = 0; i < samplesJustRead; ++i) { pBufferOut[i] = (float)(samples32[i] / 2147483648.0); } @@ -5398,287 +7097,1457 @@ drflac_uint64 drflac_read_f32(drflac* pFlac, drflac_uint64 samplesToRead, float* pBufferOut += samplesJustRead; } +#if defined(_MSC_VER) && !defined(__clang__) + #pragma warning(pop) +#elif defined(__GNUC__) || defined(__clang__) + #pragma GCC diagnostic pop +#endif + return totalSamplesRead; } -drflac_bool32 drflac_seek_to_sample(drflac* pFlac, drflac_uint64 sampleIndex) +#if 0 +static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_left_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_int32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples) { - if (pFlac == NULL) { - return DRFLAC_FALSE; - } + drflac_uint64 i; + for (i = 0; i < frameCount; ++i) { + int left = pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFrame.subframes[0].wastedBitsPerSample); + int side = pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFrame.subframes[1].wastedBitsPerSample); + int right = left - side; - // If we don't know where the first frame begins then we can't seek. This will happen when the STREAMINFO block was not present - // when the decoder was opened. - if (pFlac->firstFramePos == 0) { - return DRFLAC_FALSE; + pOutputSamples[i*2+0] = (float)(left / 2147483648.0); + pOutputSamples[i*2+1] = (float)(right / 2147483648.0); } +} +#endif - if (sampleIndex == 0) { - pFlac->currentSample = 0; - return drflac__seek_to_first_frame(pFlac); - } else { - drflac_bool32 wasSuccessful = DRFLAC_FALSE; +static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_left_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_int32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; - // Clamp the sample to the end. - if (sampleIndex >= pFlac->totalSampleCount) { - sampleIndex = pFlac->totalSampleCount - 1; - } + float factor = 1 / 2147483648.0; - // If the target sample and the current sample are in the same frame we just move the position forward. - if (sampleIndex > pFlac->currentSample) { - // Forward. - drflac_uint32 offset = (drflac_uint32)(sampleIndex - pFlac->currentSample); - if (pFlac->currentFrame.samplesRemaining > offset) { - pFlac->currentFrame.samplesRemaining -= offset; - pFlac->currentSample = sampleIndex; - return DRFLAC_TRUE; - } - } else { - // Backward. - drflac_uint32 offsetAbs = (drflac_uint32)(pFlac->currentSample - sampleIndex); - drflac_uint32 currentFrameSampleCount = pFlac->currentFrame.header.blockSize * drflac__get_channel_count_from_channel_assignment(pFlac->currentFrame.header.channelAssignment); - drflac_uint32 currentFrameSamplesConsumed = (drflac_uint32)(currentFrameSampleCount - pFlac->currentFrame.samplesRemaining); - if (currentFrameSamplesConsumed > offsetAbs) { - pFlac->currentFrame.samplesRemaining += offsetAbs; - pFlac->currentSample = sampleIndex; - return DRFLAC_TRUE; - } - } + drflac_int32 shift0 = unusedBitsPerSample + pFlac->currentFrame.subframes[0].wastedBitsPerSample; + drflac_int32 shift1 = unusedBitsPerSample + pFlac->currentFrame.subframes[1].wastedBitsPerSample; + for (i = 0; i < frameCount4; ++i) { + drflac_int32 left0 = pInputSamples0[i*4+0] << shift0; + drflac_int32 left1 = pInputSamples0[i*4+1] << shift0; + drflac_int32 left2 = pInputSamples0[i*4+2] << shift0; + drflac_int32 left3 = pInputSamples0[i*4+3] << shift0; - // Different techniques depending on encapsulation. Using the native FLAC seektable with Ogg encapsulation is a bit awkward so - // we'll instead use Ogg's natural seeking facility. - #ifndef DR_FLAC_NO_OGG - if (pFlac->container == drflac_container_ogg) - { - wasSuccessful = drflac_ogg__seek_to_sample(pFlac, sampleIndex); - } - else - #endif - { - // First try seeking via the seek table. If this fails, fall back to a brute force seek which is much slower. - wasSuccessful = drflac__seek_to_sample__seek_table(pFlac, sampleIndex); - if (!wasSuccessful) { - wasSuccessful = drflac__seek_to_sample__brute_force(pFlac, sampleIndex); - } - } + drflac_int32 side0 = pInputSamples1[i*4+0] << shift1; + drflac_int32 side1 = pInputSamples1[i*4+1] << shift1; + drflac_int32 side2 = pInputSamples1[i*4+2] << shift1; + drflac_int32 side3 = pInputSamples1[i*4+3] << shift1; - pFlac->currentSample = sampleIndex; - return wasSuccessful; + drflac_int32 right0 = left0 - side0; + drflac_int32 right1 = left1 - side1; + drflac_int32 right2 = left2 - side2; + drflac_int32 right3 = left3 - side3; + + pOutputSamples[i*8+0] = left0 * factor; + pOutputSamples[i*8+1] = right0 * factor; + pOutputSamples[i*8+2] = left1 * factor; + pOutputSamples[i*8+3] = right1 * factor; + pOutputSamples[i*8+4] = left2 * factor; + pOutputSamples[i*8+5] = right2 * factor; + pOutputSamples[i*8+6] = left3 * factor; + pOutputSamples[i*8+7] = right3 * factor; } -} + for (i = (frameCount4 << 2); i < frameCount; ++i) { + int left = pInputSamples0[i] << shift0; + int side = pInputSamples1[i] << shift1; + int right = left - side; + pOutputSamples[i*2+0] = (float)(left * factor); + pOutputSamples[i*2+1] = (float)(right * factor); + } +} -//// High Level APIs //// +#if defined(DRFLAC_SUPPORT_SSE2) +static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_left_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_int32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples) +{ + drflac_uint64 frameCount4; + __m128 factor; + int shift0; + int shift1; + drflac_uint64 i; -// I couldn't figure out where SIZE_MAX was defined for VC6. If anybody knows, let me know. -#if defined(_MSC_VER) && _MSC_VER <= 1200 -#ifdef DRFLAC_64BIT -#define SIZE_MAX ((drflac_uint64)0xFFFFFFFFFFFFFFFF) -#else -#define SIZE_MAX 0xFFFFFFFF -#endif -#endif + drflac_assert(pFlac->bitsPerSample <= 24); -// Using a macro as the definition of the drflac__full_decode_and_close_*() API family. Sue me. -#define DRFLAC_DEFINE_FULL_DECODE_AND_CLOSE(extension, type) \ -static type* drflac__full_decode_and_close_ ## extension (drflac* pFlac, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalSampleCountOut)\ -{ \ - drflac_assert(pFlac != NULL); \ - \ - type* pSampleData = NULL; \ - drflac_uint64 totalSampleCount = pFlac->totalSampleCount; \ - \ - if (totalSampleCount == 0) { \ - type buffer[4096]; \ - \ - size_t sampleDataBufferSize = sizeof(buffer); \ - pSampleData = (type*)DRFLAC_MALLOC(sampleDataBufferSize); \ - if (pSampleData == NULL) { \ - goto on_error; \ - } \ - \ - drflac_uint64 samplesRead; \ - while ((samplesRead = (drflac_uint64)drflac_read_##extension(pFlac, sizeof(buffer)/sizeof(buffer[0]), buffer)) > 0) { \ - if (((totalSampleCount + samplesRead) * sizeof(type)) > sampleDataBufferSize) { \ - sampleDataBufferSize *= 2; \ - type* pNewSampleData = (type*)DRFLAC_REALLOC(pSampleData, sampleDataBufferSize); \ - if (pNewSampleData == NULL) { \ - DRFLAC_FREE(pSampleData); \ - goto on_error; \ - } \ - \ - pSampleData = pNewSampleData; \ - } \ - \ - drflac_copy_memory(pSampleData + totalSampleCount, buffer, (size_t)(samplesRead*sizeof(type))); \ - totalSampleCount += samplesRead; \ - } \ - \ - /* At this point everything should be decoded, but we just want to fill the unused part buffer with silence - need to \ - protect those ears from random noise! */ \ - drflac_zero_memory(pSampleData + totalSampleCount, (size_t)(sampleDataBufferSize - totalSampleCount*sizeof(type))); \ - } else { \ - drflac_uint64 dataSize = totalSampleCount * sizeof(type); \ - if (dataSize > SIZE_MAX) { \ - goto on_error; /* The decoded data is too big. */ \ - } \ - \ - pSampleData = (type*)DRFLAC_MALLOC((size_t)dataSize); /* <-- Safe cast as per the check above. */ \ - if (pSampleData == NULL) { \ - goto on_error; \ - } \ - \ - totalSampleCount = drflac_read_##extension(pFlac, pFlac->totalSampleCount, pSampleData); \ - } \ - \ - if (sampleRateOut) *sampleRateOut = pFlac->sampleRate; \ - if (channelsOut) *channelsOut = pFlac->channels; \ - if (totalSampleCountOut) *totalSampleCountOut = totalSampleCount; \ - \ - drflac_close(pFlac); \ - return pSampleData; \ - \ -on_error: \ - drflac_close(pFlac); \ - return NULL; \ -} + frameCount4 = frameCount >> 2; -DRFLAC_DEFINE_FULL_DECODE_AND_CLOSE(s32, drflac_int32) -DRFLAC_DEFINE_FULL_DECODE_AND_CLOSE(s16, drflac_int16) -DRFLAC_DEFINE_FULL_DECODE_AND_CLOSE(f32, float) + factor = _mm_set1_ps(1.0f / 8388608.0f); + shift0 = (unusedBitsPerSample + pFlac->currentFrame.subframes[0].wastedBitsPerSample) - 8; + shift1 = (unusedBitsPerSample + pFlac->currentFrame.subframes[1].wastedBitsPerSample) - 8; -drflac_int32* drflac_open_and_decode_s32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount) -{ - // Safety. - if (sampleRate) *sampleRate = 0; - if (channels) *channels = 0; - if (totalSampleCount) *totalSampleCount = 0; + for (i = 0; i < frameCount4; ++i) { + __m128i inputSample0 = _mm_loadu_si128((const __m128i*)pInputSamples0 + i); + __m128i inputSample1 = _mm_loadu_si128((const __m128i*)pInputSamples1 + i); - drflac* pFlac = drflac_open(onRead, onSeek, pUserData); - if (pFlac == NULL) { - return NULL; - } + __m128i left = _mm_slli_epi32(inputSample0, shift0); + __m128i side = _mm_slli_epi32(inputSample1, shift1); + __m128i right = _mm_sub_epi32(left, side); + __m128 leftf = _mm_mul_ps(_mm_cvtepi32_ps(left), factor); + __m128 rightf = _mm_mul_ps(_mm_cvtepi32_ps(right), factor); - return drflac__full_decode_and_close_s32(pFlac, channels, sampleRate, totalSampleCount); -} + pOutputSamples[i*8+0] = ((float*)&leftf)[0]; + pOutputSamples[i*8+1] = ((float*)&rightf)[0]; + pOutputSamples[i*8+2] = ((float*)&leftf)[1]; + pOutputSamples[i*8+3] = ((float*)&rightf)[1]; + pOutputSamples[i*8+4] = ((float*)&leftf)[2]; + pOutputSamples[i*8+5] = ((float*)&rightf)[2]; + pOutputSamples[i*8+6] = ((float*)&leftf)[3]; + pOutputSamples[i*8+7] = ((float*)&rightf)[3]; + } -drflac_int16* drflac_open_and_decode_s16(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount) -{ - // Safety. - if (sampleRate) *sampleRate = 0; - if (channels) *channels = 0; - if (totalSampleCount) *totalSampleCount = 0; + for (i = (frameCount4 << 2); i < frameCount; ++i) { + int left = pInputSamples0[i] << shift0; + int side = pInputSamples1[i] << shift1; + int right = left - side; - drflac* pFlac = drflac_open(onRead, onSeek, pUserData); - if (pFlac == NULL) { - return NULL; + pOutputSamples[i*2+0] = (float)(left / 8388608.0f); + pOutputSamples[i*2+1] = (float)(right / 8388608.0f); } - - return drflac__full_decode_and_close_s16(pFlac, channels, sampleRate, totalSampleCount); } +#endif -float* drflac_open_and_decode_f32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount) +static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_left_side(drflac* pFlac, drflac_uint64 frameCount, drflac_int32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples) { - // Safety. - if (sampleRate) *sampleRate = 0; - if (channels) *channels = 0; - if (totalSampleCount) *totalSampleCount = 0; - - drflac* pFlac = drflac_open(onRead, onSeek, pUserData); - if (pFlac == NULL) { - return NULL; +#if defined(DRFLAC_SUPPORT_SSE2) + if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) { + drflac_read_pcm_frames_f32__decode_left_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#endif + { + /* Scalar fallback. */ +#if 0 + drflac_read_pcm_frames_f32__decode_left_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#else + drflac_read_pcm_frames_f32__decode_left_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#endif } - - return drflac__full_decode_and_close_f32(pFlac, channels, sampleRate, totalSampleCount); } -#ifndef DR_FLAC_NO_STDIO -drflac_int32* drflac_open_and_decode_file_s32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount) + +#if 0 +static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_right_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_int32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples) { - if (sampleRate) *sampleRate = 0; - if (channels) *channels = 0; - if (totalSampleCount) *totalSampleCount = 0; + drflac_uint64 i; + for (i = 0; i < frameCount; ++i) { + int side = pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFrame.subframes[0].wastedBitsPerSample); + int right = pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFrame.subframes[1].wastedBitsPerSample); + int left = right + side; - drflac* pFlac = drflac_open_file(filename); - if (pFlac == NULL) { - return NULL; + pOutputSamples[i*2+0] = (float)(left / 2147483648.0); + pOutputSamples[i*2+1] = (float)(right / 2147483648.0); } - - return drflac__full_decode_and_close_s32(pFlac, channels, sampleRate, totalSampleCount); } +#endif -drflac_int16* drflac_open_and_decode_file_s16(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount) +static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_right_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_int32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples) { - if (sampleRate) *sampleRate = 0; - if (channels) *channels = 0; - if (totalSampleCount) *totalSampleCount = 0; + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; - drflac* pFlac = drflac_open_file(filename); - if (pFlac == NULL) { - return NULL; - } + float factor = 1 / 2147483648.0; - return drflac__full_decode_and_close_s16(pFlac, channels, sampleRate, totalSampleCount); -} + drflac_int32 shift0 = unusedBitsPerSample + pFlac->currentFrame.subframes[0].wastedBitsPerSample; + drflac_int32 shift1 = unusedBitsPerSample + pFlac->currentFrame.subframes[1].wastedBitsPerSample; + for (i = 0; i < frameCount4; ++i) { + drflac_int32 side0 = pInputSamples0[i*4+0] << shift0; + drflac_int32 side1 = pInputSamples0[i*4+1] << shift0; + drflac_int32 side2 = pInputSamples0[i*4+2] << shift0; + drflac_int32 side3 = pInputSamples0[i*4+3] << shift0; -float* drflac_open_and_decode_file_f32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount) -{ - if (sampleRate) *sampleRate = 0; - if (channels) *channels = 0; - if (totalSampleCount) *totalSampleCount = 0; + drflac_int32 right0 = pInputSamples1[i*4+0] << shift1; + drflac_int32 right1 = pInputSamples1[i*4+1] << shift1; + drflac_int32 right2 = pInputSamples1[i*4+2] << shift1; + drflac_int32 right3 = pInputSamples1[i*4+3] << shift1; - drflac* pFlac = drflac_open_file(filename); - if (pFlac == NULL) { - return NULL; + drflac_int32 left0 = right0 + side0; + drflac_int32 left1 = right1 + side1; + drflac_int32 left2 = right2 + side2; + drflac_int32 left3 = right3 + side3; + + pOutputSamples[i*8+0] = left0 * factor; + pOutputSamples[i*8+1] = right0 * factor; + pOutputSamples[i*8+2] = left1 * factor; + pOutputSamples[i*8+3] = right1 * factor; + pOutputSamples[i*8+4] = left2 * factor; + pOutputSamples[i*8+5] = right2 * factor; + pOutputSamples[i*8+6] = left3 * factor; + pOutputSamples[i*8+7] = right3 * factor; } - return drflac__full_decode_and_close_f32(pFlac, channels, sampleRate, totalSampleCount); + for (i = (frameCount4 << 2); i < frameCount; ++i) { + int side = pInputSamples0[i] << shift0; + int right = pInputSamples1[i] << shift1; + int left = right + side; + + pOutputSamples[i*2+0] = (float)(left * factor); + pOutputSamples[i*2+1] = (float)(right * factor); + } } -#endif -drflac_int32* drflac_open_and_decode_memory_s32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount) +#if defined(DRFLAC_SUPPORT_SSE2) +static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_right_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_int32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples) { - if (sampleRate) *sampleRate = 0; - if (channels) *channels = 0; - if (totalSampleCount) *totalSampleCount = 0; + drflac_uint64 frameCount4; + __m128 factor; + int shift0; + int shift1; + drflac_uint64 i; - drflac* pFlac = drflac_open_memory(data, dataSize); - if (pFlac == NULL) { - return NULL; - } + drflac_assert(pFlac->bitsPerSample <= 24); - return drflac__full_decode_and_close_s32(pFlac, channels, sampleRate, totalSampleCount); -} + frameCount4 = frameCount >> 2; -drflac_int16* drflac_open_and_decode_memory_s16(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount) -{ - if (sampleRate) *sampleRate = 0; - if (channels) *channels = 0; - if (totalSampleCount) *totalSampleCount = 0; + factor = _mm_set1_ps(1.0f / 8388608.0f); + shift0 = (unusedBitsPerSample + pFlac->currentFrame.subframes[0].wastedBitsPerSample) - 8; + shift1 = (unusedBitsPerSample + pFlac->currentFrame.subframes[1].wastedBitsPerSample) - 8; - drflac* pFlac = drflac_open_memory(data, dataSize); - if (pFlac == NULL) { - return NULL; - } + for (i = 0; i < frameCount4; ++i) { + __m128i inputSample0 = _mm_loadu_si128((const __m128i*)pInputSamples0 + i); + __m128i inputSample1 = _mm_loadu_si128((const __m128i*)pInputSamples1 + i); - return drflac__full_decode_and_close_s16(pFlac, channels, sampleRate, totalSampleCount); -} + __m128i side = _mm_slli_epi32(inputSample0, shift0); + __m128i right = _mm_slli_epi32(inputSample1, shift1); + __m128i left = _mm_add_epi32(right, side); + __m128 leftf = _mm_mul_ps(_mm_cvtepi32_ps(left), factor); + __m128 rightf = _mm_mul_ps(_mm_cvtepi32_ps(right), factor); -float* drflac_open_and_decode_memory_f32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount) -{ - if (sampleRate) *sampleRate = 0; - if (channels) *channels = 0; - if (totalSampleCount) *totalSampleCount = 0; + pOutputSamples[i*8+0] = ((float*)&leftf)[0]; + pOutputSamples[i*8+1] = ((float*)&rightf)[0]; + pOutputSamples[i*8+2] = ((float*)&leftf)[1]; + pOutputSamples[i*8+3] = ((float*)&rightf)[1]; + pOutputSamples[i*8+4] = ((float*)&leftf)[2]; + pOutputSamples[i*8+5] = ((float*)&rightf)[2]; + pOutputSamples[i*8+6] = ((float*)&leftf)[3]; + pOutputSamples[i*8+7] = ((float*)&rightf)[3]; + } - drflac* pFlac = drflac_open_memory(data, dataSize); + for (i = (frameCount4 << 2); i < frameCount; ++i) { + int side = pInputSamples0[i] << shift0; + int right = pInputSamples1[i] << shift1; + int left = right + side; + + pOutputSamples[i*2+0] = (float)(left / 8388608.0f); + pOutputSamples[i*2+1] = (float)(right / 8388608.0f); + } +} +#endif + +static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_right_side(drflac* pFlac, drflac_uint64 frameCount, drflac_int32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples) +{ +#if defined(DRFLAC_SUPPORT_SSE2) + if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) { + drflac_read_pcm_frames_f32__decode_right_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#endif + { + /* Scalar fallback. */ +#if 0 + drflac_read_pcm_frames_f32__decode_right_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#else + drflac_read_pcm_frames_f32__decode_right_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#endif + } +} + + +#if 0 +static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_mid_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_int32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples) +{ + for (drflac_uint64 i = 0; i < frameCount; ++i) { + int mid = pInputSamples0[i] << pFlac->currentFrame.subframes[0].wastedBitsPerSample; + int side = pInputSamples1[i] << pFlac->currentFrame.subframes[1].wastedBitsPerSample; + + mid = (((drflac_uint32)mid) << 1) | (side & 0x01); + + pOutputSamples[i*2+0] = (float)((((mid + side) >> 1) << (unusedBitsPerSample)) / 2147483648.0); + pOutputSamples[i*2+1] = (float)((((mid - side) >> 1) << (unusedBitsPerSample)) / 2147483648.0); + } +} +#endif + +static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_mid_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_int32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; + + float factor = 1 / 2147483648.0; + + int shift = unusedBitsPerSample; + if (shift > 0) { + shift -= 1; + for (i = 0; i < frameCount4; ++i) { + int temp0L; + int temp1L; + int temp2L; + int temp3L; + int temp0R; + int temp1R; + int temp2R; + int temp3R; + + int mid0 = pInputSamples0[i*4+0] << pFlac->currentFrame.subframes[0].wastedBitsPerSample; + int mid1 = pInputSamples0[i*4+1] << pFlac->currentFrame.subframes[0].wastedBitsPerSample; + int mid2 = pInputSamples0[i*4+2] << pFlac->currentFrame.subframes[0].wastedBitsPerSample; + int mid3 = pInputSamples0[i*4+3] << pFlac->currentFrame.subframes[0].wastedBitsPerSample; + + int side0 = pInputSamples1[i*4+0] << pFlac->currentFrame.subframes[1].wastedBitsPerSample; + int side1 = pInputSamples1[i*4+1] << pFlac->currentFrame.subframes[1].wastedBitsPerSample; + int side2 = pInputSamples1[i*4+2] << pFlac->currentFrame.subframes[1].wastedBitsPerSample; + int side3 = pInputSamples1[i*4+3] << pFlac->currentFrame.subframes[1].wastedBitsPerSample; + + mid0 = (((drflac_uint32)mid0) << 1) | (side0 & 0x01); + mid1 = (((drflac_uint32)mid1) << 1) | (side1 & 0x01); + mid2 = (((drflac_uint32)mid2) << 1) | (side2 & 0x01); + mid3 = (((drflac_uint32)mid3) << 1) | (side3 & 0x01); + + temp0L = ((mid0 + side0) << shift); + temp1L = ((mid1 + side1) << shift); + temp2L = ((mid2 + side2) << shift); + temp3L = ((mid3 + side3) << shift); + + temp0R = ((mid0 - side0) << shift); + temp1R = ((mid1 - side1) << shift); + temp2R = ((mid2 - side2) << shift); + temp3R = ((mid3 - side3) << shift); + + pOutputSamples[i*8+0] = (float)(temp0L * factor); + pOutputSamples[i*8+1] = (float)(temp0R * factor); + pOutputSamples[i*8+2] = (float)(temp1L * factor); + pOutputSamples[i*8+3] = (float)(temp1R * factor); + pOutputSamples[i*8+4] = (float)(temp2L * factor); + pOutputSamples[i*8+5] = (float)(temp2R * factor); + pOutputSamples[i*8+6] = (float)(temp3L * factor); + pOutputSamples[i*8+7] = (float)(temp3R * factor); + } + } else { + for (i = 0; i < frameCount4; ++i) { + int temp0L; + int temp1L; + int temp2L; + int temp3L; + int temp0R; + int temp1R; + int temp2R; + int temp3R; + + int mid0 = pInputSamples0[i*4+0] << pFlac->currentFrame.subframes[0].wastedBitsPerSample; + int mid1 = pInputSamples0[i*4+1] << pFlac->currentFrame.subframes[0].wastedBitsPerSample; + int mid2 = pInputSamples0[i*4+2] << pFlac->currentFrame.subframes[0].wastedBitsPerSample; + int mid3 = pInputSamples0[i*4+3] << pFlac->currentFrame.subframes[0].wastedBitsPerSample; + + int side0 = pInputSamples1[i*4+0] << pFlac->currentFrame.subframes[1].wastedBitsPerSample; + int side1 = pInputSamples1[i*4+1] << pFlac->currentFrame.subframes[1].wastedBitsPerSample; + int side2 = pInputSamples1[i*4+2] << pFlac->currentFrame.subframes[1].wastedBitsPerSample; + int side3 = pInputSamples1[i*4+3] << pFlac->currentFrame.subframes[1].wastedBitsPerSample; + + mid0 = (((drflac_uint32)mid0) << 1) | (side0 & 0x01); + mid1 = (((drflac_uint32)mid1) << 1) | (side1 & 0x01); + mid2 = (((drflac_uint32)mid2) << 1) | (side2 & 0x01); + mid3 = (((drflac_uint32)mid3) << 1) | (side3 & 0x01); + + temp0L = ((mid0 + side0) >> 1); + temp1L = ((mid1 + side1) >> 1); + temp2L = ((mid2 + side2) >> 1); + temp3L = ((mid3 + side3) >> 1); + + temp0R = ((mid0 - side0) >> 1); + temp1R = ((mid1 - side1) >> 1); + temp2R = ((mid2 - side2) >> 1); + temp3R = ((mid3 - side3) >> 1); + + pOutputSamples[i*8+0] = (float)(temp0L * factor); + pOutputSamples[i*8+1] = (float)(temp0R * factor); + pOutputSamples[i*8+2] = (float)(temp1L * factor); + pOutputSamples[i*8+3] = (float)(temp1R * factor); + pOutputSamples[i*8+4] = (float)(temp2L * factor); + pOutputSamples[i*8+5] = (float)(temp2R * factor); + pOutputSamples[i*8+6] = (float)(temp3L * factor); + pOutputSamples[i*8+7] = (float)(temp3R * factor); + } + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + int mid = pInputSamples0[i] << pFlac->currentFrame.subframes[0].wastedBitsPerSample; + int side = pInputSamples1[i] << pFlac->currentFrame.subframes[1].wastedBitsPerSample; + + mid = (((drflac_uint32)mid) << 1) | (side & 0x01); + + pOutputSamples[i*2+0] = (float)((((mid + side) >> 1) << unusedBitsPerSample) * factor); + pOutputSamples[i*2+1] = (float)((((mid - side) >> 1) << unusedBitsPerSample) * factor); + } +} + +#if defined(DRFLAC_SUPPORT_SSE2) +static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_mid_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_int32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4; + float factor; + int shift; + __m128 factor128; + + drflac_assert(pFlac->bitsPerSample <= 24); + + frameCount4 = frameCount >> 2; + + factor = 1.0f / 8388608.0f; + factor128 = _mm_set1_ps(1.0f / 8388608.0f); + + shift = unusedBitsPerSample - 8; + if (shift == 0) { + for (i = 0; i < frameCount4; ++i) { + __m128i tempL; + __m128i tempR; + __m128 leftf; + __m128 rightf; + + __m128i inputSample0 = _mm_loadu_si128((const __m128i*)pInputSamples0 + i); + __m128i inputSample1 = _mm_loadu_si128((const __m128i*)pInputSamples1 + i); + + __m128i mid = _mm_slli_epi32(inputSample0, pFlac->currentFrame.subframes[0].wastedBitsPerSample); + __m128i side = _mm_slli_epi32(inputSample1, pFlac->currentFrame.subframes[1].wastedBitsPerSample); + + mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01))); + + tempL = _mm_add_epi32(mid, side); + tempR = _mm_sub_epi32(mid, side); + + /* Signed bit shift. */ + tempL = _mm_or_si128(_mm_srli_epi32(tempL, 1), _mm_and_si128(tempL, _mm_set1_epi32(0x80000000))); + tempR = _mm_or_si128(_mm_srli_epi32(tempR, 1), _mm_and_si128(tempR, _mm_set1_epi32(0x80000000))); + + leftf = _mm_mul_ps(_mm_cvtepi32_ps(tempL), factor128); + rightf = _mm_mul_ps(_mm_cvtepi32_ps(tempR), factor128); + + pOutputSamples[i*8+0] = ((float*)&leftf)[0]; + pOutputSamples[i*8+1] = ((float*)&rightf)[0]; + pOutputSamples[i*8+2] = ((float*)&leftf)[1]; + pOutputSamples[i*8+3] = ((float*)&rightf)[1]; + pOutputSamples[i*8+4] = ((float*)&leftf)[2]; + pOutputSamples[i*8+5] = ((float*)&rightf)[2]; + pOutputSamples[i*8+6] = ((float*)&leftf)[3]; + pOutputSamples[i*8+7] = ((float*)&rightf)[3]; + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + int mid = pInputSamples0[i] << pFlac->currentFrame.subframes[0].wastedBitsPerSample; + int side = pInputSamples1[i] << pFlac->currentFrame.subframes[1].wastedBitsPerSample; + + mid = (((drflac_uint32)mid) << 1) | (side & 0x01); + + pOutputSamples[i*2+0] = (float)(((mid + side) >> 1) * factor); + pOutputSamples[i*2+1] = (float)(((mid - side) >> 1) * factor); + } + } else { + for (i = 0; i < frameCount4; ++i) { + __m128i inputSample0; + __m128i inputSample1; + __m128i mid; + __m128i side; + __m128i tempL; + __m128i tempR; + __m128 leftf; + __m128 rightf; + + inputSample0 = _mm_loadu_si128((const __m128i*)pInputSamples0 + i); + inputSample1 = _mm_loadu_si128((const __m128i*)pInputSamples1 + i); + + mid = _mm_slli_epi32(inputSample0, pFlac->currentFrame.subframes[0].wastedBitsPerSample); + side = _mm_slli_epi32(inputSample1, pFlac->currentFrame.subframes[1].wastedBitsPerSample); + + mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01))); + + tempL = _mm_slli_epi32(_mm_srli_epi32(_mm_add_epi32(mid, side), 1), shift); + tempR = _mm_slli_epi32(_mm_srli_epi32(_mm_sub_epi32(mid, side), 1), shift); + + leftf = _mm_mul_ps(_mm_cvtepi32_ps(tempL), factor128); + rightf = _mm_mul_ps(_mm_cvtepi32_ps(tempR), factor128); + + pOutputSamples[i*8+0] = ((float*)&leftf)[0]; + pOutputSamples[i*8+1] = ((float*)&rightf)[0]; + pOutputSamples[i*8+2] = ((float*)&leftf)[1]; + pOutputSamples[i*8+3] = ((float*)&rightf)[1]; + pOutputSamples[i*8+4] = ((float*)&leftf)[2]; + pOutputSamples[i*8+5] = ((float*)&rightf)[2]; + pOutputSamples[i*8+6] = ((float*)&leftf)[3]; + pOutputSamples[i*8+7] = ((float*)&rightf)[3]; + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + int mid = pInputSamples0[i] << pFlac->currentFrame.subframes[0].wastedBitsPerSample; + int side = pInputSamples1[i] << pFlac->currentFrame.subframes[1].wastedBitsPerSample; + + mid = (((drflac_uint32)mid) << 1) | (side & 0x01); + + pOutputSamples[i*2+0] = (float)((((mid + side) >> 1) << shift) * factor); + pOutputSamples[i*2+1] = (float)((((mid - side) >> 1) << shift) * factor); + } + } +} +#endif + + +static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_mid_side(drflac* pFlac, drflac_uint64 frameCount, drflac_int32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples) +{ +#if defined(DRFLAC_SUPPORT_SSE2) + if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) { + drflac_read_pcm_frames_f32__decode_mid_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#endif + { + /* Scalar fallback. */ +#if 0 + drflac_read_pcm_frames_f32__decode_mid_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#else + drflac_read_pcm_frames_f32__decode_mid_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#endif + } +} + +#if 0 +static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_independent_stereo__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_int32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples) +{ + for (drflac_uint64 i = 0; i < frameCount; ++i) { + pOutputSamples[i*2+0] = (float)((pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFrame.subframes[0].wastedBitsPerSample)) / 2147483648.0); + pOutputSamples[i*2+1] = (float)((pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFrame.subframes[1].wastedBitsPerSample)) / 2147483648.0); + } +} +#endif + +static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_independent_stereo__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_int32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; + + float factor = 1 / 2147483648.0; + + int shift0 = (unusedBitsPerSample + pFlac->currentFrame.subframes[0].wastedBitsPerSample); + int shift1 = (unusedBitsPerSample + pFlac->currentFrame.subframes[1].wastedBitsPerSample); + + for (i = 0; i < frameCount4; ++i) { + int tempL0 = pInputSamples0[i*4+0] << shift0; + int tempL1 = pInputSamples0[i*4+1] << shift0; + int tempL2 = pInputSamples0[i*4+2] << shift0; + int tempL3 = pInputSamples0[i*4+3] << shift0; + + int tempR0 = pInputSamples1[i*4+0] << shift1; + int tempR1 = pInputSamples1[i*4+1] << shift1; + int tempR2 = pInputSamples1[i*4+2] << shift1; + int tempR3 = pInputSamples1[i*4+3] << shift1; + + pOutputSamples[i*8+0] = (float)(tempL0 * factor); + pOutputSamples[i*8+1] = (float)(tempR0 * factor); + pOutputSamples[i*8+2] = (float)(tempL1 * factor); + pOutputSamples[i*8+3] = (float)(tempR1 * factor); + pOutputSamples[i*8+4] = (float)(tempL2 * factor); + pOutputSamples[i*8+5] = (float)(tempR2 * factor); + pOutputSamples[i*8+6] = (float)(tempL3 * factor); + pOutputSamples[i*8+7] = (float)(tempR3 * factor); + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + pOutputSamples[i*2+0] = (float)((pInputSamples0[i] << shift0) * factor); + pOutputSamples[i*2+1] = (float)((pInputSamples1[i] << shift1) * factor); + } +} + +#if defined(DRFLAC_SUPPORT_SSE2) +static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_independent_stereo__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_int32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples) +{ + drflac_uint64 i; + drflac_uint64 frameCount4 = frameCount >> 2; + + float factor = 1.0f / 8388608.0f; + __m128 factor128 = _mm_set1_ps(1.0f / 8388608.0f); + + int shift0 = (unusedBitsPerSample + pFlac->currentFrame.subframes[0].wastedBitsPerSample) - 8; + int shift1 = (unusedBitsPerSample + pFlac->currentFrame.subframes[1].wastedBitsPerSample) - 8; + + for (i = 0; i < frameCount4; ++i) { + __m128i inputSample0 = _mm_loadu_si128((const __m128i*)pInputSamples0 + i); + __m128i inputSample1 = _mm_loadu_si128((const __m128i*)pInputSamples1 + i); + + __m128i i32L = _mm_slli_epi32(inputSample0, shift0); + __m128i i32R = _mm_slli_epi32(inputSample1, shift1); + + __m128 f32L = _mm_mul_ps(_mm_cvtepi32_ps(i32L), factor128); + __m128 f32R = _mm_mul_ps(_mm_cvtepi32_ps(i32R), factor128); + + pOutputSamples[i*8+0] = ((float*)&f32L)[0]; + pOutputSamples[i*8+1] = ((float*)&f32R)[0]; + pOutputSamples[i*8+2] = ((float*)&f32L)[1]; + pOutputSamples[i*8+3] = ((float*)&f32R)[1]; + pOutputSamples[i*8+4] = ((float*)&f32L)[2]; + pOutputSamples[i*8+5] = ((float*)&f32R)[2]; + pOutputSamples[i*8+6] = ((float*)&f32L)[3]; + pOutputSamples[i*8+7] = ((float*)&f32R)[3]; + } + + for (i = (frameCount4 << 2); i < frameCount; ++i) { + pOutputSamples[i*2+0] = (float)((pInputSamples0[i] << shift0) * factor); + pOutputSamples[i*2+1] = (float)((pInputSamples1[i] << shift1) * factor); + } +} +#endif + +static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_independent_stereo(drflac* pFlac, drflac_uint64 frameCount, drflac_int32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples) +{ +#if defined(DRFLAC_SUPPORT_SSE2) + if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) { + drflac_read_pcm_frames_f32__decode_independent_stereo__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); + } else +#endif + { + /* Scalar fallback. */ +#if 0 + drflac_read_pcm_frames_f32__decode_independent_stereo__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#else + drflac_read_pcm_frames_f32__decode_independent_stereo__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples); +#endif + } +} + +drflac_uint64 drflac_read_pcm_frames_f32(drflac* pFlac, drflac_uint64 framesToRead, float* pBufferOut) +{ + drflac_uint64 framesRead; + + if (pFlac == NULL || framesToRead == 0) { + return 0; + } + + if (pBufferOut == NULL) { + return drflac__seek_forward_by_pcm_frames(pFlac, framesToRead); + } + + framesRead = 0; + while (framesToRead > 0) { + /* If we've run out of samples in this frame, go to the next. */ + if (pFlac->currentFrame.samplesRemaining == 0) { + if (!drflac__read_and_decode_next_flac_frame(pFlac)) { + break; /* Couldn't read the next frame, so just break from the loop and return. */ + } + } else { + unsigned int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFrame.header.channelAssignment); + drflac_uint64 totalFramesInPacket = pFlac->currentFrame.header.blockSize; + drflac_uint64 framesReadFromPacketSoFar = totalFramesInPacket - (pFlac->currentFrame.samplesRemaining/channelCount); + drflac_uint64 iFirstPCMFrame = framesReadFromPacketSoFar; + drflac_int32 unusedBitsPerSample = 32 - pFlac->bitsPerSample; + drflac_uint64 frameCountThisIteration = framesToRead; + drflac_uint64 samplesReadThisIteration; + + if (frameCountThisIteration > pFlac->currentFrame.samplesRemaining / channelCount) { + frameCountThisIteration = pFlac->currentFrame.samplesRemaining / channelCount; + } + + if (channelCount == 2) { + const drflac_int32* pDecodedSamples0 = pFlac->currentFrame.subframes[0].pDecodedSamples + iFirstPCMFrame; + const drflac_int32* pDecodedSamples1 = pFlac->currentFrame.subframes[1].pDecodedSamples + iFirstPCMFrame; + + switch (pFlac->currentFrame.header.channelAssignment) + { + case DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE: + { + drflac_read_pcm_frames_f32__decode_left_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut); + } break; + + case DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE: + { + drflac_read_pcm_frames_f32__decode_right_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut); + } break; + + case DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE: + { + drflac_read_pcm_frames_f32__decode_mid_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut); + } break; + + case DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT: + default: + { + drflac_read_pcm_frames_f32__decode_independent_stereo(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut); + } break; + } + } else { + /* Generic interleaving. */ + drflac_uint64 i; + for (i = 0; i < frameCountThisIteration; ++i) { + unsigned int j; + for (j = 0; j < channelCount; ++j) { + pBufferOut[(i*channelCount)+j] = (float)(((pFlac->currentFrame.subframes[j].pDecodedSamples[iFirstPCMFrame + i]) << (unusedBitsPerSample + pFlac->currentFrame.subframes[j].wastedBitsPerSample)) / 2147483648.0); + } + } + } + + samplesReadThisIteration = frameCountThisIteration * channelCount; + framesRead += frameCountThisIteration; + framesReadFromPacketSoFar += frameCountThisIteration; + pBufferOut += samplesReadThisIteration; + framesToRead -= frameCountThisIteration; + pFlac->currentSample += samplesReadThisIteration; + pFlac->currentFrame.samplesRemaining -= (unsigned int)samplesReadThisIteration; + } + } + + return framesRead; +} + +drflac_bool32 drflac_seek_to_sample(drflac* pFlac, drflac_uint64 sampleIndex) +{ + if (pFlac == NULL) { + return DRFLAC_FALSE; + } + + /* + If we don't know where the first frame begins then we can't seek. This will happen when the STREAMINFO block was not present + when the decoder was opened. + */ + if (pFlac->firstFramePos == 0) { + return DRFLAC_FALSE; + } + + if (sampleIndex == 0) { + pFlac->currentSample = 0; + return drflac__seek_to_first_frame(pFlac); + } else { + drflac_bool32 wasSuccessful = DRFLAC_FALSE; + + /* Clamp the sample to the end. */ + if (sampleIndex >= pFlac->totalSampleCount) { + sampleIndex = pFlac->totalSampleCount - 1; + } + + /* If the target sample and the current sample are in the same frame we just move the position forward. */ + if (sampleIndex > pFlac->currentSample) { + /* Forward. */ + drflac_uint32 offset = (drflac_uint32)(sampleIndex - pFlac->currentSample); + if (pFlac->currentFrame.samplesRemaining > offset) { + pFlac->currentFrame.samplesRemaining -= offset; + pFlac->currentSample = sampleIndex; + return DRFLAC_TRUE; + } + } else { + /* Backward. */ + drflac_uint32 offsetAbs = (drflac_uint32)(pFlac->currentSample - sampleIndex); + drflac_uint32 currentFrameSampleCount = pFlac->currentFrame.header.blockSize * drflac__get_channel_count_from_channel_assignment(pFlac->currentFrame.header.channelAssignment); + drflac_uint32 currentFrameSamplesConsumed = (drflac_uint32)(currentFrameSampleCount - pFlac->currentFrame.samplesRemaining); + if (currentFrameSamplesConsumed > offsetAbs) { + pFlac->currentFrame.samplesRemaining += offsetAbs; + pFlac->currentSample = sampleIndex; + return DRFLAC_TRUE; + } + } + + /* + Different techniques depending on encapsulation. Using the native FLAC seektable with Ogg encapsulation is a bit awkward so + we'll instead use Ogg's natural seeking facility. + */ +#ifndef DR_FLAC_NO_OGG + if (pFlac->container == drflac_container_ogg) + { + wasSuccessful = drflac_ogg__seek_to_sample(pFlac, sampleIndex); + } + else +#endif + { + /* First try seeking via the seek table. If this fails, fall back to a brute force seek which is much slower. */ + wasSuccessful = drflac__seek_to_sample__seek_table(pFlac, sampleIndex); + if (!wasSuccessful) { + wasSuccessful = drflac__seek_to_sample__brute_force(pFlac, sampleIndex); + } + } + + pFlac->currentSample = sampleIndex; + return wasSuccessful; + } +} + +drflac_bool32 drflac_seek_to_pcm_frame(drflac* pFlac, drflac_uint64 pcmFrameIndex) +{ + if (pFlac == NULL) { + return DRFLAC_FALSE; + } + + /* + If we don't know where the first frame begins then we can't seek. This will happen when the STREAMINFO block was not present + when the decoder was opened. + */ + if (pFlac->firstFramePos == 0) { + return DRFLAC_FALSE; + } + + if (pcmFrameIndex == 0) { + pFlac->currentSample = 0; + return drflac__seek_to_first_frame(pFlac); + } else { + drflac_bool32 wasSuccessful = DRFLAC_FALSE; + + /* Clamp the sample to the end. */ + if (pcmFrameIndex >= pFlac->totalPCMFrameCount) { + pcmFrameIndex = pFlac->totalPCMFrameCount - 1; + } + + /* If the target sample and the current sample are in the same frame we just move the position forward. */ + if (pcmFrameIndex*pFlac->channels > pFlac->currentSample) { + /* Forward. */ + drflac_uint32 offset = (drflac_uint32)(pcmFrameIndex*pFlac->channels - pFlac->currentSample); + if (pFlac->currentFrame.samplesRemaining > offset) { + pFlac->currentFrame.samplesRemaining -= offset; + pFlac->currentSample = pcmFrameIndex*pFlac->channels; + return DRFLAC_TRUE; + } + } else { + /* Backward. */ + drflac_uint32 offsetAbs = (drflac_uint32)(pFlac->currentSample - pcmFrameIndex*pFlac->channels); + drflac_uint32 currentFrameSampleCount = pFlac->currentFrame.header.blockSize * drflac__get_channel_count_from_channel_assignment(pFlac->currentFrame.header.channelAssignment); + drflac_uint32 currentFrameSamplesConsumed = (drflac_uint32)(currentFrameSampleCount - pFlac->currentFrame.samplesRemaining); + if (currentFrameSamplesConsumed > offsetAbs) { + pFlac->currentFrame.samplesRemaining += offsetAbs; + pFlac->currentSample = pcmFrameIndex*pFlac->channels; + return DRFLAC_TRUE; + } + } + + /* + Different techniques depending on encapsulation. Using the native FLAC seektable with Ogg encapsulation is a bit awkward so + we'll instead use Ogg's natural seeking facility. + */ +#ifndef DR_FLAC_NO_OGG + if (pFlac->container == drflac_container_ogg) + { + wasSuccessful = drflac_ogg__seek_to_sample(pFlac, pcmFrameIndex*pFlac->channels); + } + else +#endif + { + /* First try seeking via the seek table. If this fails, fall back to a brute force seek which is much slower. */ + wasSuccessful = drflac__seek_to_sample__seek_table(pFlac, pcmFrameIndex*pFlac->channels); + if (!wasSuccessful) { + wasSuccessful = drflac__seek_to_sample__brute_force(pFlac, pcmFrameIndex*pFlac->channels); + } + } + + pFlac->currentSample = pcmFrameIndex*pFlac->channels; + return wasSuccessful; + } +} + + + +/* High Level APIs */ + +#if defined(SIZE_MAX) + #define DRFLAC_SIZE_MAX SIZE_MAX +#else + #if defined(DRFLAC_64BIT) + #define DRFLAC_SIZE_MAX ((drflac_uint64)0xFFFFFFFFFFFFFFFF) + #else + #define DRFLAC_SIZE_MAX 0xFFFFFFFF + #endif +#endif + + +/* Using a macro as the definition of the drflac__full_decode_and_close_*() API family. Sue me. */ +#define DRFLAC_DEFINE_FULL_READ_AND_CLOSE(extension, type) \ +static type* drflac__full_read_and_close_ ## extension (drflac* pFlac, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalPCMFrameCountOut)\ +{ \ + type* pSampleData = NULL; \ + drflac_uint64 totalPCMFrameCount; \ + \ + drflac_assert(pFlac != NULL); \ + \ + totalPCMFrameCount = pFlac->totalPCMFrameCount; \ + \ + if (totalPCMFrameCount == 0) { \ + type buffer[4096]; \ + drflac_uint64 pcmFramesRead; \ + size_t sampleDataBufferSize = sizeof(buffer); \ + \ + pSampleData = (type*)DRFLAC_MALLOC(sampleDataBufferSize); \ + if (pSampleData == NULL) { \ + goto on_error; \ + } \ + \ + while ((pcmFramesRead = (drflac_uint64)drflac_read_pcm_frames_##extension(pFlac, sizeof(buffer)/sizeof(buffer[0])/pFlac->channels, buffer)) > 0) { \ + if (((totalPCMFrameCount + pcmFramesRead) * pFlac->channels * sizeof(type)) > sampleDataBufferSize) { \ + type* pNewSampleData; \ + \ + sampleDataBufferSize *= 2; \ + pNewSampleData = (type*)DRFLAC_REALLOC(pSampleData, sampleDataBufferSize); \ + if (pNewSampleData == NULL) { \ + DRFLAC_FREE(pSampleData); \ + goto on_error; \ + } \ + \ + pSampleData = pNewSampleData; \ + } \ + \ + drflac_copy_memory(pSampleData + (totalPCMFrameCount*pFlac->channels), buffer, (size_t)(pcmFramesRead*pFlac->channels*sizeof(type))); \ + totalPCMFrameCount += pcmFramesRead; \ + } \ + \ + /* At this point everything should be decoded, but we just want to fill the unused part buffer with silence - need to \ + protect those ears from random noise! */ \ + drflac_zero_memory(pSampleData + (totalPCMFrameCount*pFlac->channels), (size_t)(sampleDataBufferSize - totalPCMFrameCount*pFlac->channels*sizeof(type))); \ + } else { \ + drflac_uint64 dataSize = totalPCMFrameCount*pFlac->channels*sizeof(type); \ + if (dataSize > DRFLAC_SIZE_MAX) { \ + goto on_error; /* The decoded data is too big. */ \ + } \ + \ + pSampleData = (type*)DRFLAC_MALLOC((size_t)dataSize); /* <-- Safe cast as per the check above. */ \ + if (pSampleData == NULL) { \ + goto on_error; \ + } \ + \ + totalPCMFrameCount = drflac_read_pcm_frames_##extension(pFlac, pFlac->totalPCMFrameCount, pSampleData); \ + } \ + \ + if (sampleRateOut) *sampleRateOut = pFlac->sampleRate; \ + if (channelsOut) *channelsOut = pFlac->channels; \ + if (totalPCMFrameCountOut) *totalPCMFrameCountOut = totalPCMFrameCount; \ + \ + drflac_close(pFlac); \ + return pSampleData; \ + \ +on_error: \ + drflac_close(pFlac); \ + return NULL; \ +} + +DRFLAC_DEFINE_FULL_READ_AND_CLOSE(s32, drflac_int32) +DRFLAC_DEFINE_FULL_READ_AND_CLOSE(s16, drflac_int16) +DRFLAC_DEFINE_FULL_READ_AND_CLOSE(f32, float) + +drflac_int32* drflac_open_and_read_pcm_frames_s32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalPCMFrameCountOut) +{ + drflac* pFlac; + + if (channelsOut) { + *channelsOut = 0; + } + if (sampleRateOut) { + *sampleRateOut = 0; + } + if (totalPCMFrameCountOut) { + *totalPCMFrameCountOut = 0; + } + + pFlac = drflac_open(onRead, onSeek, pUserData); + if (pFlac == NULL) { + return NULL; + } + + return drflac__full_read_and_close_s32(pFlac, channelsOut, sampleRateOut, totalPCMFrameCountOut); +} + +drflac_int32* drflac_open_and_decode_s32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalSampleCountOut) +{ + unsigned int channels; + unsigned int sampleRate; + drflac_uint64 totalPCMFrameCount; + drflac_int32* pResult; + + if (channelsOut) { + *channelsOut = 0; + } + if (sampleRateOut) { + *sampleRateOut = 0; + } + if (totalSampleCountOut) { + *totalSampleCountOut = 0; + } + + pResult = drflac_open_and_read_pcm_frames_s32(onRead, onSeek, pUserData, &channels, &sampleRate, &totalPCMFrameCount); + if (pResult == NULL) { + return NULL; + } + + if (channelsOut) { + *channelsOut = channels; + } + if (sampleRateOut) { + *sampleRateOut = sampleRate; + } + if (totalSampleCountOut) { + *totalSampleCountOut = totalPCMFrameCount * channels; + } + + return pResult; +} + + + +drflac_int16* drflac_open_and_read_pcm_frames_s16(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalPCMFrameCountOut) +{ + drflac* pFlac; + + if (channelsOut) { + *channelsOut = 0; + } + if (sampleRateOut) { + *sampleRateOut = 0; + } + if (totalPCMFrameCountOut) { + *totalPCMFrameCountOut = 0; + } + + pFlac = drflac_open(onRead, onSeek, pUserData); + if (pFlac == NULL) { + return NULL; + } + + return drflac__full_read_and_close_s16(pFlac, channelsOut, sampleRateOut, totalPCMFrameCountOut); +} + +drflac_int16* drflac_open_and_decode_s16(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalSampleCountOut) +{ + unsigned int channels; + unsigned int sampleRate; + drflac_uint64 totalPCMFrameCount; + drflac_int16* pResult; + + if (channelsOut) { + *channelsOut = 0; + } + if (sampleRateOut) { + *sampleRateOut = 0; + } + if (totalSampleCountOut) { + *totalSampleCountOut = 0; + } + + pResult = drflac_open_and_read_pcm_frames_s16(onRead, onSeek, pUserData, &channels, &sampleRate, &totalPCMFrameCount); + if (pResult == NULL) { + return NULL; + } + + if (channelsOut) { + *channelsOut = channels; + } + if (sampleRateOut) { + *sampleRateOut = sampleRate; + } + if (totalSampleCountOut) { + *totalSampleCountOut = totalPCMFrameCount * channels; + } + + return pResult; +} + + +float* drflac_open_and_read_pcm_frames_f32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalPCMFrameCountOut) +{ + drflac* pFlac; + + if (channelsOut) { + *channelsOut = 0; + } + if (sampleRateOut) { + *sampleRateOut = 0; + } + if (totalPCMFrameCountOut) { + *totalPCMFrameCountOut = 0; + } + + pFlac = drflac_open(onRead, onSeek, pUserData); + if (pFlac == NULL) { + return NULL; + } + + return drflac__full_read_and_close_f32(pFlac, channelsOut, sampleRateOut, totalPCMFrameCountOut); +} + +float* drflac_open_and_decode_f32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalSampleCountOut) +{ + unsigned int channels; + unsigned int sampleRate; + drflac_uint64 totalPCMFrameCount; + float* pResult; + + if (channelsOut) { + *channelsOut = 0; + } + if (sampleRateOut) { + *sampleRateOut = 0; + } + if (totalSampleCountOut) { + *totalSampleCountOut = 0; + } + + pResult = drflac_open_and_read_pcm_frames_f32(onRead, onSeek, pUserData, &channels, &sampleRate, &totalPCMFrameCount); + if (pResult == NULL) { + return NULL; + } + + if (channelsOut) { + *channelsOut = channels; + } + if (sampleRateOut) { + *sampleRateOut = sampleRate; + } + if (totalSampleCountOut) { + *totalSampleCountOut = totalPCMFrameCount * channels; + } + + return pResult; +} + +#ifndef DR_FLAC_NO_STDIO +drflac_int32* drflac_open_file_and_read_pcm_frames_s32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount) +{ + drflac* pFlac; + + if (sampleRate) { + *sampleRate = 0; + } + if (channels) { + *channels = 0; + } + if (totalPCMFrameCount) { + *totalPCMFrameCount = 0; + } + + pFlac = drflac_open_file(filename); + if (pFlac == NULL) { + return NULL; + } + + return drflac__full_read_and_close_s32(pFlac, channels, sampleRate, totalPCMFrameCount); +} + +drflac_int32* drflac_open_and_decode_file_s32(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalSampleCountOut) +{ + unsigned int channels; + unsigned int sampleRate; + drflac_uint64 totalPCMFrameCount; + drflac_int32* pResult; + + if (channelsOut) { + *channelsOut = 0; + } + if (sampleRateOut) { + *sampleRateOut = 0; + } + if (totalSampleCountOut) { + *totalSampleCountOut = 0; + } + + pResult = drflac_open_file_and_read_pcm_frames_s32(filename, &channels, &sampleRate, &totalPCMFrameCount); + if (pResult == NULL) { + return NULL; + } + + if (channelsOut) { + *channelsOut = channels; + } + if (sampleRateOut) { + *sampleRateOut = sampleRate; + } + if (totalSampleCountOut) { + *totalSampleCountOut = totalPCMFrameCount * channels; + } + + return pResult; +} + + +drflac_int16* drflac_open_file_and_read_pcm_frames_s16(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount) +{ + drflac* pFlac; + + if (sampleRate) { + *sampleRate = 0; + } + if (channels) { + *channels = 0; + } + if (totalPCMFrameCount) { + *totalPCMFrameCount = 0; + } + + pFlac = drflac_open_file(filename); + if (pFlac == NULL) { + return NULL; + } + + return drflac__full_read_and_close_s16(pFlac, channels, sampleRate, totalPCMFrameCount); +} + +drflac_int16* drflac_open_and_decode_file_s16(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalSampleCountOut) +{ + unsigned int channels; + unsigned int sampleRate; + drflac_uint64 totalPCMFrameCount; + drflac_int16* pResult; + + if (channelsOut) { + *channelsOut = 0; + } + if (sampleRateOut) { + *sampleRateOut = 0; + } + if (totalSampleCountOut) { + *totalSampleCountOut = 0; + } + + pResult = drflac_open_file_and_read_pcm_frames_s16(filename, &channels, &sampleRate, &totalPCMFrameCount); + if (pResult == NULL) { + return NULL; + } + + if (channelsOut) { + *channelsOut = channels; + } + if (sampleRateOut) { + *sampleRateOut = sampleRate; + } + if (totalSampleCountOut) { + *totalSampleCountOut = totalPCMFrameCount * channels; + } + + return pResult; +} + + +float* drflac_open_file_and_read_pcm_frames_f32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount) +{ + drflac* pFlac; + + if (sampleRate) { + *sampleRate = 0; + } + if (channels) { + *channels = 0; + } + if (totalPCMFrameCount) { + *totalPCMFrameCount = 0; + } + + pFlac = drflac_open_file(filename); + if (pFlac == NULL) { + return NULL; + } + + return drflac__full_read_and_close_f32(pFlac, channels, sampleRate, totalPCMFrameCount); +} + +float* drflac_open_and_decode_file_f32(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalSampleCountOut) +{ + unsigned int channels; + unsigned int sampleRate; + drflac_uint64 totalPCMFrameCount; + float* pResult; + + if (channelsOut) { + *channelsOut = 0; + } + if (sampleRateOut) { + *sampleRateOut = 0; + } + if (totalSampleCountOut) { + *totalSampleCountOut = 0; + } + + pResult = drflac_open_file_and_read_pcm_frames_f32(filename, &channels, &sampleRate, &totalPCMFrameCount); + if (pResult == NULL) { + return NULL; + } + + if (channelsOut) { + *channelsOut = channels; + } + if (sampleRateOut) { + *sampleRateOut = sampleRate; + } + if (totalSampleCountOut) { + *totalSampleCountOut = totalPCMFrameCount * channels; + } + + return pResult; +} +#endif + +drflac_int32* drflac_open_memory_and_read_pcm_frames_s32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount) +{ + drflac* pFlac; + + if (sampleRate) { + *sampleRate = 0; + } + if (channels) { + *channels = 0; + } + if (totalPCMFrameCount) { + *totalPCMFrameCount = 0; + } + + pFlac = drflac_open_memory(data, dataSize); + if (pFlac == NULL) { + return NULL; + } + + return drflac__full_read_and_close_s32(pFlac, channels, sampleRate, totalPCMFrameCount); +} + +drflac_int32* drflac_open_and_decode_memory_s32(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalSampleCountOut) +{ + unsigned int channels; + unsigned int sampleRate; + drflac_uint64 totalPCMFrameCount; + drflac_int32* pResult; + + if (channelsOut) { + *channelsOut = 0; + } + if (sampleRateOut) { + *sampleRateOut = 0; + } + if (totalSampleCountOut) { + *totalSampleCountOut = 0; + } + + pResult = drflac_open_memory_and_read_pcm_frames_s32(data, dataSize, &channels, &sampleRate, &totalPCMFrameCount); + if (pResult == NULL) { + return NULL; + } + + if (channelsOut) { + *channelsOut = channels; + } + if (sampleRateOut) { + *sampleRateOut = sampleRate; + } + if (totalSampleCountOut) { + *totalSampleCountOut = totalPCMFrameCount * channels; + } + + return pResult; +} + + +drflac_int16* drflac_open_memory_and_read_pcm_frames_s16(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount) +{ + drflac* pFlac; + + if (sampleRate) { + *sampleRate = 0; + } + if (channels) { + *channels = 0; + } + if (totalPCMFrameCount) { + *totalPCMFrameCount = 0; + } + + pFlac = drflac_open_memory(data, dataSize); + if (pFlac == NULL) { + return NULL; + } + + return drflac__full_read_and_close_s16(pFlac, channels, sampleRate, totalPCMFrameCount); +} + +drflac_int16* drflac_open_and_decode_memory_s16(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalSampleCountOut) +{ + unsigned int channels; + unsigned int sampleRate; + drflac_uint64 totalPCMFrameCount; + drflac_int16* pResult; + + if (channelsOut) { + *channelsOut = 0; + } + if (sampleRateOut) { + *sampleRateOut = 0; + } + if (totalSampleCountOut) { + *totalSampleCountOut = 0; + } + + pResult = drflac_open_memory_and_read_pcm_frames_s16(data, dataSize, &channels, &sampleRate, &totalPCMFrameCount); + if (pResult == NULL) { + return NULL; + } + + if (channelsOut) { + *channelsOut = channels; + } + if (sampleRateOut) { + *sampleRateOut = sampleRate; + } + if (totalSampleCountOut) { + *totalSampleCountOut = totalPCMFrameCount * channels; + } + + return pResult; +} + + +float* drflac_open_memory_and_read_pcm_frames_f32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount) +{ + drflac* pFlac; + + if (sampleRate) { + *sampleRate = 0; + } + if (channels) { + *channels = 0; + } + if (totalPCMFrameCount) { + *totalPCMFrameCount = 0; + } + + pFlac = drflac_open_memory(data, dataSize); if (pFlac == NULL) { return NULL; } - return drflac__full_decode_and_close_f32(pFlac, channels, sampleRate, totalSampleCount); + return drflac__full_read_and_close_f32(pFlac, channels, sampleRate, totalPCMFrameCount); +} + +float* drflac_open_and_decode_memory_f32(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalSampleCountOut) +{ + unsigned int channels; + unsigned int sampleRate; + drflac_uint64 totalPCMFrameCount; + float* pResult; + + if (channelsOut) { + *channelsOut = 0; + } + if (sampleRateOut) { + *sampleRateOut = 0; + } + if (totalSampleCountOut) { + *totalSampleCountOut = 0; + } + + pResult = drflac_open_memory_and_read_pcm_frames_f32(data, dataSize, &channels, &sampleRate, &totalPCMFrameCount); + if (pResult == NULL) { + return NULL; + } + + if (channelsOut) { + *channelsOut = channels; + } + if (sampleRateOut) { + *sampleRateOut = sampleRate; + } + if (totalSampleCountOut) { + *totalSampleCountOut = totalPCMFrameCount * channels; + } + + return pResult; } + void drflac_free(void* pSampleDataReturnedByOpenAndDecode) { DRFLAC_FREE(pSampleDataReturnedByOpenAndDecode); @@ -5687,208 +8556,347 @@ void drflac_free(void* pSampleDataReturnedByOpenAndDecode) -void drflac_init_vorbis_comment_iterator(drflac_vorbis_comment_iterator* pIter, drflac_uint32 commentCount, const char* pComments) +void drflac_init_vorbis_comment_iterator(drflac_vorbis_comment_iterator* pIter, drflac_uint32 commentCount, const void* pComments) { if (pIter == NULL) { return; } pIter->countRemaining = commentCount; - pIter->pRunningData = pComments; + pIter->pRunningData = (const char*)pComments; } const char* drflac_next_vorbis_comment(drflac_vorbis_comment_iterator* pIter, drflac_uint32* pCommentLengthOut) { - // Safety. - if (pCommentLengthOut) *pCommentLengthOut = 0; + drflac_int32 length; + const char* pComment; + + /* Safety. */ + if (pCommentLengthOut) { + *pCommentLengthOut = 0; + } if (pIter == NULL || pIter->countRemaining == 0 || pIter->pRunningData == NULL) { return NULL; } - drflac_uint32 length = drflac__le2host_32(*(drflac_uint32*)pIter->pRunningData); + length = drflac__le2host_32(*(const drflac_uint32*)pIter->pRunningData); pIter->pRunningData += 4; - const char* pComment = pIter->pRunningData; + pComment = pIter->pRunningData; pIter->pRunningData += length; pIter->countRemaining -= 1; - if (pCommentLengthOut) *pCommentLengthOut = length; + if (pCommentLengthOut) { + *pCommentLengthOut = length; + } + return pComment; } -#endif //DR_FLAC_IMPLEMENTATION - - -// REVISION HISTORY -// -// v0.9.7 - 2018-07-05 -// - Fix a warning. -// -// v0.9.6 - 2018-06-29 -// - Fix some typos. -// -// v0.9.5 - 2018-06-23 -// - Fix some warnings. -// -// v0.9.4 - 2018-06-14 -// - Optimizations to seeking. -// - Clean up. -// -// v0.9.3 - 2018-05-22 -// - Bug fix. -// -// v0.9.2 - 2018-05-12 -// - Fix a compilation error due to a missing break statement. -// -// v0.9.1 - 2018-04-29 -// - Fix compilation error with Clang. -// -// v0.9 - 2018-04-24 -// - Fix Clang build. -// - Start using major.minor.revision versioning. -// -// v0.8g - 2018-04-19 -// - Fix build on non-x86/x64 architectures. -// -// v0.8f - 2018-02-02 -// - Stop pretending to support changing rate/channels mid stream. -// -// v0.8e - 2018-02-01 -// - Fix a crash when the block size of a frame is larger than the maximum block size defined by the FLAC stream. -// - Fix a crash the the Rice partition order is invalid. -// -// v0.8d - 2017-09-22 -// - Add support for decoding streams with ID3 tags. ID3 tags are just skipped. -// -// v0.8c - 2017-09-07 -// - Fix warning on non-x86/x64 architectures. -// -// v0.8b - 2017-08-19 -// - Fix build on non-x86/x64 architectures. -// -// v0.8a - 2017-08-13 -// - A small optimization for the Clang build. -// -// v0.8 - 2017-08-12 -// - API CHANGE: Rename dr_* types to drflac_*. -// - Optimizations. This brings dr_flac back to about the same class of efficiency as the reference implementation. -// - Add support for custom implementations of malloc(), realloc(), etc. -// - Add CRC checking to Ogg encapsulated streams. -// - Fix VC++ 6 build. This is only for the C++ compiler. The C compiler is not currently supported. -// - Bug fixes. -// -// v0.7 - 2017-07-23 -// - Add support for opening a stream without a header block. To do this, use drflac_open_relaxed() / drflac_open_with_metadata_relaxed(). -// -// v0.6 - 2017-07-22 -// - Add support for recovering from invalid frames. With this change, dr_flac will simply skip over invalid frames as if they -// never existed. Frames are checked against their sync code, the CRC-8 of the frame header and the CRC-16 of the whole frame. -// -// v0.5 - 2017-07-16 -// - Fix typos. -// - Change drflac_bool* types to unsigned. -// - Add CRC checking. This makes dr_flac slower, but can be disabled with #define DR_FLAC_NO_CRC. -// -// v0.4f - 2017-03-10 -// - Fix a couple of bugs with the bitstreaming code. -// -// v0.4e - 2017-02-17 -// - Fix some warnings. -// -// v0.4d - 2016-12-26 -// - Add support for 32-bit floating-point PCM decoding. -// - Use drflac_int*/drflac_uint* sized types to improve compiler support. -// - Minor improvements to documentation. -// -// v0.4c - 2016-12-26 -// - Add support for signed 16-bit integer PCM decoding. -// -// v0.4b - 2016-10-23 -// - A minor change to drflac_bool8 and drflac_bool32 types. -// -// v0.4a - 2016-10-11 -// - Rename drBool32 to drflac_bool32 for styling consistency. -// -// v0.4 - 2016-09-29 -// - API/ABI CHANGE: Use fixed size 32-bit booleans instead of the built-in bool type. -// - API CHANGE: Rename drflac_open_and_decode*() to drflac_open_and_decode*_s32(). -// - API CHANGE: Swap the order of "channels" and "sampleRate" parameters in drflac_open_and_decode*(). Rationale for this is to -// keep it consistent with drflac_audio. -// -// v0.3f - 2016-09-21 -// - Fix a warning with GCC. -// -// v0.3e - 2016-09-18 -// - Fixed a bug where GCC 4.3+ was not getting properly identified. -// - Fixed a few typos. -// - Changed date formats to ISO 8601 (YYYY-MM-DD). -// -// v0.3d - 2016-06-11 -// - Minor clean up. -// -// v0.3c - 2016-05-28 -// - Fixed compilation error. -// -// v0.3b - 2016-05-16 -// - Fixed Linux/GCC build. -// - Updated documentation. -// -// v0.3a - 2016-05-15 -// - Minor fixes to documentation. -// -// v0.3 - 2016-05-11 -// - Optimizations. Now at about parity with the reference implementation on 32-bit builds. -// - Lots of clean up. -// -// v0.2b - 2016-05-10 -// - Bug fixes. -// -// v0.2a - 2016-05-10 -// - Made drflac_open_and_decode() more robust. -// - Removed an unused debugging variable -// -// v0.2 - 2016-05-09 -// - Added support for Ogg encapsulation. -// - API CHANGE. Have the onSeek callback take a third argument which specifies whether or not the seek -// should be relative to the start or the current position. Also changes the seeking rules such that -// seeking offsets will never be negative. -// - Have drflac_open_and_decode() fail gracefully if the stream has an unknown total sample count. -// -// v0.1b - 2016-05-07 -// - Properly close the file handle in drflac_open_file() and family when the decoder fails to initialize. -// - Removed a stale comment. -// -// v0.1a - 2016-05-05 -// - Minor formatting changes. -// - Fixed a warning on the GCC build. -// -// v0.1 - 2016-05-03 -// - Initial versioned release. + + +void drflac_init_cuesheet_track_iterator(drflac_cuesheet_track_iterator* pIter, drflac_uint32 trackCount, const void* pTrackData) +{ + if (pIter == NULL) { + return; + } + + pIter->countRemaining = trackCount; + pIter->pRunningData = (const char*)pTrackData; +} + +drflac_bool32 drflac_next_cuesheet_track(drflac_cuesheet_track_iterator* pIter, drflac_cuesheet_track* pCuesheetTrack) +{ + drflac_cuesheet_track cuesheetTrack; + const char* pRunningData; + drflac_uint64 offsetHi; + drflac_uint64 offsetLo; + + if (pIter == NULL || pIter->countRemaining == 0 || pIter->pRunningData == NULL) { + return DRFLAC_FALSE; + } + + pRunningData = pIter->pRunningData; + + offsetHi = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4; + offsetLo = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4; + cuesheetTrack.offset = offsetLo | (offsetHi << 32); + cuesheetTrack.trackNumber = pRunningData[0]; pRunningData += 1; + drflac_copy_memory(cuesheetTrack.ISRC, pRunningData, sizeof(cuesheetTrack.ISRC)); pRunningData += 12; + cuesheetTrack.isAudio = (pRunningData[0] & 0x80) != 0; + cuesheetTrack.preEmphasis = (pRunningData[0] & 0x40) != 0; pRunningData += 14; + cuesheetTrack.indexCount = pRunningData[0]; pRunningData += 1; + cuesheetTrack.pIndexPoints = (const drflac_cuesheet_track_index*)pRunningData; pRunningData += cuesheetTrack.indexCount * sizeof(drflac_cuesheet_track_index); + + pIter->pRunningData = pRunningData; + pIter->countRemaining -= 1; + + if (pCuesheetTrack) { + *pCuesheetTrack = cuesheetTrack; + } + + return DRFLAC_TRUE; +} + +#if defined(__GNUC__) + #pragma GCC diagnostic pop +#endif +#endif /* DR_FLAC_IMPLEMENTATION */ + + +/* +REVISION HISTORY +================ +v0.11.7 - 2019-05-06 + - C89 fixes. + +v0.11.6 - 2019-05-05 + - Add support for C89. + - Fix a compiler warning when CRC is disabled. + - Change license to choice of public domain or MIT-0. + +v0.11.5 - 2019-04-19 + - Fix a compiler error with GCC. + +v0.11.4 - 2019-04-17 + - Fix some warnings with GCC when compiling with -std=c99. + +v0.11.3 - 2019-04-07 + - Silence warnings with GCC. + +v0.11.2 - 2019-03-10 + - Fix a warning. + +v0.11.1 - 2019-02-17 + - Fix a potential bug with seeking. + +v0.11.0 - 2018-12-16 + - API CHANGE: Deprecated drflac_read_s32(), drflac_read_s16() and drflac_read_f32() and replaced them with + drflac_read_pcm_frames_s32(), drflac_read_pcm_frames_s16() and drflac_read_pcm_frames_f32(). The new APIs take + and return PCM frame counts instead of sample counts. To upgrade you will need to change the input count by + dividing it by the channel count, and then do the same with the return value. + - API_CHANGE: Deprecated drflac_seek_to_sample() and replaced with drflac_seek_to_pcm_frame(). Same rules as + the changes to drflac_read_*() apply. + - API CHANGE: Deprecated drflac_open_and_decode_*() and replaced with drflac_open_*_and_read_*(). Same rules as + the changes to drflac_read_*() apply. + - Optimizations. + +v0.10.0 - 2018-09-11 + - Remove the DR_FLAC_NO_WIN32_IO option and the Win32 file IO functionality. If you need to use Win32 file IO you + need to do it yourself via the callback API. + - Fix the clang build. + - Fix undefined behavior. + - Fix errors with CUESHEET metdata blocks. + - Add an API for iterating over each cuesheet track in the CUESHEET metadata block. This works the same way as the + Vorbis comment API. + - Other miscellaneous bug fixes, mostly relating to invalid FLAC streams. + - Minor optimizations. + +v0.9.11 - 2018-08-29 + - Fix a bug with sample reconstruction. + +v0.9.10 - 2018-08-07 + - Improve 64-bit detection. + +v0.9.9 - 2018-08-05 + - Fix C++ build on older versions of GCC. + +v0.9.8 - 2018-07-24 + - Fix compilation errors. + +v0.9.7 - 2018-07-05 + - Fix a warning. + +v0.9.6 - 2018-06-29 + - Fix some typos. + +v0.9.5 - 2018-06-23 + - Fix some warnings. + +v0.9.4 - 2018-06-14 + - Optimizations to seeking. + - Clean up. + +v0.9.3 - 2018-05-22 + - Bug fix. + +v0.9.2 - 2018-05-12 + - Fix a compilation error due to a missing break statement. + +v0.9.1 - 2018-04-29 + - Fix compilation error with Clang. + +v0.9 - 2018-04-24 + - Fix Clang build. + - Start using major.minor.revision versioning. + +v0.8g - 2018-04-19 + - Fix build on non-x86/x64 architectures. + +v0.8f - 2018-02-02 + - Stop pretending to support changing rate/channels mid stream. + +v0.8e - 2018-02-01 + - Fix a crash when the block size of a frame is larger than the maximum block size defined by the FLAC stream. + - Fix a crash the the Rice partition order is invalid. + +v0.8d - 2017-09-22 + - Add support for decoding streams with ID3 tags. ID3 tags are just skipped. + +v0.8c - 2017-09-07 + - Fix warning on non-x86/x64 architectures. + +v0.8b - 2017-08-19 + - Fix build on non-x86/x64 architectures. + +v0.8a - 2017-08-13 + - A small optimization for the Clang build. + +v0.8 - 2017-08-12 + - API CHANGE: Rename dr_* types to drflac_*. + - Optimizations. This brings dr_flac back to about the same class of efficiency as the reference implementation. + - Add support for custom implementations of malloc(), realloc(), etc. + - Add CRC checking to Ogg encapsulated streams. + - Fix VC++ 6 build. This is only for the C++ compiler. The C compiler is not currently supported. + - Bug fixes. + +v0.7 - 2017-07-23 + - Add support for opening a stream without a header block. To do this, use drflac_open_relaxed() / drflac_open_with_metadata_relaxed(). + +v0.6 - 2017-07-22 + - Add support for recovering from invalid frames. With this change, dr_flac will simply skip over invalid frames as if they + never existed. Frames are checked against their sync code, the CRC-8 of the frame header and the CRC-16 of the whole frame. + +v0.5 - 2017-07-16 + - Fix typos. + - Change drflac_bool* types to unsigned. + - Add CRC checking. This makes dr_flac slower, but can be disabled with #define DR_FLAC_NO_CRC. + +v0.4f - 2017-03-10 + - Fix a couple of bugs with the bitstreaming code. + +v0.4e - 2017-02-17 + - Fix some warnings. + +v0.4d - 2016-12-26 + - Add support for 32-bit floating-point PCM decoding. + - Use drflac_int* and drflac_uint* sized types to improve compiler support. + - Minor improvements to documentation. + +v0.4c - 2016-12-26 + - Add support for signed 16-bit integer PCM decoding. + +v0.4b - 2016-10-23 + - A minor change to drflac_bool8 and drflac_bool32 types. + +v0.4a - 2016-10-11 + - Rename drBool32 to drflac_bool32 for styling consistency. + +v0.4 - 2016-09-29 + - API/ABI CHANGE: Use fixed size 32-bit booleans instead of the built-in bool type. + - API CHANGE: Rename drflac_open_and_decode*() to drflac_open_and_decode*_s32(). + - API CHANGE: Swap the order of "channels" and "sampleRate" parameters in drflac_open_and_decode*(). Rationale for this is to + keep it consistent with drflac_audio. + +v0.3f - 2016-09-21 + - Fix a warning with GCC. + +v0.3e - 2016-09-18 + - Fixed a bug where GCC 4.3+ was not getting properly identified. + - Fixed a few typos. + - Changed date formats to ISO 8601 (YYYY-MM-DD). + +v0.3d - 2016-06-11 + - Minor clean up. + +v0.3c - 2016-05-28 + - Fixed compilation error. + +v0.3b - 2016-05-16 + - Fixed Linux/GCC build. + - Updated documentation. + +v0.3a - 2016-05-15 + - Minor fixes to documentation. + +v0.3 - 2016-05-11 + - Optimizations. Now at about parity with the reference implementation on 32-bit builds. + - Lots of clean up. + +v0.2b - 2016-05-10 + - Bug fixes. + +v0.2a - 2016-05-10 + - Made drflac_open_and_decode() more robust. + - Removed an unused debugging variable + +v0.2 - 2016-05-09 + - Added support for Ogg encapsulation. + - API CHANGE. Have the onSeek callback take a third argument which specifies whether or not the seek + should be relative to the start or the current position. Also changes the seeking rules such that + seeking offsets will never be negative. + - Have drflac_open_and_decode() fail gracefully if the stream has an unknown total sample count. + +v0.1b - 2016-05-07 + - Properly close the file handle in drflac_open_file() and family when the decoder fails to initialize. + - Removed a stale comment. + +v0.1a - 2016-05-05 + - Minor formatting changes. + - Fixed a warning on the GCC build. + +v0.1 - 2016-05-03 + - Initial versioned release. +*/ + /* +This software is available as a choice of the following licenses. Choose +whichever you prefer. + +=============================================================================== +ALTERNATIVE 1 - Public Domain (www.unlicense.org) +=============================================================================== This is free and unencumbered software released into the public domain. -Anyone is free to copy, modify, publish, use, compile, sell, or -distribute this software, either in source code form or as a compiled -binary, for any purpose, commercial or non-commercial, and by any -means. - -In jurisdictions that recognize copyright laws, the author or authors -of this software dedicate any and all copyright interest in the -software to the public domain. We make this dedication for the benefit -of the public at large and to the detriment of our heirs and -successors. We intend this dedication to be an overt act of -relinquishment in perpetuity of all present and future rights to this -software under copyright law. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR -OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, -ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. + +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to + +=============================================================================== +ALTERNATIVE 2 - MIT No Attribution +=============================================================================== +Copyright 2018 David Reid + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. */ diff --git a/src/external/dr_mp3.h b/src/external/dr_mp3.h index 070f0c15..26aeec56 100644 --- a/src/external/dr_mp3.h +++ b/src/external/dr_mp3.h @@ -1,57 +1,61 @@ -// MP3 audio decoder. Public domain. See "unlicense" statement at the end of this file. -// dr_mp3 - v0.4.0 - 2018-xx-xx -// -// David Reid - mackron@gmail.com -// -// Based off minimp3 (https://github.com/lieff/minimp3) which is where the real work was done. See the bottom of this file for -// differences between minimp3 and dr_mp3. - -// USAGE -// ===== -// dr_mp3 is a single-file library. To use it, do something like the following in one .c file. -// #define DR_MP3_IMPLEMENTATION -// #include "dr_mp3.h" -// -// You can then #include this file in other parts of the program as you would with any other header file. To decode audio data, -// do something like the following: -// -// drmp3 mp3; -// if (!drmp3_init_file(&mp3, "MySong.mp3", NULL)) { -// // Failed to open file -// } -// -// ... -// -// drmp3_uint64 framesRead = drmp3_read_f32(pMP3, framesToRead, pFrames); -// -// The drmp3 object is transparent so you can get access to the channel count and sample rate like so: -// -// drmp3_uint32 channels = mp3.channels; -// drmp3_uint32 sampleRate = mp3.sampleRate; -// -// The third parameter of drmp3_init_file() in the example above allows you to control the output channel count and sample rate. It -// is a pointer to a drmp3_config object. Setting any of the variables of this object to 0 will cause dr_mp3 to use defaults. -// -// The example above initializes a decoder from a file, but you can also initialize it from a block of memory and read and seek -// callbacks with drmp3_init_memory() and drmp3_init() respectively. -// -// You do need to do any annoying memory management when reading PCM frames - this is all managed internally. You can request -// any number of PCM frames in each call to drmp3_read_f32() and it will return as many PCM frames as it can, up to the requested -// amount. -// -// You can also decode an entire file in one go with drmp3_open_and_decode_f32(), drmp3_open_and_decode_memory_f32() and -// drmp3_open_and_decode_file_f32(). -// -// -// OPTIONS -// ======= -// #define these options before including this file. -// -// #define DR_MP3_NO_STDIO -// Disable drmp3_init_file(), etc. -// -// #define DR_MP3_NO_SIMD -// Disable SIMD optimizations. +/* +MP3 audio decoder. Choice of public domain or MIT-0. See license statements at the end of this file. +dr_mp3 - v0.4.4 - 2019-05-06 + +David Reid - mackron@gmail.com + +Based off minimp3 (https://github.com/lieff/minimp3) which is where the real work was done. See the bottom of this file for +differences between minimp3 and dr_mp3. +*/ + +/* +USAGE +===== +dr_mp3 is a single-file library. To use it, do something like the following in one .c file. + #define DR_MP3_IMPLEMENTATION + #include "dr_mp3.h" + +You can then #include this file in other parts of the program as you would with any other header file. To decode audio data, +do something like the following: + + drmp3 mp3; + if (!drmp3_init_file(&mp3, "MySong.mp3", NULL)) { + // Failed to open file + } + + ... + + drmp3_uint64 framesRead = drmp3_read_pcm_frames_f32(pMP3, framesToRead, pFrames); + +The drmp3 object is transparent so you can get access to the channel count and sample rate like so: + + drmp3_uint32 channels = mp3.channels; + drmp3_uint32 sampleRate = mp3.sampleRate; + +The third parameter of drmp3_init_file() in the example above allows you to control the output channel count and sample rate. It +is a pointer to a drmp3_config object. Setting any of the variables of this object to 0 will cause dr_mp3 to use defaults. + +The example above initializes a decoder from a file, but you can also initialize it from a block of memory and read and seek +callbacks with drmp3_init_memory() and drmp3_init() respectively. + +You do not need to do any annoying memory management when reading PCM frames - this is all managed internally. You can request +any number of PCM frames in each call to drmp3_read_pcm_frames_f32() and it will return as many PCM frames as it can, up to the +requested amount. + +You can also decode an entire file in one go with drmp3_open_and_read_f32(), drmp3_open_memory_and_read_f32() and +drmp3_open_file_and_read_f32(). + + +OPTIONS +======= +#define these options before including this file. + +#define DR_MP3_NO_STDIO + Disable drmp3_init_file(), etc. + +#define DR_MP3_NO_SIMD + Disable SIMD optimizations. +*/ #ifndef dr_mp3_h #define dr_mp3_h @@ -90,9 +94,20 @@ typedef drmp3_uint32 drmp3_bool32; #define DRMP3_MAX_PCM_FRAMES_PER_MP3_FRAME 1152 #define DRMP3_MAX_SAMPLES_PER_FRAME (DRMP3_MAX_PCM_FRAMES_PER_MP3_FRAME*2) +#ifdef _MSC_VER +#define DRMP3_INLINE __forceinline +#else +#ifdef __GNUC__ +#define DRMP3_INLINE __inline__ __attribute__((always_inline)) +#else +#define DRMP3_INLINE +#endif +#endif -// Low Level Push API -// ================== +/* +Low Level Push API +================== +*/ typedef struct { int frame_bytes, channels, hz, layer, bitrate_kbps; @@ -105,23 +120,30 @@ typedef struct unsigned char header[4], reserv_buf[511]; } drmp3dec; -// Initializes a low level decoder. +/* Initializes a low level decoder. */ void drmp3dec_init(drmp3dec *dec); -// Reads a frame from a low level decoder. +/* Reads a frame from a low level decoder. */ int drmp3dec_decode_frame(drmp3dec *dec, const unsigned char *mp3, int mp3_bytes, void *pcm, drmp3dec_frame_info *info); -// Helper for converting between f32 and s16. +/* Helper for converting between f32 and s16. */ void drmp3dec_f32_to_s16(const float *in, drmp3_int16 *out, int num_samples); - -// Main API (Pull API) -// =================== +/* +Main API (Pull API) +=================== +*/ +#ifndef DR_MP3_DEFAULT_CHANNELS +#define DR_MP3_DEFAULT_CHANNELS 2 +#endif +#ifndef DR_MP3_DEFAULT_SAMPLE_RATE +#define DR_MP3_DEFAULT_SAMPLE_RATE 44100 +#endif typedef struct drmp3_src drmp3_src; -typedef drmp3_uint64 (* drmp3_src_read_proc)(drmp3_src* pSRC, drmp3_uint64 frameCount, void* pFramesOut, void* pUserData); // Returns the number of frames that were read. +typedef drmp3_uint64 (* drmp3_src_read_proc)(drmp3_src* pSRC, drmp3_uint64 frameCount, void* pFramesOut, void* pUserData); /* Returns the number of frames that were read. */ typedef enum { @@ -144,7 +166,7 @@ typedef struct drmp3_uint32 sampleRateOut; drmp3_uint32 channels; drmp3_src_algorithm algorithm; - drmp3_uint32 cacheSizeInFrames; // The number of frames to read from the client at a time. + drmp3_uint32 cacheSizeInFrames; /* The number of frames to read from the client at a time. */ } drmp3_src_config; struct drmp3_src @@ -153,12 +175,12 @@ struct drmp3_src drmp3_src_read_proc onRead; void* pUserData; float bin[256]; - drmp3_src_cache cache; // <-- For simplifying and optimizing client -> memory reading. + drmp3_src_cache cache; /* <-- For simplifying and optimizing client -> memory reading. */ union { struct { - float alpha; + double alpha; drmp3_bool32 isPrevFramesLoaded : 1; drmp3_bool32 isNextFramesLoaded : 1; } linear; @@ -171,28 +193,40 @@ typedef enum drmp3_seek_origin_current } drmp3_seek_origin; -// Callback for when data is read. Return value is the number of bytes actually read. -// -// pUserData [in] The user data that was passed to drmp3_init(), drmp3_open() and family. -// pBufferOut [out] The output buffer. -// bytesToRead [in] The number of bytes to read. -// -// Returns the number of bytes actually read. -// -// A return value of less than bytesToRead indicates the end of the stream. Do _not_ return from this callback until -// either the entire bytesToRead is filled or you have reached the end of the stream. +typedef struct +{ + drmp3_uint64 seekPosInBytes; /* Points to the first byte of an MP3 frame. */ + drmp3_uint64 pcmFrameIndex; /* The index of the PCM frame this seek point targets. */ + drmp3_uint16 mp3FramesToDiscard; /* The number of whole MP3 frames to be discarded before pcmFramesToDiscard. */ + drmp3_uint16 pcmFramesToDiscard; /* The number of leading samples to read and discard. These are discarded after mp3FramesToDiscard. */ +} drmp3_seek_point; + +/* +Callback for when data is read. Return value is the number of bytes actually read. + +pUserData [in] The user data that was passed to drmp3_init(), drmp3_open() and family. +pBufferOut [out] The output buffer. +bytesToRead [in] The number of bytes to read. + +Returns the number of bytes actually read. + +A return value of less than bytesToRead indicates the end of the stream. Do _not_ return from this callback until +either the entire bytesToRead is filled or you have reached the end of the stream. +*/ typedef size_t (* drmp3_read_proc)(void* pUserData, void* pBufferOut, size_t bytesToRead); -// Callback for when data needs to be seeked. -// -// pUserData [in] The user data that was passed to drmp3_init(), drmp3_open() and family. -// offset [in] The number of bytes to move, relative to the origin. Will never be negative. -// origin [in] The origin of the seek - the current position or the start of the stream. -// -// Returns whether or not the seek was successful. -// -// Whether or not it is relative to the beginning or current position is determined by the "origin" parameter which -// will be either drmp3_seek_origin_start or drmp3_seek_origin_current. +/* +Callback for when data needs to be seeked. + +pUserData [in] The user data that was passed to drmp3_init(), drmp3_open() and family. +offset [in] The number of bytes to move, relative to the origin. Will never be negative. +origin [in] The origin of the seek - the current position or the start of the stream. + +Returns whether or not the seek was successful. + +Whether or not it is relative to the beginning or current position is determined by the "origin" parameter which +will be either drmp3_seek_origin_start or drmp3_seek_origin_current. +*/ typedef drmp3_bool32 (* drmp3_seek_proc)(void* pUserData, int offset, drmp3_seek_origin origin); typedef struct @@ -210,13 +244,16 @@ typedef struct drmp3_read_proc onRead; drmp3_seek_proc onSeek; void* pUserData; - drmp3_uint32 mp3FrameChannels; // The number of channels in the currently loaded MP3 frame. Internal use only. - drmp3_uint32 mp3FrameSampleRate; // The sample rate of the currently loaded MP3 frame. Internal use only. + drmp3_uint32 mp3FrameChannels; /* The number of channels in the currently loaded MP3 frame. Internal use only. */ + drmp3_uint32 mp3FrameSampleRate; /* The sample rate of the currently loaded MP3 frame. Internal use only. */ drmp3_uint32 pcmFramesConsumedInMP3Frame; drmp3_uint32 pcmFramesRemainingInMP3Frame; - drmp3_uint8 pcmFrames[sizeof(float)*DRMP3_MAX_SAMPLES_PER_FRAME]; // <-- Multipled by sizeof(float) to ensure there's enough room for DR_MP3_FLOAT_OUTPUT. - drmp3_uint64 currentPCMFrame; // The current PCM frame, globally, based on the output sample rate. Mainly used for seeking. + drmp3_uint8 pcmFrames[sizeof(float)*DRMP3_MAX_SAMPLES_PER_FRAME]; /* <-- Multipled by sizeof(float) to ensure there's enough room for DR_MP3_FLOAT_OUTPUT. */ + drmp3_uint64 currentPCMFrame; /* The current PCM frame, globally, based on the output sample rate. Mainly used for seeking. */ + drmp3_uint64 streamCursor; /* The current byte the decoder is sitting on in the raw stream. */ drmp3_src src; + drmp3_seek_point* pSeekPoints; /* NULL by default. Set with drmp3_bind_seek_table(). Memory is owned by the client. dr_mp3 will never attempt to free this pointer. */ + drmp3_uint32 seekPointCount; /* The number of items in pSeekPoints. When set to 0 assumes to no seek table. Defaults to zero. */ size_t dataSize; size_t dataCapacity; drmp3_uint8* pData; @@ -226,94 +263,155 @@ typedef struct const drmp3_uint8* pData; size_t dataSize; size_t currentReadPos; - } memory; // Only used for decoders that were opened against a block of memory. + } memory; /* Only used for decoders that were opened against a block of memory. */ } drmp3; -// Initializes an MP3 decoder. -// -// onRead [in] The function to call when data needs to be read from the client. -// onSeek [in] The function to call when the read position of the client data needs to move. -// pUserData [in, optional] A pointer to application defined data that will be passed to onRead and onSeek. -// -// Returns true if successful; false otherwise. -// -// Close the loader with drmp3_uninit(). -// -// See also: drmp3_init_file(), drmp3_init_memory(), drmp3_uninit() +/* +Initializes an MP3 decoder. + +onRead [in] The function to call when data needs to be read from the client. +onSeek [in] The function to call when the read position of the client data needs to move. +pUserData [in, optional] A pointer to application defined data that will be passed to onRead and onSeek. + +Returns true if successful; false otherwise. + +Close the loader with drmp3_uninit(). + +See also: drmp3_init_file(), drmp3_init_memory(), drmp3_uninit() +*/ drmp3_bool32 drmp3_init(drmp3* pMP3, drmp3_read_proc onRead, drmp3_seek_proc onSeek, void* pUserData, const drmp3_config* pConfig); -// Initializes an MP3 decoder from a block of memory. -// -// This does not create a copy of the data. It is up to the application to ensure the buffer remains valid for -// the lifetime of the drmp3 object. -// -// The buffer should contain the contents of the entire MP3 file. +/* +Initializes an MP3 decoder from a block of memory. + +This does not create a copy of the data. It is up to the application to ensure the buffer remains valid for +the lifetime of the drmp3 object. + +The buffer should contain the contents of the entire MP3 file. +*/ drmp3_bool32 drmp3_init_memory(drmp3* pMP3, const void* pData, size_t dataSize, const drmp3_config* pConfig); #ifndef DR_MP3_NO_STDIO -// Initializes an MP3 decoder from a file. -// -// This holds the internal FILE object until drmp3_uninit() is called. Keep this in mind if you're caching drmp3 -// objects because the operating system may restrict the number of file handles an application can have open at -// any given time. +/* +Initializes an MP3 decoder from a file. + +This holds the internal FILE object until drmp3_uninit() is called. Keep this in mind if you're caching drmp3 +objects because the operating system may restrict the number of file handles an application can have open at +any given time. +*/ drmp3_bool32 drmp3_init_file(drmp3* pMP3, const char* filePath, const drmp3_config* pConfig); #endif -// Uninitializes an MP3 decoder. +/* +Uninitializes an MP3 decoder. +*/ void drmp3_uninit(drmp3* pMP3); -// Reads PCM frames as interleaved 32-bit IEEE floating point PCM. -// -// Note that framesToRead specifies the number of PCM frames to read, _not_ the number of MP3 frames. +/* +Reads PCM frames as interleaved 32-bit IEEE floating point PCM. + +Note that framesToRead specifies the number of PCM frames to read, _not_ the number of MP3 frames. +*/ drmp3_uint64 drmp3_read_pcm_frames_f32(drmp3* pMP3, drmp3_uint64 framesToRead, float* pBufferOut); -// Seeks to a specific frame. -// -// Note that this is _not_ an MP3 frame, but rather a PCM frame. +/* +Reads PCM frames as interleaved signed 16-bit integer PCM. + +Note that framesToRead specifies the number of PCM frames to read, _not_ the number of MP3 frames. +*/ +drmp3_uint64 drmp3_read_pcm_frames_s16(drmp3* pMP3, drmp3_uint64 framesToRead, drmp3_int16* pBufferOut); + +/* +Seeks to a specific frame. + +Note that this is _not_ an MP3 frame, but rather a PCM frame. +*/ drmp3_bool32 drmp3_seek_to_pcm_frame(drmp3* pMP3, drmp3_uint64 frameIndex); -// Calculates the total number of PCM frames in the MP3 stream. Cannot be used for infinite streams such as internet -// radio. Runs in linear time. Returns 0 on error. +/* +Calculates the total number of PCM frames in the MP3 stream. Cannot be used for infinite streams such as internet +radio. Runs in linear time. Returns 0 on error. +*/ drmp3_uint64 drmp3_get_pcm_frame_count(drmp3* pMP3); -// Calculates the total number of MP3 frames in the MP3 stream. Cannot be used for infinite streams such as internet -// radio. Runs in linear time. Returns 0 on error. +/* +Calculates the total number of MP3 frames in the MP3 stream. Cannot be used for infinite streams such as internet +radio. Runs in linear time. Returns 0 on error. +*/ drmp3_uint64 drmp3_get_mp3_frame_count(drmp3* pMP3); +/* +Calculates the total number of MP3 and PCM frames in the MP3 stream. Cannot be used for infinite streams such as internet +radio. Runs in linear time. Returns 0 on error. + +This is equivalent to calling drmp3_get_mp3_frame_count() and drmp3_get_pcm_frame_count() except that it's more efficient. +*/ +drmp3_bool32 drmp3_get_mp3_and_pcm_frame_count(drmp3* pMP3, drmp3_uint64* pMP3FrameCount, drmp3_uint64* pPCMFrameCount); + +/* +Calculates the seekpoints based on PCM frames. This is slow. + +pSeekpoint count is a pointer to a uint32 containing the seekpoint count. On input it contains the desired count. +On output it contains the actual count. The reason for this design is that the client may request too many +seekpoints, in which case dr_mp3 will return a corrected count. + +Note that seektable seeking is not quite sample exact when the MP3 stream contains inconsistent sample rates. +*/ +drmp3_bool32 drmp3_calculate_seek_points(drmp3* pMP3, drmp3_uint32* pSeekPointCount, drmp3_seek_point* pSeekPoints); + +/* +Binds a seek table to the decoder. + +This does _not_ make a copy of pSeekPoints - it only references it. It is up to the application to ensure this +remains valid while it is bound to the decoder. + +Use drmp3_calculate_seek_points() to calculate the seek points. +*/ +drmp3_bool32 drmp3_bind_seek_table(drmp3* pMP3, drmp3_uint32 seekPointCount, drmp3_seek_point* pSeekPoints); -// Opens an decodes an entire MP3 stream as a single operation. -// -// pConfig is both an input and output. On input it contains what you want. On output it contains what you got. -// -// Free the returned pointer with drmp3_free(). +/* +Opens an decodes an entire MP3 stream as a single operation. + +pConfig is both an input and output. On input it contains what you want. On output it contains what you got. + +Free the returned pointer with drmp3_free(). +*/ float* drmp3_open_and_read_f32(drmp3_read_proc onRead, drmp3_seek_proc onSeek, void* pUserData, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount); +drmp3_int16* drmp3_open_and_read_s16(drmp3_read_proc onRead, drmp3_seek_proc onSeek, void* pUserData, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount); + float* drmp3_open_memory_and_read_f32(const void* pData, size_t dataSize, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount); +drmp3_int16* drmp3_open_memory_and_read_s16(const void* pData, size_t dataSize, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount); + #ifndef DR_MP3_NO_STDIO float* drmp3_open_file_and_read_f32(const char* filePath, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount); +drmp3_int16* drmp3_open_file_and_read_s16(const char* filePath, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount); #endif -// Frees any memory that was allocated by a public drmp3 API. +/* +Frees any memory that was allocated by a public drmp3 API. +*/ void drmp3_free(void* p); #ifdef __cplusplus } #endif -#endif // dr_mp3_h +#endif /* dr_mp3_h */ -///////////////////////////////////////////////////// -// -// IMPLEMENTATION -// -///////////////////////////////////////////////////// +/************************************************************************************************************************************************************ + ************************************************************************************************************************************************************ + + IMPLEMENTATION + + ************************************************************************************************************************************************************ + ************************************************************************************************************************************************************/ #ifdef DR_MP3_IMPLEMENTATION #include #include -#include -#include // For INT_MAX +#include /* For INT_MAX */ -// Disable SIMD when compiling with TCC for now. +/* Disable SIMD when compiling with TCC for now. */ #if defined(__TINYC__) #define DR_MP3_NO_SIMD #endif @@ -365,7 +463,7 @@ void drmp3_free(void* p); #define DR_MP3_ONLY_SIMD #endif -#if (defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64))) || ((defined(__i386__) || defined(__x86_64__)) && defined(__SSE2__)) +#if ((defined(_MSC_VER) && _MSC_VER >= 1400) && (defined(_M_IX86) || defined(_M_X64))) || ((defined(__i386__) || defined(__x86_64__)) && defined(__SSE2__)) #if defined(_MSC_VER) #include #endif @@ -780,8 +878,8 @@ static int drmp3_L3_read_side_info(drmp3_bs *bs, drmp3_L3_gr_info *gr, const drm unsigned tables, scfsi = 0; int main_data_begin, part_23_sum = 0; - int sr_idx = DRMP3_HDR_GET_MY_SAMPLE_RATE(hdr); sr_idx -= (sr_idx != 0); int gr_count = DRMP3_HDR_IS_MONO(hdr) ? 1 : 2; + int sr_idx = DRMP3_HDR_GET_MY_SAMPLE_RATE(hdr); sr_idx -= (sr_idx != 0); if (DRMP3_HDR_TEST_MPEG1(hdr)) { @@ -1070,7 +1168,7 @@ static void drmp3_L3_huffman(float *dst, drmp3_bs *bs, const drmp3_L3_gr_info *g lsb += DRMP3_PEEK_BITS(linbits); DRMP3_FLUSH_BITS(linbits); DRMP3_CHECK_BITS; - *dst = one*drmp3_L3_pow_43(lsb)*((int32_t)bs_cache < 0 ? -1: 1); + *dst = one*drmp3_L3_pow_43(lsb)*((drmp3_int32)bs_cache < 0 ? -1: 1); } else { *dst = g_drmp3_pow43[16 + lsb - 16*(bs_cache >> 31)]*one; @@ -1654,9 +1752,10 @@ typedef drmp3_int16 drmp3d_sample_t; static drmp3_int16 drmp3d_scale_pcm(float sample) { + drmp3_int16 s; if (sample >= 32766.5) return (drmp3_int16) 32767; if (sample <= -32767.5) return (drmp3_int16)-32768; - drmp3_int16 s = (drmp3_int16)(sample + .5f); + s = (drmp3_int16)(sample + .5f); s -= (s < 0); /* away from zero, to be compliant */ return (drmp3_int16)s; } @@ -1964,11 +2063,6 @@ int drmp3dec_decode_frame(drmp3dec *dec, const unsigned char *mp3, int mp3_bytes info->layer = 4 - DRMP3_HDR_GET_LAYER(hdr); info->bitrate_kbps = drmp3_hdr_bitrate_kbps(hdr); - if (!pcm) - { - return drmp3_hdr_frame_samples(hdr); - } - drmp3_bs_init(bs_frame, hdr + DRMP3_HDR_SIZE, frame_size - DRMP3_HDR_SIZE); if (DRMP3_HDR_IS_CRC(hdr)) { @@ -1984,7 +2078,7 @@ int drmp3dec_decode_frame(drmp3dec *dec, const unsigned char *mp3, int mp3_bytes return 0; } success = drmp3_L3_restore_reservoir(dec, bs_frame, &scratch, main_data_begin); - if (success) + if (success && pcm != NULL) { for (igr = 0; igr < (DRMP3_HDR_TEST_MPEG1(hdr) ? 2 : 1); igr++, pcm = DRMP3_OFFSET_PTR(pcm, sizeof(drmp3d_sample_t)*576*info->channels)) { @@ -2000,6 +2094,11 @@ int drmp3dec_decode_frame(drmp3dec *dec, const unsigned char *mp3, int mp3_bytes return 0; #else drmp3_L12_scale_info sci[1]; + + if (pcm == NULL) { + return drmp3_hdr_frame_samples(hdr); + } + drmp3_L12_read_scale_info(hdr, bs_frame, sci); memset(scratch.grbuf[0], 0, 576*2*sizeof(float)); @@ -2021,6 +2120,7 @@ int drmp3dec_decode_frame(drmp3dec *dec, const unsigned char *mp3, int mp3_bytes } #endif } + return success*drmp3_hdr_frame_samples(dec->header); } @@ -2085,11 +2185,11 @@ void drmp3dec_f32_to_s16(const float *in, drmp3_int16 *out, int num_samples) -/////////////////////////////////////////////////////////////////////////////// -// -// Main Public API -// -/////////////////////////////////////////////////////////////////////////////// +/************************************************************************************************************************************************************ + + Main Public API + + ************************************************************************************************************************************************************/ #if defined(SIZE_MAX) #define DRMP3_SIZE_MAX SIZE_MAX @@ -2101,16 +2201,13 @@ void drmp3dec_f32_to_s16(const float *in, drmp3_int16 *out, int num_samples) #endif #endif -// Options. -#ifndef DR_MP3_DEFAULT_CHANNELS -#define DR_MP3_DEFAULT_CHANNELS 2 -#endif -#ifndef DR_MP3_DEFAULT_SAMPLE_RATE -#define DR_MP3_DEFAULT_SAMPLE_RATE 44100 +/* Options. */ +#ifndef DRMP3_SEEK_LEADING_MP3_FRAMES +#define DRMP3_SEEK_LEADING_MP3_FRAMES 2 #endif -// Standard library stuff. +/* Standard library stuff. */ #ifndef DRMP3_ASSERT #include #define DRMP3_ASSERT(expression) assert(expression) @@ -2143,16 +2240,17 @@ void drmp3dec_f32_to_s16(const float *in, drmp3_int16 *out, int num_samples) #define drmp3_max(x, y) (((x) > (y)) ? (x) : (y)) #define drmp3_min(x, y) (((x) < (y)) ? (x) : (y)) -#define DRMP3_DATA_CHUNK_SIZE 16384 // The size in bytes of each chunk of data to read from the MP3 stream. minimp3 recommends 16K. +#define DRMP3_DATA_CHUNK_SIZE 16384 /* The size in bytes of each chunk of data to read from the MP3 stream. minimp3 recommends 16K. */ -static inline float drmp3_mix_f32(float x, float y, float a) +static DRMP3_INLINE float drmp3_mix_f32(float x, float y, float a) { return x*(1-a) + y*a; } static void drmp3_blend_f32(float* pOut, float* pInA, float* pInB, float factor, drmp3_uint32 channels) { - for (drmp3_uint32 i = 0; i < channels; ++i) { + drmp3_uint32 i; + for (i = 0; i < channels; ++i) { pOut[i] = drmp3_mix_f32(pInA[i], pInB[i], factor); } } @@ -2169,17 +2267,20 @@ void drmp3_src_cache_init(drmp3_src* pSRC, drmp3_src_cache* pCache) drmp3_uint64 drmp3_src_cache_read_frames(drmp3_src_cache* pCache, drmp3_uint64 frameCount, float* pFramesOut) { + drmp3_uint32 channels; + drmp3_uint64 totalFramesRead = 0; + drmp3_assert(pCache != NULL); drmp3_assert(pCache->pSRC != NULL); drmp3_assert(pCache->pSRC->onRead != NULL); drmp3_assert(frameCount > 0); drmp3_assert(pFramesOut != NULL); - drmp3_uint32 channels = pCache->pSRC->config.channels; + channels = pCache->pSRC->config.channels; - drmp3_uint64 totalFramesRead = 0; while (frameCount > 0) { - // If there's anything in memory go ahead and copy that over first. + /* If there's anything in memory go ahead and copy that over first. */ + drmp3_uint32 framesToReadFromClient; drmp3_uint64 framesRemainingInMemory = pCache->cachedFrameCount - pCache->iNextFrame; drmp3_uint64 framesToReadFromMemory = frameCount; if (framesToReadFromMemory > framesRemainingInMemory) { @@ -2196,14 +2297,14 @@ drmp3_uint64 drmp3_src_cache_read_frames(drmp3_src_cache* pCache, drmp3_uint64 f } - // At this point there are still more frames to read from the client, so we'll need to reload the cache with fresh data. + /* At this point there are still more frames to read from the client, so we'll need to reload the cache with fresh data. */ drmp3_assert(frameCount > 0); pFramesOut += framesToReadFromMemory * channels; pCache->iNextFrame = 0; pCache->cachedFrameCount = 0; - drmp3_uint32 framesToReadFromClient = drmp3_countof(pCache->pCachedFrames) / pCache->pSRC->config.channels; + framesToReadFromClient = drmp3_countof(pCache->pCachedFrames) / pCache->pSRC->config.channels; if (framesToReadFromClient > pCache->pSRC->config.cacheSizeInFrames) { framesToReadFromClient = pCache->pSRC->config.cacheSizeInFrames; } @@ -2211,7 +2312,7 @@ drmp3_uint64 drmp3_src_cache_read_frames(drmp3_src_cache* pCache, drmp3_uint64 f pCache->cachedFrameCount = (drmp3_uint32)pCache->pSRC->onRead(pCache->pSRC, framesToReadFromClient, pCache->pCachedFrames, pCache->pSRC->pUserData); - // Get out of this loop if nothing was able to be retrieved. + /* Get out of this loop if nothing was able to be retrieved. */ if (pCache->cachedFrameCount == 0) { break; } @@ -2226,11 +2327,19 @@ drmp3_uint64 drmp3_src_read_frames_linear(drmp3_src* pSRC, drmp3_uint64 frameCou drmp3_bool32 drmp3_src_init(const drmp3_src_config* pConfig, drmp3_src_read_proc onRead, void* pUserData, drmp3_src* pSRC) { - if (pSRC == NULL) return DRMP3_FALSE; + if (pSRC == NULL) { + return DRMP3_FALSE; + } + drmp3_zero_object(pSRC); - if (pConfig == NULL || onRead == NULL) return DRMP3_FALSE; - if (pConfig->channels == 0 || pConfig->channels > 2) return DRMP3_FALSE; + if (pConfig == NULL || onRead == NULL) { + return DRMP3_FALSE; + } + + if (pConfig->channels == 0 || pConfig->channels > 2) { + return DRMP3_FALSE; + } pSRC->config = *pConfig; pSRC->onRead = onRead; @@ -2246,9 +2355,11 @@ drmp3_bool32 drmp3_src_init(const drmp3_src_config* pConfig, drmp3_src_read_proc drmp3_bool32 drmp3_src_set_input_sample_rate(drmp3_src* pSRC, drmp3_uint32 sampleRateIn) { - if (pSRC == NULL) return DRMP3_FALSE; + if (pSRC == NULL) { + return DRMP3_FALSE; + } - // Must have a sample rate of > 0. + /* Must have a sample rate of > 0. */ if (sampleRateIn == 0) { return DRMP3_FALSE; } @@ -2259,9 +2370,11 @@ drmp3_bool32 drmp3_src_set_input_sample_rate(drmp3_src* pSRC, drmp3_uint32 sampl drmp3_bool32 drmp3_src_set_output_sample_rate(drmp3_src* pSRC, drmp3_uint32 sampleRateOut) { - if (pSRC == NULL) return DRMP3_FALSE; + if (pSRC == NULL) { + return DRMP3_FALSE; + } - // Must have a sample rate of > 0. + /* Must have a sample rate of > 0. */ if (sampleRateOut == 0) { return DRMP3_FALSE; } @@ -2272,16 +2385,20 @@ drmp3_bool32 drmp3_src_set_output_sample_rate(drmp3_src* pSRC, drmp3_uint32 samp drmp3_uint64 drmp3_src_read_frames_ex(drmp3_src* pSRC, drmp3_uint64 frameCount, void* pFramesOut, drmp3_bool32 flush) { - if (pSRC == NULL || frameCount == 0 || pFramesOut == NULL) return 0; + drmp3_src_algorithm algorithm; + + if (pSRC == NULL || frameCount == 0 || pFramesOut == NULL) { + return 0; + } - drmp3_src_algorithm algorithm = pSRC->config.algorithm; + algorithm = pSRC->config.algorithm; - // Always use passthrough if the sample rates are the same. + /* Always use passthrough if the sample rates are the same. */ if (pSRC->config.sampleRateIn == pSRC->config.sampleRateOut) { algorithm = drmp3_src_algorithm_none; } - // Could just use a function pointer instead of a switch for this... + /* Could just use a function pointer instead of a switch for this... */ switch (algorithm) { case drmp3_src_algorithm_none: return drmp3_src_read_frames_passthrough(pSRC, frameCount, pFramesOut, flush); @@ -2301,19 +2418,22 @@ drmp3_uint64 drmp3_src_read_frames_passthrough(drmp3_src* pSRC, drmp3_uint64 fra drmp3_assert(frameCount > 0); drmp3_assert(pFramesOut != NULL); - (void)flush; // Passthrough need not care about flushing. + (void)flush; /* Passthrough need not care about flushing. */ return pSRC->onRead(pSRC, frameCount, pFramesOut, pSRC->pUserData); } drmp3_uint64 drmp3_src_read_frames_linear(drmp3_src* pSRC, drmp3_uint64 frameCount, void* pFramesOut, drmp3_bool32 flush) { + double factor; + drmp3_uint64 totalFramesRead; + drmp3_assert(pSRC != NULL); drmp3_assert(frameCount > 0); drmp3_assert(pFramesOut != NULL); - // For linear SRC, the bin is only 2 frames: 1 prior, 1 future. + /* For linear SRC, the bin is only 2 frames: 1 prior, 1 future. */ - // Load the bin if necessary. + /* Load the bin if necessary. */ if (!pSRC->algo.linear.isPrevFramesLoaded) { drmp3_uint64 framesRead = drmp3_src_cache_read_frames(&pSRC->cache, 1, pSRC->bin); if (framesRead == 0) { @@ -2329,31 +2449,38 @@ drmp3_uint64 drmp3_src_read_frames_linear(drmp3_src* pSRC, drmp3_uint64 frameCou pSRC->algo.linear.isNextFramesLoaded = DRMP3_TRUE; } - float factor = (float)pSRC->config.sampleRateIn / pSRC->config.sampleRateOut; + factor = (double)pSRC->config.sampleRateIn / pSRC->config.sampleRateOut; - drmp3_uint64 totalFramesRead = 0; + totalFramesRead = 0; while (frameCount > 0) { - // The bin is where the previous and next frames are located. + drmp3_uint32 i; + drmp3_uint32 framesToReadFromClient; + + /* The bin is where the previous and next frames are located. */ float* pPrevFrame = pSRC->bin; float* pNextFrame = pSRC->bin + pSRC->config.channels; - drmp3_blend_f32((float*)pFramesOut, pPrevFrame, pNextFrame, pSRC->algo.linear.alpha, pSRC->config.channels); + drmp3_blend_f32((float*)pFramesOut, pPrevFrame, pNextFrame, (float)pSRC->algo.linear.alpha, pSRC->config.channels); pSRC->algo.linear.alpha += factor; - // The new alpha value is how we determine whether or not we need to read fresh frames. - drmp3_uint32 framesToReadFromClient = (drmp3_uint32)pSRC->algo.linear.alpha; + /* The new alpha value is how we determine whether or not we need to read fresh frames. */ + framesToReadFromClient = (drmp3_uint32)pSRC->algo.linear.alpha; pSRC->algo.linear.alpha = pSRC->algo.linear.alpha - framesToReadFromClient; - for (drmp3_uint32 i = 0; i < framesToReadFromClient; ++i) { - for (drmp3_uint32 j = 0; j < pSRC->config.channels; ++j) { + for (i = 0; i < framesToReadFromClient; ++i) { + drmp3_uint64 framesRead; + drmp3_uint32 j; + + for (j = 0; j < pSRC->config.channels; ++j) { pPrevFrame[j] = pNextFrame[j]; } - drmp3_uint64 framesRead = drmp3_src_cache_read_frames(&pSRC->cache, 1, pNextFrame); + framesRead = drmp3_src_cache_read_frames(&pSRC->cache, 1, pNextFrame); if (framesRead == 0) { - for (drmp3_uint32 j = 0; j < pSRC->config.channels; ++j) { - pNextFrame[j] = 0; + drmp3_uint32 k; + for (k = 0; k < pSRC->config.channels; ++k) { + pNextFrame[k] = 0; } if (pSRC->algo.linear.isNextFramesLoaded) { @@ -2372,7 +2499,7 @@ drmp3_uint64 drmp3_src_read_frames_linear(drmp3_src* pSRC, drmp3_uint64 frameCou frameCount -= 1; totalFramesRead += 1; - // If there's no frames available we need to get out of this loop. + /* If there's no frames available we need to get out of this loop. */ if (!pSRC->algo.linear.isNextFramesLoaded && (!flush || !pSRC->algo.linear.isPrevFramesLoaded)) { break; } @@ -2384,152 +2511,93 @@ drmp3_uint64 drmp3_src_read_frames_linear(drmp3_src* pSRC, drmp3_uint64 frameCou static size_t drmp3__on_read(drmp3* pMP3, void* pBufferOut, size_t bytesToRead) { - return pMP3->onRead(pMP3->pUserData, pBufferOut, bytesToRead); + size_t bytesRead = pMP3->onRead(pMP3->pUserData, pBufferOut, bytesToRead); + pMP3->streamCursor += bytesRead; + return bytesRead; } static drmp3_bool32 drmp3__on_seek(drmp3* pMP3, int offset, drmp3_seek_origin origin) { drmp3_assert(offset >= 0); - return pMP3->onSeek(pMP3->pUserData, offset, origin); -} - - -static drmp3_uint32 drmp3_decode_next_frame_ex(drmp3* pMP3, drmp3d_sample_t* pPCMFrames) -{ - drmp3_assert(pMP3 != NULL); - drmp3_assert(pMP3->onRead != NULL); - if (pMP3->atEnd) { - return 0; + if (!pMP3->onSeek(pMP3->pUserData, offset, origin)) { + return DRMP3_FALSE; } - drmp3_uint32 pcmFramesRead = 0; - do { - // minimp3 recommends doing data submission in 16K chunks. If we don't have at least 16K bytes available, get more. - if (pMP3->dataSize < DRMP3_DATA_CHUNK_SIZE) { - if (pMP3->dataCapacity < DRMP3_DATA_CHUNK_SIZE) { - pMP3->dataCapacity = DRMP3_DATA_CHUNK_SIZE; - drmp3_uint8* pNewData = (drmp3_uint8*)drmp3_realloc(pMP3->pData, pMP3->dataCapacity); - if (pNewData == NULL) { - return 0; // Out of memory. - } + if (origin == drmp3_seek_origin_start) { + pMP3->streamCursor = (drmp3_uint64)offset; + } else { + pMP3->streamCursor += offset; + } - pMP3->pData = pNewData; - } + return DRMP3_TRUE; +} - size_t bytesRead = drmp3__on_read(pMP3, pMP3->pData + pMP3->dataSize, (pMP3->dataCapacity - pMP3->dataSize)); - if (bytesRead == 0) { - if (pMP3->dataSize == 0) { - pMP3->atEnd = DRMP3_TRUE; - return 0; // No data. - } - } +static drmp3_bool32 drmp3__on_seek_64(drmp3* pMP3, drmp3_uint64 offset, drmp3_seek_origin origin) +{ + if (offset <= 0x7FFFFFFF) { + return drmp3__on_seek(pMP3, (int)offset, origin); + } - pMP3->dataSize += bytesRead; - } - if (pMP3->dataSize > INT_MAX) { - pMP3->atEnd = DRMP3_TRUE; - return 0; // File too big. - } + /* Getting here "offset" is too large for a 32-bit integer. We just keep seeking forward until we hit the offset. */ + if (!drmp3__on_seek(pMP3, 0x7FFFFFFF, drmp3_seek_origin_start)) { + return DRMP3_FALSE; + } - drmp3dec_frame_info info; - pcmFramesRead = drmp3dec_decode_frame(&pMP3->decoder, pMP3->pData, (int)pMP3->dataSize, pPCMFrames, &info); // <-- Safe size_t -> int conversion thanks to the check above. - if (pcmFramesRead != 0) { - size_t leftoverDataSize = (pMP3->dataSize - (size_t)info.frame_bytes); - for (size_t i = 0; i < leftoverDataSize; ++i) { - pMP3->pData[i] = pMP3->pData[i + (size_t)info.frame_bytes]; + offset -= 0x7FFFFFFF; + while (offset > 0) { + if (offset <= 0x7FFFFFFF) { + if (!drmp3__on_seek(pMP3, (int)offset, drmp3_seek_origin_current)) { + return DRMP3_FALSE; } - - pMP3->dataSize = leftoverDataSize; - pMP3->pcmFramesConsumedInMP3Frame = 0; - pMP3->pcmFramesRemainingInMP3Frame = pcmFramesRead; - pMP3->mp3FrameChannels = info.channels; - pMP3->mp3FrameSampleRate = info.hz; - drmp3_src_set_input_sample_rate(&pMP3->src, pMP3->mp3FrameSampleRate); - break; + offset = 0; } else { - // Need more data. minimp3 recommends doing data submission in 16K chunks. - if (pMP3->dataCapacity == pMP3->dataSize) { - // No room. Expand. - pMP3->dataCapacity += DRMP3_DATA_CHUNK_SIZE; - drmp3_uint8* pNewData = (drmp3_uint8*)drmp3_realloc(pMP3->pData, pMP3->dataCapacity); - if (pNewData == NULL) { - return 0; // Out of memory. - } - - pMP3->pData = pNewData; - } - - // Fill in a chunk. - size_t bytesRead = drmp3__on_read(pMP3, pMP3->pData + pMP3->dataSize, (pMP3->dataCapacity - pMP3->dataSize)); - if (bytesRead == 0) { - pMP3->atEnd = DRMP3_TRUE; - return 0; // Error reading more data. + if (!drmp3__on_seek(pMP3, 0x7FFFFFFF, drmp3_seek_origin_current)) { + return DRMP3_FALSE; } - - pMP3->dataSize += bytesRead; + offset -= 0x7FFFFFFF; } - } while (DRMP3_TRUE); - - return pcmFramesRead; -} - -static drmp3_uint32 drmp3_decode_next_frame(drmp3* pMP3) -{ - drmp3_assert(pMP3 != NULL); - return drmp3_decode_next_frame_ex(pMP3, (drmp3d_sample_t*)pMP3->pcmFrames); -} - -static drmp3_uint32 drmp3_seek_next_frame(drmp3* pMP3) -{ - drmp3_assert(pMP3 != NULL); - - drmp3_uint32 pcmFrameCount = drmp3_decode_next_frame_ex(pMP3, NULL); - if (pcmFrameCount == 0) { - return 0; } - // We have essentially just skipped past the frame, so just set the remaining samples to 0. - pMP3->currentPCMFrame += pcmFrameCount; - pMP3->pcmFramesConsumedInMP3Frame = pcmFrameCount; - pMP3->pcmFramesRemainingInMP3Frame = 0; - - return pcmFrameCount; + return DRMP3_TRUE; } +static drmp3_uint32 drmp3_decode_next_frame_ex(drmp3* pMP3, drmp3d_sample_t* pPCMFrames, drmp3_bool32 discard); +static drmp3_uint32 drmp3_decode_next_frame(drmp3* pMP3); + static drmp3_uint64 drmp3_read_src(drmp3_src* pSRC, drmp3_uint64 frameCount, void* pFramesOut, void* pUserData) { drmp3* pMP3 = (drmp3*)pUserData; - drmp3_assert(pMP3 != NULL); - drmp3_assert(pMP3->onRead != NULL); - float* pFramesOutF = (float*)pFramesOut; drmp3_uint64 totalFramesRead = 0; + drmp3_assert(pMP3 != NULL); + drmp3_assert(pMP3->onRead != NULL); + while (frameCount > 0) { - // Read from the in-memory buffer first. + /* Read from the in-memory buffer first. */ while (pMP3->pcmFramesRemainingInMP3Frame > 0 && frameCount > 0) { drmp3d_sample_t* frames = (drmp3d_sample_t*)pMP3->pcmFrames; #ifndef DR_MP3_FLOAT_OUTPUT if (pMP3->mp3FrameChannels == 1) { if (pMP3->channels == 1) { - // Mono -> Mono. + /* Mono -> Mono. */ pFramesOutF[0] = frames[pMP3->pcmFramesConsumedInMP3Frame] / 32768.0f; } else { - // Mono -> Stereo. + /* Mono -> Stereo. */ pFramesOutF[0] = frames[pMP3->pcmFramesConsumedInMP3Frame] / 32768.0f; pFramesOutF[1] = frames[pMP3->pcmFramesConsumedInMP3Frame] / 32768.0f; } } else { if (pMP3->channels == 1) { - // Stereo -> Mono + /* Stereo -> Mono */ float sample = 0; sample += frames[(pMP3->pcmFramesConsumedInMP3Frame*pMP3->mp3FrameChannels)+0] / 32768.0f; sample += frames[(pMP3->pcmFramesConsumedInMP3Frame*pMP3->mp3FrameChannels)+1] / 32768.0f; pFramesOutF[0] = sample * 0.5f; } else { - // Stereo -> Stereo + /* Stereo -> Stereo */ pFramesOutF[0] = frames[(pMP3->pcmFramesConsumedInMP3Frame*pMP3->mp3FrameChannels)+0] / 32768.0f; pFramesOutF[1] = frames[(pMP3->pcmFramesConsumedInMP3Frame*pMP3->mp3FrameChannels)+1] / 32768.0f; } @@ -2537,22 +2605,22 @@ static drmp3_uint64 drmp3_read_src(drmp3_src* pSRC, drmp3_uint64 frameCount, voi #else if (pMP3->mp3FrameChannels == 1) { if (pMP3->channels == 1) { - // Mono -> Mono. + /* Mono -> Mono. */ pFramesOutF[0] = frames[pMP3->pcmFramesConsumedInMP3Frame]; } else { - // Mono -> Stereo. + /* Mono -> Stereo. */ pFramesOutF[0] = frames[pMP3->pcmFramesConsumedInMP3Frame]; pFramesOutF[1] = frames[pMP3->pcmFramesConsumedInMP3Frame]; } } else { if (pMP3->channels == 1) { - // Stereo -> Mono + /* Stereo -> Mono */ float sample = 0; sample += frames[(pMP3->pcmFramesConsumedInMP3Frame*pMP3->mp3FrameChannels)+0]; sample += frames[(pMP3->pcmFramesConsumedInMP3Frame*pMP3->mp3FrameChannels)+1]; pFramesOutF[0] = sample * 0.5f; } else { - // Stereo -> Stereo + /* Stereo -> Stereo */ pFramesOutF[0] = frames[(pMP3->pcmFramesConsumedInMP3Frame*pMP3->mp3FrameChannels)+0]; pFramesOutF[1] = frames[(pMP3->pcmFramesConsumedInMP3Frame*pMP3->mp3FrameChannels)+1]; } @@ -2572,8 +2640,10 @@ static drmp3_uint64 drmp3_read_src(drmp3_src* pSRC, drmp3_uint64 frameCount, voi drmp3_assert(pMP3->pcmFramesRemainingInMP3Frame == 0); - // At this point we have exhausted our in-memory buffer so we need to re-fill. Note that the sample rate may have changed - // at this point which means we'll also need to update our sample rate conversion pipeline. + /* + At this point we have exhausted our in-memory buffer so we need to re-fill. Note that the sample rate may have changed + at this point which means we'll also need to update our sample rate conversion pipeline. + */ if (drmp3_decode_next_frame(pMP3) == 0) { break; } @@ -2582,42 +2652,8 @@ static drmp3_uint64 drmp3_read_src(drmp3_src* pSRC, drmp3_uint64 frameCount, voi return totalFramesRead; } -drmp3_bool32 drmp3_init_internal(drmp3* pMP3, drmp3_read_proc onRead, drmp3_seek_proc onSeek, void* pUserData, const drmp3_config* pConfig) +static drmp3_bool32 drmp3_init_src(drmp3* pMP3) { - drmp3_assert(pMP3 != NULL); - drmp3_assert(onRead != NULL); - - // This function assumes the output object has already been reset to 0. Do not do that here, otherwise things will break. - drmp3dec_init(&pMP3->decoder); - - // The config can be null in which case we use defaults. - drmp3_config config; - if (pConfig != NULL) { - config = *pConfig; - } else { - drmp3_zero_object(&config); - } - - pMP3->channels = config.outputChannels; - if (pMP3->channels == 0) { - pMP3->channels = DR_MP3_DEFAULT_CHANNELS; - } - - // Cannot have more than 2 channels. - if (pMP3->channels > 2) { - pMP3->channels = 2; - } - - pMP3->sampleRate = config.outputSampleRate; - if (pMP3->sampleRate == 0) { - pMP3->sampleRate = DR_MP3_DEFAULT_SAMPLE_RATE; - } - - pMP3->onRead = onRead; - pMP3->onSeek = onSeek; - pMP3->pUserData = pUserData; - - // We need a sample rate converter for converting the sample rate from the MP3 frames to the requested output sample rate. drmp3_src_config srcConfig; drmp3_zero_object(&srcConfig); srcConfig.sampleRateIn = DR_MP3_DEFAULT_SAMPLE_RATE; @@ -2628,11 +2664,190 @@ drmp3_bool32 drmp3_init_internal(drmp3* pMP3, drmp3_read_proc onRead, drmp3_seek drmp3_uninit(pMP3); return DRMP3_FALSE; } - - // Decode the first frame to confirm that it is indeed a valid MP3 stream. - if (!drmp3_decode_next_frame(pMP3)) { - drmp3_uninit(pMP3); - return DRMP3_FALSE; // Not a valid MP3 stream. + + return DRMP3_TRUE; +} + +static drmp3_uint32 drmp3_decode_next_frame_ex(drmp3* pMP3, drmp3d_sample_t* pPCMFrames, drmp3_bool32 discard) +{ + drmp3_uint32 pcmFramesRead = 0; + + drmp3_assert(pMP3 != NULL); + drmp3_assert(pMP3->onRead != NULL); + + if (pMP3->atEnd) { + return 0; + } + + do { + drmp3dec_frame_info info; + size_t leftoverDataSize; + + /* minimp3 recommends doing data submission in 16K chunks. If we don't have at least 16K bytes available, get more. */ + if (pMP3->dataSize < DRMP3_DATA_CHUNK_SIZE) { + size_t bytesRead; + + if (pMP3->dataCapacity < DRMP3_DATA_CHUNK_SIZE) { + drmp3_uint8* pNewData; + + pMP3->dataCapacity = DRMP3_DATA_CHUNK_SIZE; + pNewData = (drmp3_uint8*)drmp3_realloc(pMP3->pData, pMP3->dataCapacity); + if (pNewData == NULL) { + return 0; /* Out of memory. */ + } + + pMP3->pData = pNewData; + } + + bytesRead = drmp3__on_read(pMP3, pMP3->pData + pMP3->dataSize, (pMP3->dataCapacity - pMP3->dataSize)); + if (bytesRead == 0) { + if (pMP3->dataSize == 0) { + pMP3->atEnd = DRMP3_TRUE; + return 0; /* No data. */ + } + } + + pMP3->dataSize += bytesRead; + } + + if (pMP3->dataSize > INT_MAX) { + pMP3->atEnd = DRMP3_TRUE; + return 0; /* File too big. */ + } + + pcmFramesRead = drmp3dec_decode_frame(&pMP3->decoder, pMP3->pData, (int)pMP3->dataSize, pPCMFrames, &info); /* <-- Safe size_t -> int conversion thanks to the check above. */ + + /* Consume the data. */ + leftoverDataSize = (pMP3->dataSize - (size_t)info.frame_bytes); + if (info.frame_bytes > 0) { + memmove(pMP3->pData, pMP3->pData + info.frame_bytes, leftoverDataSize); + pMP3->dataSize = leftoverDataSize; + } + + /* + pcmFramesRead will be equal to 0 if decoding failed. If it is zero and info.frame_bytes > 0 then we have successfully + decoded the frame. A special case is if we are wanting to discard the frame, in which case we return successfully. + */ + if (pcmFramesRead > 0 || (info.frame_bytes > 0 && discard)) { + pcmFramesRead = drmp3_hdr_frame_samples(pMP3->decoder.header); + pMP3->pcmFramesConsumedInMP3Frame = 0; + pMP3->pcmFramesRemainingInMP3Frame = pcmFramesRead; + pMP3->mp3FrameChannels = info.channels; + pMP3->mp3FrameSampleRate = info.hz; + + /* We need to initialize the resampler if we don't yet have the channel count or sample rate. */ + if (pMP3->channels == 0 || pMP3->sampleRate == 0) { + if (pMP3->channels == 0) { + pMP3->channels = info.channels; + } + if (pMP3->sampleRate == 0) { + pMP3->sampleRate = info.hz; + } + drmp3_init_src(pMP3); + } + + drmp3_src_set_input_sample_rate(&pMP3->src, pMP3->mp3FrameSampleRate); + break; + } else if (info.frame_bytes == 0) { + size_t bytesRead; + + /* Need more data. minimp3 recommends doing data submission in 16K chunks. */ + if (pMP3->dataCapacity == pMP3->dataSize) { + drmp3_uint8* pNewData; + + /* No room. Expand. */ + pMP3->dataCapacity += DRMP3_DATA_CHUNK_SIZE; + pNewData = (drmp3_uint8*)drmp3_realloc(pMP3->pData, pMP3->dataCapacity); + if (pNewData == NULL) { + return 0; /* Out of memory. */ + } + + pMP3->pData = pNewData; + } + + /* Fill in a chunk. */ + bytesRead = drmp3__on_read(pMP3, pMP3->pData + pMP3->dataSize, (pMP3->dataCapacity - pMP3->dataSize)); + if (bytesRead == 0) { + pMP3->atEnd = DRMP3_TRUE; + return 0; /* Error reading more data. */ + } + + pMP3->dataSize += bytesRead; + } + } while (DRMP3_TRUE); + + return pcmFramesRead; +} + +static drmp3_uint32 drmp3_decode_next_frame(drmp3* pMP3) +{ + drmp3_assert(pMP3 != NULL); + return drmp3_decode_next_frame_ex(pMP3, (drmp3d_sample_t*)pMP3->pcmFrames, DRMP3_FALSE); +} + +#if 0 +static drmp3_uint32 drmp3_seek_next_frame(drmp3* pMP3) +{ + drmp3_uint32 pcmFrameCount; + + drmp3_assert(pMP3 != NULL); + + pcmFrameCount = drmp3_decode_next_frame_ex(pMP3, NULL); + if (pcmFrameCount == 0) { + return 0; + } + + /* We have essentially just skipped past the frame, so just set the remaining samples to 0. */ + pMP3->currentPCMFrame += pcmFrameCount; + pMP3->pcmFramesConsumedInMP3Frame = pcmFrameCount; + pMP3->pcmFramesRemainingInMP3Frame = 0; + + return pcmFrameCount; +} +#endif + +drmp3_bool32 drmp3_init_internal(drmp3* pMP3, drmp3_read_proc onRead, drmp3_seek_proc onSeek, void* pUserData, const drmp3_config* pConfig) +{ + drmp3_config config; + + drmp3_assert(pMP3 != NULL); + drmp3_assert(onRead != NULL); + + /* This function assumes the output object has already been reset to 0. Do not do that here, otherwise things will break. */ + drmp3dec_init(&pMP3->decoder); + + /* The config can be null in which case we use defaults. */ + if (pConfig != NULL) { + config = *pConfig; + } else { + drmp3_zero_object(&config); + } + + pMP3->channels = config.outputChannels; + + /* Cannot have more than 2 channels. */ + if (pMP3->channels > 2) { + pMP3->channels = 2; + } + + pMP3->sampleRate = config.outputSampleRate; + + pMP3->onRead = onRead; + pMP3->onSeek = onSeek; + pMP3->pUserData = pUserData; + + /* + We need a sample rate converter for converting the sample rate from the MP3 frames to the requested output sample rate. Note that if + we don't yet know the channel count or sample rate we defer this until the first frame is read. + */ + if (pMP3->channels != 0 && pMP3->sampleRate != 0) { + drmp3_init_src(pMP3); + } + + /* Decode the first frame to confirm that it is indeed a valid MP3 stream. */ + if (!drmp3_decode_next_frame(pMP3)) { + drmp3_uninit(pMP3); + return DRMP3_FALSE; /* Not a valid MP3 stream. */ } return DRMP3_TRUE; @@ -2652,10 +2867,12 @@ drmp3_bool32 drmp3_init(drmp3* pMP3, drmp3_read_proc onRead, drmp3_seek_proc onS static size_t drmp3__on_read_memory(void* pUserData, void* pBufferOut, size_t bytesToRead) { drmp3* pMP3 = (drmp3*)pUserData; + size_t bytesRemaining; + drmp3_assert(pMP3 != NULL); drmp3_assert(pMP3->memory.dataSize >= pMP3->memory.currentReadPos); - size_t bytesRemaining = pMP3->memory.dataSize - pMP3->memory.currentReadPos; + bytesRemaining = pMP3->memory.dataSize - pMP3->memory.currentReadPos; if (bytesToRead > bytesRemaining) { bytesToRead = bytesRemaining; } @@ -2671,26 +2888,27 @@ static size_t drmp3__on_read_memory(void* pUserData, void* pBufferOut, size_t by static drmp3_bool32 drmp3__on_seek_memory(void* pUserData, int byteOffset, drmp3_seek_origin origin) { drmp3* pMP3 = (drmp3*)pUserData; + drmp3_assert(pMP3 != NULL); if (origin == drmp3_seek_origin_current) { if (byteOffset > 0) { if (pMP3->memory.currentReadPos + byteOffset > pMP3->memory.dataSize) { - byteOffset = (int)(pMP3->memory.dataSize - pMP3->memory.currentReadPos); // Trying to seek too far forward. + byteOffset = (int)(pMP3->memory.dataSize - pMP3->memory.currentReadPos); /* Trying to seek too far forward. */ } } else { if (pMP3->memory.currentReadPos < (size_t)-byteOffset) { - byteOffset = -(int)pMP3->memory.currentReadPos; // Trying to seek too far backwards. + byteOffset = -(int)pMP3->memory.currentReadPos; /* Trying to seek too far backwards. */ } } - // This will never underflow thanks to the clamps above. + /* This will never underflow thanks to the clamps above. */ pMP3->memory.currentReadPos += byteOffset; } else { if ((drmp3_uint32)byteOffset <= pMP3->memory.dataSize) { pMP3->memory.currentReadPos = byteOffset; } else { - pMP3->memory.currentReadPos = pMP3->memory.dataSize; // Trying to seek too far forward. + pMP3->memory.currentReadPos = pMP3->memory.dataSize; /* Trying to seek too far forward. */ } } @@ -2765,21 +2983,22 @@ void drmp3_uninit(drmp3* pMP3) drmp3_uint64 drmp3_read_pcm_frames_f32(drmp3* pMP3, drmp3_uint64 framesToRead, float* pBufferOut) { + drmp3_uint64 totalFramesRead = 0; + if (pMP3 == NULL || pMP3->onRead == NULL) { return 0; } - drmp3_uint64 totalFramesRead = 0; - if (pBufferOut == NULL) { float temp[4096]; while (framesToRead > 0) { + drmp3_uint64 framesJustRead; drmp3_uint64 framesToReadRightNow = sizeof(temp)/sizeof(temp[0]) / pMP3->channels; if (framesToReadRightNow > framesToRead) { framesToReadRightNow = framesToRead; } - drmp3_uint64 framesJustRead = drmp3_read_pcm_frames_f32(pMP3, framesToReadRightNow, temp); + framesJustRead = drmp3_read_pcm_frames_f32(pMP3, framesToReadRightNow, temp); if (framesJustRead == 0) { break; } @@ -2795,22 +3014,144 @@ drmp3_uint64 drmp3_read_pcm_frames_f32(drmp3* pMP3, drmp3_uint64 framesToRead, f return totalFramesRead; } -drmp3_bool32 drmp3_seek_to_start_of_stream(drmp3* pMP3) +drmp3_uint64 drmp3_read_pcm_frames_s16(drmp3* pMP3, drmp3_uint64 framesToRead, drmp3_int16* pBufferOut) { - drmp3_assert(pMP3 != NULL); - drmp3_assert(pMP3->onSeek != NULL); + float tempF32[4096]; + drmp3_uint64 pcmFramesJustRead; + drmp3_uint64 totalPCMFramesRead = 0; - // Seek to the start of the stream to begin with. - if (!drmp3__on_seek(pMP3, 0, drmp3_seek_origin_start)) { - return DRMP3_FALSE; + if (pMP3 == NULL || pMP3->onRead == NULL) { + return 0; + } + + /* Naive implementation: read into a temp f32 buffer, then convert. */ + for (;;) { + drmp3_uint64 pcmFramesToReadThisIteration = (framesToRead - totalPCMFramesRead); + if (pcmFramesToReadThisIteration > drmp3_countof(tempF32)/pMP3->channels) { + pcmFramesToReadThisIteration = drmp3_countof(tempF32)/pMP3->channels; + } + + pcmFramesJustRead = drmp3_read_pcm_frames_f32(pMP3, pcmFramesToReadThisIteration, tempF32); + if (pcmFramesJustRead == 0) { + break; + } + + drmp3dec_f32_to_s16(tempF32, pBufferOut, (int)(pcmFramesJustRead * pMP3->channels)); /* <-- Safe cast since pcmFramesJustRead will be clamped based on the size of tempF32 which is always small. */ + pBufferOut += pcmFramesJustRead * pMP3->channels; + + totalPCMFramesRead += pcmFramesJustRead; + + if (pcmFramesJustRead < pcmFramesToReadThisIteration) { + break; + } } - // Clear any cached data. + return totalPCMFramesRead; +} + +void drmp3_reset(drmp3* pMP3) +{ + drmp3_assert(pMP3 != NULL); + pMP3->pcmFramesConsumedInMP3Frame = 0; pMP3->pcmFramesRemainingInMP3Frame = 0; pMP3->currentPCMFrame = 0; pMP3->dataSize = 0; pMP3->atEnd = DRMP3_FALSE; + pMP3->src.bin[0] = 0; + pMP3->src.bin[1] = 0; + pMP3->src.bin[2] = 0; + pMP3->src.bin[3] = 0; + pMP3->src.cache.cachedFrameCount = 0; + pMP3->src.cache.iNextFrame = 0; + pMP3->src.algo.linear.alpha = 0; + pMP3->src.algo.linear.isNextFramesLoaded = 0; + pMP3->src.algo.linear.isPrevFramesLoaded = 0; + drmp3dec_init(&pMP3->decoder); +} + +drmp3_bool32 drmp3_seek_to_start_of_stream(drmp3* pMP3) +{ + drmp3_assert(pMP3 != NULL); + drmp3_assert(pMP3->onSeek != NULL); + + /* Seek to the start of the stream to begin with. */ + if (!drmp3__on_seek(pMP3, 0, drmp3_seek_origin_start)) { + return DRMP3_FALSE; + } + + /* Clear any cached data. */ + drmp3_reset(pMP3); + return DRMP3_TRUE; +} + +float drmp3_get_cached_pcm_frame_count_from_src(drmp3* pMP3) +{ + return (pMP3->src.cache.cachedFrameCount - pMP3->src.cache.iNextFrame) + (float)pMP3->src.algo.linear.alpha; +} + +float drmp3_get_pcm_frames_remaining_in_mp3_frame(drmp3* pMP3) +{ + float factor = (float)pMP3->src.config.sampleRateOut / (float)pMP3->src.config.sampleRateIn; + float frameCountPreSRC = drmp3_get_cached_pcm_frame_count_from_src(pMP3) + pMP3->pcmFramesRemainingInMP3Frame; + return frameCountPreSRC * factor; +} + +/* +NOTE ON SEEKING +=============== +The seeking code below is a complete mess and is broken for cases when the sample rate changes. The problem +is with the resampling and the crappy resampler used by dr_mp3. What needs to happen is the following: + +1) The resampler needs to be replaced. +2) The resampler has state which needs to be updated whenever an MP3 frame is decoded outside of + drmp3_read_pcm_frames_f32(). The resampler needs an API to "flush" some imaginary input so that it's + state is updated accordingly. +*/ +drmp3_bool32 drmp3_seek_forward_by_pcm_frames__brute_force(drmp3* pMP3, drmp3_uint64 frameOffset) +{ + drmp3_uint64 framesRead; + +#if 0 + /* + MP3 is a bit annoying when it comes to seeking because of the bit reservoir. It basically means that an MP3 frame can possibly + depend on some of the data of prior frames. This means it's not as simple as seeking to the first byte of the MP3 frame that + contains the sample because that MP3 frame will need the data from the previous MP3 frame (which we just seeked past!). To + resolve this we seek past a number of MP3 frames up to a point, and then read-and-discard the remainder. + */ + drmp3_uint64 maxFramesToReadAndDiscard = (drmp3_uint64)(DRMP3_MAX_PCM_FRAMES_PER_MP3_FRAME * 3 * ((float)pMP3->src.config.sampleRateOut / (float)pMP3->src.config.sampleRateIn)); + + /* Now get rid of leading whole frames. */ + while (frameOffset > maxFramesToReadAndDiscard) { + float pcmFramesRemainingInCurrentMP3FrameF = drmp3_get_pcm_frames_remaining_in_mp3_frame(pMP3); + drmp3_uint32 pcmFramesRemainingInCurrentMP3Frame = (drmp3_uint32)pcmFramesRemainingInCurrentMP3FrameF; + if (frameOffset > pcmFramesRemainingInCurrentMP3Frame) { + frameOffset -= pcmFramesRemainingInCurrentMP3Frame; + pMP3->currentPCMFrame += pcmFramesRemainingInCurrentMP3Frame; + pMP3->pcmFramesConsumedInMP3Frame += pMP3->pcmFramesRemainingInMP3Frame; + pMP3->pcmFramesRemainingInMP3Frame = 0; + } else { + break; + } + + drmp3_uint32 pcmFrameCount = drmp3_decode_next_frame_ex(pMP3, pMP3->pcmFrames, DRMP3_FALSE); + if (pcmFrameCount == 0) { + break; + } + } + + /* The last step is to read-and-discard any remaining PCM frames to make it sample-exact. */ + framesRead = drmp3_read_pcm_frames_f32(pMP3, frameOffset, NULL); + if (framesRead != frameOffset) { + return DRMP3_FALSE; + } +#else + /* Just using a dumb read-and-discard for now pending updates to the resampler. */ + framesRead = drmp3_read_pcm_frames_f32(pMP3, frameOffset, NULL); + if (framesRead != frameOffset) { + return DRMP3_FALSE; + } +#endif return DRMP3_TRUE; } @@ -2823,51 +3164,112 @@ drmp3_bool32 drmp3_seek_to_pcm_frame__brute_force(drmp3* pMP3, drmp3_uint64 fram return DRMP3_TRUE; } - // If we're moving foward we just read from where we're at. Otherwise we need to move back to the start of - // the stream and read from the beginning. - drmp3_uint64 framesToReadAndDiscard; - if (frameIndex >= pMP3->currentPCMFrame) { - // Moving foward. - framesToReadAndDiscard = frameIndex - pMP3->currentPCMFrame; - } else { - // Moving backward. Move to the start of the stream and then move forward. - framesToReadAndDiscard = frameIndex; + /* + If we're moving foward we just read from where we're at. Otherwise we need to move back to the start of + the stream and read from the beginning. + */ + if (frameIndex < pMP3->currentPCMFrame) { + /* Moving backward. Move to the start of the stream and then move forward. */ if (!drmp3_seek_to_start_of_stream(pMP3)) { return DRMP3_FALSE; } } - // MP3 is a bit annoying when it comes to seeking because of the bit reservoir. It basically means that an MP3 frame can possibly - // depend on some of the data of prior frames. This means it's not as simple as seeking to the first byte of the MP3 frame that - // contains the sample because that MP3 frame will need the data from the previous MP3 frame (which we just seeked past!). To - // resolve this we seek past a number of MP3 frames up to a point, and then read-and-discard the remainder. - drmp3_uint64 maxFramesToReadAndDiscard = DRMP3_MAX_PCM_FRAMES_PER_MP3_FRAME * 3; + drmp3_assert(frameIndex >= pMP3->currentPCMFrame); + return drmp3_seek_forward_by_pcm_frames__brute_force(pMP3, (frameIndex - pMP3->currentPCMFrame)); +} + +drmp3_bool32 drmp3_find_closest_seek_point(drmp3* pMP3, drmp3_uint64 frameIndex, drmp3_uint32* pSeekPointIndex) +{ + drmp3_uint32 iSeekPoint; + + drmp3_assert(pSeekPointIndex != NULL); - // First get rid of anything that's still sitting in the buffer. - if (framesToReadAndDiscard > maxFramesToReadAndDiscard && framesToReadAndDiscard > pMP3->pcmFramesRemainingInMP3Frame) { - framesToReadAndDiscard -= pMP3->pcmFramesRemainingInMP3Frame; - pMP3->currentPCMFrame += pMP3->pcmFramesRemainingInMP3Frame; - pMP3->pcmFramesConsumedInMP3Frame += pMP3->pcmFramesRemainingInMP3Frame; - pMP3->pcmFramesRemainingInMP3Frame = 0; + *pSeekPointIndex = 0; + + if (frameIndex < pMP3->pSeekPoints[0].pcmFrameIndex) { + return DRMP3_FALSE; } - // Now get rid of leading whole frames. - while (framesToReadAndDiscard > maxFramesToReadAndDiscard) { - drmp3_uint32 pcmFramesSeeked = drmp3_seek_next_frame(pMP3); - if (pcmFramesSeeked == 0) { - break; + /* Linear search for simplicity to begin with while I'm getting this thing working. Once it's all working change this to a binary search. */ + for (iSeekPoint = 0; iSeekPoint < pMP3->seekPointCount; ++iSeekPoint) { + if (pMP3->pSeekPoints[iSeekPoint].pcmFrameIndex > frameIndex) { + break; /* Found it. */ } - framesToReadAndDiscard -= pcmFramesSeeked; + *pSeekPointIndex = iSeekPoint; } - // The last step is to read-and-discard any remaining PCM frames to make it sample-exact. - drmp3_uint64 framesRead = drmp3_read_pcm_frames_f32(pMP3, framesToReadAndDiscard, NULL); - if (framesRead != framesToReadAndDiscard) { - return DRMP3_FALSE; + return DRMP3_TRUE; +} + +drmp3_bool32 drmp3_seek_to_pcm_frame__seek_table(drmp3* pMP3, drmp3_uint64 frameIndex) +{ + drmp3_seek_point seekPoint; + drmp3_uint32 priorSeekPointIndex; + drmp3_uint16 iMP3Frame; + drmp3_uint64 leftoverFrames; + + drmp3_assert(pMP3 != NULL); + drmp3_assert(pMP3->pSeekPoints != NULL); + drmp3_assert(pMP3->seekPointCount > 0); + + /* If there is no prior seekpoint it means the target PCM frame comes before the first seek point. Just assume a seekpoint at the start of the file in this case. */ + if (drmp3_find_closest_seek_point(pMP3, frameIndex, &priorSeekPointIndex)) { + seekPoint = pMP3->pSeekPoints[priorSeekPointIndex]; + } else { + seekPoint.seekPosInBytes = 0; + seekPoint.pcmFrameIndex = 0; + seekPoint.mp3FramesToDiscard = 0; + seekPoint.pcmFramesToDiscard = 0; } - return DRMP3_TRUE; + /* First thing to do is seek to the first byte of the relevant MP3 frame. */ + if (!drmp3__on_seek_64(pMP3, seekPoint.seekPosInBytes, drmp3_seek_origin_start)) { + return DRMP3_FALSE; /* Failed to seek. */ + } + + /* Clear any cached data. */ + drmp3_reset(pMP3); + + /* Whole MP3 frames need to be discarded first. */ + for (iMP3Frame = 0; iMP3Frame < seekPoint.mp3FramesToDiscard; ++iMP3Frame) { + drmp3_uint32 pcmFramesReadPreSRC; + drmp3d_sample_t* pPCMFrames; + + /* Pass in non-null for the last frame because we want to ensure the sample rate converter is preloaded correctly. */ + pPCMFrames = NULL; + if (iMP3Frame == seekPoint.mp3FramesToDiscard-1) { + pPCMFrames = (drmp3d_sample_t*)pMP3->pcmFrames; + } + + /* We first need to decode the next frame, and then we need to flush the resampler. */ + pcmFramesReadPreSRC = drmp3_decode_next_frame_ex(pMP3, pPCMFrames, DRMP3_TRUE); + if (pcmFramesReadPreSRC == 0) { + return DRMP3_FALSE; + } + } + + /* We seeked to an MP3 frame in the raw stream so we need to make sure the current PCM frame is set correctly. */ + pMP3->currentPCMFrame = seekPoint.pcmFrameIndex - seekPoint.pcmFramesToDiscard; + + /* + Update resampler. This is wrong. Need to instead update it on a per MP3 frame basis. Also broken for cases when + the sample rate is being reduced in my testing. Should work fine when the input and output sample rate is the same + or a clean multiple. + */ + pMP3->src.algo.linear.alpha = (drmp3_int64)pMP3->currentPCMFrame * ((double)pMP3->src.config.sampleRateIn / pMP3->src.config.sampleRateOut); /* <-- Cast to int64 is required for VC6. */ + pMP3->src.algo.linear.alpha = pMP3->src.algo.linear.alpha - (drmp3_uint32)(pMP3->src.algo.linear.alpha); + if (pMP3->src.algo.linear.alpha > 0) { + pMP3->src.algo.linear.isPrevFramesLoaded = 1; + } + + /* + Now at this point we can follow the same process as the brute force technique where we just skip over unnecessary MP3 frames and then + read-and-discard at least 2 whole MP3 frames. + */ + leftoverFrames = frameIndex - pMP3->currentPCMFrame; + return drmp3_seek_forward_by_pcm_frames__brute_force(pMP3, leftoverFrames); } drmp3_bool32 drmp3_seek_to_pcm_frame(drmp3* pMP3, drmp3_uint64 frameIndex) @@ -2876,54 +3278,94 @@ drmp3_bool32 drmp3_seek_to_pcm_frame(drmp3* pMP3, drmp3_uint64 frameIndex) return DRMP3_FALSE; } - // We currently only support brute force seeking. - return drmp3_seek_to_pcm_frame__brute_force(pMP3, frameIndex); + if (frameIndex == 0) { + return drmp3_seek_to_start_of_stream(pMP3); + } + + /* Use the seek table if we have one. */ + if (pMP3->pSeekPoints != NULL && pMP3->seekPointCount > 0) { + return drmp3_seek_to_pcm_frame__seek_table(pMP3, frameIndex); + } else { + return drmp3_seek_to_pcm_frame__brute_force(pMP3, frameIndex); + } } -drmp3_uint64 drmp3_get_pcm_frame_count(drmp3* pMP3) +drmp3_bool32 drmp3_get_mp3_and_pcm_frame_count(drmp3* pMP3, drmp3_uint64* pMP3FrameCount, drmp3_uint64* pPCMFrameCount) { + drmp3_uint64 currentPCMFrame; + drmp3_uint64 totalPCMFrameCount; + drmp3_uint64 totalMP3FrameCount; + float totalPCMFrameCountFractionalPart; + if (pMP3 == NULL) { - return 0; + return DRMP3_FALSE; } - // The way this works is we move back to the start of the stream, iterate over each MP3 frame and calculate the frame count based - // on our output sample rate, the seek back to the PCM frame we were sitting on before calling this function. + /* + The way this works is we move back to the start of the stream, iterate over each MP3 frame and calculate the frame count based + on our output sample rate, the seek back to the PCM frame we were sitting on before calling this function. + */ - // The stream must support seeking for this to work. + /* The stream must support seeking for this to work. */ if (pMP3->onSeek == NULL) { - return 0; + return DRMP3_FALSE; } - // We'll need to seek back to where we were, so grab the PCM frame we're currently sitting on so we can restore later. - drmp3_uint64 currentPCMFrame = pMP3->currentPCMFrame; + /* We'll need to seek back to where we were, so grab the PCM frame we're currently sitting on so we can restore later. */ + currentPCMFrame = pMP3->currentPCMFrame; if (!drmp3_seek_to_start_of_stream(pMP3)) { - return 0; + return DRMP3_FALSE; } - drmp3_uint64 totalPCMFrameCount = 0; - float totalPCMFrameCountFractionalPart = 0; // <-- With resampling there will be a fractional part to each MP3 frame that we need to accumulate. + totalPCMFrameCount = 0; + totalMP3FrameCount = 0; + + totalPCMFrameCountFractionalPart = 0; /* <-- With resampling there will be a fractional part to each MP3 frame that we need to accumulate. */ for (;;) { - drmp3_uint32 pcmFramesInCurrentMP3FrameIn = drmp3_decode_next_frame_ex(pMP3, NULL); // <-- Passing in NULL here will prevent decoding of the MP3 frame which should save time. + drmp3_uint32 pcmFramesInCurrentMP3FrameIn; + float srcRatio; + float pcmFramesInCurrentMP3FrameOutF; + drmp3_uint32 pcmFramesInCurrentMP3FrameOut; + + pcmFramesInCurrentMP3FrameIn = drmp3_decode_next_frame_ex(pMP3, NULL, DRMP3_FALSE); if (pcmFramesInCurrentMP3FrameIn == 0) { break; } - float srcRatio = (float)pMP3->mp3FrameSampleRate / (float)pMP3->sampleRate; + srcRatio = (float)pMP3->mp3FrameSampleRate / (float)pMP3->sampleRate; drmp3_assert(srcRatio > 0); - float pcmFramesInCurrentMP3FrameOutF = totalPCMFrameCountFractionalPart + (pcmFramesInCurrentMP3FrameIn / srcRatio); - drmp3_uint32 pcmFramesInCurrentMP3FrameOut = (drmp3_uint32)pcmFramesInCurrentMP3FrameOutF; + pcmFramesInCurrentMP3FrameOutF = totalPCMFrameCountFractionalPart + (pcmFramesInCurrentMP3FrameIn / srcRatio); + pcmFramesInCurrentMP3FrameOut = (drmp3_uint32)pcmFramesInCurrentMP3FrameOutF; totalPCMFrameCountFractionalPart = pcmFramesInCurrentMP3FrameOutF - pcmFramesInCurrentMP3FrameOut; totalPCMFrameCount += pcmFramesInCurrentMP3FrameOut; + totalMP3FrameCount += 1; } - // Finally, we need to seek back to where we were. + /* Finally, we need to seek back to where we were. */ if (!drmp3_seek_to_start_of_stream(pMP3)) { - return 0; + return DRMP3_FALSE; } if (!drmp3_seek_to_pcm_frame(pMP3, currentPCMFrame)) { + return DRMP3_FALSE; + } + + if (pMP3FrameCount != NULL) { + *pMP3FrameCount = totalMP3FrameCount; + } + if (pPCMFrameCount != NULL) { + *pPCMFrameCount = totalPCMFrameCount; + } + + return DRMP3_TRUE; +} + +drmp3_uint64 drmp3_get_pcm_frame_count(drmp3* pMP3) +{ + drmp3_uint64 totalPCMFrameCount; + if (!drmp3_get_mp3_and_pcm_frame_count(pMP3, NULL, &totalPCMFrameCount)) { return 0; } @@ -2932,56 +3374,204 @@ drmp3_uint64 drmp3_get_pcm_frame_count(drmp3* pMP3) drmp3_uint64 drmp3_get_mp3_frame_count(drmp3* pMP3) { - if (pMP3 == NULL) { + drmp3_uint64 totalMP3FrameCount; + if (!drmp3_get_mp3_and_pcm_frame_count(pMP3, &totalMP3FrameCount, NULL)) { return 0; } - // This works the same way as drmp3_get_pcm_frame_count() - move to the start, count MP3 frames, move back to the previous position. + return totalMP3FrameCount; +} - // The stream must support seeking for this to work. - if (pMP3->onSeek == NULL) { - return 0; +void drmp3__accumulate_running_pcm_frame_count(drmp3* pMP3, drmp3_uint32 pcmFrameCountIn, drmp3_uint64* pRunningPCMFrameCount, float* pRunningPCMFrameCountFractionalPart) +{ + float srcRatio; + float pcmFrameCountOutF; + drmp3_uint32 pcmFrameCountOut; + + srcRatio = (float)pMP3->mp3FrameSampleRate / (float)pMP3->sampleRate; + drmp3_assert(srcRatio > 0); + + pcmFrameCountOutF = *pRunningPCMFrameCountFractionalPart + (pcmFrameCountIn / srcRatio); + pcmFrameCountOut = (drmp3_uint32)pcmFrameCountOutF; + *pRunningPCMFrameCountFractionalPart = pcmFrameCountOutF - pcmFrameCountOut; + *pRunningPCMFrameCount += pcmFrameCountOut; +} + +typedef struct +{ + drmp3_uint64 bytePos; + drmp3_uint64 pcmFrameIndex; /* <-- After sample rate conversion. */ +} drmp3__seeking_mp3_frame_info; + +drmp3_bool32 drmp3_calculate_seek_points(drmp3* pMP3, drmp3_uint32* pSeekPointCount, drmp3_seek_point* pSeekPoints) +{ + drmp3_uint32 seekPointCount; + drmp3_uint64 currentPCMFrame; + drmp3_uint64 totalMP3FrameCount; + drmp3_uint64 totalPCMFrameCount; + + if (pMP3 == NULL || pSeekPointCount == NULL || pSeekPoints == NULL) { + return DRMP3_FALSE; /* Invalid args. */ + } + + seekPointCount = *pSeekPointCount; + if (seekPointCount == 0) { + return DRMP3_FALSE; /* The client has requested no seek points. Consider this to be invalid arguments since the client has probably not intended this. */ } - // We'll need to seek back to where we were, so grab the PCM frame we're currently sitting on so we can restore later. - drmp3_uint64 currentPCMFrame = pMP3->currentPCMFrame; + /* We'll need to seek back to the current sample after calculating the seekpoints so we need to go ahead and grab the current location at the top. */ + currentPCMFrame = pMP3->currentPCMFrame; - if (!drmp3_seek_to_start_of_stream(pMP3)) { - return 0; + /* We never do more than the total number of MP3 frames and we limit it to 32-bits. */ + if (!drmp3_get_mp3_and_pcm_frame_count(pMP3, &totalMP3FrameCount, &totalPCMFrameCount)) { + return DRMP3_FALSE; } - drmp3_uint64 totalMP3FrameCount = 0; - for (;;) { - drmp3_uint32 pcmFramesInCurrentMP3FrameIn = drmp3_decode_next_frame_ex(pMP3, NULL); - if (pcmFramesInCurrentMP3FrameIn == 0) { - break; + /* If there's less than DRMP3_SEEK_LEADING_MP3_FRAMES+1 frames we just report 1 seek point which will be the very start of the stream. */ + if (totalMP3FrameCount < DRMP3_SEEK_LEADING_MP3_FRAMES+1) { + seekPointCount = 1; + pSeekPoints[0].seekPosInBytes = 0; + pSeekPoints[0].pcmFrameIndex = 0; + pSeekPoints[0].mp3FramesToDiscard = 0; + pSeekPoints[0].pcmFramesToDiscard = 0; + } else { + drmp3_uint64 pcmFramesBetweenSeekPoints; + drmp3__seeking_mp3_frame_info mp3FrameInfo[DRMP3_SEEK_LEADING_MP3_FRAMES+1]; + drmp3_uint64 runningPCMFrameCount = 0; + float runningPCMFrameCountFractionalPart = 0; + drmp3_uint64 nextTargetPCMFrame; + drmp3_uint32 iMP3Frame; + drmp3_uint32 iSeekPoint; + + if (seekPointCount > totalMP3FrameCount-1) { + seekPointCount = (drmp3_uint32)totalMP3FrameCount-1; } - totalMP3FrameCount += 1; + pcmFramesBetweenSeekPoints = totalPCMFrameCount / (seekPointCount+1); + + /* + Here is where we actually calculate the seek points. We need to start by moving the start of the stream. We then enumerate over each + MP3 frame. + */ + if (!drmp3_seek_to_start_of_stream(pMP3)) { + return DRMP3_FALSE; + } + + /* + We need to cache the byte positions of the previous MP3 frames. As a new MP3 frame is iterated, we cycle the byte positions in this + array. The value in the first item in this array is the byte position that will be reported in the next seek point. + */ + + /* We need to initialize the array of MP3 byte positions for the leading MP3 frames. */ + for (iMP3Frame = 0; iMP3Frame < DRMP3_SEEK_LEADING_MP3_FRAMES+1; ++iMP3Frame) { + drmp3_uint32 pcmFramesInCurrentMP3FrameIn; + + /* The byte position of the next frame will be the stream's cursor position, minus whatever is sitting in the buffer. */ + drmp3_assert(pMP3->streamCursor >= pMP3->dataSize); + mp3FrameInfo[iMP3Frame].bytePos = pMP3->streamCursor - pMP3->dataSize; + mp3FrameInfo[iMP3Frame].pcmFrameIndex = runningPCMFrameCount; + + /* We need to get information about this frame so we can know how many samples it contained. */ + pcmFramesInCurrentMP3FrameIn = drmp3_decode_next_frame_ex(pMP3, NULL, DRMP3_FALSE); + if (pcmFramesInCurrentMP3FrameIn == 0) { + return DRMP3_FALSE; /* This should never happen. */ + } + + drmp3__accumulate_running_pcm_frame_count(pMP3, pcmFramesInCurrentMP3FrameIn, &runningPCMFrameCount, &runningPCMFrameCountFractionalPart); + } + + /* + At this point we will have extracted the byte positions of the leading MP3 frames. We can now start iterating over each seek point and + calculate them. + */ + nextTargetPCMFrame = 0; + for (iSeekPoint = 0; iSeekPoint < seekPointCount; ++iSeekPoint) { + nextTargetPCMFrame += pcmFramesBetweenSeekPoints; + + for (;;) { + if (nextTargetPCMFrame < runningPCMFrameCount) { + /* The next seek point is in the current MP3 frame. */ + pSeekPoints[iSeekPoint].seekPosInBytes = mp3FrameInfo[0].bytePos; + pSeekPoints[iSeekPoint].pcmFrameIndex = nextTargetPCMFrame; + pSeekPoints[iSeekPoint].mp3FramesToDiscard = DRMP3_SEEK_LEADING_MP3_FRAMES; + pSeekPoints[iSeekPoint].pcmFramesToDiscard = (drmp3_uint16)(nextTargetPCMFrame - mp3FrameInfo[DRMP3_SEEK_LEADING_MP3_FRAMES-1].pcmFrameIndex); + break; + } else { + size_t i; + drmp3_uint32 pcmFramesInCurrentMP3FrameIn; + + /* + The next seek point is not in the current MP3 frame, so continue on to the next one. The first thing to do is cycle the cached + MP3 frame info. + */ + for (i = 0; i < drmp3_countof(mp3FrameInfo)-1; ++i) { + mp3FrameInfo[i] = mp3FrameInfo[i+1]; + } + + /* Cache previous MP3 frame info. */ + mp3FrameInfo[drmp3_countof(mp3FrameInfo)-1].bytePos = pMP3->streamCursor - pMP3->dataSize; + mp3FrameInfo[drmp3_countof(mp3FrameInfo)-1].pcmFrameIndex = runningPCMFrameCount; + + /* + Go to the next MP3 frame. This shouldn't ever fail, but just in case it does we just set the seek point and break. If it happens, it + should only ever do it for the last seek point. + */ + pcmFramesInCurrentMP3FrameIn = drmp3_decode_next_frame_ex(pMP3, NULL, DRMP3_TRUE); + if (pcmFramesInCurrentMP3FrameIn == 0) { + pSeekPoints[iSeekPoint].seekPosInBytes = mp3FrameInfo[0].bytePos; + pSeekPoints[iSeekPoint].pcmFrameIndex = nextTargetPCMFrame; + pSeekPoints[iSeekPoint].mp3FramesToDiscard = DRMP3_SEEK_LEADING_MP3_FRAMES; + pSeekPoints[iSeekPoint].pcmFramesToDiscard = (drmp3_uint16)(nextTargetPCMFrame - mp3FrameInfo[DRMP3_SEEK_LEADING_MP3_FRAMES-1].pcmFrameIndex); + break; + } + + drmp3__accumulate_running_pcm_frame_count(pMP3, pcmFramesInCurrentMP3FrameIn, &runningPCMFrameCount, &runningPCMFrameCountFractionalPart); + } + } + } + + /* Finally, we need to seek back to where we were. */ + if (!drmp3_seek_to_start_of_stream(pMP3)) { + return DRMP3_FALSE; + } + if (!drmp3_seek_to_pcm_frame(pMP3, currentPCMFrame)) { + return DRMP3_FALSE; + } } - // Finally, we need to seek back to where we were. - if (!drmp3_seek_to_start_of_stream(pMP3)) { - return 0; + *pSeekPointCount = seekPointCount; + return DRMP3_TRUE; +} + +drmp3_bool32 drmp3_bind_seek_table(drmp3* pMP3, drmp3_uint32 seekPointCount, drmp3_seek_point* pSeekPoints) +{ + if (pMP3 == NULL) { + return DRMP3_FALSE; } - if (!drmp3_seek_to_pcm_frame(pMP3, currentPCMFrame)) { - return 0; + if (seekPointCount == 0 || pSeekPoints == NULL) { + /* Unbinding. */ + pMP3->seekPointCount = 0; + pMP3->pSeekPoints = NULL; + } else { + /* Binding. */ + pMP3->seekPointCount = seekPointCount; + pMP3->pSeekPoints = pSeekPoints; } - return totalMP3FrameCount; + return DRMP3_TRUE; } float* drmp3__full_read_and_close_f32(drmp3* pMP3, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount) { - drmp3_assert(pMP3 != NULL); - drmp3_uint64 totalFramesRead = 0; drmp3_uint64 framesCapacity = 0; float* pFrames = NULL; - float temp[4096]; + + drmp3_assert(pMP3 != NULL); + for (;;) { drmp3_uint64 framesToReadRightNow = drmp3_countof(temp) / pMP3->channels; drmp3_uint64 framesJustRead = drmp3_read_pcm_frames_f32(pMP3, framesToReadRightNow, temp); @@ -2989,19 +3579,22 @@ float* drmp3__full_read_and_close_f32(drmp3* pMP3, drmp3_config* pConfig, drmp3_ break; } - // Reallocate the output buffer if there's not enough room. + /* Reallocate the output buffer if there's not enough room. */ if (framesCapacity < totalFramesRead + framesJustRead) { + drmp3_uint64 newFramesBufferSize; + float* pNewFrames; + framesCapacity *= 2; if (framesCapacity < totalFramesRead + framesJustRead) { framesCapacity = totalFramesRead + framesJustRead; } - drmp3_uint64 newFramesBufferSize = framesCapacity*pMP3->channels*sizeof(float); + newFramesBufferSize = framesCapacity*pMP3->channels*sizeof(float); if (newFramesBufferSize > DRMP3_SIZE_MAX) { break; } - float* pNewFrames = (float*)drmp3_realloc(pFrames, (size_t)newFramesBufferSize); + pNewFrames = (float*)drmp3_realloc(pFrames, (size_t)newFramesBufferSize); if (pNewFrames == NULL) { drmp3_free(pFrames); break; @@ -3013,7 +3606,7 @@ float* drmp3__full_read_and_close_f32(drmp3* pMP3, drmp3_config* pConfig, drmp3_ drmp3_copy_memory(pFrames + totalFramesRead*pMP3->channels, temp, (size_t)(framesJustRead*pMP3->channels*sizeof(float))); totalFramesRead += framesJustRead; - // If the number of frames we asked for is less that what we actually read it means we've reached the end. + /* If the number of frames we asked for is less that what we actually read it means we've reached the end. */ if (framesJustRead != framesToReadRightNow) { break; } @@ -3026,10 +3619,77 @@ float* drmp3__full_read_and_close_f32(drmp3* pMP3, drmp3_config* pConfig, drmp3_ drmp3_uninit(pMP3); - if (pTotalFrameCount) *pTotalFrameCount = totalFramesRead; + if (pTotalFrameCount) { + *pTotalFrameCount = totalFramesRead; + } + return pFrames; } +drmp3_int16* drmp3__full_read_and_close_s16(drmp3* pMP3, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount) +{ + drmp3_uint64 totalFramesRead = 0; + drmp3_uint64 framesCapacity = 0; + drmp3_int16* pFrames = NULL; + drmp3_int16 temp[4096]; + + drmp3_assert(pMP3 != NULL); + + for (;;) { + drmp3_uint64 framesToReadRightNow = drmp3_countof(temp) / pMP3->channels; + drmp3_uint64 framesJustRead = drmp3_read_pcm_frames_s16(pMP3, framesToReadRightNow, temp); + if (framesJustRead == 0) { + break; + } + + /* Reallocate the output buffer if there's not enough room. */ + if (framesCapacity < totalFramesRead + framesJustRead) { + drmp3_uint64 newFramesBufferSize; + drmp3_int16* pNewFrames; + + framesCapacity *= 2; + if (framesCapacity < totalFramesRead + framesJustRead) { + framesCapacity = totalFramesRead + framesJustRead; + } + + newFramesBufferSize = framesCapacity*pMP3->channels*sizeof(drmp3_int16); + if (newFramesBufferSize > DRMP3_SIZE_MAX) { + break; + } + + pNewFrames = (drmp3_int16*)drmp3_realloc(pFrames, (size_t)newFramesBufferSize); + if (pNewFrames == NULL) { + drmp3_free(pFrames); + break; + } + + pFrames = pNewFrames; + } + + drmp3_copy_memory(pFrames + totalFramesRead*pMP3->channels, temp, (size_t)(framesJustRead*pMP3->channels*sizeof(drmp3_int16))); + totalFramesRead += framesJustRead; + + /* If the number of frames we asked for is less that what we actually read it means we've reached the end. */ + if (framesJustRead != framesToReadRightNow) { + break; + } + } + + if (pConfig != NULL) { + pConfig->outputChannels = pMP3->channels; + pConfig->outputSampleRate = pMP3->sampleRate; + } + + drmp3_uninit(pMP3); + + if (pTotalFrameCount) { + *pTotalFrameCount = totalFramesRead; + } + + return pFrames; +} + + float* drmp3_open_and_read_f32(drmp3_read_proc onRead, drmp3_seek_proc onSeek, void* pUserData, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount) { drmp3 mp3; @@ -3040,6 +3700,17 @@ float* drmp3_open_and_read_f32(drmp3_read_proc onRead, drmp3_seek_proc onSeek, v return drmp3__full_read_and_close_f32(&mp3, pConfig, pTotalFrameCount); } +drmp3_int16* drmp3_open_and_read_s16(drmp3_read_proc onRead, drmp3_seek_proc onSeek, void* pUserData, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount) +{ + drmp3 mp3; + if (!drmp3_init(&mp3, onRead, onSeek, pUserData, pConfig)) { + return NULL; + } + + return drmp3__full_read_and_close_s16(&mp3, pConfig, pTotalFrameCount); +} + + float* drmp3_open_memory_and_read_f32(const void* pData, size_t dataSize, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount) { drmp3 mp3; @@ -3050,6 +3721,17 @@ float* drmp3_open_memory_and_read_f32(const void* pData, size_t dataSize, drmp3_ return drmp3__full_read_and_close_f32(&mp3, pConfig, pTotalFrameCount); } +drmp3_int16* drmp3_open_memory_and_read_s16(const void* pData, size_t dataSize, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount) +{ + drmp3 mp3; + if (!drmp3_init_memory(&mp3, pData, dataSize, pConfig)) { + return NULL; + } + + return drmp3__full_read_and_close_s16(&mp3, pConfig, pTotalFrameCount); +} + + #ifndef DR_MP3_NO_STDIO float* drmp3_open_file_and_read_f32(const char* filePath, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount) { @@ -3060,6 +3742,16 @@ float* drmp3_open_file_and_read_f32(const char* filePath, drmp3_config* pConfig, return drmp3__full_read_and_close_f32(&mp3, pConfig, pTotalFrameCount); } + +drmp3_int16* drmp3_open_file_and_read_s16(const char* filePath, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount) +{ + drmp3 mp3; + if (!drmp3_init_file(&mp3, filePath, pConfig)) { + return NULL; + } + + return drmp3__full_read_and_close_s16(&mp3, pConfig, pTotalFrameCount); +} #endif void drmp3_free(void* p) @@ -3069,127 +3761,172 @@ void drmp3_free(void* p) #endif /*DR_MP3_IMPLEMENTATION*/ +/* +DIFFERENCES BETWEEN minimp3 AND dr_mp3 +====================================== +- First, keep in mind that minimp3 (https://github.com/lieff/minimp3) is where all the real work was done. All of the + code relating to the actual decoding remains mostly unmodified, apart from some namespacing changes. +- dr_mp3 adds a pulling style API which allows you to deliver raw data via callbacks. So, rather than pushing data + to the decoder, the decoder _pulls_ data from your callbacks. +- In addition to callbacks, a decoder can be initialized from a block of memory and a file. +- The dr_mp3 pull API reads PCM frames rather than whole MP3 frames. +- dr_mp3 adds convenience APIs for opening and decoding entire files in one go. +- dr_mp3 is fully namespaced, including the implementation section, which is more suitable when compiling projects + as a single translation unit (aka unity builds). At the time of writing this, a unity build is not possible when + using minimp3 in conjunction with stb_vorbis. dr_mp3 addresses this. +*/ -// DIFFERENCES BETWEEN minimp3 AND dr_mp3 -// ====================================== -// - First, keep in mind that minimp3 (https://github.com/lieff/minimp3) is where all the real work was done. All of the -// code relating to the actual decoding remains mostly unmodified, apart from some namespacing changes. -// - dr_mp3 adds a pulling style API which allows you to deliver raw data via callbacks. So, rather than pushing data -// to the decoder, the decoder _pulls_ data from your callbacks. -// - In addition to callbacks, a decoder can be initialized from a block of memory and a file. -// - The dr_mp3 pull API reads PCM frames rather than whole MP3 frames. -// - dr_mp3 adds convenience APIs for opening and decoding entire files in one go. -// - dr_mp3 is fully namespaced, including the implementation section, which is more suitable when compiling projects -// as a single translation unit (aka unity builds). At the time of writing this, a unity build is not possible when -// using minimp3 in conjunction with stb_vorbis. dr_mp3 addresses this. - - -// REVISION HISTORY -// ================ -// -// v0.4.0 - 2018-xx-xx -// - API CHANGE: Rename some APIs: -// - drmp3_read_f32 -> to drmp3_read_pcm_frames_f32 -// - drmp3_seek_to_frame -> drmp3_seek_to_pcm_frame -// - drmp3_open_and_decode_f32 -> drmp3_open_and_read_f32 -// - drmp3_open_and_decode_memory_f32 -> drmp3_open_memory_and_read_f32 -// - drmp3_open_and_decode_file_f32 -> drmp3_open_file_and_read_f32 -// - Add drmp3_get_pcm_frame_count(). -// - Add drmp3_get_mp3_frame_count(). -// - Improve seeking performance. -// -// v0.3.2 - 2018-09-11 -// - Fix a couple of memory leaks. -// - Bring up to date with minimp3. -// -// v0.3.1 - 2018-08-25 -// - Fix C++ build. -// -// v0.3.0 - 2018-08-25 -// - Bring up to date with minimp3. This has a minor API change: the "pcm" parameter of drmp3dec_decode_frame() has -// been changed from short* to void* because it can now output both s16 and f32 samples, depending on whether or -// not the DR_MP3_FLOAT_OUTPUT option is set. -// -// v0.2.11 - 2018-08-08 -// - Fix a bug where the last part of a file is not read. -// -// v0.2.10 - 2018-08-07 -// - Improve 64-bit detection. -// -// v0.2.9 - 2018-08-05 -// - Fix C++ build on older versions of GCC. -// - Bring up to date with minimp3. -// -// v0.2.8 - 2018-08-02 -// - Fix compilation errors with older versions of GCC. -// -// v0.2.7 - 2018-07-13 -// - Bring up to date with minimp3. -// -// v0.2.6 - 2018-07-12 -// - Bring up to date with minimp3. -// -// v0.2.5 - 2018-06-22 -// - Bring up to date with minimp3. -// -// v0.2.4 - 2018-05-12 -// - Bring up to date with minimp3. -// -// v0.2.3 - 2018-04-29 -// - Fix TCC build. -// -// v0.2.2 - 2018-04-28 -// - Fix bug when opening a decoder from memory. -// -// v0.2.1 - 2018-04-27 -// - Efficiency improvements when the decoder reaches the end of the stream. -// -// v0.2 - 2018-04-21 -// - Bring up to date with minimp3. -// - Start using major.minor.revision versioning. -// -// v0.1d - 2018-03-30 -// - Bring up to date with minimp3. -// -// v0.1c - 2018-03-11 -// - Fix C++ build error. -// -// v0.1b - 2018-03-07 -// - Bring up to date with minimp3. -// -// v0.1a - 2018-02-28 -// - Fix compilation error on GCC/Clang. -// - Fix some warnings. -// -// v0.1 - 2018-02-xx -// - Initial versioned release. - +/* +REVISION HISTORY +================ +v0.4.4 - 2019-05-06 + - Fixes to the VC6 build. + +v0.4.3 - 2019-05-05 + - Use the channel count and/or sample rate of the first MP3 frame instead of DR_MP3_DEFAULT_CHANNELS and + DR_MP3_DEFAULT_SAMPLE_RATE when they are set to 0. To use the old behaviour, just set the relevant property to + DR_MP3_DEFAULT_CHANNELS or DR_MP3_DEFAULT_SAMPLE_RATE. + - Add s16 reading APIs + - drmp3_read_pcm_frames_s16 + - drmp3_open_memory_and_read_s16 + - drmp3_open_and_read_s16 + - drmp3_open_file_and_read_s16 + - Add drmp3_get_mp3_and_pcm_frame_count() to the public header section. + - Add support for C89. + - Change license to choice of public domain or MIT-0. + +v0.4.2 - 2019-02-21 + - Fix a warning. + +v0.4.1 - 2018-12-30 + - Fix a warning. + +v0.4.0 - 2018-12-16 + - API CHANGE: Rename some APIs: + - drmp3_read_f32 -> to drmp3_read_pcm_frames_f32 + - drmp3_seek_to_frame -> drmp3_seek_to_pcm_frame + - drmp3_open_and_decode_f32 -> drmp3_open_and_read_f32 + - drmp3_open_and_decode_memory_f32 -> drmp3_open_memory_and_read_f32 + - drmp3_open_and_decode_file_f32 -> drmp3_open_file_and_read_f32 + - Add drmp3_get_pcm_frame_count(). + - Add drmp3_get_mp3_frame_count(). + - Improve seeking performance. + +v0.3.2 - 2018-09-11 + - Fix a couple of memory leaks. + - Bring up to date with minimp3. + +v0.3.1 - 2018-08-25 + - Fix C++ build. + +v0.3.0 - 2018-08-25 + - Bring up to date with minimp3. This has a minor API change: the "pcm" parameter of drmp3dec_decode_frame() has + been changed from short* to void* because it can now output both s16 and f32 samples, depending on whether or + not the DR_MP3_FLOAT_OUTPUT option is set. + +v0.2.11 - 2018-08-08 + - Fix a bug where the last part of a file is not read. + +v0.2.10 - 2018-08-07 + - Improve 64-bit detection. + +v0.2.9 - 2018-08-05 + - Fix C++ build on older versions of GCC. + - Bring up to date with minimp3. + +v0.2.8 - 2018-08-02 + - Fix compilation errors with older versions of GCC. + +v0.2.7 - 2018-07-13 + - Bring up to date with minimp3. + +v0.2.6 - 2018-07-12 + - Bring up to date with minimp3. + +v0.2.5 - 2018-06-22 + - Bring up to date with minimp3. + +v0.2.4 - 2018-05-12 + - Bring up to date with minimp3. + +v0.2.3 - 2018-04-29 + - Fix TCC build. + +v0.2.2 - 2018-04-28 + - Fix bug when opening a decoder from memory. + +v0.2.1 - 2018-04-27 + - Efficiency improvements when the decoder reaches the end of the stream. + +v0.2 - 2018-04-21 + - Bring up to date with minimp3. + - Start using major.minor.revision versioning. + +v0.1d - 2018-03-30 + - Bring up to date with minimp3. + +v0.1c - 2018-03-11 + - Fix C++ build error. + +v0.1b - 2018-03-07 + - Bring up to date with minimp3. + +v0.1a - 2018-02-28 + - Fix compilation error on GCC/Clang. + - Fix some warnings. + +v0.1 - 2018-02-xx + - Initial versioned release. +*/ /* +This software is available as a choice of the following licenses. Choose +whichever you prefer. + +=============================================================================== +ALTERNATIVE 1 - Public Domain (www.unlicense.org) +=============================================================================== This is free and unencumbered software released into the public domain. -Anyone is free to copy, modify, publish, use, compile, sell, or -distribute this software, either in source code form or as a compiled -binary, for any purpose, commercial or non-commercial, and by any -means. - -In jurisdictions that recognize copyright laws, the author or authors -of this software dedicate any and all copyright interest in the -software to the public domain. We make this dedication for the benefit -of the public at large and to the detriment of our heirs and -successors. We intend this dedication to be an overt act of -relinquishment in perpetuity of all present and future rights to this -software under copyright law. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR -OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, -ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. + +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to + +=============================================================================== +ALTERNATIVE 2 - MIT No Attribution +=============================================================================== +Copyright 2018 David Reid + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. */ /* diff --git a/src/external/dr_wav.h b/src/external/dr_wav.h index b071d00e..b2395bfb 100644 --- a/src/external/dr_wav.h +++ b/src/external/dr_wav.h @@ -1,116 +1,155 @@ -// WAV audio loader and writer. Public domain. See "unlicense" statement at the end of this file. -// dr_wav - v0.8.1 - 2018-06-29 -// -// David Reid - mackron@gmail.com - -// USAGE -// -// This is a single-file library. To use it, do something like the following in one .c file. -// #define DR_WAV_IMPLEMENTATION -// #include "dr_wav.h" -// -// You can then #include this file in other parts of the program as you would with any other header file. Do something -// like the following to read audio data: -// -// drwav wav; -// if (!drwav_init_file(&wav, "my_song.wav")) { -// // Error opening WAV file. -// } -// -// drwav_int32* pDecodedInterleavedSamples = malloc(wav.totalSampleCount * sizeof(drwav_int32)); -// size_t numberOfSamplesActuallyDecoded = drwav_read_s32(&wav, wav.totalSampleCount, pDecodedInterleavedSamples); -// -// ... -// -// drwav_uninit(&wav); -// -// You can also use drwav_open() to allocate and initialize the loader for you: -// -// drwav* pWav = drwav_open_file("my_song.wav"); -// if (pWav == NULL) { -// // Error opening WAV file. -// } -// -// ... -// -// drwav_close(pWav); -// -// If you just want to quickly open and read the audio data in a single operation you can do something like this: -// -// unsigned int channels; -// unsigned int sampleRate; -// drwav_uint64 totalSampleCount; -// float* pSampleData = drwav_open_and_read_file_s32("my_song.wav", &channels, &sampleRate, &totalSampleCount); -// if (pSampleData == NULL) { -// // Error opening and reading WAV file. -// } -// -// ... -// -// drwav_free(pSampleData); -// -// The examples above use versions of the API that convert the audio data to a consistent format (32-bit signed PCM, in -// this case), but you can still output the audio data in its internal format (see notes below for supported formats): -// -// size_t samplesRead = drwav_read(&wav, wav.totalSampleCount, pDecodedInterleavedSamples); -// -// You can also read the raw bytes of audio data, which could be useful if dr_wav does not have native support for -// a particular data format: -// -// size_t bytesRead = drwav_read_raw(&wav, bytesToRead, pRawDataBuffer); -// -// -// dr_wav has seamless support the Sony Wave64 format. The decoder will automatically detect it and it should Just Work -// without any manual intervention. -// -// -// dr_wav can also be used to output WAV files. This does not currently support compressed formats. To use this, look at -// drwav_open_write(), drwav_open_file_write(), etc. Use drwav_write() to write samples, or drwav_write_raw() to write -// raw data in the "data" chunk. -// -// drwav_data_format format; -// format.container = drwav_container_riff; // <-- drwav_container_riff = normal WAV files, drwav_container_w64 = Sony Wave64. -// format.format = DR_WAVE_FORMAT_PCM; // <-- Any of the DR_WAVE_FORMAT_* codes. -// format.channels = 2; -// format.sampleRate = 44100; -// format.bitsPerSample = 16; -// drwav* pWav = drwav_open_file_write("data/recording.wav", &format); -// -// ... -// -// drwav_uint64 samplesWritten = drwav_write(pWav, sampleCount, pSamples); -// -// -// -// OPTIONS -// #define these options before including this file. -// -// #define DR_WAV_NO_CONVERSION_API -// Disables conversion APIs such as drwav_read_f32() and drwav_s16_to_f32(). -// -// #define DR_WAV_NO_STDIO -// Disables drwav_open_file(), drwav_open_file_write(), etc. -// -// -// -// QUICK NOTES -// - Samples are always interleaved. -// - The default read function does not do any data conversion. Use drwav_read_f32() to read and convert audio data -// to IEEE 32-bit floating point samples, drwav_read_s32() to read samples as signed 32-bit PCM and drwav_read_s16() -// to read samples as signed 16-bit PCM. Tested and supported internal formats include the following: -// - Unsigned 8-bit PCM -// - Signed 12-bit PCM -// - Signed 16-bit PCM -// - Signed 24-bit PCM -// - Signed 32-bit PCM -// - IEEE 32-bit floating point -// - IEEE 64-bit floating point -// - A-law and u-law -// - Microsoft ADPCM -// - IMA ADPCM (DVI, format code 0x11) -// - dr_wav will try to read the WAV file as best it can, even if it's not strictly conformant to the WAV format. +/* +WAV audio loader and writer. Choice of public domain or MIT-0. See license statements at the end of this file. +dr_wav - v0.9.1 - 2019-05-05 + +David Reid - mackron@gmail.com +*/ + +/* +DEPRECATED APIS +=============== +Version 0.9.0 deprecated the per-sample reading and seeking APIs and replaced them with versions that work on the resolution +of a PCM frame instead. For example, given a stereo WAV file, previously you would pass 2 to drwav_read_f32() to read one +PCM frame, whereas now you would pass in 1 to drwav_read_pcm_frames_f32(). The old APIs would return the number of samples +read, whereas now it will return the number of PCM frames. Below is a list of APIs that have been deprecated and their +replacements. + + drwav_read() -> drwav_read_pcm_frames() + drwav_read_s16() -> drwav_read_pcm_frames_s16() + drwav_read_f32() -> drwav_read_pcm_frames_f32() + drwav_read_s32() -> drwav_read_pcm_frames_s32() + drwav_seek_to_sample() -> drwav_seek_to_pcm_frame() + drwav_write() -> drwav_write_pcm_frames() + drwav_open_and_read_s16() -> drwav_open_and_read_pcm_frames_s16() + drwav_open_and_read_f32() -> drwav_open_and_read_pcm_frames_f32() + drwav_open_and_read_s32() -> drwav_open_and_read_pcm_frames_s32() + drwav_open_file_and_read_s16() -> drwav_open_file_and_read_pcm_frames_s16() + drwav_open_file_and_read_f32() -> drwav_open_file_and_read_pcm_frames_f32() + drwav_open_file_and_read_s32() -> drwav_open_file_and_read_pcm_frames_s32() + drwav_open_memory_and_read_s16() -> drwav_open_memory_and_read_pcm_frames_s16() + drwav_open_memory_and_read_f32() -> drwav_open_memory_and_read_pcm_frames_f32() + drwav_open_memory_and_read_s32() -> drwav_open_memory_and_read_pcm_frames_s32() + drwav::totalSampleCount -> drwav::totalPCMFrameCount + +Rationale: + 1) Most programs will want to read in multiples of the channel count which demands a per-frame reading API. Per-sample + reading just adds complexity and maintenance costs for no practical benefit. + 2) This is consistent with my other decoders - dr_flac and dr_mp3. + +These APIs will be removed completely in version 0.10.0. You can continue to use drwav_read_raw() if you need per-sample +reading. +*/ + +/* +USAGE +===== +This is a single-file library. To use it, do something like the following in one .c file. + #define DR_WAV_IMPLEMENTATION + #include "dr_wav.h" + +You can then #include this file in other parts of the program as you would with any other header file. Do something +like the following to read audio data: + + drwav wav; + if (!drwav_init_file(&wav, "my_song.wav")) { + // Error opening WAV file. + } + + drwav_int32* pDecodedInterleavedSamples = malloc(wav.totalPCMFrameCount * wav.channels * sizeof(drwav_int32)); + size_t numberOfSamplesActuallyDecoded = drwav_read_pcm_frames_s32(&wav, wav.totalPCMFrameCount, pDecodedInterleavedSamples); + + ... + + drwav_uninit(&wav); + +You can also use drwav_open() to allocate and initialize the loader for you: + + drwav* pWav = drwav_open_file("my_song.wav"); + if (pWav == NULL) { + // Error opening WAV file. + } + + ... + + drwav_close(pWav); + +If you just want to quickly open and read the audio data in a single operation you can do something like this: + + unsigned int channels; + unsigned int sampleRate; + drwav_uint64 totalPCMFrameCount; + float* pSampleData = drwav_open_file_and_read_pcm_frames_f32("my_song.wav", &channels, &sampleRate, &totalPCMFrameCount); + if (pSampleData == NULL) { + // Error opening and reading WAV file. + } + + ... + + drwav_free(pSampleData); + +The examples above use versions of the API that convert the audio data to a consistent format (32-bit signed PCM, in +this case), but you can still output the audio data in its internal format (see notes below for supported formats): + + size_t samplesRead = drwav_read_pcm_frames(&wav, wav.totalPCMFrameCount, pDecodedInterleavedSamples); + +You can also read the raw bytes of audio data, which could be useful if dr_wav does not have native support for +a particular data format: + + size_t bytesRead = drwav_read_raw(&wav, bytesToRead, pRawDataBuffer); + + +dr_wav can also be used to output WAV files. This does not currently support compressed formats. To use this, look at +drwav_open_write(), drwav_open_file_write(), etc. Use drwav_write_pcm_frames() to write samples, or drwav_write_raw() +to write raw data in the "data" chunk. + + drwav_data_format format; + format.container = drwav_container_riff; // <-- drwav_container_riff = normal WAV files, drwav_container_w64 = Sony Wave64. + format.format = DR_WAVE_FORMAT_PCM; // <-- Any of the DR_WAVE_FORMAT_* codes. + format.channels = 2; + format.sampleRate = 44100; + format.bitsPerSample = 16; + drwav* pWav = drwav_open_file_write("data/recording.wav", &format); + + ... + + drwav_uint64 samplesWritten = drwav_write_pcm_frames(pWav, frameCount, pSamples); +dr_wav has seamless support the Sony Wave64 format. The decoder will automatically detect it and it should Just Work +without any manual intervention. + + +OPTIONS +======= +#define these options before including this file. + +#define DR_WAV_NO_CONVERSION_API + Disables conversion APIs such as drwav_read_pcm_frames_f32() and drwav_s16_to_f32(). + +#define DR_WAV_NO_STDIO + Disables drwav_open_file(), drwav_open_file_write(), etc. + + + +QUICK NOTES +=========== +- Samples are always interleaved. +- The default read function does not do any data conversion. Use drwav_read_pcm_frames_f32(), drwav_read_pcm_frames_s32() + and drwav_read_pcm_frames_s16() to read and convert audio data to 32-bit floating point, signed 32-bit integer and + signed 16-bit integer samples respectively. Tested and supported internal formats include the following: + - Unsigned 8-bit PCM + - Signed 12-bit PCM + - Signed 16-bit PCM + - Signed 24-bit PCM + - Signed 32-bit PCM + - IEEE 32-bit floating point + - IEEE 64-bit floating point + - A-law and u-law + - Microsoft ADPCM + - IMA ADPCM (DVI, format code 0x11) +- dr_wav will try to read the WAV file as best it can, even if it's not strictly conformant to the WAV format. +*/ + #ifndef dr_wav_h #define dr_wav_h @@ -145,7 +184,7 @@ typedef drwav_uint32 drwav_bool32; extern "C" { #endif -// Common data formats. +/* Common data formats. */ #define DR_WAVE_FORMAT_PCM 0x1 #define DR_WAVE_FORMAT_ADPCM 0x2 #define DR_WAVE_FORMAT_IEEE_FLOAT 0x3 @@ -154,6 +193,14 @@ extern "C" { #define DR_WAVE_FORMAT_DVI_ADPCM 0x11 #define DR_WAVE_FORMAT_EXTENSIBLE 0xFFFE +/* Constants. */ +#ifndef DRWAV_MAX_SMPL_LOOPS +#define DRWAV_MAX_SMPL_LOOPS 1 +#endif + +/* Flags to pass into drwav_init_ex(), etc. */ +#define DRWAV_SEQUENTIAL 0x00000001 + typedef enum { drwav_seek_origin_start, @@ -166,42 +213,84 @@ typedef enum drwav_container_w64 } drwav_container; -// Callback for when data is read. Return value is the number of bytes actually read. -// -// pUserData [in] The user data that was passed to drwav_init(), drwav_open() and family. -// pBufferOut [out] The output buffer. -// bytesToRead [in] The number of bytes to read. -// -// Returns the number of bytes actually read. -// -// A return value of less than bytesToRead indicates the end of the stream. Do _not_ return from this callback until -// either the entire bytesToRead is filled or you have reached the end of the stream. +typedef struct +{ + union + { + drwav_uint8 fourcc[4]; + drwav_uint8 guid[16]; + } id; + + /* The size in bytes of the chunk. */ + drwav_uint64 sizeInBytes; + + /* + RIFF = 2 byte alignment. + W64 = 8 byte alignment. + */ + unsigned int paddingSize; +} drwav_chunk_header; + +/* +Callback for when data is read. Return value is the number of bytes actually read. + +pUserData [in] The user data that was passed to drwav_init(), drwav_open() and family. +pBufferOut [out] The output buffer. +bytesToRead [in] The number of bytes to read. + +Returns the number of bytes actually read. + +A return value of less than bytesToRead indicates the end of the stream. Do _not_ return from this callback until +either the entire bytesToRead is filled or you have reached the end of the stream. +*/ typedef size_t (* drwav_read_proc)(void* pUserData, void* pBufferOut, size_t bytesToRead); -// Callback for when data is written. Returns value is the number of bytes actually written. -// -// pUserData [in] The user data that was passed to drwav_init_write(), drwav_open_write() and family. -// pData [out] A pointer to the data to write. -// bytesToWrite [in] The number of bytes to write. -// -// Returns the number of bytes actually written. -// -// If the return value differs from bytesToWrite, it indicates an error. +/* +Callback for when data is written. Returns value is the number of bytes actually written. + +pUserData [in] The user data that was passed to drwav_init_write(), drwav_open_write() and family. +pData [out] A pointer to the data to write. +bytesToWrite [in] The number of bytes to write. + +Returns the number of bytes actually written. + +If the return value differs from bytesToWrite, it indicates an error. +*/ typedef size_t (* drwav_write_proc)(void* pUserData, const void* pData, size_t bytesToWrite); -// Callback for when data needs to be seeked. -// -// pUserData [in] The user data that was passed to drwav_init(), drwav_open() and family. -// offset [in] The number of bytes to move, relative to the origin. Will never be negative. -// origin [in] The origin of the seek - the current position or the start of the stream. -// -// Returns whether or not the seek was successful. -// -// Whether or not it is relative to the beginning or current position is determined by the "origin" parameter which -// will be either drwav_seek_origin_start or drwav_seek_origin_current. +/* +Callback for when data needs to be seeked. + +pUserData [in] The user data that was passed to drwav_init(), drwav_open() and family. +offset [in] The number of bytes to move, relative to the origin. Will never be negative. +origin [in] The origin of the seek - the current position or the start of the stream. + +Returns whether or not the seek was successful. + +Whether or not it is relative to the beginning or current position is determined by the "origin" parameter which +will be either drwav_seek_origin_start or drwav_seek_origin_current. +*/ typedef drwav_bool32 (* drwav_seek_proc)(void* pUserData, int offset, drwav_seek_origin origin); -// Structure for internal use. Only used for loaders opened with drwav_open_memory(). +/* +Callback for when drwav_init_ex/drwav_open_ex finds a chunk. + +pChunkUserData [in] The user data that was passed to the pChunkUserData parameter of drwav_init_ex(), drwav_open_ex() and family. +onRead [in] A pointer to the function to call when reading. +onSeek [in] A pointer to the function to call when seeking. +pReadSeekUserData [in] The user data that was passed to the pReadSeekUserData parameter of drwav_init_ex(), drwav_open_ex() and family. +pChunkHeader [in] A pointer to an object containing basic header information about the chunk. Use this to identify the chunk. + +Returns the number of bytes read + seeked. + +To read data from the chunk, call onRead(), passing in pReadSeekUserData as the first parameter. Do the same +for seeking with onSeek(). The return value must be the total number of bytes you have read _plus_ seeked. + +You must not attempt to read beyond the boundary of the chunk. +*/ +typedef drwav_uint64 (* drwav_chunk_proc)(void* pChunkUserData, drwav_read_proc onRead, drwav_seek_proc onSeek, void* pReadSeekUserData, const drwav_chunk_header* pChunkHeader); + +/* Structure for internal use. Only used for loaders opened with drwav_open_memory(). */ typedef struct { const drwav_uint8* data; @@ -209,7 +298,7 @@ typedef struct size_t currentReadPos; } drwav__memory_stream; -// Structure for internal use. Only used for writers opened with drwav_open_memory_write(). +/* Structure for internal use. Only used for writers opened with drwav_open_memory_write(). */ typedef struct { void** ppData; @@ -221,8 +310,8 @@ typedef struct typedef struct { - drwav_container container; // RIFF, W64. - drwav_uint32 format; // DR_WAVE_FORMAT_* + drwav_container container; /* RIFF, W64. */ + drwav_uint32 format; /* DR_WAVE_FORMAT_* */ drwav_uint32 channels; drwav_uint32 sampleRate; drwav_uint32 bitsPerSample; @@ -230,473 +319,591 @@ typedef struct typedef struct { - // The format tag exactly as specified in the wave file's "fmt" chunk. This can be used by applications - // that require support for data formats not natively supported by dr_wav. + /* + The format tag exactly as specified in the wave file's "fmt" chunk. This can be used by applications + that require support for data formats not natively supported by dr_wav. + */ drwav_uint16 formatTag; - // The number of channels making up the audio data. When this is set to 1 it is mono, 2 is stereo, etc. + /* The number of channels making up the audio data. When this is set to 1 it is mono, 2 is stereo, etc. */ drwav_uint16 channels; - // The sample rate. Usually set to something like 44100. + /* The sample rate. Usually set to something like 44100. */ drwav_uint32 sampleRate; - // Average bytes per second. You probably don't need this, but it's left here for informational purposes. + /* Average bytes per second. You probably don't need this, but it's left here for informational purposes. */ drwav_uint32 avgBytesPerSec; - // Block align. This is equal to the number of channels * bytes per sample. + /* Block align. This is equal to the number of channels * bytes per sample. */ drwav_uint16 blockAlign; - // Bits per sample. + /* Bits per sample. */ drwav_uint16 bitsPerSample; - // The size of the extended data. Only used internally for validation, but left here for informational purposes. + /* The size of the extended data. Only used internally for validation, but left here for informational purposes. */ drwav_uint16 extendedSize; - // The number of valid bits per sample. When is equal to WAVE_FORMAT_EXTENSIBLE, - // is always rounded up to the nearest multiple of 8. This variable contains information about exactly how - // many bits a valid per sample. Mainly used for informational purposes. + /* + The number of valid bits per sample. When is equal to WAVE_FORMAT_EXTENSIBLE, + is always rounded up to the nearest multiple of 8. This variable contains information about exactly how + many bits a valid per sample. Mainly used for informational purposes. + */ drwav_uint16 validBitsPerSample; - // The channel mask. Not used at the moment. + /* The channel mask. Not used at the moment. */ drwav_uint32 channelMask; - // The sub-format, exactly as specified by the wave file. + /* The sub-format, exactly as specified by the wave file. */ drwav_uint8 subFormat[16]; } drwav_fmt; typedef struct { - // A pointer to the function to call when more data is needed. + drwav_uint32 cuePointId; + drwav_uint32 type; + drwav_uint32 start; + drwav_uint32 end; + drwav_uint32 fraction; + drwav_uint32 playCount; +} drwav_smpl_loop; + + typedef struct +{ + drwav_uint32 manufacturer; + drwav_uint32 product; + drwav_uint32 samplePeriod; + drwav_uint32 midiUnityNotes; + drwav_uint32 midiPitchFraction; + drwav_uint32 smpteFormat; + drwav_uint32 smpteOffset; + drwav_uint32 numSampleLoops; + drwav_uint32 samplerData; + drwav_smpl_loop loops[DRWAV_MAX_SMPL_LOOPS]; +} drwav_smpl; + +typedef struct +{ + /* A pointer to the function to call when more data is needed. */ drwav_read_proc onRead; - // A pointer to the function to call when data needs to be written. Only used when the drwav object is opened in write mode. + /* A pointer to the function to call when data needs to be written. Only used when the drwav object is opened in write mode. */ drwav_write_proc onWrite; - // A pointer to the function to call when the wav file needs to be seeked. + /* A pointer to the function to call when the wav file needs to be seeked. */ drwav_seek_proc onSeek; - // The user data to pass to callbacks. + /* The user data to pass to callbacks. */ void* pUserData; - // Whether or not the WAV file is formatted as a standard RIFF file or W64. + /* Whether or not the WAV file is formatted as a standard RIFF file or W64. */ drwav_container container; - // Structure containing format information exactly as specified by the wav file. + /* Structure containing format information exactly as specified by the wav file. */ drwav_fmt fmt; - // The sample rate. Will be set to something like 44100. + /* The sample rate. Will be set to something like 44100. */ drwav_uint32 sampleRate; - // The number of channels. This will be set to 1 for monaural streams, 2 for stereo, etc. + /* The number of channels. This will be set to 1 for monaural streams, 2 for stereo, etc. */ drwav_uint16 channels; - // The bits per sample. Will be set to something like 16, 24, etc. + /* The bits per sample. Will be set to something like 16, 24, etc. */ drwav_uint16 bitsPerSample; - // The number of bytes per sample. - drwav_uint16 bytesPerSample; - - // Equal to fmt.formatTag, or the value specified by fmt.subFormat if fmt.formatTag is equal to 65534 (WAVE_FORMAT_EXTENSIBLE). + /* Equal to fmt.formatTag, or the value specified by fmt.subFormat if fmt.formatTag is equal to 65534 (WAVE_FORMAT_EXTENSIBLE). */ drwav_uint16 translatedFormatTag; - // The total number of samples making up the audio data. Use * to calculate - // the required size of a buffer to hold the entire audio data. - drwav_uint64 totalSampleCount; + /* The total number of PCM frames making up the audio data. */ + drwav_uint64 totalPCMFrameCount; - // The size in bytes of the data chunk. + /* The size in bytes of the data chunk. */ drwav_uint64 dataChunkDataSize; - // The position in the stream of the first byte of the data chunk. This is used for seeking. + /* The position in the stream of the first byte of the data chunk. This is used for seeking. */ drwav_uint64 dataChunkDataPos; - // The number of bytes remaining in the data chunk. + /* The number of bytes remaining in the data chunk. */ drwav_uint64 bytesRemaining; - // Only used in sequential write mode. Keeps track of the desired size of the "data" chunk at the point of initialization time. Always - // set to 0 for non-sequential writes and when the drwav object is opened in read mode. Used for validation. + /* + Only used in sequential write mode. Keeps track of the desired size of the "data" chunk at the point of initialization time. Always + set to 0 for non-sequential writes and when the drwav object is opened in read mode. Used for validation. + */ drwav_uint64 dataChunkDataSizeTargetWrite; - // Keeps track of whether or not the wav writer was initialized in sequential mode. + /* Keeps track of whether or not the wav writer was initialized in sequential mode. */ drwav_bool32 isSequentialWrite; - // A hack to avoid a DRWAV_MALLOC() when opening a decoder with drwav_open_memory(). + /* smpl chunk. */ + drwav_smpl smpl; + + + /* A hack to avoid a DRWAV_MALLOC() when opening a decoder with drwav_open_memory(). */ drwav__memory_stream memoryStream; drwav__memory_stream_write memoryStreamWrite; - // Generic data for compressed formats. This data is shared across all block-compressed formats. + /* Generic data for compressed formats. This data is shared across all block-compressed formats. */ struct { - drwav_uint64 iCurrentSample; // The index of the next sample that will be read by drwav_read_*(). This is used with "totalSampleCount" to ensure we don't read excess samples at the end of the last block. + drwav_uint64 iCurrentSample; /* The index of the next sample that will be read by drwav_read_*(). This is used with "totalSampleCount" to ensure we don't read excess samples at the end of the last block. */ } compressed; - // Microsoft ADPCM specific data. + /* Microsoft ADPCM specific data. */ struct { drwav_uint32 bytesRemainingInBlock; drwav_uint16 predictor[2]; drwav_int32 delta[2]; - drwav_int32 cachedSamples[4]; // Samples are stored in this cache during decoding. + drwav_int32 cachedSamples[4]; /* Samples are stored in this cache during decoding. */ drwav_uint32 cachedSampleCount; - drwav_int32 prevSamples[2][2]; // The previous 2 samples for each channel (2 channels at most). + drwav_int32 prevSamples[2][2]; /* The previous 2 samples for each channel (2 channels at most). */ } msadpcm; - // IMA ADPCM specific data. + /* IMA ADPCM specific data. */ struct { drwav_uint32 bytesRemainingInBlock; drwav_int32 predictor[2]; drwav_int32 stepIndex[2]; - drwav_int32 cachedSamples[16]; // Samples are stored in this cache during decoding. + drwav_int32 cachedSamples[16]; /* Samples are stored in this cache during decoding. */ drwav_uint32 cachedSampleCount; } ima; + + + drwav_uint64 totalSampleCount; /* <-- DEPRECATED. Will be removed in a future version. */ } drwav; -// Initializes a pre-allocated drwav object. -// -// onRead [in] The function to call when data needs to be read from the client. -// onSeek [in] The function to call when the read position of the client data needs to move. -// pUserData [in, optional] A pointer to application defined data that will be passed to onRead and onSeek. -// -// Returns true if successful; false otherwise. -// -// Close the loader with drwav_uninit(). -// -// This is the lowest level function for initializing a WAV file. You can also use drwav_init_file() and drwav_init_memory() -// to open the stream from a file or from a block of memory respectively. -// -// If you want dr_wav to manage the memory allocation for you, consider using drwav_open() instead. This will allocate -// a drwav object on the heap and return a pointer to it. -// -// See also: drwav_init_file(), drwav_init_memory(), drwav_uninit() +/* +Initializes a pre-allocated drwav object. + +pWav [out] A pointer to the drwav object being initialized. +onRead [in] The function to call when data needs to be read from the client. +onSeek [in] The function to call when the read position of the client data needs to move. +onChunk [in, optional] The function to call when a chunk is enumerated at initialized time. +pUserData, pReadSeekUserData [in, optional] A pointer to application defined data that will be passed to onRead and onSeek. +pChunkUserData [in, optional] A pointer to application defined data that will be passed to onChunk. +flags [in, optional] A set of flags for controlling how things are loaded. + +Returns true if successful; false otherwise. + +Close the loader with drwav_uninit(). + +This is the lowest level function for initializing a WAV file. You can also use drwav_init_file() and drwav_init_memory() +to open the stream from a file or from a block of memory respectively. + +If you want dr_wav to manage the memory allocation for you, consider using drwav_open() instead. This will allocate +a drwav object on the heap and return a pointer to it. + +Possible values for flags: + DRWAV_SEQUENTIAL: Never perform a backwards seek while loading. This disables the chunk callback and will cause this function + to return as soon as the data chunk is found. Any chunks after the data chunk will be ignored. + +drwav_init() is equivalent to "drwav_init_ex(pWav, onRead, onSeek, NULL, pUserData, NULL, 0);". + +The onChunk callback is not called for the WAVE or FMT chunks. The contents of the FMT chunk can be read from pWav->fmt +after the function returns. + +See also: drwav_init_file(), drwav_init_memory(), drwav_uninit() +*/ drwav_bool32 drwav_init(drwav* pWav, drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData); +drwav_bool32 drwav_init_ex(drwav* pWav, drwav_read_proc onRead, drwav_seek_proc onSeek, drwav_chunk_proc onChunk, void* pReadSeekUserData, void* pChunkUserData, drwav_uint32 flags); + +/* +Initializes a pre-allocated drwav object for writing. + +onWrite [in] The function to call when data needs to be written. +onSeek [in] The function to call when the write position needs to move. +pUserData [in, optional] A pointer to application defined data that will be passed to onWrite and onSeek. + +Returns true if successful; false otherwise. + +Close the writer with drwav_uninit(). -// Initializes a pre-allocated drwav object for writing. -// -// onWrite [in] The function to call when data needs to be written. -// onSeek [in] The function to call when the write position needs to move. -// pUserData [in, optional] A pointer to application defined data that will be passed to onWrite and onSeek. -// -// Returns true if successful; false otherwise. -// -// Close the writer with drwav_uninit(). -// -// This is the lowest level function for initializing a WAV file. You can also use drwav_init_file() and drwav_init_memory() -// to open the stream from a file or from a block of memory respectively. -// -// If the total sample count is known, you can use drwav_init_write_sequential(). This avoids the need for dr_wav to perform -// a post-processing step for storing the total sample count and the size of the data chunk which requires a backwards seek. -// -// If you want dr_wav to manage the memory allocation for you, consider using drwav_open() instead. This will allocate -// a drwav object on the heap and return a pointer to it. -// -// See also: drwav_init_file_write(), drwav_init_memory_write(), drwav_uninit() +This is the lowest level function for initializing a WAV file. You can also use drwav_init_file() and drwav_init_memory() +to open the stream from a file or from a block of memory respectively. + +If the total sample count is known, you can use drwav_init_write_sequential(). This avoids the need for dr_wav to perform +a post-processing step for storing the total sample count and the size of the data chunk which requires a backwards seek. + +If you want dr_wav to manage the memory allocation for you, consider using drwav_open() instead. This will allocate +a drwav object on the heap and return a pointer to it. + +See also: drwav_init_file_write(), drwav_init_memory_write(), drwav_uninit() +*/ drwav_bool32 drwav_init_write(drwav* pWav, const drwav_data_format* pFormat, drwav_write_proc onWrite, drwav_seek_proc onSeek, void* pUserData); drwav_bool32 drwav_init_write_sequential(drwav* pWav, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_write_proc onWrite, void* pUserData); -// Uninitializes the given drwav object. -// -// Use this only for objects initialized with drwav_init(). +/* +Uninitializes the given drwav object. + +Use this only for objects initialized with drwav_init(). +*/ void drwav_uninit(drwav* pWav); -// Opens a wav file using the given callbacks. -// -// onRead [in] The function to call when data needs to be read from the client. -// onSeek [in] The function to call when the read position of the client data needs to move. -// pUserData [in, optional] A pointer to application defined data that will be passed to onRead and onSeek. -// -// Returns null on error. -// -// Close the loader with drwav_close(). -// -// You can also use drwav_open_file() and drwav_open_memory() to open the stream from a file or from a block of -// memory respectively. -// -// This is different from drwav_init() in that it will allocate the drwav object for you via DRWAV_MALLOC() before -// initializing it. -// -// See also: drwav_open_file(), drwav_open_memory(), drwav_close() +/* +Opens a wav file using the given callbacks. + +onRead [in] The function to call when data needs to be read from the client. +onSeek [in] The function to call when the read position of the client data needs to move. +pUserData [in, optional] A pointer to application defined data that will be passed to onRead and onSeek. + +Returns null on error. + +Close the loader with drwav_close(). + +You can also use drwav_open_file() and drwav_open_memory() to open the stream from a file or from a block of +memory respectively. + +This is different from drwav_init() in that it will allocate the drwav object for you via DRWAV_MALLOC() before +initializing it. + +See also: drwav_init(), drwav_open_file(), drwav_open_memory(), drwav_close() +*/ drwav* drwav_open(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData); +drwav* drwav_open_ex(drwav_read_proc onRead, drwav_seek_proc onSeek, drwav_chunk_proc onChunk, void* pReadSeekUserData, void* pChunkUserData, drwav_uint32 flags); + +/* +Opens a wav file for writing using the given callbacks. + +onWrite [in] The function to call when data needs to be written. +onSeek [in] The function to call when the write position needs to move. +pUserData [in, optional] A pointer to application defined data that will be passed to onWrite and onSeek. -// Opens a wav file for writing using the given callbacks. -// -// onWrite [in] The function to call when data needs to be written. -// onSeek [in] The function to call when the write position needs to move. -// pUserData [in, optional] A pointer to application defined data that will be passed to onWrite and onSeek. -// -// Returns null on error. -// -// Close the loader with drwav_close(). -// -// You can also use drwav_open_file_write() and drwav_open_memory_write() to open the stream from a file or from a block -// of memory respectively. -// -// This is different from drwav_init_write() in that it will allocate the drwav object for you via DRWAV_MALLOC() before -// initializing it. -// -// See also: drwav_open_file_write(), drwav_open_memory_write(), drwav_close() +Returns null on error. + +Close the loader with drwav_close(). + +You can also use drwav_open_file_write() and drwav_open_memory_write() to open the stream from a file or from a block +of memory respectively. + +This is different from drwav_init_write() in that it will allocate the drwav object for you via DRWAV_MALLOC() before +initializing it. + +See also: drwav_open_file_write(), drwav_open_memory_write(), drwav_close() +*/ drwav* drwav_open_write(const drwav_data_format* pFormat, drwav_write_proc onWrite, drwav_seek_proc onSeek, void* pUserData); drwav* drwav_open_write_sequential(const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_write_proc onWrite, void* pUserData); -// Uninitializes and deletes the the given drwav object. -// -// Use this only for objects created with drwav_open(). +/* +Uninitializes and deletes the the given drwav object. + +Use this only for objects created with drwav_open(). +*/ void drwav_close(drwav* pWav); -// Reads raw audio data. -// -// This is the lowest level function for reading audio data. It simply reads the given number of -// bytes of the raw internal sample data. -// -// Consider using drwav_read_s16(), drwav_read_s32() or drwav_read_f32() for reading sample data in -// a consistent format. -// -// Returns the number of bytes actually read. +/* +Reads raw audio data. + +This is the lowest level function for reading audio data. It simply reads the given number of +bytes of the raw internal sample data. + +Consider using drwav_read_pcm_frames_s16(), drwav_read_pcm_frames_s32() or drwav_read_pcm_frames_f32() for +reading sample data in a consistent format. + +Returns the number of bytes actually read. +*/ size_t drwav_read_raw(drwav* pWav, size_t bytesToRead, void* pBufferOut); -// Reads a chunk of audio data in the native internal format. -// -// This is typically the most efficient way to retrieve audio data, but it does not do any format -// conversions which means you'll need to convert the data manually if required. -// -// If the return value is less than it means the end of the file has been reached or -// you have requested more samples than can possibly fit in the output buffer. -// -// This function will only work when sample data is of a fixed size and uncompressed. If you are -// using a compressed format consider using drwav_read_raw() or drwav_read_s16/s32/f32/etc(). -drwav_uint64 drwav_read(drwav* pWav, drwav_uint64 samplesToRead, void* pBufferOut); +/* +Reads a chunk of audio data in the native internal format. -// Seeks to the given sample. -// -// Returns true if successful; false otherwise. -drwav_bool32 drwav_seek_to_sample(drwav* pWav, drwav_uint64 sample); +This is typically the most efficient way to retrieve audio data, but it does not do any format +conversions which means you'll need to convert the data manually if required. + +If the return value is less than it means the end of the file has been reached or +you have requested more samples than can possibly fit in the output buffer. +This function will only work when sample data is of a fixed size and uncompressed. If you are +using a compressed format consider using drwav_read_raw() or drwav_read_pcm_frames_s16/s32/f32/etc(). +*/ +drwav_uint64 drwav_read_pcm_frames(drwav* pWav, drwav_uint64 framesToRead, void* pBufferOut); + +/* +Seeks to the given PCM frame. + +Returns true if successful; false otherwise. +*/ +drwav_bool32 drwav_seek_to_pcm_frame(drwav* pWav, drwav_uint64 targetFrameIndex); -// Writes raw audio data. -// -// Returns the number of bytes actually written. If this differs from bytesToWrite, it indicates an error. + +/* +Writes raw audio data. + +Returns the number of bytes actually written. If this differs from bytesToWrite, it indicates an error. +*/ size_t drwav_write_raw(drwav* pWav, size_t bytesToWrite, const void* pData); -// Writes audio data based on sample counts. -// -// Returns the number of samples written. -drwav_uint64 drwav_write(drwav* pWav, drwav_uint64 samplesToWrite, const void* pData); +/* +Writes PCM frames. +Returns the number of PCM frames written. +*/ +drwav_uint64 drwav_write_pcm_frames(drwav* pWav, drwav_uint64 framesToWrite, const void* pData); -//// Conversion Utilities //// +/* Conversion Utilities */ #ifndef DR_WAV_NO_CONVERSION_API -// Reads a chunk of audio data and converts it to signed 16-bit PCM samples. -// -// Returns the number of samples actually read. -// -// If the return value is less than it means the end of the file has been reached. -drwav_uint64 drwav_read_s16(drwav* pWav, drwav_uint64 samplesToRead, drwav_int16* pBufferOut); +/* +Reads a chunk of audio data and converts it to signed 16-bit PCM samples. -// Low-level function for converting unsigned 8-bit PCM samples to signed 16-bit PCM samples. +Returns the number of PCM frames actually read. + +If the return value is less than it means the end of the file has been reached. +*/ +drwav_uint64 drwav_read_pcm_frames_s16(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut); + +/* Low-level function for converting unsigned 8-bit PCM samples to signed 16-bit PCM samples. */ void drwav_u8_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount); -// Low-level function for converting signed 24-bit PCM samples to signed 16-bit PCM samples. +/* Low-level function for converting signed 24-bit PCM samples to signed 16-bit PCM samples. */ void drwav_s24_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount); -// Low-level function for converting signed 32-bit PCM samples to signed 16-bit PCM samples. +/* Low-level function for converting signed 32-bit PCM samples to signed 16-bit PCM samples. */ void drwav_s32_to_s16(drwav_int16* pOut, const drwav_int32* pIn, size_t sampleCount); -// Low-level function for converting IEEE 32-bit floating point samples to signed 16-bit PCM samples. +/* Low-level function for converting IEEE 32-bit floating point samples to signed 16-bit PCM samples. */ void drwav_f32_to_s16(drwav_int16* pOut, const float* pIn, size_t sampleCount); -// Low-level function for converting IEEE 64-bit floating point samples to signed 16-bit PCM samples. +/* Low-level function for converting IEEE 64-bit floating point samples to signed 16-bit PCM samples. */ void drwav_f64_to_s16(drwav_int16* pOut, const double* pIn, size_t sampleCount); -// Low-level function for converting A-law samples to signed 16-bit PCM samples. +/* Low-level function for converting A-law samples to signed 16-bit PCM samples. */ void drwav_alaw_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount); -// Low-level function for converting u-law samples to signed 16-bit PCM samples. +/* Low-level function for converting u-law samples to signed 16-bit PCM samples. */ void drwav_mulaw_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount); -// Reads a chunk of audio data and converts it to IEEE 32-bit floating point samples. -// -// Returns the number of samples actually read. -// -// If the return value is less than it means the end of the file has been reached. -drwav_uint64 drwav_read_f32(drwav* pWav, drwav_uint64 samplesToRead, float* pBufferOut); +/* +Reads a chunk of audio data and converts it to IEEE 32-bit floating point samples. + +Returns the number of PCM frames actually read. -// Low-level function for converting unsigned 8-bit PCM samples to IEEE 32-bit floating point samples. +If the return value is less than it means the end of the file has been reached. +*/ +drwav_uint64 drwav_read_pcm_frames_f32(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut); + +/* Low-level function for converting unsigned 8-bit PCM samples to IEEE 32-bit floating point samples. */ void drwav_u8_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount); -// Low-level function for converting signed 16-bit PCM samples to IEEE 32-bit floating point samples. +/* Low-level function for converting signed 16-bit PCM samples to IEEE 32-bit floating point samples. */ void drwav_s16_to_f32(float* pOut, const drwav_int16* pIn, size_t sampleCount); -// Low-level function for converting signed 24-bit PCM samples to IEEE 32-bit floating point samples. +/* Low-level function for converting signed 24-bit PCM samples to IEEE 32-bit floating point samples. */ void drwav_s24_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount); -// Low-level function for converting signed 32-bit PCM samples to IEEE 32-bit floating point samples. +/* Low-level function for converting signed 32-bit PCM samples to IEEE 32-bit floating point samples. */ void drwav_s32_to_f32(float* pOut, const drwav_int32* pIn, size_t sampleCount); -// Low-level function for converting IEEE 64-bit floating point samples to IEEE 32-bit floating point samples. +/* Low-level function for converting IEEE 64-bit floating point samples to IEEE 32-bit floating point samples. */ void drwav_f64_to_f32(float* pOut, const double* pIn, size_t sampleCount); -// Low-level function for converting A-law samples to IEEE 32-bit floating point samples. +/* Low-level function for converting A-law samples to IEEE 32-bit floating point samples. */ void drwav_alaw_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount); -// Low-level function for converting u-law samples to IEEE 32-bit floating point samples. +/* Low-level function for converting u-law samples to IEEE 32-bit floating point samples. */ void drwav_mulaw_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount); -// Reads a chunk of audio data and converts it to signed 32-bit PCM samples. -// -// Returns the number of samples actually read. -// -// If the return value is less than it means the end of the file has been reached. -drwav_uint64 drwav_read_s32(drwav* pWav, drwav_uint64 samplesToRead, drwav_int32* pBufferOut); +/* +Reads a chunk of audio data and converts it to signed 32-bit PCM samples. + +Returns the number of PCM frames actually read. + +If the return value is less than it means the end of the file has been reached. +*/ +drwav_uint64 drwav_read_pcm_frames_s32(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut); -// Low-level function for converting unsigned 8-bit PCM samples to signed 32-bit PCM samples. +/* Low-level function for converting unsigned 8-bit PCM samples to signed 32-bit PCM samples. */ void drwav_u8_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount); -// Low-level function for converting signed 16-bit PCM samples to signed 32-bit PCM samples. +/* Low-level function for converting signed 16-bit PCM samples to signed 32-bit PCM samples. */ void drwav_s16_to_s32(drwav_int32* pOut, const drwav_int16* pIn, size_t sampleCount); -// Low-level function for converting signed 24-bit PCM samples to signed 32-bit PCM samples. +/* Low-level function for converting signed 24-bit PCM samples to signed 32-bit PCM samples. */ void drwav_s24_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount); -// Low-level function for converting IEEE 32-bit floating point samples to signed 32-bit PCM samples. +/* Low-level function for converting IEEE 32-bit floating point samples to signed 32-bit PCM samples. */ void drwav_f32_to_s32(drwav_int32* pOut, const float* pIn, size_t sampleCount); -// Low-level function for converting IEEE 64-bit floating point samples to signed 32-bit PCM samples. +/* Low-level function for converting IEEE 64-bit floating point samples to signed 32-bit PCM samples. */ void drwav_f64_to_s32(drwav_int32* pOut, const double* pIn, size_t sampleCount); -// Low-level function for converting A-law samples to signed 32-bit PCM samples. +/* Low-level function for converting A-law samples to signed 32-bit PCM samples. */ void drwav_alaw_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount); -// Low-level function for converting u-law samples to signed 32-bit PCM samples. +/* Low-level function for converting u-law samples to signed 32-bit PCM samples. */ void drwav_mulaw_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount); -#endif //DR_WAV_NO_CONVERSION_API +#endif /* DR_WAV_NO_CONVERSION_API */ -//// High-Level Convenience Helpers //// +/* High-Level Convenience Helpers */ #ifndef DR_WAV_NO_STDIO +/* +Helper for initializing a wave file using stdio. -// Helper for initializing a wave file using stdio. -// -// This holds the internal FILE object until drwav_uninit() is called. Keep this in mind if you're caching drwav -// objects because the operating system may restrict the number of file handles an application can have open at -// any given time. +This holds the internal FILE object until drwav_uninit() is called. Keep this in mind if you're caching drwav +objects because the operating system may restrict the number of file handles an application can have open at +any given time. +*/ drwav_bool32 drwav_init_file(drwav* pWav, const char* filename); +drwav_bool32 drwav_init_file_ex(drwav* pWav, const char* filename, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags); -// Helper for initializing a wave file for writing using stdio. -// -// This holds the internal FILE object until drwav_uninit() is called. Keep this in mind if you're caching drwav -// objects because the operating system may restrict the number of file handles an application can have open at -// any given time. +/* +Helper for initializing a wave file for writing using stdio. + +This holds the internal FILE object until drwav_uninit() is called. Keep this in mind if you're caching drwav +objects because the operating system may restrict the number of file handles an application can have open at +any given time. +*/ drwav_bool32 drwav_init_file_write(drwav* pWav, const char* filename, const drwav_data_format* pFormat); drwav_bool32 drwav_init_file_write_sequential(drwav* pWav, const char* filename, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount); -// Helper for opening a wave file using stdio. -// -// This holds the internal FILE object until drwav_close() is called. Keep this in mind if you're caching drwav -// objects because the operating system may restrict the number of file handles an application can have open at -// any given time. +/* +Helper for opening a wave file using stdio. + +This holds the internal FILE object until drwav_close() is called. Keep this in mind if you're caching drwav +objects because the operating system may restrict the number of file handles an application can have open at +any given time. +*/ drwav* drwav_open_file(const char* filename); +drwav* drwav_open_file_ex(const char* filename, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags); + +/* +Helper for opening a wave file for writing using stdio. -// Helper for opening a wave file for writing using stdio. -// -// This holds the internal FILE object until drwav_close() is called. Keep this in mind if you're caching drwav -// objects because the operating system may restrict the number of file handles an application can have open at -// any given time. +This holds the internal FILE object until drwav_close() is called. Keep this in mind if you're caching drwav +objects because the operating system may restrict the number of file handles an application can have open at +any given time. +*/ drwav* drwav_open_file_write(const char* filename, const drwav_data_format* pFormat); drwav* drwav_open_file_write_sequential(const char* filename, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount); -#endif //DR_WAV_NO_STDIO +#endif /* DR_WAV_NO_STDIO */ + +/* +Helper for initializing a loader from a pre-allocated memory buffer. + +This does not create a copy of the data. It is up to the application to ensure the buffer remains valid for +the lifetime of the drwav object. -// Helper for initializing a loader from a pre-allocated memory buffer. -// -// This does not create a copy of the data. It is up to the application to ensure the buffer remains valid for -// the lifetime of the drwav object. -// -// The buffer should contain the contents of the entire wave file, not just the sample data. +The buffer should contain the contents of the entire wave file, not just the sample data. +*/ drwav_bool32 drwav_init_memory(drwav* pWav, const void* data, size_t dataSize); +drwav_bool32 drwav_init_memory_ex(drwav* pWav, const void* data, size_t dataSize, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags); + +/* +Helper for initializing a writer which outputs data to a memory buffer. + +dr_wav will manage the memory allocations, however it is up to the caller to free the data with drwav_free(). -// Helper for initializing a writer which outputs data to a memory buffer. -// -// dr_wav will manage the memory allocations, however it is up to the caller to free the data with drwav_free(). -// -// The buffer will remain allocated even after drwav_uninit() is called. Indeed, the buffer should not be -// considered valid until after drwav_uninit() has been called anyway. +The buffer will remain allocated even after drwav_uninit() is called. Indeed, the buffer should not be +considered valid until after drwav_uninit() has been called anyway. +*/ drwav_bool32 drwav_init_memory_write(drwav* pWav, void** ppData, size_t* pDataSize, const drwav_data_format* pFormat); drwav_bool32 drwav_init_memory_write_sequential(drwav* pWav, void** ppData, size_t* pDataSize, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount); -// Helper for opening a loader from a pre-allocated memory buffer. -// -// This does not create a copy of the data. It is up to the application to ensure the buffer remains valid for -// the lifetime of the drwav object. -// -// The buffer should contain the contents of the entire wave file, not just the sample data. +/* +Helper for opening a loader from a pre-allocated memory buffer. + +This does not create a copy of the data. It is up to the application to ensure the buffer remains valid for +the lifetime of the drwav object. + +The buffer should contain the contents of the entire wave file, not just the sample data. +*/ drwav* drwav_open_memory(const void* data, size_t dataSize); +drwav* drwav_open_memory_ex(const void* data, size_t dataSize, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags); -// Helper for opening a writer which outputs data to a memory buffer. -// -// dr_wav will manage the memory allocations, however it is up to the caller to free the data with drwav_free(). -// -// The buffer will remain allocated even after drwav_close() is called. Indeed, the buffer should not be -// considered valid until after drwav_close() has been called anyway. +/* +Helper for opening a writer which outputs data to a memory buffer. + +dr_wav will manage the memory allocations, however it is up to the caller to free the data with drwav_free(). + +The buffer will remain allocated even after drwav_close() is called. Indeed, the buffer should not be +considered valid until after drwav_close() has been called anyway. +*/ drwav* drwav_open_memory_write(void** ppData, size_t* pDataSize, const drwav_data_format* pFormat); drwav* drwav_open_memory_write_sequential(void** ppData, size_t* pDataSize, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount); #ifndef DR_WAV_NO_CONVERSION_API -// Opens and reads a wav file in a single operation. +/* Opens and reads a wav file in a single operation. */ +drwav_int16* drwav_open_and_read_pcm_frames_s16(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalFrameCount); +float* drwav_open_and_read_pcm_frames_f32(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalFrameCount); +drwav_int32* drwav_open_and_read_pcm_frames_s32(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalFrameCount); +#ifndef DR_WAV_NO_STDIO +/* Opens and decodes a wav file in a single operation. */ +drwav_int16* drwav_open_file_and_read_pcm_frames_s16(const char* filename, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalFrameCount); +float* drwav_open_file_and_read_pcm_frames_f32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalFrameCount); +drwav_int32* drwav_open_file_and_read_pcm_frames_s32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalFrameCount); +#endif + +/* Opens and decodes a wav file from a block of memory in a single operation. */ +drwav_int16* drwav_open_memory_and_read_pcm_frames_s16(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalFrameCount); +float* drwav_open_memory_and_read_pcm_frames_f32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalFrameCount); +drwav_int32* drwav_open_memory_and_read_pcm_frames_s32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalFrameCount); +#endif + +/* Frees data that was allocated internally by dr_wav. */ +void drwav_free(void* pDataReturnedByOpenAndRead); + + +/* DEPRECATED APIS */ +drwav_uint64 drwav_read(drwav* pWav, drwav_uint64 samplesToRead, void* pBufferOut); +drwav_uint64 drwav_read_s16(drwav* pWav, drwav_uint64 samplesToRead, drwav_int16* pBufferOut); +drwav_uint64 drwav_read_f32(drwav* pWav, drwav_uint64 samplesToRead, float* pBufferOut); +drwav_uint64 drwav_read_s32(drwav* pWav, drwav_uint64 samplesToRead, drwav_int32* pBufferOut); +drwav_bool32 drwav_seek_to_sample(drwav* pWav, drwav_uint64 sample); +drwav_uint64 drwav_write(drwav* pWav, drwav_uint64 samplesToWrite, const void* pData); +#ifndef DR_WAV_NO_CONVERSION_API drwav_int16* drwav_open_and_read_s16(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount); float* drwav_open_and_read_f32(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount); drwav_int32* drwav_open_and_read_s32(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount); #ifndef DR_WAV_NO_STDIO -// Opens and decodes a wav file in a single operation. -drwav_int16* drwav_open_and_read_file_s16(const char* filename, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount); -float* drwav_open_and_read_file_f32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount); -drwav_int32* drwav_open_and_read_file_s32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount); +drwav_int16* drwav_open_memory_and_read_s16(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount); +float* drwav_open_file_and_read_f32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount); +drwav_int32* drwav_open_file_and_read_s32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount); #endif - -// Opens and decodes a wav file from a block of memory in a single operation. -drwav_int16* drwav_open_and_read_memory_s16(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount); -float* drwav_open_and_read_memory_f32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount); -drwav_int32* drwav_open_and_read_memory_s32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount); +drwav_int16* drwav_open_memory_and_read_s16(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount); +float* drwav_open_memory_and_read_f32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount); +drwav_int32* drwav_open_memory_and_read_s32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount); #endif -// Frees data that was allocated internally by dr_wav. -void drwav_free(void* pDataReturnedByOpenAndRead); #ifdef __cplusplus } #endif -#endif // dr_wav_h +#endif /* dr_wav_h */ + +/************************************************************************************************************************************************************ + ************************************************************************************************************************************************************ -///////////////////////////////////////////////////// -// -// IMPLEMENTATION -// -///////////////////////////////////////////////////// + IMPLEMENTATION + ************************************************************************************************************************************************************ + ************************************************************************************************************************************************************/ #ifdef DR_WAV_IMPLEMENTATION #include -#include // For memcpy(), memset() -#include // For INT_MAX +#include /* For memcpy(), memset() */ +#include /* For INT_MAX */ #ifndef DR_WAV_NO_STDIO #include #endif -// Standard library stuff. +/* Standard library stuff. */ #ifndef DRWAV_ASSERT #include #define DRWAV_ASSERT(expression) assert(expression) @@ -727,34 +934,43 @@ void drwav_free(void* pDataReturnedByOpenAndRead); #define drwav_copy_memory DRWAV_COPY_MEMORY #define drwav_zero_memory DRWAV_ZERO_MEMORY +typedef drwav_int32 drwav_result; +#define DRWAV_SUCCESS 0 +#define DRWAV_ERROR -1 +#define DRWAV_INVALID_ARGS -2 +#define DRWAV_INVALID_OPERATION -3 +#define DRWAV_INVALID_FILE -100 +#define DRWAV_EOF -101 -#define DRWAV_MAX_SIMD_VECTOR_SIZE 64 // 64 for AVX-512 in the future. +#define DRWAV_MAX_SIMD_VECTOR_SIZE 64 /* 64 for AVX-512 in the future. */ #ifdef _MSC_VER #define DRWAV_INLINE __forceinline #else #ifdef __GNUC__ -#define DRWAV_INLINE inline __attribute__((always_inline)) +#define DRWAV_INLINE __inline__ __attribute__((always_inline)) #else -#define DRWAV_INLINE inline +#define DRWAV_INLINE #endif #endif -// I couldn't figure out where SIZE_MAX was defined for VC6. If anybody knows, let me know. -#if defined(_MSC_VER) && _MSC_VER <= 1200 - #if defined(_WIN64) - #define SIZE_MAX ((drwav_uint64)0xFFFFFFFFFFFFFFFF) +#if defined(SIZE_MAX) + #define DRWAV_SIZE_MAX SIZE_MAX +#else + #if defined(_WIN64) || defined(_LP64) || defined(__LP64__) + #define DRWAV_SIZE_MAX ((drwav_uint64)0xFFFFFFFFFFFFFFFF) #else - #define SIZE_MAX 0xFFFFFFFF + #define DRWAV_SIZE_MAX 0xFFFFFFFF #endif #endif -static const drwav_uint8 drwavGUID_W64_RIFF[16] = {0x72,0x69,0x66,0x66, 0x2E,0x91, 0xCF,0x11, 0xA5,0xD6, 0x28,0xDB,0x04,0xC1,0x00,0x00}; // 66666972-912E-11CF-A5D6-28DB04C10000 -static const drwav_uint8 drwavGUID_W64_WAVE[16] = {0x77,0x61,0x76,0x65, 0xF3,0xAC, 0xD3,0x11, 0x8C,0xD1, 0x00,0xC0,0x4F,0x8E,0xDB,0x8A}; // 65766177-ACF3-11D3-8CD1-00C04F8EDB8A -static const drwav_uint8 drwavGUID_W64_JUNK[16] = {0x6A,0x75,0x6E,0x6B, 0xF3,0xAC, 0xD3,0x11, 0x8C,0xD1, 0x00,0xC0,0x4F,0x8E,0xDB,0x8A}; // 6B6E756A-ACF3-11D3-8CD1-00C04F8EDB8A -static const drwav_uint8 drwavGUID_W64_FMT [16] = {0x66,0x6D,0x74,0x20, 0xF3,0xAC, 0xD3,0x11, 0x8C,0xD1, 0x00,0xC0,0x4F,0x8E,0xDB,0x8A}; // 20746D66-ACF3-11D3-8CD1-00C04F8EDB8A -static const drwav_uint8 drwavGUID_W64_FACT[16] = {0x66,0x61,0x63,0x74, 0xF3,0xAC, 0xD3,0x11, 0x8C,0xD1, 0x00,0xC0,0x4F,0x8E,0xDB,0x8A}; // 74636166-ACF3-11D3-8CD1-00C04F8EDB8A -static const drwav_uint8 drwavGUID_W64_DATA[16] = {0x64,0x61,0x74,0x61, 0xF3,0xAC, 0xD3,0x11, 0x8C,0xD1, 0x00,0xC0,0x4F,0x8E,0xDB,0x8A}; // 61746164-ACF3-11D3-8CD1-00C04F8EDB8A +static const drwav_uint8 drwavGUID_W64_RIFF[16] = {0x72,0x69,0x66,0x66, 0x2E,0x91, 0xCF,0x11, 0xA5,0xD6, 0x28,0xDB,0x04,0xC1,0x00,0x00}; /* 66666972-912E-11CF-A5D6-28DB04C10000 */ +static const drwav_uint8 drwavGUID_W64_WAVE[16] = {0x77,0x61,0x76,0x65, 0xF3,0xAC, 0xD3,0x11, 0x8C,0xD1, 0x00,0xC0,0x4F,0x8E,0xDB,0x8A}; /* 65766177-ACF3-11D3-8CD1-00C04F8EDB8A */ +static const drwav_uint8 drwavGUID_W64_JUNK[16] = {0x6A,0x75,0x6E,0x6B, 0xF3,0xAC, 0xD3,0x11, 0x8C,0xD1, 0x00,0xC0,0x4F,0x8E,0xDB,0x8A}; /* 6B6E756A-ACF3-11D3-8CD1-00C04F8EDB8A */ +static const drwav_uint8 drwavGUID_W64_FMT [16] = {0x66,0x6D,0x74,0x20, 0xF3,0xAC, 0xD3,0x11, 0x8C,0xD1, 0x00,0xC0,0x4F,0x8E,0xDB,0x8A}; /* 20746D66-ACF3-11D3-8CD1-00C04F8EDB8A */ +static const drwav_uint8 drwavGUID_W64_FACT[16] = {0x66,0x61,0x63,0x74, 0xF3,0xAC, 0xD3,0x11, 0x8C,0xD1, 0x00,0xC0,0x4F,0x8E,0xDB,0x8A}; /* 74636166-ACF3-11D3-8CD1-00C04F8EDB8A */ +static const drwav_uint8 drwavGUID_W64_DATA[16] = {0x64,0x61,0x74,0x61, 0xF3,0xAC, 0xD3,0x11, 0x8C,0xD1, 0x00,0xC0,0x4F,0x8E,0xDB,0x8A}; /* 61746164-ACF3-11D3-8CD1-00C04F8EDB8A */ +static const drwav_uint8 drwavGUID_W64_SMPL[16] = {0x73,0x6D,0x70,0x6C, 0xF3,0xAC, 0xD3,0x11, 0x8C,0xD1, 0x00,0xC0,0x4F,0x8E,0xDB,0x8A}; /* 6C706D73-ACF3-11D3-8CD1-00C04F8EDB8A */ static DRWAV_INLINE drwav_bool32 drwav__guid_equal(const drwav_uint8 a[16], const drwav_uint8 b[16]) { @@ -787,11 +1003,7 @@ static DRWAV_INLINE int drwav__is_little_endian() static DRWAV_INLINE unsigned short drwav__bytes_to_u16(const unsigned char* data) { - if (drwav__is_little_endian()) { - return (data[0] << 0) | (data[1] << 8); - } else { - return (data[1] << 0) | (data[0] << 8); - } + return (data[0] << 0) | (data[1] << 8); } static DRWAV_INLINE short drwav__bytes_to_s16(const unsigned char* data) @@ -801,29 +1013,20 @@ static DRWAV_INLINE short drwav__bytes_to_s16(const unsigned char* data) static DRWAV_INLINE unsigned int drwav__bytes_to_u32(const unsigned char* data) { - if (drwav__is_little_endian()) { - return (data[0] << 0) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24); - } else { - return (data[3] << 0) | (data[2] << 8) | (data[1] << 16) | (data[0] << 24); - } + return (data[0] << 0) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24); } static DRWAV_INLINE drwav_uint64 drwav__bytes_to_u64(const unsigned char* data) { - if (drwav__is_little_endian()) { - return - ((drwav_uint64)data[0] << 0) | ((drwav_uint64)data[1] << 8) | ((drwav_uint64)data[2] << 16) | ((drwav_uint64)data[3] << 24) | - ((drwav_uint64)data[4] << 32) | ((drwav_uint64)data[5] << 40) | ((drwav_uint64)data[6] << 48) | ((drwav_uint64)data[7] << 56); - } else { - return - ((drwav_uint64)data[7] << 0) | ((drwav_uint64)data[6] << 8) | ((drwav_uint64)data[5] << 16) | ((drwav_uint64)data[4] << 24) | - ((drwav_uint64)data[3] << 32) | ((drwav_uint64)data[2] << 40) | ((drwav_uint64)data[1] << 48) | ((drwav_uint64)data[0] << 56); - } + return + ((drwav_uint64)data[0] << 0) | ((drwav_uint64)data[1] << 8) | ((drwav_uint64)data[2] << 16) | ((drwav_uint64)data[3] << 24) | + ((drwav_uint64)data[4] << 32) | ((drwav_uint64)data[5] << 40) | ((drwav_uint64)data[6] << 48) | ((drwav_uint64)data[7] << 56); } static DRWAV_INLINE void drwav__bytes_to_guid(const unsigned char* data, drwav_uint8* guid) { - for (int i = 0; i < 16; ++i) { + int i; + for (i = 0; i < 16; ++i) { guid[i] = data[i]; } } @@ -836,60 +1039,44 @@ static DRWAV_INLINE drwav_bool32 drwav__is_compressed_format_tag(drwav_uint16 fo formatTag == DR_WAVE_FORMAT_DVI_ADPCM; } - drwav_uint64 drwav_read_s16__msadpcm(drwav* pWav, drwav_uint64 samplesToRead, drwav_int16* pBufferOut); drwav_uint64 drwav_read_s16__ima(drwav* pWav, drwav_uint64 samplesToRead, drwav_int16* pBufferOut); drwav_bool32 drwav_init_write__internal(drwav* pWav, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_bool32 isSequential, drwav_write_proc onWrite, drwav_seek_proc onSeek, void* pUserData); drwav* drwav_open_write__internal(const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_bool32 isSequential, drwav_write_proc onWrite, drwav_seek_proc onSeek, void* pUserData); -typedef struct -{ - union - { - drwav_uint8 fourcc[4]; - drwav_uint8 guid[16]; - } id; - - // The size in bytes of the chunk. - drwav_uint64 sizeInBytes; - - // RIFF = 2 byte alignment. - // W64 = 8 byte alignment. - unsigned int paddingSize; - -} drwav__chunk_header; - -static drwav_bool32 drwav__read_chunk_header(drwav_read_proc onRead, void* pUserData, drwav_container container, drwav_uint64* pRunningBytesReadOut, drwav__chunk_header* pHeaderOut) +static drwav_result drwav__read_chunk_header(drwav_read_proc onRead, void* pUserData, drwav_container container, drwav_uint64* pRunningBytesReadOut, drwav_chunk_header* pHeaderOut) { if (container == drwav_container_riff) { + unsigned char sizeInBytes[4]; + if (onRead(pUserData, pHeaderOut->id.fourcc, 4) != 4) { - return DRWAV_FALSE; + return DRWAV_EOF; } - unsigned char sizeInBytes[4]; if (onRead(pUserData, sizeInBytes, 4) != 4) { - return DRWAV_FALSE; + return DRWAV_INVALID_FILE; } pHeaderOut->sizeInBytes = drwav__bytes_to_u32(sizeInBytes); pHeaderOut->paddingSize = (unsigned int)(pHeaderOut->sizeInBytes % 2); *pRunningBytesReadOut += 8; } else { + unsigned char sizeInBytes[8]; + if (onRead(pUserData, pHeaderOut->id.guid, 16) != 16) { - return DRWAV_FALSE; + return DRWAV_EOF; } - unsigned char sizeInBytes[8]; if (onRead(pUserData, sizeInBytes, 8) != 8) { - return DRWAV_FALSE; + return DRWAV_INVALID_FILE; } - pHeaderOut->sizeInBytes = drwav__bytes_to_u64(sizeInBytes) - 24; // <-- Subtract 24 because w64 includes the size of the header. + pHeaderOut->sizeInBytes = drwav__bytes_to_u64(sizeInBytes) - 24; /* <-- Subtract 24 because w64 includes the size of the header. */ pHeaderOut->paddingSize = (unsigned int)(pHeaderOut->sizeInBytes % 8); *pRunningBytesReadOut += 24; } - return DRWAV_TRUE; + return DRWAV_SUCCESS; } static drwav_bool32 drwav__seek_forward(drwav_seek_proc onSeek, drwav_uint64 offset, void* pUserData) @@ -912,27 +1099,59 @@ static drwav_bool32 drwav__seek_forward(drwav_seek_proc onSeek, drwav_uint64 off return DRWAV_TRUE; } +static drwav_bool32 drwav__seek_from_start(drwav_seek_proc onSeek, drwav_uint64 offset, void* pUserData) +{ + if (offset <= 0x7FFFFFFF) { + return onSeek(pUserData, (int)offset, drwav_seek_origin_start); + } + + /* Larger than 32-bit seek. */ + if (!onSeek(pUserData, 0x7FFFFFFF, drwav_seek_origin_start)) { + return DRWAV_FALSE; + } + offset -= 0x7FFFFFFF; + + for (;;) { + if (offset <= 0x7FFFFFFF) { + return onSeek(pUserData, (int)offset, drwav_seek_origin_current); + } + + if (!onSeek(pUserData, 0x7FFFFFFF, drwav_seek_origin_current)) { + return DRWAV_FALSE; + } + offset -= 0x7FFFFFFF; + } + + /* Should never get here. */ + /*return DRWAV_TRUE; */ +} + static drwav_bool32 drwav__read_fmt(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, drwav_container container, drwav_uint64* pRunningBytesReadOut, drwav_fmt* fmtOut) { - drwav__chunk_header header; - if (!drwav__read_chunk_header(onRead, pUserData, container, pRunningBytesReadOut, &header)) { + drwav_chunk_header header; + unsigned char fmt[16]; + + if (drwav__read_chunk_header(onRead, pUserData, container, pRunningBytesReadOut, &header) != DRWAV_SUCCESS) { return DRWAV_FALSE; } - // Skip non-fmt chunks. - if ((container == drwav_container_riff && !drwav__fourcc_equal(header.id.fourcc, "fmt ")) || (container == drwav_container_w64 && !drwav__guid_equal(header.id.guid, drwavGUID_W64_FMT))) { + /* Skip non-fmt chunks. */ + while ((container == drwav_container_riff && !drwav__fourcc_equal(header.id.fourcc, "fmt ")) || (container == drwav_container_w64 && !drwav__guid_equal(header.id.guid, drwavGUID_W64_FMT))) { if (!drwav__seek_forward(onSeek, header.sizeInBytes + header.paddingSize, pUserData)) { return DRWAV_FALSE; } *pRunningBytesReadOut += header.sizeInBytes + header.paddingSize; - return drwav__read_fmt(onRead, onSeek, pUserData, container, pRunningBytesReadOut, fmtOut); + /* Try the next header. */ + if (drwav__read_chunk_header(onRead, pUserData, container, pRunningBytesReadOut, &header) != DRWAV_SUCCESS) { + return DRWAV_FALSE; + } } - // Validation. + /* Validation. */ if (container == drwav_container_riff) { if (!drwav__fourcc_equal(header.id.fourcc, "fmt ")) { return DRWAV_FALSE; @@ -944,7 +1163,6 @@ static drwav_bool32 drwav__read_fmt(drwav_read_proc onRead, drwav_seek_proc onSe } - unsigned char fmt[16]; if (onRead(pUserData, fmt, sizeof(fmt)) != sizeof(fmt)) { return DRWAV_FALSE; } @@ -964,16 +1182,18 @@ static drwav_bool32 drwav__read_fmt(drwav_read_proc onRead, drwav_seek_proc onSe if (header.sizeInBytes > 16) { unsigned char fmt_cbSize[2]; + int bytesReadSoFar = 0; + if (onRead(pUserData, fmt_cbSize, sizeof(fmt_cbSize)) != sizeof(fmt_cbSize)) { - return DRWAV_FALSE; // Expecting more data. + return DRWAV_FALSE; /* Expecting more data. */ } *pRunningBytesReadOut += sizeof(fmt_cbSize); - int bytesReadSoFar = 18; + bytesReadSoFar = 18; fmtOut->extendedSize = drwav__bytes_to_u16(fmt_cbSize); if (fmtOut->extendedSize > 0) { - // Simple validation. + /* Simple validation. */ if (fmtOut->formatTag == DR_WAVE_FORMAT_EXTENSIBLE) { if (fmtOut->extendedSize != 22) { return DRWAV_FALSE; @@ -983,7 +1203,7 @@ static drwav_bool32 drwav__read_fmt(drwav_read_proc onRead, drwav_seek_proc onSe if (fmtOut->formatTag == DR_WAVE_FORMAT_EXTENSIBLE) { unsigned char fmtext[22]; if (onRead(pUserData, fmtext, fmtOut->extendedSize) != fmtOut->extendedSize) { - return DRWAV_FALSE; // Expecting more data. + return DRWAV_FALSE; /* Expecting more data. */ } fmtOut->validBitsPerSample = drwav__bytes_to_u16(fmtext + 0); @@ -999,7 +1219,7 @@ static drwav_bool32 drwav__read_fmt(drwav_read_proc onRead, drwav_seek_proc onSe bytesReadSoFar += fmtOut->extendedSize; } - // Seek past any leftover bytes. For w64 the leftover will be defined based on the chunk size. + /* Seek past any leftover bytes. For w64 the leftover will be defined based on the chunk size. */ if (!onSeek(pUserData, (int)(header.sizeInBytes - bytesReadSoFar), drwav_seek_origin_current)) { return DRWAV_FALSE; } @@ -1051,13 +1271,18 @@ static drwav_bool32 drwav__on_seek_stdio(void* pUserData, int offset, drwav_seek } drwav_bool32 drwav_init_file(drwav* pWav, const char* filename) +{ + return drwav_init_file_ex(pWav, filename, NULL, NULL, 0); +} + +drwav_bool32 drwav_init_file_ex(drwav* pWav, const char* filename, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags) { FILE* pFile = drwav_fopen(filename, "rb"); if (pFile == NULL) { return DRWAV_FALSE; } - return drwav_init(pWav, drwav__on_read_stdio, drwav__on_seek_stdio, (void*)pFile); + return drwav_init_ex(pWav, drwav__on_read_stdio, drwav__on_seek_stdio, onChunk, (void*)pFile, pChunkUserData, flags); } @@ -1083,12 +1308,20 @@ drwav_bool32 drwav_init_file_write_sequential(drwav* pWav, const char* filename, drwav* drwav_open_file(const char* filename) { - FILE* pFile = drwav_fopen(filename, "rb"); + return drwav_open_file_ex(filename, NULL, NULL, 0); +} + +drwav* drwav_open_file_ex(const char* filename, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags) +{ + FILE* pFile; + drwav* pWav; + + pFile = drwav_fopen(filename, "rb"); if (pFile == NULL) { return DRWAV_FALSE; } - drwav* pWav = drwav_open(drwav__on_read_stdio, drwav__on_seek_stdio, (void*)pFile); + pWav = drwav_open_ex(drwav__on_read_stdio, drwav__on_seek_stdio, onChunk, (void*)pFile, pChunkUserData, flags); if (pWav == NULL) { fclose(pFile); return NULL; @@ -1100,12 +1333,15 @@ drwav* drwav_open_file(const char* filename) drwav* drwav_open_file_write__internal(const char* filename, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_bool32 isSequential) { - FILE* pFile = drwav_fopen(filename, "wb"); + FILE* pFile; + drwav* pWav; + + pFile = drwav_fopen(filename, "wb"); if (pFile == NULL) { return DRWAV_FALSE; } - drwav* pWav = drwav_open_write__internal(pFormat, totalSampleCount, isSequential, drwav__on_write_stdio, drwav__on_seek_stdio, (void*)pFile); + pWav = drwav_open_write__internal(pFormat, totalSampleCount, isSequential, drwav__on_write_stdio, drwav__on_seek_stdio, (void*)pFile); if (pWav == NULL) { fclose(pFile); return NULL; @@ -1123,16 +1359,18 @@ drwav* drwav_open_file_write_sequential(const char* filename, const drwav_data_f { return drwav_open_file_write__internal(filename, pFormat, totalSampleCount, DRWAV_TRUE); } -#endif //DR_WAV_NO_STDIO +#endif /* DR_WAV_NO_STDIO */ static size_t drwav__on_read_memory(void* pUserData, void* pBufferOut, size_t bytesToRead) { drwav__memory_stream* memory = (drwav__memory_stream*)pUserData; + size_t bytesRemaining; + drwav_assert(memory != NULL); drwav_assert(memory->dataSize >= memory->currentReadPos); - size_t bytesRemaining = memory->dataSize - memory->currentReadPos; + bytesRemaining = memory->dataSize - memory->currentReadPos; if (bytesToRead > bytesRemaining) { bytesToRead = bytesRemaining; } @@ -1153,21 +1391,21 @@ static drwav_bool32 drwav__on_seek_memory(void* pUserData, int offset, drwav_see if (origin == drwav_seek_origin_current) { if (offset > 0) { if (memory->currentReadPos + offset > memory->dataSize) { - offset = (int)(memory->dataSize - memory->currentReadPos); // Trying to seek too far forward. + return DRWAV_FALSE; /* Trying to seek too far forward. */ } } else { if (memory->currentReadPos < (size_t)-offset) { - offset = -(int)memory->currentReadPos; // Trying to seek too far backwards. + return DRWAV_FALSE; /* Trying to seek too far backwards. */ } } - // This will never underflow thanks to the clamps above. + /* This will never underflow thanks to the clamps above. */ memory->currentReadPos += offset; } else { if ((drwav_uint32)offset <= memory->dataSize) { memory->currentReadPos = offset; } else { - memory->currentReadPos = memory->dataSize; // Trying to seek too far forward. + return DRWAV_FALSE; /* Trying to seek too far forward. */ } } @@ -1177,20 +1415,23 @@ static drwav_bool32 drwav__on_seek_memory(void* pUserData, int offset, drwav_see static size_t drwav__on_write_memory(void* pUserData, const void* pDataIn, size_t bytesToWrite) { drwav__memory_stream_write* memory = (drwav__memory_stream_write*)pUserData; + size_t bytesRemaining; + drwav_assert(memory != NULL); drwav_assert(memory->dataCapacity >= memory->currentWritePos); - size_t bytesRemaining = memory->dataCapacity - memory->currentWritePos; + bytesRemaining = memory->dataCapacity - memory->currentWritePos; if (bytesRemaining < bytesToWrite) { - // Need to reallocate. + /* Need to reallocate. */ + void* pNewData; size_t newDataCapacity = (memory->dataCapacity == 0) ? 256 : memory->dataCapacity * 2; - // If doubling wasn't enough, just make it the minimum required size to write the data. + /* If doubling wasn't enough, just make it the minimum required size to write the data. */ if ((newDataCapacity - memory->currentWritePos) < bytesToWrite) { newDataCapacity = memory->currentWritePos + bytesToWrite; } - void* pNewData = DRWAV_REALLOC(*memory->ppData, newDataCapacity); + pNewData = DRWAV_REALLOC(*memory->ppData, newDataCapacity); if (pNewData == NULL) { return 0; } @@ -1199,8 +1440,7 @@ static size_t drwav__on_write_memory(void* pUserData, const void* pDataIn, size_ memory->dataCapacity = newDataCapacity; } - drwav_uint8* pDataOut = (drwav_uint8*)(*memory->ppData); - DRWAV_COPY_MEMORY(pDataOut + memory->currentWritePos, pDataIn, bytesToWrite); + DRWAV_COPY_MEMORY(((drwav_uint8*)(*memory->ppData)) + memory->currentWritePos, pDataIn, bytesToWrite); memory->currentWritePos += bytesToWrite; if (memory->dataSize < memory->currentWritePos) { @@ -1220,40 +1460,46 @@ static drwav_bool32 drwav__on_seek_memory_write(void* pUserData, int offset, drw if (origin == drwav_seek_origin_current) { if (offset > 0) { if (memory->currentWritePos + offset > memory->dataSize) { - offset = (int)(memory->dataSize - memory->currentWritePos); // Trying to seek too far forward. + offset = (int)(memory->dataSize - memory->currentWritePos); /* Trying to seek too far forward. */ } } else { if (memory->currentWritePos < (size_t)-offset) { - offset = -(int)memory->currentWritePos; // Trying to seek too far backwards. + offset = -(int)memory->currentWritePos; /* Trying to seek too far backwards. */ } } - // This will never underflow thanks to the clamps above. + /* This will never underflow thanks to the clamps above. */ memory->currentWritePos += offset; } else { if ((drwav_uint32)offset <= memory->dataSize) { memory->currentWritePos = offset; } else { - memory->currentWritePos = memory->dataSize; // Trying to seek too far forward. + memory->currentWritePos = memory->dataSize; /* Trying to seek too far forward. */ } } return DRWAV_TRUE; } -drwav_bool32 drwav_init_memory(drwav* pWav, const void* data, size_t dataSize) +drwav_bool32 drwav_init_memory(drwav* pWav, const void* data, size_t dataSize) +{ + return drwav_init_memory_ex(pWav, data, dataSize, NULL, NULL, 0); +} + +drwav_bool32 drwav_init_memory_ex(drwav* pWav, const void* data, size_t dataSize, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags) { + drwav__memory_stream memoryStream; + if (data == NULL || dataSize == 0) { return DRWAV_FALSE; } - drwav__memory_stream memoryStream; drwav_zero_memory(&memoryStream, sizeof(memoryStream)); memoryStream.data = (const unsigned char*)data; memoryStream.dataSize = dataSize; memoryStream.currentReadPos = 0; - if (!drwav_init(pWav, drwav__on_read_memory, drwav__on_seek_memory, (void*)&memoryStream)) { + if (!drwav_init_ex(pWav, drwav__on_read_memory, drwav__on_seek_memory, onChunk, (void*)&memoryStream, pChunkUserData, flags)) { return DRWAV_FALSE; } @@ -1265,14 +1511,15 @@ drwav_bool32 drwav_init_memory(drwav* pWav, const void* data, size_t dataSize) drwav_bool32 drwav_init_memory_write__internal(drwav* pWav, void** ppData, size_t* pDataSize, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_bool32 isSequential) { + drwav__memory_stream_write memoryStreamWrite; + if (ppData == NULL) { return DRWAV_FALSE; } - *ppData = NULL; // Important because we're using realloc()! + *ppData = NULL; /* Important because we're using realloc()! */ *pDataSize = 0; - drwav__memory_stream_write memoryStreamWrite; drwav_zero_memory(&memoryStreamWrite, sizeof(memoryStreamWrite)); memoryStreamWrite.ppData = ppData; memoryStreamWrite.pDataSize = pDataSize; @@ -1302,17 +1549,24 @@ drwav_bool32 drwav_init_memory_write_sequential(drwav* pWav, void** ppData, size drwav* drwav_open_memory(const void* data, size_t dataSize) { + return drwav_open_memory_ex(data, dataSize, NULL, NULL, 0); +} + +drwav* drwav_open_memory_ex(const void* data, size_t dataSize, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags) +{ + drwav__memory_stream memoryStream; + drwav* pWav; + if (data == NULL || dataSize == 0) { return NULL; } - drwav__memory_stream memoryStream; drwav_zero_memory(&memoryStream, sizeof(memoryStream)); memoryStream.data = (const unsigned char*)data; memoryStream.dataSize = dataSize; memoryStream.currentReadPos = 0; - drwav* pWav = drwav_open(drwav__on_read_memory, drwav__on_seek_memory, (void*)&memoryStream); + pWav = drwav_open_ex(drwav__on_read_memory, drwav__on_seek_memory, onChunk, (void*)&memoryStream, pChunkUserData, flags); if (pWav == NULL) { return NULL; } @@ -1325,14 +1579,16 @@ drwav* drwav_open_memory(const void* data, size_t dataSize) drwav* drwav_open_memory_write__internal(void** ppData, size_t* pDataSize, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_bool32 isSequential) { + drwav__memory_stream_write memoryStreamWrite; + drwav* pWav; + if (ppData == NULL) { return NULL; } - *ppData = NULL; // Important because we're using realloc()! + *ppData = NULL; /* Important because we're using realloc()! */ *pDataSize = 0; - drwav__memory_stream_write memoryStreamWrite; drwav_zero_memory(&memoryStreamWrite, sizeof(memoryStreamWrite)); memoryStreamWrite.ppData = ppData; memoryStreamWrite.pDataSize = pDataSize; @@ -1340,7 +1596,7 @@ drwav* drwav_open_memory_write__internal(void** ppData, size_t* pDataSize, const memoryStreamWrite.dataCapacity = 0; memoryStreamWrite.currentWritePos = 0; - drwav* pWav = drwav_open_write__internal(pFormat, totalSampleCount, isSequential, drwav__on_write_memory, drwav__on_seek_memory_write, (void*)&memoryStreamWrite); + pWav = drwav_open_write__internal(pFormat, totalSampleCount, isSequential, drwav__on_write_memory, drwav__on_seek_memory_write, (void*)&memoryStreamWrite); if (pWav == NULL) { return NULL; } @@ -1361,143 +1617,274 @@ drwav* drwav_open_memory_write_sequential(void** ppData, size_t* pDataSize, cons } +size_t drwav__on_read(drwav_read_proc onRead, void* pUserData, void* pBufferOut, size_t bytesToRead, drwav_uint64* pCursor) +{ + size_t bytesRead; + + drwav_assert(onRead != NULL); + drwav_assert(pCursor != NULL); + + bytesRead = onRead(pUserData, pBufferOut, bytesToRead); + *pCursor += bytesRead; + return bytesRead; +} + +drwav_bool32 drwav__on_seek(drwav_seek_proc onSeek, void* pUserData, int offset, drwav_seek_origin origin, drwav_uint64* pCursor) +{ + drwav_assert(onSeek != NULL); + drwav_assert(pCursor != NULL); + + if (!onSeek(pUserData, offset, origin)) { + return DRWAV_FALSE; + } + + if (origin == drwav_seek_origin_start) { + *pCursor = offset; + } else { + *pCursor += offset; + } + + return DRWAV_TRUE; +} + + +static drwav_uint32 drwav_get_bytes_per_sample(drwav* pWav) +{ + /* + The number of bytes per sample is based on the bits per sample or the block align. We prioritize floor(bitsPerSample/8), but if + this is zero or the bits per sample is not a multiple of 8 we need to fall back to the block align. + */ + drwav_uint32 bytesPerSample = pWav->bitsPerSample >> 3; + if (bytesPerSample == 0 || (pWav->bitsPerSample & 0x7) != 0) { + bytesPerSample = pWav->fmt.blockAlign/pWav->fmt.channels; + } + + return bytesPerSample; +} + +static drwav_uint32 drwav_get_bytes_per_pcm_frame(drwav* pWav) +{ + /* + The number of bytes per frame is based on the bits per sample or the block align. We prioritize floor(bitsPerSample*channels/8), but if + this is zero or the bits per frame is not a multiple of 8 we need to fall back to the block align. + */ + drwav_uint32 bitsPerFrame = pWav->bitsPerSample * pWav->fmt.channels; + drwav_uint32 bytesPerFrame = bitsPerFrame >> 3; + if (bytesPerFrame == 0 || (bitsPerFrame & 0x7) != 0) { + bytesPerFrame = pWav->fmt.blockAlign; + } + + return bytesPerFrame; +} + + drwav_bool32 drwav_init(drwav* pWav, drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData) { + return drwav_init_ex(pWav, onRead, onSeek, NULL, pUserData, NULL, 0); +} + +drwav_bool32 drwav_init_ex(drwav* pWav, drwav_read_proc onRead, drwav_seek_proc onSeek, drwav_chunk_proc onChunk, void* pReadSeekUserData, void* pChunkUserData, drwav_uint32 flags) +{ + drwav_uint64 cursor; /* <-- Keeps track of the byte position so we can seek to specific locations. */ + drwav_bool32 sequential; + unsigned char riff[4]; + drwav_fmt fmt; + unsigned short translatedFormatTag; + drwav_uint64 sampleCountFromFactChunk; + drwav_bool32 foundDataChunk; + drwav_uint64 dataChunkSize; + drwav_uint64 chunkSize; + if (onRead == NULL || onSeek == NULL) { return DRWAV_FALSE; } - drwav_zero_memory(pWav, sizeof(*pWav)); + cursor = 0; + sequential = (flags & DRWAV_SEQUENTIAL) != 0; + drwav_zero_memory(pWav, sizeof(*pWav)); + pWav->onRead = onRead; + pWav->onSeek = onSeek; + pWav->pUserData = pReadSeekUserData; - // The first 4 bytes should be the RIFF identifier. - unsigned char riff[4]; - if (onRead(pUserData, riff, sizeof(riff)) != sizeof(riff)) { - return DRWAV_FALSE; // Failed to read data. + /* The first 4 bytes should be the RIFF identifier. */ + if (drwav__on_read(onRead, pReadSeekUserData, riff, sizeof(riff), &cursor) != sizeof(riff)) { + return DRWAV_FALSE; } - // The first 4 bytes can be used to identify the container. For RIFF files it will start with "RIFF" and for - // w64 it will start with "riff". + /* + The first 4 bytes can be used to identify the container. For RIFF files it will start with "RIFF" and for + w64 it will start with "riff". + */ if (drwav__fourcc_equal(riff, "RIFF")) { pWav->container = drwav_container_riff; } else if (drwav__fourcc_equal(riff, "riff")) { + int i; + drwav_uint8 riff2[12]; + pWav->container = drwav_container_w64; - // Check the rest of the GUID for validity. - drwav_uint8 riff2[12]; - if (onRead(pUserData, riff2, sizeof(riff2)) != sizeof(riff2)) { + /* Check the rest of the GUID for validity. */ + if (drwav__on_read(onRead, pReadSeekUserData, riff2, sizeof(riff2), &cursor) != sizeof(riff2)) { return DRWAV_FALSE; } - for (int i = 0; i < 12; ++i) { + for (i = 0; i < 12; ++i) { if (riff2[i] != drwavGUID_W64_RIFF[i+4]) { return DRWAV_FALSE; } } } else { - return DRWAV_FALSE; // Unknown or unsupported container. + return DRWAV_FALSE; /* Unknown or unsupported container. */ } if (pWav->container == drwav_container_riff) { - // RIFF/WAVE unsigned char chunkSizeBytes[4]; - if (onRead(pUserData, chunkSizeBytes, sizeof(chunkSizeBytes)) != sizeof(chunkSizeBytes)) { + unsigned char wave[4]; + + /* RIFF/WAVE */ + if (drwav__on_read(onRead, pReadSeekUserData, chunkSizeBytes, sizeof(chunkSizeBytes), &cursor) != sizeof(chunkSizeBytes)) { return DRWAV_FALSE; } - unsigned int chunkSize = drwav__bytes_to_u32(chunkSizeBytes); - if (chunkSize < 36) { - return DRWAV_FALSE; // Chunk size should always be at least 36 bytes. + if (drwav__bytes_to_u32(chunkSizeBytes) < 36) { + return DRWAV_FALSE; /* Chunk size should always be at least 36 bytes. */ } - unsigned char wave[4]; - if (onRead(pUserData, wave, sizeof(wave)) != sizeof(wave)) { + if (drwav__on_read(onRead, pReadSeekUserData, wave, sizeof(wave), &cursor) != sizeof(wave)) { return DRWAV_FALSE; } if (!drwav__fourcc_equal(wave, "WAVE")) { - return DRWAV_FALSE; // Expecting "WAVE". + return DRWAV_FALSE; /* Expecting "WAVE". */ } - - pWav->dataChunkDataPos = 4 + sizeof(chunkSizeBytes) + sizeof(wave); } else { - // W64 - unsigned char chunkSize[8]; - if (onRead(pUserData, chunkSize, sizeof(chunkSize)) != sizeof(chunkSize)) { + unsigned char chunkSizeBytes[8]; + drwav_uint8 wave[16]; + + /* W64 */ + if (drwav__on_read(onRead, pReadSeekUserData, chunkSizeBytes, sizeof(chunkSizeBytes), &cursor) != sizeof(chunkSizeBytes)) { return DRWAV_FALSE; } - if (drwav__bytes_to_u64(chunkSize) < 80) { + if (drwav__bytes_to_u64(chunkSizeBytes) < 80) { return DRWAV_FALSE; } - drwav_uint8 wave[16]; - if (onRead(pUserData, wave, sizeof(wave)) != sizeof(wave)) { + if (drwav__on_read(onRead, pReadSeekUserData, wave, sizeof(wave), &cursor) != sizeof(wave)) { return DRWAV_FALSE; } if (!drwav__guid_equal(wave, drwavGUID_W64_WAVE)) { return DRWAV_FALSE; } - - pWav->dataChunkDataPos = 16 + sizeof(chunkSize) + sizeof(wave); } - // The next bytes should be the "fmt " chunk. - drwav_fmt fmt; - if (!drwav__read_fmt(onRead, onSeek, pUserData, pWav->container, &pWav->dataChunkDataPos, &fmt)) { - return DRWAV_FALSE; // Failed to read the "fmt " chunk. + /* The next bytes should be the "fmt " chunk. */ + if (!drwav__read_fmt(onRead, onSeek, pReadSeekUserData, pWav->container, &cursor, &fmt)) { + return DRWAV_FALSE; /* Failed to read the "fmt " chunk. */ } - // Basic validation. + /* Basic validation. */ if (fmt.sampleRate == 0 || fmt.channels == 0 || fmt.bitsPerSample == 0 || fmt.blockAlign == 0) { - return DRWAV_FALSE; // Invalid channel count. Probably an invalid WAV file. + return DRWAV_FALSE; /* Invalid channel count. Probably an invalid WAV file. */ } - // Translate the internal format. - unsigned short translatedFormatTag = fmt.formatTag; + /* Translate the internal format. */ + translatedFormatTag = fmt.formatTag; if (translatedFormatTag == DR_WAVE_FORMAT_EXTENSIBLE) { translatedFormatTag = drwav__bytes_to_u16(fmt.subFormat + 0); } - drwav_uint64 sampleCountFromFactChunk = 0; - // The next chunk we care about is the "data" chunk. This is not necessarily the next chunk so we'll need to loop. - drwav_uint64 dataSize; + sampleCountFromFactChunk = 0; + + /* + We need to enumerate over each chunk for two reasons: + 1) The "data" chunk may not be the next one + 2) We may want to report each chunk back to the client + + In order to correctly report each chunk back to the client we will need to keep looping until the end of the file. + */ + foundDataChunk = DRWAV_FALSE; + dataChunkSize = 0; + + /* The next chunk we care about is the "data" chunk. This is not necessarily the next chunk so we'll need to loop. */ + chunkSize = 0; for (;;) { - drwav__chunk_header header; - if (!drwav__read_chunk_header(onRead, pUserData, pWav->container, &pWav->dataChunkDataPos, &header)) { - return DRWAV_FALSE; + drwav_chunk_header header; + drwav_result result = drwav__read_chunk_header(onRead, pReadSeekUserData, pWav->container, &cursor, &header); + if (result != DRWAV_SUCCESS) { + if (!foundDataChunk) { + return DRWAV_FALSE; + } else { + break; /* Probably at the end of the file. Get out of the loop. */ + } + } + + /* Tell the client about this chunk. */ + if (!sequential && onChunk != NULL) { + drwav_uint64 callbackBytesRead = onChunk(pChunkUserData, onRead, onSeek, pReadSeekUserData, &header); + + /* + dr_wav may need to read the contents of the chunk, so we now need to seek back to the position before + we called the callback. + */ + if (callbackBytesRead > 0) { + if (!drwav__seek_from_start(onSeek, cursor, pReadSeekUserData)) { + return DRWAV_FALSE; + } + } + } + + + if (!foundDataChunk) { + pWav->dataChunkDataPos = cursor; } - dataSize = header.sizeInBytes; + chunkSize = header.sizeInBytes; if (pWav->container == drwav_container_riff) { if (drwav__fourcc_equal(header.id.fourcc, "data")) { - break; + foundDataChunk = DRWAV_TRUE; + dataChunkSize = chunkSize; } } else { if (drwav__guid_equal(header.id.guid, drwavGUID_W64_DATA)) { - break; + foundDataChunk = DRWAV_TRUE; + dataChunkSize = chunkSize; } } - // Optional. Get the total sample count from the FACT chunk. This is useful for compressed formats. + /* + If at this point we have found the data chunk and we're running in sequential mode, we need to break out of this loop. The reason for + this is that we would otherwise require a backwards seek which sequential mode forbids. + */ + if (foundDataChunk && sequential) { + break; + } + + /* Optional. Get the total sample count from the FACT chunk. This is useful for compressed formats. */ if (pWav->container == drwav_container_riff) { if (drwav__fourcc_equal(header.id.fourcc, "fact")) { drwav_uint32 sampleCount; - if (onRead(pUserData, &sampleCount, 4) != 4) { + if (drwav__on_read(onRead, pReadSeekUserData, &sampleCount, 4, &cursor) != 4) { return DRWAV_FALSE; } - pWav->dataChunkDataPos += 4; - dataSize -= 4; + chunkSize -= 4; + + if (!foundDataChunk) { + pWav->dataChunkDataPos = cursor; + } - // The sample count in the "fact" chunk is either unreliable, or I'm not understanding it properly. For now I am only enabling this - // for Microsoft ADPCM formats. + /* + The sample count in the "fact" chunk is either unreliable, or I'm not understanding it properly. For now I am only enabling this + for Microsoft ADPCM formats. + */ if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM) { sampleCountFromFactChunk = sampleCount; } else { @@ -1506,62 +1893,120 @@ drwav_bool32 drwav_init(drwav* pWav, drwav_read_proc onRead, drwav_seek_proc onS } } else { if (drwav__guid_equal(header.id.guid, drwavGUID_W64_FACT)) { - if (onRead(pUserData, &sampleCountFromFactChunk, 8) != 8) { + if (drwav__on_read(onRead, pReadSeekUserData, &sampleCountFromFactChunk, 8, &cursor) != 8) { return DRWAV_FALSE; } - pWav->dataChunkDataPos += 8; - dataSize -= 8; + chunkSize -= 8; + + if (!foundDataChunk) { + pWav->dataChunkDataPos = cursor; + } + } + } + + /* "smpl" chunk. */ + if (pWav->container == drwav_container_riff) { + if (drwav__fourcc_equal(header.id.fourcc, "smpl")) { + unsigned char smplHeaderData[36]; /* 36 = size of the smpl header section, not including the loop data. */ + if (chunkSize >= sizeof(smplHeaderData)) { + drwav_uint64 bytesJustRead = drwav__on_read(onRead, pReadSeekUserData, smplHeaderData, sizeof(smplHeaderData), &cursor); + chunkSize -= bytesJustRead; + + if (bytesJustRead == sizeof(smplHeaderData)) { + drwav_uint32 iLoop; + + pWav->smpl.manufacturer = drwav__bytes_to_u32(smplHeaderData+0); + pWav->smpl.product = drwav__bytes_to_u32(smplHeaderData+4); + pWav->smpl.samplePeriod = drwav__bytes_to_u32(smplHeaderData+8); + pWav->smpl.midiUnityNotes = drwav__bytes_to_u32(smplHeaderData+12); + pWav->smpl.midiPitchFraction = drwav__bytes_to_u32(smplHeaderData+16); + pWav->smpl.smpteFormat = drwav__bytes_to_u32(smplHeaderData+20); + pWav->smpl.smpteOffset = drwav__bytes_to_u32(smplHeaderData+24); + pWav->smpl.numSampleLoops = drwav__bytes_to_u32(smplHeaderData+28); + pWav->smpl.samplerData = drwav__bytes_to_u32(smplHeaderData+32); + + for (iLoop = 0; iLoop < pWav->smpl.numSampleLoops && iLoop < drwav_countof(pWav->smpl.loops); ++iLoop) { + unsigned char smplLoopData[24]; /* 24 = size of a loop section in the smpl chunk. */ + bytesJustRead = drwav__on_read(onRead, pReadSeekUserData, smplLoopData, sizeof(smplLoopData), &cursor); + chunkSize -= bytesJustRead; + + if (bytesJustRead == sizeof(smplLoopData)) { + pWav->smpl.loops[iLoop].cuePointId = drwav__bytes_to_u32(smplLoopData+0); + pWav->smpl.loops[iLoop].type = drwav__bytes_to_u32(smplLoopData+4); + pWav->smpl.loops[iLoop].start = drwav__bytes_to_u32(smplLoopData+8); + pWav->smpl.loops[iLoop].end = drwav__bytes_to_u32(smplLoopData+12); + pWav->smpl.loops[iLoop].fraction = drwav__bytes_to_u32(smplLoopData+16); + pWav->smpl.loops[iLoop].playCount = drwav__bytes_to_u32(smplLoopData+20); + } else { + break; /* Break from the smpl loop for loop. */ + } + } + } + } else { + /* Looks like invalid data. Ignore the chunk. */ + } + } + } else { + if (drwav__guid_equal(header.id.guid, drwavGUID_W64_SMPL)) { + /* + This path will be hit when a W64 WAV file contains a smpl chunk. I don't have a sample file to test this path, so a contribution + is welcome to add support for this. + */ } } - // If we get here it means we didn't find the "data" chunk. Seek past it. + /* Make sure we seek past the padding. */ + chunkSize += header.paddingSize; + if (!drwav__seek_forward(onSeek, chunkSize, pReadSeekUserData)) { + break; + } + cursor += chunkSize; + + if (!foundDataChunk) { + pWav->dataChunkDataPos = cursor; + } + } + + /* If we haven't found a data chunk, return an error. */ + if (!foundDataChunk) { + return DRWAV_FALSE; + } - // Make sure we seek past the padding. - dataSize += header.paddingSize; - drwav__seek_forward(onSeek, dataSize, pUserData); - pWav->dataChunkDataPos += dataSize; + /* We may have moved passed the data chunk. If so we need to move back. If running in sequential mode we can assume we are already sitting on the data chunk. */ + if (!sequential) { + if (!drwav__seek_from_start(onSeek, pWav->dataChunkDataPos, pReadSeekUserData)) { + return DRWAV_FALSE; + } + cursor = pWav->dataChunkDataPos; } + - // At this point we should be sitting on the first byte of the raw audio data. + /* At this point we should be sitting on the first byte of the raw audio data. */ - pWav->onRead = onRead; - pWav->onSeek = onSeek; - pWav->pUserData = pUserData; pWav->fmt = fmt; pWav->sampleRate = fmt.sampleRate; pWav->channels = fmt.channels; pWav->bitsPerSample = fmt.bitsPerSample; - pWav->bytesPerSample = fmt.blockAlign / fmt.channels; - pWav->bytesRemaining = dataSize; + pWav->bytesRemaining = dataChunkSize; pWav->translatedFormatTag = translatedFormatTag; - pWav->dataChunkDataSize = dataSize; - - // The bytes per sample should never be 0 at this point. This would indicate an invalid WAV file. - if (pWav->bytesPerSample == 0) { - return DRWAV_FALSE; - } + pWav->dataChunkDataSize = dataChunkSize; if (sampleCountFromFactChunk != 0) { - pWav->totalSampleCount = sampleCountFromFactChunk * fmt.channels; + pWav->totalPCMFrameCount = sampleCountFromFactChunk; } else { - pWav->totalSampleCount = dataSize / pWav->bytesPerSample; + pWav->totalPCMFrameCount = dataChunkSize / drwav_get_bytes_per_pcm_frame(pWav); if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM) { - drwav_uint64 blockCount = dataSize / fmt.blockAlign; - pWav->totalSampleCount = (blockCount * (fmt.blockAlign - (6*pWav->channels))) * 2; // x2 because two samples per byte. + drwav_uint64 blockCount = dataChunkSize / fmt.blockAlign; + pWav->totalPCMFrameCount = (((blockCount * (fmt.blockAlign - (6*pWav->channels))) * 2)) / fmt.channels; /* x2 because two samples per byte. */ } if (pWav->translatedFormatTag == DR_WAVE_FORMAT_DVI_ADPCM) { - drwav_uint64 blockCount = dataSize / fmt.blockAlign; - pWav->totalSampleCount = ((blockCount * (fmt.blockAlign - (4*pWav->channels))) * 2) + (blockCount * pWav->channels); + drwav_uint64 blockCount = dataChunkSize / fmt.blockAlign; + pWav->totalPCMFrameCount = (((blockCount * (fmt.blockAlign - (4*pWav->channels))) * 2) + (blockCount * pWav->channels)) / fmt.channels; } } - // The way we calculate the bytes per sample does not make sense for compressed formats so we just set it to 0. - if (drwav__is_compressed_format_tag(pWav->translatedFormatTag)) { - pWav->bytesPerSample = 0; - } - - // Some formats only support a certain number of channels. + /* Some formats only support a certain number of channels. */ if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM || pWav->translatedFormatTag == DR_WAVE_FORMAT_DVI_ADPCM) { if (pWav->channels > 2) { return DRWAV_FALSE; @@ -1569,22 +2014,26 @@ drwav_bool32 drwav_init(drwav* pWav, drwav_read_proc onRead, drwav_seek_proc onS } #ifdef DR_WAV_LIBSNDFILE_COMPAT - // I use libsndfile as a benchmark for testing, however in the version I'm using (from the Windows installer on the libsndfile website), - // it appears the total sample count libsndfile uses for MS-ADPCM is incorrect. It would seem they are computing the total sample count - // from the number of blocks, however this results in the inclusion of extra silent samples at the end of the last block. The correct - // way to know the total sample count is to inspect the "fact" chunk, which should always be present for compressed formats, and should - // always include the sample count. This little block of code below is only used to emulate the libsndfile logic so I can properly run my - // correctness tests against libsndfile, and is disabled by default. + /* + I use libsndfile as a benchmark for testing, however in the version I'm using (from the Windows installer on the libsndfile website), + it appears the total sample count libsndfile uses for MS-ADPCM is incorrect. It would seem they are computing the total sample count + from the number of blocks, however this results in the inclusion of extra silent samples at the end of the last block. The correct + way to know the total sample count is to inspect the "fact" chunk, which should always be present for compressed formats, and should + always include the sample count. This little block of code below is only used to emulate the libsndfile logic so I can properly run my + correctness tests against libsndfile, and is disabled by default. + */ if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM) { - drwav_uint64 blockCount = dataSize / fmt.blockAlign; - pWav->totalSampleCount = (blockCount * (fmt.blockAlign - (6*pWav->channels))) * 2; // x2 because two samples per byte. + drwav_uint64 blockCount = dataChunkSize / fmt.blockAlign; + pWav->totalPCMFrameCount = (((blockCount * (fmt.blockAlign - (6*pWav->channels))) * 2)) / fmt.channels; /* x2 because two samples per byte. */ } if (pWav->translatedFormatTag == DR_WAVE_FORMAT_DVI_ADPCM) { - drwav_uint64 blockCount = dataSize / fmt.blockAlign; - pWav->totalSampleCount = ((blockCount * (fmt.blockAlign - (4*pWav->channels))) * 2) + (blockCount * pWav->channels); + drwav_uint64 blockCount = dataChunkSize / fmt.blockAlign; + pWav->totalPCMFrameCount = (((blockCount * (fmt.blockAlign - (4*pWav->channels))) * 2) + (blockCount * pWav->channels)) / fmt.channels; } #endif + pWav->totalSampleCount = pWav->totalPCMFrameCount * pWav->channels; + return DRWAV_TRUE; } @@ -1609,17 +2058,21 @@ drwav_uint32 drwav_data_chunk_size_riff(drwav_uint64 dataChunkSize) drwav_uint64 drwav_riff_chunk_size_w64(drwav_uint64 dataChunkSize) { - return 80 + 24 + dataChunkSize; // +24 because W64 includes the size of the GUID and size fields. + return 80 + 24 + dataChunkSize; /* +24 because W64 includes the size of the GUID and size fields. */ } drwav_uint64 drwav_data_chunk_size_w64(drwav_uint64 dataChunkSize) { - return 24 + dataChunkSize; // +24 because W64 includes the size of the GUID and size fields. + return 24 + dataChunkSize; /* +24 because W64 includes the size of the GUID and size fields. */ } drwav_bool32 drwav_init_write__internal(drwav* pWav, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_bool32 isSequential, drwav_write_proc onWrite, drwav_seek_proc onSeek, void* pUserData) { + size_t runningPos = 0; + drwav_uint64 initialDataChunkSize = 0; + drwav_uint64 chunkSizeFMT; + if (pWav == NULL) { return DRWAV_FALSE; } @@ -1629,11 +2082,11 @@ drwav_bool32 drwav_init_write__internal(drwav* pWav, const drwav_data_format* pF } if (!isSequential && onSeek == NULL) { - return DRWAV_FALSE; // <-- onSeek is required when in non-sequential mode. + return DRWAV_FALSE; /* <-- onSeek is required when in non-sequential mode. */ } - // Not currently supporting compressed formats. Will need to add support for the "fact" chunk before we enable this. + /* Not currently supporting compressed formats. Will need to add support for the "fact" chunk before we enable this. */ if (pFormat->format == DR_WAVE_FORMAT_EXTENSIBLE) { return DRWAV_FALSE; } @@ -1655,21 +2108,21 @@ drwav_bool32 drwav_init_write__internal(drwav* pWav, const drwav_data_format* pF pWav->fmt.extendedSize = 0; pWav->isSequentialWrite = isSequential; - - size_t runningPos = 0; - - // The initial values for the "RIFF" and "data" chunks depends on whether or not we are initializing in sequential mode or not. In - // sequential mode we set this to its final values straight away since they can be calculated from the total sample count. In non- - // sequential mode we initialize it all to zero and fill it out in drwav_uninit() using a backwards seek. - drwav_uint64 initialDataChunkSize = 0; + /* + The initial values for the "RIFF" and "data" chunks depends on whether or not we are initializing in sequential mode or not. In + sequential mode we set this to its final values straight away since they can be calculated from the total sample count. In non- + sequential mode we initialize it all to zero and fill it out in drwav_uninit() using a backwards seek. + */ if (isSequential) { initialDataChunkSize = (totalSampleCount * pWav->fmt.bitsPerSample) / 8; - // The RIFF container has a limit on the number of samples. drwav is not allowing this. There's no practical limits for Wave64 - // so for the sake of simplicity I'm not doing any validation for that. + /* + The RIFF container has a limit on the number of samples. drwav is not allowing this. There's no practical limits for Wave64 + so for the sake of simplicity I'm not doing any validation for that. + */ if (pFormat->container == drwav_container_riff) { if (initialDataChunkSize > (0xFFFFFFFF - 36)) { - return DRWAV_FALSE; // Not enough room to store every sample. + return DRWAV_FALSE; /* Not enough room to store every sample. */ } } } @@ -1677,21 +2130,20 @@ drwav_bool32 drwav_init_write__internal(drwav* pWav, const drwav_data_format* pF pWav->dataChunkDataSizeTargetWrite = initialDataChunkSize; - // "RIFF" chunk. + /* "RIFF" chunk. */ if (pFormat->container == drwav_container_riff) { - drwav_uint32 chunkSizeRIFF = 36 + (drwav_uint32)initialDataChunkSize; // +36 = "RIFF"+[RIFF Chunk Size]+"WAVE" + [sizeof "fmt " chunk] + drwav_uint32 chunkSizeRIFF = 36 + (drwav_uint32)initialDataChunkSize; /* +36 = "RIFF"+[RIFF Chunk Size]+"WAVE" + [sizeof "fmt " chunk] */ runningPos += pWav->onWrite(pUserData, "RIFF", 4); runningPos += pWav->onWrite(pUserData, &chunkSizeRIFF, 4); runningPos += pWav->onWrite(pUserData, "WAVE", 4); } else { - drwav_uint64 chunkSizeRIFF = 80 + 24 + initialDataChunkSize; // +24 because W64 includes the size of the GUID and size fields. + drwav_uint64 chunkSizeRIFF = 80 + 24 + initialDataChunkSize; /* +24 because W64 includes the size of the GUID and size fields. */ runningPos += pWav->onWrite(pUserData, drwavGUID_W64_RIFF, 16); runningPos += pWav->onWrite(pUserData, &chunkSizeRIFF, 8); runningPos += pWav->onWrite(pUserData, drwavGUID_W64_WAVE, 16); } - // "fmt " chunk. - drwav_uint64 chunkSizeFMT; + /* "fmt " chunk. */ if (pFormat->container == drwav_container_riff) { chunkSizeFMT = 16; runningPos += pWav->onWrite(pUserData, "fmt ", 4); @@ -1711,19 +2163,19 @@ drwav_bool32 drwav_init_write__internal(drwav* pWav, const drwav_data_format* pF pWav->dataChunkDataPos = runningPos; - // "data" chunk. + /* "data" chunk. */ if (pFormat->container == drwav_container_riff) { drwav_uint32 chunkSizeDATA = (drwav_uint32)initialDataChunkSize; runningPos += pWav->onWrite(pUserData, "data", 4); runningPos += pWav->onWrite(pUserData, &chunkSizeDATA, 4); } else { - drwav_uint64 chunkSizeDATA = 24 + initialDataChunkSize; // +24 because W64 includes the size of the GUID and size fields. + drwav_uint64 chunkSizeDATA = 24 + initialDataChunkSize; /* +24 because W64 includes the size of the GUID and size fields. */ runningPos += pWav->onWrite(pUserData, drwavGUID_W64_DATA, 16); runningPos += pWav->onWrite(pUserData, &chunkSizeDATA, 8); } - // Simple validation. + /* Simple validation. */ if (pFormat->container == drwav_container_riff) { if (runningPos != 20 + chunkSizeFMT + 8) { return DRWAV_FALSE; @@ -1736,12 +2188,11 @@ drwav_bool32 drwav_init_write__internal(drwav* pWav, const drwav_data_format* pF - // Set some properties for the client's convenience. + /* Set some properties for the client's convenience. */ pWav->container = pFormat->container; pWav->channels = (drwav_uint16)pFormat->channels; pWav->sampleRate = pFormat->sampleRate; pWav->bitsPerSample = (drwav_uint16)pFormat->bitsPerSample; - pWav->bytesPerSample = (drwav_uint16)(pFormat->bitsPerSample >> 3); pWav->translatedFormatTag = (drwav_uint16)pFormat->format; return DRWAV_TRUE; @@ -1750,12 +2201,12 @@ drwav_bool32 drwav_init_write__internal(drwav* pWav, const drwav_data_format* pF drwav_bool32 drwav_init_write(drwav* pWav, const drwav_data_format* pFormat, drwav_write_proc onWrite, drwav_seek_proc onSeek, void* pUserData) { - return drwav_init_write__internal(pWav, pFormat, 0, DRWAV_FALSE, onWrite, onSeek, pUserData); // DRWAV_FALSE = Not Sequential + return drwav_init_write__internal(pWav, pFormat, 0, DRWAV_FALSE, onWrite, onSeek, pUserData); /* DRWAV_FALSE = Not Sequential */ } drwav_bool32 drwav_init_write_sequential(drwav* pWav, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_write_proc onWrite, void* pUserData) { - return drwav_init_write__internal(pWav, pFormat, totalSampleCount, DRWAV_TRUE, onWrite, NULL, pUserData); // DRWAV_TRUE = Sequential + return drwav_init_write__internal(pWav, pFormat, totalSampleCount, DRWAV_TRUE, onWrite, NULL, pUserData); /* DRWAV_TRUE = Sequential */ } void drwav_uninit(drwav* pWav) @@ -1764,17 +2215,20 @@ void drwav_uninit(drwav* pWav) return; } - // If the drwav object was opened in write mode we'll need to finalize a few things: - // - Make sure the "data" chunk is aligned to 16-bits for RIFF containers, or 64 bits for W64 containers. - // - Set the size of the "data" chunk. + /* + If the drwav object was opened in write mode we'll need to finalize a few things: + - Make sure the "data" chunk is aligned to 16-bits for RIFF containers, or 64 bits for W64 containers. + - Set the size of the "data" chunk. + */ if (pWav->onWrite != NULL) { - // Validation for sequential mode. + drwav_uint32 paddingSize = 0; + + /* Validation for sequential mode. */ if (pWav->isSequentialWrite) { drwav_assert(pWav->dataChunkDataSize == pWav->dataChunkDataSizeTargetWrite); } - // Padding. Do not adjust pWav->dataChunkDataSize - this should not include the padding. - drwav_uint32 paddingSize = 0; + /* Padding. Do not adjust pWav->dataChunkDataSize - this should not include the padding. */ if (pWav->container == drwav_container_riff) { paddingSize = (drwav_uint32)(pWav->dataChunkDataSize % 2); } else { @@ -1786,30 +2240,31 @@ void drwav_uninit(drwav* pWav) pWav->onWrite(pWav->pUserData, &paddingData, paddingSize); } - - // Chunk sizes. When using sequential mode, these will have been filled in at initialization time. We only need - // to do this when using non-sequential mode. + /* + Chunk sizes. When using sequential mode, these will have been filled in at initialization time. We only need + to do this when using non-sequential mode. + */ if (pWav->onSeek && !pWav->isSequentialWrite) { if (pWav->container == drwav_container_riff) { - // The "RIFF" chunk size. + /* The "RIFF" chunk size. */ if (pWav->onSeek(pWav->pUserData, 4, drwav_seek_origin_start)) { drwav_uint32 riffChunkSize = drwav_riff_chunk_size_riff(pWav->dataChunkDataSize); pWav->onWrite(pWav->pUserData, &riffChunkSize, 4); } - // the "data" chunk size. + /* the "data" chunk size. */ if (pWav->onSeek(pWav->pUserData, (int)pWav->dataChunkDataPos + 4, drwav_seek_origin_start)) { drwav_uint32 dataChunkSize = drwav_data_chunk_size_riff(pWav->dataChunkDataSize); pWav->onWrite(pWav->pUserData, &dataChunkSize, 4); } } else { - // The "RIFF" chunk size. + /* The "RIFF" chunk size. */ if (pWav->onSeek(pWav->pUserData, 16, drwav_seek_origin_start)) { drwav_uint64 riffChunkSize = drwav_riff_chunk_size_w64(pWav->dataChunkDataSize); pWav->onWrite(pWav->pUserData, &riffChunkSize, 8); } - // The "data" chunk size. + /* The "data" chunk size. */ if (pWav->onSeek(pWav->pUserData, (int)pWav->dataChunkDataPos + 16, drwav_seek_origin_start)) { drwav_uint64 dataChunkSize = drwav_data_chunk_size_w64(pWav->dataChunkDataSize); pWav->onWrite(pWav->pUserData, &dataChunkSize, 8); @@ -1819,8 +2274,10 @@ void drwav_uninit(drwav* pWav) } #ifndef DR_WAV_NO_STDIO - // If we opened the file with drwav_open_file() we will want to close the file handle. We can know whether or not drwav_open_file() - // was used by looking at the onRead and onSeek callbacks. + /* + If we opened the file with drwav_open_file() we will want to close the file handle. We can know whether or not drwav_open_file() + was used by looking at the onRead and onSeek callbacks. + */ if (pWav->onRead == drwav__on_read_stdio || pWav->onWrite == drwav__on_write_stdio) { fclose((FILE*)pWav->pUserData); } @@ -1829,13 +2286,18 @@ void drwav_uninit(drwav* pWav) drwav* drwav_open(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData) +{ + return drwav_open_ex(onRead, onSeek, NULL, pUserData, NULL, 0); +} + +drwav* drwav_open_ex(drwav_read_proc onRead, drwav_seek_proc onSeek, drwav_chunk_proc onChunk, void* pReadSeekUserData, void* pChunkUserData, drwav_uint32 flags) { drwav* pWav = (drwav*)DRWAV_MALLOC(sizeof(*pWav)); if (pWav == NULL) { return NULL; } - if (!drwav_init(pWav, onRead, onSeek, pUserData)) { + if (!drwav_init_ex(pWav, onRead, onSeek, onChunk, pReadSeekUserData, pChunkUserData, flags)) { DRWAV_FREE(pWav); return NULL; } @@ -1878,6 +2340,8 @@ void drwav_close(drwav* pWav) size_t drwav_read_raw(drwav* pWav, size_t bytesToRead, void* pBufferOut) { + size_t bytesRead; + if (pWav == NULL || bytesToRead == 0 || pBufferOut == NULL) { return 0; } @@ -1886,7 +2350,7 @@ size_t drwav_read_raw(drwav* pWav, size_t bytesToRead, void* pBufferOut) bytesToRead = (size_t)pWav->bytesRemaining; } - size_t bytesRead = pWav->onRead(pWav->pUserData, pBufferOut, bytesToRead); + bytesRead = pWav->onRead(pWav->pUserData, pBufferOut, bytesToRead); pWav->bytesRemaining -= bytesRead; return bytesRead; @@ -1894,28 +2358,64 @@ size_t drwav_read_raw(drwav* pWav, size_t bytesToRead, void* pBufferOut) drwav_uint64 drwav_read(drwav* pWav, drwav_uint64 samplesToRead, void* pBufferOut) { + drwav_uint32 bytesPerSample; + size_t bytesRead; + if (pWav == NULL || samplesToRead == 0 || pBufferOut == NULL) { return 0; } - // Cannot use this function for compressed formats. + /* Cannot use this function for compressed formats. */ + if (drwav__is_compressed_format_tag(pWav->translatedFormatTag)) { + return 0; + } + + bytesPerSample = drwav_get_bytes_per_sample(pWav); + if (bytesPerSample == 0) { + return 0; + } + + /* Don't try to read more samples than can potentially fit in the output buffer. */ + if (samplesToRead * bytesPerSample > DRWAV_SIZE_MAX) { + samplesToRead = DRWAV_SIZE_MAX / bytesPerSample; + } + + bytesRead = drwav_read_raw(pWav, (size_t)(samplesToRead * bytesPerSample), pBufferOut); + return bytesRead / bytesPerSample; +} + +drwav_uint64 drwav_read_pcm_frames(drwav* pWav, drwav_uint64 framesToRead, void* pBufferOut) +{ + drwav_uint32 bytesPerFrame; + size_t bytesRead; + + if (pWav == NULL || framesToRead == 0 || pBufferOut == NULL) { + return 0; + } + + /* Cannot use this function for compressed formats. */ if (drwav__is_compressed_format_tag(pWav->translatedFormatTag)) { return 0; } - // Don't try to read more samples than can potentially fit in the output buffer. - if (samplesToRead * pWav->bytesPerSample > SIZE_MAX) { - samplesToRead = SIZE_MAX / pWav->bytesPerSample; + bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav); + if (bytesPerFrame == 0) { + return 0; + } + + /* Don't try to read more samples than can potentially fit in the output buffer. */ + if (framesToRead * bytesPerFrame > DRWAV_SIZE_MAX) { + framesToRead = DRWAV_SIZE_MAX / bytesPerFrame; } - size_t bytesRead = drwav_read_raw(pWav, (size_t)(samplesToRead * pWav->bytesPerSample), pBufferOut); - return bytesRead / pWav->bytesPerSample; + bytesRead = drwav_read_raw(pWav, (size_t)(framesToRead * bytesPerFrame), pBufferOut); + return bytesRead / bytesPerFrame; } -drwav_bool32 drwav_seek_to_first_sample(drwav* pWav) +drwav_bool32 drwav_seek_to_first_pcm_frame(drwav* pWav) { if (pWav->onWrite != NULL) { - return DRWAV_FALSE; // No seeking in write mode. + return DRWAV_FALSE; /* No seeking in write mode. */ } if (!pWav->onSeek(pWav->pUserData, (int)pWav->dataChunkDataPos, drwav_seek_origin_start)) { @@ -1932,36 +2432,39 @@ drwav_bool32 drwav_seek_to_first_sample(drwav* pWav) drwav_bool32 drwav_seek_to_sample(drwav* pWav, drwav_uint64 sample) { - // Seeking should be compatible with wave files > 2GB. + /* Seeking should be compatible with wave files > 2GB. */ if (pWav->onWrite != NULL) { - return DRWAV_FALSE; // No seeking in write mode. + return DRWAV_FALSE; /* No seeking in write mode. */ } if (pWav == NULL || pWav->onSeek == NULL) { return DRWAV_FALSE; } - // If there are no samples, just return DRWAV_TRUE without doing anything. + /* If there are no samples, just return DRWAV_TRUE without doing anything. */ if (pWav->totalSampleCount == 0) { return DRWAV_TRUE; } - // Make sure the sample is clamped. + /* Make sure the sample is clamped. */ if (sample >= pWav->totalSampleCount) { sample = pWav->totalSampleCount - 1; } - - // For compressed formats we just use a slow generic seek. If we are seeking forward we just seek forward. If we are going backwards we need - // to seek back to the start. + /* + For compressed formats we just use a slow generic seek. If we are seeking forward we just seek forward. If we are going backwards we need + to seek back to the start. + */ if (drwav__is_compressed_format_tag(pWav->translatedFormatTag)) { - // TODO: This can be optimized. + /* TODO: This can be optimized. */ - // If we're seeking forward it's simple - just keep reading samples until we hit the sample we're requesting. If we're seeking backwards, - // we first need to seek back to the start and then just do the same thing as a forward seek. + /* + If we're seeking forward it's simple - just keep reading samples until we hit the sample we're requesting. If we're seeking backwards, + we first need to seek back to the start and then just do the same thing as a forward seek. + */ if (sample < pWav->compressed.iCurrentSample) { - if (!drwav_seek_to_first_sample(pWav)) { + if (!drwav_seek_to_first_pcm_frame(pWav)) { return DRWAV_FALSE; } } @@ -1971,18 +2474,18 @@ drwav_bool32 drwav_seek_to_sample(drwav* pWav, drwav_uint64 sample) drwav_int16 devnull[2048]; while (offset > 0) { + drwav_uint64 samplesRead = 0; drwav_uint64 samplesToRead = offset; if (samplesToRead > 2048) { samplesToRead = 2048; } - drwav_uint64 samplesRead = 0; if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM) { samplesRead = drwav_read_s16__msadpcm(pWav, samplesToRead, devnull); } else if (pWav->translatedFormatTag == DR_WAVE_FORMAT_DVI_ADPCM) { samplesRead = drwav_read_s16__ima(pWav, samplesToRead, devnull); } else { - assert(DRWAV_FALSE); // If this assertion is triggered it means I've implemented a new compressed format but forgot to add a branch for it here. + assert(DRWAV_FALSE); /* If this assertion is triggered it means I've implemented a new compressed format but forgot to add a branch for it here. */ } if (samplesRead != samplesToRead) { @@ -1993,19 +2496,23 @@ drwav_bool32 drwav_seek_to_sample(drwav* pWav, drwav_uint64 sample) } } } else { - drwav_uint64 totalSizeInBytes = pWav->totalSampleCount * pWav->bytesPerSample; + drwav_uint64 totalSizeInBytes; + drwav_uint64 currentBytePos; + drwav_uint64 targetBytePos; + drwav_uint64 offset; + + totalSizeInBytes = pWav->totalPCMFrameCount * drwav_get_bytes_per_pcm_frame(pWav); drwav_assert(totalSizeInBytes >= pWav->bytesRemaining); - drwav_uint64 currentBytePos = totalSizeInBytes - pWav->bytesRemaining; - drwav_uint64 targetBytePos = sample * pWav->bytesPerSample; + currentBytePos = totalSizeInBytes - pWav->bytesRemaining; + targetBytePos = sample * drwav_get_bytes_per_sample(pWav); - drwav_uint64 offset; if (currentBytePos < targetBytePos) { - // Offset forwards. + /* Offset forwards. */ offset = (targetBytePos - currentBytePos); } else { - // Offset backwards. - if (!drwav_seek_to_first_sample(pWav)) { + /* Offset backwards. */ + if (!drwav_seek_to_first_pcm_frame(pWav)) { return DRWAV_FALSE; } offset = targetBytePos; @@ -2025,14 +2532,21 @@ drwav_bool32 drwav_seek_to_sample(drwav* pWav, drwav_uint64 sample) return DRWAV_TRUE; } +drwav_bool32 drwav_seek_to_pcm_frame(drwav* pWav, drwav_uint64 targetFrameIndex) +{ + return drwav_seek_to_sample(pWav, targetFrameIndex * pWav->channels); +} + size_t drwav_write_raw(drwav* pWav, size_t bytesToWrite, const void* pData) { + size_t bytesWritten; + if (pWav == NULL || bytesToWrite == 0 || pData == NULL) { return 0; } - size_t bytesWritten = pWav->onWrite(pWav->pUserData, pData, bytesToWrite); + bytesWritten = pWav->onWrite(pWav->pUserData, pData, bytesToWrite); pWav->dataChunkDataSize += bytesWritten; return bytesWritten; @@ -2040,24 +2554,29 @@ size_t drwav_write_raw(drwav* pWav, size_t bytesToWrite, const void* pData) drwav_uint64 drwav_write(drwav* pWav, drwav_uint64 samplesToWrite, const void* pData) { + drwav_uint64 bytesToWrite; + drwav_uint64 bytesWritten; + const drwav_uint8* pRunningData; + if (pWav == NULL || samplesToWrite == 0 || pData == NULL) { return 0; } - drwav_uint64 bytesToWrite = ((samplesToWrite * pWav->bitsPerSample) / 8); - if (bytesToWrite > SIZE_MAX) { + bytesToWrite = ((samplesToWrite * pWav->bitsPerSample) / 8); + if (bytesToWrite > DRWAV_SIZE_MAX) { return 0; } - drwav_uint64 bytesWritten = 0; - const drwav_uint8* pRunningData = (const drwav_uint8*)pData; + bytesWritten = 0; + pRunningData = (const drwav_uint8*)pData; while (bytesToWrite > 0) { + size_t bytesJustWritten; drwav_uint64 bytesToWriteThisIteration = bytesToWrite; - if (bytesToWriteThisIteration > SIZE_MAX) { - bytesToWriteThisIteration = SIZE_MAX; + if (bytesToWriteThisIteration > DRWAV_SIZE_MAX) { + bytesToWriteThisIteration = DRWAV_SIZE_MAX; } - size_t bytesJustWritten = drwav_write_raw(pWav, (size_t)bytesToWriteThisIteration, pRunningData); + bytesJustWritten = drwav_write_raw(pWav, (size_t)bytesToWriteThisIteration, pRunningData); if (bytesJustWritten == 0) { break; } @@ -2070,23 +2589,28 @@ drwav_uint64 drwav_write(drwav* pWav, drwav_uint64 samplesToWrite, const void* p return (bytesWritten * 8) / pWav->bitsPerSample; } +drwav_uint64 drwav_write_pcm_frames(drwav* pWav, drwav_uint64 framesToWrite, const void* pData) +{ + return drwav_write(pWav, framesToWrite * pWav->channels, pData) / pWav->channels; +} + drwav_uint64 drwav_read_s16__msadpcm(drwav* pWav, drwav_uint64 samplesToRead, drwav_int16* pBufferOut) { + drwav_uint64 totalSamplesRead = 0; + drwav_assert(pWav != NULL); drwav_assert(samplesToRead > 0); drwav_assert(pBufferOut != NULL); - // TODO: Lots of room for optimization here. - - drwav_uint64 totalSamplesRead = 0; + /* TODO: Lots of room for optimization here. */ while (samplesToRead > 0 && pWav->compressed.iCurrentSample < pWav->totalSampleCount) { - // If there are no cached samples we need to load a new block. + /* If there are no cached samples we need to load a new block. */ if (pWav->msadpcm.cachedSampleCount == 0 && pWav->msadpcm.bytesRemainingInBlock == 0) { if (pWav->channels == 1) { - // Mono. + /* Mono. */ drwav_uint8 header[7]; if (pWav->onRead(pWav->pUserData, header, sizeof(header)) != sizeof(header)) { return totalSamplesRead; @@ -2101,7 +2625,7 @@ drwav_uint64 drwav_read_s16__msadpcm(drwav* pWav, drwav_uint64 samplesToRead, dr pWav->msadpcm.cachedSamples[3] = pWav->msadpcm.prevSamples[0][1]; pWav->msadpcm.cachedSampleCount = 2; } else { - // Stereo. + /* Stereo. */ drwav_uint8 header[14]; if (pWav->onRead(pWav->pUserData, header, sizeof(header)) != sizeof(header)) { return totalSamplesRead; @@ -2125,7 +2649,7 @@ drwav_uint64 drwav_read_s16__msadpcm(drwav* pWav, drwav_uint64 samplesToRead, dr } } - // Output anything that's cached. + /* Output anything that's cached. */ while (samplesToRead > 0 && pWav->msadpcm.cachedSampleCount > 0 && pWav->compressed.iCurrentSample < pWav->totalSampleCount) { pBufferOut[0] = (drwav_int16)pWav->msadpcm.cachedSamples[drwav_countof(pWav->msadpcm.cachedSamples) - pWav->msadpcm.cachedSampleCount]; pWav->msadpcm.cachedSampleCount -= 1; @@ -2141,22 +2665,14 @@ drwav_uint64 drwav_read_s16__msadpcm(drwav* pWav, drwav_uint64 samplesToRead, dr } - // If there's nothing left in the cache, just go ahead and load more. If there's nothing left to load in the current block we just continue to the next - // loop iteration which will trigger the loading of a new block. + /* + If there's nothing left in the cache, just go ahead and load more. If there's nothing left to load in the current block we just continue to the next + loop iteration which will trigger the loading of a new block. + */ if (pWav->msadpcm.cachedSampleCount == 0) { if (pWav->msadpcm.bytesRemainingInBlock == 0) { continue; } else { - drwav_uint8 nibbles; - if (pWav->onRead(pWav->pUserData, &nibbles, 1) != 1) { - return totalSamplesRead; - } - pWav->msadpcm.bytesRemainingInBlock -= 1; - - // TODO: Optimize away these if statements. - drwav_int32 nibble0 = ((nibbles & 0xF0) >> 4); if ((nibbles & 0x80)) { nibble0 |= 0xFFFFFFF0UL; } - drwav_int32 nibble1 = ((nibbles & 0x0F) >> 0); if ((nibbles & 0x08)) { nibble1 |= 0xFFFFFFF0UL; } - static drwav_int32 adaptationTable[] = { 230, 230, 230, 230, 307, 409, 512, 614, 768, 614, 512, 409, 307, 230, 230, 230 @@ -2164,9 +2680,24 @@ drwav_uint64 drwav_read_s16__msadpcm(drwav* pWav, drwav_uint64 samplesToRead, dr static drwav_int32 coeff1Table[] = { 256, 512, 0, 192, 240, 460, 392 }; static drwav_int32 coeff2Table[] = { 0, -256, 0, 64, 0, -208, -232 }; + drwav_uint8 nibbles; + drwav_int32 nibble0; + drwav_int32 nibble1; + + if (pWav->onRead(pWav->pUserData, &nibbles, 1) != 1) { + return totalSamplesRead; + } + pWav->msadpcm.bytesRemainingInBlock -= 1; + + /* TODO: Optimize away these if statements. */ + nibble0 = ((nibbles & 0xF0) >> 4); if ((nibbles & 0x80)) { nibble0 |= 0xFFFFFFF0UL; } + nibble1 = ((nibbles & 0x0F) >> 0); if ((nibbles & 0x08)) { nibble1 |= 0xFFFFFFF0UL; } + if (pWav->channels == 1) { - // Mono. + /* Mono. */ drwav_int32 newSample0; + drwav_int32 newSample1; + newSample0 = ((pWav->msadpcm.prevSamples[0][1] * coeff1Table[pWav->msadpcm.predictor[0]]) + (pWav->msadpcm.prevSamples[0][0] * coeff2Table[pWav->msadpcm.predictor[0]])) >> 8; newSample0 += nibble0 * pWav->msadpcm.delta[0]; newSample0 = drwav_clamp(newSample0, -32768, 32767); @@ -2180,7 +2711,6 @@ drwav_uint64 drwav_read_s16__msadpcm(drwav* pWav, drwav_uint64 samplesToRead, dr pWav->msadpcm.prevSamples[0][1] = newSample0; - drwav_int32 newSample1; newSample1 = ((pWav->msadpcm.prevSamples[0][1] * coeff1Table[pWav->msadpcm.predictor[0]]) + (pWav->msadpcm.prevSamples[0][0] * coeff2Table[pWav->msadpcm.predictor[0]])) >> 8; newSample1 += nibble1 * pWav->msadpcm.delta[0]; newSample1 = drwav_clamp(newSample1, -32768, 32767); @@ -2198,10 +2728,11 @@ drwav_uint64 drwav_read_s16__msadpcm(drwav* pWav, drwav_uint64 samplesToRead, dr pWav->msadpcm.cachedSamples[3] = newSample1; pWav->msadpcm.cachedSampleCount = 2; } else { - // Stereo. - - // Left. + /* Stereo. */ drwav_int32 newSample0; + drwav_int32 newSample1; + + /* Left. */ newSample0 = ((pWav->msadpcm.prevSamples[0][1] * coeff1Table[pWav->msadpcm.predictor[0]]) + (pWav->msadpcm.prevSamples[0][0] * coeff2Table[pWav->msadpcm.predictor[0]])) >> 8; newSample0 += nibble0 * pWav->msadpcm.delta[0]; newSample0 = drwav_clamp(newSample0, -32768, 32767); @@ -2215,8 +2746,7 @@ drwav_uint64 drwav_read_s16__msadpcm(drwav* pWav, drwav_uint64 samplesToRead, dr pWav->msadpcm.prevSamples[0][1] = newSample0; - // Right. - drwav_int32 newSample1; + /* Right. */ newSample1 = ((pWav->msadpcm.prevSamples[1][1] * coeff1Table[pWav->msadpcm.predictor[1]]) + (pWav->msadpcm.prevSamples[1][0] * coeff2Table[pWav->msadpcm.predictor[1]])) >> 8; newSample1 += nibble1 * pWav->msadpcm.delta[1]; newSample1 = drwav_clamp(newSample1, -32768, 32767); @@ -2242,19 +2772,19 @@ drwav_uint64 drwav_read_s16__msadpcm(drwav* pWav, drwav_uint64 samplesToRead, dr drwav_uint64 drwav_read_s16__ima(drwav* pWav, drwav_uint64 samplesToRead, drwav_int16* pBufferOut) { + drwav_uint64 totalSamplesRead = 0; + drwav_assert(pWav != NULL); drwav_assert(samplesToRead > 0); drwav_assert(pBufferOut != NULL); - // TODO: Lots of room for optimization here. - - drwav_uint64 totalSamplesRead = 0; + /* TODO: Lots of room for optimization here. */ while (samplesToRead > 0 && pWav->compressed.iCurrentSample < pWav->totalSampleCount) { - // If there are no cached samples we need to load a new block. + /* If there are no cached samples we need to load a new block. */ if (pWav->ima.cachedSampleCount == 0 && pWav->ima.bytesRemainingInBlock == 0) { if (pWav->channels == 1) { - // Mono. + /* Mono. */ drwav_uint8 header[4]; if (pWav->onRead(pWav->pUserData, header, sizeof(header)) != sizeof(header)) { return totalSamplesRead; @@ -2266,7 +2796,7 @@ drwav_uint64 drwav_read_s16__ima(drwav* pWav, drwav_uint64 samplesToRead, drwav_ pWav->ima.cachedSamples[drwav_countof(pWav->ima.cachedSamples) - 1] = pWav->ima.predictor[0]; pWav->ima.cachedSampleCount = 1; } else { - // Stereo. + /* Stereo. */ drwav_uint8 header[8]; if (pWav->onRead(pWav->pUserData, header, sizeof(header)) != sizeof(header)) { return totalSamplesRead; @@ -2284,7 +2814,7 @@ drwav_uint64 drwav_read_s16__ima(drwav* pWav, drwav_uint64 samplesToRead, drwav_ } } - // Output anything that's cached. + /* Output anything that's cached. */ while (samplesToRead > 0 && pWav->ima.cachedSampleCount > 0 && pWav->compressed.iCurrentSample < pWav->totalSampleCount) { pBufferOut[0] = (drwav_int16)pWav->ima.cachedSamples[drwav_countof(pWav->ima.cachedSamples) - pWav->ima.cachedSampleCount]; pWav->ima.cachedSampleCount -= 1; @@ -2299,8 +2829,10 @@ drwav_uint64 drwav_read_s16__ima(drwav* pWav, drwav_uint64 samplesToRead, drwav_ return totalSamplesRead; } - // If there's nothing left in the cache, just go ahead and load more. If there's nothing left to load in the current block we just continue to the next - // loop iteration which will trigger the loading of a new block. + /* + If there's nothing left in the cache, just go ahead and load more. If there's nothing left to load in the current block we just continue to the next + loop iteration which will trigger the loading of a new block. + */ if (pWav->ima.cachedSampleCount == 0) { if (pWav->ima.bytesRemainingInBlock == 0) { continue; @@ -2322,17 +2854,22 @@ drwav_uint64 drwav_read_s16__ima(drwav* pWav, drwav_uint64 samplesToRead, drwav_ 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767 }; - // From what I can tell with stereo streams, it looks like every 4 bytes (8 samples) is for one channel. So it goes 4 bytes for the - // left channel, 4 bytes for the right channel. + drwav_uint32 iChannel; + + /* + From what I can tell with stereo streams, it looks like every 4 bytes (8 samples) is for one channel. So it goes 4 bytes for the + left channel, 4 bytes for the right channel. + */ pWav->ima.cachedSampleCount = 8 * pWav->channels; - for (drwav_uint32 iChannel = 0; iChannel < pWav->channels; ++iChannel) { + for (iChannel = 0; iChannel < pWav->channels; ++iChannel) { + drwav_uint32 iByte; drwav_uint8 nibbles[4]; if (pWav->onRead(pWav->pUserData, &nibbles, 4) != 4) { return totalSamplesRead; } pWav->ima.bytesRemainingInBlock -= 4; - for (drwav_uint32 iByte = 0; iByte < 4; ++iByte) { + for (iByte = 0; iByte < 4; ++iByte) { drwav_uint8 nibble0 = ((nibbles[iByte] & 0x0F) >> 0); drwav_uint8 nibble1 = ((nibbles[iByte] & 0xF0) >> 4); @@ -2425,19 +2962,21 @@ static DRWAV_INLINE drwav_int16 drwav__mulaw_to_s16(drwav_uint8 sampleIn) -static void drwav__pcm_to_s16(drwav_int16* pOut, const unsigned char* pIn, size_t totalSampleCount, unsigned short bytesPerSample) +static void drwav__pcm_to_s16(drwav_int16* pOut, const unsigned char* pIn, size_t totalSampleCount, unsigned int bytesPerSample) { - // Special case for 8-bit sample data because it's treated as unsigned. + unsigned int i; + + /* Special case for 8-bit sample data because it's treated as unsigned. */ if (bytesPerSample == 1) { drwav_u8_to_s16(pOut, pIn, totalSampleCount); return; } - // Slightly more optimal implementation for common formats. + /* Slightly more optimal implementation for common formats. */ if (bytesPerSample == 2) { - for (unsigned int i = 0; i < totalSampleCount; ++i) { - *pOut++ = ((drwav_int16*)pIn)[i]; + for (i = 0; i < totalSampleCount; ++i) { + *pOut++ = ((const drwav_int16*)pIn)[i]; } return; } @@ -2451,15 +2990,15 @@ static void drwav__pcm_to_s16(drwav_int16* pOut, const unsigned char* pIn, size_ } - // Anything more than 64 bits per sample is not supported. + /* Anything more than 64 bits per sample is not supported. */ if (bytesPerSample > 8) { drwav_zero_memory(pOut, totalSampleCount * sizeof(*pOut)); return; } - // Generic, slow converter. - for (unsigned int i = 0; i < totalSampleCount; ++i) { + /* Generic, slow converter. */ + for (i = 0; i < totalSampleCount; ++i) { drwav_uint64 sample = 0; unsigned int shift = (8 - bytesPerSample) * 8; @@ -2474,16 +3013,16 @@ static void drwav__pcm_to_s16(drwav_int16* pOut, const unsigned char* pIn, size_ } } -static void drwav__ieee_to_s16(drwav_int16* pOut, const unsigned char* pIn, size_t totalSampleCount, unsigned short bytesPerSample) +static void drwav__ieee_to_s16(drwav_int16* pOut, const unsigned char* pIn, size_t totalSampleCount, unsigned int bytesPerSample) { if (bytesPerSample == 4) { - drwav_f32_to_s16(pOut, (float*)pIn, totalSampleCount); + drwav_f32_to_s16(pOut, (const float*)pIn, totalSampleCount); return; } else if (bytesPerSample == 8) { - drwav_f64_to_s16(pOut, (double*)pIn, totalSampleCount); + drwav_f64_to_s16(pOut, (const double*)pIn, totalSampleCount); return; } else { - // Only supporting 32- and 64-bit float. Output silence in all other cases. Contributions welcome for 16-bit float. + /* Only supporting 32- and 64-bit float. Output silence in all other cases. Contributions welcome for 16-bit float. */ drwav_zero_memory(pOut, totalSampleCount * sizeof(*pOut)); return; } @@ -2491,20 +3030,29 @@ static void drwav__ieee_to_s16(drwav_int16* pOut, const unsigned char* pIn, size drwav_uint64 drwav_read_s16__pcm(drwav* pWav, drwav_uint64 samplesToRead, drwav_int16* pBufferOut) { - // Fast path. - if (pWav->bytesPerSample == 2) { + drwav_uint32 bytesPerSample; + drwav_uint64 totalSamplesRead; + unsigned char sampleData[4096]; + + /* Fast path. */ + if (pWav->translatedFormatTag == DR_WAVE_FORMAT_PCM && pWav->bitsPerSample == 16) { return drwav_read(pWav, samplesToRead, pBufferOut); } + + bytesPerSample = drwav_get_bytes_per_sample(pWav); + if (bytesPerSample == 0) { + return 0; + } - drwav_uint64 totalSamplesRead = 0; - unsigned char sampleData[4096]; + totalSamplesRead = 0; + while (samplesToRead > 0) { - drwav_uint64 samplesRead = drwav_read(pWav, drwav_min(samplesToRead, sizeof(sampleData)/pWav->bytesPerSample), sampleData); + drwav_uint64 samplesRead = drwav_read(pWav, drwav_min(samplesToRead, sizeof(sampleData)/bytesPerSample), sampleData); if (samplesRead == 0) { break; } - drwav__pcm_to_s16(pBufferOut, sampleData, (size_t)samplesRead, pWav->bytesPerSample); + drwav__pcm_to_s16(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample); pBufferOut += samplesRead; samplesToRead -= samplesRead; @@ -2516,15 +3064,23 @@ drwav_uint64 drwav_read_s16__pcm(drwav* pWav, drwav_uint64 samplesToRead, drwav_ drwav_uint64 drwav_read_s16__ieee(drwav* pWav, drwav_uint64 samplesToRead, drwav_int16* pBufferOut) { - drwav_uint64 totalSamplesRead = 0; + drwav_uint64 totalSamplesRead; unsigned char sampleData[4096]; + + drwav_uint32 bytesPerSample = drwav_get_bytes_per_sample(pWav); + if (bytesPerSample == 0) { + return 0; + } + + totalSamplesRead = 0; + while (samplesToRead > 0) { - drwav_uint64 samplesRead = drwav_read(pWav, drwav_min(samplesToRead, sizeof(sampleData)/pWav->bytesPerSample), sampleData); + drwav_uint64 samplesRead = drwav_read(pWav, drwav_min(samplesToRead, sizeof(sampleData)/bytesPerSample), sampleData); if (samplesRead == 0) { break; } - drwav__ieee_to_s16(pBufferOut, sampleData, (size_t)samplesRead, pWav->bytesPerSample); + drwav__ieee_to_s16(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample); pBufferOut += samplesRead; samplesToRead -= samplesRead; @@ -2536,10 +3092,18 @@ drwav_uint64 drwav_read_s16__ieee(drwav* pWav, drwav_uint64 samplesToRead, drwav drwav_uint64 drwav_read_s16__alaw(drwav* pWav, drwav_uint64 samplesToRead, drwav_int16* pBufferOut) { - drwav_uint64 totalSamplesRead = 0; + drwav_uint64 totalSamplesRead; unsigned char sampleData[4096]; + + drwav_uint32 bytesPerSample = drwav_get_bytes_per_sample(pWav); + if (bytesPerSample == 0) { + return 0; + } + + totalSamplesRead = 0; + while (samplesToRead > 0) { - drwav_uint64 samplesRead = drwav_read(pWav, drwav_min(samplesToRead, sizeof(sampleData)/pWav->bytesPerSample), sampleData); + drwav_uint64 samplesRead = drwav_read(pWav, drwav_min(samplesToRead, sizeof(sampleData)/bytesPerSample), sampleData); if (samplesRead == 0) { break; } @@ -2556,10 +3120,18 @@ drwav_uint64 drwav_read_s16__alaw(drwav* pWav, drwav_uint64 samplesToRead, drwav drwav_uint64 drwav_read_s16__mulaw(drwav* pWav, drwav_uint64 samplesToRead, drwav_int16* pBufferOut) { - drwav_uint64 totalSamplesRead = 0; + drwav_uint64 totalSamplesRead; unsigned char sampleData[4096]; + + drwav_uint32 bytesPerSample = drwav_get_bytes_per_sample(pWav); + if (bytesPerSample == 0) { + return 0; + } + + totalSamplesRead = 0; + while (samplesToRead > 0) { - drwav_uint64 samplesRead = drwav_read(pWav, drwav_min(samplesToRead, sizeof(sampleData)/pWav->bytesPerSample), sampleData); + drwav_uint64 samplesRead = drwav_read(pWav, drwav_min(samplesToRead, sizeof(sampleData)/bytesPerSample), sampleData); if (samplesRead == 0) { break; } @@ -2580,9 +3152,9 @@ drwav_uint64 drwav_read_s16(drwav* pWav, drwav_uint64 samplesToRead, drwav_int16 return 0; } - // Don't try to read more samples than can potentially fit in the output buffer. - if (samplesToRead * sizeof(drwav_int16) > SIZE_MAX) { - samplesToRead = SIZE_MAX / sizeof(drwav_int16); + /* Don't try to read more samples than can potentially fit in the output buffer. */ + if (samplesToRead * sizeof(drwav_int16) > DRWAV_SIZE_MAX) { + samplesToRead = DRWAV_SIZE_MAX / sizeof(drwav_int16); } if (pWav->translatedFormatTag == DR_WAVE_FORMAT_PCM) { @@ -2612,10 +3184,16 @@ drwav_uint64 drwav_read_s16(drwav* pWav, drwav_uint64 samplesToRead, drwav_int16 return 0; } +drwav_uint64 drwav_read_pcm_frames_s16(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut) +{ + return drwav_read_s16(pWav, framesToRead * pWav->channels, pBufferOut) / pWav->channels; +} + void drwav_u8_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount) { int r; - for (size_t i = 0; i < sampleCount; ++i) { + size_t i; + for (i = 0; i < sampleCount; ++i) { int x = pIn[i]; r = x - 128; r = r << 8; @@ -2626,8 +3204,9 @@ void drwav_u8_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCou void drwav_s24_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount) { int r; - for (size_t i = 0; i < sampleCount; ++i) { - int x = ((int)(((unsigned int)(((unsigned char*)pIn)[i*3+0]) << 8) | ((unsigned int)(((unsigned char*)pIn)[i*3+1]) << 16) | ((unsigned int)(((unsigned char*)pIn)[i*3+2])) << 24)) >> 8; + size_t i; + for (i = 0; i < sampleCount; ++i) { + int x = ((int)(((unsigned int)(((const unsigned char*)pIn)[i*3+0]) << 8) | ((unsigned int)(((const unsigned char*)pIn)[i*3+1]) << 16) | ((unsigned int)(((const unsigned char*)pIn)[i*3+2])) << 24)) >> 8; r = x >> 8; pOut[i] = (short)r; } @@ -2636,7 +3215,8 @@ void drwav_s24_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCo void drwav_s32_to_s16(drwav_int16* pOut, const drwav_int32* pIn, size_t sampleCount) { int r; - for (size_t i = 0; i < sampleCount; ++i) { + size_t i; + for (i = 0; i < sampleCount; ++i) { int x = pIn[i]; r = x >> 16; pOut[i] = (short)r; @@ -2646,7 +3226,8 @@ void drwav_s32_to_s16(drwav_int16* pOut, const drwav_int32* pIn, size_t sampleCo void drwav_f32_to_s16(drwav_int16* pOut, const float* pIn, size_t sampleCount) { int r; - for (size_t i = 0; i < sampleCount; ++i) { + size_t i; + for (i = 0; i < sampleCount; ++i) { float x = pIn[i]; float c; c = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); @@ -2660,7 +3241,8 @@ void drwav_f32_to_s16(drwav_int16* pOut, const float* pIn, size_t sampleCount) void drwav_f64_to_s16(drwav_int16* pOut, const double* pIn, size_t sampleCount) { int r; - for (size_t i = 0; i < sampleCount; ++i) { + size_t i; + for (i = 0; i < sampleCount; ++i) { double x = pIn[i]; double c; c = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); @@ -2673,29 +3255,33 @@ void drwav_f64_to_s16(drwav_int16* pOut, const double* pIn, size_t sampleCount) void drwav_alaw_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount) { - for (size_t i = 0; i < sampleCount; ++i) { + size_t i; + for (i = 0; i < sampleCount; ++i) { pOut[i] = drwav__alaw_to_s16(pIn[i]); } } void drwav_mulaw_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount) { - for (size_t i = 0; i < sampleCount; ++i) { + size_t i; + for (i = 0; i < sampleCount; ++i) { pOut[i] = drwav__mulaw_to_s16(pIn[i]); } } -static void drwav__pcm_to_f32(float* pOut, const unsigned char* pIn, size_t sampleCount, unsigned short bytesPerSample) +static void drwav__pcm_to_f32(float* pOut, const unsigned char* pIn, size_t sampleCount, unsigned int bytesPerSample) { - // Special case for 8-bit sample data because it's treated as unsigned. + unsigned int i; + + /* Special case for 8-bit sample data because it's treated as unsigned. */ if (bytesPerSample == 1) { drwav_u8_to_f32(pOut, pIn, sampleCount); return; } - // Slightly more optimal implementation for common formats. + /* Slightly more optimal implementation for common formats. */ if (bytesPerSample == 2) { drwav_s16_to_f32(pOut, (const drwav_int16*)pIn, sampleCount); return; @@ -2710,15 +3296,15 @@ static void drwav__pcm_to_f32(float* pOut, const unsigned char* pIn, size_t samp } - // Anything more than 64 bits per sample is not supported. + /* Anything more than 64 bits per sample is not supported. */ if (bytesPerSample > 8) { drwav_zero_memory(pOut, sampleCount * sizeof(*pOut)); return; } - // Generic, slow converter. - for (unsigned int i = 0; i < sampleCount; ++i) { + /* Generic, slow converter. */ + for (i = 0; i < sampleCount; ++i) { drwav_uint64 sample = 0; unsigned int shift = (8 - bytesPerSample) * 8; @@ -2733,18 +3319,19 @@ static void drwav__pcm_to_f32(float* pOut, const unsigned char* pIn, size_t samp } } -static void drwav__ieee_to_f32(float* pOut, const unsigned char* pIn, size_t sampleCount, unsigned short bytesPerSample) +static void drwav__ieee_to_f32(float* pOut, const unsigned char* pIn, size_t sampleCount, unsigned int bytesPerSample) { if (bytesPerSample == 4) { - for (unsigned int i = 0; i < sampleCount; ++i) { - *pOut++ = ((float*)pIn)[i]; + unsigned int i; + for (i = 0; i < sampleCount; ++i) { + *pOut++ = ((const float*)pIn)[i]; } return; } else if (bytesPerSample == 8) { - drwav_f64_to_f32(pOut, (double*)pIn, sampleCount); + drwav_f64_to_f32(pOut, (const double*)pIn, sampleCount); return; } else { - // Only supporting 32- and 64-bit float. Output silence in all other cases. Contributions welcome for 16-bit float. + /* Only supporting 32- and 64-bit float. Output silence in all other cases. Contributions welcome for 16-bit float. */ drwav_zero_memory(pOut, sampleCount * sizeof(*pOut)); return; } @@ -2753,19 +3340,23 @@ static void drwav__ieee_to_f32(float* pOut, const unsigned char* pIn, size_t sam drwav_uint64 drwav_read_f32__pcm(drwav* pWav, drwav_uint64 samplesToRead, float* pBufferOut) { - if (pWav->bytesPerSample == 0) { + drwav_uint64 totalSamplesRead; + unsigned char sampleData[4096]; + + drwav_uint32 bytesPerSample = drwav_get_bytes_per_sample(pWav); + if (bytesPerSample == 0) { return 0; } - drwav_uint64 totalSamplesRead = 0; - unsigned char sampleData[4096]; + totalSamplesRead = 0; + while (samplesToRead > 0) { - drwav_uint64 samplesRead = drwav_read(pWav, drwav_min(samplesToRead, sizeof(sampleData)/pWav->bytesPerSample), sampleData); + drwav_uint64 samplesRead = drwav_read(pWav, drwav_min(samplesToRead, sizeof(sampleData)/bytesPerSample), sampleData); if (samplesRead == 0) { break; } - drwav__pcm_to_f32(pBufferOut, sampleData, (size_t)samplesRead, pWav->bytesPerSample); + drwav__pcm_to_f32(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample); pBufferOut += samplesRead; samplesToRead -= samplesRead; @@ -2777,8 +3368,10 @@ drwav_uint64 drwav_read_f32__pcm(drwav* pWav, drwav_uint64 samplesToRead, float* drwav_uint64 drwav_read_f32__msadpcm(drwav* pWav, drwav_uint64 samplesToRead, float* pBufferOut) { - // We're just going to borrow the implementation from the drwav_read_s16() since ADPCM is a little bit more complicated than other formats and I don't - // want to duplicate that code. + /* + We're just going to borrow the implementation from the drwav_read_s16() since ADPCM is a little bit more complicated than other formats and I don't + want to duplicate that code. + */ drwav_uint64 totalSamplesRead = 0; drwav_int16 samples16[2048]; while (samplesToRead > 0) { @@ -2787,7 +3380,7 @@ drwav_uint64 drwav_read_f32__msadpcm(drwav* pWav, drwav_uint64 samplesToRead, fl break; } - drwav_s16_to_f32(pBufferOut, samples16, (size_t)samplesRead); // <-- Safe cast because we're clamping to 2048. + drwav_s16_to_f32(pBufferOut, samples16, (size_t)samplesRead); /* <-- Safe cast because we're clamping to 2048. */ pBufferOut += samplesRead; samplesToRead -= samplesRead; @@ -2799,8 +3392,10 @@ drwav_uint64 drwav_read_f32__msadpcm(drwav* pWav, drwav_uint64 samplesToRead, fl drwav_uint64 drwav_read_f32__ima(drwav* pWav, drwav_uint64 samplesToRead, float* pBufferOut) { - // We're just going to borrow the implementation from the drwav_read_s16() since IMA-ADPCM is a little bit more complicated than other formats and I don't - // want to duplicate that code. + /* + We're just going to borrow the implementation from the drwav_read_s16() since IMA-ADPCM is a little bit more complicated than other formats and I don't + want to duplicate that code. + */ drwav_uint64 totalSamplesRead = 0; drwav_int16 samples16[2048]; while (samplesToRead > 0) { @@ -2809,7 +3404,7 @@ drwav_uint64 drwav_read_f32__ima(drwav* pWav, drwav_uint64 samplesToRead, float* break; } - drwav_s16_to_f32(pBufferOut, samples16, (size_t)samplesRead); // <-- Safe cast because we're clamping to 2048. + drwav_s16_to_f32(pBufferOut, samples16, (size_t)samplesRead); /* <-- Safe cast because we're clamping to 2048. */ pBufferOut += samplesRead; samplesToRead -= samplesRead; @@ -2821,24 +3416,29 @@ drwav_uint64 drwav_read_f32__ima(drwav* pWav, drwav_uint64 samplesToRead, float* drwav_uint64 drwav_read_f32__ieee(drwav* pWav, drwav_uint64 samplesToRead, float* pBufferOut) { - // Fast path. - if (pWav->translatedFormatTag == DR_WAVE_FORMAT_IEEE_FLOAT && pWav->bytesPerSample == 4) { + drwav_uint64 totalSamplesRead; + unsigned char sampleData[4096]; + drwav_uint32 bytesPerSample; + + /* Fast path. */ + if (pWav->translatedFormatTag == DR_WAVE_FORMAT_IEEE_FLOAT && pWav->bitsPerSample == 32) { return drwav_read(pWav, samplesToRead, pBufferOut); } - - if (pWav->bytesPerSample == 0) { + + bytesPerSample = drwav_get_bytes_per_sample(pWav); + if (bytesPerSample == 0) { return 0; } - drwav_uint64 totalSamplesRead = 0; - unsigned char sampleData[4096]; + totalSamplesRead = 0; + while (samplesToRead > 0) { - drwav_uint64 samplesRead = drwav_read(pWav, drwav_min(samplesToRead, sizeof(sampleData)/pWav->bytesPerSample), sampleData); + drwav_uint64 samplesRead = drwav_read(pWav, drwav_min(samplesToRead, sizeof(sampleData)/bytesPerSample), sampleData); if (samplesRead == 0) { break; } - drwav__ieee_to_f32(pBufferOut, sampleData, (size_t)samplesRead, pWav->bytesPerSample); + drwav__ieee_to_f32(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample); pBufferOut += samplesRead; samplesToRead -= samplesRead; @@ -2850,14 +3450,17 @@ drwav_uint64 drwav_read_f32__ieee(drwav* pWav, drwav_uint64 samplesToRead, float drwav_uint64 drwav_read_f32__alaw(drwav* pWav, drwav_uint64 samplesToRead, float* pBufferOut) { - if (pWav->bytesPerSample == 0) { + drwav_uint64 totalSamplesRead; + unsigned char sampleData[4096]; + drwav_uint32 bytesPerSample = drwav_get_bytes_per_sample(pWav); + if (bytesPerSample == 0) { return 0; } - drwav_uint64 totalSamplesRead = 0; - unsigned char sampleData[4096]; + totalSamplesRead = 0; + while (samplesToRead > 0) { - drwav_uint64 samplesRead = drwav_read(pWav, drwav_min(samplesToRead, sizeof(sampleData)/pWav->bytesPerSample), sampleData); + drwav_uint64 samplesRead = drwav_read(pWav, drwav_min(samplesToRead, sizeof(sampleData)/bytesPerSample), sampleData); if (samplesRead == 0) { break; } @@ -2874,14 +3477,18 @@ drwav_uint64 drwav_read_f32__alaw(drwav* pWav, drwav_uint64 samplesToRead, float drwav_uint64 drwav_read_f32__mulaw(drwav* pWav, drwav_uint64 samplesToRead, float* pBufferOut) { - if (pWav->bytesPerSample == 0) { + drwav_uint64 totalSamplesRead; + unsigned char sampleData[4096]; + + drwav_uint32 bytesPerSample = drwav_get_bytes_per_sample(pWav); + if (bytesPerSample == 0) { return 0; } - drwav_uint64 totalSamplesRead = 0; - unsigned char sampleData[4096]; + totalSamplesRead = 0; + while (samplesToRead > 0) { - drwav_uint64 samplesRead = drwav_read(pWav, drwav_min(samplesToRead, sizeof(sampleData)/pWav->bytesPerSample), sampleData); + drwav_uint64 samplesRead = drwav_read(pWav, drwav_min(samplesToRead, sizeof(sampleData)/bytesPerSample), sampleData); if (samplesRead == 0) { break; } @@ -2902,9 +3509,9 @@ drwav_uint64 drwav_read_f32(drwav* pWav, drwav_uint64 samplesToRead, float* pBuf return 0; } - // Don't try to read more samples than can potentially fit in the output buffer. - if (samplesToRead * sizeof(float) > SIZE_MAX) { - samplesToRead = SIZE_MAX / sizeof(float); + /* Don't try to read more samples than can potentially fit in the output buffer. */ + if (samplesToRead * sizeof(float) > DRWAV_SIZE_MAX) { + samplesToRead = DRWAV_SIZE_MAX / sizeof(float); } if (pWav->translatedFormatTag == DR_WAVE_FORMAT_PCM) { @@ -2934,22 +3541,31 @@ drwav_uint64 drwav_read_f32(drwav* pWav, drwav_uint64 samplesToRead, float* pBuf return 0; } +drwav_uint64 drwav_read_pcm_frames_f32(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut) +{ + return drwav_read_f32(pWav, framesToRead * pWav->channels, pBufferOut) / pWav->channels; +} + void drwav_u8_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount) { + size_t i; + if (pOut == NULL || pIn == NULL) { return; } #ifdef DR_WAV_LIBSNDFILE_COMPAT - // It appears libsndfile uses slightly different logic for the u8 -> f32 conversion to dr_wav, which in my opinion is incorrect. It appears - // libsndfile performs the conversion something like "f32 = (u8 / 256) * 2 - 1", however I think it should be "f32 = (u8 / 255) * 2 - 1" (note - // the divisor of 256 vs 255). I use libsndfile as a benchmark for testing, so I'm therefore leaving this block here just for my automated - // correctness testing. This is disabled by default. - for (size_t i = 0; i < sampleCount; ++i) { + /* + It appears libsndfile uses slightly different logic for the u8 -> f32 conversion to dr_wav, which in my opinion is incorrect. It appears + libsndfile performs the conversion something like "f32 = (u8 / 256) * 2 - 1", however I think it should be "f32 = (u8 / 255) * 2 - 1" (note + the divisor of 256 vs 255). I use libsndfile as a benchmark for testing, so I'm therefore leaving this block here just for my automated + correctness testing. This is disabled by default. + */ + for (i = 0; i < sampleCount; ++i) { *pOut++ = (pIn[i] / 256.0f) * 2 - 1; } #else - for (size_t i = 0; i < sampleCount; ++i) { + for (i = 0; i < sampleCount; ++i) { *pOut++ = (pIn[i] / 255.0f) * 2 - 1; } #endif @@ -2957,22 +3573,26 @@ void drwav_u8_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount) void drwav_s16_to_f32(float* pOut, const drwav_int16* pIn, size_t sampleCount) { + size_t i; + if (pOut == NULL || pIn == NULL) { return; } - for (size_t i = 0; i < sampleCount; ++i) { + for (i = 0; i < sampleCount; ++i) { *pOut++ = pIn[i] / 32768.0f; } } void drwav_s24_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount) { + size_t i; + if (pOut == NULL || pIn == NULL) { return; } - for (size_t i = 0; i < sampleCount; ++i) { + for (i = 0; i < sampleCount; ++i) { unsigned int s0 = pIn[i*3 + 0]; unsigned int s1 = pIn[i*3 + 1]; unsigned int s2 = pIn[i*3 + 2]; @@ -2984,59 +3604,68 @@ void drwav_s24_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount) void drwav_s32_to_f32(float* pOut, const drwav_int32* pIn, size_t sampleCount) { + size_t i; if (pOut == NULL || pIn == NULL) { return; } - for (size_t i = 0; i < sampleCount; ++i) { + for (i = 0; i < sampleCount; ++i) { *pOut++ = (float)(pIn[i] / 2147483648.0); } } void drwav_f64_to_f32(float* pOut, const double* pIn, size_t sampleCount) { + size_t i; + if (pOut == NULL || pIn == NULL) { return; } - for (size_t i = 0; i < sampleCount; ++i) { + for (i = 0; i < sampleCount; ++i) { *pOut++ = (float)pIn[i]; } } void drwav_alaw_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount) { + size_t i; + if (pOut == NULL || pIn == NULL) { return; } - for (size_t i = 0; i < sampleCount; ++i) { + for (i = 0; i < sampleCount; ++i) { *pOut++ = drwav__alaw_to_s16(pIn[i]) / 32768.0f; } } void drwav_mulaw_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount) { + size_t i; + if (pOut == NULL || pIn == NULL) { return; } - for (size_t i = 0; i < sampleCount; ++i) { + for (i = 0; i < sampleCount; ++i) { *pOut++ = drwav__mulaw_to_s16(pIn[i]) / 32768.0f; } } -static void drwav__pcm_to_s32(drwav_int32* pOut, const unsigned char* pIn, size_t totalSampleCount, unsigned short bytesPerSample) +static void drwav__pcm_to_s32(drwav_int32* pOut, const unsigned char* pIn, size_t totalSampleCount, unsigned int bytesPerSample) { - // Special case for 8-bit sample data because it's treated as unsigned. + unsigned int i; + + /* Special case for 8-bit sample data because it's treated as unsigned. */ if (bytesPerSample == 1) { drwav_u8_to_s32(pOut, pIn, totalSampleCount); return; } - // Slightly more optimal implementation for common formats. + /* Slightly more optimal implementation for common formats. */ if (bytesPerSample == 2) { drwav_s16_to_s32(pOut, (const drwav_int16*)pIn, totalSampleCount); return; @@ -3046,22 +3675,22 @@ static void drwav__pcm_to_s32(drwav_int32* pOut, const unsigned char* pIn, size_ return; } if (bytesPerSample == 4) { - for (unsigned int i = 0; i < totalSampleCount; ++i) { - *pOut++ = ((drwav_int32*)pIn)[i]; + for (i = 0; i < totalSampleCount; ++i) { + *pOut++ = ((const drwav_int32*)pIn)[i]; } return; } - // Anything more than 64 bits per sample is not supported. + /* Anything more than 64 bits per sample is not supported. */ if (bytesPerSample > 8) { drwav_zero_memory(pOut, totalSampleCount * sizeof(*pOut)); return; } - // Generic, slow converter. - for (unsigned int i = 0; i < totalSampleCount; ++i) { + /* Generic, slow converter. */ + for (i = 0; i < totalSampleCount; ++i) { drwav_uint64 sample = 0; unsigned int shift = (8 - bytesPerSample) * 8; @@ -3076,16 +3705,16 @@ static void drwav__pcm_to_s32(drwav_int32* pOut, const unsigned char* pIn, size_ } } -static void drwav__ieee_to_s32(drwav_int32* pOut, const unsigned char* pIn, size_t totalSampleCount, unsigned short bytesPerSample) +static void drwav__ieee_to_s32(drwav_int32* pOut, const unsigned char* pIn, size_t totalSampleCount, unsigned int bytesPerSample) { if (bytesPerSample == 4) { - drwav_f32_to_s32(pOut, (float*)pIn, totalSampleCount); + drwav_f32_to_s32(pOut, (const float*)pIn, totalSampleCount); return; } else if (bytesPerSample == 8) { - drwav_f64_to_s32(pOut, (double*)pIn, totalSampleCount); + drwav_f64_to_s32(pOut, (const double*)pIn, totalSampleCount); return; } else { - // Only supporting 32- and 64-bit float. Output silence in all other cases. Contributions welcome for 16-bit float. + /* Only supporting 32- and 64-bit float. Output silence in all other cases. Contributions welcome for 16-bit float. */ drwav_zero_memory(pOut, totalSampleCount * sizeof(*pOut)); return; } @@ -3094,24 +3723,29 @@ static void drwav__ieee_to_s32(drwav_int32* pOut, const unsigned char* pIn, size drwav_uint64 drwav_read_s32__pcm(drwav* pWav, drwav_uint64 samplesToRead, drwav_int32* pBufferOut) { - // Fast path. - if (pWav->translatedFormatTag == DR_WAVE_FORMAT_PCM && pWav->bytesPerSample == 4) { + drwav_uint64 totalSamplesRead; + unsigned char sampleData[4096]; + drwav_uint32 bytesPerSample; + + /* Fast path. */ + if (pWav->translatedFormatTag == DR_WAVE_FORMAT_PCM && pWav->bitsPerSample == 32) { return drwav_read(pWav, samplesToRead, pBufferOut); } - - if (pWav->bytesPerSample == 0) { + + bytesPerSample = drwav_get_bytes_per_sample(pWav); + if (bytesPerSample == 0) { return 0; } - drwav_uint64 totalSamplesRead = 0; - unsigned char sampleData[4096]; + totalSamplesRead = 0; + while (samplesToRead > 0) { - drwav_uint64 samplesRead = drwav_read(pWav, drwav_min(samplesToRead, sizeof(sampleData)/pWav->bytesPerSample), sampleData); + drwav_uint64 samplesRead = drwav_read(pWav, drwav_min(samplesToRead, sizeof(sampleData)/bytesPerSample), sampleData); if (samplesRead == 0) { break; } - drwav__pcm_to_s32(pBufferOut, sampleData, (size_t)samplesRead, pWav->bytesPerSample); + drwav__pcm_to_s32(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample); pBufferOut += samplesRead; samplesToRead -= samplesRead; @@ -3123,8 +3757,10 @@ drwav_uint64 drwav_read_s32__pcm(drwav* pWav, drwav_uint64 samplesToRead, drwav_ drwav_uint64 drwav_read_s32__msadpcm(drwav* pWav, drwav_uint64 samplesToRead, drwav_int32* pBufferOut) { - // We're just going to borrow the implementation from the drwav_read_s16() since ADPCM is a little bit more complicated than other formats and I don't - // want to duplicate that code. + /* + We're just going to borrow the implementation from the drwav_read_s16() since ADPCM is a little bit more complicated than other formats and I don't + want to duplicate that code. + */ drwav_uint64 totalSamplesRead = 0; drwav_int16 samples16[2048]; while (samplesToRead > 0) { @@ -3133,7 +3769,7 @@ drwav_uint64 drwav_read_s32__msadpcm(drwav* pWav, drwav_uint64 samplesToRead, dr break; } - drwav_s16_to_s32(pBufferOut, samples16, (size_t)samplesRead); // <-- Safe cast because we're clamping to 2048. + drwav_s16_to_s32(pBufferOut, samples16, (size_t)samplesRead); /* <-- Safe cast because we're clamping to 2048. */ pBufferOut += samplesRead; samplesToRead -= samplesRead; @@ -3145,8 +3781,10 @@ drwav_uint64 drwav_read_s32__msadpcm(drwav* pWav, drwav_uint64 samplesToRead, dr drwav_uint64 drwav_read_s32__ima(drwav* pWav, drwav_uint64 samplesToRead, drwav_int32* pBufferOut) { - // We're just going to borrow the implementation from the drwav_read_s16() since IMA-ADPCM is a little bit more complicated than other formats and I don't - // want to duplicate that code. + /* + We're just going to borrow the implementation from the drwav_read_s16() since IMA-ADPCM is a little bit more complicated than other formats and I don't + want to duplicate that code. + */ drwav_uint64 totalSamplesRead = 0; drwav_int16 samples16[2048]; while (samplesToRead > 0) { @@ -3155,7 +3793,7 @@ drwav_uint64 drwav_read_s32__ima(drwav* pWav, drwav_uint64 samplesToRead, drwav_ break; } - drwav_s16_to_s32(pBufferOut, samples16, (size_t)samplesRead); // <-- Safe cast because we're clamping to 2048. + drwav_s16_to_s32(pBufferOut, samples16, (size_t)samplesRead); /* <-- Safe cast because we're clamping to 2048. */ pBufferOut += samplesRead; samplesToRead -= samplesRead; @@ -3167,19 +3805,23 @@ drwav_uint64 drwav_read_s32__ima(drwav* pWav, drwav_uint64 samplesToRead, drwav_ drwav_uint64 drwav_read_s32__ieee(drwav* pWav, drwav_uint64 samplesToRead, drwav_int32* pBufferOut) { - if (pWav->bytesPerSample == 0) { + drwav_uint64 totalSamplesRead; + unsigned char sampleData[4096]; + + drwav_uint32 bytesPerSample = drwav_get_bytes_per_sample(pWav); + if (bytesPerSample == 0) { return 0; } - drwav_uint64 totalSamplesRead = 0; - unsigned char sampleData[4096]; + totalSamplesRead = 0; + while (samplesToRead > 0) { - drwav_uint64 samplesRead = drwav_read(pWav, drwav_min(samplesToRead, sizeof(sampleData)/pWav->bytesPerSample), sampleData); + drwav_uint64 samplesRead = drwav_read(pWav, drwav_min(samplesToRead, sizeof(sampleData)/bytesPerSample), sampleData); if (samplesRead == 0) { break; } - drwav__ieee_to_s32(pBufferOut, sampleData, (size_t)samplesRead, pWav->bytesPerSample); + drwav__ieee_to_s32(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample); pBufferOut += samplesRead; samplesToRead -= samplesRead; @@ -3191,14 +3833,18 @@ drwav_uint64 drwav_read_s32__ieee(drwav* pWav, drwav_uint64 samplesToRead, drwav drwav_uint64 drwav_read_s32__alaw(drwav* pWav, drwav_uint64 samplesToRead, drwav_int32* pBufferOut) { - if (pWav->bytesPerSample == 0) { + drwav_uint64 totalSamplesRead; + unsigned char sampleData[4096]; + + drwav_uint32 bytesPerSample = drwav_get_bytes_per_sample(pWav); + if (bytesPerSample == 0) { return 0; } - drwav_uint64 totalSamplesRead = 0; - unsigned char sampleData[4096]; + totalSamplesRead = 0; + while (samplesToRead > 0) { - drwav_uint64 samplesRead = drwav_read(pWav, drwav_min(samplesToRead, sizeof(sampleData)/pWav->bytesPerSample), sampleData); + drwav_uint64 samplesRead = drwav_read(pWav, drwav_min(samplesToRead, sizeof(sampleData)/bytesPerSample), sampleData); if (samplesRead == 0) { break; } @@ -3215,14 +3861,18 @@ drwav_uint64 drwav_read_s32__alaw(drwav* pWav, drwav_uint64 samplesToRead, drwav drwav_uint64 drwav_read_s32__mulaw(drwav* pWav, drwav_uint64 samplesToRead, drwav_int32* pBufferOut) { - if (pWav->bytesPerSample == 0) { + drwav_uint64 totalSamplesRead; + unsigned char sampleData[4096]; + + drwav_uint32 bytesPerSample = drwav_get_bytes_per_sample(pWav); + if (bytesPerSample == 0) { return 0; } - drwav_uint64 totalSamplesRead = 0; - unsigned char sampleData[4096]; + totalSamplesRead = 0; + while (samplesToRead > 0) { - drwav_uint64 samplesRead = drwav_read(pWav, drwav_min(samplesToRead, sizeof(sampleData)/pWav->bytesPerSample), sampleData); + drwav_uint64 samplesRead = drwav_read(pWav, drwav_min(samplesToRead, sizeof(sampleData)/bytesPerSample), sampleData); if (samplesRead == 0) { break; } @@ -3243,9 +3893,9 @@ drwav_uint64 drwav_read_s32(drwav* pWav, drwav_uint64 samplesToRead, drwav_int32 return 0; } - // Don't try to read more samples than can potentially fit in the output buffer. - if (samplesToRead * sizeof(drwav_int32) > SIZE_MAX) { - samplesToRead = SIZE_MAX / sizeof(drwav_int32); + /* Don't try to read more samples than can potentially fit in the output buffer. */ + if (samplesToRead * sizeof(drwav_int32) > DRWAV_SIZE_MAX) { + samplesToRead = DRWAV_SIZE_MAX / sizeof(drwav_int32); } @@ -3276,35 +3926,46 @@ drwav_uint64 drwav_read_s32(drwav* pWav, drwav_uint64 samplesToRead, drwav_int32 return 0; } +drwav_uint64 drwav_read_pcm_frames_s32(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut) +{ + return drwav_read_s32(pWav, framesToRead * pWav->channels, pBufferOut) / pWav->channels; +} + void drwav_u8_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount) { + size_t i; + if (pOut == NULL || pIn == NULL) { return; } - for (size_t i = 0; i < sampleCount; ++i) { + for (i = 0; i < sampleCount; ++i) { *pOut++ = ((int)pIn[i] - 128) << 24; } } void drwav_s16_to_s32(drwav_int32* pOut, const drwav_int16* pIn, size_t sampleCount) { + size_t i; + if (pOut == NULL || pIn == NULL) { return; } - for (size_t i = 0; i < sampleCount; ++i) { + for (i = 0; i < sampleCount; ++i) { *pOut++ = pIn[i] << 16; } } void drwav_s24_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount) { + size_t i; + if (pOut == NULL || pIn == NULL) { return; } - for (size_t i = 0; i < sampleCount; ++i) { + for (i = 0; i < sampleCount; ++i) { unsigned int s0 = pIn[i*3 + 0]; unsigned int s1 = pIn[i*3 + 1]; unsigned int s2 = pIn[i*3 + 2]; @@ -3316,44 +3977,52 @@ void drwav_s24_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCo void drwav_f32_to_s32(drwav_int32* pOut, const float* pIn, size_t sampleCount) { + size_t i; + if (pOut == NULL || pIn == NULL) { return; } - for (size_t i = 0; i < sampleCount; ++i) { + for (i = 0; i < sampleCount; ++i) { *pOut++ = (drwav_int32)(2147483648.0 * pIn[i]); } } void drwav_f64_to_s32(drwav_int32* pOut, const double* pIn, size_t sampleCount) { + size_t i; + if (pOut == NULL || pIn == NULL) { return; } - for (size_t i = 0; i < sampleCount; ++i) { + for (i = 0; i < sampleCount; ++i) { *pOut++ = (drwav_int32)(2147483648.0 * pIn[i]); } } void drwav_alaw_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount) { + size_t i; + if (pOut == NULL || pIn == NULL) { return; } - for (size_t i = 0; i < sampleCount; ++i) { + for (i = 0; i < sampleCount; ++i) { *pOut++ = ((drwav_int32)drwav__alaw_to_s16(pIn[i])) << 16; } } void drwav_mulaw_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount) { + size_t i; + if (pOut == NULL || pIn == NULL) { return; } - for (size_t i= 0; i < sampleCount; ++i) { + for (i= 0; i < sampleCount; ++i) { *pOut++ = ((drwav_int32)drwav__mulaw_to_s16(pIn[i])) << 16; } } @@ -3362,105 +4031,145 @@ void drwav_mulaw_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sample drwav_int16* drwav__read_and_close_s16(drwav* pWav, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount) { + drwav_uint64 sampleDataSize; + drwav_int16* pSampleData; + drwav_uint64 samplesRead; + drwav_assert(pWav != NULL); - drwav_uint64 sampleDataSize = pWav->totalSampleCount * sizeof(drwav_int16); - if (sampleDataSize > SIZE_MAX) { + sampleDataSize = pWav->totalSampleCount * sizeof(drwav_int16); + if (sampleDataSize > DRWAV_SIZE_MAX) { drwav_uninit(pWav); - return NULL; // File's too big. + return NULL; /* File's too big. */ } - drwav_int16* pSampleData = (drwav_int16*)DRWAV_MALLOC((size_t)sampleDataSize); // <-- Safe cast due to the check above. + pSampleData = (drwav_int16*)DRWAV_MALLOC((size_t)sampleDataSize); /* <-- Safe cast due to the check above. */ if (pSampleData == NULL) { drwav_uninit(pWav); - return NULL; // Failed to allocate memory. + return NULL; /* Failed to allocate memory. */ } - drwav_uint64 samplesRead = drwav_read_s16(pWav, (size_t)pWav->totalSampleCount, pSampleData); + samplesRead = drwav_read_s16(pWav, (size_t)pWav->totalSampleCount, pSampleData); if (samplesRead != pWav->totalSampleCount) { DRWAV_FREE(pSampleData); drwav_uninit(pWav); - return NULL; // There was an error reading the samples. + return NULL; /* There was an error reading the samples. */ } drwav_uninit(pWav); - if (sampleRate) *sampleRate = pWav->sampleRate; - if (channels) *channels = pWav->channels; - if (totalSampleCount) *totalSampleCount = pWav->totalSampleCount; + if (sampleRate) { + *sampleRate = pWav->sampleRate; + } + if (channels) { + *channels = pWav->channels; + } + if (totalSampleCount) { + *totalSampleCount = pWav->totalSampleCount; + } + return pSampleData; } float* drwav__read_and_close_f32(drwav* pWav, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount) { + drwav_uint64 sampleDataSize; + float* pSampleData; + drwav_uint64 samplesRead; + drwav_assert(pWav != NULL); - drwav_uint64 sampleDataSize = pWav->totalSampleCount * sizeof(float); - if (sampleDataSize > SIZE_MAX) { + sampleDataSize = pWav->totalSampleCount * sizeof(float); + if (sampleDataSize > DRWAV_SIZE_MAX) { drwav_uninit(pWav); - return NULL; // File's too big. + return NULL; /* File's too big. */ } - float* pSampleData = (float*)DRWAV_MALLOC((size_t)sampleDataSize); // <-- Safe cast due to the check above. + pSampleData = (float*)DRWAV_MALLOC((size_t)sampleDataSize); /* <-- Safe cast due to the check above. */ if (pSampleData == NULL) { drwav_uninit(pWav); - return NULL; // Failed to allocate memory. + return NULL; /* Failed to allocate memory. */ } - drwav_uint64 samplesRead = drwav_read_f32(pWav, (size_t)pWav->totalSampleCount, pSampleData); + samplesRead = drwav_read_f32(pWav, (size_t)pWav->totalSampleCount, pSampleData); if (samplesRead != pWav->totalSampleCount) { DRWAV_FREE(pSampleData); drwav_uninit(pWav); - return NULL; // There was an error reading the samples. + return NULL; /* There was an error reading the samples. */ } drwav_uninit(pWav); - if (sampleRate) *sampleRate = pWav->sampleRate; - if (channels) *channels = pWav->channels; - if (totalSampleCount) *totalSampleCount = pWav->totalSampleCount; + if (sampleRate) { + *sampleRate = pWav->sampleRate; + } + if (channels) { + *channels = pWav->channels; + } + if (totalSampleCount) { + *totalSampleCount = pWav->totalSampleCount; + } + return pSampleData; } drwav_int32* drwav__read_and_close_s32(drwav* pWav, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount) { + drwav_uint64 sampleDataSize; + drwav_int32* pSampleData; + drwav_uint64 samplesRead; + drwav_assert(pWav != NULL); - drwav_uint64 sampleDataSize = pWav->totalSampleCount * sizeof(drwav_int32); - if (sampleDataSize > SIZE_MAX) { + sampleDataSize = pWav->totalSampleCount * sizeof(drwav_int32); + if (sampleDataSize > DRWAV_SIZE_MAX) { drwav_uninit(pWav); - return NULL; // File's too big. + return NULL; /* File's too big. */ } - drwav_int32* pSampleData = (drwav_int32*)DRWAV_MALLOC((size_t)sampleDataSize); // <-- Safe cast due to the check above. + pSampleData = (drwav_int32*)DRWAV_MALLOC((size_t)sampleDataSize); /* <-- Safe cast due to the check above. */ if (pSampleData == NULL) { drwav_uninit(pWav); - return NULL; // Failed to allocate memory. + return NULL; /* Failed to allocate memory. */ } - drwav_uint64 samplesRead = drwav_read_s32(pWav, (size_t)pWav->totalSampleCount, pSampleData); + samplesRead = drwav_read_s32(pWav, (size_t)pWav->totalSampleCount, pSampleData); if (samplesRead != pWav->totalSampleCount) { DRWAV_FREE(pSampleData); drwav_uninit(pWav); - return NULL; // There was an error reading the samples. + return NULL; /* There was an error reading the samples. */ } drwav_uninit(pWav); - if (sampleRate) *sampleRate = pWav->sampleRate; - if (channels) *channels = pWav->channels; - if (totalSampleCount) *totalSampleCount = pWav->totalSampleCount; + if (sampleRate) { + *sampleRate = pWav->sampleRate; + } + if (channels) { + *channels = pWav->channels; + } + if (totalSampleCount) { + *totalSampleCount = pWav->totalSampleCount; + } + return pSampleData; } drwav_int16* drwav_open_and_read_s16(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount) { - if (sampleRate) *sampleRate = 0; - if (channels) *channels = 0; - if (totalSampleCount) *totalSampleCount = 0; - drwav wav; + + if (channels) { + *channels = 0; + } + if (sampleRate) { + *sampleRate = 0; + } + if (totalSampleCount) { + *totalSampleCount = 0; + } + if (!drwav_init(&wav, onRead, onSeek, pUserData)) { return NULL; } @@ -3468,13 +4177,55 @@ drwav_int16* drwav_open_and_read_s16(drwav_read_proc onRead, drwav_seek_proc onS return drwav__read_and_close_s16(&wav, channels, sampleRate, totalSampleCount); } -float* drwav_open_and_read_f32(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount) +drwav_int16* drwav_open_and_read_pcm_frames_s16(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut) { - if (sampleRate) *sampleRate = 0; - if (channels) *channels = 0; - if (totalSampleCount) *totalSampleCount = 0; + unsigned int channels; + unsigned int sampleRate; + drwav_uint64 totalSampleCount; + drwav_int16* result; + + if (channelsOut) { + *channelsOut = 0; + } + if (sampleRateOut) { + *sampleRateOut = 0; + } + if (totalFrameCountOut) { + *totalFrameCountOut = 0; + } + result = drwav_open_and_read_s16(onRead, onSeek, pUserData, &channels, &sampleRate, &totalSampleCount); + if (result == NULL) { + return NULL; + } + + if (channelsOut) { + *channelsOut = channels; + } + if (sampleRateOut) { + *sampleRateOut = sampleRate; + } + if (totalFrameCountOut) { + *totalFrameCountOut = totalSampleCount / channels; + } + + return result; +} + +float* drwav_open_and_read_f32(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount) +{ drwav wav; + + if (sampleRate) { + *sampleRate = 0; + } + if (channels) { + *channels = 0; + } + if (totalSampleCount) { + *totalSampleCount = 0; + } + if (!drwav_init(&wav, onRead, onSeek, pUserData)) { return NULL; } @@ -3482,13 +4233,55 @@ float* drwav_open_and_read_f32(drwav_read_proc onRead, drwav_seek_proc onSeek, v return drwav__read_and_close_f32(&wav, channels, sampleRate, totalSampleCount); } -drwav_int32* drwav_open_and_read_s32(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount) +float* drwav_open_and_read_pcm_frames_f32(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut) { - if (sampleRate) *sampleRate = 0; - if (channels) *channels = 0; - if (totalSampleCount) *totalSampleCount = 0; + unsigned int channels; + unsigned int sampleRate; + drwav_uint64 totalSampleCount; + float* result; + + if (channelsOut) { + *channelsOut = 0; + } + if (sampleRateOut) { + *sampleRateOut = 0; + } + if (totalFrameCountOut) { + *totalFrameCountOut = 0; + } + + result = drwav_open_and_read_f32(onRead, onSeek, pUserData, &channels, &sampleRate, &totalSampleCount); + if (result == NULL) { + return NULL; + } + + if (channelsOut) { + *channelsOut = channels; + } + if (sampleRateOut) { + *sampleRateOut = sampleRate; + } + if (totalFrameCountOut) { + *totalFrameCountOut = totalSampleCount / channels; + } + + return result; +} +drwav_int32* drwav_open_and_read_s32(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount) +{ drwav wav; + + if (sampleRate) { + *sampleRate = 0; + } + if (channels) { + *channels = 0; + } + if (totalSampleCount) { + *totalSampleCount = 0; + } + if (!drwav_init(&wav, onRead, onSeek, pUserData)) { return NULL; } @@ -3496,14 +4289,56 @@ drwav_int32* drwav_open_and_read_s32(drwav_read_proc onRead, drwav_seek_proc onS return drwav__read_and_close_s32(&wav, channels, sampleRate, totalSampleCount); } -#ifndef DR_WAV_NO_STDIO -drwav_int16* drwav_open_and_read_file_s16(const char* filename, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount) +drwav_int32* drwav_open_and_read_pcm_frames_s32(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut) { - if (sampleRate) *sampleRate = 0; - if (channels) *channels = 0; - if (totalSampleCount) *totalSampleCount = 0; + unsigned int channels; + unsigned int sampleRate; + drwav_uint64 totalSampleCount; + drwav_int32* result; + + if (channelsOut) { + *channelsOut = 0; + } + if (sampleRateOut) { + *sampleRateOut = 0; + } + if (totalFrameCountOut) { + *totalFrameCountOut = 0; + } + + result = drwav_open_and_read_s32(onRead, onSeek, pUserData, &channels, &sampleRate, &totalSampleCount); + if (result == NULL) { + return NULL; + } + + if (channelsOut) { + *channelsOut = channels; + } + if (sampleRateOut) { + *sampleRateOut = sampleRate; + } + if (totalFrameCountOut) { + *totalFrameCountOut = totalSampleCount / channels; + } + + return result; +} +#ifndef DR_WAV_NO_STDIO +drwav_int16* drwav_open_file_and_read_s16(const char* filename, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount) +{ drwav wav; + + if (sampleRate) { + *sampleRate = 0; + } + if (channels) { + *channels = 0; + } + if (totalSampleCount) { + *totalSampleCount = 0; + } + if (!drwav_init_file(&wav, filename)) { return NULL; } @@ -3511,13 +4346,55 @@ drwav_int16* drwav_open_and_read_file_s16(const char* filename, unsigned int* ch return drwav__read_and_close_s16(&wav, channels, sampleRate, totalSampleCount); } -float* drwav_open_and_read_file_f32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount) +drwav_int16* drwav_open_file_and_read_pcm_frames_s16(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut) { - if (sampleRate) *sampleRate = 0; - if (channels) *channels = 0; - if (totalSampleCount) *totalSampleCount = 0; + unsigned int channels; + unsigned int sampleRate; + drwav_uint64 totalSampleCount; + drwav_int16* result; + + if (channelsOut) { + *channelsOut = 0; + } + if (sampleRateOut) { + *sampleRateOut = 0; + } + if (totalFrameCountOut) { + *totalFrameCountOut = 0; + } + + result = drwav_open_file_and_read_s16(filename, &channels, &sampleRate, &totalSampleCount); + if (result == NULL) { + return NULL; + } + + if (channelsOut) { + *channelsOut = channels; + } + if (sampleRateOut) { + *sampleRateOut = sampleRate; + } + if (totalFrameCountOut) { + *totalFrameCountOut = totalSampleCount / channels; + } + return result; +} + +float* drwav_open_file_and_read_f32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount) +{ drwav wav; + + if (sampleRate) { + *sampleRate = 0; + } + if (channels) { + *channels = 0; + } + if (totalSampleCount) { + *totalSampleCount = 0; + } + if (!drwav_init_file(&wav, filename)) { return NULL; } @@ -3525,28 +4402,112 @@ float* drwav_open_and_read_file_f32(const char* filename, unsigned int* channels return drwav__read_and_close_f32(&wav, channels, sampleRate, totalSampleCount); } -drwav_int32* drwav_open_and_read_file_s32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount) +float* drwav_open_file_and_read_pcm_frames_f32(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut) { - if (sampleRate) *sampleRate = 0; - if (channels) *channels = 0; - if (totalSampleCount) *totalSampleCount = 0; + unsigned int channels; + unsigned int sampleRate; + drwav_uint64 totalSampleCount; + float* result; + + if (channelsOut) { + *channelsOut = 0; + } + if (sampleRateOut) { + *sampleRateOut = 0; + } + if (totalFrameCountOut) { + *totalFrameCountOut = 0; + } + + result = drwav_open_file_and_read_f32(filename, &channels, &sampleRate, &totalSampleCount); + if (result == NULL) { + return NULL; + } + if (channelsOut) { + *channelsOut = channels; + } + if (sampleRateOut) { + *sampleRateOut = sampleRate; + } + if (totalFrameCountOut) { + *totalFrameCountOut = totalSampleCount / channels; + } + + return result; +} + +drwav_int32* drwav_open_file_and_read_s32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount) +{ drwav wav; + + if (sampleRate) { + *sampleRate = 0; + } + if (channels) { + *channels = 0; + } + if (totalSampleCount) { + *totalSampleCount = 0; + } + if (!drwav_init_file(&wav, filename)) { return NULL; } return drwav__read_and_close_s32(&wav, channels, sampleRate, totalSampleCount); } -#endif -drwav_int16* drwav_open_and_read_memory_s16(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount) +drwav_int32* drwav_open_file_and_read_pcm_frames_s32(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut) { - if (sampleRate) *sampleRate = 0; - if (channels) *channels = 0; - if (totalSampleCount) *totalSampleCount = 0; + unsigned int channels; + unsigned int sampleRate; + drwav_uint64 totalSampleCount; + drwav_int32* result; + + if (channelsOut) { + *channelsOut = 0; + } + if (sampleRateOut) { + *sampleRateOut = 0; + } + if (totalFrameCountOut) { + *totalFrameCountOut = 0; + } + + result = drwav_open_file_and_read_s32(filename, &channels, &sampleRate, &totalSampleCount); + if (result == NULL) { + return NULL; + } + + if (channelsOut) { + *channelsOut = channels; + } + if (sampleRateOut) { + *sampleRateOut = sampleRate; + } + if (totalFrameCountOut) { + *totalFrameCountOut = totalSampleCount / channels; + } + + return result; +} +#endif +drwav_int16* drwav_open_memory_and_read_s16(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount) +{ drwav wav; + + if (sampleRate) { + *sampleRate = 0; + } + if (channels) { + *channels = 0; + } + if (totalSampleCount) { + *totalSampleCount = 0; + } + if (!drwav_init_memory(&wav, data, dataSize)) { return NULL; } @@ -3554,13 +4515,55 @@ drwav_int16* drwav_open_and_read_memory_s16(const void* data, size_t dataSize, u return drwav__read_and_close_s16(&wav, channels, sampleRate, totalSampleCount); } -float* drwav_open_and_read_memory_f32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount) +drwav_int16* drwav_open_memory_and_read_pcm_frames_s16(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut) { - if (sampleRate) *sampleRate = 0; - if (channels) *channels = 0; - if (totalSampleCount) *totalSampleCount = 0; + unsigned int channels; + unsigned int sampleRate; + drwav_uint64 totalSampleCount; + drwav_int16* result; + + if (channelsOut) { + *channelsOut = 0; + } + if (sampleRateOut) { + *sampleRateOut = 0; + } + if (totalFrameCountOut) { + *totalFrameCountOut = 0; + } + + result = drwav_open_memory_and_read_s16(data, dataSize, &channels, &sampleRate, &totalSampleCount); + if (result == NULL) { + return NULL; + } + + if (channelsOut) { + *channelsOut = channels; + } + if (sampleRateOut) { + *sampleRateOut = sampleRate; + } + if (totalFrameCountOut) { + *totalFrameCountOut = totalSampleCount / channels; + } + + return result; +} +float* drwav_open_memory_and_read_f32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount) +{ drwav wav; + + if (sampleRate) { + *sampleRate = 0; + } + if (channels) { + *channels = 0; + } + if (totalSampleCount) { + *totalSampleCount = 0; + } + if (!drwav_init_memory(&wav, data, dataSize)) { return NULL; } @@ -3568,20 +4571,97 @@ float* drwav_open_and_read_memory_f32(const void* data, size_t dataSize, unsigne return drwav__read_and_close_f32(&wav, channels, sampleRate, totalSampleCount); } -drwav_int32* drwav_open_and_read_memory_s32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount) +float* drwav_open_memory_and_read_pcm_frames_f32(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut) { - if (sampleRate) *sampleRate = 0; - if (channels) *channels = 0; - if (totalSampleCount) *totalSampleCount = 0; + unsigned int channels; + unsigned int sampleRate; + drwav_uint64 totalSampleCount; + float* result; + + if (channelsOut) { + *channelsOut = 0; + } + if (sampleRateOut) { + *sampleRateOut = 0; + } + if (totalFrameCountOut) { + *totalFrameCountOut = 0; + } + + result = drwav_open_memory_and_read_f32(data, dataSize, &channels, &sampleRate, &totalSampleCount); + if (result == NULL) { + return NULL; + } + + if (channelsOut) { + *channelsOut = channels; + } + if (sampleRateOut) { + *sampleRateOut = sampleRate; + } + if (totalFrameCountOut) { + *totalFrameCountOut = totalSampleCount / channels; + } + + return result; +} +drwav_int32* drwav_open_memory_and_read_s32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount) +{ drwav wav; + + if (sampleRate) { + *sampleRate = 0; + } + if (channels) { + *channels = 0; + } + if (totalSampleCount) { + *totalSampleCount = 0; + } + if (!drwav_init_memory(&wav, data, dataSize)) { return NULL; } return drwav__read_and_close_s32(&wav, channels, sampleRate, totalSampleCount); } -#endif //DR_WAV_NO_CONVERSION_API + +drwav_int32* drwav_open_memory_and_read_pcm_frames_s32(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut) +{ + unsigned int channels; + unsigned int sampleRate; + drwav_uint64 totalSampleCount; + drwav_int32* result; + + if (channelsOut) { + *channelsOut = 0; + } + if (sampleRateOut) { + *sampleRateOut = 0; + } + if (totalFrameCountOut) { + *totalFrameCountOut = 0; + } + + result = drwav_open_memory_and_read_s32(data, dataSize, &channels, &sampleRate, &totalSampleCount); + if (result == NULL) { + return NULL; + } + + if (channelsOut) { + *channelsOut = channels; + } + if (sampleRateOut) { + *sampleRateOut = sampleRate; + } + if (totalFrameCountOut) { + *totalFrameCountOut = totalSampleCount / channels; + } + + return result; +} +#endif /* DR_WAV_NO_CONVERSION_API */ void drwav_free(void* pDataReturnedByOpenAndRead) @@ -3589,136 +4669,203 @@ void drwav_free(void* pDataReturnedByOpenAndRead) DRWAV_FREE(pDataReturnedByOpenAndRead); } -#endif //DR_WAV_IMPLEMENTATION - - -// REVISION HISTORY -// -// v0.8.1 - 2018-06-29 -// - Add support for sequential writing APIs. -// - Disable seeking in write mode. -// - Fix bugs with Wave64. -// - Fix typos. -// -// v0.8 - 2018-04-27 -// - Bug fix. -// - Start using major.minor.revision versioning. -// -// v0.7f - 2018-02-05 -// - Restrict ADPCM formats to a maximum of 2 channels. -// -// v0.7e - 2018-02-02 -// - Fix a crash. -// -// v0.7d - 2018-02-01 -// - Fix a crash. -// -// v0.7c - 2018-02-01 -// - Set drwav.bytesPerSample to 0 for all compressed formats. -// - Fix a crash when reading 16-bit floating point WAV files. In this case dr_wav will output silence for -// all format conversion reading APIs (*_s16, *_s32, *_f32 APIs). -// - Fix some divide-by-zero errors. -// -// v0.7b - 2018-01-22 -// - Fix errors with seeking of compressed formats. -// - Fix compilation error when DR_WAV_NO_CONVERSION_API -// -// v0.7a - 2017-11-17 -// - Fix some GCC warnings. -// -// v0.7 - 2017-11-04 -// - Add writing APIs. -// -// v0.6 - 2017-08-16 -// - API CHANGE: Rename dr_* types to drwav_*. -// - Add support for custom implementations of malloc(), realloc(), etc. -// - Add support for Microsoft ADPCM. -// - Add support for IMA ADPCM (DVI, format code 0x11). -// - Optimizations to drwav_read_s16(). -// - Bug fixes. -// -// v0.5g - 2017-07-16 -// - Change underlying type for booleans to unsigned. -// -// v0.5f - 2017-04-04 -// - Fix a minor bug with drwav_open_and_read_s16() and family. -// -// v0.5e - 2016-12-29 -// - Added support for reading samples as signed 16-bit integers. Use the _s16() family of APIs for this. -// - Minor fixes to documentation. -// -// v0.5d - 2016-12-28 -// - Use drwav_int*/drwav_uint* sized types to improve compiler support. -// -// v0.5c - 2016-11-11 -// - Properly handle JUNK chunks that come before the FMT chunk. -// -// v0.5b - 2016-10-23 -// - A minor change to drwav_bool8 and drwav_bool32 types. -// -// v0.5a - 2016-10-11 -// - Fixed a bug with drwav_open_and_read() and family due to incorrect argument ordering. -// - Improve A-law and mu-law efficiency. -// -// v0.5 - 2016-09-29 -// - API CHANGE. Swap the order of "channels" and "sampleRate" parameters in drwav_open_and_read*(). Rationale for this is to -// keep it consistent with dr_audio and dr_flac. -// -// v0.4b - 2016-09-18 -// - Fixed a typo in documentation. -// -// v0.4a - 2016-09-18 -// - Fixed a typo. -// - Change date format to ISO 8601 (YYYY-MM-DD) -// -// v0.4 - 2016-07-13 -// - API CHANGE. Make onSeek consistent with dr_flac. -// - API CHANGE. Rename drwav_seek() to drwav_seek_to_sample() for clarity and consistency with dr_flac. -// - Added support for Sony Wave64. -// -// v0.3a - 2016-05-28 -// - API CHANGE. Return drwav_bool32 instead of int in onSeek callback. -// - Fixed a memory leak. -// -// v0.3 - 2016-05-22 -// - Lots of API changes for consistency. -// -// v0.2a - 2016-05-16 -// - Fixed Linux/GCC build. -// -// v0.2 - 2016-05-11 -// - Added support for reading data as signed 32-bit PCM for consistency with dr_flac. -// -// v0.1a - 2016-05-07 -// - Fixed a bug in drwav_open_file() where the file handle would not be closed if the loader failed to initialize. -// -// v0.1 - 2016-05-04 -// - Initial versioned release. +#endif /* DR_WAV_IMPLEMENTATION */ + + +/* +REVISION HISTORY +================ +v0.9.1 - 2019-05-05 + - Add support for C89. + - Change license to choice of public domain or MIT-0. + +v0.9.0 - 2018-12-16 + - API CHANGE: Add new reading APIs for reading by PCM frames instead of samples. Old APIs have been deprecated and + will be removed in v0.10.0. Deprecated APIs and their replacements: + drwav_read() -> drwav_read_pcm_frames() + drwav_read_s16() -> drwav_read_pcm_frames_s16() + drwav_read_f32() -> drwav_read_pcm_frames_f32() + drwav_read_s32() -> drwav_read_pcm_frames_s32() + drwav_seek_to_sample() -> drwav_seek_to_pcm_frame() + drwav_write() -> drwav_write_pcm_frames() + drwav_open_and_read_s16() -> drwav_open_and_read_pcm_frames_s16() + drwav_open_and_read_f32() -> drwav_open_and_read_pcm_frames_f32() + drwav_open_and_read_s32() -> drwav_open_and_read_pcm_frames_s32() + drwav_open_file_and_read_s16() -> drwav_open_file_and_read_pcm_frames_s16() + drwav_open_file_and_read_f32() -> drwav_open_file_and_read_pcm_frames_f32() + drwav_open_file_and_read_s32() -> drwav_open_file_and_read_pcm_frames_s32() + drwav_open_memory_and_read_s16() -> drwav_open_memory_and_read_pcm_frames_s16() + drwav_open_memory_and_read_f32() -> drwav_open_memory_and_read_pcm_frames_f32() + drwav_open_memory_and_read_s32() -> drwav_open_memory_and_read_pcm_frames_s32() + drwav::totalSampleCount -> drwav::totalPCMFrameCount + - API CHANGE: Rename drwav_open_and_read_file_*() to drwav_open_file_and_read_*(). + - API CHANGE: Rename drwav_open_and_read_memory_*() to drwav_open_memory_and_read_*(). + - Add built-in support for smpl chunks. + - Add support for firing a callback for each chunk in the file at initialization time. + - This is enabled through the drwav_init_ex(), etc. family of APIs. + - Handle invalid FMT chunks more robustly. + +v0.8.5 - 2018-09-11 + - Const correctness. + - Fix a potential stack overflow. + +v0.8.4 - 2018-08-07 + - Improve 64-bit detection. + +v0.8.3 - 2018-08-05 + - Fix C++ build on older versions of GCC. + +v0.8.2 - 2018-08-02 + - Fix some big-endian bugs. + +v0.8.1 - 2018-06-29 + - Add support for sequential writing APIs. + - Disable seeking in write mode. + - Fix bugs with Wave64. + - Fix typos. + +v0.8 - 2018-04-27 + - Bug fix. + - Start using major.minor.revision versioning. + +v0.7f - 2018-02-05 + - Restrict ADPCM formats to a maximum of 2 channels. + +v0.7e - 2018-02-02 + - Fix a crash. + +v0.7d - 2018-02-01 + - Fix a crash. + +v0.7c - 2018-02-01 + - Set drwav.bytesPerSample to 0 for all compressed formats. + - Fix a crash when reading 16-bit floating point WAV files. In this case dr_wav will output silence for + all format conversion reading APIs (*_s16, *_s32, *_f32 APIs). + - Fix some divide-by-zero errors. + +v0.7b - 2018-01-22 + - Fix errors with seeking of compressed formats. + - Fix compilation error when DR_WAV_NO_CONVERSION_API + +v0.7a - 2017-11-17 + - Fix some GCC warnings. + +v0.7 - 2017-11-04 + - Add writing APIs. + +v0.6 - 2017-08-16 + - API CHANGE: Rename dr_* types to drwav_*. + - Add support for custom implementations of malloc(), realloc(), etc. + - Add support for Microsoft ADPCM. + - Add support for IMA ADPCM (DVI, format code 0x11). + - Optimizations to drwav_read_s16(). + - Bug fixes. + +v0.5g - 2017-07-16 + - Change underlying type for booleans to unsigned. + +v0.5f - 2017-04-04 + - Fix a minor bug with drwav_open_and_read_s16() and family. + +v0.5e - 2016-12-29 + - Added support for reading samples as signed 16-bit integers. Use the _s16() family of APIs for this. + - Minor fixes to documentation. + +v0.5d - 2016-12-28 + - Use drwav_int* and drwav_uint* sized types to improve compiler support. + +v0.5c - 2016-11-11 + - Properly handle JUNK chunks that come before the FMT chunk. + +v0.5b - 2016-10-23 + - A minor change to drwav_bool8 and drwav_bool32 types. + +v0.5a - 2016-10-11 + - Fixed a bug with drwav_open_and_read() and family due to incorrect argument ordering. + - Improve A-law and mu-law efficiency. + +v0.5 - 2016-09-29 + - API CHANGE. Swap the order of "channels" and "sampleRate" parameters in drwav_open_and_read*(). Rationale for this is to + keep it consistent with dr_audio and dr_flac. + +v0.4b - 2016-09-18 + - Fixed a typo in documentation. + +v0.4a - 2016-09-18 + - Fixed a typo. + - Change date format to ISO 8601 (YYYY-MM-DD) + +v0.4 - 2016-07-13 + - API CHANGE. Make onSeek consistent with dr_flac. + - API CHANGE. Rename drwav_seek() to drwav_seek_to_sample() for clarity and consistency with dr_flac. + - Added support for Sony Wave64. + +v0.3a - 2016-05-28 + - API CHANGE. Return drwav_bool32 instead of int in onSeek callback. + - Fixed a memory leak. + +v0.3 - 2016-05-22 + - Lots of API changes for consistency. +v0.2a - 2016-05-16 + - Fixed Linux/GCC build. + +v0.2 - 2016-05-11 + - Added support for reading data as signed 32-bit PCM for consistency with dr_flac. + +v0.1a - 2016-05-07 + - Fixed a bug in drwav_open_file() where the file handle would not be closed if the loader failed to initialize. + +v0.1 - 2016-05-04 + - Initial versioned release. +*/ /* +This software is available as a choice of the following licenses. Choose +whichever you prefer. + +=============================================================================== +ALTERNATIVE 1 - Public Domain (www.unlicense.org) +=============================================================================== This is free and unencumbered software released into the public domain. -Anyone is free to copy, modify, publish, use, compile, sell, or -distribute this software, either in source code form or as a compiled -binary, for any purpose, commercial or non-commercial, and by any -means. - -In jurisdictions that recognize copyright laws, the author or authors -of this software dedicate any and all copyright interest in the -software to the public domain. We make this dedication for the benefit -of the public at large and to the detriment of our heirs and -successors. We intend this dedication to be an overt act of -relinquishment in perpetuity of all present and future rights to this -software under copyright law. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR -OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, -ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. + +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to + +=============================================================================== +ALTERNATIVE 2 - MIT No Attribution +=============================================================================== +Copyright 2018 David Reid + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. */ -- cgit v1.2.3 From 9994f16479d4ad20dbe223a6ce2e9f58a15e3cd6 Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 16 May 2019 15:40:28 +0200 Subject: Review build config on web --- src/Makefile | 47 +++++++++++++++++++++++++++++------------------ 1 file changed, 29 insertions(+), 18 deletions(-) (limited to 'src') diff --git a/src/Makefile b/src/Makefile index c50d4279..379b5635 100644 --- a/src/Makefile +++ b/src/Makefile @@ -154,8 +154,8 @@ endif ifeq ($(PLATFORM),PLATFORM_WEB) # Emscripten required variables - EMSDK_PATH = C:/emsdk - EMSCRIPTEN_VERSION ?= 1.38.30 + EMSDK_PATH ?= D:/emsdk + EMSCRIPTEN_VERSION ?= 1.38.31 CLANG_VERSION = e$(EMSCRIPTEN_VERSION)_64bit PYTHON_VERSION = 2.7.13.1_64bit\python-2.7.13.amd64 NODE_VERSION = 8.9.1_64bit @@ -254,21 +254,20 @@ endif # Define compiler flags: -# -O1 defines optimization level -# -g enable debugging -# -s strip unnecessary data from build -# -Wall turns on most, but not all, compiler warnings -# -std=c99 defines C language mode (standard C from 1999 revision) -# -std=gnu99 defines C language mode (GNU C from 1999 revision) -# -Wno-missing-braces ignore invalid warning (GCC bug 53119) -# -D_DEFAULT_SOURCE use with -std=c99 on Linux and PLATFORM_WEB, required for timespec -# -Werror=pointer-arith catch unportable code that does direct arithmetic on void pointers -# -fno-strict-aliasing jar_xm.h does shady stuff (breaks strict aliasing) +# -O1 defines optimization level +# -g include debug information on compilation +# -s strip unnecessary data from build +# -Wall turns on most, but not all, compiler warnings +# -std=c99 defines C language mode (standard C from 1999 revision) +# -std=gnu99 defines C language mode (GNU C from 1999 revision) +# -Wno-missing-braces ignore invalid warning (GCC bug 53119) +# -D_DEFAULT_SOURCE use with -std=c99 on Linux and PLATFORM_WEB, required for timespec +# -Werror=pointer-arith catch unportable code that does direct arithmetic on void pointers +# -fno-strict-aliasing jar_xm.h does shady stuff (breaks strict aliasing) CFLAGS += -O1 -Wall -std=c99 -D_DEFAULT_SOURCE -Wno-missing-braces -Werror=pointer-arith -fno-strict-aliasing -ifeq ($(RAYLIB_BUILD_MODE), DEBUG) +ifeq ($(RAYLIB_BUILD_MODE),DEBUG) CFLAGS += -g - #CC = clang endif # Additional flags for compiler (if desired) @@ -280,12 +279,24 @@ ifeq ($(PLATFORM),PLATFORM_DESKTOP) CFLAGS += -Werror=implicit-function-declaration endif ifeq ($(PLATFORM),PLATFORM_WEB) - # -O2 # if used, also set --memory-init-file 0 - # --memory-init-file 0 # to avoid an external memory initialization code file (.mem) - # -s ALLOW_MEMORY_GROWTH=1 # to allow memory resizing + # -Os # size optimization + # -O2 # optimization level 2, if used, also set --memory-init-file 0 + # -s USE_GLFW=3 # Use glfw3 library (context/input management) + # -s ALLOW_MEMORY_GROWTH=1 # to allow memory resizing -> WARNING: Audio buffers could FAIL! # -s TOTAL_MEMORY=16777216 # to specify heap memory size (default = 16MB) # -s USE_PTHREADS=1 # multithreading support - CFLAGS += -s USE_GLFW=3 -s ASSERTIONS=1 --profiling + # -s WASM=0 # disable Web Assembly, emitted by default + # -s EMTERPRETIFY=1 # enable emscripten code interpreter (very slow) + # -s EMTERPRETIFY_ASYNC=1 # support synchronous loops by emterpreter + # -s FORCE_FILESYSTEM=1 # force filesystem to load/save files data + # -s ASSERTIONS=1 # enable runtime checks for common memory allocation errors (-O1 and above turn it off) + # --profiling # include information for code profiling + # --memory-init-file 0 # to avoid an external memory initialization code file (.mem) + # --preload-file resources # specify a resources folder for data compilation + CFLAGS += -s USE_GLFW=3 + ifeq ($(RAYLIB_BUILD_MODE),DEBUG) + CFLAGS += -s ASSERTIONS=1 --profiling + endif endif ifeq ($(PLATFORM),PLATFORM_ANDROID) # Compiler flags for arquitecture -- cgit v1.2.3 From cf4fde94568f779a5d9afea8a9d712caff774e38 Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 16 May 2019 16:10:52 +0200 Subject: Corrected bug on NEON --- src/external/miniaudio.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/external/miniaudio.h b/src/external/miniaudio.h index 5db50a96..f51a1b68 100644 --- a/src/external/miniaudio.h +++ b/src/external/miniaudio.h @@ -29347,8 +29347,8 @@ static MA_INLINE float32x4_t ma_src_sinc__interpolation_factor__neon(const ma_sr { float32x4_t xabs; int32x4_t ixabs; - float32x4_t a - float32x4_t r + float32x4_t a; + float32x4_t r; int* ixabsv; float lo[4]; float hi[4]; -- cgit v1.2.3 From 97160fd970dec330703a1579b8659942ca04b441 Mon Sep 17 00:00:00 2001 From: Ilya Kolbin Date: Fri, 17 May 2019 17:56:05 +0300 Subject: fixed GLFW compiler flag for OSX --- src/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/Makefile b/src/Makefile index 379b5635..d4197609 100644 --- a/src/Makefile +++ b/src/Makefile @@ -221,7 +221,7 @@ ifeq ($(PLATFORM),PLATFORM_DESKTOP) ifeq ($(PLATFORM_OS),OSX) # OSX default compiler CC = clang - GLFW_CFLAGS = -x objective-c + GLFW_CFLAGS = -ObjC endif ifeq ($(PLATFORM_OS),BSD) # FreeBSD, OpenBSD, NetBSD, DragonFly default compiler -- cgit v1.2.3 From e1ecebfff91bec7621ca180cd92f7a2789e47ee0 Mon Sep 17 00:00:00 2001 From: Ahmad Fatoum Date: Fri, 17 May 2019 20:19:47 +0200 Subject: Revert "fixed GLFW compiler flag for OSX" This reverts #841 commit 97160fd970dec330703a1579b8659942ca04b441. --- src/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/Makefile b/src/Makefile index d4197609..379b5635 100644 --- a/src/Makefile +++ b/src/Makefile @@ -221,7 +221,7 @@ ifeq ($(PLATFORM),PLATFORM_DESKTOP) ifeq ($(PLATFORM_OS),OSX) # OSX default compiler CC = clang - GLFW_CFLAGS = -ObjC + GLFW_CFLAGS = -x objective-c endif ifeq ($(PLATFORM_OS),BSD) # FreeBSD, OpenBSD, NetBSD, DragonFly default compiler -- cgit v1.2.3 From 5ef7beb0c509b61d2ccc913360fea4c446ff4d4c Mon Sep 17 00:00:00 2001 From: Ahmad Fatoum Date: Fri, 17 May 2019 20:24:01 +0200 Subject: Makefile: move -x objective-c option before filename From the Clang documentation[1]: > -x, --language , --language= > Treat subsequent input files as having type Follow the advice. Fixes #840. [1]: https://clang.llvm.org/docs/ClangCommandLineReference.html --- src/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/Makefile b/src/Makefile index 379b5635..24d12ec7 100644 --- a/src/Makefile +++ b/src/Makefile @@ -508,7 +508,7 @@ core.o : core.c raylib.h rlgl.h utils.h raymath.h camera.h gestures.h # Compile rglfw module rglfw.o : rglfw.c - $(CC) -c $< $(CFLAGS) $(GLFW_CFLAGS) $(INCLUDE_PATHS) -D$(PLATFORM) -D$(GRAPHICS) + $(CC) $(CFLAGS) $(GLFW_CFLAGS) -c $< $(INCLUDE_PATHS) -D$(PLATFORM) -D$(GRAPHICS) # Compile shapes module shapes.o : shapes.c raylib.h rlgl.h -- cgit v1.2.3 From e01a381aec92abe76c40711ea6c0873b3a10df0a Mon Sep 17 00:00:00 2001 From: Wilhem Barbier Date: Tue, 14 May 2019 14:06:17 +0200 Subject: Load glTF --- src/models.c | 308 +++++++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 287 insertions(+), 21 deletions(-) (limited to 'src') diff --git a/src/models.c b/src/models.c index bd83e925..c66a7b17 100644 --- a/src/models.c +++ b/src/models.c @@ -60,6 +60,7 @@ #if defined(SUPPORT_FILEFORMAT_GLTF) #define CGLTF_IMPLEMENTATION #include "external/cgltf.h" // glTF file format loading + #include "external/stb_image.h" #endif #if defined(SUPPORT_MESH_GENERATION) @@ -637,7 +638,7 @@ Model LoadModel(const char *fileName) if (IsFileExtension(fileName, ".obj")) model = LoadOBJ(fileName); #endif #if defined(SUPPORT_FILEFORMAT_GLTF) - if (IsFileExtension(fileName, ".gltf")) model = LoadGLTF(fileName); + if (IsFileExtension(fileName, ".gltf") || IsFileExtension(fileName, ".glb")) model = LoadGLTF(fileName); #endif #if defined(SUPPORT_FILEFORMAT_IQM) if (IsFileExtension(fileName, ".iqm")) model = LoadIQM(fileName); @@ -3241,6 +3242,108 @@ static Model LoadIQM(const char *fileName) #endif #if defined(SUPPORT_FILEFORMAT_GLTF) + +const unsigned char base64_table[] = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 62, 0, 0, 0, 63, 52, 53, + 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, + 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, + 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 0, 0, 0, 0, 0, 0, 26, 27, 28, + 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, + 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, + 49, 50, 51 +}; + +int GetSizeBase64(char* input) +{ + int size = 0; + for (int i = 0; input[4*i] != 0; i++) + { + if (input[4*i+3] == '=') + { + if (input[4*i+2] == '=') + { + size += 1; + } + else + { + size += 2; + } + } + else size += 3; + } + return size; +} + +unsigned char* DecodeBase64(char* input, int* size) +{ + *size = 0; + for (int i = 0; input[4*i] != 0; i++) + { + if (input[4*i+3] == '=') + { + if (input[4*i+2] == '=') + { + *size += 1; + } + else + { + *size += 2; + } + } + else *size += 3; + } + + unsigned char* buf = (unsigned char*)RL_MALLOC(*size); + for (int i = 0; i < *size/3; i++) + { + unsigned char a = base64_table[(int)input[4*i]]; + unsigned char b = base64_table[(int)input[4*i+1]]; + unsigned char c = base64_table[(int)input[4*i+2]]; + unsigned char d = base64_table[(int)input[4*i+3]]; + + buf[3*i] = (a << 2) | (b >> 4); + buf[3*i+1] = (b << 4) | (c >> 2); + buf[3*i+2] = (c << 6) | d; + } + + if (*size % 3 == 1) + { + int n = *size/3; + unsigned char a = base64_table[(int)input[4*n]]; + unsigned char b = base64_table[(int)input[4*n+1]]; + buf[*size-1] = (a << 2) | (b >> 4); + } + else if (*size % 3 == 2) + { + int n = *size/3 ; + unsigned char a = base64_table[(int)input[4*n]]; + unsigned char b = base64_table[(int)input[4*n+1]]; + unsigned char c = base64_table[(int)input[4*n+2]]; + buf[*size-2] = (a << 2) | (b >> 4); + buf[*size-1] = (b << 4) | (c >> 2); + } + return buf; +} + +#define LOAD_ACCESSOR(type, nbcomp, acc, dst) \ +{ \ + int n = 0; \ + type* buf = (type*)acc->buffer_view->buffer->data+acc->buffer_view->offset/sizeof(type)+acc->offset/sizeof(type); \ + for (int k = 0; k < acc->count; k++) {\ + for (int l = 0; l < nbcomp; l++) {\ + dst[nbcomp*k+l] = buf[n+l];\ + }\ + n += acc->stride/sizeof(type);\ + }\ +} + + // Load glTF mesh data static Model LoadGLTF(const char *fileName) { @@ -3266,48 +3369,211 @@ static Model LoadGLTF(const char *fileName) // glTF data loading cgltf_options options = { 0 }; - cgltf_data *data; + cgltf_data *data = NULL; cgltf_result result = cgltf_parse(&options, buffer, size, &data); - RL_FREE(buffer); - if (result == cgltf_result_success) { - TraceLog(LOG_INFO, "[%s][%s] Model meshes/materials: %i/%i", (data->file_type == 2)? "glb" : "gltf", data->meshes_count, data->materials_count); + + TraceLog(LOG_INFO, "[%s][%s] Model meshes/materials: %i/%i", fileName, (data->file_type == 2)? "glb" : "gltf", data->meshes_count, data->materials_count); // Read data buffers result = cgltf_load_buffers(&options, data, fileName); + int nb_primitives = 0; + for (int i = 0; i < data->meshes_count; i++) + { + nb_primitives += (int)data->meshes[i].primitives_count; + } + // Process glTF data and map to model - model.meshCount = data->meshes_count; - model.meshes = RL_MALLOC(model.meshCount*sizeof(Mesh)); + model.meshCount = nb_primitives; + model.meshes = RL_CALLOC(model.meshCount, sizeof(Mesh)); + model.materialCount = data->materials_count + 1; + model.materials = RL_MALLOC(model.materialCount * sizeof(Material)); + model.meshMaterial = RL_MALLOC(model.meshCount * sizeof(int)); + + for (int i = 0; i < model.materialCount - 1; i++) + { + + Texture2D texture; + const char* dir_path = GetDirectoryPath(fileName); + Color tint; + if (data->materials[i].pbr_metallic_roughness.base_color_factor) + { + tint.r = (unsigned char)(data->materials[i].pbr_metallic_roughness.base_color_factor[0] * 255.99f); + tint.g = (unsigned char)(data->materials[i].pbr_metallic_roughness.base_color_factor[1] * 255.99f); + tint.b = (unsigned char)(data->materials[i].pbr_metallic_roughness.base_color_factor[2] * 255.99f); + tint.a = (unsigned char)(data->materials[i].pbr_metallic_roughness.base_color_factor[3] * 255.99f); + } + else + { + tint.r = 1.f; + tint.g = 1.f; + tint.b = 1.f; + tint.a = 1.f; + } + if (data->materials[i].pbr_metallic_roughness.base_color_texture.texture) + { + + cgltf_image* img = data->materials[i].pbr_metallic_roughness.base_color_texture.texture->image; + if (img->uri) { + if (strlen(img->uri) > 5 && img->uri[0] == 'd' + && img->uri[1] == 'a' + && img->uri[2] == 't' + && img->uri[3] == 'a' + && img->uri[4] == ':') + { + // data URI + // format: data:;base64, + + // find the comma + int i = 0; + while (img->uri[i] != ',' && img->uri[i] != 0) + { + i++; + } + if (img->uri[i] == 0) { + TraceLog(LOG_WARNING, "[%s] Invalid data URI", fileName); + } + else + { + int size; + unsigned char* data = DecodeBase64(img->uri+i+1, &size); + int w, h; + unsigned char* raw = stbi_load_from_memory(data, size, &w, &h, NULL, 4); + Image image = LoadImagePro(raw, w, h, UNCOMPRESSED_R8G8B8A8); + ImageColorTint(&image, tint); + texture = LoadTextureFromImage(image); + UnloadImage(image); + } + } + else + { + char* texture_name = img->uri; + char* texture_path = RL_MALLOC(strlen(dir_path) + strlen(texture_name) + 2); + strcpy(texture_path, dir_path); + strcat(texture_path, "/"); + strcat(texture_path, texture_name); + + Image image = LoadImage(texture_path); + ImageColorTint(&image, tint); + texture = LoadTextureFromImage(image); + UnloadImage(image); + } + } + else if (img->buffer_view) + { + unsigned char* data = RL_MALLOC(img->buffer_view->size); + int n = img->buffer_view->offset; + int stride = img->buffer_view->stride ? img->buffer_view->stride : 1; + for (int i = 0; i < img->buffer_view->size; i++) + { + data[i] = ((unsigned char*)img->buffer_view->buffer->data)[n]; + n += stride; + } + + int w, h; + unsigned char* raw = stbi_load_from_memory(data, img->buffer_view->size, &w, &h, NULL, 4); + Image image = LoadImagePro(raw, w, h, UNCOMPRESSED_R8G8B8A8); + ImageColorTint(&image, tint); + texture = LoadTextureFromImage(image); + UnloadImage(image); + } + else + { + Image image = LoadImageEx(&tint, 1, 1); + texture = LoadTextureFromImage(image); + UnloadImage(image); + } + model.materials[i] = LoadMaterialDefault(); + model.materials[i].maps[MAP_DIFFUSE].texture = texture; + } + } + model.materials[model.materialCount-1] = LoadMaterialDefault(); + + int prim_index = 0; - for (int i = 0; i < model.meshCount; i++) + for (int i = 0; i < data->meshes_count; i++) { - // NOTE: Only support meshes defined by triangle primitives - //if (data->meshes[i].primitives[n].type == cgltf_primitive_type_triangles) + + for (int p = 0; p < data->meshes[i].primitives_count; p++) { - // data.meshes[i].name not used - model.meshes[i].vertexCount = data->meshes[i].primitives_count*3; - model.meshes[i].triangleCount = data->meshes[i].primitives_count; - // data.meshes[i].weights not used (array of weights to be applied to the Morph Targets) - model.meshes[i].vertices = RL_MALLOC(sizeof(float)*model.meshes[i].vertexCount*3); // Default vertex positions - model.meshes[i].normals = RL_MALLOC(sizeof(float)*model.meshes[i].vertexCount*3); // Default vertex normals - model.meshes[i].texcoords = RL_MALLOC(sizeof(float)*model.meshes[i].vertexCount*2); // Default vertex texcoords + for (int j = 0; j < data->meshes[i].primitives[p].attributes_count; j++) + { + if (data->meshes[i].primitives[p].attributes[j].type == cgltf_attribute_type_position) + { + cgltf_accessor* acc = data->meshes[i].primitives[p].attributes[j].data; + model.meshes[prim_index].vertexCount = acc->count; + model.meshes[prim_index].vertices = RL_MALLOC(sizeof(float)*model.meshes[prim_index].vertexCount*3); + + LOAD_ACCESSOR(float, 3, acc, model.meshes[prim_index].vertices) + } + else if (data->meshes[i].primitives[p].attributes[j].type == cgltf_attribute_type_normal) + { + cgltf_accessor* acc = data->meshes[i].primitives[p].attributes[j].data; + model.meshes[prim_index].normals = RL_MALLOC(sizeof(float)*acc->count*3); + + LOAD_ACCESSOR(float, 3, acc, model.meshes[prim_index].normals) + + } + else if (data->meshes[i].primitives[p].attributes[j].type == cgltf_attribute_type_texcoord) + { + cgltf_accessor* acc = data->meshes[i].primitives[p].attributes[j].data; + if (acc->component_type == cgltf_component_type_r_32f) + { + model.meshes[prim_index].texcoords = RL_MALLOC(sizeof(float)*acc->count*2); + LOAD_ACCESSOR(float, 2, acc, model.meshes[prim_index].texcoords) + } + else + { + // TODO: support normalized unsigned byte/unsigned short texture coordinates + TraceLog(LOG_WARNING, "[%s] Texture coordinates must be float", fileName); + } + } + } - model.meshes[i].indices = RL_MALLOC(sizeof(unsigned short)*model.meshes[i].triangleCount*3); + cgltf_accessor* acc = data->meshes[i].primitives[p].indices; + if (acc) + { + if (acc->component_type == cgltf_component_type_r_16u) + { + model.meshes[prim_index].triangleCount = acc->count / 3; + model.meshes[prim_index].indices = RL_MALLOC(sizeof(unsigned short)*model.meshes[prim_index].triangleCount*3); + LOAD_ACCESSOR(unsigned short, 1, acc, model.meshes[prim_index].indices) + } + else + { + // TODO: support unsigned byte/unsigned int + TraceLog(LOG_WARNING, "[%s] Indices must be unsigned short", fileName); + } + } + else + { + // unindexed mesh + model.meshes[prim_index].triangleCount = model.meshes[prim_index].vertexCount / 3; + } + if (data->meshes[i].primitives[p].material) + { + // compute the offset + model.meshMaterial[prim_index] = data->meshes[i].primitives[p].material - data->materials; + } + else + { + model.meshMaterial[prim_index] = model.materialCount - 1;; + } + prim_index++; } } - // NOTE: data.buffers[] should be loaded to model.meshes and data.images[] should be loaded to model.materials - // Use buffers[n].uri and images[n].uri... or use cgltf_load_buffers(&options, data, fileName); - cgltf_free(data); } else TraceLog(LOG_WARNING, "[%s] glTF data could not be loaded", fileName); + RL_FREE(buffer); + return model; } #endif -- cgit v1.2.3 From 371abb0a26e0c5068351db8d17a64acace89a36a Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 20 May 2019 11:13:38 +0200 Subject: Review glTF implementation formatting Added comments for the future --- src/models.c | 239 ++++++++++++++++++++++++++++++----------------------------- 1 file changed, 123 insertions(+), 116 deletions(-) (limited to 'src') diff --git a/src/models.c b/src/models.c index c66a7b17..9dddb757 100644 --- a/src/models.c +++ b/src/models.c @@ -60,7 +60,7 @@ #if defined(SUPPORT_FILEFORMAT_GLTF) #define CGLTF_IMPLEMENTATION #include "external/cgltf.h" // glTF file format loading - #include "external/stb_image.h" + #include "external/stb_image.h" // glTF texture images loading #endif #if defined(SUPPORT_MESH_GENERATION) @@ -3243,7 +3243,7 @@ static Model LoadIQM(const char *fileName) #if defined(SUPPORT_FILEFORMAT_GLTF) -const unsigned char base64_table[] = { +static const unsigned char base64Table[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -3259,94 +3259,102 @@ const unsigned char base64_table[] = { 49, 50, 51 }; -int GetSizeBase64(char* input) +static int GetSizeBase64(char *input) { int size = 0; + for (int i = 0; input[4*i] != 0; i++) { - if (input[4*i+3] == '=') + if (input[4*i + 3] == '=') { - if (input[4*i+2] == '=') - { - size += 1; - } - else - { - size += 2; - } + if (input[4*i + 2] == '=') size += 1; + else size += 2; } else size += 3; } + return size; } -unsigned char* DecodeBase64(char* input, int* size) +static unsigned char *DecodeBase64(char *input, int *size) { *size = 0; for (int i = 0; input[4*i] != 0; i++) { - if (input[4*i+3] == '=') + if (input[4*i + 3] == '=') { - if (input[4*i+2] == '=') - { - *size += 1; - } - else - { - *size += 2; - } + if (input[4*i + 2] == '=') *size += 1; + else *size += 2; } else *size += 3; } - unsigned char* buf = (unsigned char*)RL_MALLOC(*size); + unsigned char *buf = (unsigned char *)RL_MALLOC(*size); for (int i = 0; i < *size/3; i++) { - unsigned char a = base64_table[(int)input[4*i]]; - unsigned char b = base64_table[(int)input[4*i+1]]; - unsigned char c = base64_table[(int)input[4*i+2]]; - unsigned char d = base64_table[(int)input[4*i+3]]; + unsigned char a = base64Table[(int)input[4*i]]; + unsigned char b = base64Table[(int)input[4*i + 1]]; + unsigned char c = base64Table[(int)input[4*i + 2]]; + unsigned char d = base64Table[(int)input[4*i + 3]]; buf[3*i] = (a << 2) | (b >> 4); - buf[3*i+1] = (b << 4) | (c >> 2); - buf[3*i+2] = (c << 6) | d; + buf[3*i + 1] = (b << 4) | (c >> 2); + buf[3*i + 2] = (c << 6) | d; } - if (*size % 3 == 1) + if (*size%3 == 1) { int n = *size/3; - unsigned char a = base64_table[(int)input[4*n]]; - unsigned char b = base64_table[(int)input[4*n+1]]; - buf[*size-1] = (a << 2) | (b >> 4); + unsigned char a = base64Table[(int)input[4*n]]; + unsigned char b = base64Table[(int)input[4*n + 1]]; + buf[*size - 1] = (a << 2) | (b >> 4); } - else if (*size % 3 == 2) + else if (*size%3 == 2) { - int n = *size/3 ; - unsigned char a = base64_table[(int)input[4*n]]; - unsigned char b = base64_table[(int)input[4*n+1]]; - unsigned char c = base64_table[(int)input[4*n+2]]; - buf[*size-2] = (a << 2) | (b >> 4); - buf[*size-1] = (b << 4) | (c >> 2); + int n = *size/3; + unsigned char a = base64Table[(int)input[4*n]]; + unsigned char b = base64Table[(int)input[4*n + 1]]; + unsigned char c = base64Table[(int)input[4*n + 2]]; + buf[*size - 2] = (a << 2) | (b >> 4); + buf[*size - 1] = (b << 4) | (c >> 2); } return buf; } -#define LOAD_ACCESSOR(type, nbcomp, acc, dst) \ -{ \ - int n = 0; \ - type* buf = (type*)acc->buffer_view->buffer->data+acc->buffer_view->offset/sizeof(type)+acc->offset/sizeof(type); \ - for (int k = 0; k < acc->count; k++) {\ - for (int l = 0; l < nbcomp; l++) {\ - dst[nbcomp*k+l] = buf[n+l];\ - }\ - n += acc->stride/sizeof(type);\ - }\ -} - - // Load glTF mesh data static Model LoadGLTF(const char *fileName) { + /*********************************************************************************** + + Function implemented by Wilhem Barbier (@wbrbr) + + Features: + - Supports .gltf and .glb files + - Supports embedded (base64) or external textures + - Loads the albedo/diffuse texture (other maps could be added) + - Supports multiple mesh per model and multiple primitives per model + + Some restrictions (not exhaustive): + - Triangle-only meshes + - Not supported node hierarchies or transforms + - Only loads the diffuse texture... but not too hard to support other maps (normal, roughness/metalness...) + - Only supports unsigned short indices (no byte/unsigned int) + - Only supports float for texture coordinates (no byte/unsigned short) + + *************************************************************************************/ + + #define LOAD_ACCESSOR(type, nbcomp, acc, dst) \ + { \ + int n = 0; \ + type* buf = (type*)acc->buffer_view->buffer->data+acc->buffer_view->offset/sizeof(type)+acc->offset/sizeof(type); \ + for (int k = 0; k < acc->count; k++) {\ + for (int l = 0; l < nbcomp; l++) {\ + dst[nbcomp*k+l] = buf[n+l];\ + }\ + n += acc->stride/sizeof(type);\ + }\ + } + Model model = { 0 }; // glTF file loading @@ -3374,20 +3382,17 @@ static Model LoadGLTF(const char *fileName) if (result == cgltf_result_success) { - TraceLog(LOG_INFO, "[%s][%s] Model meshes/materials: %i/%i", fileName, (data->file_type == 2)? "glb" : "gltf", data->meshes_count, data->materials_count); // Read data buffers result = cgltf_load_buffers(&options, data, fileName); - int nb_primitives = 0; - for (int i = 0; i < data->meshes_count; i++) - { - nb_primitives += (int)data->meshes[i].primitives_count; - } + int primitivesCount = 0; + + for (int i = 0; i < data->meshes_count; i++) primitivesCount += (int)data->meshes[i].primitives_count; // Process glTF data and map to model - model.meshCount = nb_primitives; + model.meshCount = primitivesCount; model.meshes = RL_CALLOC(model.meshCount, sizeof(Mesh)); model.materialCount = data->materials_count + 1; model.materials = RL_MALLOC(model.materialCount * sizeof(Material)); @@ -3395,10 +3400,10 @@ static Model LoadGLTF(const char *fileName) for (int i = 0; i < model.materialCount - 1; i++) { - - Texture2D texture; - const char* dir_path = GetDirectoryPath(fileName); - Color tint; + Color tint = WHITE; + Texture2D texture = { 0 }; + const char *texPath = GetDirectoryPath(fileName); + if (data->materials[i].pbr_metallic_roughness.base_color_factor) { tint.r = (unsigned char)(data->materials[i].pbr_metallic_roughness.base_color_factor[0] * 255.99f); @@ -3413,35 +3418,34 @@ static Model LoadGLTF(const char *fileName) tint.b = 1.f; tint.a = 1.f; } + if (data->materials[i].pbr_metallic_roughness.base_color_texture.texture) { - cgltf_image* img = data->materials[i].pbr_metallic_roughness.base_color_texture.texture->image; - if (img->uri) { - if (strlen(img->uri) > 5 && img->uri[0] == 'd' - && img->uri[1] == 'a' - && img->uri[2] == 't' - && img->uri[3] == 'a' - && img->uri[4] == ':') + + if (img->uri) + { + if ((strlen(img->uri) > 5) && + (img->uri[0] == 'd') && + (img->uri[1] == 'a') && + (img->uri[2] == 't') && + (img->uri[3] == 'a') && + (img->uri[4] == ':')) { - // data URI - // format: data:;base64, + // Data URI + // Format: data:;base64, - // find the comma + // Find the comma int i = 0; - while (img->uri[i] != ',' && img->uri[i] != 0) - { - i++; - } - if (img->uri[i] == 0) { - TraceLog(LOG_WARNING, "[%s] Invalid data URI", fileName); - } + while ((img->uri[i] != ',') && (img->uri[i] != 0)) i++; + + if (img->uri[i] == 0) TraceLog(LOG_WARNING, "[%s] Invalid data URI", fileName); else { int size; - unsigned char* data = DecodeBase64(img->uri+i+1, &size); + unsigned char *data = DecodeBase64(img->uri+i+1, &size); int w, h; - unsigned char* raw = stbi_load_from_memory(data, size, &w, &h, NULL, 4); + unsigned char *raw = stbi_load_from_memory(data, size, &w, &h, NULL, 4); Image image = LoadImagePro(raw, w, h, UNCOMPRESSED_R8G8B8A8); ImageColorTint(&image, tint); texture = LoadTextureFromImage(image); @@ -3450,13 +3454,13 @@ static Model LoadGLTF(const char *fileName) } else { - char* texture_name = img->uri; - char* texture_path = RL_MALLOC(strlen(dir_path) + strlen(texture_name) + 2); - strcpy(texture_path, dir_path); - strcat(texture_path, "/"); - strcat(texture_path, texture_name); + char *textureName = img->uri; + char *texturePath = RL_MALLOC(strlen(texPath) + strlen(textureName) + 2); + strcpy(texturePath, texPath); + strcat(texturePath, "/"); + strcat(texturePath, textureName); - Image image = LoadImage(texture_path); + Image image = LoadImage(texturePath); ImageColorTint(&image, tint); texture = LoadTextureFromImage(image); UnloadImage(image); @@ -3464,9 +3468,10 @@ static Model LoadGLTF(const char *fileName) } else if (img->buffer_view) { - unsigned char* data = RL_MALLOC(img->buffer_view->size); + unsigned char *data = RL_MALLOC(img->buffer_view->size); int n = img->buffer_view->offset; int stride = img->buffer_view->stride ? img->buffer_view->stride : 1; + for (int i = 0; i < img->buffer_view->size; i++) { data[i] = ((unsigned char*)img->buffer_view->buffer->data)[n]; @@ -3474,7 +3479,7 @@ static Model LoadGLTF(const char *fileName) } int w, h; - unsigned char* raw = stbi_load_from_memory(data, img->buffer_view->size, &w, &h, NULL, 4); + unsigned char *raw = stbi_load_from_memory(data, img->buffer_view->size, &w, &h, NULL, 4); Image image = LoadImagePro(raw, w, h, UNCOMPRESSED_R8G8B8A8); ImageColorTint(&image, tint); texture = LoadTextureFromImage(image); @@ -3486,45 +3491,45 @@ static Model LoadGLTF(const char *fileName) texture = LoadTextureFromImage(image); UnloadImage(image); } + model.materials[i] = LoadMaterialDefault(); model.materials[i].maps[MAP_DIFFUSE].texture = texture; } } - model.materials[model.materialCount-1] = LoadMaterialDefault(); + + model.materials[model.materialCount - 1] = LoadMaterialDefault(); - int prim_index = 0; + int primitiveIndex = 0; for (int i = 0; i < data->meshes_count; i++) { - for (int p = 0; p < data->meshes[i].primitives_count; p++) { - for (int j = 0; j < data->meshes[i].primitives[p].attributes_count; j++) { if (data->meshes[i].primitives[p].attributes[j].type == cgltf_attribute_type_position) { - cgltf_accessor* acc = data->meshes[i].primitives[p].attributes[j].data; - model.meshes[prim_index].vertexCount = acc->count; - model.meshes[prim_index].vertices = RL_MALLOC(sizeof(float)*model.meshes[prim_index].vertexCount*3); + cgltf_accessor *acc = data->meshes[i].primitives[p].attributes[j].data; + model.meshes[primitiveIndex].vertexCount = acc->count; + model.meshes[primitiveIndex].vertices = RL_MALLOC(sizeof(float)*model.meshes[primitiveIndex].vertexCount*3); - LOAD_ACCESSOR(float, 3, acc, model.meshes[prim_index].vertices) + LOAD_ACCESSOR(float, 3, acc, model.meshes[primitiveIndex].vertices) } else if (data->meshes[i].primitives[p].attributes[j].type == cgltf_attribute_type_normal) { - cgltf_accessor* acc = data->meshes[i].primitives[p].attributes[j].data; - model.meshes[prim_index].normals = RL_MALLOC(sizeof(float)*acc->count*3); - - LOAD_ACCESSOR(float, 3, acc, model.meshes[prim_index].normals) + cgltf_accessor *acc = data->meshes[i].primitives[p].attributes[j].data; + model.meshes[primitiveIndex].normals = RL_MALLOC(sizeof(float)*acc->count*3); + LOAD_ACCESSOR(float, 3, acc, model.meshes[primitiveIndex].normals) } else if (data->meshes[i].primitives[p].attributes[j].type == cgltf_attribute_type_texcoord) { - cgltf_accessor* acc = data->meshes[i].primitives[p].attributes[j].data; + cgltf_accessor *acc = data->meshes[i].primitives[p].attributes[j].data; + if (acc->component_type == cgltf_component_type_r_32f) { - model.meshes[prim_index].texcoords = RL_MALLOC(sizeof(float)*acc->count*2); - LOAD_ACCESSOR(float, 2, acc, model.meshes[prim_index].texcoords) + model.meshes[primitiveIndex].texcoords = RL_MALLOC(sizeof(float)*acc->count*2); + LOAD_ACCESSOR(float, 2, acc, model.meshes[primitiveIndex].texcoords) } else { @@ -3534,14 +3539,15 @@ static Model LoadGLTF(const char *fileName) } } - cgltf_accessor* acc = data->meshes[i].primitives[p].indices; + cgltf_accessor *acc = data->meshes[i].primitives[p].indices; + if (acc) { if (acc->component_type == cgltf_component_type_r_16u) { - model.meshes[prim_index].triangleCount = acc->count / 3; - model.meshes[prim_index].indices = RL_MALLOC(sizeof(unsigned short)*model.meshes[prim_index].triangleCount*3); - LOAD_ACCESSOR(unsigned short, 1, acc, model.meshes[prim_index].indices) + model.meshes[primitiveIndex].triangleCount = acc->count/3; + model.meshes[primitiveIndex].indices = RL_MALLOC(sizeof(unsigned short)*model.meshes[primitiveIndex].triangleCount*3); + LOAD_ACCESSOR(unsigned short, 1, acc, model.meshes[primitiveIndex].indices) } else { @@ -3551,20 +3557,21 @@ static Model LoadGLTF(const char *fileName) } else { - // unindexed mesh - model.meshes[prim_index].triangleCount = model.meshes[prim_index].vertexCount / 3; + // Unindexed mesh + model.meshes[primitiveIndex].triangleCount = model.meshes[primitiveIndex].vertexCount/3; } if (data->meshes[i].primitives[p].material) { - // compute the offset - model.meshMaterial[prim_index] = data->meshes[i].primitives[p].material - data->materials; + // Compute the offset + model.meshMaterial[primitiveIndex] = data->meshes[i].primitives[p].material - data->materials; } else { - model.meshMaterial[prim_index] = model.materialCount - 1;; + model.meshMaterial[primitiveIndex] = model.materialCount - 1;; } - prim_index++; + + primitiveIndex++; } } -- cgit v1.2.3 From a43a7980a30a52462956b23f2473e8ef8f38d1fb Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 20 May 2019 11:21:55 +0200 Subject: Update raylib version to 2.5 --- src/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index a467899f..879ac220 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -3,7 +3,7 @@ project(raylib C) include(GNUInstallDirs) list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/../cmake") -set(PROJECT_VERSION 2.0.0) +set(PROJECT_VERSION 2.5.0) set(API_VERSION 2) include("CMakeOptions.txt") -- cgit v1.2.3 From 72ab65277b0050635bfcde0b7ff471358e563659 Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 20 May 2019 16:37:44 +0200 Subject: Avoid some warnings --- src/physac.h | 19 ++----------------- 1 file changed, 2 insertions(+), 17 deletions(-) (limited to 'src') diff --git a/src/physac.h b/src/physac.h index 374aa4bc..42cb0198 100644 --- a/src/physac.h +++ b/src/physac.h @@ -323,8 +323,6 @@ static void InitTimer(void); static uint64_t GetTimeCount(void); // Get hi-res MONOTONIC time measure in mseconds static double GetCurrentTime(void); // Get current time measure in milliseconds -static int GetRandomNumber(int min, int max); // Returns a random number between min and max (both included) - // Math functions static Vector2 MathCross(float value, Vector2 vector); // Returns the cross product of a vector and a value static float MathCrossVector2(Vector2 v1, Vector2 v2); // Returns the cross product of two vectors @@ -1771,7 +1769,7 @@ static float FindAxisLeastPenetration(int *faceIndex, PhysicsShape shapeA, Physi int bestIndex = 0; PolygonData dataA = shapeA.vertexData; - PolygonData dataB = shapeB.vertexData; + //PolygonData dataB = shapeB.vertexData; for (int i = 0; i < dataA.vertexCount; i++) { @@ -1921,7 +1919,7 @@ static void InitTimer(void) // Get hi-res MONOTONIC time measure in seconds static uint64_t GetTimeCount(void) { - uint64_t value; + uint64_t value = 0; #if defined(_WIN32) QueryPerformanceCounter((unsigned long long int *) &value); @@ -1946,19 +1944,6 @@ static double GetCurrentTime(void) return (double)(GetTimeCount() - baseTime)/frequency*1000; } -// Returns a random number between min and max (both included) -static int GetRandomNumber(int min, int max) -{ - if (min > max) - { - int tmp = max; - max = min; - min = tmp; - } - - return (rand()%(abs(max - min) + 1) + min); -} - // Returns the cross product of a vector and a value static inline Vector2 MathCross(float value, Vector2 vector) { -- cgit v1.2.3 From 316b6aa1813fb8f5cd56ea135368de73eccc49f6 Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 20 May 2019 17:21:46 +0200 Subject: Reverted change that breaks mouse on web --- src/core.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/core.c b/src/core.c index 5b0ca86c..28283d88 100644 --- a/src/core.c +++ b/src/core.c @@ -2163,11 +2163,12 @@ bool IsMouseButtonPressed(int button) if ((currentMouseState[button] != previousMouseState[button]) && (currentMouseState[button] == 1)) pressed = true; #endif +/* #if defined(PLATFORM_WEB) Vector2 pos = GetTouchPosition(0); if ((pos.x > 0) && (pos.y > 0)) pressed = true; // There was a touch! #endif - +*/ return pressed; } @@ -2239,13 +2240,14 @@ Vector2 GetMousePosition(void) #else position = (Vector2){ (mousePosition.x + mouseOffset.x)*mouseScale.x, (mousePosition.y + mouseOffset.y)*mouseScale.y }; #endif +/* #if defined(PLATFORM_WEB) Vector2 pos = GetTouchPosition(0); // Touch position has priority over mouse position if ((pos.x > 0) && (pos.y > 0)) position = pos; // There was a touch! #endif - +*/ return position; } -- cgit v1.2.3 From 8db2203bccea99aad83de63c00b594cce87d59da Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 21 May 2019 10:16:52 +0200 Subject: Review paths --- src/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/Makefile b/src/Makefile index 24d12ec7..15767561 100644 --- a/src/Makefile +++ b/src/Makefile @@ -154,7 +154,7 @@ endif ifeq ($(PLATFORM),PLATFORM_WEB) # Emscripten required variables - EMSDK_PATH ?= D:/emsdk + EMSDK_PATH ?= C:/emsdk EMSCRIPTEN_VERSION ?= 1.38.31 CLANG_VERSION = e$(EMSCRIPTEN_VERSION)_64bit PYTHON_VERSION = 2.7.13.1_64bit\python-2.7.13.amd64 -- cgit v1.2.3 From 0027868d1f4ba76043e1cdfbb5c172696ad0985b Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 21 May 2019 17:46:52 +0200 Subject: Review Makefiles --- src/Makefile | 7 ------- 1 file changed, 7 deletions(-) (limited to 'src') diff --git a/src/Makefile b/src/Makefile index 15767561..8198e147 100644 --- a/src/Makefile +++ b/src/Makefile @@ -144,13 +144,6 @@ ifeq ($(PLATFORM),PLATFORM_DESKTOP) RAYLIB_PATH = $(realpath $(RAYLIB_PREFIX)) endif endif -# Default path for raylib on Raspberry Pi, if installed in different path, update it! -# TODO: update install: target in src/Makefile for RPI, consider relation to LINUX. -# WARNING: The following is copied from examples/Makefile and is here only for reference. -# Consequences of enabling this are UNKNOWN. Please test and report. -#ifeq ($(PLATFORM),PLATFORM_RPI) -# RAYLIB_PATH ?= /home/pi/raylib -#endif ifeq ($(PLATFORM),PLATFORM_WEB) # Emscripten required variables -- cgit v1.2.3 From b1806f660070ec5b54fe20bd266f8b33b3c3bc13 Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 21 May 2019 20:59:13 +0200 Subject: Add config SUPPORT_SSH_KEYBOARD_RPI Allow to reconfigure stdin to read input keys, this process could lead to undesired effects. Use with care. Disabled by default. --- src/CMakeOptions.txt | 1 + src/config.h | 2 ++ src/core.c | 29 +++++++++++++++++++++-------- 3 files changed, 24 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/CMakeOptions.txt b/src/CMakeOptions.txt index 5e1d9e47..49b83571 100644 --- a/src/CMakeOptions.txt +++ b/src/CMakeOptions.txt @@ -25,6 +25,7 @@ set(OFF ${INCLUDE_EVERYTHING} CACHE INTERNAL "Replace any OFF by default with \$ option(SUPPORT_CAMERA_SYSTEM "Provide camera module (camera.h) with multiple predefined cameras: free, 1st/3rd person, orbital" ON) option(SUPPORT_GESTURES_SYSTEM "Gestures module is included (gestures.h) to support gestures detection: tap, hold, swipe, drag" ON) option(SUPPORT_MOUSE_GESTURES "Mouse gestures are directly mapped like touches and processed by gestures system" ON) +option(SUPPORT_SSH_KEYBOARD_RPI "Reconfigure standard input to receive key inputs, works with SSH connection" OFF) option(SUPPORT_DEFAULT_FONT "Default font is loaded on window initialization to be available for the user to render simple text. If enabled, uses external module functions to load default raylib font (module: text)" ON) option(SUPPORT_SCREEN_CAPTURE "Allow automatic screen capture of current screen pressing F12, defined in KeyCallback()" ON) option(SUPPORT_GIF_RECORDING "Allow automatic gif recording of current screen pressing CTRL+F12, defined in KeyCallback()" ON) diff --git a/src/config.h b/src/config.h index ebe1a7da..dd365f1f 100644 --- a/src/config.h +++ b/src/config.h @@ -43,6 +43,8 @@ // Mouse gestures are directly mapped like touches and processed by gestures system #define SUPPORT_MOUSE_GESTURES 1 // Use busy wait loop for timing sync, if not defined, a high-resolution timer is setup and used +//#define SUPPORT_SSH_KEYBOARD_RPI 1 +//Reconfigure standard input to receive key inputs, works with SSH connection. //#define SUPPORT_BUSY_WAIT_LOOP 1 // Wait for events passively (sleeping while no events) instead of polling them actively every frame //#define SUPPORT_EVENTS_WAITING 1 diff --git a/src/core.c b/src/core.c index 28283d88..d8d85144 100644 --- a/src/core.c +++ b/src/core.c @@ -50,6 +50,11 @@ * #define SUPPORT_TOUCH_AS_MOUSE * Touch input and mouse input are shared. Mouse functions also return touch information. * +* #define SUPPORT_SSH_KEYBOARD_RPI (Raspberry Pi only) +* Reconfigure standard input to receive key inputs, works with SSH connection. +* WARNING: Reconfiguring standard input could lead to undesired effects, like breaking other running processes or +* blocking the device is not restored properly. Use with care. +* * #define SUPPORT_BUSY_WAIT_LOOP * Use busy wait loop for timing sync, if not defined, a high-resolution timer is setup and used * @@ -489,16 +494,19 @@ static EM_BOOL EmscriptenGamepadCallback(int eventType, const EmscriptenGamepadE #endif #if defined(PLATFORM_RPI) +#if defined(SUPPORT_SSH_KEYBOARD_RPI) +static void InitKeyboard(void); // Init raw keyboard system (standard input reading) +static void ProcessKeyboard(void); // Process keyboard events +static void RestoreKeyboard(void); // Restore keyboard system +#endif + static void InitEvdevInput(void); // Evdev inputs initialization static void EventThreadSpawn(char *device); // Identifies a input device and spawns a thread to handle it if needed static void *EventThread(void *arg); // Input device events reading thread -static void InitKeyboard(void); // Init raw keyboard system (standard input reading) -static void ProcessKeyboard(void); // Process keyboard events -static void RestoreKeyboard(void); // Restore keyboard system static void InitGamepad(void); // Init raw gamepad input static void *GamepadThread(void *arg); // Mouse reading thread -#endif +#endif // PLATFORM_RPI #if defined(_WIN32) // NOTE: We include Sleep() function signature here to avoid windows.h inclusion @@ -610,8 +618,10 @@ void InitWindow(int width, int height, const char *title) #if defined(PLATFORM_RPI) // Init raw input system InitEvdevInput(); // Evdev inputs initialization - InitKeyboard(); // Keyboard init InitGamepad(); // Gamepad init +#if defined(SUPPORT_SSH_KEYBOARD_RPI) + InitKeyboard(); // Keyboard init +#endif #endif #if defined(PLATFORM_WEB) @@ -3544,7 +3554,7 @@ static void PollInputEvents(void) } #endif -#if defined(PLATFORM_RPI) +#if defined(PLATFORM_RPI) && defined(SUPPORT_SSH_KEYBOARD_RPI) // NOTE: Keyboard reading could be done using input_event(s) reading or just read from stdin, // we now use both methods inside here. 2nd method is still used for legacy purposes (Allows for input trough SSH console) ProcessKeyboard(); @@ -4181,6 +4191,8 @@ static EM_BOOL EmscriptenGamepadCallback(int eventType, const EmscriptenGamepadE #endif #if defined(PLATFORM_RPI) + +#if defined(SUPPORT_SSH_KEYBOARD_RPI) // Initialize Keyboard system (using standard input) static void InitKeyboard(void) { @@ -4341,6 +4353,7 @@ static void RestoreKeyboard(void) // Reconfigure keyboard to default mode ioctl(STDIN_FILENO, KDSKBMODE, defaultKeyboardMode); } +#endif //SUPPORT_SSH_KEYBOARD_RPI // Initialise user input from evdev(/dev/input/event) this means mouse, keyboard or gamepad devices static void InitEvdevInput(void) @@ -4739,7 +4752,7 @@ static void *EventThread(void *arg) // Gesture update if (gestureUpdate) { -#if defined(SUPPORT_GESTURES_SYSTEM) + #if defined(SUPPORT_GESTURES_SYSTEM) GestureEvent gestureEvent = { 0 }; gestureEvent.pointCount = 0; @@ -4761,7 +4774,7 @@ static void *EventThread(void *arg) gestureEvent.position[3] = touchPosition[3]; ProcessGestureEvent(gestureEvent); -#endif + #endif } } else -- cgit v1.2.3 From be7e56f51e0f9c1c8bf38cab8d451f148b46458b Mon Sep 17 00:00:00 2001 From: Ray Date: Wed, 22 May 2019 10:40:51 +0200 Subject: Move emscripten web shell to src --- src/core.c | 2 +- src/shell.html | 269 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 270 insertions(+), 1 deletion(-) create mode 100644 src/shell.html (limited to 'src') diff --git a/src/core.c b/src/core.c index d8d85144..8dd1090b 100644 --- a/src/core.c +++ b/src/core.c @@ -1640,7 +1640,7 @@ void TakeScreenshot(const char *fileName) #if defined(PLATFORM_WEB) // Download file from MEMFS (emscripten memory filesystem) - // SaveFileFromMEMFSToDisk() function is defined in raylib/templates/web_shel/shell.html + // SaveFileFromMEMFSToDisk() function is defined in raylib/src/shell.html emscripten_run_script(TextFormat("SaveFileFromMEMFSToDisk('%s','%s')", GetFileName(path), GetFileName(path))); #endif diff --git a/src/shell.html b/src/shell.html new file mode 100644 index 00000000..5d8e7e91 --- /dev/null +++ b/src/shell.html @@ -0,0 +1,269 @@ + + + + + + + raylib HTML5 GAME + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+ + + + + + + {{{ SCRIPT }}} + + \ No newline at end of file -- cgit v1.2.3 From a33b0002ee599670a3de5e52f4dcc0e226fb4f61 Mon Sep 17 00:00:00 2001 From: Ray Date: Wed, 22 May 2019 10:55:03 +0200 Subject: Review js formatting for better readability --- src/shell.html | 176 ++++++++++++++++++++++++++++++--------------------------- 1 file changed, 93 insertions(+), 83 deletions(-) (limited to 'src') diff --git a/src/shell.html b/src/shell.html index 5d8e7e91..42cd711a 100644 --- a/src/shell.html +++ b/src/shell.html @@ -173,96 +173,106 @@ jwE50AGjLCVuS8Yt4H7OgZLKK5EKOsLviEWJSL/+0uMi7gLUSBseYwqEbXvSHCec1CJvZPyHCmYQffaB {{{ SCRIPT }}} -- cgit v1.2.3 From 7421ac9e24095a4104285691a7b4fa620629277d Mon Sep 17 00:00:00 2001 From: Ray Date: Wed, 22 May 2019 12:33:28 +0200 Subject: Add code to resume blocked AudioContexts --- src/shell.html | 53 ++++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 48 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/shell.html b/src/shell.html index 42cd711a..a0e730e1 100644 --- a/src/shell.html +++ b/src/shell.html @@ -85,7 +85,8 @@ jwE50AGjLCVuS8Yt4H7OgZLKK5EKOsLviEWJSL/+0uMi7gLUSBseYwqEbXvSHCec1CJvZPyHCmYQffaB margin: 0; margin-top: 20px; margin-left: 20px; - display: inline-block; vertical-align: top; + display: inline-block; + vertical-align: top; -webkit-animation: rotation .8s linear infinite; -moz-animation: rotation .8s linear infinite; -o-animation: rotation .8s linear infinite; @@ -253,8 +254,7 @@ jwE50AGjLCVuS8Yt4H7OgZLKK5EKOsLviEWJSL/+0uMi7gLUSBseYwqEbXvSHCec1CJvZPyHCmYQffaB progressElement.value = null; progressElement.max = null; progressElement.hidden = true; - - if (!text) spinnerElement.hidden = true; + if (!text) spinnerElement.style.display = 'none'; } statusElement.innerHTML = text; @@ -263,7 +263,8 @@ jwE50AGjLCVuS8Yt4H7OgZLKK5EKOsLviEWJSL/+0uMi7gLUSBseYwqEbXvSHCec1CJvZPyHCmYQffaB monitorRunDependencies: function(left) { this.totalDependencies = Math.max(this.totalDependencies, left); Module.setStatus(left ? 'Preparing... (' + (this.totalDependencies-left) + '/' + this.totalDependencies + ')' : 'All downloads complete.'); - } + }, + //noInitialRun: true }; Module.setStatus('Downloading...'); @@ -274,6 +275,48 @@ jwE50AGjLCVuS8Yt4H7OgZLKK5EKOsLviEWJSL/+0uMi7gLUSBseYwqEbXvSHCec1CJvZPyHCmYQffaB Module.setStatus = function(text) { if (text) Module.printErr('[post-exception status] ' + text); }; }; + + + {{{ SCRIPT }}} - \ No newline at end of file + -- cgit v1.2.3 From f45691ca8ddf165b4527097762b38e038c350509 Mon Sep 17 00:00:00 2001 From: Ray Date: Wed, 22 May 2019 16:12:47 +0200 Subject: Rename function to follow javascript notation --- src/core.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/core.c b/src/core.c index 8dd1090b..26a8b2a4 100644 --- a/src/core.c +++ b/src/core.c @@ -1640,8 +1640,8 @@ void TakeScreenshot(const char *fileName) #if defined(PLATFORM_WEB) // Download file from MEMFS (emscripten memory filesystem) - // SaveFileFromMEMFSToDisk() function is defined in raylib/src/shell.html - emscripten_run_script(TextFormat("SaveFileFromMEMFSToDisk('%s','%s')", GetFileName(path), GetFileName(path))); + // saveFileFromMEMFSToDisk() function is defined in raylib/src/shell.html + emscripten_run_script(TextFormat("saveFileFromMEMFSToDisk('%s','%s')", GetFileName(path), GetFileName(path))); #endif TraceLog(LOG_INFO, "Screenshot taken: %s", path); @@ -3610,8 +3610,8 @@ static void KeyCallback(GLFWwindow *window, int key, int scancode, int action, i #if defined(PLATFORM_WEB) // Download file from MEMFS (emscripten memory filesystem) - // SaveFileFromMEMFSToDisk() function is defined in raylib/templates/web_shel/shell.html - emscripten_run_script(TextFormat("SaveFileFromMEMFSToDisk('%s','%s')", TextFormat("screenrec%03i.gif", screenshotCounter - 1), TextFormat("screenrec%03i.gif", screenshotCounter - 1))); + // saveFileFromMEMFSToDisk() function is defined in raylib/templates/web_shel/shell.html + emscripten_run_script(TextFormat("saveFileFromMEMFSToDisk('%s','%s')", TextFormat("screenrec%03i.gif", screenshotCounter - 1), TextFormat("screenrec%03i.gif", screenshotCounter - 1))); #endif TraceLog(LOG_INFO, "End animated GIF recording"); -- cgit v1.2.3 From 31bcaffd7d11c9b24776facb527e20eb5e0030c6 Mon Sep 17 00:00:00 2001 From: Ray Date: Wed, 22 May 2019 16:13:59 +0200 Subject: Added AudioContext Resume/Suspend button --- src/shell.html | 79 +++++++++++++++++++++++++++++++--------------------------- 1 file changed, 42 insertions(+), 37 deletions(-) (limited to 'src') diff --git a/src/shell.html b/src/shell.html index a0e730e1..db823882 100644 --- a/src/shell.html +++ b/src/shell.html @@ -133,7 +133,7 @@ jwE50AGjLCVuS8Yt4H7OgZLKK5EKOsLviEWJSL/+0uMi7gLUSBseYwqEbXvSHCec1CJvZPyHCmYQffaB display: inline-block; float: right; vertical-align: top; - margin-top: 30px; + margin-top: 15px; margin-right: 20px; } @@ -148,6 +148,21 @@ jwE50AGjLCVuS8Yt4H7OgZLKK5EKOsLviEWJSL/+0uMi7gLUSBseYwqEbXvSHCec1CJvZPyHCmYQffaB font-family: 'Lucida Console', Monaco, monospace; outline: none; } + + input[type=button] { + background-color: lightgray; + border: 4px solid darkgray; + color: black; + text-decoration: none; + cursor: pointer; + width: 140px; + height: 50px; + } + + input[type=button]:hover { + background-color: #f5f5f5ff; + border-color: black; + } @@ -158,7 +173,8 @@ jwE50AGjLCVuS8Yt4H7OgZLKK5EKOsLviEWJSL/+0uMi7gLUSBseYwqEbXvSHCec1CJvZPyHCmYQffaB
Downloading...
- + +
@@ -174,7 +190,7 @@ jwE50AGjLCVuS8Yt4H7OgZLKK5EKOsLviEWJSL/+0uMi7gLUSBseYwqEbXvSHCec1CJvZPyHCmYQffaB @@ -276,46 +292,35 @@ jwE50AGjLCVuS8Yt4H7OgZLKK5EKOsLviEWJSL/+0uMi7gLUSBseYwqEbXvSHCec1CJvZPyHCmYQffaB }; - + {{{ SCRIPT }}} -- cgit v1.2.3 From 13a1744ca980a9259f2767b7593c73683cd4e420 Mon Sep 17 00:00:00 2001 From: Wilhem Barbier Date: Wed, 22 May 2019 20:27:19 +0200 Subject: Fix #848 --- src/models.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/models.c b/src/models.c index 9dddb757..a33edfd3 100644 --- a/src/models.c +++ b/src/models.c @@ -3044,7 +3044,7 @@ static Model LoadIQM(const char *fileName) fread(imesh, sizeof(IQMMesh)*iqm.num_meshes, 1, iqmFile); model.meshCount = iqm.num_meshes; - model.meshes = RL_MALLOC(model.meshCount*sizeof(Mesh)); + model.meshes = RL_CALLOC(model.meshCount, sizeof(Mesh)); char name[MESH_NAME_LENGTH]; -- cgit v1.2.3 From 78817305c5165b31a60e954bf8f26acc5a57c1ff Mon Sep 17 00:00:00 2001 From: Wilhem Barbier Date: Wed, 22 May 2019 22:15:32 +0200 Subject: Add rewind for the XM music format --- src/raudio.c | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/raudio.c b/src/raudio.c index e5aef5cf..002d89d7 100644 --- a/src/raudio.c +++ b/src/raudio.c @@ -1314,6 +1314,20 @@ void ResumeMusicStream(Music music) if (music != NULL) ResumeAudioStream(music->stream); } +void jar_xm_reset(jar_xm_context_t* ctx) +{ + // I don't know what I am doing + // this is probably very broken + // but it kinda works + for (uint16_t i = 0; i < jar_xm_get_number_of_channels(ctx); i++) + { + jar_xm_cut_note(&ctx->channels[i]); + } + ctx->current_row = 0; + ctx->current_table_index = 1; + ctx->current_tick = 0; +} + // Stop music playing (close stream) // TODO: To clear a buffer, make sure they have been already processed! void StopMusicStream(Music music) @@ -1335,7 +1349,7 @@ void StopMusicStream(Music music) case MUSIC_AUDIO_MP3: drmp3_seek_to_pcm_frame(&music->ctxMp3, 0); break; #endif #if defined(SUPPORT_FILEFORMAT_XM) - case MUSIC_MODULE_XM: /* TODO: Restart XM context */ break; + case MUSIC_MODULE_XM: jar_xm_reset(music->ctxXm); break; #endif #if defined(SUPPORT_FILEFORMAT_MOD) case MUSIC_MODULE_MOD: jar_mod_seek_start(&music->ctxMod); break; -- cgit v1.2.3 From dec604bd71dccb04a768c33b15cecb573644c10a Mon Sep 17 00:00:00 2001 From: Wilhem Barbier Date: Thu, 23 May 2019 16:40:15 +0200 Subject: Move jar_xm_reset to jar_xm.h --- src/external/jar_xm.h | 17 ++++++++++++++++- src/raudio.c | 14 -------------- 2 files changed, 16 insertions(+), 15 deletions(-) (limited to 'src') diff --git a/src/external/jar_xm.h b/src/external/jar_xm.h index c8c9e3c9..36b774d2 100644 --- a/src/external/jar_xm.h +++ b/src/external/jar_xm.h @@ -1925,7 +1925,6 @@ static void jar_xm_handle_note_and_instrument(jar_xm_context_t* ctx, jar_xm_chan case 33: /* Xxy: Extra stuff */ switch(s->effect_param >> 4) { - case 1: /* X1y: Extra fine portamento up */ if(s->effect_param & 0x0F) { ch->extra_fine_portamento_up_param = s->effect_param & 0x0F; @@ -2660,6 +2659,22 @@ int jar_xm_create_context_from_file(jar_xm_context_t** ctx, uint32_t rate, const return 0; } +// not part of the original library +void jar_xm_reset(jar_xm_context_t* ctx) +{ + // I don't know what I am doing + // this is probably very broken + // but it kinda works + for (uint16_t i = 0; i < jar_xm_get_number_of_channels(ctx); i++) + { + jar_xm_cut_note(&ctx->channels[i]); + } + ctx->current_row = 0; + ctx->current_table_index = 1; + ctx->current_tick = 0; +} + + #endif//end of JAR_XM_IMPLEMENTATION //------------------------------------------------------------------------------- diff --git a/src/raudio.c b/src/raudio.c index 002d89d7..6ac0110c 100644 --- a/src/raudio.c +++ b/src/raudio.c @@ -1314,20 +1314,6 @@ void ResumeMusicStream(Music music) if (music != NULL) ResumeAudioStream(music->stream); } -void jar_xm_reset(jar_xm_context_t* ctx) -{ - // I don't know what I am doing - // this is probably very broken - // but it kinda works - for (uint16_t i = 0; i < jar_xm_get_number_of_channels(ctx); i++) - { - jar_xm_cut_note(&ctx->channels[i]); - } - ctx->current_row = 0; - ctx->current_table_index = 1; - ctx->current_tick = 0; -} - // Stop music playing (close stream) // TODO: To clear a buffer, make sure they have been already processed! void StopMusicStream(Music music) -- cgit v1.2.3 From d4487bcfa7484632b16cd0107ad8efbacbb6e8af Mon Sep 17 00:00:00 2001 From: flashback-fx Date: Fri, 24 May 2019 19:07:59 +0000 Subject: Use tgmath.h and float constants in easings.h --- src/easings.h | 180 +++++++++++++++++++++++++++++----------------------------- 1 file changed, 90 insertions(+), 90 deletions(-) (limited to 'src') diff --git a/src/easings.h b/src/easings.h index 892ce352..c7ee5649 100644 --- a/src/easings.h +++ b/src/easings.h @@ -1,7 +1,7 @@ /******************************************************************************************* * * raylib easings (header only file) -* +* * Useful easing functions for values animation * * This header uses: @@ -32,31 +32,31 @@ * * Robert Penner License * --------------------------------------------------------------------------------- -* Open source under the BSD License. +* Open source under the BSD License. * * Copyright (c) 2001 Robert Penner. All rights reserved. * -* Redistribution and use in source and binary forms, with or without modification, +* 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, +* - 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 +* - 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 author nor the names of contributors may be used -* to endorse or promote products derived from this software without specific +* - Neither the name of the author nor the names of 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 +* 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. * --------------------------------------------------------------------------------- * @@ -90,7 +90,7 @@ #define EASEDEF extern #endif -#include // Required for: sin(), cos(), sqrt(), pow() +#include // Required for: sin(), cos(), sqrt(), pow() #ifndef PI #define PI 3.14159265358979323846f //Required as PI is not always defined in math.h @@ -107,153 +107,153 @@ EASEDEF float EaseLinearOut(float t, float b, float c, float d) { return (c*t/d EASEDEF float EaseLinearInOut(float t,float b, float c, float d) { return (c*t/d + b); } // Sine Easing functions -EASEDEF float EaseSineIn(float t, float b, float c, float d) { return (-c*cos(t/d*(PI/2)) + c + b); } -EASEDEF float EaseSineOut(float t, float b, float c, float d) { return (c*sin(t/d*(PI/2)) + b); } -EASEDEF float EaseSineInOut(float t, float b, float c, float d) { return (-c/2*(cos(PI*t/d) - 1) + b); } +EASEDEF float EaseSineIn(float t, float b, float c, float d) { return (-c*cos(t/d*(PI/2.0f)) + c + b); } +EASEDEF float EaseSineOut(float t, float b, float c, float d) { return (c*sin(t/d*(PI/2.0f)) + b); } +EASEDEF float EaseSineInOut(float t, float b, float c, float d) { return (-c/2.0f*(cos(PI*t/d) - 1.0f) + b); } // Circular Easing functions -EASEDEF float EaseCircIn(float t, float b, float c, float d) { t /= d; return (-c*(sqrt(1 - t*t) - 1) + b); } -EASEDEF float EaseCircOut(float t, float b, float c, float d) { t = t/d - 1; return (c*sqrt(1 - t*t) + b); } -EASEDEF float EaseCircInOut(float t, float b, float c, float d) +EASEDEF float EaseCircIn(float t, float b, float c, float d) { t /= d; return (-c*(sqrt(1.0f - t*t) - 1.0f) + b); } +EASEDEF float EaseCircOut(float t, float b, float c, float d) { t = t/d - 1.0f; return (c*sqrt(1.0f - t*t) + b); } +EASEDEF float EaseCircInOut(float t, float b, float c, float d) { - if ((t/=d/2) < 1) return (-c/2*(sqrt(1 - t*t) - 1) + b); - t -= 2; return (c/2*(sqrt(1 - t*t) + 1) + b); + if ((t/=d/2.0f) < 1.0f) return (-c/2.0f*(sqrt(1.0f - t*t) - 1.0f) + b); + t -= 2.0f; return (c/2.0f*(sqrt(1.0f - t*t) + 1.0f) + b); } // Cubic Easing functions EASEDEF float EaseCubicIn(float t, float b, float c, float d) { t /= d; return (c*t*t*t + b); } -EASEDEF float EaseCubicOut(float t, float b, float c, float d) { t = t/d-1; return (c*(t*t*t + 1) + b); } -EASEDEF float EaseCubicInOut(float t, float b, float c, float d) -{ - if ((t/=d/2) < 1) return (c/2*t*t*t + b); - t -= 2; return (c/2*(t*t*t + 2) + b); +EASEDEF float EaseCubicOut(float t, float b, float c, float d) { t = t/d - 1.0f; return (c*(t*t*t + 1.0f) + b); } +EASEDEF float EaseCubicInOut(float t, float b, float c, float d) +{ + if ((t/=d/2.0f) < 1.0f) return (c/2.0f*t*t*t + b); + t -= 2.0f; return (c/2.0f*(t*t*t + 2.0f) + b); } // Quadratic Easing functions EASEDEF float EaseQuadIn(float t, float b, float c, float d) { t /= d; return (c*t*t + b); } -EASEDEF float EaseQuadOut(float t, float b, float c, float d) { t /= d; return (-c*t*(t - 2) + b); } -EASEDEF float EaseQuadInOut(float t, float b, float c, float d) +EASEDEF float EaseQuadOut(float t, float b, float c, float d) { t /= d; return (-c*t*(t - 2.0f) + b); } +EASEDEF float EaseQuadInOut(float t, float b, float c, float d) { if ((t/=d/2) < 1) return (((c/2)*(t*t)) + b); - t--; return (-c/2*(((t - 2)*t) - 1) + b); + return (-c/2.0f*(((t - 1.0f)*(t - 3.0f)) - 1.0f) + b); } // Exponential Easing functions -EASEDEF float EaseExpoIn(float t, float b, float c, float d) { return (t == 0) ? b : (c*pow(2, 10*(t/d - 1)) + b); } -EASEDEF float EaseExpoOut(float t, float b, float c, float d) { return (t == d) ? (b + c) : (c*(-pow(2, -10*t/d) + 1) + b); } -EASEDEF float EaseExpoInOut(float t, float b, float c, float d) +EASEDEF float EaseExpoIn(float t, float b, float c, float d) { return (t == 0.0f) ? b : (c*pow(2.0f, 10.0f*(t/d - 1.0f)) + b); } +EASEDEF float EaseExpoOut(float t, float b, float c, float d) { return (t == d) ? (b + c) : (c*(-pow(2.0f, -10.0f*t/d) + 1.0f) + b); } +EASEDEF float EaseExpoInOut(float t, float b, float c, float d) { - if (t == 0) return b; + if (t == 0.0f) return b; if (t == d) return (b + c); - if ((t/=d/2) < 1) return (c/2*pow(2, 10*(t - 1)) + b); - - return (c/2*(-pow(2, -10*--t) + 2) + b); + if ((t/=d/2.0f) < 1.0f) return (c/2.0f*pow(2.0f, 10.0f*(t - 1.0f)) + b); + + return (c/2.0f*(-pow(2.0f, -10.0f*(t - 1.0f)) + 2.0f) + b); } // Back Easing functions -EASEDEF float EaseBackIn(float t, float b, float c, float d) +EASEDEF float EaseBackIn(float t, float b, float c, float d) { float s = 1.70158f; float postFix = t/=d; - return (c*(postFix)*t*((s + 1)*t - s) + b); + return (c*(postFix)*t*((s + 1.0f)*t - s) + b); } EASEDEF float EaseBackOut(float t, float b, float c, float d) -{ +{ float s = 1.70158f; - t = t/d - 1; - return (c*(t*t*((s + 1)*t + s) + 1) + b); + t = t/d - 1.0f; + return (c*(t*t*((s + 1.0f)*t + s) + 1.0f) + b); } EASEDEF float EaseBackInOut(float t, float b, float c, float d) { float s = 1.70158f; - if ((t/=d/2) < 1) + if ((t/=d/2.0f) < 1.0f) { s *= 1.525f; - return (c/2*(t*t*((s + 1)*t - s)) + b); + return (c/2.0f*(t*t*((s + 1.0f)*t - s)) + b); } - - float postFix = t-=2; + + float postFix = t-=2.0f; s *= 1.525f; - return (c/2*((postFix)*t*((s + 1)*t + s) + 2) + b); + return (c/2.0f*((postFix)*t*((s + 1.0f)*t + s) + 2.0f) + b); } // Bounce Easing functions -EASEDEF float EaseBounceOut(float t, float b, float c, float d) +EASEDEF float EaseBounceOut(float t, float b, float c, float d) { - if ((t/=d) < (1/2.75f)) + if ((t/=d) < (1.0f/2.75f)) { return (c*(7.5625f*t*t) + b); - } - else if (t < (2/2.75f)) + } + else if (t < (2.0f/2.75f)) { float postFix = t-=(1.5f/2.75f); return (c*(7.5625f*(postFix)*t + 0.75f) + b); - } - else if (t < (2.5/2.75)) + } + else if (t < (2.5/2.75)) { float postFix = t-=(2.25f/2.75f); return (c*(7.5625f*(postFix)*t + 0.9375f) + b); - } - else + } + else { float postFix = t-=(2.625f/2.75f); return (c*(7.5625f*(postFix)*t + 0.984375f) + b); } } -EASEDEF float EaseBounceIn(float t, float b, float c, float d) { return (c - EaseBounceOut(d-t, 0, c, d) + b); } -EASEDEF float EaseBounceInOut(float t, float b, float c, float d) +EASEDEF float EaseBounceIn(float t, float b, float c, float d) { return (c - EaseBounceOut(d - t, 0.0f, c, d) + b); } +EASEDEF float EaseBounceInOut(float t, float b, float c, float d) { - if (t < d/2) return (EaseBounceIn(t*2, 0, c, d)*0.5f + b); - else return (EaseBounceOut(t*2-d, 0, c, d)*0.5f + c*0.5f + b); + if (t < d/2.0f) return (EaseBounceIn(t*2.0f, 0.0f, c, d)*0.5f + b); + else return (EaseBounceOut(t*2.0f - d, 0.0f, c, d)*0.5f + c*0.5f + b); } // Elastic Easing functions -EASEDEF float EaseElasticIn(float t, float b, float c, float d) +EASEDEF float EaseElasticIn(float t, float b, float c, float d) { - if (t == 0) return b; - if ((t/=d) == 1) return (b + c); - + if (t == 0.0f) return b; + if ((t/=d) == 1.0f) return (b + c); + float p = d*0.3f; - float a = c; - float s = p/4; - float postFix = a*pow(2, 10*(t-=1)); - - return (-(postFix*sin((t*d-s)*(2*PI)/p )) + b); + float a = c; + float s = p/4.0f; + float postFix = a*pow(2.0f, 10.0f*(t-=1.0f)); + + return (-(postFix*sin((t*d-s)*(2.0f*PI)/p )) + b); } EASEDEF float EaseElasticOut(float t, float b, float c, float d) { - if (t == 0) return b; - if ((t/=d) == 1) return (b + c); - + if (t == 0.0f) return b; + if ((t/=d) == 1.0f) return (b + c); + float p = d*0.3f; - float a = c; - float s = p/4; - - return (a*pow(2,-10*t)*sin((t*d-s)*(2*PI)/p) + c + b); + float a = c; + float s = p/4.0f; + + return (a*pow(2.0f,-10.0f*t)*sin((t*d-s)*(2.0f*PI)/p) + c + b); } EASEDEF float EaseElasticInOut(float t, float b, float c, float d) { - if (t == 0) return b; - if ((t/=d/2) == 2) return (b + c); - + if (t == 0.0f) return b; + if ((t/=d/2.0f) == 2.0f) return (b + c); + float p = d*(0.3f*1.5f); float a = c; - float s = p/4; + float s = p/4.0f; - if (t < 1) + if (t < 1.0f) { - float postFix = a*pow(2, 10*(t-=1)); - return -0.5f*(postFix*sin((t*d-s)*(2*PI)/p)) + b; + float postFix = a*pow(2.0f, 10.0f*(t-=1.0f)); + return -0.5f*(postFix*sin((t*d-s)*(2.0f*PI)/p)) + b; } - - float postFix = a*pow(2, -10*(t-=1)); - - return (postFix*sin((t*d-s)*(2*PI)/p)*0.5f + c + b); + + float postFix = a*pow(2.0f, -10.0f*(t-=1.0f)); + + return (postFix*sin((t*d-s)*(2.0f*PI)/p)*0.5f + c + b); } #ifdef __cplusplus -- cgit v1.2.3 From 241c4c8d14225bdf30c168802d4b16b59d5043e0 Mon Sep 17 00:00:00 2001 From: Ray Date: Sat, 25 May 2019 01:33:03 +0200 Subject: Review easings PR --- src/easings.h | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/easings.h b/src/easings.h index c7ee5649..1b08af0a 100644 --- a/src/easings.h +++ b/src/easings.h @@ -90,7 +90,7 @@ #define EASEDEF extern #endif -#include // Required for: sin(), cos(), sqrt(), pow() +#include // Required for: sinf(), cosf(), sqrt(), pow() #ifndef PI #define PI 3.14159265358979323846f //Required as PI is not always defined in math.h @@ -107,9 +107,9 @@ EASEDEF float EaseLinearOut(float t, float b, float c, float d) { return (c*t/d EASEDEF float EaseLinearInOut(float t,float b, float c, float d) { return (c*t/d + b); } // Sine Easing functions -EASEDEF float EaseSineIn(float t, float b, float c, float d) { return (-c*cos(t/d*(PI/2.0f)) + c + b); } -EASEDEF float EaseSineOut(float t, float b, float c, float d) { return (c*sin(t/d*(PI/2.0f)) + b); } -EASEDEF float EaseSineInOut(float t, float b, float c, float d) { return (-c/2.0f*(cos(PI*t/d) - 1.0f) + b); } +EASEDEF float EaseSineIn(float t, float b, float c, float d) { return (-c*cosf(t/d*(PI/2.0f)) + c + b); } +EASEDEF float EaseSineOut(float t, float b, float c, float d) { return (c*sinf(t/d*(PI/2.0f)) + b); } +EASEDEF float EaseSineInOut(float t, float b, float c, float d) { return (-c/2.0f*(cosf(PI*t/d) - 1.0f) + b); } // Circular Easing functions EASEDEF float EaseCircIn(float t, float b, float c, float d) { t /= d; return (-c*(sqrt(1.0f - t*t) - 1.0f) + b); } @@ -221,7 +221,7 @@ EASEDEF float EaseElasticIn(float t, float b, float c, float d) float s = p/4.0f; float postFix = a*pow(2.0f, 10.0f*(t-=1.0f)); - return (-(postFix*sin((t*d-s)*(2.0f*PI)/p )) + b); + return (-(postFix*sinf((t*d-s)*(2.0f*PI)/p )) + b); } EASEDEF float EaseElasticOut(float t, float b, float c, float d) @@ -233,7 +233,7 @@ EASEDEF float EaseElasticOut(float t, float b, float c, float d) float a = c; float s = p/4.0f; - return (a*pow(2.0f,-10.0f*t)*sin((t*d-s)*(2.0f*PI)/p) + c + b); + return (a*pow(2.0f,-10.0f*t)*sinf((t*d-s)*(2.0f*PI)/p) + c + b); } EASEDEF float EaseElasticInOut(float t, float b, float c, float d) @@ -248,12 +248,12 @@ EASEDEF float EaseElasticInOut(float t, float b, float c, float d) if (t < 1.0f) { float postFix = a*pow(2.0f, 10.0f*(t-=1.0f)); - return -0.5f*(postFix*sin((t*d-s)*(2.0f*PI)/p)) + b; + return -0.5f*(postFix*sinf((t*d-s)*(2.0f*PI)/p)) + b; } float postFix = a*pow(2.0f, -10.0f*(t-=1.0f)); - return (postFix*sin((t*d-s)*(2.0f*PI)/p)*0.5f + c + b); + return (postFix*sinf((t*d-s)*(2.0f*PI)/p)*0.5f + c + b); } #ifdef __cplusplus -- cgit v1.2.3 From bef809d841adf3b008cf51c08be4f3ff6d94807c Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 27 May 2019 13:03:14 +0200 Subject: Setup version for release --- src/config.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/config.h b/src/config.h index dd365f1f..72d602e6 100644 --- a/src/config.h +++ b/src/config.h @@ -25,7 +25,7 @@ * **********************************************************************************************/ -#define RAYLIB_VERSION "2.5-dev" +#define RAYLIB_VERSION "2.5" // Edit to control what features Makefile'd raylib is compiled with #if defined(RAYLIB_CMAKE) -- cgit v1.2.3 From 4e0a5909e725a1951b7fcc10421d3c41b31f15f4 Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 28 May 2019 12:08:04 +0200 Subject: Hide progress bar --- src/shell.html | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/shell.html b/src/shell.html index db823882..7db891be 100644 --- a/src/shell.html +++ b/src/shell.html @@ -125,8 +125,8 @@ jwE50AGjLCVuS8Yt4H7OgZLKK5EKOsLviEWJSL/+0uMi7gLUSBseYwqEbXvSHCec1CJvZPyHCmYQffaB } #progress { - height: 20px; - width: 30px; + height: 0px; + width: 0px; } #controls { @@ -264,7 +264,7 @@ jwE50AGjLCVuS8Yt4H7OgZLKK5EKOsLviEWJSL/+0uMi7gLUSBseYwqEbXvSHCec1CJvZPyHCmYQffaB text = m[1]; progressElement.value = parseInt(m[2])*100; progressElement.max = parseInt(m[4])*100; - progressElement.hidden = false; + progressElement.hidden = true; spinnerElement.hidden = false; } else { progressElement.value = null; -- cgit v1.2.3 From efdc6f87d53d319816b3fc76a00f309f110f3955 Mon Sep 17 00:00:00 2001 From: Ray Date: Wed, 29 May 2019 13:47:57 +0200 Subject: Define standard examples size --- src/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/Makefile b/src/Makefile index 8198e147..9411b0e2 100644 --- a/src/Makefile +++ b/src/Makefile @@ -147,7 +147,7 @@ endif ifeq ($(PLATFORM),PLATFORM_WEB) # Emscripten required variables - EMSDK_PATH ?= C:/emsdk + EMSDK_PATH ?= D:/emsdk EMSCRIPTEN_VERSION ?= 1.38.31 CLANG_VERSION = e$(EMSCRIPTEN_VERSION)_64bit PYTHON_VERSION = 2.7.13.1_64bit\python-2.7.13.amd64 -- cgit v1.2.3 From e660621389d32bb35be78a67968155a26478c32b Mon Sep 17 00:00:00 2001 From: Wilhem Barbier Date: Wed, 29 May 2019 17:14:31 +0200 Subject: Fix jar_xm_reset --- src/external/jar_xm.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/external/jar_xm.h b/src/external/jar_xm.h index 36b774d2..de6ad410 100644 --- a/src/external/jar_xm.h +++ b/src/external/jar_xm.h @@ -2670,7 +2670,7 @@ void jar_xm_reset(jar_xm_context_t* ctx) jar_xm_cut_note(&ctx->channels[i]); } ctx->current_row = 0; - ctx->current_table_index = 1; + ctx->current_table_index = ctx->module.restart_position; ctx->current_tick = 0; } -- cgit v1.2.3 From 1a32e76fbdfa63f6ea872351ac2e817f55213a9a Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 30 May 2019 18:09:33 +0200 Subject: Review compilation resources --- src/raylib.dll.rc.data | Bin 0 -> 11182 bytes src/raylib.rc.data | Bin 0 -> 11182 bytes 2 files changed, 0 insertions(+), 0 deletions(-) create mode 100644 src/raylib.dll.rc.data create mode 100644 src/raylib.rc.data (limited to 'src') diff --git a/src/raylib.dll.rc.data b/src/raylib.dll.rc.data new file mode 100644 index 00000000..ee25445f Binary files /dev/null and b/src/raylib.dll.rc.data differ diff --git a/src/raylib.rc.data b/src/raylib.rc.data new file mode 100644 index 00000000..d80e01ad Binary files /dev/null and b/src/raylib.rc.data differ -- cgit v1.2.3 From 093042b760e5c404b89542d1597ddd14c3ec2843 Mon Sep 17 00:00:00 2001 From: Ray Date: Sat, 1 Jun 2019 13:08:48 +0200 Subject: Comments review --- src/config.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/config.h b/src/config.h index 72d602e6..b4c5c3d1 100644 --- a/src/config.h +++ b/src/config.h @@ -42,9 +42,9 @@ #define SUPPORT_GESTURES_SYSTEM 1 // Mouse gestures are directly mapped like touches and processed by gestures system #define SUPPORT_MOUSE_GESTURES 1 -// Use busy wait loop for timing sync, if not defined, a high-resolution timer is setup and used +// Reconfigure standard input to receive key inputs, works with SSH connection. //#define SUPPORT_SSH_KEYBOARD_RPI 1 -//Reconfigure standard input to receive key inputs, works with SSH connection. +// Use busy wait loop for timing sync, if not defined, a high-resolution timer is setup and used //#define SUPPORT_BUSY_WAIT_LOOP 1 // Wait for events passively (sleeping while no events) instead of polling them actively every frame //#define SUPPORT_EVENTS_WAITING 1 -- cgit v1.2.3 From 2eb7e96f4b626a0387edde7b1add7d36db04588d Mon Sep 17 00:00:00 2001 From: Reece Mackie <20544390+Rover656@users.noreply.github.com> Date: Sun, 2 Jun 2019 19:31:17 +0100 Subject: Add MP3 config --- src/config.h.in | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/config.h.in b/src/config.h.in index b07b7e94..47bb6fd7 100644 --- a/src/config.h.in +++ b/src/config.h.in @@ -74,6 +74,7 @@ #cmakedefine SUPPORT_FILEFORMAT_XM 1 #cmakedefine SUPPORT_FILEFORMAT_MOD 1 #cmakedefine SUPPORT_FILEFORMAT_FLAC 1 +#cmakedefine SUPPORT_FILEFORMAT_MP3 1 // utils.c /* Show TraceLog() output messages. NOTE: By default LOG_DEBUG traces not shown */ -- cgit v1.2.3 From 6f9c176d939c8035b0f14836de80e916826c0325 Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 4 Jun 2019 18:09:17 +0200 Subject: Support SSH keyboard on RPI --- src/config.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/config.h b/src/config.h index b4c5c3d1..07cf5fe7 100644 --- a/src/config.h +++ b/src/config.h @@ -43,7 +43,7 @@ // Mouse gestures are directly mapped like touches and processed by gestures system #define SUPPORT_MOUSE_GESTURES 1 // Reconfigure standard input to receive key inputs, works with SSH connection. -//#define SUPPORT_SSH_KEYBOARD_RPI 1 +#define SUPPORT_SSH_KEYBOARD_RPI 1 // Use busy wait loop for timing sync, if not defined, a high-resolution timer is setup and used //#define SUPPORT_BUSY_WAIT_LOOP 1 // Wait for events passively (sleeping while no events) instead of polling them actively every frame -- cgit v1.2.3 From 767ac9bc3e64fd6df8e9bda46b695266c92e018b Mon Sep 17 00:00:00 2001 From: PompPenguin Date: Tue, 4 Jun 2019 17:29:18 -0400 Subject: Update camera.h Updated CAMERA_THIRD_PERSON --- src/camera.h | 71 +++++++++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 51 insertions(+), 20 deletions(-) (limited to 'src') diff --git a/src/camera.h b/src/camera.h index d80f8346..18e1e4b7 100644 --- a/src/camera.h +++ b/src/camera.h @@ -410,8 +410,7 @@ void UpdateCamera(Camera *camera) } break; case CAMERA_FIRST_PERSON: - case CAMERA_THIRD_PERSON: - { + { camera->position.x += (sinf(cameraAngle.x)*direction[MOVE_BACK] - sinf(cameraAngle.x)*direction[MOVE_FRONT] - cosf(cameraAngle.x)*direction[MOVE_LEFT] + @@ -433,7 +432,7 @@ void UpdateCamera(Camera *camera) // Camera orientation calculation cameraAngle.x += (mousePositionDelta.x*-CAMERA_MOUSE_MOVE_SENSITIVITY); cameraAngle.y += (mousePositionDelta.y*-CAMERA_MOUSE_MOVE_SENSITIVITY); - + // Angle clamp if (cameraAngle.y > CAMERA_FIRST_PERSON_MIN_CLAMP*DEG2RAD) cameraAngle.y = CAMERA_FIRST_PERSON_MIN_CLAMP*DEG2RAD; else if (cameraAngle.y < CAMERA_FIRST_PERSON_MAX_CLAMP*DEG2RAD) cameraAngle.y = CAMERA_FIRST_PERSON_MAX_CLAMP*DEG2RAD; @@ -442,28 +441,60 @@ void UpdateCamera(Camera *camera) camera->target.x = camera->position.x - sinf(cameraAngle.x)*CAMERA_FIRST_PERSON_FOCUS_DISTANCE; camera->target.y = camera->position.y + sinf(cameraAngle.y)*CAMERA_FIRST_PERSON_FOCUS_DISTANCE; camera->target.z = camera->position.z - cosf(cameraAngle.x)*CAMERA_FIRST_PERSON_FOCUS_DISTANCE; - - if (cameraMode == CAMERA_FIRST_PERSON) - { - if (isMoving) swingCounter++; + + if (isMoving) swingCounter++; - // Camera position update - // NOTE: On CAMERA_FIRST_PERSON player Y-movement is limited to player 'eyes position' - camera->position.y = playerEyesPosition - sinf(swingCounter/CAMERA_FIRST_PERSON_STEP_TRIGONOMETRIC_DIVIDER)/CAMERA_FIRST_PERSON_STEP_DIVIDER; + // Camera position update + // NOTE: On CAMERA_FIRST_PERSON player Y-movement is limited to player 'eyes position' + camera->position.y = playerEyesPosition - sinf(swingCounter/CAMERA_FIRST_PERSON_STEP_TRIGONOMETRIC_DIVIDER)/CAMERA_FIRST_PERSON_STEP_DIVIDER; - camera->up.x = sinf(swingCounter/(CAMERA_FIRST_PERSON_STEP_TRIGONOMETRIC_DIVIDER*2))/CAMERA_FIRST_PERSON_WAVING_DIVIDER; - camera->up.z = -sinf(swingCounter/(CAMERA_FIRST_PERSON_STEP_TRIGONOMETRIC_DIVIDER*2))/CAMERA_FIRST_PERSON_WAVING_DIVIDER; - } - else if (cameraMode == CAMERA_THIRD_PERSON) - { - // Camera zoom - cameraTargetDistance -= (mouseWheelMove*CAMERA_MOUSE_SCROLL_SENSITIVITY); - if (cameraTargetDistance < CAMERA_THIRD_PERSON_DISTANCE_CLAMP) cameraTargetDistance = CAMERA_THIRD_PERSON_DISTANCE_CLAMP; - } + camera->up.x = sinf(swingCounter/(CAMERA_FIRST_PERSON_STEP_TRIGONOMETRIC_DIVIDER*2))/CAMERA_FIRST_PERSON_WAVING_DIVIDER; + camera->up.z = -sinf(swingCounter/(CAMERA_FIRST_PERSON_STEP_TRIGONOMETRIC_DIVIDER*2))/CAMERA_FIRST_PERSON_WAVING_DIVIDER; + + } break; + case CAMERA_THIRD_PERSON: + { + camera->position.x += (sinf(cameraAngle.x)*direction[MOVE_BACK] - + sinf(cameraAngle.x)*direction[MOVE_FRONT] - + cosf(cameraAngle.x)*direction[MOVE_LEFT] + + cosf(cameraAngle.x)*direction[MOVE_RIGHT])/PLAYER_MOVEMENT_SENSITIVITY; + + camera->position.y += (sinf(cameraAngle.y)*direction[MOVE_FRONT] - + sinf(cameraAngle.y)*direction[MOVE_BACK] + + 1.0f*direction[MOVE_UP] - 1.0f*direction[MOVE_DOWN])/PLAYER_MOVEMENT_SENSITIVITY; + + camera->position.z += (cosf(cameraAngle.x)*direction[MOVE_BACK] - + cosf(cameraAngle.x)*direction[MOVE_FRONT] + + sinf(cameraAngle.x)*direction[MOVE_LEFT] - + sinf(cameraAngle.x)*direction[MOVE_RIGHT])/PLAYER_MOVEMENT_SENSITIVITY; + + bool isMoving = false; // Required for swinging + + for (int i = 0; i < 6; i++) if (direction[i]) { isMoving = true; break; } + + // Camera orientation calculation + cameraAngle.x += (mousePositionDelta.x*-CAMERA_MOUSE_MOVE_SENSITIVITY); + cameraAngle.y += (mousePositionDelta.y*-CAMERA_MOUSE_MOVE_SENSITIVITY); + + // Angle clamp + if (cameraAngle.y > CAMERA_THIRD_PERSON_MIN_CLAMP*DEG2RAD) cameraAngle.y = CAMERA_THIRD_PERSON_MIN_CLAMP*DEG2RAD; + else if (cameraAngle.y < CAMERA_THIRD_PERSON_MAX_CLAMP*DEG2RAD) cameraAngle.y = CAMERA_THIRD_PERSON_MAX_CLAMP*DEG2RAD; + + // Camera zoom + cameraTargetDistance -= (mouseWheelMove*CAMERA_MOUSE_SCROLL_SENSITIVITY); + + // Camera distance clamp + if (cameraTargetDistance < CAMERA_THIRD_PERSON_DISTANCE_CLAMP) cameraTargetDistance = CAMERA_THIRD_PERSON_DISTANCE_CLAMP; + + // TODO: It seems camera->position is not correctly updated or some rounding issue makes the camera move straight to camera->target... + camera->position.x = sinf(cameraAngle.x)*cameraTargetDistance*cosf(cameraAngle.y) + camera->target.x; + if (cameraAngle.y <= 0.0f) camera->position.y = sinf(cameraAngle.y)*cameraTargetDistance*sinf(cameraAngle.y) + camera->target.y; + else camera->position.y = -sinf(cameraAngle.y)*cameraTargetDistance*sinf(cameraAngle.y) + camera->target.y; + camera->position.z = cosf(cameraAngle.x)*cameraTargetDistance*cosf(cameraAngle.y) + camera->target.z; } break; default: break; - } + } } // Set camera pan key to combine with mouse movement (free camera) -- cgit v1.2.3 From 7367140fb4dfddfc7e77993a725dc3252bded920 Mon Sep 17 00:00:00 2001 From: PompPenguin Date: Tue, 4 Jun 2019 18:06:10 -0400 Subject: Update camera.h Removed unused code for CAMERA_THIRD_PERSON. --- src/camera.h | 3 --- 1 file changed, 3 deletions(-) (limited to 'src') diff --git a/src/camera.h b/src/camera.h index 18e1e4b7..1d580a20 100644 --- a/src/camera.h +++ b/src/camera.h @@ -469,9 +469,6 @@ void UpdateCamera(Camera *camera) sinf(cameraAngle.x)*direction[MOVE_LEFT] - sinf(cameraAngle.x)*direction[MOVE_RIGHT])/PLAYER_MOVEMENT_SENSITIVITY; - bool isMoving = false; // Required for swinging - - for (int i = 0; i < 6; i++) if (direction[i]) { isMoving = true; break; } // Camera orientation calculation cameraAngle.x += (mousePositionDelta.x*-CAMERA_MOUSE_MOVE_SENSITIVITY); -- cgit v1.2.3 From e103320ad8fdee61273b7da1162c120625de398d Mon Sep 17 00:00:00 2001 From: Ahmad Fatoum Date: Tue, 4 Jun 2019 16:25:13 +0200 Subject: build: increment API_VERSION after release With v2.5.0 out, increment API_VERSION, so binaries dynamically linked against the released raylib aren't accidentally paired with a development or later released raylib that may be incompatible. --- src/CMakeLists.txt | 2 +- src/Makefile | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 879ac220..9e381493 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -4,7 +4,7 @@ include(GNUInstallDirs) list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/../cmake") set(PROJECT_VERSION 2.5.0) -set(API_VERSION 2) +set(API_VERSION 251) include("CMakeOptions.txt") include(BuildType) diff --git a/src/Makefile b/src/Makefile index 9411b0e2..0f57f232 100644 --- a/src/Makefile +++ b/src/Makefile @@ -43,7 +43,7 @@ # Define required raylib variables RAYLIB_VERSION = 2.5.0 -RAYLIB_API_VERSION = 2 +RAYLIB_API_VERSION = 251 # See below for alternatives. RAYLIB_PATH = .. -- cgit v1.2.3 From e3ef73826448496383440cfc449ca6d00c722637 Mon Sep 17 00:00:00 2001 From: Ray Date: Wed, 5 Jun 2019 13:01:58 +0200 Subject: Replace TABS by spaces --- src/camera.h | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) (limited to 'src') diff --git a/src/camera.h b/src/camera.h index 1d580a20..a933447d 100644 --- a/src/camera.h +++ b/src/camera.h @@ -317,7 +317,7 @@ void UpdateCamera(Camera *camera) if (cameraTargetDistance > CAMERA_FREE_DISTANCE_MAX_CLAMP) cameraTargetDistance = CAMERA_FREE_DISTANCE_MAX_CLAMP; } // Camera looking down - // TODO: Review, weird comparisson of cameraTargetDistance == 120.0f? + // TODO: Review, weird comparisson of cameraTargetDistance == 120.0f? else if ((camera->position.y > camera->target.y) && (cameraTargetDistance == CAMERA_FREE_DISTANCE_MAX_CLAMP) && (mouseWheelMove < 0)) { camera->target.x += mouseWheelMove*(camera->target.x - camera->position.x)*CAMERA_MOUSE_SCROLL_SENSITIVITY/cameraTargetDistance; @@ -338,7 +338,7 @@ void UpdateCamera(Camera *camera) if (cameraTargetDistance < CAMERA_FREE_DISTANCE_MIN_CLAMP) cameraTargetDistance = CAMERA_FREE_DISTANCE_MIN_CLAMP; } // Camera looking up - // TODO: Review, weird comparisson of cameraTargetDistance == 120.0f? + // TODO: Review, weird comparisson of cameraTargetDistance == 120.0f? else if ((camera->position.y < camera->target.y) && (cameraTargetDistance == CAMERA_FREE_DISTANCE_MAX_CLAMP) && (mouseWheelMove < 0)) { camera->target.x += mouseWheelMove*(camera->target.x - camera->position.x)*CAMERA_MOUSE_SCROLL_SENSITIVITY/cameraTargetDistance; @@ -410,7 +410,7 @@ void UpdateCamera(Camera *camera) } break; case CAMERA_FIRST_PERSON: - { + { camera->position.x += (sinf(cameraAngle.x)*direction[MOVE_BACK] - sinf(cameraAngle.x)*direction[MOVE_FRONT] - cosf(cameraAngle.x)*direction[MOVE_LEFT] + @@ -432,7 +432,7 @@ void UpdateCamera(Camera *camera) // Camera orientation calculation cameraAngle.x += (mousePositionDelta.x*-CAMERA_MOUSE_MOVE_SENSITIVITY); cameraAngle.y += (mousePositionDelta.y*-CAMERA_MOUSE_MOVE_SENSITIVITY); - + // Angle clamp if (cameraAngle.y > CAMERA_FIRST_PERSON_MIN_CLAMP*DEG2RAD) cameraAngle.y = CAMERA_FIRST_PERSON_MIN_CLAMP*DEG2RAD; else if (cameraAngle.y < CAMERA_FIRST_PERSON_MAX_CLAMP*DEG2RAD) cameraAngle.y = CAMERA_FIRST_PERSON_MAX_CLAMP*DEG2RAD; @@ -441,7 +441,7 @@ void UpdateCamera(Camera *camera) camera->target.x = camera->position.x - sinf(cameraAngle.x)*CAMERA_FIRST_PERSON_FOCUS_DISTANCE; camera->target.y = camera->position.y + sinf(cameraAngle.y)*CAMERA_FIRST_PERSON_FOCUS_DISTANCE; camera->target.z = camera->position.z - cosf(cameraAngle.x)*CAMERA_FIRST_PERSON_FOCUS_DISTANCE; - + if (isMoving) swingCounter++; // Camera position update @@ -469,12 +469,11 @@ void UpdateCamera(Camera *camera) sinf(cameraAngle.x)*direction[MOVE_LEFT] - sinf(cameraAngle.x)*direction[MOVE_RIGHT])/PLAYER_MOVEMENT_SENSITIVITY; - // Camera orientation calculation cameraAngle.x += (mousePositionDelta.x*-CAMERA_MOUSE_MOVE_SENSITIVITY); cameraAngle.y += (mousePositionDelta.y*-CAMERA_MOUSE_MOVE_SENSITIVITY); - // Angle clamp + // Angle clamp if (cameraAngle.y > CAMERA_THIRD_PERSON_MIN_CLAMP*DEG2RAD) cameraAngle.y = CAMERA_THIRD_PERSON_MIN_CLAMP*DEG2RAD; else if (cameraAngle.y < CAMERA_THIRD_PERSON_MAX_CLAMP*DEG2RAD) cameraAngle.y = CAMERA_THIRD_PERSON_MAX_CLAMP*DEG2RAD; @@ -484,14 +483,15 @@ void UpdateCamera(Camera *camera) // Camera distance clamp if (cameraTargetDistance < CAMERA_THIRD_PERSON_DISTANCE_CLAMP) cameraTargetDistance = CAMERA_THIRD_PERSON_DISTANCE_CLAMP; - // TODO: It seems camera->position is not correctly updated or some rounding issue makes the camera move straight to camera->target... - camera->position.x = sinf(cameraAngle.x)*cameraTargetDistance*cosf(cameraAngle.y) + camera->target.x; - if (cameraAngle.y <= 0.0f) camera->position.y = sinf(cameraAngle.y)*cameraTargetDistance*sinf(cameraAngle.y) + camera->target.y; - else camera->position.y = -sinf(cameraAngle.y)*cameraTargetDistance*sinf(cameraAngle.y) + camera->target.y; - camera->position.z = cosf(cameraAngle.x)*cameraTargetDistance*cosf(cameraAngle.y) + camera->target.z; + // TODO: It seems camera->position is not correctly updated or some rounding issue makes the camera move straight to camera->target... + camera->position.x = sinf(cameraAngle.x)*cameraTargetDistance*cosf(cameraAngle.y) + camera->target.x; + if (cameraAngle.y <= 0.0f) camera->position.y = sinf(cameraAngle.y)*cameraTargetDistance*sinf(cameraAngle.y) + camera->target.y; + else camera->position.y = -sinf(cameraAngle.y)*cameraTargetDistance*sinf(cameraAngle.y) + camera->target.y; + camera->position.z = cosf(cameraAngle.x)*cameraTargetDistance*cosf(cameraAngle.y) + camera->target.z; + } break; default: break; - } + } } // Set camera pan key to combine with mouse movement (free camera) -- cgit v1.2.3 From 272d9d58e39f442b282dd27f2811269991f89592 Mon Sep 17 00:00:00 2001 From: Mohamed Shazan Date: Thu, 6 Jun 2019 15:03:03 +0530 Subject: Add VS2017.ANGLE Project --- src/core.c | 6 +++++- src/external/ANGLE/lib/x64/d3dcompiler_47.dll | Bin 0 -> 4493352 bytes src/external/ANGLE/lib/x64/libEGL.dll | Bin 0 -> 62976 bytes src/external/ANGLE/lib/x64/libEGL.lib | Bin 0 -> 14164 bytes src/external/ANGLE/lib/x64/libGLESv2.dll | Bin 0 -> 18712576 bytes src/external/ANGLE/lib/x64/libGLESv2.lib | Bin 0 -> 548600 bytes src/external/ANGLE/lib/x86/d3dcompiler_47.dll | Bin 0 -> 3705472 bytes src/external/ANGLE/lib/x86/libEGL.dll | Bin 0 -> 51712 bytes src/external/ANGLE/lib/x86/libEGL.lib | Bin 0 -> 14992 bytes src/external/ANGLE/lib/x86/libGLESv2.dll | Bin 0 -> 16666624 bytes src/external/ANGLE/lib/x86/libGLESv2.lib | Bin 0 -> 575538 bytes 11 files changed, 5 insertions(+), 1 deletion(-) create mode 100644 src/external/ANGLE/lib/x64/d3dcompiler_47.dll create mode 100644 src/external/ANGLE/lib/x64/libEGL.dll create mode 100644 src/external/ANGLE/lib/x64/libEGL.lib create mode 100644 src/external/ANGLE/lib/x64/libGLESv2.dll create mode 100644 src/external/ANGLE/lib/x64/libGLESv2.lib create mode 100644 src/external/ANGLE/lib/x86/d3dcompiler_47.dll create mode 100644 src/external/ANGLE/lib/x86/libEGL.dll create mode 100644 src/external/ANGLE/lib/x86/libEGL.lib create mode 100644 src/external/ANGLE/lib/x86/libGLESv2.dll create mode 100644 src/external/ANGLE/lib/x86/libGLESv2.lib (limited to 'src') diff --git a/src/core.c b/src/core.c index 26a8b2a4..45539d24 100644 --- a/src/core.c +++ b/src/core.c @@ -2470,7 +2470,11 @@ static bool InitGraphicsDevice(int width, int height) glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API); - glfwWindowHint(GLFW_CONTEXT_CREATION_API, GLFW_NATIVE_CONTEXT_API); // Alternative: GLFW_EGL_CONTEXT_API (ANGLE) +#if defined(PLATFORM_DESKTOP) + glfwWindowHint(GLFW_CONTEXT_CREATION_API, GLFW_EGL_CONTEXT_API); +#else + glfwWindowHint(GLFW_CONTEXT_CREATION_API, GLFW_NATIVE_CONTEXT_API); +#endif } if (fullscreen) diff --git a/src/external/ANGLE/lib/x64/d3dcompiler_47.dll b/src/external/ANGLE/lib/x64/d3dcompiler_47.dll new file mode 100644 index 00000000..47040da0 Binary files /dev/null and b/src/external/ANGLE/lib/x64/d3dcompiler_47.dll differ diff --git a/src/external/ANGLE/lib/x64/libEGL.dll b/src/external/ANGLE/lib/x64/libEGL.dll new file mode 100644 index 00000000..71c20a7a Binary files /dev/null and b/src/external/ANGLE/lib/x64/libEGL.dll differ diff --git a/src/external/ANGLE/lib/x64/libEGL.lib b/src/external/ANGLE/lib/x64/libEGL.lib new file mode 100644 index 00000000..b440f78c Binary files /dev/null and b/src/external/ANGLE/lib/x64/libEGL.lib differ diff --git a/src/external/ANGLE/lib/x64/libGLESv2.dll b/src/external/ANGLE/lib/x64/libGLESv2.dll new file mode 100644 index 00000000..66fcba06 Binary files /dev/null and b/src/external/ANGLE/lib/x64/libGLESv2.dll differ diff --git a/src/external/ANGLE/lib/x64/libGLESv2.lib b/src/external/ANGLE/lib/x64/libGLESv2.lib new file mode 100644 index 00000000..af5ba5ad Binary files /dev/null and b/src/external/ANGLE/lib/x64/libGLESv2.lib differ diff --git a/src/external/ANGLE/lib/x86/d3dcompiler_47.dll b/src/external/ANGLE/lib/x86/d3dcompiler_47.dll new file mode 100644 index 00000000..4ffad2d7 Binary files /dev/null and b/src/external/ANGLE/lib/x86/d3dcompiler_47.dll differ diff --git a/src/external/ANGLE/lib/x86/libEGL.dll b/src/external/ANGLE/lib/x86/libEGL.dll new file mode 100644 index 00000000..a9cb4a9a Binary files /dev/null and b/src/external/ANGLE/lib/x86/libEGL.dll differ diff --git a/src/external/ANGLE/lib/x86/libEGL.lib b/src/external/ANGLE/lib/x86/libEGL.lib new file mode 100644 index 00000000..1954ceb3 Binary files /dev/null and b/src/external/ANGLE/lib/x86/libEGL.lib differ diff --git a/src/external/ANGLE/lib/x86/libGLESv2.dll b/src/external/ANGLE/lib/x86/libGLESv2.dll new file mode 100644 index 00000000..47a71ff7 Binary files /dev/null and b/src/external/ANGLE/lib/x86/libGLESv2.dll differ diff --git a/src/external/ANGLE/lib/x86/libGLESv2.lib b/src/external/ANGLE/lib/x86/libGLESv2.lib new file mode 100644 index 00000000..562310cc Binary files /dev/null and b/src/external/ANGLE/lib/x86/libGLESv2.lib differ -- cgit v1.2.3 From 498c172d8e8f35def505045970a6adf50730c392 Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 6 Jun 2019 11:38:45 +0200 Subject: Review function prototype --- src/raylib.h | 2 +- src/rlgl.h | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/raylib.h b/src/raylib.h index 21202f18..9ce2e079 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -1304,7 +1304,7 @@ RLAPI void SetShaderValueMatrix(Shader shader, int uniformLoc, Matrix mat); RLAPI void SetShaderValueTexture(Shader shader, int uniformLoc, Texture2D texture); // Set shader uniform value for texture RLAPI void SetMatrixProjection(Matrix proj); // Set a custom projection matrix (replaces internal projection matrix) RLAPI void SetMatrixModelview(Matrix view); // Set a custom modelview matrix (replaces internal modelview matrix) -RLAPI Matrix GetMatrixModelview(); // Get internal modelview matrix +RLAPI Matrix GetMatrixModelview(void); // Get internal modelview matrix // Texture maps generation (PBR) // NOTE: Required shaders should be provided diff --git a/src/rlgl.h b/src/rlgl.h index 639a107e..10d21fcc 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -525,7 +525,7 @@ RLAPI void SetShaderValueV(Shader shader, int uniformLoc, const void *value, int RLAPI void SetShaderValueMatrix(Shader shader, int uniformLoc, Matrix mat); // Set shader uniform value (matrix 4x4) RLAPI void SetMatrixProjection(Matrix proj); // Set a custom projection matrix (replaces internal projection matrix) RLAPI void SetMatrixModelview(Matrix view); // Set a custom modelview matrix (replaces internal modelview matrix) -RLAPI Matrix GetMatrixModelview(); // Get internal modelview matrix +RLAPI Matrix GetMatrixModelview(void); // Get internal modelview matrix // Texture maps generation (PBR) // NOTE: Required shaders should be provided @@ -3137,7 +3137,7 @@ void SetMatrixModelview(Matrix view) } // Return internal modelview matrix -Matrix GetMatrixModelview() +Matrix GetMatrixModelview(void) { Matrix matrix = MatrixIdentity(); #if defined(GRAPHICS_API_OPENGL_11) -- cgit v1.2.3 From eb1b2535f6ef5f5adb609f5e8741b20c633e15de Mon Sep 17 00:00:00 2001 From: Mohamed Shazan Date: Thu, 6 Jun 2019 16:44:37 +0530 Subject: Change ANGLE binaries location --- src/external/ANGLE/lib/x64/d3dcompiler_47.dll | Bin 4493352 -> 0 bytes src/external/ANGLE/lib/x64/libEGL.dll | Bin 62976 -> 0 bytes src/external/ANGLE/lib/x64/libEGL.lib | Bin 14164 -> 0 bytes src/external/ANGLE/lib/x64/libGLESv2.dll | Bin 18712576 -> 0 bytes src/external/ANGLE/lib/x64/libGLESv2.lib | Bin 548600 -> 0 bytes src/external/ANGLE/lib/x86/d3dcompiler_47.dll | Bin 3705472 -> 0 bytes src/external/ANGLE/lib/x86/libEGL.dll | Bin 51712 -> 0 bytes src/external/ANGLE/lib/x86/libEGL.lib | Bin 14992 -> 0 bytes src/external/ANGLE/lib/x86/libGLESv2.dll | Bin 16666624 -> 0 bytes src/external/ANGLE/lib/x86/libGLESv2.lib | Bin 575538 -> 0 bytes 10 files changed, 0 insertions(+), 0 deletions(-) delete mode 100644 src/external/ANGLE/lib/x64/d3dcompiler_47.dll delete mode 100644 src/external/ANGLE/lib/x64/libEGL.dll delete mode 100644 src/external/ANGLE/lib/x64/libEGL.lib delete mode 100644 src/external/ANGLE/lib/x64/libGLESv2.dll delete mode 100644 src/external/ANGLE/lib/x64/libGLESv2.lib delete mode 100644 src/external/ANGLE/lib/x86/d3dcompiler_47.dll delete mode 100644 src/external/ANGLE/lib/x86/libEGL.dll delete mode 100644 src/external/ANGLE/lib/x86/libEGL.lib delete mode 100644 src/external/ANGLE/lib/x86/libGLESv2.dll delete mode 100644 src/external/ANGLE/lib/x86/libGLESv2.lib (limited to 'src') diff --git a/src/external/ANGLE/lib/x64/d3dcompiler_47.dll b/src/external/ANGLE/lib/x64/d3dcompiler_47.dll deleted file mode 100644 index 47040da0..00000000 Binary files a/src/external/ANGLE/lib/x64/d3dcompiler_47.dll and /dev/null differ diff --git a/src/external/ANGLE/lib/x64/libEGL.dll b/src/external/ANGLE/lib/x64/libEGL.dll deleted file mode 100644 index 71c20a7a..00000000 Binary files a/src/external/ANGLE/lib/x64/libEGL.dll and /dev/null differ diff --git a/src/external/ANGLE/lib/x64/libEGL.lib b/src/external/ANGLE/lib/x64/libEGL.lib deleted file mode 100644 index b440f78c..00000000 Binary files a/src/external/ANGLE/lib/x64/libEGL.lib and /dev/null differ diff --git a/src/external/ANGLE/lib/x64/libGLESv2.dll b/src/external/ANGLE/lib/x64/libGLESv2.dll deleted file mode 100644 index 66fcba06..00000000 Binary files a/src/external/ANGLE/lib/x64/libGLESv2.dll and /dev/null differ diff --git a/src/external/ANGLE/lib/x64/libGLESv2.lib b/src/external/ANGLE/lib/x64/libGLESv2.lib deleted file mode 100644 index af5ba5ad..00000000 Binary files a/src/external/ANGLE/lib/x64/libGLESv2.lib and /dev/null differ diff --git a/src/external/ANGLE/lib/x86/d3dcompiler_47.dll b/src/external/ANGLE/lib/x86/d3dcompiler_47.dll deleted file mode 100644 index 4ffad2d7..00000000 Binary files a/src/external/ANGLE/lib/x86/d3dcompiler_47.dll and /dev/null differ diff --git a/src/external/ANGLE/lib/x86/libEGL.dll b/src/external/ANGLE/lib/x86/libEGL.dll deleted file mode 100644 index a9cb4a9a..00000000 Binary files a/src/external/ANGLE/lib/x86/libEGL.dll and /dev/null differ diff --git a/src/external/ANGLE/lib/x86/libEGL.lib b/src/external/ANGLE/lib/x86/libEGL.lib deleted file mode 100644 index 1954ceb3..00000000 Binary files a/src/external/ANGLE/lib/x86/libEGL.lib and /dev/null differ diff --git a/src/external/ANGLE/lib/x86/libGLESv2.dll b/src/external/ANGLE/lib/x86/libGLESv2.dll deleted file mode 100644 index 47a71ff7..00000000 Binary files a/src/external/ANGLE/lib/x86/libGLESv2.dll and /dev/null differ diff --git a/src/external/ANGLE/lib/x86/libGLESv2.lib b/src/external/ANGLE/lib/x86/libGLESv2.lib deleted file mode 100644 index 562310cc..00000000 Binary files a/src/external/ANGLE/lib/x86/libGLESv2.lib and /dev/null differ -- cgit v1.2.3 From baf225dc01250bb5c2918b854c24c6e45ccdea4d Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 6 Jun 2019 23:52:49 +0200 Subject: Update emsdk version for testing --- src/Makefile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/Makefile b/src/Makefile index 9411b0e2..a2db4e73 100644 --- a/src/Makefile +++ b/src/Makefile @@ -147,8 +147,8 @@ endif ifeq ($(PLATFORM),PLATFORM_WEB) # Emscripten required variables - EMSDK_PATH ?= D:/emsdk - EMSCRIPTEN_VERSION ?= 1.38.31 + EMSDK_PATH ?= C:/emsdk + EMSCRIPTEN_VERSION ?= 1.38.32 CLANG_VERSION = e$(EMSCRIPTEN_VERSION)_64bit PYTHON_VERSION = 2.7.13.1_64bit\python-2.7.13.amd64 NODE_VERSION = 8.9.1_64bit -- cgit v1.2.3